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 | pypa__pip | src/pip/_vendor/idna/core.py | {
"start": 259,
"end": 366
} | class ____(UnicodeError):
"""Base exception for all IDNA-encoding related problems"""
pass
| IDNAError |
python | openai__openai-python | src/openai/types/responses/parsed_response.py | {
"start": 3232,
"end": 3799
} | class ____(Response, GenericModel, Generic[ContentType]):
if TYPE_CHECKING:
output: List[ParsedResponseOutputItem[ContentType]] # type: ignore[assignment]
else:
output: List[ParsedResponseOutputItem]
@property
def output_parsed(self) -> Optional[ContentType]:
for output in self.output:
if output.type == "message":
for content in output.content:
if content.type == "output_text" and content.parsed:
return content.parsed
return None
| ParsedResponse |
python | realpython__materials | structural-pattern-matching/repl_enhanced.py | {
"start": 1778,
"end": 3891
} | class ____:
lines: list[str] = field(default_factory=list)
def execute(self) -> None:
exec("\n".join(self.lines), globals())
self.lines = []
def main() -> None:
print('Type "help" for more information, "exit" or "quit" to finish.')
console = Console()
block = CodeBlock()
while True:
try:
match console.input():
case command if command.lower() in COMMANDS:
match command.lower():
case "help":
print(f"Python {sys.version}")
case "exit" | "quit":
break
case line if line.endswith(":"):
block.lines.append(line)
console.reindent(line)
console.indent()
case line if line.lstrip() == "":
console.reindent(line)
console.dedent()
if console.indentation_level == 0 and block.lines:
block.execute()
case line if console.indentation_level > 0:
block.lines.append(line)
case expression if valid(expression, "eval"):
_ = eval(expression)
if _ is not None:
print(_)
case statement if valid(statement, "exec"):
exec(statement)
case _:
print("Please type a command or valid Python")
except KeyboardInterrupt:
print("\nKeyboardInterrupt")
console.indentation_level = 0
block.lines = []
except EOFError:
print()
sys.exit()
except Exception:
traceback.print_exc(file=sys.stdout)
console.indentation_level = 0
block.lines = []
def valid(code: str, mode: Literal["eval", "exec"]) -> bool:
try:
ast.parse(code, mode=mode)
return True
except SyntaxError:
return False
if __name__ == "__main__":
main()
| CodeBlock |
python | doocs__leetcode | lcof2/剑指 Offer II 017. 含有所有字符的最短字符串/Solution.py | {
"start": 0,
"end": 816
} | class ____:
def minWindow(self, s: str, t: str) -> str:
m, n = len(s), len(t)
if n > m:
return ""
need, window = defaultdict(int), defaultdict(int)
for c in t:
need[c] += 1
start, minLen = 0, inf
left, right = 0, 0
while right < m:
window[s[right]] += 1
right += 1
while self.check(need, window):
if right - left < minLen:
minLen = right - left
start = left
window[s[left]] -= 1
left += 1
return "" if minLen == inf else s[start : start + minLen]
def check(self, need, window):
for k, v in need.items():
if window[k] < v:
return False
return True
| Solution |
python | scipy__scipy | scipy/signal/tests/test_signaltools.py | {
"start": 188445,
"end": 190377
} | class ____:
@skip_xp_backends(np_only=True, reason="list inputs are numpy-specific")
def test_array_like(self, xp):
# From docstring example: with lists
original = [0.0, 1, 0, 0, 1, 1, 0, 0]
impulse_response = [2, 1]
recorded = xp.asarray([0.0, 2, 1, 0, 2, 3, 1, 0, 0])
recovered, remainder = signal.deconvolve(recorded, impulse_response)
xp_assert_close(recovered, original)
def test_basic(self, xp):
# From docstring example
original = xp.asarray([0.0, 1, 0, 0, 1, 1, 0, 0], dtype=xp.float64)
impulse_response = xp.asarray([2, 1])
recorded = xp.asarray([0.0, 2, 1, 0, 2, 3, 1, 0, 0])
recovered, remainder = signal.deconvolve(recorded, impulse_response)
xp_assert_close(recovered, original)
@xfail_xp_backends("cupy", reason="different error message")
def test_n_dimensional_signal(self, xp):
recorded = xp.asarray([[0, 0], [0, 0]])
impulse_response = xp.asarray([0, 0])
with pytest.raises(ValueError, match="^Parameter signal must be non-empty"):
quotient, remainder = signal.deconvolve(recorded, impulse_response)
@xfail_xp_backends("cupy", reason="different error message")
def test_n_dimensional_divisor(self, xp):
recorded = xp.asarray([0, 0])
impulse_response = xp.asarray([[0, 0], [0, 0]])
with pytest.raises(ValueError, match="^Parameter divisor must be non-empty"):
quotient, remainder = signal.deconvolve(recorded, impulse_response)
def test_divisor_greater_signal(self, xp):
"""Return signal as `remainder` when ``len(divisior) > len(signal)``. """
sig, div = xp.asarray([0, 1, 2]), xp.asarray([0, 1, 2, 4, 5])
quotient, remainder = signal.deconvolve(sig, div)
xp_assert_equal(remainder, sig)
assert xp_size(xp.asarray(quotient)) == 0
@make_xp_test_case(detrend)
| TestDeconvolve |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 97260,
"end": 97497
} | class ____:
xlPrintErrorsBlank = 1 # from enum XlPrintErrors
xlPrintErrorsDash = 2 # from enum XlPrintErrors
xlPrintErrorsDisplayed = 0 # from enum XlPrintErrors
xlPrintErrorsNA = 3 # from enum XlPrintErrors
| PrintErrors |
python | scipy__scipy | scipy/integrate/tests/test_integrate.py | {
"start": 6540,
"end": 7693
} | class ____(TestODEClass):
ode_class = complex_ode
def test_vode(self):
# Check the vode solver
for problem_cls in PROBLEMS:
problem = problem_cls()
if not problem.stiff:
self._do_problem(problem, 'vode', 'adams')
else:
self._do_problem(problem, 'vode', 'bdf')
def test_lsoda(self):
# Check the lsoda solver
for problem_cls in PROBLEMS:
problem = problem_cls()
self._do_problem(problem, 'lsoda')
def test_dopri5(self):
# Check the dopri5 solver
for problem_cls in PROBLEMS:
problem = problem_cls()
if problem.stiff:
continue
if hasattr(problem, 'jac'):
continue
self._do_problem(problem, 'dopri5')
def test_dop853(self):
# Check the dop853 solver
for problem_cls in PROBLEMS:
problem = problem_cls()
if problem.stiff:
continue
if hasattr(problem, 'jac'):
continue
self._do_problem(problem, 'dop853')
| TestComplexOde |
python | spyder-ide__spyder | spyder/plugins/plots/widgets/main_widget.py | {
"start": 1636,
"end": 16701
} | class ____(ShellConnectMainWidget):
# PluginMainWidget API
SHOW_MESSAGE_WHEN_EMPTY = True
IMAGE_WHEN_EMPTY = "plots"
MESSAGE_WHEN_EMPTY = _("No plots to show")
DESCRIPTION_WHEN_EMPTY = _(
"Run plot-generating code in the Editor or IPython console to see "
"your figures appear here. This pane only supports static images, so "
"it can't display interactive plots like Bokeh, Plotly or Altair."
)
# Signals
sig_figure_loaded = Signal()
"""This signal is emitted when a figure is loaded succesfully"""
def __init__(self, name=None, plugin=None, parent=None):
super().__init__(name, plugin, parent)
# Widgets
self.zoom_disp = QSpinBox(self)
self.zoom_disp.ID = PlotsWidgetToolbarItems.ZoomSpinBox
self._right_clicked_thumbnail = None
# Widget setup
self.zoom_disp.setAlignment(Qt.AlignCenter)
self.zoom_disp.setButtonSymbols(QSpinBox.NoButtons)
self.zoom_disp.setReadOnly(True)
self.zoom_disp.setSuffix(' %')
self.zoom_disp.setRange(0, 9999)
self.zoom_disp.setValue(100)
# ---- PluginMainWidget API
# ------------------------------------------------------------------------
def get_title(self):
return _('Plots')
def get_focus_widget(self):
widget = self.current_widget()
if widget and widget.thumbnails_sb.current_thumbnail is not None:
if widget.figviewer.figcanvas.fig:
widget = widget.thumbnails_sb.scrollarea
return widget
def setup(self):
# Menu actions
self.mute_action = self.create_action(
name=PlotsWidgetActions.ToggleMuteInlinePlotting,
text=_("Mute inline plotting"),
tip=_("Mute inline plotting in the ipython console."),
toggled=True,
initial=self.get_conf('mute_inline_plotting'),
option='mute_inline_plotting'
)
self.outline_action = self.create_action(
name=PlotsWidgetActions.ToggleShowPlotOutline,
text=_("Show plot outline"),
tip=_("Show the plot outline."),
toggled=True,
initial=self.get_conf('show_plot_outline'),
option='show_plot_outline'
)
self.fit_action = self.create_action(
name=PlotsWidgetActions.ToggleAutoFitPlotting,
text=_("Fit plots to pane"),
tip=_("Fit plot to the pane size"),
icon=self.create_icon("plot.fit_to_pane"),
toggled=self.fit_to_pane,
initial=False,
register_shortcut=True,
)
# Toolbar actions
save_action = self.create_action(
name=PlotsWidgetActions.Save,
text=_("Save plot as..."),
tip=_("Save plot as..."),
icon=self.create_icon('filesave'),
triggered=self.save_plot,
register_shortcut=True,
)
save_all_action = self.create_action(
name=PlotsWidgetActions.SaveAll,
text=_("Save all plots..."),
tip=_("Save all plots..."),
icon=self.create_icon('save_all'),
triggered=self.save_all_plots,
register_shortcut=True,
)
copy_action = self.create_action(
name=PlotsWidgetActions.Copy,
text=_("Copy image"),
tip=_("Copy plot to clipboard as image"),
icon=self.create_icon('editcopy'),
triggered=self.copy_image,
register_shortcut=True,
)
remove_action = self.create_action(
name=PlotsWidgetActions.Close,
text=_("Remove plot"),
icon=self.create_icon('editclear'),
triggered=self.remove_plot,
register_shortcut=True,
)
remove_all_action = self.create_action(
name=PlotsWidgetActions.CloseAll,
text=_("Remove all plots"),
tip=_("Remove all plots"),
icon=self.create_icon('editdelete'),
triggered=self.remove_all_plots,
register_shortcut=True,
)
previous_action = self.create_action(
name=PlotsWidgetActions.MoveToPreviousFigure,
text=_("Previous plot"),
tip=_("Previous plot"),
icon=self.create_icon('previous'),
triggered=self.previous_plot,
register_shortcut=True,
)
next_action = self.create_action(
name=PlotsWidgetActions.MoveToNextFigure,
text=_("Next plot"),
tip=_("Next plot"),
icon=self.create_icon('next'),
triggered=self.next_plot,
register_shortcut=True,
)
zoom_in_action = self.create_action(
name=PlotsWidgetActions.ZoomIn,
text=_("Zoom in"),
tip=_("Zoom in"),
icon=self.create_icon('zoom_in'),
triggered=self.zoom_in,
register_shortcut=True,
)
zoom_out_action = self.create_action(
name=PlotsWidgetActions.ZoomOut,
text=_("Zoom out"),
tip=_("Zoom out"),
icon=self.create_icon('zoom_out'),
triggered=self.zoom_out,
register_shortcut=True,
)
# Options menu
options_menu = self.get_options_menu()
self.add_item_to_menu(self.mute_action, menu=options_menu)
self.add_item_to_menu(self.outline_action, menu=options_menu)
# Main toolbar
main_toolbar = self.get_main_toolbar()
for item in [
save_action,
save_all_action,
copy_action,
remove_action,
remove_all_action,
]:
self.add_item_to_toolbar(
item,
toolbar=main_toolbar,
section=PlotsWidgetMainToolbarSections.Edit,
)
stretcher = self.create_stretcher(
PlotsWidgetToolbarItems.ToolbarStretcher
)
for item in [
self.zoom_disp,
zoom_out_action,
zoom_in_action,
self.fit_action,
stretcher,
previous_action,
next_action,
]:
self.add_item_to_toolbar(
item,
toolbar=main_toolbar,
section=PlotsWidgetMainToolbarSections.ZoomAndMove,
)
# Context menu
context_menu = self.create_menu(PluginMainWidgetMenus.Context)
for item in [save_action, copy_action, remove_action]:
self.add_item_to_menu(item, menu=context_menu)
def update_actions(self):
value = False
widget = self.current_widget()
figviewer = None
if widget and not self.is_current_widget_error_message():
figviewer = widget.figviewer
value = figviewer.figcanvas.fig is not None
widget.set_pane_empty(not value)
with signals_blocked(self.fit_action):
self.fit_action.setChecked(figviewer.auto_fit_plotting)
for __, action in self.get_actions().items():
try:
if action and action not in [
self.mute_action,
self.outline_action,
self.undock_action,
self.close_action,
self.dock_action,
self.toggle_view_action,
self.lock_unlock_action,
]:
action.setEnabled(value)
except (RuntimeError, AttributeError):
pass
self.zoom_disp.setEnabled(value)
@on_conf_change(
option=["mute_inline_plotting", "show_plot_outline", "save_dir"]
)
def on_section_conf_change(self, option, value):
for index in range(self.count()):
widget = self._stack.widget(index)
if widget:
widget.setup({option: value})
self.update_actions()
# ---- Public API
# ------------------------------------------------------------------------
def create_new_widget(self, shellwidget):
fig_browser = FigureBrowser(parent=self,
background_color=MAIN_BG_COLOR)
fig_browser.set_shellwidget(shellwidget)
fig_browser.sig_redirect_stdio_requested.connect(
self.sig_redirect_stdio_requested)
fig_browser.sig_figure_menu_requested.connect(
self.show_figure_menu)
fig_browser.sig_thumbnail_menu_requested.connect(
self.show_thumbnail_menu)
fig_browser.sig_figure_loaded.connect(self.update_actions)
fig_browser.sig_save_dir_changed.connect(
lambda val: self.set_conf('save_dir', val))
fig_browser.sig_zoom_changed.connect(self.zoom_disp.setValue)
fig_browser.sig_show_empty_message_requested.connect(
self.switch_empty_message
)
return fig_browser
def close_widget(self, fig_browser):
fig_browser.sig_redirect_stdio_requested.disconnect(
self.sig_redirect_stdio_requested)
fig_browser.sig_figure_menu_requested.disconnect(
self.show_figure_menu)
fig_browser.sig_thumbnail_menu_requested.disconnect(
self.show_thumbnail_menu)
fig_browser.sig_figure_loaded.disconnect(self.update_actions)
fig_browser.sig_save_dir_changed.disconnect()
fig_browser.sig_zoom_changed.disconnect(self.zoom_disp.setValue)
fig_browser.close()
fig_browser.setParent(None)
def switch_widget(self, fig_browser, old_fig_browser):
option_keys = [
("mute_inline_plotting", True),
("show_plot_outline", True),
("save_dir", getcwd_or_home()),
]
conf_values = {k: self.get_conf(k, d) for k, d in option_keys}
fig_browser.setup(conf_values)
def show_figure_menu(self, qpoint):
"""
Show main figure menu and display on given `qpoint`.
Parameters
----------
qpoint: QPoint
The point to display the menu in global coordinated.
"""
self._right_clicked_thumbnail = None
widget = self.current_widget()
if widget:
self.get_menu(PluginMainWidgetMenus.Context).popup(qpoint)
def show_thumbnail_menu(self, qpoint, thumbnail):
"""
Show menu on a given `thumbnail` and display on given `qpoint`.
Parameters
----------
qpoint: QPoint
The point to display the menu in global coordinated.
"""
self._right_clicked_thumbnail = thumbnail
widget = self.current_widget()
if widget:
self.get_menu(PluginMainWidgetMenus.Context).popup(qpoint)
def save_plot(self):
"""
Save currently active plot or plot selected to be saved with
context menu in the thumbnails scrollbar.
"""
widget = self.current_widget()
if widget:
if self._right_clicked_thumbnail is None:
widget.thumbnails_sb.save_current_figure_as()
else:
widget.thumbnails_sb.save_thumbnail_figure_as(
self._right_clicked_thumbnail)
# Reset the toolbar buttons to use the figviewer and not the thumbnail
# selection
self._right_clicked_thumbnail = None
def save_all_plots(self):
"""Save all available plots."""
widget = self.current_widget()
if widget:
widget.thumbnails_sb.save_all_figures_as()
def copy_image(self):
"""
Copy currently active plot or plot selected to be copied with
context menu in the thumbnails scrollbar into the clipboard.
"""
widget = self.current_widget()
if widget and widget.figviewer and widget.figviewer.figcanvas.fig:
if self._right_clicked_thumbnail is None:
widget.figviewer.figcanvas.copy_figure()
else:
self._right_clicked_thumbnail.canvas.copy_figure()
# Reset the toolbar buttons to use the figviewer and not the thumbnail
# selection
self._right_clicked_thumbnail = None
def add_plot(self, fig, fmt, shellwidget):
"""
Add a plot to the figure browser with the given shellwidget, if any.
"""
fig_browser = self.get_widget_for_shellwidget(shellwidget)
if fig_browser and not self.is_current_widget_error_message():
fig_browser.add_figure(fig, fmt)
def remove_plot(self):
"""
Remove currently active plot or plot selected to be removed with
context menu in the thumbnails scrollbar.
"""
widget = self.current_widget()
if widget:
if self._right_clicked_thumbnail is None:
widget.thumbnails_sb.remove_current_thumbnail()
else:
widget.thumbnails_sb.remove_thumbnail(
self._right_clicked_thumbnail)
# Reset the toolbar buttons to use the figviewer and not the thumbnail
# selection
self._right_clicked_thumbnail = None
self.update_actions()
def remove_all_plots(self):
"""Remove all available plots.."""
widget = self.current_widget()
if widget:
widget.thumbnails_sb.remove_all_thumbnails()
self.update_actions()
def previous_plot(self):
"""Select the previous plot in the thumbnails scrollbar."""
widget = self.current_widget()
if widget:
widget.thumbnails_sb.go_previous_thumbnail()
def next_plot(self):
"""Select the next plot in the thumbnails scrollbar."""
widget = self.current_widget()
if widget:
widget.thumbnails_sb.go_next_thumbnail()
def zoom_in(self):
"""Perform a zoom in on the main figure."""
widget = self.current_widget()
if widget:
with signals_blocked(self.fit_action):
self.fit_action.setChecked(False)
widget.figviewer.auto_fit_plotting = False
widget.zoom_in()
def zoom_out(self):
"""Perform a zoom out on the main figure."""
widget = self.current_widget()
if widget:
with signals_blocked(self.fit_action):
self.fit_action.setChecked(False)
widget.figviewer.auto_fit_plotting = False
widget.zoom_out()
def fit_to_pane(self, state):
"""Fit current plot to the pane size."""
widget = self.current_widget()
if widget:
figviewer = widget.figviewer
if state:
figviewer.auto_fit_plotting = True
figviewer.scale_image()
else:
figviewer.auto_fit_plotting = False
figviewer.zoom_in(to_full_size=True)
| PlotsWidget |
python | python-attrs__attrs | tests/test_validators.py | {
"start": 3429,
"end": 6255
} | class ____:
"""
Tests for `matches_re`.
"""
def test_in_all(self):
"""
validator is in ``__all__``.
"""
assert matches_re.__name__ in validator_module.__all__
def test_match(self):
"""
Silent on matches, raises ValueError on mismatches.
"""
@attr.s
class ReTester:
str_match = attr.ib(validator=matches_re("a|ab"))
ReTester("ab") # shouldn't raise exceptions
with pytest.raises(TypeError):
ReTester(1)
with pytest.raises(ValueError):
ReTester("1")
with pytest.raises(ValueError):
ReTester("a1")
def test_flags(self):
"""
Flags are propagated to the match function.
"""
@attr.s
class MatchTester:
val = attr.ib(validator=matches_re("a", re.IGNORECASE, re.match))
MatchTester("A1") # test flags and using re.match
def test_precompiled_pattern(self):
"""
Pre-compiled patterns are accepted.
"""
pattern = re.compile("a")
@attr.s
class RePatternTester:
val = attr.ib(validator=matches_re(pattern))
RePatternTester("a")
def test_precompiled_pattern_no_flags(self):
"""
A pre-compiled pattern cannot be combined with a 'flags' argument.
"""
pattern = re.compile("")
with pytest.raises(
TypeError, match="can only be used with a string pattern"
):
matches_re(pattern, flags=re.IGNORECASE)
def test_different_func(self):
"""
Changing the match functions works.
"""
@attr.s
class SearchTester:
val = attr.ib(validator=matches_re("a", 0, re.search))
SearchTester("bab") # re.search will match
def test_catches_invalid_func(self):
"""
Invalid match functions are caught.
"""
with pytest.raises(ValueError) as ei:
matches_re("a", 0, lambda: None)
assert (
"'func' must be one of None, fullmatch, match, search."
== ei.value.args[0]
)
@pytest.mark.parametrize(
"func", [None, getattr(re, "fullmatch", None), re.match, re.search]
)
def test_accepts_all_valid_func(self, func):
"""
Every valid match function is accepted.
"""
matches_re("a", func=func)
def test_repr(self):
"""
__repr__ is meaningful.
"""
assert repr(matches_re("a")).startswith(
"<matches_re validator for pattern"
)
def always_pass(_, __, ___):
"""
Toy validator that always passes.
"""
def always_fail(_, __, ___):
"""
Toy validator that always fails.
"""
0 / 0
| TestMatchesRe |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_polymorphic_rel.py | {
"start": 1200,
"end": 64394
} | class ____:
__sparse_driver_backend__ = True
__dialect__ = "default_enhanced"
@classmethod
def setup_mappers(cls):
super().setup_mappers()
global people, engineers, managers, boss
global companies, paperwork, machines
people, engineers, managers, boss, companies, paperwork, machines = (
cls.tables.people,
cls.tables.engineers,
cls.tables.managers,
cls.tables.boss,
cls.tables.companies,
cls.tables.paperwork,
cls.tables.machines,
)
@classmethod
def insert_data(cls, connection):
super().insert_data(connection)
global all_employees, c1_employees, c2_employees
global c1, c2, e1, e2, e3, b1, m1
c1, c2, all_employees, c1_employees, c2_employees = (
cls.c1,
cls.c2,
cls.all_employees,
cls.c1_employees,
cls.c2_employees,
)
e1, e2, e3, b1, m1 = cls.e1, cls.e2, cls.e3, cls.b1, cls.m1
@testing.requires.ctes
def test_cte_clone_issue(self):
"""test #8357"""
sess = fixture_session()
cte = select(Engineer.person_id).cte(name="test_cte")
stmt = (
select(Engineer)
.where(exists().where(Engineer.person_id == cte.c.person_id))
.where(exists().where(Engineer.person_id == cte.c.person_id))
).order_by(Engineer.person_id)
self.assert_compile(
stmt,
"WITH test_cte AS (SELECT engineers.person_id AS person_id "
"FROM people JOIN engineers ON people.person_id = "
"engineers.person_id) SELECT engineers.person_id, "
"people.person_id AS person_id_1, people.company_id, "
"people.name, people.type, engineers.status, "
"engineers.engineer_name, engineers.primary_language FROM people "
"JOIN engineers ON people.person_id = engineers.person_id WHERE "
"(EXISTS (SELECT * FROM test_cte WHERE engineers.person_id = "
"test_cte.person_id)) AND (EXISTS (SELECT * FROM test_cte "
"WHERE engineers.person_id = test_cte.person_id)) "
"ORDER BY engineers.person_id",
)
result = sess.scalars(stmt)
eq_(
result.all(),
[
Engineer(name="dilbert"),
Engineer(name="wally"),
Engineer(name="vlad"),
],
)
def test_loads_at_once(self):
"""
Test that all objects load from the full query, when
with_polymorphic is used.
"""
sess = fixture_session()
def go():
eq_(
sess.query(Person).order_by(Person.person_id).all(),
all_employees,
)
count = {"": 14, "Polymorphic": 9}.get(self.select_type, 10)
self.assert_sql_count(testing.db, go, count)
def test_primary_eager_aliasing_joinedload(self):
# For both joinedload() and subqueryload(), if the original q is
# not loading the subclass table, the joinedload doesn't happen.
sess = fixture_session()
def go():
eq_(
sess.query(Person)
.order_by(Person.person_id)
.options(joinedload(Engineer.machines))[1:3],
all_employees[1:3],
)
count = {"": 6, "Polymorphic": 3}.get(self.select_type, 4)
self.assert_sql_count(testing.db, go, count)
def test_primary_eager_aliasing_subqueryload(self):
# test that subqueryload does not occur because the parent
# row cannot support it
sess = fixture_session()
def go():
eq_(
sess.query(Person)
.order_by(Person.person_id)
.options(subqueryload(Engineer.machines))
.all(),
all_employees,
)
count = {"": 14, "Polymorphic": 7}.get(self.select_type, 8)
self.assert_sql_count(testing.db, go, count)
def test_primary_eager_aliasing_selectinload(self):
# test that selectinload does not occur because the parent
# row cannot support it
sess = fixture_session()
def go():
eq_(
sess.query(Person)
.order_by(Person.person_id)
.options(selectinload(Engineer.machines))
.all(),
all_employees,
)
count = {"": 14, "Polymorphic": 7}.get(self.select_type, 8)
self.assert_sql_count(testing.db, go, count)
def test_primary_eager_aliasing_three_reset_selectable(self):
"""test now related to #7262
See test_primary_eager_aliasing_three_dont_reset_selectable for the
non-reset selectable version.
"""
# assert the JOINs don't over JOIN
sess = fixture_session()
# note selectable=None
wp = with_polymorphic(Person, "*", None)
def go():
eq_(
sess.query(wp)
.order_by(wp.person_id)
.options(joinedload(wp.Engineer.machines))[1:3],
all_employees[1:3],
)
self.assert_sql_count(testing.db, go, 3)
eq_(
sess.scalar(
select(func.count("*")).select_from(
sess.query(wp)
.options(joinedload(wp.Engineer.machines))
.order_by(wp.person_id)
.limit(2)
.offset(1)
.subquery()
)
),
2,
)
def test_get_one(self):
"""
For all mappers, ensure the primary key has been calculated as
just the "person_id" column.
"""
sess = fixture_session()
eq_(
sess.get(Person, e1.person_id),
Engineer(name="dilbert", primary_language="java"),
)
def test_get_two(self):
sess = fixture_session()
eq_(
sess.get(Engineer, e1.person_id),
Engineer(name="dilbert", primary_language="java"),
)
def test_get_three(self):
sess = fixture_session()
eq_(
sess.get(Manager, b1.person_id),
Boss(name="pointy haired boss", golf_swing="fore"),
)
def test_lazyload_related_w_cache_check(self):
sess = fixture_session()
c1 = sess.get(Company, 1)
c2 = sess.get(Company, 2)
q1 = (
sess.query(Person)
.filter(with_parent(c1, Company.employees))
.order_by(Person.person_id)
)
eq_(
q1.all(),
[
Engineer(name="dilbert"),
Engineer(name="wally"),
Boss(name="pointy haired boss"),
Manager(name="dogbert"),
],
)
q2 = (
sess.query(Person)
.filter(with_parent(c2, Company.employees))
.order_by(Person.person_id)
)
eq_(q2.all(), [Engineer(name="vlad")])
def test_multi_join(self):
sess = fixture_session()
e = aliased(Person)
c = aliased(Company)
q = (
sess.query(Company, Person, c, e)
.join(Person, Company.employees)
.join(e, c.employees)
.filter(Person.person_id != e.person_id)
.filter(Person.name == "dilbert")
.filter(e.name == "wally")
)
eq_(q.count(), 1)
eq_(
q.all(),
[
(
Company(company_id=1, name="MegaCorp, Inc."),
Engineer(
status="regular engineer",
engineer_name="dilbert",
name="dilbert",
company_id=1,
primary_language="java",
person_id=1,
type="engineer",
),
Company(company_id=1, name="MegaCorp, Inc."),
Engineer(
status="regular engineer",
engineer_name="wally",
name="wally",
company_id=1,
primary_language="c++",
person_id=2,
type="engineer",
),
)
],
)
def test_multi_join_future(self):
sess = fixture_session(future=True)
e = aliased(Person)
c = aliased(Company)
q = (
select(Company, Person, c, e)
.join(Person, Company.employees)
.join(e, c.employees)
.filter(Person.person_id != e.person_id)
.filter(Person.name == "dilbert")
.filter(e.name == "wally")
)
eq_(
sess.execute(
select(func.count()).select_from(q.subquery())
).scalar(),
1,
)
eq_(
sess.execute(q).all(),
[
(
Company(company_id=1, name="MegaCorp, Inc."),
Engineer(
status="regular engineer",
engineer_name="dilbert",
name="dilbert",
company_id=1,
primary_language="java",
person_id=1,
type="engineer",
),
Company(company_id=1, name="MegaCorp, Inc."),
Engineer(
status="regular engineer",
engineer_name="wally",
name="wally",
company_id=1,
primary_language="c++",
person_id=2,
type="engineer",
),
)
],
)
def test_filter_on_subclass_one(self):
sess = fixture_session()
eq_(sess.query(Engineer).all()[0], Engineer(name="dilbert"))
def test_filter_on_subclass_one_future(self):
sess = fixture_session(future=True)
eq_(
sess.execute(select(Engineer)).scalar(),
Engineer(name="dilbert"),
)
def test_filter_on_subclass_two(self):
sess = fixture_session()
eq_(sess.query(Engineer).first(), Engineer(name="dilbert"))
def test_filter_on_subclass_three(self):
sess = fixture_session()
eq_(
sess.query(Engineer)
.filter(Engineer.person_id == e1.person_id)
.first(),
Engineer(name="dilbert"),
)
def test_filter_on_subclass_four(self):
sess = fixture_session()
eq_(
sess.query(Manager)
.filter(Manager.person_id == m1.person_id)
.one(),
Manager(name="dogbert"),
)
def test_filter_on_subclass_five(self):
sess = fixture_session()
eq_(
sess.query(Manager)
.filter(Manager.person_id == b1.person_id)
.one(),
Boss(name="pointy haired boss"),
)
def test_filter_on_subclass_six(self):
sess = fixture_session()
eq_(
sess.query(Boss).filter(Boss.person_id == b1.person_id).one(),
Boss(name="pointy haired boss"),
)
def test_join_from_polymorphic_nonaliased_one(self):
sess = fixture_session()
eq_(
sess.query(Person)
.join(Person.paperwork)
.filter(Paperwork.description.like("%review%"))
.all(),
[b1, m1],
)
def test_join_from_polymorphic_nonaliased_one_future(self):
sess = fixture_session(future=True)
eq_(
sess.execute(
select(Person)
.join(Person.paperwork)
.filter(Paperwork.description.like("%review%"))
)
.unique()
.scalars()
.all(),
[b1, m1],
)
def test_join_from_polymorphic_nonaliased_two(self):
sess = fixture_session()
eq_(
sess.query(Person)
.order_by(Person.person_id)
.join(Person.paperwork)
.filter(Paperwork.description.like("%#2%"))
.all(),
[e1, m1],
)
def test_join_from_polymorphic_nonaliased_three(self):
sess = fixture_session()
eq_(
sess.query(Engineer)
.order_by(Person.person_id)
.join(Person.paperwork)
.filter(Paperwork.description.like("%#2%"))
.all(),
[e1],
)
def test_join_from_polymorphic_nonaliased_four(self):
sess = fixture_session()
eq_(
sess.query(Person)
.order_by(Person.person_id)
.join(Person.paperwork)
.filter(Person.name.like("%dog%"))
.filter(Paperwork.description.like("%#2%"))
.all(),
[m1],
)
def test_join_from_polymorphic_aliased_one_future(self):
sess = fixture_session(future=True)
pa = aliased(Paperwork)
eq_(
sess.execute(
select(Person)
.order_by(Person.person_id)
.join(Person.paperwork.of_type(pa))
.filter(pa.description.like("%review%"))
)
.unique()
.scalars()
.all(),
[b1, m1],
)
def test_join_from_polymorphic_explicit_aliased_one(self):
sess = fixture_session()
pa = aliased(Paperwork)
eq_(
sess.query(Person)
.order_by(Person.person_id)
.join(pa, Person.paperwork)
.filter(pa.description.like("%review%"))
.all(),
[b1, m1],
)
def test_join_from_polymorphic_explicit_aliased_two(self):
sess = fixture_session()
pa = aliased(Paperwork)
eq_(
sess.query(Person)
.order_by(Person.person_id)
.join(pa, Person.paperwork)
.filter(pa.description.like("%#2%"))
.all(),
[e1, m1],
)
def test_join_from_polymorphic_explicit_aliased_three(self):
sess = fixture_session()
pa = aliased(Paperwork)
eq_(
sess.query(Engineer)
.order_by(Person.person_id)
.join(pa, Person.paperwork)
.filter(pa.description.like("%#2%"))
.all(),
[e1],
)
def test_join_from_polymorphic_aliased_four(self):
sess = fixture_session()
pa = aliased(Paperwork)
eq_(
sess.query(Person)
.order_by(Person.person_id)
.join(pa, Person.paperwork)
.filter(Person.name.like("%dog%"))
.filter(pa.description.like("%#2%"))
.all(),
[m1],
)
def test_join_from_with_polymorphic_nonaliased_one_future(self):
sess = fixture_session(future=True)
pm = with_polymorphic(Person, [Manager])
eq_(
sess.execute(
select(pm)
.order_by(pm.person_id)
.join(pm.paperwork)
.filter(Paperwork.description.like("%review%"))
)
.unique()
.scalars()
.all(),
[b1, m1],
)
def test_join_from_with_polymorphic_nonaliased_two_future(self):
sess = fixture_session()
wp = with_polymorphic(Person, [Manager, Engineer])
eq_(
sess.query(wp)
.order_by(wp.person_id)
.join(wp.paperwork)
.filter(Paperwork.description.like("%#2%"))
.all(),
[e1, m1],
)
def test_join_from_with_polymorphic_nonaliased_three_future(self):
sess = fixture_session()
wp = with_polymorphic(Person, [Manager, Engineer])
eq_(
sess.query(wp)
.order_by(wp.person_id)
.join(wp.paperwork)
.filter(wp.name.like("%dog%"))
.filter(Paperwork.description.like("%#2%"))
.all(),
[m1],
)
def test_join_from_with_polymorphic_explicit_aliased_one_future(self):
sess = fixture_session()
pa = aliased(Paperwork)
wp = with_polymorphic(Person, [Manager])
eq_(
sess.query(wp)
.join(pa, wp.paperwork)
.filter(pa.description.like("%review%"))
.all(),
[b1, m1],
)
def test_join_from_with_polymorphic_explicit_aliased_two_future(self):
sess = fixture_session()
pa = aliased(Paperwork)
wp = with_polymorphic(Person, [Manager, Engineer])
eq_(
sess.query(wp)
.order_by(wp.person_id)
.join(pa, wp.paperwork)
.filter(pa.description.like("%#2%"))
.all(),
[e1, m1],
)
def test_join_from_with_polymorphic_ot_explicit_aliased_two_future(self):
sess = fixture_session()
pa = aliased(Paperwork)
wp = with_polymorphic(Person, [Manager, Engineer])
eq_(
sess.query(wp)
.order_by(wp.person_id)
.join(wp.paperwork.of_type(pa))
.filter(pa.description.like("%#2%"))
.all(),
[e1, m1],
)
def test_join_from_with_polymorphic_aliased_three_future(self):
sess = fixture_session()
pa = aliased(Paperwork)
wp = with_polymorphic(Person, [Manager, Engineer])
eq_(
sess.query(wp)
.order_by(wp.person_id)
.join(pa, wp.paperwork)
.filter(wp.name.like("%dog%"))
.filter(pa.description.like("%#2%"))
.all(),
[m1],
)
def test_join_from_with_polymorphic_ot_aliased_three_future(self):
sess = fixture_session()
pa = aliased(Paperwork)
wp = with_polymorphic(Person, [Manager, Engineer])
eq_(
sess.query(wp)
.order_by(wp.person_id)
.join(wp.paperwork.of_type(pa))
.filter(wp.name.like("%dog%"))
.filter(pa.description.like("%#2%"))
.all(),
[m1],
)
def test_join_to_polymorphic_nonaliased(self):
sess = fixture_session()
eq_(
sess.query(Company)
.join(Company.employees)
.filter(Person.name == "vlad")
.one(),
c2,
)
def test_join_to_polymorphic_explicit_aliased(self):
sess = fixture_session()
ea = aliased(Person)
eq_(
sess.query(Company)
.join(ea, Company.employees)
.filter(ea.name == "vlad")
.one(),
c2,
)
def test_polymorphic_any_one(self):
sess = fixture_session()
any_ = Company.employees.any(Person.name == "vlad")
eq_(sess.query(Company).filter(any_).all(), [c2])
def test_polymorphic_any_explicit_alias_two(self):
sess = fixture_session()
# test that the aliasing on "Person" does not bleed into the
# EXISTS clause generated by any()
any_ = Company.employees.any(Person.name == "wally")
ea = aliased(Person)
eq_(
sess.query(Company)
.join(ea, Company.employees)
.filter(ea.name == "dilbert")
.filter(any_)
.all(),
[c1],
)
def test_polymorphic_any_three(self):
sess = fixture_session()
any_ = Company.employees.any(Person.name == "vlad")
ea = aliased(Person)
eq_(
sess.query(Company)
.join(ea, Company.employees)
.filter(ea.name == "dilbert")
.filter(any_)
.all(),
[],
)
def test_polymorphic_any_eight(self):
sess = fixture_session()
any_ = Engineer.machines.any(Machine.name == "Commodore 64")
eq_(
sess.query(Person).order_by(Person.person_id).filter(any_).all(),
[e2, e3],
)
def test_polymorphic_any_nine(self):
sess = fixture_session()
any_ = Person.paperwork.any(Paperwork.description == "review #2")
eq_(
sess.query(Person).order_by(Person.person_id).filter(any_).all(),
[m1],
)
def test_join_from_columns_or_subclass_one(self):
sess = fixture_session()
expected = [("dogbert",), ("pointy haired boss",)]
eq_(sess.query(Manager.name).order_by(Manager.name).all(), expected)
def test_join_from_columns_or_subclass_two(self):
sess = fixture_session()
expected = [("dogbert",), ("dogbert",), ("pointy haired boss",)]
eq_(
sess.query(Manager.name)
.join(Paperwork, Manager.paperwork)
.order_by(Manager.name)
.all(),
expected,
)
def test_join_from_columns_or_subclass_three(self):
sess = fixture_session()
expected = [
("dilbert",),
("dilbert",),
("dogbert",),
("dogbert",),
("pointy haired boss",),
("vlad",),
("wally",),
("wally",),
]
eq_(
sess.query(Person.name)
.join(Paperwork, Person.paperwork)
.order_by(Person.name)
.all(),
expected,
)
def test_join_from_columns_or_subclass_four(self):
sess = fixture_session()
# Load Person.name, joining from Person -> paperwork, get all
# the people.
expected = [
("dilbert",),
("dilbert",),
("dogbert",),
("dogbert",),
("pointy haired boss",),
("vlad",),
("wally",),
("wally",),
]
eq_(
sess.query(Person.name)
.join(paperwork, Person.person_id == paperwork.c.person_id)
.order_by(Person.name)
.all(),
expected,
)
def test_join_from_columns_or_subclass_five(self):
sess = fixture_session()
# same, on manager. get only managers.
expected = [("dogbert",), ("dogbert",), ("pointy haired boss",)]
eq_(
sess.query(Manager.name)
.join(paperwork, Manager.person_id == paperwork.c.person_id)
.order_by(Person.name)
.all(),
expected,
)
def test_join_from_columns_or_subclass_six(self):
sess = fixture_session()
if self.select_type == "":
# this now raises, due to [ticket:1892]. Manager.person_id
# is now the "person_id" column on Manager. SQL is incorrect.
assert_raises(
sa_exc.DBAPIError,
sess.query(Person.name)
.join(paperwork, Manager.person_id == paperwork.c.person_id)
.order_by(Person.name)
.all,
)
elif self.select_type == "Unions":
# with the union, not something anyone would really be using
# here, it joins to the full result set. This is 0.6's
# behavior and is more or less wrong.
expected = [
("dilbert",),
("dilbert",),
("dogbert",),
("dogbert",),
("pointy haired boss",),
("vlad",),
("wally",),
("wally",),
]
eq_(
sess.query(Person.name)
.join(paperwork, Manager.person_id == paperwork.c.person_id)
.order_by(Person.name)
.all(),
expected,
)
else:
# when a join is present and managers.person_id is available,
# you get the managers.
expected = [("dogbert",), ("dogbert",), ("pointy haired boss",)]
eq_(
sess.query(Person.name)
.join(paperwork, Manager.person_id == paperwork.c.person_id)
.order_by(Person.name)
.all(),
expected,
)
def test_join_from_columns_or_subclass_seven(self):
sess = fixture_session()
eq_(
sess.query(Manager)
.join(Paperwork, Manager.paperwork)
.order_by(Manager.name)
.all(),
[m1, b1],
)
def test_join_from_columns_or_subclass_eight(self):
sess = fixture_session()
expected = [("dogbert",), ("dogbert",), ("pointy haired boss",)]
eq_(
sess.query(Manager.name)
.join(paperwork, Manager.person_id == paperwork.c.person_id)
.order_by(Manager.name)
.all(),
expected,
)
def test_join_from_columns_or_subclass_nine(self):
sess = fixture_session()
eq_(
sess.query(Manager.person_id)
.join(paperwork, Manager.person_id == paperwork.c.person_id)
.order_by(Manager.name)
.all(),
[(4,), (4,), (3,)],
)
def test_join_from_columns_or_subclass_ten(self):
sess = fixture_session()
expected = [
("pointy haired boss", "review #1"),
("dogbert", "review #2"),
("dogbert", "review #3"),
]
eq_(
sess.query(Manager.name, Paperwork.description)
.join(Paperwork, Manager.person_id == Paperwork.person_id)
.order_by(Paperwork.paperwork_id)
.all(),
expected,
)
def test_join_from_columns_or_subclass_eleven(self):
sess = fixture_session()
expected = [("pointy haired boss",), ("dogbert",), ("dogbert",)]
malias = aliased(Manager)
eq_(
sess.query(malias.name)
.join(paperwork, malias.person_id == paperwork.c.person_id)
.all(),
expected,
)
def test_subclass_option_pathing(self):
sess = fixture_session()
dilbert = (
sess.query(Person)
.options(defaultload(Engineer.machines).defer(Machine.name))
.filter(Person.name == "dilbert")
.first()
)
m = dilbert.machines[0]
assert "name" not in m.__dict__
eq_(m.name, "IBM ThinkPad")
def test_expire(self):
"""
Test that individual column refresh doesn't get tripped up by
the select_table mapper.
"""
sess = fixture_session()
name = "dogbert"
m1 = sess.query(Manager).filter(Manager.name == name).one()
sess.expire(m1)
assert m1.status == "regular manager"
name = "pointy haired boss"
m2 = sess.query(Manager).filter(Manager.name == name).one()
sess.expire(m2, ["manager_name", "golf_swing"])
assert m2.golf_swing == "fore"
def test_with_polymorphic_one_future(self):
sess = fixture_session()
def go():
wp = with_polymorphic(Person, [Engineer])
eq_(
sess.query(wp)
.filter(wp.Engineer.primary_language == "java")
.all(),
self._emps_wo_relationships_fixture()[0:1],
)
self.assert_sql_count(testing.db, go, 1)
def test_with_polymorphic_two_future_adhoc_wp(self):
"""test #7262
compare to
test_with_polymorphic_two_future_default_wp
"""
sess = fixture_session()
def go():
wp = with_polymorphic(Person, "*", selectable=None)
eq_(
sess.query(wp).order_by(wp.person_id).all(),
self._emps_wo_relationships_fixture(),
)
self.assert_sql_count(testing.db, go, 1)
def test_with_polymorphic_three_future(self, nocache):
sess = fixture_session()
def go():
wp = with_polymorphic(Person, [Engineer])
eq_(
sess.query(wp).order_by(wp.person_id).all(),
self._emps_wo_relationships_fixture(),
)
self.assert_sql_count(testing.db, go, 3)
def test_with_polymorphic_four_future(self):
sess = fixture_session()
def go():
wp = with_polymorphic(
Person, Engineer, selectable=people.outerjoin(engineers)
)
eq_(
sess.query(wp).order_by(wp.person_id).all(),
self._emps_wo_relationships_fixture(),
)
self.assert_sql_count(testing.db, go, 3)
def test_with_polymorphic_five_future_override_selectable(self):
"""test part of #7262
this is kind of a hack though, people wouldn't know to do this
this way.
"""
sess = fixture_session()
def go():
# needs both [Person] and the selectable=None part
# TODO: why do we need [Person] and can't send []? possible
# bug
wp = with_polymorphic(Person, [Person], selectable=None)
# limit the polymorphic join down to just "Person",
# overriding select_table
eq_(
sess.query(wp).all(),
self._emps_wo_relationships_fixture(),
)
self.assert_sql_count(testing.db, go, 6)
def test_with_polymorphic_six_future(self):
assert_raises(
sa_exc.InvalidRequestError, with_polymorphic, Person, [Paperwork]
)
assert_raises(
sa_exc.InvalidRequestError, with_polymorphic, Engineer, [Boss]
)
assert_raises(
sa_exc.InvalidRequestError, with_polymorphic, Engineer, [Person]
)
def test_with_polymorphic_seven_future(self):
sess = fixture_session()
# compare to entities without related collections to prevent
# additional lazy SQL from firing on loaded entities
wp = with_polymorphic(Person, "*")
eq_(
sess.query(wp).order_by(wp.person_id).all(),
self._emps_wo_relationships_fixture(),
)
def test_relationship_to_polymorphic_one(self):
expected = self._company_with_emps_machines_fixture()
sess = fixture_session()
def go():
# test load Companies with lazy load to 'employees'
eq_(sess.query(Company).all(), expected)
count = {"": 10, "Polymorphic": 5}.get(self.select_type, 6)
self.assert_sql_count(testing.db, go, count)
def test_relationship_to_polymorphic_two(self):
expected = self._company_with_emps_machines_fixture()
sess = fixture_session()
def go():
# with #2438, of_type() is recognized. This
# overrides the with_polymorphic of the mapper
# and we get a consistent 3 queries now.
eq_(
sess.query(Company)
.options(
joinedload(Company.employees.of_type(Engineer)).joinedload(
Engineer.machines
)
)
.all(),
expected,
)
# in the old case, we would get this
# count = {'':7, 'Polymorphic':1}.get(self.select_type, 2)
# query one is company->Person/Engineer->Machines
# query two is managers + boss for row #3
# query three is managers for row #4
count = 3
self.assert_sql_count(testing.db, go, count)
def test_relationship_to_polymorphic_three(self):
expected = self._company_with_emps_machines_fixture()
sess = fixture_session()
sess = fixture_session()
def go():
eq_(
sess.query(Company)
.options(
subqueryload(
Company.employees.of_type(Engineer)
).subqueryload(Engineer.machines)
)
.all(),
expected,
)
# the old case where subqueryload_all
# didn't work with of_tyoe
# count = { '':8, 'Joins':4, 'Unions':4, 'Polymorphic':3,
# 'AliasedJoins':4}[self.select_type]
# query one is company->Person/Engineer->Machines
# query two is Person/Engineer subq
# query three is Machines subq
# (however this test can't tell if the Q was a
# lazyload or subqload ...)
# query four is managers + boss for row #3
# query five is managers for row #4
count = 5
self.assert_sql_count(testing.db, go, count)
def test_joinedload_on_subclass(self):
sess = fixture_session()
expected = [
Engineer(
name="dilbert",
engineer_name="dilbert",
primary_language="java",
status="regular engineer",
machines=[
Machine(name="IBM ThinkPad"),
Machine(name="IPhone"),
],
)
]
def go():
# test load People with joinedload to engineers + machines
wp = with_polymorphic(Person, "*")
eq_(
sess.query(wp)
.options(joinedload(wp.Engineer.machines))
.filter(wp.name == "dilbert")
.all(),
expected,
)
self.assert_sql_count(testing.db, go, 1)
def test_subqueryload_on_subclass(self):
sess = fixture_session()
expected = [
Engineer(
name="dilbert",
engineer_name="dilbert",
primary_language="java",
status="regular engineer",
machines=[
Machine(name="IBM ThinkPad"),
Machine(name="IPhone"),
],
)
]
def go():
wp = with_polymorphic(Person, "*")
eq_(
sess.query(wp)
.options(subqueryload(wp.Engineer.machines))
.filter(wp.name == "dilbert")
.all(),
expected,
)
self.assert_sql_count(testing.db, go, 2)
def test_query_subclass_join_to_base_relationship(self):
sess = fixture_session()
# non-polymorphic
eq_(sess.query(Engineer).join(Person.paperwork).all(), [e1, e2, e3])
def test_join_to_subclass_manual_alias(self):
sess = fixture_session()
target = aliased(Engineer, people.join(engineers))
eq_(
sess.query(Company)
.join(Company.employees.of_type(target))
.filter(target.primary_language == "java")
.all(),
[c1],
)
def test_join_to_subclass_one(self):
sess = fixture_session()
eq_(
sess.query(Company)
.select_from(companies.join(people).join(engineers))
.filter(Engineer.primary_language == "java")
.all(),
[c1],
)
def test_join_to_subclass_three(self):
sess = fixture_session()
ealias = aliased(Engineer)
eq_(
sess.query(Company)
.join(ealias, Company.employees)
.filter(ealias.primary_language == "java")
.all(),
[c1],
)
def test_join_to_subclass_six(self):
sess = fixture_session()
eq_(
sess.query(Company)
.join(Company.employees.of_type(Engineer))
.join(Engineer.machines)
.all(),
[c1, c2],
)
def test_join_to_subclass_six_point_five(self):
sess = fixture_session()
q = (
sess.query(Company)
.join(Company.employees.of_type(Engineer))
.join(Engineer.machines)
.filter(Engineer.name == "dilbert")
)
self.assert_compile(
q,
"SELECT companies.company_id AS companies_company_id, "
"companies.name AS companies_name FROM companies JOIN "
"(people JOIN engineers ON people.person_id = "
"engineers.person_id) ON "
"companies.company_id = people.company_id "
"JOIN machines ON engineers.person_id = machines.engineer_id "
"WHERE people.name = :name_1",
)
eq_(
q.all(),
[c1],
)
def test_join_to_subclass_eight(self):
sess = fixture_session()
eq_(sess.query(Person).join(Engineer.machines).all(), [e1, e2, e3])
def test_join_to_subclass_nine(self):
sess = fixture_session()
eq_(
sess.query(Company)
.select_from(companies.join(people).join(engineers))
.filter(Engineer.primary_language == "java")
.all(),
[c1],
)
def test_join_to_subclass_ten(self):
sess = fixture_session()
eq_(
sess.query(Company)
.join(Company.employees)
.filter(Engineer.primary_language == "java")
.all(),
[c1],
)
def test_join_to_subclass_eleven(self):
sess = fixture_session()
eq_(
sess.query(Company)
.select_from(companies.join(people).join(engineers))
.filter(Engineer.primary_language == "java")
.all(),
[c1],
)
def test_join_to_subclass_twelve(self):
sess = fixture_session()
eq_(sess.query(Person).join(Engineer.machines).all(), [e1, e2, e3])
def test_join_to_subclass_thirteen(self):
sess = fixture_session()
eq_(
sess.query(Person)
.join(Engineer.machines)
.filter(Machine.name.ilike("%ibm%"))
.all(),
[e1, e3],
)
def test_join_to_subclass_fourteen(self):
sess = fixture_session()
eq_(
sess.query(Company)
.join(Company.employees)
.join(Engineer.machines)
.all(),
[c1, c2],
)
def test_join_to_subclass_fifteen(self):
sess = fixture_session()
eq_(
sess.query(Company)
.join(Company.employees)
.join(Engineer.machines)
.filter(Machine.name.ilike("%thinkpad%"))
.all(),
[c1],
)
def test_join_to_subclass_sixteen(self):
sess = fixture_session()
# non-polymorphic
eq_(sess.query(Engineer).join(Engineer.machines).all(), [e1, e2, e3])
def test_join_to_subclass_seventeen(self):
sess = fixture_session()
eq_(
sess.query(Engineer)
.join(Engineer.machines)
.filter(Machine.name.ilike("%ibm%"))
.all(),
[e1, e3],
)
def test_join_and_thru_polymorphic_nonaliased_one(self):
sess = fixture_session()
eq_(
sess.query(Company)
.join(Company.employees)
.join(Person.paperwork.and_(Paperwork.description.like("%#2%")))
.all(),
[c1],
)
def test_join_and_thru_polymorphic_aliased_one(self):
sess = fixture_session()
ea = aliased(Person)
pa = aliased(Paperwork)
eq_(
sess.query(Company)
.join(ea, Company.employees)
.join(pa, ea.paperwork.and_(pa.description.like("%#2%")))
.all(),
[c1],
)
def test_join_through_polymorphic_nonaliased_one(self):
sess = fixture_session()
eq_(
sess.query(Company)
.join(Company.employees)
.join(Person.paperwork)
.filter(Paperwork.description.like("%#2%"))
.all(),
[c1],
)
def test_join_through_polymorphic_nonaliased_two(self):
sess = fixture_session()
eq_(
sess.query(Company)
.join(Company.employees)
.join(Person.paperwork)
.filter(Paperwork.description.like("%#%"))
.all(),
[c1, c2],
)
def test_join_through_polymorphic_nonaliased_three(self):
sess = fixture_session()
eq_(
sess.query(Company)
.join(Company.employees)
.join(Person.paperwork)
.filter(Person.name.in_(["dilbert", "vlad"]))
.filter(Paperwork.description.like("%#2%"))
.all(),
[c1],
)
def test_join_through_polymorphic_nonaliased_four(self):
sess = fixture_session()
eq_(
sess.query(Company)
.join(Company.employees)
.join(Person.paperwork)
.filter(Person.name.in_(["dilbert", "vlad"]))
.filter(Paperwork.description.like("%#%"))
.all(),
[c1, c2],
)
def test_join_through_polymorphic_nonaliased_five(self):
sess = fixture_session()
eq_(
sess.query(Company)
.join(Company.employees)
.filter(Person.name.in_(["dilbert", "vlad"]))
.join(Person.paperwork)
.filter(Paperwork.description.like("%#2%"))
.all(),
[c1],
)
def test_join_through_polymorphic_nonaliased_six(self):
sess = fixture_session()
eq_(
sess.query(Company)
.join(Company.employees)
.filter(Person.name.in_(["dilbert", "vlad"]))
.join(Person.paperwork)
.filter(Paperwork.description.like("%#%"))
.all(),
[c1, c2],
)
def test_join_through_polymorphic_aliased_one(self):
sess = fixture_session()
ea = aliased(Person)
pa = aliased(Paperwork)
eq_(
sess.query(Company)
.join(ea, Company.employees)
.join(pa, ea.paperwork)
.filter(pa.description.like("%#2%"))
.all(),
[c1],
)
def test_join_through_polymorphic_aliased_two(self):
sess = fixture_session()
ea = aliased(Person)
pa = aliased(Paperwork)
eq_(
sess.query(Company)
.join(ea, Company.employees)
.join(pa, ea.paperwork)
.filter(pa.description.like("%#%"))
.all(),
[c1, c2],
)
def test_join_through_polymorphic_aliased_three(self):
sess = fixture_session()
ea = aliased(Person)
pa = aliased(Paperwork)
eq_(
sess.query(Company)
.join(ea, Company.employees)
.join(pa, ea.paperwork)
.filter(ea.name.in_(["dilbert", "vlad"]))
.filter(pa.description.like("%#2%"))
.all(),
[c1],
)
def test_join_through_polymorphic_aliased_four(self):
sess = fixture_session()
ea = aliased(Person)
pa = aliased(Paperwork)
eq_(
sess.query(Company)
.join(ea, Company.employees)
.join(pa, ea.paperwork) # we can't use "paperwork" here?
.filter(ea.name.in_(["dilbert", "vlad"]))
.filter(pa.description.like("%#%"))
.all(),
[c1, c2],
)
def test_join_through_polymorphic_aliased_five(self):
sess = fixture_session()
ea = aliased(Person)
pa = aliased(Paperwork)
eq_(
sess.query(Company)
.join(ea, Company.employees)
.filter(ea.name.in_(["dilbert", "vlad"]))
.join(pa, ea.paperwork)
.filter(pa.description.like("%#2%"))
.all(),
[c1],
)
def test_join_through_polymorphic_aliased_six(self):
sess = fixture_session()
pa = aliased(Paperwork)
ea = aliased(Person)
eq_(
sess.query(Company)
.join(ea, Company.employees)
.filter(ea.name.in_(["dilbert", "vlad"]))
.join(pa, ea.paperwork)
.filter(pa.description.like("%#%"))
.all(),
[c1, c2],
)
def test_explicit_polymorphic_join_one(self):
sess = fixture_session()
# join from Company to Engineer; join condition formulated by
# ORMJoin using regular table foreign key connections. Engineer
# is expressed as "(select * people join engineers) as anon_1"
# so the join is contained.
eq_(
sess.query(Company)
.join(Engineer)
.filter(Engineer.engineer_name == "vlad")
.one(),
c2,
)
def test_explicit_polymorphic_join_two(self):
sess = fixture_session()
# same, using explicit join condition. Query.join() must
# adapt the on clause here to match the subquery wrapped around
# "people join engineers".
eq_(
sess.query(Company)
.join(Engineer, Company.company_id == Engineer.company_id)
.filter(Engineer.engineer_name == "vlad")
.one(),
c2,
)
def test_filter_on_baseclass(self):
sess = fixture_session()
eq_(sess.query(Person).order_by(Person.person_id).all(), all_employees)
eq_(
sess.query(Person).order_by(Person.person_id).first(),
all_employees[0],
)
eq_(
sess.query(Person)
.order_by(Person.person_id)
.filter(Person.person_id == e2.person_id)
.one(),
e2,
)
def test_from_alias(self):
sess = fixture_session()
palias = aliased(Person)
eq_(
sess.query(palias)
.order_by(palias.person_id)
.filter(palias.name.in_(["dilbert", "wally"]))
.all(),
[e1, e2],
)
def test_self_referential_one(self):
sess = fixture_session()
palias = aliased(Person)
expected = [(m1, e1), (m1, e2), (m1, b1)]
eq_(
sess.query(Person, palias)
.filter(Person.company_id == palias.company_id)
.filter(Person.name == "dogbert")
.filter(Person.person_id > palias.person_id)
.order_by(Person.person_id, palias.person_id)
.all(),
expected,
)
def test_self_referential_two_future(self):
# TODO: this is the SECOND test *EVER* of an aliased class of
# an aliased class.
sess = fixture_session(future=True)
expected = [(m1, e1), (m1, e2), (m1, b1)]
# not aliasing the first class
p1 = Person
p2 = aliased(Person)
stmt = (
select(p1, p2)
.filter(p1.company_id == p2.company_id)
.filter(p1.name == "dogbert")
.filter(p1.person_id > p2.person_id)
)
subq = stmt.subquery()
pa1 = aliased(p1, subq)
pa2 = aliased(p2, subq)
stmt2 = select(pa1, pa2).order_by(pa1.person_id, pa2.person_id)
eq_(
sess.execute(stmt2).unique().all(),
expected,
)
def test_self_referential_two_point_five_future(self):
# TODO: this is the first test *EVER* of an aliased class of
# an aliased class. we should add many more tests for this.
# new case added in Id810f485c5f7ed971529489b84694e02a3356d6d
sess = fixture_session(future=True)
expected = [(m1, e1), (m1, e2), (m1, b1)]
# aliasing the first class
p1 = aliased(Person)
p2 = aliased(Person)
stmt = (
select(p1, p2)
.filter(p1.company_id == p2.company_id)
.filter(p1.name == "dogbert")
.filter(p1.person_id > p2.person_id)
)
subq = stmt.subquery()
pa1 = aliased(p1, subq)
pa2 = aliased(p2, subq)
stmt2 = select(pa1, pa2).order_by(pa1.person_id, pa2.person_id)
eq_(
sess.execute(stmt2).unique().all(),
expected,
)
def test_nesting_queries(self):
# query.statement places a flag "no_adapt" on the returned
# statement. This prevents the polymorphic adaptation in the
# second "filter" from hitting it, which would pollute the
# subquery and usually results in recursion overflow errors
# within the adaption.
sess = fixture_session()
subq = (
sess.query(engineers.c.person_id)
.filter(Engineer.primary_language == "java")
.statement.scalar_subquery()
)
eq_(sess.query(Person).filter(Person.person_id.in_(subq)).one(), e1)
def test_mixed_entities_one(self):
sess = fixture_session()
expected = [
(
Engineer(
status="regular engineer",
engineer_name="dilbert",
name="dilbert",
company_id=1,
primary_language="java",
person_id=1,
type="engineer",
),
"MegaCorp, Inc.",
),
(
Engineer(
status="regular engineer",
engineer_name="wally",
name="wally",
company_id=1,
primary_language="c++",
person_id=2,
type="engineer",
),
"MegaCorp, Inc.",
),
(
Engineer(
status="elbonian engineer",
engineer_name="vlad",
name="vlad",
company_id=2,
primary_language="cobol",
person_id=5,
type="engineer",
),
"Elbonia, Inc.",
),
]
eq_(
sess.query(Engineer, Company.name)
.join(Company.employees)
.order_by(Person.person_id)
.filter(Person.type == "engineer")
.all(),
expected,
)
def _join_to_poly_wp_one(self, sess):
wp = with_polymorphic(self.classes.Person, "*")
return (
sess.query(wp.name, self.classes.Company.name)
.join(self.classes.Company.employees.of_type(wp))
.order_by(wp.person_id)
)
def _join_to_poly_wp_two(self, sess):
wp = with_polymorphic(self.classes.Person, "*", aliased=True)
return (
sess.query(wp.name, self.classes.Company.name)
.join(self.classes.Company.employees.of_type(wp))
.order_by(wp.person_id)
)
def _join_to_poly_wp_three(self, sess):
wp = with_polymorphic(
self.classes.Person, "*", aliased=True, flat=True
)
return (
sess.query(wp.name, self.classes.Company.name)
.join(self.classes.Company.employees.of_type(wp))
.order_by(wp.person_id)
)
@testing.combinations(
lambda self, sess: (
sess.query(self.classes.Person.name, self.classes.Company.name)
.join(self.classes.Company.employees)
.order_by(self.classes.Person.person_id)
),
_join_to_poly_wp_one,
_join_to_poly_wp_two,
_join_to_poly_wp_three,
)
def test_mixed_entities_join_to_poly(self, q):
sess = fixture_session()
expected = [
("dilbert", "MegaCorp, Inc."),
("wally", "MegaCorp, Inc."),
("pointy haired boss", "MegaCorp, Inc."),
("dogbert", "MegaCorp, Inc."),
("vlad", "Elbonia, Inc."),
]
eq_(
q(self, sess).all(),
expected,
)
def test_mixed_entities_two(self):
sess = fixture_session()
expected = [
("java", "MegaCorp, Inc."),
("cobol", "Elbonia, Inc."),
("c++", "MegaCorp, Inc."),
]
eq_(
sess.query(Engineer.primary_language, Company.name)
.join(Company.employees)
.filter(Person.type == "engineer")
.order_by(desc(Engineer.primary_language))
.all(),
expected,
)
def test_mixed_entities_three(self):
sess = fixture_session()
palias = aliased(Person)
expected = [
(
Engineer(
status="elbonian engineer",
engineer_name="vlad",
name="vlad",
primary_language="cobol",
),
"Elbonia, Inc.",
Engineer(
status="regular engineer",
engineer_name="dilbert",
name="dilbert",
company_id=1,
primary_language="java",
person_id=1,
type="engineer",
),
)
]
eq_(
sess.query(Person, Company.name, palias)
.join(Company.employees)
.filter(Company.name == "Elbonia, Inc.")
.filter(palias.name == "dilbert")
.filter(palias.person_id != Person.person_id)
.all(),
expected,
)
def test_mixed_entities_four(self):
sess = fixture_session()
palias = aliased(Person)
expected = [
(
Engineer(
status="regular engineer",
engineer_name="dilbert",
name="dilbert",
company_id=1,
primary_language="java",
person_id=1,
type="engineer",
),
"Elbonia, Inc.",
Engineer(
status="elbonian engineer",
engineer_name="vlad",
name="vlad",
primary_language="cobol",
),
)
]
eq_(
sess.query(palias, Company.name, Person)
.select_from(join(palias, Company, true()))
.join(Company.employees)
.filter(Company.name == "Elbonia, Inc.")
.filter(palias.name == "dilbert")
.all(),
expected,
)
def test_mixed_entities_five(self):
sess = fixture_session()
palias = aliased(Person)
expected = [("vlad", "Elbonia, Inc.", "dilbert")]
eq_(
sess.query(Person.name, Company.name, palias.name)
.join(Company.employees)
.filter(Company.name == "Elbonia, Inc.")
.filter(palias.name == "dilbert")
.filter(palias.company_id != Person.company_id)
.all(),
expected,
)
def test_mixed_entities_six(self):
sess = fixture_session()
palias = aliased(Person)
expected = [
("manager", "dogbert", "engineer", "dilbert"),
("manager", "dogbert", "engineer", "wally"),
("manager", "dogbert", "boss", "pointy haired boss"),
]
eq_(
sess.query(Person.type, Person.name, palias.type, palias.name)
.filter(Person.company_id == palias.company_id)
.filter(Person.name == "dogbert")
.filter(Person.person_id > palias.person_id)
.order_by(Person.person_id, palias.person_id)
.all(),
expected,
)
def test_mixed_entities_seven(self):
sess = fixture_session()
expected = [
("dilbert", "tps report #1"),
("dilbert", "tps report #2"),
("dogbert", "review #2"),
("dogbert", "review #3"),
("pointy haired boss", "review #1"),
("vlad", "elbonian missive #3"),
("wally", "tps report #3"),
("wally", "tps report #4"),
]
eq_(
sess.query(Person.name, Paperwork.description)
.filter(Person.person_id == Paperwork.person_id)
.order_by(Person.name, Paperwork.description)
.all(),
expected,
)
def test_mixed_entities_eight(self):
sess = fixture_session()
eq_(
sess.query(func.count(Person.person_id))
.filter(Engineer.primary_language == "java")
.all(),
[(1,)],
)
def test_mixed_entities_nine(self):
sess = fixture_session()
expected = [("Elbonia, Inc.", 1), ("MegaCorp, Inc.", 4)]
eq_(
sess.query(Company.name, func.count(Person.person_id))
.filter(Company.company_id == Person.company_id)
.group_by(Company.name)
.order_by(Company.name)
.all(),
expected,
)
def test_mixed_entities_ten(self):
sess = fixture_session()
expected = [("Elbonia, Inc.", 1), ("MegaCorp, Inc.", 4)]
eq_(
sess.query(Company.name, func.count(Person.person_id))
.join(Company.employees)
.group_by(Company.name)
.order_by(Company.name)
.all(),
expected,
)
# def test_mixed_entities(self):
# sess = fixture_session()
# TODO: I think raise error on these for now. different
# inheritance/loading schemes have different results here,
# all incorrect
#
# eq_(
# sess.query(Person.name, Engineer.primary_language).all(),
# [])
# def test_mixed_entities(self):
# sess = fixture_session()
# eq_(sess.query(
# Person.name,
# Engineer.primary_language,
# Manager.manager_name)
# .all(),
# [])
def test_mixed_entities_eleven(self):
sess = fixture_session()
expected = [("java",), ("c++",), ("cobol",)]
eq_(
sess.query(Engineer.primary_language)
.filter(Person.type == "engineer")
.all(),
expected,
)
def test_mixed_entities_twelve(self):
sess = fixture_session()
expected = [("vlad", "Elbonia, Inc.")]
eq_(
sess.query(Person.name, Company.name)
.join(Company.employees)
.filter(Company.name == "Elbonia, Inc.")
.all(),
expected,
)
def test_mixed_entities_thirteen(self):
sess = fixture_session()
expected = [("pointy haired boss", "fore")]
eq_(sess.query(Boss.name, Boss.golf_swing).all(), expected)
def test_mixed_entities_fourteen(self):
sess = fixture_session()
expected = [("dilbert", "java"), ("wally", "c++"), ("vlad", "cobol")]
eq_(
sess.query(Engineer.name, Engineer.primary_language).all(),
expected,
)
def test_mixed_entities_fifteen(self):
sess = fixture_session()
expected = [
(
"Elbonia, Inc.",
Engineer(
status="elbonian engineer",
engineer_name="vlad",
name="vlad",
primary_language="cobol",
),
)
]
eq_(
sess.query(Company.name, Person)
.join(Company.employees)
.filter(Company.name == "Elbonia, Inc.")
.all(),
expected,
)
def test_mixed_entities_sixteen(self):
sess = fixture_session()
expected = [
(
Engineer(
status="elbonian engineer",
engineer_name="vlad",
name="vlad",
primary_language="cobol",
),
"Elbonia, Inc.",
)
]
eq_(
sess.query(Person, Company.name)
.join(Company.employees)
.filter(Company.name == "Elbonia, Inc.")
.all(),
expected,
)
def test_mixed_entities_seventeen(self):
sess = fixture_session()
expected = [("pointy haired boss",), ("dogbert",)]
eq_(sess.query(Manager.name).all(), expected)
def test_mixed_entities_eighteen(self):
sess = fixture_session()
expected = [("pointy haired boss foo",), ("dogbert foo",)]
eq_(sess.query(Manager.name + " foo").all(), expected)
def test_mixed_entities_nineteen(self):
sess = fixture_session()
row = (
sess.query(Engineer.name, Engineer.primary_language)
.filter(Engineer.name == "dilbert")
.first()
)
assert row.name == "dilbert"
assert row.primary_language == "java"
def test_correlation_one(self):
sess = fixture_session()
# this for a long time did not work with PolymorphicAliased and
# PolymorphicUnions, which was due to the no_replacement_traverse
# annotation added to query.statement which then went into
# scalar_subquery(). this is removed as of :ticket:`4304` so now
# works.
eq_(
sess.query(Person.name)
.filter(
sess.query(Company.name)
.filter(Company.company_id == Person.company_id)
.correlate(Person)
.scalar_subquery()
== "Elbonia, Inc."
)
.all(),
[(e3.name,)],
)
def test_correlation_two(self):
sess = fixture_session()
paliased = aliased(Person)
eq_(
sess.query(paliased.name)
.filter(
sess.query(Company.name)
.filter(Company.company_id == paliased.company_id)
.correlate(paliased)
.scalar_subquery()
== "Elbonia, Inc."
)
.all(),
[(e3.name,)],
)
def test_correlation_three(self):
sess = fixture_session()
paliased = aliased(Person, flat=True)
eq_(
sess.query(paliased.name)
.filter(
sess.query(Company.name)
.filter(Company.company_id == paliased.company_id)
.correlate(paliased)
.scalar_subquery()
== "Elbonia, Inc."
)
.all(),
[(e3.name,)],
)
def test_with_polymorphic_named(self):
session = fixture_session()
poly = with_polymorphic(Person, "*", name="poly_name")
res = session.execute(select(poly)).mappings()
eq_(res.keys(), ["poly_name"])
eq_(len(res.all()), 5)
| _PolymorphicTestBase |
python | google__jax | tests/pallas/tpu_pallas_interpret_test.py | {
"start": 1926,
"end": 2079
} | class ____():
"""Represents a grid point and the ID of the core that has processed it."""
grid_point: tuple[int, ...]
core_id: int
| ProcessedGridPoint |
python | pytest-dev__pytest | src/_pytest/doctest.py | {
"start": 16665,
"end": 25478
} | class ____(Module):
def collect(self) -> Iterable[DoctestItem]:
import doctest
class MockAwareDocTestFinder(doctest.DocTestFinder):
py_ver_info_minor = sys.version_info[:2]
is_find_lineno_broken = (
py_ver_info_minor < (3, 11)
or (py_ver_info_minor == (3, 11) and sys.version_info.micro < 9)
or (py_ver_info_minor == (3, 12) and sys.version_info.micro < 3)
)
if is_find_lineno_broken:
def _find_lineno(self, obj, source_lines):
"""On older Pythons, doctest code does not take into account
`@property`. https://github.com/python/cpython/issues/61648
Moreover, wrapped Doctests need to be unwrapped so the correct
line number is returned. #8796
"""
if isinstance(obj, property):
obj = getattr(obj, "fget", obj)
if hasattr(obj, "__wrapped__"):
# Get the main obj in case of it being wrapped
obj = inspect.unwrap(obj)
# Type ignored because this is a private function.
return super()._find_lineno( # type:ignore[misc]
obj,
source_lines,
)
if sys.version_info < (3, 13):
def _from_module(self, module, object):
"""`cached_property` objects are never considered a part
of the 'current module'. As such they are skipped by doctest.
Here we override `_from_module` to check the underlying
function instead. https://github.com/python/cpython/issues/107995
"""
if isinstance(object, functools.cached_property):
object = object.func
# Type ignored because this is a private function.
return super()._from_module(module, object) # type: ignore[misc]
try:
module = self.obj
except Collector.CollectError:
if self.config.getvalue("doctest_ignore_import_errors"):
skip(f"unable to import module {self.path!r}")
else:
raise
# While doctests currently don't support fixtures directly, we still
# need to pick up autouse fixtures.
self.session._fixturemanager.parsefactories(self)
# Uses internal doctest module parsing mechanism.
finder = MockAwareDocTestFinder()
optionflags = get_optionflags(self.config)
runner = _get_runner(
verbose=False,
optionflags=optionflags,
checker=_get_checker(),
continue_on_failure=_get_continue_on_failure(self.config),
)
for test in finder.find(module, module.__name__):
if test.examples: # skip empty doctests
yield DoctestItem.from_parent(
self, name=test.name, runner=runner, dtest=test
)
def _init_checker_class() -> type[doctest.OutputChecker]:
import doctest
class LiteralsOutputChecker(doctest.OutputChecker):
# Based on doctest_nose_plugin.py from the nltk project
# (https://github.com/nltk/nltk) and on the "numtest" doctest extension
# by Sebastien Boisgerault (https://github.com/boisgera/numtest).
_unicode_literal_re = re.compile(r"(\W|^)[uU]([rR]?[\'\"])", re.UNICODE)
_bytes_literal_re = re.compile(r"(\W|^)[bB]([rR]?[\'\"])", re.UNICODE)
_number_re = re.compile(
r"""
(?P<number>
(?P<mantissa>
(?P<integer1> [+-]?\d*)\.(?P<fraction>\d+)
|
(?P<integer2> [+-]?\d+)\.
)
(?:
[Ee]
(?P<exponent1> [+-]?\d+)
)?
|
(?P<integer3> [+-]?\d+)
(?:
[Ee]
(?P<exponent2> [+-]?\d+)
)
)
""",
re.VERBOSE,
)
def check_output(self, want: str, got: str, optionflags: int) -> bool:
if super().check_output(want, got, optionflags):
return True
allow_unicode = optionflags & _get_allow_unicode_flag()
allow_bytes = optionflags & _get_allow_bytes_flag()
allow_number = optionflags & _get_number_flag()
if not allow_unicode and not allow_bytes and not allow_number:
return False
def remove_prefixes(regex: re.Pattern[str], txt: str) -> str:
return re.sub(regex, r"\1\2", txt)
if allow_unicode:
want = remove_prefixes(self._unicode_literal_re, want)
got = remove_prefixes(self._unicode_literal_re, got)
if allow_bytes:
want = remove_prefixes(self._bytes_literal_re, want)
got = remove_prefixes(self._bytes_literal_re, got)
if allow_number:
got = self._remove_unwanted_precision(want, got)
return super().check_output(want, got, optionflags)
def _remove_unwanted_precision(self, want: str, got: str) -> str:
wants = list(self._number_re.finditer(want))
gots = list(self._number_re.finditer(got))
if len(wants) != len(gots):
return got
offset = 0
for w, g in zip(wants, gots, strict=True):
fraction: str | None = w.group("fraction")
exponent: str | None = w.group("exponent1")
if exponent is None:
exponent = w.group("exponent2")
precision = 0 if fraction is None else len(fraction)
if exponent is not None:
precision -= int(exponent)
if float(w.group()) == approx(float(g.group()), abs=10**-precision):
# They're close enough. Replace the text we actually
# got with the text we want, so that it will match when we
# check the string literally.
got = (
got[: g.start() + offset] + w.group() + got[g.end() + offset :]
)
offset += w.end() - w.start() - (g.end() - g.start())
return got
return LiteralsOutputChecker
def _get_checker() -> doctest.OutputChecker:
"""Return a doctest.OutputChecker subclass that supports some
additional options:
* ALLOW_UNICODE and ALLOW_BYTES options to ignore u'' and b''
prefixes (respectively) in string literals. Useful when the same
doctest should run in Python 2 and Python 3.
* NUMBER to ignore floating-point differences smaller than the
precision of the literal number in the doctest.
An inner class is used to avoid importing "doctest" at the module
level.
"""
global CHECKER_CLASS
if CHECKER_CLASS is None:
CHECKER_CLASS = _init_checker_class()
return CHECKER_CLASS()
def _get_allow_unicode_flag() -> int:
"""Register and return the ALLOW_UNICODE flag."""
import doctest
return doctest.register_optionflag("ALLOW_UNICODE")
def _get_allow_bytes_flag() -> int:
"""Register and return the ALLOW_BYTES flag."""
import doctest
return doctest.register_optionflag("ALLOW_BYTES")
def _get_number_flag() -> int:
"""Register and return the NUMBER flag."""
import doctest
return doctest.register_optionflag("NUMBER")
def _get_report_choice(key: str) -> int:
"""Return the actual `doctest` module flag value.
We want to do it as late as possible to avoid importing `doctest` and all
its dependencies when parsing options, as it adds overhead and breaks tests.
"""
import doctest
return {
DOCTEST_REPORT_CHOICE_UDIFF: doctest.REPORT_UDIFF,
DOCTEST_REPORT_CHOICE_CDIFF: doctest.REPORT_CDIFF,
DOCTEST_REPORT_CHOICE_NDIFF: doctest.REPORT_NDIFF,
DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE: doctest.REPORT_ONLY_FIRST_FAILURE,
DOCTEST_REPORT_CHOICE_NONE: 0,
}[key]
@fixture(scope="session")
def doctest_namespace() -> dict[str, Any]:
"""Fixture that returns a :py:class:`dict` that will be injected into the
namespace of doctests.
Usually this fixture is used in conjunction with another ``autouse`` fixture:
.. code-block:: python
@pytest.fixture(autouse=True)
def add_np(doctest_namespace):
doctest_namespace["np"] = numpy
For more details: :ref:`doctest_namespace`.
"""
return dict()
| DoctestModule |
python | anthropics__anthropic-sdk-python | src/anthropic/resources/models.py | {
"start": 11794,
"end": 12088
} | class ____:
def __init__(self, models: Models) -> None:
self._models = models
self.retrieve = to_streamed_response_wrapper(
models.retrieve,
)
self.list = to_streamed_response_wrapper(
models.list,
)
| ModelsWithStreamingResponse |
python | Textualize__textual | tests/test_binding_inheritance.py | {
"start": 21926,
"end": 24202
} | class ____(AppKeyRecorder):
"""An application with a priority binding."""
BINDINGS = [
Binding("0", "record('app_0')", "0", priority=False),
Binding("a", "record('app_a')", "a", priority=True),
Binding("b", "record('app_b')", "b", priority=False),
Binding("c", "record('app_c')", "c", priority=False),
Binding("d", "record('app_d')", "c", priority=True),
Binding("e", "record('app_e')", "e", priority=True),
Binding("f", "record('app_f')", "f", priority=False),
]
SCREENS = {"main": PriorityOverlapScreen}
def on_mount(self) -> None:
self.push_screen("main")
async def test_overlapping_priority_bindings() -> None:
"""Test an app stack with overlapping bindings."""
async with PriorityOverlapApp().run_test() as pilot:
await pilot.press(*"0abcdef")
assert pilot.app.pressed_keys == [
"widget_0",
"app_a",
"screen_b",
"widget_c",
"app_d",
"app_e",
"screen_f",
]
async def test_skip_action() -> None:
"""Test that a binding may be skipped by an action raising SkipAction"""
class Handle(Widget, can_focus=True):
BINDINGS = [("t", "test('foo')", "Test")]
def action_test(self, text: str) -> None:
self.app.exit(text)
no_handle_invoked = False
class NoHandle(Widget, can_focus=True):
BINDINGS = [("t", "test('bar')", "Test")]
def action_test(self, text: str) -> bool:
nonlocal no_handle_invoked
no_handle_invoked = True
raise SkipAction()
class SkipApp(App):
def compose(self) -> ComposeResult:
yield Handle(NoHandle())
def on_mount(self) -> None:
self.query_one(NoHandle).focus()
async with SkipApp().run_test() as pilot:
# Check the NoHandle widget has focus
assert pilot.app.query_one(NoHandle).has_focus
# Press the "t" key
await pilot.press("t")
# Check the action on the no handle widget was called
assert no_handle_invoked
# Check the return value, confirming that the action on Handle was called
assert pilot.app.return_value == "foo"
| PriorityOverlapApp |
python | readthedocs__readthedocs.org | readthedocs/builds/migrations/0046_identifier_null.py | {
"start": 149,
"end": 558
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("builds", "0045_alter_build_status"),
]
operations = [
migrations.AlterField(
model_name="version",
name="identifier",
field=models.CharField(
blank=True, max_length=255, null=True, verbose_name="Identifier"
),
),
]
| Migration |
python | ray-project__ray | python/ray/tune/tests/test_tune_restore.py | {
"start": 18457,
"end": 21762
} | class ____(unittest.TestCase):
def test(self):
"""Trainable crashes with fail_fast flag and the original crash message
should bubble up."""
def f(config):
ray.tune.report({"a": 1})
time.sleep(0.1)
raise RuntimeError("Error happens in trainable!!")
with self.assertRaisesRegex(RayTaskError, "Error happens in trainable!!"):
tune.run(f, fail_fast=TuneController.RAISE)
@pytest.mark.parametrize(
"trial_config", [{}, {"attr": 4}, {"nested": {"key": "value"}}]
)
def test_trial_last_result_restore(trial_config):
metrics = {"metric1": 4, "nested2": {"metric3": 6}}
metrics["config"] = trial_config
trial = Trial(trainable_name="stub", config=trial_config, stub=True)
trial.update_last_result(metrics)
result = _TrainingResult(
checkpoint=Checkpoint(path="file:///tmp/no_data"), metrics=metrics
)
trial.temporary_state.restoring_from = result
trial.on_restore()
assert trial.run_metadata.last_result == metrics
def test_stacktrace():
"""Test proper stacktrace is printed for RayTaskError."""
CMD = """
from ray import tune
def train_fn(config):
raise Exception("Inducing exception for testing purposes.")
tune.run(train_fn, num_samples=1)
"""
with pytest.raises(subprocess.CalledProcessError) as exc_info:
run_string_as_driver(CMD)
assert "Inducing exception for testing purposes." in exc_info.value.output.decode()
@pytest.mark.parametrize(
"resume",
[
True,
"AUTO",
"AUTO+ERRORED",
"AUTO+ERRORED_ONLY",
"AUTO+RESTART_ERRORED",
"AUTO+RESTART_ERRORED_ONLY",
],
)
def test_resume_options(tmp_path, resume):
tmp_path.joinpath("dummy_ckpt").mkdir()
def train_fn(config):
checkpoint = ray.tune.get_checkpoint()
if not checkpoint:
ray.tune.report(
{"finish_marker": False},
checkpoint=Checkpoint.from_directory(tmp_path / "dummy_ckpt"),
)
raise RuntimeError("failing on the first run!!")
ray.tune.report({"finish_marker": True})
analysis = tune.run(
train_fn,
storage_path=str(tmp_path),
name="test_resume_options",
raise_on_failed_trial=False,
)
results = ray.tune.ResultGrid(analysis)
assert not results[0].metrics.get("finish_marker", False)
analysis = tune.run(
train_fn,
storage_path=str(tmp_path),
name="test_resume_options",
resume=resume,
raise_on_failed_trial=False,
)
results = ray.tune.ResultGrid(analysis)
if resume in [True, "AUTO", "AUTO+RESTART_ERRORED", "AUTO+RESTART_ERRORED_ONLY"]:
# These options either don't resume the errored trial,
# or restart it without a checkpoint --> leading to the RuntimeError again
assert not results[0].metrics.get("finish_marker")
else:
assert results[0].metrics.get("finish_marker")
# For some reason, different tests are coupled through tune.registry.
# After running `ResourceExhaustedTest`, there is always a super huge `training_func` to
# be put through GCS, which will fail subsequent tests.
# tldr, make sure that this test is the last test in the file.
| TrainableCrashWithFailFast |
python | google__pytype | pytype/tests/test_reingest1.py | {
"start": 150,
"end": 6546
} | class ____(test_base.BaseTest):
"""Tests for reloading the pyi we generate."""
def test_container(self):
ty = self.Infer("""
class Container:
def Add(self):
pass
class A(Container):
pass
""")
with test_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(ty))
self.Check(
"""
# u.py
from foo import A
A().Add()
""",
pythonpath=[d.path],
)
def test_union(self):
ty = self.Infer("""
class Union:
pass
x = {"Union": Union}
""")
with test_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(ty))
self.Check(
"""
from foo import Union
""",
pythonpath=[d.path],
)
def test_identity_decorators(self):
foo = self.Infer("""
def decorate(f):
return f
""")
with test_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
ty = self.Infer(
"""
import foo
@foo.decorate
def f():
return 3
def g():
return f()
""",
pythonpath=[d.path],
)
self.assertTypesMatchPytd(
ty,
"""
import foo
def f() -> int: ...
def g() -> int: ...
""",
)
@test_base.skip("Needs better handling of Union[Callable, f] in output.py.")
def test_maybe_identity_decorators(self):
foo = self.Infer("""
def maybe_decorate(f):
return f or (lambda *args: 42)
""")
with test_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
ty = self.Infer(
"""
import foo
@foo.maybe_decorate
def f():
return 3
def g():
return f()
""",
pythonpath=[d.path],
)
self.assertTypesMatchPytd(
ty,
"""
import foo
def f() -> int: ...
def g() -> int: ...
""",
)
def test_namedtuple(self):
foo = self.Infer("""
import collections
X = collections.namedtuple("X", ["a", "b"])
""")
with test_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
self.Check(
"""
import foo
foo.X(0, 0)
foo.X(a=0, b=0)
""",
pythonpath=[d.path],
)
def test_new_chain(self):
foo = self.Infer("""
class X:
def __new__(cls, x):
return super(X, cls).__new__(cls)
""")
with test_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
self.Check(
"""
import foo
class Y(foo.X):
def __new__(cls, x):
return super(Y, cls).__new__(cls, x)
def __init__(self, x):
self.x = x
Y("x").x
""",
pythonpath=[d.path],
)
def test_namedtuple_subclass(self):
foo = self.Infer("""
import collections
class X(collections.namedtuple("X", ["a"])):
def __new__(cls, a, b):
_ = b
return super(X, cls).__new__(cls, a)
""")
with test_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
_, errors = self.InferWithErrors(
"""
import foo
foo.X("hello", "world")
foo.X(42) # missing-parameter[e]
""",
pythonpath=[d.path],
)
self.assertErrorRegexes(errors, {"e": r"b.*__new__"})
def test_alias(self):
foo = self.Infer("""
class _Foo:
def __new__(cls, _):
return super(_Foo, cls).__new__(cls)
Foo = _Foo
""")
with test_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
self.Check(
"""
import foo
foo.Foo("hello world")
""",
pythonpath=[d.path],
)
def test_dynamic_attributes(self):
foo1 = self.Infer("""
HAS_DYNAMIC_ATTRIBUTES = True
""")
foo2 = self.Infer("""
has_dynamic_attributes = True
""")
with test_utils.Tempdir() as d:
d.create_file("foo1.pyi", pytd_utils.Print(foo1))
d.create_file("foo2.pyi", pytd_utils.Print(foo2))
d.create_file(
"bar.pyi",
"""
from foo1 import xyz
from foo2 import zyx
""",
)
self.Check(
"""
import foo1
import foo2
import bar
foo1.abc
foo2.abc
bar.xyz
bar.zyx
""",
pythonpath=[d.path],
)
def test_inherited_mutation(self):
foo = self.Infer("""
class MyList(list):
write = list.append
""")
with test_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
ty = self.Infer(
"""
import foo
lst = foo.MyList()
lst.write(42)
""",
pythonpath=[d.path],
)
# MyList is not parameterized because it inherits from List[Any].
self.assertTypesMatchPytd(
ty,
"""
import foo
lst = ... # type: foo.MyList
""",
)
@test_base.skip("Need to give MyList.write the right self mutation.")
def test_inherited_mutation_in_generic_class(self):
foo = self.Infer("""
from typing import List, TypeVar
T = TypeVar("T")
class MyList(List[T]):
write = list.append
""")
with test_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
ty = self.Infer(
"""
import foo
lst = foo.MyList()
lst.write(42)
""",
pythonpath=[d.path],
)
self.assertTypesMatchPytd(
ty,
"""
import foo
lst = ... # type: foo.MyList[int]
""",
)
def test_instantiate_imported_generic(self):
foo = self.Infer("""
from typing import Generic, TypeVar
T = TypeVar('T')
class Foo(Generic[T]):
def __init__(self):
pass
""")
with test_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils.Print(foo))
ty = self.Infer(
"""
import foo
x = foo.Foo[int]()
""",
pythonpath=[d.path],
)
self.assertTypesMatchPytd(
ty,
"""
import foo
x: foo.Foo[int]
""",
)
| ReingestTest |
python | huggingface__transformers | src/transformers/models/superpoint/modeling_superpoint.py | {
"start": 14524,
"end": 19471
} | class ____(SuperPointPreTrainedModel):
"""
SuperPoint model. It consists of a SuperPointEncoder, a SuperPointInterestPointDecoder and a
SuperPointDescriptorDecoder. SuperPoint was proposed in `SuperPoint: Self-Supervised Interest Point Detection and
Description <https://huggingface.co/papers/1712.07629>`__ by Daniel DeTone, Tomasz Malisiewicz, and Andrew Rabinovich. It
is a fully convolutional neural network that extracts keypoints and descriptors from an image. It is trained in a
self-supervised manner, using a combination of a photometric loss and a loss based on the homographic adaptation of
keypoints. It is made of a convolutional encoder and two decoders: one for keypoints and one for descriptors.
"""
def __init__(self, config: SuperPointConfig) -> None:
super().__init__(config)
self.config = config
self.encoder = SuperPointEncoder(config)
self.keypoint_decoder = SuperPointInterestPointDecoder(config)
self.descriptor_decoder = SuperPointDescriptorDecoder(config)
self.post_init()
@auto_docstring
def forward(
self,
pixel_values: torch.FloatTensor,
labels: Optional[torch.LongTensor] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, SuperPointKeypointDescriptionOutput]:
r"""
Examples:
```python
>>> from transformers import AutoImageProcessor, SuperPointForKeypointDetection
>>> import torch
>>> from PIL import Image
>>> import requests
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> processor = AutoImageProcessor.from_pretrained("magic-leap-community/superpoint")
>>> model = SuperPointForKeypointDetection.from_pretrained("magic-leap-community/superpoint")
>>> inputs = processor(image, return_tensors="pt")
>>> outputs = model(**inputs)
```"""
loss = None
if labels is not None:
raise ValueError("SuperPoint does not support training for now.")
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
pixel_values = self.extract_one_channel_pixel_values(pixel_values)
batch_size, _, height, width = pixel_values.shape
encoder_outputs = self.encoder(
pixel_values,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
last_hidden_state = encoder_outputs[0]
list_keypoints_scores = [
self.keypoint_decoder(last_hidden_state[None, ...]) for last_hidden_state in last_hidden_state
]
list_keypoints = [keypoints_scores[0] for keypoints_scores in list_keypoints_scores]
list_scores = [keypoints_scores[1] for keypoints_scores in list_keypoints_scores]
list_descriptors = [
self.descriptor_decoder(last_hidden_state[None, ...], keypoints[None, ...])
for last_hidden_state, keypoints in zip(last_hidden_state, list_keypoints)
]
maximum_num_keypoints = max(keypoints.shape[0] for keypoints in list_keypoints)
keypoints = torch.zeros((batch_size, maximum_num_keypoints, 2), device=pixel_values.device)
scores = torch.zeros((batch_size, maximum_num_keypoints), device=pixel_values.device)
descriptors = torch.zeros(
(batch_size, maximum_num_keypoints, self.config.descriptor_decoder_dim),
device=pixel_values.device,
)
mask = torch.zeros((batch_size, maximum_num_keypoints), device=pixel_values.device, dtype=torch.int)
for i, (_keypoints, _scores, _descriptors) in enumerate(zip(list_keypoints, list_scores, list_descriptors)):
keypoints[i, : _keypoints.shape[0]] = _keypoints
scores[i, : _scores.shape[0]] = _scores
descriptors[i, : _descriptors.shape[0]] = _descriptors
mask[i, : _scores.shape[0]] = 1
# Convert to relative coordinates
keypoints = keypoints / torch.tensor([width, height], device=keypoints.device)
hidden_states = encoder_outputs[1] if output_hidden_states else None
if not return_dict:
return tuple(v for v in [loss, keypoints, scores, descriptors, mask, hidden_states] if v is not None)
return SuperPointKeypointDescriptionOutput(
loss=loss,
keypoints=keypoints,
scores=scores,
descriptors=descriptors,
mask=mask,
hidden_states=hidden_states,
)
__all__ = ["SuperPointForKeypointDetection", "SuperPointPreTrainedModel"]
| SuperPointForKeypointDetection |
python | ray-project__ray | rllib/offline/offline_env_runner.py | {
"start": 865,
"end": 13101
} | class ____(SingleAgentEnvRunner):
"""The environment runner to record the single agent case."""
@override(SingleAgentEnvRunner)
@OverrideToImplementCustomLogic_CallToSuperRecommended
def __init__(self, *, config: AlgorithmConfig, **kwargs):
# Initialize the parent.
super().__init__(config=config, **kwargs)
# override SingleAgentEnvRunner
self.episodes_to_numpy = False
# Get the data context for this `EnvRunner`.
data_context = ray.data.DataContext.get_current()
# Limit the resources for Ray Data to the CPUs given to this `EnvRunner`.
data_context.execution_options.resource_limits = (
data_context.execution_options.resource_limits.copy(
cpu=config.num_cpus_per_env_runner
)
)
# Set the output write method.
self.output_write_method = self.config.output_write_method
self.output_write_method_kwargs = self.config.output_write_method_kwargs
# Set the filesystem.
self.filesystem = self.config.output_filesystem
self.filesystem_kwargs = self.config.output_filesystem_kwargs
self.filesystem_object = None
# Set the output base path.
self.output_path = self.config.output
# Set the subdir (environment specific).
self.subdir_path = self.config.env.lower()
# Set the worker-specific path name. Note, this is
# specifically to enable multi-threaded writing into
# the same directory.
self.worker_path = "run-" + f"{self.worker_index}".zfill(6)
# If a specific filesystem is given, set it up. Note, this could
# be `gcsfs` for GCS, `pyarrow` for S3 or `adlfs` for Azure Blob Storage.
# this filesystem is specifically needed, if a session has to be created
# with the cloud provider.
if self.filesystem == "gcs":
import gcsfs
self.filesystem_object = gcsfs.GCSFileSystem(**self.filesystem_kwargs)
elif self.filesystem == "s3":
from pyarrow import fs
self.filesystem_object = fs.S3FileSystem(**self.filesystem_kwargs)
elif self.filesystem == "abs":
import adlfs
self.filesystem_object = adlfs.AzureBlobFileSystem(**self.filesystem_kwargs)
elif self.filesystem is not None:
raise ValueError(
f"Unknown filesystem: {self.filesystem}. Filesystems can be "
"'gcs' for GCS, 's3' for S3, or 'abs'"
)
# Add the filesystem object to the write method kwargs.
self.output_write_method_kwargs.update(
{
"filesystem": self.filesystem_object,
}
)
# If we should store `SingleAgentEpisodes` or column data.
self.output_write_episodes = self.config.output_write_episodes
# Which columns should be compressed in the output data.
self.output_compress_columns = self.config.output_compress_columns
# Buffer these many rows before writing to file.
self.output_max_rows_per_file = self.config.output_max_rows_per_file
# If the user defines a maximum number of rows per file, set the
# event to `False` and check during sampling.
if self.output_max_rows_per_file:
self.write_data_this_iter = False
# Otherwise the event is always `True` and we write always sampled
# data immediately to disk.
else:
self.write_data_this_iter = True
# If the remaining data should be stored. Note, this is only
# relevant in case `output_max_rows_per_file` is defined.
self.write_remaining_data = self.config.output_write_remaining_data
# Counts how often `sample` is called to define the output path for
# each file.
self._sample_counter = 0
# Define the buffer for experiences stored until written to disk.
self._samples = []
@override(SingleAgentEnvRunner)
@OverrideToImplementCustomLogic
def sample(
self,
*,
num_timesteps: int = None,
num_episodes: int = None,
explore: bool = None,
random_actions: bool = False,
force_reset: bool = False,
) -> List[SingleAgentEpisode]:
"""Samples from environments and writes data to disk."""
# Call the super sample method.
samples = super().sample(
num_timesteps=num_timesteps,
num_episodes=num_episodes,
explore=explore,
random_actions=random_actions,
force_reset=force_reset,
)
self._sample_counter += 1
# Add data to the buffers.
if self.output_write_episodes:
import msgpack
import msgpack_numpy as mnp
if log_once("msgpack"):
logger.info(
"Packing episodes with `msgpack` and encode array with "
"`msgpack_numpy` for serialization. This is needed for "
"recording episodes."
)
# Note, we serialize episodes with `msgpack` and `msgpack_numpy` to
# ensure version compatibility.
assert all(eps.is_numpy is False for eps in samples)
self._samples.extend(
[msgpack.packb(eps.get_state(), default=mnp.encode) for eps in samples]
)
else:
self._map_episodes_to_data(samples)
# If the user defined the maximum number of rows to write.
if self.output_max_rows_per_file:
# Check, if this number is reached.
if len(self._samples) >= self.output_max_rows_per_file:
# Start the recording of data.
self.write_data_this_iter = True
if self.write_data_this_iter:
# If the user wants a maximum number of experiences per file,
# cut the samples to write to disk from the buffer.
if self.output_max_rows_per_file:
# Reset the event.
self.write_data_this_iter = False
# Ensure that all data ready to be written is released from
# the buffer. Note, this is important in case we have many
# episodes sampled and a relatively small `output_max_rows_per_file`.
while len(self._samples) >= self.output_max_rows_per_file:
# Extract the number of samples to be written to disk this
# iteration.
samples_to_write = self._samples[: self.output_max_rows_per_file]
# Reset the buffer to the remaining data. This only makes sense, if
# `rollout_fragment_length` is smaller `output_max_rows_per_file` or
# a 2 x `output_max_rows_per_file`.
self._samples = self._samples[self.output_max_rows_per_file :]
samples_ds = ray.data.from_items(samples_to_write)
# Otherwise, write the complete data.
else:
samples_ds = ray.data.from_items(self._samples)
try:
# Setup the path for writing data. Each run will be written to
# its own file. A run is a writing event. The path will look
# like. 'base_path/env-name/00000<WorkerID>-00000<RunID>'.
path = (
Path(self.output_path)
.joinpath(self.subdir_path)
.joinpath(self.worker_path + f"-{self._sample_counter}".zfill(6))
)
getattr(samples_ds, self.output_write_method)(
path.as_posix(), **self.output_write_method_kwargs
)
logger.info(f"Wrote samples to storage at {path}.")
except Exception as e:
logger.error(e)
self.metrics.log_value(
key="recording_buffer_size",
value=len(self._samples),
)
# Finally return the samples as usual.
return samples
@override(EnvRunner)
@OverrideToImplementCustomLogic
def stop(self) -> None:
"""Writes the reamining samples to disk
Note, if the user defined `max_rows_per_file` the
number of rows for the remaining samples could be
less than the defined maximum row number by the user.
"""
# If there are samples left over we have to write htem to disk. them
# to a dataset.
if self._samples and self.write_remaining_data:
# Convert them to a `ray.data.Dataset`.
samples_ds = ray.data.from_items(self._samples)
# Increase the sample counter for the folder/file name.
self._sample_counter += 1
# Try to write the dataset to disk/cloud storage.
try:
# Setup the path for writing data. Each run will be written to
# its own file. A run is a writing event. The path will look
# like. 'base_path/env-name/00000<WorkerID>-00000<RunID>'.
path = (
Path(self.output_path)
.joinpath(self.subdir_path)
.joinpath(self.worker_path + f"-{self._sample_counter}".zfill(6))
)
getattr(samples_ds, self.output_write_method)(
path.as_posix(), **self.output_write_method_kwargs
)
logger.info(
f"Wrote final samples to storage at {path}. Note "
"Note, final samples could be smaller in size than "
f"`max_rows_per_file`, if defined."
)
except Exception as e:
logger.error(e)
logger.debug(f"Experience buffer length: {len(self._samples)}")
@OverrideToImplementCustomLogic
def _map_episodes_to_data(self, samples: List[EpisodeType]) -> None:
"""Converts list of episodes to list of single dict experiences.
Note, this method also appends all sampled experiences to the
buffer.
Args:
samples: List of episodes to be converted.
"""
# Loop through all sampled episodes.
for sample in samples:
# Loop through all items of the episode.
for i in range(len(sample)):
sample_data = {
Columns.EPS_ID: sample.id_,
Columns.AGENT_ID: sample.agent_id,
Columns.MODULE_ID: sample.module_id,
# Compress observations, if requested.
Columns.OBS: pack_if_needed(sample.get_observations(i))
if Columns.OBS in self.output_compress_columns
else sample.get_observations(i),
# Compress actions, if requested.
Columns.ACTIONS: pack_if_needed(sample.get_actions(i))
if Columns.ACTIONS in self.output_compress_columns
else sample.get_actions(i),
Columns.REWARDS: sample.get_rewards(i),
# Compress next observations, if requested.
Columns.NEXT_OBS: pack_if_needed(sample.get_observations(i + 1))
if Columns.OBS in self.output_compress_columns
else sample.get_observations(i + 1),
Columns.TERMINATEDS: False
if i < len(sample) - 1
else sample.is_terminated,
Columns.TRUNCATEDS: False
if i < len(sample) - 1
else sample.is_truncated,
**{
# Compress any extra model output, if requested.
k: pack_if_needed(sample.get_extra_model_outputs(k, i))
if k in self.output_compress_columns
else sample.get_extra_model_outputs(k, i)
for k in sample.extra_model_outputs.keys()
},
}
# Finally append to the data buffer.
self._samples.append(sample_data)
| OfflineSingleAgentEnvRunner |
python | coleifer__peewee | playhouse/pool.py | {
"start": 2111,
"end": 2360
} | class ____(object):
def __lt__(self, other):
return True
def locked(fn):
@functools.wraps(fn)
def inner(self, *args, **kwargs):
with self._pool_lock:
return fn(self, *args, **kwargs)
return inner
| _sentinel |
python | numba__numba | numba/stencils/stencilparfor.py | {
"start": 41974,
"end": 44974
} | class ____(object):
def __init__(self, typingctx, targetctx, args, f_ir):
from numba.core.compiler import StateDict
self.state = StateDict()
self.state.typingctx = typingctx
self.state.targetctx = targetctx
self.state.args = args
self.state.func_ir = f_ir
self.state.typemap = None
self.state.return_type = None
self.state.calltypes = None
def _get_const_index_expr(stencil_ir, func_ir, index_var):
"""
infer index_var as constant if it is of a expression form like c-1 where c
is a constant in the outer function.
index_var is assumed to be inside stencil kernel
"""
const_val = guard(
_get_const_index_expr_inner, stencil_ir, func_ir, index_var)
if const_val is not None:
return const_val
return index_var
def _get_const_index_expr_inner(stencil_ir, func_ir, index_var):
"""inner constant inference function that calls constant, unary and binary
cases.
"""
require(isinstance(index_var, ir.Var))
# case where the index is a const itself in outer function
var_const = guard(_get_const_two_irs, stencil_ir, func_ir, index_var)
if var_const is not None:
return var_const
# get index definition
index_def = ir_utils.get_definition(stencil_ir, index_var)
# match inner_var = unary(index_var)
var_const = guard(
_get_const_unary_expr, stencil_ir, func_ir, index_def)
if var_const is not None:
return var_const
# match inner_var = arg1 + arg2
var_const = guard(
_get_const_binary_expr, stencil_ir, func_ir, index_def)
if var_const is not None:
return var_const
raise GuardException
def _get_const_two_irs(ir1, ir2, var):
"""get constant in either of two IRs if available
otherwise, throw GuardException
"""
var_const = guard(find_const, ir1, var)
if var_const is not None:
return var_const
var_const = guard(find_const, ir2, var)
if var_const is not None:
return var_const
raise GuardException
def _get_const_unary_expr(stencil_ir, func_ir, index_def):
"""evaluate constant unary expr if possible
otherwise, raise GuardException
"""
require(isinstance(index_def, ir.Expr) and index_def.op == 'unary')
inner_var = index_def.value
# return -c as constant
const_val = _get_const_index_expr_inner(stencil_ir, func_ir, inner_var)
op = OPERATORS_TO_BUILTINS[index_def.fn]
return eval("{}{}".format(op, const_val))
def _get_const_binary_expr(stencil_ir, func_ir, index_def):
"""evaluate constant binary expr if possible
otherwise, raise GuardException
"""
require(isinstance(index_def, ir.Expr) and index_def.op == 'binop')
arg1 = _get_const_index_expr_inner(stencil_ir, func_ir, index_def.lhs)
arg2 = _get_const_index_expr_inner(stencil_ir, func_ir, index_def.rhs)
op = OPERATORS_TO_BUILTINS[index_def.fn]
return eval("{}{}{}".format(arg1, op, arg2))
| DummyPipeline |
python | doocs__leetcode | solution/2200-2299/2213.Longest Substring of One Repeating Character/Solution.py | {
"start": 243,
"end": 1891
} | class ____:
__slots__ = "s", "tr"
def __init__(self, s: str):
self.s = list(s)
n = len(s)
self.tr: List[Node | None] = [None] * (n * 4)
self.build(1, 1, n)
def build(self, u: int, l: int, r: int):
self.tr[u] = Node(l, r)
if l == r:
return
mid = (l + r) // 2
self.build(u << 1, l, mid)
self.build(u << 1 | 1, mid + 1, r)
self.pushup(u)
def query(self, u: int, l: int, r: int) -> int:
if self.tr[u].l >= l and self.tr[u].r <= r:
return self.tr[u].mx
mid = (self.tr[u].l + self.tr[u].r) // 2
ans = 0
if r <= mid:
ans = self.query(u << 1, l, r)
if l > mid:
ans = max(ans, self.query(u << 1 | 1, l, r))
return ans
def modify(self, u: int, x: int, v: str):
if self.tr[u].l == self.tr[u].r:
self.s[x - 1] = v
return
mid = (self.tr[u].l + self.tr[u].r) // 2
if x <= mid:
self.modify(u << 1, x, v)
else:
self.modify(u << 1 | 1, x, v)
self.pushup(u)
def pushup(self, u: int):
root, left, right = self.tr[u], self.tr[u << 1], self.tr[u << 1 | 1]
root.lmx = left.lmx
root.rmx = right.rmx
root.mx = max(left.mx, right.mx)
a, b = left.r - left.l + 1, right.r - right.l + 1
if self.s[left.r - 1] == self.s[right.l - 1]:
if left.lmx == a:
root.lmx += right.lmx
if right.rmx == b:
root.rmx += left.rmx
root.mx = max(root.mx, left.rmx + right.lmx)
| SegmentTree |
python | kamyu104__LeetCode-Solutions | Python/find-sum-of-array-product-of-magical-sequences.py | {
"start": 65,
"end": 1723
} | class ____(object):
def magicalSum(self, m, k, nums):
"""
:type m: int
:type k: int
:type nums: List[int]
:rtype: int
"""
def popcount(x):
return bin(x).count('1')
MOD = 10**9+7
fact, inv, inv_fact = [[1]*2 for _ in xrange(3)]
for _ in xrange(m+1):
fact.append(fact[-1]*len(inv) % MOD)
inv.append(inv[MOD%len(inv)]*(MOD-MOD//len(inv)) % MOD) # https://cp-algorithms.com/algebra/module-inverse.html
inv_fact.append(inv_fact[-1]*inv[-1] % MOD)
dp = [[[0]*(m+1) for _ in xrange(k+1)] for _ in xrange(m+1)] # dp[c][b][l]: sum of carry c with b set bits with remain size of l
dp[0][0][m] = 1
for x in nums:
new_dp = [[[0]*(m+1) for _ in xrange(k+1)] for _ in xrange(m+1)]
for c in xrange(m+1):
for b in xrange(k+1):
for l in xrange(m+1):
if not dp[c][b][l]:
continue
base = 1
for cnt in xrange(l+1):
nc, nb, nl = (c+cnt)>>1, b+((c+cnt)&1), l-cnt
if nb > k:
continue
new_dp[nc][nb][nl] = (new_dp[nc][nb][nl]+dp[c][b][l]*base*inv_fact[cnt]) % MOD
base = (base*x)%MOD
dp = new_dp
return (reduce(lambda accu, x: (accu+x)%MOD, (dp[c][k-popcount(c)][0] for c in xrange(m+1) if k-popcount(c) >= 0), 0)*fact[m])%MOD
# Time: O(n * k * m^2)
# Space: O(k * m^2)
# dp, combinatorics
| Solution |
python | davidhalter__jedi | jedi/inference/value/klass.py | {
"start": 18905,
"end": 19275
} | class ____(AbstractSignature):
"""
It represents the ``__init__`` signature of a class with dataclass semantics.
.. code:: python
"""
def __init__(self, value, param_names):
super().__init__(value)
self._param_names = param_names
def get_param_names(self, resolve_stars=False):
return self._param_names
| DataclassSignature |
python | mlflow__mlflow | tests/tracking/integration_test_utils.py | {
"start": 3597,
"end": 5159
} | class ____(Thread):
"""Run a FastAPI/uvicorn app in a background thread, usable as a context manager."""
def __init__(self, app: FastAPI, port: int):
super().__init__(name="mlflow-tracking-server", daemon=True)
self.host = "127.0.0.1"
self.port = port
self.url = f"http://{self.host}:{port}"
self.health_url = f"{self.url}/health"
config = uvicorn.Config(app, host=self.host, port=self.port, log_level="error")
self.server = uvicorn.Server(config)
def run(self) -> None:
"""Thread target: let Uvicorn manage its own event loop."""
self.server.run()
def shutdown(self) -> None:
"""Ask Uvicorn to exit; the serving loop checks this flag."""
self.server.should_exit = True
def __enter__(self) -> str:
"""Use as a context manager for tests or short-lived runs."""
self.start()
# Quick readiness wait (poll the health endpoint if available)
deadline = time.time() + 5.0
while time.time() < deadline:
try:
r = requests.get(self.health_url, timeout=0.2)
if r.ok:
break
except (requests.ConnectionError, requests.Timeout):
pass
time.sleep(0.1)
return self.url
def __exit__(self, exc_type, exc, tb) -> bool | None:
"""Clean up resources when exiting context."""
self.shutdown()
# Give the server a moment to wind down
self.join(timeout=5.0)
return None
| ServerThread |
python | getsentry__sentry | src/sentry/issues/suspect_flags.py | {
"start": 335,
"end": 430
} | class ____(TypedDict):
baseline: dict[str, float]
outliers: dict[str, float]
| Distribution |
python | getsentry__sentry | src/sentry/testutils/cases.py | {
"start": 35846,
"end": 37690
} | class ____(TransactionTestCase):
browser: Browser
@pytest.fixture(autouse=True)
def _setup_today(self):
with mock.patch(
"django.utils.timezone.now",
return_value=(datetime(2013, 5, 18, 15, 13, 58, 132928, tzinfo=UTC)),
):
yield
def wait_for_loading(self):
# NOTE: [data-test-id="loading-placeholder"] is not used here as
# some dashboards have placeholders that never complete.
self.browser.wait_until_not('[data-test-id="events-request-loading"]')
self.browser.wait_until_not('[data-test-id="loading-indicator"]')
self.browser.wait_until_not(".loading")
def tearDown(self):
# Avoid tests finishing before their API calls have finished.
# NOTE: This is not fool-proof, it requires loading indicators to be
# used when API requests are made.
self.wait_for_loading()
super().tearDown()
def save_cookie(self, name, value, **params):
self.browser.save_cookie(name=name, value=value, **params)
def save_session(self):
self.session.save()
self.save_cookie(name=settings.SESSION_COOKIE_NAME, value=self.session.session_key)
# Forward session cookie to django client.
self.client.cookies[settings.SESSION_COOKIE_NAME] = self.session.session_key
def dismiss_assistant(self, which=None):
if which is None:
which = ("issue", "issue_stream")
if isinstance(which, str):
which = [which]
for item in which:
res = self.client.put(
"/api/0/assistant/",
content_type="application/json",
data=json.dumps({"guide": item, "status": "viewed", "useful": True}),
)
assert res.status_code == 201, res.content
| AcceptanceTestCase |
python | pypa__virtualenv | src/virtualenv/create/describe.py | {
"start": 2507,
"end": 2710
} | class ____(Describe, ABC):
@classmethod
def can_describe(cls, interpreter):
return interpreter.version_info.major == 3 and super().can_describe(interpreter) # noqa: PLR2004
| Python3Supports |
python | celery__celery | t/unit/worker/test_revoke.py | {
"start": 34,
"end": 238
} | class ____:
def test_is_working(self):
state.revoked.add('foo')
assert 'foo' in state.revoked
state.revoked.pop_value('foo')
assert 'foo' not in state.revoked
| test_revoked |
python | mozilla__bleach | tests/test_linkify.py | {
"start": 23399,
"end": 25053
} | class ____:
def test_no_href_links(self):
s = '<a name="anchor">x</a>'
assert linkify(s) == s
def test_rel_already_there(self):
"""Make sure rel attribute is updated not replaced"""
linked = 'Click <a href="http://example.com" rel="tooltip">here</a>.'
link_good = (
'Click <a href="http://example.com" rel="tooltip nofollow">here</a>.'
)
assert linkify(linked) == link_good
assert linkify(link_good) == link_good
def test_only_text_is_linkified(self):
some_text = "text"
some_type = int
no_type = None
assert linkify(some_text) == some_text
with pytest.raises(TypeError):
linkify(some_type)
with pytest.raises(TypeError):
linkify(no_type)
@pytest.mark.parametrize(
"text, expected",
[
("abc", "abc"),
("example.com", '<a href="http://example.com" rel="nofollow">example.com</a>'),
(
"http://example.com?b=1&c=2",
'<a href="http://example.com?b=1&c=2" rel="nofollow">http://example.com?b=1&c=2</a>',
),
(
"http://example.com?b=1&c=2",
'<a href="http://example.com?b=1&c=2" rel="nofollow">http://example.com?b=1&c=2</a>',
),
(
"link: https://example.com/watch#anchor",
'link: <a href="https://example.com/watch#anchor" rel="nofollow">https://example.com/watch#anchor</a>',
),
],
)
def test_linkify_filter(text, expected):
cleaner = Cleaner(filters=[LinkifyFilter])
assert cleaner.clean(text) == expected
| TestLinkify |
python | gevent__gevent | src/greentest/3.14/test_httpservers.py | {
"start": 58429,
"end": 62988
} | class ____(unittest.TestCase):
""" Test url parsing """
def setUp(self):
self.translated_1 = os.path.join(os.getcwd(), 'filename')
self.translated_2 = os.path.join('foo', 'filename')
self.translated_3 = os.path.join('bar', 'filename')
self.handler_1 = SocketlessRequestHandler()
self.handler_2 = SocketlessRequestHandler(directory='foo')
self.handler_3 = SocketlessRequestHandler(directory=pathlib.PurePath('bar'))
def test_query_arguments(self):
path = self.handler_1.translate_path('/filename')
self.assertEqual(path, self.translated_1)
path = self.handler_2.translate_path('/filename')
self.assertEqual(path, self.translated_2)
path = self.handler_3.translate_path('/filename')
self.assertEqual(path, self.translated_3)
path = self.handler_1.translate_path('/filename?foo=bar')
self.assertEqual(path, self.translated_1)
path = self.handler_2.translate_path('/filename?foo=bar')
self.assertEqual(path, self.translated_2)
path = self.handler_3.translate_path('/filename?foo=bar')
self.assertEqual(path, self.translated_3)
path = self.handler_1.translate_path('/filename?a=b&spam=eggs#zot')
self.assertEqual(path, self.translated_1)
path = self.handler_2.translate_path('/filename?a=b&spam=eggs#zot')
self.assertEqual(path, self.translated_2)
path = self.handler_3.translate_path('/filename?a=b&spam=eggs#zot')
self.assertEqual(path, self.translated_3)
def test_start_with_double_slash(self):
path = self.handler_1.translate_path('//filename')
self.assertEqual(path, self.translated_1)
path = self.handler_2.translate_path('//filename')
self.assertEqual(path, self.translated_2)
path = self.handler_3.translate_path('//filename')
self.assertEqual(path, self.translated_3)
path = self.handler_1.translate_path('//filename?foo=bar')
self.assertEqual(path, self.translated_1)
path = self.handler_2.translate_path('//filename?foo=bar')
self.assertEqual(path, self.translated_2)
path = self.handler_3.translate_path('//filename?foo=bar')
self.assertEqual(path, self.translated_3)
def test_windows_colon(self):
with support.swap_attr(server.os, 'path', ntpath):
path = self.handler_1.translate_path('c:c:c:foo/filename')
path = path.replace(ntpath.sep, os.sep)
self.assertEqual(path, self.translated_1)
path = self.handler_2.translate_path('c:c:c:foo/filename')
path = path.replace(ntpath.sep, os.sep)
self.assertEqual(path, self.translated_2)
path = self.handler_3.translate_path('c:c:c:foo/filename')
path = path.replace(ntpath.sep, os.sep)
self.assertEqual(path, self.translated_3)
path = self.handler_1.translate_path('\\c:../filename')
path = path.replace(ntpath.sep, os.sep)
self.assertEqual(path, self.translated_1)
path = self.handler_2.translate_path('\\c:../filename')
path = path.replace(ntpath.sep, os.sep)
self.assertEqual(path, self.translated_2)
path = self.handler_3.translate_path('\\c:../filename')
path = path.replace(ntpath.sep, os.sep)
self.assertEqual(path, self.translated_3)
path = self.handler_1.translate_path('c:\\c:..\\foo/filename')
path = path.replace(ntpath.sep, os.sep)
self.assertEqual(path, self.translated_1)
path = self.handler_2.translate_path('c:\\c:..\\foo/filename')
path = path.replace(ntpath.sep, os.sep)
self.assertEqual(path, self.translated_2)
path = self.handler_3.translate_path('c:\\c:..\\foo/filename')
path = path.replace(ntpath.sep, os.sep)
self.assertEqual(path, self.translated_3)
path = self.handler_1.translate_path('c:c:foo\\c:c:bar/filename')
path = path.replace(ntpath.sep, os.sep)
self.assertEqual(path, self.translated_1)
path = self.handler_2.translate_path('c:c:foo\\c:c:bar/filename')
path = path.replace(ntpath.sep, os.sep)
self.assertEqual(path, self.translated_2)
path = self.handler_3.translate_path('c:c:foo\\c:c:bar/filename')
path = path.replace(ntpath.sep, os.sep)
self.assertEqual(path, self.translated_3)
| SimpleHTTPRequestHandlerTestCase |
python | wandb__wandb | wandb/vendor/pygments/lexers/markup.py | {
"start": 15994,
"end": 16468
} | class ____(DelegatingLexer):
"""
Subclass of the `MozPreprocHashLexer` that highlights unlexed data with the
`JavascriptLexer`.
.. versionadded:: 2.0
"""
name = "Javascript+mozpreproc"
aliases = ['javascript+mozpreproc']
filenames = ['*.js.in']
mimetypes = []
def __init__(self, **options):
super(MozPreprocJavascriptLexer, self).__init__(
JavascriptLexer, MozPreprocHashLexer, **options)
| MozPreprocJavascriptLexer |
python | ray-project__ray | python/ray/data/_internal/issue_detection/detectors/high_memory_detector.py | {
"start": 1295,
"end": 4698
} | class ____(IssueDetector):
# Many nodes have a 4 GiB : 1 core ratio, but this isn't always the case (e.g., for
# high memory nodes).
_MEMORY_PER_CORE_ESTIMATE = 4 * 1024**3
def __init__(
self,
dataset_id: str,
operators: List["PhysicalOperator"],
config: HighMemoryIssueDetectorConfig,
):
self._dataset_id = dataset_id
self._detector_cfg = config
self._operators = operators
self._initial_memory_requests: Dict[MapOperator, int] = {}
for op in operators:
if isinstance(op, MapOperator):
self._initial_memory_requests[op] = (
op._get_dynamic_ray_remote_args().get("memory") or 0
)
@classmethod
def from_executor(cls, executor: "StreamingExecutor") -> "HighMemoryIssueDetector":
"""Factory method to create a HighMemoryIssueDetector from a StreamingExecutor.
Args:
executor: The StreamingExecutor instance to extract dependencies from.
Returns:
An instance of HighMemoryIssueDetector.
"""
operators = list(executor._topology.keys()) if executor._topology else []
ctx = executor._data_context
return cls(
dataset_id=executor._dataset_id,
operators=operators,
config=ctx.issue_detectors_config.high_memory_detector_config,
)
def detect(self) -> List[Issue]:
issues = []
for op in self._operators:
if not isinstance(op, MapOperator):
continue
if op.metrics.average_max_uss_per_task is None:
continue
remote_args = op._get_dynamic_ray_remote_args()
num_cpus_per_task = remote_args.get("num_cpus", 1)
max_memory_per_task = self._MEMORY_PER_CORE_ESTIMATE * num_cpus_per_task
if (
op.metrics.average_max_uss_per_task > self._initial_memory_requests[op]
and op.metrics.average_max_uss_per_task >= max_memory_per_task
):
message = HIGH_MEMORY_PERIODIC_WARNING.format(
op_name=op.name,
memory_per_task=memory_string(op.metrics.average_max_uss_per_task),
initial_memory_request=memory_string(
self._initial_memory_requests[op]
),
detection_time_interval_s=self.detection_time_interval_s(),
)
issues.append(
Issue(
dataset_name=self._dataset_id,
operator_id=op.id,
issue_type=IssueType.HIGH_MEMORY,
message=_format_message(message),
)
)
return issues
def detection_time_interval_s(self) -> float:
return self._detector_cfg.detection_time_interval_s
def _format_message(message: str) -> str:
# Apply some formatting to make the message look nicer when printed.
formatted_paragraphs = []
for paragraph in message.split("\n\n"):
formatted_paragraph = textwrap.fill(paragraph, break_long_words=False).strip()
formatted_paragraphs.append(formatted_paragraph)
formatted_message = "\n\n".join(formatted_paragraphs)
return "\n\n" + formatted_message + "\n"
| HighMemoryIssueDetector |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDict13.py | {
"start": 726,
"end": 853
} | class ____(ParentD):
# This should generate an error because "x" is NotRequired in the parent.
x: NotRequired[int]
| ChildD |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/collective_ops_test.py | {
"start": 52852,
"end": 54185
} | class ____(test.TestCase):
def setUp(self):
super().setUp()
_setup_context()
def testMap(self):
group_size = 2
group_key = 100
instance_key = 100
def create_dataset_and_fetch_one(t):
dataset = dataset_ops.Dataset.from_tensor_slices([t])
def reduce_fn(t):
# A token is created for each device.
token = create_ordering_token()
return CollectiveOpsV2.all_reduce(
t,
group_size=group_size,
group_key=group_key,
instance_key=instance_key,
ordering_token=token)
dataset = dataset.map(reduce_fn)
return next(iter(dataset))
@def_function.function
def f():
with ops.device('CPU:0'):
value0 = create_dataset_and_fetch_one([1.])
with ops.device('CPU:1'):
value1 = create_dataset_and_fetch_one([2.])
return value0, value1
self.assertAllEqual(self.evaluate(f()), [[3.], [3.]])
@combinations.generate(
combinations.times(
combinations.combine(collective_op=[
combinations.NamedObject('all_reduce_v2',
CollectiveOpsV2.all_reduce),
combinations.NamedObject('all_gather_v2',
CollectiveOpsV2.all_gather)
]), device_combination))
| InputPipelineTest |
python | pytorch__pytorch | torch/_dynamo/variables/builtin.py | {
"start": 8130,
"end": 127999
} | class ____(VariableTracker):
"""
A VariableTracker that represents a built-in value (functions and operators).
A lot of the code here assumes it will be a function object.
The BuiltinVariable class wraps Python built-in functions (like len, isinstance, etc.)
and operators (like +, -, *, etc.) to enable symbolic execution during tracing. This allows
Dynamo to properly handle these operations when converting Python code to FX graphs while
maintaining correct semantics and enabling optimizations.
"""
_SENTINEL = object()
_nonvar_fields = {
"fn",
*VariableTracker._nonvar_fields,
}
@classmethod
def create_with_source(cls, value: Any, source: Source) -> "BuiltinVariable":
install_guard(source.make_guard(GuardBuilder.BUILTIN_MATCH))
return cls(value, source=source)
@staticmethod
@functools.cache
def _constant_fold_functions() -> set[Callable[..., Any]]:
fns: set[Callable[..., Any]] = {
abs,
all,
any,
bool,
callable,
chr,
complex,
divmod,
float,
getattr,
int,
len,
max,
min,
ord,
pow,
repr,
round,
str,
str.format,
sum,
type,
operator.abs,
operator.pos,
operator.neg,
operator.not_,
operator.truth,
operator.invert,
operator.pow,
operator.mul,
operator.matmul,
operator.floordiv,
operator.truediv,
operator.mod,
operator.add,
operator.sub,
operator.getitem,
operator.length_hint,
operator.lshift,
operator.rshift,
operator.and_,
operator.or_,
operator.xor,
operator.ipow,
operator.imul,
operator.imatmul,
operator.ifloordiv,
operator.itruediv,
operator.imod,
operator.iadd,
operator.isub,
operator.ilshift,
operator.irshift,
operator.iand,
operator.ixor,
operator.ior,
operator.index,
}
from .tensor import supported_comparison_ops
fns.update(supported_comparison_ops.values())
fns.update(x for x in math.__dict__.values() if isinstance(x, type(math.sqrt)))
return fns
def can_constant_fold_through(self) -> bool:
return self.fn in self._constant_fold_functions()
@staticmethod
@functools.cache
def _fx_graph_functions() -> set[Callable[..., Any]]:
fns = {
operator.abs,
operator.pos,
operator.neg,
operator.not_,
operator.invert,
operator.pow,
operator.mul,
operator.matmul,
operator.floordiv,
operator.truediv,
operator.mod,
operator.add,
operator.lt,
operator.gt,
operator.ge,
operator.le,
operator.ne,
operator.eq,
operator.sub,
operator.length_hint,
operator.lshift,
operator.rshift,
operator.and_,
operator.or_,
operator.xor,
operator.ipow,
operator.imul,
operator.imatmul,
operator.ifloordiv,
operator.itruediv,
operator.getitem,
operator.imod,
operator.iadd,
operator.isub,
operator.ilshift,
operator.irshift,
operator.iand,
operator.ixor,
operator.ior,
}
return fns # type: ignore[return-value]
@staticmethod
@functools.cache
def _binops() -> dict[
Callable[..., object], tuple[list[str], Callable[..., object]]
]:
# function -> ([forward name, reverse name, in-place name], in-place op)
fns: dict[Callable[..., object], tuple[list[str], Callable[..., object]]] = {
operator.add: (["__add__", "__radd__", "__iadd__"], operator.iadd),
operator.sub: (["__sub__", "__rsub__", "__isub__"], operator.isub),
operator.mul: (["__mul__", "__rmul__", "__imul__"], operator.imul),
operator.truediv: (
["__truediv__", "__rtruediv__", "__itruediv__"],
operator.itruediv,
),
operator.floordiv: (
["__floordiv__", "__rfloordiv__", "__ifloordiv__"],
operator.ifloordiv,
),
operator.mod: (["__mod__", "__rmod__", "__imod__"], operator.imod),
pow: (["__pow__", "__rpow__", "__ipow__"], operator.ipow),
operator.pow: (["__pow__", "__rpow__", "__ipow__"], operator.ipow),
operator.lshift: (
["__lshift__", "__rlshift__", "__ilshift__"],
operator.ilshift,
),
operator.rshift: (
["__rshift__", "__rrshift__", "__irshift__"],
operator.irshift,
),
operator.xor: (["__xor__", "__rxor__", "__ixor__"], operator.xor),
# NB: The follow binary operators are not supported for now, since the
# corresponding magic methods aren't defined on SymInt / SymFloat:
# operator.matmul
# divmod
# operator.and_
# operator.or_
}
return fns
@staticmethod
@functools.cache
def _binop_handlers() -> dict[
Callable[..., object],
list[
tuple[
tuple[
type[VariableTracker],
_TrackersType,
],
_HandlerCallback,
]
],
]:
# Multiple dispatch mechanism defining custom binop behavior for certain type
# combinations. Handlers are attempted in order, and will be used if the type checks
# match. They are expected to have the signature:
# fn(tx, arg0: VariableTracker, arg1: VariableTracker) -> VariableTracker
from .functions import BaseUserFunctionVariable, UserFunctionVariable
from .nn_module import NNModuleVariable
from .tensor import supported_const_comparison_ops
from .torch import BaseTorchVariable
from .user_defined import (
UserDefinedClassVariable,
UserDefinedObjectVariable,
UserDefinedVariable,
)
# Override table contains: op_fn -> [list of handlers]
op_handlers: dict[Any, list[Any]] = {}
for (
op,
(magic_method_names, in_place_op),
) in BuiltinVariable._binops().items():
op_handlers[op] = []
op_handlers[in_place_op] = []
forward_name, reverse_name, inplace_name = magic_method_names
# User-defined args (highest precedence)
def user_defined_handler(
tx: "InstructionTranslator",
a: VariableTracker,
b: VariableTracker,
*,
forward_name: str = forward_name,
reverse_name: str = reverse_name,
) -> VariableTracker:
# Manually handle reversing logic if needed (e.g. call __radd__)
# TODO: If we expand this to handle tensor args, we need to manually
# handle cases like this:
#
# class A(int):
# def __radd__(self, other):
# print("woof")
# torch.randn(3) + A(3)
#
# In this example, A.__radd__() is not called -> nothing is printed, because
# Tensor.__add__ only does a subtype test against int, ignoring the subclass.
# To be fully correct, we should not call A.__radd__() here, and there may be
# other cases to reason about and add exceptions for.
if isinstance(a, UserDefinedVariable):
return a.call_method(tx, forward_name, [b], {})
else:
return b.call_method(tx, reverse_name, [a], {})
op_handlers[op].append(
((UserDefinedVariable, VariableTracker), user_defined_handler)
)
op_handlers[op].append(
((VariableTracker, UserDefinedVariable), user_defined_handler)
)
def user_defined_inplace_handler(
tx: "InstructionTranslator",
a: VariableTracker,
b: VariableTracker,
*,
forward_name: str = inplace_name,
) -> VariableTracker:
return a.call_method(tx, forward_name, [b], {})
op_handlers[in_place_op].append(
((UserDefinedVariable, VariableTracker), user_defined_inplace_handler)
)
op_handlers[in_place_op].append(
((VariableTracker, UserDefinedVariable), user_defined_inplace_handler)
)
# Dynamic shape args
def dynamic_handler(
tx: "InstructionTranslator",
a: VariableTracker,
b: VariableTracker,
*,
fn: Callable[..., Any] = op,
) -> VariableTracker:
from .builder import wrap_fx_proxy
return wrap_fx_proxy(
tx,
tx.output.create_proxy(
"call_function", fn, *proxy_args_kwargs([a, b], {})
),
)
op_handlers[op].append(
((SymNodeVariable, VariableTracker), dynamic_handler)
)
op_handlers[op].append(
((VariableTracker, SymNodeVariable), dynamic_handler)
)
# NB: Prefer out-of-place op when calling in-place op to generate valid graph
op_handlers[in_place_op].append(
((SymNodeVariable, VariableTracker), dynamic_handler)
)
op_handlers[in_place_op].append(
((VariableTracker, SymNodeVariable), dynamic_handler)
)
# Special cases - lower precedence but still prefer these over constant folding
# List-like addition (e.g. [1, 2] + [3, 4])
def tuple_add_handler(
tx: "InstructionTranslator", a: BaseListVariable, b: VariableTracker
) -> VariableTracker:
return TupleVariable([*a.items, *b.unpack_var_sequence(tx)])
def size_add_handler(
tx: "InstructionTranslator", a: BaseListVariable, b: VariableTracker
) -> VariableTracker:
return SizeVariable([*a.items, *b.unpack_var_sequence(tx)])
list_like_addition_handlers: list[
tuple[
tuple[
type[VariableTracker],
_TrackersType,
],
_HandlerCallback,
]
] = [
# NB: Prefer the tuple-specific logic over base logic because of
# some SizeVariable weirdness. Specifically, the tuple-specific logic
# drops the subclass type (e.g. SizeVariable) and returns TupleVariables.
(
(SizeVariable, SizeVariable),
size_add_handler,
),
(
(SizeVariable, TupleVariable),
size_add_handler,
),
(
(TupleVariable, SizeVariable),
size_add_handler,
),
(
(TupleVariable, TupleVariable),
tuple_add_handler,
),
(
(TupleVariable, ConstantVariable),
tuple_add_handler,
),
(
(ConstantVariable, TupleVariable),
lambda tx, a, b: TupleVariable(
[
*a.unpack_var_sequence(tx),
*b.items,
],
),
),
(
(
ListVariable,
(BaseListVariable, ConstantVariable, ListIteratorVariable),
),
lambda tx, a, b: ListVariable(
[*a.items, *b.unpack_var_sequence(tx)],
mutation_type=ValueMutationNew(),
),
),
(
(BaseListVariable, BaseListVariable),
lambda tx, a, b: type(a)(
[
*a.items,
*b.items,
]
),
),
]
op_handlers[operator.add].extend(list_like_addition_handlers)
def list_iadd_handler(
tx: "InstructionTranslator", a: BaseListVariable, b: VariableTracker
) -> Any:
if a.is_immutable() or not b.has_unpack_var_sequence(tx):
# Handler doesn't apply
return None
seq = b.unpack_var_sequence(tx)
tx.output.side_effects.mutation(a)
a.items.extend(seq)
return a
list_like_iadd_handlers: list[Any] = [
(
(ListVariable, VariableTracker),
list_iadd_handler,
),
(
(TupleVariable, TupleVariable),
tuple_add_handler,
),
(
(TupleVariable, ConstantVariable),
tuple_add_handler,
),
]
op_handlers[operator.iadd].extend(list_like_iadd_handlers)
# List-like expansion (e.g. [1, 2, 3] * 3)
def expand_list_like(
tx: "InstructionTranslator", lst: VariableTracker, const: VariableTracker
) -> VariableTracker:
if isinstance(lst, ConstantVariable):
lst, const = const, lst
try:
assert isinstance(lst, BaseListVariable)
return lst.__class__(
items=lst.items * const.as_python_constant(),
mutation_type=ValueMutationNew(),
)
except MemoryError as exc:
raise_observed_exception(
type(exc),
tx,
args=list(map(ConstantVariable.create, exc.args)),
)
list_like_expansion_handlers: list[
tuple[
tuple[type[VariableTracker], type[VariableTracker]],
_HandlerCallback,
]
] = [
((ListVariable, ConstantVariable), expand_list_like),
((TupleVariable, ConstantVariable), expand_list_like),
((ConstantVariable, ListVariable), expand_list_like),
((ConstantVariable, TupleVariable), expand_list_like),
]
op_handlers[operator.mul].extend(list_like_expansion_handlers)
def create_cmp_op_handlers(
op: Callable[..., Any],
) -> list[tuple[tuple[_TrackersType, _TrackersType], _HandlerCallback]]:
def compare_by_value(
tx: "InstructionTranslator", a: VariableTracker, b: VariableTracker
) -> VariableTracker:
try:
return ConstantVariable(op(a.value, b.value)) # type: ignore[attr-defined]
except TypeError as exc:
raise_observed_exception(
type(exc),
tx,
args=list(map(ConstantVariable.create, exc.args)),
)
result: list[
tuple[
tuple[
_TrackersType,
_TrackersType,
],
_HandlerCallback,
]
] = [((ConstantVariable, ConstantVariable), compare_by_value)]
if op in polyfill_fn_mapping:
# For constants, speedup the comparison instead of using
# polyfill. Removing this line causes major regression for pr
# time benchmark - add_loop_eager.
result = [((ConstantVariable, ConstantVariable), compare_by_value)]
op_var = BuiltinVariable(op)
# Special handling of SymNode variable
result.extend(
[
(
(SymNodeVariable, VariableTracker),
op_var._comparison_with_symnode,
),
(
(VariableTracker, SymNodeVariable),
op_var._comparison_with_symnode,
),
]
)
def handler(
tx: "InstructionTranslator", a: VariableTracker, b: VariableTracker
) -> VariableTracker:
return tx.inline_user_function_return(
VariableTracker.build(tx, polyfill_fn_mapping[op]), [a, b], {}
)
result.append(((VariableTracker, VariableTracker), handler))
return result
result = [((ConstantVariable, ConstantVariable), compare_by_value)]
if op in supported_const_comparison_ops.values() and op.__name__.startswith(
"is_"
):
# Tensor is None, List is not None, etc
none_result = op(object(), None)
def never(
tx: "InstructionTranslator", a: VariableTracker, b: VariableTracker
) -> VariableTracker:
return ConstantVariable(none_result)
obj_op_none = never
none_op_obj = never
types_that_are_never_none = (
TensorVariable,
SymNodeVariable,
NNModuleVariable,
BaseListVariable,
UserDefinedVariable,
BaseUserFunctionVariable,
ConstDictVariable,
BaseTorchVariable,
)
result.extend(
[
(
(types_that_are_never_none, ConstantVariable),
obj_op_none,
),
(
(ConstantVariable, types_that_are_never_none),
none_op_obj,
),
]
)
op_var = BuiltinVariable(op)
result.extend(
[
(
(
(UserFunctionVariable, BuiltinVariable),
(UserFunctionVariable, BuiltinVariable),
),
lambda tx, a, b: ConstantVariable(op(a.fn, b.fn)),
),
(
(
NNModuleVariable,
NNModuleVariable,
),
lambda tx, a, b: ConstantVariable(
op(
tx.output.get_submodule(a.module_key),
tx.output.get_submodule(b.module_key),
)
),
),
(
(UserDefinedObjectVariable, UserDefinedObjectVariable),
compare_by_value,
),
(
(UserDefinedClassVariable, UserDefinedClassVariable),
compare_by_value,
),
(
(
(StreamVariable, EventVariable, ConstantVariable),
(StreamVariable, EventVariable, ConstantVariable),
),
compare_by_value,
),
(
(TensorVariable, VariableTracker),
op_var._comparison_with_tensor,
),
(
(VariableTracker, TensorVariable),
op_var._comparison_with_tensor,
),
(
(SymNodeVariable, VariableTracker),
op_var._comparison_with_symnode,
),
(
(VariableTracker, SymNodeVariable),
op_var._comparison_with_symnode,
),
]
)
def handle_is(
tx: "InstructionTranslator",
left: VariableTracker,
right: VariableTracker,
) -> VariableTracker | None:
# If the two objects are of different type, we can safely return False
# and True for `is` and `is not`, respectively
if type(left) is not type(right):
return ConstantVariable.create(op.__name__ != "is_")
if left is right:
return ConstantVariable.create(op(left, right))
if (
istype(left, variables.ExceptionVariable)
and istype(right, variables.ExceptionVariable)
and left.exc_type is not right.exc_type
):
return ConstantVariable.create(op(left, right))
return None
result.append(((VariableTracker, VariableTracker), handle_is)) # type: ignore[arg-type]
return result
for op in supported_comparison_ops.values():
assert callable(op)
assert op not in op_handlers
op_handlers[op] = create_cmp_op_handlers(op)
return op_handlers
@staticmethod
def _find_binop_handler(
op: Callable[..., Any], a_type: type[VariableTracker], b_type: type
) -> list[_HandlerCallback] | None:
handlers = BuiltinVariable._binop_handlers().get(op)
if handlers is None:
return None
matches = []
for (type1, type2), handler in handlers:
if issubclass(a_type, type1) and issubclass(b_type, type2):
matches.append(handler)
return matches
def can_insert_in_graph(self) -> bool:
return self.fn in self._fx_graph_functions()
def __init__(self, fn: Any, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.fn = fn
def __repr__(self) -> str:
if self.fn is None:
name = "None"
else:
name = self.fn.__name__
return f"{self.__class__.__name__}({name})"
def as_python_constant(self) -> Any:
return self.fn
def as_proxy(self) -> Any:
DTYPE = {
bool: torch.bool,
int: torch.int64,
float: torch.float64,
}
if self.fn in DTYPE:
return DTYPE[self.fn]
return super().as_proxy()
def reconstruct(self, codegen: "PyCodegen") -> None:
name = self.fn.__name__
assert self.fn.__module__ == "builtins"
assert name not in codegen.tx.f_globals, "shadowed global"
codegen.append_output(codegen.create_load_global(name, add=True))
def constant_args(self, *args: VariableTracker, **kwargs: VariableTracker) -> bool:
return check_constant_args(args, kwargs)
def tensor_args(self, *args: VariableTracker) -> bool:
any_tensor = False
for arg in args:
if isinstance(arg, variables.GetAttrVariable):
return False
any_tensor = any_tensor or isinstance(arg, variables.TensorVariable)
return any_tensor
def tensor_args_type(self, arg_types: list[type]) -> bool:
any_tensor = False
for arg_type in arg_types:
if issubclass(arg_type, variables.GetAttrVariable):
return False
any_tensor = any_tensor or issubclass(arg_type, variables.TensorVariable)
return any_tensor
def python_and_tensor_constant_only(
self, *args: VariableTracker, **kwargs: VariableTracker
) -> bool:
tensor_args = []
non_tensor_args = []
for i in itertools.chain(args, kwargs.values()):
if isinstance(i, variables.TensorVariable):
tensor_args.append(i)
else:
non_tensor_args.append(i)
return all(
is_constant_source(t.source) if t.source is not None else False
for t in tensor_args
) and self.constant_args(*non_tensor_args)
@staticmethod
def unwrap_unspec_args_kwargs(
args: Sequence[VariableTracker], kwargs: dict[str, VariableTracker]
) -> tuple[list[Any], dict[str, Any]]:
return [x.as_python_constant() for x in args], {
k: v.as_python_constant() for k, v in kwargs.items()
}
def has_constant_handler(
self, args: Sequence[VariableTracker], kwargs: dict[str, VariableTracker]
) -> bool:
return self.can_constant_fold_through() and check_unspec_or_constant_args(
args, kwargs
)
@staticmethod
def _make_handler(
fn: Callable[..., Any], arg_types: list[type], has_kwargs: bool
) -> Callable[
[
"InstructionTranslator",
Sequence[VariableTracker],
dict[str, VariableTracker],
],
VariableTracker | None,
]:
from .lazy import LazyVariableTracker
obj = BuiltinVariable(fn)
handlers: list[_HandlerCallback] = []
if any(issubclass(t, LazyVariableTracker) for t in arg_types):
return lambda tx, args, kwargs: obj.call_function(
tx, [v.realize() for v in args], kwargs
)
if inspect.isclass(fn) and (
issubclass(fn, Exception)
# GeneratorExit doesn't inherit from Exception
# >>> issubclass(GeneratorExit, Exception)
# False
or fn is GeneratorExit
):
def create_exception_class_object(
tx: "InstructionTranslator",
args: Sequence[VariableTracker],
kwargs: dict[str, VariableTracker],
) -> VariableTracker:
if fn is AssertionError and not all(
isinstance(x, variables.ConstantVariable)
and isinstance(x.value, str)
for x in args
):
unimplemented(
gb_type="assert with non-string message",
context=str(args),
explanation="Dynamo only supports asserts with string messages",
hints=[*graph_break_hints.SUPPORTABLE],
)
return variables.ExceptionVariable(fn, args, kwargs)
return create_exception_class_object
if obj.can_insert_in_graph() and not (
fn is operator.getitem
and not issubclass(arg_types[0], variables.TensorVariable)
):
if obj.tensor_args_type(arg_types):
return obj._handle_insert_op_in_graph
elif has_kwargs:
# need runtime check for kwargs
handlers.append(obj._handle_insert_op_in_graph)
# Handle binary ops (e.g. __add__ / __radd__, __iadd__, etc.)
# NB: Tensor args are handled above and not here
if len(arg_types) == 2 and not has_kwargs:
# Try to find a handler for the arg types; otherwise, fall through to constant handler
binop_handlers = BuiltinVariable._find_binop_handler(fn, *arg_types)
if not binop_handlers:
pass
elif len(binop_handlers) == 1:
(binop_handler,) = binop_handlers
handlers.append(lambda tx, args, _: binop_handler(tx, *args))
else:
def call_binop_handlers(
tx: "InstructionTranslator", args: Any, _: Any
) -> Any:
# pyrefly: ignore [not-iterable]
for fn in binop_handlers:
rv = fn(tx, *args)
if rv:
return rv
return None
handlers.append(call_binop_handlers)
self_handler = getattr(obj, f"call_{fn.__name__}", None)
if self_handler:
def call_self_handler(
tx: "InstructionTranslator",
args: Sequence[VariableTracker],
kwargs: dict[str, VariableTracker],
) -> VariableTracker | None:
try:
# pyrefly: ignore [not-callable]
return self_handler(tx, *args, **kwargs)
except TypeError:
# Check if binding is bad. inspect signature bind is expensive.
# So check only when handler call fails.
try:
# pyrefly: ignore [bad-argument-type]
inspect.signature(self_handler).bind(tx, *args, **kwargs)
except TypeError as e:
has_constant_handler = obj.has_constant_handler(args, kwargs)
if not has_constant_handler:
log.warning( # noqa: G200
"incorrect arg count %s %s and no constant handler",
self_handler,
e,
)
unimplemented(
gb_type="invalid call to builtin op handler",
context=f"invalid args to {self_handler}: {args} {kwargs}",
explanation=f"Encountered TypeError when trying to handle op {fn.__name__}",
hints=[*graph_break_hints.DIFFICULT],
)
else:
raise
except Unsupported as exc:
has_constant_handler = obj.has_constant_handler(args, kwargs)
if not has_constant_handler:
raise
# Actually, we will handle this just fine
exc.remove_from_stats()
return None
handlers.append(call_self_handler)
if obj.can_constant_fold_through():
if (
all(issubclass(x, ConstantVariable) for x in arg_types)
and not has_kwargs
):
def constant_fold_handler(
tx: "InstructionTranslator",
args: Sequence[VariableTracker],
kwargs: dict[str, VariableTracker],
) -> VariableTracker | None:
# fast path
try:
res = fn(
*[x.as_python_constant() for x in args],
)
except Exception as exc:
raise_observed_exception(
type(exc),
tx,
args=list(map(ConstantVariable.create, exc.args)),
)
except AsPythonConstantNotImplementedError as exc:
unimplemented(
gb_type="constant fold exception",
context=f"attempted to run function {fn} with arguments {args}",
explanation="Encountered exception when attempting to constant fold.",
hints=[*graph_break_hints.DYNAMO_BUG],
from_exc=exc,
)
# pyrefly: ignore [unbound-name]
return VariableTracker.build(tx, res)
else:
def constant_fold_handler(
tx: "InstructionTranslator",
args: Sequence[VariableTracker],
kwargs: dict[str, VariableTracker],
) -> VariableTracker | None:
# path with a runtime check
if check_unspec_or_constant_args(args, kwargs):
try:
res = fn(
*[x.as_python_constant() for x in args],
**{
k: v.as_python_constant() for k, v in kwargs.items()
},
)
except AsPythonConstantNotImplementedError as exc:
unimplemented(
gb_type="constant fold exception",
context=f"attempted to run function {fn} with arguments {args}",
explanation="Encountered exception when attempting to constant fold.",
hints=[*graph_break_hints.DYNAMO_BUG],
from_exc=exc,
)
except Exception as exc:
raise_observed_exception(
type(exc),
tx,
args=list(map(ConstantVariable.create, exc.args)),
)
# pyrefly: ignore [unbound-name]
return VariableTracker.build(tx, res)
return None
handlers.append(constant_fold_handler)
def call_unimplemented(args: Sequence[VariableTracker]) -> None:
real_arg_types = [arg.python_type_name() for arg in args]
unimplemented(
gb_type="Failed to trace builtin operator",
context=f"builtin {fn.__name__} {arg_types} {has_kwargs}",
explanation=f"Dynamo does not know how to trace builtin operator `{fn.__name__}` "
f"with argument types {real_arg_types} (has_kwargs {has_kwargs})",
hints=[
f"Avoid calling builtin `{fn.__name__}` with argument types {real_arg_types}. "
f"Consider using an equivalent alternative function/method to `{fn.__name__}`.",
"If you are attempting to call a logging function (e.g. `print`), "
"you can try adding it to `torch._dynamo.config.reorderable_logging_functions`.",
"Please report an issue to PyTorch.",
],
)
if len(handlers) == 0:
return lambda tx, args, kwargs: call_unimplemented(args)
elif len(handlers) == 1:
(handler,) = handlers
def builtin_dispatch(
tx: "InstructionTranslator",
args: Sequence[VariableTracker],
kwargs: dict[str, VariableTracker],
) -> VariableTracker | None:
rv = handler(tx, args, kwargs)
if rv:
return rv
call_unimplemented(args)
return rv
else:
def builtin_dispatch(
tx: "InstructionTranslator",
args: Sequence[VariableTracker],
kwargs: dict[str, VariableTracker],
) -> VariableTracker | None:
rv = None
for fn in handlers:
rv = fn(tx, args, kwargs)
if rv:
return rv
call_unimplemented(args)
return rv
return builtin_dispatch
def call_vars(self, tx: "InstructionTranslator", *args: Any) -> VariableTracker:
if len(args) == 0:
unimplemented(
gb_type="unimplemented builtin op vars() with no arguments",
context=f"vars: {self} {args}",
explanation=f"Dynamo does not know how to trace builtin operator {self.fn} with no arguments",
hints=[*graph_break_hints.SUPPORTABLE],
)
assert len(args) == 1
# vars(obj) is obj.__dict__ if __dict__ is present else TypeError
try:
return args[0].var_getattr(tx, "__dict__")
except ObservedAttributeError:
raise_observed_exception(TypeError, tx)
def _handle_insert_op_in_graph(
self,
tx: "InstructionTranslator",
args: Sequence[VariableTracker],
kwargs: dict[str, VariableTracker],
) -> VariableTracker | None:
from .builder import wrap_fx_proxy, wrap_fx_proxy_cls
if kwargs and not self.tensor_args(*args, *kwargs.values()):
return None
# insert handling for torch function here
from .builder import SourcelessBuilder
from .torch_function import can_dispatch_torch_function, dispatch_torch_function
global BUILTIN_TO_TENSOR_RFN_MAP, BUILTIN_TO_TENSOR_FN_MAP
if can_dispatch_torch_function(tx, args, kwargs):
# Only remap the fn to tensor methods if we aren't exporting
# export serde does not handle method descriptors today
if not tx.export:
# Ensure the builtin maps are populated before accessing them
populate_builtin_to_tensor_fn_map()
# Use sourceless builder, we built the map ourselves
if not isinstance(args[0], TensorVariable):
if self.fn in BUILTIN_TO_TENSOR_RFN_MAP:
func = BUILTIN_TO_TENSOR_RFN_MAP[self.fn]
else:
func = BUILTIN_TO_TENSOR_FN_MAP[self.fn]
tmp = args[0]
# swap args and call reverse version of func
args[0] = args[1] # type: ignore[index]
args[1] = tmp # type: ignore[index]
else:
func = BUILTIN_TO_TENSOR_FN_MAP[self.fn]
else:
func = self.fn
fn_var = SourcelessBuilder.create(tx, func)
return dispatch_torch_function(tx, fn_var, args, kwargs)
fn = self.fn
try:
# Constant fold for constant tensor and python constants
if self.python_and_tensor_constant_only(*args, **kwargs):
from ..bytecode_transformation import unique_id
from .functions import invoke_and_store_as_constant
return invoke_and_store_as_constant(
tx, fn, unique_id(fn.__name__), args, kwargs
)
if fn in IN_PLACE_DESUGARING_MAP and isinstance(
args[0], variables.ConstantVariable
):
# In-place operators like += usually mustate tensor
# values, but in the edge case of immutable values they
# re-bind the variable.
#
# The easiest way to keep the graph consistent in this
# scenario is to de-sugar eagerly.
fn = IN_PLACE_DESUGARING_MAP[fn]
args = [args[0], args[1]] # type: ignore[assignment]
if fn is operator.getitem and isinstance(args[1], SymNodeVariable):
# Standard indexing will force specialization due to
# __index__. Rewrite as a regular torch op which will
# trace fine
fn = torch.select
args = [
args[0],
variables.ConstantVariable.create(0),
args[1],
] # type: ignore[assignment]
# Interaction between ndarray and tensors:
# We prefer the tensor op whenever there are tensors involved
if check_numpy_ndarray_args(args, kwargs) and not any(
type(arg) is variables.TensorVariable for arg in args
):
proxy = tx.output.create_proxy(
"call_function",
numpy_operator_wrapper(fn),
*proxy_args_kwargs(args, kwargs),
)
return wrap_fx_proxy_cls(variables.NumpyNdarrayVariable, tx, proxy)
if (
fn is operator.eq
and len(args) == 2
and isinstance(args[0], variables.TensorVariable)
):
# Dynamo expects `__eq__` str while operator.eq gives just `eq`
# TODO - supporting all comparison operators could also work but
# it fails lots of tests because graph str changes.
return args[0].call_method(tx, "__eq__", args[1:], kwargs)
proxy = tx.output.create_proxy(
"call_function",
fn,
*proxy_args_kwargs(args, kwargs),
)
if any(isinstance(arg, FakeItemVariable) for arg in args):
return wrap_fx_proxy_cls(
FakeItemVariable,
tx,
proxy,
)
elif check_unspec_python_args(args, kwargs):
_args, _kwargs = self.unwrap_unspec_args_kwargs(args, kwargs)
raw_value = fn(*_args, **_kwargs)
need_unwrap = any(
x.need_unwrap
for x in itertools.chain(args, kwargs.values())
if isinstance(x, variables.UnspecializedPythonVariable)
)
return wrap_fx_proxy_cls(
UnspecializedPythonVariable,
tx,
proxy,
raw_value=raw_value,
need_unwrap=need_unwrap,
)
elif all(isinstance(x, SymNodeVariable) for x in args):
return SymNodeVariable.create(tx, proxy, None)
else:
# Work around for vision_maskrcnn due to precision difference
# specialize the dividend when float divide by tensor
if fn is operator.truediv and isinstance(
args[0], variables.UnspecializedPythonVariable
):
args = list(args)
args[0] = args[0].as_python_constant()
return wrap_fx_proxy(tx, proxy)
except NotImplementedError:
unimplemented(
gb_type="unimplemented builtin op on tensor arguments",
context=f"partial tensor op: {self} {args} {kwargs}",
explanation=f"Dynamo does not know how to trace builtin operator {self.fn} with tensor arguments",
hints=[*graph_break_hints.SUPPORTABLE],
)
call_function_handler_cache: dict[
tuple[object, ...],
Callable[
[
"InstructionTranslator",
Sequence[VariableTracker],
dict[str, VariableTracker],
],
VariableTracker,
],
] = {}
def call_function(
self,
tx: "InstructionTranslator",
args: Sequence[VariableTracker],
kwargs: dict[str, VariableTracker],
) -> VariableTracker:
key: tuple[object, ...]
if kwargs:
kwargs = {k: v.realize() for k, v in kwargs.items()}
key = (self.fn, *(type(x) for x in args), True)
else:
key = (self.fn, *(type(x) for x in args))
handler = self.call_function_handler_cache.get(key)
if not handler:
self.call_function_handler_cache[key] = handler = self._make_handler( # type: ignore[assignment]
self.fn, [type(x) for x in args], bool(kwargs)
)
assert handler is not None
return handler(tx, args, kwargs) # type: ignore[return-value]
def call_method(
self,
tx: "InstructionTranslator",
name: str,
args: list[VariableTracker],
kwargs: dict[str, VariableTracker],
) -> VariableTracker:
if self.fn is object and name == "__setattr__":
assert len(args) == 3
assert len(kwargs) == 0
obj, name_var, val = args
obj = obj.realize()
if (
isinstance(obj, UserDefinedObjectVariable)
and tx.output.side_effects.is_attribute_mutation(obj)
and name_var.is_python_constant()
):
return obj.method_setattr_standard(tx, name_var, val)
if name == "__new__":
# Supported __new__ methods
if self.fn is object and len(args) == 1:
assert len(kwargs) == 0
return tx.output.side_effects.track_new_user_defined_object(
self, args[0], args[1:]
)
if self.fn is dict and len(args) == 1 and not kwargs:
dict_vt = ConstDictVariable({}, dict, mutation_type=ValueMutationNew())
if isinstance(args[0], BuiltinVariable) and args[0].fn is dict:
return dict_vt
# We don't have to set the underlying dict_vt in
# UserDefinedDictVariable because it will be set to empty
# ConstDictVariableTracker in the constructor.
return tx.output.side_effects.track_new_user_defined_object(
self,
args[0],
args[1:],
)
if (
self.fn is tuple
and len(args) == 2
and args[1].has_force_unpack_var_sequence(tx)
and not kwargs
):
if isinstance(args[0], BuiltinVariable) and args[0].fn is tuple:
init_args = args[1].force_unpack_var_sequence(tx)
return variables.TupleVariable(
init_args, mutation_type=ValueMutationNew()
)
return tx.output.side_effects.track_new_user_defined_object(
self,
args[0],
args[1:],
)
if self.fn is list:
list_vt = ListVariable([], mutation_type=ValueMutationNew())
if isinstance(args[0], BuiltinVariable) and args[0].fn is list:
return list_vt
return tx.output.side_effects.track_new_user_defined_object(
self,
args[0],
args[1:],
)
if self.fn is float and len(args) == 1 and name in ("fromhex", "hex"):
if isinstance(args[0], ConstantVariable):
try:
fn = getattr(float, name)
res = fn(args[0].as_python_constant())
return variables.ConstantVariable.create(res)
except (OverflowError, ValueError) as e:
raise_observed_exception(
type(e),
tx,
args=list(map(ConstantVariable.create, e.args)),
)
if self.fn is object and name == "__init__":
# object.__init__ is a no-op
return variables.ConstantVariable(None)
if self.fn is dict and name == "fromkeys":
return BuiltinVariable.call_custom_dict_fromkeys(tx, dict, *args, **kwargs)
if self.fn is dict:
resolved_fn = getattr(self.fn, name)
if resolved_fn in dict_methods:
if isinstance(args[0], variables.UserDefinedDictVariable):
# pyrefly: ignore [missing-attribute]
return args[0]._dict_vt.call_method(tx, name, args[1:], kwargs)
elif isinstance(args[0], variables.ConstDictVariable):
return args[0].call_method(tx, name, args[1:], kwargs)
if self.fn is set:
resolved_fn = getattr(self.fn, name)
if resolved_fn in set_methods:
if isinstance(args[0], variables.UserDefinedSetVariable):
# pyrefly: ignore [missing-attribute]
return args[0]._set_vt.call_method(tx, name, args[1:], kwargs)
elif isinstance(args[0], variables.SetVariable):
return args[0].call_method(tx, name, args[1:], kwargs)
if self.fn is frozenset:
resolved_fn = getattr(self.fn, name)
if resolved_fn in frozenset_methods:
if isinstance(args[0], variables.FrozensetVariable):
return args[0].call_method(tx, name, args[1:], kwargs)
if self.fn is str and len(args) >= 1:
resolved_fn = getattr(self.fn, name)
if resolved_fn in str_methods:
if isinstance(args[0], ConstantVariable):
return args[0].call_method(tx, name, args[1:], kwargs)
if self.fn is float and len(args) >= 1:
if isinstance(args[0], ConstantVariable):
return ConstantVariable.create(
getattr(float, name)(args[0].as_python_constant())
)
return super().call_method(tx, name, args, kwargs)
def _call_int_float(
self, tx: "InstructionTranslator", arg: VariableTracker
) -> VariableTracker | None:
# Handle cases like int(torch.seed())
# Also handle sym_float to sym_int cases
if isinstance(arg, (SymNodeVariable, variables.TensorVariable)):
if isinstance(arg, variables.TensorVariable):
item = arg.call_method(tx, "item", [], {})
else:
item = arg
fn_ = sym_int if self.fn is int else sym_float
from torch._dynamo.variables.builder import wrap_fx_proxy
return wrap_fx_proxy(
tx=tx,
proxy=tx.output.create_proxy(
"call_function",
fn_,
(item.as_proxy(),),
{},
),
)
return None
call_int = _call_int_float
call_float = _call_int_float
def call_bool(
self, tx: "InstructionTranslator", arg: VariableTracker
) -> VariableTracker | None:
# Emulate `PyBool_Type.tp_vectorcall` which boils down to `PyObject_IsTrue`.
# https://github.com/python/cpython/blob/3.12/Objects/object.c#L1674-L1697
if isinstance(arg, SymNodeVariable):
# Note that we delay specializing on symbolic values to avoid
# unnecessary guards. Specialization will happen later if, e.g., the
# resulting boolean is used for branching.
if isinstance(arg.sym_num, torch.SymBool):
return arg
# Emulate `nb_bool` of int/float objects
# - https://github.com/python/cpython/blob/3.12/Objects/longobject.c#L4940-L4944
# - https://github.com/python/cpython/blob/3.12/Objects/floatobject.c#L878-L882
assert istype(arg.sym_num, (torch.SymInt, torch.SymFloat))
return SymNodeVariable.create(tx, arg.as_proxy() != 0)
# TODO handle more cases and merge this with this with `generic_jump`.
return None
def call_repr(self, tx: "InstructionTranslator", arg):
"""Handle repr() on user defined objects."""
if isinstance(arg, variables.UserDefinedObjectVariable):
repr_method = arg.value.__repr__
if type(arg.value).__repr__ is object.__repr__:
# Default repr - build and trace it
fn_vt = VariableTracker.build(tx, repr_method)
return fn_vt.call_function(tx, [], {})
else:
# Custom repr - inline the method for tracing
bound_method = repr_method.__func__
fn_vt = VariableTracker.build(tx, bound_method)
return fn_vt.call_function(tx, [arg], {})
def call_str(
self, tx: "InstructionTranslator", arg: VariableTracker
) -> VariableTracker | None:
# Handle `str` on a user defined function or object
if isinstance(arg, (variables.UserFunctionVariable)):
return variables.ConstantVariable.create(value=str(arg.fn))
elif isinstance(arg, (variables.UserDefinedObjectVariable)):
# Check if object has __str__ method
if hasattr(arg.value, "__str__"):
str_method = arg.value.__str__
elif hasattr(arg.value, "__repr__"):
# account for __repr__ functions when __str__ is absent
str_method = arg.value.__repr__
else:
unimplemented(
gb_type="failed to call str() on user defined object",
context=str(arg),
explanation="User defined object has no __str__ or __repr__ method",
hints=[*graph_break_hints.USER_ERROR],
)
if type(arg.value).__str__ is object.__str__:
# Rely on the object str method
try:
# pyrefly: ignore [unbound-name]
return variables.ConstantVariable.create(value=str_method())
except AttributeError:
# Graph break
return None
# pyrefly: ignore [unbound-name]
elif is_wrapper_or_member_descriptor(str_method):
unimplemented(
gb_type="Attempted to a str() method implemented in C/C++",
context="",
explanation=f"{type(arg.value)} has a C/C++ based str method. This is not supported.",
hints=["Write the str method in Python"],
)
else:
# Overrides for custom str method
# Pass method as function to call tx.inline_user_function_return
bound_method = str_method.__func__ # type: ignore[attr-defined]
try:
# Only supports certain function types
user_func_variable = VariableTracker.build(tx, bound_method)
except AssertionError:
# Won't be able to do inline the str method, return to avoid graph break
log.warning("Failed to create UserFunctionVariable", exc_info=True)
return None
# Inline the user function
return user_func_variable.call_function(tx, [arg], {})
elif isinstance(arg, (variables.ExceptionVariable,)):
if len(arg.args) == 0:
value = f"{arg.exc_type}"
else:
value = ", ".join(a.as_python_constant() for a in arg.args)
return variables.ConstantVariable.create(value=value)
return None
def _call_min_max(
self, tx: "InstructionTranslator", *args: VariableTracker
) -> VariableTracker | None:
if len(args) == 1 and args[0].has_force_unpack_var_sequence(tx):
items = args[0].force_unpack_var_sequence(tx)
return self._call_min_max_seq(tx, items)
elif len(args) == 2:
return self._call_min_max_binary(tx, args[0], args[1])
elif len(args) > 2:
return self._call_min_max_seq(tx, args)
return None
def _call_min_max_seq(
self, tx: "InstructionTranslator", items: Sequence[VariableTracker]
) -> VariableTracker:
assert len(items) > 0
if len(items) == 1:
return items[0]
return functools.reduce(functools.partial(self._call_min_max_binary, tx), items) # type: ignore[arg-type,return-value]
def _call_min_max_binary(
self,
tx: "InstructionTranslator",
a: VariableTracker | None,
b: VariableTracker | None,
) -> VariableTracker | None:
if a is None or b is None:
# a or b could be none if we reduce and _call_min_max_binary failed
# to return something
return None
if self.tensor_args(a, b):
if not isinstance(a, variables.TensorVariable):
a, b = b, a
assert isinstance(a, variables.TensorVariable)
# result of an item call is a scalar convert to a tensor
if isinstance(a, FakeItemVariable):
a = variables.TorchInGraphFunctionVariable(torch.tensor).call_function(
tx, [a], {}
)
# Dynamic input does not get resolved, rather, gets stored as call_function
if isinstance(a, SymNodeVariable) or isinstance(b, SymNodeVariable):
from .builder import wrap_fx_proxy_cls
return wrap_fx_proxy_cls(
type(a),
tx=tx,
proxy=tx.output.create_proxy(
"call_function",
self.fn,
*proxy_args_kwargs([a, b], {}),
),
)
# convert min/max to torch ops
if b.is_python_constant():
fn: VariableTracker
if isinstance(a, variables.NumpyNdarrayVariable):
import numpy as np
fn = variables.NumpyVariable(np.clip)
else:
fn = variables.TorchInGraphFunctionVariable(torch.clamp)
kwargs = {"min": b} if (self.fn is max) else {"max": b}
result = fn.call_function(tx, [a], kwargs)
else:
if isinstance(a, variables.NumpyNdarrayVariable):
import numpy as np
np_fn = {max: np.maximum, min: np.minimum}[self.fn]
fn = variables.NumpyVariable(np_fn)
else:
torch_fn = {max: torch.maximum, min: torch.minimum}[self.fn]
fn = variables.TorchInGraphFunctionVariable(torch_fn)
result = fn.call_function(tx, [a, b], {})
# return unspec if both a, b are unspec or const
if all(
isinstance(
i,
(
variables.UnspecializedPythonVariable,
variables.ConstantVariable,
),
)
for i in [a, b]
):
if any(isinstance(val, FakeItemVariable) for val in [a, b]):
return variables.FakeItemVariable.from_tensor_variable(result)
if b.is_python_constant():
raw_b = b.as_python_constant()
else:
raw_b = b.raw_value # type: ignore[attr-defined]
if self.fn is max:
raw_res = max(a.raw_value, raw_b) # type: ignore[attr-defined]
else:
raw_res = min(a.raw_value, raw_b) # type: ignore[attr-defined]
need_unwrap = any(
x.need_unwrap
for x in [a, b]
if isinstance(x, variables.UnspecializedPythonVariable)
)
return variables.UnspecializedPythonVariable.from_tensor_variable(
result, raw_res, need_unwrap
)
# otherwise return tensor
else:
return result
elif isinstance(a, SymNodeVariable) or isinstance(b, SymNodeVariable):
py_fn = torch.sym_max if self.fn is max else torch.sym_min
proxy = tx.output.create_proxy(
"call_function", py_fn, *proxy_args_kwargs([a, b], {})
)
return SymNodeVariable.create(tx, proxy, None)
elif isinstance(a, ConstantVariable) and isinstance(b, ConstantVariable):
value = self.fn(
a.as_python_constant(),
b.as_python_constant(),
)
return ConstantVariable(value)
return None
call_min = _call_min_max
call_max = _call_min_max
def call_abs(
self, tx: "InstructionTranslator", arg: VariableTracker
) -> VariableTracker:
# Call arg.__abs__()
abs_method = BuiltinVariable(getattr).call_function(
tx, [arg, ConstantVariable.create("__abs__")], {}
)
return abs_method.call_function(tx, [], {})
def call_pos(
self, tx: "InstructionTranslator", arg: VariableTracker
) -> VariableTracker:
# Call arg.__pos__()
pos_method = BuiltinVariable(getattr).call_function(
tx, [arg, ConstantVariable.create("__pos__")], {}
)
return pos_method.call_function(tx, [], {})
def call_index(
self, tx: "InstructionTranslator", arg: VariableTracker
) -> VariableTracker:
if isinstance(arg, variables.TensorVariable):
unimplemented(
gb_type="unsupported index(Tensor)",
context="",
explanation="Dynamo does not support tracing builtin index() on a Tensor",
hints=[],
)
arg = guard_if_dyn(arg)
constant_value = operator.index(arg)
return variables.ConstantVariable.create(constant_value)
def call_round(
self,
tx: "InstructionTranslator",
arg: VariableTracker,
*args: VariableTracker,
**kwargs: VariableTracker,
) -> VariableTracker:
# Call arg.__round__()
round_method = BuiltinVariable(getattr).call_function(
tx, [arg, ConstantVariable.create("__round__")], {}
)
return round_method.call_function(tx, args, kwargs)
def call_range(
self, tx: "InstructionTranslator", *args: VariableTracker
) -> VariableTracker | None:
if check_unspec_or_constant_args(args, {}):
return variables.RangeVariable(args)
elif self._dynamic_args(*args):
args = tuple(
variables.ConstantVariable.create(guard_if_dyn(arg)) for arg in args
)
return variables.RangeVariable(args)
# None no-ops this handler and lets the driving function proceed
return None
def _dynamic_args(self, *args: VariableTracker, **kwargs: VariableTracker) -> bool:
return any(isinstance(x, SymNodeVariable) for x in args) or any(
isinstance(x, SymNodeVariable) for x in kwargs.values()
)
def call_slice(
self, tx: "InstructionTranslator", *args: VariableTracker
) -> VariableTracker:
return variables.SliceVariable(args, tx)
def _dyn_proxy(
self, tx: "InstructionTranslator", *args: Any, **kwargs: Any
) -> VariableTracker:
from .builder import wrap_fx_proxy
return wrap_fx_proxy(
tx,
tx.output.create_proxy(
"call_function", self.fn, *proxy_args_kwargs(args, kwargs)
),
)
# NOTE must handle IteratorVariable separately!
def _call_iter_tuple_list(
self,
tx: "InstructionTranslator",
obj: VariableTracker | None = None,
*args: VariableTracker,
**kwargs: VariableTracker,
) -> VariableTracker | None:
assert not isinstance(obj, variables.IteratorVariable)
if self._dynamic_args(*args, **kwargs):
return self._dyn_proxy(tx, *args, **kwargs)
cls = variables.BaseListVariable.cls_for(self.fn)
if obj is None:
return cls(
[],
mutation_type=ValueMutationNew(),
)
elif obj.has_unpack_var_sequence(tx):
if obj.source and not is_constant_source(obj.source):
if isinstance(obj, TupleIteratorVariable):
install_guard(
obj.source.make_guard(GuardBuilder.TUPLE_ITERATOR_LEN)
)
else:
if (
getattr(obj, "source", False)
and isinstance(obj, ConstDictVariable)
and not istype(obj, (SetVariable, FrozensetVariable))
):
tx.output.guard_on_key_order.add(obj.source)
if isinstance(obj, variables.MappingProxyVariable):
# This could be an overguarding, but its rare to iterate
# through a mapping proxy and not use the keys.
install_guard(
obj.source.make_guard(GuardBuilder.MAPPING_KEYS_CHECK)
)
elif not isinstance(obj, variables.UnspecializedNNModuleVariable):
# Prevent calling __len__ method for guards, the tracing
# of __iter__ will insert the right guards later.
install_guard(
obj.source.make_guard(GuardBuilder.SEQUENCE_LENGTH)
)
return cls(
list(obj.unpack_var_sequence(tx)),
mutation_type=ValueMutationNew(),
)
return None
def _call_iter_tuple_generator(
self,
tx: "InstructionTranslator",
obj: VariableTracker,
*args: VariableTracker,
**kwargs: VariableTracker,
) -> VariableTracker:
cls = variables.BaseListVariable.cls_for(self.fn)
return cls(
list(obj.force_unpack_var_sequence(tx)), # exhaust generator
mutation_type=ValueMutationNew(),
)
def _call_tuple_list(
self,
tx: "InstructionTranslator",
obj: VariableTracker | None = None,
*args: VariableTracker,
**kwargs: VariableTracker,
) -> VariableTracker | None:
if isinstance(obj, variables.IteratorVariable):
cls = variables.BaseListVariable.cls_for(self.fn)
return cls(
list(obj.force_unpack_var_sequence(tx)),
mutation_type=ValueMutationNew(),
)
elif isinstance(obj, variables.LocalGeneratorObjectVariable) or (
isinstance(obj, UserDefinedObjectVariable)
and obj.has_force_unpack_var_sequence(tx)
):
return self._call_iter_tuple_generator(tx, obj, *args, **kwargs)
else:
return self._call_iter_tuple_list(tx, obj, *args, **kwargs)
def call_iter(
self,
tx: "InstructionTranslator",
obj: VariableTracker,
*args: VariableTracker,
**kwargs: VariableTracker,
) -> VariableTracker:
# avoid the overhead of tracing the polyfill if we already know the class implemented __iter__
if isinstance(
obj,
(
variables.ListVariable,
variables.RangeVariable,
variables.IteratorVariable,
variables.ConstDictVariable,
variables.NNModuleVariable,
variables.TensorVariable,
),
):
return obj.call_method(tx, "__iter__", [], {})
else:
# If the object doesn't implement a __iter__ method, it will be an error in eager mode when calling iter on it anyway.
# If the object implements a __iter__ method, inlining effectively forwards the call to another iter call
# (e.g. when __iter__ just returns iter(self.list)) or return a user-defined iterator.
# If the object implements a __getitem__ method, iter(...) will call obj.__getitem__()
# with an integer argument starting at 0, until __getitem__ raises IndexError
ret = variables.UserFunctionVariable(
polyfills.builtins.iter_ # type: ignore[arg-type]
).call_function(tx, [obj, *args], {})
if args:
# iter(obj, sentinel) returns an object that implements
# __iter__ and __next__ methods (UserDefinedObjectVariable)
# Wrap the return value in a IteratorVariable subclass (LazyObjectIteratorVariable)
# that forwards the next_variable call to the object.
ret = variables.ObjectIteratorVariable(ret)
return ret
call_tuple = _call_tuple_list
call_list = _call_tuple_list
def call_callable(
self, tx: "InstructionTranslator", arg: VariableTracker
) -> VariableTracker | None:
from .functions import BaseUserFunctionVariable, FunctoolsPartialVariable
from .nn_module import NNModuleVariable
if isinstance(
arg,
(
variables.UserDefinedClassVariable,
BaseUserFunctionVariable,
FunctoolsPartialVariable,
NNModuleVariable,
),
):
return variables.ConstantVariable.create(True)
elif isinstance(arg, UserDefinedVariable):
return variables.ConstantVariable.create(callable(arg.value))
elif isinstance(
arg,
(
ConstantVariable,
SymNodeVariable,
TensorVariable,
ListVariable,
TupleVariable,
ListIteratorVariable,
),
):
return variables.ConstantVariable.create(False)
else:
return None
def call_cast(
self, _: Any, *args: VariableTracker, **kwargs: VariableTracker
) -> VariableTracker | None:
if len(args) == 2:
return args[1]
unimplemented(
gb_type="bad args to builtin cast()",
context=f"got args {args} {kwargs}",
explanation="Dynamo expects exactly 2 args to builtin cast().",
hints=["Ensure your call to cast() has exactly 2 arguments."],
)
def call_dir(
self, tx: "InstructionTranslator", arg: VariableTracker
) -> VariableTracker | None:
if isinstance(arg, variables.UserDefinedClassVariable):
return VariableTracker.build(tx, dir(arg.value))
if isinstance(arg, BuiltinVariable):
return VariableTracker.build(tx, dir(arg.fn))
return None
def call_dict(
self,
tx: "InstructionTranslator",
/,
*args: VariableTracker,
**kwargs: VariableTracker,
) -> VariableTracker:
return BuiltinVariable.call_custom_dict(tx, dict, *args, **kwargs)
@staticmethod
def call_custom_dict(
tx: "InstructionTranslator",
user_cls: type,
/,
*args: VariableTracker,
**kwargs: VariableTracker,
) -> VariableTracker:
args_list = list(args)
if (
len(args_list) == 1
and isinstance(args_list[0], variables.GetAttrVariable)
and isinstance(args_list[0].obj, variables.UserDefinedClassVariable)
and not tx.output.side_effects.has_pending_mutation(args_list[0].obj)
):
# Forward the GetAttrVariable(foo, "__dict__") to a realized vt of
# VT(foo.__dict__). This simplifies the construction of the new
# dict.
args_list[0] = args_list[0].get_forwarded_dict(tx)
return tx.inline_user_function_return(
VariableTracker.build(tx, polyfills.construct_dict),
[VariableTracker.build(tx, user_cls), *args_list],
kwargs,
)
@staticmethod
def call_custom_dict_fromkeys(
tx: "InstructionTranslator",
user_cls: type,
/,
*args: VariableTracker,
**kwargs: VariableTracker,
) -> VariableTracker:
if user_cls not in {dict, OrderedDict, defaultdict}:
unimplemented(
gb_type="Unsupported dict type for fromkeys()",
context=f"{user_cls.__name__}.fromkeys(): {args} {kwargs}",
explanation=f"Failed to call {user_cls.__name__}.fromkeys() because "
f"{user_cls.__name__} is not any type of dict, OrderedDict, or defaultdict",
hints=[
f"Ensure {user_cls.__name__} is a type of dict, OrderedDict, or defaultdict.",
],
)
if kwargs:
# Only `OrderedDict.fromkeys` accepts `value` passed by keyword
if (
user_cls is not OrderedDict
or len(args) != 1
or len(kwargs) != 1
or "value" not in kwargs
):
raise_args_mismatch(
tx,
f"{user_cls.__name__}.fromkeys",
"1 args and 1 kwargs (`value`)",
f"{len(args)} args and {len(kwargs)} kwargs",
)
args = (*args, kwargs.pop("value"))
if len(args) == 0:
raise_args_mismatch(
tx,
f"{user_cls.__name__}.fromkeys",
"at least 1 args",
f"{len(args)} args",
)
if len(args) == 1:
args = (*args, ConstantVariable.create(None))
if len(args) != 2:
raise_args_mismatch(
tx,
f"{user_cls.__name__}.fromkeys",
"2 args",
f"{len(args)} args",
)
# pyrefly: ignore [bad-unpacking]
arg, value = args
DictVariableType = (
ConstDictVariable if user_cls is not defaultdict else DefaultDictVariable
)
if isinstance(arg, dict):
arg_list = [ConstantVariable.create(k) for k in arg]
return DictVariableType(
# pyrefly: ignore [bad-argument-type]
dict.fromkeys(arg_list, value),
user_cls,
mutation_type=ValueMutationNew(),
)
elif arg.has_force_unpack_var_sequence(tx):
keys = arg.force_unpack_var_sequence(tx)
if all(is_hashable(v) for v in keys):
return DictVariableType(
# pyrefly: ignore [bad-argument-type]
dict.fromkeys(keys, value),
user_cls,
mutation_type=ValueMutationNew(),
)
unimplemented(
gb_type="failed to call dict.fromkeys()",
context=f"{user_cls.__name__}.fromkeys(): {args} {kwargs}",
explanation=f"Failed to call {user_cls.__name__}.fromkeys() because "
"arguments could not be automatically converted to a list, "
"or some dict key is not hashable.",
hints=[
"Manually convert the argument to a list.",
"Ensure all keys are hashable.",
],
)
def call_set(
self,
tx: "InstructionTranslator",
*args: VariableTracker,
**kwargs: VariableTracker,
) -> VariableTracker:
# Can we merge this implementation and call_dict's one?
assert not kwargs
if not args:
return SetVariable([], mutation_type=ValueMutationNew())
if len(args) != 1:
raise_observed_exception(
TypeError,
tx,
args=[
ConstantVariable.create(
f"set() takes 1 positional argument but {len(args)} were given"
)
],
)
arg = args[0]
if istype(arg, variables.SetVariable):
return arg.clone(mutation_type=ValueMutationNew())
elif arg.has_force_unpack_var_sequence(tx):
items = arg.force_unpack_var_sequence(tx)
return SetVariable(items, mutation_type=ValueMutationNew())
elif isinstance(arg, variables.UserDefinedObjectVariable) and isinstance(
arg.value, KeysView
):
iter_fn = arg.var_getattr(tx, "__iter__")
if isinstance(iter_fn, variables.UserMethodVariable):
out = tx.inline_user_function_return(iter_fn, args, kwargs)
if isinstance(out, SetVariable):
return out
return BuiltinVariable(set).call_set(tx, out)
raise_observed_exception(
TypeError,
tx,
args=[ConstantVariable.create("failed to construct builtin set()")],
)
def call_frozenset(
self,
tx: "InstructionTranslator",
*args: VariableTracker,
**kwargs: VariableTracker,
) -> VariableTracker:
assert not kwargs
if not args:
return FrozensetVariable([])
if len(args) != 1:
raise_observed_exception(
TypeError,
tx,
args=[
ConstantVariable.create(
f"frozenset() takes 1 positional argument but {len(args)} were given"
)
],
)
arg = args[0]
if istype(arg, variables.FrozensetVariable):
return FrozensetVariable([x.vt for x in arg.set_items])
elif arg.has_force_unpack_var_sequence(tx):
items = arg.force_unpack_var_sequence(tx)
return FrozensetVariable(items)
raise_observed_exception(
TypeError,
tx,
args=[ConstantVariable.create("failed to construct builtin frozenset()")],
)
def call_zip(
self,
tx: "InstructionTranslator",
*args: VariableTracker,
**kwargs: VariableTracker,
) -> VariableTracker:
if kwargs:
if not (len(kwargs) == 1 and "strict" in kwargs):
raise_args_mismatch(
tx,
"zip",
"1 kwargs (`strict`)",
f"{len(kwargs)} kwargs",
)
strict = kwargs.pop("strict", ConstantVariable.create(False))
iter_args = [BuiltinVariable(iter).call_function(tx, [arg], {}) for arg in args]
return variables.ZipVariable(
iter_args,
strict=strict.as_python_constant(),
mutation_type=ValueMutationNew(),
)
def call_len(
self,
tx: "InstructionTranslator",
*args: VariableTracker,
**kwargs: VariableTracker,
) -> VariableTracker:
try:
return args[0].call_method(tx, "__len__", list(args[1:]), kwargs)
except AttributeError as e:
raise_observed_exception(type(e), tx, args=list(e.args))
def call_getitem(
self,
tx: "InstructionTranslator",
*args: VariableTracker,
**kwargs: VariableTracker,
) -> VariableTracker:
return args[0].call_method(tx, "__getitem__", list(args[1:]), kwargs)
def call_isinstance(
self,
tx: "InstructionTranslator",
arg: VariableTracker,
isinstance_type_var: VariableTracker,
) -> VariableTracker:
try:
arg_type = arg.python_type()
except NotImplementedError:
unimplemented(
gb_type="builtin isinstance() cannot determine type of argument",
context=f"isinstance({arg}, {isinstance_type_var})",
explanation=f"Dynamo doesn't have a rule to determine the type of argument {arg}",
hints=[*graph_break_hints.DYNAMO_BUG],
)
isinstance_type = isinstance_type_var.as_python_constant()
if isinstance(arg, variables.TensorVariable) and arg.dtype is not None:
def _tensor_isinstance(
tensor_var: VariableTracker, tensor_type: Any
) -> bool:
def check_type(ty: Any) -> bool:
if ty not in tensortype_to_dtype:
example_val = arg.as_proxy().node.meta["example_value"]
if (
is_traceable_wrapper_subclass(example_val)
and ty is torch.nn.parameter.Parameter
):
# N.B: we are calling isinstance directly on the example value.
# torch.nn.Parameter has a meta-class that overrides __isinstance__,
# the isinstance check here allows us to invoke that logic.
return isinstance(example_val, ty)
else:
return issubclass(arg.python_type(), ty)
dtypes = tensortype_to_dtype[ty]
# pyrefly: ignore [missing-attribute]
return arg.dtype in dtypes
if type(tensor_type) is tuple:
return any(check_type(ty) for ty in tensor_type)
else:
return check_type(tensor_type)
return variables.ConstantVariable.create(
_tensor_isinstance(arg, isinstance_type)
)
# UserDefinedObject with C extensions can have torch.Tensor attributes,
# so break graph.
if isinstance(arg, variables.UserDefinedObjectVariable) and isinstance(
arg.value, types.MemberDescriptorType
):
unimplemented(
gb_type="isinstance() called on user defined object with C extensions",
context=f"isinstance({arg}, {isinstance_type})",
explanation="User-defined object with C extensions can have torch.Tensor "
"attributes; intentionally graph breaking.",
hints=[*graph_break_hints.SUPPORTABLE],
)
# handle __instancecheck__ defined in user class
if (
isinstance(arg, variables.UserDefinedObjectVariable)
and "__instancecheck__" in isinstance_type.__class__.__dict__
):
return variables.ConstantVariable.create(
isinstance_type.__class__.__instancecheck__(isinstance_type, arg.value)
)
if isinstance(arg, variables.UserDefinedExceptionClassVariable):
# pyrefly: ignore [unbound-name]
return ConstantVariable.create(isinstance(arg_type, isinstance_type))
isinstance_type_tuple: tuple[type, ...]
if isinstance(isinstance_type, type) or callable(
# E.g. isinstance(obj, typing.Sequence)
getattr(isinstance_type, "__instancecheck__", None)
):
isinstance_type_tuple = (isinstance_type,)
elif isinstance(isinstance_type, types.UnionType):
isinstance_type_tuple = isinstance_type.__args__
elif isinstance(isinstance_type, tuple) and all(
isinstance(tp, type) or callable(getattr(tp, "__instancecheck__", None))
for tp in isinstance_type
):
isinstance_type_tuple = isinstance_type
else:
raise_observed_exception(
TypeError,
tx,
args=[
"isinstance() arg 2 must be a type, a tuple of types, or a union"
],
)
try:
# NB: `isinstance()` does not call `__subclasscheck__` but use `__instancecheck__`.
# But usually `isinstance(obj, type_info)` and `issubclass(type(obj), type_info)` gives
# the same result.
# WARNING: This might run arbitrary user code `__subclasscheck__` and we did not trace
# through it. This is a limitation of the current implementation.
# Usually `__subclasscheck__` and `__instancecheck__` can be constant fold through, it
# might not be a big issue and we trade off it for performance.
# pyrefly: ignore [unbound-name]
val = issubclass(arg_type, isinstance_type_tuple)
except TypeError:
# pyrefly: ignore [unbound-name]
val = arg_type in isinstance_type_tuple
return variables.ConstantVariable.create(val)
def call_issubclass(
self,
tx: "InstructionTranslator",
left_ty: VariableTracker,
right_ty: VariableTracker,
) -> VariableTracker:
"""Checks if first arg is subclass of right arg"""
try:
left_ty_py = left_ty.as_python_constant()
right_ty_py = right_ty.as_python_constant()
except NotImplementedError:
unimplemented(
gb_type="issubclass() with non-constant arguments",
context=f"issubclass({left_ty}, {right_ty})",
explanation="issubclass() with non-constant arguments not supported.",
hints=[
"Make sure your arguments are types.",
*graph_break_hints.USER_ERROR,
],
)
# WARNING: This might run arbitrary user code `__subclasscheck__`.
# See the comment in call_isinstance above.
# pyrefly: ignore [unbound-name]
return variables.ConstantVariable(issubclass(left_ty_py, right_ty_py))
def call_super(
self, tx: "InstructionTranslator", a: VariableTracker, b: VariableTracker
) -> VariableTracker:
return variables.SuperVariable(a, b)
def call_next(
self, tx: "InstructionTranslator", *args: VariableTracker
) -> VariableTracker:
arg = args[0]
try:
return arg.next_variable(tx)
except ObservedUserStopIteration:
if len(args) == 2:
return args[1]
raise
except Unsupported as ex:
if isinstance(arg, variables.BaseListVariable):
ex.remove_from_stats()
return arg.items[0]
raise
def call_hasattr(
self, tx: "InstructionTranslator", obj: VariableTracker, attr: VariableTracker
) -> VariableTracker | None:
if attr.is_python_constant():
name = attr.as_python_constant()
if isinstance(obj, variables.BuiltinVariable):
return variables.ConstantVariable(hasattr(obj.fn, name))
return obj.call_obj_hasattr(tx, name)
return None
def call_map(
self, tx: "InstructionTranslator", fn: VariableTracker, *seqs: VariableTracker
) -> VariableTracker:
seq_list = [
seq.unpack_var_sequence(tx) if seq.has_unpack_var_sequence(tx) else seq
for seq in seqs
]
return variables.MapVariable(
fn,
seq_list, # type: ignore[arg-type]
mutation_type=ValueMutationNew(),
)
def call_filter(
self, tx: "InstructionTranslator", fn: VariableTracker, seq: VariableTracker
) -> VariableTracker:
seq_or_list = (
seq.unpack_var_sequence(tx) if seq.has_unpack_var_sequence(tx) else seq
)
return variables.FilterVariable(
fn,
seq_or_list, # type: ignore[arg-type]
mutation_type=ValueMutationNew(),
)
def var_getattr(self, tx: "InstructionTranslator", name: str) -> VariableTracker:
source = self.source and AttrSource(self.source, name)
if self.fn is object:
# for object, we can just directly read the attribute
try:
value = getattr(self.fn, name)
except AttributeError:
raise_observed_exception(AttributeError, tx)
# pyrefly: ignore [unbound-name]
if not callable(value):
# pyrefly: ignore [unbound-name]
return VariableTracker.build(tx, value, source)
return variables.GetAttrVariable(self, name, source=source)
def call_getattr(
self,
tx: "InstructionTranslator",
obj: VariableTracker,
name_var: VariableTracker,
default: VariableTracker | None = None,
) -> VariableTracker | None:
if not name_var.is_python_constant():
unimplemented(
gb_type="getattr() with non-constant name argument",
context=f"getattr({obj}, {name_var}, {default})",
explanation="getattr() with non-constant name argument is not supported",
hints=["Ensure the name argument of getattr() is a string"],
)
name = name_var.as_python_constant()
# See NOTE [Tensor "grad" and "_grad" attr]
if isinstance(obj, TensorVariable) and name == "_grad":
name = "grad"
if tx.output.side_effects.is_attribute_mutation(obj):
if isinstance(obj, variables.UnspecializedNNModuleVariable):
if (
name
in (
"named_parameters",
"parameters",
"named_buffers",
"buffers",
"named_modules",
"modules",
)
and obj.is_state_mutated
and tx.output.side_effects.has_pending_mutation(obj)
):
unimplemented(
gb_type="getattr() on nn.Module with pending mutation",
context=f"getattr({obj}, {name}, {default})",
explanation="Intentionally graph breaking on getattr() on a nn.Module "
"with a pending mutation",
hints=[],
)
if tx.output.side_effects.has_pending_mutation_of_attr(obj, name):
return tx.output.side_effects.load_attr(obj, name)
if default is not None:
hasattr_var = self.call_hasattr(tx, obj, name_var)
if hasattr_var is not None:
assert hasattr_var.as_python_constant() in (True, False)
if not hasattr_var.as_python_constant():
return default
else:
return default
source = obj.source and AttrSource(obj.source, name)
if name in {"__bases__", "__base__", "__flags__"}:
try:
value = obj.as_python_constant()
if isinstance(value, type):
if name == "__bases__":
tuple_args = [
VariableTracker.build(
tx, b, source and GetItemSource(source, i)
)
for i, b in enumerate(value.__bases__)
]
return variables.TupleVariable(tuple_args, source=source)
if name == "__base__":
return VariableTracker.build(tx, value.__base__, source)
if name == "__flags__":
return ConstantVariable.create(value.__flags__)
except NotImplementedError:
pass
if isinstance(obj, variables.NNModuleVariable):
return obj.var_getattr(tx, name)
elif isinstance(
obj,
(
variables.TensorVariable,
variables.NamedTupleVariable,
variables.ConstantVariable,
variables.DistributedVariable,
variables.UserDefinedClassVariable,
variables.UserDefinedObjectVariable,
),
):
if (
isinstance(obj, variables.UserDefinedObjectVariable)
and issubclass(obj.value.__class__, unittest.TestCase)
and config.enable_trace_unittest
and name
in (
"assertRaisesRegex",
"assertNotWarns",
"assertWarnsRegex",
"assertWarns",
)
):
unimplemented(
gb_type="Failed to trace unittest method",
context=f"function: unittest.TestCase.{name}",
explanation=f"Dynamo does not know how to trace unittest method `{name}` ",
hints=[
f"Avoid calling `TestCase.{name}`. "
"Please report an issue to PyTorch.",
],
)
if isinstance(obj, TensorVariable):
fake_val = obj.proxy.node.meta["example_value"]
if (
isinstance(fake_val, torch.Tensor)
and is_sparse_any(fake_val)
and (not tx.export or not config.capture_sparse_compute)
):
unimplemented(
gb_type="Attempted to wrap sparse Tensor",
context="",
explanation="torch.compile does not support sparse Tensors",
hints=[*graph_break_hints.SUPPORTABLE],
)
try:
return obj.var_getattr(tx, name)
except AsPythonConstantNotImplementedError:
# dont fallback on as_python_constant error because this leads
# to a failure later on, and leads to a wrong stacktrace
raise
except NotImplementedError:
return variables.GetAttrVariable(obj, name, source=source)
elif isinstance(obj, variables.TorchInGraphFunctionVariable):
# Get OpOverload from an OpOverloadPacket, e.g., torch.ops.aten.add.default.
member = getattr(obj.value, name)
if isinstance(
member, (torch._ops.OpOverloadPacket, torch._ops.OpOverload)
) and torch._dynamo.trace_rules.is_aten_op_or_tensor_method(member):
return variables.TorchInGraphFunctionVariable(member, source=source)
elif name in cmp_name_to_op_mapping:
return variables.GetAttrVariable(obj, name, source=source)
else:
return None
elif isinstance(obj, DummyModule):
# TODO(mlazos) - Do we need this?
if obj.is_torch or name not in obj.value.__dict__:
member = getattr(obj.value, name)
else:
member = obj.value.__dict__[name]
if config.replay_record_enabled:
tx.exec_recorder.record_module_access(obj.value, name, member) # type: ignore[arg-type, union-attr]
return VariableTracker.build(tx, member, source)
elif istype(obj, variables.UserFunctionVariable) and name in (
"__name__",
"__module__",
):
return ConstantVariable.create(getattr(obj.fn, name))
else:
try:
return obj.var_getattr(tx, name)
except NotImplementedError:
return variables.GetAttrVariable(obj, name, source=source)
def call_setattr(
self,
tx: "InstructionTranslator",
obj: VariableTracker,
name_var: VariableTracker,
val: VariableTracker,
) -> VariableTracker | None:
if isinstance(
obj,
(
variables.PlacementVariable,
variables.NamedTupleVariable,
variables.UserDefinedObjectVariable,
variables.NestedUserFunctionVariable,
variables.ExceptionVariable,
),
):
return obj.call_method(tx, "__setattr__", [name_var, val], {})
elif (
tx.output.side_effects.is_attribute_mutation(obj)
and name_var.is_python_constant()
):
name = name_var.as_python_constant()
if isinstance(obj, variables.TensorVariable):
from .builder import wrap_fx_proxy
# Some special handling for tensor attributes.
if name == "requires_grad":
# TODO(voz): Make it work properly
unimplemented(
gb_type="setattr() on Tensor.requires_grad",
context=f"setattr({obj}, {name}, {val})",
explanation="setattr() on Tensor.requires_grad not supported. "
"Mutating requires_grad can introduce a new leaf from non-leaf or vice versa in "
"the middle of the graph, which AOTAutograd does not currently know how to handle.",
hints=[*graph_break_hints.SUPPORTABLE],
)
elif name == "data":
# See comments on `test_set_data_on_scoped_tensor` for plans
# to support this.
if obj.source is None:
unimplemented(
gb_type="Failed to mutate tensor data attribute",
context=f"setattr({obj}, {name}, {val})",
explanation="Dyanmo only supports mutating `.data`"
" of tensor created outside `torch.compile` region",
hints=[
"Don't mutate `.data` on this tensor, or move "
"the mutation out of `torch.compile` region",
],
)
elif obj.dtype != val.dtype: # type: ignore[attr-defined]
unimplemented(
gb_type="Failed to mutate tensor data attribute to different dtype",
context=f"setattr({obj}, {name}, {val})",
explanation="Dyanmo only supports mutating `.data`"
" of tensor to a new one with the same dtype",
hints=[
"Don't mutate `.data` on this tensor, or move "
"the mutation out of `torch.compile` region",
],
)
# Remove the old reference in tracked fakes - if we don't do this
# new .data value size and shape differences will cause
# tracked fakes to produce incorrect guards. This is sound because the TensorVariable
# coming out of set_() below will be a new one, and get
# installed in tracked fakes.
to_remove = [
tf for tf in tx.output.tracked_fakes if tf.source == obj.source
]
for tf in to_remove:
tx.output.tracked_fakes.remove(tf)
# Step 1 - disable grads
with dynamo_disable_grad(tx), torch.no_grad():
# Step 2 - call `set_`
out = wrap_fx_proxy(
tx,
tx.output.create_proxy(
"call_function",
torch.Tensor.set_,
*proxy_args_kwargs([obj, val], {}),
),
)
# Step 3 - drop the version counter - this is a step required to get
# .data setting to play correctly with the autograd engine.
# Essentially, dynamo is trying to faithfully preserve the (absurd)
# behavior of .data= from eager mode
def _lower_version_count_by_1(x: torch.Tensor) -> torch.Tensor:
version = x._version
if version > 0:
version = version - 1
torch._C._autograd._unsafe_set_version_counter((x,), (version,))
return x
tx.output.create_proxy(
"call_function",
_lower_version_count_by_1,
(out.as_proxy(),),
{},
)
_lower_version_count_by_1(obj.as_proxy().node.meta["example_value"])
# This handles options prop, guards and ends with a clone
# Step 4 - replace all reference to the current object with the new one
return out
elif name in ("_grad", "grad"):
# NOTE: [Tensor "grad" and "_grad" attr]
# _grad and grad share the same setter/getter, see
# THPVariable_properties, and here we make sure setting one
# enables reading `val` from the other, by routing all
# read/write to `grad`.
name = "grad"
elif is_tensor_getset_descriptor(name):
# Attribute like `torch.Tensor.real` has special setters we
# don't yet support; it's not as simple adding an entry to
# the side effect mapping.
unimplemented(
gb_type="Failed to set tensor attribute",
context=f"setattr({obj}, {name}, {val})",
explanation="Dyanmo doesn't support setting these tensor attributes",
hints=[
f"Don't mutate attribute '{name}' on tensors, or "
"move the mutation out of `torch.compile` region",
],
)
tx.output.side_effects.store_attr(obj, name, val)
return val
elif isinstance(obj, variables.NNModuleVariable):
if not tx.output.is_root_tracer():
raise AttributeMutationError(
"Can't inplace modify module params/buffers inside HigherOrderOp"
)
if name_var.is_python_constant() and isinstance(
val, variables.TensorVariable
):
assigning_fake_val = get_fake_value(val.as_proxy().node, tx)
try:
getattr_var = obj.var_getattr(tx, name_var.as_python_constant())
except (AttributeError, ObservedAttributeError):
getattr_var = None
if isinstance(getattr_var, variables.TensorVariable):
# get_fake_val will get the same fake tensor
existing_fake_attr = get_fake_value(getattr_var.as_proxy().node, tx)
# same tensor identity, setattr is a no-op
mod_setattr = inspect.getattr_static(obj.module_type, "__setattr__")
if (
existing_fake_attr is assigning_fake_val
and mod_setattr is torch.nn.Module.__setattr__
):
return getattr_var
obj.convert_to_unspecialized(tx)
return None
def call_delattr(
self,
tx: "InstructionTranslator",
obj: VariableTracker,
name_var: VariableTracker,
) -> VariableTracker:
return obj.call_method(tx, "__delattr__", [name_var], {})
def call_type(
self, tx: "InstructionTranslator", obj: VariableTracker
) -> VariableTracker:
try:
py_type = obj.python_type()
except NotImplementedError as error:
raise UserError(
UserErrorType.INVALID_INPUT,
str(error),
case_name="unknown_python_type",
) from None
source = obj.source and TypeSource(obj.source)
if (
source is None
and isinstance(obj, variables.UserDefinedObjectVariable)
and obj.cls_source
):
source = obj.cls_source
if py_type is torch.Tensor:
# In some cases torch isn't available in globals
name = tx.output.install_global_by_id("", torch)
source = AttrSource(GlobalSource(name), "Tensor")
return VariableTracker.build(tx, py_type, source)
def call_reversed(
self, tx: "InstructionTranslator", obj: VariableTracker
) -> VariableTracker | None:
if obj.has_unpack_var_sequence(tx):
items = list(reversed(obj.unpack_var_sequence(tx)))
return variables.TupleVariable(items)
return None
def call_sorted(
self,
tx: "InstructionTranslator",
obj: VariableTracker,
**kwargs: VariableTracker,
) -> VariableTracker | None:
if obj.has_force_unpack_var_sequence(tx) and not isinstance(
obj, variables.TensorVariable
):
list_var = variables.ListVariable(
obj.force_unpack_var_sequence(tx),
mutation_type=ValueMutationNew(),
)
list_var.call_method(tx, "sort", [], kwargs)
return list_var
return None
# neg is a constant fold function, so we only get here if constant fold is not valid
def call_neg(
self, tx: "InstructionTranslator", a: VariableTracker
) -> VariableTracker | None:
if isinstance(a, SymNodeVariable):
return SymNodeVariable.create(
tx,
(operator.neg)(a.as_proxy()),
sym_num=None,
)
if (
isinstance(a, UserDefinedObjectVariable)
and a.call_obj_hasattr(tx, "__neg__").value # type: ignore[attr-defined]
):
return a.call_method(tx, "__neg__", [], {})
# None no-ops this handler and lets the driving function proceed
return None
def call_format(
self,
tx: "InstructionTranslator",
_format_string: VariableTracker,
*args: VariableTracker,
**kwargs: VariableTracker,
) -> VariableTracker:
format_string = _format_string.as_python_constant()
format_string = str(format_string)
return variables.StringFormatVariable.create(format_string, args, kwargs)
def call_id(
self, tx: "InstructionTranslator", *args: VariableTracker
) -> VariableTracker:
if len(args) > 0 and isinstance(args[0], variables.NNModuleVariable):
nn_mod_variable = args[0]
mod = tx.output.get_submodule(nn_mod_variable.module_key)
return variables.ConstantVariable.create(id(mod))
elif len(args) == 1 and isinstance(
args[0],
(variables.UserDefinedClassVariable, variables.UserDefinedObjectVariable),
):
if args[0].source:
if isinstance(args[0], variables.UserDefinedClassVariable):
install_guard(args[0].source.make_guard(GuardBuilder.CLASS_MATCH))
else:
install_guard(args[0].source.make_guard(GuardBuilder.ID_MATCH))
constant_result = id(args[0].value)
return variables.ConstantVariable.create(constant_result)
elif len(args) == 1 and isinstance(args[0], TensorVariable):
tensor_variable = args[0]
return tensor_variable.call_id(tx)
elif istype(args[0], variables.UserFunctionVariable):
return variables.ConstantVariable.create(id(args[0].fn))
elif istype(args[0], variables.SkipFunctionVariable):
return variables.ConstantVariable.create(id(args[0].value))
elif istype(args[0], variables.FunctoolsPartialVariable):
return variables.ConstantVariable.create(id(args[0].fake_value))
else:
unimplemented(
gb_type="id() with unsupported args",
context=str(args),
explanation=f"Dynamo doesn't know how to trace id() call with args {args}",
hints=[
"Supported args are Tensors, and functions/nn.Modules/user-defined objects "
"from outside the compiled region.",
*graph_break_hints.SUPPORTABLE,
],
)
def call_deepcopy(
self, tx: "InstructionTranslator", x: VariableTracker
) -> VariableTracker:
unimplemented(
gb_type="copy.deepcopy()",
context=f"copy.deepcopy({x})",
explanation="Dynamo does not support copy.deepcopy()",
hints=[
"Avoid calling copy.deepcopy()",
*graph_break_hints.SUPPORTABLE,
],
)
def _comparison_with_tensor(
self, tx: "InstructionTranslator", left: VariableTracker, right: VariableTracker
) -> VariableTracker:
from .builder import wrap_fx_proxy_cls
from .tensor import supported_tensor_comparison_op_values
op = self.fn
if op in [operator.is_, operator.is_not]:
is_result = (
isinstance(left, TensorVariable)
and isinstance(right, TensorVariable)
and id(extract_fake_example_value(left.as_proxy().node))
== id(extract_fake_example_value(right.as_proxy().node))
)
if op is operator.is_:
return ConstantVariable.create(is_result)
else:
return ConstantVariable.create(not is_result)
if op not in supported_tensor_comparison_op_values:
unimplemented(
gb_type="unsupported Tensor comparison op",
context=f"{op.__name__}({left}, {right})",
explanation=f"Dynamo does not support the comparison op {op.__name__} "
f"with Tensor arguments {left}, {right}",
hints=[*graph_break_hints.SUPPORTABLE],
)
if (
isinstance(left, TensorVariable)
and isinstance(right, TensorVariable)
and (left.size and right.size) is not None
and left.size != right.size
):
try:
torch.broadcast_shapes(left.size, right.size)
except RuntimeError:
# not broadcastable, can't be compared
unimplemented(
gb_type="failed to broadcast when attempting Tensor comparison op",
context=f"{op.__name__}({left}, {right})",
explanation=f"Dynamo was unable to broad cast the arguments {left}, {right} "
f"when attempting to trace the comparison op {op.__name__}.",
hints=[*graph_break_hints.USER_ERROR],
)
tensor_cls = left if isinstance(left, TensorVariable) else right
proxy = tx.output.create_proxy(
"call_function", op, (left.as_proxy(), right.as_proxy()), {}
)
return wrap_fx_proxy_cls(
type(tensor_cls), # handle Ndarrays and Tensors
tx,
proxy,
)
def _comparison_with_symnode(
self, tx: "InstructionTranslator", left: VariableTracker, right: VariableTracker
) -> VariableTracker:
from .tensor import supported_tensor_comparison_op_values
op = self.fn
if op not in supported_tensor_comparison_op_values:
unimplemented(
gb_type="unsupported SymNode comparison op",
context=f"{op.__name__}({left}, {right})",
explanation=f"Dynamo does not support the comparison op {op.__name__} "
f"with SymNode arguments {left}, {right}",
hints=[*graph_break_hints.SUPPORTABLE],
)
# This is seen in inspect signature where we check if the value is a default value
if isinstance(right, variables.UserDefinedClassVariable):
return variables.ConstantVariable(op(object(), None))
proxy = tx.output.create_proxy(
"call_function", op, (left.as_proxy(), right.as_proxy()), {}
)
return SymNodeVariable.create(
tx,
proxy,
sym_num=None,
)
def call_xor(
self, tx: "InstructionTranslator", a: VariableTracker, b: VariableTracker
) -> VariableTracker | None:
# Rely on constant_handler
if isinstance(a, ConstantVariable) and isinstance(b, ConstantVariable):
return None
if isinstance(a, (SymNodeVariable, ConstantVariable)) and isinstance(
b, (SymNodeVariable, ConstantVariable)
):
return SymNodeVariable.create(
tx,
tx.output.create_proxy(
"call_function", operator.xor, *proxy_args_kwargs([a, b], {})
),
sym_num=None,
)
if isinstance(
a,
(DictKeysVariable, SetVariable, UserDefinedObjectVariable),
):
return a.call_method(tx, "__xor__", [b], {})
return None
def call_ixor(
self, tx: "InstructionTranslator", a: VariableTracker, b: VariableTracker
) -> VariableTracker | None:
if isinstance(a, (DictKeysVariable, SetVariable, UserDefinedObjectVariable)):
return a.call_method(tx, "__ixor__", [b], {})
return None
def call_sub(
self, tx: "InstructionTranslator", a: VariableTracker, b: VariableTracker
) -> VariableTracker | None:
if isinstance(a, (DictKeysVariable, SetVariable, UserDefinedObjectVariable)):
return a.call_method(tx, "__sub__", [b], {})
return None
def call_isub(
self, tx: "InstructionTranslator", a: VariableTracker, b: VariableTracker
) -> VariableTracker | None:
if isinstance(a, (DictKeysVariable, SetVariable, UserDefinedObjectVariable)):
return a.call_method(tx, "__isub__", [b], {})
return None
def call_and_(
self, tx: "InstructionTranslator", a: VariableTracker, b: VariableTracker
) -> VariableTracker | None:
# Rely on constant_handler
if isinstance(a, ConstantVariable) and isinstance(b, ConstantVariable):
return None
if isinstance(a, (SymNodeVariable, ConstantVariable)) and isinstance(
b, (SymNodeVariable, ConstantVariable)
):
return SymNodeVariable.create(
tx,
tx.output.create_proxy(
"call_function", operator.and_, *proxy_args_kwargs([a, b], {})
),
sym_num=None,
)
if isinstance(a, (DictKeysVariable, SetVariable, UserDefinedObjectVariable)):
return a.call_method(tx, "__and__", [b], {})
# None no-ops this handler and lets the driving function proceed
return None
def call_iand(
self, tx: "InstructionTranslator", a: VariableTracker, b: VariableTracker
) -> VariableTracker | None:
# Rely on constant_handler
if isinstance(a, ConstantVariable) and isinstance(b, ConstantVariable):
return None
if isinstance(a, (SymNodeVariable, ConstantVariable)) and isinstance(
b, (SymNodeVariable, ConstantVariable)
):
return SymNodeVariable.create(
tx,
tx.output.create_proxy(
"call_function", operator.iand, *proxy_args_kwargs([a, b], {})
),
sym_num=None,
)
if isinstance(a, (DictKeysVariable, SetVariable, UserDefinedObjectVariable)):
return a.call_method(tx, "__iand__", [b], {})
return None
def call_or_(
self, tx: "InstructionTranslator", a: VariableTracker, b: VariableTracker
) -> VariableTracker | None:
# Rely on constant_handler
if isinstance(a, ConstantVariable) and isinstance(b, ConstantVariable):
return None
if isinstance(a, (SymNodeVariable, ConstantVariable)) and isinstance(
b, (SymNodeVariable, ConstantVariable)
):
return SymNodeVariable.create(
tx,
tx.output.create_proxy(
"call_function", operator.or_, *proxy_args_kwargs([a, b], {})
),
sym_num=None,
)
# This call looks like `{"one": torch.ones(1)} | {"two": torch.ones(2)}`.
if isinstance(
a,
(
ConstDictVariable,
DictKeysVariable,
MutableMappingVariable,
SetVariable,
UserDefinedDictVariable,
UserDefinedObjectVariable,
),
):
# TODO(guilhermeleobas): forward the call to b.__ror__(a) if
# a.__ror__(b) returns NotImplemented
return a.call_method(tx, "__or__", [b], {})
# None no-ops this handler and lets the driving function proceed
return None
def call_ior(
self, tx: "InstructionTranslator", a: VariableTracker, b: VariableTracker
) -> VariableTracker | None:
# Rely on constant_handler
if isinstance(a, ConstantVariable) and isinstance(b, ConstantVariable):
return None
if isinstance(a, (SymNodeVariable, ConstantVariable)) and isinstance(
b, (SymNodeVariable, ConstantVariable)
):
return SymNodeVariable.create(
tx,
tx.output.create_proxy(
"call_function", operator.ior, *proxy_args_kwargs([a, b], {})
),
sym_num=None,
)
# This call looks like `{"one": torch.ones(1)} |= {"two": torch.ones(2)}`.
if isinstance(
a,
(
ConstDictVariable,
DictKeysVariable,
MutableMappingVariable,
SetVariable,
UserDefinedObjectVariable,
),
):
return a.call_method(tx, "__ior__", [b], {})
# None no-ops this handler and lets the driving function proceed
return None
def call_not_(
self, tx: "InstructionTranslator", a: VariableTracker
) -> VariableTracker | None:
if isinstance(a, SymNodeVariable):
return SymNodeVariable.create(
tx,
tx.output.create_proxy(
"call_function", operator.not_, *proxy_args_kwargs([a], {})
),
sym_num=None,
)
# Unwrap the underlying ConstDictVariable
if isinstance(a, DictViewVariable):
a = a.dv_dict
if isinstance(a, (ListVariable, ConstDictVariable)):
return ConstantVariable.create(len(a.items) == 0)
return None
def call_contains(
self, tx: "InstructionTranslator", a: VariableTracker, b: VariableTracker
) -> VariableTracker:
return a.call_method(tx, "__contains__", [b], {})
@contextlib.contextmanager
def dynamo_disable_grad(tx: "InstructionTranslator") -> typing.Iterator[None]:
from . import GradModeVariable
gmv = GradModeVariable.create(tx, False)
try:
gmv.enter(tx)
yield
finally:
gmv.exit(tx)
| BuiltinVariable |
python | kamyu104__LeetCode-Solutions | Python/alternating-groups-i.py | {
"start": 60,
"end": 634
} | class ____(object):
def numberOfAlternatingGroups(self, colors):
"""
:type colors: List[int]
:rtype: int
"""
k = 3
result = curr = left = 0
for right in xrange(len(colors)+k-1):
if right-left+1 == k:
result += int(curr == k-1)
curr -= int(colors[left] != colors[(left+1)%len(colors)])
left += 1
curr += int(colors[right%len(colors)] != colors[(right+1)%len(colors)])
return result
# Time: O(n)
# Space: O(1)
# sliding window
| Solution |
python | kamyu104__LeetCode-Solutions | Python/replace-all-s-to-avoid-consecutive-repeating-characters.py | {
"start": 29,
"end": 445
} | class ____(object):
def modifyString(self, s):
"""
:type s: str
:rtype: str
"""
s = list(s)
for i in xrange(len(s)):
if s[i] != '?':
continue
for c in ('a', 'b', 'c'):
if (i == 0 or s[i-1] != c) and (i == len(s)-1 or c != s[i+1]):
break
s[i] = c
return "".join(s)
| Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/super1.py | {
"start": 358,
"end": 651
} | class ____(ClassA):
def __init__(self):
pass
def method3(self):
return self.__class__()
@staticmethod
def aaa():
# This should generate an error because the zero-arg form
# of super is illegal in a static method.
super().method1()
| ClassC |
python | ray-project__ray | python/ray/air/_internal/mlflow.py | {
"start": 315,
"end": 12627
} | class ____:
"""Util class for setting up and logging to MLflow.
Use this util for any library that needs MLflow logging/tracking logic
such as Ray Tune or Ray Train.
"""
def __init__(self):
import mlflow
self._mlflow = mlflow
self.experiment_id = None
def __deepcopy__(self, memo=None):
# mlflow is a module, and thus cannot be copied
_mlflow = self._mlflow
self.__dict__.pop("_mlflow")
dict_copy = deepcopy(self.__dict__, memo)
copied_object = _MLflowLoggerUtil()
copied_object.__dict__.update(dict_copy)
self._mlflow = _mlflow
copied_object._mlflow = _mlflow
return copied_object
def setup_mlflow(
self,
tracking_uri: Optional[str] = None,
registry_uri: Optional[str] = None,
experiment_id: Optional[str] = None,
experiment_name: Optional[str] = None,
tracking_token: Optional[str] = None,
artifact_location: Optional[str] = None,
create_experiment_if_not_exists: bool = True,
):
"""
Sets up MLflow.
Sets the Mlflow tracking uri & token, and registry URI. Also sets
the MLflow experiment that the logger should use, and possibly
creates new experiment if it does not exist.
Args:
tracking_uri: The tracking URI for the MLflow tracking
server.
registry_uri: The registry URI for the MLflow model registry.
experiment_id: The id of an already existing MLflow
experiment to use for logging. If None is passed in
here and the MFLOW_EXPERIMENT_ID is not set, or the
experiment with this id does not exist,
``experiment_name`` will be used instead. This argument takes
precedence over ``experiment_name`` if both are passed in.
experiment_name: The experiment name to use for logging.
If None is passed in here, the MLFLOW_EXPERIMENT_NAME environment
variable is used to determine the experiment name.
If the experiment with the name already exists with MLflow,
it will be reused. If not, a new experiment will be created
with the provided name if
``create_experiment_if_not_exists`` is set to True.
artifact_location: The location to store run artifacts.
If not provided, MLFlow picks an appropriate default.
Ignored if experiment already exists.
tracking_token: Tracking token used to authenticate with MLflow.
create_experiment_if_not_exists: Whether to create an
experiment with the provided name if it does not already
exist. Defaults to True.
Returns:
Whether setup is successful.
"""
if tracking_token:
os.environ["MLFLOW_TRACKING_TOKEN"] = tracking_token
self._mlflow.set_tracking_uri(tracking_uri)
self._mlflow.set_registry_uri(registry_uri)
# First check experiment_id.
experiment_id = (
experiment_id
if experiment_id is not None
else os.environ.get("MLFLOW_EXPERIMENT_ID")
)
if experiment_id is not None:
from mlflow.exceptions import MlflowException
try:
self._mlflow.get_experiment(experiment_id=experiment_id)
logger.debug(
f"Experiment with provided id {experiment_id} "
"exists. Setting that as the experiment."
)
self.experiment_id = experiment_id
return
except MlflowException:
pass
# Then check experiment_name.
experiment_name = (
experiment_name
if experiment_name is not None
else os.environ.get("MLFLOW_EXPERIMENT_NAME")
)
if experiment_name is not None and self._mlflow.get_experiment_by_name(
name=experiment_name
):
logger.debug(
f"Experiment with provided name {experiment_name} "
"exists. Setting that as the experiment."
)
self.experiment_id = self._mlflow.get_experiment_by_name(
experiment_name
).experiment_id
return
# An experiment with the provided id or name does not exist.
# Create a new experiment if applicable.
if experiment_name and create_experiment_if_not_exists:
logger.debug(
"Existing experiment not found. Creating new "
f"experiment with name: {experiment_name}"
)
self.experiment_id = self._mlflow.create_experiment(
name=experiment_name, artifact_location=artifact_location
)
return
if create_experiment_if_not_exists:
raise ValueError(
f"Experiment with the provided experiment_id: "
f"{experiment_id} does not exist and no "
f"experiment_name provided. At least one of "
f"these has to be provided."
)
else:
raise ValueError(
f"Experiment with the provided experiment_id: "
f"{experiment_id} or experiment_name: "
f"{experiment_name} does not exist. Please "
f"create an MLflow experiment and provide "
f"either its id or name."
)
def _parse_dict(self, dict_to_log: Dict) -> Dict:
"""Parses provided dict to convert all values to float.
MLflow can only log metrics that are floats. This does not apply to
logging parameters or artifacts.
Args:
dict_to_log: The dictionary containing the metrics to log.
Returns:
A dictionary containing the metrics to log with all values being
converted to floats, or skipped if not able to be converted.
"""
new_dict = {}
for key, value in dict_to_log.items():
try:
value = float(value)
new_dict[key] = value
except (ValueError, TypeError):
logger.debug(
"Cannot log key {} with value {} since the "
"value cannot be converted to float.".format(key, value)
)
continue
return new_dict
def start_run(
self,
run_name: Optional[str] = None,
tags: Optional[Dict] = None,
set_active: bool = False,
) -> "Run":
"""Starts a new run and possibly sets it as the active run.
Args:
tags: Tags to set for the new run.
set_active: Whether to set the new run as the active run.
If an active run already exists, then that run is returned.
Returns:
The newly created MLflow run.
"""
import mlflow
from mlflow.utils.mlflow_tags import MLFLOW_RUN_NAME
if tags is None:
tags = {}
if set_active:
return self._start_active_run(run_name=run_name, tags=tags)
client = self._get_client()
# If `mlflow==1.30.0` and we don't use `run_name`, then MLflow might error. For
# more information, see #29749.
if version.parse(mlflow.__version__) >= version.parse("1.30.0"):
run = client.create_run(
run_name=run_name, experiment_id=self.experiment_id, tags=tags
)
else:
tags[MLFLOW_RUN_NAME] = run_name
run = client.create_run(experiment_id=self.experiment_id, tags=tags)
return run
def _start_active_run(
self, run_name: Optional[str] = None, tags: Optional[Dict] = None
) -> "Run":
"""Starts a run and sets it as the active run if one does not exist.
If an active run already exists, then returns it.
"""
active_run = self._mlflow.active_run()
if active_run:
return active_run
return self._mlflow.start_run(
run_name=run_name, experiment_id=self.experiment_id, tags=tags
)
def _run_exists(self, run_id: str) -> bool:
"""Check if run with the provided id exists."""
from mlflow.exceptions import MlflowException
try:
self._mlflow.get_run(run_id=run_id)
return True
except MlflowException:
return False
def _get_client(self) -> "MlflowClient":
"""Returns an ml.tracking.MlflowClient instance to use for logging."""
tracking_uri = self._mlflow.get_tracking_uri()
registry_uri = self._mlflow.get_registry_uri()
from mlflow.tracking import MlflowClient
return MlflowClient(tracking_uri=tracking_uri, registry_uri=registry_uri)
def log_params(self, params_to_log: Dict, run_id: Optional[str] = None):
"""Logs the provided parameters to the run specified by run_id.
If no ``run_id`` is passed in, then logs to the current active run.
If there is not active run, then creates a new run and sets it as
the active run.
Args:
params_to_log: Dictionary of parameters to log.
run_id (Optional[str]): The ID of the run to log to.
"""
params_to_log = flatten_dict(params_to_log)
if run_id and self._run_exists(run_id):
client = self._get_client()
for key, value in params_to_log.items():
client.log_param(run_id=run_id, key=key, value=value)
else:
for key, value in params_to_log.items():
self._mlflow.log_param(key=key, value=value)
def log_metrics(self, step, metrics_to_log: Dict, run_id: Optional[str] = None):
"""Logs the provided metrics to the run specified by run_id.
If no ``run_id`` is passed in, then logs to the current active run.
If there is not active run, then creates a new run and sets it as
the active run.
Args:
metrics_to_log: Dictionary of metrics to log.
run_id (Optional[str]): The ID of the run to log to.
"""
metrics_to_log = flatten_dict(metrics_to_log)
metrics_to_log = self._parse_dict(metrics_to_log)
if run_id and self._run_exists(run_id):
client = self._get_client()
for key, value in metrics_to_log.items():
client.log_metric(run_id=run_id, key=key, value=value, step=step)
else:
for key, value in metrics_to_log.items():
self._mlflow.log_metric(key=key, value=value, step=step)
def save_artifacts(self, dir: str, run_id: Optional[str] = None):
"""Saves directory as artifact to the run specified by run_id.
If no ``run_id`` is passed in, then saves to the current active run.
If there is not active run, then creates a new run and sets it as
the active run.
Args:
dir: Path to directory containing the files to save.
run_id (Optional[str]): The ID of the run to log to.
"""
if run_id and self._run_exists(run_id):
client = self._get_client()
client.log_artifacts(run_id=run_id, local_dir=dir)
else:
self._mlflow.log_artifacts(local_dir=dir)
def end_run(self, status: Optional[str] = None, run_id=None):
"""Terminates the run specified by run_id.
If no ``run_id`` is passed in, then terminates the
active run if one exists.
Args:
status (Optional[str]): The status to set when terminating the run.
run_id (Optional[str]): The ID of the run to terminate.
"""
if (
run_id
and self._run_exists(run_id)
and not (
self._mlflow.active_run()
and self._mlflow.active_run().info.run_id == run_id
)
):
client = self._get_client()
client.set_terminated(run_id=run_id, status=status)
else:
self._mlflow.end_run(status=status)
| _MLflowLoggerUtil |
python | matplotlib__matplotlib | lib/matplotlib/sphinxext/mathmpl.py | {
"start": 3049,
"end": 7871
} | class ____(Directive):
"""
The ``.. mathmpl::`` directive, as documented in the module's docstring.
"""
has_content = True
required_arguments = 0
optional_arguments = 0
final_argument_whitespace = False
option_spec = {'fontset': fontset_choice,
'fontsize': validate_float_or_None}
def run(self):
latex = ''.join(self.content)
node = latex_math(self.block_text)
node['latex'] = latex
node['fontset'] = self.options.get('fontset', 'cm')
node['fontsize'] = self.options.get('fontsize',
setup.app.config.mathmpl_fontsize)
return [node]
# This uses mathtext to render the expression
def latex2png(latex, filename, fontset='cm', fontsize=10, dpi=100):
with mpl.rc_context({'mathtext.fontset': fontset, 'font.size': fontsize}):
try:
depth = mathtext.math_to_image(
f"${latex}$", filename, dpi=dpi, format="png")
except Exception:
_api.warn_external(f"Could not render math expression {latex}")
depth = 0
return depth
# LaTeX to HTML translation stuff:
def latex2html(node, source):
inline = isinstance(node.parent, nodes.TextElement)
latex = node['latex']
fontset = node['fontset']
fontsize = node['fontsize']
name = 'math-{}'.format(
hashlib.sha256(
f'{latex}{fontset}{fontsize}'.encode(),
usedforsecurity=False,
).hexdigest()[-10:])
destdir = Path(setup.app.builder.outdir, '_images', 'mathmpl')
destdir.mkdir(parents=True, exist_ok=True)
dest = destdir / f'{name}.png'
depth = latex2png(latex, dest, fontset, fontsize=fontsize)
srcset = []
for size in setup.app.config.mathmpl_srcset:
filename = f'{name}-{size.replace(".", "_")}.png'
latex2png(latex, destdir / filename, fontset, fontsize=fontsize,
dpi=100 * float(size[:-1]))
srcset.append(
f'{setup.app.builder.imgpath}/mathmpl/{filename} {size}')
if srcset:
srcset = (f'srcset="{setup.app.builder.imgpath}/mathmpl/{name}.png, ' +
', '.join(srcset) + '" ')
if inline:
cls = ''
else:
cls = 'class="center" '
if inline and depth != 0:
style = 'style="position: relative; bottom: -%dpx"' % (depth + 1)
else:
style = ''
return (f'<img src="{setup.app.builder.imgpath}/mathmpl/{name}.png"'
f' {srcset}{cls}{style}/>')
def _config_inited(app, config):
# Check for srcset hidpi images
for i, size in enumerate(app.config.mathmpl_srcset):
if size[-1] == 'x': # "2x" = "2.0"
try:
float(size[:-1])
except ValueError:
raise ConfigError(
f'Invalid value for mathmpl_srcset parameter: {size!r}. '
'Must be a list of strings with the multiplicative '
'factor followed by an "x". e.g. ["2.0x", "1.5x"]')
else:
raise ConfigError(
f'Invalid value for mathmpl_srcset parameter: {size!r}. '
'Must be a list of strings with the multiplicative '
'factor followed by an "x". e.g. ["2.0x", "1.5x"]')
def setup(app):
setup.app = app
app.add_config_value('mathmpl_fontsize', 10.0, True)
app.add_config_value('mathmpl_srcset', [], True)
try:
app.connect('config-inited', _config_inited) # Sphinx 1.8+
except ExtensionError:
app.connect('env-updated', lambda app, env: _config_inited(app, None))
# Add visit/depart methods to HTML-Translator:
def visit_latex_math_html(self, node):
source = self.document.attributes['source']
self.body.append(latex2html(node, source))
def depart_latex_math_html(self, node):
pass
# Add visit/depart methods to LaTeX-Translator:
def visit_latex_math_latex(self, node):
inline = isinstance(node.parent, nodes.TextElement)
if inline:
self.body.append('$%s$' % node['latex'])
else:
self.body.extend(['\\begin{equation}',
node['latex'],
'\\end{equation}'])
def depart_latex_math_latex(self, node):
pass
app.add_node(latex_math,
html=(visit_latex_math_html, depart_latex_math_html),
latex=(visit_latex_math_latex, depart_latex_math_latex))
app.add_role('mathmpl', math_role)
app.add_directive('mathmpl', MathDirective)
if sphinx.version_info < (1, 8):
app.add_role('math', math_role)
app.add_directive('math', MathDirective)
metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
return metadata
| MathDirective |
python | pytorch__pytorch | test/distributed/tensor/test_redistribute.py | {
"start": 27305,
"end": 31524
} | class ____(DTensorTestBase):
@property
def world_size(self) -> int:
return 8
@with_comms
def test_multi_dim_mesh(self):
devices = torch.arange(self.world_size)
for mesh_shape in [devices, devices.view(4, 2), devices.view(2, 2, 2)]:
mesh_shape = torch.arange(self.world_size).view(-1, 2)
device_mesh = DeviceMesh(self.device_type, mesh_shape)
tensor_shape = (16, 24)
if torch.distributed.get_rank() == 0:
full_tensor = torch.randn(*tensor_shape)
else:
# these should be entirely ignored
# because distribute_tensor is expected to override shards in ranks != 0
full_tensor = torch.ones(*tensor_shape)
possibilities = [Replicate()] + [Shard(i) for i in range(full_tensor.ndim)]
all_outputs = list(itertools.product(*(mesh_shape.ndim * [possibilities])))
all_inputs = list(
itertools.product(*(mesh_shape.ndim * [possibilities + [Partial()]]))
)
for inputs in all_inputs:
# if partial, temporarily make it Replicated, then replace replicated with partial afterwards
repl_inputs = [Replicate() if s.is_partial() else s for s in inputs]
dt = distribute_tensor(full_tensor, device_mesh, repl_inputs)
if repl_inputs != inputs:
# create a new DTensor reinterpreting some of the replicated entries as "Partial"
dt = DTensor.from_local(
dt.to_local(), device_mesh, inputs, run_check=False
)
for outputs in all_outputs:
# redistribute on target outputs
dt2 = dt.redistribute(device_mesh, outputs)
# replicate and then get first shard
local_full = dt2.full_tensor()
if torch.distributed.get_rank() == 0:
self.assertEqual(local_full.shape, full_tensor.shape)
num_sums = 1
for idx, input in enumerate(inputs):
if input.is_partial():
num_sums *= mesh_shape.size(idx)
expected = num_sums * full_tensor
self.assertEqual(local_full, expected)
@with_comms
def test_redistribute_shard_dim_multi_dim_mesh(self):
mesh = init_device_mesh(self.device_type, (2, 2, 2))
input_data = torch.randn((8, 8, 8), device=self.device_type)
sharding_src_dst_pairs_3d = [
([Shard(0), Shard(0), Shard(0)], [Shard(1), Shard(1), Shard(1)]),
([Shard(0), Shard(1), Shard(0)], [Shard(1), Shard(0), Shard(0)]),
([Shard(0), Shard(1), Shard(2)], [Shard(2), Shard(1), Shard(0)]),
([Shard(1), Shard(0), Shard(0)], [Replicate(), Shard(0), Shard(0)]),
([Shard(1), Replicate(), Shard(0)], [Replicate(), Shard(0), Shard(0)]),
([Shard(0), Shard(0), Shard(1)], [Shard(0), Shard(1), Shard(2)]),
]
comm_counts_3d = [
3, # 2: S0 - R, 1: S1 -> R, 0: S0 -> S1
3, # 2: S0 -> R, 1: S1 -> R, 0: S0 -> S1, 1: R -> S0, 2: R -> S0
2, # 2: S2 -> R, 0: S1 -> S2
1, # 0: S1 -> R
2, # 2: S0 -> R, 1: R -> S0, 2: R -> S0, 0: S1 -> R
2, # 2: S1 -> S2, 1: S0 -> S1
]
comm_mode = CommDebugMode()
for idx, (src_placement, dst_placement) in enumerate(sharding_src_dst_pairs_3d):
expected_dt = distribute_tensor(input_data.clone(), mesh, dst_placement)
sharded_dt = distribute_tensor(input_data, mesh, src_placement)
with comm_mode:
out_dt = sharded_dt.redistribute(mesh, dst_placement)
self.assertEqual(out_dt.placements, expected_dt.placements)
self.assertEqual(comm_mode.get_total_counts(), comm_counts_3d[idx])
local_out_dt = out_dt.to_local()
local_expected_dt = expected_dt.to_local()
self.assertEqual(local_out_dt, local_expected_dt)
| MultiDimRedistributeTest |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/events.py | {
"start": 3631,
"end": 3681
} | class ____(Event):
__slots__ = ()
| StreamEndEvent |
python | sqlalchemy__sqlalchemy | test/orm/test_cycles.py | {
"start": 42390,
"end": 43900
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"a_table",
metadata,
Column(
"id",
Integer(),
primary_key=True,
test_needs_autoincrement=True,
),
Column("fui", String(128)),
Column("b", Integer(), ForeignKey("a_table.id")),
)
@classmethod
def setup_classes(cls):
class A(cls.Basic):
pass
def test_one(self):
"""
Test that post_update remembers to be involved in update operations as
well, since it replaces the normal dependency processing completely
[ticket:413]
"""
A, a_table = self.classes.A, self.tables.a_table
self.mapper_registry.map_imperatively(
A,
a_table,
properties={
"foo": relationship(
A, remote_side=[a_table.c.id], post_update=True
)
},
)
session = fixture_session()
f1 = A(fui="f1")
session.add(f1)
session.flush()
f2 = A(fui="f2", foo=f1)
# at this point f1 is already inserted. but we need post_update
# to fire off anyway
session.add(f2)
session.flush()
session.expunge_all()
f1 = session.get(A, f1.id)
f2 = session.get(A, f2.id)
assert f2.foo is f1
| SelfReferentialPostUpdateTest2 |
python | lepture__authlib | authlib/jose/drafts/_jwe_algorithms.py | {
"start": 581,
"end": 7199
} | class ____(JWEAlgorithmWithTagAwareKeyAgreement):
EXTRA_HEADERS = ["epk", "apu", "apv", "skid"]
ALLOWED_KEY_CLS = (ECKey, OKPKey)
# https://datatracker.ietf.org/doc/html/draft-madden-jose-ecdh-1pu-04
def __init__(self, key_size=None):
if key_size is None:
self.name = "ECDH-1PU"
self.description = "ECDH-1PU in the Direct Key Agreement mode"
else:
self.name = f"ECDH-1PU+A{key_size}KW"
self.description = (
f"ECDH-1PU using Concat KDF and CEK wrapped with A{key_size}KW"
)
self.key_size = key_size
self.aeskw = AESAlgorithm(key_size)
def prepare_key(self, raw_data):
if isinstance(raw_data, self.ALLOWED_KEY_CLS):
return raw_data
return ECKey.import_key(raw_data)
def generate_preset(self, enc_alg, key):
epk = self._generate_ephemeral_key(key)
h = self._prepare_headers(epk)
preset = {"epk": epk, "header": h}
if self.key_size is not None:
cek = enc_alg.generate_cek()
preset["cek"] = cek
return preset
def compute_shared_key(self, shared_key_e, shared_key_s):
return shared_key_e + shared_key_s
def compute_fixed_info(self, headers, bit_size, tag):
if tag is None:
cctag = b""
else:
cctag = u32be_len_input(tag)
# AlgorithmID
if self.key_size is None:
alg_id = u32be_len_input(headers["enc"])
else:
alg_id = u32be_len_input(headers["alg"])
# PartyUInfo
apu_info = u32be_len_input(headers.get("apu"), True)
# PartyVInfo
apv_info = u32be_len_input(headers.get("apv"), True)
# SuppPubInfo
pub_info = struct.pack(">I", bit_size) + cctag
return alg_id + apu_info + apv_info + pub_info
def compute_derived_key(self, shared_key, fixed_info, bit_size):
ckdf = ConcatKDFHash(
algorithm=hashes.SHA256(),
length=bit_size // 8,
otherinfo=fixed_info,
backend=default_backend(),
)
return ckdf.derive(shared_key)
def deliver_at_sender(
self,
sender_static_key,
sender_ephemeral_key,
recipient_pubkey,
headers,
bit_size,
tag,
):
shared_key_s = sender_static_key.exchange_shared_key(recipient_pubkey)
shared_key_e = sender_ephemeral_key.exchange_shared_key(recipient_pubkey)
shared_key = self.compute_shared_key(shared_key_e, shared_key_s)
fixed_info = self.compute_fixed_info(headers, bit_size, tag)
return self.compute_derived_key(shared_key, fixed_info, bit_size)
def deliver_at_recipient(
self,
recipient_key,
sender_static_pubkey,
sender_ephemeral_pubkey,
headers,
bit_size,
tag,
):
shared_key_s = recipient_key.exchange_shared_key(sender_static_pubkey)
shared_key_e = recipient_key.exchange_shared_key(sender_ephemeral_pubkey)
shared_key = self.compute_shared_key(shared_key_e, shared_key_s)
fixed_info = self.compute_fixed_info(headers, bit_size, tag)
return self.compute_derived_key(shared_key, fixed_info, bit_size)
def _generate_ephemeral_key(self, key):
return key.generate_key(key["crv"], is_private=True)
def _prepare_headers(self, epk):
# REQUIRED_JSON_FIELDS contains only public fields
pub_epk = {k: epk[k] for k in epk.REQUIRED_JSON_FIELDS}
pub_epk["kty"] = epk.kty
return {"epk": pub_epk}
def generate_keys_and_prepare_headers(self, enc_alg, key, sender_key, preset=None):
if not isinstance(enc_alg, CBCHS2EncAlgorithm):
raise InvalidEncryptionAlgorithmForECDH1PUWithKeyWrappingError()
if preset and "epk" in preset:
epk = preset["epk"]
h = {}
else:
epk = self._generate_ephemeral_key(key)
h = self._prepare_headers(epk)
if preset and "cek" in preset:
cek = preset["cek"]
else:
cek = enc_alg.generate_cek()
return {"epk": epk, "cek": cek, "header": h}
def _agree_upon_key_at_sender(
self, enc_alg, headers, key, sender_key, epk, tag=None
):
if self.key_size is None:
bit_size = enc_alg.CEK_SIZE
else:
bit_size = self.key_size
public_key = key.get_op_key("wrapKey")
return self.deliver_at_sender(
sender_key, epk, public_key, headers, bit_size, tag
)
def _wrap_cek(self, cek, dk):
kek = self.aeskw.prepare_key(dk)
return self.aeskw.wrap_cek(cek, kek)
def agree_upon_key_and_wrap_cek(
self, enc_alg, headers, key, sender_key, epk, cek, tag
):
dk = self._agree_upon_key_at_sender(enc_alg, headers, key, sender_key, epk, tag)
return self._wrap_cek(cek, dk)
def wrap(self, enc_alg, headers, key, sender_key, preset=None):
# In this class this method is used in direct key agreement mode only
if self.key_size is not None:
raise RuntimeError("Invalid algorithm state detected")
if preset and "epk" in preset:
epk = preset["epk"]
h = {}
else:
epk = self._generate_ephemeral_key(key)
h = self._prepare_headers(epk)
dk = self._agree_upon_key_at_sender(enc_alg, headers, key, sender_key, epk)
return {"ek": b"", "cek": dk, "header": h}
def unwrap(self, enc_alg, ek, headers, key, sender_key, tag=None):
if "epk" not in headers:
raise ValueError('Missing "epk" in headers')
if self.key_size is None:
bit_size = enc_alg.CEK_SIZE
else:
bit_size = self.key_size
sender_pubkey = sender_key.get_op_key("wrapKey")
epk = key.import_key(headers["epk"])
epk_pubkey = epk.get_op_key("wrapKey")
dk = self.deliver_at_recipient(
key, sender_pubkey, epk_pubkey, headers, bit_size, tag
)
if self.key_size is None:
return dk
kek = self.aeskw.prepare_key(dk)
return self.aeskw.unwrap(enc_alg, ek, headers, kek)
JWE_DRAFT_ALG_ALGORITHMS = [
ECDH1PUAlgorithm(None), # ECDH-1PU
ECDH1PUAlgorithm(128), # ECDH-1PU+A128KW
ECDH1PUAlgorithm(192), # ECDH-1PU+A192KW
ECDH1PUAlgorithm(256), # ECDH-1PU+A256KW
]
def register_jwe_alg_draft(cls):
for alg in JWE_DRAFT_ALG_ALGORITHMS:
cls.register_algorithm(alg)
| ECDH1PUAlgorithm |
python | fluentpython__example-code-2e | 24-class-metaprog/autoconst/autoconst_demo.py | {
"start": 742,
"end": 846
} | class ____(AutoConst):
banana
coconut
vanilla
print('Flavor.vanilla ==', Flavor.vanilla) | Flavor |
python | ansible__ansible | test/integration/targets/task-args/action_plugins/echo.py | {
"start": 84,
"end": 244
} | class ____(ActionBase):
def run(self, tmp=None, task_vars=None):
action_args = self._task.args
return dict(action_args=action_args)
| ActionModule |
python | numba__numba | numba/np/ufunc/wrappers.py | {
"start": 24350,
"end": 24997
} | class ____(object):
"""
Handle GFunc argument loading where a scalar type is used in the core
function.
Note: It still has a stride because the input to the gufunc can be an array
for this argument.
"""
def __init__(self, dtype, stride):
self.dtype = dtype
self.stride = stride
def load(self, context, builder, data, ind):
# Load at base + ind * stride
data = builder.gep(data, [builder.mul(ind, self.stride)])
dptr = builder.bitcast(data,
context.get_data_type(self.dtype).as_pointer())
return builder.load(dptr)
| _ScalarArgLoader |
python | spack__spack | lib/spack/spack/environment/environment.py | {
"start": 119695,
"end": 119807
} | class ____(SpackEnvironmentError):
"""Class for errors regarding view generation."""
| SpackEnvironmentViewError |
python | getsentry__sentry | src/sentry/incidents/endpoints/serializers/workflow_engine_detector.py | {
"start": 1669,
"end": 16136
} | class ____(Serializer):
"""
A temporary serializer to be used by the old alert rule endpoints to return data read from the new ACI models
"""
def __init__(self, expand: list[str] | None = None, prepare_component_fields: bool = False):
self.expand = expand or []
self.prepare_component_fields = prepare_component_fields
def add_sentry_app_installations_by_sentry_app_id(
self, actions: list[Action], organization_id: int
) -> Mapping[str, RpcSentryAppComponentContext]:
sentry_app_installations_by_sentry_app_id: Mapping[str, RpcSentryAppComponentContext] = {}
if self.prepare_component_fields:
sentry_app_ids = [
int(action.config.get("target_identifier"))
for action in actions
if action.config.get("sentry_app_identifier") is not None
]
install_contexts = app_service.get_component_contexts(
filter={"app_ids": sentry_app_ids, "organization_id": organization_id},
component_type="alert-rule-action",
)
sentry_app_installations_by_sentry_app_id = {
str(context.installation.sentry_app.id): context
for context in install_contexts
if context.installation.sentry_app
}
return sentry_app_installations_by_sentry_app_id
def add_triggers_and_actions(
self,
result: DefaultDict[Detector, dict[str, Any]],
detectors: dict[int, Detector],
sentry_app_installations_by_sentry_app_id: Mapping[str, RpcSentryAppComponentContext],
serialized_data_conditions: list[dict[str, Any]],
) -> None:
for serialized in serialized_data_conditions:
errors = []
alert_rule_id = serialized.get("alertRuleId")
assert alert_rule_id
try:
detector_id = AlertRuleDetector.objects.values_list("detector_id", flat=True).get(
alert_rule_id=alert_rule_id
)
except AlertRuleDetector.DoesNotExist:
detector_id = get_object_id_from_fake_id(int(alert_rule_id))
detector = detectors[int(detector_id)]
alert_rule_triggers = result[detector].setdefault("triggers", [])
for action in serialized.get("actions", []):
if action is None:
continue
# Prepare AlertRuleTriggerActions that are SentryApp components
install_context = None
sentry_app_id = str(action.get("sentryAppId"))
if sentry_app_id:
install_context = sentry_app_installations_by_sentry_app_id.get(sentry_app_id)
if install_context:
rpc_install = install_context.installation
rpc_component = install_context.component
rpc_app = rpc_install.sentry_app
assert rpc_app
action["sentryAppInstallationUuid"] = rpc_install.uuid
component = (
prepare_ui_component(
rpc_install,
rpc_component,
None,
action.get("settings"),
)
if rpc_component
else None
)
if component is None:
errors.append({"detail": f"Could not fetch details from {rpc_app.name}"})
action["disabled"] = True
continue
action["formFields"] = component.app_schema.get("settings", {})
if errors:
result[detector]["errors"] = errors
alert_rule_triggers.append(serialized)
def add_projects(
self, result: DefaultDict[Detector, dict[str, Any]], detectors: dict[int, Detector]
) -> None:
detector_projects = set()
for detector in detectors.values():
detector_projects.add((detector.id, detector.project.slug))
for detector_id, project_slug in detector_projects:
rule_result = result[detectors[detector_id]].setdefault(
"projects", []
) # keyerror I guess could be here
rule_result.append(project_slug)
def add_created_by(
self, result: DefaultDict[Detector, dict[str, Any]], detectors: Sequence[Detector]
) -> None:
user_by_user_id: MutableMapping[int, RpcUser] = {
user.id: user
for user in user_service.get_many_by_id(
ids=[
detector.created_by_id
for detector in detectors
if detector.created_by_id is not None
]
)
}
for detector in detectors:
# this is based on who created or updated it during dual write
rpc_user = None
if detector.created_by_id:
rpc_user = user_by_user_id.get(detector.created_by_id)
if not rpc_user:
result[detector]["created_by"] = None
else:
created_by = dict(
id=rpc_user.id, name=rpc_user.get_display_name(), email=rpc_user.email
)
result[detector]["created_by"] = created_by
def add_owner(
self, result: DefaultDict[Detector, dict[str, Any]], detectors: Sequence[Detector]
) -> None:
for detector in detectors:
if detector.owner_user_id or detector.owner_team_id:
actor = detector.owner
if actor:
result[detector]["owner"] = actor.identifier
def add_latest_incident(
self,
result: DefaultDict[Detector, dict[str, Any]],
user: User | RpcUser | AnonymousUser,
detectors: dict[int, Detector],
detector_to_action_ids: defaultdict[Detector, list[int]],
) -> None:
all_action_ids = []
for action_ids in detector_to_action_ids.values():
all_action_ids.extend(action_ids)
wf_action_group_statuses = WorkflowActionGroupStatus.objects.filter(
action_id__in=all_action_ids
)
detector_to_group_ids = defaultdict(set)
for wf_action_group_status in wf_action_group_statuses:
for detector, action_ids in detector_to_action_ids.items():
if wf_action_group_status.action_id in action_ids:
detector_to_group_ids[detector].add(wf_action_group_status.group_id)
open_periods = None
group_ids = {
wf_action_group_status.group_id for wf_action_group_status in wf_action_group_statuses
}
if group_ids:
open_periods = GroupOpenPeriod.objects.filter(group__in=group_ids)
for detector in detectors.values():
# TODO: this serializer is half baked
if open_periods:
latest_open_periods = open_periods.filter(
Q(group__in=detector_to_group_ids[detector])
).order_by("-date_started")
serialized_group_open_period = serialize(
latest_open_periods.first(), user, WorkflowEngineIncidentSerializer()
)
result[detector]["latestIncident"] = serialized_group_open_period
def get_attrs(
self, item_list: Sequence[Detector], user: User | RpcUser | AnonymousUser, **kwargs: Any
) -> defaultdict[Detector, dict[str, Any]]:
detectors = {item.id: item for item in item_list}
detector_ids = [item.id for item in item_list]
result: DefaultDict[Detector, dict[str, Any]] = defaultdict(dict)
detector_workflow_condition_group_ids = [
detector.workflow_condition_group.id
for detector in detectors.values()
if detector.workflow_condition_group
]
detector_trigger_data_conditions = DataCondition.objects.filter(
condition_group__in=detector_workflow_condition_group_ids,
condition_result__in=[DetectorPriorityLevel.HIGH, DetectorPriorityLevel.MEDIUM],
)
workflow_dcg_ids = DataConditionGroup.objects.filter(
workflowdataconditiongroup__workflow__in=Subquery(
DetectorWorkflow.objects.filter(detector__in=detector_ids).values_list(
"workflow_id", flat=True
)
)
).values_list("id", flat=True)
action_filter_data_condition_groups = DataCondition.objects.filter(
comparison__in=[
detector_trigger.condition_result
for detector_trigger in detector_trigger_data_conditions
],
condition_group__in=Subquery(workflow_dcg_ids),
)
dcgas = DataConditionGroupAction.objects.filter(
condition_group__in=[
action_filter.condition_group
for action_filter in action_filter_data_condition_groups
]
).select_related("action")
actions = [dcga.action for dcga in dcgas]
# add sentry app data
organization_id = [detector.project.organization_id for detector in detectors.values()][0]
sentry_app_installations_by_sentry_app_id = (
self.add_sentry_app_installations_by_sentry_app_id(actions, organization_id)
)
# add trigger and action data
serialized_data_conditions: list[dict[str, Any]] = []
for trigger in detector_trigger_data_conditions:
serialized_data_conditions.extend(
serialize(
[trigger],
user,
WorkflowEngineDataConditionSerializer(),
**kwargs,
)
)
self.add_triggers_and_actions(
result,
detectors,
sentry_app_installations_by_sentry_app_id,
serialized_data_conditions,
)
self.add_projects(result, detectors)
self.add_created_by(result, list(detectors.values()))
self.add_owner(result, list(detectors.values()))
# skipping snapshot data
if "latestIncident" in self.expand:
# to get the actions for a detector, we need to go from detector -> workflow -> action filters for that workflow -> actions
detector_workflow_values = DetectorWorkflow.objects.filter(
detector__in=detector_ids
).values_list("detector_id", "workflow_id")
detector_id_to_workflow_ids = defaultdict(list)
for detector_id, workflow_id in detector_workflow_values:
detector_id_to_workflow_ids[detector_id].append(workflow_id)
workflow_action_values = dcgas.values_list(
"condition_group__workflowdataconditiongroup__workflow_id", "action_id"
)
workflow_id_to_action_ids = defaultdict(list)
for workflow_id, action_id in workflow_action_values:
workflow_id_to_action_ids[workflow_id].append(action_id)
detector_to_action_ids = defaultdict(list)
for detector_id in detectors:
for workflow_id in detector_id_to_workflow_ids.get(detector_id, []):
detector_to_action_ids[detectors[detector_id]].extend(
workflow_id_to_action_ids.get(workflow_id, [])
)
self.add_latest_incident(result, user, detectors, detector_to_action_ids)
# add information from snubaquery
data_source_detectors = DataSourceDetector.objects.filter(detector_id__in=detectors.keys())
query_subscriptions = QuerySubscription.objects.filter(
id__in=[dsd.data_source.source_id for dsd in data_source_detectors]
)
for detector in detectors.values():
data_source_detector = data_source_detectors.get(Q(detector=detector))
query_subscription = query_subscriptions.get(
Q(id=data_source_detector.data_source.source_id)
)
result[detector]["query"] = query_subscription.snuba_query.query
result[detector]["aggregate"] = query_subscription.snuba_query.aggregate
result[detector]["timeWindow"] = query_subscription.snuba_query.time_window / 60
result[detector]["resolution"] = query_subscription.snuba_query.resolution / 60
return result
def serialize(self, obj: Detector, attrs, user, **kwargs) -> AlertRuleSerializerResponse:
triggers = attrs.get("triggers", [])
alert_rule_id = None
if triggers:
alert_rule_id = triggers[0].get("alertRuleId")
else:
try:
alert_rule_id = AlertRuleDetector.objects.values_list(
"alert_rule_id", flat=True
).get(detector=obj)
except AlertRuleDetector.DoesNotExist:
# this detector does not have an analog in the old system,
# but we need to return *something*
alert_rule_id = get_fake_id_from_object_id(obj.id)
data: AlertRuleSerializerResponse = {
"id": str(alert_rule_id),
"name": obj.name,
"organizationId": str(obj.project.organization_id),
"status": (
AlertRuleStatus.PENDING.value
if obj.enabled is True
else AlertRuleStatus.DISABLED.value
),
"query": attrs.get("query"),
"aggregate": attrs.get("aggregate"),
"timeWindow": attrs.get("timeWindow"),
"resolution": attrs.get("resolution"),
"thresholdPeriod": 1, # unset on detectors
"triggers": triggers,
"projects": sorted(attrs.get("projects", [])),
"owner": attrs.get("owner", None),
"dateModified": obj.date_updated,
"dateCreated": obj.date_added,
"createdBy": attrs.get("created_by"),
"description": obj.description if obj.description else "",
"detectionType": obj.config.get("detection_type"),
}
if "latestIncident" in self.expand:
data["latestIncident"] = attrs.get("latestIncident", None)
return data
| WorkflowEngineDetectorSerializer |
python | pytorch__pytorch | torch/fx/proxy.py | {
"start": 27511,
"end": 30484
} | class ____(Proxy):
"""
A special proxy which lets "shape", "size", "dim", and a few other
attribute accesses pass through to the underlying module parameter object,
so that conditional tests on these attributes will not throw exception during tracing
"""
def __init__(self, tracer: TracerBase, node: Node, name, param):
super().__init__(node, tracer)
assert isinstance(param, torch.nn.Parameter)
self.param = param
self.name = name
def __repr__(self) -> str:
return f"ParameterProxy({self.name})"
@property
def shape(self):
return self.param.shape
def size(self):
return self.param.size()
def dim(self):
return self.param.dim()
@property
def ndim(self):
return self.param.ndim
def numel(self):
return self.param.numel()
def nelement(self):
return self.param.nelement()
for method in magic_methods:
def _scope(method):
def impl(*args, **kwargs):
tracer = args[0].tracer
target = getattr(operator, method)
return tracer.create_proxy("call_function", target, args, kwargs)
impl.__name__ = method
as_magic = f"__{method.strip('_')}__"
setattr(Proxy, as_magic, impl)
_scope(method)
def _define_reflectable(orig_method_name):
method_name = f"__r{orig_method_name.strip('_')}__"
def impl(self, rhs):
target = getattr(operator, orig_method_name)
return self.tracer.create_proxy("call_function", target, (rhs, self), {})
impl.__name__ = method_name
impl.__qualname__ = method_name
setattr(Proxy, method_name, impl)
for orig_method_name in reflectable_magic_methods:
_define_reflectable(orig_method_name)
def _no_nodes_error(arg):
raise RuntimeError(
"Keys for dictionaries used as an argument cannot contain a "
f"Node. Got key: {arg}"
)
def _create_arg_dict(self, a):
r = {}
for k, v in a.items():
if not isinstance(k, str):
# Check for invalid dict keys. We do not want a Proxy to appear
# anywhere within the key. Since keys can be collection types,
# we iterate through the key with map_arg
k = self.create_arg(k)
map_arg(k, _no_nodes_error)
r[k] = self.create_arg(v)
return r
_create_arg_bypass = {
t: lambda self, a: a
for t in [
*base_types,
type(None),
type(...),
torch._ops.OpOverload,
torch._ops.HigherOrderOperator,
]
}
_create_arg_bypass[Proxy] = lambda self, a: a.node
_create_arg_bypass[tuple] = lambda self, a: tuple(self.create_arg(elem) for elem in a)
_create_arg_bypass[list] = lambda self, a: [self.create_arg(elem) for elem in a]
_create_arg_bypass[dict] = _create_arg_dict
_create_arg_bypass[immutable_list] = _create_arg_bypass[list]
_create_arg_bypass[immutable_dict] = _create_arg_bypass[dict]
| ParameterProxy |
python | doocs__leetcode | solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/Solution2.py | {
"start": 0,
"end": 346
} | class ____:
def getNoZeroIntegers(self, n: int) -> List[int]:
def f(x: int) -> bool:
while x:
if x % 10 == 0:
return False
x //= 10
return True
for a in count(1):
b = n - a
if f(a) and f(b):
return [a, b]
| Solution |
python | pytest-dev__pytest-mock | src/pytest_mock/plugin.py | {
"start": 964,
"end": 1972
} | class ____:
"""
Cache MagicMock and Patcher instances so we can undo them later.
"""
cache: list[MockCacheItem] = field(default_factory=list)
def _find(self, mock: MockType) -> MockCacheItem:
for mock_item in self.cache:
if mock_item.mock is mock:
return mock_item
raise ValueError("This mock object is not registered")
def add(self, mock: MockType, **kwargs: Any) -> MockCacheItem:
self.cache.append(MockCacheItem(mock=mock, **kwargs))
return self.cache[-1]
def remove(self, mock: MockType) -> None:
mock_item = self._find(mock)
if mock_item.patch:
mock_item.patch.stop()
self.cache.remove(mock_item)
def clear(self) -> None:
for mock_item in reversed(self.cache):
if mock_item.patch is not None:
mock_item.patch.stop()
self.cache.clear()
def __iter__(self) -> Iterator[MockCacheItem]:
return iter(self.cache)
| MockCache |
python | scrapy__scrapy | tests/test_downloadermiddleware_robotstxt.py | {
"start": 800,
"end": 10493
} | class ____:
def setup_method(self):
self.crawler = mock.MagicMock()
self.crawler.settings = Settings()
self.crawler.engine.download_async = mock.AsyncMock()
def teardown_method(self):
del self.crawler
def test_robotstxt_settings(self):
self.crawler.settings = Settings()
self.crawler.settings.set("USER_AGENT", "CustomAgent")
with pytest.raises(NotConfigured):
RobotsTxtMiddleware(self.crawler)
def _get_successful_crawler(self) -> Crawler:
crawler = self.crawler
crawler.settings.set("ROBOTSTXT_OBEY", True)
ROBOTS = """
User-Agent: *
Disallow: /admin/
Disallow: /static/
# taken from https://en.wikipedia.org/robots.txt
Disallow: /wiki/K%C3%A4ytt%C3%A4j%C3%A4:
Disallow: /wiki/Käyttäjä:
User-Agent: UnicödeBöt
Disallow: /some/randome/page.html
""".encode()
response = TextResponse("http://site.local/robots.txt", body=ROBOTS)
async def return_response(request):
deferred = Deferred()
call_later(0, deferred.callback, response)
return await maybe_deferred_to_future(deferred)
crawler.engine.download_async.side_effect = return_response
return crawler
@deferred_f_from_coro_f
async def test_robotstxt(self):
middleware = RobotsTxtMiddleware(self._get_successful_crawler())
await self.assertNotIgnored(Request("http://site.local/allowed"), middleware)
self.assertRobotsTxtRequested("http://site.local")
await self.assertIgnored(Request("http://site.local/admin/main"), middleware)
await self.assertIgnored(Request("http://site.local/static/"), middleware)
await self.assertIgnored(
Request("http://site.local/wiki/K%C3%A4ytt%C3%A4j%C3%A4:"), middleware
)
await self.assertIgnored(
Request("http://site.local/wiki/Käyttäjä:"), middleware
)
@deferred_f_from_coro_f
async def test_robotstxt_multiple_reqs(self) -> None:
middleware = RobotsTxtMiddleware(self._get_successful_crawler())
d1 = deferred_from_coro(
middleware.process_request(Request("http://site.local/allowed1"))
)
d2 = deferred_from_coro(
middleware.process_request(Request("http://site.local/allowed2"))
)
await maybe_deferred_to_future(DeferredList([d1, d2], fireOnOneErrback=True))
@pytest.mark.only_asyncio
@deferred_f_from_coro_f
async def test_robotstxt_multiple_reqs_asyncio(self) -> None:
middleware = RobotsTxtMiddleware(self._get_successful_crawler())
c1 = middleware.process_request(Request("http://site.local/allowed1"))
c2 = middleware.process_request(Request("http://site.local/allowed2"))
await asyncio.gather(c1, c2)
@deferred_f_from_coro_f
async def test_robotstxt_ready_parser(self):
middleware = RobotsTxtMiddleware(self._get_successful_crawler())
await self.assertNotIgnored(Request("http://site.local/allowed"), middleware)
await self.assertNotIgnored(Request("http://site.local/allowed"), middleware)
@deferred_f_from_coro_f
async def test_robotstxt_meta(self):
middleware = RobotsTxtMiddleware(self._get_successful_crawler())
meta = {"dont_obey_robotstxt": True}
await self.assertNotIgnored(
Request("http://site.local/allowed", meta=meta), middleware
)
await self.assertNotIgnored(
Request("http://site.local/admin/main", meta=meta), middleware
)
await self.assertNotIgnored(
Request("http://site.local/static/", meta=meta), middleware
)
def _get_garbage_crawler(self) -> Crawler:
crawler = self.crawler
crawler.settings.set("ROBOTSTXT_OBEY", True)
response = Response(
"http://site.local/robots.txt", body=b"GIF89a\xd3\x00\xfe\x00\xa2"
)
async def return_response(request):
deferred = Deferred()
call_later(0, deferred.callback, response)
return await maybe_deferred_to_future(deferred)
crawler.engine.download_async.side_effect = return_response
return crawler
@deferred_f_from_coro_f
async def test_robotstxt_garbage(self):
# garbage response should be discarded, equal 'allow all'
middleware = RobotsTxtMiddleware(self._get_garbage_crawler())
await self.assertNotIgnored(Request("http://site.local"), middleware)
await self.assertNotIgnored(Request("http://site.local/allowed"), middleware)
await self.assertNotIgnored(Request("http://site.local/admin/main"), middleware)
await self.assertNotIgnored(Request("http://site.local/static/"), middleware)
def _get_emptybody_crawler(self) -> Crawler:
crawler = self.crawler
crawler.settings.set("ROBOTSTXT_OBEY", True)
response = Response("http://site.local/robots.txt")
async def return_response(request):
deferred = Deferred()
call_later(0, deferred.callback, response)
return await maybe_deferred_to_future(deferred)
crawler.engine.download_async.side_effect = return_response
return crawler
@deferred_f_from_coro_f
async def test_robotstxt_empty_response(self):
# empty response should equal 'allow all'
middleware = RobotsTxtMiddleware(self._get_emptybody_crawler())
await self.assertNotIgnored(Request("http://site.local/allowed"), middleware)
await self.assertNotIgnored(Request("http://site.local/admin/main"), middleware)
await self.assertNotIgnored(Request("http://site.local/static/"), middleware)
@deferred_f_from_coro_f
async def test_robotstxt_error(self, caplog: pytest.LogCaptureFixture) -> None:
self.crawler.settings.set("ROBOTSTXT_OBEY", True)
err = error.DNSLookupError("Robotstxt address not found")
async def return_failure(request):
deferred = Deferred()
call_later(0, deferred.errback, failure.Failure(err))
return await maybe_deferred_to_future(deferred)
self.crawler.engine.download_async.side_effect = return_failure
middleware = RobotsTxtMiddleware(self.crawler)
await middleware.process_request(Request("http://site.local"))
assert "DNS lookup failed: Robotstxt address not found" in caplog.text
@deferred_f_from_coro_f
async def test_robotstxt_immediate_error(self):
self.crawler.settings.set("ROBOTSTXT_OBEY", True)
err = error.DNSLookupError("Robotstxt address not found")
async def immediate_failure(request):
raise err
self.crawler.engine.download_async.side_effect = immediate_failure
middleware = RobotsTxtMiddleware(self.crawler)
await self.assertNotIgnored(Request("http://site.local"), middleware)
@deferred_f_from_coro_f
async def test_ignore_robotstxt_request(self):
self.crawler.settings.set("ROBOTSTXT_OBEY", True)
async def ignore_request(request):
deferred = Deferred()
call_later(0, deferred.errback, failure.Failure(IgnoreRequest()))
return await maybe_deferred_to_future(deferred)
self.crawler.engine.download_async.side_effect = ignore_request
middleware = RobotsTxtMiddleware(self.crawler)
with mock.patch(
"scrapy.downloadermiddlewares.robotstxt.logger"
) as mw_module_logger:
await self.assertNotIgnored(
Request("http://site.local/allowed"), middleware
)
assert not mw_module_logger.error.called
def test_robotstxt_user_agent_setting(self):
crawler = self._get_successful_crawler()
crawler.settings.set("ROBOTSTXT_USER_AGENT", "Examplebot")
crawler.settings.set("USER_AGENT", "Mozilla/5.0 (X11; Linux x86_64)")
middleware = RobotsTxtMiddleware(crawler)
rp = mock.MagicMock(return_value=True)
middleware.process_request_2(rp, Request("http://site.local/allowed"))
rp.allowed.assert_called_once_with("http://site.local/allowed", "Examplebot")
@deferred_f_from_coro_f
async def test_robotstxt_local_file(self):
middleware = RobotsTxtMiddleware(self._get_emptybody_crawler())
middleware.process_request_2 = mock.MagicMock()
await middleware.process_request(Request("data:text/plain,Hello World data"))
assert not middleware.process_request_2.called
await middleware.process_request(
Request("file:///tests/sample_data/test_site/nothinghere.html")
)
assert not middleware.process_request_2.called
await middleware.process_request(Request("http://site.local/allowed"))
assert middleware.process_request_2.called
async def assertNotIgnored(
self, request: Request, middleware: RobotsTxtMiddleware
) -> None:
try:
await middleware.process_request(request)
except IgnoreRequest:
pytest.fail("IgnoreRequest was raised unexpectedly")
async def assertIgnored(
self, request: Request, middleware: RobotsTxtMiddleware
) -> None:
with pytest.raises(IgnoreRequest):
await middleware.process_request(request)
def assertRobotsTxtRequested(self, base_url: str) -> None:
calls = self.crawler.engine.download_async.call_args_list
request = calls[0][0][0]
assert request.url == f"{base_url}/robots.txt"
assert request.callback == NO_CALLBACK
@pytest.mark.skipif(not rerp_available(), reason="Rerp parser is not installed")
| TestRobotsTxtMiddleware |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeAlias15.py | {
"start": 243,
"end": 504
} | class ____(Exception):
pass
def func1(errs: MaybeSequence[type[Exception]]):
pass
func1(HttpError)
func1(Exception)
def func2(x: MaybeSequence[type[HttpError]]):
reveal_type(x, expected_text="type[HttpError] | Sequence[type[HttpError]]")
| HttpError |
python | getsentry__sentry | tests/sentry/workflow_engine/endpoints/test_organization_detector_index.py | {
"start": 2556,
"end": 27469
} | class ____(OrganizationDetectorIndexBaseTest):
def test_simple(self) -> None:
detector = self.create_detector(
project=self.project, name="Test Detector", type=MetricIssue.slug
)
detector_2 = self.create_detector(
project=self.project, name="Test Detector 2", type=MetricIssue.slug
)
response = self.get_success_response(
self.organization.slug, qs_params={"project": self.project.id}
)
assert response.data == serialize([detector, detector_2])
# Verify openIssues field is present in serialized response
for detector_data in response.data:
assert "openIssues" in detector_data
assert isinstance(detector_data["openIssues"], int)
# Verify X-Hits header is present and correct
assert "X-Hits" in response
hits = int(response["X-Hits"])
assert hits == 2
def test_uptime_detector(self) -> None:
subscription = self.create_uptime_subscription()
data_source = self.create_data_source(
organization_id=self.organization.id,
source_id=subscription.id,
type=DATA_SOURCE_UPTIME_SUBSCRIPTION,
)
detector = self.create_detector(
project=self.project,
name="Test Detector",
type=UptimeDomainCheckFailure.slug,
config={
"mode": 1,
"environment": "production",
"recovery_threshold": 1,
"downtime_threshold": 3,
},
)
self.create_data_source_detector(
data_source=data_source,
detector=detector,
)
response = self.get_success_response(
self.organization.slug, qs_params={"project": self.project.id}
)
assert response.data[0]["dataSources"][0]["queryObj"] == serialize(subscription)
def test_empty_result(self) -> None:
response = self.get_success_response(
self.organization.slug, qs_params={"project": self.project.id}
)
assert len(response.data) == 0
def test_project_unspecified(self) -> None:
d1 = self.create_detector(
project=self.project, name="A Test Detector", type=MetricIssue.slug
)
d2 = self.create_detector(
project=self.create_project(),
name="B Test Detector 2",
type=MetricIssue.slug,
)
response = self.get_success_response(
self.organization.slug,
)
assert {d["name"] for d in response.data} == {d1.name, d2.name}
def test_invalid_project(self) -> None:
self.create_detector(project=self.project, name="A Test Detector", type=MetricIssue.slug)
# project might exist, but you're not allowed to know that.
self.get_error_response(
self.organization.slug,
qs_params={"project": 512345},
status_code=403,
)
def test_filter_by_ids(self) -> None:
detector = self.create_detector(
project=self.project, name="Test Detector", type=MetricIssue.slug
)
detector_2 = self.create_detector(
project_id=self.project.id, name="Test Detector 2", type=MetricIssue.slug
)
self.create_detector(
project_id=self.project.id, name="Test Detector 3", type=MetricIssue.slug
)
response = self.get_success_response(
self.organization.slug,
qs_params=[("id", str(detector.id)), ("id", str(detector_2.id))],
)
assert len(response.data) == 2
assert {d["id"] for d in response.data} == {str(detector.id), str(detector_2.id)}
# Test with non-existent ID
response = self.get_success_response(
self.organization.slug,
qs_params={"id": "999999"},
)
assert len(response.data) == 0
# Test with invalid ID format
response = self.get_error_response(
self.organization.slug,
qs_params={"id": "not-an-id"},
status_code=400,
)
assert response.data == {"id": ["Invalid ID format"]}
def test_invalid_sort_by(self) -> None:
response = self.get_error_response(
self.organization.slug,
qs_params={"project": self.project.id, "sortBy": "general_malaise"},
)
assert "sortBy" in response.data
def test_sort_by_name(self) -> None:
detector = self.create_detector(
project=self.project, name="A Test Detector", type=MetricIssue.slug
)
detector_2 = self.create_detector(
project=self.project, name="B Test Detector 2", type=MetricIssue.slug
)
response = self.get_success_response(
self.organization.slug, qs_params={"project": self.project.id, "sortBy": "-name"}
)
assert [d["name"] for d in response.data] == [
detector_2.name,
detector.name,
]
def test_sort_by_connected_workflows(self) -> None:
workflow = self.create_workflow(
organization_id=self.organization.id,
)
workflow_2 = self.create_workflow(
organization_id=self.organization.id,
)
detector = self.create_detector(
project=self.project, name="Test Detector", type=MetricIssue.slug
)
detector_2 = self.create_detector(
project=self.project, name="Test Detector 2", type=MetricIssue.slug
)
self.create_detector_workflow(detector=detector, workflow=workflow)
self.create_detector_workflow(detector=detector, workflow=workflow_2)
response1 = self.get_success_response(
self.organization.slug,
qs_params={"project": self.project.id, "sortBy": "-connectedWorkflows"},
)
assert [d["name"] for d in response1.data] == [
detector.name,
detector_2.name,
]
response2 = self.get_success_response(
self.organization.slug,
qs_params={"project": self.project.id, "sortBy": "connectedWorkflows"},
)
assert [d["name"] for d in response2.data] == [
detector_2.name,
detector.name,
]
def test_sort_by_latest_group(self) -> None:
detector_1 = self.create_detector(
project=self.project, name="Detector 1", type=MetricIssue.slug
)
detector_2 = self.create_detector(
project=self.project, name="Detector 2", type=MetricIssue.slug
)
detector_3 = self.create_detector(
project=self.project, name="Detector 3", type=MetricIssue.slug
)
detector_4 = self.create_detector(
project=self.project, name="Detector 4 No Groups", type=MetricIssue.slug
)
group_1 = self.create_group(project=self.project)
group_2 = self.create_group(project=self.project)
group_3 = self.create_group(project=self.project)
# detector_1 has the oldest group
detector_group_1 = DetectorGroup.objects.create(detector=detector_1, group=group_1)
detector_group_1.date_added = before_now(hours=3)
detector_group_1.save()
# detector_2 has the newest grbefore_now
detector_group_2 = DetectorGroup.objects.create(detector=detector_2, group=group_2)
detector_group_2.date_added = before_now(hours=1) # Most recent
detector_group_2.save()
# detector_3 has one in the middle
detector_group_3 = DetectorGroup.objects.create(detector=detector_3, group=group_3)
detector_group_3.date_added = before_now(hours=2)
detector_group_3.save()
# Test descending sort (newest groups first)
response = self.get_success_response(
self.organization.slug, qs_params={"project": self.project.id, "sortBy": "-latestGroup"}
)
assert [d["name"] for d in response.data] == [
detector_2.name,
detector_3.name,
detector_1.name,
detector_4.name, # No groups, should be last
]
# Test ascending sort (oldest groups first)
response2 = self.get_success_response(
self.organization.slug, qs_params={"project": self.project.id, "sortBy": "latestGroup"}
)
assert [d["name"] for d in response2.data] == [
detector_4.name, # No groups, should be first
detector_1.name,
detector_3.name,
detector_2.name,
]
def test_sort_by_open_issues(self) -> None:
detector_1 = self.create_detector(
project=self.project, name="Detector 1", type=MetricIssue.slug
)
detector_2 = self.create_detector(
project=self.project, name="Detector 2", type=MetricIssue.slug
)
detector_3 = self.create_detector(
project=self.project, name="Detector 3", type=MetricIssue.slug
)
detector_4 = self.create_detector(
project=self.project, name="Detector 4 No Groups", type=MetricIssue.slug
)
# Create groups with different statuses
from sentry.models.group import GroupStatus
# detector_1 has 2 open issues and 1 resolved
open_group_1 = self.create_group(project=self.project, status=GroupStatus.UNRESOLVED)
open_group_2 = self.create_group(project=self.project, status=GroupStatus.UNRESOLVED)
resolved_group_1 = self.create_group(project=self.project, status=GroupStatus.RESOLVED)
DetectorGroup.objects.create(detector=detector_1, group=open_group_1)
DetectorGroup.objects.create(detector=detector_1, group=open_group_2)
DetectorGroup.objects.create(detector=detector_1, group=resolved_group_1)
# detector_2 has 1 open issue
open_group_3 = self.create_group(project=self.project, status=GroupStatus.UNRESOLVED)
DetectorGroup.objects.create(detector=detector_2, group=open_group_3)
# detector_3 has 3 open issues
open_group_4 = self.create_group(project=self.project, status=GroupStatus.UNRESOLVED)
open_group_5 = self.create_group(project=self.project, status=GroupStatus.UNRESOLVED)
open_group_6 = self.create_group(project=self.project, status=GroupStatus.UNRESOLVED)
DetectorGroup.objects.create(detector=detector_3, group=open_group_4)
DetectorGroup.objects.create(detector=detector_3, group=open_group_5)
DetectorGroup.objects.create(detector=detector_3, group=open_group_6)
# detector_4 has no groups
# Test descending sort (most open issues first)
response = self.get_success_response(
self.organization.slug, qs_params={"project": self.project.id, "sortBy": "-openIssues"}
)
expected_order = [detector_3.name, detector_1.name, detector_2.name, detector_4.name]
actual_order = [d["name"] for d in response.data]
assert actual_order == expected_order
# Verify open issues counts in serialized response
open_issues_by_name = {d["name"]: d["openIssues"] for d in response.data}
assert open_issues_by_name[detector_1.name] == 2
assert open_issues_by_name[detector_2.name] == 1
assert open_issues_by_name[detector_3.name] == 3
assert open_issues_by_name[detector_4.name] == 0
# Test ascending sort (least open issues first)
response2 = self.get_success_response(
self.organization.slug, qs_params={"project": self.project.id, "sortBy": "openIssues"}
)
expected_order_asc = [detector_4.name, detector_2.name, detector_1.name, detector_3.name]
actual_order_asc = [d["name"] for d in response2.data]
assert actual_order_asc == expected_order_asc
def test_query_by_name(self) -> None:
detector = self.create_detector(
project=self.project, name="Apple Detector", type=MetricIssue.slug
)
detector2 = self.create_detector(
project=self.project, name="Green Apple Detector", type=MetricIssue.slug
)
self.create_detector(project=self.project, name="Banana Detector", type=MetricIssue.slug)
response = self.get_success_response(
self.organization.slug, qs_params={"project": self.project.id, "query": "apple"}
)
assert {d["name"] for d in response.data} == {detector.name, detector2.name}
# Exact insensitive match when explicitly by name
response = self.get_success_response(
self.organization.slug,
qs_params={"project": self.project.id, "query": 'name:"Apple Detector"'},
)
assert {d["name"] for d in response.data} == {detector.name}
def test_query_by_type(self) -> None:
detector = self.create_detector(
project=self.project, name="Detector 1", type=MetricIssue.slug
)
detector2 = self.create_detector(
project=self.project,
name="Detector 2",
type=ErrorGroupType.slug,
)
response = self.get_success_response(
self.organization.slug, qs_params={"project": self.project.id, "query": "type:error"}
)
assert {d["name"] for d in response.data} == {detector2.name}
# Query for multiple types.
response2 = self.get_success_response(
self.organization.slug,
qs_params={"project": self.project.id, "query": "type:[error, metric_issue]"},
)
assert {d["name"] for d in response2.data} == {detector.name, detector2.name}
response3 = self.get_success_response(
self.organization.slug,
qs_params={"project": self.project.id, "query": "!type:metric_issue"},
)
assert {d["name"] for d in response3.data} == {detector2.name}
def test_query_by_type_alias(self) -> None:
"""
Users can query by simplfied aliases like "metric", "uptime" instead of the full type names.
"""
metric_detector = self.create_detector(
project=self.project, name="Metric Detector", type=MetricIssue.slug
)
uptime_detector = self.create_detector(
project=self.project,
name="Uptime Detector",
type=UptimeDomainCheckFailure.slug,
config={
"mode": 1,
"environment": "production",
"recovery_threshold": 1,
"downtime_threshold": 3,
},
)
cron_detector = self.create_detector(
project=self.project,
name="Cron Detector",
type=MonitorIncidentType.slug,
)
response = self.get_success_response(
self.organization.slug, qs_params={"project": self.project.id, "query": "type:metric"}
)
assert {d["name"] for d in response.data} == {metric_detector.name}
response = self.get_success_response(
self.organization.slug, qs_params={"project": self.project.id, "query": "type:uptime"}
)
assert {d["name"] for d in response.data} == {uptime_detector.name}
response = self.get_success_response(
self.organization.slug, qs_params={"project": self.project.id, "query": "type:cron"}
)
assert {d["name"] for d in response.data} == {cron_detector.name}
def test_general_query(self) -> None:
detector = self.create_detector(
project=self.project,
name="Lookfor 1",
type=MetricIssue.slug,
description="Delicious",
)
detector2 = self.create_detector(
project=self.project,
name="Lookfor 2",
type=ErrorGroupType.slug,
description="Exciting",
)
response = self.get_success_response(
self.organization.slug, qs_params={"project": self.project.id, "query": "delicious"}
)
assert {d["name"] for d in response.data} == {detector.name}
response2 = self.get_success_response(
self.organization.slug, qs_params={"project": self.project.id, "query": "metric"}
)
assert {d["name"] for d in response2.data} == {detector.name}
response3 = self.get_success_response(
self.organization.slug, qs_params={"project": self.project.id, "query": "lookfor"}
)
assert {d["name"] for d in response3.data} == {detector.name, detector2.name}
def test_query_by_assignee_user_email(self) -> None:
user = self.create_user(email="assignee@example.com")
self.create_member(organization=self.organization, user=user)
assigned_detector = self.create_detector(
project=self.project,
name="Assigned Detector",
type=MetricIssue.slug,
owner_user_id=user.id,
)
self.create_detector(
project=self.project,
name="Unassigned Detector",
type=MetricIssue.slug,
)
response = self.get_success_response(
self.organization.slug,
qs_params={"project": self.project.id, "query": f"assignee:{user.email}"},
)
assert {d["name"] for d in response.data} == {assigned_detector.name}
def test_query_by_assignee_user_username(self) -> None:
user = self.create_user(username="testuser")
self.create_member(organization=self.organization, user=user)
assigned_detector = self.create_detector(
project=self.project,
name="Assigned Detector",
type=MetricIssue.slug,
owner_user_id=user.id,
)
self.create_detector(
project=self.project,
name="Unassigned Detector",
type=MetricIssue.slug,
)
response = self.get_success_response(
self.organization.slug,
qs_params={"project": self.project.id, "query": f"assignee:{user.username}"},
)
assert {d["name"] for d in response.data} == {assigned_detector.name}
def test_query_by_assignee_team(self) -> None:
team = self.create_team(organization=self.organization, slug="test-team")
self.project.add_team(team)
assigned_detector = self.create_detector(
project=self.project,
name="Team Detector",
type=MetricIssue.slug,
owner_team_id=team.id,
)
self.create_detector(
project=self.project,
name="Unassigned Detector",
type=MetricIssue.slug,
)
response = self.get_success_response(
self.organization.slug,
qs_params={"project": self.project.id, "query": f"assignee:#{team.slug}"},
)
assert {d["name"] for d in response.data} == {assigned_detector.name}
def test_query_by_assignee_me(self) -> None:
self.login_as(user=self.user)
assigned_detector = self.create_detector(
project=self.project,
name="My Detector",
type=MetricIssue.slug,
owner_user_id=self.user.id,
)
self.create_detector(
project=self.project,
name="Other Detector",
type=MetricIssue.slug,
)
response = self.get_success_response(
self.organization.slug,
qs_params={"project": self.project.id, "query": "assignee:me"},
)
assert {d["name"] for d in response.data} == {assigned_detector.name}
def test_query_by_assignee_none(self) -> None:
user = self.create_user()
self.create_member(organization=self.organization, user=user)
team = self.create_team(organization=self.organization)
self.create_detector(
project=self.project,
name="User Assigned",
type=MetricIssue.slug,
owner_user_id=user.id,
)
self.create_detector(
project=self.project,
name="Team Assigned",
type=MetricIssue.slug,
owner_team_id=team.id,
)
unassigned_detector = self.create_detector(
project=self.project,
name="Unassigned Detector",
type=MetricIssue.slug,
)
response = self.get_success_response(
self.organization.slug,
qs_params={"project": self.project.id, "query": "assignee:none"},
)
assert {d["name"] for d in response.data} == {unassigned_detector.name}
def test_query_by_assignee_multiple_values(self) -> None:
user = self.create_user(email="user1@example.com")
self.create_member(organization=self.organization, user=user)
team = self.create_team(organization=self.organization, slug="test-team")
self.project.add_team(team)
detector1 = self.create_detector(
project=self.project,
name="Detector 1",
type=MetricIssue.slug,
owner_user_id=user.id,
)
detector2 = self.create_detector(
project=self.project,
name="Detector 2",
type=MetricIssue.slug,
owner_team_id=team.id,
)
self.create_detector(
project=self.project,
name="Other Detector",
type=MetricIssue.slug,
)
response = self.get_success_response(
self.organization.slug,
qs_params={
"project": self.project.id,
"query": f"assignee:[{user.email}, #{team.slug}]",
},
)
assert {d["name"] for d in response.data} == {detector1.name, detector2.name}
def test_query_by_assignee_negation(self) -> None:
user = self.create_user(email="exclude@example.com")
self.create_member(organization=self.organization, user=user)
self.create_detector(
project=self.project,
name="Excluded Detector",
type=MetricIssue.slug,
owner_user_id=user.id,
)
included_detector = self.create_detector(
project=self.project,
name="Included Detector",
type=MetricIssue.slug,
)
response = self.get_success_response(
self.organization.slug,
qs_params={"project": self.project.id, "query": f"!assignee:{user.email}"},
)
assert {d["name"] for d in response.data} == {included_detector.name}
def test_query_by_assignee_invalid_user(self) -> None:
self.create_detector(
project=self.project,
name="Valid Detector",
type=MetricIssue.slug,
)
# Query with non-existent user should return no results
response = self.get_success_response(
self.organization.slug,
qs_params={"project": self.project.id, "query": "assignee:nonexistent@example.com"},
)
assert len(response.data) == 0
def test_query_by_project_owner_user(self) -> None:
new_project = self.create_project(organization=self.organization)
detector = self.create_detector(
project_id=new_project.id, name="Test Detector", type=MetricIssue.slug
)
owner = self.create_user()
self.create_member(
user=owner,
role="owner",
organization=self.organization,
)
self.login_as(user=owner)
# Verify that the owner can see detectors for projects that they are not a member of
response = self.get_success_response(
self.organization.slug,
qs_params={"project": new_project.id},
status_code=200,
)
assert {d["name"] for d in response.data} == {detector.name}
def test_query_by_id_owner_user(self) -> None:
self.detector = self.create_detector(
project=self.project,
name="Detector 1",
type=MetricIssue.slug,
)
self.detector_2 = self.create_detector(
project=self.project,
name="Detector 2",
type=MetricIssue.slug,
)
owner = self.create_user()
self.create_member(
user=owner,
role="owner",
organization=self.organization,
)
self.login_as(user=owner)
# Verify that the owner can see detectors for projects that they are not a member of
response = self.get_success_response(
self.organization.slug,
qs_params=[("id", str(self.detector.id)), ("id", str(self.detector_2.id))],
status_code=200,
)
assert {d["name"] for d in response.data} == {self.detector.name, self.detector_2.name}
@region_silo_test
@with_feature("organizations:incidents")
| OrganizationDetectorIndexGetTest |
python | weaviate__weaviate-python-client | weaviate/collections/classes/aggregate.py | {
"start": 1074,
"end": 1229
} | class ____:
"""The aggregation result for a text property."""
count: Optional[int]
top_occurrences: List[TopOccurrence]
@dataclass
| AggregateText |
python | Pylons__pyramid | tests/test_i18n.py | {
"start": 17231,
"end": 17427
} | class ____:
def ugettext(self, text):
return text
gettext = ugettext
def ungettext(self, singular, plural, n):
return singular
ngettext = ungettext
| DummyTranslations |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py | {
"start": 54718,
"end": 55795
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("dataset.Dataset.to_dict"))
@mock.patch(VERTEX_AI_PATH.format("dataset.DatasetHook"))
def test_execute(self, mock_hook, to_dict_mock):
op = ExportDataOperator(
task_id=TASK_ID,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
region=GCP_LOCATION,
project_id=GCP_PROJECT,
dataset_id=TEST_DATASET_ID,
export_config=TEST_EXPORT_CONFIG,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
op.execute(context={})
mock_hook.assert_called_once_with(gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN)
mock_hook.return_value.export_data.assert_called_once_with(
region=GCP_LOCATION,
project_id=GCP_PROJECT,
dataset=TEST_DATASET_ID,
export_config=TEST_EXPORT_CONFIG,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
| TestVertexAIExportDataOperator |
python | doocs__leetcode | solution/0600-0699/0636.Exclusive Time of Functions/Solution.py | {
"start": 0,
"end": 507
} | class ____:
def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:
stk = []
ans = [0] * n
pre = 0
for log in logs:
i, op, t = log.split(":")
i, cur = int(i), int(t)
if op[0] == "s":
if stk:
ans[stk[-1]] += cur - pre
stk.append(i)
pre = cur
else:
ans[stk.pop()] += cur - pre + 1
pre = cur + 1
return ans
| Solution |
python | tox-dev__tox | src/tox/tox_env/python/virtual_env/package/pyproject.py | {
"start": 3035,
"end": 17281
} | class ____(PythonPackageToxEnv, ABC):
"""local file system python virtual environment package builder."""
def __init__(self, create_args: ToxEnvCreateArgs) -> None:
super().__init__(create_args)
self._frontend_: Pep517VirtualEnvFrontend | None = None
self.builds: defaultdict[str, list[EnvConfigSet]] = defaultdict(list)
self.call_require_hooks: set[str] = set()
self._distribution_meta: PathDistribution | None = None
self._package_dependencies: list[Requirement] | None = None
self._package_name: str | None = None
self._pkg_lock = RLock() # can build only one package at a time
self._package_paths: set[Path] = set()
self._root: Path | None = None
@property
def root(self) -> Path:
if self._root is None:
self._root = self.conf["package_root"]
return self._root
@root.setter
def root(self, value: Path) -> None:
# Recreating the frontend with a new root would orphan the current frontend.backend_executor, if any, making tox
# hang upon exit waiting for its threads and subprocesses (#3512).
# Therefore, we make sure to close the existing back-end executor in the case of an existing PEP 517 frontend.
if self._frontend is not None:
self._frontend.backend_executor.close()
self._root = value
self._frontend_ = None # force recreating the frontend with new root
@staticmethod
def id() -> str:
return "virtualenv-pep-517"
@property
def _frontend(self) -> Pep517VirtualEnvFrontend:
if self._frontend_ is None:
self._frontend_ = Pep517VirtualEnvFrontend(self.root, self)
return self._frontend_
def register_config(self) -> None:
super().register_config()
self.conf.add_config(
keys=["meta_dir"],
of_type=Path,
default=lambda conf, name: self.env_dir / ".meta", # noqa: ARG005
desc="directory where to put the project metadata files",
)
self.conf.add_config(
keys=["pkg_dir"],
of_type=Path,
default=lambda conf, name: self.env_dir / "dist", # noqa: ARG005
desc="directory where to put project packages",
)
for key in ("sdist", "wheel", "editable"):
self._add_config_settings(key)
self.conf.add_config(
keys=["fresh_subprocess"],
of_type=bool,
default=self._frontend.backend.split(".")[0] == "setuptools",
desc="create a fresh subprocess for every backend request",
)
def _add_config_settings(self, build_type: str) -> None:
# config settings passed to PEP-517-compliant build backend https://peps.python.org/pep-0517/#config-settings
keys = {
"sdist": ["get_requires_for_build_sdist", "build_sdist"],
"wheel": ["get_requires_for_build_wheel", "prepare_metadata_for_build_wheel", "build_wheel"],
"editable": ["get_requires_for_build_editable", "prepare_metadata_for_build_editable", "build_editable"],
}
for key in keys.get(build_type, []):
self.conf.add_config(
keys=[f"config_settings_{key}"],
of_type=dict[str, str],
default=None, # type: ignore[arg-type]
desc=f"config settings passed to the {key} backend API endpoint",
)
@property
def pkg_dir(self) -> Path:
return cast("Path", self.conf["pkg_dir"])
@property
def meta_folder(self) -> Path:
meta_folder: Path = self.conf["meta_dir"]
meta_folder.mkdir(exist_ok=True)
return meta_folder
@property
def meta_folder_if_populated(self) -> Path | None:
"""Return the metadata directory if it contains any files, otherwise None."""
meta_folder = self.meta_folder
if meta_folder.exists() and tuple(meta_folder.iterdir()):
return meta_folder
return None
def register_run_env(self, run_env: RunToxEnv) -> Generator[tuple[str, str], PackageToxEnv, None]:
yield from super().register_run_env(run_env)
build_type = run_env.conf["package"]
self.call_require_hooks.add(build_type)
self.builds[build_type].append(run_env.conf)
def _setup_env(self) -> None:
super()._setup_env()
if "sdist" in self.call_require_hooks or "external" in self.call_require_hooks:
self._setup_build_requires("sdist")
if "wheel" in self.call_require_hooks:
self._setup_build_requires("wheel")
if "editable" in self.call_require_hooks:
if not self._frontend.optional_hooks["build_editable"]:
raise BuildEditableNotSupportedError
self._setup_build_requires("editable")
def _setup_build_requires(self, of_type: str) -> None:
settings: ConfigSettings = self.conf[f"config_settings_get_requires_for_build_{of_type}"]
requires = getattr(self._frontend, f"get_requires_for_build_{of_type}")(config_settings=settings).requires
self._install(requires, PythonPackageToxEnv.__name__, f"requires_for_build_{of_type}")
def _teardown(self) -> None:
executor = self._frontend.backend_executor
if executor is not None: # pragma: no branch
try:
if executor.is_alive:
self._frontend._send("_exit") # try first on amicable shutdown # noqa: SLF001
except SystemExit: # pragma: no cover # if already has been interrupted ignore
pass
finally:
executor.close()
for path in self._package_paths:
if path.exists():
logging.debug("delete package %s", path)
path.unlink()
super()._teardown()
def perform_packaging(self, for_env: EnvConfigSet) -> list[Package]:
"""Build the package to install."""
try:
deps = self._load_deps(for_env)
except BuildEditableNotSupportedError:
self.call_require_hooks.remove("editable")
targets = [e for e in self.builds.pop("editable") if e["package"] == "editable"]
names = ", ".join(sorted({t.env_name for t in targets if t.env_name}))
logging.error( # noqa: TRY400
"package config for %s is editable, however the build backend %s does not support PEP-660, falling "
"back to editable-legacy - change your configuration to it",
names,
cast("Pep517VirtualEnvFrontend", self._frontend_).backend,
)
for env in targets:
env._defined["package"].value = "editable-legacy" # type: ignore[attr-defined] # noqa: SLF001
self.builds["editable-legacy"].append(env)
self._run_state["setup"] = False # force setup again as we need to provision wheel to get dependencies
deps = self._load_deps(for_env)
of_type: str = for_env["package"]
if of_type == "editable-legacy":
self.setup()
config_settings: ConfigSettings = self.conf["config_settings_get_requires_for_build_sdist"]
sdist_requires = self._frontend.get_requires_for_build_sdist(config_settings=config_settings).requires
deps = [*self.requires(), *sdist_requires, *deps]
package: Package = EditableLegacyPackage(self.core["tox_root"], deps) # the folder itself is the package
elif of_type == "sdist":
self.setup()
with self._pkg_lock:
config_settings = self.conf["config_settings_build_sdist"]
sdist = self._frontend.build_sdist(sdist_directory=self.pkg_dir, config_settings=config_settings).sdist
sdist = create_session_view(sdist, self._package_temp_path)
self._package_paths.add(sdist)
package = SdistPackage(sdist, deps)
elif of_type in {"wheel", "editable"}:
w_env = self._wheel_build_envs.get(for_env["wheel_build_env"])
if w_env is not None and w_env is not self:
with w_env.display_context(self._has_display_suspended):
return w_env.perform_packaging(for_env)
else:
self.setup()
method = "build_editable" if of_type == "editable" else "build_wheel"
config_settings = self.conf[f"config_settings_{method}"]
with self._pkg_lock:
wheel = getattr(self._frontend, method)(
wheel_directory=self.pkg_dir,
metadata_directory=self.meta_folder_if_populated,
config_settings=config_settings,
).wheel
wheel = create_session_view(wheel, self._package_temp_path)
self._package_paths.add(wheel)
package = (EditablePackage if of_type == "editable" else WheelPackage)(wheel, deps)
else: # pragma: no cover # for when we introduce new packaging types and don't implement
msg = f"cannot handle package type {of_type}"
raise TypeError(msg) # pragma: no cover
return [package]
@property
def _package_temp_path(self) -> Path:
return cast("Path", self.core["temp_dir"]) / "package"
def _load_deps(self, for_env: EnvConfigSet) -> list[Requirement]:
# first check if this is statically available via PEP-621
deps = self._load_deps_from_static(for_env)
if deps is None:
deps = self._load_deps_from_built_metadata(for_env)
return deps
def _load_deps_from_static(self, for_env: EnvConfigSet) -> list[Requirement] | None:
pyproject_file = self.core["package_root"] / "pyproject.toml"
if not pyproject_file.exists(): # check if it's static PEP-621 metadata
return None
with pyproject_file.open("rb") as file_handler:
pyproject = tomllib.load(file_handler)
if "project" not in pyproject:
return None # is not a PEP-621 pyproject
project = pyproject["project"]
extras: set[str] = for_env["extras"]
for dynamic in project.get("dynamic", []):
if dynamic == "dependencies" or (extras and dynamic == "optional-dependencies"):
return None # if any dependencies are dynamic we can just calculate all dynamically
deps_with_markers: list[tuple[Requirement, set[str | None]]] = [
(Requirement(i), {None}) for i in project.get("dependencies", [])
]
optional_deps = project.get("optional-dependencies", {})
for extra, reqs in optional_deps.items():
deps_with_markers.extend((Requirement(req), {extra}) for req in (reqs or []))
return dependencies_with_extras_from_markers(
deps_with_markers=deps_with_markers,
extras=extras,
package_name=project.get("name", "."),
)
def _load_deps_from_built_metadata(self, for_env: EnvConfigSet) -> list[Requirement]:
# dependencies might depend on the python environment we're running in => if we build a wheel use that env
# to calculate the package metadata, otherwise ourselves
of_type: str = for_env["package"]
reqs: list[Requirement] | None = None
name = ""
if of_type in {"wheel", "editable"}: # wheel packages
w_env = self._wheel_build_envs.get(for_env["wheel_build_env"])
if w_env is not None and w_env is not self:
with w_env.display_context(self._has_display_suspended):
if isinstance(w_env, Pep517VirtualEnvPackager):
reqs, name = w_env.get_package_dependencies(for_env), w_env.get_package_name(for_env)
else:
reqs = []
if reqs is None:
reqs = self.get_package_dependencies(for_env)
name = self.get_package_name(for_env)
extras: set[str] = for_env["extras"]
return dependencies_with_extras(reqs, extras, name)
def get_package_dependencies(self, for_env: EnvConfigSet) -> list[Requirement]:
with self._pkg_lock:
if self._package_dependencies is None: # pragma: no branch
self._ensure_meta_present(for_env)
requires: list[str] = cast("PathDistribution", self._distribution_meta).requires or []
self._package_dependencies = [Requirement(i) for i in requires] # pragma: no branch
return self._package_dependencies
def get_package_name(self, for_env: EnvConfigSet) -> str:
with self._pkg_lock:
if self._package_name is None: # pragma: no branch
self._ensure_meta_present(for_env)
self._package_name = cast("PathDistribution", self._distribution_meta).metadata["Name"]
return self._package_name
def _ensure_meta_present(self, for_env: EnvConfigSet) -> None:
if self._distribution_meta is not None: # pragma: no branch
return # pragma: no cover
# even if we don't build a wheel we need the requirements for it should we want to build its metadata
target: Literal["editable", "wheel"] = "editable" if for_env["package"] == "editable" else "wheel"
self.call_require_hooks.add(target)
self.setup()
hook = getattr(self._frontend, f"prepare_metadata_for_build_{target}")
config: ConfigSettings = self.conf[f"config_settings_prepare_metadata_for_build_{target}"]
result: MetadataForBuildWheelResult | MetadataForBuildEditableResult | None = hook(self.meta_folder, config)
if result is None:
config = self.conf[f"config_settings_build_{target}"]
dist_info_path, _, __ = self._frontend.metadata_from_built(self.meta_folder, target, config)
dist_info = str(dist_info_path)
else:
dist_info = str(result.metadata)
self._distribution_meta = Distribution.at(dist_info)
def requires(self) -> tuple[Requirement, ...]:
return self._frontend.requires
| Pep517VenvPackager |
python | tensorflow__tensorflow | tensorflow/python/ops/control_flow_v2_toggles_test.py | {
"start": 885,
"end": 1604
} | class ____(test.TestCase):
def testOutputAllIntermediates(self):
self.assertIsNone(
control_flow_util_v2._EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE)
control_flow_util_v2.set_output_all_intermediates(True)
self.assertTrue(
control_flow_util_v2._EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE)
control_flow_util_v2.set_output_all_intermediates(False)
self.assertFalse(
control_flow_util_v2._EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE)
control_flow_util_v2.set_output_all_intermediates(None)
self.assertIsNone(
control_flow_util_v2._EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE)
if __name__ == '__main__':
googletest.main()
| ControlFlowV2TogglesTest |
python | encode__django-rest-framework | tests/schemas/test_coreapi.py | {
"start": 31296,
"end": 32642
} | class ____(TestCase):
def setUp(self):
self.patterns = [
path('example/', ManyToManySourceView.as_view()),
]
def test_schema_for_regular_views(self):
"""
Ensure that AutoField many to many fields are output as Integer.
"""
generator = SchemaGenerator(title='Example API', patterns=self.patterns)
schema = generator.get_schema()
expected = coreapi.Document(
url='',
title='Example API',
content={
'example': {
'create': coreapi.Link(
url='/example/',
action='post',
encoding='application/json',
fields=[
coreapi.Field('name', required=True, location='form', schema=coreschema.String(title='Name')),
coreapi.Field('targets', required=True, location='form', schema=coreschema.Array(title='Targets', items=coreschema.Integer())),
]
)
}
}
)
assert schema == expected
@unittest.skipUnless(coreapi, 'coreapi is not installed')
@override_settings(REST_FRAMEWORK={'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.AutoSchema'})
| TestSchemaGeneratorWithManyToMany |
python | Pylons__pyramid | tests/test_config/pkgs/scannable/another.py | {
"start": 532,
"end": 933
} | class ____:
def __init__(self, context, request):
self.context = context
self.request = request
def __call__(self):
return 'another_stacked_class'
stacked_class = view_config(
name='another_stacked_class1', renderer=null_renderer
)(stacked_class)
stacked_class = view_config(
name='another_stacked_class2', renderer=null_renderer
)(stacked_class)
| stacked_class |
python | kamyu104__LeetCode-Solutions | Python/spiral-matrix.py | {
"start": 33,
"end": 944
} | class ____(object):
# @param matrix, a list of lists of integers
# @return a list of integers
def spiralOrder(self, matrix):
result = []
if matrix == []:
return result
left, right, top, bottom = 0, len(matrix[0]) - 1, 0, len(matrix) - 1
while left <= right and top <= bottom:
for j in xrange(left, right + 1):
result.append(matrix[top][j])
for i in xrange(top + 1, bottom):
result.append(matrix[i][right])
for j in reversed(xrange(left, right + 1)):
if top < bottom:
result.append(matrix[bottom][j])
for i in reversed(xrange(top + 1, bottom)):
if left < right:
result.append(matrix[i][left])
left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1
return result
| Solution |
python | sqlalchemy__sqlalchemy | test/orm/test_events.py | {
"start": 117396,
"end": 125336
} | class ____(fixtures.MappedTest):
"""Test RegistryEvents functionality."""
@testing.variation("scenario", ["direct", "reentrant", "plain"])
@testing.variation("include_optional", [True, False])
@testing.variation(
"type_features",
[
"none",
"plain_pep593",
"plain_pep695",
"generic_pep593",
"plain_pep593_pep695",
"generic_pep593_pep695",
"generic_pep593_pep695_w_compound",
],
)
def test_resolve_type_annotation_event(
self,
scenario: testing.Variation,
include_optional: testing.Variation,
type_features: testing.Variation,
):
reg = registry(type_annotation_map={str: String(70)})
Base = reg.generate_base()
MyCustomType: Any
if type_features.none:
MyCustomType = type("MyCustomType", (object,), {})
elif type_features.plain_pep593:
MyCustomType = Annotated[float, mapped_column()]
elif type_features.plain_pep695:
MyCustomType = TypeAliasType("MyCustomType", float)
elif type_features.generic_pep593:
T = TypeVar("T")
MyCustomType = Annotated[T, mapped_column()]
elif type_features.plain_pep593_pep695:
MyCustomType = TypeAliasType( # type: ignore
"MyCustomType", Annotated[float, mapped_column()]
)
elif type_features.generic_pep593_pep695:
T = TypeVar("T")
MyCustomType = TypeAliasType( # type: ignore
"MyCustomType", Annotated[T, mapped_column()], type_params=(T,)
)
elif type_features.generic_pep593_pep695_w_compound:
T = TypeVar("T")
MyCustomType = TypeAliasType( # type: ignore
"MyCustomType",
Annotated[T | float, mapped_column()],
type_params=(T,),
)
else:
type_features.fail()
@event.listens_for(reg, "resolve_type_annotation")
def resolve_custom_type(
type_resolve: TypeResolve,
) -> TypeEngine[Any] | None:
assert type_resolve.cls.__name__ == "MyClass"
if (
type_resolve.resolved_type is int
and type_resolve.raw_pep_695_type is None
and type_resolve.raw_pep_593_type is None
):
return None
if type_features.none:
assert type_resolve.resolved_type is MyCustomType
elif type_features.plain_pep593:
assert type_resolve.resolved_type is float
assert type_resolve.raw_pep_593_type is not None
assert type_resolve.raw_pep_593_type.__args__[0] is float
assert type_resolve.pep_593_resolved_argument is float
elif type_features.plain_pep695:
assert type_resolve.raw_pep_695_type is MyCustomType
assert type_resolve.pep_695_resolved_value is float
assert type_resolve.resolved_type is float
elif type_features.generic_pep593:
assert type_resolve.raw_pep_695_type is None
assert type_resolve.pep_593_resolved_argument is str
assert type_resolve.resolved_type is str
elif type_features.plain_pep593_pep695:
assert type_resolve.raw_pep_695_type is not None
assert type_resolve.pep_593_resolved_argument is float
assert type_resolve.resolved_type is float
assert type_resolve.raw_pep_695_type is MyCustomType
elif type_features.generic_pep593_pep695:
assert type_resolve.raw_pep_695_type is not None
assert type_resolve.pep_593_resolved_argument is str
elif type_features.generic_pep593_pep695_w_compound:
assert type_resolve.raw_pep_695_type is not None
assert type_resolve.raw_pep_695_type.__origin__ is MyCustomType
assert type_resolve.pep_593_resolved_argument == str | float
assert type_resolve.resolved_type == str | float
else:
type_features.fail()
if scenario.direct:
return String(50)
elif scenario.reentrant:
return type_resolve.resolve(str)
else:
scenario.fail()
use_type_args = (
type_features.generic_pep593
or type_features.generic_pep593_pep695
or type_features.generic_pep593_pep695_w_compound
)
class MyClass(Base):
__tablename__ = "mytable"
id: Mapped[int] = mapped_column(primary_key=True)
if include_optional:
if scenario.direct or scenario.reentrant:
if use_type_args:
data: Mapped[Optional[MyCustomType[str]]]
else:
data: Mapped[Optional[MyCustomType]]
else:
data: Mapped[Optional[int]]
else:
if scenario.direct or scenario.reentrant:
if use_type_args:
data: Mapped[MyCustomType[str]]
else:
data: Mapped[MyCustomType]
else:
data: Mapped[int]
result = MyClass.data.expression.type
if scenario.direct:
assert isinstance(result, String)
eq_(result.length, 50)
elif scenario.reentrant:
assert isinstance(result, String)
eq_(result.length, 70)
elif scenario.plain:
assert isinstance(result, Integer)
def test_type_resolve_instantiates_type(self, decl_base):
MyType = int
@event.listens_for(decl_base, "resolve_type_annotation")
def resolve_custom_type(
type_resolve: TypeResolve,
) -> TypeEngine[Any] | None:
if type_resolve.resolved_type is MyType:
return Integer # <--- note not instantiated
class User(decl_base):
__tablename__ = "user"
id: Mapped[MyType] = mapped_column(primary_key=True)
assert isinstance(User.__table__.c.id.type, Integer)
@testing.variation(
"listen_type", ["registry", "generated_base", "explicit_base"]
)
def test_before_after_configured_events(self, listen_type):
"""Test the before_configured and after_configured events."""
reg = registry()
if listen_type.generated_base:
Base = reg.generate_base()
else:
class Base(DeclarativeBase):
registry = reg
mock = Mock()
if listen_type.registry:
@event.listens_for(reg, "before_configured")
def before_configured(registry_inst):
mock.before_configured(registry_inst)
@event.listens_for(reg, "after_configured")
def after_configured(registry_inst):
mock.after_configured(registry_inst)
else:
@event.listens_for(Base, "before_configured")
def before_configured(registry_inst):
mock.before_configured(registry_inst)
@event.listens_for(Base, "after_configured")
def after_configured(registry_inst):
mock.after_configured(registry_inst)
# Create a simple mapped class to trigger configuration
class TestClass(Base):
__tablename__ = "test_table"
id = Column(Integer, primary_key=True)
# Configure the registry
reg.configure()
# Check that events were fired in the correct order
eq_(
mock.mock_calls,
[call.before_configured(reg), call.after_configured(reg)],
)
| RegistryEventsTest |
python | apache__airflow | providers/apache/drill/tests/unit/apache/drill/hooks/test_drill.py | {
"start": 1850,
"end": 7167
} | class ____:
def setup_method(self):
self.cur = MagicMock(rowcount=0)
self.conn = conn = MagicMock()
self.conn.login = "drill_user"
self.conn.password = "secret"
self.conn.host = "host"
self.conn.port = "8047"
self.conn.conn_type = "drill"
self.conn.extra_dejson = {"dialect_driver": "drill+sadrill", "storage_plugin": "dfs"}
self.conn.cursor.return_value = self.cur
class TestDrillHook(DrillHook):
def get_conn(self):
return conn
def get_connection(self, conn_id):
return conn
self.db_hook = TestDrillHook
@pytest.mark.parametrize(
("host", "port", "conn_type", "extra_dejson", "expected_uri"),
[
(
"host",
"8047",
"drill",
{"dialect_driver": "drill+sadrill", "storage_plugin": "dfs"},
"drill://host:8047/dfs?dialect_driver=drill+sadrill",
),
(
"host",
None,
"drill",
{"dialect_driver": "drill+sadrill", "storage_plugin": "dfs"},
"drill://host/dfs?dialect_driver=drill+sadrill",
),
(
"host",
"8047",
None,
{"dialect_driver": "drill+sadrill", "storage_plugin": "dfs"},
"drill://host:8047/dfs?dialect_driver=drill+sadrill",
),
(
"host",
"8047",
"drill",
{}, # no extra_dejson fields
"drill://host:8047/dfs?dialect_driver=drill+sadrill",
),
(
"myhost",
1234,
"custom",
{"dialect_driver": "mydriver", "storage_plugin": "myplugin"},
"custom://myhost:1234/myplugin?dialect_driver=mydriver",
),
(
"host",
"8047",
"drill",
{"storage_plugin": "myplugin"},
"drill://host:8047/myplugin?dialect_driver=drill+sadrill",
),
(
"host",
"8047",
"drill",
{"dialect_driver": "mydriver"},
"drill://host:8047/dfs?dialect_driver=mydriver",
),
],
)
def test_get_uri(self, host, port, conn_type, extra_dejson, expected_uri):
self.conn.host = host
self.conn.port = port
self.conn.conn_type = conn_type
self.conn.extra_dejson = extra_dejson
db_hook = self.db_hook()
assert db_hook.get_uri() == expected_uri
def test_get_first_record(self):
statement = "SQL"
result_sets = [("row1",), ("row2",)]
self.cur.fetchone.return_value = result_sets[0]
assert result_sets[0] == self.db_hook().get_first(statement)
assert self.conn.close.call_count == 1
assert self.cur.close.call_count == 1
self.cur.execute.assert_called_once_with(statement)
def test_get_records(self):
statement = "SQL"
result_sets = [("row1",), ("row2",)]
self.cur.fetchall.return_value = result_sets
assert result_sets == self.db_hook().get_records(statement)
assert self.conn.close.call_count == 1
assert self.cur.close.call_count == 1
self.cur.execute.assert_called_once_with(statement)
def test_get_df_pandas(self):
statement = "SQL"
column = "col"
result_sets = [("row1",), ("row2",)]
self.cur.description = [(column,)]
self.cur.fetchall.return_value = result_sets
df = self.db_hook().get_df(statement, df_type="pandas")
assert column == df.columns[0]
for i, item in enumerate(result_sets):
assert item[0] == df.values.tolist()[i][0]
assert self.conn.close.call_count == 1
assert self.cur.close.call_count == 1
self.cur.execute.assert_called_once_with(statement)
def test_get_df_polars(self):
statement = "SQL"
column = "col"
result_sets = [("row1",), ("row2",)]
mock_execute = MagicMock()
mock_execute.description = [(column, None, None, None, None, None, None)]
mock_execute.fetchall.return_value = result_sets
self.cur.execute.return_value = mock_execute
df = self.db_hook().get_df(statement, df_type="polars")
self.cur.execute.assert_called_once_with(statement)
mock_execute.fetchall.assert_called_once_with()
assert column == df.columns[0]
assert result_sets[0][0] == df.row(0)[0]
assert result_sets[1][0] == df.row(1)[0]
def test_set_autocommit_raises_not_implemented(self):
db_hook = self.db_hook()
conn = db_hook.get_conn()
with pytest.raises(NotImplementedError, match=r"There are no transactions in Drill."):
db_hook.set_autocommit(conn=conn, autocommit=True)
def test_insert_rows_raises_not_implemented(self):
db_hook = self.db_hook()
with pytest.raises(NotImplementedError, match=r"There is no INSERT statement in Drill."):
db_hook.insert_rows(table="my_table", rows=[("a",)])
| TestDrillHook |
python | huggingface__transformers | tests/generation/test_configuration_utils.py | {
"start": 34137,
"end": 37730
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls._token = TOKEN
def test_push_to_hub(self):
with TemporaryHubRepo(token=self._token) as tmp_repo:
config = GenerationConfig(
do_sample=True,
temperature=0.7,
length_penalty=1.0,
)
config.push_to_hub(tmp_repo.repo_id, token=self._token)
new_config = GenerationConfig.from_pretrained(tmp_repo.repo_id)
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(v, getattr(new_config, k))
def test_push_to_hub_via_save_pretrained(self):
with TemporaryHubRepo(token=self._token) as tmp_repo:
config = GenerationConfig(
do_sample=True,
temperature=0.7,
length_penalty=1.0,
)
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(tmp_dir, repo_id=tmp_repo.repo_id, push_to_hub=True, token=self._token)
new_config = GenerationConfig.from_pretrained(tmp_repo.repo_id)
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(v, getattr(new_config, k))
def test_push_to_hub_in_organization(self):
with TemporaryHubRepo(namespace="valid_org", token=self._token) as tmp_repo:
config = GenerationConfig(
do_sample=True,
temperature=0.7,
length_penalty=1.0,
)
config.push_to_hub(tmp_repo.repo_id, token=self._token)
new_config = GenerationConfig.from_pretrained(tmp_repo.repo_id)
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(v, getattr(new_config, k))
def test_push_to_hub_in_organization_via_save_pretrained(self):
with TemporaryHubRepo(namespace="valid_org", token=self._token) as tmp_repo:
config = GenerationConfig(
do_sample=True,
temperature=0.7,
length_penalty=1.0,
)
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(tmp_dir, repo_id=tmp_repo.repo_id, push_to_hub=True, token=self._token)
new_config = GenerationConfig.from_pretrained(tmp_repo.repo_id)
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(v, getattr(new_config, k))
def test_push_to_hub_on_pr_revision(self):
with TemporaryHubRepo(token=self._token) as tmp_repo:
# create a PR
pr = create_pull_request(repo_id=tmp_repo.repo_id, title="Test PR", token=self._token)
revision = f"refs/pr/{pr.num}"
# push to PR ref
config = GenerationConfig(
do_sample=True,
temperature=0.7,
length_penalty=1.0,
)
config.push_to_hub(tmp_repo.repo_id, token=self._token, revision=revision)
# load from PR ref
new_config = GenerationConfig.from_pretrained(tmp_repo.repo_id, revision=revision)
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(v, getattr(new_config, k))
| ConfigPushToHubTester |
python | PyCQA__pylint | tests/functional/n/not_async_context_manager.py | {
"start": 351,
"end": 425
} | class ____:
def __aenter__(self):
pass
| PartialAsyncContextManager |
python | django__django | tests/timezones/models.py | {
"start": 31,
"end": 92
} | class ____(models.Model):
dt = models.DateTimeField()
| Event |
python | django__django | tests/lookup/models.py | {
"start": 1089,
"end": 1248
} | class ____(models.TextField):
def get_prep_value(self, value):
return None if value == "" else value
@NulledTextField.register_lookup
| NulledTextField |
python | walkccc__LeetCode | solutions/2559. Count Vowel Strings in Ranges/2559.py | {
"start": 0,
"end": 453
} | class ____:
def vowelStrings(
self,
words: list[str],
queries: list[list[int]],
) -> list[int]:
VOWELS = 'aeiou'
# prefix[i] := the number of the first i words that start with and end in a vowel
prefix = [0] * (len(words) + 1)
for i, word in enumerate(words):
prefix[i + 1] += prefix[i] + (word[0] in VOWELS and word[-1] in VOWELS)
return [prefix[r + 1] - prefix[l]
for l, r in queries]
| Solution |
python | Farama-Foundation__Gymnasium | gymnasium/envs/mujoco/mujoco_rendering.py | {
"start": 5325,
"end": 10714
} | class ____(BaseRender):
"""Offscreen rendering class with opengl context."""
def __init__(
self,
model: "mujoco.MjMujoco",
data: "mujoco.MjData",
width: int,
height: int,
max_geom: int = 1000,
visual_options: dict[int, bool] = {},
):
# We must make GLContext before MjrContext
self._get_opengl_backend(width, height)
super().__init__(model, data, width, height, max_geom, visual_options)
self._init_camera()
def _init_camera(self):
self.cam.type = mujoco.mjtCamera.mjCAMERA_FREE
self.cam.fixedcamid = -1
for i in range(3):
self.cam.lookat[i] = np.median(self.data.geom_xpos[:, i])
self.cam.distance = self.model.stat.extent
def _get_opengl_backend(self, width: int, height: int):
self.backend = os.environ.get("MUJOCO_GL")
if self.backend is not None:
try:
self.opengl_context = _ALL_RENDERERS[self.backend](width, height)
except KeyError as e:
raise RuntimeError(
f"Environment variable {'MUJOCO_GL'} must be one of {_ALL_RENDERERS.keys()!r}: got {self.backend!r}."
) from e
else:
for name, _ in _ALL_RENDERERS.items():
try:
self.opengl_context = _ALL_RENDERERS[name](width, height)
self.backend = name
break
except: # noqa:E722
pass
if self.backend is None:
raise RuntimeError(
"No OpenGL backend could be imported. Attempting to create a "
"rendering context will result in a RuntimeError."
)
def _set_mujoco_buffer(self):
mujoco.mjr_setBuffer(mujoco.mjtFramebuffer.mjFB_OFFSCREEN, self.con)
def make_context_current(self):
self.opengl_context.make_current()
def free(self):
self.opengl_context.free()
def __del__(self):
self.free()
def render(
self,
render_mode: str | None,
camera_id: int | None = None,
segmentation: bool = False,
):
if camera_id is not None:
if camera_id == -1:
self.cam.type = mujoco.mjtCamera.mjCAMERA_FREE
else:
self.cam.type = mujoco.mjtCamera.mjCAMERA_FIXED
self.cam.fixedcamid = camera_id
mujoco.mjv_updateScene(
self.model,
self.data,
self.vopt,
self.pert,
self.cam,
mujoco.mjtCatBit.mjCAT_ALL,
self.scn,
)
if segmentation:
self.scn.flags[mujoco.mjtRndFlag.mjRND_SEGMENT] = 1
self.scn.flags[mujoco.mjtRndFlag.mjRND_IDCOLOR] = 1
for marker_params in self._markers:
self._add_marker_to_scene(marker_params)
mujoco.mjr_render(self.viewport, self.scn, self.con)
for gridpos, (text1, text2) in self._overlays.items():
mujoco.mjr_overlay(
mujoco.mjtFontScale.mjFONTSCALE_150,
gridpos,
self.viewport,
text1.encode(),
text2.encode(),
self.con,
)
if segmentation:
self.scn.flags[mujoco.mjtRndFlag.mjRND_SEGMENT] = 0
self.scn.flags[mujoco.mjtRndFlag.mjRND_IDCOLOR] = 0
rgb_arr = np.zeros(
3 * self.viewport.width * self.viewport.height, dtype=np.uint8
)
depth_arr = np.zeros(
self.viewport.width * self.viewport.height, dtype=np.float32
)
mujoco.mjr_readPixels(rgb_arr, depth_arr, self.viewport, self.con)
# Process rendered images according to render_mode
if render_mode in ["depth_array", "rgbd_tuple"]:
depth_img = depth_arr.reshape((self.viewport.height, self.viewport.width))
# original image is upside-down, so flip it
depth_img = depth_img[::-1, :]
if render_mode in ["rgb_array", "rgbd_tuple"]:
rgb_img = rgb_arr.reshape((self.viewport.height, self.viewport.width, 3))
# original image is upside-down, so flip it
rgb_img = rgb_img[::-1, :]
if segmentation:
seg_img = (
rgb_img[:, :, 0]
+ rgb_img[:, :, 1] * (2**8)
+ rgb_img[:, :, 2] * (2**16)
)
seg_img[seg_img >= (self.scn.ngeom + 1)] = 0
seg_ids = np.full(
(self.scn.ngeom + 1, 2), fill_value=-1, dtype=np.int32
)
for i in range(self.scn.ngeom):
geom = self.scn.geoms[i]
if geom.segid != -1:
seg_ids[geom.segid + 1, 0] = geom.objtype
seg_ids[geom.segid + 1, 1] = geom.objid
rgb_img = seg_ids[seg_img]
self._markers.clear()
# Return processed images based on render_mode
if render_mode == "rgb_array":
return rgb_img
elif render_mode == "depth_array":
return depth_img
else: # "rgbd_tuple"
return rgb_img, depth_img
def close(self):
self.free()
glfw.terminate()
| OffScreenViewer |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 34410,
"end": 35760
} | class ____(MixinSequenceOfValues):
"""
x-axis major tick lines
Parameters
----------
theme_element : element_line
"""
def apply_ax(self, ax: Axes):
super().apply_ax(ax)
params = ax.xaxis.get_tick_params(which="major")
# TODO: Remove this code when the minimum matplotlib >= 3.10.0,
# and use the commented one below it
import matplotlib as mpl
from packaging import version
vinstalled = version.parse(mpl.__version__)
v310 = version.parse("3.10.0")
name = "bottom" if vinstalled >= v310 else "left"
if not params.get(name, False):
return
# if not params.get("bottom", False):
# return
tick_params = {}
properties = self.properties
with suppress(KeyError):
tick_params["width"] = properties.pop("linewidth")
with suppress(KeyError):
tick_params["color"] = properties.pop("color")
if tick_params:
ax.xaxis.set_tick_params(which="major", **tick_params)
lines = [t.tick1line for t in ax.xaxis.get_major_ticks()]
self.set(lines, properties)
def blank_ax(self, ax: Axes):
super().blank_ax(ax)
for tick in ax.xaxis.get_major_ticks():
tick.tick1line.set_visible(False)
| axis_ticks_major_x |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/class_interval.py | {
"start": 7856,
"end": 8093
} | class ____(A18):
@staticmethod
def m(arg):
# Expect an issue
B18.m(arg)
def test_static_methods():
# Expect an issue
C18.m0(_test_source())
# Expect an issue
c = C18()
c.m0(_test_source())
| C18 |
python | paramiko__paramiko | paramiko/agent.py | {
"start": 12035,
"end": 13070
} | class ____(AgentSSH):
"""
Client interface for using private keys from an SSH agent running on the
local machine. If an SSH agent is running, this class can be used to
connect to it and retrieve `.PKey` objects which can be used when
attempting to authenticate to remote SSH servers.
Upon initialization, a session with the local machine's SSH agent is
opened, if one is running. If no agent is running, initialization will
succeed, but `get_keys` will return an empty tuple.
:raises: `.SSHException` --
if an SSH agent is found, but speaks an incompatible protocol
.. versionchanged:: 2.10
Added support for native openssh agent on windows (extending previous
putty pageant support)
"""
def __init__(self):
AgentSSH.__init__(self)
conn = get_agent_connection()
if not conn:
return
self._connect(conn)
def close(self):
"""
Close the SSH agent connection.
"""
self._close()
| Agent |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_internal/metadata/base.py | {
"start": 2613,
"end": 21211
} | class ____(Protocol):
@classmethod
def from_directory(cls, directory: str) -> "BaseDistribution":
"""Load the distribution from a metadata directory.
:param directory: Path to a metadata directory, e.g. ``.dist-info``.
"""
raise NotImplementedError()
@classmethod
def from_metadata_file_contents(
cls,
metadata_contents: bytes,
filename: str,
project_name: str,
) -> "BaseDistribution":
"""Load the distribution from the contents of a METADATA file.
This is used to implement PEP 658 by generating a "shallow" dist object that can
be used for resolution without downloading or building the actual dist yet.
:param metadata_contents: The contents of a METADATA file.
:param filename: File name for the dist with this metadata.
:param project_name: Name of the project this dist represents.
"""
raise NotImplementedError()
@classmethod
def from_wheel(cls, wheel: "Wheel", name: str) -> "BaseDistribution":
"""Load the distribution from a given wheel.
:param wheel: A concrete wheel definition.
:param name: File name of the wheel.
:raises InvalidWheel: Whenever loading of the wheel causes a
:py:exc:`zipfile.BadZipFile` exception to be thrown.
:raises UnsupportedWheel: If the wheel is a valid zip, but malformed
internally.
"""
raise NotImplementedError()
def __repr__(self) -> str:
return f"{self.raw_name} {self.raw_version} ({self.location})"
def __str__(self) -> str:
return f"{self.raw_name} {self.raw_version}"
@property
def location(self) -> Optional[str]:
"""Where the distribution is loaded from.
A string value is not necessarily a filesystem path, since distributions
can be loaded from other sources, e.g. arbitrary zip archives. ``None``
means the distribution is created in-memory.
Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If
this is a symbolic link, we want to preserve the relative path between
it and files in the distribution.
"""
raise NotImplementedError()
@property
def editable_project_location(self) -> Optional[str]:
"""The project location for editable distributions.
This is the directory where pyproject.toml or setup.py is located.
None if the distribution is not installed in editable mode.
"""
# TODO: this property is relatively costly to compute, memoize it ?
direct_url = self.direct_url
if direct_url:
if direct_url.is_local_editable():
return url_to_path(direct_url.url)
else:
# Search for an .egg-link file by walking sys.path, as it was
# done before by dist_is_editable().
egg_link_path = egg_link_path_from_sys_path(self.raw_name)
if egg_link_path:
# TODO: get project location from second line of egg_link file
# (https://github.com/pypa/pip/issues/10243)
return self.location
return None
@property
def installed_location(self) -> Optional[str]:
"""The distribution's "installed" location.
This should generally be a ``site-packages`` directory. This is
usually ``dist.location``, except for legacy develop-installed packages,
where ``dist.location`` is the source code location, and this is where
the ``.egg-link`` file is.
The returned location is normalized (in particular, with symlinks removed).
"""
raise NotImplementedError()
@property
def info_location(self) -> Optional[str]:
"""Location of the .[egg|dist]-info directory or file.
Similarly to ``location``, a string value is not necessarily a
filesystem path. ``None`` means the distribution is created in-memory.
For a modern .dist-info installation on disk, this should be something
like ``{location}/{raw_name}-{version}.dist-info``.
Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If
this is a symbolic link, we want to preserve the relative path between
it and other files in the distribution.
"""
raise NotImplementedError()
@property
def installed_by_distutils(self) -> bool:
"""Whether this distribution is installed with legacy distutils format.
A distribution installed with "raw" distutils not patched by setuptools
uses one single file at ``info_location`` to store metadata. We need to
treat this specially on uninstallation.
"""
info_location = self.info_location
if not info_location:
return False
return pathlib.Path(info_location).is_file()
@property
def installed_as_egg(self) -> bool:
"""Whether this distribution is installed as an egg.
This usually indicates the distribution was installed by (older versions
of) easy_install.
"""
location = self.location
if not location:
return False
return location.endswith(".egg")
@property
def installed_with_setuptools_egg_info(self) -> bool:
"""Whether this distribution is installed with the ``.egg-info`` format.
This usually indicates the distribution was installed with setuptools
with an old pip version or with ``single-version-externally-managed``.
Note that this ensure the metadata store is a directory. distutils can
also installs an ``.egg-info``, but as a file, not a directory. This
property is *False* for that case. Also see ``installed_by_distutils``.
"""
info_location = self.info_location
if not info_location:
return False
if not info_location.endswith(".egg-info"):
return False
return pathlib.Path(info_location).is_dir()
@property
def installed_with_dist_info(self) -> bool:
"""Whether this distribution is installed with the "modern format".
This indicates a "modern" installation, e.g. storing metadata in the
``.dist-info`` directory. This applies to installations made by
setuptools (but through pip, not directly), or anything using the
standardized build backend interface (PEP 517).
"""
info_location = self.info_location
if not info_location:
return False
if not info_location.endswith(".dist-info"):
return False
return pathlib.Path(info_location).is_dir()
@property
def canonical_name(self) -> NormalizedName:
raise NotImplementedError()
@property
def version(self) -> Version:
raise NotImplementedError()
@property
def raw_version(self) -> str:
raise NotImplementedError()
@property
def setuptools_filename(self) -> str:
"""Convert a project name to its setuptools-compatible filename.
This is a copy of ``pkg_resources.to_filename()`` for compatibility.
"""
return self.raw_name.replace("-", "_")
@property
def direct_url(self) -> Optional[DirectUrl]:
"""Obtain a DirectUrl from this distribution.
Returns None if the distribution has no `direct_url.json` metadata,
or if `direct_url.json` is invalid.
"""
try:
content = self.read_text(DIRECT_URL_METADATA_NAME)
except FileNotFoundError:
return None
try:
return DirectUrl.from_json(content)
except (
UnicodeDecodeError,
json.JSONDecodeError,
DirectUrlValidationError,
) as e:
logger.warning(
"Error parsing %s for %s: %s",
DIRECT_URL_METADATA_NAME,
self.canonical_name,
e,
)
return None
@property
def installer(self) -> str:
try:
installer_text = self.read_text("INSTALLER")
except (OSError, ValueError, NoneMetadataError):
return "" # Fail silently if the installer file cannot be read.
for line in installer_text.splitlines():
cleaned_line = line.strip()
if cleaned_line:
return cleaned_line
return ""
@property
def requested(self) -> bool:
return self.is_file("REQUESTED")
@property
def editable(self) -> bool:
return bool(self.editable_project_location)
@property
def local(self) -> bool:
"""If distribution is installed in the current virtual environment.
Always True if we're not in a virtualenv.
"""
if self.installed_location is None:
return False
return is_local(self.installed_location)
@property
def in_usersite(self) -> bool:
if self.installed_location is None or user_site is None:
return False
return self.installed_location.startswith(normalize_path(user_site))
@property
def in_site_packages(self) -> bool:
if self.installed_location is None or site_packages is None:
return False
return self.installed_location.startswith(normalize_path(site_packages))
def is_file(self, path: InfoPath) -> bool:
"""Check whether an entry in the info directory is a file."""
raise NotImplementedError()
def iter_distutils_script_names(self) -> Iterator[str]:
"""Find distutils 'scripts' entries metadata.
If 'scripts' is supplied in ``setup.py``, distutils records those in the
installed distribution's ``scripts`` directory, a file for each script.
"""
raise NotImplementedError()
def read_text(self, path: InfoPath) -> str:
"""Read a file in the info directory.
:raise FileNotFoundError: If ``path`` does not exist in the directory.
:raise NoneMetadataError: If ``path`` exists in the info directory, but
cannot be read.
"""
raise NotImplementedError()
def iter_entry_points(self) -> Iterable[BaseEntryPoint]:
raise NotImplementedError()
def _metadata_impl(self) -> email.message.Message:
raise NotImplementedError()
@functools.cached_property
def metadata(self) -> email.message.Message:
"""Metadata of distribution parsed from e.g. METADATA or PKG-INFO.
This should return an empty message if the metadata file is unavailable.
:raises NoneMetadataError: If the metadata file is available, but does
not contain valid metadata.
"""
metadata = self._metadata_impl()
self._add_egg_info_requires(metadata)
return metadata
@property
def metadata_dict(self) -> Dict[str, Any]:
"""PEP 566 compliant JSON-serializable representation of METADATA or PKG-INFO.
This should return an empty dict if the metadata file is unavailable.
:raises NoneMetadataError: If the metadata file is available, but does
not contain valid metadata.
"""
return msg_to_json(self.metadata)
@property
def metadata_version(self) -> Optional[str]:
"""Value of "Metadata-Version:" in distribution metadata, if available."""
return self.metadata.get("Metadata-Version")
@property
def raw_name(self) -> str:
"""Value of "Name:" in distribution metadata."""
# The metadata should NEVER be missing the Name: key, but if it somehow
# does, fall back to the known canonical name.
return self.metadata.get("Name", self.canonical_name)
@property
def requires_python(self) -> SpecifierSet:
"""Value of "Requires-Python:" in distribution metadata.
If the key does not exist or contains an invalid value, an empty
SpecifierSet should be returned.
"""
value = self.metadata.get("Requires-Python")
if value is None:
return SpecifierSet()
try:
# Convert to str to satisfy the type checker; this can be a Header object.
spec = SpecifierSet(str(value))
except InvalidSpecifier as e:
message = "Package %r has an invalid Requires-Python: %s"
logger.warning(message, self.raw_name, e)
return SpecifierSet()
return spec
def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:
"""Dependencies of this distribution.
For modern .dist-info distributions, this is the collection of
"Requires-Dist:" entries in distribution metadata.
"""
raise NotImplementedError()
def iter_raw_dependencies(self) -> Iterable[str]:
"""Raw Requires-Dist metadata."""
return self.metadata.get_all("Requires-Dist", [])
def iter_provided_extras(self) -> Iterable[NormalizedName]:
"""Extras provided by this distribution.
For modern .dist-info distributions, this is the collection of
"Provides-Extra:" entries in distribution metadata.
The return value of this function is expected to be normalised names,
per PEP 685, with the returned value being handled appropriately by
`iter_dependencies`.
"""
raise NotImplementedError()
def _iter_declared_entries_from_record(self) -> Optional[Iterator[str]]:
try:
text = self.read_text("RECORD")
except FileNotFoundError:
return None
# This extra Path-str cast normalizes entries.
return (str(pathlib.Path(row[0])) for row in csv.reader(text.splitlines()))
def _iter_declared_entries_from_legacy(self) -> Optional[Iterator[str]]:
try:
text = self.read_text("installed-files.txt")
except FileNotFoundError:
return None
paths = (p for p in text.splitlines(keepends=False) if p)
root = self.location
info = self.info_location
if root is None or info is None:
return paths
try:
info_rel = pathlib.Path(info).relative_to(root)
except ValueError: # info is not relative to root.
return paths
if not info_rel.parts: # info *is* root.
return paths
return (
_convert_installed_files_path(pathlib.Path(p).parts, info_rel.parts)
for p in paths
)
def iter_declared_entries(self) -> Optional[Iterator[str]]:
"""Iterate through file entries declared in this distribution.
For modern .dist-info distributions, this is the files listed in the
``RECORD`` metadata file. For legacy setuptools distributions, this
comes from ``installed-files.txt``, with entries normalized to be
compatible with the format used by ``RECORD``.
:return: An iterator for listed entries, or None if the distribution
contains neither ``RECORD`` nor ``installed-files.txt``.
"""
return (
self._iter_declared_entries_from_record()
or self._iter_declared_entries_from_legacy()
)
def _iter_requires_txt_entries(self) -> Iterator[RequiresEntry]:
"""Parse a ``requires.txt`` in an egg-info directory.
This is an INI-ish format where an egg-info stores dependencies. A
section name describes extra other environment markers, while each entry
is an arbitrary string (not a key-value pair) representing a dependency
as a requirement string (no markers).
There is a construct in ``importlib.metadata`` called ``Sectioned`` that
does mostly the same, but the format is currently considered private.
"""
try:
content = self.read_text("requires.txt")
except FileNotFoundError:
return
extra = marker = "" # Section-less entries don't have markers.
for line in content.splitlines():
line = line.strip()
if not line or line.startswith("#"): # Comment; ignored.
continue
if line.startswith("[") and line.endswith("]"): # A section header.
extra, _, marker = line.strip("[]").partition(":")
continue
yield RequiresEntry(requirement=line, extra=extra, marker=marker)
def _iter_egg_info_extras(self) -> Iterable[str]:
"""Get extras from the egg-info directory."""
known_extras = {""}
for entry in self._iter_requires_txt_entries():
extra = canonicalize_name(entry.extra)
if extra in known_extras:
continue
known_extras.add(extra)
yield extra
def _iter_egg_info_dependencies(self) -> Iterable[str]:
"""Get distribution dependencies from the egg-info directory.
To ease parsing, this converts a legacy dependency entry into a PEP 508
requirement string. Like ``_iter_requires_txt_entries()``, there is code
in ``importlib.metadata`` that does mostly the same, but not do exactly
what we need.
Namely, ``importlib.metadata`` does not normalize the extra name before
putting it into the requirement string, which causes marker comparison
to fail because the dist-info format do normalize. This is consistent in
all currently available PEP 517 backends, although not standardized.
"""
for entry in self._iter_requires_txt_entries():
extra = canonicalize_name(entry.extra)
if extra and entry.marker:
marker = f'({entry.marker}) and extra == "{extra}"'
elif extra:
marker = f'extra == "{extra}"'
elif entry.marker:
marker = entry.marker
else:
marker = ""
if marker:
yield f"{entry.requirement} ; {marker}"
else:
yield entry.requirement
def _add_egg_info_requires(self, metadata: email.message.Message) -> None:
"""Add egg-info requires.txt information to the metadata."""
if not metadata.get_all("Requires-Dist"):
for dep in self._iter_egg_info_dependencies():
metadata["Requires-Dist"] = dep
if not metadata.get_all("Provides-Extra"):
for extra in self._iter_egg_info_extras():
metadata["Provides-Extra"] = extra
| BaseDistribution |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/sagemaker.py | {
"start": 69495,
"end": 74013
} | class ____(SageMakerBaseOperator):
"""
Register a SageMaker model by creating a model version that specifies the model group to which it belongs.
Will create the model group if it does not exist already.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:SageMakerRegisterModelVersionOperator`
:param image_uri: The Amazon EC2 Container Registry (Amazon ECR) path where inference code is stored.
:param model_url: The Amazon S3 path where the model artifacts (the trained weights of the model), which
result from model training, are stored. This path must point to a single gzip compressed tar archive
(.tar.gz suffix).
:param package_group_name: The name of the model package group that the model is going to be registered
to. Will be created if it doesn't already exist.
:param package_group_desc: Description of the model package group, if it was to be created (optional).
:param package_desc: Description of the model package (optional).
:param model_approval: Approval status of the model package. Defaults to PendingManualApproval
:param extras: Can contain extra parameters for the boto call to create_model_package, and/or overrides
for any parameter defined above. For a complete list of available parameters, see
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker.html#SageMaker.Client.create_model_package
:param aws_conn_id: The Airflow connection used for AWS credentials.
If this is ``None`` or empty then the default boto3 behaviour is used. If
running Airflow in a distributed manner and aws_conn_id is None or
empty, then default boto3 configuration would be used (and must be
maintained on each worker node).
:param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
:param verify: Whether or not to verify SSL certificates. See:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
:return str: Returns the ARN of the model package created.
"""
template_fields: Sequence[str] = aws_template_fields(
"image_uri",
"model_url",
"package_group_name",
"package_group_desc",
"package_desc",
"model_approval",
)
def __init__(
self,
*,
image_uri: str,
model_url: str,
package_group_name: str,
package_group_desc: str = "",
package_desc: str = "",
model_approval: ApprovalStatus = ApprovalStatus.PENDING_MANUAL_APPROVAL,
extras: dict | None = None,
config: dict | None = None,
**kwargs,
):
super().__init__(config=config or {}, **kwargs)
self.image_uri = image_uri
self.model_url = model_url
self.package_group_name = package_group_name
self.package_group_desc = package_group_desc
self.package_desc = package_desc
self.model_approval = model_approval
self.extras = extras
def execute(self, context: Context):
# create a model package group if it does not exist
group_created = self.hook.create_model_package_group(self.package_group_name, self.package_desc)
# then create a model package in that group
input_dict = {
"InferenceSpecification": {
"Containers": [
{
"Image": self.image_uri,
"ModelDataUrl": self.model_url,
}
],
"SupportedContentTypes": ["text/csv"],
"SupportedResponseMIMETypes": ["text/csv"],
},
"ModelPackageGroupName": self.package_group_name,
"ModelPackageDescription": self.package_desc,
"ModelApprovalStatus": self.model_approval.value,
}
if self.extras:
input_dict.update(self.extras) # overrides config above if keys are redefined in extras
try:
res = self.hook.conn.create_model_package(**input_dict)
return res["ModelPackageArn"]
except ClientError:
# rollback group creation if adding the model to it was not successful
if group_created:
self.hook.conn.delete_model_package_group(ModelPackageGroupName=self.package_group_name)
raise
| SageMakerRegisterModelVersionOperator |
python | doocs__leetcode | solution/0600-0699/0669.Trim a Binary Search Tree/Solution2.py | {
"start": 192,
"end": 864
} | class ____:
def trimBST(
self, root: Optional[TreeNode], low: int, high: int
) -> Optional[TreeNode]:
while root and (root.val < low or root.val > high):
root = root.left if root.val > high else root.right
if root is None:
return None
node = root
while node.left:
if node.left.val < low:
node.left = node.left.right
else:
node = node.left
node = root
while node.right:
if node.right.val > high:
node.right = node.right.left
else:
node = node.right
return root
| Solution |
python | great-expectations__great_expectations | great_expectations/core/batch.py | {
"start": 9274,
"end": 19836
} | class ____(SerializableDictDot):
"""
This class is for internal inter-object protocol purposes only.
As such, it contains all attributes of a batch_request, but does not validate them.
See the BatchRequest class, which extends BatchRequestBase and validates the attributes.
BatchRequestBase is used for the internal protocol purposes exclusively, not part of API for the developer users.
Previously, the very same BatchRequest was used for both the internal protocol purposes and as part of the API
exposed to developers. However, while convenient for internal data interchange, using the same BatchRequest class
as arguments to the externally-exported DataContext.get_batch_list() and DataContext.get_validator() API calls for
obtaining batches and/or validators was insufficiently expressive to fulfill the needs of both. In the user-accessible
API, BatchRequest, must enforce that all members of the triple, consisting of data_source_name, data_connector_name,
and data_asset_name, are not NULL. Whereas for the internal protocol, BatchRequest is used as a flexible bag of attributes,
in which any fields are allowed to be NULL. Hence, now, BatchRequestBase is dedicated for the use as the bag oof attributes
for the internal protocol use, whereby NULL values are allowed as per the internal needs. The BatchRequest class extends
BatchRequestBase and adds to it strong validation (described above plus additional attribute validation) so as to formally
validate user specified fields.
""" # noqa: E501 # FIXME CoP
def __init__( # noqa: PLR0913 # FIXME CoP
self,
datasource_name: str,
data_connector_name: str,
data_asset_name: str,
data_connector_query: dict | None = None,
limit: int | None = None,
runtime_parameters: dict | None = None,
batch_identifiers: dict | None = None,
batch_spec_passthrough: dict | None = None,
) -> None:
self._datasource_name = datasource_name
self._data_connector_name = data_connector_name
self._data_asset_name = data_asset_name
self._data_connector_query = data_connector_query
self._limit = limit
self._runtime_parameters = runtime_parameters
self._batch_identifiers = batch_identifiers
self._batch_spec_passthrough = batch_spec_passthrough
@property
def datasource_name(self) -> str:
return self._datasource_name
@datasource_name.setter
def datasource_name(self, value: str) -> None:
self._datasource_name = value
@property
def data_connector_name(self) -> str:
return self._data_connector_name
@data_connector_name.setter
def data_connector_name(self, value: str) -> None:
self._data_connector_name = value
@property
def data_asset_name(self) -> str:
return self._data_asset_name
@data_asset_name.setter
def data_asset_name(self, data_asset_name) -> None:
self._data_asset_name = data_asset_name
@property
def data_connector_query(self) -> dict | None:
return self._data_connector_query
@data_connector_query.setter
def data_connector_query(self, value: dict) -> None:
self._data_connector_query = value
@property
def limit(self) -> int | None:
return self._limit
@limit.setter
def limit(self, value: int) -> None:
self._limit = value
@property
def runtime_parameters(self) -> dict | None:
return self._runtime_parameters
@runtime_parameters.setter
def runtime_parameters(self, value: dict) -> None:
self._runtime_parameters = value
@property
def batch_identifiers(self) -> dict | None:
return self._batch_identifiers
@batch_identifiers.setter
def batch_identifiers(self, value: dict) -> None:
self._batch_identifiers = value
@property
def batch_spec_passthrough(self) -> dict | None:
return self._batch_spec_passthrough
@batch_spec_passthrough.setter
def batch_spec_passthrough(self, value: dict) -> None:
self._batch_spec_passthrough = value
@property
def id(self) -> IDDictID:
return IDDict(self.to_json_dict()).to_id()
@override
def to_dict(self) -> BlockConfigBatchRequestTypedDict: # type: ignore[override] # TypedDict is more specific dict type
return standardize_batch_request_display_ordering(
batch_request=super().to_dict() # type: ignore[arg-type] # TypedDict is more specific dict type
)
# While this class is private, it is inherited from and this method is part
# of the public api on the child.
@override
def to_json_dict(self) -> dict[str, JSONValues]:
"""Returns a JSON-serializable dict representation of this BatchRequestBase.
Returns:
A JSON-serializable dict representation of this BatchRequestBase.
"""
# TODO: <Alex>2/4/2022</Alex>
# This implementation of "SerializableDictDot.to_json_dict() occurs frequently and should ideally serve as the # noqa: E501 # FIXME CoP
# reference implementation in the "SerializableDictDot" class itself. However, the circular import dependencies, # noqa: E501 # FIXME CoP
# due to the location of the "great_expectations/types/__init__.py" and "great_expectations/core/util.py" modules # noqa: E501 # FIXME CoP
# make this refactoring infeasible at the present time.
# if batch_data appears in BatchRequest, temporarily replace it with
# str placeholder before calling convert_to_json_serializable so that
# batch_data is not serialized
serializeable_dict: dict
if batch_request_contains_batch_data(batch_request=self):
if self.runtime_parameters is None:
raise ValueError("BatchRequestBase missing runtime_parameters during serialization") # noqa: TRY003 # FIXME CoP
batch_data: BatchRequestBase | dict = self.runtime_parameters["batch_data"]
self.runtime_parameters["batch_data"] = str(type(batch_data))
serializeable_dict = convert_to_json_serializable(data=self.to_dict()) # type: ignore[call-overload] # TypedDict is more specific dict type
# after getting serializable_dict, restore original batch_data
self.runtime_parameters["batch_data"] = batch_data
else:
serializeable_dict = convert_to_json_serializable(data=self.to_dict()) # type: ignore[call-overload] # TypedDict is more specific dict type
return serializeable_dict
def __deepcopy__(self, memo):
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for key, value in self.to_raw_dict().items():
value_copy = safe_deep_copy(data=value, memo=memo)
setattr(result, key, value_copy)
return result
@override
def __eq__(self, other):
if not isinstance(other, self.__class__):
# Delegate comparison to the other instance's __eq__.
return NotImplemented
return self.id == other.id
@override
def __hash__(self) -> int:
return hash(self.id)
@override
def __repr__(self) -> str:
"""
# TODO: <Alex>2/4/2022</Alex>
This implementation of a custom "__repr__()" occurs frequently and should ideally serve as the reference
implementation in the "SerializableDictDot" class. However, the circular import dependencies, due to the
location of the "great_expectations/types/__init__.py" and "great_expectations/core/util.py" modules make this
refactoring infeasible at the present time.
""" # noqa: E501 # FIXME CoP
json_dict: dict = self.to_json_dict()
deep_filter_properties_iterable(
properties=json_dict,
inplace=True,
)
return json.dumps(json_dict, indent=2)
@override
def __str__(self) -> str:
"""
# TODO: <Alex>2/4/2022</Alex>
This implementation of a custom "__str__()" occurs frequently and should ideally serve as the reference
implementation in the "SerializableDictDot" class. However, the circular import dependencies, due to the
location of the "great_expectations/types/__init__.py" and "great_expectations/core/util.py" modules make this
refactoring infeasible at the present time.
""" # noqa: E501 # FIXME CoP
return self.__repr__()
@staticmethod
def _validate_init_parameters(
datasource_name: str,
data_connector_name: str,
data_asset_name: str,
data_connector_query: dict | None = None,
limit: int | None = None,
) -> None:
# TODO test and check all logic in this validator!
if not (datasource_name and isinstance(datasource_name, str)):
raise TypeError( # noqa: TRY003 # FIXME CoP
f"""The type of an datasource name must be a string (Python "str"). The type given is
"{type(datasource_name)!s}", which is illegal.
""" # noqa: E501 # FIXME CoP
)
if not (data_connector_name and isinstance(data_connector_name, str)):
raise TypeError( # noqa: TRY003 # FIXME CoP
f"""The type of data_connector name must be a string (Python "str"). The type given is
"{type(data_connector_name)!s}", which is illegal.
""" # noqa: E501 # FIXME CoP
)
if not (data_asset_name and isinstance(data_asset_name, str)):
raise TypeError( # noqa: TRY003 # FIXME CoP
f"""The type of data_asset name must be a string (Python "str"). The type given is
"{type(data_asset_name)!s}", which is illegal.
"""
)
# TODO Abe 20201015: Switch this to DataConnectorQuery.
if data_connector_query and not isinstance(data_connector_query, dict):
raise TypeError( # noqa: TRY003 # FIXME CoP
f"""The type of data_connector_query must be a dict object. The type given is
"{type(data_connector_query)!s}", which is illegal.
"""
)
if limit and not isinstance(limit, int):
raise TypeError( # noqa: TRY003 # FIXME CoP
f"""The type of limit must be an integer (Python "int"). The type given is "{type(limit)!s}", which
is illegal.
""" # noqa: E501 # FIXME CoP
)
| BatchRequestBase |
python | huggingface__transformers | src/transformers/models/got_ocr2/modeling_got_ocr2.py | {
"start": 8312,
"end": 12284
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, window_size):
super().__init__()
self.layer_norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.attn = GotOcr2VisionAttention(config, window_size)
self.layer_norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.mlp = GotOcr2MLPBlock(config)
self.window_size = window_size
def window_partition(self, hidden_states: torch.Tensor, window_size: int) -> tuple[torch.Tensor, tuple[int, int]]:
"""
Args:
Partition into non-overlapping windows with padding if needed.
hidden_states (tensor): input tokens with [batch_size, height, width, channel]. window_size (int): window
size.
Returns:
windows: windows after partition with [batch_size * num_windows, window_size, window_size, channel].
(pad_height, pad_width): padded height and width before partition
"""
batch_size, height, width, channel = hidden_states.shape
pad_h = (window_size - height % window_size) % window_size
pad_w = (window_size - width % window_size) % window_size
hidden_states = F.pad(hidden_states, (0, 0, 0, pad_w, 0, pad_h))
pad_height, pad_width = height + pad_h, width + pad_w
hidden_states = hidden_states.reshape(
batch_size, pad_height // window_size, window_size, pad_width // window_size, window_size, channel
)
windows = hidden_states.permute(0, 1, 3, 2, 4, 5).contiguous().reshape(-1, window_size, window_size, channel)
return windows, (pad_height, pad_width)
def window_unpartition(
self, windows: torch.Tensor, window_size: int, padding_shape: tuple[int, int], original_shape: tuple[int, int]
) -> torch.Tensor:
"""
Args:
Window unpartition into original sequences and removing padding.
hidden_states (tensor):
input tokens with [batch_size * num_windows, window_size, window_size, channel].
window_size (int):
window size.
padding_shape (Tuple):
padded height and width (pad_height, pad_width).
original_shape (Tuple): original height and width (height, width) before padding.
Returns:
hidden_states: unpartitioned sequences with [batch_size, height, width, channel].
"""
pad_height, pad_width = padding_shape
height, width = original_shape
batch_size = windows.shape[0] // (pad_height * pad_width // window_size // window_size)
hidden_states = windows.reshape(
batch_size, pad_height // window_size, pad_width // window_size, window_size, window_size, -1
)
hidden_states = (
hidden_states.permute(0, 1, 3, 2, 4, 5).contiguous().reshape(batch_size, pad_height, pad_width, -1)
)
hidden_states = hidden_states[:, :height, :width, :].contiguous()
return hidden_states
def forward(self, hidden_states: torch.Tensor) -> tuple[torch.FloatTensor]:
residual = hidden_states
hidden_states = self.layer_norm1(hidden_states)
# Window partition
if self.window_size > 0:
height, width = hidden_states.shape[1], hidden_states.shape[2]
hidden_states, padding_shape = self.window_partition(hidden_states, self.window_size)
hidden_states, attn_weights = self.attn(
hidden_states=hidden_states,
)
# Reverse window partition
if self.window_size > 0:
hidden_states = self.window_unpartition(hidden_states, self.window_size, padding_shape, (height, width))
hidden_states = residual + hidden_states
layernorm_output = self.layer_norm2(hidden_states)
hidden_states = hidden_states + self.mlp(layernorm_output)
return hidden_states
@auto_docstring
| GotOcr2VisionLayer |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/launcher/sync_in_memory_run_launcher.py | {
"start": 493,
"end": 1593
} | class ____(RunLauncher, ConfigurableClass):
"""This run launcher launches runs synchronously, in memory, and is intended only for test.
Use the :py:class:`dagster.DefaultRunLauncher`.
"""
def __init__(self, inst_data: Optional[ConfigurableClassData] = None):
self._inst_data = inst_data
self._repository = None
self._instance_ref = None
super().__init__()
@property
def inst_data(self) -> Optional[ConfigurableClassData]:
return self._inst_data
@classmethod
def config_type(cls) -> UserConfigSchema:
return {}
@classmethod
def from_config_value(
cls, inst_data: ConfigurableClassData, config_value: Mapping[str, Any]
) -> Self:
return cls(inst_data=inst_data)
def launch_run(self, context: LaunchRunContext) -> None:
recon_job = recon_job_from_origin(context.job_code_origin) # type: ignore
execute_run(recon_job, context.dagster_run, self._instance)
def terminate(self, run_id):
check.not_implemented("Termination not supported.")
| SyncInMemoryRunLauncher |
python | wandb__wandb | tests/unit_tests/test_internal_api.py | {
"start": 12121,
"end": 22052
} | class ____:
"""Tests `upload_file`."""
class TestSimple:
def test_adds_headers_to_request(
self, mock_responses: RequestsMock, example_file: Path
):
response_callback = Mock(return_value=(200, {}, "success!"))
mock_responses.add_callback(
"PUT", "http://example.com/upload-dst", response_callback
)
internal.InternalApi().upload_file(
"http://example.com/upload-dst",
example_file.open("rb"),
extra_headers={"X-Test": "test"},
)
assert response_callback.call_args[0][0].headers["X-Test"] == "test"
def test_returns_response_on_success(
self, mock_responses: RequestsMock, example_file: Path
):
mock_responses.put(
"http://example.com/upload-dst", status=200, body="success!"
)
resp = internal.InternalApi().upload_file(
"http://example.com/upload-dst", example_file.open("rb")
)
assert resp.content == b"success!"
# test_async_returns_response_on_success: doesn't exist,
# because `upload_file_async` doesn't return the response.
@pytest.mark.parametrize(
"response,expected_errtype",
[
((400, {}, ""), requests.exceptions.HTTPError),
((500, {}, ""), retry.TransientError),
((502, {}, ""), retry.TransientError),
(requests.exceptions.ConnectionError(), retry.TransientError),
(requests.exceptions.Timeout(), retry.TransientError),
(RuntimeError("oh no"), RuntimeError),
],
)
def test_returns_transienterror_on_transient_issues(
self,
mock_responses: RequestsMock,
example_file: Path,
response: MockResponseOrException,
expected_errtype: Type[Exception],
):
mock_responses.add_callback(
"PUT",
"http://example.com/upload-dst",
Mock(return_value=response),
)
with pytest.raises(expected_errtype):
internal.InternalApi().upload_file(
"http://example.com/upload-dst", example_file.open("rb")
)
class TestProgressCallback:
def test_smoke(self, mock_responses: RequestsMock, example_file: Path):
file_contents = "some text"
example_file.write_text(file_contents)
def response_callback(request: requests.models.PreparedRequest):
assert request.body.read() == file_contents.encode()
return (200, {}, "success!")
mock_responses.add_callback(
"PUT", "http://example.com/upload-dst", response_callback
)
progress_callback = Mock()
internal.InternalApi().upload_file(
"http://example.com/upload-dst",
example_file.open("rb"),
callback=progress_callback,
)
assert progress_callback.call_args_list == [
call(len(file_contents), len(file_contents))
]
def test_handles_multiple_calls(
self, mock_responses: RequestsMock, example_file: Path
):
example_file.write_text("12345")
def response_callback(request: requests.models.PreparedRequest):
assert request.body.read(2) == b"12"
assert request.body.read(2) == b"34"
assert request.body.read() == b"5"
assert request.body.read() == b""
return (200, {}, "success!")
mock_responses.add_callback(
"PUT", "http://example.com/upload-dst", response_callback
)
progress_callback = Mock()
internal.InternalApi().upload_file(
"http://example.com/upload-dst",
example_file.open("rb"),
callback=progress_callback,
)
assert progress_callback.call_args_list == [
call(2, 2),
call(2, 4),
call(1, 5),
call(0, 5),
]
@pytest.mark.parametrize(
"failure",
[
requests.exceptions.Timeout(),
requests.exceptions.ConnectionError(),
(400, {}, ""),
(500, {}, ""),
],
)
def test_rewinds_on_failure(
self,
mock_responses: RequestsMock,
example_file: Path,
failure: MockResponseOrException,
):
example_file.write_text("1234567")
def response_callback(request: requests.models.PreparedRequest):
assert request.body.read(2) == b"12"
assert request.body.read(2) == b"34"
return failure
mock_responses.add_callback(
"PUT", "http://example.com/upload-dst", response_callback
)
progress_callback = Mock()
with pytest.raises((retry.TransientError, requests.RequestException)):
internal.InternalApi().upload_file(
"http://example.com/upload-dst",
example_file.open("rb"),
callback=progress_callback,
)
assert progress_callback.call_args_list == [
call(2, 2),
call(2, 4),
call(-4, 0),
]
@pytest.mark.parametrize(
"request_headers,response,expected_errtype",
[
(
{"x-amz-meta-md5": "1234"},
(400, {}, "blah blah RequestTimeout blah blah"),
retry.TransientError,
),
(
{"x-amz-meta-md5": "1234"},
(400, {}, "non-timeout-related error message"),
requests.RequestException,
),
(
{"x-amz-meta-md5": "1234"},
requests.exceptions.ConnectionError(),
retry.TransientError,
),
(
{},
(400, {}, "blah blah RequestTimeout blah blah"),
requests.RequestException,
),
],
)
def test_transient_failure_on_special_aws_request_timeout(
self,
mock_responses: RequestsMock,
example_file: Path,
request_headers: Mapping[str, str],
response,
expected_errtype: Type[Exception],
):
mock_responses.add_callback(
"PUT", "http://example.com/upload-dst", Mock(return_value=response)
)
with pytest.raises(expected_errtype):
internal.InternalApi().upload_file(
"http://example.com/upload-dst",
example_file.open("rb"),
extra_headers=request_headers,
)
# test_async_transient_failure_on_special_aws_request_timeout: see
# `test_async_retries_on_special_aws_request_timeout` on TestUploadRetry.
class TestAzure:
MAGIC_HEADERS = {"x-ms-blob-type": "SomeBlobType"}
@pytest.mark.parametrize(
"request_headers,uses_azure_lib",
[
({}, False),
(MAGIC_HEADERS, True),
],
)
def test_uses_azure_lib_if_available(
self,
mock_responses: RequestsMock,
example_file: Path,
request_headers: Mapping[str, str],
uses_azure_lib: bool,
):
api = internal.InternalApi()
if uses_azure_lib:
api._azure_blob_module = Mock()
else:
mock_responses.put("http://example.com/upload-dst")
api.upload_file(
"http://example.com/upload-dst",
example_file.open("rb"),
extra_headers=request_headers,
)
if uses_azure_lib:
api._azure_blob_module.BlobClient.from_blob_url().upload_blob.assert_called_once()
else:
assert len(mock_responses.calls) == 1
@pytest.mark.parametrize(
"response,expected_errtype,check_err",
[
(
(400, {}, "my-reason"),
requests.RequestException,
lambda e: e.response.status_code == 400 and "my-reason" in str(e),
),
(
(500, {}, "my-reason"),
retry.TransientError,
lambda e: (
e.exception.response.status_code == 500
and "my-reason" in str(e.exception)
),
),
(
requests.exceptions.ConnectionError("my-reason"),
retry.TransientError,
lambda e: "my-reason" in str(e.exception),
),
],
)
def test_translates_azure_err_to_normal_err(
self,
mock_responses: RequestsMock,
example_file: Path,
response: MockResponseOrException,
expected_errtype: Type[Exception],
check_err: Callable[[Exception], bool],
):
mock_responses.add_callback(
"PUT", "https://example.com/foo/bar/baz", Mock(return_value=response)
)
with pytest.raises(expected_errtype) as e:
internal.InternalApi().upload_file(
"https://example.com/foo/bar/baz",
example_file.open("rb"),
extra_headers=self.MAGIC_HEADERS,
)
assert check_err(e.value), e.value
| TestUploadFile |
python | vyperlang__vyper | vyper/ast/nodes.py | {
"start": 30368,
"end": 30434
} | class ____(Operator):
__slots__ = ()
_op = operator.not_
| Not |
python | huggingface__transformers | src/transformers/models/git/processing_git.py | {
"start": 698,
"end": 1394
} | class ____(ProcessorMixin):
r"""
Constructs a GIT processor which wraps a CLIP image processor and a BERT tokenizer into a single processor.
[`GitProcessor`] offers all the functionalities of [`CLIPImageProcessor`] and [`BertTokenizerFast`]. See the
[`~GitProcessor.__call__`] and [`~GitProcessor.decode`] for more information.
Args:
image_processor ([`AutoImageProcessor`]):
The image processor is a required input.
tokenizer ([`AutoTokenizer`]):
The tokenizer is a required input.
"""
def __init__(self, image_processor, tokenizer):
super().__init__(image_processor, tokenizer)
__all__ = ["GitProcessor"]
| GitProcessor |
python | apache__airflow | airflow-core/tests/unit/plugins/test_plugin.py | {
"start": 5674,
"end": 5732
} | class ____(AirflowPlugin):
name = "plugin-b"
| MockPluginB |
python | ansible__ansible | lib/ansible/plugins/doc_fragments/backup.py | {
"start": 191,
"end": 507
} | class ____(object):
# Standard documentation fragment
DOCUMENTATION = r"""
options:
backup:
description:
- Create a backup file including the timestamp information so you can get
the original file back if you somehow clobbered it incorrectly.
type: bool
default: no
"""
| ModuleDocFragment |
python | walkccc__LeetCode | solutions/576. Out of Boundary Paths/576.py | {
"start": 0,
"end": 552
} | class ____:
def findPaths(self, m, n, maxMove, startRow, startColumn):
MOD = 1000000007
@functools.lru_cache(None)
def dp(k: int, i: int, j: int) -> int:
"""
Returns the number of paths to move the ball at (i, j) out-of-bounds with
k moves.
"""
if i < 0 or i == m or j < 0 or j == n:
return 1
if k == 0:
return 0
return (dp(k - 1, i + 1, j) + dp(k - 1, i - 1, j) +
dp(k - 1, i, j + 1) + dp(k - 1, i, j - 1)) % MOD
return dp(maxMove, startRow, startColumn)
| Solution |
python | astropy__astropy | astropy/extern/ply/yacc.py | {
"start": 59253,
"end": 79204
} | class ____(object):
def __init__(self, terminals):
self.Productions = [None] # A list of all of the productions. The first
# entry is always reserved for the purpose of
# building an augmented grammar
self.Prodnames = {} # A dictionary mapping the names of nonterminals to a list of all
# productions of that nonterminal.
self.Prodmap = {} # A dictionary that is only used to detect duplicate
# productions.
self.Terminals = {} # A dictionary mapping the names of terminal symbols to a
# list of the rules where they are used.
for term in terminals:
self.Terminals[term] = []
self.Terminals['error'] = []
self.Nonterminals = {} # A dictionary mapping names of nonterminals to a list
# of rule numbers where they are used.
self.First = {} # A dictionary of precomputed FIRST(x) symbols
self.Follow = {} # A dictionary of precomputed FOLLOW(x) symbols
self.Precedence = {} # Precedence rules for each terminal. Contains tuples of the
# form ('right',level) or ('nonassoc', level) or ('left',level)
self.UsedPrecedence = set() # Precedence rules that were actually used by the grammer.
# This is only used to provide error checking and to generate
# a warning about unused precedence rules.
self.Start = None # Starting symbol for the grammar
def __len__(self):
return len(self.Productions)
def __getitem__(self, index):
return self.Productions[index]
# -----------------------------------------------------------------------------
# set_precedence()
#
# Sets the precedence for a given terminal. assoc is the associativity such as
# 'left','right', or 'nonassoc'. level is a numeric level.
#
# -----------------------------------------------------------------------------
def set_precedence(self, term, assoc, level):
assert self.Productions == [None], 'Must call set_precedence() before add_production()'
if term in self.Precedence:
raise GrammarError('Precedence already specified for terminal %r' % term)
if assoc not in ['left', 'right', 'nonassoc']:
raise GrammarError("Associativity must be one of 'left','right', or 'nonassoc'")
self.Precedence[term] = (assoc, level)
# -----------------------------------------------------------------------------
# add_production()
#
# Given an action function, this function assembles a production rule and
# computes its precedence level.
#
# The production rule is supplied as a list of symbols. For example,
# a rule such as 'expr : expr PLUS term' has a production name of 'expr' and
# symbols ['expr','PLUS','term'].
#
# Precedence is determined by the precedence of the right-most non-terminal
# or the precedence of a terminal specified by %prec.
#
# A variety of error checks are performed to make sure production symbols
# are valid and that %prec is used correctly.
# -----------------------------------------------------------------------------
def add_production(self, prodname, syms, func=None, file='', line=0):
if prodname in self.Terminals:
raise GrammarError('%s:%d: Illegal rule name %r. Already defined as a token' % (file, line, prodname))
if prodname == 'error':
raise GrammarError('%s:%d: Illegal rule name %r. error is a reserved word' % (file, line, prodname))
if not _is_identifier.match(prodname):
raise GrammarError('%s:%d: Illegal rule name %r' % (file, line, prodname))
# Look for literal tokens
for n, s in enumerate(syms):
if s[0] in "'\"":
try:
c = eval(s)
if (len(c) > 1):
raise GrammarError('%s:%d: Literal token %s in rule %r may only be a single character' %
(file, line, s, prodname))
if c not in self.Terminals:
self.Terminals[c] = []
syms[n] = c
continue
except SyntaxError:
pass
if not _is_identifier.match(s) and s != '%prec':
raise GrammarError('%s:%d: Illegal name %r in rule %r' % (file, line, s, prodname))
# Determine the precedence level
if '%prec' in syms:
if syms[-1] == '%prec':
raise GrammarError('%s:%d: Syntax error. Nothing follows %%prec' % (file, line))
if syms[-2] != '%prec':
raise GrammarError('%s:%d: Syntax error. %%prec can only appear at the end of a grammar rule' %
(file, line))
precname = syms[-1]
prodprec = self.Precedence.get(precname)
if not prodprec:
raise GrammarError('%s:%d: Nothing known about the precedence of %r' % (file, line, precname))
else:
self.UsedPrecedence.add(precname)
del syms[-2:] # Drop %prec from the rule
else:
# If no %prec, precedence is determined by the rightmost terminal symbol
precname = rightmost_terminal(syms, self.Terminals)
prodprec = self.Precedence.get(precname, ('right', 0))
# See if the rule is already in the rulemap
map = '%s -> %s' % (prodname, syms)
if map in self.Prodmap:
m = self.Prodmap[map]
raise GrammarError('%s:%d: Duplicate rule %s. ' % (file, line, m) +
'Previous definition at %s:%d' % (m.file, m.line))
# From this point on, everything is valid. Create a new Production instance
pnumber = len(self.Productions)
if prodname not in self.Nonterminals:
self.Nonterminals[prodname] = []
# Add the production number to Terminals and Nonterminals
for t in syms:
if t in self.Terminals:
self.Terminals[t].append(pnumber)
else:
if t not in self.Nonterminals:
self.Nonterminals[t] = []
self.Nonterminals[t].append(pnumber)
# Create a production and add it to the list of productions
p = Production(pnumber, prodname, syms, prodprec, func, file, line)
self.Productions.append(p)
self.Prodmap[map] = p
# Add to the global productions list
try:
self.Prodnames[prodname].append(p)
except KeyError:
self.Prodnames[prodname] = [p]
# -----------------------------------------------------------------------------
# set_start()
#
# Sets the starting symbol and creates the augmented grammar. Production
# rule 0 is S' -> start where start is the start symbol.
# -----------------------------------------------------------------------------
def set_start(self, start=None):
if not start:
start = self.Productions[1].name
if start not in self.Nonterminals:
raise GrammarError('start symbol %s undefined' % start)
self.Productions[0] = Production(0, "S'", [start])
self.Nonterminals[start].append(0)
self.Start = start
# -----------------------------------------------------------------------------
# find_unreachable()
#
# Find all of the nonterminal symbols that can't be reached from the starting
# symbol. Returns a list of nonterminals that can't be reached.
# -----------------------------------------------------------------------------
def find_unreachable(self):
# Mark all symbols that are reachable from a symbol s
def mark_reachable_from(s):
if s in reachable:
return
reachable.add(s)
for p in self.Prodnames.get(s, []):
for r in p.prod:
mark_reachable_from(r)
reachable = set()
mark_reachable_from(self.Productions[0].prod[0])
return [s for s in self.Nonterminals if s not in reachable]
# -----------------------------------------------------------------------------
# infinite_cycles()
#
# This function looks at the various parsing rules and tries to detect
# infinite recursion cycles (grammar rules where there is no possible way
# to derive a string of only terminals).
# -----------------------------------------------------------------------------
def infinite_cycles(self):
terminates = {}
# Terminals:
for t in self.Terminals:
terminates[t] = True
terminates['$end'] = True
# Nonterminals:
# Initialize to false:
for n in self.Nonterminals:
terminates[n] = False
# Then propagate termination until no change:
while True:
some_change = False
for (n, pl) in self.Prodnames.items():
# Nonterminal n terminates iff any of its productions terminates.
for p in pl:
# Production p terminates iff all of its rhs symbols terminate.
for s in p.prod:
if not terminates[s]:
# The symbol s does not terminate,
# so production p does not terminate.
p_terminates = False
break
else:
# didn't break from the loop,
# so every symbol s terminates
# so production p terminates.
p_terminates = True
if p_terminates:
# symbol n terminates!
if not terminates[n]:
terminates[n] = True
some_change = True
# Don't need to consider any more productions for this n.
break
if not some_change:
break
infinite = []
for (s, term) in terminates.items():
if not term:
if s not in self.Prodnames and s not in self.Terminals and s != 'error':
# s is used-but-not-defined, and we've already warned of that,
# so it would be overkill to say that it's also non-terminating.
pass
else:
infinite.append(s)
return infinite
# -----------------------------------------------------------------------------
# undefined_symbols()
#
# Find all symbols that were used the grammar, but not defined as tokens or
# grammar rules. Returns a list of tuples (sym, prod) where sym in the symbol
# and prod is the production where the symbol was used.
# -----------------------------------------------------------------------------
def undefined_symbols(self):
result = []
for p in self.Productions:
if not p:
continue
for s in p.prod:
if s not in self.Prodnames and s not in self.Terminals and s != 'error':
result.append((s, p))
return result
# -----------------------------------------------------------------------------
# unused_terminals()
#
# Find all terminals that were defined, but not used by the grammar. Returns
# a list of all symbols.
# -----------------------------------------------------------------------------
def unused_terminals(self):
unused_tok = []
for s, v in self.Terminals.items():
if s != 'error' and not v:
unused_tok.append(s)
return unused_tok
# ------------------------------------------------------------------------------
# unused_rules()
#
# Find all grammar rules that were defined, but not used (maybe not reachable)
# Returns a list of productions.
# ------------------------------------------------------------------------------
def unused_rules(self):
unused_prod = []
for s, v in self.Nonterminals.items():
if not v:
p = self.Prodnames[s][0]
unused_prod.append(p)
return unused_prod
# -----------------------------------------------------------------------------
# unused_precedence()
#
# Returns a list of tuples (term,precedence) corresponding to precedence
# rules that were never used by the grammar. term is the name of the terminal
# on which precedence was applied and precedence is a string such as 'left' or
# 'right' corresponding to the type of precedence.
# -----------------------------------------------------------------------------
def unused_precedence(self):
unused = []
for termname in self.Precedence:
if not (termname in self.Terminals or termname in self.UsedPrecedence):
unused.append((termname, self.Precedence[termname][0]))
return unused
# -------------------------------------------------------------------------
# _first()
#
# Compute the value of FIRST1(beta) where beta is a tuple of symbols.
#
# During execution of compute_first1, the result may be incomplete.
# Afterward (e.g., when called from compute_follow()), it will be complete.
# -------------------------------------------------------------------------
def _first(self, beta):
# We are computing First(x1,x2,x3,...,xn)
result = []
for x in beta:
x_produces_empty = False
# Add all the non-<empty> symbols of First[x] to the result.
for f in self.First[x]:
if f == '<empty>':
x_produces_empty = True
else:
if f not in result:
result.append(f)
if x_produces_empty:
# We have to consider the next x in beta,
# i.e. stay in the loop.
pass
else:
# We don't have to consider any further symbols in beta.
break
else:
# There was no 'break' from the loop,
# so x_produces_empty was true for all x in beta,
# so beta produces empty as well.
result.append('<empty>')
return result
# -------------------------------------------------------------------------
# compute_first()
#
# Compute the value of FIRST1(X) for all symbols
# -------------------------------------------------------------------------
def compute_first(self):
if self.First:
return self.First
# Terminals:
for t in self.Terminals:
self.First[t] = [t]
self.First['$end'] = ['$end']
# Nonterminals:
# Initialize to the empty set:
for n in self.Nonterminals:
self.First[n] = []
# Then propagate symbols until no change:
while True:
some_change = False
for n in self.Nonterminals:
for p in self.Prodnames[n]:
for f in self._first(p.prod):
if f not in self.First[n]:
self.First[n].append(f)
some_change = True
if not some_change:
break
return self.First
# ---------------------------------------------------------------------
# compute_follow()
#
# Computes all of the follow sets for every non-terminal symbol. The
# follow set is the set of all symbols that might follow a given
# non-terminal. See the Dragon book, 2nd Ed. p. 189.
# ---------------------------------------------------------------------
def compute_follow(self, start=None):
# If already computed, return the result
if self.Follow:
return self.Follow
# If first sets not computed yet, do that first.
if not self.First:
self.compute_first()
# Add '$end' to the follow list of the start symbol
for k in self.Nonterminals:
self.Follow[k] = []
if not start:
start = self.Productions[1].name
self.Follow[start] = ['$end']
while True:
didadd = False
for p in self.Productions[1:]:
# Here is the production set
for i, B in enumerate(p.prod):
if B in self.Nonterminals:
# Okay. We got a non-terminal in a production
fst = self._first(p.prod[i+1:])
hasempty = False
for f in fst:
if f != '<empty>' and f not in self.Follow[B]:
self.Follow[B].append(f)
didadd = True
if f == '<empty>':
hasempty = True
if hasempty or i == (len(p.prod)-1):
# Add elements of follow(a) to follow(b)
for f in self.Follow[p.name]:
if f not in self.Follow[B]:
self.Follow[B].append(f)
didadd = True
if not didadd:
break
return self.Follow
# -----------------------------------------------------------------------------
# build_lritems()
#
# This function walks the list of productions and builds a complete set of the
# LR items. The LR items are stored in two ways: First, they are uniquely
# numbered and placed in the list _lritems. Second, a linked list of LR items
# is built for each production. For example:
#
# E -> E PLUS E
#
# Creates the list
#
# [E -> . E PLUS E, E -> E . PLUS E, E -> E PLUS . E, E -> E PLUS E . ]
# -----------------------------------------------------------------------------
def build_lritems(self):
for p in self.Productions:
lastlri = p
i = 0
lr_items = []
while True:
if i > len(p):
lri = None
else:
lri = LRItem(p, i)
# Precompute the list of productions immediately following
try:
lri.lr_after = self.Prodnames[lri.prod[i+1]]
except (IndexError, KeyError):
lri.lr_after = []
try:
lri.lr_before = lri.prod[i-1]
except IndexError:
lri.lr_before = None
lastlri.lr_next = lri
if not lri:
break
lr_items.append(lri)
lastlri = lri
i += 1
p.lr_items = lr_items
# -----------------------------------------------------------------------------
# == Class LRTable ==
#
# This basic class represents a basic table of LR parsing information.
# Methods for generating the tables are not defined here. They are defined
# in the derived class LRGeneratedTable.
# -----------------------------------------------------------------------------
| Grammar |
python | jazzband__django-oauth-toolkit | oauth2_provider/backends.py | {
"start": 218,
"end": 974
} | class ____:
"""
Authenticate against an OAuth2 access token
"""
def authenticate(self, request=None, **credentials):
if request is not None:
try:
valid, request = OAuthLibCore.verify_request(request, scopes=[])
except ValueError as error:
if str(error) == "Invalid hex encoding in query string.":
raise SuspiciousOperation(error)
else:
raise
else:
if valid:
return request.user
return None
def get_user(self, user_id):
try:
return UserModel.objects.get(pk=user_id)
except UserModel.DoesNotExist:
return None
| OAuth2Backend |
python | falconry__falcon | tests/test_response_body.py | {
"start": 2391,
"end": 3463
} | class ____:
def on_get(self, req, resp):
resp.content_type = 'text/x-malbolge'
resp.media = "'&%$#\"!76543210/43,P0).'&%I6"
resp.status = falcon.HTTP_725
def test_unsupported_response_content_type(asgi, util):
app = util.create_app(asgi)
app.add_route('/test.mal', CodeResource())
resp = testing.simulate_get(app, '/test.mal')
assert resp.status_code == 415
def test_response_body_rendition_error(asgi, util):
class MalbolgeHandler(falcon.media.BaseHandler):
def serialize(self, media, content_type):
raise falcon.HTTPError(falcon.HTTP_753)
app = util.create_app(asgi)
app.resp_options.media_handlers['text/x-malbolge'] = MalbolgeHandler()
app.add_route('/test.mal', CodeResource())
resp = testing.simulate_get(app, '/test.mal')
assert resp.status_code == 753
# NOTE(kgriffs): Validate that del works on media handlers.
del app.resp_options.media_handlers['text/x-malbolge']
resp = testing.simulate_get(app, '/test.mal')
assert resp.status_code == 415
| CodeResource |
python | huggingface__transformers | src/transformers/convert_slow_tokenizer.py | {
"start": 60899,
"end": 68433
} | class ____:
def __init__(
self,
vocab_file=None,
pattern=r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+""",
add_prefix_space=False,
additional_special_tokens=None,
**kwargs,
):
self.vocab_file = vocab_file
self.pattern = pattern
self.add_prefix_space = add_prefix_space
self.additional_special_tokens = (
additional_special_tokens.keys()
if isinstance(additional_special_tokens, dict)
else additional_special_tokens
)
def extract_vocab_merges_from_model(self, tiktoken_url: str):
import base64
import json
with open(self.vocab_file, "r", encoding="utf-8") as f:
untyped = json.load(f)
self.pattern = untyped["config"]["pattern"]
self.additional_special_tokens = [
AddedToken(k["token_str"], special=k["is_control"]) for k in untyped["special_tokens"]
]
bpe_ranks = untyped["vocab"]
byte_encoder = bytes_to_unicode()
@lru_cache
def token_bytes_to_string(b):
return "".join([byte_encoder[ord(char)] for char in b.decode("latin-1")])
merges = []
vocab = {}
for idx, token in enumerate(self.additional_special_tokens):
vocab[token.content] = idx
bpe_ranks = [base64.b64decode(k["token_bytes"]) for k in bpe_ranks]
rank_set = set(bpe_ranks)
for rank, token in enumerate(tqdm(bpe_ranks, desc="Converting tekken.json to tokenizer.json")):
vocab[token_bytes_to_string(token)] = rank
if len(token) == 1:
continue
local = []
for index in range(1, len(token)):
piece_l, piece_r = token[:index], token[index:]
if piece_l in rank_set and piece_r in rank_set and (piece_l + piece_r) in rank_set:
local.append((piece_l, piece_r, rank))
local = sorted(local, key=lambda x: (bpe_ranks.index(x[0]), bpe_ranks.index(x[1])), reverse=False)
merges.extend(local)
merges = sorted(merges, key=lambda val: val[2], reverse=False)
merges = [(token_bytes_to_string(val[0]), token_bytes_to_string(val[1])) for val in merges]
return vocab, merges
def tokenizer(self):
vocab_scores, merges = self.extract_vocab_merges_from_model(self.vocab_file)
tokenizer = Tokenizer(BPE(vocab_scores, merges, fuse_unk=False))
if hasattr(tokenizer.model, "ignore_merges"):
tokenizer.model.ignore_merges = True
return tokenizer
def converted(self) -> Tokenizer:
tokenizer = self.tokenizer()
tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
[
pre_tokenizers.Split(Regex(self.pattern), behavior="isolated", invert=False),
pre_tokenizers.ByteLevel(add_prefix_space=self.add_prefix_space, use_regex=False),
]
)
tokenizer.decoder = decoders.ByteLevel()
tokenizer.add_tokens(self.additional_special_tokens)
tokenizer.post_processor = processors.ByteLevel(trim_offsets=False)
return tokenizer
SLOW_TO_FAST_CONVERTERS = {
"AlbertTokenizer": AlbertConverter,
"BartTokenizer": RobertaConverter,
"BarthezTokenizer": BarthezConverter,
"BertTokenizer": BertConverter,
"BigBirdTokenizer": BigBirdConverter,
"BlenderbotTokenizer": BlenderbotConverter,
"CamembertTokenizer": CamembertConverter,
"CLIPTokenizer": CLIPConverter,
"CodeGenTokenizer": GPT2Converter,
"ConvBertTokenizer": BertConverter,
"DebertaTokenizer": DebertaConverter,
"DebertaV2Tokenizer": DebertaV2Converter,
"DistilBertTokenizer": BertConverter,
"DPRReaderTokenizer": BertConverter,
"DPRQuestionEncoderTokenizer": BertConverter,
"DPRContextEncoderTokenizer": BertConverter,
"ElectraTokenizer": BertConverter,
"FNetTokenizer": AlbertConverter,
"FunnelTokenizer": FunnelConverter,
"GPT2Tokenizer": GPT2Converter,
"HerbertTokenizer": HerbertConverter,
"LayoutLMTokenizer": BertConverter,
"LayoutLMv2Tokenizer": BertConverter,
"LayoutLMv3Tokenizer": RobertaConverter,
"LayoutXLMTokenizer": XLMRobertaConverter,
"LongformerTokenizer": RobertaConverter,
"LEDTokenizer": RobertaConverter,
"LxmertTokenizer": BertConverter,
"MarkupLMTokenizer": MarkupLMConverter,
"MBartTokenizer": MBartConverter,
"MBart50Tokenizer": MBart50Converter,
"MPNetTokenizer": MPNetConverter,
"MobileBertTokenizer": BertConverter,
"MvpTokenizer": RobertaConverter,
"NllbTokenizer": NllbConverter,
"OpenAIGPTTokenizer": OpenAIGPTConverter,
"PegasusTokenizer": PegasusConverter,
"Qwen2Tokenizer": Qwen2Converter,
"ReformerTokenizer": ReformerConverter,
"RemBertTokenizer": RemBertConverter,
"RobertaTokenizer": RobertaConverter,
"RoFormerTokenizer": RoFormerConverter,
"SeamlessM4TTokenizer": SeamlessM4TConverter,
"SqueezeBertTokenizer": BertConverter,
"T5Tokenizer": T5Converter,
"UdopTokenizer": UdopConverter,
"WhisperTokenizer": WhisperConverter,
"XLMRobertaTokenizer": XLMRobertaConverter,
"XLNetTokenizer": XLNetConverter,
"SplinterTokenizer": SplinterConverter,
"XGLMTokenizer": XGLMConverter,
"LlamaTokenizer": LlamaConverter,
"CodeLlamaTokenizer": LlamaConverter,
"GemmaTokenizer": GemmaConverter,
"Phi3Tokenizer": LlamaConverter,
}
def convert_slow_tokenizer(transformer_tokenizer, from_tiktoken=False) -> Tokenizer:
"""
Utilities to convert a slow tokenizer instance in a fast tokenizer instance.
Args:
transformer_tokenizer ([`~tokenization_utils_base.PreTrainedTokenizer`]):
Instance of a slow tokenizer to convert in the backend tokenizer for
[`~tokenization_utils_base.PreTrainedTokenizerFast`].
from_tiktoken (bool, optional): Whether to use the `tiktoken` library to convert the tokenizer instead of sentencepiece.
Defaults to False.
Return:
A instance of [`~tokenizers.Tokenizer`] to be used as the backend tokenizer of a
[`~tokenization_utils_base.PreTrainedTokenizerFast`]
"""
tokenizer_class_name = transformer_tokenizer.__class__.__name__
if tokenizer_class_name in SLOW_TO_FAST_CONVERTERS and not from_tiktoken:
converter_class = SLOW_TO_FAST_CONVERTERS[tokenizer_class_name]
return converter_class(transformer_tokenizer).converted()
elif transformer_tokenizer.vocab_file.endswith("tekken.json"):
transformer_tokenizer.original_tokenizer = transformer_tokenizer
logger.info("Converting from Mistral tekken.json")
return MistralConverter(transformer_tokenizer.vocab_file).converted()
else:
try:
logger.info("Converting from Tiktoken")
return TikTokenConverter(
vocab_file=transformer_tokenizer.vocab_file,
extra_special_tokens=transformer_tokenizer.extra_special_tokens,
).converted()
except Exception:
raise ValueError(
f"Converting from SentencePiece and Tiktoken failed, if a converter for SentencePiece is available, provide a model path "
f"with a SentencePiece tokenizer.model file."
f"Currently available slow->fast converters: {list(SLOW_TO_FAST_CONVERTERS.keys())}"
)
| MistralConverter |
python | sanic-org__sanic | sanic/config.py | {
"start": 2418,
"end": 13501
} | class ____(dict, metaclass=DescriptorMeta):
"""Configuration object for Sanic.
You can use this object to both: (1) configure how Sanic will operate, and
(2) manage your application's custom configuration values.
"""
ACCESS_LOG: bool
AUTO_EXTEND: bool
AUTO_RELOAD: bool
EVENT_AUTOREGISTER: bool
DEPRECATION_FILTER: FilterWarningType
FORWARDED_FOR_HEADER: str
FORWARDED_SECRET: Optional[str]
GRACEFUL_SHUTDOWN_TIMEOUT: float
GRACEFUL_TCP_CLOSE_TIMEOUT: float
INSPECTOR: bool
INSPECTOR_HOST: str
INSPECTOR_PORT: int
INSPECTOR_TLS_KEY: Union[Path, str, Default]
INSPECTOR_TLS_CERT: Union[Path, str, Default]
INSPECTOR_API_KEY: str
KEEP_ALIVE_TIMEOUT: int
KEEP_ALIVE: bool
LOCAL_CERT_CREATOR: Union[str, LocalCertCreator]
LOCAL_TLS_KEY: Union[Path, str, Default]
LOCAL_TLS_CERT: Union[Path, str, Default]
LOCALHOST: str
LOG_EXTRA: Union[Default, bool]
MOTD: bool
MOTD_DISPLAY: dict[str, str]
NO_COLOR: bool
NOISY_EXCEPTIONS: bool
PROXIES_COUNT: Optional[int]
REAL_IP_HEADER: Optional[str]
REQUEST_BUFFER_SIZE: int
REQUEST_MAX_HEADER_SIZE: int
REQUEST_ID_HEADER: str
REQUEST_MAX_SIZE: int
REQUEST_TIMEOUT: int
RESPONSE_TIMEOUT: int
SERVER_NAME: str
TLS_CERT_PASSWORD: str
TOUCHUP: Union[Default, bool]
USE_UVLOOP: Union[Default, bool]
WEBSOCKET_MAX_SIZE: int
WEBSOCKET_PING_INTERVAL: int
WEBSOCKET_PING_TIMEOUT: int
def __init__(
self,
defaults: Optional[
dict[str, Union[str, bool, int, float, None]]
] = None,
env_prefix: Optional[str] = SANIC_PREFIX,
keep_alive: Optional[bool] = None,
*,
converters: Optional[Sequence[Callable[[str], Any]]] = None,
):
defaults = defaults or {}
super().__init__({**DEFAULT_CONFIG, **defaults})
self._configure_warnings()
self._converters = [str, str_to_bool, float, int]
if converters:
for converter in converters:
self.register_type(converter)
if keep_alive is not None:
self.KEEP_ALIVE = keep_alive
if env_prefix != SANIC_PREFIX:
if env_prefix:
self.load_environment_vars(env_prefix)
else:
self.load_environment_vars(SANIC_PREFIX)
self._configure_header_size()
self._check_error_format()
self._init = True
def __getattr__(self, attr: Any):
try:
return self[attr]
except KeyError as ke:
raise AttributeError(f"Config has no '{ke.args[0]}'")
def __setattr__(self, attr: str, value: Any) -> None:
self.update({attr: value})
def __setitem__(self, attr: str, value: Any) -> None:
self.update({attr: value})
def update(self, *other: Any, **kwargs: Any) -> None:
"""Update the config with new values.
This method will update the config with the values from the provided
`other` objects, and then update the config with the provided
`kwargs`. The `other` objects can be any object that can be converted
to a dictionary, such as a `dict`, `Config` object, or `str` path to a
Python file. The `kwargs` must be a dictionary of key-value pairs.
.. note::
Only upper case settings are considered
Args:
*other: Any number of objects that can be converted to a
dictionary.
**kwargs: Any number of key-value pairs.
Raises:
AttributeError: If a key is not in the config.
Examples:
```python
config.update(
{"A": 1, "B": 2},
{"C": 3, "D": 4},
E=5,
F=6,
)
```
"""
kwargs.update({k: v for item in other for k, v in dict(item).items()})
setters: dict[str, Any] = {
k: kwargs.pop(k)
for k in {**kwargs}.keys()
if k in self.__class__.__setters__
}
for key, value in setters.items():
try:
super().__setattr__(key, value)
except AttributeError:
...
super().update(**kwargs)
for attr, value in {**setters, **kwargs}.items():
self._post_set(attr, value)
def _post_set(self, attr, value) -> None:
if self.get("_init"):
if attr in (
"REQUEST_MAX_HEADER_SIZE",
"REQUEST_BUFFER_SIZE",
"REQUEST_MAX_SIZE",
):
self._configure_header_size()
if attr == "LOCAL_CERT_CREATOR" and not isinstance(
self.LOCAL_CERT_CREATOR, LocalCertCreator
):
self.LOCAL_CERT_CREATOR = LocalCertCreator[
self.LOCAL_CERT_CREATOR.upper()
]
elif attr == "DEPRECATION_FILTER":
self._configure_warnings()
@property
def FALLBACK_ERROR_FORMAT(self) -> str:
if isinstance(self._FALLBACK_ERROR_FORMAT, Default):
return DEFAULT_FORMAT
return self._FALLBACK_ERROR_FORMAT
@FALLBACK_ERROR_FORMAT.setter
def FALLBACK_ERROR_FORMAT(self, value):
self._check_error_format(value)
if (
not isinstance(self._FALLBACK_ERROR_FORMAT, Default)
and value != self._FALLBACK_ERROR_FORMAT
):
error_logger.warning(
"Setting config.FALLBACK_ERROR_FORMAT on an already "
"configured value may have unintended consequences."
)
self._FALLBACK_ERROR_FORMAT = value
def _configure_header_size(self):
Http.set_header_max_size(
self.REQUEST_MAX_HEADER_SIZE,
self.REQUEST_BUFFER_SIZE - 4096,
self.REQUEST_MAX_SIZE,
)
def _configure_warnings(self):
filterwarnings(
self.DEPRECATION_FILTER,
category=DeprecationWarning,
module=r"sanic.*",
)
def _check_error_format(self, format: Optional[str] = None):
check_error_format(format or self.FALLBACK_ERROR_FORMAT)
def load_environment_vars(self, prefix=SANIC_PREFIX):
"""Load environment variables into the config.
Looks for prefixed environment variables and applies them to the
configuration if present. This is called automatically when Sanic
starts up to load environment variables into config. Environment
variables should start with the defined prefix and should only
contain uppercase letters.
It will automatically hydrate the following types:
- ``int``
- ``float``
- ``bool``
Anything else will be imported as a ``str``. If you would like to add
additional types to this list, you can use
:meth:`sanic.config.Config.register_type`. Just make sure that they
are registered before you instantiate your application.
You likely won't need to call this method directly.
See [Configuration](/en/guide/deployment/configuration) for more details.
Args:
prefix (str): The prefix to use when looking for environment
variables. Defaults to `SANIC_`.
Examples:
```python
# Environment variables
# SANIC_SERVER_NAME=example.com
# SANIC_SERVER_PORT=9999
# SANIC_SERVER_AUTORELOAD=true
# Python
app.config.load_environment_vars()
```
""" # noqa: E501
for key, value in environ.items():
if not key.startswith(prefix) or not key.isupper():
continue
_, config_key = key.split(prefix, 1)
for converter in reversed(self._converters):
try:
self[config_key] = converter(value)
break
except ValueError:
pass
def update_config(self, config: Union[bytes, str, dict[str, Any], Any]):
"""Update app.config.
.. note::
Only upper case settings are considered
See [Configuration](/en/guide/deployment/configuration) for more details.
Args:
config (Union[bytes, str, dict, Any]): Path to py file holding
settings, dict holding settings, or any object holding
settings.
Examples:
You can upload app config by providing path to py file
holding settings.
```python
# /some/py/file
A = 1
B = 2
```
```python
config.update_config("${some}/py/file")
```
Yes you can put environment variable here, but they must be provided
in format: ``${some_env_var}``, and mark that ``$some_env_var`` is
treated as plain string.
You can upload app config by providing dict holding settings.
```python
d = {"A": 1, "B": 2}
config.update_config(d)
```
You can upload app config by providing any object holding settings,
but in such case config.__dict__ will be used as dict holding settings.
```python
class C:
A = 1
B = 2
config.update_config(C)
```
""" # noqa: E501
if isinstance(config, (bytes, str, Path)):
config = load_module_from_file_location(location=config)
if not isinstance(config, dict):
cfg = {}
if not isclass(config):
cfg.update(
{
key: getattr(config, key)
for key in config.__class__.__dict__.keys()
}
)
config = dict(config.__dict__)
config.update(cfg)
config = dict(filter(lambda i: i[0].isupper(), config.items()))
self.update(config)
load = update_config
def register_type(self, converter: Callable[[str], Any]) -> None:
"""Register a custom type converter.
Allows for adding custom function to cast from a string value to any
other type. The function should raise ValueError if it is not the
correct type.
Args:
converter (Callable[[str], Any]): A function that takes a string
and returns a value of any type.
Examples:
```python
def my_converter(value: str) -> Any:
# Do something to convert the value
return value
config.register_type(my_converter)
```
"""
if converter in self._converters:
error_logger.warning(
f"Configuration value converter '{converter.__name__}' has "
"already been registered"
)
return
self._converters.append(converter)
| Config |
python | google__python-fire | examples/widget/widget_test.py | {
"start": 677,
"end": 1081
} | class ____(testutils.BaseTestCase):
def testWidgetWhack(self):
toy = widget.Widget()
self.assertEqual(toy.whack(), 'whack!')
self.assertEqual(toy.whack(3), 'whack! whack! whack!')
def testWidgetBang(self):
toy = widget.Widget()
self.assertEqual(toy.bang(), 'bang bang!')
self.assertEqual(toy.bang('boom'), 'boom bang!')
if __name__ == '__main__':
testutils.main()
| WidgetTest |
python | apache__airflow | shared/logging/src/airflow_shared/logging/structlog.py | {
"start": 5941,
"end": 6297
} | class ____(structlog.WriteLogger):
__slots__ = ("name",)
def __init__(self, name: str | None = None, file: TextIO | None = None):
self.name = name
if file is not None:
file = make_file_io_non_caching(file)
super().__init__(file)
LogOutputType = TypeVar("LogOutputType", bound=TextIO | BinaryIO)
| NamedWriteLogger |
python | tensorflow__tensorflow | tensorflow/python/training/saver_test.py | {
"start": 117398,
"end": 130990
} | class ____(test.TestCase):
def _get_test_dir(self, dirname):
test_dir = os.path.join(self.get_temp_dir(), dirname)
gfile.MakeDirs(test_dir)
return test_dir
def _testScopedSave(self, test_dir, exported_filename, ckpt_filename):
graph = ops_lib.Graph()
with graph.as_default():
# Creates an inference graph.
# Hidden 1
images = constant_op.constant(
1.2, dtypes.float32, shape=[100, 28], name="images")
with ops_lib.name_scope("hidden1"):
weights1 = variable_v1.VariableV1(
random_ops.truncated_normal([28, 128],
stddev=1.0 / math.sqrt(float(28))),
name="weights")
# The use of cond.cond here is purely for adding test
# coverage the save and restore of control flow context (which doesn't
# make any sense here from a machine learning perspective). The typical
# biases is a simple Variable without the conditions.
biases1 = variable_v1.VariableV1(
cond.cond(
math_ops.less(random.random(), 0.5),
lambda: array_ops.ones([128]), lambda: array_ops.zeros([128])),
name="biases")
hidden1 = nn_ops.relu(math_ops.matmul(images, weights1) + biases1)
# Hidden 2
with ops_lib.name_scope("hidden2"):
weights2 = variable_v1.VariableV1(
random_ops.truncated_normal([128, 32],
stddev=1.0 / math.sqrt(float(128))),
name="weights")
# The use of while_loop.while_loop here is purely for adding test
# coverage the save and restore of control flow context (which doesn't
# make any sense here from a machine learning perspective). The typical
# biases is a simple Variable without the conditions.
def loop_cond(it, _):
return it < 2
def loop_body(it, biases2):
biases2 += constant_op.constant(0.1, shape=[32])
return it + 1, biases2
_, biases2 = while_loop.while_loop(loop_cond, loop_body, [
constant_op.constant(0),
variable_v1.VariableV1(array_ops.zeros([32]))
])
hidden2 = nn_ops.relu(math_ops.matmul(hidden1, weights2) + biases2)
# Linear
with ops_lib.name_scope("softmax_linear"):
weights3 = variable_v1.VariableV1(
random_ops.truncated_normal([32, 10],
stddev=1.0 / math.sqrt(float(32))),
name="weights")
biases3 = variable_v1.VariableV1(array_ops.zeros([10]), name="biases")
logits = math_ops.matmul(hidden2, weights3) + biases3
ops_lib.add_to_collection("logits", logits)
# Adds user_defined proto in three formats: string, bytes and Any.
# Any proto should just pass through.
queue_runner = queue_runner_pb2.QueueRunnerDef(queue_name="test_queue")
ops_lib.add_to_collection("user_defined_string_collection",
str(queue_runner))
ops_lib.add_to_collection("user_defined_bytes_collection",
queue_runner.SerializeToString())
any_buf = Any()
any_buf.Pack(queue_runner)
ops_lib.add_to_collection("user_defined_any_collection", any_buf)
_, var_list = meta_graph.export_scoped_meta_graph(
filename=os.path.join(test_dir, exported_filename),
graph=ops_lib.get_default_graph(),
export_scope="hidden1")
self.assertEqual(["biases:0", "weights:0"], sorted(var_list.keys()))
with graph.as_default(), self.session() as sess:
self.evaluate(variables.global_variables_initializer())
saver = saver_module.Saver(var_list=var_list, max_to_keep=1)
saver.save(sess, os.path.join(test_dir, ckpt_filename), write_state=False)
def _testScopedRestore(self, test_dir, exported_filename,
new_exported_filename, ckpt_filename):
graph = ops_lib.Graph()
# Create all the missing inputs.
with graph.as_default():
new_image = constant_op.constant(
1.2, dtypes.float32, shape=[100, 28], name="images")
var_list = meta_graph.import_scoped_meta_graph(
os.path.join(test_dir, exported_filename),
graph=graph,
input_map={"$unbound_inputs_images": new_image},
import_scope="new_hidden1")
self.assertEqual(["biases:0", "weights:0"], sorted(var_list.keys()))
hidden1 = graph.as_graph_element("new_hidden1/Relu:0")
weights1 = graph.as_graph_element("new_hidden1/weights:0")
biases1 = graph.as_graph_element("new_hidden1/biases:0")
with graph.as_default():
# Hidden 2
with ops_lib.name_scope("hidden2"):
weights = variable_v1.VariableV1(
random_ops.truncated_normal([128, 32],
stddev=1.0 / math.sqrt(float(128))),
name="weights")
# The use of while_loop.while_loop here is purely for adding test
# coverage the save and restore of control flow context (which doesn't
# make any sense here from a machine learning perspective). The typical
# biases is a simple Variable without the conditions.
def loop_cond(it, _):
return it < 2
def loop_body(it, biases):
biases += constant_op.constant(0.1, shape=[32])
return it + 1, biases
_, biases = while_loop.while_loop(loop_cond, loop_body, [
constant_op.constant(0),
variable_v1.VariableV1(array_ops.zeros([32]))
])
hidden2 = nn_ops.relu(math_ops.matmul(hidden1, weights) + biases)
# Linear
with ops_lib.name_scope("softmax_linear"):
weights = variable_v1.VariableV1(
random_ops.truncated_normal([32, 10],
stddev=1.0 / math.sqrt(float(32))),
name="weights")
biases = variable_v1.VariableV1(array_ops.zeros([10]), name="biases")
logits = math_ops.matmul(hidden2, weights) + biases
ops_lib.add_to_collection("logits", logits)
# The rest of the variables.
rest_variables = list(
set(variables.global_variables()) - set(var_list.keys()))
init_rest_op = variables.variables_initializer(rest_variables)
with graph.as_default(), self.session() as sess:
saver = saver_module.Saver(var_list=var_list, max_to_keep=1)
saver.restore(sess, os.path.join(test_dir, ckpt_filename))
# Verify that we have restored weights1 and biases1.
self.evaluate([weights1, biases1])
# Initialize the rest of the variables and run logits.
self.evaluate(init_rest_op)
self.evaluate(logits)
# Verifies that we can save the subgraph under "hidden1" and restore it
# into "new_hidden1" in the new graph.
def testScopedSaveAndRestore(self):
test_dir = self._get_test_dir("scoped_export_import")
ckpt_filename = "ckpt"
self._testScopedSave(test_dir, "exported_hidden1.pbtxt", ckpt_filename)
self._testScopedRestore(test_dir, "exported_hidden1.pbtxt",
"exported_new_hidden1.pbtxt", ckpt_filename)
# Verifies that we can copy the subgraph under "hidden1" and copy it
# to different name scope in the same graph or different graph.
def testCopyScopedGraph(self):
test_dir = self._get_test_dir("scoped_copy")
saver0_ckpt = os.path.join(test_dir, "saver0.ckpt")
graph1 = ops_lib.Graph()
with graph1.as_default():
with ops_lib.name_scope("hidden1"):
images = constant_op.constant(
1.0, dtypes.float32, shape=[3, 2], name="images")
weights1 = variable_v1.VariableV1([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]],
name="weights")
biases1 = variable_v1.VariableV1([0.1] * 3, name="biases")
nn_ops.relu(math_ops.matmul(images, weights1) + biases1, name="relu")
# Run the graph and save scoped checkpoint.
with graph1.as_default(), self.session(graph=graph1) as sess:
self.evaluate(variables.global_variables_initializer())
_, var_list_1 = meta_graph.export_scoped_meta_graph(
export_scope="hidden1")
saver = saver_module.Saver(var_list=var_list_1, max_to_keep=1)
saver.save(sess, saver0_ckpt, write_state=False)
expected = np.reshape([[5.0999999, 7.0999999, 9.10000038] * 3], (3, 3))
# Verifies copy to the same graph with the same name fails.
with graph1.as_default():
with self.assertRaisesWithPredicateMatch(
ValueError, lambda e: "need to be different" in str(e)):
meta_graph.copy_scoped_meta_graph(
from_scope="hidden1", to_scope="hidden1")
# Verifies copy to the same graph.
with graph1.as_default():
var_list_2 = meta_graph.copy_scoped_meta_graph(
from_scope="hidden1", to_scope="hidden2")
with graph1.as_default(), self.session(graph=graph1) as sess:
saver1 = saver_module.Saver(var_list=var_list_1, max_to_keep=1)
saver1.restore(sess, saver0_ckpt)
saver2 = saver_module.Saver(var_list=var_list_2, max_to_keep=1)
saver2.restore(sess, saver0_ckpt)
self.assertAllClose(expected, sess.run("hidden1/relu:0"))
self.assertAllClose(expected, sess.run("hidden2/relu:0"))
# Verifies copy to different graph.
graph2 = ops_lib.Graph()
with graph2.as_default():
new_var_list_1 = meta_graph.copy_scoped_meta_graph(
from_scope="hidden1",
to_scope="new_hidden1",
from_graph=graph1,
to_graph=graph2)
with self.session() as sess:
saver3 = saver_module.Saver(var_list=new_var_list_1, max_to_keep=1)
saver3.restore(sess, saver0_ckpt)
self.assertAllClose(expected, sess.run("new_hidden1/relu:0"))
def testExportGraphDefWithScope(self):
test_dir = self._get_test_dir("export_graph_def")
saver0_ckpt = os.path.join(test_dir, "saver0.ckpt")
graph1 = ops_lib.Graph()
with graph1.as_default():
with ops_lib.name_scope("hidden1"):
images = constant_op.constant(
1.0, dtypes.float32, shape=[3, 2], name="images")
weights1 = variable_v1.VariableV1([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]],
name="weights")
biases1 = variable_v1.VariableV1([0.1] * 3, name="biases")
nn_ops.relu(math_ops.matmul(images, weights1) + biases1, name="relu")
# Run the graph and save scoped checkpoint.
with self.session(graph=graph1) as sess:
self.evaluate(variables.global_variables_initializer())
_, var_list_1 = meta_graph.export_scoped_meta_graph(
graph_def=graph1.as_graph_def(), export_scope="hidden1")
saver = saver_module.Saver(var_list=var_list_1, max_to_keep=1)
saver.save(sess, saver0_ckpt, write_state=False)
expected = np.reshape([[5.0999999, 7.0999999, 9.10000038] * 3], (3, 3))
# Verifies that we can run successfully after restoring.
graph2 = ops_lib.Graph()
with graph2.as_default():
new_var_list_1 = meta_graph.copy_scoped_meta_graph(
from_scope="hidden1",
to_scope="new_hidden1",
from_graph=graph1,
to_graph=graph2)
with self.session(graph=graph2) as sess:
saver3 = saver_module.Saver(var_list=new_var_list_1, max_to_keep=1)
saver3.restore(sess, saver0_ckpt)
self.assertAllClose(expected, sess.run("new_hidden1/relu:0"))
def testSerializeSaverWithScope(self):
test_dir = self._get_test_dir("export_graph_def")
saver1_ckpt = os.path.join(test_dir, "saver1.ckpt")
saver2_ckpt = os.path.join(test_dir, "saver2.ckpt")
graph = ops_lib.Graph()
with graph.as_default():
with ops_lib.name_scope("hidden1"):
variable1 = variable_v1.VariableV1([1.0], name="variable1")
saver1 = saver_module.Saver(var_list=[variable1])
graph.add_to_collection(ops_lib.GraphKeys.SAVERS, saver1)
with ops_lib.name_scope("hidden2"):
variable2 = variable_v1.VariableV1([2.0], name="variable2")
saver2 = saver_module.Saver(var_list=[variable2], name="hidden2/")
graph.add_to_collection(ops_lib.GraphKeys.SAVERS, saver2)
with self.session(graph=graph) as sess:
self.evaluate(variables.global_variables_initializer())
saver1.save(sess, saver1_ckpt, write_state=False)
saver2.save(sess, saver2_ckpt, write_state=False)
graph1 = ops_lib.Graph()
with graph1.as_default():
var_dict1 = meta_graph.copy_scoped_meta_graph(
from_scope="hidden1",
to_scope="new_hidden1",
from_graph=graph,
to_graph=graph1)
self.assertEqual(1, len(var_dict1))
saver_list1 = graph1.get_collection(ops_lib.GraphKeys.SAVERS)
self.assertEqual(1, len(saver_list1))
with self.session(graph=graph1) as sess:
saver_list1[0].restore(sess, saver1_ckpt)
self.assertEqual(1.0, self.evaluate(var_dict1["variable1:0"]))
graph2 = ops_lib.Graph()
with graph2.as_default():
var_dict2 = meta_graph.copy_scoped_meta_graph(
from_scope="hidden2",
to_scope="new_hidden2",
from_graph=graph,
to_graph=graph2)
self.assertEqual(1, len(var_dict2))
saver_list2 = graph2.get_collection(ops_lib.GraphKeys.SAVERS)
self.assertEqual(1, len(saver_list2))
with self.session(graph=graph2) as sess:
saver_list2[0].restore(sess, saver2_ckpt)
self.assertEqual(2.0, self.evaluate(var_dict2["variable2:0"]))
| ScopedGraphTest |
python | gevent__gevent | src/greentest/3.11/test_wsgiref.py | {
"start": 9888,
"end": 16643
} | class ____(TestCase):
def checkShift(self,sn_in,pi_in,part,sn_out,pi_out):
env = {'SCRIPT_NAME':sn_in,'PATH_INFO':pi_in}
util.setup_testing_defaults(env)
self.assertEqual(util.shift_path_info(env),part)
self.assertEqual(env['PATH_INFO'],pi_out)
self.assertEqual(env['SCRIPT_NAME'],sn_out)
return env
def checkDefault(self, key, value, alt=None):
# Check defaulting when empty
env = {}
util.setup_testing_defaults(env)
if isinstance(value, StringIO):
self.assertIsInstance(env[key], StringIO)
elif isinstance(value,BytesIO):
self.assertIsInstance(env[key],BytesIO)
else:
self.assertEqual(env[key], value)
# Check existing value
env = {key:alt}
util.setup_testing_defaults(env)
self.assertIs(env[key], alt)
def checkCrossDefault(self,key,value,**kw):
util.setup_testing_defaults(kw)
self.assertEqual(kw[key],value)
def checkAppURI(self,uri,**kw):
util.setup_testing_defaults(kw)
self.assertEqual(util.application_uri(kw),uri)
def checkReqURI(self,uri,query=1,**kw):
util.setup_testing_defaults(kw)
self.assertEqual(util.request_uri(kw,query),uri)
def checkFW(self,text,size,match):
def make_it(text=text,size=size):
return util.FileWrapper(StringIO(text),size)
compare_generic_iter(make_it,match)
it = make_it()
self.assertFalse(it.filelike.closed)
for item in it:
pass
self.assertFalse(it.filelike.closed)
it.close()
self.assertTrue(it.filelike.closed)
def testSimpleShifts(self):
self.checkShift('','/', '', '/', '')
self.checkShift('','/x', 'x', '/x', '')
self.checkShift('/','', None, '/', '')
self.checkShift('/a','/x/y', 'x', '/a/x', '/y')
self.checkShift('/a','/x/', 'x', '/a/x', '/')
def testNormalizedShifts(self):
self.checkShift('/a/b', '/../y', '..', '/a', '/y')
self.checkShift('', '/../y', '..', '', '/y')
self.checkShift('/a/b', '//y', 'y', '/a/b/y', '')
self.checkShift('/a/b', '//y/', 'y', '/a/b/y', '/')
self.checkShift('/a/b', '/./y', 'y', '/a/b/y', '')
self.checkShift('/a/b', '/./y/', 'y', '/a/b/y', '/')
self.checkShift('/a/b', '///./..//y/.//', '..', '/a', '/y/')
self.checkShift('/a/b', '///', '', '/a/b/', '')
self.checkShift('/a/b', '/.//', '', '/a/b/', '')
self.checkShift('/a/b', '/x//', 'x', '/a/b/x', '/')
self.checkShift('/a/b', '/.', None, '/a/b', '')
def testDefaults(self):
for key, value in [
('SERVER_NAME','127.0.0.1'),
('SERVER_PORT', '80'),
('SERVER_PROTOCOL','HTTP/1.0'),
('HTTP_HOST','127.0.0.1'),
('REQUEST_METHOD','GET'),
('SCRIPT_NAME',''),
('PATH_INFO','/'),
('wsgi.version', (1,0)),
('wsgi.run_once', 0),
('wsgi.multithread', 0),
('wsgi.multiprocess', 0),
('wsgi.input', BytesIO()),
('wsgi.errors', StringIO()),
('wsgi.url_scheme','http'),
]:
self.checkDefault(key,value)
def testCrossDefaults(self):
self.checkCrossDefault('HTTP_HOST',"foo.bar",SERVER_NAME="foo.bar")
self.checkCrossDefault('wsgi.url_scheme',"https",HTTPS="on")
self.checkCrossDefault('wsgi.url_scheme',"https",HTTPS="1")
self.checkCrossDefault('wsgi.url_scheme',"https",HTTPS="yes")
self.checkCrossDefault('wsgi.url_scheme',"http",HTTPS="foo")
self.checkCrossDefault('SERVER_PORT',"80",HTTPS="foo")
self.checkCrossDefault('SERVER_PORT',"443",HTTPS="on")
def testGuessScheme(self):
self.assertEqual(util.guess_scheme({}), "http")
self.assertEqual(util.guess_scheme({'HTTPS':"foo"}), "http")
self.assertEqual(util.guess_scheme({'HTTPS':"on"}), "https")
self.assertEqual(util.guess_scheme({'HTTPS':"yes"}), "https")
self.assertEqual(util.guess_scheme({'HTTPS':"1"}), "https")
def testAppURIs(self):
self.checkAppURI("http://127.0.0.1/")
self.checkAppURI("http://127.0.0.1/spam", SCRIPT_NAME="/spam")
self.checkAppURI("http://127.0.0.1/sp%E4m", SCRIPT_NAME="/sp\xe4m")
self.checkAppURI("http://spam.example.com:2071/",
HTTP_HOST="spam.example.com:2071", SERVER_PORT="2071")
self.checkAppURI("http://spam.example.com/",
SERVER_NAME="spam.example.com")
self.checkAppURI("http://127.0.0.1/",
HTTP_HOST="127.0.0.1", SERVER_NAME="spam.example.com")
self.checkAppURI("https://127.0.0.1/", HTTPS="on")
self.checkAppURI("http://127.0.0.1:8000/", SERVER_PORT="8000",
HTTP_HOST=None)
def testReqURIs(self):
self.checkReqURI("http://127.0.0.1/")
self.checkReqURI("http://127.0.0.1/spam", SCRIPT_NAME="/spam")
self.checkReqURI("http://127.0.0.1/sp%E4m", SCRIPT_NAME="/sp\xe4m")
self.checkReqURI("http://127.0.0.1/spammity/spam",
SCRIPT_NAME="/spammity", PATH_INFO="/spam")
self.checkReqURI("http://127.0.0.1/spammity/sp%E4m",
SCRIPT_NAME="/spammity", PATH_INFO="/sp\xe4m")
self.checkReqURI("http://127.0.0.1/spammity/spam;ham",
SCRIPT_NAME="/spammity", PATH_INFO="/spam;ham")
self.checkReqURI("http://127.0.0.1/spammity/spam;cookie=1234,5678",
SCRIPT_NAME="/spammity", PATH_INFO="/spam;cookie=1234,5678")
self.checkReqURI("http://127.0.0.1/spammity/spam?say=ni",
SCRIPT_NAME="/spammity", PATH_INFO="/spam",QUERY_STRING="say=ni")
self.checkReqURI("http://127.0.0.1/spammity/spam?s%E4y=ni",
SCRIPT_NAME="/spammity", PATH_INFO="/spam",QUERY_STRING="s%E4y=ni")
self.checkReqURI("http://127.0.0.1/spammity/spam", 0,
SCRIPT_NAME="/spammity", PATH_INFO="/spam",QUERY_STRING="say=ni")
def testFileWrapper(self):
self.checkFW("xyz"*50, 120, ["xyz"*40,"xyz"*10])
def testHopByHop(self):
for hop in (
"Connection Keep-Alive Proxy-Authenticate Proxy-Authorization "
"TE Trailers Transfer-Encoding Upgrade"
).split():
for alt in hop, hop.title(), hop.upper(), hop.lower():
self.assertTrue(util.is_hop_by_hop(alt))
# Not comprehensive, just a few random header names
for hop in (
"Accept Cache-Control Date Pragma Trailer Via Warning"
).split():
for alt in hop, hop.title(), hop.upper(), hop.lower():
self.assertFalse(util.is_hop_by_hop(alt))
| UtilityTests |
python | pikepdf__pikepdf | src/pikepdf/codec.py | {
"start": 4763,
"end": 6094
} | class ____(codecs.IncrementalDecoder):
"""Implement PdfDocEncoding incremental decoder."""
def decode(self, input: Any, final: bool = False) -> str: # type: ignore
"""Implement codecs.IncrementalDecoder.decode for pdfdoc."""
return pdfdoc_decode(bytes(input), 'strict')[0]
def find_pdfdoc(encoding: str) -> codecs.CodecInfo | None:
"""Register pdfdoc codec with Python.
Both pdfdoc and pdfdoc_pikepdf are registered. Use "pdfdoc_pikepdf" if pikepdf's
codec is required. If another third party package installs a codec named pdfdoc,
the first imported by Python will be registered and will service all encoding.
Unfortunately, Python's codec infrastructure does not give a better mechanism
for resolving conflicts.
"""
if encoding in ('pdfdoc', 'pdfdoc_pikepdf'):
codec = PdfDocCodec()
return codecs.CodecInfo(
name=encoding,
encode=codec.encode,
decode=codec.decode,
streamwriter=PdfDocStreamWriter,
streamreader=PdfDocStreamReader,
incrementalencoder=PdfDocIncrementalEncoder,
incrementaldecoder=PdfDocIncrementalDecoder,
)
return None # pragma: no cover
codecs.register(find_pdfdoc)
__all__ = ['utf8_to_pdf_doc', 'pdf_doc_to_utf8']
| PdfDocIncrementalDecoder |
python | ray-project__ray | python/ray/actor.py | {
"start": 14994,
"end": 18441
} | class ____:
"""A container for the metadata required to invoke an actor method.
This class intentionally does *not* hold a reference to the `ActorHandle`, as that causes
a circular reference that delays `ActorHandle` destruction until the Python GC runs.
Instead, it can be used as a factory to lazily generate `ActorMethod` instances that can
be used to submit actor tasks for this method.
"""
def __init__(
self,
method_name: str,
num_returns: Optional[Union[int, Literal["streaming"]]],
max_task_retries: int,
retry_exceptions: Union[bool, list, tuple],
is_generator: bool,
generator_backpressure_num_objects: int,
enable_task_events: bool,
decorator: Optional[Any] = None,
signature: Optional[List[inspect.Parameter]] = None,
tensor_transport: Optional[TensorTransportEnum] = None,
):
"""Initialize an _ActorMethodMetadata.
Args:
method_name: The name of the actor method.
num_returns: The default number of return values that the method
invocation should return. If None is given, it uses
DEFAULT_ACTOR_METHOD_NUM_RETURN_VALS for a normal actor task
and "streaming" for a generator task (when `is_generator` is True).
max_task_retries: Number of retries on method failure.
retry_exceptions: Boolean or list/tuple of exceptions to retry.
is_generator: True if the method is a generator.
generator_backpressure_num_objects: Generator-only config for backpressure.
enable_task_events: True if task events are enabled for this method.
decorator: Optional decorator for the method invocation.
signature: The signature of the actor method.
tensor_transport: The tensor transport protocol to use for the actor method.
"""
self._method_name = method_name
# Default case.
if num_returns is None:
if is_generator:
num_returns = "streaming"
else:
num_returns = ray_constants.DEFAULT_ACTOR_METHOD_NUM_RETURN_VALS
self._num_returns = num_returns
self._max_task_retries = max_task_retries
self._retry_exceptions = retry_exceptions
self._is_generator = is_generator
self._generator_backpressure_num_objects = generator_backpressure_num_objects
self._enable_task_events = enable_task_events
self._decorator = decorator
self._signature = signature
self._tensor_transport = tensor_transport
def bind(self, actor_handle: "ActorHandle") -> "ActorMethod":
"""
Produce a bound ActorMethod that holds a strong reference to actor_handle.
"""
return ActorMethod(
actor_handle,
self._method_name,
self._num_returns,
self._max_task_retries,
self._retry_exceptions,
self._is_generator,
self._generator_backpressure_num_objects,
self._enable_task_events,
decorator=self._decorator,
signature=self._signature,
tensor_transport=self._tensor_transport,
)
# Create objects to wrap method invocations. This is done so that we can
# invoke methods with actor.method.remote() instead of actor.method().
@PublicAPI
| _ActorMethodMetadata |
python | facebookresearch__faiss | tests/test_binary_io.py | {
"start": 3911,
"end": 5454
} | class ____(unittest.TestCase):
def __init__(self, *args, **kwargs):
unittest.TestCase.__init__(self, *args, **kwargs)
d = 32
nt = 200
nb = 1500
nq = 500
(self.xt, self.xb, self.xq) = make_binary_dataset(d, nb, nt, nq)
def test_hnsw(self):
d = self.xq.shape[1] * 8
index = faiss.IndexBinaryHNSW(d)
index.add(self.xb)
D, I = index.search(self.xq, 3)
fd, tmpnam = tempfile.mkstemp()
os.close(fd)
try:
faiss.write_index_binary(index, tmpnam)
index2 = faiss.read_index_binary(tmpnam)
D2, I2 = index2.search(self.xq, 3)
assert (I2 == I).all()
assert (D2 == D).all()
finally:
os.remove(tmpnam)
def test_ivf_hnsw(self):
d = self.xq.shape[1] * 8
quantizer = faiss.IndexBinaryHNSW(d)
index = faiss.IndexBinaryIVF(quantizer, d, 8)
index.cp.min_points_per_centroid = 5 # quiet warning
index.nprobe = 4
index.train(self.xt)
index.add(self.xb)
D, I = index.search(self.xq, 3)
fd, tmpnam = tempfile.mkstemp()
os.close(fd)
try:
faiss.write_index_binary(index, tmpnam)
index2 = faiss.read_index_binary(tmpnam)
D2, I2 = index2.search(self.xq, 3)
assert (I2 == I).all()
assert (D2 == D).all()
finally:
os.remove(tmpnam)
if __name__ == '__main__':
unittest.main()
| TestBinaryHNSW |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.