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 | Pylons__pyramid | tests/test_authentication.py | {
"start": 8943,
"end": 16847
} | class ____(unittest.TestCase):
def _getTargetClass(self):
from pyramid.authentication import RepozeWho1AuthenticationPolicy
return RepozeWho1AuthenticationPolicy
def _makeOne(self, identifier_name='auth_tkt', callback=None):
return self._getTargetClass()(identifier_name, callback)
def test_class_implements_IAuthenticationPolicy(self):
from zope.interface.verify import verifyClass
from pyramid.interfaces import IAuthenticationPolicy
verifyClass(IAuthenticationPolicy, self._getTargetClass())
def test_instance_implements_IAuthenticationPolicy(self):
from zope.interface.verify import verifyObject
from pyramid.interfaces import IAuthenticationPolicy
verifyObject(IAuthenticationPolicy, self._makeOne())
def test_unauthenticated_userid_returns_None(self):
request = DummyRequest({})
policy = self._makeOne()
self.assertEqual(policy.unauthenticated_userid(request), None)
def test_unauthenticated_userid(self):
request = DummyRequest(
{'repoze.who.identity': {'repoze.who.userid': 'fred'}}
)
policy = self._makeOne()
self.assertEqual(policy.unauthenticated_userid(request), 'fred')
def test_authenticated_userid_None(self):
request = DummyRequest({})
policy = self._makeOne()
self.assertEqual(policy.authenticated_userid(request), None)
def test_authenticated_userid(self):
request = DummyRequest(
{'repoze.who.identity': {'repoze.who.userid': 'fred'}}
)
policy = self._makeOne()
self.assertEqual(policy.authenticated_userid(request), 'fred')
def test_authenticated_userid_repoze_who_userid_is_None(self):
request = DummyRequest(
{'repoze.who.identity': {'repoze.who.userid': None}}
)
policy = self._makeOne()
self.assertEqual(policy.authenticated_userid(request), None)
def test_authenticated_userid_with_callback_returns_None(self):
request = DummyRequest(
{'repoze.who.identity': {'repoze.who.userid': 'fred'}}
)
def callback(identity, request):
return None
policy = self._makeOne(callback=callback)
self.assertEqual(policy.authenticated_userid(request), None)
def test_authenticated_userid_with_callback_returns_something(self):
request = DummyRequest(
{'repoze.who.identity': {'repoze.who.userid': 'fred'}}
)
def callback(identity, request):
return ['agroup']
policy = self._makeOne(callback=callback)
self.assertEqual(policy.authenticated_userid(request), 'fred')
def test_authenticated_userid_unclean_principal_Authenticated(self):
request = DummyRequest(
{
'repoze.who.identity': {
'repoze.who.userid': 'system.Authenticated'
}
}
)
policy = self._makeOne()
self.assertEqual(policy.authenticated_userid(request), None)
def test_authenticated_userid_unclean_principal_Everyone(self):
request = DummyRequest(
{'repoze.who.identity': {'repoze.who.userid': 'system.Everyone'}}
)
policy = self._makeOne()
self.assertEqual(policy.authenticated_userid(request), None)
def test_effective_principals_None(self):
from pyramid.authorization import Everyone
request = DummyRequest({})
policy = self._makeOne()
self.assertEqual(policy.effective_principals(request), [Everyone])
def test_effective_principals_userid_only(self):
from pyramid.authorization import Authenticated, Everyone
request = DummyRequest(
{'repoze.who.identity': {'repoze.who.userid': 'fred'}}
)
policy = self._makeOne()
self.assertEqual(
policy.effective_principals(request),
[Everyone, Authenticated, 'fred'],
)
def test_effective_principals_userid_and_groups(self):
from pyramid.authorization import Authenticated, Everyone
request = DummyRequest(
{
'repoze.who.identity': {
'repoze.who.userid': 'fred',
'groups': ['quux', 'biz'],
}
}
)
def callback(identity, request):
return identity['groups']
policy = self._makeOne(callback=callback)
self.assertEqual(
policy.effective_principals(request),
[Everyone, Authenticated, 'fred', 'quux', 'biz'],
)
def test_effective_principals_userid_callback_returns_None(self):
from pyramid.authorization import Everyone
request = DummyRequest(
{
'repoze.who.identity': {
'repoze.who.userid': 'fred',
'groups': ['quux', 'biz'],
}
}
)
def callback(identity, request):
return None
policy = self._makeOne(callback=callback)
self.assertEqual(policy.effective_principals(request), [Everyone])
def test_effective_principals_repoze_who_userid_is_None(self):
from pyramid.authorization import Everyone
request = DummyRequest(
{'repoze.who.identity': {'repoze.who.userid': None}}
)
policy = self._makeOne()
self.assertEqual(policy.effective_principals(request), [Everyone])
def test_effective_principals_repoze_who_userid_is_unclean_Everyone(self):
from pyramid.authorization import Everyone
request = DummyRequest(
{'repoze.who.identity': {'repoze.who.userid': 'system.Everyone'}}
)
policy = self._makeOne()
self.assertEqual(policy.effective_principals(request), [Everyone])
def test_effective_principals_repoze_who_userid_is_unclean_Authenticated(
self,
):
from pyramid.authorization import Everyone
request = DummyRequest(
{
'repoze.who.identity': {
'repoze.who.userid': 'system.Authenticated'
}
}
)
policy = self._makeOne()
self.assertEqual(policy.effective_principals(request), [Everyone])
def test_remember_no_plugins(self):
request = DummyRequest({})
policy = self._makeOne()
result = policy.remember(request, 'fred')
self.assertEqual(result, [])
def test_remember(self):
authtkt = DummyWhoPlugin()
request = DummyRequest({'repoze.who.plugins': {'auth_tkt': authtkt}})
policy = self._makeOne()
result = policy.remember(request, 'fred')
self.assertEqual(result[0], request.environ)
self.assertEqual(result[1], {'repoze.who.userid': 'fred'})
def test_remember_kwargs(self):
authtkt = DummyWhoPlugin()
request = DummyRequest({'repoze.who.plugins': {'auth_tkt': authtkt}})
policy = self._makeOne()
result = policy.remember(request, 'fred', max_age=23)
self.assertEqual(
result[1], {'repoze.who.userid': 'fred', 'max_age': 23}
)
def test_forget_no_plugins(self):
request = DummyRequest({})
policy = self._makeOne()
result = policy.forget(request)
self.assertEqual(result, [])
def test_forget(self):
authtkt = DummyWhoPlugin()
request = DummyRequest(
{
'repoze.who.plugins': {'auth_tkt': authtkt},
'repoze.who.identity': {'repoze.who.userid': 'fred'},
}
)
policy = self._makeOne()
result = policy.forget(request)
self.assertEqual(result[0], request.environ)
self.assertEqual(result[1], request.environ['repoze.who.identity'])
| TestRepozeWho1AuthenticationPolicy |
python | ansible__ansible | test/units/module_utils/facts/test_collectors.py | {
"start": 2191,
"end": 2604
} | class ____(collector.BaseFactCollector):
name = 'exc_throwing'
def __init__(self, collectors=None, namespace=None, exception=None):
super(ExceptionThrowingCollector, self).__init__(collectors, namespace)
self._exception = exception or CollectorException('collection failed')
def collect(self, module=None, collected_facts=None):
raise self._exception
| ExceptionThrowingCollector |
python | apache__airflow | providers/smtp/src/airflow/providers/smtp/notifications/smtp.py | {
"start": 1232,
"end": 7023
} | class ____(BaseNotifier):
"""
SMTP Notifier.
Accepts keyword arguments. The only required arguments are `from_email` and `to`. Examples:
.. code-block:: python
EmptyOperator(task_id="task", on_failure_callback=SmtpNotifier(from_email=None, to="my@mail.com"))
EmptyOperator(
task_id="task",
on_failure_callback=SmtpNotifier(
from_email="myemail@myemail.com",
to="myemail@myemail.com",
subject="Task {{ ti.task_id }} failed",
),
)
You can define a default template for subject and html_content in the SMTP connection configuration.
:param smtp_conn_id: The :ref:`smtp connection id <howto/connection:smtp>`
that contains the information used to authenticate the client.
"""
template_fields = (
"from_email",
"to",
"subject",
"html_content",
"files",
"cc",
"bcc",
"mime_subtype",
"mime_charset",
"custom_headers",
)
def __init__(
self,
to: str | Iterable[str],
from_email: str | None = None,
subject: str | None = None,
html_content: str | None = None,
files: list[str] | None = None,
cc: str | Iterable[str] | None = None,
bcc: str | Iterable[str] | None = None,
mime_subtype: str = "mixed",
mime_charset: str = "utf-8",
custom_headers: dict[str, Any] | None = None,
smtp_conn_id: str = SmtpHook.default_conn_name,
auth_type: str = "basic",
*,
template: str | None = None,
**kwargs,
):
if AIRFLOW_V_3_1_PLUS:
# Support for passing context was added in 3.1.0
super().__init__(**kwargs)
else:
super().__init__()
self.smtp_conn_id = smtp_conn_id
self.from_email = from_email
self.to = to
self.files = files
self.cc = cc
self.bcc = bcc
self.mime_subtype = mime_subtype
self.mime_charset = mime_charset
self.custom_headers = custom_headers
self.subject = subject
self.html_content = html_content
self.auth_type = auth_type
if self.html_content is None and template is not None:
self.html_content = self._read_template(template)
@staticmethod
def _read_template(template_path: str) -> str:
return Path(template_path).read_text().replace("\n", "").strip()
@cached_property
def hook(self) -> SmtpHook:
"""Smtp Events Hook."""
return SmtpHook(smtp_conn_id=self.smtp_conn_id, auth_type=self.auth_type)
def _build_email_content(self, smtp: SmtpHook, context: Context):
fields_to_re_render = []
if self.from_email is None:
if smtp.from_email is not None:
self.from_email = smtp.from_email
else:
raise ValueError("You should provide `from_email` or define it in the connection")
fields_to_re_render.append("from_email")
if self.subject is None:
smtp_default_templated_subject_path: str
if smtp.subject_template:
smtp_default_templated_subject_path = smtp.subject_template
else:
smtp_default_templated_subject_path = (
Path(__file__).parent / "templates" / "email_subject.jinja2"
).as_posix()
self.subject = self._read_template(smtp_default_templated_subject_path)
fields_to_re_render.append("subject")
if self.html_content is None:
smtp_default_templated_html_content_path: str
if smtp.html_content_template:
smtp_default_templated_html_content_path = smtp.html_content_template
else:
smtp_default_templated_html_content_path = (
Path(__file__).parent / "templates" / "email.html"
).as_posix()
self.html_content = self._read_template(smtp_default_templated_html_content_path)
fields_to_re_render.append("html_content")
if fields_to_re_render:
jinja_env = self.get_template_env(dag=context.get("dag"))
self._do_render_template_fields(self, fields_to_re_render, context, jinja_env, set())
def notify(self, context: Context):
"""Send a email via smtp server."""
with self.hook as smtp_hook:
self._build_email_content(smtp_hook, context)
smtp_hook.send_email_smtp(
smtp_conn_id=self.smtp_conn_id,
from_email=self.from_email,
to=self.to,
subject=self.subject,
html_content=self.html_content,
files=self.files,
cc=self.cc,
bcc=self.bcc,
mime_subtype=self.mime_subtype,
mime_charset=self.mime_charset,
custom_headers=self.custom_headers,
)
async def async_notify(self, context: Context):
"""Send a email via smtp server (async)."""
async with self.hook as smtp_hook:
self._build_email_content(smtp_hook, context)
await smtp_hook.asend_email_smtp(
smtp_conn_id=self.smtp_conn_id,
from_email=self.from_email,
to=self.to,
subject=self.subject,
html_content=self.html_content,
files=self.files,
cc=self.cc,
bcc=self.bcc,
mime_subtype=self.mime_subtype,
mime_charset=self.mime_charset,
custom_headers=self.custom_headers,
)
send_smtp_notification = SmtpNotifier
| SmtpNotifier |
python | walkccc__LeetCode | solutions/785. Is Graph Bipartite?/785.py | {
"start": 79,
"end": 778
} | class ____:
def isBipartite(self, graph: list[list[int]]) -> bool:
colors = [Color.WHITE] * len(graph)
for i in range(len(graph)):
# This node has been colored, so do nothing.
if colors[i] != Color.WHITE:
continue
# Always paint red for a white node.
colors[i] = Color.RED
# BFS.
q = collections.deque([i])
while q:
for _ in range(len(q)):
u = q.popleft()
for v in graph[u]:
if colors[v] == colors[u]:
return False
if colors[v] == Color.WHITE:
colors[v] = Color.RED if colors[u] == Color.GREEN else Color.GREEN
q.append(v)
return True
| Solution |
python | apache__airflow | providers/standard/tests/unit/standard/operators/test_latest_only_operator.py | {
"start": 2375,
"end": 13634
} | class ____:
@staticmethod
def clean_db():
clear_db_runs()
clear_db_xcom()
def setup_class(self):
self.clean_db()
def setup_method(self):
self.freezer = time_machine.travel(FROZEN_NOW, tick=False)
self.freezer.start()
def teardown_method(self):
self.freezer.stop()
self.clean_db()
def test_run(self, dag_maker):
with dag_maker(
default_args={"owner": "airflow", "start_date": DEFAULT_DATE}, schedule=INTERVAL, serialized=True
):
LatestOnlyOperator(task_id="latest")
dr = dag_maker.create_dagrun()
dag_maker.run_ti("latest", dr)
def test_skipping_non_latest(self, dag_maker):
with dag_maker(
default_args={"owner": "airflow", "start_date": DEFAULT_DATE}, schedule=INTERVAL, serialized=True
):
latest_task = LatestOnlyOperator(task_id="latest")
downstream_task = EmptyOperator(task_id="downstream")
downstream_task2 = EmptyOperator(task_id="downstream_2")
downstream_task3 = EmptyOperator(task_id="downstream_3", trigger_rule=TriggerRule.NONE_FAILED)
downstream_task.set_upstream(latest_task)
downstream_task2.set_upstream(downstream_task)
downstream_task3.set_upstream(downstream_task)
triggered_by_kwargs = {"triggered_by": DagRunTriggeredByType.TEST} if AIRFLOW_V_3_0_PLUS else {}
dr0 = dag_maker.create_dagrun(
run_type=DagRunType.SCHEDULED,
start_date=timezone.utcnow(),
logical_date=DEFAULT_DATE,
state=State.RUNNING,
data_interval=DataInterval(DEFAULT_DATE, DEFAULT_DATE),
**triggered_by_kwargs,
)
dr1 = dag_maker.create_dagrun(
run_type=DagRunType.SCHEDULED,
start_date=timezone.utcnow(),
logical_date=timezone.datetime(2016, 1, 1, 12),
state=State.RUNNING,
data_interval=DataInterval(timezone.datetime(2016, 1, 1, 12), timezone.datetime(2016, 1, 1, 12)),
**triggered_by_kwargs,
)
dr2 = dag_maker.create_dagrun(
run_type=DagRunType.SCHEDULED,
start_date=timezone.utcnow(),
logical_date=END_DATE,
state=State.RUNNING,
data_interval=DataInterval(END_DATE + INTERVAL, END_DATE + INTERVAL),
**triggered_by_kwargs,
)
if AIRFLOW_V_3_0_1:
from airflow.exceptions import DownstreamTasksSkipped
# AIP-72
# Running the "latest" task for each of the DAG runs to test the skipping of downstream tasks
# via the DownstreamTasksSkipped exception call.
# The DownstreamTasksSkipped exception is raised when the task completes successfully so
# we can simulate the downstream tasks being skipped by setting their state to SKIPPED
# and the task that raised the exception to SUCCESS.
latest_ti0 = dr0.get_task_instance(task_id="latest")
with pytest.raises(DownstreamTasksSkipped) as exc_info:
latest_ti0.run()
assert exc_info.value.tasks == [("downstream", -1)]
# TODO: Set state is needed until #45549 is completed.
latest_ti0.set_state(State.SUCCESS)
dr0.get_task_instance(task_id="downstream").set_state(State.SKIPPED)
# ---
latest_ti1 = dr1.get_task_instance(task_id="latest")
latest_ti1.task = latest_task
with pytest.raises(DownstreamTasksSkipped) as exc_info:
latest_ti1.run()
assert exc_info.value.tasks == [("downstream", -1)]
# TODO: Set state is needed until #45549 is completed.
latest_ti1.set_state(State.SUCCESS)
dr1.get_task_instance(task_id="downstream").set_state(State.SKIPPED)
# The last DAG run should run all tasks and latest task should be successful
# and not raise DownstreamTasksSkipped exception
latest_ti2 = dr2.get_task_instance(task_id="latest")
latest_ti2.task = latest_task
latest_ti2.run()
else:
for dr in [dr0, dr1, dr2]:
dag_maker.run_ti("latest", dr)
if AIRFLOW_V_3_0_PLUS:
date_getter = operator.attrgetter("logical_date")
else:
date_getter = operator.attrgetter("execution_date")
latest_instances = get_task_instances("latest")
exec_date_to_latest_state = {date_getter(ti): ti.state for ti in latest_instances}
assert exec_date_to_latest_state == {
timezone.datetime(2016, 1, 1): "success",
timezone.datetime(2016, 1, 1, 12): "success",
timezone.datetime(2016, 1, 2): "success",
}
# Verify the state of the other downstream tasks
for dr in [dr0, dr1, dr2]:
dag_maker.run_ti("downstream", dr)
dag_maker.run_ti("downstream_2", dr)
dag_maker.run_ti("downstream_3", dr)
downstream_instances = get_task_instances("downstream")
exec_date_to_downstream_state = {date_getter(ti): ti.state for ti in downstream_instances}
assert exec_date_to_downstream_state == {
timezone.datetime(2016, 1, 1): "skipped",
timezone.datetime(2016, 1, 1, 12): "skipped",
timezone.datetime(2016, 1, 2): "success",
}
downstream_instances = get_task_instances("downstream_2")
exec_date_to_downstream_state = {date_getter(ti): ti.state for ti in downstream_instances}
assert exec_date_to_downstream_state == {
timezone.datetime(2016, 1, 1): None,
timezone.datetime(2016, 1, 1, 12): None,
timezone.datetime(2016, 1, 2): "success",
}
downstream_instances = get_task_instances("downstream_3")
exec_date_to_downstream_state = {date_getter(ti): ti.state for ti in downstream_instances}
assert exec_date_to_downstream_state == {
timezone.datetime(2016, 1, 1): "success",
timezone.datetime(2016, 1, 1, 12): "success",
timezone.datetime(2016, 1, 2): "success",
}
def test_not_skipping_manual(self, dag_maker):
with dag_maker(
default_args={"owner": "airflow", "start_date": DEFAULT_DATE}, schedule=INTERVAL, serialized=True
):
latest_task = LatestOnlyOperator(task_id="latest")
downstream_task = EmptyOperator(task_id="downstream")
downstream_task2 = EmptyOperator(task_id="downstream_2")
downstream_task.set_upstream(latest_task)
downstream_task2.set_upstream(downstream_task)
triggered_by_kwargs = {"triggered_by": DagRunTriggeredByType.TEST} if AIRFLOW_V_3_0_PLUS else {}
dag_maker.create_dagrun(
run_type=DagRunType.MANUAL,
start_date=timezone.utcnow(),
logical_date=DEFAULT_DATE,
state=State.RUNNING,
data_interval=DataInterval(DEFAULT_DATE, DEFAULT_DATE),
**triggered_by_kwargs,
)
logical_date = timezone.datetime(2016, 1, 1, 12)
dag_maker.create_dagrun(
run_type=DagRunType.MANUAL,
start_date=timezone.utcnow(),
logical_date=logical_date,
state=State.RUNNING,
data_interval=DataInterval(logical_date, logical_date),
**triggered_by_kwargs,
)
dag_maker.create_dagrun(
run_type=DagRunType.MANUAL,
start_date=timezone.utcnow(),
logical_date=END_DATE,
state=State.RUNNING,
data_interval=DataInterval(END_DATE, END_DATE),
**triggered_by_kwargs,
)
# Get all created dag runs and run tasks for each
all_drs = dag_maker.session.query(DagRun).filter_by(dag_id=dag_maker.dag.dag_id).all()
for dr in all_drs:
dag_maker.run_ti("latest", dr)
dag_maker.run_ti("downstream", dr)
dag_maker.run_ti("downstream_2", dr)
latest_instances = get_task_instances("latest")
if AIRFLOW_V_3_0_PLUS:
exec_date_to_latest_state = {ti.logical_date: ti.state for ti in latest_instances}
else:
exec_date_to_latest_state = {ti.execution_date: ti.state for ti in latest_instances}
assert exec_date_to_latest_state == {
timezone.datetime(2016, 1, 1): "success",
timezone.datetime(2016, 1, 1, 12): "success",
timezone.datetime(2016, 1, 2): "success",
}
downstream_instances = get_task_instances("downstream")
if AIRFLOW_V_3_0_PLUS:
exec_date_to_downstream_state = {ti.logical_date: ti.state for ti in downstream_instances}
else:
exec_date_to_downstream_state = {ti.execution_date: ti.state for ti in downstream_instances}
assert exec_date_to_downstream_state == {
timezone.datetime(2016, 1, 1): "success",
timezone.datetime(2016, 1, 1, 12): "success",
timezone.datetime(2016, 1, 2): "success",
}
downstream_instances = get_task_instances("downstream_2")
if AIRFLOW_V_3_0_PLUS:
exec_date_to_downstream_state = {ti.logical_date: ti.state for ti in downstream_instances}
else:
exec_date_to_downstream_state = {ti.execution_date: ti.state for ti in downstream_instances}
assert exec_date_to_downstream_state == {
timezone.datetime(2016, 1, 1): "success",
timezone.datetime(2016, 1, 1, 12): "success",
timezone.datetime(2016, 1, 2): "success",
}
@pytest.mark.skipif(not AIRFLOW_V_3_0_PLUS, reason="Only applicable to Airflow 3.0+")
def test_zero_length_interval_treated_as_latest(self, run_task):
"""Test that when the data_interval_start and data_interval_end are the same, the task is treated as latest."""
with DAG(
"test_dag",
schedule=DeltaTriggerTimetable(datetime.timedelta(hours=1)),
start_date=DEFAULT_DATE,
catchup=False,
):
latest_task = LatestOnlyOperator(task_id="latest")
downstream_task = EmptyOperator(task_id="downstream")
latest_task >> downstream_task
run_task(latest_task, run_type=DagRunType.SCHEDULED)
assert run_task.dagrun.data_interval_start == run_task.dagrun.data_interval_end
# The task will raise DownstreamTasksSkipped exception if it is not the latest run
assert run_task.state == State.SUCCESS
def test_regular_latest_only_run(self, dag_maker):
"""Test latest_only running in normal mode."""
with dag_maker(
"test_dag",
start_date=DEFAULT_DATE,
schedule="* * * * *",
catchup=False,
):
latest_task = LatestOnlyOperator(task_id="latest")
downstream_task = EmptyOperator(task_id="downstream")
latest_task >> downstream_task
dr = dag_maker.create_dagrun(
run_type=DagRunType.SCHEDULED,
)
dag_maker.run_ti("latest", dr)
| TestLatestOnlyOperator |
python | great-expectations__great_expectations | great_expectations/core/partitioners.py | {
"start": 1563,
"end": 1778
} | class ____(pydantic.BaseModel):
column_names: List[str]
sort_ascending: bool = True
method_name: Literal["partition_on_multi_column_values"] = "partition_on_multi_column_values"
| PartitionerMultiColumnValue |
python | openai__openai-python | src/openai/cli/_tools/migrate.py | {
"start": 1098,
"end": 4497
} | class ____(BaseModel):
# internal
unknown_args: List[str] = []
def migrate(args: MigrateArgs) -> None:
grit_path = install()
try:
subprocess.check_call([grit_path, "apply", "openai", *args.unknown_args])
except subprocess.CalledProcessError:
# stdout and stderr are forwarded by subprocess so an error will already
# have been displayed
raise SilentCLIError() from None
# handles downloading the Grit CLI until they provide their own PyPi package
KEYGEN_ACCOUNT = "custodian-dev"
def _cache_dir() -> Path:
xdg = os.environ.get("XDG_CACHE_HOME")
if xdg is not None:
return Path(xdg)
return Path.home() / ".cache"
def _debug(message: str) -> None:
if not os.environ.get("DEBUG"):
return
sys.stdout.write(f"[DEBUG]: {message}\n")
def install() -> Path:
"""Installs the Grit CLI and returns the location of the binary"""
if sys.platform == "win32":
raise CLIError("Windows is not supported yet in the migration CLI")
_debug("Using Grit installer from GitHub")
platform = "apple-darwin" if sys.platform == "darwin" else "unknown-linux-gnu"
dir_name = _cache_dir() / "openai-python"
install_dir = dir_name / ".install"
target_dir = install_dir / "bin"
target_path = target_dir / "grit"
temp_file = target_dir / "grit.tmp"
if target_path.exists():
_debug(f"{target_path} already exists")
sys.stdout.flush()
return target_path
_debug(f"Using Grit CLI path: {target_path}")
target_dir.mkdir(parents=True, exist_ok=True)
if temp_file.exists():
temp_file.unlink()
arch = _get_arch()
_debug(f"Using architecture {arch}")
file_name = f"grit-{arch}-{platform}"
download_url = f"https://github.com/getgrit/gritql/releases/latest/download/{file_name}.tar.gz"
sys.stdout.write(f"Downloading Grit CLI from {download_url}\n")
with httpx.Client() as client:
download_response = client.get(download_url, follow_redirects=True)
if download_response.status_code != 200:
raise CLIError(f"Failed to download Grit CLI from {download_url}")
with open(temp_file, "wb") as file:
for chunk in download_response.iter_bytes():
file.write(chunk)
unpacked_dir = target_dir / "cli-bin"
unpacked_dir.mkdir(parents=True, exist_ok=True)
with tarfile.open(temp_file, "r:gz") as archive:
if sys.version_info >= (3, 12):
archive.extractall(unpacked_dir, filter="data")
else:
archive.extractall(unpacked_dir)
_move_files_recursively(unpacked_dir, target_dir)
shutil.rmtree(unpacked_dir)
os.remove(temp_file)
os.chmod(target_path, 0o755)
sys.stdout.flush()
return target_path
def _move_files_recursively(source_dir: Path, target_dir: Path) -> None:
for item in source_dir.iterdir():
if item.is_file():
item.rename(target_dir / item.name)
elif item.is_dir():
_move_files_recursively(item, target_dir)
def _get_arch() -> str:
architecture = platform.machine().lower()
# Map the architecture names to Grit equivalents
arch_map = {
"x86_64": "x86_64",
"amd64": "x86_64",
"armv7l": "aarch64",
"arm64": "aarch64",
}
return arch_map.get(architecture, architecture)
| MigrateArgs |
python | huggingface__transformers | src/transformers/models/reformer/modeling_reformer.py | {
"start": 77420,
"end": 78796
} | class ____(ModelOutput):
r"""
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_predict, hidden_size)`):
Sequence of hidden-states at the last layer of the model.
`num_predict` corresponds to `target_mapping.shape[1]`. If `target_mapping` is `None`, then `num_predict`
corresponds to `sequence_length`.
past_buckets_states (`list[tuple(torch.LongTensor, torch.FloatTensor)]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
List of `tuple(torch.LongTensor, torch.FloatTensor` of length `config.n_layers`, with the first element
being the previous *buckets* of shape `(batch_size, num_heads, num_hashes, sequence_length)`) and the
second being the previous *hidden_states* of shape `(batch_size, sequence_length, hidden_size)`).
Contains precomputed buckets and hidden-states that can be used (see `past_buckets_states` input) to speed
up sequential decoding.
"""
last_hidden_state: torch.FloatTensor
past_buckets_states: Optional[list[tuple[torch.LongTensor, torch.FloatTensor]]] = None
hidden_states: Optional[tuple[torch.FloatTensor]] = None
attentions: Optional[tuple[torch.FloatTensor]] = None
@dataclass
@auto_docstring(
custom_intro="""
Output type of [`ReformerModelWithLMHead`].
"""
)
| ReformerModelOutput |
python | ahupp__python-magic | test/python_magic_test.py | {
"start": 517,
"end": 5086
} | class ____:
file_name: str
mime_results: List[str]
text_results: List[str]
no_check_elf_results: Union[List[str], None]
buf_equals_file: bool = True
# magic_descriptor is broken (?) in centos 7, so don't run those tests
SKIP_FROM_DESCRIPTOR = bool(os.environ.get("SKIP_FROM_DESCRIPTOR"))
COMMON_PLAIN = [{}]
NO_SOFT = [{"check_soft": False}]
COMMON_MIME = [{"mime": True}]
CASES = {
b"magic._pyc_": [
(
COMMON_MIME,
[
"application/octet-stream",
"text/x-bytecode.python",
"application/x-bytecode.python",
],
),
(COMMON_PLAIN, ["python 2.4 byte-compiled"]),
(NO_SOFT, ["data"]),
],
b"test.pdf": [
(COMMON_MIME, ["application/pdf"]),
(
COMMON_PLAIN,
[
"PDF document, version 1.2",
"PDF document, version 1.2, 2 pages",
"PDF document, version 1.2, 2 page(s)",
],
),
(NO_SOFT, ["ASCII text"]),
],
b"test.gz": [
(COMMON_MIME, ["application/gzip", "application/x-gzip"]),
(
COMMON_PLAIN,
[
'gzip compressed data, was "test", from Unix, last modified: Sun Jun 29 01:32:52 2008',
'gzip compressed data, was "test", last modified: Sun Jun 29 01:32:52 2008, from Unix',
'gzip compressed data, was "test", last modified: Sun Jun 29 01:32:52 2008, from Unix, original size 15',
'gzip compressed data, was "test", last modified: Sun Jun 29 01:32:52 2008, from Unix, original size modulo 2^32 15',
'gzip compressed data, was "test", last modified: Sun Jun 29 01:32:52 2008, from Unix, truncated',
],
),
(
[{"extension": True}],
[
# some versions return '' for the extensions of a gz file,
# including w/ the command line. Who knows...
"gz/tgz/tpz/zabw/svgz/adz/kmy/xcfgz",
"gz/tgz/tpz/zabw/svgz",
"",
"???",
],
),
(NO_SOFT, ["data"]),
],
b"test.snappy.parquet": [
(COMMON_MIME, ["application/octet-stream"]),
(COMMON_PLAIN, ["Apache Parquet", "Par archive data"]),
(NO_SOFT, ["data"]),
],
b"test.json": [
(COMMON_MIME, ["application/json"]),
(COMMON_PLAIN, ["JSON text data"]),
(
[{"mime": True, "check_json": False}],
[
"text/plain",
],
),
(NO_SOFT, ["JSON text data"]),
],
b"elf-NetBSD-x86_64-echo": [
# TODO: soft, no elf
(
COMMON_PLAIN,
[
"ELF 64-bit LSB shared object, x86-64, version 1 (SYSV)",
"ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /libexec/ld.elf_so, for NetBSD 8.0, not stripped",
],
),
(
COMMON_MIME,
[
"application/x-pie-executable",
"application/x-sharedlib",
],
),
(
[{"check_elf": False}],
[
"ELF 64-bit LSB shared object, x86-64, version 1 (SYSV)",
],
),
# TODO: sometimes
# "ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /libexec/ld.elf_so, for NetBSD 8.0, not stripped",
(NO_SOFT, ["data"]),
],
b"text.txt": [
(COMMON_MIME, ["text/plain"]),
(COMMON_PLAIN, ["ASCII text"]),
(
[{"mime_encoding": True}],
[
"us-ascii",
],
),
(NO_SOFT, ["ASCII text"]),
],
b"text-iso8859-1.txt": [
(
[{"mime_encoding": True}],
[
"iso-8859-1",
],
),
],
b"\xce\xbb": [
(COMMON_MIME, ["text/plain"]),
],
b"name_use.jpg": [
([{"extension": True}], ["jpeg/jpg/jpe/jfif"]),
],
b"keep-going.jpg": [
(COMMON_MIME, ["image/jpeg"]),
(
[{"mime": True, "keep_going": True}],
[
"image/jpeg\\012- application/octet-stream",
],
),
],
b"../../magic/loader.py": [
(
COMMON_MIME,
[
"text/x-python",
"text/x-script.python",
],
)
],
}
| TestFile |
python | Netflix__metaflow | metaflow/_vendor/click/types.py | {
"start": 21391,
"end": 25045
} | class ____(CompositeParamType):
"""The default behavior of Click is to apply a type on a value directly.
This works well in most cases, except for when `nargs` is set to a fixed
count and different types should be used for different items. In this
case the :class:`Tuple` type can be used. This type can only be used
if `nargs` is set to a fixed number.
For more information see :ref:`tuple-type`.
This can be selected by using a Python tuple literal as a type.
:param types: a list of types that should be used for the tuple items.
"""
def __init__(self, types):
self.types = [convert_type(ty) for ty in types]
@property
def name(self):
return "<{}>".format(" ".join(ty.name for ty in self.types))
@property
def arity(self):
return len(self.types)
def convert(self, value, param, ctx):
if len(value) != len(self.types):
raise TypeError(
"It would appear that nargs is set to conflict with the"
" composite type arity."
)
return tuple(ty(x, param, ctx) for ty, x in zip(self.types, value))
def convert_type(ty, default=None):
"""Converts a callable or python type into the most appropriate
param type.
"""
guessed_type = False
if ty is None and default is not None:
if isinstance(default, tuple):
ty = tuple(map(type, default))
else:
ty = type(default)
guessed_type = True
if isinstance(ty, tuple):
return Tuple(ty)
if isinstance(ty, ParamType):
return ty
if ty is text_type or ty is str or ty is None:
return STRING
if ty is int:
return INT
# Booleans are only okay if not guessed. This is done because for
# flags the default value is actually a bit of a lie in that it
# indicates which of the flags is the one we want. See get_default()
# for more information.
if ty is bool and not guessed_type:
return BOOL
if ty is float:
return FLOAT
if guessed_type:
return STRING
# Catch a common mistake
if __debug__:
try:
if issubclass(ty, ParamType):
raise AssertionError(
"Attempted to use an uninstantiated parameter type ({}).".format(ty)
)
except TypeError:
pass
return FuncParamType(ty)
#: A dummy parameter type that just does nothing. From a user's
#: perspective this appears to just be the same as `STRING` but internally
#: no string conversion takes place. This is necessary to achieve the
#: same bytes/unicode behavior on Python 2/3 in situations where you want
#: to not convert argument types. This is usually useful when working
#: with file paths as they can appear in bytes and unicode.
#:
#: For path related uses the :class:`Path` type is a better choice but
#: there are situations where an unprocessed type is useful which is why
#: it is is provided.
#:
#: .. versionadded:: 4.0
UNPROCESSED = UnprocessedParamType()
#: A unicode string parameter type which is the implicit default. This
#: can also be selected by using ``str`` as type.
STRING = StringParamType()
#: An integer parameter. This can also be selected by using ``int`` as
#: type.
INT = IntParamType()
#: A floating point value parameter. This can also be selected by using
#: ``float`` as type.
FLOAT = FloatParamType()
#: A boolean parameter. This is the default for boolean flags. This can
#: also be selected by using ``bool`` as a type.
BOOL = BoolParamType()
#: A UUID parameter.
UUID = UUIDParameterType()
| Tuple |
python | catalyst-team__catalyst | catalyst/contrib/layers/se.py | {
"start": 84,
"end": 1384
} | class ____(nn.Module): # noqa: N801
"""
The channel-wise SE (Squeeze and Excitation) block from the
`Squeeze-and-Excitation Networks`__ paper.
Adapted from
https://www.kaggle.com/c/tgs-salt-identification-challenge/discussion/65939
and
https://www.kaggle.com/c/tgs-salt-identification-challenge/discussion/66178
Shape:
- Input: (batch, channels, height, width)
- Output: (batch, channels, height, width) (same shape as input)
__ https://arxiv.org/abs/1709.01507
"""
def __init__(self, in_channels: int, r: int = 16):
"""
Args:
in_channels: The number of channels
in the feature map of the input.
r: The reduction ratio of the intermediate channels.
Default: 16.
"""
super().__init__()
self.linear1 = nn.Linear(in_channels, in_channels // r)
self.linear2 = nn.Linear(in_channels // r, in_channels)
def forward(self, x: torch.Tensor):
"""Forward call."""
input_x = x
x = x.view(*(x.shape[:-2]), -1).mean(-1)
x = F.relu(self.linear1(x), inplace=True)
x = self.linear2(x)
x = x.unsqueeze(-1).unsqueeze(-1)
x = torch.sigmoid(x)
x = torch.mul(input_x, x)
return x
| cSE |
python | celery__celery | t/unit/tasks/test_chord.py | {
"start": 8078,
"end": 9710
} | class ____(ChordCase):
def test_eager(self):
from celery import chord
@self.app.task(shared=False)
def addX(x, y):
return x + y
@self.app.task(shared=False)
def sumX(n):
return sum(n)
self.app.conf.task_always_eager = True
x = chord(addX.s(i, i) for i in range(10))
body = sumX.s()
result = x(body)
assert result.get() == sum(i + i for i in range(10))
def test_apply(self):
self.app.conf.task_always_eager = False
from celery import chord
m = Mock()
m.app.conf.task_always_eager = False
m.AsyncResult = AsyncResult
prev, chord.run = chord.run, m
try:
x = chord(self.add.s(i, i) for i in range(10))
body = self.add.s(2)
result = x(body)
assert result.id
# does not modify original signature
with pytest.raises(KeyError):
body.options['task_id']
chord.run.assert_called()
finally:
chord.run = prev
def test_init(self):
from celery import chord
from celery.utils.serialization import pickle
@self.app.task(shared=False)
def addX(x, y):
return x + y
@self.app.task(shared=False)
def sumX(n):
return sum(n)
x = chord(addX.s(i, i) for i in range(10))
# kwargs used to nest and recurse in serialization/deserialization
# (#6810)
assert x.kwargs['kwargs'] == {}
assert pickle.loads(pickle.dumps(x)).kwargs == x.kwargs
| test_chord |
python | google__jax | jax/experimental/jax2tf/tests/call_tf_test.py | {
"start": 40538,
"end": 62204
} | class ____(tf_test_util.JaxToTfTestCase):
"""Reloading output of call_tf into TF with jax2tf."""
def setUp(self):
if tf is None:
raise unittest.SkipTest("Test requires tensorflow")
# TODO(b/171320191): this line works around a missing context initialization
# bug in TensorFlow.
_ = tf.add(1, 1)
super().setUp()
def test_alternate(self):
# Alternate sin/cos with sin in TF and cos in JAX
f_tf_inner = tf.math.sin
def f_jax(x_jax):
y_jax = jnp.cos(x_jax)
z_jax = jax2tf.call_tf(f_tf_inner)(y_jax)
return jnp.cos(z_jax)
def f_tf_outer(x_tf):
y_tf = tf.math.sin(x_tf)
z_tf = jax2tf.convert(f_jax)(y_tf)
return tf.math.sin(z_tf)
x = np.float32(0.7)
self.assertAllClose(np.sin(np.cos(np.sin(np.cos(np.sin(x))))),
f_tf_outer(x).numpy())
xv = tf.Variable(x)
with tf.GradientTape() as tape:
res = f_tf_outer(xv)
g_tf = tape.gradient(res, xv)
_, gf = tf_test_util.ComputeTfValueAndGrad(f_tf_outer, (x,))
# Eager
expected_res = np.sin(np.cos(np.sin(np.cos(np.sin(x)))))
self.assertAllClose(expected_res, f_tf_outer(x).numpy())
# Gradient
expected_grad = (np.cos(np.cos(np.sin(np.cos(np.sin(x))))) *
np.sin(np.sin(np.cos(np.sin(x)))) *
np.cos(np.cos(np.sin(x))) *
np.sin(np.sin(x)) *
np.cos(x))
self.assertAllClose(expected_grad, g_tf.numpy())
# Graph
self.assertAllClose(expected_res,
tf.function(f_tf_outer, autograph=False)(x).numpy())
# Compiled
self.assertAllClose(expected_res,
tf.function(f_tf_outer, autograph=False,
jit_compile=True)(x).numpy())
def test_saved_model(self):
x = np.array([.7, .8], dtype=np.float32)
def fun_tf(x):
return tf.math.sin(x)
def fun_jax(x):
return jax2tf.call_tf(fun_tf)(x)
# Now convert and save to SavedModel
fun_tf_rt = jax2tf.convert(fun_jax)
res = fun_tf_rt(x)
self.assertAllClose(np.sin(x), res.numpy())
res = tf.function(fun_tf_rt, autograph=False)(x)
self.assertAllClose(np.sin(x), res.numpy())
res = tf.function(fun_tf_rt, jit_compile=True, autograph=False)(x)
self.assertAllClose(np.sin(x), res.numpy())
reloaded_f, _ = tf_test_util.SaveAndLoadFunction(
fun_tf_rt, input_args=[x])
res = reloaded_f(x)
self.assertAllClose(np.sin(x), res.numpy())
def test_saved_model_polymorphic_input_static_output(self):
x = np.array([.7, .8], dtype=np.float32)
def fun_tf(x):
return tf.math.reduce_sum(tf.math.sin(x))
def fun_jax(x):
return jax2tf.call_tf(fun_tf)(x)
# Now convert and save to SavedModel
fun_tf_rt = jax2tf.convert(fun_jax)
res = fun_tf_rt(x)
self.assertAllClose(fun_tf(x), res.numpy())
res = tf.function(fun_tf_rt, autograph=False)(x)
self.assertAllClose(fun_tf(x), res.numpy())
res = tf.function(fun_tf_rt, jit_compile=True, autograph=False)(x)
self.assertAllClose(fun_tf(x), res.numpy())
reloaded_f, _ = tf_test_util.SaveAndLoadFunction(
fun_tf_rt, input_args=[x])
res = reloaded_f(x)
self.assertAllClose(fun_tf(x), res.numpy())
def test_function_dynamic_shape(self):
# Call a function for which shape inference does not give an output
# shape.
x = np.array([-1, 0, 1], dtype=np.int32)
def fun_tf(x): # x:i32[3]
# The shape depends on the value of x
return tf.cond(x[0] >= 0, lambda: x, lambda: x[1:])
# Call in eager mode. Should work!
res1 = jax2tf.call_tf(fun_tf)(x)
expected = x[1:]
self.assertAllClose(expected, res1, check_dtypes=False)
# Now under jit, should fail because the function is not compilable
with self.assertRaisesRegex(ValueError, _call_tf_dynamic_shape_error):
fun_jax = jax.jit(jax2tf.call_tf(fun_tf))
fun_jax(x)
# TODO(necula): this should work in op-by-op mode, but it fails because
# jax2tf.convert does abstract evaluation.
with self.assertRaisesRegex(ValueError, _call_tf_dynamic_shape_error):
fun_tf_rt = jax2tf.convert(jax2tf.call_tf(fun_tf))
fun_tf_rt(x)
@_parameterized_jit
def test_shape_poly_error_no_output_shape_dtype(self, with_jit=True):
x = np.array([7, 8, 9, 10], dtype=np.float32)
def fun_jax(x):
return jax2tf.call_tf(tf.math.sin)(x)
fun_tf_rt = _maybe_tf_jit(with_jit,
jax2tf.convert(fun_jax, polymorphic_shapes=["b, ..."]))
with self.assertRaisesRegex(ValueError, _call_tf_dynamic_shape_error):
fun_tf_rt(x)
@_parameterized_jit
def test_shape_poly_error_mismatch_output_shape_dtype_tree(self, with_jit=False):
x = np.array([7, 8, 9, 10], dtype=np.float32)
def fun_jax(x):
return jax2tf.call_tf(tf.math.sin,
output_shape_dtype=(jax.ShapeDtypeStruct(x.shape, x.dtype),
jax.ShapeDtypeStruct(x.shape, x.dtype)))(x)
fun_tf_rt = _maybe_tf_jit(with_jit,
jax2tf.convert(fun_jax, polymorphic_shapes=["b, ..."]))
with self.assertRaisesRegex(
ValueError,
"The pytree of the TensorFlow function results does not match the pytree of the declared output_shape_dtype"):
fun_tf_rt(x)
@parameterized.named_parameters(
_named_test(with_jit=with_jit, kind=kind)
for with_jit in [True, False]
for kind in ["bad_rank", "bad_dim", "bad_dtype", "bad_dtype_x64"])
def test_shape_poly_error_mismatch_output_shape_dtype(self, with_jit=False, kind="bad_rank"):
x = np.array([7, 8, 9, 10], dtype=np.float32)
if kind == "bad_rank":
def fun_jax(x):
return jax2tf.call_tf(lambda x: x,
# Wrong shape rank
output_shape_dtype=jax.ShapeDtypeStruct((), x.dtype))(x)
elif kind == "bad_dim":
def fun_jax(x):
bad_shape = (5 + x.shape[0],)
y = jax2tf.call_tf(lambda x: x,
# Wrong dimension
output_shape_dtype=jax.ShapeDtypeStruct(bad_shape, x.dtype))(x)
# JAX will believe that the following is Ok, leading to downstream error in TF
return y + jnp.ones(bad_shape, dtype=x.dtype)
elif kind == "bad_dtype":
def fun_jax(x):
return jax2tf.call_tf(lambda x: x,
output_shape_dtype=jax.ShapeDtypeStruct(x.shape, np.int32))(x)
elif kind == "bad_dtype_x64":
def fun_jax(x):
return jax2tf.call_tf(lambda x: x * np.float64(3.),
output_shape_dtype=jax.ShapeDtypeStruct(x.shape, np.float64))(x)
else:
assert False
expect_ex = ValueError
expect_error = r"The shapes or dtypes returned by the TensorFlow function do not match the declared output_shape_dtype"
# Call without shape polymorphism
fun_tf_rt = _maybe_tf_jit(with_jit, jax2tf.convert(fun_jax))
with self.assertRaisesRegex(expect_ex, expect_error):
fun_tf_rt(x)
# Now with shape polymorphism
if kind == "bad_dim" and with_jit:
# TODO: in jit more the error pops up later, at AddV2
expect_error = "Dimensions must be equal, but are 4 and 9 for .* AddV2"
if kind == "bad_dim":
# TODO(b/268386622): call_tf with shape polymorphism and native serialization.
expect_error = "Error compiling TensorFlow function"
fun_tf_rt = _maybe_tf_jit(with_jit,
jax2tf.convert(fun_jax, polymorphic_shapes=["b, ..."]))
with self.assertRaisesRegex(expect_ex, expect_error):
fun_tf_rt(x)
@parameterized.named_parameters(
_named_test(f2_function=f2_function, f2_saved_model=f2_saved_model,
f4_function=f4_function, f4_saved_model=f4_saved_model)
for f2_function in [True, False]
for f2_saved_model in [True, False]
for f4_function in [True, False]
for f4_saved_model in [True, False])
def test_several_round_trips(self,
f2_function=False, f2_saved_model=False,
f4_function=False, f4_saved_model=False):
x = np.array(.7, dtype=np.float32)
# f(n)(x) = 2. * x^n
def f(n):
def fn(x):
acc = np.array(2., dtype=x.dtype)
for i in range(n):
acc *= x
return acc
return fn
f2_tf = lambda x: x * jax2tf.convert(f(1))(x)
if f2_function:
f2_tf = tf.function(f2_tf, autograph=False)
if f2_saved_model:
f2_tf, _ = tf_test_util.SaveAndLoadFunction(f2_tf, input_args=[x])
self.assertAllClose(f(2)(x), f2_tf(x).numpy())
_, (g_f2_ft,) = tf_test_util.ComputeTfValueAndGrad(f2_tf, [x])
self.assertAllClose(jax.grad(f(2))(x), g_f2_ft.numpy())
f3_jax = lambda x: x * jax2tf.call_tf(f2_tf)(x)
self.assertAllClose(f(3)(x), f3_jax(x))
self.assertAllClose(f(3)(x), jax.jit(f3_jax)(x))
self.assertAllClose(jax.grad(f(3))(x), jax.grad(f3_jax)(x))
f4_tf = lambda x: x * jax2tf.convert(f3_jax)(x)
self.assertAllClose(f(4)(x), f4_tf(x).numpy())
_, (g_f4_ft,) = tf_test_util.ComputeTfValueAndGrad(f4_tf, [x])
self.assertAllClose(jax.grad(f(4))(x), g_f4_ft.numpy())
if f4_function:
f4_tf = tf.function(f4_tf, autograph=False)
if f4_saved_model:
f4_tf, _ = tf_test_util.SaveAndLoadFunction(f4_tf, input_args=[x])
self.assertAllClose(f(4)(x), f4_tf(x).numpy())
_, (g_f4_ft,) = tf_test_util.ComputeTfValueAndGrad(f4_tf, [x])
self.assertAllClose(jax.grad(f(4))(x), g_f4_ft.numpy())
@classmethod
def _walk_stablehlo_operations(cls, op, cb):
"""walk the stablehlo operation recursive with callback function."""
cb(op)
for region in op.operation.regions:
for block in region:
for op in block:
cls._walk_stablehlo_operations(op, cb)
def test_call_tf_graph(self):
const = tf.Variable(0.0, dtype=tf.float32)
@tf.function(jit_compile=True)
def tf_func_1(x):
return x * x + const
@tf.function
def tf_func_2(x, y):
return tf_func_1(x) + y
@tf.function
def tf_func_3(x, y, z):
return tf_func_2(x, y) + z, z
x = jnp.array(3.0, dtype=jnp.float32)
y = jnp.array(3.0, dtype=jnp.float32)
z = jnp.array(5.0, dtype=jnp.float32)
f_jax = jax.jit(jax2tf.call_tf(tf_func_3, call_tf_graph=False))
stablehlo_module = f_jax.lower(x, y, z).compiler_ir("stablehlo")
self.assertNotIn("stablehlo.custom_call", str(stablehlo_module))
f_jax = jax.jit(
jax2tf.call_tf(
tf_func_3,
call_tf_graph=True,
)
)
with self.assertRaisesRegex(
ValueError,
"call_tf_graph=True only support exporting by jax2tf.convert currently",
):
stablehlo_module = f_jax.lower(x, y, z).compiler_ir("stablehlo")
self.assertIn("stablehlo.custom_call", str(stablehlo_module))
called_index_list = []
def _extract_info(op):
if op.operation.name != "stablehlo.custom_call":
return
tf_backend_config = ir.DictAttr(op.attributes["tf.backend_config"])
called_index = ir.IntegerAttr(tf_backend_config["called_index"]).value
called_index_list.append(called_index)
self._walk_stablehlo_operations(stablehlo_module, _extract_info)
self.assertLen(called_index_list, 1)
@parameterized.named_parameters(
dict(
testcase_name="multiple_outputs",
tf_f=lambda x: tf.py_function(np.sin, [x], tf.float32),
output_shape_dtype=jax.ShapeDtypeStruct((10,), jnp.float32),
),
dict(
testcase_name="zero_outputs",
tf_f=lambda x: print(tf.strings.length(tf.constant("hello, world"))),
output_shape_dtype=None,
),
)
def test_call_tf_graph_non_compilable(self, tf_f, output_shape_dtype):
inputs = jnp.ones([10], dtype=jnp.float32)
called_index_list = []
xla_call_module_list = []
def _extract_info(op):
if op.operation.name != "stablehlo.custom_call":
return
tf_backend_config = ir.DictAttr(op.attributes["tf.backend_config"])
called_index = ir.IntegerAttr(tf_backend_config["called_index"]).value
called_index_list.append(called_index)
jax_f = jax2tf.call_tf(
tf_f,
call_tf_graph=True,
output_shape_dtype=output_shape_dtype,
)
# Eager mode
self.assertAllClose(tf_f(inputs), jax_f(inputs))
# Jit mode
stablehlo_module = None
with self.assertRaisesRegex(
ValueError,
"call_tf_graph=True only support exporting by jax2tf.convert currently",
):
stablehlo_module = jax.jit(jax_f).lower(inputs).compiler_ir("stablehlo")
if stablehlo_module:
self.assertIn(
"stablehlo.custom_call @tf.call_tf_function",
str(stablehlo_module),
)
self.assertIn("tf.backend_config", str(stablehlo_module))
self._walk_stablehlo_operations(stablehlo_module, _extract_info)
self.assertLen(called_index_list, 1)
# Test model exporting and reloading.
# There is no runtime support yet so it can not run.
tf_f_rt = jax2tf.convert(
jax_f,
with_gradient=False,
)
_, restored_model = tf_test_util.SaveAndLoadFunction(
tf_f_rt, input_args=[inputs]
)
func_def = restored_model.f.concrete_functions[0]
for node_def in func_def.graph.as_graph_def().node:
if node_def.op == "XlaCallModule":
xla_call_module_list.append(node_def)
# There is only one xla_call_module in the saved model.
self.assertLen(xla_call_module_list, 1)
# Check the xla_call_module version and function_list attributes.
xla_call_module = xla_call_module_list[0]
self.assertGreaterEqual(xla_call_module.attr["version"].i, 5)
self.assertIn("function_list", str(xla_call_module.attr))
xla_call_module_list.clear()
called_index_list.clear()
# If JAX calls same tensorflow function by `jax2tf.call_tf` twice,
# it should return two different tf concrete functions.
def jax_f_2(x):
res1 = jax2tf.call_tf(
tf_f,
call_tf_graph=True,
output_shape_dtype=output_shape_dtype,
)(x)
res2 = jax2tf.call_tf(
tf_f,
call_tf_graph=True,
output_shape_dtype=output_shape_dtype,
)(x)
return res1, res2
stablehlo_module = None
with self.assertRaisesRegex(ValueError, "call_tf_graph=True only support exporting by jax2tf.convert currently"):
stablehlo_module = jax.jit(jax_f_2).lower(inputs).compiler_ir("stablehlo")
if stablehlo_module:
self._walk_stablehlo_operations(stablehlo_module, _extract_info)
xla_call_module_list.clear()
def test_b279454591(self):
"""Test case when tensorflow function returns `StatefulPartitionedCall` op."""
inputs = jnp.ones([10], dtype=jnp.float32)
# With one or more outputs, it is okay.
def tf_f(x):
y = tf.math.sin(3.0)
tf.print(y)
return x
jax_f = jax2tf.call_tf(
tf.function(tf_f),
call_tf_graph=True,
)
tf_f_rt = jax2tf.convert(
jax_f,
with_gradient=False,
)
_, _ = tf_test_util.SaveAndLoadFunction(tf_f_rt, input_args=[inputs])
# With zero output, it return `StatefulPartitionedCall` op instead.
def tf_f_2():
y = tf.math.sin(3.0)
tf.print(y)
return
jax_f_2 = jax2tf.call_tf(tf.function(tf_f_2), call_tf_graph=True)
tf_f_rt_2 = jax2tf.convert(
jax_f_2,
with_gradient=False,
)
_, _ = tf_test_util.SaveAndLoadFunction(tf_f_rt_2, input_args=[])
@jtu.parameterized_filterable(
kwargs=[dict(version=version) for version in [9]]
)
def test_call_tf_graph_ordered(self, *, version: int):
with config.jax_export_calling_convention_version(version):
logging.info(
"Using JAX serialization version %s",
jax.config.jax_export_calling_convention_version)
@tf.function
def tf_print(x):
tf.print(x)
call_tf_print = jax2tf.call_tf(
tf_print,
call_tf_graph=True,
ordered=True,
)
x = jnp.array(1.0, dtype=jnp.float32)
def body(i, x):
call_tf_print(x)
return x + 1
@jax.jit
def f_jax(x):
return jax.lax.fori_loop(0, 4, body, x)
num_custom_calls = 0
def _check_mlir_ops(op):
nonlocal num_custom_calls
if (
op.operation.name == "stablehlo.custom_call"
and ir.StringAttr(op.attributes["call_target_name"]).value
== "tf.call_tf_function"
):
num_custom_calls += 1
# The custom call op must have `has_token_input_output` attribute.
tf_backend_config = ir.DictAttr(op.attributes["tf.backend_config"])
self.assertTrue(
ir.BoolAttr(tf_backend_config["has_token_input_output"]).value
)
# Verify that the first argument/result of the custom call op is a token
# type. This is a calling convention defined by `has_token_input_output`.
self.assertTrue(hlo.TokenType.isinstance(op.operands[0].type))
self.assertTrue(hlo.TokenType.isinstance(op.results[0].type))
stablehlo_module = None
with self.assertRaisesRegex(
ValueError,
"call_tf_graph=True only support exporting by jax2tf.convert currently",
):
lower = f_jax.lower(x)
self.assertNotEmpty(lower._lowering.compile_args["ordered_effects"])
stablehlo_module = lower.compiler_ir("stablehlo")
if stablehlo_module:
self._walk_stablehlo_operations(stablehlo_module, _check_mlir_ops)
self.assertEqual(num_custom_calls, 1)
f_tf = jax2tf.convert(
f_jax,
with_gradient=False,
)
_, restored_model = tf_test_util.SaveAndLoadFunction(f_tf, input_args=[x])
@jtu.parameterized_filterable(
kwargs=[dict(poly=poly, version=version)
for poly in [True, False]
for version in [9]]
)
def test_call_tf_ordered_dead_inputs(self, *, poly: bool, version: int):
with config.jax_export_calling_convention_version(version):
logging.info(
"Using JAX serialization version %s",
jax.config.jax_export_calling_convention_version)
def f_jax(x1, x_dead, x3):
return (x1, jax2tf.call_tf(lambda x: tf.math.sin(x), ordered=True,
call_tf_graph=True)(x3))
if poly:
polymorphic_shapes = ["b", None, None]
else:
polymorphic_shapes = None
f_tf = jax2tf.convert(f_jax, polymorphic_shapes=polymorphic_shapes)
x1 = np.arange(3, dtype=np.float32)
x_dead = np.arange(4, dtype=np.float32)
x3 = np.arange(5, dtype=np.float32)
self.assertAllClose(f_jax(x1, x_dead, x3),
f_tf(x1, x_dead, x3))
@jtu.parameterized_filterable(
kwargs=[dict(ordered=ordered, version=version)
for ordered in [True, False]
for version in [9]
]
)
def test_call_tf_graph_polymorphic(self, ordered: bool, version: int):
with config.jax_export_calling_convention_version(version):
logging.info(
"Using JAX serialization version %s",
jax.config.jax_export_calling_convention_version)
@tf.function(jit_compile=True, autograph=False)
@partial(jax2tf.convert,
with_gradient=False,
polymorphic_shapes=["(b)"])
@jax.jit
def tf_f_2(x):
tf_f = lambda x: print(tf.strings.length(tf.constant("hello, world")))
jax2tf.call_tf(tf_f,
call_tf_graph=True,
ordered=ordered)(x)
return x
x = np.arange(3, dtype=np.int32)
_ = tf.function(tf_f_2, autograph=False).get_concrete_function(x)
# TODO(b/293927250): call_tf_graph=True only accept concrete_function. The
# workaround here is to set `module.call=concrete_fn.`.
@unittest.skip(
"The root cause here is because the XLACallModule.function_list attribute"
" depends on JAX call_tf lowering. The 2nd time tf.SavedModel TF tracing"
" will not trigger call_tf tracing since it was already cached. The"
" solution is to create the `CallTFContext` to make TF tracing and JAX"
" tracing work together correctly."
)
def test_call_tf_graph_save_and_load(self):
def jax_func(x):
def func_tf(x):
return tf.math.sin(x)
return jnp.cos(
jax2tf.call_tf(func_tf, output_shape_dtype=x, call_tf_graph=True)(x)
)
data_inputs = (np.array([0.5, 0.7], dtype=np.float32),)
def tf_func(the_input):
res = jax2tf.convert(jax_func)(the_input)
return tf.identity(res, name="the_result")
jit_tf_func = tf.function(
tf_func,
autograph=False,
jit_compile=True,
)
# The next line is necessary to reproduce this issue. It trigger TF
# ConcreteFunction tracing. Otherwise, you will fail with another error
# `Found zero restored functions for caller function`.
_ = jit_tf_func.get_concrete_function(*data_inputs)
module = tf.Module()
module.call = jit_tf_func # Switching to concrete_function works.
root_dir = self.create_tempdir()
saved_model_dir = os.path.join(root_dir, "saved_model")
tf.saved_model.save(
module,
saved_model_dir,
options=tf.saved_model.SaveOptions(experimental_custom_gradients=False),
)
loaded_model = tf.saved_model.load(saved_model_dir)
res = loaded_model.call(*data_inputs)
self.assertAllClose(jax_func(*data_inputs), res)
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
| RoundTripToTfTest |
python | Textualize__textual | tests/test_binding_inheritance.py | {
"start": 5095,
"end": 5256
} | class ____(Screen):
"""A screen with a simple low-priority alpha key binding."""
BINDINGS = [Binding("a", "a", "a", priority=False)]
| ScreenWithLowBindings |
python | huggingface__transformers | tests/models/sam3_tracker/test_modeling_sam3_tracker.py | {
"start": 8163,
"end": 21034
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as SAM's vision encoder does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
all_model_classes = (Sam3TrackerModel,) if is_torch_available() else ()
pipeline_model_mapping = (
{"feature-extraction": Sam3TrackerModel, "mask-generation": Sam3TrackerModel} if is_torch_available() else {}
)
test_resize_embeddings = False
_is_composite = True
def setUp(self):
self.model_tester = Sam3TrackerModelTester(self)
common_properties = ["initializer_range"]
self.config_tester = ConfigTester(
self, config_class=Sam3TrackerConfig, has_text_modality=False, common_properties=common_properties
)
def test_config(self):
self.config_tester.run_common_tests()
@unittest.skip(reason="SAM's vision encoder does not use inputs_embeds")
def test_inputs_embeds(self):
pass
def test_model_get_set_embeddings(self):
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
model = model_class(config)
self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
x = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(x, nn.Linear))
def test_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*config_and_inputs)
# Overriding as Sam3TrackerModel returns vision_attentions
def test_attention_outputs(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
config.return_dict = True
for model_class in self.all_model_classes:
inputs_dict["output_attentions"] = True
inputs_dict["output_hidden_states"] = False
config.return_dict = True
model = model_class._from_config(config, attn_implementation="eager")
config = model.config
model.to(torch_device)
model.eval()
with torch.no_grad():
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
attentions = outputs.vision_attentions
expected_num_attentions = self.model_tester.num_hidden_layers
self.assertEqual(len(attentions), expected_num_attentions)
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
config.mask_decoder_config.output_attentions = True
config.vision_config.output_attentions = True
config.output_attentions = True
model = model_class(config)
model.to(torch_device)
model.eval()
with torch.no_grad():
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
attentions = outputs.vision_attentions
self.assertEqual(len(attentions), expected_num_attentions)
# Check attention is always last and order is fine
inputs_dict["output_attentions"] = True
inputs_dict["output_hidden_states"] = True
model = model_class(config)
model.to(torch_device)
model.eval()
with torch.no_grad():
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
attentions = outputs.vision_attentions
self.assertEqual(len(attentions), expected_num_attentions)
# Override as Sam3TrackerModel has different sub-modules
def test_sdpa_can_dispatch_composite_models(self):
"""
Tests if composite models dispatch correctly on SDPA/eager when requested so when loading the model.
This tests only by looking at layer names, as usually SDPA layers are called "SDPAAttention".
In contrast to the above test, this one checks if the "config._attn_implementation" is a dict after the model
is loaded, because we manually replicate requested attn implementation on each sub-config when loading.
See https://github.com/huggingface/transformers/pull/32238 for more info
The test tries to cover most general cases of composite models, VLMs with vision and text configs. Any model
that has a different set of sub-configs has to overwrite this test.
"""
if not self.has_attentions:
self.skipTest(reason="Model architecture does not support attentions")
if not self._is_composite:
self.skipTest(f"{self.all_model_classes[0].__name__} does not support SDPA")
for model_class in self.all_model_classes:
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
model = model_class(config)
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(tmpdirname)
model_sdpa = model_class.from_pretrained(tmpdirname, attn_implementation="sdpa")
model_sdpa = model_sdpa.eval().to(torch_device)
vision_encoder_sdpa = getattr(model_sdpa, "vision_encoder")
mask_decoder_sdpa = getattr(model_sdpa, "mask_decoder")
# `None` as it is the requested one which will be assigned to each sub-config
# Sub-model will dispatch to SDPA if it can (checked below that `SDPA` layers are present)
self.assertTrue(mask_decoder_sdpa.config._attn_implementation == "sdpa")
self.assertTrue(vision_encoder_sdpa.config._attn_implementation == "sdpa")
model_eager = model_class.from_pretrained(tmpdirname, attn_implementation="eager")
model_eager = model_eager.eval().to(torch_device)
self.assertTrue(getattr(model_eager, "mask_decoder").config._attn_implementation == "eager")
self.assertTrue(getattr(model_eager, "vision_encoder").config._attn_implementation == "eager")
for name, submodule in model_eager.named_modules():
class_name = submodule.__class__.__name__
if (
class_name.endswith("Attention")
and getattr(submodule, "config", None)
and submodule.config._attn_implementation == "sdpa"
):
raise ValueError("The eager model should not have SDPA attention layers")
# Override as Sam3TrackerModel doesn't have hidden states
@unittest.skip(reason="skip for now (head_size should be a multiple of 8)")
def flash_attn_inference_equivalence(
self, attn_implementation: str, padding_side: str, atol: float = 4e-2, rtol: float = 4e-2
):
r"""
Tests the equivalence between the eager and flash attention implementations.
This test is only for inference and runs with `dtype=torch.bfloat16`.
"""
if not self.has_attentions:
self.skipTest(reason="Model architecture does not support attentions")
for model_class in self.all_model_classes:
if (attn_implementation == "flash_attention_2" and not model_class._supports_flash_attn_2) or (
attn_implementation == "flash_attention_3" and not model_class._supports_flash_attn_3
):
self.skipTest(f"{model_class.__name__} does not support {attn_implementation}")
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
model = model_class(config)
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(tmpdirname)
model_fa = model_class.from_pretrained(
tmpdirname, dtype=torch.bfloat16, attn_implementation=attn_implementation
)
model_fa.to(torch_device)
model = model_class.from_pretrained(tmpdirname, dtype=torch.bfloat16)
model.to(torch_device)
dummy_input = inputs_dict[model.main_input_name][:1]
if dummy_input.dtype in [torch.float32, torch.float16]:
dummy_input = dummy_input.to(torch.bfloat16)
dummy_attention_mask = inputs_dict.get("attention_mask", None)
if dummy_attention_mask is not None:
dummy_attention_mask = dummy_attention_mask[:1]
if padding_side == "left":
dummy_attention_mask[:, 1:] = 1
dummy_attention_mask[:, :1] = 0
else:
dummy_attention_mask[:, :-1] = 1
dummy_attention_mask[:, -1:] = 0
if model.config.is_encoder_decoder:
decoder_input_ids = inputs_dict.get("decoder_input_ids", dummy_input)[:1]
outputs = model(dummy_input, decoder_input_ids=decoder_input_ids, output_hidden_states=True)
outputs_fa = model_fa(dummy_input, decoder_input_ids=decoder_input_ids, output_hidden_states=True)
else:
outputs = model(dummy_input, output_hidden_states=True)
outputs_fa = model_fa(dummy_input, output_hidden_states=True)
logits = outputs.vision_hidden_states[-1]
logits_fa = outputs_fa.vision_hidden_states[-1]
assert torch.allclose(logits_fa, logits, atol=atol, rtol=rtol)
if model.config.is_encoder_decoder:
other_inputs = {
"decoder_input_ids": decoder_input_ids,
"decoder_attention_mask": dummy_attention_mask,
"output_hidden_states": True,
}
if dummy_attention_mask is not None:
other_inputs["attention_mask"] = dummy_attention_mask
outputs = model(dummy_input, **other_inputs)
outputs_fa = model_fa(dummy_input, **other_inputs)
else:
other_inputs = {
"output_hidden_states": True,
}
if dummy_attention_mask is not None:
other_inputs["attention_mask"] = dummy_attention_mask
outputs = model(dummy_input, **other_inputs)
outputs_fa = model_fa(dummy_input, **other_inputs)
logits = outputs.vision_hidden_states[-1]
logits_fa = outputs_fa.vision_hidden_states[-1]
if padding_side == "left":
assert torch.allclose(logits_fa[1:], logits[1:], atol=atol, rtol=rtol)
# check with inference + dropout
model.train()
_ = model_fa(dummy_input, **other_inputs)
else:
assert torch.allclose(logits_fa[:-1], logits[:-1], atol=atol, rtol=rtol)
# Override as difference slightly higher than the threshold
def test_batching_equivalence(self, atol=5e-4, rtol=5e-4):
super().test_batching_equivalence(atol=atol, rtol=rtol)
@unittest.skip(reason="Sam3TrackerModel does not support training")
def test_retain_grad_hidden_states_attentions(self):
pass
@unittest.skip(reason="Hidden_states is tested in sub modules tests")
def test_hidden_states_output(self):
pass
@slow
def test_model_from_pretrained(self):
model_name = "facebook/sam2.1-hiera-tiny"
model = Sam3TrackerModel.from_pretrained(model_name)
self.assertIsNotNone(model)
def test_sdpa_can_compile_dynamic(self):
self.skipTest(reason="SAM2 model can't be compiled dynamic yet")
def prepare_image():
img_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/truck.jpg"
raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB")
return raw_image
def prepare_groceries_image():
img_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/groceries.jpg"
raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB")
return raw_image
def prepare_dog_img():
img_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/dog-sam.png"
raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB")
return raw_image
def prepare_video():
video_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/bedroom.mp4"
raw_video, _ = load_video(video_url)
return raw_video
@slow
| Sam3TrackerModelTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 376744,
"end": 377497
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of UpdateTeamDiscussionComment"""
__schema__ = github_schema
__field_names__ = ("id", "body", "body_version", "client_mutation_id")
id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="id")
"""The ID of the comment to modify."""
body = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="body")
"""The updated text of the comment."""
body_version = sgqlc.types.Field(String, graphql_name="bodyVersion")
"""The current version of the body content."""
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
| UpdateTeamDiscussionCommentInput |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/common/db/test_dags.py | {
"start": 1322,
"end": 13822
} | class ____:
"""Unit tests for generate_dag_with_latest_run_query function."""
@staticmethod
def _clear_db():
clear_db_runs()
clear_db_dags()
clear_db_dag_bundles()
@pytest.fixture(autouse=True)
def setup_teardown(self):
"""Setup and teardown for each test."""
self._clear_db()
yield
self._clear_db()
@pytest.fixture
def dag_with_queued_run(self, session, testing_dag_bundle):
"""Returns a DAG with a QUEUED DagRun and null start_date."""
dag_id = "dag_with_queued_run"
# Create DagModel
dag_model = DagModel(
dag_id=dag_id,
bundle_name="testing",
is_stale=False,
is_paused=False,
fileloc="/tmp/dag.py",
)
session.add(dag_model)
session.flush()
# Create DagRun with start_date=None (QUEUED state)
dagrun = DagRun(
dag_id=dag_id,
run_id="manual__queued",
run_type="manual",
logical_date=utcnow(),
state=DagRunState.QUEUED,
start_date=None,
)
session.add(dagrun)
session.commit()
return dag_model, dagrun
@pytest.fixture
def dag_with_running_run(self, session):
"""Returns a DAG with a RUNNING DagRun and a valid start_date."""
dag_id = "dag_with_running_run"
# Create DagModel
dag_model = DagModel(
dag_id=dag_id,
bundle_name="testing",
is_stale=False,
is_paused=False,
fileloc="/tmp/dag2.py",
)
session.add(dag_model)
session.flush()
# Create DagRun with start_date set (RUNNING state)
start_time = utcnow()
dagrun = DagRun(
dag_id=dag_id,
run_id="manual__running",
run_type="manual",
logical_date=start_time,
state=DagRunState.RUNNING,
start_date=start_time,
)
session.add(dagrun)
session.commit()
return dag_model, dagrun
def test_includes_queued_run_without_start_date(self, dag_with_queued_run, session):
"""DAGs with QUEUED runs and null start_date should be included when no filters are applied, and joined DagRun state must not be None."""
dag_model, _ = dag_with_queued_run
query = generate_dag_with_latest_run_query(
max_run_filters=[],
order_by=SortParam(allowed_attrs=["dag_id"], model=DagModel).set_value(["dag_id"]),
)
# Also fetch joined DagRun's state and start_date
extended_query = query.add_columns(DagRun.state, DagRun.start_date)
result = session.execute(extended_query).fetchall()
dag_row = next((row for row in result if row[0].dag_id == dag_model.dag_id), None)
assert dag_row is not None
dagrun_state = dag_row[1]
assert dagrun_state is not None, "Joined DagRun state must not be None"
def test_includes_queued_run_when_ordering_by_state(
self, dag_with_queued_run, dag_with_running_run, session
):
"""DAGs with QUEUED runs and null start_date, and RUNNING runs must all have joined DagRun info not None."""
queued_dag_model, _ = dag_with_queued_run
running_dag_model, _ = dag_with_running_run
query = generate_dag_with_latest_run_query(
max_run_filters=[],
order_by=SortParam(allowed_attrs=["last_run_state"], model=DagModel).set_value(
["last_run_state"]
),
)
extended_query = query.add_columns(DagRun.state, DagRun.start_date)
result = session.execute(extended_query).fetchall()
# QUEUED DAG
queued_row = next((row for row in result if row[0].dag_id == queued_dag_model.dag_id), None)
assert queued_row is not None
assert queued_row[1] is not None, "Joined DagRun state for QUEUED DAG must not be None"
# RUNNING DAG
running_row = next((row for row in result if row[0].dag_id == running_dag_model.dag_id), None)
assert running_row is not None
assert running_row[1] is not None, "Joined DagRun state for RUNNING DAG must not be None"
assert running_row[2] is not None, "Joined DagRun start_date for RUNNING DAG must not be None"
def test_includes_queued_run_when_ordering_by_start_date(
self, dag_with_queued_run, dag_with_running_run, session
):
"""DAGs with QUEUED runs and RUNNING runs must all have joined DagRun info not None when ordering by start_date."""
queued_dag_model, _ = dag_with_queued_run
running_dag_model, _ = dag_with_running_run
query = generate_dag_with_latest_run_query(
max_run_filters=[],
order_by=SortParam(allowed_attrs=["last_run_start_date"], model=DagModel).set_value(
["last_run_start_date"]
),
)
extended_query = query.add_columns(DagRun.state, DagRun.start_date)
result = session.execute(extended_query).fetchall()
# QUEUED DAG
queued_row = next((row for row in result if row[0].dag_id == queued_dag_model.dag_id), None)
assert queued_row is not None
assert queued_row[1] is not None, "Joined DagRun state for QUEUED DAG must not be None"
# RUNNING DAG
running_row = next((row for row in result if row[0].dag_id == running_dag_model.dag_id), None)
assert running_row is not None
assert running_row[1] is not None, "Joined DagRun state for RUNNING DAG must not be None"
assert running_row[2] is not None, "Joined DagRun start_date for RUNNING DAG must not be None"
@pytest.mark.usefixtures("testing_dag_bundle")
def test_latest_queued_run_without_start_date_is_included(self, session):
"""Even if the latest DagRun is QUEUED+start_date=None, joined DagRun state must not be None."""
dag_id = "dag_with_multiple_runs"
dag_model = DagModel(
dag_id=dag_id,
bundle_name="testing",
is_stale=False,
is_paused=False,
fileloc="/tmp/dag3.py",
)
session.add(dag_model)
session.flush()
older_run = DagRun(
dag_id=dag_id,
run_id="manual__older",
run_type="manual",
logical_date=datetime(2025, 1, 1, tzinfo=timezone.utc),
state=DagRunState.SUCCESS,
start_date=datetime(2025, 1, 1, tzinfo=timezone.utc),
)
session.add(older_run)
newer_run = DagRun(
dag_id=dag_id,
run_id="manual__newer_queued",
run_type="manual",
logical_date=utcnow(),
state=DagRunState.QUEUED,
start_date=None,
)
session.add(newer_run)
session.commit()
query = generate_dag_with_latest_run_query(
max_run_filters=[],
order_by=SortParam(allowed_attrs=["last_run_state"], model=DagModel).set_value(
["last_run_state"]
),
)
extended_query = query.add_columns(DagRun.state, DagRun.start_date)
result = session.execute(extended_query).fetchall()
dag_row = next((row for row in result if row[0].dag_id == dag_id), None)
assert dag_row is not None
assert dag_row[1] is not None, (
"Even if latest DagRun is QUEUED+start_date=None, state must not be None"
)
def test_queued_runs_with_null_start_date_are_properly_joined(
self, dag_with_queued_run, dag_with_running_run, session
):
"""
Verifies that DAGs with null start_date are properly joined in the query.
If a WHERE clause filters out null start_dates, these DAGs would be excluded.
This test ensures they are still present and joined correctly.
"""
queued_dag_model, _ = dag_with_queued_run
running_dag_model, _ = dag_with_running_run
query = generate_dag_with_latest_run_query(
max_run_filters=[],
order_by=SortParam(allowed_attrs=["last_run_state"], model=DagModel).set_value(
["last_run_state"]
),
)
extended_query = query.add_columns(DagRun.state, DagRun.start_date)
result = session.execute(extended_query).fetchall()
# Find results for each DAG
queued_dag_result = None
running_dag_result = None
for row in result:
dag_model = row[0]
if dag_model.dag_id == queued_dag_model.dag_id:
queued_dag_result = row
elif dag_model.dag_id == running_dag_model.dag_id:
running_dag_result = row
# Assert both DAGs are present
assert queued_dag_result is not None, f"Queued DAG {queued_dag_model.dag_id} should be in results"
assert running_dag_result is not None, f"Running DAG {running_dag_model.dag_id} should be in results"
# if WHERE start_date IS NOT NULL is present,
# the queued DAG should have NO DagRun information joined (state=None, start_date=None)
# But the running DAG should have DagRun information joined
queued_dagrun_state = queued_dag_result[1]
running_dagrun_state = running_dag_result[1]
assert queued_dagrun_state is not None, (
"Queued DAG should have DagRun state joined, but got None. "
"This suggests the WHERE start_date IS NOT NULL condition is excluding it."
)
assert running_dagrun_state is not None, "Running DAG should have DagRun state joined"
@pytest.mark.usefixtures("testing_dag_bundle")
def test_filters_by_dag_ids_when_provided(self, session):
"""
Verify that when dag_ids is provided, only those DAGs and their runs are queried.
This is a performance optimization: both the main DAG query and the DagRun subquery
should only process accessible DAGs when the user has limited access.
"""
dag_ids = ["dag_accessible_1", "dag_accessible_2", "dag_inaccessible_3"]
for dag_id in dag_ids:
dag_model = DagModel(
dag_id=dag_id,
bundle_name="testing",
is_stale=False,
is_paused=False,
fileloc=f"/tmp/{dag_id}.py",
)
session.add(dag_model)
session.flush()
# Create 2 runs for each DAG
for run_idx in range(2):
dagrun = DagRun(
dag_id=dag_id,
run_id=f"manual__{run_idx}",
run_type="manual",
logical_date=datetime(2024, 1, 1 + run_idx, tzinfo=timezone.utc),
state=DagRunState.SUCCESS,
start_date=datetime(2024, 1, 1 + run_idx, 1, tzinfo=timezone.utc),
)
session.add(dagrun)
session.commit()
# User has access to only 2 DAGs
accessible_dag_ids = {"dag_accessible_1", "dag_accessible_2"}
# Query with dag_ids filter
query_filtered = generate_dag_with_latest_run_query(
max_run_filters=[],
order_by=SortParam(allowed_attrs=["last_run_state"], model=DagModel).set_value(
["last_run_state"]
),
dag_ids=accessible_dag_ids,
)
# Query without dag_ids filter
query_unfiltered = generate_dag_with_latest_run_query(
max_run_filters=[],
order_by=SortParam(allowed_attrs=["last_run_state"], model=DagModel).set_value(
["last_run_state"]
),
)
result_filtered = session.execute(query_filtered.add_columns(DagRun.state)).fetchall()
result_unfiltered = session.execute(query_unfiltered.add_columns(DagRun.state)).fetchall()
# Filtered query should only return accessible DAGs
filtered_dag_ids = {row[0].dag_id for row in result_filtered}
assert filtered_dag_ids == accessible_dag_ids
# Unfiltered query returns all DAGs
unfiltered_dag_ids = {row[0].dag_id for row in result_unfiltered}
assert unfiltered_dag_ids == set(dag_ids)
# All accessible DAGs should have DagRun info
filtered_dags_with_runs = {row[0].dag_id for row in result_filtered if row[1] is not None}
assert filtered_dags_with_runs == accessible_dag_ids
| TestGenerateDagWithLatestRunQuery |
python | keras-team__keras | keras/src/saving/saving_lib_test.py | {
"start": 478,
"end": 1675
} | class ____(keras.layers.Layer):
def __init__(self, units, **kwargs):
super().__init__(**kwargs)
self.units = units
self.nested_layer = keras.layers.Dense(self.units, name="dense")
def build(self, input_shape):
self.additional_weights = [
self.add_weight(
shape=(),
name="my_additional_weight",
initializer="ones",
trainable=True,
),
self.add_weight(
shape=(),
name="my_additional_weight_2",
initializer="ones",
trainable=True,
),
]
self.weights_in_dict = {
"my_weight": self.add_weight(
shape=(),
name="my_dict_weight",
initializer="ones",
trainable=True,
),
}
self.nested_layer.build(input_shape)
def call(self, inputs):
return self.nested_layer(inputs)
def two(self):
return 2
ASSETS_DATA = "These are my assets"
VARIABLES_DATA = np.random.random((10,))
@keras.saving.register_keras_serializable(package="my_custom_package")
| MyDense |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-google/llama_index/vector_stores/google/genai_extension.py | {
"start": 4732,
"end": 14141
} | class ____(credentials.Credentials):
"""
Credentials that do not provide any authentication information.
Useful for unit tests where the credentials are not used.
"""
@property
def expired(self) -> bool:
"""Returns `False`, test credentials never expire."""
return False
@property
def valid(self) -> bool:
"""Returns `True`, test credentials are always valid."""
return True
def refresh(self, request: Any) -> None:
"""
Raises :class:``InvalidOperation``, test credentials cannot be
refreshed.
"""
raise exceptions.InvalidOperation("Test credentials cannot be refreshed.")
def apply(self, headers: Any, token: Any = None) -> None:
"""
Anonymous credentials do nothing to the request.
The optional ``token`` argument is not supported.
Raises:
google.auth.exceptions.InvalidValue: If a token was specified.
"""
if token is not None:
raise exceptions.InvalidValue("Test credentials don't support tokens.")
def before_request(self, request: Any, method: Any, url: Any, headers: Any) -> None:
"""Test credentials do nothing to the request."""
def _get_credentials() -> Optional[credentials.Credentials]:
"""
Returns a credential from the config if set or a fake credentials for unit testing.
If _config.testing is True, a fake credential is returned.
Otherwise, we are in a real environment and will use credentials if provided or None is returned.
If None is passed to the clients later on, the actual credentials will be
inferred by the rules specified in google.auth package.
"""
if _config.testing:
return TestCredentials()
elif _config.auth_credentials:
return _config.auth_credentials
return None
def build_semantic_retriever() -> genai.RetrieverServiceClient:
credentials = _get_credentials()
return genai.RetrieverServiceClient(
credentials=credentials,
client_info=gapic_v1.client_info.ClientInfo(user_agent=_USER_AGENT),
client_options=client_options_lib.ClientOptions(
api_endpoint=_config.api_endpoint
),
)
def build_generative_service() -> genai.GenerativeServiceClient:
credentials = _get_credentials()
return genai.GenerativeServiceClient(
credentials=credentials,
client_info=gapic_v1.client_info.ClientInfo(user_agent=_USER_AGENT),
client_options=client_options_lib.ClientOptions(
api_endpoint=_config.api_endpoint
),
)
def list_corpora(
*,
client: genai.RetrieverServiceClient,
) -> Iterator[Corpus]:
for corpus in client.list_corpora(
genai.ListCorporaRequest(page_size=_config.page_size)
):
yield Corpus.from_corpus(corpus)
def get_corpus(
*,
corpus_id: str,
client: genai.RetrieverServiceClient,
) -> Optional[Corpus]:
try:
corpus = client.get_corpus(
genai.GetCorpusRequest(name=str(EntityName(corpus_id=corpus_id)))
)
return Corpus.from_corpus(corpus)
except Exception as e:
# If the corpus does not exist, the server returns a permission error.
if not isinstance(e, gapi_exception.PermissionDenied):
raise
_logger.warning(f"Corpus {corpus_id} not found: {e}")
return None
def create_corpus(
*,
corpus_id: Optional[str] = None,
display_name: Optional[str] = None,
client: genai.RetrieverServiceClient,
) -> Corpus:
name: Optional[str]
if corpus_id is not None:
name = str(EntityName(corpus_id=corpus_id))
else:
name = None
new_display_name = display_name or f"Untitled {datetime.datetime.now()}"
new_corpus = client.create_corpus(
genai.CreateCorpusRequest(
corpus=genai.Corpus(name=name, display_name=new_display_name)
)
)
return Corpus.from_corpus(new_corpus)
def delete_corpus(
*,
corpus_id: str,
client: genai.RetrieverServiceClient,
) -> None:
client.delete_corpus(
genai.DeleteCorpusRequest(name=str(EntityName(corpus_id=corpus_id)), force=True)
)
def list_documents(
*,
corpus_id: str,
client: genai.RetrieverServiceClient,
) -> Iterator[Document]:
for document in client.list_documents(
genai.ListDocumentsRequest(
parent=str(EntityName(corpus_id=corpus_id)), page_size=_DEFAULT_PAGE_SIZE
)
):
yield Document.from_document(document)
def get_document(
*,
corpus_id: str,
document_id: str,
client: genai.RetrieverServiceClient,
) -> Optional[Document]:
try:
document = client.get_document(
genai.GetDocumentRequest(
name=str(EntityName(corpus_id=corpus_id, document_id=document_id))
)
)
return Document.from_document(document)
except Exception as e:
if not isinstance(e, gapi_exception.NotFound):
raise
_logger.warning(f"Document {document_id} in corpus {corpus_id} not found: {e}")
return None
def create_document(
*,
corpus_id: str,
document_id: Optional[str] = None,
display_name: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None,
client: genai.RetrieverServiceClient,
) -> Document:
name: Optional[str]
if document_id is not None:
name = str(EntityName(corpus_id=corpus_id, document_id=document_id))
else:
name = None
new_display_name = display_name or f"Untitled {datetime.datetime.now()}"
new_metadatas = _convert_to_metadata(metadata) if metadata else None
new_document = client.create_document(
genai.CreateDocumentRequest(
parent=str(EntityName(corpus_id=corpus_id)),
document=genai.Document(
name=name, display_name=new_display_name, custom_metadata=new_metadatas
),
)
)
return Document.from_document(new_document)
def delete_document(
*,
corpus_id: str,
document_id: str,
client: genai.RetrieverServiceClient,
) -> None:
client.delete_document(
genai.DeleteDocumentRequest(
name=str(EntityName(corpus_id=corpus_id, document_id=document_id)),
force=True,
)
)
def batch_create_chunk(
*,
corpus_id: str,
document_id: str,
texts: List[str],
metadatas: Optional[List[Dict[str, Any]]] = None,
client: genai.RetrieverServiceClient,
) -> List[genai.Chunk]:
if metadatas is None:
metadatas = [{} for _ in texts]
if len(texts) != len(metadatas):
raise ValueError(
f"metadatas's length {len(metadatas)} and texts's length {len(texts)} are mismatched"
)
doc_name = str(EntityName(corpus_id=corpus_id, document_id=document_id))
created_chunks: List[genai.Chunk] = []
batch_request = genai.BatchCreateChunksRequest(
parent=doc_name,
requests=[],
)
for text, metadata in zip(texts, metadatas):
batch_request.requests.append(
genai.CreateChunkRequest(
parent=doc_name,
chunk=genai.Chunk(
data=genai.ChunkData(string_value=text),
custom_metadata=_convert_to_metadata(metadata),
),
)
)
if len(batch_request.requests) >= _MAX_REQUEST_PER_CHUNK:
response = client.batch_create_chunks(batch_request)
created_chunks.extend(list(response.chunks))
# Prepare a new batch for next round.
batch_request = genai.BatchCreateChunksRequest(
parent=doc_name,
requests=[],
)
# Process left over.
if len(batch_request.requests) > 0:
response = client.batch_create_chunks(batch_request)
created_chunks.extend(list(response.chunks))
return created_chunks
def delete_chunk(
*,
corpus_id: str,
document_id: str,
chunk_id: str,
client: genai.RetrieverServiceClient,
) -> None:
client.delete_chunk(
genai.DeleteChunkRequest(
name=str(
EntityName(
corpus_id=corpus_id, document_id=document_id, chunk_id=chunk_id
)
)
)
)
def query_corpus(
*,
corpus_id: str,
query: str,
k: int = 4,
filter: Optional[Dict[str, Any]] = None,
client: genai.RetrieverServiceClient,
) -> List[genai.RelevantChunk]:
response = client.query_corpus(
genai.QueryCorpusRequest(
name=str(EntityName(corpus_id=corpus_id)),
query=query,
metadata_filters=_convert_filter(filter),
results_count=k,
)
)
return list(response.relevant_chunks)
def query_document(
*,
corpus_id: str,
document_id: str,
query: str,
k: int = 4,
filter: Optional[Dict[str, Any]] = None,
client: genai.RetrieverServiceClient,
) -> List[genai.RelevantChunk]:
response = client.query_document(
genai.QueryDocumentRequest(
name=str(EntityName(corpus_id=corpus_id, document_id=document_id)),
query=query,
metadata_filters=_convert_filter(filter),
results_count=k,
)
)
return list(response.relevant_chunks)
@dataclass
| TestCredentials |
python | kamyu104__LeetCode-Solutions | Python/clear-digits.py | {
"start": 457,
"end": 759
} | class ____(object):
def clearDigits(self, s):
"""
:type s: str
:rtype: str
"""
result = []
for x in s:
if x.isdigit():
result.pop()
continue
result.append(x)
return "".join(result)
| Solution2 |
python | kamyu104__LeetCode-Solutions | Python/array-partition-i.py | {
"start": 549,
"end": 849
} | class ____(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
result = 0
for i in xrange(0, len(nums), 2):
result += nums[i]
return result
# Time: O(nlogn)
# Space: O(n)
| Solution2 |
python | django-extensions__django-extensions | tests/management/commands/test_describe_form.py | {
"start": 1208,
"end": 1668
} | class ____(forms.Form):
title = forms.CharField(label='Title', max_length=50)
body = forms.CharField(label='Body')"""
call_command("describe_form", "testapp.BaseModel", stdout=self.out)
self.assertIn(expected_result, self.out.getvalue())
def test_should_print_form_definition_for_TestModel_with_non_editable_field(self):
expected_result = """from django import forms
from testapp.models import NonEditableModel
| BaseModelForm |
python | cython__cython | tests/run/qualname.py | {
"start": 3218,
"end": 4238
} | class ____:
"""
>>> print(CdefModifyNames.qn_reassigned, CdefModifyNames.m_reassigned)
I'm not a qualname I'm not a module
# TODO - enable when https://github.com/cython/cython/issues/4815 is fixed
#>>> hasattr(CdefModifyNames, "qn_deleted")
#False
#>>> hasattr(CdefModifyNames, "m_deleted")
#False
#>>> print(CdefModifyNames.l["__qualname__"], CdefModifyNames.l["__module__"])
#I'm not a qualname I'm not a module
"""
__qualname__ = "I'm not a qualname"
__module__ = "I'm not a module"
qn_reassigned = __qualname__
m_reassigned = __module__
# TODO - locals and cdef classes is unreliable, irrespective of qualname
#l = locals().copy()
# TODO del inside cdef class scope is broken
# https://github.com/cython/cython/issues/4815
#del __qualname__
#del __module__
#try:
# qn_deleted = __qualname__
#except NameError:
# pass
#try:
# m_deleted = __module__
#except NameError:
# pass
| CdefModifyNames |
python | facebook__pyre-check | client/language_server/code_navigation_request.py | {
"start": 2686,
"end": 6845
} | class ____:
path: Path
client_id: str
def to_json(self) -> List[object]:
return [
"FileClosed",
{
"path": f"{self.path}",
"client_id": self.client_id,
},
]
def invalid_response(response: str, raw_request: str) -> ErrorResponse:
return ErrorResponse(
message=f"Invalid response {response} to pyre language server request.",
originating_request=raw_request,
)
ResponseKind = TypeVar(
"ResponseKind",
bound=Union[
json_mixins.CamlCaseAndExcludeJsonMixin,
json_mixins.SnakeCaseAndExcludeJsonMixin,
],
)
def parse_response(
response: Dict[str, Any], response_type: Type[ResponseKind], raw_request: str
) -> Union[ResponseKind, ErrorResponse]:
try:
return response_type.cached_schema().load(response)
except AssertionError as error:
return ErrorResponse(
message=f"Assertion error when parsing JSON into the response schema: {error}",
originating_request=raw_request,
)
def parse_raw_response(
raw_response: str,
expected_response_kind: str,
response_type: Type[ResponseKind],
raw_request: str,
) -> Union[ResponseKind, ErrorResponse]:
try:
response = json.loads(raw_response)
if (
not isinstance(response, list)
or len(response) != 2
or response[0] != expected_response_kind
):
return invalid_response(raw_response, raw_request)
except Exception as error:
return ErrorResponse(message=f"Exception while parsing response: {error}")
return parse_response(response[1], response_type, raw_request)
async def async_handle_type_errors_request(
socket_path: Path,
type_errors_request: TypeErrorsRequest,
) -> Union[TypeErrorsResponse, ErrorResponse]:
raw_request = json.dumps(["Query", type_errors_request.to_json()])
response = await daemon_connection.attempt_send_async_raw_request(
socket_path, raw_request
)
if isinstance(response, daemon_connection.DaemonConnectionFailure):
return ErrorResponse(
message=response.error_message, error_source=response.error_source
)
return parse_raw_response(
response,
expected_response_kind="TypeErrors",
response_type=TypeErrorsResponse,
raw_request=raw_request,
)
async def async_handle_register_client(
socket_path: Path, register_client: RegisterClient
) -> Union[str, daemon_connection.DaemonConnectionFailure]:
raw_command = json.dumps(["Command", register_client.to_json()])
response = await daemon_connection.attempt_send_async_raw_request(
socket_path, raw_command
)
return response
async def async_handle_dispose_client(
socket_path: Path, dispose_client: DisposeClient
) -> Union[str, daemon_connection.DaemonConnectionFailure]:
raw_command = json.dumps(["Command", dispose_client.to_json()])
response = await daemon_connection.attempt_send_async_raw_request(
socket_path, raw_command
)
return response
async def async_handle_local_update(
socket_path: Path, local_update: LocalUpdate
) -> Union[str, daemon_connection.DaemonConnectionFailure]:
raw_command = json.dumps(["Command", local_update.to_json()])
response = await daemon_connection.attempt_send_async_raw_request(
socket_path, raw_command
)
return response
async def async_handle_file_opened(
socket_path: Path, file_opened: FileOpened
) -> Union[str, daemon_connection.DaemonConnectionFailure]:
raw_command = json.dumps(["Command", file_opened.to_json()])
response = await daemon_connection.attempt_send_async_raw_request(
socket_path, raw_command
)
return response
async def async_handle_file_closed(
socket_path: Path, file_closed: FileClosed
) -> Union[str, daemon_connection.DaemonConnectionFailure]:
raw_command = json.dumps(["Command", file_closed.to_json()])
response = await daemon_connection.attempt_send_async_raw_request(
socket_path, raw_command
)
return response
| FileClosed |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/pipes/context_injectors.py | {
"start": 1943,
"end": 2282
} | class ____(PipesEnvContextInjector):
"""Injects context via AWS Lambda event input.
Should be paired with :py:class`~dagster_pipes.PipesMappingParamsLoader` on the Lambda side.
"""
def no_messages_debug_text(self) -> str:
return "Attempted to inject context via the lambda event input."
| PipesLambdaEventContextInjector |
python | pytorch__pytorch | benchmarks/dynamo/dist_util.py | {
"start": 953,
"end": 1170
} | class ____(torch.nn.Module):
def __init__(self, a, b):
super().__init__()
self.weight = nn.Parameter(torch.randn(a, b))
def forward(self, x):
return torch.mm(x, self.weight)
| CustomLinear |
python | joke2k__faker | faker/providers/address/en_CA/__init__.py | {
"start": 129,
"end": 9037
} | class ____(AddressProvider):
# Source: https://www.canadapost.ca/tools/pg/manual/PGaddress-e.asp#1449294
#
# 'W' and 'Z' are valid in non-initial position (easily verified in the
# wild), but online official documentation is hard to find, so just ignore
# them for now.
postal_code_letters = (
"A",
"B",
"C",
"E",
"G",
"H",
"J",
"K",
"L",
"M",
"N",
"P",
"R",
"S",
"T",
"V",
"X",
"Y",
)
city_prefixes: ElementsType[str] = ("North", "East", "West", "South", "New", "Lake", "Port")
city_suffixes: ElementsType[str] = (
"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",
)
postal_code_formats = ("?%? %?%", "?%?%?%")
provinces = (
"Alberta",
"British Columbia",
"Manitoba",
"New Brunswick",
"Newfoundland and Labrador",
"Northwest Territories",
"Nova Scotia",
"Nunavut",
"Ontario",
"Prince Edward Island",
"Quebec",
"Saskatchewan",
"Yukon Territory",
)
provinces_abbr = (
"AB",
"BC",
"MB",
"NB",
"NL",
"NT",
"NS",
"NU",
"ON",
"PE",
"QC",
"SK",
"YT",
)
provinces_postcode_prefixes = {
"NL": ["A"],
"NS": ["B"],
"PE": ["C"],
"NB": ["E"],
"QC": ["G", "H", "J"],
"ON": ["K", "L", "M", "N", "P"],
"MB": ["R"],
"SK": ["S"],
"AB": ["T"],
"BC": ["V"],
"NU": ["X"],
"NT": ["X"],
"YT": ["Y"],
}
city_formats: ElementsType[str] = (
"{{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 = ("{{street_address}}\n{{city}}, {{province_abbr}} {{postalcode}}",)
secondary_address_formats = ("Apt. ###", "Suite ###")
def administrative_unit(self) -> str:
""" """
return self.random_element(self.provinces)
province = administrative_unit
def province_abbr(self) -> str:
return self.random_element(self.provinces_abbr)
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 postal_code_letter(self) -> str:
"""
Returns a random letter from the list of allowable
letters in a canadian postal code
"""
return self.random_element(self.postal_code_letters)
def _postcode_replace(self, postal_code_format: str) -> str:
"""
Replaces all question mark ('?') occurrences with a random letter
from given postal_code_format, then passes result to numerify to insert
numbers
"""
temp = re.sub(r"\?", lambda x: self.postal_code_letter(), postal_code_format)
return self.numerify(temp)
def postcode(self) -> str:
"""
Returns a random postcode
"""
return self._postcode_replace(self.random_element(self.postal_code_formats))
def postcode_in_province(self, province_abbr: Optional[str] = None) -> str:
"""
Returns a random postcode within the provided province abbreviation
"""
if province_abbr is None:
province_abbr = self.random_element(self.provinces_abbr)
if province_abbr in self.provinces_abbr:
postal_code_format: str = self.random_element(self.postal_code_formats)
postal_code_format = postal_code_format.replace(
"?",
self.generator.random_element(self.provinces_postcode_prefixes[province_abbr]),
1,
)
return self._postcode_replace(postal_code_format)
else:
raise Exception("Province Abbreviation not found in list")
def postalcode_in_province(self, province_abbr: Optional[str] = None) -> str:
return self.postcode_in_province(province_abbr)
def postalcode(self) -> str:
return self.postcode()
| Provider |
python | sympy__sympy | sympy/polys/numberfields/modules.py | {
"start": 8293,
"end": 23783
} | class ____:
"""
Generic finitely-generated module.
This is an abstract base class, and should not be instantiated directly.
The two concrete subclasses are :py:class:`~.PowerBasis` and
:py:class:`~.Submodule`.
Every :py:class:`~.Submodule` is derived from another module, referenced
by its ``parent`` attribute. If ``S`` is a submodule, then we refer to
``S.parent``, ``S.parent.parent``, and so on, as the "ancestors" of
``S``. Thus, every :py:class:`~.Module` is either a
:py:class:`~.PowerBasis` or a :py:class:`~.Submodule`, some ancestor of
which is a :py:class:`~.PowerBasis`.
"""
@property
def n(self):
"""The number of generators of this module."""
raise NotImplementedError
def mult_tab(self):
"""
Get the multiplication table for this module (if closed under mult).
Explanation
===========
Computes a dictionary ``M`` of dictionaries of lists, representing the
upper triangular half of the multiplication table.
In other words, if ``0 <= i <= j < self.n``, then ``M[i][j]`` is the
list ``c`` of coefficients such that
``g[i] * g[j] == sum(c[k]*g[k], k in range(self.n))``,
where ``g`` is the list of generators of this module.
If ``j < i`` then ``M[i][j]`` is undefined.
Examples
========
>>> from sympy.polys import Poly, cyclotomic_poly
>>> from sympy.polys.numberfields.modules import PowerBasis
>>> T = Poly(cyclotomic_poly(5))
>>> A = PowerBasis(T)
>>> print(A.mult_tab()) # doctest: +SKIP
{0: {0: [1, 0, 0, 0], 1: [0, 1, 0, 0], 2: [0, 0, 1, 0], 3: [0, 0, 0, 1]},
1: {1: [0, 0, 1, 0], 2: [0, 0, 0, 1], 3: [-1, -1, -1, -1]},
2: {2: [-1, -1, -1, -1], 3: [1, 0, 0, 0]},
3: {3: [0, 1, 0, 0]}}
Returns
=======
dict of dict of lists
Raises
======
ClosureFailure
If the module is not closed under multiplication.
"""
raise NotImplementedError
@property
def parent(self):
"""
The parent module, if any, for this module.
Explanation
===========
For a :py:class:`~.Submodule` this is its ``parent`` attribute; for a
:py:class:`~.PowerBasis` this is ``None``.
Returns
=======
:py:class:`~.Module`, ``None``
See Also
========
Module
"""
return None
def represent(self, elt):
r"""
Represent a module element as an integer-linear combination over the
generators of this module.
Explanation
===========
In our system, to "represent" always means to write a
:py:class:`~.ModuleElement` as a :ref:`ZZ`-linear combination over the
generators of the present :py:class:`~.Module`. Furthermore, the
incoming :py:class:`~.ModuleElement` must belong to an ancestor of
the present :py:class:`~.Module` (or to the present
:py:class:`~.Module` itself).
The most common application is to represent a
:py:class:`~.ModuleElement` in a :py:class:`~.Submodule`. For example,
this is involved in computing multiplication tables.
On the other hand, representing in a :py:class:`~.PowerBasis` is an
odd case, and one which tends not to arise in practice, except for
example when using a :py:class:`~.ModuleEndomorphism` on a
:py:class:`~.PowerBasis`.
In such a case, (1) the incoming :py:class:`~.ModuleElement` must
belong to the :py:class:`~.PowerBasis` itself (since the latter has no
proper ancestors) and (2) it is "representable" iff it belongs to
$\mathbb{Z}[\theta]$ (although generally a
:py:class:`~.PowerBasisElement` may represent any element of
$\mathbb{Q}(\theta)$, i.e. any algebraic number).
Examples
========
>>> from sympy import Poly, cyclotomic_poly
>>> from sympy.polys.numberfields.modules import PowerBasis, to_col
>>> from sympy.abc import zeta
>>> T = Poly(cyclotomic_poly(5))
>>> A = PowerBasis(T)
>>> a = A(to_col([2, 4, 6, 8]))
The :py:class:`~.ModuleElement` ``a`` has all even coefficients.
If we represent ``a`` in the submodule ``B = 2*A``, the coefficients in
the column vector will be halved:
>>> B = A.submodule_from_gens([2*A(i) for i in range(4)])
>>> b = B.represent(a)
>>> print(b.transpose()) # doctest: +SKIP
DomainMatrix([[1, 2, 3, 4]], (1, 4), ZZ)
However, the element of ``B`` so defined still represents the same
algebraic number:
>>> print(a.poly(zeta).as_expr())
8*zeta**3 + 6*zeta**2 + 4*zeta + 2
>>> print(B(b).over_power_basis().poly(zeta).as_expr())
8*zeta**3 + 6*zeta**2 + 4*zeta + 2
Parameters
==========
elt : :py:class:`~.ModuleElement`
The module element to be represented. Must belong to some ancestor
module of this module (including this module itself).
Returns
=======
:py:class:`~.DomainMatrix` over :ref:`ZZ`
This will be a column vector, representing the coefficients of a
linear combination of this module's generators, which equals the
given element.
Raises
======
ClosureFailure
If the given element cannot be represented as a :ref:`ZZ`-linear
combination over this module.
See Also
========
.Submodule.represent
.PowerBasis.represent
"""
raise NotImplementedError
def ancestors(self, include_self=False):
"""
Return the list of ancestor modules of this module, from the
foundational :py:class:`~.PowerBasis` downward, optionally including
``self``.
See Also
========
Module
"""
c = self.parent
a = [] if c is None else c.ancestors(include_self=True)
if include_self:
a.append(self)
return a
def power_basis_ancestor(self):
"""
Return the :py:class:`~.PowerBasis` that is an ancestor of this module.
See Also
========
Module
"""
if isinstance(self, PowerBasis):
return self
c = self.parent
if c is not None:
return c.power_basis_ancestor()
return None
def nearest_common_ancestor(self, other):
"""
Locate the nearest common ancestor of this module and another.
Returns
=======
:py:class:`~.Module`, ``None``
See Also
========
Module
"""
sA = self.ancestors(include_self=True)
oA = other.ancestors(include_self=True)
nca = None
for sa, oa in zip(sA, oA):
if sa == oa:
nca = sa
else:
break
return nca
@property
def number_field(self):
r"""
Return the associated :py:class:`~.AlgebraicField`, if any.
Explanation
===========
A :py:class:`~.PowerBasis` can be constructed on a :py:class:`~.Poly`
$f$ or on an :py:class:`~.AlgebraicField` $K$. In the latter case, the
:py:class:`~.PowerBasis` and all its descendant modules will return $K$
as their ``.number_field`` property, while in the former case they will
all return ``None``.
Returns
=======
:py:class:`~.AlgebraicField`, ``None``
"""
return self.power_basis_ancestor().number_field
def is_compat_col(self, col):
"""Say whether *col* is a suitable column vector for this module."""
return isinstance(col, DomainMatrix) and col.shape == (self.n, 1) and col.domain.is_ZZ
def __call__(self, spec, denom=1):
r"""
Generate a :py:class:`~.ModuleElement` belonging to this module.
Examples
========
>>> from sympy.polys import Poly, cyclotomic_poly
>>> from sympy.polys.numberfields.modules import PowerBasis, to_col
>>> T = Poly(cyclotomic_poly(5))
>>> A = PowerBasis(T)
>>> e = A(to_col([1, 2, 3, 4]), denom=3)
>>> print(e) # doctest: +SKIP
[1, 2, 3, 4]/3
>>> f = A(2)
>>> print(f) # doctest: +SKIP
[0, 0, 1, 0]
Parameters
==========
spec : :py:class:`~.DomainMatrix`, int
Specifies the numerators of the coefficients of the
:py:class:`~.ModuleElement`. Can be either a column vector over
:ref:`ZZ`, whose length must equal the number $n$ of generators of
this module, or else an integer ``j``, $0 \leq j < n$, which is a
shorthand for column $j$ of $I_n$, the $n \times n$ identity
matrix.
denom : int, optional (default=1)
Denominator for the coefficients of the
:py:class:`~.ModuleElement`.
Returns
=======
:py:class:`~.ModuleElement`
The coefficients are the entries of the *spec* vector, divided by
*denom*.
"""
if isinstance(spec, int) and 0 <= spec < self.n:
spec = DomainMatrix.eye(self.n, ZZ)[:, spec].to_dense()
if not self.is_compat_col(spec):
raise ValueError('Compatible column vector required.')
return make_mod_elt(self, spec, denom=denom)
def starts_with_unity(self):
"""Say whether the module's first generator equals unity."""
raise NotImplementedError
def basis_elements(self):
"""
Get list of :py:class:`~.ModuleElement` being the generators of this
module.
"""
return [self(j) for j in range(self.n)]
def zero(self):
"""Return a :py:class:`~.ModuleElement` representing zero."""
return self(0) * 0
def one(self):
"""
Return a :py:class:`~.ModuleElement` representing unity,
and belonging to the first ancestor of this module (including
itself) that starts with unity.
"""
return self.element_from_rational(1)
def element_from_rational(self, a):
"""
Return a :py:class:`~.ModuleElement` representing a rational number.
Explanation
===========
The returned :py:class:`~.ModuleElement` will belong to the first
module on this module's ancestor chain (including this module
itself) that starts with unity.
Examples
========
>>> from sympy.polys import Poly, cyclotomic_poly, QQ
>>> from sympy.polys.numberfields.modules import PowerBasis
>>> T = Poly(cyclotomic_poly(5))
>>> A = PowerBasis(T)
>>> a = A.element_from_rational(QQ(2, 3))
>>> print(a) # doctest: +SKIP
[2, 0, 0, 0]/3
Parameters
==========
a : int, :ref:`ZZ`, :ref:`QQ`
Returns
=======
:py:class:`~.ModuleElement`
"""
raise NotImplementedError
def submodule_from_gens(self, gens, hnf=True, hnf_modulus=None):
"""
Form the submodule generated by a list of :py:class:`~.ModuleElement`
belonging to this module.
Examples
========
>>> from sympy.polys import Poly, cyclotomic_poly
>>> from sympy.polys.numberfields.modules import PowerBasis
>>> T = Poly(cyclotomic_poly(5))
>>> A = PowerBasis(T)
>>> gens = [A(0), 2*A(1), 3*A(2), 4*A(3)//5]
>>> B = A.submodule_from_gens(gens)
>>> print(B) # doctest: +SKIP
Submodule[[5, 0, 0, 0], [0, 10, 0, 0], [0, 0, 15, 0], [0, 0, 0, 4]]/5
Parameters
==========
gens : list of :py:class:`~.ModuleElement` belonging to this module.
hnf : boolean, optional (default=True)
If True, we will reduce the matrix into Hermite Normal Form before
forming the :py:class:`~.Submodule`.
hnf_modulus : int, None, optional (default=None)
Modulus for use in the HNF reduction algorithm. See
:py:func:`~sympy.polys.matrices.normalforms.hermite_normal_form`.
Returns
=======
:py:class:`~.Submodule`
See Also
========
submodule_from_matrix
"""
if not all(g.module == self for g in gens):
raise ValueError('Generators must belong to this module.')
n = len(gens)
if n == 0:
raise ValueError('Need at least one generator.')
m = gens[0].n
d = gens[0].denom if n == 1 else ilcm(*[g.denom for g in gens])
B = DomainMatrix.zeros((m, 0), ZZ).hstack(*[(d // g.denom) * g.col for g in gens])
if hnf:
B = hermite_normal_form(B, D=hnf_modulus)
return self.submodule_from_matrix(B, denom=d)
def submodule_from_matrix(self, B, denom=1):
"""
Form the submodule generated by the elements of this module indicated
by the columns of a matrix, with an optional denominator.
Examples
========
>>> from sympy.polys import Poly, cyclotomic_poly, ZZ
>>> from sympy.polys.matrices import DM
>>> from sympy.polys.numberfields.modules import PowerBasis
>>> T = Poly(cyclotomic_poly(5))
>>> A = PowerBasis(T)
>>> B = A.submodule_from_matrix(DM([
... [0, 10, 0, 0],
... [0, 0, 7, 0],
... ], ZZ).transpose(), denom=15)
>>> print(B) # doctest: +SKIP
Submodule[[0, 10, 0, 0], [0, 0, 7, 0]]/15
Parameters
==========
B : :py:class:`~.DomainMatrix` over :ref:`ZZ`
Each column gives the numerators of the coefficients of one
generator of the submodule. Thus, the number of rows of *B* must
equal the number of generators of the present module.
denom : int, optional (default=1)
Common denominator for all generators of the submodule.
Returns
=======
:py:class:`~.Submodule`
Raises
======
ValueError
If the given matrix *B* is not over :ref:`ZZ` or its number of rows
does not equal the number of generators of the present module.
See Also
========
submodule_from_gens
"""
m, n = B.shape
if not B.domain.is_ZZ:
raise ValueError('Matrix must be over ZZ.')
if not m == self.n:
raise ValueError('Matrix row count must match base module.')
return Submodule(self, B, denom=denom)
def whole_submodule(self):
"""
Return a submodule equal to this entire module.
Explanation
===========
This is useful when you have a :py:class:`~.PowerBasis` and want to
turn it into a :py:class:`~.Submodule` (in order to use methods
belonging to the latter).
"""
B = DomainMatrix.eye(self.n, ZZ)
return self.submodule_from_matrix(B)
def endomorphism_ring(self):
"""Form the :py:class:`~.EndomorphismRing` for this module."""
return EndomorphismRing(self)
| Module |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/managed_kafka.py | {
"start": 25978,
"end": 29366
} | class ____(ManagedKafkaBaseOperator):
"""
List the topics in a given cluster.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param location: Required. The ID of the Google Cloud region that the service belongs to.
:param cluster_id: Required. The ID of the cluster whose topics are to be listed.
:param page_size: Optional. The maximum number of topics to return. The service may return fewer than
this value. If unset or zero, all topics for the parent is returned.
:param page_token: Optional. A page token, received from a previous ``ListTopics`` call. Provide this
to retrieve the subsequent page. When paginating, all other parameters provided to ``ListTopics``
must match the call that provided the page token.
:param retry: Designation of what errors, if any, should be retried.
:param timeout: The timeout for this request.
:param metadata: Strings which should be sent along with the request as metadata.
:param gcp_conn_id: The connection ID to use connecting to Google Cloud.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
"""
template_fields: Sequence[str] = tuple({"cluster_id"} | set(ManagedKafkaBaseOperator.template_fields))
operator_extra_links = (ApacheKafkaClusterLink(),)
def __init__(
self,
cluster_id: str,
page_size: int | None = None,
page_token: str | None = None,
*args,
**kwargs,
) -> None:
super().__init__(*args, **kwargs)
self.cluster_id = cluster_id
self.page_size = page_size
self.page_token = page_token
@property
def extra_links_params(self) -> dict[str, Any]:
return {
"location": self.location,
"cluster_id": self.cluster_id,
"project_id": self.project_id,
}
def execute(self, context: Context):
ApacheKafkaClusterLink.persist(context=context)
self.log.info("Listing Topics for cluster %s.", self.cluster_id)
try:
topic_list_pager = self.hook.list_topics(
project_id=self.project_id,
location=self.location,
cluster_id=self.cluster_id,
page_size=self.page_size,
page_token=self.page_token,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
context["ti"].xcom_push(
key="topic_page",
value=types.ListTopicsResponse.to_dict(topic_list_pager._response),
)
except Exception as error:
raise AirflowException(error)
return [types.Topic.to_dict(topic) for topic in topic_list_pager]
| ManagedKafkaListTopicsOperator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-recharge/unit_tests/integration/streams/test_events.py | {
"start": 501,
"end": 1834
} | class ____(StreamTestCase):
_STREAM_NAME = "events"
@HttpMocker()
def test_given_one_page_when_read_then_return_records(self, http_mocker: HttpMocker) -> None:
req = self.stream_request().with_limit(250).with_created_min(START_DATE).build()
http_mocker.get(
req,
get_stream_response(_STREAM_NAME).with_record(get_stream_record(_STREAM_NAME, "id", _CURSOR_FIELD)).build(),
)
output = read_full_refresh(self._config, _STREAM_NAME)
assert len(output.records) == 1
@HttpMocker()
def test_given_multiple_pages_when_read_then_return_records(self, http_mocker: HttpMocker) -> None:
http_mocker.get(
self.stream_request().with_limit(250).with_next_page_token(NEXT_PAGE_TOKEN).build(),
get_stream_response(_STREAM_NAME).with_record(get_stream_record(_STREAM_NAME, "id", _CURSOR_FIELD)).build(),
)
http_mocker.get(
self.stream_request().with_limit(250).with_created_min(START_DATE).build(),
get_stream_response(_STREAM_NAME).with_pagination().with_record(get_stream_record(_STREAM_NAME, "id", _CURSOR_FIELD)).build(),
)
output = read_full_refresh(self._config, _STREAM_NAME)
assert len(output.records) == 2
@freezegun.freeze_time(NOW.isoformat())
| TestFullRefresh |
python | cherrypy__cherrypy | cherrypy/test/helper.py | {
"start": 1017,
"end": 2918
} | class ____(Supervisor):
"""Base for modeling/controlling servers which run in the same process.
When the server side runs in a different process, start/stop can
dump all state between each test module easily. When the server side
runs in the same process as the client, however, we have to do a bit
more work to ensure config and mounted apps are reset between tests.
"""
using_apache = False
using_wsgi = False
def __init__(self, **kwargs):
"""Initialize the local supervisor."""
for k, v in kwargs.items():
setattr(self, k, v)
cherrypy.server.httpserver = self.httpserver_class
# This is perhaps the wrong place for this call but this is the only
# place that i've found so far that I KNOW is early enough to set this.
cherrypy.config.update({'log.screen': False})
engine = cherrypy.engine
if hasattr(engine, 'signal_handler'):
engine.signal_handler.subscribe()
if hasattr(engine, 'console_control_handler'):
engine.console_control_handler.subscribe()
def start(self, modulename=None):
"""Load and start the HTTP server."""
if modulename:
# Unhook httpserver so cherrypy.server.start() creates a new
# one (with config from setup_server, if declared).
cherrypy.server.httpserver = None
cherrypy.engine.start()
self.sync_apps()
def sync_apps(self):
"""Tell the server about any apps which the setup functions mounted."""
pass
def stop(self):
"""Stop the HTTP server."""
td = getattr(self, 'teardown', None)
if td:
td()
cherrypy.engine.exit()
for name, server in getattr(cherrypy, 'servers', {}).copy().items():
server.unsubscribe()
del cherrypy.servers[name]
| LocalSupervisor |
python | doocs__leetcode | solution/0100-0199/0141.Linked List Cycle/Solution2.py | {
"start": 136,
"end": 390
} | class ____:
def hasCycle(self, head: ListNode) -> bool:
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow == fast:
return True
return False
| Solution |
python | tensorflow__tensorflow | third_party/xla/build_tools/configure/configure.py | {
"start": 10026,
"end": 21241
} | class ____:
"""Represents XLA configuration options."""
backend: Backend
os: OS
python_bin_path: str
host_compiler: HostCompiler
compiler_options: list[str]
# CUDA specific
cuda_compiler: CudaCompiler
using_nccl: bool
# ROCM specific
rocm_compiler: RocmCompiler
# SYCL specific
sycl_compiler: SyclCompiler
def to_bazelrc_lines(
self,
dpav: DiscoverablePathsAndVersions,
) -> list[str]:
"""Creates a bazelrc given an XLAConfigOptions.
Necessary paths are provided by the user, or retrieved via
`self._get_relevant_paths`.
Args:
dpav: DiscoverablePathsAndVersions that may hold user-specified paths and
versions. The dpav will then read from `self` to determine what to try
to auto-configure.
Returns:
The lines of a bazelrc.
"""
dpav.get_relevant_paths_and_versions(self)
rc = []
build_and_test_tag_filters = list(_DEFAULT_BUILD_AND_TEST_TAG_FILTERS)
if self.os == OS.DARWIN:
build_and_test_tag_filters.append("-no_mac")
# Platform independent options based on host compiler
if self.host_compiler == HostCompiler.GCC:
rc.append(f"build --action_env GCC_HOST_COMPILER_PATH={dpav.gcc_path}")
elif self.host_compiler == HostCompiler.CLANG:
if dpav.clang_path:
rc.append("build --config clang_local")
rc.append(f"build --action_env CLANG_COMPILER_PATH={dpav.clang_path}")
rc.append(f"build --repo_env CC={dpav.clang_path}")
rc.append(f"build --repo_env BAZEL_COMPILER={dpav.clang_path}")
self.compiler_options.append("-Wno-error=unused-command-line-argument")
if dpav.lld_path:
rc.append(f"build --linkopt --ld-path={dpav.lld_path}")
if self.backend == Backend.CPU:
build_and_test_tag_filters.append("-gpu")
elif self.backend == Backend.CUDA:
build_and_test_tag_filters.append("-rocm-only")
build_and_test_tag_filters.append("-oneapi-only")
compiler_pair = self.cuda_compiler, self.host_compiler
if compiler_pair == (CudaCompiler.CLANG, HostCompiler.CLANG):
if not dpav.clang_path:
rc.append("build --config cuda_clang")
else:
rc.append("build --config cuda_clang_local")
rc.append(
f"build --action_env CLANG_CUDA_COMPILER_PATH={dpav.clang_path}"
)
elif compiler_pair == (CudaCompiler.NVCC, HostCompiler.CLANG):
if not dpav.clang_path:
rc.append("build --config cuda_nvcc")
else:
rc.append("build --config cuda_nvcc_clang_local")
# This is demanded by cuda_configure.bzl
rc.append(
f"build --action_env CLANG_CUDA_COMPILER_PATH={dpav.clang_path}"
)
elif compiler_pair == (CudaCompiler.NVCC, HostCompiler.GCC):
rc.append("build --config cuda")
else:
raise NotImplementedError(
"CUDA clang with host compiler gcc not supported"
)
# Lines needed for CUDA backend regardless of CUDA/host compiler
if dpav.cuda_version:
rc.append(
f"build:cuda --repo_env HERMETIC_CUDA_VERSION={dpav.cuda_version}"
)
rc.append(
"build:cuda --repo_env HERMETIC_CUDA_COMPUTE_CAPABILITIES="
f"{','.join(dpav.cuda_compute_capabilities)}"
)
if dpav.cudnn_version:
rc.append(
f"build:cuda --repo_env HERMETIC_CUDNN_VERSION={dpav.cudnn_version}"
)
if dpav.local_cuda_path:
rc.append(
f"build:cuda --repo_env LOCAL_CUDA_PATH={dpav.local_cuda_path}"
)
if dpav.local_cudnn_path:
rc.append(
f"build:cuda --repo_env LOCAL_CUDNN_PATH={dpav.local_cudnn_path}"
)
if dpav.local_nccl_path:
rc.append(
f"build:cuda --repo_env LOCAL_NCCL_PATH={dpav.local_nccl_path}"
)
if not self.using_nccl:
rc.append("build --config nonccl")
elif self.backend == Backend.ROCM:
build_and_test_tag_filters.append("-cuda-only")
build_and_test_tag_filters.append("-oneapi-only")
compiler_pair = self.rocm_compiler, self.host_compiler
if compiler_pair == (RocmCompiler.HIPCC, HostCompiler.CLANG):
rc.append("build --config rocm")
# This is demanded by rocm_configure.bzl.
rc.append(f"build --action_env CLANG_COMPILER_PATH={dpav.clang_path}")
elif compiler_pair == (RocmCompiler.HIPCC, HostCompiler.GCC):
rc.append("build --config rocm")
else:
raise NotImplementedError("ROCm clang with host compiler not supported")
elif self.backend == Backend.SYCL:
build_and_test_tag_filters.append("-cuda-only")
build_and_test_tag_filters.append("-rocm-only")
build_and_test_tag_filters.append("-no-oneapi")
compiler_pair = self.sycl_compiler, self.host_compiler
if compiler_pair == (SyclCompiler.ICPX, HostCompiler.CLANG):
rc.append("build --config sycl")
rc.append("build --config icpx_clang")
else:
raise NotImplementedError(" Sycl with host compiler not supported")
# Lines that are added for every backend
if dpav.ld_library_path:
rc.append(f"build --action_env LD_LIBRARY_PATH={dpav.ld_library_path}")
# Needed due to error in @upb//:upb which is a dep of @com_github_grpc_grpc
# error: defining a type within 'offsetof' is a Clang extension
if dpav.clang_major_version in (16, 17, 18):
self.compiler_options.append("-Wno-gnu-offsetof-extensions")
# error: defining a type within 'offsetof' is a C23 extension
if dpav.clang_major_version and dpav.clang_major_version >= 19:
self.compiler_options.append("-Wno-c23-extensions")
# Avoid XNNPACK using `-mavxvnniint8` (needs clang-16+/gcc-13+)
if (
dpav.clang_major_version is not None and dpav.clang_major_version < 16
) or (dpav.gcc_major_version is not None and dpav.gcc_major_version < 13):
rc.append("build --define=xnn_enable_avxvnniint8=false")
# Avoid XNNPACK using `-mavx512fp16` (needs clang-14+/gcc-12+).
if (
dpav.clang_major_version is not None and dpav.clang_major_version < 14
) or (dpav.gcc_major_version is not None and dpav.gcc_major_version < 12):
rc.append("build --define=xnn_enable_avx512fp16=false")
rc.append(f"build --action_env PYTHON_BIN_PATH={self.python_bin_path}")
rc.append(f"build --python_path {self.python_bin_path}")
rc.append("test --test_env LD_LIBRARY_PATH")
rc.append("test --test_size_filters small,medium")
rc.extend([
f"build --copt {compiler_option}"
for compiler_option in self.compiler_options
])
# Add build and test tag filters
build_and_test_tag_filters = ",".join(build_and_test_tag_filters)
rc.append(f"build --build_tag_filters {build_and_test_tag_filters}")
rc.append(f"build --test_tag_filters {build_and_test_tag_filters}")
rc.append(f"test --build_tag_filters {build_and_test_tag_filters}")
rc.append(f"test --test_tag_filters {build_and_test_tag_filters}")
return rc
def _parse_args():
"""Creates an argparse.ArgumentParser and parses arguments."""
# pylint: disable=C3001
comma_separated_list = lambda l: [s.strip() for s in l.split(",")]
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument(
"--backend",
type=Backend.from_str,
choices=list(Backend),
required=True,
)
parser.add_argument(
"--os", type=OS.from_str, choices=list(OS), default=platform.system()
)
parser.add_argument(
"--host_compiler",
type=HostCompiler.from_str,
choices=list(HostCompiler),
default="clang",
)
parser.add_argument(
"--cuda_compiler",
type=CudaCompiler.from_str,
choices=list(CudaCompiler),
default="nvcc",
)
parser.add_argument(
"--rocm_compiler",
type=RocmCompiler.from_str,
choices=list(RocmCompiler),
default="hipcc",
)
parser.add_argument(
"--sycl_compiler",
type=SyclCompiler.from_str,
choices=list(SyclCompiler),
default="icpx",
)
parser.add_argument(
"--cuda_compute_capabilities",
type=comma_separated_list,
default=None,
)
parser.add_argument("--python_bin_path", default=sys.executable)
parser.add_argument(
"--compiler_options",
type=comma_separated_list,
default="-Wno-sign-compare",
)
parser.add_argument("--nccl", action="store_true")
# Path and version overrides
path_help = "Optional: will be found on PATH if possible."
parser.add_argument("--clang_path", help=path_help)
parser.add_argument("--gcc_path", help=path_help)
parser.add_argument(
"--ld_library_path",
help=(
"Optional: will be automatically taken from the current environment"
" if flag is not set"
),
)
parser.add_argument("--lld_path", help=path_help)
# CUDA specific
parser.add_argument(
"--cuda_version",
help="Optional: CUDA will be downloaded by Bazel if the flag is set",
)
parser.add_argument(
"--cudnn_version",
help="Optional: CUDNN will be downloaded by Bazel if the flag is set",
)
parser.add_argument(
"--local_cuda_path",
help=(
"Optional: Local CUDA dir will be used in dependencies if the flag"
" is set"
),
)
parser.add_argument(
"--local_cudnn_path",
help=(
"Optional: Local CUDNN dir will be used in dependencies if the flag"
" is set"
),
)
parser.add_argument(
"--local_nccl_path",
help=(
"Optional: Local NCCL dir will be used in dependencies if the flag"
" is set"
),
)
return parser.parse_args()
def main():
# Setup logging
logging.basicConfig()
logging.getLogger().setLevel(logging.INFO)
args = _parse_args()
config = XLAConfigOptions(
backend=args.backend,
os=args.os,
host_compiler=args.host_compiler,
cuda_compiler=args.cuda_compiler,
python_bin_path=args.python_bin_path,
compiler_options=args.compiler_options,
using_nccl=args.nccl,
rocm_compiler=args.rocm_compiler,
sycl_compiler=args.sycl_compiler,
)
bazelrc_lines = config.to_bazelrc_lines(
DiscoverablePathsAndVersions(
clang_path=args.clang_path,
gcc_path=args.gcc_path,
lld_path=args.lld_path,
ld_library_path=args.ld_library_path,
cuda_version=args.cuda_version,
cudnn_version=args.cudnn_version,
cuda_compute_capabilities=args.cuda_compute_capabilities,
local_cuda_path=args.local_cuda_path,
local_cudnn_path=args.local_cudnn_path,
local_nccl_path=args.local_nccl_path,
)
)
bazelrc_path = _XLA_SRC_ROOT / _XLA_BAZELRC_NAME
bazelrc_contents = "\n".join(bazelrc_lines) + "\n"
with (bazelrc_path).open("w") as f:
logging.info("Writing bazelrc to %s...", bazelrc_path)
f.write(bazelrc_contents)
def is_hermetic_build(backend: Backend, os_host: OS):
return (
backend != Backend.ROCM
and os_host == OS.LINUX
)
if __name__ == "__main__":
raise SystemExit(main())
| XLAConfigOptions |
python | readthedocs__readthedocs.org | readthedocs/api/v2/models.py | {
"start": 1786,
"end": 2370
} | class ____(AbstractAPIKey):
"""
API key for securely interacting with the API from the builders.
The key is attached to a single project,
it can be used to have write access to the API V2.
"""
project = models.ForeignKey(
Project,
on_delete=models.CASCADE,
related_name="build_api_keys",
help_text=_("Project that this API key grants access to"),
)
objects = BuildAPIKeyManager()
class Meta(AbstractAPIKey.Meta):
verbose_name = _("Build API key")
verbose_name_plural = _("Build API keys")
| BuildAPIKey |
python | pytorch__pytorch | tools/experimental/torchfuzz/operators/constant.py | {
"start": 212,
"end": 4982
} | class ____(Operator):
"""Operator for generating constants."""
def __init__(self):
super().__init__("constant")
self.template = "default" # Track template for DTensor compatibility
@property
def torch_op_name(self) -> str | None:
"""Constant is not a torch operation, it generates constant values."""
return None
def set_template(self, template: str):
"""Set the template for context-aware code generation."""
self.template = template
def can_produce(self, output_spec: Spec) -> bool:
"""Constant can produce any type of output."""
return True
def fuzz_inputs_specs(self, output_spec: Spec) -> list[Spec]:
"""Constant requires no inputs for fuzzing."""
return []
def codegen(
self, output_name: str, input_names: list[str], output_spec: Spec
) -> str:
"""Generate code for constant creation."""
# Create constant by calling fuzzing functions during codegen with deterministic seed
# Use a deterministic hash based on the variable name to ensure reproducibility across processes
import hashlib
var_seed = int(hashlib.md5(output_name.encode()).hexdigest()[:8], 16) % (2**31) # noqa: S324
if isinstance(output_spec, ScalarSpec):
# Call fuzz_scalar during codegen and embed the result
actual_value = fuzz_scalar(output_spec, seed=var_seed)
# Format the value for embedding in code
if isinstance(actual_value, bool):
value_str = str(actual_value)
elif isinstance(actual_value, (int, float)):
value_str = repr(actual_value)
elif isinstance(actual_value, complex):
value_str = f"complex({actual_value.real}, {actual_value.imag})"
else:
value_str = repr(actual_value)
return f"{output_name} = {value_str}"
elif isinstance(output_spec, TensorSpec):
# Call fuzz_tensor_simple during codegen and embed the result
actual_tensor = fuzz_tensor_simple(
output_spec.size, output_spec.stride, output_spec.dtype, seed=var_seed
)
# Convert tensor to code representation
size_str = str(output_spec.size)
dtype_str = f"torch.{output_spec.dtype}".replace("torch.torch.", "torch.")
# Handle empty tensors (with 0 elements)
if actual_tensor.numel() == 0:
# For empty tensors, use a default fill value based on dtype
import torch
default_values = {
torch.float16: 1.0,
torch.float32: 1.0,
torch.float64: 1.0,
torch.bfloat16: 1.0,
torch.int8: 1,
torch.int16: 1,
torch.int32: 1,
torch.int64: 1,
torch.bool: True,
torch.complex64: 1.0,
torch.complex128: 1.0,
}
fill_value = default_values.get(output_spec.dtype, 1)
tensor_creation = (
f"torch.full({size_str}, {fill_value}, dtype={dtype_str})"
)
else:
# For non-empty tensors, use the first element as fill value
fill_value = actual_tensor.flatten()[0].item()
# For integer types, clamp the value to a smaller range to avoid
# issues when used in arithmetic with embedding indices
import torch
if output_spec.dtype in [
torch.int8,
torch.int16,
torch.int32,
torch.int64,
]:
# Clamp integer values to [0, 3] to avoid index overflow in multiplication
# Even with multiplication, indices should stay in reasonable range
# pyrefly: ignore [bad-argument-type]
fill_value = max(0, min(3, abs(fill_value)))
tensor_creation = (
f"torch.full({size_str}, {fill_value}, dtype={dtype_str})"
)
# For DTensor template, convert to DTensor
if self.template == "dtensor":
return (
f"{output_name}_local = {tensor_creation}.to('cuda')\n"
f" {output_name} = DTensor.from_local({output_name}_local, mesh, placements)"
)
else:
return f"{output_name} = {tensor_creation}"
else:
return f"# Unknown output spec type for constant: {type(output_spec)}"
| ConstantOperator |
python | python__mypy | mypy/plugin.py | {
"start": 31554,
"end": 36250
} | class ____(Plugin):
"""A plugin that represents a sequence of chained plugins.
Each lookup method returns the hook for the first plugin that
reports a match.
This class should not be subclassed -- use Plugin as the base class
for all plugins.
"""
# TODO: Support caching of lookup results (through a LRU cache, for example).
def __init__(self, options: Options, plugins: list[Plugin]) -> None:
"""Initialize chained plugin.
Assume that the child plugins aren't mutated (results may be cached).
"""
super().__init__(options)
self._plugins = plugins
def set_modules(self, modules: dict[str, MypyFile]) -> None:
for plugin in self._plugins:
plugin.set_modules(modules)
def report_config_data(self, ctx: ReportConfigContext) -> Any:
config_data = [plugin.report_config_data(ctx) for plugin in self._plugins]
return config_data if any(x is not None for x in config_data) else None
def get_additional_deps(self, file: MypyFile) -> list[tuple[int, str, int]]:
deps = []
for plugin in self._plugins:
deps.extend(plugin.get_additional_deps(file))
return deps
def get_type_analyze_hook(self, fullname: str) -> Callable[[AnalyzeTypeContext], Type] | None:
# Micro-optimization: Inline iteration over plugins
for plugin in self._plugins:
hook = plugin.get_type_analyze_hook(fullname)
if hook is not None:
return hook
return None
def get_function_signature_hook(
self, fullname: str
) -> Callable[[FunctionSigContext], FunctionLike] | None:
# Micro-optimization: Inline iteration over plugins
for plugin in self._plugins:
hook = plugin.get_function_signature_hook(fullname)
if hook is not None:
return hook
return None
def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:
return self._find_hook(lambda plugin: plugin.get_function_hook(fullname))
def get_method_signature_hook(
self, fullname: str
) -> Callable[[MethodSigContext], FunctionLike] | None:
# Micro-optimization: Inline iteration over plugins
for plugin in self._plugins:
hook = plugin.get_method_signature_hook(fullname)
if hook is not None:
return hook
return None
def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:
# Micro-optimization: Inline iteration over plugins
for plugin in self._plugins:
hook = plugin.get_method_hook(fullname)
if hook is not None:
return hook
return None
def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None:
# Micro-optimization: Inline iteration over plugins
for plugin in self._plugins:
hook = plugin.get_attribute_hook(fullname)
if hook is not None:
return hook
return None
def get_class_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None:
return self._find_hook(lambda plugin: plugin.get_class_attribute_hook(fullname))
def get_class_decorator_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:
return self._find_hook(lambda plugin: plugin.get_class_decorator_hook(fullname))
def get_class_decorator_hook_2(
self, fullname: str
) -> Callable[[ClassDefContext], bool] | None:
return self._find_hook(lambda plugin: plugin.get_class_decorator_hook_2(fullname))
def get_metaclass_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:
return self._find_hook(lambda plugin: plugin.get_metaclass_hook(fullname))
def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:
return self._find_hook(lambda plugin: plugin.get_base_class_hook(fullname))
def get_customize_class_mro_hook(
self, fullname: str
) -> Callable[[ClassDefContext], None] | None:
return self._find_hook(lambda plugin: plugin.get_customize_class_mro_hook(fullname))
def get_dynamic_class_hook(
self, fullname: str
) -> Callable[[DynamicClassDefContext], None] | None:
return self._find_hook(lambda plugin: plugin.get_dynamic_class_hook(fullname))
def _find_hook(self, lookup: Callable[[Plugin], T]) -> T | None:
for plugin in self._plugins:
hook = lookup(plugin)
if hook is not None:
return hook
return None
| ChainedPlugin |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefault2.py | {
"start": 2521,
"end": 2674
} | class ____[**P = [1, int]]: ...
# This should generate an error because it combines a traditional ParamSpec
# with a new-style (PEP 695) ParamSpec.
| ClassP8 |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/execution.py | {
"start": 2817,
"end": 4607
} | class ____(graphene.ObjectType):
key = graphene.NonNull(graphene.String)
inputs = non_null_list(GrapheneExecutionStepInput)
outputs = non_null_list(GrapheneExecutionStepOutput)
solidHandleID = graphene.NonNull(graphene.String)
kind = graphene.NonNull(GrapheneStepKind)
metadata = non_null_list(GrapheneMetadataItemDefinition)
class Meta:
name = "ExecutionStep"
def __init__(
self, remote_execution_plan: RemoteExecutionPlan, execution_step_snap: ExecutionStepSnap
):
super().__init__()
self._remote_execution_plan = check.inst_param(
remote_execution_plan, "remote_execution_plan", RemoteExecutionPlan
)
self._plan_snapshot = remote_execution_plan.execution_plan_snapshot
self._step_snap = check.inst_param(
execution_step_snap, "execution_step_snap", ExecutionStepSnap
)
def resolve_metadata(self, _graphene_info: ResolveInfo):
return [
GrapheneMetadataItemDefinition(key=mdi.key, value=mdi.value)
for mdi in self._step_snap.metadata_items
]
def resolve_inputs(self, _graphene_info: ResolveInfo):
return [
GrapheneExecutionStepInput(inp, self._remote_execution_plan)
for inp in self._step_snap.inputs
]
def resolve_outputs(self, _graphene_info: ResolveInfo):
return [GrapheneExecutionStepOutput(out) for out in self._step_snap.outputs]
def resolve_key(self, _graphene_info: ResolveInfo):
return self._step_snap.key
def resolve_solidHandleID(self, _graphene_info: ResolveInfo):
return self._step_snap.node_handle_id
def resolve_kind(self, _graphene_info: ResolveInfo):
return self._step_snap.kind.value
| GrapheneExecutionStep |
python | matplotlib__matplotlib | galleries/examples/user_interfaces/embedding_in_wx2_sgskip.py | {
"start": 462,
"end": 1495
} | class ____(wx.Frame):
def __init__(self):
super().__init__(None, -1, 'CanvasFrame', size=(550, 350))
self.figure = Figure()
self.axes = self.figure.add_subplot()
t = np.arange(0.0, 3.0, 0.01)
s = np.sin(2 * np.pi * t)
self.axes.plot(t, s)
self.canvas = FigureCanvas(self, -1, self.figure)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.EXPAND)
self.SetSizer(self.sizer)
self.Fit()
self.add_toolbar() # comment this out for no toolbar
def add_toolbar(self):
self.toolbar = NavigationToolbar(self.canvas)
self.toolbar.Realize()
# By adding toolbar in sizer, we are able to put it at the bottom
# of the frame - so appearance is closer to GTK version.
self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
# update the axes menu on the toolbar
self.toolbar.update()
# Alternatively you could use:
# class App(wx.App):
| CanvasFrame |
python | facelessuser__pymdown-extensions | tests/util.py | {
"start": 625,
"end": 3307
} | class ____(unittest.TestCase):
"""Markdown unittest test case base."""
extension = []
extension_configs = {}
base = CURRENT_DIR
def setUp(self):
"""Setup."""
for k1, v1 in self.extension_configs.items():
if v1 is not None:
for k2, v2 in v1.items():
if isinstance(v2, str):
v1[k2] = v2.replace(
'{{BASE}}', self.base
).replace(
'{{RELATIVE}}', CURRENT_DIR
)
self.extension_configs[k1] = v1
self.md = markdown.Markdown(extensions=self.extension, extension_configs=self.extension_configs)
def dedent(self, text, strip=False):
"""Reduce indentation."""
return textwrap.dedent(text).strip('\n') if strip else textwrap.dedent(text)
def check_markdown(self, text, expected, dedent=False):
"""Check the markdown."""
if dedent:
# For markdown, beginning and ending new lines get stripped out with
# no issues, but for HTML (expected), we need to trim.
# If there are tests that are newline sensitive, it may make sense
# to call dedent directly to control this.
text = self.dedent(text)
expected = self.dedent(expected, True)
results = self.md.convert(text)
diff = list(
difflib.unified_diff(
expected.splitlines(True),
results.splitlines(True),
'Expected',
'Actual',
n=3
)
)
print(''.join(diff))
self.assertTrue(not diff)
def yaml_load(stream, loader=yaml.Loader, object_pairs_hook=OrderedDict):
"""
Custom YAML loader.
Make all YAML dictionaries load as ordered Dicts.
http://stackoverflow.com/a/21912744/3609487
Load all strings as unicode.
http://stackoverflow.com/a/2967461/3609487
"""
def construct_mapping(loader, node):
"""Convert to ordered dict."""
loader.flatten_mapping(node)
return object_pairs_hook(loader.construct_pairs(node))
def construct_yaml_str(self, node):
"""Override the default string handling function to always return unicode objects."""
return self.construct_scalar(node)
class Loader(loader):
"""Custom Loader."""
Loader.add_constructor(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
construct_mapping
)
Loader.add_constructor(
'tag:yaml.org,2002:str',
construct_yaml_str
)
return yaml.load(stream, Loader)
| MdCase |
python | spyder-ide__spyder | external-deps/qtconsole/qtconsole/rich_jupyter_widget.py | {
"start": 1106,
"end": 1174
} | class ____(Exception):
"""Exception for Latex errors"""
| LatexError |
python | mlflow__mlflow | dev/clint/src/clint/rules/isinstance_union_syntax.py | {
"start": 48,
"end": 1749
} | class ____(Rule):
def _message(self) -> str:
return (
"Use `isinstance(obj, (X, Y))` instead of `isinstance(obj, X | Y)`. "
"The union syntax with `|` is slower than using a tuple of types."
)
@staticmethod
def check(node: ast.Call) -> bool:
"""
Returns True if the call is isinstance with union syntax (X | Y) in the second argument.
Examples that should be flagged:
- isinstance(obj, str | int)
- isinstance(obj, int | str | float)
- isinstance(value, (dict | list))
Examples that should NOT be flagged:
- isinstance(obj, (str, int))
- isinstance(obj, str)
- other_func(obj, str | int)
"""
# Check if this is an isinstance call
if not (isinstance(node.func, ast.Name) and node.func.id == "isinstance"):
return False
# Check if the second argument uses union syntax (X | Y)
match node.args:
case [_, type_arg]:
return IsinstanceUnionSyntax._has_union_syntax(type_arg)
case _:
return False
@staticmethod
def _has_union_syntax(node: ast.expr) -> bool:
"""
Returns True if the node contains union syntax with BitOr operator.
This handles nested cases like (A | B) | C.
"""
match node:
case ast.BinOp(op=ast.BitOr()):
return True
case ast.Tuple(elts=elts):
# Check if any element in the tuple has union syntax
return any(map(IsinstanceUnionSyntax._has_union_syntax, elts))
case _:
return False
| IsinstanceUnionSyntax |
python | django-import-export__django-import-export | tests/core/forms.py | {
"start": 407,
"end": 553
} | class ____(AuthorFormMixin, ConfirmImportForm):
"""Customized ConfirmImportForm, with author field required"""
pass
| CustomConfirmImportForm |
python | donnemartin__system-design-primer | solutions/object_oriented_design/call_center/call_center.py | {
"start": 1833,
"end": 1977
} | class ____(object):
def __init__(self, rank):
self.state = CallState.READY
self.rank = rank
self.employee = None
| Call |
python | Lightning-AI__lightning | tests/tests_pytorch/helpers/advanced_models.py | {
"start": 1695,
"end": 2188
} | class ____(nn.Module):
def __init__(self, img_shape: tuple):
super().__init__()
self.model = nn.Sequential(
nn.Linear(int(np.prod(img_shape)), 512),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear(512, 256),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear(256, 1),
nn.Sigmoid(),
)
def forward(self, img):
img_flat = img.view(img.size(0), -1)
return self.model(img_flat)
| Discriminator |
python | sqlalchemy__sqlalchemy | test/base/test_events.py | {
"start": 23296,
"end": 23958
} | class ____(TearDownLocalEventsFixture, fixtures.TestBase):
"""test that ad-hoc subclasses are garbage collected."""
def setup_test(self):
class TargetEvents(event.Events):
def some_event(self, x, y):
pass
class Target:
dispatch = event.dispatcher(TargetEvents)
self.Target = Target
@testing.requires.predictable_gc
def test_subclass(self):
class SubTarget(self.Target):
pass
st = SubTarget()
st.dispatch.some_event(1, 2)
del st
del SubTarget
gc_collect()
eq_(self.Target.__subclasses__(), [])
| SubclassGrowthTest |
python | readthedocs__readthedocs.org | readthedocs/projects/views/private.py | {
"start": 28388,
"end": 28540
} | class ____(ProjectRedirectsMixin, ListView):
template_name = "redirects/redirect_list.html"
context_object_name = "redirects"
| ProjectRedirectsList |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/dagster_types.py | {
"start": 4146,
"end": 4329
} | class ____(graphene.ObjectType):
class Meta:
interfaces = (GrapheneDagsterType, GrapheneWrappingDagsterType)
name = "NullableDagsterType"
| GrapheneNullableDagsterType |
python | run-llama__llama_index | llama-index-core/llama_index/core/llama_dataset/rag.py | {
"start": 3697,
"end": 6421
} | class ____(BaseLlamaDataset[BaseQueryEngine]):
"""RagDataset class."""
_example_type = LabelledRagDataExample
def to_pandas(self) -> Any:
"""Create pandas dataframe."""
try:
import pandas as pd
except ImportError:
raise ImportError(
"pandas is required for this function. Please install it with `pip install pandas`."
)
data: Dict[str, List] = {
"query": [],
"reference_contexts": [],
"reference_answer": [],
"reference_answer_by": [],
"query_by": [],
}
for example in self.examples:
if not isinstance(example, LabelledRagDataExample):
raise ValueError(
"All examples in the dataset must be of type LabelledRagDataExample."
)
data["query"].append(example.query)
data["reference_contexts"].append(example.reference_contexts)
data["reference_answer"].append(example.reference_answer)
data["reference_answer_by"].append(str(example.reference_answer_by))
data["query_by"].append(str(example.query_by))
return pd.DataFrame(data)
async def _apredict_example( # type: ignore
self,
predictor: BaseQueryEngine,
example: LabelledRagDataExample,
sleep_time_in_seconds: int,
) -> RagExamplePrediction:
"""Async predict RAG example with a query engine."""
await asyncio.sleep(sleep_time_in_seconds)
response = await predictor.aquery(example.query)
return RagExamplePrediction(
response=str(response), contexts=[s.text for s in response.source_nodes]
)
def _predict_example( # type: ignore
self,
predictor: BaseQueryEngine,
example: LabelledRagDataExample,
sleep_time_in_seconds: int = 0,
) -> RagExamplePrediction:
"""Predict RAG example with a query engine."""
time.sleep(sleep_time_in_seconds)
response = predictor.query(example.query)
return RagExamplePrediction(
response=str(response), contexts=[s.text for s in response.source_nodes]
)
def _construct_prediction_dataset( # type: ignore
self, predictions: Sequence[RagExamplePrediction]
) -> RagPredictionDataset:
"""Construct prediction dataset."""
return RagPredictionDataset(predictions=predictions)
@property
def class_name(self) -> str:
"""Class name."""
return "LabelledRagDataset"
# British English + American English
LabeledRagDataExample = LabelledRagDataExample
LabeledRagDataset = LabelledRagDataset
| LabelledRagDataset |
python | pypa__setuptools | setuptools/_vendor/platformdirs/macos.py | {
"start": 112,
"end": 5580
} | class ____(PlatformDirsABC):
"""
Platform directories for the macOS operating system.
Follows the guidance from
`Apple documentation <https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/MacOSXDirectories/MacOSXDirectories.html>`_.
Makes use of the `appname <platformdirs.api.PlatformDirsABC.appname>`,
`version <platformdirs.api.PlatformDirsABC.version>`,
`ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.
"""
@property
def user_data_dir(self) -> str:
""":return: data directory tied to the user, e.g. ``~/Library/Application Support/$appname/$version``"""
return self._append_app_name_and_version(os.path.expanduser("~/Library/Application Support")) # noqa: PTH111
@property
def site_data_dir(self) -> str:
"""
:return: data directory shared by users, e.g. ``/Library/Application Support/$appname/$version``.
If we're using a Python binary managed by `Homebrew <https://brew.sh>`_, the directory
will be under the Homebrew prefix, e.g. ``/opt/homebrew/share/$appname/$version``.
If `multipath <platformdirs.api.PlatformDirsABC.multipath>` is enabled, and we're in Homebrew,
the response is a multi-path string separated by ":", e.g.
``/opt/homebrew/share/$appname/$version:/Library/Application Support/$appname/$version``
"""
is_homebrew = sys.prefix.startswith("/opt/homebrew")
path_list = [self._append_app_name_and_version("/opt/homebrew/share")] if is_homebrew else []
path_list.append(self._append_app_name_and_version("/Library/Application Support"))
if self.multipath:
return os.pathsep.join(path_list)
return path_list[0]
@property
def user_config_dir(self) -> str:
""":return: config directory tied to the user, same as `user_data_dir`"""
return self.user_data_dir
@property
def site_config_dir(self) -> str:
""":return: config directory shared by the users, same as `site_data_dir`"""
return self.site_data_dir
@property
def user_cache_dir(self) -> str:
""":return: cache directory tied to the user, e.g. ``~/Library/Caches/$appname/$version``"""
return self._append_app_name_and_version(os.path.expanduser("~/Library/Caches")) # noqa: PTH111
@property
def site_cache_dir(self) -> str:
"""
:return: cache directory shared by users, e.g. ``/Library/Caches/$appname/$version``.
If we're using a Python binary managed by `Homebrew <https://brew.sh>`_, the directory
will be under the Homebrew prefix, e.g. ``/opt/homebrew/var/cache/$appname/$version``.
If `multipath <platformdirs.api.PlatformDirsABC.multipath>` is enabled, and we're in Homebrew,
the response is a multi-path string separated by ":", e.g.
``/opt/homebrew/var/cache/$appname/$version:/Library/Caches/$appname/$version``
"""
is_homebrew = sys.prefix.startswith("/opt/homebrew")
path_list = [self._append_app_name_and_version("/opt/homebrew/var/cache")] if is_homebrew else []
path_list.append(self._append_app_name_and_version("/Library/Caches"))
if self.multipath:
return os.pathsep.join(path_list)
return path_list[0]
@property
def user_state_dir(self) -> str:
""":return: state directory tied to the user, same as `user_data_dir`"""
return self.user_data_dir
@property
def user_log_dir(self) -> str:
""":return: log directory tied to the user, e.g. ``~/Library/Logs/$appname/$version``"""
return self._append_app_name_and_version(os.path.expanduser("~/Library/Logs")) # noqa: PTH111
@property
def user_documents_dir(self) -> str:
""":return: documents directory tied to the user, e.g. ``~/Documents``"""
return os.path.expanduser("~/Documents") # noqa: PTH111
@property
def user_downloads_dir(self) -> str:
""":return: downloads directory tied to the user, e.g. ``~/Downloads``"""
return os.path.expanduser("~/Downloads") # noqa: PTH111
@property
def user_pictures_dir(self) -> str:
""":return: pictures directory tied to the user, e.g. ``~/Pictures``"""
return os.path.expanduser("~/Pictures") # noqa: PTH111
@property
def user_videos_dir(self) -> str:
""":return: videos directory tied to the user, e.g. ``~/Movies``"""
return os.path.expanduser("~/Movies") # noqa: PTH111
@property
def user_music_dir(self) -> str:
""":return: music directory tied to the user, e.g. ``~/Music``"""
return os.path.expanduser("~/Music") # noqa: PTH111
@property
def user_desktop_dir(self) -> str:
""":return: desktop directory tied to the user, e.g. ``~/Desktop``"""
return os.path.expanduser("~/Desktop") # noqa: PTH111
@property
def user_runtime_dir(self) -> str:
""":return: runtime directory tied to the user, e.g. ``~/Library/Caches/TemporaryItems/$appname/$version``"""
return self._append_app_name_and_version(os.path.expanduser("~/Library/Caches/TemporaryItems")) # noqa: PTH111
@property
def site_runtime_dir(self) -> str:
""":return: runtime directory shared by users, same as `user_runtime_dir`"""
return self.user_runtime_dir
__all__ = [
"MacOS",
]
| MacOS |
python | keras-team__keras | keras/src/layers/pooling/global_max_pooling_test.py | {
"start": 174,
"end": 2788
} | class ____(testing.TestCase):
@parameterized.parameters(
("channels_last", False, (3, 5, 4), (3, 4)),
("channels_last", True, (3, 5, 4), (3, 1, 4)),
("channels_first", False, (3, 5, 4), (3, 5)),
)
def test_global_max_pooling1d(
self,
data_format,
keepdims,
input_shape,
output_shape,
):
self.run_layer_test(
layers.GlobalMaxPooling1D,
init_kwargs={
"data_format": data_format,
"keepdims": keepdims,
},
input_shape=input_shape,
expected_output_shape=output_shape,
expected_num_trainable_weights=0,
expected_num_non_trainable_weights=0,
expected_num_losses=0,
supports_masking=False,
assert_built_after_instantiation=True,
)
@parameterized.parameters(
("channels_last", False, (3, 5, 6, 4), (3, 4)),
("channels_last", True, (3, 5, 6, 4), (3, 1, 1, 4)),
("channels_first", False, (3, 5, 6, 4), (3, 5)),
)
def test_global_max_pooling2d(
self,
data_format,
keepdims,
input_shape,
output_shape,
):
self.run_layer_test(
layers.GlobalMaxPooling2D,
init_kwargs={
"data_format": data_format,
"keepdims": keepdims,
},
input_shape=input_shape,
expected_output_shape=output_shape,
expected_num_trainable_weights=0,
expected_num_non_trainable_weights=0,
expected_num_losses=0,
supports_masking=False,
assert_built_after_instantiation=True,
)
@parameterized.parameters(
("channels_last", False, (3, 5, 6, 5, 4), (3, 4)),
("channels_last", True, (3, 5, 6, 5, 4), (3, 1, 1, 1, 4)),
("channels_first", False, (3, 5, 6, 5, 4), (3, 5)),
)
def test_global_max_pooling3d(
self,
data_format,
keepdims,
input_shape,
output_shape,
):
self.run_layer_test(
layers.GlobalMaxPooling3D,
init_kwargs={
"data_format": data_format,
"keepdims": keepdims,
},
input_shape=input_shape,
expected_output_shape=output_shape,
expected_num_trainable_weights=0,
expected_num_non_trainable_weights=0,
expected_num_losses=0,
supports_masking=False,
assert_built_after_instantiation=True,
)
| GlobalMaxPoolingBasicTest |
python | getsentry__sentry | src/sentry/sentry_metrics/aggregation_option_registry.py | {
"start": 187,
"end": 316
} | class ____(Enum):
HIST = "hist"
TEN_SECOND = "ten_second"
DISABLE_PERCENTILES = "disable_percentiles"
| AggregationOption |
python | walkccc__LeetCode | solutions/442. Find All Duplicates in an Array/442.py | {
"start": 0,
"end": 218
} | class ____:
def findDuplicates(self, nums: list[int]) -> list[int]:
ans = []
for num in nums:
nums[abs(num) - 1] *= -1
if nums[abs(num) - 1] > 0:
ans.append(abs(num))
return ans
| Solution |
python | ipython__ipython | IPython/external/pickleshare.py | {
"start": 1504,
"end": 8042
} | class ____(collections_abc.MutableMapping):
"""The main 'connection' object for PickleShare database"""
def __init__(self, root):
"""Return a db object that will manage the specied directory"""
if not isinstance(root, str):
root = str(root)
root = os.path.abspath(os.path.expanduser(root))
self.root = Path(root)
if not self.root.is_dir():
# catching the exception is necessary if multiple processes are concurrently trying to create a folder
# exists_ok keyword argument of mkdir does the same but only from Python 3.5
try:
self.root.mkdir(parents=True)
except OSError as e:
if e.errno != errno.EEXIST:
raise
# cache has { 'key' : (obj, orig_mod_time) }
self.cache = {}
def __getitem__(self, key):
"""db['key'] reading"""
fil = self.root / key
try:
mtime = fil.stat()[stat.ST_MTIME]
except OSError:
raise KeyError(key)
if fil in self.cache and mtime == self.cache[fil][1]:
return self.cache[fil][0]
try:
# The cached item has expired, need to read
with fil.open("rb") as f:
obj = pickle.loads(f.read())
except:
raise KeyError(key)
self.cache[fil] = (obj, mtime)
return obj
def __setitem__(self, key, value):
"""db['key'] = 5"""
fil = self.root / key
parent = fil.parent
if parent and not parent.is_dir():
parent.mkdir(parents=True)
# We specify protocol 2, so that we can mostly go between Python 2
# and Python 3. We can upgrade to protocol 3 when Python 2 is obsolete.
with fil.open("wb") as f:
pickle.dump(value, f, protocol=2)
try:
self.cache[fil] = (value, fil.stat().st_mtime)
except OSError as e:
if e.errno != errno.ENOENT:
raise
def hset(self, hashroot, key, value):
"""hashed set"""
hroot = self.root / hashroot
if not hroot.is_dir():
hroot.mkdir()
hfile = hroot / gethashfile(key)
d = self.get(hfile, {})
d.update({key: value})
self[hfile] = d
def hget(self, hashroot, key, default=_sentinel, fast_only=True):
"""hashed get"""
hroot = self.root / hashroot
hfile = hroot / gethashfile(key)
d = self.get(hfile, _sentinel)
# print "got dict",d,"from",hfile
if d is _sentinel:
if fast_only:
if default is _sentinel:
raise KeyError(key)
return default
# slow mode ok, works even after hcompress()
d = self.hdict(hashroot)
return d.get(key, default)
def hdict(self, hashroot):
"""Get all data contained in hashed category 'hashroot' as dict"""
hfiles = self.keys(hashroot + "/*")
hfiles.sort()
last = len(hfiles) and hfiles[-1] or ""
if last.endswith("xx"):
# print "using xx"
hfiles = [last] + hfiles[:-1]
all = {}
for f in hfiles:
# print "using",f
try:
all.update(self[f])
except KeyError:
print("Corrupt", f, "deleted - hset is not threadsafe!")
del self[f]
self.uncache(f)
return all
def hcompress(self, hashroot):
"""Compress category 'hashroot', so hset is fast again
hget will fail if fast_only is True for compressed items (that were
hset before hcompress).
"""
hfiles = self.keys(hashroot + "/*")
all = {}
for f in hfiles:
# print "using",f
all.update(self[f])
self.uncache(f)
self[hashroot + "/xx"] = all
for f in hfiles:
p = self.root / f
if p.name == "xx":
continue
p.unlink()
def __delitem__(self, key):
"""del db["key"]"""
fil = self.root / key
self.cache.pop(fil, None)
try:
fil.unlink()
except OSError:
# notfound and permission denied are ok - we
# lost, the other process wins the conflict
pass
def _normalized(self, p):
"""Make a key suitable for user's eyes"""
return str(p.relative_to(self.root)).replace("\\", "/")
def keys(self, globpat=None):
"""All keys in DB, or all keys matching a glob"""
if globpat is None:
files = self.root.rglob("*")
else:
files = self.root.glob(globpat)
return [self._normalized(p) for p in files if p.is_file()]
def __iter__(self):
return iter(self.keys())
def __len__(self):
return len(self.keys())
def uncache(self, *items):
"""Removes all, or specified items from cache
Use this after reading a large amount of large objects
to free up memory, when you won't be needing the objects
for a while.
"""
if not items:
self.cache = {}
for it in items:
self.cache.pop(it, None)
def waitget(self, key, maxwaittime=60):
"""Wait (poll) for a key to get a value
Will wait for `maxwaittime` seconds before raising a KeyError.
The call exits normally if the `key` field in db gets a value
within the timeout period.
Use this for synchronizing different processes or for ensuring
that an unfortunately timed "db['key'] = newvalue" operation
in another process (which causes all 'get' operation to cause a
KeyError for the duration of pickling) won't screw up your program
logic.
"""
wtimes = [0.2] * 3 + [0.5] * 2 + [1]
tries = 0
waited = 0
while 1:
try:
val = self[key]
return val
except KeyError:
pass
if waited > maxwaittime:
raise KeyError(key)
time.sleep(wtimes[tries])
waited += wtimes[tries]
if tries < len(wtimes) - 1:
tries += 1
def getlink(self, folder):
"""Get a convenient link for accessing items"""
return PickleShareLink(self, folder)
def __repr__(self):
return "PickleShareDB('%s')" % self.root
| PickleShareDB |
python | walkccc__LeetCode | solutions/692. Top K Frequent Words/692-2.py | {
"start": 225,
"end": 568
} | class ____:
def topKFrequent(self, words: list[str], k: int) -> list[str]:
ans = []
heap = []
for word, freq in collections.Counter(words).items():
heapq.heappush(heap, T(word, freq))
if len(heap) > k:
heapq.heappop(heap)
while heap:
ans.append(heapq.heappop(heap).word)
return ans[::-1]
| Solution |
python | pola-rs__polars | py-polars/tests/unit/io/database/test_async.py | {
"start": 996,
"end": 1814
} | class ____:
"""Mock SurrealDB connection/client object."""
__module__ = "surrealdb"
def __init__(self, url: str, mock_data: list[dict[str, Any]]) -> None:
self._mock_data = mock_data.copy()
self.url = url
async def __aenter__(self) -> Any:
await self.connect()
return self
async def __aexit__(self, *args: object, **kwargs: Any) -> None:
await self.close()
async def close(self) -> None:
pass
async def connect(self) -> None:
pass
async def use(self, namespace: str, database: str) -> None:
pass
async def query(
self, query: str, variables: dict[str, Any] | None = None
) -> list[dict[str, Any]]:
return [{"result": self._mock_data, "status": "OK", "time": "32.083µs"}]
| MockSurrealConnection |
python | zarr-developers__zarr-python | tests/test_store/test_logging.py | {
"start": 443,
"end": 5226
} | class ____(StoreTests[LoggingStore[LocalStore], cpu.Buffer]):
# store_cls is needed to do an isintsance check, so can't be a subscripted generic
store_cls = LoggingStore # type: ignore[assignment]
buffer_cls = cpu.Buffer
async def get(self, store: LoggingStore[LocalStore], key: str) -> Buffer:
return self.buffer_cls.from_bytes((store._store.root / key).read_bytes())
async def set(self, store: LoggingStore[LocalStore], key: str, value: Buffer) -> None:
parent = (store._store.root / key).parent
if not parent.exists():
parent.mkdir(parents=True)
(store._store.root / key).write_bytes(value.to_bytes())
@pytest.fixture
def store_kwargs(self, tmp_path: Path) -> StoreKwargs:
return {"store": LocalStore(str(tmp_path)), "log_level": "DEBUG"}
@pytest.fixture
def open_kwargs(self, tmp_path: Path) -> dict[str, type[LocalStore] | str]:
return {"store_cls": LocalStore, "root": str(tmp_path), "log_level": "DEBUG"}
@pytest.fixture
def store(self, store_kwargs: StoreKwargs) -> LoggingStore[LocalStore]:
return self.store_cls(**store_kwargs)
def test_store_supports_writes(self, store: LoggingStore[LocalStore]) -> None:
assert store.supports_writes
def test_store_supports_listing(self, store: LoggingStore[LocalStore]) -> None:
assert store.supports_listing
def test_store_repr(self, store: LoggingStore[LocalStore]) -> None:
assert f"{store!r}" == f"LoggingStore(LocalStore, 'file://{store._store.root.as_posix()}')"
def test_store_str(self, store: LoggingStore[LocalStore]) -> None:
assert str(store) == f"logging-file://{store._store.root.as_posix()}"
async def test_default_handler(
self, local_store: LocalStore, capsys: pytest.CaptureFixture[str]
) -> None:
# Store and then remove existing handlers to enter default handler code path
handlers = logging.getLogger().handlers[:]
for h in handlers:
logging.getLogger().removeHandler(h)
# Test logs are sent to stdout
wrapped = LoggingStore(store=local_store)
buffer = default_buffer_prototype().buffer
res = await wrapped.set("foo/bar/c/0", buffer.from_bytes(b"\x01\x02\x03\x04")) # type: ignore[func-returns-value]
assert res is None
captured = capsys.readouterr()
assert len(captured) == 2
assert "Calling LocalStore.set" in captured.out
assert "Finished LocalStore.set" in captured.out
# Restore handlers
for h in handlers:
logging.getLogger().addHandler(h)
def test_is_open_setter_raises(self, store: LoggingStore[LocalStore]) -> None:
"Test that a user cannot change `_is_open` without opening the underlying store."
with pytest.raises(
NotImplementedError, match="LoggingStore must be opened via the `_open` method"
):
store._is_open = True
@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"])
async def test_logging_store(store: Store, caplog: pytest.LogCaptureFixture) -> None:
wrapped = LoggingStore(store=store, log_level="DEBUG")
buffer = default_buffer_prototype().buffer
caplog.clear()
res = await wrapped.set("foo/bar/c/0", buffer.from_bytes(b"\x01\x02\x03\x04")) # type: ignore[func-returns-value]
assert res is None
assert len(caplog.record_tuples) == 2
for tup in caplog.record_tuples:
assert str(store) in tup[0]
assert f"Calling {type(store).__name__}.set" in caplog.record_tuples[0][2]
assert f"Finished {type(store).__name__}.set" in caplog.record_tuples[1][2]
caplog.clear()
keys = [k async for k in wrapped.list()]
assert keys == ["foo/bar/c/0"]
assert len(caplog.record_tuples) == 2
for tup in caplog.record_tuples:
assert str(store) in tup[0]
assert f"Calling {type(store).__name__}.list" in caplog.record_tuples[0][2]
assert f"Finished {type(store).__name__}.list" in caplog.record_tuples[1][2]
@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"])
async def test_logging_store_counter(store: Store) -> None:
wrapped = LoggingStore(store=store, log_level="DEBUG")
arr = zarr.create(shape=(10,), store=wrapped, overwrite=True)
arr[:] = 1
assert wrapped.counter["set"] == 2
assert wrapped.counter["list"] == 0
assert wrapped.counter["list_dir"] == 0
assert wrapped.counter["list_prefix"] == 0
if store.supports_deletes:
assert wrapped.counter["get"] == 0 # 1 if overwrite=False
assert wrapped.counter["delete_dir"] == 1
else:
assert wrapped.counter["get"] == 1
assert wrapped.counter["delete_dir"] == 0
| TestLoggingStore |
python | getsentry__sentry | tests/sentry/api/helpers/test_deprecation.py | {
"start": 912,
"end": 1508
} | class ____(Endpoint):
permission_classes = ()
@deprecated(test_date, suggested_api=replacement_api)
def get(self, request):
return Response({"ok": True})
def head(self, request):
return Response({"ok": True})
@deprecated(test_date, suggested_api=replacement_api, key="override")
def post(self, request):
return Response({"ok": True})
@deprecated(test_date, url_names=["sentry-dummy-delete-deprecated"])
def delete(self, request):
return Response({"ok": True})
dummy_endpoint = DummyEndpoint.as_view()
@no_silo_test
| DummyEndpoint |
python | cython__cython | Cython/Compiler/PyrexTypes.py | {
"start": 89882,
"end": 97249
} | class ____(CNumericType):
is_complex = 1
has_attributes = 1
scope = None
@property
def to_py_function(self):
return "__pyx_PyComplex_FromComplex%s" % self.implementation_suffix
def __init__(self, real_type):
if real_type.is_typedef:
real_type = real_type.resolve_known_type()
self.funcsuffix = "_%s" % real_type.specialization_name()
if not real_type.is_float:
# neither C nor C++ supports non-floating complex numbers,
# so fall back the on Cython implementation.
self.implementation_suffix = "_Cy"
elif real_type.is_typedef and real_type.typedef_is_external:
# C can't handle typedefs in complex numbers,
# so in this case also fall back on the Cython implementation.
self.implementation_suffix = "_CyTypedef"
else:
self.implementation_suffix = ""
if real_type.is_float:
self.math_h_modifier = real_type.math_h_modifier
else:
self.math_h_modifier = "_UNUSED"
self.real_type = real_type
CNumericType.__init__(self, real_type.rank + 0.5, real_type.signed)
self.binops = {}
self.from_parts = "%s_from_parts" % self.specialization_name()
self.default_value = "%s(0, 0)" % self.from_parts
def __eq__(self, other):
if isinstance(self, CComplexType) and isinstance(other, CComplexType):
return self.real_type == other.real_type
else:
return False
def __ne__(self, other):
if isinstance(self, CComplexType) and isinstance(other, CComplexType):
return self.real_type != other.real_type
else:
return True
def __lt__(self, other):
if isinstance(self, CComplexType) and isinstance(other, CComplexType):
return self.real_type < other.real_type
else:
# this is arbitrary, but it makes sure we always have
# *some* kind of order
return False
def __hash__(self):
return ~hash(self.real_type)
def declaration_code(self, entity_code,
for_display = 0, dll_linkage = None, pyrex = 0):
if pyrex or for_display:
real_code = self.real_type.declaration_code("", for_display, dll_linkage, pyrex)
base_code = "%s complex" % real_code
else:
base_code = public_decl(self.sign_and_name(), dll_linkage)
return self.base_declaration_code(base_code, entity_code)
def sign_and_name(self):
real_type_name = self.real_type.specialization_name()
real_type_name = real_type_name.replace('long__double','long_double')
real_type_name = real_type_name.replace('PY_LONG_LONG','long_long')
return Naming.type_prefix + real_type_name + "_complex"
def assignable_from(self, src_type):
# Temporary hack/feature disabling, see #441
if (not src_type.is_complex and src_type.is_numeric and src_type.is_typedef
and src_type.typedef_is_external):
return False
elif src_type.is_pyobject:
return True
else:
return super().assignable_from(src_type)
def assignable_from_resolved_type(self, src_type):
return (src_type.is_complex and self.real_type.assignable_from_resolved_type(src_type.real_type)
or src_type.is_numeric and self.real_type.assignable_from_resolved_type(src_type)
or src_type is error_type)
def attributes_known(self):
if self.scope is None:
from . import Symtab
self.scope = scope = Symtab.CClassScope(
'',
None,
visibility="extern",
parent_type=self)
scope.directives = {}
scope.declare_var("real", self.real_type, None, cname="real", is_cdef=True)
scope.declare_var("imag", self.real_type, None, cname="imag", is_cdef=True)
scope.declare_cfunction(
"conjugate",
CFuncType(self, [CFuncTypeArg("self", self, None)], nogil=True),
pos=None,
defining=1,
cname="__Pyx_c_conj%s" % self.funcsuffix)
return True
def _utility_code_context(self):
return {
'type': self.empty_declaration_code(),
'type_name': self.specialization_name(),
'real_type': self.real_type.empty_declaration_code(),
'func_suffix': self.funcsuffix,
'm': self.math_h_modifier,
'is_float': int(self.real_type.is_float),
'is_extern_float_typedef': int(
self.real_type.is_float and self.real_type.is_typedef and self.real_type.typedef_is_external)
}
def create_declaration_utility_code(self, env):
# This must always be run, because a single CComplexType instance can be shared
# across multiple compilations (the one created in the module scope)
if self.real_type.is_float:
env.use_utility_code(UtilityCode.load_cached('Header', 'Complex.c'))
utility_code_context = self._utility_code_context()
env.use_utility_code(UtilityCode.load_cached(
'RealImag' + self.implementation_suffix, 'Complex.c'))
env.use_utility_code(TempitaUtilityCode.load_cached(
'Declarations', 'Complex.c', utility_code_context))
env.use_utility_code(TempitaUtilityCode.load_cached(
'Arithmetic', 'Complex.c', utility_code_context))
return True
def can_coerce_to_pyobject(self, env):
return True
def can_coerce_from_pyobject(self, env):
return True
def create_to_py_utility_code(self, env):
self.create_declaration_utility_code(env)
env.use_utility_code(TempitaUtilityCode.load_cached(
'ToPy', 'Complex.c', self._utility_code_context()))
return True
def create_from_py_utility_code(self, env):
self.create_declaration_utility_code(env)
env.use_utility_code(TempitaUtilityCode.load_cached(
'FromPy', 'Complex.c', self._utility_code_context()))
self.from_py_function = "__Pyx_PyComplex_As_" + self.specialization_name()
return True
def lookup_op(self, nargs, op):
try:
return self.binops[nargs, op]
except KeyError:
pass
try:
op_name = complex_ops[nargs, op]
self.binops[nargs, op] = func_name = "__Pyx_c_%s%s" % (op_name, self.funcsuffix)
return func_name
except KeyError:
return None
def unary_op(self, op):
return self.lookup_op(1, op)
def binary_op(self, op):
return self.lookup_op(2, op)
def py_type_name(self):
return "complex"
def cast_code(self, expr_code):
return expr_code
def real_code(self, expr_code):
return "__Pyx_CREAL%s(%s)" % (self.implementation_suffix, expr_code)
def imag_code(self, expr_code):
return "__Pyx_CIMAG%s(%s)" % (self.implementation_suffix, expr_code)
complex_ops = {
(1, '-'): 'neg',
(1, 'zero'): 'is_zero',
(2, '+'): 'sum',
(2, '-'): 'diff',
(2, '*'): 'prod',
(2, '/'): 'quot',
(2, '**'): 'pow',
(2, '=='): 'eq',
}
| CComplexType |
python | django-haystack__django-haystack | haystack/inputs.py | {
"start": 73,
"end": 571
} | class ____:
"""
The base input type. Doesn't do much. You want ``Raw`` instead.
"""
input_type_name = "base"
post_process = True
def __init__(self, query_string, **kwargs):
self.query_string = query_string
self.kwargs = kwargs
def __repr__(self):
return "<%s '%s'>" % (self.__class__.__name__, self)
def __str__(self):
return force_str(self.query_string)
def prepare(self, query_obj):
return self.query_string
| BaseInput |
python | viewflow__viewflow | viewflow/forms/renderers.py | {
"start": 3655,
"end": 3729
} | class ____(TextareaRenderer):
tag = "vf-field-editor"
| TrixEditorRenderer |
python | joke2k__faker | faker/providers/address/en_PH/__init__.py | {
"start": 181,
"end": 43225
} | class ____(AddressProvider):
"""
Provider for addresses for en_PH locale
Like many things in the Philippines, even addresses are more complicated than necessary. This provider is already
a gross oversimplification, and it is still a lot more complicated VS providers from other locales despite taking
shortcuts. Below are some tidbits of information that, as a whole, shaped the design decisions of this provider.
- There are many levels of geopolitical division, thus many levels of local government:
* There are three major island groups - Luzon, Visayas, Mindanao
* Those major groups are divided into 17 different regions.
* Each region is divided into provinces with the exception of the National Capital Region aka Metro Manila.
* Each province is composed of multiple cities/municipalities.
* Metro Manila, like a province, is composed of multiple cities/municipalities, but it is a region.
* Each city/municipality is composed of multiple smaller local government units called barangays.
* In some places, some barangays are divided further, and as of 2019, there are 42,045 barangays on record.
- Metro Manila is part of Luzon geographically, but it is almost always treated as a separate entity politically,
economically, statistically, and so on, since it is home to around 13% of the population despite being only around
0.2% of the country's total land area.
- Names of cities, municipalities, and barangays vary a lot. Furthermore, if a place has a non-English name, there
will almost always be no English translation and vice-versa. It is essentially impossible to generate fake city,
municipality, and barangay names in a similar manner used in the other "en" locales while being locale specific.
- Subdivisions and other higher density housing (like high-rise condominiums) are popular in real estate.
- The 13th floor is omitted in buildings like in many parts of the world.
- The floor number distribution is partly based on the tallest buildings in the Philippines and partly anecdotal,
but the general idea is that the higher the floor number is, the lower probability of it appearing. Furthermore,
as the floor number approaches the highest floors of the tallest buildings, the probability plummets further.
- The address distribution is based on the official 2015 population census.
- Addresses should include a barangay, but it has been dropped to keep things sane, all things considered.
- In addition to numbered floors, buildings have ground floors and may have lower ground, upper ground, mezzanine,
and basement floors. Buildings may also have units on any of those floors, but the naming scheme varies, so they
have been dropped, again to keep things sane.
Sources:
- https://en.wikipedia.org/wiki/Provinces_of_the_Philippines
- https://en.wikipedia.org/wiki/List_of_cities_and_municipalities_in_the_Philippines
- https://en.wikipedia.org/wiki/Barangay
- https://en.wikipedia.org/wiki/Postal_addresses_in_the_Philippines
- https://en.wikipedia.org/wiki/List_of_ZIP_codes_in_the_Philippines
- https://www.phlpost.gov.ph/
- http://en.wikipedia.org/wiki/List_of_tallest_buildings_in_the_Philippines
- https://psa.gov.ph/sites/default/files/attachments/hsd/pressrelease/2015%20population%20counts%20Summary_0.xlsx
"""
metro_manila_postcodes = tuple(x for x in range(400, 1849))
luzon_province_postcodes = tuple(x for x in range(1850, 5000)) + tuple(x for x in range(5100, 5600))
visayas_province_postcodes = (
tuple(x for x in range(5000, 5100)) + tuple(x for x in range(5600, 5800)) + tuple(x for x in range(6000, 6900))
)
mindanao_province_postcodes = (
tuple(x for x in range(7000, 7600)) + tuple(x for x in range(8000, 8900)) + tuple(x for x in range(9000, 9900))
)
postcodes = (
metro_manila_postcodes + luzon_province_postcodes + visayas_province_postcodes + mindanao_province_postcodes
)
metro_manila_lgus = (
"Caloocan",
"Las Piñas",
"Makati",
"Malabon",
"Mandaluyong",
"Manila",
"Marikina",
"Muntinlupa",
"Navotas",
"Parañaque",
"Pasay",
"Pasig",
"Pateros",
"Quezon City",
"San Juan",
"Taguig",
"Valenzuela",
)
province_lgus = (
"Aborlan",
"Abra de Ilog",
"Abucay",
"Abulug",
"Abuyog",
"Adams",
"Agdangan",
"Aglipay",
"Agno",
"Agoncillo",
"Agoo",
"Aguilar",
"Aguinaldo",
"Agutaya",
"Ajuy",
"Akbar",
"Al-Barka",
"Alabat",
"Alabel",
"Alamada",
"Alaminos",
"Alangalang",
"Albuera",
"Alburquerque",
"Alcala",
"Alcantara",
"Alcoy",
"Alegria",
"Aleosan",
"Alfonso Castañeda",
"Alfonso Lista",
"Alfonso",
"Aliaga",
"Alicia",
"Alilem",
"Alimodian",
"Alitagtag",
"Allacapan",
"Allen",
"Almagro",
"Almeria",
"Aloguinsan",
"Aloran",
"Altavas",
"Alubijid",
"Amadeo",
"Amai Manabilang",
"Ambaguio",
"Amlan",
"Ampatuan",
"Amulung",
"Anahawan",
"Anao",
"Anda",
"Angadanan",
"Angat",
"Angeles",
"Angono",
"Anilao",
"Anini-y",
"Antequera",
"Antipas",
"Antipolo",
"Apalit",
"Aparri",
"Araceli",
"Arakan",
"Arayat",
"Argao",
"Aringay",
"Aritao",
"Aroroy",
"Arteche",
"Asingan",
"Asipulo",
"Asturias",
"Asuncion",
"Atimonan",
"Atok",
"Aurora",
"Ayungon",
"Baao",
"Babatngon",
"Bacacay",
"Bacarra",
"Baclayon",
"Bacnotan",
"Baco",
"Bacolod-Kalawi",
"Bacolod",
"Bacolor",
"Bacong",
"Bacoor",
"Bacuag",
"Badian",
"Badiangan",
"Badoc",
"Bagabag",
"Bagac",
"Bagamanoc",
"Baganga",
"Baggao",
"Bago",
"Baguio",
"Bagulin",
"Bagumbayan",
"Bais",
"Bakun",
"Balabac",
"Balabagan",
"Balagtas",
"Balamban",
"Balanga",
"Balangiga",
"Balangkayan",
"Balaoan",
"Balasan",
"Balatan",
"Balayan",
"Balbalan",
"Baleno",
"Baler",
"Balete",
"Baliangao",
"Baliguian",
"Balilihan",
"Balindong",
"Balingasag",
"Balingoan",
"Baliuag",
"Ballesteros",
"Baloi",
"Balud",
"Balungao",
"Bamban",
"Bambang",
"Banate",
"Banaue",
"Banaybanay",
"Banayoyo",
"Banga",
"Bangar",
"Bangued",
"Bangui",
"Banguingui",
"Bani",
"Banisilan",
"Banna",
"Bansalan",
"Bansud",
"Bantay",
"Bantayan",
"Banton",
"Baras",
"Barbaza",
"Barcelona",
"Barili",
"Barira",
"Barlig",
"Barobo",
"Barotac Nuevo",
"Barotac Viejo",
"Baroy",
"Barugo",
"Basay",
"Basco",
"Basey",
"Basilisa",
"Basista",
"Basud",
"Batac",
"Batad",
"Batan",
"Batangas City",
"Bataraza",
"Bato",
"Batuan",
"Bauan",
"Bauang",
"Bauko",
"Baungon",
"Bautista",
"Bay",
"Bayabas",
"Bayambang",
"Bayang",
"Bayawan",
"Baybay",
"Bayog",
"Bayombong",
"Bayugan",
"Belison",
"Benito Soliven",
"Besao",
"Bien Unido",
"Bilar",
"Biliran",
"Binalbagan",
"Binalonan",
"Biñan",
"Binangonan",
"Bindoy",
"Bingawan",
"Binidayan",
"Binmaley",
"Binuangan",
"Biri",
"Bislig",
"Boac",
"Bobon",
"Bocaue",
"Bogo",
"Bokod",
"Bolinao",
"Boliney",
"Boljoon",
"Bombon",
"Bongabon",
"Bongabong",
"Bongao",
"Bonifacio",
"Bontoc",
"Borbon",
"Borongan",
"Boston",
"Botolan",
"Braulio E. Dujali",
"Brooke's Point",
"Buadiposo-Buntong",
"Bubong",
"Bucay",
"Bucloc",
"Buenavista",
"Bugallon",
"Bugasong",
"Buguey",
"Buguias",
"Buhi",
"Bula",
"Bulakan",
"Bulalacao",
"Bulan",
"Buldon",
"Buluan",
"Bulusan",
"Bunawan",
"Burauen",
"Burdeos",
"Burgos",
"Buruanga",
"Bustos",
"Busuanga",
"Butig",
"Butuan",
"Buug",
"Caba",
"Cabadbaran",
"Cabagan",
"Cabanatuan",
"Cabangan",
"Cabanglasan",
"Cabarroguis",
"Cabatuan",
"Cabiao",
"Cabucgayan",
"Cabugao",
"Cabusao",
"Cabuyao",
"Cadiz",
"Cagayan de Oro",
"Cagayancillo",
"Cagdianao",
"Cagwait",
"Caibiran",
"Cainta",
"Cajidiocan",
"Calabanga",
"Calaca",
"Calamba",
"Calanasan",
"Calanogas",
"Calapan",
"Calape",
"Calasiao",
"Calatagan",
"Calatrava",
"Calauag",
"Calauan",
"Calayan",
"Calbayog",
"Calbiga",
"Calinog",
"Calintaan",
"Calubian",
"Calumpit",
"Caluya",
"Camalaniugan",
"Camalig",
"Camaligan",
"Camiling",
"Can-avid",
"Canaman",
"Candaba",
"Candelaria",
"Candijay",
"Candon",
"Candoni",
"Canlaon",
"Cantilan",
"Caoayan",
"Capalonga",
"Capas",
"Capoocan",
"Capul",
"Caraga",
"Caramoan",
"Caramoran",
"Carasi",
"Carcar",
"Cardona",
"Carigara",
"Carles",
"Carmen",
"Carmona",
"Carranglan",
"Carrascal",
"Casiguran",
"Castilla",
"Castillejos",
"Cataingan",
"Catanauan",
"Catarman",
"Catbalogan",
"Cateel",
"Catigbian",
"Catmon",
"Catubig",
"Cauayan",
"Cavinti",
"Cavite City",
"Cawayan",
"Cebu City",
"Cervantes",
"Clarin",
"Claver",
"Claveria",
"Columbio",
"Compostela",
"Concepcion",
"Conner",
"Consolacion",
"Corcuera",
"Cordon",
"Cordova",
"Corella",
"Coron",
"Cortes",
"Cotabato City",
"Cuartero",
"Cuenca",
"Culaba",
"Culasi",
"Culion",
"Currimao",
"Cuyapo",
"Cuyo",
"Daanbantayan",
"Daet",
"Dagami",
"Dagohoy",
"Daguioman",
"Dagupan",
"Dalaguete",
"Damulog",
"Danao",
"Dangcagan",
"Danglas",
"Dao",
"Dapa",
"Dapitan",
"Daraga",
"Daram",
"Dasmariñas",
"Dasol",
"Datu Abdullah Sangki",
"Datu Anggal Midtimbang",
"Datu Blah T. Sinsuat",
"Datu Hoffer Ampatuan",
"Datu Montawal",
"Datu Odin Sinsuat",
"Datu Paglas",
"Datu Piang",
"Datu Salibo",
"Datu Saudi-Ampatuan",
"Datu Unsay",
"Dauin",
"Dauis",
"Davao City",
"Del Carmen",
"Del Gallego",
"Delfin Albano",
"Diadi",
"Diffun",
"Digos",
"Dilasag",
"Dimasalang",
"Dimataling",
"Dimiao",
"Dinagat",
"Dinalungan",
"Dinalupihan",
"Dinapigue",
"Dinas",
"Dingalan",
"Dingle",
"Dingras",
"Dipaculao",
"Diplahan",
"Dipolog",
"Ditsaan-Ramain",
"Divilacan",
"Dolores",
"Don Carlos",
"Don Marcelino",
"Don Victoriano Chiongbian",
"Doña Remedios Trinidad",
"Donsol",
"Dueñas",
"Duero",
"Dulag",
"Dumaguete",
"Dumalag",
"Dumalinao",
"Dumalneg",
"Dumangas",
"Dumanjug",
"Dumaran",
"Dumarao",
"Dumingag",
"Dupax del Norte",
"Dupax del Sur",
"Echague",
"El Nido",
"El Salvador",
"Enrile",
"Enrique B. Magalona",
"Enrique Villanueva",
"Escalante",
"Esperanza",
"Estancia",
"Famy",
"Ferrol",
"Flora",
"Floridablanca",
"Gabaldon",
"Gainza",
"Galimuyod",
"Gamay",
"Gamu",
"Ganassi",
"Gandara",
"Gapan",
"Garchitorena",
"Garcia Hernandez",
"Gasan",
"Gattaran",
"General Emilio Aguinaldo",
"General Luna",
"General MacArthur",
"General Mamerto Natividad",
"General Mariano Alvarez",
"General Nakar",
"General Salipada K. Pendatun",
"General Santos",
"General Tinio",
"General Trias",
"Gerona",
"Getafe",
"Gigaquit",
"Gigmoto",
"Ginatilan",
"Gingoog",
"Giporlos",
"Gitagum",
"Glan",
"Gloria",
"Goa",
"Godod",
"Gonzaga",
"Governor Generoso",
"Gregorio del Pilar",
"Guagua",
"Gubat",
"Guiguinto",
"Guihulngan",
"Guimba",
"Guimbal",
"Guinayangan",
"Guindulman",
"Guindulungan",
"Guinobatan",
"Guinsiliban",
"Guipos",
"Guiuan",
"Gumaca",
"Gutalac",
"Hadji Mohammad Ajul",
"Hadji Muhtamad",
"Hadji Panglima Tahil",
"Hagonoy",
"Hamtic",
"Hermosa",
"Hernani",
"Hilongos",
"Himamaylan",
"Hinabangan",
"Hinatuan",
"Hindang",
"Hingyon",
"Hinigaran",
"Hinoba-an",
"Hinunangan",
"Hinundayan",
"Hungduan",
"Iba",
"Ibaan",
"Ibajay",
"Igbaras",
"Iguig",
"Ilagan",
"Iligan",
"Ilog",
"Iloilo City",
"Imelda",
"Impasugong",
"Imus",
"Inabanga",
"Indanan",
"Indang",
"Infanta",
"Initao",
"Inopacan",
"Ipil",
"Iriga",
"Irosin",
"Isabel",
"Isabela City",
"Isabela",
"Isulan",
"Itbayat",
"Itogon",
"Ivana",
"Ivisan",
"Jabonga",
"Jaen",
"Jagna",
"Jalajala",
"Jamindan",
"Janiuay",
"Jaro",
"Jasaan",
"Javier",
"Jiabong",
"Jimalalud",
"Jimenez",
"Jipapad",
"Jolo",
"Jomalig",
"Jones",
"Jordan",
"Jose Abad Santos",
"Jose Dalman",
"Jose Panganiban",
"Josefina",
"Jovellar",
"Juban",
"Julita",
"Kabacan",
"Kabankalan",
"Kabasalan",
"Kabayan",
"Kabugao",
"Kabuntalan",
"Kadingilan",
"Kalamansig",
"Kalawit",
"Kalayaan",
"Kalibo",
"Kalilangan",
"Kalingalan Caluang",
"Kananga",
"Kapai",
"Kapalong",
"Kapangan",
"Kapatagan",
"Kasibu",
"Katipunan",
"Kauswagan",
"Kawayan",
"Kawit",
"Kayapa",
"Kiamba",
"Kiangan",
"Kibawe",
"Kiblawan",
"Kibungan",
"Kidapawan",
"Kinoguitan",
"Kitaotao",
"Kitcharao",
"Kolambugan",
"Koronadal",
"Kumalarang",
"La Carlota",
"La Castellana",
"La Libertad",
"La Paz",
"La Trinidad",
"Laak",
"Labangan",
"Labason",
"Labo",
"Labrador",
"Lacub",
"Lagangilang",
"Lagawe",
"Lagayan",
"Lagonglong",
"Lagonoy",
"Laguindingan",
"Lake Sebu",
"Lakewood",
"Lal-lo",
"Lala",
"Lambayong",
"Lambunao",
"Lamitan",
"Lamut",
"Langiden",
"Languyan",
"Lantapan",
"Lantawan",
"Lanuza",
"Laoac",
"Laoag",
"Laoang",
"Lapinig",
"Lapu-Lapu",
"Lapuyan",
"Larena",
"Las Navas",
"Las Nieves",
"Lasam",
"Laua-an",
"Laur",
"Laurel",
"Lavezares",
"Lawaan",
"Lazi",
"Lebak",
"Leganes",
"Legazpi",
"Lemery",
"Leon B. Postigo",
"Leon",
"Leyte",
"Lezo",
"Lian",
"Lianga",
"Libacao",
"Libagon",
"Libertad",
"Libjo",
"Libmanan",
"Libon",
"Libona",
"Libungan",
"Licab",
"Licuan-Baay",
"Lidlidda",
"Ligao",
"Lila",
"Liliw",
"Liloan",
"Liloy",
"Limasawa",
"Limay",
"Linamon",
"Linapacan",
"Lingayen",
"Lingig",
"Lipa",
"Llanera",
"Llorente",
"Loay",
"Lobo",
"Loboc",
"Looc",
"Loon",
"Lope de Vega",
"Lopez Jaena",
"Lopez",
"Loreto",
"Los Baños",
"Luba",
"Lubang",
"Lubao",
"Lubuagan",
"Lucban",
"Lucena",
"Lugait",
"Lugus",
"Luisiana",
"Lumba-Bayabao",
"Lumbaca-Unayan",
"Lumban",
"Lumbatan",
"Lumbayanague",
"Luna",
"Lupao",
"Lupi",
"Lupon",
"Lutayan",
"Luuk",
"M'lang",
"Maasim",
"Maasin",
"Maayon",
"Mabalacat",
"Mabinay",
"Mabini",
"Mabitac",
"Mabuhay",
"Macabebe",
"Macalelon",
"MacArthur",
"Maco",
"Maconacon",
"Macrohon",
"Madalag",
"Madalum",
"Madamba",
"Maddela",
"Madrid",
"Madridejos",
"Magalang",
"Magallanes",
"Magarao",
"Magdalena",
"Magdiwang",
"Magpet",
"Magsaysay",
"Magsingal",
"Maguing",
"Mahaplag",
"Mahatao",
"Mahayag",
"Mahinog",
"Maigo",
"Maimbung",
"Mainit",
"Maitum",
"Majayjay",
"Makato",
"Makilala",
"Malabang",
"Malabuyoc",
"Malalag",
"Malangas",
"Malapatan",
"Malasiqui",
"Malay",
"Malaybalay",
"Malibcong",
"Malilipot",
"Malimono",
"Malinao",
"Malita",
"Malitbog",
"Mallig",
"Malolos",
"Malungon",
"Maluso",
"Malvar",
"Mamasapano",
"Mambajao",
"Mamburao",
"Mambusao",
"Manabo",
"Manaoag",
"Manapla",
"Manay",
"Mandaon",
"Mandaue",
"Mangaldan",
"Mangatarem",
"Mangudadatu",
"Manito",
"Manjuyod",
"Mankayan",
"Manolo Fortich",
"Mansalay",
"Manticao",
"Manukan",
"Mapanas",
"Mapandan",
"Mapun",
"Marabut",
"Maragondon",
"Maragusan",
"Maramag",
"Marantao",
"Marawi",
"Marcos",
"Margosatubig",
"Maria Aurora",
"Maria",
"Maribojoc",
"Marihatag",
"Marilao",
"Maripipi",
"Mariveles",
"Marogong",
"Masantol",
"Masbate City",
"Masinloc",
"Masiu",
"Maslog",
"Mataasnakahoy",
"Matag-ob",
"Matalam",
"Matalom",
"Matanao",
"Matanog",
"Mati",
"Matnog",
"Matuguinao",
"Matungao",
"Mauban",
"Mawab",
"Mayantoc",
"Maydolong",
"Mayorga",
"Mayoyao",
"Medellin",
"Medina",
"Mendez",
"Mercedes",
"Merida",
"Mexico",
"Meycauayan",
"Miagao",
"Midsalip",
"Midsayap",
"Milagros",
"Milaor",
"Mina",
"Minalabac",
"Minalin",
"Minglanilla",
"Moalboal",
"Mobo",
"Mogpog",
"Moises Padilla",
"Molave",
"Moncada",
"Mondragon",
"Monkayo",
"Monreal",
"Montevista",
"Morong",
"Motiong",
"Mulanay",
"Mulondo",
"Munai",
"Muñoz",
"Murcia",
"Mutia",
"Naawan",
"Nabas",
"Nabua",
"Nabunturan",
"Naga",
"Nagbukel",
"Nagcarlan",
"Nagtipunan",
"Naguilian",
"Naic",
"Nampicuan",
"Narra",
"Narvacan",
"Nasipit",
"Nasugbu",
"Natividad",
"Natonin",
"Naujan",
"Naval",
"New Bataan",
"New Corella",
"New Lucena",
"New Washington",
"Norala",
"Northern Kabuntalan",
"Norzagaray",
"Noveleta",
"Nueva Era",
"Nueva Valencia",
"Numancia",
"Nunungan",
"Oas",
"Obando",
"Ocampo",
"Odiongan",
"Old Panamao",
"Olongapo",
"Olutanga",
"Omar",
"Opol",
"Orani",
"Oras",
"Orion",
"Ormoc",
"Oroquieta",
"Oslob",
"Oton",
"Ozamiz",
"Padada",
"Padre Burgos",
"Padre Garcia",
"Paete",
"Pagadian",
"Pagalungan",
"Pagayawan",
"Pagbilao",
"Paglat",
"Pagsanghan",
"Pagsanjan",
"Pagudpud",
"Pakil",
"Palanan",
"Palanas",
"Palapag",
"Palauig",
"Palayan",
"Palimbang",
"Palo",
"Palompon",
"Paluan",
"Pambujan",
"Pamplona",
"Panabo",
"Panaon",
"Panay",
"Pandag",
"Pandami",
"Pandan",
"Pandi",
"Panganiban",
"Pangantucan",
"Pangil",
"Panglao",
"Panglima Estino",
"Panglima Sugala",
"Pangutaran",
"Paniqui",
"Panitan",
"Pantabangan",
"Pantao Ragat",
"Pantar",
"Pantukan",
"Panukulan",
"Paoay",
"Paombong",
"Paracale",
"Paracelis",
"Paranas",
"Parang",
"Pasacao",
"Pasil",
"Passi",
"Pastrana",
"Pasuquin",
"Pata",
"Patikul",
"Patnanungan",
"Patnongon",
"Pavia",
"Payao",
"Peñablanca",
"Peñaranda",
"Peñarrubia",
"Perez",
"Piagapo",
"Piat",
"Picong",
"Piddig",
"Pidigan",
"Pigcawayan",
"Pikit",
"Pila",
"Pilar",
"Pili",
"Pililla",
"Pinabacdao",
"Pinamalayan",
"Pinamungajan",
"Piñan",
"Pinili",
"Pintuyan",
"Pinukpuk",
"Pio Duran",
"Pio V. Corpuz",
"Pitogo",
"Placer",
"Plaridel",
"Pola",
"Polanco",
"Polangui",
"Polillo",
"Polomolok",
"Pontevedra",
"Poona Bayabao",
"Poona Piagapo",
"Porac",
"Poro",
"Pototan",
"Pozorrubio",
"Presentacion",
"President Carlos P. Garcia",
"President Manuel A. Roxas",
"President Quirino",
"President Roxas",
"Prieto Diaz",
"Prosperidad",
"Pualas",
"Pudtol",
"Puerto Galera",
"Puerto Princesa",
"Pugo",
"Pulilan",
"Pulupandan",
"Pura",
"Quezon",
"Quinapondan",
"Quirino",
"Ragay",
"Rajah Buayan",
"Ramon Magsaysay",
"Ramon",
"Ramos",
"Rapu-Rapu",
"Real",
"Reina Mercedes",
"Remedios T. Romualdez",
"Rizal",
"Rodriguez",
"Romblon",
"Ronda",
"Rosales",
"Rosario",
"Roseller Lim",
"Roxas City",
"Roxas",
"Sabangan",
"Sablan",
"Sablayan",
"Sabtang",
"Sadanga",
"Sagada",
"Sagay",
"Sagbayan",
"Sagñay",
"Saguday",
"Saguiaran",
"Saint Bernard",
"Salay",
"Salcedo",
"Sallapadan",
"Salug",
"Salvador Benedicto",
"Salvador",
"Samal",
"Samboan",
"Sampaloc",
"San Agustin",
"San Andres",
"San Antonio",
"San Benito",
"San Carlos",
"San Clemente",
"San Dionisio",
"San Emilio",
"San Enrique",
"San Esteban",
"San Fabian",
"San Felipe",
"San Fernando",
"San Francisco",
"San Gabriel",
"San Guillermo",
"San Ildefonso",
"San Isidro",
"San Jacinto",
"San Joaquin",
"San Jorge",
"San Jose de Buan",
"San Jose de Buenavista",
"San Jose del Monte",
"San Jose",
"San Juan",
"San Julian",
"San Leonardo",
"San Lorenzo Ruiz",
"San Lorenzo",
"San Luis",
"San Manuel",
"San Marcelino",
"San Mariano",
"San Mateo",
"San Miguel",
"San Narciso",
"San Nicolas",
"San Pablo",
"San Pascual",
"San Pedro",
"San Policarpo",
"San Quintin",
"San Rafael",
"San Remigio",
"San Ricardo",
"San Roque",
"San Sebastian",
"San Simon",
"San Teodoro",
"San Vicente",
"Sanchez-Mira",
"Santa Ana",
"Santa Barbara",
"Santa Catalina",
"Santa Cruz",
"Santa Elena",
"Santa Fe",
"Santa Ignacia",
"Santa Josefa",
"Santa Lucia",
"Santa Magdalena",
"Santa Marcela",
"Santa Margarita",
"Santa Maria",
"Santa Monica",
"Santa Praxedes",
"Santa Rita",
"Santa Rosa",
"Santa Teresita",
"Santa",
"Santander",
"Santiago",
"Santo Domingo",
"Santo Niño",
"Santo Tomas",
"Santol",
"Sapa-Sapa",
"Sapad",
"Sapang Dalaga",
"Sapian",
"Sara",
"Sarangani",
"Sariaya",
"Sarrat",
"Sasmuan",
"Sebaste",
"Senator Ninoy Aquino",
"Sergio Osmeña Sr.",
"Sevilla",
"Shariff Aguak",
"Shariff Saydona Mustapha",
"Siasi",
"Siaton",
"Siay",
"Siayan",
"Sibagat",
"Sibalom",
"Sibonga",
"Sibuco",
"Sibulan",
"Sibunag",
"Sibutad",
"Sibutu",
"Sierra Bullones",
"Sigay",
"Sigma",
"Sikatuna",
"Silago",
"Silang",
"Silay",
"Silvino Lobos",
"Simunul",
"Sinacaban",
"Sinait",
"Sindangan",
"Siniloan",
"Siocon",
"Sipalay",
"Sipocot",
"Siquijor",
"Sirawai",
"Siruma",
"Sison",
"Sitangkai",
"Socorro",
"Sofronio Española",
"Sogod",
"Solana",
"Solano",
"Solsona",
"Sominot",
"Sorsogon City",
"South Ubian",
"South Upi",
"Sual",
"Subic",
"Sudipen",
"Sugbongcogon",
"Sugpon",
"Sulat",
"Sulop",
"Sultan Dumalondong",
"Sultan Kudarat",
"Sultan Mastura",
"Sultan Naga Dimaporo",
"Sultan sa Barongis",
"Sultan Sumagka",
"Sumilao",
"Sumisip",
"Surallah",
"Surigao City",
"Suyo",
"T'Boli",
"Taal",
"Tabaco",
"Tabango",
"Tabina",
"Tabogon",
"Tabontabon",
"Tabuan-Lasa",
"Tabuelan",
"Tabuk",
"Tacloban",
"Tacurong",
"Tadian",
"Taft",
"Tagana-an",
"Tagapul-an",
"Tagaytay",
"Tagbilaran",
"Tagbina",
"Tagkawayan",
"Tago",
"Tagoloan II",
"Tagoloan",
"Tagudin",
"Tagum",
"Talacogon",
"Talaingod",
"Talakag",
"Talalora",
"Talavera",
"Talayan",
"Talibon",
"Talipao",
"Talisay",
"Talisayan",
"Talugtug",
"Talusan",
"Tambulig",
"Tampakan",
"Tamparan",
"Tampilisan",
"Tanauan",
"Tanay",
"Tandag",
"Tandubas",
"Tangalan",
"Tangcal",
"Tangub",
"Tanjay",
"Tantangan",
"Tanudan",
"Tanza",
"Tapaz",
"Tapul",
"Taraka",
"Tarangnan",
"Tarlac City",
"Tarragona",
"Tayabas",
"Tayasan",
"Taysan",
"Taytay",
"Tayug",
"Tayum",
"Teresa",
"Ternate",
"Tiaong",
"Tibiao",
"Tigaon",
"Tigbao",
"Tigbauan",
"Tinambac",
"Tineg",
"Tinglayan",
"Tingloy",
"Tinoc",
"Tipo-Tipo",
"Titay",
"Tiwi",
"Tobias Fornier",
"Toboso",
"Toledo",
"Tolosa",
"Tomas Oppus",
"Torrijos",
"Trece Martires",
"Trento",
"Trinidad",
"Tuao",
"Tuba",
"Tubajon",
"Tubao",
"Tubaran",
"Tubay",
"Tubigon",
"Tublay",
"Tubo",
"Tubod",
"Tubungan",
"Tuburan",
"Tudela",
"Tugaya",
"Tuguegarao",
"Tukuran",
"Tulunan",
"Tumauini",
"Tunga",
"Tungawan",
"Tupi",
"Turtle Islands",
"Tuy",
"Ubay",
"Umingan",
"Ungkaya Pukan",
"Unisan",
"Upi",
"Urbiztondo",
"Urdaneta",
"Uson",
"Uyugan",
"Valderrama",
"Valencia",
"Valladolid",
"Vallehermoso",
"Veruela",
"Victoria",
"Victorias",
"Viga",
"Vigan",
"Villaba",
"Villanueva",
"Villareal",
"Villasis",
"Villaverde",
"Villaviciosa",
"Vincenzo A. Sagun",
"Vintar",
"Vinzons",
"Virac",
"Wao",
"Zamboanga City",
"Zamboanguita",
"Zaragoza",
"Zarraga",
"Zumarraga",
)
luzon_provinces = (
"Abra",
"Albay",
"Apayao",
"Aurora",
"Bataan",
"Batanes",
"Batangas",
"Benguet",
"Bulacan",
"Cagayan",
"Camarines Norte",
"Camarines Sur",
"Catanduanes",
"Cavite",
"Ifugao",
"Ilocos Norte",
"Ilocos Sur",
"Isabela",
"Kalinga",
"La Union",
"Laguna",
"Marinduque",
"Masbate",
"Mountain Province",
"Nueva Ecija",
"Nueva Vizcaya",
"Occidental Mindoro",
"Oriental Mindoro",
"Palawan",
"Pampanga",
"Pangasinan",
"Quezon",
"Quirino",
"Rizal",
"Romblon",
"Sorsogon",
"Tarlac",
"Zambales",
)
visayas_provinces = (
"Aklan",
"Antique",
"Biliran",
"Bohol",
"Capiz",
"Cebu",
"Eastern Samar",
"Guimaras",
"Iloilo",
"Leyte",
"Negros Occidental",
"Negros Oriental",
"Northern Samar",
"Samar",
"Siquijor",
"Southern Leyte",
)
mindanao_provinces = (
"Agusan del Norte",
"Agusan del Sur",
"Basilan",
"Bukidnon",
"Camiguin",
"Compostela Valley",
"Cotabato",
"Davao del Norte",
"Davao del Sur",
"Davao Occidental",
"Davao Oriental",
"Dinagat Islands",
"Lanao del Norte",
"Lanao del Sur",
"Maguindanao",
"Misamis Occidental",
"Misamis Oriental",
"Sarangani",
"South Cotabato",
"Sultan Kudarat",
"Sulu",
"Surigao del Norte",
"Surigao del Sur",
"Tawi-Tawi",
"Zamboanga del Norte",
"Zamboanga del Sur",
"Zamboanga Sibugay",
)
provinces = luzon_provinces + visayas_provinces + mindanao_provinces
partitioned_building_number_formats = (
"{{standalone_building_number}}?",
"{{standalone_building_number}} ?",
"{{standalone_building_number}}-?",
"{{standalone_building_number}} Unit ?",
)
building_unit_number_formats = (
"Unit {{floor_unit_number}}",
"Room {{floor_unit_number}}",
"{{floor_number}}F",
"{{ordinal_floor_number}} Floor",
)
building_name_formats = (
"{{last_name}} {{building_name_suffix}}",
"{{random_object_name}} {{building_name_suffix}}",
)
building_name_suffixes = (
"Apartment",
"Apartments",
"Building",
"Building %",
"Building Tower %",
"Condominiums",
"Condominiums %",
"Condominiums Tower %",
"Place",
"Place %",
"Place Tower %",
"Residences",
"Residences %",
"Residences Tower %",
"Suites",
"Suites %",
"Suites Tower %",
"Tower",
"Towers",
"Towers %",
)
subdivision_unit_number_formats = (
"B{{subdivision_block_number}} L{{subdivision_lot_number}}",
"Block {{subdivision_block_number}} Lot {{subdivision_lot_number}}",
)
subdivision_name_formats = (
"{{last_name}} {{subdivision_name_suffix}}",
"{{random_object_name}} {{subdivision_name_suffix}}",
)
subdivision_name_suffixes = (
"Cove",
"Cove %",
"Cove Phase %",
"Estates",
"Estates %",
"Estates Phase %",
"Grove",
"Grove %",
"Grove Phase %",
"Homes",
"Homes %",
"Homes Phase %",
"Subdivision",
"Subdivision %",
"Subdivision Phase %",
"Village",
"Village %",
"Village Phase %",
)
floor_numbers = OrderedDict(
[(str(x), 0.08) for x in range(2, 5)] # Floors 2 to 4, 24% of the time
+ [(str(x), 0.32356832089420257 / x) for x in range(5, 13)] # Floors 5 to 12, 33% of the time
+ [(str(x), 0.30341265418486174 / (x - 1)) for x in range(14, 30)] # Floors 14 to 29, 25% of the time
+ [(str(x), 0.30096338222652870 / (x - 1)) for x in range(30, 50)] # Floors 30 to 49, 16% of the time
+ [(str(x), 0.04570476167856688 / (x - 1)) for x in range(50, 75)] # Floors 50 to 74, 1.9% of the time
+ [(str(x), 0.003415677066138734 / (x - 1)) for x in range(75, 100)] # Floors 75 to 99, 0.1% of the time
)
street_suffixes = OrderedDict(
[
("Avenue", 0.12),
("Avenue Extension", 0.01),
("Boulevard", 0.05),
("Boulevard Extension", 0.008),
("Circle", 0.002),
("Drive", 0.15),
("Drive Extension", 0.03),
("Expressway", 0.01),
("Extension", 0.05),
("Highway", 0.02),
("Road", 0.2),
("Road Extension", 0.04),
("Service Road", 0.01),
("Street", 0.3),
]
)
street_name_formats = (
"{{last_name}} {{street_suffix}}",
"{{ordinal_street_number}} {{street_suffix}}",
"{{gemstone_name}} {{street_suffix}}",
"{{mountain_name}} {{street_suffix}}",
"{{plant_name}} {{street_suffix}}",
"{{space_object_name}} {{street_suffix}}",
)
street_address_formats = (
"{{standalone_building_number}} {{street_name}}",
"{{partitioned_building_number}} {{street_name}}",
"{{subdivision_unit_number}} {{subdivision_name}}, {{street_name}}",
"{{subdivision_unit_number}} {{street_name}}, {{subdivision_name}}",
"{{standalone_building_number}} {{street_name}}, {{subdivision_name}}",
"{{building_unit_number}} {{building_name}}, {{standalone_building_number}} {{street_name}}",
)
metro_manila_address_formats = ("{{street_address}}, {{metro_manila_lgu}}, {{metro_manila_postcode}} Metro Manila",)
luzon_province_address_formats = (
"{{street_address}}, {{province_lgu}}, {{luzon_province_postcode}} {{luzon_province}}",
)
visayas_province_address_formats = (
"{{street_address}}, {{province_lgu}}, {{visayas_province_postcode}} {{visayas_province}}",
)
mindanao_province_address_formats = (
"{{street_address}}, {{province_lgu}}, {{mindanao_province_postcode}} {{mindanao_province}}",
)
address_formats = OrderedDict(
[
*[(fmt, 0.127524) for fmt in metro_manila_address_formats],
*[(fmt, 0.485317) for fmt in luzon_province_address_formats],
*[(fmt, 0.148142) for fmt in visayas_province_address_formats],
*[(fmt, 0.239017) for fmt in mindanao_province_address_formats],
]
)
def _ordinal_string(self, num: Union[int, str]) -> str:
if isinstance(num, str):
num = int(num)
suffix = ["th", "st", "nd", "rd", "th"][min(num % 10, 4)]
if 11 <= num % 100 <= 13:
suffix = "th"
return str(num) + suffix
def _create_postcode(self, postcodes: Sequence[int]) -> str:
return f"{self.random_element(postcodes):04d}"
def _create_address(self, address_formats: ElementsType[str]) -> str:
return self.generator.parse(self.random_element(address_formats))
def metro_manila_postcode(self) -> str:
return self._create_postcode(self.metro_manila_postcodes)
def luzon_province_postcode(self) -> str:
return self._create_postcode(self.luzon_province_postcodes)
def visayas_province_postcode(self) -> str:
return self._create_postcode(self.visayas_province_postcodes)
def mindanao_province_postcode(self) -> str:
return self._create_postcode(self.mindanao_province_postcodes)
def postcode(self) -> str:
return self._create_postcode(self.postcodes)
def luzon_province(self) -> str:
return self.random_element(self.luzon_provinces)
def visayas_province(self) -> str:
return self.random_element(self.visayas_provinces)
def mindanao_province(self) -> str:
return self.random_element(self.mindanao_provinces)
def administrative_unit(self) -> str:
return self.random_element(self.provinces)
province = administrative_unit
def standalone_building_number(self) -> str:
return str(self.random_int(min=1))
def partitioned_building_number(self) -> str:
pattern: str = self.lexify(
self.random_element(self.partitioned_building_number_formats),
letters=ascii_uppercase[:10],
)
return self.generator.parse(pattern)
def building_number(self) -> str:
if self.random_int() % 2 == 0:
return self.standalone_building_number()
else:
return self.partitioned_building_number()
def ordinal_street_number(self) -> str:
return self._ordinal_string(self.random_int(1, 99))
def floor_number(self) -> str:
return self.random_element(self.floor_numbers)
def ordinal_floor_number(self) -> str:
return self._ordinal_string(self.floor_number())
def floor_unit_number(self) -> str:
return f"{self.floor_number()}{self.random_int(1, 40):02d}"
def building_unit_number(self) -> str:
return self.generator.parse(self.random_element(self.building_unit_number_formats))
def building_name(self) -> str:
return self.generator.parse(self.random_element(self.building_name_formats))
def building_name_suffix(self) -> str:
return self.numerify(self.random_element(self.building_name_suffixes))
def subdivision_block_number(self) -> str:
return f"{self.random_int(1, 25):02d}"
def subdivision_lot_number(self) -> str:
return f"{self.random_int(1, 99):02d}"
def subdivision_unit_number(self) -> str:
return self.generator.parse(self.random_element(self.subdivision_unit_number_formats))
def subdivision_name(self) -> str:
return self.generator.parse(self.random_element(self.subdivision_name_formats))
def subdivision_name_suffix(self) -> str:
return self.numerify(self.random_element(self.subdivision_name_suffixes))
def metro_manila_lgu(self) -> str:
return self.random_element(self.metro_manila_lgus)
def province_lgu(self) -> str:
return self.random_element(self.province_lgus)
def metro_manila_address(self) -> str:
return self._create_address(self.metro_manila_address_formats)
def luzon_province_address(self) -> str:
return self._create_address(self.luzon_province_address_formats)
def visayas_province_address(self) -> str:
return self._create_address(self.visayas_province_address_formats)
def mindanao_province_address(self) -> str:
return self._create_address(self.mindanao_province_address_formats)
def address(self) -> str:
return self._create_address(self.address_formats)
| Provider |
python | spack__spack | lib/spack/spack/mirrors/utils.py | {
"start": 5864,
"end": 8312
} | class ____:
def __init__(self):
# Counter is used to easily merge mirror stats for one spec into mirror stats for all specs
self.present = Counter()
self.new = Counter()
self.errors = Counter()
def merge(self, ext_mirror_stat: MirrorStatsForOneSpec):
# For the sake of parallelism we need a way to reduce/merge different
# MirrorStats objects.
self.present.update(ext_mirror_stat.present)
self.new.update(ext_mirror_stat.new)
self.errors.update(ext_mirror_stat.errors)
def stats(self):
# Convert dictionary to list
present_list = list(self.present.keys())
new_list = list(self.new.keys())
errors_list = list(self.errors.keys())
return present_list, new_list, errors_list
def create_mirror_from_package_object(
pkg_obj, mirror_cache: "spack.caches.MirrorCache", mirror_stats: MirrorStatsForOneSpec
) -> bool:
"""Add a single package object to a mirror.
The package object is only required to have an associated spec
with a concrete version.
Args:
pkg_obj (spack.package_base.PackageBase): package object with to be added.
mirror_cache: mirror where to add the spec.
mirror_stats: statistics on the current mirror
Return:
True if the spec was added successfully, False otherwise
"""
tty.msg("Adding package {} to mirror".format(pkg_obj.spec.format("{name}{@version}")))
max_retries = 3
for num_retries in range(max_retries):
try:
# Includes patches and resources
with pkg_obj.stage as pkg_stage:
pkg_stage.cache_mirror(mirror_cache, mirror_stats)
break
except Exception as e:
pkg_obj.stage.destroy()
if num_retries + 1 == max_retries:
if spack.config.get("config:debug"):
traceback.print_exc()
else:
tty.warn(
"Error while fetching %s" % pkg_obj.spec.format("{name}{@version}"), str(e)
)
mirror_stats.error()
return False
return True
def require_mirror_name(mirror_name):
"""Find a mirror by name and raise if it does not exist"""
mirror = MirrorCollection().get(mirror_name)
if not mirror:
raise ValueError(f'no mirror named "{mirror_name}"')
return mirror
| MirrorStatsForAllSpecs |
python | pydantic__pydantic | pydantic-core/tests/serializers/test_union.py | {
"start": 3815,
"end": 18359
} | class ____(ModelB):
pass
@pytest.mark.parametrize('input_value', [ModelB(b'bite', 2.3456), SubclassB(b'bite', 2.3456)])
def test_model_b(model_serializer: SchemaSerializer, input_value):
assert model_serializer.to_python(input_value) == {'c': b'bite', 'd': '2.35'}
assert model_serializer.to_python(input_value, mode='json') == {'c': 'bite', 'd': '2.35'}
assert model_serializer.to_json(input_value) == b'{"c":"bite","d":"2.35"}'
def test_keys():
s = SchemaSerializer(
core_schema.dict_schema(
core_schema.union_schema(
[
core_schema.int_schema(),
core_schema.float_schema(serialization=core_schema.format_ser_schema('0.0f')),
]
),
core_schema.int_schema(),
)
)
assert s.to_python({1: 2, 2.111: 3}) == {1: 2, 2.111: 3}
assert s.to_python({1: 2, 2.111: 3}, mode='json') == {'1': 2, '2': 3}
assert s.to_json({1: 2, 2.111: 3}) == b'{"1":2,"2":3}'
def test_union_of_functions():
def repr_function(value, _info):
if value == 'unexpected':
raise PydanticSerializationUnexpectedValue()
return f'func: {value!r}'
s = SchemaSerializer(
core_schema.union_schema(
[
core_schema.any_schema(
serialization=core_schema.plain_serializer_function_ser_schema(repr_function, info_arg=True)
),
core_schema.float_schema(serialization=core_schema.format_ser_schema('_^14')),
]
)
)
assert s.to_python('foobar') == "func: 'foobar'"
assert s.to_python('foobar', mode='json') == "func: 'foobar'"
assert s.to_json('foobar') == b'"func: \'foobar\'"'
assert s.to_python('unexpected') == 'unexpected'
assert s.to_python('unexpected', mode='json') == '__unexpected__'
assert s.to_json('unexpected') == b'"__unexpected__"'
def test_typed_dict_literal():
s = SchemaSerializer(
core_schema.union_schema(
[
core_schema.typed_dict_schema(
dict(
pet_type=core_schema.typed_dict_field(core_schema.literal_schema(['cat'])),
sound=core_schema.typed_dict_field(
core_schema.int_schema(serialization=core_schema.format_ser_schema('04d'))
),
)
),
core_schema.typed_dict_schema(
dict(
pet_type=core_schema.typed_dict_field(core_schema.literal_schema(['dog'])),
sound=core_schema.typed_dict_field(
core_schema.float_schema(serialization=core_schema.format_ser_schema('0.3f'))
),
)
),
]
)
)
assert s.to_python(dict(pet_type='cat', sound=3), mode='json') == {'pet_type': 'cat', 'sound': '0003'}
assert s.to_python(dict(pet_type='dog', sound=3), mode='json') == {'pet_type': 'dog', 'sound': '3.000'}
def test_typed_dict_missing():
s = SchemaSerializer(
core_schema.union_schema(
[
core_schema.typed_dict_schema(dict(foo=core_schema.typed_dict_field(core_schema.int_schema()))),
core_schema.typed_dict_schema(
dict(
foo=core_schema.typed_dict_field(
core_schema.int_schema(
serialization=core_schema.format_ser_schema('04d', when_used='always')
)
),
bar=core_schema.typed_dict_field(core_schema.int_schema()),
)
),
]
)
)
assert s.to_python(dict(foo=1)) == {'foo': 1}
assert s.to_python(dict(foo=1), mode='json') == {'foo': 1}
assert s.to_json(dict(foo=1)) == b'{"foo":1}'
assert s.to_python(dict(foo=1, bar=2)) == {'foo': '0001', 'bar': 2}
assert s.to_python(dict(foo=1, bar=2), mode='json') == {'foo': '0001', 'bar': 2}
assert s.to_json(dict(foo=1, bar=2)) == b'{"foo":"0001","bar":2}'
def test_typed_dict_extra():
"""
TODO, needs tests for each case
"""
s = SchemaSerializer(
core_schema.union_schema(
[
core_schema.typed_dict_schema(
dict(
foo=core_schema.typed_dict_field(core_schema.int_schema()),
bar=core_schema.typed_dict_field(core_schema.int_schema()),
)
),
core_schema.typed_dict_schema(
dict(
foo=core_schema.typed_dict_field(
core_schema.int_schema(serialization=core_schema.format_ser_schema('04d'))
)
)
),
]
)
)
assert s.to_python(dict(foo=1, bar=2)) == {'foo': 1, 'bar': 2}
assert s.to_python(dict(foo=1, bar=2), mode='json') == {'foo': 1, 'bar': 2}
assert s.to_json(dict(foo=1, bar=2)) == b'{"foo":1,"bar":2}'
assert s.to_python(dict(foo=1)) == {'foo': 1}
assert s.to_python(dict(foo=1), mode='json') == {'foo': '0001'}
assert s.to_json(dict(foo=1)) == b'{"foo":"0001"}'
def test_typed_dict_different_fields():
"""
TODO, needs tests for each case
"""
s = SchemaSerializer(
core_schema.union_schema(
[
core_schema.typed_dict_schema(
dict(
foo=core_schema.typed_dict_field(core_schema.int_schema()),
bar=core_schema.typed_dict_field(core_schema.int_schema()),
)
),
core_schema.typed_dict_schema(
dict(
spam=core_schema.typed_dict_field(core_schema.int_schema()),
ham=core_schema.typed_dict_field(
core_schema.int_schema(serialization=core_schema.format_ser_schema('04d'))
),
)
),
]
)
)
assert s.to_python(dict(foo=1, bar=2)) == {'foo': 1, 'bar': 2}
assert s.to_python(dict(foo=1, bar=2), mode='json') == {'foo': 1, 'bar': 2}
assert s.to_json(dict(foo=1, bar=2)) == b'{"foo":1,"bar":2}'
assert s.to_python(dict(spam=1, ham=2)) == {'spam': 1, 'ham': 2}
assert s.to_python(dict(spam=1, ham=2), mode='json') == {'spam': 1, 'ham': '0002'}
assert s.to_json(dict(spam=1, ham=2)) == b'{"spam":1,"ham":"0002"}'
def test_dataclass_union():
@dataclasses.dataclass
class BaseUser:
name: str
@dataclasses.dataclass
class User(BaseUser):
surname: str
@dataclasses.dataclass
class DBUser(User):
password_hash: str
@dataclasses.dataclass
class Item:
name: str
price: float
user_schema = core_schema.dataclass_schema(
User,
core_schema.dataclass_args_schema(
'User',
[
core_schema.dataclass_field(name='name', schema=core_schema.str_schema()),
core_schema.dataclass_field(name='surname', schema=core_schema.str_schema()),
],
),
['name', 'surname'],
)
item_schema = core_schema.dataclass_schema(
Item,
core_schema.dataclass_args_schema(
'Item',
[
core_schema.dataclass_field(name='name', schema=core_schema.str_schema()),
core_schema.dataclass_field(name='price', schema=core_schema.float_schema()),
],
),
['name', 'price'],
)
s = SchemaSerializer(core_schema.union_schema([user_schema, item_schema]))
assert s.to_python(User(name='foo', surname='bar')) == {'name': 'foo', 'surname': 'bar'}
assert s.to_python(DBUser(name='foo', surname='bar', password_hash='x')) == {'name': 'foo', 'surname': 'bar'}
assert s.to_json(DBUser(name='foo', surname='bar', password_hash='x')) == b'{"name":"foo","surname":"bar"}'
def test_model_union():
class BaseUser:
def __init__(self, name: str):
self.name = name
class User(BaseUser):
def __init__(self, name: str, surname: str):
super().__init__(name)
self.surname = surname
class DBUser(User):
def __init__(self, name: str, surname: str, password_hash: str):
super().__init__(name, surname)
self.password_hash = password_hash
class Item:
def __init__(self, name: str, price: float):
self.name = name
self.price = price
user_schema = core_schema.model_schema(
User,
core_schema.model_fields_schema(
{
'name': core_schema.model_field(schema=core_schema.str_schema()),
'surname': core_schema.model_field(schema=core_schema.str_schema()),
}
),
)
item_schema = core_schema.model_schema(
Item,
core_schema.model_fields_schema(
{
'name': core_schema.model_field(schema=core_schema.str_schema()),
'price': core_schema.model_field(schema=core_schema.float_schema()),
}
),
)
s = SchemaSerializer(core_schema.union_schema([user_schema, item_schema]))
assert s.to_python(User(name='foo', surname='bar')) == {'name': 'foo', 'surname': 'bar'}
assert s.to_python(DBUser(name='foo', surname='bar', password_hash='x')) == {'name': 'foo', 'surname': 'bar'}
assert s.to_json(DBUser(name='foo', surname='bar', password_hash='x')) == b'{"name":"foo","surname":"bar"}'
@pytest.mark.parametrize(('data', 'json_value'), [(False, 'false'), ('abc', '"abc"')])
def test_union_literal_with_other_type(data, json_value):
class Model(BaseModel):
value: Union[Literal[False], str]
value_types_reversed: Union[str, Literal[False]]
s = SchemaSerializer(
core_schema.model_schema(
Model,
core_schema.model_fields_schema(
{
'value': core_schema.model_field(
core_schema.union_schema([core_schema.literal_schema([False]), core_schema.str_schema()])
),
'value_types_reversed': core_schema.model_field(
core_schema.union_schema([core_schema.str_schema(), core_schema.literal_schema([False])])
),
}
),
)
)
m = Model(value=data, value_types_reversed=data)
assert s.to_python(m) == {'value': data, 'value_types_reversed': data}
assert s.to_json(m) == f'{{"value":{json_value},"value_types_reversed":{json_value}}}'.encode()
def test_union_serializes_model_subclass_from_definition() -> None:
class BaseModel:
__slots__ = '__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__'
def __init__(self, **kwargs: Any):
for key, value in kwargs.items():
setattr(self, key, value)
class User(BaseModel):
name: str
class DBUser(User):
password: str
__pydantic_serializer__: ClassVar[SchemaSerializer]
DBUser.__pydantic_serializer__ = SchemaSerializer(
core_schema.model_schema(
DBUser,
core_schema.model_fields_schema(
{
'name': core_schema.model_field(core_schema.str_schema()),
'password': core_schema.model_field(core_schema.str_schema()),
}
),
)
)
class Item(BaseModel):
price: float
s = SchemaSerializer(
core_schema.definitions_schema(
core_schema.union_schema(
[core_schema.definition_reference_schema('User'), core_schema.definition_reference_schema('Item')]
),
[
core_schema.model_schema(
User,
core_schema.model_fields_schema({'name': core_schema.model_field(core_schema.str_schema())}),
ref='User',
),
core_schema.model_schema(
Item,
core_schema.model_fields_schema({'price': core_schema.model_field(core_schema.float_schema())}),
ref='Item',
),
],
)
)
assert s.to_python(DBUser(name='John', password='secret')) == {'name': 'John'}
def test_union_serializes_list_of_model_subclass_from_definition() -> None:
class BaseModel:
__slots__ = '__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__'
def __init__(self, **kwargs: Any):
for key, value in kwargs.items():
setattr(self, key, value)
class User(BaseModel):
name: str
class DBUser(User):
password: str
__pydantic_serializer__: ClassVar[SchemaSerializer]
DBUser.__pydantic_serializer__ = SchemaSerializer(
core_schema.model_schema(
DBUser,
core_schema.model_fields_schema(
{
'name': core_schema.model_field(core_schema.str_schema()),
'password': core_schema.model_field(core_schema.str_schema()),
}
),
)
)
class Item(BaseModel):
price: float
s = SchemaSerializer(
core_schema.definitions_schema(
core_schema.union_schema(
[
core_schema.list_schema(core_schema.definition_reference_schema('User'), strict=False),
core_schema.list_schema(core_schema.definition_reference_schema('Item'), strict=False),
]
),
[
core_schema.model_schema(
User,
core_schema.model_fields_schema({'name': core_schema.model_field(core_schema.str_schema())}),
ref='User',
),
core_schema.model_schema(
Item,
core_schema.model_fields_schema({'price': core_schema.model_field(core_schema.float_schema())}),
ref='Item',
),
],
)
)
assert s.to_python([DBUser(name='John', password='secret')]) == [{'name': 'John'}]
EXAMPLE_UUID = uuid.uuid4()
| SubclassB |
python | django-compressor__django-compressor | compressor/filters/css_default.py | {
"start": 4502,
"end": 6010
} | class ____(CssAbsoluteFilter):
"""
Do similar to ``CssAbsoluteFilter`` URL processing
but add a *relative URL prefix* instead of ``settings.COMPRESS_URL``.
"""
run_with_compression_disabled = True
def post_process_url(self, url):
"""
Replace ``settings.COMPRESS_URL`` URL prefix with '../' * (N + 1)
where N is the *depth* of ``settings.COMPRESS_OUTPUT_DIR`` folder.
E.g. by default ``settings.COMPRESS_OUTPUT_DIR == 'CACHE'``,
the depth is 1, and the prefix will be '../../'.
If ``settings.COMPRESS_OUTPUT_DIR == 'my/compiled/data'``,
the depth is 3, and the prefix will be '../../../../'.
Example:
- original file URL: '/static/my-app/style.css'
- it has an image link: ``url(images/logo.svg)``
- compiled file URL: '/static/CACHE/css/output.abcdef123456.css'
- replaced image link URL: ``url(../../my-app/images/logo.svg)``
"""
old_prefix = self.url
if self.has_scheme:
old_prefix = "{}{}".format(self.protocol, old_prefix)
# One level up from 'css' / 'js' folder
new_prefix = ".."
# N levels up from ``settings.COMPRESS_OUTPUT_DIR``
new_prefix += "/.." * len(
list(
filter(
None, os.path.normpath(settings.COMPRESS_OUTPUT_DIR).split(os.sep)
)
)
)
return re.sub("^{}".format(old_prefix), new_prefix, url)
| CssRelativeFilter |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-azure-cv/llama_index/tools/azure_cv/base.py | {
"start": 258,
"end": 1694
} | class ____(BaseToolSpec):
"""Azure Cognitive Vision tool spec."""
spec_functions = ["process_image"]
def __init__(
self,
resource: str,
api_key: str,
language: Optional[str] = "en",
api_version: Optional[str] = "2023-04-01-preview",
) -> None:
"""Initialize with parameters."""
self.api_key = api_key
self.cv_url = CV_URL_TMPL.format(resource=resource)
self.language = language
self.api_version = api_version
def process_image(self, url: str, features: List[str]):
"""
This tool accepts an image url or file and can process and return a variety of text depending on the use case.
You can use the features argument to configure what text you want returned.
Args:
url (str): The url for the image to caption
features (List[str]): Instructions on how to process the image. Valid keys are tags, objects, read, caption
"""
response = requests.post(
f"{self.cv_url}?features={','.join(features)}&language={self.language}&api-version={self.api_version}",
headers={"Ocp-Apim-Subscription-Key": self.api_key},
json={"url": url},
)
response_json = response.json()
if "read" in features:
response_json["readResult"] = response_json["readResult"]["content"]
return response_json
| AzureCVToolSpec |
python | huggingface__transformers | src/transformers/models/internvl/modular_internvl.py | {
"start": 17456,
"end": 24137
} | class ____(LlavaModel):
def pixel_shuffle(self, vision_features: torch.Tensor, scale_factor: float = 0.5):
"""Perform pixel shuffle downsampling on vision features.
Args:
vision_features (`torch.Tensor`):
Input tensor of shape (batch_size, width, height, channels).
scale_factor (`float`, *optional*, defaults to `0.5`):
Factor by which to downsample. Default is 0.5, which halves the dimensions.
Returns:
vision_features (`torch.Tensor`):
Downsampled tensor of shape (batch_size, height*scale_factor, width*scale_factor, channels/(scale_factor^2)).
"""
batch_size, width, height, channels = vision_features.size()
if height % scale_factor != 0 or width % scale_factor != 0:
raise ValueError("Height and width must be divisible by scale_factor for proper downsampling.")
# Reshape to allow downsampling
vision_features = vision_features.view(
batch_size, width, int(height * scale_factor), int(channels / scale_factor)
)
# Permute dimensions to align downsampled axis correctly
vision_features = vision_features.permute(0, 2, 1, 3).contiguous()
# Reshape to achieve final downsampled dimensions
vision_features = vision_features.view(
batch_size, int(height * scale_factor), int(width * scale_factor), int(channels / (scale_factor**2))
)
# Swap height and width back for proper orientation
vision_features = vision_features.permute(0, 2, 1, 3).contiguous()
return vision_features
def get_image_features(
self,
pixel_values: torch.FloatTensor,
vision_feature_layer: Optional[Union[int, list[int]]] = None,
vision_feature_select_strategy: Optional[str] = None,
**kwargs,
):
"""
Obtains image last hidden states from the vision tower and apply multimodal projection.
Args:
pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
The tensors corresponding to the input images.
vision_feature_layer (`int` or `list[int]`):
Layer index or list of layer indices to extract features from.
Returns:
vision_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`.
"""
vision_feature_layer = (
vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
)
vision_feature_select_strategy = (
vision_feature_select_strategy
if vision_feature_select_strategy is not None
else self.config.vision_feature_select_strategy
)
pixel_values = pixel_values.to(dtype=self.dtype) # fp16 compatibility
downsample_ratio = self.config.downsample_ratio
if vision_feature_layer == -1:
vision_features = self.vision_tower(pixel_values=pixel_values).last_hidden_state
else:
vision_features = self.vision_model(pixel_values=pixel_values).hidden_states[vision_feature_layer]
if vision_feature_select_strategy == "default":
vision_features = vision_features[:, 1:, :]
# Calculate dimensions based on vision features
channels = vision_features.shape[1]
feature_size = int(channels**0.5)
batch_size = vision_features.shape[0]
# Reshape tensor to spatial dimensions
vision_features = vision_features.reshape(batch_size, feature_size, feature_size, -1)
# Apply downsampling using pixel shuffle
vision_features = self.pixel_shuffle(vision_features, scale_factor=downsample_ratio)
# Reshape tensor to prepare for projection
vision_features = vision_features.reshape(batch_size, -1, vision_features.shape[-1])
# Project features through multi-modal projector
vision_features = self.multi_modal_projector(vision_features)
return vision_features
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
pixel_values: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
vision_feature_layer: Optional[Union[int, list[int]]] = None,
vision_feature_select_strategy: Optional[str] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> Union[tuple, InternVLModelOutputWithPast]:
vision_feature_layer = (
vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
)
vision_feature_select_strategy = (
vision_feature_select_strategy
if vision_feature_select_strategy is not None
else self.config.vision_feature_select_strategy
)
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if inputs_embeds is None:
inputs_embeds = self.get_input_embeddings()(input_ids)
if pixel_values is not None:
image_features = self.get_image_features(
pixel_values=pixel_values,
vision_feature_layer=vision_feature_layer,
vision_feature_select_strategy=vision_feature_select_strategy,
)
image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
special_image_mask = self.get_placeholder_mask(
input_ids, inputs_embeds=inputs_embeds, image_features=image_features
)
inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
outputs = self.language_model(
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
cache_position=cache_position,
**kwargs,
)
return InternVLModelOutputWithPast(
last_hidden_state=outputs.last_hidden_state,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
image_hidden_states=image_features if pixel_values is not None else None,
)
| InternVLModel |
python | django__django | tests/staticfiles_tests/test_finders.py | {
"start": 1926,
"end": 2600
} | class ____(TestFinders, StaticFilesTestCase):
"""
Test DefaultStorageFinder.
"""
def setUp(self):
super().setUp()
self.finder = finders.DefaultStorageFinder(
storage=storage.StaticFilesStorage(location=settings.MEDIA_ROOT)
)
test_file_path = os.path.join(settings.MEDIA_ROOT, "media-file.txt")
self.find_first = ("media-file.txt", test_file_path)
self.find_all = ("media-file.txt", [test_file_path])
@override_settings(
STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"],
STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "documents")],
)
| TestDefaultStorageFinder |
python | pyparsing__pyparsing | pyparsing/testing.py | {
"start": 200,
"end": 15260
} | class ____:
"""
namespace class for classes useful in writing unit tests
"""
class reset_pyparsing_context:
"""
Context manager to be used when writing unit tests that modify pyparsing config values:
- packrat parsing
- bounded recursion parsing
- default whitespace characters
- default keyword characters
- literal string auto-conversion class
- ``__diag__`` settings
Example:
.. testcode::
ppt = pyparsing.pyparsing_test
class MyTestClass(ppt.TestParseResultsAsserts):
def test_literal(self):
with ppt.reset_pyparsing_context():
# test that literals used to construct
# a grammar are automatically suppressed
ParserElement.inline_literals_using(Suppress)
term = Word(alphas) | Word(nums)
group = Group('(' + term[...] + ')')
# assert that the '()' characters
# are not included in the parsed tokens
self.assertParseAndCheckList(
group,
"(abc 123 def)",
['abc', '123', 'def']
)
# after exiting context manager, literals
# are converted to Literal expressions again
"""
def __init__(self):
self._save_context = {}
def save(self):
self._save_context["default_whitespace"] = ParserElement.DEFAULT_WHITE_CHARS
self._save_context["default_keyword_chars"] = Keyword.DEFAULT_KEYWORD_CHARS
self._save_context["literal_string_class"] = (
ParserElement._literalStringClass
)
self._save_context["verbose_stacktrace"] = ParserElement.verbose_stacktrace
self._save_context["packrat_enabled"] = ParserElement._packratEnabled
if ParserElement._packratEnabled:
self._save_context["packrat_cache_size"] = (
ParserElement.packrat_cache.size
)
else:
self._save_context["packrat_cache_size"] = None
self._save_context["packrat_parse"] = ParserElement._parse
self._save_context["recursion_enabled"] = (
ParserElement._left_recursion_enabled
)
self._save_context["__diag__"] = {
name: getattr(__diag__, name) for name in __diag__._all_names
}
self._save_context["__compat__"] = {
"collect_all_And_tokens": __compat__.collect_all_And_tokens
}
return self
def restore(self):
# reset pyparsing global state
if (
ParserElement.DEFAULT_WHITE_CHARS
!= self._save_context["default_whitespace"]
):
ParserElement.set_default_whitespace_chars(
self._save_context["default_whitespace"]
)
ParserElement.verbose_stacktrace = self._save_context["verbose_stacktrace"]
Keyword.DEFAULT_KEYWORD_CHARS = self._save_context["default_keyword_chars"]
ParserElement.inline_literals_using(
self._save_context["literal_string_class"]
)
for name, value in self._save_context["__diag__"].items():
(__diag__.enable if value else __diag__.disable)(name)
ParserElement._packratEnabled = False
if self._save_context["packrat_enabled"]:
ParserElement.enable_packrat(self._save_context["packrat_cache_size"])
else:
ParserElement._parse = self._save_context["packrat_parse"]
ParserElement._left_recursion_enabled = self._save_context[
"recursion_enabled"
]
__compat__.collect_all_And_tokens = self._save_context["__compat__"]
return self
def copy(self):
ret = type(self)()
ret._save_context.update(self._save_context)
return ret
def __enter__(self):
return self.save()
def __exit__(self, *args):
self.restore()
class TestParseResultsAsserts(unittest.TestCase):
"""
A mixin class to add parse results assertion methods to normal unittest.TestCase classes.
"""
def assertParseResultsEquals(
self, result, expected_list=None, expected_dict=None, msg=None
):
"""
Unit test assertion to compare a :class:`ParseResults` object with an optional ``expected_list``,
and compare any defined results names with an optional ``expected_dict``.
"""
if expected_list is not None:
self.assertEqual(expected_list, result.as_list(), msg=msg)
if expected_dict is not None:
self.assertEqual(expected_dict, result.as_dict(), msg=msg)
def assertParseAndCheckList(
self, expr, test_string, expected_list, msg=None, verbose=True
):
"""
Convenience wrapper assert to test a parser element and input string, and assert that
the resulting :meth:`ParseResults.as_list` is equal to the ``expected_list``.
"""
result = expr.parse_string(test_string, parse_all=True)
if verbose:
print(result.dump())
else:
print(result.as_list())
self.assertParseResultsEquals(result, expected_list=expected_list, msg=msg)
def assertParseAndCheckDict(
self, expr, test_string, expected_dict, msg=None, verbose=True
):
"""
Convenience wrapper assert to test a parser element and input string, and assert that
the resulting :meth:`ParseResults.as_dict` is equal to the ``expected_dict``.
"""
result = expr.parse_string(test_string, parse_all=True)
if verbose:
print(result.dump())
else:
print(result.as_list())
self.assertParseResultsEquals(result, expected_dict=expected_dict, msg=msg)
def assertRunTestResults(
self, run_tests_report, expected_parse_results=None, msg=None
):
"""
Unit test assertion to evaluate output of
:meth:`~ParserElement.run_tests`.
If a list of list-dict tuples is given as the
``expected_parse_results`` argument, then these are zipped
with the report tuples returned by ``run_tests()``
and evaluated using :meth:`assertParseResultsEquals`.
Finally, asserts that the overall
`:meth:~ParserElement.run_tests` success value is ``True``.
:param run_tests_report: the return value from :meth:`ParserElement.run_tests`
:type run_tests_report: tuple[bool, list[tuple[str, ParseResults | Exception]]]
:param expected_parse_results: (optional)
:type expected_parse_results: list[tuple[str | list | dict | Exception, ...]]
"""
run_test_success, run_test_results = run_tests_report
if expected_parse_results is None:
self.assertTrue(
run_test_success, msg=msg if msg is not None else "failed runTests"
)
return
merged = [
(*rpt, expected)
for rpt, expected in zip(run_test_results, expected_parse_results)
]
for test_string, result, expected in merged:
# expected should be a tuple containing a list and/or a dict or an exception,
# and optional failure message string
# an empty tuple will skip any result validation
fail_msg = next((exp for exp in expected if isinstance(exp, str)), None)
expected_exception = next(
(
exp
for exp in expected
if isinstance(exp, type) and issubclass(exp, Exception)
),
None,
)
if expected_exception is not None:
with self.assertRaises(
expected_exception=expected_exception, msg=fail_msg or msg
):
if isinstance(result, Exception):
raise result
else:
expected_list = next(
(exp for exp in expected if isinstance(exp, list)), None
)
expected_dict = next(
(exp for exp in expected if isinstance(exp, dict)), None
)
if (expected_list, expected_dict) != (None, None):
self.assertParseResultsEquals(
result,
expected_list=expected_list,
expected_dict=expected_dict,
msg=fail_msg or msg,
)
else:
# warning here maybe?
print(f"no validation for {test_string!r}")
# do this last, in case some specific test results can be reported instead
self.assertTrue(
run_test_success, msg=msg if msg is not None else "failed runTests"
)
@contextmanager
def assertRaisesParseException(
self, exc_type=ParseException, expected_msg=None, msg=None
):
if expected_msg is not None:
if isinstance(expected_msg, str):
expected_msg = re.escape(expected_msg)
with self.assertRaisesRegex(exc_type, expected_msg, msg=msg) as ctx:
yield ctx
else:
with self.assertRaises(exc_type, msg=msg) as ctx:
yield ctx
@staticmethod
def with_line_numbers(
s: str,
start_line: typing.Optional[int] = None,
end_line: typing.Optional[int] = None,
expand_tabs: bool = True,
eol_mark: str = "|",
mark_spaces: typing.Optional[str] = None,
mark_control: typing.Optional[str] = None,
*,
indent: typing.Union[str, int] = "",
base_1: bool = True,
) -> str:
"""
Helpful method for debugging a parser - prints a string with line and column numbers.
(Line and column numbers are 1-based by default - if debugging a parse action,
pass base_1=False, to correspond to the loc value passed to the parse action.)
:param s: string to be printed with line and column numbers
:param start_line: starting line number in s to print (default=1)
:param end_line: ending line number in s to print (default=len(s))
:param expand_tabs: expand tabs to spaces, to match the pyparsing default
:param eol_mark: string to mark the end of lines, helps visualize trailing spaces
:param mark_spaces: special character to display in place of spaces
:param mark_control: convert non-printing control characters to a placeholding
character; valid values:
- ``"unicode"`` - replaces control chars with Unicode symbols, such as "␍" and "␊"
- any single character string - replace control characters with given string
- ``None`` (default) - string is displayed as-is
:param indent: string to indent with line and column numbers; if an int
is passed, converted to ``" " * indent``
:param base_1: whether to label string using base 1; if False, string will be
labeled based at 0
:returns: input string with leading line numbers and column number headers
.. versionchanged:: 3.2.0
New ``indent`` and ``base_1`` arguments.
"""
if expand_tabs:
s = s.expandtabs()
if isinstance(indent, int):
indent = " " * indent
indent = indent.expandtabs()
if mark_control is not None:
mark_control = typing.cast(str, mark_control)
if mark_control == "unicode":
transtable_map = {
c: u for c, u in zip(range(0, 33), range(0x2400, 0x2433))
}
transtable_map[127] = 0x2421
tbl = str.maketrans(transtable_map)
eol_mark = ""
else:
ord_mark_control = ord(mark_control)
tbl = str.maketrans(
{c: ord_mark_control for c in list(range(0, 32)) + [127]}
)
s = s.translate(tbl)
if mark_spaces is not None and mark_spaces != " ":
if mark_spaces == "unicode":
tbl = str.maketrans({9: 0x2409, 32: 0x2423})
s = s.translate(tbl)
else:
s = s.replace(" ", mark_spaces)
if start_line is None:
start_line = 0
if end_line is None:
end_line = len(s.splitlines())
end_line = min(end_line, len(s.splitlines()))
start_line = min(max(0, start_line), end_line)
if mark_control != "unicode":
s_lines = s.splitlines()[max(start_line - base_1, 0) : end_line]
else:
s_lines = [
line + "␊" for line in s.split("␊")[max(start_line - base_1, 0) : end_line]
]
if not s_lines:
return ""
lineno_width = len(str(end_line))
max_line_len = max(len(line) for line in s_lines)
lead = indent + " " * (lineno_width + 1)
if max_line_len >= 99:
header0 = (
lead
+ ("" if base_1 else " ")
+ "".join(
f"{' ' * 99}{(i + 1) % 100}"
for i in range(max(max_line_len // 100, 1))
)
+ "\n"
)
else:
header0 = ""
header1 = (
("" if base_1 else " ")
+ lead
+ "".join(f" {(i + 1) % 10}" for i in range(-(-max_line_len // 10)))
+ "\n"
)
digits = "1234567890"
header2 = (
lead + ("" if base_1 else "0") + digits * (-(-max_line_len // 10)) + "\n"
)
return (
header0
+ header1
+ header2
+ "\n".join(
f"{indent}{i:{lineno_width}d}:{line}{eol_mark}"
for i, line in enumerate(s_lines, start=start_line + base_1)
)
+ "\n"
)
| pyparsing_test |
python | vyperlang__vyper | vyper/venom/passes/machinery/inst_updater.py | {
"start": 255,
"end": 4877
} | class ____:
"""
A helper class for updating instructions which also updates the
basic block and dfg in place
"""
def __init__(self, dfg: DFGAnalysis):
self.dfg = dfg
def update_operands(
self, inst: IRInstruction, replace_dict: dict[IROperand, IROperand], annotation: str = ""
):
old_operands = inst.operands
new_operands = [replace_dict[op] if op in replace_dict else op for op in old_operands]
self.update(inst, inst.opcode, new_operands, annotation=annotation)
# move the uses of old_var to new_inst
def move_uses(self, old_var: IRVariable, new_inst: IRInstruction):
new_var = new_inst.output
for use in list(self.dfg.get_uses(old_var)):
self.update_operands(use, {old_var: new_var})
def update(
self,
inst: IRInstruction,
opcode: str,
new_operands: list[IROperand],
new_output: Optional[IRVariable] = None,
annotation: str = "",
) -> IRInstruction:
# sanity
assert all(isinstance(op, IROperand) for op in new_operands)
original_str = str(inst)
old_operands = inst.operands
for op in old_operands:
if not isinstance(op, IRVariable):
continue
uses = self.dfg.get_uses(op)
uses.discard(inst)
for op in new_operands:
if isinstance(op, IRVariable):
self.dfg.add_use(op, inst)
old_outputs = inst.get_outputs()
if opcode in NO_OUTPUT_INSTRUCTIONS:
for output in old_outputs:
assert new_output is None
assert len(uses := self.dfg.get_uses(output)) == 0, (inst, uses)
self.dfg.remove_producing_instruction(output)
inst.set_outputs([])
else:
# new_output is None is sentinel meaning "no change"
if new_output is not None:
# multi-output instructions are not currently updated this way
assert len(old_outputs) <= 1
old_primary = old_outputs[0] if len(old_outputs) > 0 else None
if old_primary is not None and old_primary != new_output:
self.dfg.remove_producing_instruction(old_primary)
self.dfg.set_producing_instruction(new_output, inst)
inst.set_outputs([new_output])
inst.opcode = opcode
inst.operands = new_operands
if annotation:
inst.annotation = original_str + " " + annotation
return inst
def nop(self, inst: IRInstruction, annotation: str = ""):
self.update(inst, "nop", [], annotation=annotation)
def nop_multi(self, to_nop: Iterable[IRInstruction]):
q = deque(to_nop)
bound = (2 + len(q)) ** 2 # set bound to at least 2**2
for _ in range(bound): # bounded `while True`
if len(q) == 0:
return
# NOTE: this doesn't work for dfg cycles.
inst = q.popleft()
# Check if ANY output has uses
outputs = inst.get_outputs()
has_uses = any(len(self.dfg.get_uses(output)) > 0 for output in outputs)
if has_uses:
q.append(inst)
else:
self.nop(inst)
# this should only happen if we try to delete a dfg cycle, cross
# that bridge when we get to it.
raise CompilerPanic("infinite loop") # pragma: nocover
def remove(self, inst: IRInstruction):
self.nop(inst) # for dfg updates and checks
inst.parent.remove_instruction(inst)
def mk_assign(
self, inst: IRInstruction, op: IROperand, new_output: Optional[IRVariable] = None
):
self.update(inst, "assign", [op], new_output=new_output)
def add_before(
self, inst: IRInstruction, opcode: str, args: list[IROperand]
) -> Optional[IRVariable]:
"""
Insert another instruction before the given instruction
"""
index = inst.parent.instructions.index(inst)
var = None
if opcode not in NO_OUTPUT_INSTRUCTIONS:
var = inst.parent.parent.get_next_variable()
operands = list(args)
new_inst = IRInstruction(opcode, operands, [var] if var is not None else None)
inst.parent.insert_instruction(new_inst, index)
for op in new_inst.operands:
if isinstance(op, IRVariable):
self.dfg.add_use(op, new_inst)
if var is not None:
self.dfg.set_producing_instruction(var, new_inst)
return var
| InstUpdater |
python | tornadoweb__tornado | tornado/websocket.py | {
"start": 27760,
"end": 29029
} | class ____:
def __init__(
self,
persistent: bool,
max_wbits: Optional[int],
max_message_size: int,
compression_options: Optional[Dict[str, Any]] = None,
) -> None:
self._max_message_size = max_message_size
if max_wbits is None:
max_wbits = zlib.MAX_WBITS
if not (8 <= max_wbits <= zlib.MAX_WBITS):
raise ValueError(
"Invalid max_wbits value %r; allowed range 8-%d",
max_wbits,
zlib.MAX_WBITS,
)
self._max_wbits = max_wbits
if persistent:
self._decompressor = (
self._create_decompressor()
) # type: Optional[_Decompressor]
else:
self._decompressor = None
def _create_decompressor(self) -> "_Decompressor":
return zlib.decompressobj(-self._max_wbits)
def decompress(self, data: bytes) -> bytes:
decompressor = self._decompressor or self._create_decompressor()
result = decompressor.decompress(
data + b"\x00\x00\xff\xff", self._max_message_size
)
if decompressor.unconsumed_tail:
raise _DecompressTooLargeError()
return result
| _PerMessageDeflateDecompressor |
python | pyparsing__pyparsing | examples/test_bibparse.py | {
"start": 149,
"end": 9006
} | class ____(unittest.TestCase):
def test_names(self):
# check various types of names
# All names can contains alphas, but not some special chars
bad_chars = "\"#%'(),={}"
for name_type, dig1f in (
(bp.macro_def, False),
(bp.field_name, False),
(bp.entry_type, False),
(bp.cite_key, True),
):
if dig1f: # can start with digit
self.assertEqual("2t", name_type.parse_string("2t")[0])
else:
self.assertRaises(ParseException, name_type.parse_string, "2t")
# All of the names cannot contain some characters
for char in bad_chars:
self.assertRaises(ParseException, name_type.parse_string, char)
# standard strings all OK
self.assertEqual("simple_test", name_type.parse_string("simple_test")[0])
# Test macro ref
mr = bp.macro_ref
# can't start with digit
self.assertRaises(ParseException, mr.parse_string, "2t")
for char in bad_chars:
self.assertRaises(ParseException, mr.parse_string, char)
self.assertEqual("simple_test", mr.parse_string("simple_test")[0].name)
def test_numbers(self):
self.assertEqual("1066", bp.number.parse_string("1066")[0])
self.assertEqual("0", bp.number.parse_string("0")[0])
self.assertRaises(ParseException, bp.number.parse_string, "-4")
self.assertRaises(ParseException, bp.number.parse_string, "+4")
self.assertRaises(ParseException, bp.number.parse_string, ".4")
# something point something leaves a trailing .4 unmatched
self.assertEqual("0", bp.number.parse_string("0.4")[0])
def test_parse_string(self):
# test string building blocks
self.assertEqual(bp.chars_no_quotecurly.parse_string("x")[0], "x")
self.assertEqual(bp.chars_no_quotecurly.parse_string("a string")[0], "a string")
self.assertEqual(bp.chars_no_quotecurly.parse_string('a "string')[0], "a ")
self.assertEqual(bp.chars_no_curly.parse_string("x")[0], "x")
self.assertEqual(bp.chars_no_curly.parse_string("a string")[0], "a string")
self.assertEqual(bp.chars_no_curly.parse_string("a {string")[0], "a ")
self.assertEqual(bp.chars_no_curly.parse_string("a }string")[0], "a ")
# test more general strings together
for obj in (bp.curly_string, bp.string, bp.field_value):
self.assertEqual(obj.parse_string("{}").as_list(), [])
self.assertEqual(obj.parse_string('{a "string}')[0], 'a "string')
self.assertEqual(
["a ", ["nested"], " string"],
obj.parse_string("{a {nested} string}").as_list(),
)
self.assertEqual(
["a ", ["double ", ["nested"]], " string"],
obj.parse_string("{a {double {nested}} string}").as_list(),
)
for obj in (bp.quoted_string, bp.string, bp.field_value):
self.assertEqual([], obj.parse_string('""').as_list())
self.assertEqual("a string", obj.parse_string('"a string"')[0])
self.assertEqual(
["a ", ["nested"], " string"],
obj.parse_string('"a {nested} string"').as_list(),
)
self.assertEqual(
["a ", ["double ", ["nested"]], " string"],
obj.parse_string('"a {double {nested}} string"').as_list(),
)
# check macro def in string
self.assertEqual(Macro("someascii"), bp.string.parse_string("someascii")[0])
self.assertRaises(ParseException, bp.string.parse_string, "%#= validstring")
# check number in string
self.assertEqual(bp.string.parse_string("1994")[0], "1994")
def test_parse_field(self):
# test field value - hashes included
fv = bp.field_value
# Macro
self.assertEqual(Macro("aname"), fv.parse_string("aname")[0])
self.assertEqual(Macro("aname"), fv.parse_string("ANAME")[0])
# String and macro
self.assertEqual(
[Macro("aname"), "some string"],
fv.parse_string('aname # "some string"').as_list(),
)
# Nested string
self.assertEqual(
[Macro("aname"), "some ", ["string"]],
fv.parse_string("aname # {some {string}}").as_list(),
)
# String and number
self.assertEqual(
["a string", "1994"], fv.parse_string('"a string" # 1994').as_list()
)
# String and number and macro
self.assertEqual(
["a string", "1994", Macro("a_macro")],
fv.parse_string('"a string" # 1994 # a_macro').as_list(),
)
def test_comments(self):
res = bp.comment.parse_string("@Comment{about something}")
self.assertEqual(res.as_list(), ["comment", "{about something}"])
self.assertEqual(
["comment", "{about something"],
bp.comment.parse_string("@COMMENT{about something").as_list(),
)
self.assertEqual(
["comment", "(about something"],
bp.comment.parse_string("@comment(about something").as_list(),
)
self.assertEqual(
["comment", " about something"],
bp.comment.parse_string("@COMment about something").as_list(),
)
self.assertRaises(
ParseException, bp.comment.parse_string, "@commentabout something"
)
self.assertRaises(
ParseException, bp.comment.parse_string, "@comment+about something"
)
self.assertRaises(
ParseException, bp.comment.parse_string, '@comment"about something'
)
def test_preamble(self):
res = bp.preamble.parse_string('@preamble{"about something"}')
self.assertEqual(res.as_list(), ["preamble", "about something"])
self.assertEqual(
["preamble", "about something"],
bp.preamble.parse_string("@PREamble{{about something}}").as_list(),
)
self.assertEqual(
["preamble", "about something"],
bp.preamble.parse_string(
"""@PREamble{
{about something}
}"""
).as_list(),
)
def test_macro(self):
res = bp.macro.parse_string('@string{ANAME = "about something"}')
self.assertEqual(res.as_list(), ["string", "aname", "about something"])
self.assertEqual(
["string", "aname", "about something"],
bp.macro.parse_string("@string{aname = {about something}}").as_list(),
)
def test_entry(self):
txt = """@some_entry{akey, aname = "about something",
another={something else}}"""
res = bp.entry.parse_string(txt)
self.assertEqual(
[
"some_entry",
"akey",
["aname", "about something"],
["another", "something else"],
],
res.as_list(),
)
# Case conversion
txt = """@SOME_ENTRY{akey, ANAME = "about something",
another={something else}}"""
res = bp.entry.parse_string(txt)
self.assertEqual(
[
"some_entry",
"akey",
["aname", "about something"],
["another", "something else"],
],
res.as_list(),
)
def test_bibfile(self):
txt = """@some_entry{akey, aname = "about something",
another={something else}}"""
res = bp.bibfile.parse_string(txt)
self.assertEqual(
[
[
"some_entry",
"akey",
["aname", "about something"],
["another", "something else"],
]
],
res.as_list(),
)
def test_bib1(self):
# First pass whole bib-like tests
txt = """
Some introductory text
(implicit comment)
@ARTICLE{Brett2002marsbar,
author = {Matthew Brett and Jean-Luc Anton and Romain Valabregue and Jean-Baptise
Poline},
title = {{Region of interest analysis using an SPM toolbox}},
journal = {Neuroimage},
year = {2002},
volume = {16},
pages = {1140--1141},
number = {2}
}
@some_entry{akey, aname = "about something",
another={something else}}
"""
res = bp.bibfile.parse_string(txt)
self.assertEqual(len(res), 3)
res2 = bp.parse_str(txt)
self.assertEqual(res.as_list(), res2.as_list())
res3 = [r.as_list()[0] for r, start, end in bp.definitions.scan_string(txt)]
self.assertEqual(res.as_list(), res3)
if __name__ == "__main__":
unittest.main()
| TestBibparse |
python | dagster-io__dagster | python_modules/libraries/dagster-dlt/dagster_dlt/components/dlt_load_collection/component.py | {
"start": 1732,
"end": 2528
} | class ____(Resolvable):
"""Represents a single dlt load, a combination of pipeline and source."""
pipeline: Annotated[
Pipeline,
Resolver(lambda ctx, path: _load_object_from_python_path(ctx, path), model_field_type=str),
]
source: Annotated[
DltSource,
Resolver(
lambda ctx, path: _load_object_from_python_path(ctx, path),
model_field_type=str,
),
]
translation: Optional[
Annotated[
TranslationFn[DltResourceTranslatorData],
TranslationFnResolver[DltResourceTranslatorData](
lambda data: {"resource": data.resource, "pipeline": data.pipeline}
),
]
] = None
@public
@scaffold_with(DltLoadCollectionScaffolder)
@dataclass
| DltLoadSpecModel |
python | ray-project__ray | python/ray/serve/_private/build_app.py | {
"start": 1330,
"end": 8228
} | class ____:
# Name of the application.
name: str
route_prefix: Optional[str]
logging_config: Optional[LoggingConfig]
# Name of the application's 'ingress' deployment
# (the one exposed over gRPC/HTTP/handle).
ingress_deployment_name: str
# List of unique deployments comprising the app.
deployments: List[Deployment]
# Dict[name, DeploymentHandle] mapping deployment names to the handles that replaced
# them in other deployments' init args/kwargs.
deployment_handles: Dict[str, DeploymentHandle]
external_scaler_enabled: bool
def _make_deployment_handle_default(
deployment: Deployment, app_name: str
) -> DeploymentHandle:
return DeploymentHandle(
deployment.name,
app_name=app_name,
)
def build_app(
app: Application,
*,
name: str,
route_prefix: Optional[str] = None,
logging_config: Optional[Union[Dict, LoggingConfig]] = None,
default_runtime_env: Optional[Dict[str, Any]] = None,
make_deployment_handle: Optional[
Callable[[Deployment, str], DeploymentHandle]
] = None,
external_scaler_enabled: bool = False,
) -> BuiltApplication:
"""Builds the application into a list of finalized deployments.
The following transformations are made:
- Application objects in constructor args/kwargs are converted to
DeploymentHandles for injection at runtime.
- Name conflicts from deployments that use the same class are handled
by appending a monotonically increasing suffix (e.g., SomeClass_1).
Returns: BuiltApplication
"""
if make_deployment_handle is None:
make_deployment_handle = _make_deployment_handle_default
handles = IDDict()
deployment_names = IDDict()
deployments = _build_app_recursive(
app,
app_name=name,
handles=handles,
deployment_names=deployment_names,
default_runtime_env=default_runtime_env,
make_deployment_handle=make_deployment_handle,
)
return BuiltApplication(
name=name,
route_prefix=route_prefix,
logging_config=logging_config,
ingress_deployment_name=app._bound_deployment.name,
deployments=deployments,
deployment_handles={
deployment_names[app]: handle for app, handle in handles.items()
},
external_scaler_enabled=external_scaler_enabled,
)
def _build_app_recursive(
app: Application,
*,
app_name: str,
deployment_names: IDDict[Application, str],
handles: IDDict[Application, DeploymentHandle],
default_runtime_env: Optional[Dict[str, Any]] = None,
make_deployment_handle: Callable[[Deployment, str], DeploymentHandle],
) -> List[Deployment]:
"""Recursively traverses the graph of Application objects.
Each Application will have an associated DeploymentHandle created that will replace
it in any occurrences in other Applications' args or kwargs.
Also collects a list of the unique Applications encountered and returns them as
deployable Deployment objects.
"""
# This application has already been encountered.
# There's no need to recurse into its child args and we don't want to create
# a duplicate entry for it in the list of deployments.
if app in handles:
return []
deployments = []
scanner = _PyObjScanner(source_type=Application)
try:
# Recursively traverse any Application objects bound to init args/kwargs.
child_apps = scanner.find_nodes(
(app._bound_deployment.init_args, app._bound_deployment.init_kwargs)
)
for child_app in child_apps:
deployments.extend(
_build_app_recursive(
child_app,
app_name=app_name,
handles=handles,
deployment_names=deployment_names,
make_deployment_handle=make_deployment_handle,
default_runtime_env=default_runtime_env,
)
)
# Replace Application objects with their corresponding DeploymentHandles.
new_init_args, new_init_kwargs = scanner.replace_nodes(handles)
final_deployment = app._bound_deployment.options(
name=_get_unique_deployment_name_memoized(app, deployment_names),
_init_args=new_init_args,
_init_kwargs=new_init_kwargs,
)
final_deployment = _set_default_runtime_env(
final_deployment, default_runtime_env
)
# Create the DeploymentHandle that will be used to replace this application
# in the arguments of its parent(s).
handles[app] = make_deployment_handle(
final_deployment,
app_name,
)
return deployments + [final_deployment]
finally:
scanner.clear()
def _set_default_runtime_env(
d: Deployment, default_runtime_env: Optional[Dict[str, Any]]
) -> Deployment:
"""Configures the deployment with the provided default runtime_env.
If the deployment does not have a runtime_env configured, the default will be set.
If it does have a runtime_env configured but that runtime_env does not have a
working_dir, only the working_dir field will be set.
Else the deployment's runtime_env will be left untouched.
"""
if not default_runtime_env:
return d
ray_actor_options = deepcopy(d.ray_actor_options or {})
default_working_dir = default_runtime_env.get("working_dir", None)
if "runtime_env" not in ray_actor_options:
ray_actor_options["runtime_env"] = default_runtime_env
elif default_working_dir is not None:
ray_actor_options["runtime_env"].setdefault("working_dir", default_working_dir)
return d.options(ray_actor_options=ray_actor_options)
def _get_unique_deployment_name_memoized(
app: Application, deployment_names: IDDict[Application, str]
) -> str:
"""Generates a name for the deployment.
This is used to handle collisions when the user does not specify a name
explicitly, so typically we'd use the class name as the default.
In that case, we append a monotonically increasing suffix to the name, e.g.,
Deployment, then Deployment_1, then Deployment_2, ...
Names are memoized in the `deployment_names` dict, which should be passed to
subsequent calls to this function.
"""
if app in deployment_names:
return deployment_names[app]
idx = 1
name = app._bound_deployment.name
while name in deployment_names.values():
name = f"{app._bound_deployment.name}_{idx}"
idx += 1
if idx != 1:
logger.warning(
"There are multiple deployments with the same name "
f"'{app._bound_deployment.name}'. Renaming one to '{name}'."
)
deployment_names[app] = name
return name
| BuiltApplication |
python | ZoranPandovski__al-go-rithms | data_structures/Graphs/graph/Python/kahn_algorithm.py | {
"start": 104,
"end": 2150
} | class ____:
def __init__(self,vertices):
self.graph = defaultdict(list) #dictionary containing adjacency List
self.V = vertices #No. of vertices
# function to add an edge to graph
def addEdge(self,u,v):
self.graph[u].append(v)
def topological_sort(self):
#initialise in_degrees
in_degree = [0 for i in range(self.V)]
#calculate in_degrees of all vertices
for i in self.graph:
for j in self.graph[i]:
in_degree[j]+=1
#queue to keep track of vertices with 0 in_degree. These will be first in our topological ordering
queue = []
for i in range(self.V):
if(in_degree[i] == 0):
queue.append(i)
#list for our topological ordering
top_order = []
# keep track of visited vertices to ensure there is no cycle
cnt = 0
#run loop until all vertices are added
while queue:
u = queue.pop(0)
top_order.append(u)
#remove edges outgoing from u
for vertex in self.graph[u]:
in_degree[vertex] -= 1
#new vertices which are "roots" get added to the queue
if in_degree[vertex] == 0:
queue.append(vertex)
cnt += 1
if cnt != self.V:
print("No topolocial ordering exists.")
else:
print(top_order)
def main():
#Normal case
g= Graph(6)
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
print("Following is a Topological Sort of the given graph")
g.topological_sort()
# Cyclic graph
g2= Graph(6)
g2.addEdge(5, 2);
g2.addEdge(2, 5);
g2.addEdge(4, 0);
g2.addEdge(4, 1);
g2.addEdge(2, 3);
g2.addEdge(3, 1);
g2.addEdge(5, 0);
print("Following is a Topological Sort of the given graph")
g2.topological_sort()
if __name__ == '__main__':
main()
| Graph |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-vectara-query/llama_index/tools/vectara_query/base.py | {
"start": 435,
"end": 10846
} | class ____(BaseToolSpec):
"""Vectara Query tool spec."""
spec_functions = ["semantic_search", "rag_query"]
def __init__(
self,
vectara_corpus_key: Optional[str] = None,
vectara_api_key: Optional[str] = None,
num_results: int = 5,
offset: int = 0,
lambda_val: Union[List[float], float] = 0.005,
semantics: Union[List[str], str] = "default",
custom_dimensions: Union[List[Dict], Dict] = {},
n_sentences_before: int = 2,
n_sentences_after: int = 2,
metadata_filter: Union[List[str], str] = "",
reranker: str = "mmr",
rerank_k: int = 50,
rerank_limit: Optional[int] = None,
rerank_cutoff: Optional[float] = None,
mmr_diversity_bias: float = 0.2,
udf_expression: str = None,
rerank_chain: List[Dict] = None,
summarizer_prompt_name: str = "vectara-summary-ext-24-05-sml",
summary_num_results: int = 5,
summary_response_lang: str = "eng",
prompt_text: Optional[str] = None,
max_response_chars: Optional[int] = None,
max_tokens: Optional[int] = None,
temperature: Optional[float] = None,
frequency_penalty: Optional[float] = None,
presence_penalty: Optional[float] = None,
citations_style: Optional[str] = None,
citations_url_pattern: Optional[str] = None,
citations_text_pattern: Optional[str] = None,
save_history: bool = False,
callback_manager: Optional[CallbackManager] = None,
**kwargs: Any,
) -> None:
"""
Initializes the Vectara API and query parameters.
Parameters
----------
- vectara_corpus_key (str): The corpus key for the corpus you want to search for information.
If not specified, reads for environment variable "VECTARA_CORPUS_KEY".
- vectara_api_key (str): An API key that has query permissions for the given corpus.
If not specified, reads for environment variable "VECTARA_API_KEY".
- num_results (int): Number of search results to return with response.
- offset (int): Number of results to skip.
- lambda_val (Union[List[float], float]): Lambda value for the Vectara query.
Provide single value for one corpus or a list of values for each corpus.
- semantics (Union[List[str], str]): Indicates whether the query is intended as a query or response.
Provide single value for one corpus or a list of values for each corpus.
- custom_dimensions (Dict): Custom dimensions for the query.
See (https://docs.vectara.com/docs/learn/semantic-search/add-custom-dimensions)
for more details about usage.
Provide single dict for one corpus or a list of dicts for each corpus.
- n_sentences_before (int): Number of sentences before the summary.
- n_sentences_after (int): Number of sentences after the summary.
- metadata_filter (Union[List[str], str]): A string with expressions to filter the search documents for each corpus.
Provide single string for one corpus or a list of strings for each corpus (if multiple corpora).
- reranker (str): The reranker to use, either mmr, slingshot (i.e. multilingual_reranker_v1), userfn, or chain.
- rerank_k (int): Number of top-k documents for reranking.
- rerank_limit (int): maximum number of results to return after reranking, defaults to 50.
Don't specify this for chain reranking. Instead, put the "limit" parameter in the dict for each individual reranker.
- rerank_cutoff (float): minimum score threshold for results to include after reranking, defaults to 0.
Don't specify this for chain reranking. Instead, put the "chain" parameter in the dict for each individual reranker.
- mmr_diversity_bias (float): MMR diversity bias.
- udf_expression (str): the user defined expression for reranking results.
See (https://docs.vectara.com/docs/learn/user-defined-function-reranker)
for more details about syntax for udf reranker expressions.
- rerank_chain: a list of rerankers to be applied in a sequence and their associated parameters
for the chain reranker. Each element should specify the "type" of reranker (mmr, slingshot, userfn)
and any other parameters (e.g. "limit" or "cutoff" for any type, "diversity_bias" for mmr, and "user_function" for udf).
If using slingshot/multilingual_reranker_v1, it must be first in the list.
- summarizer_prompt_name (str): If enable_summarizer is True, the Vectara summarizer to use.
- summary_num_results (int): If enable_summarizer is True, the number of summary results.
- summary_response_lang (str): If enable_summarizer is True, the response language for the summary.
- prompt_text (str): the custom prompt, using appropriate prompt variables and functions.
See (https://docs.vectara.com/docs/1.0/prompts/custom-prompts-with-metadata)
for more details.
- max_response_chars (int): the desired maximum number of characters for the generated summary.
- max_tokens (int): the maximum number of tokens to be returned by the LLM.
- temperature (float): The sampling temperature; higher values lead to more randomness.
- frequency_penalty (float): How much to penalize repeating tokens in the response, reducing likelihood of repeating the same line.
- presence_penalty (float): How much to penalize repeating tokens in the response, increasing the diversity of topics.
- citations_style (str): The style of the citations in the summary generation,
either "numeric", "html", "markdown", or "none". Defaults to None.
- citations_url_pattern (str): URL pattern for html and markdown citations.
If non-empty, specifies the URL pattern to use for citations; e.g. "{doc.url}".
See (https://docs.vectara.com/docs/api-reference/search-apis/search#citation-format-in-summary) for more details.
Defaults to None.
- citations_text_pattern (str): The displayed text for citations.
If not specified, numeric citations are displayed.
- save_history (bool): Whether to save the query in history. Defaults to False.
"""
self.index = VectaraIndex(
vectara_corpus_key=vectara_corpus_key,
vectara_api_key=vectara_api_key,
)
self.retriever = VectaraRetriever(
index=self.index,
similarity_top_k=num_results,
offset=offset,
lambda_val=lambda_val,
semantics=semantics,
custom_dimensions=custom_dimensions,
n_sentences_before=n_sentences_before,
n_sentences_after=n_sentences_after,
filter=metadata_filter,
reranker=reranker,
rerank_k=rerank_k,
rerank_limit=rerank_limit,
rerank_cutoff=rerank_cutoff,
mmr_diversity_bias=mmr_diversity_bias,
udf_expression=udf_expression,
rerank_chain=rerank_chain,
summary_enabled=False,
callback_manager=callback_manager,
**kwargs,
)
query_engine_retriever = VectaraRetriever(
index=self.index,
similarity_top_k=num_results,
offset=offset,
lambda_val=lambda_val,
semantics=semantics,
custom_dimensions=custom_dimensions,
n_sentences_before=n_sentences_before,
n_sentences_after=n_sentences_after,
filter=metadata_filter,
reranker=reranker,
rerank_k=rerank_k,
rerank_limit=rerank_limit,
rerank_cutoff=rerank_cutoff,
mmr_diversity_bias=mmr_diversity_bias,
udf_expression=udf_expression,
rerank_chain=rerank_chain,
summary_enabled=True,
summary_response_lang=summary_response_lang,
summary_num_results=summary_num_results,
summary_prompt_name=summarizer_prompt_name,
prompt_text=prompt_text,
max_response_chars=max_response_chars,
max_tokens=max_tokens,
temperature=temperature,
frequency_penalty=frequency_penalty,
citations_style=citations_style,
citations_url_pattern=citations_url_pattern,
citations_text_pattern=citations_text_pattern,
callback_manager=callback_manager,
**kwargs,
)
self.query_engine = VectaraQueryEngine(retriever=query_engine_retriever)
def semantic_search(
self,
query: str,
) -> List[Dict]:
"""
Makes a query to a Vectara corpus and returns the top search results from the retrieved documents.
Parameters
----------
query (str): The input query from the user.
Returns
-------
List[Dict]: A list of retrieved documents with their associated metadata
"""
response = self.retriever._retrieve(query_bundle=QueryBundle(query_str=query))
if len(response) == 0:
return []
return [
{
"text": doc.node.text_resource.text,
"citation_metadata": doc.node.metadata,
}
for doc in response
]
def rag_query(
self,
query: str,
) -> Dict:
"""
Makes a query to a Vectara corpus and returns the generated summary, the citation metadata, and the factual consistency score.
Parameters
----------
query (str): The input query from the user.
Returns
-------
Dict: A dictionary containing the generated summary, citation metadata, and the factual consistency score.
"""
response = self.query_engine._query(query_bundle=QueryBundle(query_str=query))
if str(response) == "None":
return {}
return {
"summary": response.response,
"citation_metadata": response.source_nodes,
"factual_consistency_score": response.metadata["fcs"]
if "fcs" in response.metadata
else 0.0,
}
| VectaraQueryToolSpec |
python | ray-project__ray | python/ray/data/llm.py | {
"start": 13565,
"end": 24457
} | class ____(_ServeDeploymentProcessorConfig):
"""The configuration for the serve deployment processor.
This processor enables sharing serve deployments across multiple processors. This is useful
for sharing the same LLM engine across multiple processors.
Args:
deployment_name: The name of the serve deployment to use.
app_name: The name of the serve application to use.
batch_size: The batch size to send to the serve deployment. Large batch sizes are
likely to saturate the compute resources and could achieve higher throughput.
On the other hand, small batch sizes are more fault-tolerant and could
reduce bubbles in the data pipeline. You can tune the batch size to balance
the throughput and fault-tolerance based on your use case.
dtype_mapping: The mapping of the request class name to the request class. If this is
not provided, the serve deployment is expected to accept a dict as the request.
concurrency: The number of workers for data parallelism. Default to 1. Note that this is
not the concurrency of the underlying serve deployment.
Examples:
.. testcode::
:skipif: True
import ray
from ray import serve
from ray.data.llm import ServeDeploymentProcessorConfig, build_llm_processor
from ray.serve.llm import (
LLMConfig,
ModelLoadingConfig,
build_llm_deployment,
)
from ray.serve.llm.openai_api_models import CompletionRequest
llm_config = LLMConfig(
model_loading_config=ModelLoadingConfig(
model_id="facebook/opt-1.3b",
model_source="facebook/opt-1.3b",
),
accelerator_type="A10G",
deployment_config=dict(
name="facebook",
autoscaling_config=dict(
min_replicas=1,
max_replicas=1,
),
),
engine_kwargs=dict(
enable_prefix_caching=True,
enable_chunked_prefill=True,
max_num_batched_tokens=4096,
),
)
APP_NAME = "facebook_opt_app"
DEPLOYMENT_NAME = "facebook_deployment"
override_serve_options = dict(name=DEPLOYMENT_NAME)
llm_app = build_llm_deployment(
llm_config, override_serve_options=override_serve_options
)
app = serve.run(llm_app, name=APP_NAME)
config = ServeDeploymentProcessorConfig(
deployment_name=DEPLOYMENT_NAME,
app_name=APP_NAME,
dtype_mapping={
"CompletionRequest": CompletionRequest,
},
concurrency=1,
batch_size=64,
)
processor = build_llm_processor(
config,
preprocess=lambda row: dict(
method="completions",
dtype="CompletionRequest",
request_kwargs=dict(
model="facebook/opt-1.3b",
prompt=f"This is a prompt for {row['id']}",
stream=False,
),
),
postprocess=lambda row: dict(
resp=row["choices"][0]["text"],
),
)
# The processor requires specific input columns, which depend on
# your processor config. You can use the following API to check
# the required input columns:
processor.log_input_column_names()
ds = ray.data.range(10)
ds = processor(ds)
for row in ds.take_all():
print(row)
"""
pass
@PublicAPI(stability="alpha")
def build_llm_processor(
config: ProcessorConfig,
preprocess: Optional[UserDefinedFunction] = None,
postprocess: Optional[UserDefinedFunction] = None,
preprocess_map_kwargs: Optional[Dict[str, Any]] = None,
postprocess_map_kwargs: Optional[Dict[str, Any]] = None,
builder_kwargs: Optional[Dict[str, Any]] = None,
) -> Processor:
"""Build a LLM processor using the given config.
Args:
config: The processor config. Supports nested stage configs for per-stage
control over batch_size, concurrency, runtime_env, num_cpus, and memory
(e.g., ``chat_template_stage=ChatTemplateStageConfig(batch_size=128)``
or ``tokenize_stage={"batch_size": 256, "concurrency": 2}``). Legacy
boolean flags (``apply_chat_template``, ``tokenize``, ``detokenize``,
``has_image``) are deprecated but still supported with deprecation warnings.
preprocess: An optional lambda function that takes a row (dict) as input
and returns a preprocessed row (dict). The output row must contain the
required fields for the following processing stages. Each row
can contain a `sampling_params` field which will be used by the
engine for row-specific sampling parameters.
Note that all columns will be carried over until the postprocess stage.
postprocess: An optional lambda function that takes a row (dict) as input
and returns a postprocessed row (dict). To keep all the original columns,
you can use the `**row` syntax to return all the original columns.
preprocess_map_kwargs: Optional kwargs to pass to Dataset.map() for the
preprocess stage. Useful for controlling resources (e.g., num_cpus=0.5)
and concurrency independently of the main LLM stage.
postprocess_map_kwargs: Optional kwargs to pass to Dataset.map() for the
postprocess stage. Useful for controlling resources (e.g., num_cpus=0.25)
and concurrency independently of the main LLM stage.
builder_kwargs: Optional additional kwargs to pass to the processor builder
function. These will be passed through to the registered builder and
should match the signature of the specific builder being used.
For example, vLLM and SGLang processors support `chat_template_kwargs`.
Returns:
The built processor.
Examples:
Basic usage:
.. testcode::
:skipif: True
import ray
from ray.data.llm import vLLMEngineProcessorConfig, build_llm_processor
config = vLLMEngineProcessorConfig(
model_source="meta-llama/Meta-Llama-3.1-8B-Instruct",
engine_kwargs=dict(
enable_prefix_caching=True,
enable_chunked_prefill=True,
max_num_batched_tokens=4096,
),
concurrency=1,
batch_size=64,
)
processor = build_llm_processor(
config,
preprocess=lambda row: dict(
messages=[
{"role": "system", "content": "You are a calculator"},
{"role": "user", "content": f"{row['id']} ** 3 = ?"},
],
sampling_params=dict(
temperature=0.3,
max_tokens=20,
detokenize=False,
),
),
postprocess=lambda row: dict(
resp=row["generated_text"],
**row, # This will return all the original columns in the dataset.
),
)
ds = ray.data.range(300)
ds = processor(ds)
for row in ds.take_all():
print(row)
Using map_kwargs to control preprocess/postprocess resources:
.. testcode::
:skipif: True
import ray
from ray.data.llm import vLLMEngineProcessorConfig, build_llm_processor
config = vLLMEngineProcessorConfig(
model_source="meta-llama/Meta-Llama-3.1-8B-Instruct",
concurrency=1,
batch_size=64,
)
processor = build_llm_processor(
config,
preprocess=lambda row: dict(
messages=[{"role": "user", "content": row["prompt"]}],
sampling_params=dict(temperature=0.3, max_tokens=20),
),
postprocess=lambda row: dict(resp=row["generated_text"]),
preprocess_map_kwargs={"num_cpus": 0.5},
postprocess_map_kwargs={"num_cpus": 0.25},
)
ds = ray.data.range(300)
ds = processor(ds)
for row in ds.take_all():
print(row)
Using builder_kwargs to pass chat_template_kwargs:
.. testcode::
:skipif: True
import ray
from ray.data.llm import vLLMEngineProcessorConfig, build_llm_processor
config = vLLMEngineProcessorConfig(
model_source="Qwen/Qwen3-0.6B",
chat_template_stage={"enabled": True},
concurrency=1,
batch_size=64,
)
processor = build_llm_processor(
config,
preprocess=lambda row: dict(
messages=[
{"role": "user", "content": row["prompt"]},
],
sampling_params=dict(
temperature=0.6,
max_tokens=100,
),
),
builder_kwargs=dict(
chat_template_kwargs={"enable_thinking": True},
),
)
ds = ray.data.from_items([{"prompt": "What is 2+2?"}])
ds = processor(ds)
for row in ds.take_all():
print(row)
"""
from ray.llm._internal.batch.processor import ProcessorBuilder
ProcessorBuilder.validate_builder_kwargs(builder_kwargs)
build_kwargs = dict(
preprocess=preprocess,
postprocess=postprocess,
preprocess_map_kwargs=preprocess_map_kwargs,
postprocess_map_kwargs=postprocess_map_kwargs,
)
# Pass through any additional builder kwargs
if builder_kwargs is not None:
build_kwargs.update(builder_kwargs)
return ProcessorBuilder.build(config, **build_kwargs)
__all__ = [
"ProcessorConfig",
"Processor",
"HttpRequestProcessorConfig",
"vLLMEngineProcessorConfig",
"SGLangEngineProcessorConfig",
"ServeDeploymentProcessorConfig",
"build_llm_processor",
]
| ServeDeploymentProcessorConfig |
python | joke2k__faker | tests/providers/test_currency.py | {
"start": 15092,
"end": 15517
} | class ____:
"""Test ro_RO currency provider"""
num_samples = 100
@classmethod
def setup_class(cls):
from faker.providers.currency.ro_RO import Provider as RoRoCurrencyProvider
cls.provider = RoRoCurrencyProvider
def test_pricetag(self, faker, num_samples):
for _ in range(num_samples):
pricetag = faker.pricetag()
assert isinstance(pricetag, str)
| TestRoRo |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/exc.py | {
"start": 11726,
"end": 12121
} | class ____(NoReferenceError):
"""Raised by ``ForeignKey`` when the referred ``Table`` cannot be
located.
"""
def __init__(self, message: str, tname: str):
NoReferenceError.__init__(self, message)
self.table_name = tname
def __reduce__(self) -> Union[str, Tuple[Any, ...]]:
return self.__class__, (self.args[0], self.table_name)
| NoReferencedTableError |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 52586,
"end": 52872
} | class ____(BaseModel):
"""
DAG Stats serializer for responses.
"""
dag_id: Annotated[str, Field(title="Dag Id")]
dag_display_name: Annotated[str, Field(title="Dag Display Name")]
stats: Annotated[list[DagStatsStateResponse], Field(title="Stats")]
| DagStatsResponse |
python | dask__dask | dask/array/cupy_entry_point.py | {
"start": 735,
"end": 2114
} | class ____(ArrayBackendEntrypoint):
def __init__(self):
"""Register data-directed dispatch functions"""
if _cupy(strict=False):
register_cupy()
@classmethod
def to_backend_dispatch(cls):
return to_cupy_dispatch
@classmethod
def to_backend(cls, data: Array, **kwargs):
if isinstance(data._meta, _cupy().ndarray):
# Already a cupy-backed collection
return data
return data.map_blocks(cls.to_backend_dispatch(), **kwargs)
@property
def RandomState(self):
return _cupy().random.RandomState
@property
def default_bit_generator(self):
return _cupy().random.XORWOW
@staticmethod
def ones(*args, **kwargs):
return _da_with_cupy_meta("ones", *args, **kwargs)
@staticmethod
def zeros(*args, **kwargs):
return _da_with_cupy_meta("zeros", *args, **kwargs)
@staticmethod
def empty(*args, **kwargs):
return _da_with_cupy_meta("empty", *args, **kwargs)
@staticmethod
def full(*args, **kwargs):
return _da_with_cupy_meta("full", *args, **kwargs)
@staticmethod
def arange(*args, like=None, **kwargs):
like = _cupy().empty(()) if like is None else like
with config.set({"array.backend": "numpy"}):
return da.arange(*args, like=like, **kwargs)
| CupyBackendEntrypoint |
python | pyodide__pyodide | benchmark/benchmarks/pystone_benchmarks/pystone.py | {
"start": 1892,
"end": 7311
} | class ____:
def __init__(self, PtrComp=None, Discr=0, EnumComp=0, IntComp=0, StringComp=0):
self.PtrComp = PtrComp
self.Discr = Discr
self.EnumComp = EnumComp
self.IntComp = IntComp
self.StringComp = StringComp
def copy(self):
return Record(
self.PtrComp, self.Discr, self.EnumComp, self.IntComp, self.StringComp
)
TRUE = 1
FALSE = 0
def main(loops=LOOPS):
benchtime, stones = pystones(loops)
print("%g" % benchtime)
def pystones(loops=LOOPS):
return Proc0(loops)
IntGlob = 0
BoolGlob = FALSE
Char1Glob = "\0"
Char2Glob = "\0"
Array1Glob = [0] * 51
Array2Glob = [x[:] for x in [Array1Glob] * 51]
PtrGlb = None
PtrGlbNext = None
def Proc0(loops=LOOPS):
global IntGlob
global BoolGlob
global Char1Glob
global Char2Glob
global Array1Glob
global Array2Glob
global PtrGlb
global PtrGlbNext
starttime = perf_counter()
for i in range(loops):
pass
nulltime = perf_counter() - starttime
PtrGlbNext = Record()
PtrGlb = Record()
PtrGlb.PtrComp = PtrGlbNext
PtrGlb.Discr = Ident1
PtrGlb.EnumComp = Ident3
PtrGlb.IntComp = 40
PtrGlb.StringComp = "DHRYSTONE PROGRAM, SOME STRING"
String1Loc = "DHRYSTONE PROGRAM, 1'ST STRING"
Array2Glob[8][7] = 10
starttime = perf_counter()
for i in range(loops):
Proc5()
Proc4()
IntLoc1 = 2
IntLoc2 = 3
String2Loc = "DHRYSTONE PROGRAM, 2'ND STRING"
EnumLoc = Ident2
BoolGlob = not Func2(String1Loc, String2Loc)
while IntLoc1 < IntLoc2:
IntLoc3 = 5 * IntLoc1 - IntLoc2
IntLoc3 = Proc7(IntLoc1, IntLoc2)
IntLoc1 = IntLoc1 + 1
Proc8(Array1Glob, Array2Glob, IntLoc1, IntLoc3)
PtrGlb = Proc1(PtrGlb)
CharIndex = "A"
while CharIndex <= Char2Glob:
if EnumLoc == Func1(CharIndex, "C"):
EnumLoc = Proc6(Ident1)
CharIndex = chr(ord(CharIndex) + 1)
IntLoc3 = IntLoc2 * IntLoc1
IntLoc2 = IntLoc3 / IntLoc1
IntLoc2 = 7 * (IntLoc3 - IntLoc2) - IntLoc1
IntLoc1 = Proc2(IntLoc1)
benchtime = perf_counter() - starttime - nulltime
if benchtime == 0.0:
loopsPerBenchtime = 0.0
else:
loopsPerBenchtime = loops / benchtime
return benchtime, loopsPerBenchtime
def Proc1(PtrParIn):
PtrParIn.PtrComp = NextRecord = PtrGlb.copy()
PtrParIn.IntComp = 5
NextRecord.IntComp = PtrParIn.IntComp
NextRecord.PtrComp = PtrParIn.PtrComp
NextRecord.PtrComp = Proc3(NextRecord.PtrComp)
if NextRecord.Discr == Ident1:
NextRecord.IntComp = 6
NextRecord.EnumComp = Proc6(PtrParIn.EnumComp)
NextRecord.PtrComp = PtrGlb.PtrComp
NextRecord.IntComp = Proc7(NextRecord.IntComp, 10)
else:
PtrParIn = NextRecord.copy()
NextRecord.PtrComp = None
return PtrParIn
def Proc2(IntParIO):
IntLoc = IntParIO + 10
while 1:
if Char1Glob == "A":
IntLoc = IntLoc - 1
IntParIO = IntLoc - IntGlob
EnumLoc = Ident1
if EnumLoc == Ident1:
break
return IntParIO
def Proc3(PtrParOut):
global IntGlob
if PtrGlb is not None:
PtrParOut = PtrGlb.PtrComp
else:
IntGlob = 100
PtrGlb.IntComp = Proc7(10, IntGlob)
return PtrParOut
def Proc4():
global Char2Glob
BoolLoc = Char1Glob == "A"
BoolLoc = BoolLoc or BoolGlob
Char2Glob = "B"
def Proc5():
global Char1Glob
global BoolGlob
Char1Glob = "A"
BoolGlob = FALSE
def Proc6(EnumParIn):
EnumParOut = EnumParIn
if not Func3(EnumParIn):
EnumParOut = Ident4
if EnumParIn == Ident1:
EnumParOut = Ident1
elif EnumParIn == Ident2:
if IntGlob > 100:
EnumParOut = Ident1
else:
EnumParOut = Ident4
elif EnumParIn == Ident3:
EnumParOut = Ident2
elif EnumParIn == Ident4:
pass
elif EnumParIn == Ident5:
EnumParOut = Ident3
return EnumParOut
def Proc7(IntParI1, IntParI2):
IntLoc = IntParI1 + 2
IntParOut = IntParI2 + IntLoc
return IntParOut
def Proc8(Array1Par, Array2Par, IntParI1, IntParI2):
global IntGlob
IntLoc = IntParI1 + 5
Array1Par[IntLoc] = IntParI2
Array1Par[IntLoc + 1] = Array1Par[IntLoc]
Array1Par[IntLoc + 30] = IntLoc
for IntIndex in range(IntLoc, IntLoc + 2):
Array2Par[IntLoc][IntIndex] = IntLoc
Array2Par[IntLoc][IntLoc - 1] = Array2Par[IntLoc][IntLoc - 1] + 1
Array2Par[IntLoc + 20][IntLoc] = Array1Par[IntLoc]
IntGlob = 5
def Func1(CharPar1, CharPar2):
CharLoc1 = CharPar1
CharLoc2 = CharLoc1
if CharLoc2 != CharPar2:
return Ident1
else:
return Ident2
def Func2(StrParI1, StrParI2):
IntLoc = 1
while IntLoc <= 1:
if Func1(StrParI1[IntLoc], StrParI2[IntLoc + 1]) == Ident1:
CharLoc = "A"
IntLoc = IntLoc + 1
if CharLoc >= "W" and CharLoc <= "Z":
IntLoc = 7
if CharLoc == "X":
return TRUE
else:
if StrParI1 > StrParI2:
IntLoc = IntLoc + 7
return TRUE
else:
return FALSE
def Func3(EnumParIn):
EnumLoc = EnumParIn
if EnumLoc == Ident3:
return TRUE
return FALSE
def pystone():
main(LOOPS)
| Record |
python | dagster-io__dagster | python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/core/graphql_client.py | {
"start": 947,
"end": 6634
} | class ____:
def __init__(
self,
session: requests.Session,
headers: Optional[dict[str, Any]] = None,
verify: bool = True,
timeout: int = DEFAULT_TIMEOUT,
cookies: Optional[dict[str, Any]] = None,
proxies: Optional[dict[str, Any]] = None,
max_retries: int = 0,
backoff_factor: float = DEFAULT_BACKOFF_FACTOR,
):
self.headers = headers or {}
self.verify = verify
self.timeout = timeout
self.cookies = cookies
self._session = session
self._proxies = proxies
self._max_retries = max_retries
self._backoff_factor = backoff_factor
@property
def session(self) -> requests.Session:
return self._session
def post(self, *args, **kwargs):
return self.execute("POST", *args, **kwargs)
def get(self, *args, **kwargs):
return self.execute("GET", *args, **kwargs)
def put(self, *args, **kwargs):
return self.execute("PUT", *args, **kwargs)
def execute(
self,
method: str,
url: str,
headers: Optional[Mapping[str, str]] = None,
idempotent: bool = False,
**kwargs,
):
retry_on_read_timeout = idempotent or bool(
headers.get("Idempotency-Key") if headers else False
)
return _retry_loop(
lambda: self._execute_retry(method, url, headers, **kwargs),
max_retries=self._max_retries,
backoff_factor=self._backoff_factor,
retry_on_read_timeout=retry_on_read_timeout,
)
def _execute_retry(
self,
method: str,
url: str,
headers: Optional[Mapping[str, Any]],
**kwargs,
):
response = self._session.request(
method,
url,
headers={
**(self.headers if self.headers is not None else {}),
**(headers if headers is not None else {}),
},
cookies=self.cookies,
timeout=self.timeout,
verify=self.verify,
proxies=self._proxies,
**kwargs,
)
try:
result = response.json()
if not isinstance(result, dict):
result = {}
except ValueError:
result = {}
if "maintenance" in result:
maintenance_info = result["maintenance"]
raise DagsterCloudMaintenanceException(
message=maintenance_info.get("message"),
timeout=maintenance_info.get("timeout"),
retry_interval=maintenance_info.get("retry_interval"),
)
if "errors" in result:
raise DagsterCloudAgentServerError(f"Error in GraphQL response: {result['errors']}")
response.raise_for_status()
return result
def _retry_loop(
execute_retry: Callable,
max_retries: int,
backoff_factor: float,
retry_on_read_timeout: bool,
):
start_time = time.time()
retry_number = 0
error_msg_set = set()
requested_sleep_time = None
while True:
try:
return execute_retry()
except (HTTPError, RequestsConnectionError, RequestsReadTimeout, ChunkedEncodingError) as e:
retryable_error = False
if isinstance(e, HTTPError):
retryable_error = e.response.status_code in RETRY_STATUS_CODES
error_msg = e.response.status_code
requested_sleep_time = _get_retry_after_sleep_time(e.response.headers)
elif isinstance(e, RequestsConnectionError):
retryable_error = True
error_msg = str(e)
else:
retryable_error = retry_on_read_timeout
error_msg = str(e)
error_msg_set.add(error_msg)
if retryable_error and retry_number < max_retries:
retry_number += 1
sleep_time = 0
if requested_sleep_time:
sleep_time = requested_sleep_time
else:
sleep_time = backoff_factor * (2**retry_number)
logger.warning(
f"Error in Dagster Cloud request ({error_msg}). Retrying in"
f" {sleep_time} seconds..."
)
time.sleep(sleep_time)
else:
# Throw the error straight if no retries were involved
if max_retries == 0 or not retryable_error:
if isinstance(e, HTTPError):
raise DagsterCloudHTTPError(e) from e
else:
raise
else:
if len(error_msg_set) == 1:
status_code_msg = str(next(iter(error_msg_set)))
else:
status_code_msg = str(error_msg_set)
raise DagsterCloudAgentServerError(
f"Max retries ({max_retries}) exceeded, too many"
f" {status_code_msg} error responses."
) from e
except DagsterCloudMaintenanceException as e:
if time.time() - start_time > e.timeout:
raise
logger.warning(
"Dagster Cloud is currently unavailable due to scheduled maintenance. Retrying"
f" in {e.retry_interval} seconds..."
)
time.sleep(e.retry_interval)
except DagsterCloudAgentServerError:
raise
except Exception as e:
raise DagsterCloudAgentServerError(str(e)) from e
| DagsterCloudAgentHttpClient |
python | getsentry__sentry | src/sentry/snuba/models.py | {
"start": 4045,
"end": 4627
} | class ____(Model):
__relocation_scope__ = RelocationScope.Organization
class EventType(Enum):
ERROR = 0
DEFAULT = 1
TRANSACTION = 2
TRACE_ITEM_SPAN = 3
TRACE_ITEM_LOG = 4
snuba_query = FlexibleForeignKey("sentry.SnubaQuery")
type = models.SmallIntegerField()
class Meta:
app_label = "sentry"
db_table = "sentry_snubaqueryeventtype"
unique_together = (("snuba_query", "type"),)
@property
def event_type(self):
return self.EventType(self.type)
@region_silo_model
| SnubaQueryEventType |
python | getsentry__sentry | tests/sentry/issues/test_issue_search.py | {
"start": 8830,
"end": 10119
} | class ____(TestCase):
def test_valid(self) -> None:
for status_string, status_val in STATUS_QUERY_CHOICES.items():
filters = [SearchFilter(SearchKey("status"), "=", SearchValue([status_string]))]
result = convert_query_values(filters, [self.project], self.user, None)
assert result[0].value.raw_value == [status_val]
filters = [SearchFilter(SearchKey("status"), "=", SearchValue([status_val]))]
result = convert_query_values(filters, [self.project], self.user, None)
assert result[0].value.raw_value == [status_val]
def test_invalid(self) -> None:
filters = [SearchFilter(SearchKey("status"), "=", SearchValue("wrong"))]
with pytest.raises(InvalidSearchQuery, match="invalid status value"):
convert_query_values(filters, [self.project], self.user, None)
with pytest.raises(
InvalidSearchQuery,
match=r"Aggregate filters \(count_unique\(user\)\) are not supported in issue searches.",
):
convert_query_values(
[AggregateFilter(AggregateKey("count_unique(user)"), ">", SearchValue("1"))],
[self.project],
self.user,
None,
)
| ConvertStatusValueTest |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 48496,
"end": 48542
} | class ____(ssl2_info):
pass
| lapack_ssl2_info |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefaultClass2.py | {
"start": 1123,
"end": 1472
} | class ____(Generic[T1, T2, T3]): ...
h1 = ClassH()
reveal_type(h1, expected_text="ClassH[str, str, list[str]]")
h2 = ClassH[int]()
reveal_type(h2, expected_text="ClassH[int, int, list[int]]")
h3 = ClassH[int, float]()
reveal_type(h3, expected_text="ClassH[int, float, list[float]]")
# This should generate an error because T2 depends on T1.
| ClassH |
python | django__django | tests/migrations/test_migrations_squashed_loop/2_auto.py | {
"start": 35,
"end": 233
} | class ____(migrations.Migration):
replaces = [("migrations", "2_squashed")]
dependencies = [("migrations", "1_auto")]
operations = [migrations.RunPython(migrations.RunPython.noop)]
| Migration |
python | getsentry__sentry | src/sentry/replays/usecases/query/conditions/aggregate.py | {
"start": 6586,
"end": 7255
} | class ____(GenericBase):
@staticmethod
def visit_eq(expression: Expression, value: UUID) -> Condition:
return contains(UUIDArray.visit_eq(expression, value))
@staticmethod
def visit_neq(expression: Expression, value: UUID) -> Condition:
return does_not_contain(UUIDArray.visit_eq(expression, value))
@staticmethod
def visit_in(expression: Expression, value: list[UUID]) -> Condition:
return contains(UUIDArray.visit_in(expression, value))
@staticmethod
def visit_not_in(expression: Expression, value: list[UUID]) -> Condition:
return does_not_contain(UUIDArray.visit_in(expression, value))
| SumOfUUIDArray |
python | getsentry__sentry | src/sentry/workflow_engine/handlers/condition/latest_release_handler.py | {
"start": 4385,
"end": 5242
} | class ____(DataConditionHandler[WorkflowEventData]):
group = DataConditionHandler.Group.ACTION_FILTER
subgroup = DataConditionHandler.Subgroup.EVENT_ATTRIBUTES
comparison_json_schema = {"type": "boolean"}
@staticmethod
def evaluate_value(event_data: WorkflowEventData, comparison: Any) -> bool:
event = event_data.event
if not isinstance(event, GroupEvent):
return False
latest_release = get_latest_release_for_env(event_data.workflow_env, event)
if not latest_release:
return False
releases = (
v.lower()
for k, v in event.tags
if k.lower() == "release" or tagstore.backend.get_standardized_key(k) == "release"
)
return any(release == latest_release.version.lower() for release in releases)
| LatestReleaseConditionHandler |
python | getsentry__sentry | tests/sentry/integrations/aws_lambda/test_utils.py | {
"start": 1148,
"end": 1480
} | class ____(TestCase):
def test_simple(self) -> None:
fn = {
"Runtime": "nodejs10.x",
"FunctionArn": "arn:aws:lambda:us-east-2:599817902985:function:lambdaB",
}
assert get_latest_layer_for_function(fn) == "arn:aws:lambda:us-east-2:1234:layer:my-layer:3"
| GetLatestLayerForFunctionTest |
python | sympy__sympy | sympy/codegen/ast.py | {
"start": 42729,
"end": 43817
} | class ____(Token):
""" Attribute (possibly parametrized)
For use with :class:`sympy.codegen.ast.Node` (which takes instances of
``Attribute`` as ``attrs``).
Parameters
==========
name : str
parameters : Tuple
Examples
========
>>> from sympy.codegen.ast import Attribute
>>> volatile = Attribute('volatile')
>>> volatile
volatile
>>> print(repr(volatile))
Attribute(String('volatile'))
>>> a = Attribute('foo', [1, 2, 3])
>>> a
foo(1, 2, 3)
>>> a.parameters == (1, 2, 3)
True
"""
__slots__ = _fields = ('name', 'parameters')
defaults = {'parameters': Tuple()}
_construct_name = String
_construct_parameters = staticmethod(_mk_Tuple)
def _sympystr(self, printer, *args, **kwargs):
result = str(self.name)
if self.parameters:
result += '(%s)' % ', '.join((printer._print(
arg, *args, **kwargs) for arg in self.parameters))
return result
value_const = Attribute('value_const')
pointer_const = Attribute('pointer_const')
| Attribute |
python | huggingface__transformers | src/transformers/models/clip/modeling_clip.py | {
"start": 26547,
"end": 28071
} | class ____(nn.Module):
def __init__(self, config: CLIPVisionConfig):
super().__init__()
self.config = config
embed_dim = config.hidden_size
self.embeddings = CLIPVisionEmbeddings(config)
self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
self.encoder = CLIPEncoder(config)
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
@auto_docstring
def forward(
self,
pixel_values: Optional[torch.FloatTensor] = None,
interpolate_pos_encoding: Optional[bool] = False,
**kwargs: Unpack[TransformersKwargs],
) -> BaseModelOutputWithPooling:
if pixel_values is None:
raise ValueError("You have to specify pixel_values")
hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
hidden_states = self.pre_layrnorm(hidden_states)
encoder_outputs: BaseModelOutput = self.encoder(
inputs_embeds=hidden_states,
**kwargs,
)
last_hidden_state = encoder_outputs.last_hidden_state
pooled_output = last_hidden_state[:, 0, :]
pooled_output = self.post_layernorm(pooled_output)
return BaseModelOutputWithPooling(
last_hidden_state=last_hidden_state,
pooler_output=pooled_output,
)
@auto_docstring(
custom_intro="""
The vision model from CLIP without any head or projection on top.
"""
)
| CLIPVisionTransformer |
python | PrefectHQ__prefect | src/prefect/workers/base.py | {
"start": 2972,
"end": 12774
} | class ____(BaseModel):
command: Optional[str] = Field(
default=None,
description=(
"The command to use when starting a flow run. "
"In most cases, this should be left blank and the command "
"will be automatically generated by the worker."
),
)
env: dict[str, Optional[str]] = Field(
default_factory=dict,
title="Environment Variables",
description="Environment variables to set when starting a flow run.",
)
labels: dict[str, str] = Field(
default_factory=dict,
description=(
"Labels applied to infrastructure created by the worker using "
"this job configuration."
),
)
name: Optional[str] = Field(
default=None,
description=(
"Name given to infrastructure created by the worker using this "
"job configuration."
),
)
_related_objects: dict[str, Any] = PrivateAttr(default_factory=dict)
@property
def is_using_a_runner(self) -> bool:
return self.command is not None and "prefect flow-run execute" in self.command
@field_validator("command")
@classmethod
def _coerce_command(cls, v: str | None) -> str | None:
return return_v_or_none(v)
@field_validator("env", mode="before")
@classmethod
def _coerce_env(cls, v: dict[str, Any]) -> dict[str, str | None]:
return {k: str(v) if v is not None else None for k, v in v.items()}
@staticmethod
def _get_base_config_defaults(variables: dict[str, Any]) -> dict[str, Any]:
"""Get default values from base config for all variables that have them."""
defaults: dict[str, Any] = {}
for variable_name, attrs in variables.items():
# We remote `None` values because we don't want to use them in templating.
# The currently logic depends on keys not existing to populate the correct value
# in some cases.
# Pydantic will provide default values if the keys are missing when creating
# a configuration class.
if "default" in attrs and attrs.get("default") is not None:
defaults[variable_name] = attrs["default"]
return defaults
@classmethod
@inject_client
async def from_template_and_values(
cls,
base_job_template: dict[str, Any],
values: dict[str, Any],
client: "PrefectClient | None" = None,
):
"""Creates a valid worker configuration object from the provided base
configuration and overrides.
Important: this method expects that the base_job_template was already
validated server-side.
"""
base_config: dict[str, Any] = base_job_template["job_configuration"]
variables_schema = base_job_template["variables"]
variables = cls._get_base_config_defaults(
variables_schema.get("properties", {})
)
# merge variable defaults for `env` into base config before they're replaced by
# deployment overrides
if variables.get("env"):
if isinstance(base_config.get("env"), dict):
# Merge: preserve env vars from job_configuration
base_config["env"] = base_config["env"] | variables.get("env")
else:
# Replace template with defaults
base_config["env"] = variables.get("env")
variables.update(values)
# deep merge `env`
if isinstance(base_config.get("env"), dict) and (
deployment_env := variables.get("env")
):
base_config["env"] = base_config.get("env") | deployment_env
populated_configuration = apply_values(template=base_config, values=variables)
populated_configuration = await resolve_block_document_references(
template=populated_configuration, client=client
)
populated_configuration = await resolve_variables(
template=populated_configuration, client=client
)
return cls(**populated_configuration)
@classmethod
def json_template(cls) -> dict[str, Any]:
"""Returns a dict with job configuration as keys and the corresponding templates as values
Defaults to using the job configuration parameter name as the template variable name.
e.g.
```python
{
key1: '{{ key1 }}', # default variable template
key2: '{{ template2 }}', # `template2` specifically provide as template
}
```
"""
configuration: dict[str, Any] = {}
properties = cls.model_json_schema()["properties"]
for k, v in properties.items():
if v.get("template"):
template = v["template"]
else:
template = "{{ " + k + " }}"
configuration[k] = template
return configuration
def prepare_for_flow_run(
self,
flow_run: "FlowRun",
deployment: "DeploymentResponse | None" = None,
flow: "APIFlow | None" = None,
work_pool: "WorkPool | None" = None,
worker_name: str | None = None,
) -> None:
"""
Prepare the job configuration for a flow run.
This method is called by the worker before starting a flow run. It
should be used to set any configuration values that are dependent on
the flow run.
Args:
flow_run: The flow run to be executed.
deployment: The deployment that the flow run is associated with.
flow: The flow that the flow run is associated with.
work_pool: The work pool that the flow run is running in.
worker_name: The name of the worker that is submitting the flow run.
"""
self._related_objects = {
"deployment": deployment,
"flow": flow,
"flow-run": flow_run,
}
env = {
**self._base_environment(),
**self._base_flow_run_environment(flow_run),
**(self.env if isinstance(self.env, dict) else {}), # pyright: ignore[reportUnnecessaryIsInstance]
}
self.env = {key: value for key, value in env.items() if value is not None}
self.labels = {
**self._base_flow_run_labels(flow_run),
**self._base_work_pool_labels(work_pool),
**self._base_worker_name_label(worker_name),
**self._base_flow_labels(flow),
**self._base_deployment_labels(deployment),
**self.labels,
}
self.name = self.name or flow_run.name
self.command = self.command or self._base_flow_run_command()
@staticmethod
def _base_flow_run_command() -> str:
"""
Generate a command for a flow run job.
"""
return "prefect flow-run execute"
@staticmethod
def _base_flow_run_labels(flow_run: "FlowRun") -> dict[str, str]:
"""
Generate a dictionary of labels for a flow run job.
"""
return {
"prefect.io/flow-run-id": str(flow_run.id),
"prefect.io/flow-run-name": flow_run.name,
"prefect.io/version": prefect.__version__,
}
@classmethod
def _base_environment(cls) -> dict[str, str]:
"""
Environment variables that should be passed to all created infrastructure.
These values should be overridable with the `env` field.
"""
return get_current_settings().to_environment_variables(exclude_unset=True)
@staticmethod
def _base_flow_run_environment(flow_run: "FlowRun | None") -> dict[str, str]:
"""
Generate a dictionary of environment variables for a flow run job.
"""
if flow_run is None:
return {}
return {"PREFECT__FLOW_RUN_ID": str(flow_run.id)}
@staticmethod
def _base_deployment_labels(
deployment: "DeploymentResponse | None",
) -> dict[str, str]:
if deployment is None:
return {}
labels = {
"prefect.io/deployment-id": str(deployment.id),
"prefect.io/deployment-name": deployment.name,
}
if deployment.updated is not None:
labels["prefect.io/deployment-updated"] = deployment.updated.astimezone(
ZoneInfo("UTC")
).isoformat()
return labels
@staticmethod
def _base_flow_labels(flow: "APIFlow | None") -> dict[str, str]:
if flow is None:
return {}
return {
"prefect.io/flow-id": str(flow.id),
"prefect.io/flow-name": flow.name,
}
@staticmethod
def _base_work_pool_labels(work_pool: "WorkPool | None") -> dict[str, str]:
"""Adds the work pool labels to the job manifest."""
if work_pool is None:
return {}
return {
"prefect.io/work-pool-name": work_pool.name,
"prefect.io/work-pool-id": str(work_pool.id),
}
@staticmethod
def _base_worker_name_label(worker_name: str | None) -> dict[str, str]:
"""Adds the worker name label to the job manifest."""
if worker_name is None:
return {}
return {"prefect.io/worker-name": worker_name}
def _related_resources(self) -> list[RelatedResource]:
tags: set[str] = set()
related: list[RelatedResource] = []
for kind, obj in self._related_objects.items():
if obj is None:
continue
if hasattr(obj, "tags"):
tags.update(obj.tags)
related.append(object_as_related_resource(kind=kind, role=kind, object=obj))
return related + tags_as_related_resources(tags)
| BaseJobConfiguration |
python | python-pillow__Pillow | src/PIL/ImageFilter.py | {
"start": 4226,
"end": 4765
} | class ____(Filter):
"""
Create a mode filter. Picks the most frequent pixel value in a box with the
given size. Pixel values that occur only once or twice are ignored; if no
pixel value occurs more than twice, the original pixel value is preserved.
:param size: The kernel size, in pixels.
"""
name = "Mode"
def __init__(self, size: int = 3) -> None:
self.size = size
def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
return image.modefilter(self.size)
| ModeFilter |
python | numba__numba | numba/tests/test_dispatcher.py | {
"start": 36893,
"end": 38046
} | class ____(SerialMixin, unittest.TestCase):
def run_fc_multiproc(self, fc):
try:
ctx = multiprocessing.get_context('spawn')
except AttributeError:
ctx = multiprocessing
# RE: issue #5973, this doesn't use multiprocessing.Pool.map as doing so
# causes the TBB library to segfault under certain conditions. It's not
# clear whether the cause is something in the complexity of the Pool
# itself, e.g. watcher threads etc, or if it's a problem synonymous with
# a "timing attack".
for a in [1, 2, 3]:
p = ctx.Process(target=_checker, args=(fc, a,))
p.start()
p.join(_TEST_TIMEOUT)
self.assertEqual(p.exitcode, 0)
def test_int_def_param(self):
""" Tests issue #4888"""
self.run_fc_multiproc(add_y1)
def test_none_def_param(self):
""" Tests None as a default parameter"""
self.run_fc_multiproc(add_func)
def test_function_def_param(self):
""" Tests a function as a default parameter"""
self.run_fc_multiproc(add_func)
| TestMultiprocessingDefaultParameters |
python | huggingface__transformers | src/transformers/models/deit/modeling_deit.py | {
"start": 14214,
"end": 14750
} | class ____(nn.Module):
def __init__(self, config: DeiTConfig):
super().__init__()
self.config = config
self.layer = nn.ModuleList([DeiTLayer(config) for _ in range(config.num_hidden_layers)])
self.gradient_checkpointing = False
def forward(self, hidden_states: torch.Tensor) -> BaseModelOutput:
for i, layer_module in enumerate(self.layer):
hidden_states = layer_module(hidden_states)
return BaseModelOutput(last_hidden_state=hidden_states)
@auto_docstring
| DeiTEncoder |
python | encode__django-rest-framework | tests/test_request.py | {
"start": 13184,
"end": 13341
} | class ____(TestCase):
def test_deepcopy_works(self):
request = Request(factory.get('/', secure=False))
copy.deepcopy(request)
| TestDeepcopy |
python | pytorch__pytorch | test/distributed/_composable/test_replicate_with_compiler.py | {
"start": 2493,
"end": 13679
} | class ____(MultiProcessInductorTestCase):
@property
def world_size(self) -> int:
return min(2, torch.get_device_module(device_type).device_count())
def _test_compile(
self,
*,
no_sync: bool,
setup_func: Optional[Callable] = None,
no_inductor: bool = False,
no_compile_forward: bool = False,
checkpoint: bool = False,
device: Union[str, torch.device],
):
self.create_pg(device)
torch._dynamo.config.optimize_ddp = "python_reducer"
torch.manual_seed(123)
if device_type == "xpu":
torch.use_deterministic_algorithms(True, warn_only=True)
model = Net(checkpoint=checkpoint).to(device)
input = torch.randn([1, DIM], device=device)
compiled_replicate_model = replicate(deepcopy(model))
if not no_compile_forward:
compiled_replicate_model = torch.compile(
compiled_replicate_model, fullgraph=False
)
compiled_replicate_optim = torch.optim.Adam(
compiled_replicate_model.parameters()
)
compiled_ddp_model = DDP(deepcopy(model))
if not no_compile_forward:
compiled_ddp_model = torch.compile(compiled_ddp_model, fullgraph=True)
compiled_ddp_optim = torch.optim.Adam(compiled_ddp_model.parameters())
model = replicate(model)
optim = torch.optim.Adam(model.parameters())
if setup_func:
setup_func(model, compiled_replicate_model, compiled_ddp_model)
models = [model, compiled_replicate_model, compiled_ddp_model]
optims = [optim, compiled_replicate_optim, compiled_ddp_optim]
sync_contexts = [
contextlib.nullcontext(),
contextlib.nullcontext(),
compiled_ddp_model.no_sync(),
]
# Run multiple iterations so that we could test no_sync
for i in range(2):
# Setting a different random seed so that if the allreduces are not
# executed correctly, the gradients won't be correct compared to the
# eager DDP.
torch.manual_seed(123 + self.rank + i)
input = torch.randn([1, DIM], device=device)
for model_idx in range(3):
if no_sync and i % 2 == 0:
context = sync_contexts[model_idx]
if model_idx <= 1:
models[model_idx].set_requires_gradient_sync(False)
else:
context = contextlib.nullcontext()
if model_idx <= 1:
models[model_idx].set_requires_gradient_sync(True)
context = contextlib.nullcontext()
with context:
bwd_context = (
contextlib.nullcontext()
if model_idx == 0
else compiled_autograd._enable(compiler_fn(no_inductor))
)
with bwd_context:
loss = models[model_idx](input).sum()
loss.backward()
if not no_sync or i % 2 == 1:
for p1, p2, p3 in zip(
model.parameters(),
compiled_replicate_model.parameters(),
compiled_ddp_model.parameters(),
):
self.assertEqual(p1.grad, p2.grad)
self.assertEqual(p1.grad, p3.grad)
for optim in optims:
optim.step()
optim.zero_grad()
self.assertEqual(
tuple(model.parameters()), tuple(compiled_replicate_model.parameters())
)
self.assertEqual(
tuple(model.parameters()), tuple(compiled_ddp_model.parameters())
)
dist.destroy_process_group()
def test_compile_cpu(self):
# Test the coalesced_op with CPU.
torch._inductor.config._fuse_ddp_communication_passes = [
"fuse_ddp_with_coalesced_op",
"schedule_comm_wait",
]
self._test_compile(no_sync=False, device="cpu")
def test_compile_cpu_no_sync(self):
# Test the coalesced_op with CPU.
torch._inductor.config._fuse_ddp_communication_passes = [
"fuse_ddp_with_coalesced_op",
"schedule_comm_wait",
]
self._test_compile(no_sync=True, device="cpu")
@unittest.skipIf(not HAS_GPU, "Inductor+gpu needs triton and recent GPU arch")
@skip_if_lt_x_gpu(2)
@torch._inductor.config.patch(
reorder_for_locality=False, reorder_for_peak_memory=False
)
def test_compile_gpu(self):
self._test_compile(no_sync=False, checkpoint=False, device=device_type)
@unittest.skipIf(not HAS_GPU, "Inductor+gpu needs triton and recent GPU arch")
@skip_if_lt_x_gpu(2)
@torch._inductor.config.patch(
reorder_for_locality=False, reorder_for_peak_memory=False
)
def test_compile_gpu_ac(self):
self._test_compile(no_sync=False, checkpoint=True, device=device_type)
@unittest.skipIf(not HAS_GPU, "Inductor+gpu needs triton and recent GPU arch")
@skip_if_lt_x_gpu(2)
def test_compile_bf16(self):
# Check device capability wrt bf16
if (
not sm_is_or_higher_than(torch.device(device_type), 8, 0)
and torch.version.hip is None
):
self.skipTest("bf16 requires sm >= 8.0")
def setup(model, compiled_replicate_model, compiled_ddp_model) -> None:
model.register_comm_hook(None, ddp_default_hooks.bf16_compress_hook)
compiled_m = compiled_replicate_model._orig_mod
compiled_m.register_comm_hook(None, ddp_default_hooks.bf16_compress_hook)
compiled_ddp_model.register_comm_hook(
None, ddp_default_hooks.bf16_compress_hook
)
self._test_compile(no_sync=False, setup_func=setup, device=device_type)
@unittest.skipIf(not HAS_GPU, "Inductor+gpu needs triton and recent GPU arch")
@skip_if_lt_x_gpu(2)
def test_compile_fp16(self):
def setup(model, compiled_replicate_model, compiled_ddp_model) -> None:
model.register_comm_hook(None, ddp_default_hooks.fp16_compress_hook)
compiled_m = compiled_replicate_model._orig_mod
compiled_m.register_comm_hook(None, ddp_default_hooks.fp16_compress_hook)
compiled_ddp_model.register_comm_hook(
None, ddp_default_hooks.fp16_compress_hook
)
# TODO: figure out why we need to disable Inductor to avoid test errors.
self._test_compile(
no_sync=False, setup_func=setup, no_inductor=True, device=device_type
)
@unittest.skipIf(not HAS_GPU, "Inductor+gpu needs triton and recent GPU arch")
@skip_if_lt_x_gpu(2)
def test_compile_backward_only(self):
self._test_compile(no_sync=False, no_compile_forward=True, device=device_type)
def _test_bucketing(self, init_process_group=True, loop=1):
if init_process_group:
dist.init_process_group(
backend="gloo",
rank=self.rank,
world_size=self.world_size,
store=dist.FileStore(self.file_name, self.world_size),
)
model = Net()
input = torch.randn([1, DIM])
torch._dynamo.config.optimize_ddp = "python_reducer"
compiled_replicate_model = torch.compile(
replicate(deepcopy(model)), fullgraph=False
)
def bwd(loss):
with compiled_autograd._enable(compiler_fn()):
loss.backward()
for i in range(loop):
loss = compiled_replicate_model(input).sum()
if i != loop - 1:
# Leave the last bwd for the run_and_get_triton_code.
bwd(loss)
code = run_and_get_triton_code(functools.partial(bwd, loss=loss))
self.assertEqual(counters["inductor"]["ddp_buckets"], 3)
return code
@torch._inductor.config.patch(
_fuse_ddp_communication_passes=[
"fuse_ddp_with_coalesced_op",
"schedule_comm_wait",
]
)
# todo: This pass mucks things up since Inductor thinks its inference
# and can apply this. Should turn off these passes in compiled autograd
@torch._inductor.config.patch(
reorder_for_locality=False,
reorder_for_peak_memory=False,
# The correctness of this test relies on the pointless permute ops
# in the joint graph does not get eliminated..
pattern_matcher=False,
)
def test_bucketing_coalesced_op(self):
# Gradient is None
code = self._test_bucketing()
self.assertEqual(counters["inductor"]["ddp_buckets"], 3)
fc = FileCheck()
for _ in range(3):
fc.check("cpp_fused_").check(
"torch.ops._c10d_functional.all_reduce_coalesced_.default("
)
for _ in range(3):
fc.check("torch.ops._c10d_functional.wait_tensor.default")
fc.run(code)
# Gradient is None
code = self._test_bucketing(init_process_group=False, loop=2)
self.assertEqual(counters["inductor"]["ddp_buckets"], 3)
fc = FileCheck()
for _ in range(3):
fc.check("cpp_fused_").check(
"torch.ops._c10d_functional.all_reduce_coalesced_.default("
)
for _ in range(3):
fc.check("torch.ops._c10d_functional.wait_tensor.default")
fc.run(code)
@torch._inductor.config.patch(
_fuse_ddp_communication_passes=[
"fuse_ddp_with_concat_op",
"schedule_comm_wait",
]
)
# todo: This pass mucks things up since Inductor thinks its inference
# and can apply this. Should turn off these passes in compiled autograd
@torch._inductor.config.patch(
reorder_for_locality=False,
reorder_for_peak_memory=False,
# The correctness of this test relies on the pointless permute ops
# in the joint graph does not get eliminated..
pattern_matcher=False,
)
def test_bucketing_concat_op(self):
# Gradient is None
code = self._test_bucketing()
self.assertEqual(counters["inductor"]["ddp_buckets"], 3)
fc = FileCheck()
for _ in range(3):
fc.check("aten.flatten.using_ints(").check("cpp_fused_").check(
"torch.ops._c10d_functional.all_reduce_.default("
)
for _ in range(3):
fc.check("torch.ops._c10d_functional.wait_tensor.default")
fc.run(code)
# Gradient is not None
code = self._test_bucketing(init_process_group=False, loop=2)
self.assertEqual(counters["inductor"]["ddp_buckets"], 3)
fc = FileCheck()
for _ in range(3):
fc.check("aten.flatten.using_ints(").check("cpp_fused_").check(
"torch.ops._c10d_functional.all_reduce_.default("
)
for _ in range(3):
fc.check("torch.ops._c10d_functional.wait_tensor.default")
fc.run(code)
| ReplicateTest |
python | ansible__ansible | lib/ansible/utils/context_objects.py | {
"start": 1907,
"end": 2794
} | class ____(ImmutableDict):
"""
Hold a parsed copy of cli arguments
We have both this non-Singleton version and the Singleton, GlobalCLIArgs, version to leave us
room to implement a Context object in the future. Whereas there should only be one set of args
in a global context, individual Context objects might want to pretend that they have different
command line switches to trigger different behaviour when they run. So if we support Contexts
in the future, they would use CLIArgs instead of GlobalCLIArgs to store their version of command
line flags.
"""
def __init__(self, mapping):
toplevel = {}
for key, value in mapping.items():
toplevel[key] = _make_immutable(value)
super(CLIArgs, self).__init__(toplevel)
@classmethod
def from_options(cls, options):
return cls(vars(options))
| CLIArgs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.