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__warehouse
tests/unit/organizations/test_models.py
{ "start": 10803, "end": 11397 }
class ____: def test_traversal_finds(self, db_request): organization = DBOrganizationFactory.create(name="foo") team = DBTeamFactory.create(organization=organization, name="Bar") root = TeamFactory(db_request) assert root["foo"]["bar"] == team def test_traversal_cant_find(self, db_request): organization = DBOrganizationFactory.create(name="foo") DBTeamFactory.create(organization=organization, name="Bar") root = TeamFactory(db_request) with pytest.raises(KeyError): root["foo"]["invalid"]
TestTeamFactory
python
pytest-dev__pytest
src/_pytest/mark/expression.py
{ "start": 9303, "end": 9831 }
class ____(Mapping[str, MatcherNameAdapter]): """Adapts a matcher function to a locals mapping as required by eval().""" def __init__(self, matcher: ExpressionMatcher) -> None: self.matcher = matcher def __getitem__(self, key: str) -> MatcherNameAdapter: return MatcherNameAdapter(matcher=self.matcher, name=key[len(IDENT_PREFIX) :]) def __iter__(self) -> Iterator[str]: raise NotImplementedError() def __len__(self) -> int: raise NotImplementedError() @final
MatcherAdapter
python
celery__celery
t/unit/worker/test_bootsteps.py
{ "start": 5005, "end": 9415 }
class ____: class Blueprint(bootsteps.Blueprint): name = 'test_Blueprint' def test_steps_added_to_unclaimed(self): class tnA(bootsteps.Step): name = 'test_Blueprint.A' class tnB(bootsteps.Step): name = 'test_Blueprint.B' class xxA(bootsteps.Step): name = 'xx.A' class Blueprint(self.Blueprint): default_steps = [tnA, tnB] blueprint = Blueprint() assert tnA in blueprint.types assert tnB in blueprint.types assert xxA not in blueprint.types def test_init(self): blueprint = self.Blueprint() assert blueprint.name == 'test_Blueprint' def test_close__on_close_is_None(self): blueprint = self.Blueprint() blueprint.on_close = None blueprint.send_all = Mock() blueprint.close(1) blueprint.send_all.assert_called_with( 1, 'close', 'closing', reverse=False, ) def test_send_all_with_None_steps(self): parent = Mock() blueprint = self.Blueprint() parent.steps = [None, None, None] blueprint.send_all(parent, 'close', 'Closing', reverse=False) def test_send_all_raises(self): parent = Mock() blueprint = self.Blueprint() parent.steps = [Mock()] parent.steps[0].foo.side_effect = KeyError() blueprint.send_all(parent, 'foo', propagate=False) with pytest.raises(KeyError): blueprint.send_all(parent, 'foo', propagate=True) def test_stop_state_in_TERMINATE(self): blueprint = self.Blueprint() blueprint.state = bootsteps.TERMINATE blueprint.stop(Mock()) def test_join_raises_IGNORE_ERRORS(self): prev, bootsteps.IGNORE_ERRORS = bootsteps.IGNORE_ERRORS, (KeyError,) try: blueprint = self.Blueprint() blueprint.shutdown_complete = Mock() blueprint.shutdown_complete.wait.side_effect = KeyError('luke') blueprint.join(timeout=10) blueprint.shutdown_complete.wait.assert_called_with(timeout=10) finally: bootsteps.IGNORE_ERRORS = prev def test_connect_with(self): class b1s1(bootsteps.Step): pass class b1s2(bootsteps.Step): last = True class b2s1(bootsteps.Step): pass class b2s2(bootsteps.Step): last = True b1 = self.Blueprint([b1s1, b1s2]) b2 = self.Blueprint([b2s1, b2s2]) b1.apply(Mock()) b2.apply(Mock()) b1.connect_with(b2) assert b1s1 in b1.graph assert b2s1 in b1.graph assert b2s2 in b1.graph assert repr(b1s1) assert str(b1s1) def test_topsort_raises_KeyError(self): class Step(bootsteps.Step): requires = ('xyxxx.fsdasewe.Unknown',) b = self.Blueprint([Step]) b.steps = b.claim_steps() with pytest.raises(ImportError): b._finalize_steps(b.steps) Step.requires = () b.steps = b.claim_steps() b._finalize_steps(b.steps) with patch('celery.bootsteps.DependencyGraph') as Dep: g = Dep.return_value = Mock() g.topsort.side_effect = KeyError('foo') with pytest.raises(KeyError): b._finalize_steps(b.steps) def test_apply(self): class MyBlueprint(bootsteps.Blueprint): name = 'test_apply' def modules(self): return ['A', 'B'] class B(bootsteps.Step): name = 'test_apply.B' class C(bootsteps.Step): name = 'test_apply.C' requires = [B] class A(bootsteps.Step): name = 'test_apply.A' requires = [C] class D(bootsteps.Step): name = 'test_apply.D' last = True x = MyBlueprint([A, D]) x.apply(self) assert isinstance(x.order[0], B) assert isinstance(x.order[1], C) assert isinstance(x.order[2], A) assert isinstance(x.order[3], D) assert A in x.types assert x[A.name] is x.order[2] def test_find_last_but_no_steps(self): class MyBlueprint(bootsteps.Blueprint): name = 'qwejwioqjewoqiej' x = MyBlueprint() x.apply(self) assert x._find_last() is None
test_Blueprint
python
Lightning-AI__lightning
examples/pytorch/tensor_parallel/train.py
{ "start": 346, "end": 2773 }
class ____(L.LightningModule): def __init__(self): super().__init__() self.model_args = ModelArgs(vocab_size=32000) self.model = Transformer(self.model_args) def configure_model(self): # User-defined function that applies the desired parallelizations specific to the model # (TP, FSDP2, activation checkpointing, ...) parallelize(self.model, device_mesh=self.device_mesh) def on_train_start(self) -> None: self.model.init_weights() def training_step(self, batch): inputs = batch[:, :-1] labels = batch[:, 1:] output = self.model(inputs) # Optional: Parallelize loss computation across class dimension (see parallelism.py) with loss_parallel(): return F.cross_entropy(output.reshape(-1, output.size(-1)), labels.reshape(-1)) def backward(self, *args, **kwargs): with loss_parallel(): super().backward(*args, **kwargs) def configure_optimizers(self): return torch.optim.AdamW(self.model.parameters(), lr=3e-3, foreach=True) def train_dataloader(self): dataset = RandomTokenDataset(vocab_size=self.model_args.vocab_size, seq_length=128) # Trainer configures the sampler automatically for you such that # all batches in a tensor-parallel group are identical return DataLoader(dataset, batch_size=8, num_workers=4) def train(): strategy = ModelParallelStrategy( # Define the size of the 2D parallelism # Set to "auto" to apply TP intra-node and DP inter-node data_parallel_size=2, tensor_parallel_size=2, ) trainer = L.Trainer( accelerator="cuda", devices=4, strategy=strategy, limit_train_batches=10, max_epochs=1, ) # Initialize the model with trainer.init_module(empty_init=True): model = Llama3() trainer.print(f"Number of model parameters: {sum(p.numel() for p in model.parameters()) / 1e9:.1f} B") trainer.print("Starting training ...") trainer.fit(model) trainer.print("Training successfully completed!") trainer.print(f"Peak memory usage: {torch.cuda.max_memory_allocated() / 1e9:.02f} GB") if __name__ == "__main__": assert torch.cuda.device_count() >= 4, "This example requires at least 4 GPUs with 24 GB of memory each." torch.set_float32_matmul_precision("high") train()
Llama3
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol30.py
{ "start": 327, "end": 373 }
class ____(Protocol): v1: ClassVar[float]
P2
python
pallets__flask
src/flask/json/tag.py
{ "start": 1625, "end": 2803 }
class ____: """Base class for defining type tags for :class:`TaggedJSONSerializer`.""" __slots__ = ("serializer",) #: The tag to mark the serialized object with. If empty, this tag is #: only used as an intermediate step during tagging. key: str = "" def __init__(self, serializer: TaggedJSONSerializer) -> None: """Create a tagger for the given serializer.""" self.serializer = serializer def check(self, value: t.Any) -> bool: """Check if the given value should be tagged by this tag.""" raise NotImplementedError def to_json(self, value: t.Any) -> t.Any: """Convert the Python object to an object that is a valid JSON type. The tag will be added later.""" raise NotImplementedError def to_python(self, value: t.Any) -> t.Any: """Convert the JSON representation back to the correct type. The tag will already be removed.""" raise NotImplementedError def tag(self, value: t.Any) -> dict[str, t.Any]: """Convert the value to a valid JSON type and add the tag structure around it.""" return {self.key: self.to_json(value)}
JSONTag
python
pandas-dev__pandas
pandas/tests/plotting/frame/test_frame_subplots.py
{ "start": 577, "end": 28961 }
class ____: @pytest.mark.slow @pytest.mark.parametrize("kind", ["bar", "barh", "line", "area"]) def test_subplots(self, kind): df = DataFrame( np.random.default_rng(2).random((10, 3)), index=list(string.ascii_letters[:10]), ) axes = df.plot(kind=kind, subplots=True, sharex=True, legend=True) _check_axes_shape(axes, axes_num=3, layout=(3, 1)) assert axes.shape == (3,) for ax, column in zip(axes, df.columns, strict=True): _check_legend_labels(ax, labels=[pprint_thing(column)]) for ax in axes[:-2]: _check_visible(ax.xaxis) # xaxis must be visible for grid _check_visible(ax.get_xticklabels(), visible=False) if kind != "bar": # change https://github.com/pandas-dev/pandas/issues/26714 _check_visible(ax.get_xticklabels(minor=True), visible=False) _check_visible(ax.xaxis.get_label(), visible=False) _check_visible(ax.get_yticklabels()) _check_visible(axes[-1].xaxis) _check_visible(axes[-1].get_xticklabels()) _check_visible(axes[-1].get_xticklabels(minor=True)) _check_visible(axes[-1].xaxis.get_label()) _check_visible(axes[-1].get_yticklabels()) @pytest.mark.slow @pytest.mark.parametrize("kind", ["bar", "barh", "line", "area"]) def test_subplots_no_share_x(self, kind): df = DataFrame( np.random.default_rng(2).random((10, 3)), index=list(string.ascii_letters[:10]), ) axes = df.plot(kind=kind, subplots=True, sharex=False) for ax in axes: _check_visible(ax.xaxis) _check_visible(ax.get_xticklabels()) _check_visible(ax.get_xticklabels(minor=True)) _check_visible(ax.xaxis.get_label()) _check_visible(ax.get_yticklabels()) @pytest.mark.slow @pytest.mark.parametrize("kind", ["bar", "barh", "line", "area"]) def test_subplots_no_legend(self, kind): df = DataFrame( np.random.default_rng(2).random((10, 3)), index=list(string.ascii_letters[:10]), ) axes = df.plot(kind=kind, subplots=True, legend=False) for ax in axes: assert ax.get_legend() is None @pytest.mark.parametrize("kind", ["line", "area"]) def test_subplots_timeseries(self, kind): idx = date_range(start="2014-07-01", freq="ME", periods=10) df = DataFrame(np.random.default_rng(2).random((10, 3)), index=idx) axes = df.plot(kind=kind, subplots=True, sharex=True) _check_axes_shape(axes, axes_num=3, layout=(3, 1)) for ax in axes[:-2]: # GH 7801 _check_visible(ax.xaxis) # xaxis must be visible for grid _check_visible(ax.get_xticklabels(), visible=False) _check_visible(ax.get_xticklabels(minor=True), visible=False) _check_visible(ax.xaxis.get_label(), visible=False) _check_visible(ax.get_yticklabels()) _check_visible(axes[-1].xaxis) _check_visible(axes[-1].get_xticklabels()) _check_visible(axes[-1].get_xticklabels(minor=True)) _check_visible(axes[-1].xaxis.get_label()) _check_visible(axes[-1].get_yticklabels()) _check_ticks_props(axes, xrot=0) @pytest.mark.parametrize("kind", ["line", "area"]) def test_subplots_timeseries_rot(self, kind): idx = date_range(start="2014-07-01", freq="ME", periods=10) df = DataFrame(np.random.default_rng(2).random((10, 3)), index=idx) axes = df.plot(kind=kind, subplots=True, sharex=False, rot=45, fontsize=7) for ax in axes: _check_visible(ax.xaxis) _check_visible(ax.get_xticklabels()) _check_visible(ax.get_xticklabels(minor=True)) _check_visible(ax.xaxis.get_label()) _check_visible(ax.get_yticklabels()) _check_ticks_props(ax, xlabelsize=7, xrot=45, ylabelsize=7) @pytest.mark.parametrize( "col", ["numeric", "timedelta", "datetime_no_tz", "datetime_all_tz"] ) def test_subplots_timeseries_y_axis(self, col): # GH16953 data = { "numeric": np.array([1, 2, 5]), "timedelta": [ pd.Timedelta(-10, unit="s"), pd.Timedelta(10, unit="m"), pd.Timedelta(10, unit="h"), ], "datetime_no_tz": [ pd.to_datetime("2017-08-01 00:00:00"), pd.to_datetime("2017-08-01 02:00:00"), pd.to_datetime("2017-08-02 00:00:00"), ], "datetime_all_tz": [ pd.to_datetime("2017-08-01 00:00:00", utc=True), pd.to_datetime("2017-08-01 02:00:00", utc=True), pd.to_datetime("2017-08-02 00:00:00", utc=True), ], "text": ["This", "should", "fail"], } testdata = DataFrame(data) ax = testdata.plot(y=col) result = ax.get_lines()[0].get_data()[1] expected = testdata[col].values assert (result == expected).all() def test_subplots_timeseries_y_text_error(self): # GH16953 data = { "numeric": np.array([1, 2, 5]), "text": ["This", "should", "fail"], } testdata = DataFrame(data) msg = "no numeric data to plot" with pytest.raises(TypeError, match=msg): testdata.plot(y="text") @pytest.mark.xfail(reason="not support for period, categorical, datetime_mixed_tz") def test_subplots_timeseries_y_axis_not_supported(self): """ This test will fail for: period: since period isn't yet implemented in ``select_dtypes`` and because it will need a custom value converter + tick formatter (as was done for x-axis plots) categorical: because it will need a custom value converter + tick formatter (also doesn't work for x-axis, as of now) datetime_mixed_tz: because of the way how pandas handles ``Series`` of ``datetime`` objects with different timezone, generally converting ``datetime`` objects in a tz-aware form could help with this problem """ data = { "numeric": np.array([1, 2, 5]), "period": [ pd.Period("2017-08-01 00:00:00", freq="h"), pd.Period("2017-08-01 02:00", freq="h"), pd.Period("2017-08-02 00:00:00", freq="h"), ], "categorical": pd.Categorical( ["c", "b", "a"], categories=["a", "b", "c"], ordered=False ), "datetime_mixed_tz": [ pd.to_datetime("2017-08-01 00:00:00", utc=True), pd.to_datetime("2017-08-01 02:00:00"), pd.to_datetime("2017-08-02 00:00:00"), ], } testdata = DataFrame(data) ax_period = testdata.plot(x="numeric", y="period") assert ( ax_period.get_lines()[0].get_data()[1] == testdata["period"].values ).all() ax_categorical = testdata.plot(x="numeric", y="categorical") assert ( ax_categorical.get_lines()[0].get_data()[1] == testdata["categorical"].values ).all() ax_datetime_mixed_tz = testdata.plot(x="numeric", y="datetime_mixed_tz") assert ( ax_datetime_mixed_tz.get_lines()[0].get_data()[1] == testdata["datetime_mixed_tz"].values ).all() @pytest.mark.parametrize( "layout, exp_layout", [ [(2, 2), (2, 2)], [(-1, 2), (2, 2)], [(2, -1), (2, 2)], [(1, 4), (1, 4)], [(-1, 4), (1, 4)], [(4, -1), (4, 1)], ], ) def test_subplots_layout_multi_column(self, layout, exp_layout): # GH 6667 df = DataFrame( np.random.default_rng(2).random((10, 3)), index=list(string.ascii_letters[:10]), ) axes = df.plot(subplots=True, layout=layout) _check_axes_shape(axes, axes_num=3, layout=exp_layout) assert axes.shape == exp_layout def test_subplots_layout_multi_column_error(self): # GH 6667 df = DataFrame( np.random.default_rng(2).random((10, 3)), index=list(string.ascii_letters[:10]), ) msg = "Layout of 1x1 must be larger than required size 3" with pytest.raises(ValueError, match=msg): df.plot(subplots=True, layout=(1, 1)) msg = "At least one dimension of layout must be positive" with pytest.raises(ValueError, match=msg): df.plot(subplots=True, layout=(-1, -1)) @pytest.mark.parametrize( "kwargs, expected_axes_num, expected_layout, expected_shape", [ ({}, 1, (1, 1), (1,)), ({"layout": (3, 3)}, 1, (3, 3), (3, 3)), ], ) def test_subplots_layout_single_column( self, kwargs, expected_axes_num, expected_layout, expected_shape ): # GH 6667 df = DataFrame( np.random.default_rng(2).random((10, 1)), index=list(string.ascii_letters[:10]), ) axes = df.plot(subplots=True, **kwargs) _check_axes_shape( axes, axes_num=expected_axes_num, layout=expected_layout, ) assert axes.shape == expected_shape @pytest.mark.slow @pytest.mark.parametrize("idx", [range(5), date_range("1/1/2000", periods=5)]) def test_subplots_warnings(self, idx): # GH 9464 with tm.assert_produces_warning(None): df = DataFrame(np.random.default_rng(2).standard_normal((5, 4)), index=idx) df.plot(subplots=True, layout=(3, 2)) def test_subplots_multiple_axes(self): # GH 5353, 6970, GH 7069 fig, axes = mpl.pyplot.subplots(2, 3) df = DataFrame( np.random.default_rng(2).random((10, 3)), index=list(string.ascii_letters[:10]), ) returned = df.plot(subplots=True, ax=axes[0], sharex=False, sharey=False) _check_axes_shape(returned, axes_num=3, layout=(1, 3)) assert returned.shape == (3,) assert returned[0].figure is fig # draw on second row returned = df.plot(subplots=True, ax=axes[1], sharex=False, sharey=False) _check_axes_shape(returned, axes_num=3, layout=(1, 3)) assert returned.shape == (3,) assert returned[0].figure is fig _check_axes_shape(axes, axes_num=6, layout=(2, 3)) def test_subplots_multiple_axes_error(self): # GH 5353, 6970, GH 7069 df = DataFrame( np.random.default_rng(2).random((10, 3)), index=list(string.ascii_letters[:10]), ) msg = "The number of passed axes must be 3, the same as the output plot" _, axes = mpl.pyplot.subplots(2, 3) with pytest.raises(ValueError, match=msg): # pass different number of axes from required df.plot(subplots=True, ax=axes) @pytest.mark.parametrize( "layout, exp_layout", [ [(2, 1), (2, 2)], [(2, -1), (2, 2)], [(-1, 2), (2, 2)], ], ) def test_subplots_multiple_axes_2_dim(self, layout, exp_layout): # GH 5353, 6970, GH 7069 # pass 2-dim axes and invalid layout # invalid layout should not affect to input and return value # (show warning is tested in # TestDataFrameGroupByPlots.test_grouped_box_multiple_axes _, axes = mpl.pyplot.subplots(2, 2) df = DataFrame( np.random.default_rng(2).random((10, 4)), index=list(string.ascii_letters[:10]), ) with tm.assert_produces_warning(UserWarning, match="layout keyword is ignored"): returned = df.plot( subplots=True, ax=axes, layout=layout, sharex=False, sharey=False ) _check_axes_shape(returned, axes_num=4, layout=exp_layout) assert returned.shape == (4,) def test_subplots_multiple_axes_single_col(self): # GH 5353, 6970, GH 7069 # single column _, axes = mpl.pyplot.subplots(1, 1) df = DataFrame( np.random.default_rng(2).random((10, 1)), index=list(string.ascii_letters[:10]), ) axes = df.plot(subplots=True, ax=[axes], sharex=False, sharey=False) _check_axes_shape(axes, axes_num=1, layout=(1, 1)) assert axes.shape == (1,) def test_subplots_ts_share_axes(self): # GH 3964 _, axes = mpl.pyplot.subplots(3, 3, sharex=True, sharey=True) mpl.pyplot.subplots_adjust(left=0.05, right=0.95, hspace=0.3, wspace=0.3) df = DataFrame( np.random.default_rng(2).standard_normal((10, 9)), index=date_range(start="2014-07-01", freq="ME", periods=10), ) for i, ax in enumerate(axes.ravel()): df[i].plot(ax=ax, fontsize=5) # Rows other than bottom should not be visible for ax in axes[0:-1].ravel(): _check_visible(ax.get_xticklabels(), visible=False) # Bottom row should be visible for ax in axes[-1].ravel(): _check_visible(ax.get_xticklabels(), visible=True) # First column should be visible for ax in axes[[0, 1, 2], [0]].ravel(): _check_visible(ax.get_yticklabels(), visible=True) # Other columns should not be visible for ax in axes[[0, 1, 2], [1]].ravel(): _check_visible(ax.get_yticklabels(), visible=False) for ax in axes[[0, 1, 2], [2]].ravel(): _check_visible(ax.get_yticklabels(), visible=False) def test_subplots_sharex_axes_existing_axes(self): # GH 9158 d = {"A": [1.0, 2.0, 3.0, 4.0], "B": [4.0, 3.0, 2.0, 1.0], "C": [5, 1, 3, 4]} df = DataFrame(d, index=date_range("2014 10 11", "2014 10 14")) axes = df[["A", "B"]].plot(subplots=True) df["C"].plot(ax=axes[0], secondary_y=True) _check_visible(axes[0].get_xticklabels(), visible=False) _check_visible(axes[1].get_xticklabels(), visible=True) for ax in axes.ravel(): _check_visible(ax.get_yticklabels(), visible=True) def test_subplots_dup_columns(self): # GH 10962 df = DataFrame(np.random.default_rng(2).random((5, 5)), columns=list("aaaaa")) axes = df.plot(subplots=True) for ax in axes: _check_legend_labels(ax, labels=["a"]) assert len(ax.lines) == 1 def test_subplots_dup_columns_secondary_y(self): # GH 10962 df = DataFrame(np.random.default_rng(2).random((5, 5)), columns=list("aaaaa")) axes = df.plot(subplots=True, secondary_y="a") for ax in axes: # (right) is only attached when subplots=False _check_legend_labels(ax, labels=["a"]) assert len(ax.lines) == 1 def test_subplots_dup_columns_secondary_y_no_subplot(self): # GH 10962 df = DataFrame(np.random.default_rng(2).random((5, 5)), columns=list("aaaaa")) ax = df.plot(secondary_y="a") _check_legend_labels(ax, labels=["a (right)"] * 5) assert len(ax.lines) == 0 assert len(ax.right_ax.lines) == 5 @pytest.mark.xfail( is_platform_linux(), reason="Weird rounding problems", strict=False, ) def test_bar_log_no_subplots(self): # GH3254, GH3298 matplotlib/matplotlib#1882, #1892 # regressions in 1.2.1 expected = np.array([0.1, 1.0, 10.0, 100]) # no subplots df = DataFrame({"A": [3] * 5, "B": list(range(1, 6))}, index=range(5)) ax = df.plot.bar(grid=True, log=True) tm.assert_numpy_array_equal(ax.yaxis.get_ticklocs(), expected) @pytest.mark.xfail( is_platform_linux(), reason="Weird rounding problems", strict=False, ) def test_bar_log_subplots(self): expected = np.array([0.1, 1.0, 10.0, 100.0, 1000.0, 1e4]) ax = DataFrame([Series([200, 300]), Series([300, 500])]).plot.bar( log=True, subplots=True ) tm.assert_numpy_array_equal(ax[0].yaxis.get_ticklocs(), expected) tm.assert_numpy_array_equal(ax[1].yaxis.get_ticklocs(), expected) def test_boxplot_subplots_return_type_default(self, hist_df): df = hist_df # normal style: return_type=None result = df.plot.box(subplots=True) assert isinstance(result, Series) _check_box_return_type( result, None, expected_keys=["height", "weight", "category"] ) @pytest.mark.parametrize("rt", ["dict", "axes", "both"]) def test_boxplot_subplots_return_type(self, hist_df, rt): df = hist_df returned = df.plot.box(return_type=rt, subplots=True) _check_box_return_type( returned, rt, expected_keys=["height", "weight", "category"], check_ax_title=False, ) def test_df_subplots_patterns_minorticks(self): # GH 10657 df = DataFrame( np.random.default_rng(2).standard_normal((10, 2)), index=date_range("1/1/2000", periods=10), columns=list("AB"), ) # shared subplots _, axes = plt.subplots(2, 1, sharex=True) axes = df.plot(subplots=True, ax=axes) for ax in axes: assert len(ax.lines) == 1 _check_visible(ax.get_yticklabels(), visible=True) # xaxis of 1st ax must be hidden _check_visible(axes[0].get_xticklabels(), visible=False) _check_visible(axes[0].get_xticklabels(minor=True), visible=False) _check_visible(axes[1].get_xticklabels(), visible=True) _check_visible(axes[1].get_xticklabels(minor=True), visible=True) def test_df_subplots_patterns_minorticks_1st_ax_hidden(self): # GH 10657 df = DataFrame( np.random.default_rng(2).standard_normal((10, 2)), index=date_range("1/1/2000", periods=10), columns=list("AB"), ) _, axes = plt.subplots(2, 1) with tm.assert_produces_warning(UserWarning, match="sharex and sharey"): axes = df.plot(subplots=True, ax=axes, sharex=True) for ax in axes: assert len(ax.lines) == 1 _check_visible(ax.get_yticklabels(), visible=True) # xaxis of 1st ax must be hidden _check_visible(axes[0].get_xticklabels(), visible=False) _check_visible(axes[0].get_xticklabels(minor=True), visible=False) _check_visible(axes[1].get_xticklabels(), visible=True) _check_visible(axes[1].get_xticklabels(minor=True), visible=True) def test_df_subplots_patterns_minorticks_not_shared(self): # GH 10657 df = DataFrame( np.random.default_rng(2).standard_normal((10, 2)), index=date_range("1/1/2000", periods=10), columns=list("AB"), ) # not shared _, axes = plt.subplots(2, 1) axes = df.plot(subplots=True, ax=axes) for ax in axes: assert len(ax.lines) == 1 _check_visible(ax.get_yticklabels(), visible=True) _check_visible(ax.get_xticklabels(), visible=True) _check_visible(ax.get_xticklabels(minor=True), visible=True) def test_subplots_sharex_false(self): # test when sharex is set to False, two plots should have different # labels, GH 25160 df = DataFrame(np.random.default_rng(2).random((10, 2))) df.iloc[5:, 1] = np.nan df.iloc[:5, 0] = np.nan _, axs = mpl.pyplot.subplots(2, 1) df.plot.line(ax=axs, subplots=True, sharex=False) expected_ax1 = np.arange(4.5, 10, 0.5) expected_ax2 = np.arange(-0.5, 5, 0.5) tm.assert_numpy_array_equal(axs[0].get_xticks(), expected_ax1) tm.assert_numpy_array_equal(axs[1].get_xticks(), expected_ax2) def test_subplots_constrained_layout(self, temp_file): # GH 25261 idx = date_range(start="now", periods=10) df = DataFrame(np.random.default_rng(2).random((10, 3)), index=idx) kwargs = {} if hasattr(mpl.pyplot.Figure, "get_constrained_layout"): kwargs["constrained_layout"] = True _, axes = mpl.pyplot.subplots(2, **kwargs) with tm.assert_produces_warning(None): df.plot(ax=axes[0]) with temp_file.open(mode="wb") as path: mpl.pyplot.savefig(path) @pytest.mark.parametrize( "index_name, old_label, new_label", [ (None, "", "new"), ("old", "old", "new"), (None, "", ""), (None, "", 1), (None, "", [1, 2]), ], ) @pytest.mark.parametrize("kind", ["line", "area", "bar"]) def test_xlabel_ylabel_dataframe_subplots( self, kind, index_name, old_label, new_label ): # GH 9093 df = DataFrame([[1, 2], [2, 5]], columns=["Type A", "Type B"]) df.index.name = index_name # default is the ylabel is not shown and xlabel is index name axes = df.plot(kind=kind, subplots=True) assert all(ax.get_ylabel() == "" for ax in axes) assert all(ax.get_xlabel() == old_label for ax in axes) # old xlabel will be overridden and assigned ylabel will be used as ylabel axes = df.plot(kind=kind, ylabel=new_label, xlabel=new_label, subplots=True) assert all(ax.get_ylabel() == str(new_label) for ax in axes) assert all(ax.get_xlabel() == str(new_label) for ax in axes) @pytest.mark.parametrize( "kwargs", [ # stacked center {"kind": "bar", "stacked": True}, {"kind": "bar", "stacked": True, "width": 0.9}, {"kind": "barh", "stacked": True}, {"kind": "barh", "stacked": True, "width": 0.9}, # center {"kind": "bar", "stacked": False}, {"kind": "bar", "stacked": False, "width": 0.9}, {"kind": "barh", "stacked": False}, {"kind": "barh", "stacked": False, "width": 0.9}, # subplots center {"kind": "bar", "subplots": True}, {"kind": "bar", "subplots": True, "width": 0.9}, {"kind": "barh", "subplots": True}, {"kind": "barh", "subplots": True, "width": 0.9}, # align edge {"kind": "bar", "stacked": True, "align": "edge"}, {"kind": "bar", "stacked": True, "width": 0.9, "align": "edge"}, {"kind": "barh", "stacked": True, "align": "edge"}, {"kind": "barh", "stacked": True, "width": 0.9, "align": "edge"}, {"kind": "bar", "stacked": False, "align": "edge"}, {"kind": "bar", "stacked": False, "width": 0.9, "align": "edge"}, {"kind": "barh", "stacked": False, "align": "edge"}, {"kind": "barh", "stacked": False, "width": 0.9, "align": "edge"}, {"kind": "bar", "subplots": True, "align": "edge"}, {"kind": "bar", "subplots": True, "width": 0.9, "align": "edge"}, {"kind": "barh", "subplots": True, "align": "edge"}, {"kind": "barh", "subplots": True, "width": 0.9, "align": "edge"}, ], ) def test_bar_align_multiple_columns(self, kwargs): # GH2157 df = DataFrame({"A": [3] * 5, "B": list(range(5))}, index=range(5)) self._check_bar_alignment(df, **kwargs) @pytest.mark.parametrize( "kwargs", [ {"kind": "bar", "stacked": False}, {"kind": "bar", "stacked": True}, {"kind": "barh", "stacked": False}, {"kind": "barh", "stacked": True}, {"kind": "bar", "subplots": True}, {"kind": "barh", "subplots": True}, ], ) def test_bar_align_single_column(self, kwargs): df = DataFrame(np.random.default_rng(2).standard_normal(5)) self._check_bar_alignment(df, **kwargs) @pytest.mark.parametrize( "kwargs", [ {"kind": "bar", "stacked": False}, {"kind": "bar", "stacked": True}, {"kind": "barh", "stacked": False}, {"kind": "barh", "stacked": True}, {"kind": "bar", "subplots": True}, {"kind": "barh", "subplots": True}, ], ) def test_bar_barwidth_position(self, kwargs): df = DataFrame(np.random.default_rng(2).standard_normal((5, 5))) self._check_bar_alignment(df, width=0.9, position=0.2, **kwargs) @pytest.mark.parametrize("w", [1, 1.0]) def test_bar_barwidth_position_int(self, w): # GH 12979 df = DataFrame(np.random.default_rng(2).standard_normal((5, 5))) ax = df.plot.bar(stacked=True, width=w) ticks = ax.xaxis.get_ticklocs() tm.assert_numpy_array_equal(ticks, np.array([0, 1, 2, 3, 4])) assert ax.get_xlim() == (-0.75, 4.75) # check left-edge of bars assert ax.patches[0].get_x() == -0.5 assert ax.patches[-1].get_x() == 3.5 @pytest.mark.parametrize( "kind, kwargs", [ ["bar", {"stacked": True}], ["barh", {"stacked": False}], ["barh", {"stacked": True}], ["bar", {"subplots": True}], ["barh", {"subplots": True}], ], ) def test_bar_barwidth_position_int_width_1(self, kind, kwargs): # GH 12979 df = DataFrame(np.random.default_rng(2).standard_normal((5, 5))) self._check_bar_alignment(df, kind=kind, width=1, **kwargs) def _check_bar_alignment( self, df, kind="bar", stacked=False, subplots=False, align="center", width=0.5, position=0.5, ): axes = df.plot( kind=kind, stacked=stacked, subplots=subplots, align=align, width=width, position=position, grid=True, ) axes = _flatten_visible(axes) for ax in axes: if kind == "bar": axis = ax.xaxis ax_min, ax_max = ax.get_xlim() min_edge = min(p.get_x() for p in ax.patches) max_edge = max(p.get_x() + p.get_width() for p in ax.patches) elif kind == "barh": axis = ax.yaxis ax_min, ax_max = ax.get_ylim() min_edge = min(p.get_y() for p in ax.patches) max_edge = max(p.get_y() + p.get_height() for p in ax.patches) else: raise ValueError # GH 7498 # compare margins between lim and bar edges tm.assert_almost_equal(ax_min, min_edge - 0.25) tm.assert_almost_equal(ax_max, max_edge + 0.25) p = ax.patches[0] if kind == "bar" and (stacked is True or subplots is True): edge = p.get_x() center = edge + p.get_width() * position elif kind == "bar" and stacked is False: center = p.get_x() + p.get_width() * len(df.columns) * position edge = p.get_x() elif kind == "barh" and (stacked is True or subplots is True): center = p.get_y() + p.get_height() * position edge = p.get_y() elif kind == "barh" and stacked is False: center = p.get_y() + p.get_height() * len(df.columns) * position edge = p.get_y() else: raise ValueError # Check the ticks locates on integer assert (axis.get_ticklocs() == np.arange(len(df))).all() if align == "center": # Check whether the bar locates on center tm.assert_almost_equal(axis.get_ticklocs()[0], center) elif align == "edge": # Check whether the bar's edge starts from the tick tm.assert_almost_equal(axis.get_ticklocs()[0], edge) else: raise ValueError return axes
TestDataFramePlotsSubplots
python
PrefectHQ__prefect
src/prefect/cli/transfer/_dag.py
{ "start": 837, "end": 1068 }
class ____(Enum): """State of a node during traversal.""" PENDING = "pending" READY = "ready" IN_PROGRESS = "in_progress" COMPLETED = "completed" FAILED = "failed" SKIPPED = "skipped" @dataclass
NodeState
python
google__jax
jax/_src/hijax.py
{ "start": 6954, "end": 7173 }
class ____(type): def __instancecheck__(self, instance): return (super().__instancecheck__(instance) or isinstance(instance, core.Tracer) and isinstance(core.typeof(instance), BoxTy))
_BoxMeta
python
getsentry__sentry
src/sentry/models/debugfile.py
{ "start": 1441, "end": 3964 }
class ____(BaseManager["ProjectDebugFile"]): def find_missing(self, checksums: Iterable[str], project: Project) -> list[str]: if not checksums: return [] checksums = [x.lower() for x in checksums] missing = set(checksums) found = ProjectDebugFile.objects.filter( checksum__in=checksums, project_id=project.id ).values_list("checksum", flat=True) missing.difference_update(checksum for checksum in found if checksum is not None) return sorted(missing) def find_by_debug_ids( self, project: Project, debug_ids: Container[str], features: Iterable[str] | None = None ) -> dict[str, ProjectDebugFile]: """Finds debug information files matching the given debug identifiers. If a set of features is specified, only files that satisfy all features will be returned. This does not apply to legacy debug files that were not tagged with features. Returns a dict of debug files keyed by their debug identifier. """ features = frozenset(features) if features is not None else frozenset() query = Q(project_id=project.id, debug_id__in=debug_ids) difs = list(ProjectDebugFile.objects.filter(query).select_related("file").order_by("-id")) # because otherwise this would be a circular import: from sentry.debug_files.debug_files import maybe_renew_debug_files maybe_renew_debug_files(difs) difs_by_id: dict[str, list[ProjectDebugFile]] = {} for dif in difs: difs_by_id.setdefault(dif.debug_id, []).append(dif) rv = {} for debug_id, group in difs_by_id.items(): with_features = [dif for dif in group if "features" in (dif.data or ())] # In case we've never computed features for any of these files, we # just take the first one and assume that it matches. if not with_features: rv[debug_id] = group[0] continue # There's at least one file with computed features. Older files are # considered redundant and will be deleted. We search for the first # file matching the given feature set. This might not resolve if no # DIF matches the given feature set. for dif in with_features: if dif.features >= features: rv[debug_id] = dif break return rv @region_silo_model
ProjectDebugFileManager
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeParams7.py
{ "start": 425, "end": 487 }
class ____(str): ... A5 = ClassA[..., StrSubclass]
StrSubclass
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/op_invocation.py
{ "start": 1279, "end": 23494 }
class ____(NamedTuple): input_args: tuple[Any, ...] input_kwargs: dict[str, Any] resources_by_param_name: dict[str, Any] config_arg: Any def _separate_args_and_kwargs( compute_fn: "DecoratedOpFunction", args: tuple[Any, ...], kwargs: dict[str, Any], resource_arg_mapping: dict[str, Any], ) -> SeparatedArgsKwargs: """Given a decorated compute function, a set of args and kwargs, and set of resource param names, separates the set of resource inputs from op/asset inputs returns a tuple of the categorized args and kwargs. We use the remaining args and kwargs to cleanly invoke the compute function, and we use the extracted resource inputs to populate the execution context. """ resources_from_args_and_kwargs = {} params = get_function_params(compute_fn.decorated_fn) adjusted_args = [] params_without_context = params[1:] if compute_fn.has_context_arg() else params config_arg = kwargs.get("config") # Get any (non-kw) args that correspond to resource inputs & strip them from the args list for i, arg in enumerate(args): param = params_without_context[i] if i < len(params_without_context) else None if param and param.kind != inspect.Parameter.KEYWORD_ONLY: if param.name in resource_arg_mapping: resources_from_args_and_kwargs[param.name] = arg continue if param.name == "config": config_arg = arg continue adjusted_args.append(arg) # Get any kwargs that correspond to resource inputs & strip them from the kwargs dict for resource_arg in resource_arg_mapping: if resource_arg in kwargs: resources_from_args_and_kwargs[resource_arg] = kwargs[resource_arg] adjusted_kwargs = { k: v for k, v in kwargs.items() if k not in resources_from_args_and_kwargs and k != "config" } return SeparatedArgsKwargs( input_args=tuple(adjusted_args), input_kwargs=adjusted_kwargs, resources_by_param_name=resources_from_args_and_kwargs, config_arg=config_arg, ) def _get_op_context( context, ) -> "OpExecutionContext": from dagster._core.execution.context.compute import AssetExecutionContext if isinstance(context, AssetExecutionContext): return context.op_execution_context return context def direct_invocation_result( def_or_invocation: Union[ "OpDefinition", "PendingNodeInvocation[OpDefinition]", "AssetsDefinition" ], *args, **kwargs, ) -> Any: from dagster._config.pythonic_config import Config from dagster._core.definitions.assets.definition.assets_definition import AssetsDefinition from dagster._core.definitions.composition import PendingNodeInvocation from dagster._core.definitions.decorators.op_decorator import DecoratedOpFunction from dagster._core.definitions.op_definition import OpDefinition from dagster._core.execution.context.invocation import ( BaseDirectExecutionContext, build_op_context, ) from dagster._core.execution.plan.compute_generator import invoke_compute_fn if isinstance(def_or_invocation, OpDefinition): op_def = def_or_invocation pending_invocation = None assets_def = None elif isinstance(def_or_invocation, AssetsDefinition): assets_def = def_or_invocation op_def = assets_def.op pending_invocation = None elif isinstance(def_or_invocation, PendingNodeInvocation): pending_invocation = def_or_invocation op_def = def_or_invocation.node_def assets_def = None else: check.failed(f"unexpected direct invocation target {def_or_invocation}") compute_fn = op_def.compute_fn if not isinstance(compute_fn, DecoratedOpFunction): raise DagsterInvalidInvocationError( "Attempted to directly invoke an op/asset that was not constructed using the `@op` or" " `@asset` decorator. Only decorated functions can be directly invoked." ) context = None if compute_fn.has_context_arg(): if len(args) + len(kwargs) == 0: raise DagsterInvalidInvocationError( f"Decorated function '{compute_fn.name}' has context argument, but" " no context was provided when invoking." ) if len(args) > 0: if args[0] is not None and not isinstance(args[0], BaseDirectExecutionContext): raise DagsterInvalidInvocationError( f"Decorated function '{compute_fn.name}' has context argument, " "but no context was provided when invoking." ) context = args[0] # update args to omit context args = args[1:] else: # context argument is provided under kwargs context_param_name = get_function_params(compute_fn.decorated_fn)[0].name if context_param_name not in kwargs: raise DagsterInvalidInvocationError( f"Decorated function '{compute_fn.name}' has context argument " f"'{context_param_name}', but no value for '{context_param_name}' was " f"found when invoking. Provided kwargs: {kwargs}" ) context = kwargs[context_param_name] # update kwargs to remove context kwargs = { kwarg: val for kwarg, val in kwargs.items() if not kwarg == context_param_name } # allow passing context, even if the function doesn't have an arg for it elif len(args) > 0 and isinstance(args[0], BaseDirectExecutionContext): context = args[0] args = args[1:] resource_arg_mapping = {arg.name: arg.name for arg in compute_fn.get_resource_args()} # The user is allowed to invoke an op with an arbitrary mix of args and kwargs. # We ensure that these args and kwargs are correctly categorized as inputs, config, or resource objects and then validated. # # Depending on arg/kwarg type, we do various things: # - Any resources passed as parameters are also made available to user-defined code as part of the op execution context # - Provide high-quality error messages (e.g. if something tried to pass a value to an input typed Nothing) # - Default values are applied appropriately # - Inputs are type checked # # We recollect all the varying args/kwargs into a dictionary and invoke the user-defined function with kwargs only. extracted = _separate_args_and_kwargs(compute_fn, args, kwargs, resource_arg_mapping) input_args = extracted.input_args input_kwargs = extracted.input_kwargs resources_by_param_name = extracted.resources_by_param_name config_input = extracted.config_arg bound_context = (context or build_op_context()).bind( op_def=op_def, pending_invocation=pending_invocation, assets_def=assets_def, resources_from_args=resources_by_param_name, config_from_args=( config_input._convert_to_config_dictionary() # noqa: SLF001 if isinstance(config_input, Config) else config_input ), ) try: # if the compute function fails, we want to ensure we unbind the context. This # try-except handles "vanilla" asset and op invocation (generators and async handled in # _type_check_output_wrapper) input_dict = _resolve_inputs(op_def, input_args, input_kwargs, bound_context) # type: ignore # (pyright bug) result = invoke_compute_fn( fn=compute_fn.decorated_fn, context=bound_context, # type: ignore # (pyright bug) kwargs=input_dict, context_arg_provided=compute_fn.has_context_arg(), config_arg_cls=( compute_fn.get_config_arg().annotation if compute_fn.has_config_arg() else None ), resource_args=resource_arg_mapping, ) return _type_check_output_wrapper(op_def, result, bound_context) # type: ignore # (pyright bug) except Exception: bound_context.unbind() # type: ignore # (pyright bug) raise def _resolve_inputs( op_def: "OpDefinition", args, kwargs, context: "BaseDirectExecutionContext" ) -> Mapping[str, Any]: from dagster._core.execution.plan.execute_step import do_type_check nothing_input_defs = [ input_def for input_def in op_def.input_defs if input_def.dagster_type.is_nothing ] # Check kwargs for nothing inputs, and error if someone provided one. for input_def in nothing_input_defs: if input_def.name in kwargs: node_label = op_def.node_type_str raise DagsterInvalidInvocationError( f"Attempted to provide value for nothing input '{input_def.name}'. Nothing " f"dependencies are ignored when directly invoking {node_label}s." ) # Discard nothing dependencies - we ignore them during invocation. input_defs_by_name = { input_def.name: input_def for input_def in op_def.input_defs if not input_def.dagster_type.is_nothing } # Fail early if too many inputs were provided. if len(input_defs_by_name) < len(args) + len(kwargs): if len(nothing_input_defs) > 0: suggestion = ( "This may be because you attempted to provide a value for a nothing " "dependency. Nothing dependencies are ignored when directly invoking ops." ) else: suggestion = ( "This may be because an argument was provided for the context parameter, " "but no context parameter was defined for the op." ) node_label = op_def.node_type_str raise DagsterInvalidInvocationError( f"Too many input arguments were provided for {node_label} '{context.per_invocation_properties.alias}'." f" {suggestion}" ) # If more args were provided than the function has positional args, then fail early. positional_inputs = cast("DecoratedOpFunction", op_def.compute_fn).positional_inputs() if len(args) > len(positional_inputs): raise DagsterInvalidInvocationError( f"{op_def.node_type_str} '{op_def.name}' has {len(positional_inputs)} positional" f" inputs, but {len(args)} positional inputs were provided." ) input_dict = {} for position, value in enumerate(args): input_name = positional_inputs[position] input_dict[input_name] = value # check for args/kwargs collisions if input_name in kwargs: raise DagsterInvalidInvocationError( f"{op_def.node_type_str} {op_def.name} got multiple values for argument" f" '{input_name}'" ) for input_name in positional_inputs[len(args) :]: input_def = input_defs_by_name[input_name] if input_name in kwargs: input_dict[input_name] = kwargs[input_name] elif input_def.has_default_value: input_dict[input_name] = input_def.default_value else: raise DagsterInvalidInvocationError( f'No value provided for required input "{input_name}".' ) unassigned_kwargs = {k: v for k, v in kwargs.items() if k not in input_dict} # If there are unassigned inputs, then they may be intended for use with a variadic keyword argument. if unassigned_kwargs and cast("DecoratedOpFunction", op_def.compute_fn).has_var_kwargs(): input_dict.update(unassigned_kwargs) # Type check inputs op_label = context.per_invocation_properties.step_description for input_name, val in input_dict.items(): input_def = input_defs_by_name[input_name] dagster_type = input_def.dagster_type type_check = do_type_check(context.for_type(dagster_type), dagster_type, val) if not type_check.success: raise DagsterTypeCheckDidNotPass( description=( f'Type check failed for {op_label} input "{input_def.name}" - ' f'expected type "{dagster_type.display_name}". ' f"Description: {type_check.description}" ), metadata=type_check.metadata, dagster_type=dagster_type, ) return input_dict def _key_for_result(result: AssetResult, context: "BaseDirectExecutionContext") -> AssetKey: if not context.per_invocation_properties.assets_def: raise DagsterInvariantViolationError( f"Op {context.per_invocation_properties.alias} does not have an assets definition." ) if result.asset_key: return result.asset_key if ( context.per_invocation_properties.assets_def and len(context.per_invocation_properties.assets_def.keys) == 1 ): return next(iter(context.per_invocation_properties.assets_def.keys)) raise DagsterInvariantViolationError( f"{result.__class__.__name__} did not include asset_key and it can not be inferred. Specify which" f" asset_key, options are: {context.per_invocation_properties.assets_def.keys}" ) def _output_name_for_result_obj( event: Union[AssetResult, AssetCheckResult], context: "BaseDirectExecutionContext", ): if not context.per_invocation_properties.assets_def: raise DagsterInvariantViolationError( f"Op {context.per_invocation_properties.alias} does not have an assets definition." ) if isinstance(event, AssetResult): asset_key = _key_for_result(event, context) return context.per_invocation_properties.assets_def.get_output_name_for_asset_key(asset_key) elif isinstance(event, AssetCheckResult): check_names_by_asset_key = {} for spec in context.per_invocation_properties.assets_def.check_specs: if spec.asset_key not in check_names_by_asset_key: check_names_by_asset_key[spec.asset_key] = [] check_names_by_asset_key[spec.asset_key].append(spec.name) return context.per_invocation_properties.assets_def.get_output_name_for_asset_check_key( event.resolve_target_check_key(check_names_by_asset_key) ) def _handle_gen_event( event: T, op_def: "OpDefinition", context: "BaseDirectExecutionContext", output_defs: Mapping[str, OutputDefinition], outputs_seen: set[str], ) -> T: if isinstance( event, (AssetMaterialization, AssetObservation, ExpectationResult), ): return event elif isinstance(event, (AssetResult, AssetCheckResult)): output_name = _output_name_for_result_obj(event, context) outputs_seen.add(output_name) return event else: if not isinstance(event, (Output, DynamicOutput)): raise DagsterInvariantViolationError( f"When yielding outputs from a {op_def.node_type_str} generator," " they should be wrapped in an `Output` object." ) else: output_def = output_defs[event.output_name] _type_check_output(output_def, event, context) if output_def.name in outputs_seen and not isinstance( output_def, DynamicOutputDefinition ): raise DagsterInvariantViolationError( f"Invocation of {op_def.node_type_str} '{context.per_invocation_properties.alias}' yielded" f" an output '{output_def.name}' multiple times." ) outputs_seen.add(output_def.name) return event def _type_check_output_wrapper( op_def: "OpDefinition", result: Any, context: "BaseDirectExecutionContext" ) -> Any: """Type checks and returns the result of a op. If the op result is itself a generator, then wrap in a fxn that will type check and yield outputs. """ output_defs = {output_def.name: output_def for output_def in op_def.output_defs} # Async generator case if inspect.isasyncgen(result): async def to_gen(async_gen): outputs_seen = set() try: # if the compute function fails, we want to ensure we unbind the context. For # async generators, the errors will only be surfaced here async for event in async_gen: yield _handle_gen_event(event, op_def, context, output_defs, outputs_seen) except Exception: context.unbind() raise for output_def in op_def.output_defs: if ( output_def.name not in outputs_seen and output_def.is_required and not output_def.is_dynamic ): # We require explicitly returned/yielded for asset observations assets_def = context.per_invocation_properties.assets_def is_observable_asset = assets_def is not None and assets_def.is_observable if output_def.dagster_type.is_nothing and not is_observable_asset: # implicitly yield None as we do in execute_step yield Output(output_name=output_def.name, value=None) else: raise DagsterInvariantViolationError( f"Invocation of {op_def.node_type_str} '{context.per_invocation_properties.alias}' did not" f" return an output for non-optional output '{output_def.name}'" ) context.unbind() return to_gen(result) # Coroutine result case elif inspect.iscoroutine(result): async def type_check_coroutine(coro): try: # if the compute function fails, we want to ensure we unbind the context. For # async, the errors will only be surfaced here out = await coro except Exception: context.unbind() raise return _type_check_function_output(op_def, out, context) return type_check_coroutine(result) # Regular generator case elif inspect.isgenerator(result): def type_check_gen(gen): outputs_seen = set() try: # if the compute function fails, we want to ensure we unbind the context. For # generators, the errors will only be surfaced here for event in gen: yield _handle_gen_event(event, op_def, context, output_defs, outputs_seen) except Exception: context.unbind() raise for output_def in op_def.output_defs: if ( output_def.name not in outputs_seen and output_def.is_required and not output_def.is_dynamic ): # We require explicitly returned/yielded for asset observations assets_def = context.per_invocation_properties.assets_def is_observable_asset = assets_def is not None and assets_def.is_observable if output_def.dagster_type.is_nothing and not is_observable_asset: # implicitly yield None as we do in execute_step yield Output(output_name=output_def.name, value=None) else: raise DagsterInvariantViolationError( f'Invocation of {op_def.node_type_str} "{context.per_invocation_properties.alias}" did not' f' return an output for non-optional output "{output_def.name}"' ) context.unbind() return type_check_gen(result) # Non-generator case return _type_check_function_output(op_def, result, context) def _type_check_function_output( op_def: "OpDefinition", result: T, context: "BaseDirectExecutionContext" ) -> T: from dagster._core.execution.plan.compute_generator import ( validate_and_coerce_op_result_to_iterator, ) output_defs_by_name = {output_def.name: output_def for output_def in op_def.output_defs} op_context = _get_op_context(context) for event in validate_and_coerce_op_result_to_iterator(result, op_context, op_def.output_defs): if isinstance(event, (Output, DynamicOutput)): _type_check_output(output_defs_by_name[event.output_name], event, context) elif isinstance(event, AssetResult): # ensure result objects are contextually valid _output_name_for_result_obj(event, context) context.unbind() return result def _type_check_output( output_def: "OutputDefinition", output: Union[Output, DynamicOutput], context: "BaseDirectExecutionContext", ) -> None: """Validates and performs core type check on a provided output. Args: output_def (OutputDefinition): The output definition to validate against. output (Any): The output to validate. context (BaseDirectExecutionContext): Context containing resources to be used for type check. """ from dagster._core.execution.plan.execute_step import do_type_check op_label = context.per_invocation_properties.step_description dagster_type = output_def.dagster_type type_check = do_type_check(context.for_type(dagster_type), dagster_type, output.value) if not type_check.success: raise DagsterTypeCheckDidNotPass( description=( f'Type check failed for {op_label} output "{output.output_name}" - ' f'expected type "{dagster_type.display_name}". ' f"Description: {type_check.description}" ), metadata=type_check.metadata, dagster_type=dagster_type, ) context.observe_output( output_def.name, output.mapping_key if isinstance(output, DynamicOutput) else None )
SeparatedArgsKwargs
python
huggingface__transformers
src/transformers/models/speech_to_text/configuration_speech_to_text.py
{ "start": 788, "end": 9825 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Speech2TextModel`]. It is used to instantiate a Speech2Text model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the Speech2Text [facebook/s2t-small-librispeech-asr](https://huggingface.co/facebook/s2t-small-librispeech-asr) architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: vocab_size (`int`, *optional*, defaults to 10000): Vocabulary size of the Speech2Text model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`Speech2TextModel`] encoder_layers (`int`, *optional*, defaults to 12): Number of encoder layers. encoder_ffn_dim (`int`, *optional*, defaults to 2048): Dimensionality of the "intermediate" (often named feed-forward) layer in encoder. encoder_attention_heads (`int`, *optional*, defaults to 4): Number of attention heads for each attention layer in the Transformer encoder. decoder_layers (`int`, *optional*, defaults to 6): Number of decoder layers. decoder_ffn_dim (`int`, *optional*, defaults to 2048): Dimensionality of the "intermediate" (often named feed-forward) layer in decoder. decoder_attention_heads (`int`, *optional*, defaults to 4): Number of attention heads for each attention layer in the Transformer decoder. encoder_layerdrop (`float`, *optional*, defaults to 0.0): The LayerDrop probability for the encoder. See the [LayerDrop paper](https://huggingface.co/papers/1909.11556) for more details. decoder_layerdrop (`float`, *optional*, defaults to 0.0): The LayerDrop probability for the decoder. See the [LayerDrop paper](https://huggingface.co/papers/1909.11556) for more details. use_cache (`bool`, *optional*, defaults to `True`): Whether the model should return the last key/values attentions (not used by all models). is_encoder_decoder (`bool`, *optional*, defaults to `True`): Whether the model is set up as an encoder-decoder architecture for sequence-to-sequence tasks. activation_function (`str` or `function`, *optional*, defaults to `"relu"`): The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"silu"` and `"gelu_new"` are supported. d_model (`int`, *optional*, defaults to 256): Dimensionality of the layers and the pooler layer. dropout (`float`, *optional*, defaults to 0.1): The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities. activation_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for activations inside the fully connected layer. init_std (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. decoder_start_token_id (`int`, *optional*, defaults to 2): The initial token ID of the decoder when decoding sequences. scale_embedding (`bool`, *optional*, defaults to `True`): Whether the embeddings are scaled by the square root of `d_model`. pad_token_id (`int`, *optional*, defaults to 1): Padding token id. bos_token_id (`int`, *optional*, defaults to 0): The id of the beginning-of-sequence token. eos_token_id (`int`, *optional*, defaults to 2): The id of the end-of-sequence token. max_source_positions (`int`, *optional*, defaults to 6000): The maximum sequence length of log-mel filter-bank features that this model might ever be used with. max_target_positions (`int`, *optional*, defaults to 1024): The maximum sequence length that this model might ever be used with. Typically, set this to something large just in case (e.g., 512 or 1024 or 2048). num_conv_layers (`int`, *optional*, defaults to 2): Number of 1D convolutional layers in the conv module. conv_kernel_sizes (`tuple[int]`, *optional*, defaults to `(5, 5)`): A tuple of integers defining the kernel size of each 1D convolutional layer in the conv module. The length of `conv_kernel_sizes` has to match `num_conv_layers`. conv_channels (`int`, *optional*, defaults to 1024): An integer defining the number of output channels of each convolution layers except the final one in the conv module. input_feat_per_channel (`int`, *optional*, defaults to 80): An integer specifying the size of feature vector. This is also the dimensions of log-mel filter-bank features. input_channels (`int`, *optional*, defaults to 1): An integer specifying number of input channels of the input feature vector. Example: ```python >>> from transformers import Speech2TextConfig, Speech2TextModel >>> # Initializing a Speech2Text s2t_transformer_s style configuration >>> configuration = Speech2TextConfig() >>> # Initializing a model (with random weights) from the s2t_transformer_s style configuration >>> model = Speech2TextModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "speech_to_text" keys_to_ignore_at_inference = ["past_key_values"] attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self, vocab_size=10000, encoder_layers=12, encoder_ffn_dim=2048, encoder_attention_heads=4, decoder_layers=6, decoder_ffn_dim=2048, decoder_attention_heads=4, encoder_layerdrop=0.0, decoder_layerdrop=0.0, use_cache=True, is_encoder_decoder=True, activation_function="relu", d_model=256, dropout=0.1, attention_dropout=0.0, activation_dropout=0.0, init_std=0.02, decoder_start_token_id=2, scale_embedding=True, pad_token_id=1, bos_token_id=0, eos_token_id=2, max_source_positions=6000, max_target_positions=1024, num_conv_layers=2, conv_kernel_sizes=(5, 5), conv_channels=1024, input_feat_per_channel=80, input_channels=1, **kwargs, ): self.vocab_size = vocab_size self.d_model = d_model self.encoder_ffn_dim = encoder_ffn_dim self.encoder_layers = encoder_layers self.encoder_attention_heads = encoder_attention_heads self.decoder_ffn_dim = decoder_ffn_dim self.decoder_layers = decoder_layers self.decoder_attention_heads = decoder_attention_heads self.dropout = dropout self.attention_dropout = attention_dropout self.activation_dropout = activation_dropout self.activation_function = activation_function self.init_std = init_std self.encoder_layerdrop = encoder_layerdrop self.decoder_layerdrop = decoder_layerdrop self.use_cache = use_cache self.num_hidden_layers = encoder_layers self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True self.max_source_positions = max_source_positions self.max_target_positions = max_target_positions self.num_conv_layers = num_conv_layers self.conv_kernel_sizes = list(conv_kernel_sizes) self.conv_channels = conv_channels self.input_feat_per_channel = input_feat_per_channel self.input_channels = input_channels if len(self.conv_kernel_sizes) != self.num_conv_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.conv_kernel_sizes)` == `config.num_conv_layers` " f"but is `len(config.conv_kernel_sizes) = {len(self.conv_kernel_sizes)}`, " f"`config.num_conv_layers = {self.num_conv_layers}`." ) super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, is_encoder_decoder=is_encoder_decoder, decoder_start_token_id=decoder_start_token_id, **kwargs, ) __all__ = ["Speech2TextConfig"]
Speech2TextConfig
python
pytorch__pytorch
test/torch_np/numpy_tests/lib/test_function_base.py
{ "start": 3104, "end": 5158 }
class ____(TestCase): def test_basic(self): assert_raises(ValueError, np.rot90, np.ones(4)) assert_raises( (ValueError, RuntimeError), np.rot90, np.ones((2, 2, 2)), axes=(0, 1, 2) ) assert_raises(ValueError, np.rot90, np.ones((2, 2)), axes=(0, 2)) assert_raises(ValueError, np.rot90, np.ones((2, 2)), axes=(1, 1)) assert_raises(ValueError, np.rot90, np.ones((2, 2, 2)), axes=(-2, 1)) a = [[0, 1, 2], [3, 4, 5]] b1 = [[2, 5], [1, 4], [0, 3]] b2 = [[5, 4, 3], [2, 1, 0]] b3 = [[3, 0], [4, 1], [5, 2]] b4 = [[0, 1, 2], [3, 4, 5]] for k in range(-3, 13, 4): assert_equal(np.rot90(a, k=k), b1) for k in range(-2, 13, 4): assert_equal(np.rot90(a, k=k), b2) for k in range(-1, 13, 4): assert_equal(np.rot90(a, k=k), b3) for k in range(0, 13, 4): assert_equal(np.rot90(a, k=k), b4) assert_equal(np.rot90(np.rot90(a, axes=(0, 1)), axes=(1, 0)), a) assert_equal(np.rot90(a, k=1, axes=(1, 0)), np.rot90(a, k=-1, axes=(0, 1))) def test_axes(self): a = np.ones((50, 40, 3)) assert_equal(np.rot90(a).shape, (40, 50, 3)) assert_equal(np.rot90(a, axes=(0, 2)), np.rot90(a, axes=(0, -1))) assert_equal(np.rot90(a, axes=(1, 2)), np.rot90(a, axes=(-2, -1))) def test_rotation_axes(self): a = np.arange(8).reshape((2, 2, 2)) a_rot90_01 = [[[2, 3], [6, 7]], [[0, 1], [4, 5]]] a_rot90_12 = [[[1, 3], [0, 2]], [[5, 7], [4, 6]]] a_rot90_20 = [[[4, 0], [6, 2]], [[5, 1], [7, 3]]] a_rot90_10 = [[[4, 5], [0, 1]], [[6, 7], [2, 3]]] assert_equal(np.rot90(a, axes=(0, 1)), a_rot90_01) assert_equal(np.rot90(a, axes=(1, 0)), a_rot90_10) assert_equal(np.rot90(a, axes=(1, 2)), a_rot90_12) for k in range(1, 5): assert_equal( np.rot90(a, k=k, axes=(2, 0)), np.rot90(a_rot90_20, k=k - 1, axes=(2, 0)), )
TestRot90
python
getsentry__sentry
src/sentry/notifications/notifications/activity/assigned.py
{ "start": 1815, "end": 2673 }
class ____(GroupActivityNotification): metrics_key = "assigned_activity" title = "Assigned" def get_assignee(self) -> str: return get_assignee_str(self.activity, self.organization) def get_description(self) -> tuple[str, str | None, Mapping[str, Any]]: return "{author} assigned {an issue} to {assignee}", None, {"assignee": self.get_assignee()} def get_notification_title( self, provider: ExternalProviders, context: Mapping[str, Any] | None = None ) -> str: assignee = self.get_assignee() if not self.user: return f"Issue automatically assigned to {assignee}" author = self.user.get_display_name() if assignee == "themselves": author, assignee = assignee, author return f"Issue assigned to {assignee} by {author}"
AssignedActivityNotification
python
rapidsai__cudf
python/cudf/cudf/core/column/timedelta.py
{ "start": 1353, "end": 13792 }
class ____(TemporalBaseColumn): _NP_SCALAR = np.timedelta64 _PD_SCALAR = pd.Timedelta _VALID_BINARY_OPERATIONS = { "__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__", "__add__", "__sub__", "__mul__", "__mod__", "__truediv__", "__floordiv__", "__radd__", "__rsub__", "__rmul__", "__rmod__", "__rtruediv__", "__rfloordiv__", } _VALID_PLC_TYPES = { plc.TypeId.DURATION_SECONDS, plc.TypeId.DURATION_MILLISECONDS, plc.TypeId.DURATION_MICROSECONDS, plc.TypeId.DURATION_NANOSECONDS, } def __init__( self, plc_column: plc.Column, size: int, dtype: np.dtype, offset: int, null_count: int, exposed: bool, ) -> None: if cudf.get_option("mode.pandas_compatible"): if not dtype.kind == "m": raise ValueError("dtype must be a timedelta numpy dtype.") elif not (isinstance(dtype, np.dtype) and dtype.kind == "m"): raise ValueError("dtype must be a timedelta numpy dtype.") super().__init__( plc_column=plc_column, size=size, dtype=dtype, offset=offset, null_count=null_count, exposed=exposed, ) def _clear_cache(self) -> None: super()._clear_cache() attrs = ( "days", "seconds", "microseconds", "nanoseconds", "time_unit", ) for attr in attrs: try: delattr(self, attr) except AttributeError: pass def __contains__(self, item: DatetimeLikeScalar) -> bool: try: # call-overload must be ignored because numpy stubs only accept literal # time unit strings, but we're passing self.time_unit which is valid at runtime item = self._NP_SCALAR(item, self.time_unit) # type: ignore[call-overload] except ValueError: # If item cannot be converted to duration type # np.timedelta64 raises ValueError, hence `item` # cannot exist in `self`. return False return super().__contains__(item.to_numpy()) def _binaryop(self, other: ColumnBinaryOperand, op: str) -> ColumnBase: reflect, op = self._check_reflected_op(op) other = self._normalize_binop_operand(other) if other is NotImplemented: return NotImplemented this: ColumnBinaryOperand = self out_dtype = None other_cudf_dtype = ( cudf_dtype_from_pa_type(other.type) if isinstance(other, pa.Scalar) else other.dtype ) if other_cudf_dtype.kind == "m": # TODO: pandas will allow these operators to work but return false # when comparing to non-timedelta dtypes. We should do the same. if op in { "__eq__", "__ne__", "__lt__", "__gt__", "__le__", "__ge__", "NULL_EQUALS", "NULL_NOT_EQUALS", }: out_dtype = get_dtype_of_same_kind( self.dtype, np.dtype(np.bool_) ) elif op == "__mod__": out_dtype = find_common_type((self.dtype, other_cudf_dtype)) elif op in {"__truediv__", "__floordiv__"}: common_dtype = find_common_type((self.dtype, other_cudf_dtype)) out_dtype = ( get_dtype_of_same_kind(self.dtype, np.dtype(np.float64)) if op == "__truediv__" else self._UNDERLYING_DTYPE ) this = self.astype(common_dtype).astype(out_dtype) if isinstance(other, pa.Scalar): if other.is_valid: # pyarrow.cast doesn't support casting duration to float # so go through numpy other_np = pa.array([other]).to_numpy( zero_copy_only=False ) other_np = other_np.astype(common_dtype).astype( out_dtype ) other = pa.array(other_np)[0] else: other = pa.scalar( None, type=cudf_dtype_to_pa_type(out_dtype) ) else: other = other.astype(common_dtype).astype(out_dtype) elif op in {"__add__", "__sub__"}: out_dtype = find_common_type((self.dtype, other_cudf_dtype)) elif other_cudf_dtype.kind in {"f", "i", "u"}: if op in {"__mul__", "__mod__", "__truediv__", "__floordiv__"}: out_dtype = self.dtype elif op in {"__eq__", "__ne__", "NULL_EQUALS", "NULL_NOT_EQUALS"}: if isinstance(other, ColumnBase) and not isinstance( other, TimeDeltaColumn ): fill_value = op in ("__ne__", "NULL_NOT_EQUALS") result = self._all_bools_with_nulls( other, bool_fill_value=fill_value, ) if cudf.get_option("mode.pandas_compatible"): result = result.fillna(fill_value) return result if out_dtype is None: return NotImplemented elif isinstance(other, pa.Scalar): other = pa_scalar_to_plc_scalar(other) lhs, rhs = (other, this) if reflect else (this, other) result = binaryop.binaryop(lhs, rhs, op, out_dtype) if ( cudf.get_option("mode.pandas_compatible") and out_dtype.kind == "b" and not is_pandas_nullable_extension_dtype(out_dtype) ): result = result.fillna(op == "__ne__") return result def _scan(self, op: str) -> ColumnBase: if op == "cumprod": raise TypeError("cumprod not supported for Timedelta.") return self.scan(op.replace("cum", ""), True)._with_type_metadata( self.dtype ) def total_seconds(self) -> ColumnBase: conversion = unit_to_nanoseconds_conversion[self.time_unit] / 1e9 # Typecast to decimal128 to avoid floating point precision issues # https://github.com/rapidsai/cudf/issues/17664 return ( (self.astype(self._UNDERLYING_DTYPE) * conversion) .astype( cudf.Decimal128Dtype(cudf.Decimal128Dtype.MAX_PRECISION, 9) ) .round(decimals=abs(int(math.log10(conversion)))) .astype(np.dtype(np.float64)) ) def as_datetime_column(self, dtype: np.dtype) -> None: # type: ignore[override] raise TypeError( f"cannot astype a timedelta from {self.dtype} to {dtype}" ) def strftime(self, format: str) -> StringColumn: if len(self) == 0: return super().strftime(format) else: with acquire_spill_lock(): return type(self).from_pylibcudf( # type: ignore[return-value] plc.strings.convert.convert_durations.from_durations( self.plc_column, format ) ) def as_string_column(self, dtype: DtypeObj) -> StringColumn: if cudf.get_option("mode.pandas_compatible"): if isinstance(dtype, np.dtype) and dtype.kind == "O": raise MixedTypeError( f"cannot astype a timedelta like from {self.dtype} to {dtype}" ) return self.strftime("%D days %H:%M:%S") def as_timedelta_column(self, dtype: np.dtype) -> TimeDeltaColumn: if dtype == self.dtype: return self return self.cast(dtype=dtype) # type: ignore[return-value] def sum( self, skipna: bool = True, min_count: int = 0, ) -> pd.Timedelta: return self._PD_SCALAR( # Since sum isn't overridden in Numerical[Base]Column, mypy only # sees the signature from Reducible (which doesn't have the extra # parameters from ColumnBase._reduce) so we have to ignore this. self.astype(self._UNDERLYING_DTYPE).sum( # type: ignore[call-arg] skipna=skipna, min_count=min_count ), unit=self.time_unit, ).as_unit(self.time_unit) @functools.cached_property def components(self) -> dict[str, NumericalColumn]: """ Return a dict of the components of the Timedeltas. Returns ------- dict[str, NumericalColumn] """ date_meta = { "hours": ["D", "h"], "minutes": ["h", "m"], "seconds": ["m", "s"], "milliseconds": ["s", "ms"], "microseconds": ["ms", "us"], "nanoseconds": ["us", "ns"], } data = {"days": self.days} reached_self_unit = False for result_key, (mod_unit, div_unit) in date_meta.items(): if not reached_self_unit: res_col = ( self % get_np_td_unit_conversion(mod_unit, self.dtype) ) // get_np_td_unit_conversion(div_unit, self.dtype) reached_self_unit = self.time_unit == div_unit else: res_col = as_column( 0, length=len(self), dtype=self._UNDERLYING_DTYPE ) if self.nullable: res_col = res_col.set_mask(self.mask) data[result_key] = res_col return data @functools.cached_property def days(self) -> NumericalColumn: """ Number of days for each element. Returns ------- NumericalColumn """ return self // get_np_td_unit_conversion("D", self.dtype) @functools.cached_property def seconds(self) -> NumericalColumn: """ Number of seconds (>= 0 and less than 1 day). Returns ------- NumericalColumn """ # This property must return the number of seconds (>= 0 and # less than 1 day) for each element, hence first performing # mod operation to remove the number of days and then performing # division operation to extract the number of seconds. return ( self % get_np_td_unit_conversion("D", self.dtype) ) // get_np_td_unit_conversion("s", None) @functools.cached_property def microseconds(self) -> NumericalColumn: """ Number of microseconds (>= 0 and less than 1 second). Returns ------- NumericalColumn """ # This property must return the number of microseconds (>= 0 and # less than 1 second) for each element, hence first performing # mod operation to remove the number of seconds and then performing # division operation to extract the number of microseconds. return ( self % get_np_td_unit_conversion("s", self.dtype) ) // get_np_td_unit_conversion("us", None) @functools.cached_property def nanoseconds(self) -> NumericalColumn: """ Return the number of nanoseconds (n), where 0 <= n < 1 microsecond. Returns ------- NumericalColumn """ # This property must return the number of nanoseconds (>= 0 and # less than 1 microsecond) for each element, hence first performing # mod operation to remove the number of microseconds and then # performing division operation to extract the number # of nanoseconds. if self.time_unit != "ns": res_col = as_column( 0, length=len(self), dtype=self._UNDERLYING_DTYPE ) if self.nullable: res_col = res_col.set_mask(self.mask) return cast("cudf.core.column.NumericalColumn", res_col) return ( self % get_np_td_unit_conversion("us", None) ) // get_np_td_unit_conversion("ns", None)
TimeDeltaColumn
python
python__mypy
mypyc/irbuild/nonlocalcontrol.py
{ "start": 1525, "end": 1988 }
class ____(NonlocalControl): """Default nonlocal control outside any statements that affect it.""" def gen_break(self, builder: IRBuilder, line: int) -> None: assert False, "break outside of loop" def gen_continue(self, builder: IRBuilder, line: int) -> None: assert False, "continue outside of loop" def gen_return(self, builder: IRBuilder, value: Value, line: int) -> None: builder.add(Return(value))
BaseNonlocalControl
python
huggingface__transformers
src/transformers/models/dab_detr/modeling_dab_detr.py
{ "start": 29378, "end": 30636 }
class ____(nn.Module): def __init__(self, config: DabDetrConfig): super().__init__() hidden_size = config.hidden_size self.final_layer_norm = nn.LayerNorm(hidden_size) self.fc1 = nn.Linear(hidden_size, config.decoder_ffn_dim) self.fc2 = nn.Linear(config.decoder_ffn_dim, hidden_size) self.activation_fn = ACT2FN[config.activation_function] self.dropout = config.dropout self.activation_dropout = config.activation_dropout self.keep_query_pos = config.keep_query_pos def forward(self, hidden_states: torch.Tensor): residual = hidden_states hidden_states = self.activation_fn(self.fc1(hidden_states)) hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training) hidden_states = self.fc2(hidden_states) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states hidden_states = self.final_layer_norm(hidden_states) return hidden_states # Modified from transformers.models.detr.modeling_detr.DetrEncoderLayer with DetrEncoderLayer->DabDetrEncoderLayer,DetrConfig->DabDetrConfig
DabDetrDecoderLayerFFN
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/assertsql.py
{ "start": 13850, "end": 14179 }
class ____(AllOf): def process_statement(self, execute_observed): for rule in self.rules: rule.process_statement(execute_observed) if rule.is_consumed: self.is_consumed = True break else: self.errormessage = list(self.rules)[0].errormessage
Or
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/models/secrets.py
{ "start": 1088, "end": 2644 }
class ____(SecretStore): def __init__(self, gcp_credentials: Secret) -> None: service_account_info = json.loads(gcp_credentials.value) credentials = service_account.Credentials.from_service_account_info(service_account_info) self.gsm_client = secretmanager_v1.SecretManagerServiceClient.from_service_account_info(service_account_info) # This assumes the service account can only read a single project: the one it was created on. # If we want to read secrets from multiple project we'd have to create a secret mapping (in an env var?) # Which would map secret store aliases to project ids. self.project_id = credentials.project_id def _fetch_secret(self, name: str) -> str: request = secretmanager_v1.ListSecretVersionsRequest( parent=f"projects/{self.project_id}/secrets/{name}", ) secret_versions = self.gsm_client.list_secret_versions(request=request) if not secret_versions: raise SecretNotFoundError(f"No secret found in GSM for secret {name}") for version in secret_versions: # 1 means enabled version if version.state == 1: request = secretmanager_v1.AccessSecretVersionRequest( name=version.name, ) response = self.gsm_client.access_secret_version(request=request) return response.payload.data.decode() raise SecretNotFoundError(f"No enabled secret version in GSM found for secret {name}")
GSMSecretStore
python
buildout__buildout
src/zc/buildout/buildout.py
{ "start": 8990, "end": 59017 }
class ____(DictMixin): COMMANDS = set() def __init__(self, config_file, cloptions, use_user_defaults=True, command=None, args=()): __doing__ = 'Initializing.' # default options _buildout_default_options_copy = copy.deepcopy( _buildout_default_options) data = dict(buildout=_buildout_default_options_copy) self._buildout_dir = os.getcwd() if config_file and not _isurl(config_file): config_file = os.path.abspath(config_file) if not os.path.exists(config_file): if command == 'init': self._init_config(config_file, args) elif command == 'setup': # Sigh. This model of a buildout instance # with methods is breaking down. :( config_file = None data['buildout']['directory'] = SectionKey( '.', 'COMPUTED_VALUE') else: raise zc.buildout.UserError( "Couldn't open %s" % config_file) elif command == 'init': raise zc.buildout.UserError( "%r already exists." % config_file) if config_file: data['buildout']['directory'] = SectionKey( os.path.dirname(config_file), 'COMPUTED_VALUE') cloptions = dict( (section, dict((option, SectionKey(value, 'COMMAND_LINE_VALUE')) for (_, option, value) in v)) for (section, v) in itertools.groupby(sorted(cloptions), lambda v: v[0]) ) override = copy.deepcopy(cloptions.get('buildout', {})) # load user defaults, which override defaults user_config = _get_user_config() if use_user_defaults and os.path.exists(user_config): download_options = data['buildout'] user_defaults, _ = _open( os.path.dirname(user_config), user_config, [], download_options, override, set(), {} ) for_download_options = _update(data, user_defaults) else: user_defaults = {} for_download_options = copy.deepcopy(data) # load configuration files if config_file: download_options = for_download_options['buildout'] cfg_data, _ = _open( os.path.dirname(config_file), config_file, [], download_options, override, set(), user_defaults ) data = _update(data, cfg_data) # extends from command-line if 'buildout' in cloptions: cl_extends = cloptions['buildout'].pop('extends', None) if cl_extends: for extends in cl_extends.value.split(): download_options = for_download_options['buildout'] cfg_data, _ = _open( os.path.dirname(extends), os.path.basename(extends), [], download_options, override, set(), user_defaults ) data = _update(data, cfg_data) # apply command-line options data = _update(data, cloptions) # Set up versions section, if necessary if 'versions' not in data['buildout']: data['buildout']['versions'] = SectionKey( 'versions', 'DEFAULT_VALUE') if 'versions' not in data: data['versions'] = {} # Default versions: versions_section_name = data['buildout']['versions'].value if versions_section_name: versions = data[versions_section_name] else: versions = {} if 'zc.buildout' not in versions: # Prevent downgrading of zc.buildout itself due to prefer-final. ws = pkg_resources.working_set dist = ws.find( pkg_resources.Requirement.parse('zc-buildout') ) if dist is None: # older setuptools dist = ws.find( pkg_resources.Requirement.parse('zc.buildout') ) if dist is None: # This would be really strange, but I prefer an explicit # failure here over an unclear error later. raise ValueError( "Could not find distribution for zc.buildout in working set." ) minimum = dist.version versions['zc.buildout'] = SectionKey(f'>={minimum}', 'DEFAULT_VALUE') if 'zc.recipe.egg' not in versions: # zc.buildout and zc.recipe egg are closely linked, but zc.buildout # does NOT depend on it: we do not want to add it to our # install_requires. (One could debate why, although one answer # would be to avoid a circular dependency. Maybe we could merge them, # as I see no use case for Buildout without recipes. But we would # need to update the zc.recipe.egg test setup first.) # # Anyway: we use a different way to set a minimum version. # Originally (in 2013, zc.buildout 2.0.0b1) we made sure # zc.recipe.egg>=2.0.0a3 was pinned, mostly to avoid problems # when prefer-final is true. # Later (in 2018, zc.buildout 2.12.1) we updated the minimum version # to 2.0.6, to avoid a KeyError: 'allow-unknown-extras'. # See https://github.com/buildout/buildout/pull/461 # I wonder if we really need a minimum version, as older versions # are unlikely to even be installable by supported Python versions. # But if we ever really need a more recent minimum version, # it is easy to update a version here. versions['zc.recipe.egg'] = SectionKey('>=2.0.6', 'DEFAULT_VALUE') # Absolutize some particular directory, handling also the ~/foo form, # and considering the location of the configuration file that generated # the setting as the base path, falling back to the main configuration # file location for name in ('download-cache', 'eggs-directory', 'extends-cache'): if name in data['buildout']: sectionkey = data['buildout'][name] origdir = sectionkey.value src = sectionkey.source if '${' in origdir: continue if not os.path.isabs(origdir): if src in ('DEFAULT_VALUE', 'COMPUTED_VALUE', 'COMMAND_LINE_VALUE'): if 'directory' in data['buildout']: basedir = data['buildout']['directory'].value else: basedir = self._buildout_dir else: if _isurl(src): raise zc.buildout.UserError( 'Setting "%s" to a non absolute location ("%s") ' 'within a\n' 'remote configuration file ("%s") is ambiguous.' % ( name, origdir, src)) basedir = os.path.dirname(src) absdir = os.path.expanduser(origdir) if not os.path.isabs(absdir): absdir = os.path.join(basedir, absdir) absdir = os.path.abspath(absdir) sectionkey.setDirectory(absdir) self._annotated = copy.deepcopy(data) self._raw = _unannotate(data) self._data = {} self._parts = [] # provide some defaults before options are parsed # because while parsing options those attributes might be # used already (Gottfried Ganssauge) buildout_section = self._raw['buildout'] # Try to make sure we have absolute paths for standard # directories. We do this before doing substitutions, in case # a one of these gets read by another section. If any # variable references are used though, we leave it as is in # _buildout_path. if 'directory' in buildout_section: self._buildout_dir = buildout_section['directory'] for name in ('bin', 'parts', 'eggs', 'develop-eggs'): d = self._buildout_path(buildout_section[name+'-directory']) buildout_section[name+'-directory'] = d # Attributes on this buildout object shouldn't be used by # recipes in their __init__. It can cause bugs, because the # recipes will be instantiated below (``options = self['buildout']``) # before this has completed initializing. These attributes are # left behind for legacy support but recipe authors should # beware of using them. A better practice is for a recipe to # use the buildout['buildout'] options. links = buildout_section['find-links'] self._links = links and links.split() or () allow_hosts = buildout_section['allow-hosts'].split('\n') self._allow_hosts = tuple([host.strip() for host in allow_hosts if host.strip() != '']) self._logger = logging.getLogger('zc.buildout') self.offline = bool_option(buildout_section, 'offline') self.newest = ((not self.offline) and bool_option(buildout_section, 'newest') ) ################################################################## ## WARNING!!! ## ALL ATTRIBUTES MUST HAVE REASONABLE DEFAULTS AT THIS POINT ## OTHERWISE ATTRIBUTEERRORS MIGHT HAPPEN ANY TIME FROM RECIPES. ## RECIPES SHOULD GENERALLY USE buildout['buildout'] OPTIONS, NOT ## BUILDOUT ATTRIBUTES. ################################################################## # initialize some attrs and buildout directories. options = self['buildout'] # now reinitialize links = options.get('find-links', '') self._links = links and links.split() or () allow_hosts = options['allow-hosts'].split('\n') self._allow_hosts = tuple([host.strip() for host in allow_hosts if host.strip() != '']) self._buildout_dir = options['directory'] # Make sure we have absolute paths for standard directories. We do this # a second time here in case someone overrode these in their configs. for name in ('bin', 'parts', 'eggs', 'develop-eggs'): d = self._buildout_path(options[name+'-directory']) options[name+'-directory'] = d if options['installed']: options['installed'] = os.path.join(options['directory'], options['installed']) self._setup_logging() self._setup_socket_timeout() # finish w versions if versions_section_name: # refetching section name just to avoid a warning versions = self[versions_section_name] else: # remove annotations versions = dict((k, v.value) for (k, v) in versions.items()) options['versions'] # refetching section name just to avoid a warning self.versions = versions zc.buildout.easy_install.default_versions(versions) zc.buildout.easy_install.prefer_final( bool_option(options, 'prefer-final')) zc.buildout.easy_install.use_dependency_links( bool_option(options, 'use-dependency-links')) zc.buildout.easy_install.index_url(options.get('index', '').strip()) zc.buildout.easy_install.allow_picked_versions( bool_option(options, 'allow-picked-versions')) self.show_picked_versions = bool_option(options, 'show-picked-versions') self.update_versions_file = options['update-versions-file'] zc.buildout.easy_install.store_required_by(self.show_picked_versions or self.update_versions_file) download_cache = options.get('download-cache') extends_cache = options.get('extends-cache') # Since zc.buildout version 5 we maintain separate directories for each # buildout eggs format version. Current idea: we use v5 from zc.buildout # 5.x onwards. Later versions will likely also use v5, as the current # expectation is that they will be compatible, just like zc.buildout # 1.x through 4.x are compatible. # If you know what you are doing, you can set eggs-directory-version to # an empty string. This can be fine if you don't have any previous eggs # and only use zc.buildout 5 or later. It should also be fine in case # you don't use any namespace packages; but you would be wrong, because # you are using zc.buildout and probably zc.recipe.egg, so you use the # zc namespace. Still, if those are the only two packages, it might # possibly work. if options['eggs-directory-version']: options['eggs-directory'] = os.path.join( options['eggs-directory'], options['eggs-directory-version']) if bool_option(options, 'abi-tag-eggs', 'false'): from zc.buildout.pep425tags import get_abi_tag options['eggs-directory'] = os.path.join( options['eggs-directory'], get_abi_tag()) eggs_cache = options.get('eggs-directory') for cache in [download_cache, extends_cache, eggs_cache]: if cache: cache = os.path.join(options['directory'], cache) if not os.path.exists(cache): self._logger.info('Creating directory %r.', cache) os.makedirs(cache) if download_cache: # Actually, we want to use a subdirectory in there called 'dist'. download_cache = os.path.join(download_cache, 'dist') if not os.path.exists(download_cache): os.mkdir(download_cache) zc.buildout.easy_install.download_cache(download_cache) if bool_option(options, 'install-from-cache'): if self.offline: raise zc.buildout.UserError( "install-from-cache can't be used with offline mode.\n" "Nothing is installed, even from cache, in offline\n" "mode, which might better be called 'no-install mode'.\n" ) zc.buildout.easy_install.install_from_cache(True) # "Use" each of the defaults so they aren't reported as unused options. for name in _buildout_default_options: options[name] os.chdir(options['directory']) def _buildout_path(self, name): if '${' in name: return name return os.path.join(self._buildout_dir, name) @command def bootstrap(self, args): __doing__ = 'Bootstrapping.' if os.path.exists(self['buildout']['develop-eggs-directory']): if os.path.isdir(self['buildout']['develop-eggs-directory']): rmtree(self['buildout']['develop-eggs-directory']) self._logger.debug( "Removed existing develop-eggs directory") self._setup_directories() # Now copy buildout and setuptools eggs, and record destination eggs: entries = [] for dist in zc.buildout.easy_install.buildout_and_setuptools_dists: if dist.precedence == pkg_resources.DEVELOP_DIST: dest = os.path.join(self['buildout']['develop-eggs-directory'], dist.key + '.egg-link') with open(dest, 'w') as fh: fh.write(dist.location) entries.append(dist.location) else: dest = os.path.join(self['buildout']['eggs-directory'], os.path.basename(dist.location)) entries.append(dest) if not os.path.exists(dest): if os.path.isdir(dist.location): shutil.copytree(dist.location, dest) else: shutil.copy2(dist.location, dest) # Create buildout script ws = pkg_resources.WorkingSet(entries) ws.require('zc.buildout') options = self['buildout'] eggs_dir = options['eggs-directory'] develop_eggs_dir = options['develop-eggs-directory'] ws = zc.buildout.easy_install.sort_working_set( ws, eggs_dir=eggs_dir, develop_eggs_dir=develop_eggs_dir ) zc.buildout.easy_install.scripts( ['zc.buildout'], ws, sys.executable, options['bin-directory'], relative_paths = ( bool_option(options, 'relative-paths', False) and options['directory'] or ''), ) def _init_config(self, config_file, args): print_('Creating %r.' % config_file) f = open(config_file, 'w') sep = re.compile(r'[\\/]') if args: eggs = '\n '.join(a for a in args if not sep.search(a)) sepsub = os.path.sep == '/' and '/' or re.escape(os.path.sep) paths = '\n '.join( sep.sub(sepsub, a) for a in args if sep.search(a)) f.write('[buildout]\n' 'parts = py\n' '\n' '[py]\n' 'recipe = zc.recipe.egg\n' 'interpreter = py\n' 'eggs =\n' ) if eggs: f.write(' %s\n' % eggs) if paths: f.write('extra-paths =\n %s\n' % paths) for p in [a for a in args if sep.search(a)]: if not os.path.exists(p): os.mkdir(p) else: f.write('[buildout]\nparts =\n') f.close() @command def init(self, args): self.bootstrap(()) if args: self.install(()) @command def install(self, install_args): __doing__ = 'Installing.' self._load_extensions() self._setup_directories() # Add develop-eggs directory to path so that it gets searched # for eggs: sys.path.insert(0, self['buildout']['develop-eggs-directory']) # Check for updates. This could cause the process to be restarted self._maybe_upgrade() # load installed data (installed_part_options, installed_exists )= self._read_installed_part_options() # Remove old develop eggs self._uninstall( installed_part_options['buildout'].get( 'installed_develop_eggs', '') ) # Build develop eggs installed_develop_eggs = self._develop() installed_part_options['buildout']['installed_develop_eggs' ] = installed_develop_eggs if installed_exists: self._update_installed( installed_develop_eggs=installed_develop_eggs) # get configured and installed part lists conf_parts = self['buildout']['parts'] conf_parts = conf_parts and conf_parts.split() or [] installed_parts = installed_part_options['buildout']['parts'] installed_parts = installed_parts and installed_parts.split() or [] if install_args: install_parts = install_args uninstall_missing = False else: install_parts = conf_parts uninstall_missing = True # load and initialize recipes [self[part]['recipe'] for part in install_parts] if not install_args: install_parts = self._parts if self._log_level < logging.DEBUG: sections = list(self) sections.sort() print_() print_('Configuration data:') for section in sorted(self._data): _save_options(section, self[section], sys.stdout) print_() # compute new part recipe signatures self._compute_part_signatures(install_parts) # uninstall parts that are no-longer used or who's configs # have changed for part in reversed(installed_parts): if part in install_parts: old_options = installed_part_options[part].copy() installed_files = old_options.pop('__buildout_installed__') new_options = self.get(part) if old_options == new_options: # The options are the same, but are all of the # installed files still there? If not, we should # reinstall. if not installed_files: continue for f in installed_files.split('\n'): if not os.path.exists(self._buildout_path(f)): break else: continue # output debugging info if self._logger.getEffectiveLevel() < logging.DEBUG: for k in old_options: if k not in new_options: self._logger.debug("Part %s, dropped option %s.", part, k) elif old_options[k] != new_options[k]: self._logger.debug( "Part %s, option %s changed:\n%r != %r", part, k, new_options[k], old_options[k], ) for k in new_options: if k not in old_options: self._logger.debug("Part %s, new option %s.", part, k) elif not uninstall_missing: continue self._uninstall_part(part, installed_part_options) installed_parts = [p for p in installed_parts if p != part] if installed_exists: self._update_installed(parts=' '.join(installed_parts)) # Check for unused buildout options: _check_for_unused_options_in_section(self, 'buildout') # install new parts for part in install_parts: signature = self[part].pop('__buildout_signature__') saved_options = self[part].copy() recipe = self[part].recipe if part in installed_parts: # update need_to_save_installed = False __doing__ = 'Updating %s.', part self._logger.info(*__doing__) old_options = installed_part_options[part] old_installed_files = old_options['__buildout_installed__'] try: update = recipe.update except AttributeError: update = recipe.install self._logger.warning( "The recipe for %s doesn't define an update " "method. Using its install method.", part) try: installed_files = self[part]._call(update) except: installed_parts.remove(part) self._uninstall(old_installed_files) if installed_exists: self._update_installed( parts=' '.join(installed_parts)) raise old_installed_files = old_installed_files.split('\n') if installed_files is None: installed_files = old_installed_files else: if isinstance(installed_files, str): installed_files = [installed_files] else: installed_files = list(installed_files) need_to_save_installed = [ p for p in installed_files if p not in old_installed_files] if need_to_save_installed: installed_files = (old_installed_files + need_to_save_installed) else: # install need_to_save_installed = True __doing__ = 'Installing %s.', part self._logger.info(*__doing__) installed_files = self[part]._call(recipe.install) if installed_files is None: self._logger.warning( "The %s install returned None. A path or " "iterable os paths should be returned.", part) installed_files = () elif isinstance(installed_files, str): installed_files = [installed_files] else: installed_files = list(installed_files) installed_part_options[part] = saved_options saved_options['__buildout_installed__' ] = '\n'.join(installed_files) saved_options['__buildout_signature__'] = signature installed_parts = [p for p in installed_parts if p != part] installed_parts.append(part) _check_for_unused_options_in_section(self, part) if need_to_save_installed: installed_part_options['buildout']['parts'] = ( ' '.join(installed_parts)) self._save_installed_options(installed_part_options) installed_exists = True else: assert installed_exists self._update_installed(parts=' '.join(installed_parts)) if installed_develop_eggs: if not installed_exists: self._save_installed_options(installed_part_options) elif (not installed_parts) and installed_exists: os.remove(self['buildout']['installed']) if self.show_picked_versions or self.update_versions_file: self._print_picked_versions() self._print_namespace_packages() self._unload_extensions() def _update_installed(self, **buildout_options): installed = self['buildout']['installed'] f = open(installed, 'a') f.write('\n[buildout]\n') for option, value in list(buildout_options.items()): _save_option(option, value, f) f.close() def _uninstall_part(self, part, installed_part_options): # uninstall part __doing__ = 'Uninstalling %s.', part self._logger.info(*__doing__) # run uninstall recipe recipe, entry = _recipe(installed_part_options[part]) try: uninstaller = _install_and_load( recipe, 'zc.buildout.uninstall', entry, self) self._logger.info('Running uninstall recipe.') uninstaller(part, installed_part_options[part]) except (ImportError, pkg_resources.DistributionNotFound): pass # remove created files and directories self._uninstall( installed_part_options[part]['__buildout_installed__']) def _setup_directories(self): __doing__ = 'Setting up buildout directories' # Create buildout directories for name in ('bin', 'parts', 'develop-eggs'): d = self['buildout'][name+'-directory'] if not os.path.exists(d): self._logger.info('Creating directory %r.', d) os.mkdir(d) def _develop(self): """Install sources by running in editable mode. Traditionally: run `setup.py develop` on them. Nowadays: run `pip install -e` on them, as there may not be a `setup.py`, but `pyproject.toml` instead, using for example `hatchling`. """ __doing__ = 'Processing directories listed in the develop option' develop = self['buildout'].get('develop') if not develop: return '' dest = self['buildout']['develop-eggs-directory'] old_files = os.listdir(dest) env = dict(os.environ, PYTHONPATH=zc.buildout.easy_install.setuptools_pythonpath) here = os.getcwd() try: try: for setup in develop.split(): setup = self._buildout_path(setup) files = glob.glob(setup) if not files: self._logger.warning("Couldn't develop %r (not found)", setup) else: files.sort() for setup in files: self._logger.info("Develop: %r", setup) __doing__ = 'Processing develop directory %r.', setup zc.buildout.easy_install.develop(setup, dest) except: # if we had an error, we need to roll back changes, by # removing any files we created. self._sanity_check_develop_eggs_files(dest, old_files) self._uninstall('\n'.join( [os.path.join(dest, f) for f in os.listdir(dest) if f not in old_files ])) raise else: self._sanity_check_develop_eggs_files(dest, old_files) return '\n'.join([os.path.join(dest, f) for f in os.listdir(dest) if f not in old_files ]) finally: os.chdir(here) def _sanity_check_develop_eggs_files(self, dest, old_files): for f in os.listdir(dest): if f in old_files: continue if not (os.path.isfile(os.path.join(dest, f)) and f.endswith('.egg-link')): self._logger.warning( "Unexpected entry, %r, in develop-eggs directory.", f) def _compute_part_signatures(self, parts): # Compute recipe signature and add to options for part in parts: options = self.get(part) if options is None: options = self[part] = {} recipe, entry = _recipe(options) req = pkg_resources.Requirement.parse(recipe) sig = _dists_sig(pkg_resources.working_set.resolve([req])) options['__buildout_signature__'] = ' '.join(sig) def _read_installed_part_options(self): old = self['buildout']['installed'] if old and os.path.isfile(old): fp = open(old) sections = zc.buildout.configparser.parse(fp, old) fp.close() result = {} for section, options in sections.items(): for option, value in options.items(): if '%(' in value: for k, v in _spacey_defaults: value = value.replace(k, v) options[option] = value result[section] = self.Options(self, section, options) return result, True else: return ({'buildout': self.Options(self, 'buildout', {'parts': ''})}, False, ) def _uninstall(self, installed): for f in installed.split('\n'): if not f: continue f = self._buildout_path(f) if os.path.isdir(f): rmtree(f) elif os.path.isfile(f): try: os.remove(f) except OSError: if not ( sys.platform == 'win32' and (realpath(os.path.join(os.path.dirname(sys.argv[0]), 'buildout.exe')) == realpath(f) ) # Sigh. This is the executable used to run the buildout # and, of course, it's in use. Leave it. ): raise def _install(self, part): options = self[part] recipe, entry = _recipe(options) recipe_class = pkg_resources.load_entry_point( recipe, 'zc.buildout', entry) installed = recipe_class(self, part, options).install() if installed is None: installed = [] elif isinstance(installed, str): installed = [installed] base = self._buildout_path('') installed = [d.startswith(base) and d[len(base):] or d for d in installed] return ' '.join(installed) def _save_installed_options(self, installed_options): installed = self['buildout']['installed'] if not installed: return f = open(installed, 'w') _save_options('buildout', installed_options['buildout'], f) for part in installed_options['buildout']['parts'].split(): print_(file=f) _save_options(part, installed_options[part], f) f.close() def _error(self, message, *args): raise zc.buildout.UserError(message % args) def _setup_socket_timeout(self): timeout = self['buildout']['socket-timeout'] if timeout != '': try: timeout = int(timeout) import socket self._logger.info( 'Setting socket time out to %d seconds.', timeout) socket.setdefaulttimeout(timeout) except ValueError: self._logger.warning("Default socket timeout is used !\n" "Value in configuration is not numeric: [%s].\n", timeout) def _setup_logging(self): root_logger = logging.getLogger() self._logger = logging.getLogger('zc.buildout') handler = logging.StreamHandler(sys.stdout) log_format = self['buildout']['log-format'] if not log_format: # No format specified. Use different formatter for buildout # and other modules, showing logger name except for buildout log_format = '%(name)s: %(message)s' buildout_handler = logging.StreamHandler(sys.stdout) buildout_handler.setFormatter(logging.Formatter('%(message)s')) self._logger.propagate = False self._logger.addHandler(buildout_handler) handler.setFormatter(logging.Formatter(log_format)) root_logger.addHandler(handler) level = self['buildout']['log-level'] if level in ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'): level = getattr(logging, level) else: try: level = int(level) except ValueError: self._error("Invalid logging level %s", level) verbosity = self['buildout'].get('verbosity', 0) try: verbosity = int(verbosity) except ValueError: self._error("Invalid verbosity %s", verbosity) level -= verbosity root_logger.setLevel(level) self._log_level = level def _maybe_upgrade(self): # See if buildout or setuptools or other dependencies need to be upgraded. # If they do, do the upgrade and restart the buildout process. __doing__ = 'Checking for upgrades.' if 'BUILDOUT_RESTART_AFTER_UPGRADE' in os.environ: return if not self.newest: return # We must install `wheel` before `setuptools`` to avoid confusion between # the true `wheel` package and the one vendorized by `setuptools`. # See https://github.com/buildout/buildout/issues/691 projects = ('zc.buildout', 'wheel', 'pip', 'setuptools') ws = zc.buildout.easy_install.install( projects, self['buildout']['eggs-directory'], links = self['buildout'].get('find-links', '').split(), index = self['buildout'].get('index'), path = [self['buildout']['develop-eggs-directory']], allow_hosts = self._allow_hosts ) upgraded = [] for project in projects: canonicalized_name = packaging_utils.canonicalize_name(project) req = pkg_resources.Requirement.parse(canonicalized_name) dist = ws.find(req) if dist is None and canonicalized_name != project: # Try with the original project name. Depending on which setuptools # version is used, this is either useless or a life saver. req = pkg_resources.Requirement.parse(project) dist = ws.find(req) importlib.import_module(project) if dist is None: # This is unexpected. This must be some problem with how we use # setuptools/pkg_resources. But since the import worked, it feels # safe to ignore. self._logger.warning( "Could not find %s in working set during upgrade check. Ignoring.", project, ) continue if not inspect.getfile(sys.modules[project]).startswith(dist.location): upgraded.append(dist) if not upgraded: return __doing__ = 'Upgrading.' should_run = realpath( os.path.join(os.path.abspath(self['buildout']['bin-directory']), 'buildout') ) if sys.platform == 'win32': should_run += '-script.py' if (realpath(os.path.abspath(sys.argv[0])) != should_run): self._logger.debug("Running %r.", realpath(sys.argv[0])) self._logger.debug("Local buildout is %r.", should_run) self._logger.warning("Not upgrading because not running a local " "buildout command.") return self._logger.info("Upgraded:\n %s;\nRestarting.", ",\n ".join([("%s version %s" % (dist.project_name, dist.version) ) for dist in upgraded ] ), ) # the new dist is different, so we've upgraded. # Update the scripts and return True options = self['buildout'] eggs_dir = options['eggs-directory'] develop_eggs_dir = options['develop-eggs-directory'] ws = zc.buildout.easy_install.sort_working_set( ws, eggs_dir=eggs_dir, develop_eggs_dir=develop_eggs_dir ) zc.buildout.easy_install.scripts( ['zc.buildout'], ws, sys.executable, options['bin-directory'], relative_paths = ( bool_option(options, 'relative-paths', False) and options['directory'] or ''), ) # Restart args = sys.argv[:] if not __debug__: args.insert(0, '-O') args.insert(0, sys.executable) env=dict(os.environ, BUILDOUT_RESTART_AFTER_UPGRADE='1') sys.exit(subprocess.call(args, env=env)) def _load_extensions(self): __doing__ = 'Loading extensions.' specs = self['buildout'].get('extensions', '').split() for superceded_extension in ['buildout-versions', 'buildout.dumppickedversions']: if superceded_extension in specs: msg = ("Buildout now includes 'buildout-versions' (and part " "of the older 'buildout.dumppickedversions').\n" "Remove the extension from your configuration and " "look at the 'show-picked-versions' option in " "buildout's documentation.") raise zc.buildout.UserError(msg) if specs: path = [self['buildout']['develop-eggs-directory']] if self.offline: dest = None path.append(self['buildout']['eggs-directory']) else: dest = self['buildout']['eggs-directory'] zc.buildout.easy_install.install( specs, dest, path=path, working_set=pkg_resources.working_set, links = self['buildout'].get('find-links', '').split(), index = self['buildout'].get('index'), newest=self.newest, allow_hosts=self._allow_hosts) # Clear cache because extensions might now let us read pages we # couldn't read before. zc.buildout.easy_install.clear_index_cache() for ep in pkg_resources.iter_entry_points('zc.buildout.extension'): ep.load()(self) def _unload_extensions(self): __doing__ = 'Unloading extensions.' specs = self['buildout'].get('extensions', '').split() if specs: for ep in pkg_resources.iter_entry_points( 'zc.buildout.unloadextension'): ep.load()(self) def _print_picked_versions(self): picked_versions, required_by = (zc.buildout.easy_install .get_picked_versions()) if not picked_versions: # Don't print empty output. return output = _format_picked_versions(picked_versions, required_by) if self.show_picked_versions: print_("Versions had to be automatically picked.") print_("The following part definition lists the versions picked:") print_('\n'.join(output)) if self.update_versions_file: # Write to the versions file. if os.path.exists(self.update_versions_file): output[:1] = [ '', '# Added by buildout at %s' % datetime.datetime.now() ] output.append('') f = open(self.update_versions_file, 'a') f.write(('\n'.join(output))) f.close() print_("Picked versions have been written to " + self.update_versions_file) def _print_namespace_packages(self): namespace_packages = zc.buildout.easy_install.get_namespace_packages() if not namespace_packages: # Don't print empty output. return print(""" ** WARNING ** Some development packages are using old style namespace packages. You should switch to native namespaces (PEP 420). If you get a ModuleNotFound or an ImportError when importing a package from one of these namespaces, you can try this as a temporary workaround: pip install horse-with-no-namespace Note: installing horse-with-no-namespace with buildout will not work. You must install it into the virtualenv with pip (or uv) before running the buildout. The following list shows the affected packages and their namespaces: """ ) for key, value in namespace_packages: print(f"* {key}: {', '.join(value.splitlines())}") @command def setup(self, args): if not args: raise zc.buildout.UserError( "The setup command requires the path to a setup script or \n" "directory containing a setup script, and its arguments." ) setup = args.pop(0) if os.path.isdir(setup): setup = os.path.join(setup, 'setup.py') self._logger.info("Running setup script %r.", setup) setup = os.path.abspath(setup) fd, tsetup = tempfile.mkstemp() try: os.write(fd, (zc.buildout.easy_install.runsetup_template % dict( setupdir=os.path.dirname(setup), setup=setup, __file__ = setup, extra="", )).encode()) args = [sys.executable, tsetup] + args zc.buildout.easy_install.call_subprocess(args) finally: os.close(fd) os.remove(tsetup) @command def runsetup(self, args): self.setup(args) @command def query(self, args=None): if args is None or len(args) != 1: _error('The query command requires a single argument.') option = args[0] option = option.split(':') if len(option) == 1: option = 'buildout', option[0] elif len(option) != 2: _error('Invalid option:', args[0]) section, option = option verbose = self['buildout'].get('verbosity', 0) != 0 if verbose: print_('${%s:%s}' % (section, option)) try: print_(self._raw[section][option]) except KeyError: if section in self._raw: _error('Key not found:', option) else: _error('Section not found:', section) @command def annotate(self, args=None): verbose = self['buildout'].get('verbosity', 0) != 0 section = None if args is None: sections = [] else: sections = args _print_annotate(self._annotated, verbose, sections, self._buildout_dir) def print_options(self, base_path=None): for section in sorted(self._data): if section == 'buildout' or section == self['buildout']['versions']: continue print_('['+section+']') for k, v in sorted(self._data[section].items()): if '\n' in v: v = '\n ' + v.replace('\n', '\n ') else: v = ' '+v if base_path: v = v.replace(os.getcwd(), base_path) print_("%s =%s" % (k, v)) def __getitem__(self, section): __doing__ = 'Getting section %s.', section try: return self._data[section] except KeyError: pass try: data = self._raw[section] except KeyError: raise MissingSection(section) options = self.Options(self, section, data) self._data[section] = options options._initialize() return options def __setitem__(self, name, data): if name in self._raw: raise KeyError("Section already exists", name) self._raw[name] = dict((k, str(v)) for (k, v) in data.items()) self[name] # Add to parts def parse(self, data): from io import StringIO import textwrap sections = zc.buildout.configparser.parse( StringIO(textwrap.dedent(data)), '', _default_globals) for name in sections: if name in self._raw: raise KeyError("Section already exists", name) self._raw[name] = dict((k, str(v)) for (k, v) in sections[name].items()) for name in sections: self[name] # Add to parts def __delitem__(self, key): raise NotImplementedError('__delitem__') def keys(self): return list(self._raw.keys()) def __iter__(self): return iter(self._raw) def __len__(self): return len(self._raw) def _install_and_load(spec, group, entry, buildout): __doing__ = 'Loading recipe %r.', spec try: req = pkg_resources.Requirement.parse(spec) buildout_options = buildout['buildout'] if pkg_resources.working_set.find(req) is None: __doing__ = 'Installing recipe %s.', spec if buildout.offline: dest = None path = [buildout_options['develop-eggs-directory'], buildout_options['eggs-directory'], ] else: dest = buildout_options['eggs-directory'] path = [buildout_options['develop-eggs-directory']] # Pin versions when processing the buildout section versions_section_name = buildout['buildout'].get('versions', 'versions') versions = buildout.get(versions_section_name, {}) zc.buildout.easy_install.allow_picked_versions( bool_option(buildout['buildout'], 'allow-picked-versions') ) zc.buildout.easy_install.install( [spec], dest, links=buildout._links, index=buildout_options.get('index'), path=path, working_set=pkg_resources.working_set, newest=buildout.newest, allow_hosts=buildout._allow_hosts, versions=versions, ) __doing__ = 'Loading %s recipe entry %s:%s.', group, spec, entry return pkg_resources.load_entry_point( req.project_name, group, entry) except Exception: v = sys.exc_info()[1] buildout._logger.log( 1, "Couldn't load %s entry point %s\nfrom %s:\n%s.", group, entry, spec, v) raise
Buildout
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/internal/conjecture/optimiser.py
{ "start": 853, "end": 8856 }
class ____: """A fairly basic optimiser designed to increase the value of scores for targeted property-based testing. This implements a fairly naive hill climbing algorithm based on randomly regenerating parts of the test case to attempt to improve the result. It is not expected to produce amazing results, because it is designed to be run in a fairly small testing budget, so it prioritises finding easy wins and bailing out quickly if that doesn't work. For more information about targeted property-based testing, see Löscher, Andreas, and Konstantinos Sagonas. "Targeted property-based testing." Proceedings of the 26th ACM SIGSOFT International Symposium on Software Testing and Analysis. ACM, 2017. """ def __init__( self, engine: ConjectureRunner, data: ConjectureResult, target: str, max_improvements: int = 100, ) -> None: """Optimise ``target`` starting from ``data``. Will stop either when we seem to have found a local maximum or when the target score has been improved ``max_improvements`` times. This limit is in place to deal with the fact that the target score may not be bounded above.""" self.engine = engine self.current_data = data self.target = target self.max_improvements = max_improvements self.improvements = 0 def run(self) -> None: self.hill_climb() def score_function(self, data: ConjectureResult) -> float: return data.target_observations.get(self.target, NO_SCORE) @property def current_score(self) -> float: return self.score_function(self.current_data) def consider_new_data(self, data: ConjectureResult | _Overrun) -> bool: """Consider a new data object as a candidate target. If it is better than the current one, return True.""" if data.status < Status.VALID: return False assert isinstance(data, ConjectureResult) score = self.score_function(data) if score < self.current_score: return False if score > self.current_score: self.improvements += 1 self.current_data = data return True assert score == self.current_score # We allow transitions that leave the score unchanged as long as they # don't increase the number of nodes. This gives us a certain amount of # freedom for lateral moves that will take us out of local maxima. if len(data.nodes) <= len(self.current_data.nodes): self.current_data = data return True return False def hill_climb(self) -> None: """The main hill climbing loop where we actually do the work: Take data, and attempt to improve its score for target. select_example takes a data object and returns an index to an example where we should focus our efforts.""" nodes_examined = set() prev: ConjectureResult | None = None i = len(self.current_data.nodes) - 1 while i >= 0 and self.improvements <= self.max_improvements: if prev is not self.current_data: i = len(self.current_data.nodes) - 1 prev = self.current_data if i in nodes_examined: i -= 1 continue nodes_examined.add(i) node = self.current_data.nodes[i] assert node.index is not None # we can only (sensibly & easily) define hill climbing for # numeric-style nodes. It's not clear hill-climbing a string is # useful, for instance. if node.type not in {"integer", "float", "bytes", "boolean"}: continue def attempt_replace(k: int) -> bool: """ Try replacing the current node in the current best test case with a value which is "k times larger", where the exact notion of "larger" depends on the choice_type. Note that we use the *current* best and not the one we started with. This helps ensure that if we luck into a good draw when making random choices we get to keep the good bits. """ # we don't want to infinitely drive up an unbounded score. if abs(k) > 2**20: return False node = self.current_data.nodes[i] assert node.index is not None if node.was_forced: return False # pragma: no cover new_choice: ChoiceT if node.type in {"integer", "float"}: assert isinstance(node.value, (int, float)) new_choice = node.value + k elif node.type == "boolean": assert isinstance(node.value, bool) if abs(k) > 1: return False if k == -1: new_choice = False if k == 1: new_choice = True if k == 0: # pragma: no cover new_choice = node.value else: assert node.type == "bytes" assert isinstance(node.value, bytes) v = int_from_bytes(node.value) # can't go below zero for bytes if v + k < 0: return False v += k # allow adding k to increase the number of bytes. we don't want # to decrease so that b"01" doesn't turn into b"1". size = max(len(node.value), bits_to_bytes(v.bit_length())) new_choice = int_to_bytes(v, size) if not choice_permitted(new_choice, node.constraints): return False for _ in range(3): choices = self.current_data.choices attempt_choices = ( choices[: node.index] + (new_choice,) + choices[node.index + 1 :] ) attempt = self.engine.cached_test_function( attempt_choices, extend="full" ) if self.consider_new_data(attempt): return True if attempt.status is Status.OVERRUN: return False assert isinstance(attempt, ConjectureResult) if len(attempt.nodes) == len(self.current_data.nodes): return False for j, ex in enumerate(self.current_data.spans): if ex.start >= node.index + 1: break # pragma: no cover if ex.end <= node.index: continue ex_attempt = attempt.spans[j] if ex.choice_count == ex_attempt.choice_count: continue # pragma: no cover replacement = attempt.choices[ex_attempt.start : ex_attempt.end] if self.consider_new_data( self.engine.cached_test_function( choices[: node.index] + replacement + self.current_data.choices[ex.end :] ) ): return True return False # we don't know whether a target score increases or decreases with # respect to the value of some node, so try both directions. find_integer(lambda k: attempt_replace(k)) find_integer(lambda k: attempt_replace(-k))
Optimiser
python
pyparsing__pyparsing
examples/tiny/tiny_ast.py
{ "start": 17628, "end": 19051 }
class ____(TinyNode): """Statement form of a function call. Holds the function name and argument expressions; on execution the arguments are evaluated and `TinyEngine.call_function` is invoked. The return value (if any) is ignored in statement context. """ statement_type: ClassVar[str] = "call_stmt" name: str = "" args: List[object] = field(default_factory=list) @classmethod def from_parsed(cls, parsed: pp.ParseResults) -> CallStmtNode: func_group: pp.ParseResults | None = None for item in parsed: if isinstance(item, pp.ParseResults) and "type" in item and item["type"] == "func_call": # type: ignore[index] func_group = item break if func_group is None: return cls(name="", args=[]) name = func_group.name raw_args = func_group.args or [] return cls(name=name, args=list(raw_args)) def execute(self, engine: "TinyEngine") -> object | None: # noqa: F821 - forward ref arg_values = [engine.eval_expr(arg) for arg in self.args] _ = engine.call_function(self.name, arg_values) return None __all__ = [ "TinyNode", "MainDeclNode", "FunctionDeclStmtNode", "DeclStmtNode", "AssignStmtNode", "IfStmtNode", "RepeatStmtNode", "ReadStmtNode", "WriteStmtNode", "ReturnStmtNode", "CallStmtNode", ]
CallStmtNode
python
aio-libs__aiohttp
aiohttp/client_middleware_digest_auth.py
{ "start": 4775, "end": 17017 }
class ____: """ HTTP digest authentication middleware for aiohttp client. This middleware intercepts 401 Unauthorized responses containing a Digest authentication challenge, calculates the appropriate digest credentials, and automatically retries the request with the proper Authorization header. Features: - Handles all aspects of Digest authentication handshake automatically - Supports all standard hash algorithms: - MD5, MD5-SESS - SHA, SHA-SESS - SHA256, SHA256-SESS, SHA-256, SHA-256-SESS - SHA512, SHA512-SESS, SHA-512, SHA-512-SESS - Supports 'auth' and 'auth-int' quality of protection modes - Properly handles quoted strings and parameter parsing - Includes replay attack protection with client nonce count tracking - Supports preemptive authentication per RFC 7616 Section 3.6 Standards compliance: - RFC 7616: HTTP Digest Access Authentication (primary reference) - RFC 2617: HTTP Authentication (deprecated by RFC 7616) - RFC 1945: Section 11.1 (username restrictions) Implementation notes: The core digest calculation is inspired by the implementation in https://github.com/requests/requests/blob/v2.18.4/requests/auth.py with added support for modern digest auth features and error handling. """ def __init__( self, login: str, password: str, preemptive: bool = True, ) -> None: if login is None: raise ValueError("None is not allowed as login value") if password is None: raise ValueError("None is not allowed as password value") if ":" in login: raise ValueError('A ":" is not allowed in username (RFC 1945#section-11.1)') self._login_str: Final[str] = login self._login_bytes: Final[bytes] = login.encode("utf-8") self._password_bytes: Final[bytes] = password.encode("utf-8") self._last_nonce_bytes = b"" self._nonce_count = 0 self._challenge: DigestAuthChallenge = {} self._preemptive: bool = preemptive # Set of URLs defining the protection space self._protection_space: list[str] = [] async def _encode(self, method: str, url: URL, body: Payload | Literal[b""]) -> str: """ Build digest authorization header for the current challenge. Args: method: The HTTP method (GET, POST, etc.) url: The request URL body: The request body (used for qop=auth-int) Returns: A fully formatted Digest authorization header string Raises: ClientError: If the challenge is missing required parameters or contains unsupported values """ challenge = self._challenge if "realm" not in challenge: raise ClientError( "Malformed Digest auth challenge: Missing 'realm' parameter" ) if "nonce" not in challenge: raise ClientError( "Malformed Digest auth challenge: Missing 'nonce' parameter" ) # Empty realm values are allowed per RFC 7616 (SHOULD, not MUST, contain host name) realm = challenge["realm"] nonce = challenge["nonce"] # Empty nonce values are not allowed as they are security-critical for replay protection if not nonce: raise ClientError( "Security issue: Digest auth challenge contains empty 'nonce' value" ) qop_raw = challenge.get("qop", "") # Preserve original algorithm case for response while using uppercase for processing algorithm_original = challenge.get("algorithm", "MD5") algorithm = algorithm_original.upper() opaque = challenge.get("opaque", "") # Convert string values to bytes once nonce_bytes = nonce.encode("utf-8") realm_bytes = realm.encode("utf-8") path = URL(url).path_qs # Process QoP qop = "" qop_bytes = b"" if qop_raw: valid_qops = {"auth", "auth-int"}.intersection( {q.strip() for q in qop_raw.split(",") if q.strip()} ) if not valid_qops: raise ClientError( f"Digest auth error: Unsupported Quality of Protection (qop) value(s): {qop_raw}" ) qop = "auth-int" if "auth-int" in valid_qops else "auth" qop_bytes = qop.encode("utf-8") if algorithm not in DigestFunctions: raise ClientError( f"Digest auth error: Unsupported hash algorithm: {algorithm}. " f"Supported algorithms: {', '.join(SUPPORTED_ALGORITHMS)}" ) hash_fn: Final = DigestFunctions[algorithm] def H(x: bytes) -> bytes: """RFC 7616 Section 3: Hash function H(data) = hex(hash(data)).""" return hash_fn(x).hexdigest().encode() def KD(s: bytes, d: bytes) -> bytes: """RFC 7616 Section 3: KD(secret, data) = H(concat(secret, ":", data)).""" return H(b":".join((s, d))) # Calculate A1 and A2 A1 = b":".join((self._login_bytes, realm_bytes, self._password_bytes)) A2 = f"{method.upper()}:{path}".encode() if qop == "auth-int": if isinstance(body, Payload): # will always be empty bytes unless Payload entity_bytes = await body.as_bytes() # Get bytes from Payload else: entity_bytes = body entity_hash = H(entity_bytes) A2 = b":".join((A2, entity_hash)) HA1 = H(A1) HA2 = H(A2) # Nonce count handling if nonce_bytes == self._last_nonce_bytes: self._nonce_count += 1 else: self._nonce_count = 1 self._last_nonce_bytes = nonce_bytes ncvalue = f"{self._nonce_count:08x}" ncvalue_bytes = ncvalue.encode("utf-8") # Generate client nonce cnonce = hashlib.sha1( b"".join( [ str(self._nonce_count).encode("utf-8"), nonce_bytes, time.ctime().encode("utf-8"), os.urandom(8), ] ) ).hexdigest()[:16] cnonce_bytes = cnonce.encode("utf-8") # Special handling for session-based algorithms if algorithm.upper().endswith("-SESS"): HA1 = H(b":".join((HA1, nonce_bytes, cnonce_bytes))) # Calculate the response digest if qop: noncebit = b":".join( (nonce_bytes, ncvalue_bytes, cnonce_bytes, qop_bytes, HA2) ) response_digest = KD(HA1, noncebit) else: response_digest = KD(HA1, b":".join((nonce_bytes, HA2))) # Define a dict mapping of header fields to their values # Group fields into always-present, optional, and qop-dependent header_fields = { # Always present fields "username": escape_quotes(self._login_str), "realm": escape_quotes(realm), "nonce": escape_quotes(nonce), "uri": path, "response": response_digest.decode(), "algorithm": algorithm_original, } # Optional fields if opaque: header_fields["opaque"] = escape_quotes(opaque) # QoP-dependent fields if qop: header_fields["qop"] = qop header_fields["nc"] = ncvalue header_fields["cnonce"] = cnonce # Build header using templates for each field type pairs: list[str] = [] for field, value in header_fields.items(): if field in QUOTED_AUTH_FIELDS: pairs.append(f'{field}="{value}"') else: pairs.append(f"{field}={value}") return f"Digest {', '.join(pairs)}" def _in_protection_space(self, url: URL) -> bool: """ Check if the given URL is within the current protection space. According to RFC 7616, a URI is in the protection space if any URI in the protection space is a prefix of it (after both have been made absolute). """ request_str = str(url) for space_str in self._protection_space: # Check if request starts with space URL if not request_str.startswith(space_str): continue # Exact match or space ends with / (proper directory prefix) if len(request_str) == len(space_str) or space_str[-1] == "/": return True # Check next char is / to ensure proper path boundary if request_str[len(space_str)] == "/": return True return False def _authenticate(self, response: ClientResponse) -> bool: """ Takes the given response and tries digest-auth, if needed. Returns true if the original request must be resent. """ if response.status != 401: return False auth_header = response.headers.get("www-authenticate", "") if not auth_header: return False # No authentication header present method, sep, headers = auth_header.partition(" ") if not sep: # No space found in www-authenticate header return False # Malformed auth header, missing scheme separator if method.lower() != "digest": # Not a digest auth challenge (could be Basic, Bearer, etc.) return False if not headers: # We have a digest scheme but no parameters return False # Malformed digest header, missing parameters # We have a digest auth header with content if not (header_pairs := parse_header_pairs(headers)): # Failed to parse any key-value pairs return False # Malformed digest header, no valid parameters # Extract challenge parameters self._challenge = {} for field in CHALLENGE_FIELDS: if value := header_pairs.get(field): self._challenge[field] = value # Update protection space based on domain parameter or default to origin origin = response.url.origin() if domain := self._challenge.get("domain"): # Parse space-separated list of URIs self._protection_space = [] for uri in domain.split(): # Remove quotes if present uri = uri.strip('"') if uri.startswith("/"): # Path-absolute, relative to origin self._protection_space.append(str(origin.join(URL(uri)))) else: # Absolute URI self._protection_space.append(str(URL(uri))) else: # No domain specified, protection space is entire origin self._protection_space = [str(origin)] # Return True only if we found at least one challenge parameter return bool(self._challenge) async def __call__( self, request: ClientRequest, handler: ClientHandlerType ) -> ClientResponse: """Run the digest auth middleware.""" response = None for retry_count in range(2): # Apply authorization header if: # 1. This is a retry after 401 (retry_count > 0), OR # 2. Preemptive auth is enabled AND we have a challenge AND the URL is in protection space if retry_count > 0 or ( self._preemptive and self._challenge and self._in_protection_space(request.url) ): request.headers[hdrs.AUTHORIZATION] = await self._encode( request.method, request.url, request.body ) # Send the request response = await handler(request) # Check if we need to authenticate if not self._authenticate(response): break # At this point, response is guaranteed to be defined assert response is not None return response
DigestAuthMiddleware
python
facelessuser__soupsieve
tests/test_level3/test_nth_last_child.py
{ "start": 61, "end": 1365 }
class ____(util.TestCase): """Test `nth` last child selectors.""" def test_nth_last_child(self): """Test `nth` last child.""" markup = """ <body> <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id="5"></span> <span id="6"></span> <p id="7"></p> <p id="8"></p> <p id="9"></p> <p id="10"></p> <span id="11"></span> </body> """ self.assert_selector( markup, "p:nth-last-child(2)", ['10'], flags=util.HTML ) def test_nth_last_child_complex(self): """Test `nth` last child complex.""" markup = """ <body> <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id="5"></span> <span id="6"></span> <p id="7"></p> <p id="8"></p> <p id="9"></p> <p id="10"></p> <span id="11"></span> </body> """ self.assert_selector( markup, "p:nth-last-child(2n + 1)", ['1', '7', '9'], flags=util.HTML )
TestNthLastChild
python
ray-project__ray
python/ray/serve/tests/unit/test_application_state.py
{ "start": 99621, "end": 130529 }
class ____: """Test application-level autoscaling policy registration, execution, and lifecycle.""" def _create_app_config( self, app_name="test_app", has_policy=True, deployments=None ): """Helper to create a ServeApplicationSchema with optional autoscaling policy.""" if deployments is None: deployments = [ DeploymentSchema( name="d1", autoscaling_config={ "target_ongoing_requests": 1, "min_replicas": 1, "max_replicas": 5, "initial_replicas": 1, }, ) ] return ServeApplicationSchema( name=app_name, import_path="fake.import.path", route_prefix="/hi", autoscaling_policy={ "policy_function": "ray.serve.tests.unit.test_application_state:simple_app_level_policy" } if has_policy else None, deployments=deployments, ) def _deploy_app_with_mocks(self, app_state_manager, app_config): """Helper to deploy an app with proper mocking to avoid Ray initialization.""" with patch( "ray.serve._private.application_state.build_serve_application" ) as mock_build: mock_build.return_value = Mock() app_state_manager.apply_app_configs([app_config]) app_state = app_state_manager._application_states[app_config.name] app_state._build_app_task_info = Mock() app_state._build_app_task_info.code_version = "test_version" app_state._build_app_task_info.config = app_config app_state._build_app_task_info.target_capacity = None app_state._build_app_task_info.target_capacity_direction = None # Mock reconcile to succeed with patch.object(app_state, "_reconcile_build_app_task") as mock_reconcile: deployment_infos = {} for deployment in app_config.deployments: deployment_infos[deployment.name] = deployment_info( deployment.name, "/hi" if deployment.name == "d1" else None, autoscaling_config={ "target_ongoing_requests": 1, "min_replicas": 1, "max_replicas": 5, "initial_replicas": 1, }, ) mock_reconcile.return_value = ( None, deployment_infos, BuildAppStatus.SUCCEEDED, "", ) app_state.update() return app_state def _register_deployments(self, app_state_manager, app_config): """Helper to register deployments with autoscaling manager.""" asm = app_state_manager._autoscaling_state_manager for deployment in app_config.deployments: deployment_id = DeploymentID(name=deployment.name, app_name=app_config.name) deployment_info_obj = deployment_info( deployment.name, "/hi" if deployment.name == "d1" else None, autoscaling_config={ "target_ongoing_requests": 1, "min_replicas": 1, "max_replicas": 5, "initial_replicas": 1, }, ) asm.register_deployment(deployment_id, deployment_info_obj, 1) return asm def _deploy_multiple_apps_with_mocks(self, app_state_manager, app_configs): """Helper to deploy multiple apps simultaneously with proper mocking.""" # Deploy all apps at once with patch( "ray.serve._private.application_state.build_serve_application" ) as mock_build: mock_build.return_value = Mock() app_state_manager.apply_app_configs(app_configs) # Mock the build app tasks for all apps for app_config in app_configs: app_state = app_state_manager._application_states[app_config.name] app_state._build_app_task_info = Mock() app_state._build_app_task_info.code_version = "test_version" app_state._build_app_task_info.config = app_config app_state._build_app_task_info.target_capacity = None app_state._build_app_task_info.target_capacity_direction = None # Mock reconcile to succeed with patch.object(app_state, "_reconcile_build_app_task") as mock_reconcile: deployment_infos = {} for deployment in app_config.deployments: deployment_infos[deployment.name] = deployment_info( deployment.name, "/hi" if deployment.name == "d1" else None, autoscaling_config={ "target_ongoing_requests": 1, "min_replicas": 1, "max_replicas": 5, "initial_replicas": 1, }, ) mock_reconcile.return_value = ( None, deployment_infos, BuildAppStatus.SUCCEEDED, "", ) app_state.update() return app_state_manager._autoscaling_state_manager def test_app_level_autoscaling_policy_registration_and_execution( self, mocked_application_state_manager ): """Test that application-level autoscaling policy is registered and executed when set in config.""" ( app_state_manager, deployment_state_manager, _, ) = mocked_application_state_manager # Create app config with policy app_config = self._create_app_config() # Deploy app app_state = self._deploy_app_with_mocks(app_state_manager, app_config) # Register deployments asm = self._register_deployments(app_state_manager, app_config) # Verify policy was registered assert asm._application_has_policy("test_app") is True assert app_state.should_autoscale() is True assert asm.should_autoscale_application("test_app") is True # Create replicas and test autoscaling d1_id = DeploymentID(name="d1", app_name="test_app") d1_replicas = [ ReplicaID(unique_id=f"d1_replica_{i}", deployment_id=d1_id) for i in [1, 2] ] asm.update_running_replica_ids(d1_id, d1_replicas) # Clear scaling decisions and test autoscaling deployment_state_manager._scaling_decisions.clear() app_state_manager.update() # Verify policy was executed (scales to 3 replicas) assert deployment_state_manager._scaling_decisions[d1_id] == 3 def test_app_level_autoscaling_policy_recovery( self, mocked_application_state_manager ): """Test that application-level autoscaling policy is registered when recovered from checkpoint.""" ( app_state_manager, deployment_state_manager, kv_store, ) = mocked_application_state_manager # Deploy app with policy app_config = self._create_app_config() _ = self._deploy_app_with_mocks(app_state_manager, app_config) asm = self._register_deployments(app_state_manager, app_config) # Save checkpoint app_state_manager.update() # Simulate controller crash - create new managers new_deployment_state_manager = MockDeploymentStateManager(kv_store) new_app_state_manager = ApplicationStateManager( new_deployment_state_manager, asm, MockEndpointState(), kv_store, LoggingConfig(), ) # Recovery happens automatically during initialization # Verify app-level policy was recovered assert asm._application_has_policy("test_app") is True # Test that recovered policy still works d1_id = DeploymentID(name="d1", app_name="test_app") d1_replicas = [ ReplicaID(unique_id=f"d1_replica_{i}", deployment_id=d1_id) for i in [1, 2] ] asm.update_running_replica_ids(d1_id, d1_replicas) new_deployment_state_manager._scaling_decisions.clear() new_app_state_manager.update() assert new_deployment_state_manager._scaling_decisions[d1_id] == 3 def test_app_level_autoscaling_policy_deregistration_on_deletion( self, mocked_application_state_manager ): """Test that application-level autoscaling policy is deregistered when application is deleted.""" ( app_state_manager, deployment_state_manager, _, ) = mocked_application_state_manager # Deploy app with policy app_config = self._create_app_config() _ = self._deploy_app_with_mocks(app_state_manager, app_config) asm = self._register_deployments(app_state_manager, app_config) # Verify app is registered assert asm._application_has_policy("test_app") is True # Delete the application deployment_state_manager.delete_deployment( DeploymentID(name="d1", app_name="test_app") ) deployment_state_manager.set_deployment_deleted( DeploymentID(name="d1", app_name="test_app") ) app_state_manager.delete_app("test_app") app_state_manager.update() # Verify app-level policy is deregistered assert asm._application_has_policy("test_app") is False assert asm.should_autoscale_application("test_app") is False def test_app_level_autoscaling_policy_add_and_remove_from_config( self, mocked_application_state_manager ): """Test that application-level autoscaling policy is registered when added and deregistered when removed.""" ( app_state_manager, deployment_state_manager, _, ) = mocked_application_state_manager # Deploy app without policy initially app_config_no_policy = self._create_app_config(has_policy=False) _ = self._deploy_app_with_mocks(app_state_manager, app_config_no_policy) asm = self._register_deployments(app_state_manager, app_config_no_policy) # Verify no app-level policy initially # Note: The app might be registered but without a policy assert asm._application_has_policy("test_app") is False # Now add app-level autoscaling policy app_config_with_policy = self._create_app_config(has_policy=True) _ = self._deploy_app_with_mocks(app_state_manager, app_config_with_policy) # Verify app-level policy is registered assert asm._application_has_policy("test_app") is True # Now remove app-level autoscaling policy app_config_no_policy_again = self._create_app_config(has_policy=False) _ = self._deploy_app_with_mocks(app_state_manager, app_config_no_policy_again) # Verify app-level policy is deregistered # Note: The app might still exist but without a policy assert asm._application_has_policy("test_app") is False assert asm.should_autoscale_application("test_app") is False def test_app_level_autoscaling_policy_with_multiple_deployments( self, mocked_application_state_manager ): """Test that app-level autoscaling policy works correctly with multiple deployments.""" ( app_state_manager, deployment_state_manager, _, ) = mocked_application_state_manager # Create app with multiple deployments deployments = [ DeploymentSchema( name="d1", autoscaling_config={ "target_ongoing_requests": 1, "min_replicas": 1, "max_replicas": 10, "initial_replicas": 1, }, ), DeploymentSchema( name="d2", autoscaling_config={ "target_ongoing_requests": 1, "min_replicas": 1, "max_replicas": 10, "initial_replicas": 1, }, ), DeploymentSchema( name="d3", autoscaling_config={ "target_ongoing_requests": 1, "min_replicas": 1, "max_replicas": 10, "initial_replicas": 1, }, ), ] app_config = self._create_app_config(deployments=deployments) _ = self._deploy_app_with_mocks(app_state_manager, app_config) asm = self._register_deployments(app_state_manager, app_config) # Verify policy was registered assert asm._application_has_policy("test_app") is True # Create replicas for all deployments deployment_ids = [ DeploymentID(name=f"d{i}", app_name="test_app") for i in range(1, 4) ] for i, deployment_id in enumerate(deployment_ids): replicas = [ ReplicaID(unique_id=f"d{i+1}_replica_{j}", deployment_id=deployment_id) for j in [1, 2] ] asm.update_running_replica_ids(deployment_id, replicas) # Test autoscaling deployment_state_manager._scaling_decisions.clear() app_state_manager.update() # Verify all deployments were scaled to 3 (our policy scales all to 3) assert asm.should_autoscale_application("test_app") is True for deployment_id in deployment_ids: assert deployment_id in deployment_state_manager._scaling_decisions assert deployment_state_manager._scaling_decisions[deployment_id] == 3 def test_app_level_autoscaling_policy_state_persistence( self, mocked_application_state_manager ): """Test that app-level autoscaling policy state is maintained across multiple calls.""" ( app_state_manager, deployment_state_manager, _, ) = mocked_application_state_manager # Deploy app with policy app_config = self._create_app_config() _ = self._deploy_app_with_mocks(app_state_manager, app_config) asm = self._register_deployments(app_state_manager, app_config) # Create replicas d1_id = DeploymentID(name="d1", app_name="test_app") d1_replicas = [ ReplicaID(unique_id=f"d1_replica_{i}", deployment_id=d1_id) for i in [1, 2] ] asm.update_running_replica_ids(d1_id, d1_replicas) # Test multiple autoscaling calls for i in range(3): deployment_state_manager._scaling_decisions.clear() app_state_manager.update() assert asm.should_autoscale_application("test_app") is True assert deployment_state_manager._scaling_decisions[d1_id] == 3 def test_autoscaling_state_manager_helper_methods( self, mocked_application_state_manager ): """Test the new helper methods in AutoscalingStateManager.""" ( app_state_manager, deployment_state_manager, _, ) = mocked_application_state_manager asm = app_state_manager._autoscaling_state_manager # Test with no applications registered assert asm._application_has_policy("nonexistent_app") is False assert asm.should_autoscale_application("nonexistent_app") is False # Deploy app with policy app_config = self._create_app_config() _ = self._deploy_app_with_mocks(app_state_manager, app_config) asm = self._register_deployments(app_state_manager, app_config) # Test helper methods assert asm._application_has_policy("test_app") is True assert asm.should_autoscale_application("test_app") is True d1_id = DeploymentID(name="d1", app_name="test_app") assert asm.should_autoscale_deployment(d1_id) is True # Test with app without policy app_config_no_policy = self._create_app_config(has_policy=False) _ = self._deploy_app_with_mocks(app_state_manager, app_config_no_policy) asm_no_policy = self._register_deployments( app_state_manager, app_config_no_policy ) assert asm_no_policy._application_has_policy("test_app") is False assert ( asm_no_policy.should_autoscale_application("test_app") is True ) # App exists but no policy assert asm_no_policy.should_autoscale_deployment(d1_id) is True def test_get_decision_num_replicas_method(self, mocked_application_state_manager): """Test the get_decision_num_replicas method in AutoscalingStateManager.""" ( app_state_manager, deployment_state_manager, _, ) = mocked_application_state_manager # Deploy app with policy app_config = self._create_app_config() _ = self._deploy_app_with_mocks(app_state_manager, app_config) asm = self._register_deployments(app_state_manager, app_config) # Create replicas d1_id = DeploymentID(name="d1", app_name="test_app") d1_replicas = [ ReplicaID(unique_id=f"d1_replica_{i}", deployment_id=d1_id) for i in [1, 2] ] asm.update_running_replica_ids(d1_id, d1_replicas) # Test get_decision_num_replicas deployment_to_target_num_replicas = {d1_id: 2} decisions = asm.get_decision_num_replicas( "test_app", deployment_to_target_num_replicas ) assert d1_id in decisions assert decisions[d1_id] == 3 # Our policy scales to 3 def test_multiple_applications_autoscaling_isolation( self, mocked_application_state_manager ): """Test that autoscaling works correctly with multiple applications.""" ( app_state_manager, deployment_state_manager, _, ) = mocked_application_state_manager # Deploy both apps simultaneously app_config1 = self._create_app_config(app_name="app1") app_config2 = self._create_app_config(app_name="app2", has_policy=False) # Deploy both apps using new helper asm = self._deploy_multiple_apps_with_mocks( app_state_manager, [app_config1, app_config2] ) # Register deployments for both apps using existing helper asm = self._register_deployments(app_state_manager, app_config1) asm = self._register_deployments(app_state_manager, app_config2) # Test isolation assert asm._application_has_policy("app1") is True assert asm._application_has_policy("app2") is False assert asm.should_autoscale_application("app1") is True assert asm.should_autoscale_application("app2") is True # Test deployment-level isolation d1_app1_id = DeploymentID(name="d1", app_name="app1") d1_app2_id = DeploymentID(name="d1", app_name="app2") asm.update_running_replica_ids( d1_app1_id, [ ReplicaID(unique_id=f"d1_app1_replica_{i}", deployment_id=d1_app1_id) for i in [1, 2] ], ) asm.update_running_replica_ids( d1_app2_id, [ ReplicaID(unique_id=f"d1_app2_replica_{i}", deployment_id=d1_app2_id) for i in [1, 2] ], ) assert asm.should_autoscale_deployment(d1_app1_id) is True assert asm.should_autoscale_deployment(d1_app2_id) is True deployment_state_manager._scaling_decisions.clear() app_state_manager.update() # Both apps should be autoscaled, but with different behaviors: # app1 has an app-level policy, so it scales to 3 replicas # app2 doesn't have an app-level policy, so it uses deployment-level autoscaling (scales to 1) assert d1_app1_id in deployment_state_manager._scaling_decisions assert deployment_state_manager._scaling_decisions[d1_app1_id] == 3 assert d1_app2_id in deployment_state_manager._scaling_decisions assert deployment_state_manager._scaling_decisions[d1_app2_id] == 1 def test_autoscaling_state_manager_edge_cases( self, mocked_application_state_manager ): """Test edge cases for AutoscalingStateManager methods.""" ( app_state_manager, deployment_state_manager, _, ) = mocked_application_state_manager asm = app_state_manager._autoscaling_state_manager # Test with empty app name assert asm._application_has_policy("") is False assert asm.should_autoscale_application("") is False # Test with None app name assert asm._application_has_policy(None) is False assert asm.should_autoscale_application(None) is False # Test get_decision_num_replicas with nonexistent app with pytest.raises(KeyError): asm.get_decision_num_replicas("nonexistent_app", {}) # Test should_autoscale_deployment with nonexistent deployment nonexistent_deployment_id = DeploymentID( name="nonexistent", app_name="nonexistent_app" ) assert asm.should_autoscale_deployment(nonexistent_deployment_id) is False def test_autoscaling_with_deployment_level_configs( self, mocked_application_state_manager ): """Test that app-level autoscaling respects deployment-level autoscaling configs.""" ( app_state_manager, deployment_state_manager, _, ) = mocked_application_state_manager # Create app with deployments that have different autoscaling configs deployments = [ DeploymentSchema( name="d1", autoscaling_config={ "target_ongoing_requests": 1, "min_replicas": 1, "max_replicas": 3, # Lower max "initial_replicas": 1, }, ), DeploymentSchema( name="d2", autoscaling_config={ "target_ongoing_requests": 1, "min_replicas": 1, "max_replicas": 10, # Higher max "initial_replicas": 1, }, ), ] app_config = self._create_app_config(deployments=deployments) _ = self._deploy_app_with_mocks(app_state_manager, app_config) asm = self._register_deployments(app_state_manager, app_config) # Create replicas d1_id = DeploymentID(name="d1", app_name="test_app") d2_id = DeploymentID(name="d2", app_name="test_app") d1_replicas = [ ReplicaID(unique_id=f"d1_replica_{i}", deployment_id=d1_id) for i in [1, 2] ] d2_replicas = [ ReplicaID(unique_id=f"d2_replica_{i}", deployment_id=d2_id) for i in [1, 2] ] asm.update_running_replica_ids(d1_id, d1_replicas) asm.update_running_replica_ids(d2_id, d2_replicas) # Test autoscaling deployment_state_manager._scaling_decisions.clear() app_state_manager.update() # Verify both deployments were scaled, but d1 should be capped at max_replicas=3 assert d1_id in deployment_state_manager._scaling_decisions assert d2_id in deployment_state_manager._scaling_decisions assert ( deployment_state_manager._scaling_decisions[d1_id] == 3 ) # Capped by max_replicas assert ( deployment_state_manager._scaling_decisions[d2_id] == 3 ) # Our policy scales to 3 def test_get_external_scaler_enabled(mocked_application_state_manager): """Test get_external_scaler_enabled returns correct value based on app config. Test that get_external_scaler_enabled returns True when an app is deployed with external_scaler_enabled=True, False when deployed with external_scaler_enabled=False, and False for non-existent apps. """ app_state_manager, _, _ = mocked_application_state_manager # Deploy app with external_scaler_enabled=True app_state_manager.deploy_app( "app_with_external_scaler", [deployment_params("deployment1", "/route1")], ApplicationArgsProto(external_scaler_enabled=True), ) # Deploy app with external_scaler_enabled=False app_state_manager.deploy_app( "app_without_external_scaler", [deployment_params("deployment2", "/route2")], ApplicationArgsProto(external_scaler_enabled=False), ) # Test that get_external_scaler_enabled returns True for app with external scaler enabled assert ( app_state_manager.get_external_scaler_enabled("app_with_external_scaler") is True ) # Test that get_external_scaler_enabled returns False for app without external scaler assert ( app_state_manager.get_external_scaler_enabled("app_without_external_scaler") is False ) # Test that get_external_scaler_enabled returns False for non-existent app assert app_state_manager.get_external_scaler_enabled("non_existent_app") is False def test_deploy_apps_with_external_scaler_enabled(mocked_application_state_manager): """Test that deploy_apps correctly uses external_scaler_enabled from name_to_application_args. This test verifies that when deploy_apps is called with name_to_application_args containing external_scaler_enabled values, the ApplicationState is correctly initialized with the appropriate external_scaler_enabled value for each app. """ ( app_state_manager, deployment_state_manager, kv_store, ) = mocked_application_state_manager # Deploy multiple apps with different external_scaler_enabled settings name_to_deployment_args = { "app_with_scaler": [deployment_params("d1", "/with_scaler")], "app_without_scaler": [deployment_params("d2", "/without_scaler")], "app_default": [deployment_params("d3", "/default")], } name_to_application_args = { "app_with_scaler": ApplicationArgsProto(external_scaler_enabled=True), "app_without_scaler": ApplicationArgsProto(external_scaler_enabled=False), "app_default": ApplicationArgsProto(external_scaler_enabled=False), } # Call deploy_apps app_state_manager.deploy_apps(name_to_deployment_args, name_to_application_args) # Verify that external_scaler_enabled is correctly set for each app assert app_state_manager.get_external_scaler_enabled("app_with_scaler") is True assert app_state_manager.get_external_scaler_enabled("app_without_scaler") is False assert app_state_manager.get_external_scaler_enabled("app_default") is False # Verify the internal state is also correct app_state_with_scaler = app_state_manager._application_states["app_with_scaler"] app_state_without_scaler = app_state_manager._application_states[ "app_without_scaler" ] app_state_default = app_state_manager._application_states["app_default"] assert app_state_with_scaler.external_scaler_enabled is True assert app_state_without_scaler.external_scaler_enabled is False assert app_state_default.external_scaler_enabled is False # Verify that all apps are in the correct state assert app_state_with_scaler.status == ApplicationStatus.DEPLOYING assert app_state_without_scaler.status == ApplicationStatus.DEPLOYING assert app_state_default.status == ApplicationStatus.DEPLOYING def test_external_scaler_enabled_recovery_from_checkpoint( mocked_application_state_manager, ): """Test that external_scaler_enabled is correctly recovered from checkpoint. This test verifies that after a controller crash and recovery, the external_scaler_enabled flag is correctly restored from the checkpoint for both apps with external_scaler_enabled=True and external_scaler_enabled=False. """ ( app_state_manager, deployment_state_manager, kv_store, ) = mocked_application_state_manager app_name_with_scaler = "app_with_external_scaler" app_name_without_scaler = "app_without_external_scaler" deployment_id_with_scaler = DeploymentID(name="d1", app_name=app_name_with_scaler) deployment_id_without_scaler = DeploymentID( name="d2", app_name=app_name_without_scaler ) # Deploy app with external_scaler_enabled=True app_state_manager.deploy_app( app_name_with_scaler, [deployment_params("d1")], ApplicationArgsProto(external_scaler_enabled=True), ) # Deploy app with external_scaler_enabled=False app_state_manager.deploy_app( app_name_without_scaler, [deployment_params("d2")], ApplicationArgsProto(external_scaler_enabled=False), ) # Verify initial state assert app_state_manager.get_external_scaler_enabled(app_name_with_scaler) is True assert ( app_state_manager.get_external_scaler_enabled(app_name_without_scaler) is False ) # Make deployments healthy and update app_state_manager.update() deployment_state_manager.set_deployment_healthy(deployment_id_with_scaler) deployment_state_manager.set_deployment_healthy(deployment_id_without_scaler) app_state_manager.update() # Save checkpoint app_state_manager.save_checkpoint() # Simulate controller crash - create new managers with the same kv_store new_deployment_state_manager = MockDeploymentStateManager(kv_store) new_app_state_manager = ApplicationStateManager( new_deployment_state_manager, AutoscalingStateManager(), MockEndpointState(), kv_store, LoggingConfig(), ) # Verify that external_scaler_enabled is correctly recovered from checkpoint assert ( new_app_state_manager.get_external_scaler_enabled(app_name_with_scaler) is True ) assert ( new_app_state_manager.get_external_scaler_enabled(app_name_without_scaler) is False ) # Verify the internal state is also correct app_state_with_scaler = new_app_state_manager._application_states[ app_name_with_scaler ] app_state_without_scaler = new_app_state_manager._application_states[ app_name_without_scaler ] assert app_state_with_scaler.external_scaler_enabled is True assert app_state_without_scaler.external_scaler_enabled is False
TestApplicationLevelAutoscaling
python
huggingface__transformers
src/transformers/models/vit_msn/modeling_vit_msn.py
{ "start": 1372, "end": 5405 }
class ____(nn.Module): """ Construct the CLS token, position and patch embeddings. Optionally, also the mask token. """ def __init__(self, config: ViTMSNConfig, use_mask_token: bool = False) -> None: super().__init__() self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) if use_mask_token else None self.patch_embeddings = ViTMSNPatchEmbeddings(config) num_patches = self.patch_embeddings.num_patches self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.hidden_size)) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.patch_size = config.patch_size self.config = config # Copied from transformers.models.vit.modeling_vit.ViTEmbeddings.interpolate_pos_encoding def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor: """ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution images. This method is also adapted to support torch.jit tracing. Adapted from: - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211 """ num_patches = embeddings.shape[1] - 1 num_positions = self.position_embeddings.shape[1] - 1 # always interpolate when tracing to ensure the exported model works for dynamic input shapes if not torch.jit.is_tracing() and num_patches == num_positions and height == width: return self.position_embeddings class_pos_embed = self.position_embeddings[:, :1] patch_pos_embed = self.position_embeddings[:, 1:] dim = embeddings.shape[-1] new_height = height // self.patch_size new_width = width // self.patch_size sqrt_num_positions = torch_int(num_positions**0.5) patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim) patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2) patch_pos_embed = nn.functional.interpolate( patch_pos_embed, size=(new_height, new_width), mode="bicubic", align_corners=False, ) patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) return torch.cat((class_pos_embed, patch_pos_embed), dim=1) def forward( self, pixel_values: torch.Tensor, bool_masked_pos: Optional[torch.BoolTensor] = None, interpolate_pos_encoding: bool = False, ) -> torch.Tensor: batch_size, num_channels, height, width = pixel_values.shape embeddings = self.patch_embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding) if bool_masked_pos is not None: seq_length = embeddings.shape[1] mask_tokens = self.mask_token.expand(batch_size, seq_length, -1) # replace the masked visual tokens by mask_tokens mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens) embeddings = embeddings * (1.0 - mask) + mask_tokens * mask # add the [CLS] token to the embedded patch tokens cls_tokens = self.cls_token.expand(batch_size, -1, -1) embeddings = torch.cat((cls_tokens, embeddings), dim=1) # add positional encoding to each token if interpolate_pos_encoding: embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width) else: embeddings = embeddings + self.position_embeddings embeddings = self.dropout(embeddings) return embeddings # Copied from transformers.models.vit.modeling_vit.ViTPatchEmbeddings with ViT->ViTMSN
ViTMSNEmbeddings
python
patrys__httmock
tests.py
{ "start": 11249, "end": 11844 }
class ____(unittest.TestCase): @with_httmock(any_mock) def test_stream_request(self): r = requests.get('http://domain.com/', stream=True) self.assertEqual(r.raw.read(), b'Hello from domain.com') @with_httmock(dict_any_mock) def test_stream_request_with_dict_mock(self): r = requests.get('http://domain.com/', stream=True) self.assertEqual(r.raw.read(), b'Hello from domain.com') @with_httmock(any_mock) def test_non_stream_request(self): r = requests.get('http://domain.com/') self.assertEqual(r.raw.read(), b'')
StreamTest
python
scikit-learn__scikit-learn
sklearn/ensemble/_forest.py
{ "start": 89347, "end": 103557 }
class ____(ForestRegressor): """ An extra-trees regressor. This class implements a meta estimator that fits a number of randomized decision trees (a.k.a. extra-trees) on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting. This estimator has native support for missing values (NaNs) for random splits. During training, a random threshold will be chosen to split the non-missing values on. Then the non-missing values will be sent to the left and right child based on the randomly selected threshold, while the missing values will also be randomly sent to the left or right child. This is repeated for every feature considered at each split. The best split among these is chosen. Read more in the :ref:`User Guide <forest>`. Parameters ---------- n_estimators : int, default=100 The number of trees in the forest. .. versionchanged:: 0.22 The default value of ``n_estimators`` changed from 10 to 100 in 0.22. criterion : {"squared_error", "absolute_error", "friedman_mse", "poisson"}, \ default="squared_error" The function to measure the quality of a split. Supported criteria are "squared_error" for the mean squared error, which is equal to variance reduction as feature selection criterion and minimizes the L2 loss using the mean of each terminal node, "friedman_mse", which uses mean squared error with Friedman's improvement score for potential splits, "absolute_error" for the mean absolute error, which minimizes the L1 loss using the median of each terminal node, and "poisson" which uses reduction in Poisson deviance to find splits. Training using "absolute_error" is significantly slower than when using "squared_error". .. versionadded:: 0.18 Mean Absolute Error (MAE) criterion. max_depth : int, default=None The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. min_samples_split : int or float, default=2 The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a fraction and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for fractions. min_samples_leaf : int or float, default=1 The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least ``min_samples_leaf`` training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a fraction and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for fractions. min_weight_fraction_leaf : float, default=0.0 The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. max_features : {"sqrt", "log2", None}, int or float, default=1.0 The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a fraction and `max(1, int(max_features * n_features_in_))` features are considered at each split. - If "sqrt", then `max_features=sqrt(n_features)`. - If "log2", then `max_features=log2(n_features)`. - If None or 1.0, then `max_features=n_features`. .. note:: The default of 1.0 is equivalent to bagged trees and more randomness can be achieved by setting smaller values, e.g. 0.3. .. versionchanged:: 1.1 The default of `max_features` changed from `"auto"` to 1.0. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. max_leaf_nodes : int, default=None Grow trees with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_decrease : float, default=0.0 A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of samples, ``N_t`` is the number of samples at the current node, ``N_t_L`` is the number of samples in the left child, and ``N_t_R`` is the number of samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. .. versionadded:: 0.19 bootstrap : bool, default=False Whether bootstrap samples are used when building trees. If False, the whole dataset is used to build each tree. oob_score : bool or callable, default=False Whether to use out-of-bag samples to estimate the generalization score. By default, :func:`~sklearn.metrics.r2_score` is used. Provide a callable with signature `metric(y_true, y_pred)` to use a custom metric. Only available if `bootstrap=True`. For an illustration of out-of-bag (OOB) error estimation, see the example :ref:`sphx_glr_auto_examples_ensemble_plot_ensemble_oob.py`. n_jobs : int, default=None The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`, :meth:`decision_path` and :meth:`apply` are all parallelized over the trees. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. random_state : int, RandomState instance or None, default=None Controls 3 sources of randomness: - the bootstrapping of the samples used when building trees (if ``bootstrap=True``) - the sampling of the features to consider when looking for the best split at each node (if ``max_features < n_features``) - the draw of the splits for each of the `max_features` See :term:`Glossary <random_state>` for details. verbose : int, default=0 Controls the verbosity when fitting and predicting. warm_start : bool, default=False When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. See :term:`Glossary <warm_start>` and :ref:`tree_ensemble_warm_start` for details. ccp_alpha : non-negative float, default=0.0 Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ``ccp_alpha`` will be chosen. By default, no pruning is performed. See :ref:`minimal_cost_complexity_pruning` for details. See :ref:`sphx_glr_auto_examples_tree_plot_cost_complexity_pruning.py` for an example of such pruning. .. versionadded:: 0.22 max_samples : int or float, default=None If bootstrap is True, the number of samples to draw from X to train each base estimator. - If None (default), then draw `X.shape[0]` samples. - If int, then draw `max_samples` samples. - If float, then draw `max_samples * X.shape[0]` samples. Thus, `max_samples` should be in the interval `(0.0, 1.0]`. .. versionadded:: 0.22 monotonic_cst : array-like of int of shape (n_features), default=None Indicates the monotonicity constraint to enforce on each feature. - 1: monotonically increasing - 0: no constraint - -1: monotonically decreasing If monotonic_cst is None, no constraints are applied. Monotonicity constraints are not supported for: - multioutput regressions (i.e. when `n_outputs_ > 1`), - regressions trained on data with missing values. Read more in the :ref:`User Guide <monotonic_cst_gbdt>`. .. versionadded:: 1.4 Attributes ---------- estimator_ : :class:`~sklearn.tree.ExtraTreeRegressor` The child estimator template used to create the collection of fitted sub-estimators. .. versionadded:: 1.2 `base_estimator_` was renamed to `estimator_`. estimators_ : list of DecisionTreeRegressor The collection of fitted sub-estimators. feature_importances_ : ndarray of shape (n_features,) The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See :func:`sklearn.inspection.permutation_importance` as an alternative. n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 0.24 feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Defined only when `X` has feature names that are all strings. .. versionadded:: 1.0 n_outputs_ : int The number of outputs. oob_score_ : float Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when ``oob_score`` is True. oob_prediction_ : ndarray of shape (n_samples,) or (n_samples, n_outputs) Prediction computed with out-of-bag estimate on the training set. This attribute exists only when ``oob_score`` is True. estimators_samples_ : list of arrays The subset of drawn samples (i.e., the in-bag samples) for each base estimator. Each subset is defined by an array of the indices selected. .. versionadded:: 1.4 See Also -------- ExtraTreesClassifier : An extra-trees classifier with random splits. RandomForestClassifier : A random forest classifier with optimal splits. RandomForestRegressor : Ensemble regressor using trees with optimal splits. Notes ----- The default values for the parameters controlling the size of the trees (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values. References ---------- .. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", Machine Learning, 63(1), 3-42, 2006. Examples -------- >>> from sklearn.datasets import load_diabetes >>> from sklearn.model_selection import train_test_split >>> from sklearn.ensemble import ExtraTreesRegressor >>> X, y = load_diabetes(return_X_y=True) >>> X_train, X_test, y_train, y_test = train_test_split( ... X, y, random_state=0) >>> reg = ExtraTreesRegressor(n_estimators=100, random_state=0).fit( ... X_train, y_train) >>> reg.score(X_test, y_test) 0.2727... """ _parameter_constraints: dict = { **ForestRegressor._parameter_constraints, **DecisionTreeRegressor._parameter_constraints, } _parameter_constraints.pop("splitter") def __init__( self, n_estimators=100, *, criterion="squared_error", max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features=1.0, max_leaf_nodes=None, min_impurity_decrease=0.0, bootstrap=False, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, ccp_alpha=0.0, max_samples=None, monotonic_cst=None, ): super().__init__( estimator=ExtraTreeRegressor(), n_estimators=n_estimators, estimator_params=( "criterion", "max_depth", "min_samples_split", "min_samples_leaf", "min_weight_fraction_leaf", "max_features", "max_leaf_nodes", "min_impurity_decrease", "random_state", "ccp_alpha", "monotonic_cst", ), bootstrap=bootstrap, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start, max_samples=max_samples, ) self.criterion = criterion self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_features = max_features self.max_leaf_nodes = max_leaf_nodes self.min_impurity_decrease = min_impurity_decrease self.ccp_alpha = ccp_alpha self.monotonic_cst = monotonic_cst
ExtraTreesRegressor
python
getsentry__sentry-python
sentry_sdk/integrations/grpc/aio/client.py
{ "start": 1283, "end": 2292 }
class ____(ClientInterceptor, UnaryUnaryClientInterceptor): # type: ignore async def intercept_unary_unary( self, continuation: Callable[[ClientCallDetails, Message], UnaryUnaryCall], client_call_details: ClientCallDetails, request: Message, ) -> Union[UnaryUnaryCall, Message]: method = client_call_details.method with sentry_sdk.start_span( op=OP.GRPC_CLIENT, name="unary unary call to %s" % method.decode(), origin=SPAN_ORIGIN, ) as span: span.set_data("type", "unary unary") span.set_data("method", method) client_call_details = self._update_client_call_details_metadata_from_scope( client_call_details ) response = await continuation(client_call_details, request) status_code = await response.code() span.set_data("code", status_code.name) return response
SentryUnaryUnaryClientInterceptor
python
Netflix__metaflow
metaflow/plugins/cards/card_modules/chevron/tokenizer.py
{ "start": 52, "end": 7400 }
class ____(SyntaxError): pass # # Helper functions # def grab_literal(template, l_del): """Parse a literal from the template""" global _CURRENT_LINE try: # Look for the next tag and move the template to it literal, template = template.split(l_del, 1) _CURRENT_LINE += literal.count("\n") return (literal, template) # There are no more tags in the template? except ValueError: # Then the rest of the template is a literal return (template, "") def l_sa_check(template, literal, is_standalone): """Do a preliminary check to see if a tag could be a standalone""" # If there is a newline, or the previous tag was a standalone if literal.find("\n") != -1 or is_standalone: padding = literal.split("\n")[-1] # If all the characters since the last newline are spaces if padding.isspace() or padding == "": # Then the next tag could be a standalone return True else: # Otherwise it can't be return False def r_sa_check(template, tag_type, is_standalone): """Do a final checkto see if a tag could be a standalone""" # Check right side if we might be a standalone if is_standalone and tag_type not in ["variable", "no escape"]: on_newline = template.split("\n", 1) # If the stuff to the right of us are spaces we're a standalone if on_newline[0].isspace() or not on_newline[0]: return True else: return False # If we're a tag can't be a standalone else: return False def parse_tag(template, l_del, r_del): """Parse a tag from a template""" global _CURRENT_LINE global _LAST_TAG_LINE tag_types = { "!": "comment", "#": "section", "^": "inverted section", "/": "end", ">": "partial", "=": "set delimiter?", "{": "no escape?", "&": "no escape", } # Get the tag try: tag, template = template.split(r_del, 1) except ValueError: raise ChevronError("unclosed tag " "at line {0}".format(_CURRENT_LINE)) # Find the type meaning of the first character tag_type = tag_types.get(tag[0], "variable") # If the type is not a variable if tag_type != "variable": # Then that first character is not needed tag = tag[1:] # If we might be a set delimiter tag if tag_type == "set delimiter?": # Double check to make sure we are if tag.endswith("="): tag_type = "set delimiter" # Remove the equal sign tag = tag[:-1] # Otherwise we should complain else: raise ChevronError( "unclosed set delimiter tag\n" "at line {0}".format(_CURRENT_LINE) ) # If we might be a no html escape tag elif tag_type == "no escape?": # And we have a third curly brace # (And are using curly braces as delimiters) if l_del == "{{" and r_del == "}}" and template.startswith("}"): # Then we are a no html escape tag template = template[1:] tag_type = "no escape" # Strip the whitespace off the key and return return ((tag_type, tag.strip()), template) # # The main tokenizing function # def tokenize(template, def_ldel="{{", def_rdel="}}"): """Tokenize a mustache template Tokenizes a mustache template in a generator fashion, using file-like objects. It also accepts a string containing the template. Arguments: template -- a file-like object, or a string of a mustache template def_ldel -- The default left delimiter ("{{" by default, as in spec compliant mustache) def_rdel -- The default right delimiter ("}}" by default, as in spec compliant mustache) Returns: A generator of mustache tags in the form of a tuple -- (tag_type, tag_key) Where tag_type is one of: * literal * section * inverted section * end * partial * no escape And tag_key is either the key or in the case of a literal tag, the literal itself. """ global _CURRENT_LINE, _LAST_TAG_LINE _CURRENT_LINE = 1 _LAST_TAG_LINE = None # If the template is a file-like object then read it try: template = template.read() except AttributeError: pass is_standalone = True open_sections = [] l_del = def_ldel r_del = def_rdel while template: literal, template = grab_literal(template, l_del) # If the template is completed if not template: # Then yield the literal and leave yield ("literal", literal) break # Do the first check to see if we could be a standalone is_standalone = l_sa_check(template, literal, is_standalone) # Parse the tag tag, template = parse_tag(template, l_del, r_del) tag_type, tag_key = tag # Special tag logic # If we are a set delimiter tag if tag_type == "set delimiter": # Then get and set the delimiters dels = tag_key.strip().split(" ") l_del, r_del = dels[0], dels[-1] # If we are a section tag elif tag_type in ["section", "inverted section"]: # Then open a new section open_sections.append(tag_key) _LAST_TAG_LINE = _CURRENT_LINE # If we are an end tag elif tag_type == "end": # Then check to see if the last opened section # is the same as us try: last_section = open_sections.pop() except IndexError: raise ChevronError( 'Trying to close tag "{0}"\n' "Looks like it was not opened.\n" "line {1}".format(tag_key, _CURRENT_LINE + 1) ) if tag_key != last_section: # Otherwise we need to complain raise ChevronError( 'Trying to close tag "{0}"\n' 'last open tag is "{1}"\n' "line {2}".format(tag_key, last_section, _CURRENT_LINE + 1) ) # Do the second check to see if we're a standalone is_standalone = r_sa_check(template, tag_type, is_standalone) # Which if we are if is_standalone: # Remove the stuff before the newline template = template.split("\n", 1)[-1] # Partials need to keep the spaces on their left if tag_type != "partial": # But other tags don't literal = literal.rstrip(" ") # Start yielding # Ignore literals that are empty if literal != "": yield ("literal", literal) # Ignore comments and set delimiters if tag_type not in ["comment", "set delimiter?"]: yield (tag_type, tag_key) # If there are any open sections when we're done if open_sections: # Then we need to complain raise ChevronError( "Unexpected EOF\n" 'the tag "{0}" was never closed\n' "was opened at line {1}".format(open_sections[-1], _LAST_TAG_LINE) )
ChevronError
python
django__django
django/contrib/auth/backends.py
{ "start": 12845, "end": 12965 }
class ____(RemoteUserBackend): def user_can_authenticate(self, user): return True
AllowAllUsersRemoteUserBackend
python
pytorch__pytorch
torch/_inductor/ir.py
{ "start": 39910, "end": 69805 }
class ____(Loops): reduction_ranges: Sequence[_IntLike] reduction_type: ReductionType # self.dtype represents the dst dtype src_dtype: torch.dtype reduction_hint: ReductionHint def __str__(self) -> str: return self._to_str(("ranges", "reduction_ranges", "reduction_type")) __repr__ = __str__ @cache_on_self_and_args("Reduction") def get_free_symbol_uses(self, unbacked_only: bool = False) -> OrderedSet[Symbol]: return super().get_free_symbol_uses(unbacked_only) | OrderedSet().union( *(get_free_symbols(e, unbacked_only) for e in self.reduction_ranges) ) def get_reduction_size(self) -> Sequence[Expr]: return self.reduction_ranges def get_reduction_type(self) -> Optional[str]: return self.reduction_type def store_reduction( self, output_name: Optional[str], indexer: Callable[[Sequence[Expr]], Never], vars: Sequence[Expr], reduction_vars: Sequence[Symbol], ) -> None: value = ops.reduction( self.dtype, self.src_dtype, self.reduction_type, self.inner_fn(vars, reduction_vars), ) ops.store_reduction(output_name or "unnamed", indexer(vars), value) def index_length(self) -> int: return len(self.ranges) + len(self.reduction_ranges) def inner_fn_args(self) -> Sequence[Sequence[Expr]]: index = self._index(self.ranges) rindex = self._index(self.reduction_ranges, SymT.R0_INDEX) return (index, rindex) def inner_fn_free_symbols(self, unbacked_only: bool = False) -> OrderedSet[Symbol]: index = self._index(self.ranges) rindex = self._index(self.reduction_ranges, SymT.R0_INDEX) return extract_free_symbols( self.inner_fn, index, rindex, unbacked_only=unbacked_only ) def constant_to_device(self, device: torch.device) -> IRNode: """Move this to a given device. Requires that all reads are to constants.""" loader = self.make_loader() loader = patch.object(ConstantBuffer, "override_device", device)(loader) return Reduction( device=device, dtype=self.dtype, inner_fn=loader, ranges=self.ranges, reduction_ranges=self.reduction_ranges, reduction_type=self.reduction_type, src_dtype=self.src_dtype, reduction_hint=ReductionHint.DEFAULT, ) @staticmethod def num_splits( device: torch.device, dst_dtype: torch.dtype, src_dtype: torch.dtype, inner_fn: Callable[_P, OpsValue], ranges: Sequence[_IntLike], reduction_ranges: Sequence[_IntLike], reduction_type: Union[ReductionType, Literal["scan"]], reduction_numel: Expr, input_node: Optional[IRNode] = None, ) -> tuple[ReductionHint, _IntLike]: reduction_numel_hint = V.graph.sizevars.symbolic_hint(reduction_numel) numel_hint = V.graph.sizevars.symbolic_hint(sympy_product(ranges)) should_split = reduction_type == "scan" or ( not V.graph.has_feature(device, BackendFeature.REDUCE_TO_SINGLE_ELEMENT) and reduction_type not in ( "argmax", "argmin", ) and config.split_reductions ) if not (_is_static(reduction_numel_hint) and _is_static(numel_hint)): # We don't support unbacked symints return ReductionHint.DEFAULT, 1 if reduction_type == "dot": # Don't split when doing native matmul return ReductionHint.DEFAULT, 1 props = DeviceProperties.create(device) num_sm = props.multi_processor_count min_elements_per_thread = 32 if should_split: inner_reduction_splits: Callable[[int, int], int] = functools.partial( V.choices.reduction_split_factor, device, inner_reduction=True ) outer_reduction_splits: Callable[[int, int], int] = functools.partial( V.choices.reduction_split_factor, device, inner_reduction=False ) else: def inner_reduction_splits( reduction_numel_hint: int, numel_hint: int, ) -> int: return 1 outer_reduction_splits = inner_reduction_splits # easy cases if numel_hint == 1: split = inner_reduction_splits(reduction_numel_hint, numel_hint) if split == 1: # No need to split. return ReductionHint.INNER, split if input_node is not None and isinstance(input_node, TensorBox): with patch.object(FlexibleLayout, "allow_indexing", True): ( new_ranges, new_reduction_ranges, ) = extract_input_node_reduction_ranges(input_node) if new_ranges is not None and new_reduction_ranges is not None: extracted_numel_hint = V.graph.sizevars.symbolic_hint( sympy_product(new_ranges + new_reduction_ranges) ) if reduction_numel_hint == extracted_numel_hint: log.debug( "Use previous IRNode's range and reduction_ranges instead of split. " "current ranges: %s, current reduction ranges: %s, current split: %d, " "new ranges: %s, new reduction ranges: %s", ranges, reduction_ranges, split, new_ranges, new_reduction_ranges, ) # If the input_node or its dependent nodes are also Reduction nodes, # use reduction_sizes of this node or its dependent nodes directly. return ReductionHint.INNER, -1 return ReductionHint.INNER, split if ( reduction_numel_hint <= min_elements_per_thread or numel_hint >= num_sm * 2 * 32 ): return ReductionHint.DEFAULT, 1 r = Reduction( device=device, dtype=dst_dtype, inner_fn=inner_fn, ranges=ranges, reduction_ranges=reduction_ranges, reduction_type=reduction_type if reduction_type != "scan" else "sum", src_dtype=src_dtype, reduction_hint=ReductionHint.DEFAULT, ) def get_read_indices(r: Reduction) -> tuple[Sequence[Expr], bool]: device = r.get_device() assert device is not None cb = ComputedBuffer( name=None, layout=FlexibleLayout( device=device, dtype=r.get_dtype(), size=r.get_size(), ), data=r, ) read_writes = cb.get_read_writes() # try finding the full size producer # TODO this will fail for something like ((1, N) * (N, 1)).sum() # this would also possibly be wrong for producers with the different contiguity but we hope those cases are rare assert read_writes.range_vars is not None range_vars = [ r for r in read_writes.range_vars if isinstance(r, Expr) and not isinstance(r, sympy.Number) ] indices = [] changed = False for md in sorted(read_writes.reads, key=lambda x: x.name): if all(r in md.index.free_symbols for r in range_vars): indices.append(md.index) if md.name in V.graph.name_to_buffer: buf = V.graph.name_to_buffer[md.name] original_stride = getattr(buf.layout, "stride", None) buf.decide_layout() if getattr(buf.layout, "stride", None) != original_stride: changed = True return indices, changed indices, changed = get_read_indices(r) if changed: indices, _ = get_read_indices(r) if len(indices) == 0: # TODO determine splits when all inputs are broadcast return ReductionHint.DEFAULT, 1 (_, reduction_vars), ranges1 = dependencies.index_vars_squeeze( r.get_size(), r.get_reduction_size() ) num_outer = 0 num_inner = 0 for i in indices: j = V.graph.sizevars.simplify_with_ranges(i, ranges1) strides = V.graph.sizevars.stride_hints( j, reduction_vars, list(ranges1.keys()) ) outer = all(s > 1 for s in strides) if outer: num_outer += 1 else: num_inner += 1 if num_inner > num_outer: return ReductionHint.INNER, inner_reduction_splits( reduction_numel_hint, numel_hint ) else: return ReductionHint.OUTER, outer_reduction_splits( reduction_numel_hint, numel_hint ) @staticmethod def _unroll_reduction_fn( inner_fn: Callable[[Sequence[_IntLike], Sequence[_IntLike]], OpsValue], reduction_ranges: Sequence[_IntLike], reduction_type: str, src_dtype: torch.dtype, ) -> Callable[[Sequence[_IntLike]], OpsValue]: """Convert inner_fn from a reduction to an pointwise""" reduction_ranges = V.graph.sizevars.guard_int_seq(reduction_ranges) combine_fn = get_reduction_combine_fn(reduction_type, src_dtype) def fn(index: Sequence[_IntLike]) -> Any: return functools.reduce( combine_fn, ( value_fn(index, rindex) for rindex in itertools.product( *[range(x) for x in reduction_ranges] ) ), ) value_fn: Callable[[Sequence[_IntLike], Sequence[_IntLike]], Any] if reduction_type in ("argmin", "argmax"): flatten_index = _fixed_indexer( reduction_ranges, FlexibleLayout.contiguous_strides(reduction_ranges), ) def value_fn( index: Sequence[_IntLike], rindex: Sequence[_IntLike] ) -> tuple[OpsValue, OpsValue]: rindex = [sympy.expand(i) for i in rindex] return ( inner_fn(index, rindex), ops.index_expr(flatten_index(rindex), torch.int64), ) return lambda index: fn(index)[1] else: value_fn = inner_fn return fn @classmethod # pyrefly: ignore [bad-override] def create( cls, device: torch.device, dst_dtype: torch.dtype, src_dtype: torch.dtype, inner_fn: Callable[..., Any], ranges: Sequence[Expr], reduction_ranges: Sequence[Expr], reduction_type: ReductionType, reduction_hint: ReductionHint = ReductionHint.DEFAULT, input_node: Optional[IRNode] = None, ) -> Union[TensorBox, ShapeAsConstantBuffer]: """ Create a reduction node. May split the reduction to multiple layers to expose more parallelism. """ reduction_numel = V.graph.sizevars.simplify(sympy_product(reduction_ranges)) if reduction_numel == 0: # N.B. This is a hack to generate the literal of the given type # Ideally, we should be fixing `def constant` in triton.py # but it breaks due to hardcoded dtypes in other places def py_cnst(val: object) -> Union[bool, float, int]: if dst_dtype == torch.bool: return bool(val) elif dst_dtype.is_floating_point: assert isinstance(val, SupportsFloat), type(val) return float(val) else: assert isinstance(val, SupportsInt), type(val) return int(val) rtypes_to_inits = { "sum": py_cnst(0), "xor_sum": py_cnst(0), "prod": py_cnst(1), "any": py_cnst(0), # "all" is desugared to `!any(!val)` } assert reduction_type in rtypes_to_inits, ( f"{reduction_type} not supported for zero-dimension tensors!" ) def const_fn(index: int) -> OpsValue: return ops.constant(rtypes_to_inits[reduction_type], dst_dtype) return Pointwise.create( device=device, dtype=src_dtype, inner_fn=const_fn, ranges=list(ranges), ) if reduction_numel == 1: # this reduction is actually a pointwise op if reduction_type in ("argmin", "argmax"): def fn(index: int) -> OpsValue: return ops.constant(0, dst_dtype) else: def fn(index: int) -> OpsValue: reduction_index = [sympy.S.Zero for _ in reduction_ranges] return inner_fn(index, reduction_index) return Pointwise.create( device=device, dtype=dst_dtype, inner_fn=fn, ranges=ranges ) if ( isinstance(reduction_numel, Integer) and V.graph.sizevars.size_hint_or_throw(reduction_numel) < config.unroll_reductions_threshold and (sympy_product(ranges) != 1 or is_gpu(device.type)) and reduction_type != "dot" ): # When native matmul, don't unroll the dot reduction. # NB: This works around https://github.com/pytorch/pytorch/issues/140457 # since turning reductions into pointwise ops can exacerbate this problem return Pointwise.create( device=device, dtype=dst_dtype, inner_fn=cls._unroll_reduction_fn( inner_fn, reduction_ranges, reduction_type, src_dtype ), ranges=ranges, ) # triton doesn't support reduce to single element well, so break it up hint, split = cls.num_splits( device, dst_dtype, src_dtype, inner_fn, ranges, reduction_ranges, reduction_type, reduction_numel, input_node, ) def _maybe_increase_split(split: int) -> int: # don't apply min_num_split constraint for static shape case. if _is_static(reduction_numel): return split if split > 1: return max(split, config.min_num_split) else: return split split = _maybe_increase_split(split) # intermediate reduction in split can contain complex indexing, # and num_splits will fail to correctly set the hint # reuse the passed hint if available if reduction_hint == ReductionHint.DEFAULT: reduction_hint = hint if split == -1: assert input_node is not None with patch.object(FlexibleLayout, "allow_indexing", True): new_ranges, new_reduction_ranges = extract_input_node_reduction_ranges( input_node ) assert new_ranges is not None assert new_reduction_ranges is not None return cls.create_multilayer_existing_ranges( device, dst_dtype, src_dtype, inner_fn, ranges, reduction_ranges, new_ranges, new_reduction_ranges, reduction_type, reduction_hint, ) elif split > 1: # triton doesn't support reduce to single element well, so break it up out = cls.create_multilayer( device, dst_dtype, src_dtype, inner_fn, ranges, reduction_ranges, reduction_type, split, reduction_hint, input_node, ) # Find the reduction that get split split_reduction = None if config.triton.mix_order_reduction and isinstance(out, TensorBox): def _find_split_reduction( cur_node: TensorBox, ) -> Optional[ComputedBuffer]: read_names = cur_node.get_read_names() if len(read_names) != 1: return None bufname = next(iter(read_names)) if bufname not in V.graph.name_to_buffer: return None buf = V.graph.name_to_buffer[bufname] if not isinstance(buf, ComputedBuffer): return None assert buf.data.get_reduction_type() is not None return buf split_reduction = _find_split_reduction(out) if split_reduction: # If a reduction is split to more than 2 layers, # say there are 3 layers, # we always have the correct setting for layer1 (top layer). # The setting on layer2 may be incorrect but it's fine # since they are never get used. # TODO: should we skip setting these fields for layer2 assert isinstance(split_reduction.data, Reduction), ( f"{type(split_reduction.data)}" ) split_reduction._split_size = split_reduction.data.reduction_ranges[0] split_reduction._original_inner_fn = inner_fn split_reduction._original_ranges = ranges split_reduction._original_reduction_ranges = reduction_ranges return out out = TensorBox.create( Reduction( device=device, dtype=dst_dtype, inner_fn=inner_fn, ranges=ranges, reduction_ranges=reduction_ranges, reduction_type=reduction_type, src_dtype=src_dtype, reduction_hint=reduction_hint, ) ) return out @staticmethod def default_accumulator( reduction_type: str, dtype: torch.dtype ) -> Union[_NumLike, Sequence[_NumLike]]: if reduction_type in ("max", "argmax"): if is_float_dtype(dtype): return float("-inf") elif is_boolean_dtype(dtype): return False else: return torch.iinfo(dtype).min if reduction_type in ("min", "argmin"): if is_float_dtype(dtype): return float("inf") elif is_boolean_dtype(dtype): return True else: return torch.iinfo(dtype).max zero = False if is_boolean_dtype(dtype) else 0 one = True if is_boolean_dtype(dtype) else 1 return { "sum": zero, "prod": one, "dot": zero, "xor_sum": zero, "any": zero, "welford_reduce": (zero, zero, zero), "welford_combine": (zero, zero, zero), "online_softmax_reduce": (float("-inf"), zero), }[reduction_type] @staticmethod def default_value( reduction_type: str, dtype: torch.dtype ) -> Union[_NumLike, Sequence[_NumLike]]: if reduction_type == "welford_reduce": return 0 return Reduction.default_accumulator(reduction_type, dtype) @staticmethod def _multilayer_second_step_hint( split: _IntLike, numel_hint: int, reduction_hint: ReductionHint ) -> ReductionHint: if split == -1: return reduction_hint if split <= 512 and numel_hint <= 512 and reduction_hint == ReductionHint.OUTER: return ReductionHint.OUTER_TINY if ( split <= 1024 and numel_hint <= 256 and reduction_hint == ReductionHint.OUTER ): return ReductionHint.OUTER_TINY return reduction_hint @classmethod def check_for_split_dense_dim_reindexing( cls, reduction_numel: _IntLike, input_node: Optional[IRNode] ) -> Optional[int]: """ If we are reducing over the full tensor, and it is non-dense in the last dimension, reindex so we reduce over the dense dimension. initially just handle complete reduction case """ if input_node is None: return None if not V.graph.sizevars.statically_known_equals( input_node.get_numel(), reduction_numel ): return None input_node.realize() try: # finalize layout as_storage_and_layout(input_node) except NotImplementedError: return None strides = input_node.get_stride() for i, s in enumerate(strides[:-1]): if V.graph.sizevars.statically_known_equals(s, 1): return i return None @classmethod def _multilayer_wrap_loader( cls, loader: Callable[..., OpsValue], reduction_ranges: Sequence[_IntLike], reduction_numel: _IntLike, split: _IntLike, block_size: _IntLike, default: Union[_NumLike, Sequence[_NumLike]], input_node: Optional[IRNode] = None, ) -> Callable[..., object]: dense_index = cls.check_for_split_dense_dim_reindexing( reduction_numel, input_node ) reindex = View.dynamic_reshape_indexer( reduction_ranges, [reduction_numel], dense_index ) need_mask = not V.graph.sizevars.statically_known_true( sympy.Eq(reduction_numel % split, 0) ) def wrapper_fn( index: Sequence[Symbol], reduction_index: Sequence[Symbol] ) -> OpsValue: (reduction_index,) = reduction_index *new_index, reduction_block = index indices = block_size * reduction_block + reduction_index def body() -> OpsValue: return loader(new_index, reindex([indices])) if need_mask: index_dtype = dtype_from_size(reduction_numel) mask = ops.lt( ops.index_expr(indices, index_dtype), ops.index_expr(reduction_numel, index_dtype), ) return ops.masked(mask, body, default) else: return body() return wrapper_fn @classmethod def _multilayer_wrap_loader_existing_ranges( cls, loader: Callable[[Sequence[Expr], Sequence[Expr]], OpsValue], original_ranges: Sequence[Expr], original_reduction_ranges: Sequence[Expr], new_ranges: Sequence[Integer], new_reduction_ranges: Sequence[Integer], ) -> Callable[[Sequence[sympy.Expr], Sequence[sympy.Expr]], OpsValue]: assert all(r == 1 for r in original_ranges), ( f"Only enabled for numel_hint == 1, found {original_ranges=}" ) reindex = View.dynamic_reshape_indexer( original_reduction_ranges, tuple(new_ranges) + tuple(new_reduction_ranges) ) def wrapper_fn( merged_index: Sequence[Expr], new_reduction_index: Sequence[Expr], ) -> OpsValue: original_idx = merged_index[: len(original_ranges)] new_index = merged_index[len(original_ranges) :] return loader( original_idx, reindex(tuple(new_index) + tuple(new_reduction_index)), ) return wrapper_fn @classmethod def create_multilayer_helper( cls, device: torch.device, dst_dtype: torch.dtype, src_dtype: torch.dtype, wrapper_fn: Callable[..., Any], original_ranges: Sequence[Expr], original_reduction_ranges: Sequence[Expr], new_ranges: list[Expr], new_reduction_ranges: list[Integer], reduction_type: ReductionType, split: _IntLike, reduction_hint: ReductionHint, ) -> Union[TensorBox, ShapeAsConstantBuffer]: """ Break a large reduction up into multiple smaller reductions recursively """ # triton will automatically compute reductions in fp32 if reducing over fp16/bf16 # within the kernel. keep the intermediate in fp32 so as to keep the whole reduction # in fp32 and not reduce precision by breaking up the kernel into multiple layers intermediate_dtype = ( dst_dtype if dst_dtype not in (torch.float16, torch.bfloat16) else torch.float ) intermediate = Reduction.create( device, intermediate_dtype, src_dtype, wrapper_fn, new_ranges, new_reduction_ranges, reduction_type, reduction_hint, ) intermediate.realize() intermediate_loader = intermediate.make_loader() def intermediate_fn( index: Sequence[_IntLike], reduction_index: Sequence[_IntLike] ) -> OpsValue: return intermediate_loader([*index, *reduction_index]) numel_hint = V.graph.sizevars.size_hint(sympy_product(original_ranges)) reduction_hint = cls._multilayer_second_step_hint( split, numel_hint, reduction_hint ) assert original_ranges == new_ranges[: len(original_ranges)] return TensorBox.create( Reduction( device=device, dtype=dst_dtype, inner_fn=intermediate_fn, ranges=original_ranges, reduction_ranges=new_ranges[len(original_ranges) :], reduction_type=reduction_type, src_dtype=src_dtype, reduction_hint=reduction_hint, ) ) @classmethod def create_multilayer( cls, device: torch.device, dst_dtype: torch.dtype, src_dtype: torch.dtype, inner_fn: Callable[..., Any], ranges: Sequence[Expr], reduction_ranges: Sequence[Expr], reduction_type: ReductionType, split: _IntLike, reduction_hint: ReductionHint, input_node: Optional[IRNode] = None, ) -> Union[TensorBox, ShapeAsConstantBuffer]: """ Break a large reduction up into multiple smaller reductions recursively """ # TODO(jansel): realize the reduction so we can do dynamic indexing reduction_numel = sympy_product(reduction_ranges) block_size = FloorDiv(reduction_numel + (split - 1), split) default = cls.default_value(reduction_type, dst_dtype) wrapper_fn = cls._multilayer_wrap_loader( inner_fn, reduction_ranges, reduction_numel, split, block_size, default, input_node, ) return cls.create_multilayer_helper( device, dst_dtype, src_dtype, wrapper_fn, ranges, reduction_ranges, [*ranges, split], [block_size], reduction_type, split, reduction_hint, ) @classmethod def create_multilayer_existing_ranges( cls, device: torch.device, dst_dtype: torch.dtype, src_dtype: torch.dtype, inner_fn: Callable[..., Any], original_ranges: Sequence[Expr], original_reduction_ranges: Sequence[Expr], new_ranges: list[Integer], new_reduction_ranges: list[Integer], reduction_type: ReductionType, reduction_hint: ReductionHint, ) -> Union[TensorBox, ShapeAsConstantBuffer]: """ Break a large reduction up into multiple smaller reductions recursively """ wrapper_fn = cls._multilayer_wrap_loader_existing_ranges( inner_fn, original_ranges, original_reduction_ranges, new_ranges, new_reduction_ranges, ) return cls.create_multilayer_helper( device, dst_dtype, src_dtype, wrapper_fn, original_ranges, original_reduction_ranges, [*original_ranges, *new_ranges], new_reduction_ranges, reduction_type, -1, reduction_hint, ) def _fixed_indexer( size: Sequence[int], stride: Optional[Sequence[int]] = None, offset: Expr = Integer(0), ) -> Callable[[Sequence[Expr]], Expr]: """A closure containing math to read a given element""" def indexer(index: Sequence[int]) -> int: assert stride is not None and len(index) == len(stride) assert len(index) == len(size) result = offset for idx, st, sz in zip(index, stride, size): if sz != 1: result = result + idx * st return result return indexer INNER_FN_TY: TypeAlias = Callable[[Sequence[Expr], Sequence[Expr]], OpsValue]
Reduction
python
pydantic__pydantic
tests/mypy/outputs/mypy-default_ini/root_models.py
{ "start": 606, "end": 1578 }
class ____(BaseModel, Generic[V]): m1: Maybe[int] m2: Maybe[V] m3: Maybe # MYPY: error: Missing type parameters for generic type "Maybe" [type-arg] Model[str](m1=1, m2='dog', m3=[]) # MYPY: error: Argument "m1" to "Model" has incompatible type "int"; expected "Maybe[int]" [arg-type] # MYPY: error: Argument "m2" to "Model" has incompatible type "str"; expected "Maybe[str]" [arg-type] # MYPY: error: Argument "m3" to "Model" has incompatible type "list[Never]"; expected "Maybe[Any]" [arg-type] m = Model[str](m1=Maybe(None), m2=Maybe('dog'), m3=Maybe([])) Model(m1=None, m2={}, m3=[]) # MYPY: error: Argument "m1" to "Model" has incompatible type "None"; expected "Maybe[int]" [arg-type] # MYPY: error: Argument "m2" to "Model" has incompatible type "dict[Never, Never]"; expected "Maybe[Never]" [arg-type] # MYPY: error: Argument "m3" to "Model" has incompatible type "list[Never]"; expected "Maybe[Any]" [arg-type] assert_type(m.m1, Maybe[int])
Model
python
great-expectations__great_expectations
great_expectations/render/components.py
{ "start": 7222, "end": 8415 }
class ____(RenderedComponentContent): def __init__( self, header, subheader=None, header_row=None, styling=None, content_block_type="header", ) -> None: super().__init__(content_block_type=content_block_type, styling=styling) self.header = header self.header_row = header_row self.subheader = subheader @override def to_json_dict(self) -> dict[str, JSONValues]: """Returns a JSON-serializable dict representation of this RenderedHeaderContent. Returns: A JSON-serializable dict representation of this RenderedHeaderContent. """ d = super().to_json_dict() if isinstance(self.header, RenderedContent): d["header"] = self.header.to_json_dict() else: d["header"] = self.header if self.subheader is not None: if isinstance(self.subheader, RenderedContent): d["subheader"] = self.subheader.to_json_dict() else: d["subheader"] = self.subheader if self.header_row: d["header_row"] = self.header_row return d
RenderedHeaderContent
python
getsentry__sentry
src/sentry/api/endpoints/organization_events_meta.py
{ "start": 7270, "end": 13826 }
class ____(OrganizationEventsV2EndpointBase): publish_status = { "GET": ApiPublishStatus.PRIVATE, } def get(self, request: Request, organization: Organization) -> Response: try: snuba_params = self.get_snuba_params(request, organization) except NoProjects: return Response({}) use_eap = request.GET.get("dataset", None) == "spans" orderby = self.get_orderby(request) or ["timestamp"] with handle_query_errors(): if use_eap: result = get_eap_span_samples(request, snuba_params, orderby) dataset = Spans else: result = get_span_samples(request, snuba_params, orderby) dataset = spans_indexed return Response( self.handle_results_with_meta( request, organization, snuba_params.project_ids, {"data": result["data"], "meta": result["meta"]}, True, dataset, ) ) def get_span_samples( request: Request, snuba_params: SnubaParams, orderby: list[str] | None ) -> EventsResponse: is_frontend = is_frontend_request(request) buckets = request.GET.get("intervals", 3) lower_bound = request.GET.get("lowerBound", 0) first_bound = request.GET.get("firstBound") second_bound = request.GET.get("secondBound") upper_bound = request.GET.get("upperBound") column = request.GET.get("column", "span.self_time") selected_columns = request.GET.getlist("additionalFields", []) + [ "project", "transaction.id", column, "timestamp", "span_id", "profile_id", "trace", ] if lower_bound is None or upper_bound is None: bound_results = spans_metrics.query( selected_columns=[ f"p50({column}) as first_bound", f"p95({column}) as second_bound", ], snuba_params=snuba_params, query=request.query_params.get("query"), referrer=Referrer.API_SPAN_SAMPLE_GET_BOUNDS.value, query_source=(QuerySource.FRONTEND if is_frontend else QuerySource.API), ) if len(bound_results["data"]) != 1: raise ParseError("Could not find bounds") bound_data = bound_results["data"][0] first_bound, second_bound = bound_data["first_bound"], bound_data["second_bound"] if lower_bound == 0 or upper_bound == 0: raise ParseError("Could not find bounds") result = spans_indexed.query( selected_columns=[ f"bounded_sample({column}, {lower_bound}, {first_bound}) as lower", f"bounded_sample({column}, {first_bound}, {second_bound}) as middle", f"bounded_sample({column}, {second_bound}{', ' if upper_bound else ''}{upper_bound}) as top", f"rounded_time({buckets})", "profile_id", ], orderby=["-profile_id"], snuba_params=snuba_params, query=request.query_params.get("query"), sample=options.get("insights.span-samples-query.sample-rate") or None, referrer=Referrer.API_SPAN_SAMPLE_GET_SPAN_IDS.value, query_source=(QuerySource.FRONTEND if is_frontend else QuerySource.API), ) span_ids = [] for row in result["data"]: lower, middle, top = row["lower"], row["middle"], row["top"] if lower: span_ids.append(lower) if middle: span_ids.append(middle) if top: span_ids.append(top) if len(span_ids) > 0: query = f"span_id:[{','.join(span_ids)}] {request.query_params.get('query')}" else: query = request.query_params.get("query") return spans_indexed.query( selected_columns=selected_columns, orderby=orderby, snuba_params=snuba_params, query=query, limit=9, referrer=Referrer.API_SPAN_SAMPLE_GET_SPAN_DATA.value, query_source=(QuerySource.FRONTEND if is_frontend else QuerySource.API), transform_alias_to_input_format=True, ) def get_eap_span_samples( request: Request, snuba_params: SnubaParams, orderby: list[str] | None ) -> EAPResponse: lower_bound = request.GET.get("lowerBound", 0) first_bound = request.GET.get("firstBound") second_bound = request.GET.get("secondBound") upper_bound = request.GET.get("upperBound") column = request.GET.get("column", "span.self_time") if first_bound is None or second_bound is None: raise ParseError("Must provide first and second bounds") selected_columns = request.GET.getlist("additionalFields", []) + [ "project", "transaction.span_id", column, "timestamp", "span_id", "profile.id", "trace", ] query_string = request.query_params.get("query") bounds_query_string = f"{column}:>{lower_bound}ms {column}:<{upper_bound}ms {query_string}" rpc_res = Spans.run_table_query( params=snuba_params, query_string=bounds_query_string, config=SearchResolverConfig(), offset=0, limit=100, sampling_mode=snuba_params.sampling_mode, orderby=["-profile.id"], referrer=Referrer.API_SPAN_SAMPLE_GET_SPAN_IDS.value, selected_columns=[ f"bounded_sample({column}, {lower_bound}, {first_bound}) as lower", f"bounded_sample({column}, {first_bound}, {second_bound}) as middle", f"bounded_sample({column}, {second_bound}{', ' if upper_bound else ''}{upper_bound}) as top", "profile.id", "id", ], ) span_ids = [] for row in rpc_res["data"]: lower, middle, top = row["lower"], row["middle"], row["top"] if lower: span_ids.append(row["id"]) if middle: span_ids.append(row["id"]) if top: span_ids.append(row["id"]) samples_query_string = ( f"span_id:[{','.join(span_ids)}] {query_string}" if len(span_ids) > 0 else query_string ) return Spans.run_table_query( params=snuba_params, config=SearchResolverConfig(use_aggregate_conditions=False), offset=0, limit=9, sampling_mode=snuba_params.sampling_mode, query_string=samples_query_string, orderby=orderby, referrer=Referrer.API_SPAN_SAMPLE_GET_SPAN_DATA.value, selected_columns=selected_columns, )
OrganizationSpansSamplesEndpoint
python
python__mypy
mypy/messages.py
{ "start": 114139, "end": 136729 }
class ____(TypeTraverserVisitor): def __init__(self) -> None: self.types: list[Type] = [] def visit_instance(self, t: Instance) -> None: self.types.append(t) super().visit_instance(t) def visit_type_alias_type(self, t: TypeAliasType) -> None: if t.alias and not t.is_recursive: get_proper_type(t).accept(self) else: self.types.append(t) super().visit_type_alias_type(t) def visit_type_var(self, t: TypeVarType) -> None: self.types.append(t) super().visit_type_var(t) def visit_type_var_tuple(self, t: TypeVarTupleType) -> None: self.types.append(t) super().visit_type_var_tuple(t) def visit_param_spec(self, t: ParamSpecType) -> None: self.types.append(t) super().visit_param_spec(t) def scoped_type_var_name(t: TypeVarLikeType) -> str: if not t.id.namespace: return t.name # TODO: support rare cases when both TypeVar name and namespace suffix coincide. *_, suffix = t.id.namespace.split(".") return f"{t.name}@{suffix}" def find_type_overlaps(*types: Type) -> set[str]: """Return a set of fullnames that share a short name and appear in either type. This is used to ensure that distinct types with the same short name are printed with their fullname. """ d: dict[str, set[str]] = {} for type in types: for t in collect_all_named_types(type): if isinstance(t, ProperType) and isinstance(t, Instance): d.setdefault(t.type.name, set()).add(t.type.fullname) elif isinstance(t, TypeAliasType) and t.alias: d.setdefault(t.alias.name, set()).add(t.alias.fullname) else: assert isinstance(t, TypeVarLikeType) d.setdefault(t.name, set()).add(scoped_type_var_name(t)) for shortname in d.keys(): if f"typing.{shortname}" in TYPES_FOR_UNIMPORTED_HINTS: d[shortname].add(f"typing.{shortname}") overlaps: set[str] = set() for fullnames in d.values(): if len(fullnames) > 1: overlaps.update(fullnames) return overlaps def format_type( typ: Type, options: Options, verbosity: int = 0, module_names: bool = False ) -> str: """ Convert a type to a relatively short string suitable for error messages. `verbosity` is a coarse-grained control on the verbosity of the type This function returns a string appropriate for unmodified use in error messages; this means that it will be quoted in most cases. If modification of the formatted string is required, callers should use format_type_bare. """ return quote_type_string(format_type_bare(typ, options, verbosity, module_names)) def format_type_bare( typ: Type, options: Options, verbosity: int = 0, module_names: bool = False ) -> str: """ Convert a type to a relatively short string suitable for error messages. `verbosity` is a coarse-grained control on the verbosity of the type `fullnames` specifies a set of names that should be printed in full This function will return an unquoted string. If a caller doesn't need to perform post-processing on the string output, format_type should be used instead. (The caller may want to use quote_type_string after processing has happened, to maintain consistent quoting in messages.) """ return format_type_inner(typ, verbosity, options, find_type_overlaps(typ), module_names) def format_type_distinctly(*types: Type, options: Options, bare: bool = False) -> tuple[str, ...]: """Jointly format types to distinct strings. Increase the verbosity of the type strings until they become distinct while also requiring that distinct types with the same short name are formatted distinctly. By default, the returned strings are created using format_type() and will be quoted accordingly. If ``bare`` is True, the returned strings will not be quoted; callers who need to do post-processing of the strings before quoting them (such as prepending * or **) should use this. """ overlapping = find_type_overlaps(*types) def format_single(arg: Type) -> str: return format_type_inner(arg, verbosity=0, options=options, fullnames=overlapping) min_verbosity = 0 # Prevent emitting weird errors like: # ... has incompatible type "Callable[[int], Child]"; expected "Callable[[int], Parent]" if len(types) == 2: left, right = types left = get_proper_type(left) right = get_proper_type(right) # If the right type has named arguments, they may be the reason for incompatibility. # This excludes cases when right is Callable[[Something], None] without named args, # because that's usually the right thing to do. if ( isinstance(left, CallableType) and isinstance(right, CallableType) and any(right.arg_names) and is_subtype(left, right, ignore_pos_arg_names=True) ): min_verbosity = 1 for verbosity in range(min_verbosity, 2): strs = [ format_type_inner(type, verbosity=verbosity, options=options, fullnames=overlapping) for type in types ] if len(set(strs)) == len(strs): break if bare: return tuple(strs) else: return tuple(quote_type_string(s) for s in strs) def pretty_class_or_static_decorator(tp: CallableType) -> str | None: """Return @classmethod or @staticmethod, if any, for the given callable type.""" definition = get_func_def(tp) if definition is not None and isinstance(definition, SYMBOL_FUNCBASE_TYPES): if definition.is_class: return "@classmethod" if definition.is_static: return "@staticmethod" return None def pretty_callable(tp: CallableType, options: Options, skip_self: bool = False) -> str: """Return a nice easily-readable representation of a callable type. For example: def [T <: int] f(self, x: int, y: T) -> None If skip_self is True, print an actual callable type, as it would appear when bound on an instance/class, rather than how it would appear in the defining statement. """ s = "" asterisk = False slash = False for i in range(len(tp.arg_types)): if s: s += ", " if tp.arg_kinds[i].is_named() and not asterisk: s += "*, " asterisk = True if tp.arg_kinds[i] == ARG_STAR: s += "*" asterisk = True if tp.arg_kinds[i] == ARG_STAR2: s += "**" name = tp.arg_names[i] if name: s += name + ": " type_str = format_type_bare(tp.arg_types[i], options) if tp.arg_kinds[i] == ARG_STAR2 and tp.unpack_kwargs: type_str = f"Unpack[{type_str}]" s += type_str if tp.arg_kinds[i].is_optional(): s += " = ..." if ( not slash and tp.arg_kinds[i].is_positional() and name is None and ( i == len(tp.arg_types) - 1 or (tp.arg_names[i + 1] is not None or not tp.arg_kinds[i + 1].is_positional()) ) ): s += ", /" slash = True # If we got a "special arg" (i.e: self, cls, etc...), prepend it to the arg list definition = get_func_def(tp) if ( isinstance(definition, FuncDef) and hasattr(definition, "arguments") and not tp.from_concatenate ): definition_arg_names = [arg.variable.name for arg in definition.arguments] if ( len(definition_arg_names) > len(tp.arg_names) and definition_arg_names[0] and not skip_self ): if s: s = ", " + s s = definition_arg_names[0] + s s = f"{definition.name}({s})" elif tp.name: first_arg = get_first_arg(tp) if first_arg: if s: s = ", " + s s = first_arg + s s = f"{tp.name.split()[0]}({s})" # skip "of Class" part else: s = f"({s})" s += " -> " if tp.type_guard is not None: s += f"TypeGuard[{format_type_bare(tp.type_guard, options)}]" elif tp.type_is is not None: s += f"TypeIs[{format_type_bare(tp.type_is, options)}]" else: s += format_type_bare(tp.ret_type, options) if tp.variables: tvars = [] for tvar in tp.variables: if isinstance(tvar, TypeVarType): upper_bound = get_proper_type(tvar.upper_bound) if not ( isinstance(upper_bound, Instance) and upper_bound.type.fullname == "builtins.object" ): tvars.append(f"{tvar.name}: {format_type_bare(upper_bound, options)}") elif tvar.values: tvars.append( "{}: ({})".format( tvar.name, ", ".join([format_type_bare(tp, options) for tp in tvar.values]), ) ) else: tvars.append(tvar.name) else: # For other TypeVarLikeTypes, just use the repr tvars.append(repr(tvar)) s = f"[{', '.join(tvars)}] {s}" return f"def {s}" def get_first_arg(tp: CallableType) -> str | None: definition = get_func_def(tp) if not isinstance(definition, FuncDef) or not definition.info or definition.is_static: return None return definition.original_first_arg def variance_string(variance: int) -> str: if variance == COVARIANT: return "covariant" elif variance == CONTRAVARIANT: return "contravariant" else: return "invariant" def get_missing_protocol_members(left: Instance, right: Instance, skip: list[str]) -> list[str]: """Find all protocol members of 'right' that are not implemented (i.e. completely missing) in 'left'. """ assert right.type.is_protocol missing: list[str] = [] for member in right.type.protocol_members: if member in skip: continue if not find_member(member, left, left): missing.append(member) return missing def get_conflict_protocol_types( left: Instance, right: Instance, class_obj: bool = False, options: Options | None = None ) -> list[tuple[str, Type, Type, bool]]: """Find members that are defined in 'left' but have incompatible types. Return them as a list of ('member', 'got', 'expected', 'is_lvalue'). """ assert right.type.is_protocol conflicts: list[tuple[str, Type, Type, bool]] = [] for member in right.type.protocol_members: if member in ("__init__", "__new__"): continue supertype = find_member(member, right, left) assert supertype is not None subtype = mypy.typeops.get_protocol_member(left, member, class_obj) if not subtype: continue is_compat = is_subtype(subtype, supertype, ignore_pos_arg_names=True, options=options) if not is_compat: conflicts.append((member, subtype, supertype, False)) superflags = get_member_flags(member, right) if IS_SETTABLE not in superflags: continue different_setter = False if IS_EXPLICIT_SETTER in superflags: set_supertype = find_member(member, right, left, is_lvalue=True) if set_supertype and not is_same_type(set_supertype, supertype): different_setter = True supertype = set_supertype if IS_EXPLICIT_SETTER in get_member_flags(member, left): set_subtype = mypy.typeops.get_protocol_member(left, member, class_obj, is_lvalue=True) if set_subtype and not is_same_type(set_subtype, subtype): different_setter = True subtype = set_subtype if not is_compat and not different_setter: # We already have this conflict listed, avoid duplicates. continue assert supertype is not None and subtype is not None is_compat = is_subtype(supertype, subtype, options=options) if not is_compat: conflicts.append((member, subtype, supertype, different_setter)) return conflicts def get_bad_protocol_flags( left: Instance, right: Instance, class_obj: bool = False ) -> list[tuple[str, set[int], set[int]]]: """Return all incompatible attribute flags for members that are present in both 'left' and 'right'. """ assert right.type.is_protocol all_flags: list[tuple[str, set[int], set[int]]] = [] for member in right.type.protocol_members: if find_member(member, left, left, class_obj=class_obj): all_flags.append( ( member, get_member_flags(member, left, class_obj=class_obj), get_member_flags(member, right), ) ) bad_flags = [] for name, subflags, superflags in all_flags: if ( IS_CLASSVAR in subflags and IS_CLASSVAR not in superflags and IS_SETTABLE in superflags or IS_CLASSVAR in superflags and IS_CLASSVAR not in subflags or IS_SETTABLE in superflags and IS_SETTABLE not in subflags or IS_CLASS_OR_STATIC in superflags and IS_CLASS_OR_STATIC not in subflags or class_obj and IS_VAR in superflags and IS_CLASSVAR not in subflags or class_obj and IS_CLASSVAR in superflags ): bad_flags.append((name, subflags, superflags)) return bad_flags def capitalize(s: str) -> str: """Capitalize the first character of a string.""" if s == "": return "" else: return s[0].upper() + s[1:] def extract_type(name: str) -> str: """If the argument is the name of a method (of form C.m), return the type portion in quotes (e.g. "y"). Otherwise, return the string unmodified. """ name = re.sub('^"[a-zA-Z0-9_]+" of ', "", name) return name def strip_quotes(s: str) -> str: """Strip a double quote at the beginning and end of the string, if any.""" s = re.sub('^"', "", s) s = re.sub('"$', "", s) return s def format_string_list(lst: list[str]) -> str: assert lst if len(lst) == 1: return lst[0] elif len(lst) <= 5: return f"{', '.join(lst[:-1])} and {lst[-1]}" else: return "%s, ... and %s (%i methods suppressed)" % ( ", ".join(lst[:2]), lst[-1], len(lst) - 3, ) def format_item_name_list(s: Iterable[str]) -> str: lst = list(s) if len(lst) <= 5: return "(" + ", ".join([f'"{name}"' for name in lst]) + ")" else: return "(" + ", ".join([f'"{name}"' for name in lst[:5]]) + ", ...)" def callable_name(type: FunctionLike) -> str | None: name = type.get_name() if name is not None and name[0] != "<": return f'"{name}"'.replace(" of ", '" of "') return name def for_function(callee: CallableType) -> str: name = callable_name(callee) if name is not None: return f" for {name}" return "" def wrong_type_arg_count(low: int, high: int, act: str, name: str) -> str: if low == high: s = f"{low} type arguments" if low == 0: s = "no type arguments" elif low == 1: s = "1 type argument" else: s = f"between {low} and {high} type arguments" if act == "0": act = "none" return f'"{name}" expects {s}, but {act} given' def find_defining_module(modules: dict[str, MypyFile], typ: CallableType) -> MypyFile | None: if not typ.definition: return None fullname = typ.definition.fullname if "." in fullname: for i in range(fullname.count(".")): module_name = fullname.rsplit(".", i + 1)[0] try: return modules[module_name] except KeyError: pass assert False, "Couldn't determine module from CallableType" return None # For hard-coding suggested missing member alternatives. COMMON_MISTAKES: Final[dict[str, Sequence[str]]] = {"add": ("append", "extend")} def _real_quick_ratio(a: str, b: str) -> float: # this is an upper bound on difflib.SequenceMatcher.ratio # similar to difflib.SequenceMatcher.real_quick_ratio, but faster since we don't instantiate al = len(a) bl = len(b) return 2.0 * min(al, bl) / (al + bl) def best_matches(current: str, options: Collection[str], n: int) -> list[str]: if not current: return [] # narrow down options cheaply options = [o for o in options if _real_quick_ratio(current, o) > 0.75] if len(options) >= 50: options = [o for o in options if abs(len(o) - len(current)) <= 1] ratios = {option: difflib.SequenceMatcher(a=current, b=option).ratio() for option in options} options = [option for option, ratio in ratios.items() if ratio > 0.75] return sorted(options, key=lambda v: (-ratios[v], v))[:n] def pretty_seq(args: Sequence[str], conjunction: str) -> str: quoted = ['"' + a + '"' for a in args] if len(quoted) == 1: return quoted[0] if len(quoted) == 2: return f"{quoted[0]} {conjunction} {quoted[1]}" last_sep = ", " + conjunction + " " return ", ".join(quoted[:-1]) + last_sep + quoted[-1] def append_invariance_notes( notes: list[str], arg_type: Instance, expected_type: Instance ) -> list[str]: """Explain that the type is invariant and give notes for how to solve the issue.""" invariant_type = "" covariant_suggestion = "" if ( arg_type.type.fullname == "builtins.list" and expected_type.type.fullname == "builtins.list" and is_subtype(arg_type.args[0], expected_type.args[0]) ): invariant_type = "list" covariant_suggestion = 'Consider using "Sequence" instead, which is covariant' elif ( arg_type.type.fullname == "builtins.dict" and expected_type.type.fullname == "builtins.dict" and is_same_type(arg_type.args[0], expected_type.args[0]) and is_subtype(arg_type.args[1], expected_type.args[1]) ): invariant_type = "dict" covariant_suggestion = ( 'Consider using "Mapping" instead, which is covariant in the value type' ) if invariant_type and covariant_suggestion: notes.append( f'"{invariant_type}" is invariant -- see ' + "https://mypy.readthedocs.io/en/stable/common_issues.html#variance" ) notes.append(covariant_suggestion) return notes def append_union_note( notes: list[str], arg_type: UnionType, expected_type: UnionType, options: Options ) -> list[str]: """Point to specific union item(s) that may cause failure in subtype check.""" non_matching = [] items = flatten_nested_unions(arg_type.items) if len(items) < MAX_UNION_ITEMS: return notes for item in items: if not is_subtype(item, expected_type): non_matching.append(item) if non_matching: types = ", ".join([format_type(typ, options) for typ in non_matching]) notes.append(f"Item{plural_s(non_matching)} in the first union not in the second: {types}") return notes def append_numbers_notes( notes: list[str], arg_type: Instance, expected_type: Instance ) -> list[str]: """Explain if an unsupported type from "numbers" is used in a subtype check.""" if expected_type.type.fullname in UNSUPPORTED_NUMBERS_TYPES: notes.append('Types from "numbers" aren\'t supported for static type checking') notes.append("See https://peps.python.org/pep-0484/#the-numeric-tower") notes.append("Consider using a protocol instead, such as typing.SupportsFloat") return notes def make_inferred_type_note( context: Context, subtype: Type, supertype: Type, supertype_str: str ) -> str: """Explain that the user may have forgotten to type a variable. The user does not expect an error if the inferred container type is the same as the return type of a function and the argument type(s) are a subtype of the argument type(s) of the return type. This note suggests that they add a type annotation with the return type instead of relying on the inferred type. """ subtype = get_proper_type(subtype) supertype = get_proper_type(supertype) if ( isinstance(subtype, Instance) and isinstance(supertype, Instance) and subtype.type.fullname == supertype.type.fullname and subtype.args and supertype.args and isinstance(context, ReturnStmt) and isinstance(context.expr, NameExpr) and isinstance(context.expr.node, Var) and context.expr.node.is_inferred ): for subtype_arg, supertype_arg in zip(subtype.args, supertype.args): if not is_subtype(subtype_arg, supertype_arg): return "" var_name = context.expr.name return 'Perhaps you need a type annotation for "{}"? Suggestion: {}'.format( var_name, supertype_str ) return "" def format_key_list(keys: list[str], *, short: bool = False) -> str: formatted_keys = [f'"{key}"' for key in keys] td = "" if short else "TypedDict " if len(keys) == 0: return f"no {td}keys" elif len(keys) == 1: return f"{td}key {formatted_keys[0]}" else: return f"{td}keys ({', '.join(formatted_keys)})" def ignore_last_known_values(t: UnionType) -> Type: """This will avoid types like str | str in error messages. last_known_values are kept during union simplification, but may cause weird formatting for e.g. tuples of literals. """ union_items: list[Type] = [] seen_instances = set() for item in t.items: if isinstance(item, ProperType) and isinstance(item, Instance): erased = item.copy_modified(last_known_value=None) if erased in seen_instances: continue seen_instances.add(erased) union_items.append(erased) else: union_items.append(item) return UnionType.make_union(union_items, t.line, t.column)
CollectAllNamedTypesQuery
python
astropy__astropy
astropy/modeling/functional_models.py
{ "start": 79553, "end": 82255 }
class ____(Fittable2DModel): """ Two dimensional Box model. Parameters ---------- amplitude : float Amplitude x_0 : float x position of the center of the box function x_width : float Width in x direction of the box y_0 : float y position of the center of the box function y_width : float Width in y direction of the box See Also -------- Box1D, Gaussian2D, Moffat2D Notes ----- Model formula: .. math:: f(x, y) = \\left \\{ \\begin{array}{ll} A : & x_0 - w_x/2 \\leq x \\leq x_0 + w_x/2 \\text{ and} \\\\ & y_0 - w_y/2 \\leq y \\leq y_0 + w_y/2 \\\\ 0 : & \\text{else} \\end{array} \\right. """ amplitude = Parameter(default=1, description="Amplitude", mag=True) x_0 = Parameter( default=0, description="X position of the center of the box function" ) y_0 = Parameter( default=0, description="Y position of the center of the box function" ) x_width = Parameter(default=1, description="Width in x direction of the box") y_width = Parameter(default=1, description="Width in y direction of the box") @staticmethod def evaluate(x, y, amplitude, x_0, y_0, x_width, y_width): """Two dimensional Box model function.""" x_range = np.logical_and(x >= x_0 - x_width / 2.0, x <= x_0 + x_width / 2.0) y_range = np.logical_and(y >= y_0 - y_width / 2.0, y <= y_0 + y_width / 2.0) result = np.select([np.logical_and(x_range, y_range)], [amplitude], 0) if isinstance(amplitude, Quantity): return Quantity(result, unit=amplitude.unit, copy=False, subok=True) return result @property def bounding_box(self): """ Tuple defining the default ``bounding_box``. ``((y_low, y_high), (x_low, x_high))`` """ dx = self.x_width / 2 dy = self.y_width / 2 return ((self.y_0 - dy, self.y_0 + dy), (self.x_0 - dx, self.x_0 + dx)) @property def input_units(self): if self.x_0.input_unit is None: return None return { self.inputs[0]: self.x_0.input_unit, self.inputs[1]: self.y_0.input_unit, } def _parameter_units_for_data_units(self, inputs_unit, outputs_unit): return { "x_0": inputs_unit[self.inputs[0]], "y_0": inputs_unit[self.inputs[1]], "x_width": inputs_unit[self.inputs[0]], "y_width": inputs_unit[self.inputs[1]], "amplitude": outputs_unit[self.outputs[0]], }
Box2D
python
walkccc__LeetCode
solutions/1499. Max Value of Equation/1499-2.py
{ "start": 0, "end": 533 }
class ____: def findMaxValueOfEquation(self, points: list[list[int]], k: int) -> int: ans = -math.inf maxQ = collections.deque() # (y - x, x) for x, y in points: # Remove the invalid points, xj - xi > k while maxQ and x - maxQ[0][1] > k: maxQ.popleft() if maxQ: ans = max(ans, x + y + maxQ[0][0]) # Remove the points that contribute less value and have a bigger x. while maxQ and y - x >= maxQ[-1][0]: maxQ.pop() maxQ.append((y - x, x)) return ans
Solution
python
pytorch__pytorch
torch/_inductor/codegen/common.py
{ "start": 7769, "end": 7964 }
class ____: name: str buffer: str dtype: torch.dtype offset: sympy.Expr = sympy.S.Zero # c++ only alias_of: Optional[str] = None # halide only @dataclasses.dataclass
TensorArg
python
google__pytype
pytype/tests/test_functions2.py
{ "start": 10443, "end": 22092 }
class ____(test_base.BaseTest): """Tests for functions.""" def test_make_function(self): src = """ def uses_annotations(x: int) -> int: i, j = 3, 4 return i def uses_pos_defaults(x, y=1): i, j = 3, 4 return __any_object__ def uses_kw_defaults(x, *myargs, y=1): i, j = 3, 4 return __any_object__ def uses_kwargs(x, **mykwargs): i, j = 3, 4 return __any_object__ """ output = """ from typing import Any def uses_annotations(x: int) -> int: ... def uses_pos_defaults(x, y=...) -> Any: ... def uses_kw_defaults(x, *myargs, y=...) -> Any: ... def uses_kwargs(x, **mykwargs) -> Any: ... """ self.assertTypesMatchPytd(self.Infer(src), output) self.assertTypesMatchPytd(self.Infer(src), output) def test_make_function2(self): ty = self.Infer(""" def f(x, *myargs, y): return __any_object__ """) self.assertTypesMatchPytd( ty, """ from typing import Any def f(x, *myargs, y) -> Any: ... """, ) def test_make_function3(self): ty = self.Infer(""" def f(a = 2, *args, b:int = 1, **kwargs): x = 0 def g(i:int = 3) -> int: return x return g y = f(2) """) self.assertTypesMatchPytd( ty, """ from typing import Any, Callable def f(a=..., *args, b: int = ..., **kwargs) -> Callable[Any, int]: ... def y(i: int = ...) -> int: ... """, ) def test_make_function_deep(self): ty = self.Infer(""" def f(a = 2, *args, b:int = 1, **kwargs): x = 0 def g(i:int = 3) -> int: return x + i return g y = f(2) """) # Does not infer a:int when deep=True. self.assertTypesMatchPytd( ty, """ from typing import Any, Callable def f(a = ..., *args, b: int = ..., **kwargs) -> Callable[Any, int]: ... def y(i: int = ...) -> int: ... """, ) def test_defaults(self): ty = self.Infer(""" def foo(a, b, c, d=0, e=0, f=0, g=0, *myargs, u, v, x, y=0, z=0, **mykwargs): return 3 """) self.assertTypesMatchPytd( ty, """ def foo(a, b, c, d=..., e=..., f=..., g=..., *myargs, u, v, x, y=..., z=..., **mykwargs) -> int: ... """, ) def test_defaults_and_annotations(self): ty = self.Infer(""" def foo(a, b, c:int, d=0, e=0, f=0, g=0, *myargs, u:str, v, x:float=0, y=0, z=0, **mykwargs): return 3 """) self.assertTypesMatchPytd( ty, """ def foo(a, b, c:int, d=..., e=..., f=..., g=..., *myargs, u:str, v, x:float=..., y=..., z=..., **mykwargs) -> int: ... """, ) def test_namedtuple_defaults(self): self.Check(""" from typing import NamedTuple class Foo(NamedTuple): field: int Foo.__new__.__defaults__ = ((),) * len(Foo._fields) """) def test_matching_functions(self): ty = self.Infer(""" def f(): return 3 class Foo: def match_method(self): return map(self.method, []) def match_function(self): return map(f, []) def match_pytd_function(self): return map(map, []) def match_bound_pytd_function(self): return map({}.keys, []) def method(self): pass """) self.assertTypesMatchPytd( ty, """ from typing import Iterator def f() -> int: ... class Foo: def match_method(self) -> Iterator[nothing]: ... def match_function(self) -> Iterator[nothing]: ... def match_pytd_function(self) -> Iterator[nothing]: ... def match_bound_pytd_function(self) -> Iterator[nothing]: ... def method(self) -> NoneType: ... """, ) def test_build_with_unpack(self): ty = self.Infer(""" a = [1,2,3,4] b = [1,2,3,4] c = {'1':2, '3':4} d = {'5':6, '7':8} e = {'9':10, 'B':12} # Test merging two dicts into an args dict for k x = {'a': 1, 'c': 2} y = {'b': 1, 'd': 2} def f(**kwargs): print(kwargs) def g(*args): print(args) def h(*args, **kwargs): print(args, kwargs) def j(a=1, b=2, c=3): print(a, b,c) def k(a, b, c, d, **kwargs): print(a, b, c, d, kwargs) p = [*a, *b] # BUILD_LIST_UNPACK q = {*a, *b} # BUILD_SET_UNPACK r = (*a, *b) # BUILD_TUPLE_UNPACK s = {**c, **d} # BUILD_MAP_UNPACK f(**c, **d, **e) # BUILD_MAP_UNPACK_WITH_CALL g(*a, *b) # BUILD_TUPLE_UNPACK_WITH_CALL h(*a, *b, **c, **d) j(**{'a': 1, 'b': 2}) # BUILD_CONST_KEY_MAP k(**x, **y, **e) # BUILD_MAP_UNPACK_WITH_CALL """) self.assertTypesMatchPytd( ty, """ from typing import Dict, List, Set, Tuple a = ... # type: List[int] b = ... # type: List[int] c = ... # type: Dict[str, int] d = ... # type: Dict[str, int] e = ... # type: Dict[str, int] p = ... # type: List[int] q = ... # type: Set[int] r = ... # type: Tuple[int, int, int, int, int, int, int, int] s = ... # type: Dict[str, int] x = ... # type: Dict[str, int] y = ... # type: Dict[str, int] def f(**kwargs) -> None: ... def g(*args) -> None: ... def h(*args, **kwargs) -> None: ... def j(a = ..., b = ..., c = ...) -> None: ... def k(a, b, c, d, **kwargs) -> None: ... """, ) def test_unpack_str(self): ty = self.Infer(""" s1 = "abc" s2 = "def" tup = (*s1, *s2) """) self.assertTypesMatchPytd( ty, """ from typing import Tuple s1 = ... # type: str s2 = ... # type: str tup = ... # type: Tuple[str, str, str, str, str, str] """, ) def test_unpack_tuple(self): # The **kwargs unpacking in the wrapper seems to prevent pytype from # eagerly expanding the splat in the tuple literal. ty = self.Infer(""" def f(*, xs: tuple[int, ...], **kwargs: object): def wrapper(): out = f( xs=(42, *kwargs.pop("xs", ())), **kwargs, )() return wrapper """) self.assertTypesMatchPytd( ty, """ from typing import Any, Callable def f(*, xs: tuple[int, ...], **kwargs: object) -> Callable[[], Any]: ... """, ) def test_unpack_tuple_invalid(self): self.InferWithErrors(""" def f(*, xs: tuple[int, ...], **kwargs: object): def wrapper(): out = f( # wrong-arg-types xs=(object(), *kwargs.pop("xs", ())), **kwargs, )() return wrapper """) def test_unpack_nonliteral(self): ty = self.Infer(""" def f(x, **kwargs): return kwargs['y'] def g(**kwargs): return f(x=10, **kwargs) """) self.assertTypesMatchPytd( ty, """ from typing import Any def f(x, **kwargs) -> Any: ... def g(**kwargs) -> Any: ... """, ) def test_unpack_multiple_bindings(self): ty = self.Infer(""" if __random__: x = {'a': 1, 'c': 2} else: x = {'a': '1', 'c': '2'} if __random__: y = {'b': 1, 'd': 2} else: y = {'b': b'1', 'd': b'2'} z = {**x, **y} """) self.assertTypesMatchPytd( ty, """ from typing import Dict, TypeVar, Union x = ... # type: Dict[str, Union[str, int]] y = ... # type: Dict[str, Union[bytes, int]] z = ... # type: Dict[str, Union[bytes, int, str]] """, ) def test_kwonly(self): self.Check(""" from typing import Optional def foo(x: int, *, z: Optional[int] = None) -> None: pass foo(1, z=5) """) def test_varargs_with_kwonly(self): self.Check(""" def foo(x: int, *args: int, z: int) -> None: pass foo(1, 2, z=5) """) def test_varargs_with_missing_kwonly(self): errors = self.CheckWithErrors(""" def foo(x: int, *args: int, z: int) -> None: pass foo(1, 2, 5) # missing-parameter[e] """) self.assertErrorRegexes(errors, {"e": r"\bz\b"}) def test_multiple_varargs_packs(self): self.Check(""" from typing import Tuple def foo1(*x: int): pass def foo2(x: str, y: bytes, *z: int): pass foo1(*[1, 2, 3], *[4, 5, 6]) foo2('abc', b'def', *[1, 2, 3], *[4, 5, 6]) def bar(y: Tuple[int], *z: int): foo1(*y, *z) foo2('abc', b'def', *y, *z) """) def text_multiple_varargs_packs_errors(self): errors = self.CheckWithErrors(""" def foo(x: str, *y: int): pass foo(*[1, 2, 3], *[4, 5, 6]) # wrong-arg-types[e1] def bar(*z: int): foo(*z, *z) # wrong-arg-types[e2] """) self.assertErrorRegexes(errors, {"e1": r"str.*int", "e2": r"str.*int"}) def test_kwonly_to_callable(self): ty = self.Infer(""" def f(x, *, y): pass class Foo: def __init__(self): self.f = f """) self.assertTypesMatchPytd( ty, """ from typing import Callable def f(x, *, y) -> None: ... class Foo: f: Callable def __init__(self) -> None: ... """, ) def test_positional_only_parameter(self): ty, errors = self.InferWithErrors(""" def f(x, /, y): pass f(0, 1) # ok f(0, y=1) # ok f(x=0, y=1) # wrong-keyword-args[e] """) self.assertTypesMatchPytd( ty, """ def f(x, /, y) -> None: ... """, ) # TODO(rechen): We currently print "Actually passed: (x, y)", which is # confusing. We should somehow indicate that x was passed in by keyword. self.assertErrorSequences( errors, {"e": ["Invalid keyword argument x", "Expected: (x, /, y)"]} ) def test_positional_only_parameter_pyi(self): with test_utils.Tempdir() as d: d.create_file( "foo.pyi", """ def f(x, /, y) -> None: ... """, ) errors = self.CheckWithErrors( """ import foo foo.f(0, 1) # ok foo.f(0, y=1) # ok foo.f(x=0, y=1) # wrong-keyword-args[e] """, pythonpath=[d.path], ) # TODO(rechen): We currently print "Actually passed: (x, y)", which is # confusing. We should somehow indicate that x was passed in by keyword. self.assertErrorSequences( errors, {"e": ["Invalid keyword argument x", "Expected: (x, /, y)"]} ) def test_positional_and_keyword_arguments(self): with test_utils.Tempdir() as d: d.create_file( "foo.pyi", """ def f(x, /, **kwargs) -> None: ... """, ) self.Check( """ import foo def f(x, /, **kwargs): pass foo.f(1, x=1) f(1, x=1) """, pythonpath=[d.path], ) def test_posonly_starstararg_clash(self): self.Check(""" def f(arg: int, /, **kwargs: str): pass f(1, arg='text') """) def test_pyi_posonly_starstararg_clash(self): with test_utils.Tempdir() as d: d.create_file( "foo.pyi", """ def f(arg: int, /, **kwargs: str) -> None: ... """, ) self.Check( """ import foo foo.f(1, arg='text') """, pythonpath=[d.path], )
TestFunctionsPython3Feature
python
psf__black
src/blib2to3/pytree.py
{ "start": 15319, "end": 18335 }
class ____: """ A pattern is a tree matching pattern. It looks for a specific node type (token or symbol), and optionally for a specific content. This is an abstract base class. There are three concrete subclasses: - LeafPattern matches a single leaf node; - NodePattern matches a single node (usually non-leaf); - WildcardPattern matches a sequence of nodes of variable length. """ # Defaults for instance variables type: int | None type = None # Node type (token if < 256, symbol if >= 256) content: Any = None # Optional content matching pattern name: str | None = None # Optional name used to store match in results dict def __new__(cls, *args, **kwds): """Constructor that prevents BasePattern from being instantiated.""" assert cls is not BasePattern, "Cannot instantiate BasePattern" return object.__new__(cls) def __repr__(self) -> str: assert self.type is not None args = [type_repr(self.type), self.content, self.name] while args and args[-1] is None: del args[-1] return f"{self.__class__.__name__}({', '.join(map(repr, args))})" def _submatch(self, node, results=None) -> bool: raise NotImplementedError def optimize(self) -> "BasePattern": """ A subclass can define this as a hook for optimizations. Returns either self or another node with the same effect. """ return self def match(self, node: NL, results: _Results | None = None) -> bool: """ Does this pattern exactly match a node? Returns True if it matches, False if not. If results is not None, it must be a dict which will be updated with the nodes matching named subpatterns. Default implementation for non-wildcard patterns. """ if self.type is not None and node.type != self.type: return False if self.content is not None: r: _Results | None = None if results is not None: r = {} if not self._submatch(node, r): return False if r: assert results is not None results.update(r) if results is not None and self.name: results[self.name] = node return True def match_seq(self, nodes: list[NL], results: _Results | None = None) -> bool: """ Does this pattern exactly match a sequence of nodes? Default implementation for non-wildcard patterns. """ if len(nodes) != 1: return False return self.match(nodes[0], results) def generate_matches(self, nodes: list[NL]) -> Iterator[tuple[int, _Results]]: """ Generator yielding all matches for this pattern. Default implementation for non-wildcard patterns. """ r: _Results = {} if nodes and self.match(nodes[0], r): yield 1, r
BasePattern
python
plotly__plotly.py
plotly/graph_objs/splom/marker/colorbar/_title.py
{ "start": 233, "end": 4006 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "splom.marker.colorbar" _path_str = "splom.marker.colorbar.title" _valid_props = {"font", "side", "text"} @property def font(self): """ Sets this color bar's title font. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.splom.marker.colorbar.title.Font` - A dict of string/value properties that will be passed to the Font constructor Returns ------- plotly.graph_objs.splom.marker.colorbar.title.Font """ return self["font"] @font.setter def font(self, val): self["font"] = val @property def side(self): """ Determines the location of color bar's title with respect to the color bar. Defaults to "top" when `orientation` if "v" and defaults to "right" when `orientation` if "h". The 'side' property is an enumeration that may be specified as: - One of the following enumeration values: ['right', 'top', 'bottom'] Returns ------- Any """ return self["side"] @side.setter def side(self, val): self["side"] = val @property def text(self): """ Sets the title of the color bar. The 'text' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["text"] @text.setter def text(self, val): self["text"] = val @property def _prop_descriptions(self): return """\ font Sets this color bar's title font. side Determines the location of color bar's title with respect to the color bar. Defaults to "top" when `orientation` if "v" and defaults to "right" when `orientation` if "h". text Sets the title of the color bar. """ def __init__(self, arg=None, font=None, side=None, text=None, **kwargs): """ Construct a new Title object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.splom.marker.colorbar.Title` font Sets this color bar's title font. side Determines the location of color bar's title with respect to the color bar. Defaults to "top" when `orientation` if "v" and defaults to "right" when `orientation` if "h". text Sets the title of the color bar. Returns ------- Title """ super().__init__("title") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.splom.marker.colorbar.Title constructor must be a dict or an instance of :class:`plotly.graph_objs.splom.marker.colorbar.Title`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("font", arg, font) self._set_property("side", arg, side) self._set_property("text", arg, text) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Title
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_P.py
{ "start": 14542, "end": 15627 }
class ____(Benchmark): r""" Powell objective function. This class defines the Powell [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Powell}}(x) = (x_3+10x_1)^2 + 5(x_2-x_4)^2 + (x_1-2x_2)^4 + 10(x_3-x_4)^4 Here, :math:`n` represents the number of dimensions and :math:`x_i \in [-4, 5]` for :math:`i = 1, ..., 4`. *Global optimum*: :math:`f(x) = 0` for :math:`x_i = 0` for :math:`i = 1, ..., 4` ..[1] Powell, M. An iterative method for finding stationary values of a function of several variables Computer Journal, 1962, 5, 147-151 """ def __init__(self, dimensions=4): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-4.0] * self.N, [5.0] * self.N)) self.global_optimum = [[0, 0, 0, 0]] self.fglob = 0 def fun(self, x, *args): self.nfev += 1 return ((x[0] + 10 * x[1]) ** 2 + 5 * (x[2] - x[3]) ** 2 + (x[1] - 2 * x[2]) ** 4 + 10 * (x[0] - x[3]) ** 4)
Powell
python
huggingface__transformers
tests/models/altclip/test_modeling_altclip.py
{ "start": 1428, "end": 4514 }
class ____: def __init__( self, parent, batch_size=12, image_size=30, patch_size=2, num_channels=3, is_training=True, hidden_size=32, projection_dim=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, dropout=0.1, attention_dropout=0.1, initializer_range=0.02, scope=None, ): self.parent = parent self.batch_size = batch_size self.image_size = image_size self.patch_size = patch_size self.num_channels = num_channels self.is_training = is_training self.hidden_size = hidden_size self.projection_dim = projection_dim self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.dropout = dropout self.attention_dropout = attention_dropout self.initializer_range = initializer_range self.scope = scope # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) num_patches = (image_size // patch_size) ** 2 self.seq_length = num_patches + 1 def prepare_config_and_inputs(self): pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) config = self.get_config() return config, pixel_values def get_config(self): return AltCLIPVisionConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, hidden_size=self.hidden_size, projection_dim=self.projection_dim, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, dropout=self.dropout, attention_dropout=self.attention_dropout, initializer_range=self.initializer_range, ) def create_and_check_model(self, config, pixel_values): model = AltCLIPVisionModel(config=config) model.to(torch_device) model.eval() with torch.no_grad(): result = model(pixel_values) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) image_size = (self.image_size, self.image_size) patch_size = (self.patch_size, self.patch_size) num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, num_patches + 1, self.hidden_size)) self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, pixel_values = config_and_inputs inputs_dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch
AltCLIPVisionModelTester
python
kamyu104__LeetCode-Solutions
Python/jump-game-vi.py
{ "start": 50, "end": 540 }
class ____(object): def maxResult(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ score = 0 dq = collections.deque() for i, num in enumerate(nums): if dq and dq[0][0] == i-k-1: dq.popleft() score = num if not dq else dq[0][1]+num while dq and dq[-1][1] <= score: dq.pop() dq.append((i, score)) return score
Solution
python
getsentry__sentry
src/sentry/notifications/types.py
{ "start": 2390, "end": 6022 }
class ____(Enum): SELF_ACTIVITY = "personalActivityNotifications" SELF_ASSIGN = "selfAssignOnResolve" VALID_VALUES_FOR_KEY = { NotificationSettingEnum.APPROVAL: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.DEPLOY: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.COMMITTED_ONLY, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.ISSUE_ALERTS: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.QUOTA: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.QUOTA_ERRORS: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.QUOTA_TRANSACTIONS: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.QUOTA_ATTACHMENTS: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.QUOTA_REPLAYS: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.QUOTA_MONITOR_SEATS: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.QUTOA_UPTIME: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.QUOTA_SPANS: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.QUOTA_PROFILE_DURATION: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.QUOTA_PROFILE_DURATION_UI: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.QUOTA_SEER_BUDGET: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.QUOTA_WARNINGS: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.QUOTA_SPEND_ALLOCATIONS: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.QUOTA_LOG_BYTES: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.QUOTA_SEER_USERS: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.QUOTA_THRESHOLDS: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.WORKFLOW: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.SUBSCRIBE_ONLY, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.SPIKE_PROTECTION: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.REPORTS: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.BROKEN_MONITORS: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, }
UserOptionsSettingsKey
python
pyqtgraph__pyqtgraph
pyqtgraph/parametertree/parameterTypes/font.py
{ "start": 114, "end": 581 }
class ____(WidgetParameterItem): def makeWidget(self): w = QtWidgets.QFontComboBox() w.setMaximumHeight(20) w.sigChanged = w.currentFontChanged w.value = w.currentFont w.setValue = w.setCurrentFont self.hideWidget = False return w def updateDisplayLabel(self, value=None): if value is None: value = self.widget.currentText() super().updateDisplayLabel(value)
FontParameterItem
python
python-openxml__python-docx
tests/image/test_png.py
{ "start": 10602, "end": 12643 }
class ____: def it_constructs_the_appropriate_Chunk_subclass(self, call_fixture): chunk_type, stream_rdr_, offset, chunk_cls_ = call_fixture chunk = _ChunkFactory(chunk_type, stream_rdr_, offset) chunk_cls_.from_offset.assert_called_once_with(chunk_type, stream_rdr_, offset) assert isinstance(chunk, _Chunk) # fixtures ------------------------------------------------------- @pytest.fixture( params=[ PNG_CHUNK_TYPE.IHDR, PNG_CHUNK_TYPE.pHYs, PNG_CHUNK_TYPE.IEND, ] ) def call_fixture(self, request, _IHDRChunk_, _pHYsChunk_, _Chunk_, stream_rdr_): chunk_type = request.param chunk_cls_ = { PNG_CHUNK_TYPE.IHDR: _IHDRChunk_, PNG_CHUNK_TYPE.pHYs: _pHYsChunk_, PNG_CHUNK_TYPE.IEND: _Chunk_, }[chunk_type] offset = 999 return chunk_type, stream_rdr_, offset, chunk_cls_ @pytest.fixture def _Chunk_(self, request, chunk_): _Chunk_ = class_mock(request, "docx.image.png._Chunk") _Chunk_.from_offset.return_value = chunk_ return _Chunk_ @pytest.fixture def chunk_(self, request): return instance_mock(request, _Chunk) @pytest.fixture def _IHDRChunk_(self, request, ihdr_chunk_): _IHDRChunk_ = class_mock(request, "docx.image.png._IHDRChunk") _IHDRChunk_.from_offset.return_value = ihdr_chunk_ return _IHDRChunk_ @pytest.fixture def ihdr_chunk_(self, request): return instance_mock(request, _IHDRChunk) @pytest.fixture def _pHYsChunk_(self, request, phys_chunk_): _pHYsChunk_ = class_mock(request, "docx.image.png._pHYsChunk") _pHYsChunk_.from_offset.return_value = phys_chunk_ return _pHYsChunk_ @pytest.fixture def phys_chunk_(self, request): return instance_mock(request, _pHYsChunk) @pytest.fixture def stream_rdr_(self, request): return instance_mock(request, StreamReader)
Describe_ChunkFactory
python
google__jax
tests/pallas/pallas_test.py
{ "start": 87042, "end": 87118 }
class ____(PallasCheckifyTest): INTERPRET = True
PallasCheckifyInterpretTest
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/nested_auto_heights.py
{ "start": 186, "end": 1362 }
class ____(App[None]): CSS = """ Screen { background: red; } #my-static-container { border: heavy lightgreen; background: green; height: auto; max-height: 10; } #my-static-wrapper { border: heavy lightblue; background: blue; width: auto; height: auto; } #my-static { border: heavy gray; background: black; width: auto; height: auto; } """ BINDINGS = [ ("1", "1", "1"), ("2", "2", "2"), ("q", "quit", "Quit"), ] def compose(self) -> ComposeResult: self._static = Static("", id="my-static") yield VerticalScroll( VerticalScroll( self._static, id="my-static-wrapper", ), id="my-static-container", ) def action_1(self) -> None: self._static.update( "\n".join(f"Lorem {i} Ipsum {i} Sit {i}" for i in range(1, 21)) ) def action_2(self) -> None: self._static.update("JUST ONE LINE") if __name__ == "__main__": app = NestedAutoApp() app.run()
NestedAutoApp
python
realpython__materials
python-docstrings/classes_docstring.py
{ "start": 0, "end": 894 }
class ____: """ Represents a magical potion composed of various ingredients. Attributes ---------- name : str The name of the potion. ingredients : list of str A list of ingredients used in the potion. potency : int The strength level of the potion. Methods ------- brew(): Completes the potion and sets its potency. describe(): Returns a human-readable summary of the potion. """ def __init__(self, name, ingredients): self.name = name self.ingredients = ingredients self.potency = 0 def brew(self): """Simulate brewing the potion by calculating potency.""" self.potency = len(self.ingredients) * 10 def describe(self): """Return a string describing the potion and its strength.""" return f"{self.name} (Potency: {self.potency})"
Potion
python
charliermarsh__ruff
scripts/check_docs_formatted.py
{ "start": 4163, "end": 12389 }
class ____(ValueError): """Raised when ruff fails to parse file.""" def format_str(code: str, extension: Literal["py", "pyi"]) -> str: """Format a code block with ruff by writing to a temporary file.""" # Run ruff to format the tmp file try: completed_process = subprocess.run( ["ruff", "format", "--stdin-filename", f"file.{extension}", "-"], check=True, capture_output=True, text=True, input=code, ) except subprocess.CalledProcessError as e: err = e.stderr if "error: Failed to parse" in err: raise InvalidInput(err) from e raise NotImplementedError( "This error has not been handled correctly, please update " f"`check_docs_formatted.py\n\nError:\n\n{err}", ) from e return completed_process.stdout def format_contents(src: str) -> tuple[str, Sequence[CodeBlockError]]: """Format a single docs content.""" errors: list[CodeBlockError] = [] def _snipped_match(match: Match[str]) -> str: language = match["language"] extension: Literal["py", "pyi"] match language: case "python": extension = "py" case "pyi": extension = "pyi" case _: # We are only interested in checking the formatting of py or pyi code # blocks so we can return early if the language is not one of these. return f"{match['before']}{match['code']}{match['after']}" code = textwrap.dedent(match["code"]) try: code = format_str(code, extension) except InvalidInput as e: errors.append(CodeBlockError(e)) except NotImplementedError as e: raise e code = textwrap.indent(code, match["indent"]) return f"{match['before']}{code}{match['after']}" src = SNIPPED_RE.sub(_snipped_match, src) return src, errors def format_file(file: Path, error_known: bool, args: argparse.Namespace) -> int: """Check the formatting of a single docs file. Returns the exit code for the script. """ with file.open() as f: contents = f.read() if file.parent.name == "rules": # Check contents contains "What it does" section if "## What it does" not in contents: print(f"Docs for `{file.name}` are missing the `What it does` section.") return 1 # Check contents contains "Why is this bad?" section if "## Why is this bad?" not in contents: print(f"Docs for `{file.name}` are missing the `Why is this bad?` section.") return 1 # Remove everything before the first example contents = contents[contents.find("## Example") :] # Remove everything after the last example contents = contents[: contents.rfind("```")] + "```" new_contents, errors = format_contents(contents) if errors and not args.skip_errors and not error_known: for error in errors: rule_name = file.name.split(".")[0] print( f"Docs parse error for `{rule_name}` docs. Either fix or add to " f"`KNOWN_PARSE_ERRORS`. {error}", ) return 2 if contents != new_contents: rule_name = file.name.split(".")[0] print( f"Rule `{rule_name}` docs are not formatted. Either format the rule or add " f"to `KNOWN_FORMATTING_VIOLATIONS`. The example section should be " f"rewritten to:", ) # Add indentation so that snipped can be copied directly to docs for line in new_contents.splitlines(): output_line = "///" if len(line) > 0: output_line = f"{output_line} {line}" print(output_line) print("\n") return 1 return 0 def find_backticked_shortcut_links( path: Path, all_config_names: dict[str, object] ) -> set[str]: """Check for links of the form: [`foobar`]. See explanation at #16010. """ with path.open() as file: contents = file.read() broken_link_names: set[str] = set() for match in BACKTICKED_SHORTCUT_LINK_RE.finditer(contents): name = match["name"] if name is not None and name not in all_config_names: broken_link_names.add(name) return broken_link_names def main(argv: Sequence[str] | None = None) -> int: """Check code snippets in docs are formatted by Ruff.""" parser = argparse.ArgumentParser( description="Check code snippets in docs are formatted by Ruff.", ) parser.add_argument("--skip-errors", action="store_true") parser.add_argument("--generate-docs", action="store_true") args = parser.parse_args(argv) if args.generate_docs: # Generate docs from generate_mkdocs import main as generate_docs generate_docs() # Get static docs static_docs = [Path("docs") / f for f in os.listdir("docs") if f.endswith(".md")] # Check rules generated if not Path("docs/rules").exists(): print("Please generate rules first.") return 1 # Get generated rules generated_docs = [ Path("docs/rules") / f for f in os.listdir("docs/rules") if f.endswith(".md") ] if len(generated_docs) == 0: print("Please generate rules first.") return 1 # Check known formatting violations and parse errors are sorted alphabetically and # have no duplicates. This will reduce the diff when adding new violations for known_list, file_string in [ (KNOWN_FORMATTING_VIOLATIONS, "formatting violations"), (KNOWN_PARSE_ERRORS, "parse errors"), ]: if known_list != sorted(known_list): print( f"Known {file_string} is not sorted alphabetically. Please sort and " f"re-run.", ) return 1 duplicates = list({x for x in known_list if known_list.count(x) > 1}) if len(duplicates) > 0: print(f"Known {file_string} has duplicates:") print("\n".join([f" - {x}" for x in duplicates])) print("Please remove them and re-run.") return 1 ruff_config_output = subprocess.check_output( ["ruff", "config", "--output-format", "json"], encoding="utf-8" ) all_config_names = json.loads(ruff_config_output) violations = 0 errors = 0 broken_links: dict[str, set[str]] = {} print("Checking docs formatting...") for file in [*static_docs, *generated_docs]: rule_name = file.name.split(".")[0] if rule_name in KNOWN_FORMATTING_VIOLATIONS: continue error_known = rule_name in KNOWN_PARSE_ERRORS result = format_file(file, error_known, args) if result == 1: violations += 1 elif result == 2 and not error_known: errors += 1 broken_links_in_file = find_backticked_shortcut_links(file, all_config_names) if broken_links_in_file: broken_links[file.name] = broken_links_in_file if violations > 0: print(f"Formatting violations identified: {violations}") if errors > 0: print(f"New code block parse errors identified: {errors}") if broken_links: print() print("Do not use backticked shortcut links: [`foobar`]") print( "They work with Mkdocs but cannot be rendered by CommonMark and GFM-compliant implementers." ) print("Instead, use an explicit label:") print("```markdown") print("[`lorem.ipsum`][lorem-ipsum]") print() print("[lorem-ipsum]: https://example.com/") print("```") print() print("The following links are found to be broken:") for filename, link_names in broken_links.items(): print(f"- {filename}:") print("\n".join(f" - {name}" for name in link_names)) if violations > 0 or errors > 0 or broken_links: return 1 print("All docs are formatted correctly.") return 0 if __name__ == "__main__": raise SystemExit(main())
InvalidInput
python
Unity-Technologies__ml-agents
ml-agents-envs/mlagents_envs/envs/pettingzoo_env_factory.py
{ "start": 585, "end": 1957 }
class ____: def __init__(self, env_id: str) -> None: self.env_id = env_id def env( self, seed: Optional[int] = None, **kwargs: Union[List, int, bool, None] ) -> UnityAECEnv: """ Creates the environment with env_id from unity's default_registry and wraps it in a UnityToPettingZooWrapper :param seed: The seed for the action spaces of the agents. :param kwargs: Any argument accepted by `UnityEnvironment`class except file_name """ # If not side_channels specified, add the followings if "side_channels" not in kwargs: kwargs["side_channels"] = [ EngineConfigurationChannel(), EnvironmentParametersChannel(), StatsSideChannel(), ] _env = None # If no base port argument is provided, try ports starting at 6000 until one is free if "base_port" not in kwargs: port = 6000 while _env is None: try: kwargs["base_port"] = port _env = default_registry[self.env_id].make(**kwargs) except UnityWorkerInUseException: port += 1 pass else: _env = default_registry[self.env_id].make(**kwargs) return UnityAECEnv(_env, seed)
PettingZooEnvFactory
python
getsentry__sentry
src/sentry/api/serializers/rest_framework/dashboard.py
{ "start": 26560, "end": 47704 }
class ____(CamelSnakeSerializer[Dashboard]): # Is a string because output serializers also make it a string. id = serializers.CharField(required=False, help_text="A dashboard's unique id.") title = serializers.CharField( required=False, max_length=255, help_text="The user-defined dashboard title." ) widgets = DashboardWidgetSerializer( many=True, required=False, help_text="A json list of widgets saved in this dashboard." ) projects = serializers.ListField( child=serializers.IntegerField(), required=False, help_text="The saved projects filter for this dashboard.", ) environment = serializers.ListField( child=serializers.CharField(), required=False, allow_null=True, help_text="The saved environment filter for this dashboard.", ) period = serializers.CharField( required=False, allow_null=True, help_text="The saved time range period for this dashboard." ) start = serializers.DateTimeField( required=False, allow_null=True, help_text="The saved start time for this dashboard." ) end = serializers.DateTimeField( required=False, allow_null=True, help_text="The saved end time for this dashboard." ) filters = serializers.DictField( required=False, help_text="The saved filters for this dashboard." ) utc = serializers.BooleanField( required=False, help_text="Setting that lets you display saved time range for this dashboard in UTC.", ) validate_id = validate_id permissions = DashboardPermissionsSerializer( required=False, allow_null=True, help_text="Permissions that restrict users from editing dashboards", ) def validate_projects(self, projects): from sentry.api.validators import validate_project_ids return validate_project_ids(projects, {project.id for project in self.context["projects"]}) def validate(self, data): start = data.get("start") end = data.get("end") if start and end and start >= end: raise serializers.ValidationError("start must be before end") if len(data.get("widgets", [])) > Dashboard.MAX_WIDGETS: raise serializers.ValidationError( f"Number of widgets must be less than {Dashboard.MAX_WIDGETS}" ) permissions = data.get("permissions") if permissions and self.instance: currentUser = self.context["request"].user # managers and owners has_write_access = self.context["request"].access.has_scope("org:write") if self.instance.created_by_id != currentUser.id and not has_write_access: raise serializers.ValidationError( "Only the Dashboard Creator may modify Dashboard Edit Access" ) return data def update_dashboard_filters(self, instance, validated_data): page_filter_keys = ["environment", "period", "start", "end", "utc"] dashboard_filter_keys = ["release", "release_id"] if features.has( "organizations:dashboards-global-filters", organization=self.context["organization"], actor=self.context["request"].user, ): dashboard_filter_keys.append("global_filter") filters = {} if "projects" in validated_data: if validated_data["projects"] == ALL_ACCESS_PROJECTS: filters["all_projects"] = True instance.projects.clear() else: if instance.filters and instance.filters.get("all_projects"): filters["all_projects"] = False instance.projects.set(validated_data["projects"]) for key in page_filter_keys: if key in validated_data: filters[key] = validated_data[key] for key in dashboard_filter_keys: if "filters" in validated_data and key in validated_data["filters"]: filters[key] = validated_data["filters"][key] if filters: instance.filters = filters instance.save() def update_permissions(self, instance, validated_data): if "permissions" in validated_data and validated_data["permissions"] is not None: permissions_data = validated_data["permissions"] permissions = DashboardPermissions.objects.update_or_create( dashboard=instance, defaults={ "is_editable_by_everyone": permissions_data["is_editable_by_everyone"], }, )[0] if "teams_with_edit_access" in permissions_data: teams_data = permissions_data["teams_with_edit_access"] if teams_data == [] or permissions_data["is_editable_by_everyone"] is True: permissions.teams_with_edit_access.clear() else: permissions.teams_with_edit_access.set( Team.objects.filter( id__in=teams_data, organization=self.context["organization"] ) ) instance.permissions = permissions def create(self, validated_data): """ Create a dashboard, and create any widgets and their queries Only call save() on this serializer from within a transaction or bad things will happen """ self.instance = Dashboard.objects.create( organization=self.context["organization"], title=validated_data["title"], created_by_id=self.context["request"].user.id, ) assert self.instance is not None if "widgets" in validated_data: self.update_widgets(self.instance, validated_data["widgets"]) self.update_dashboard_filters(self.instance, validated_data) self.update_permissions(self.instance, validated_data) schedule_update_project_configs(self.instance) return self.instance def update(self, instance, validated_data): """ Update a dashboard, the connected widgets and queries - Widgets in the dashboard currently, but not in validated_data will be removed. - Widgets without ids will be created. - Widgets with matching IDs will be updated. Only call save() on this serializer from within a transaction or bad things will happen """ instance.title = validated_data.get("title", instance.title) instance.save() if "widgets" in validated_data: self.update_widgets(instance, validated_data["widgets"]) self.update_dashboard_filters(instance, validated_data) self.update_permissions(instance, validated_data) schedule_update_project_configs(instance) return instance def update_widgets(self, instance, widget_data): with sentry_sdk.start_span(op="function", name="dashboard.update_widgets"): widget_ids = [widget["id"] for widget in widget_data if "id" in widget] existing_widgets = DashboardWidget.objects.filter(dashboard=instance, id__in=widget_ids) existing_map = {widget.id: widget for widget in existing_widgets} # Remove widgets that are not in the current request. self.remove_missing_widgets(instance.id, widget_ids) for i, data in enumerate(widget_data): widget_id = data.get("id") if widget_id and widget_id in existing_map: # Update existing widget. self.update_widget(existing_map[widget_id], data) elif not widget_id: # Create a new widget. self.create_widget(instance, data) else: raise serializers.ValidationError( "You cannot update widgets that are not part of this dashboard." ) def remove_missing_widgets(self, dashboard_id, keep_ids): """ Removes current widgets belonging to dashboard not in keep_ids. """ DashboardWidget.objects.filter(dashboard_id=dashboard_id).exclude(id__in=keep_ids).delete() def create_widget(self, dashboard, widget_data): widget = DashboardWidget.objects.create( dashboard=dashboard, display_type=widget_data["display_type"], title=widget_data["title"], description=widget_data.get("description", None), thresholds=widget_data.get("thresholds", None), interval=widget_data.get("interval", "5m"), widget_type=widget_data.get("widget_type", DashboardWidgetTypes.ERROR_EVENTS), discover_widget_split=widget_data.get("discover_widget_split", None), limit=widget_data.get("limit", None), detail={"layout": widget_data.get("layout")}, dataset_source=widget_data.get("dataset_source", DatasetSourcesTypes.USER.value), ) new_queries = [] query_data_list = widget_data.pop("queries") for i, query in enumerate(query_data_list): new_queries.append( DashboardWidgetQuery( widget=widget, fields=query["fields"], aggregates=query.get("aggregates"), columns=query.get("columns"), field_aliases=query.get("field_aliases"), conditions=query["conditions"], name=query.get("name", ""), orderby=query.get("orderby", ""), order=i, is_hidden=query.get("is_hidden", False), selected_aggregate=query.get("selected_aggregate"), ) ) DashboardWidgetQuery.objects.bulk_create(new_queries) # Handle field links for each query for query_obj, query_data in zip(new_queries, query_data_list): if "linked_dashboards" in query_data and query_data["linked_dashboards"]: self._update_or_create_field_links( query_obj, query_data.get("linked_dashboards", []), widget ) if widget.widget_type in [ DashboardWidgetTypes.DISCOVER, DashboardWidgetTypes.TRANSACTION_LIKE, ]: self._check_query_cardinality(new_queries) def _check_query_cardinality(self, new_queries: Sequence[DashboardWidgetQuery]): organization = self.context["organization"] max_cardinality_allowed = options.get("on_demand.max_widget_cardinality.on_query_count") # To match the format of the extraction state function in ondemand ondemand_feature = features.has( "organizations:on-demand-metrics-extraction-widgets", organization ) current_widget_specs = get_current_widget_specs(organization) for new_query in new_queries: query_cardinality = all( check_field_cardinality( new_query.columns, organization, max_cardinality_allowed ).values() ) set_or_create_on_demand_state( new_query, organization, query_cardinality, ondemand_feature, current_widget_specs, ) def _update_or_create_field_links( self, query: DashboardWidgetQuery, linked_dashboards: list[LinkedDashboard], widget: DashboardWidget, ): """ Update DashboardFieldLink entries for a query. linked_dashboards is expected to be an array of dicts with format {"field": str, "dashboard_id": int} This can be further optimized, currently we are doing one bulk update for every widget query, but we could do one bulk update for all widget queries at once. In practice a table typically has only one query, so this is not a big deal. """ organization = self.context["organization"] user = self.context["request"].user if not features.has("organizations:dashboards-drilldown-flow", organization, actor=user): return with sentry_sdk.start_span( op="function", name="dashboard.update_or_create_field_links" ) as span: # Get the set of fields that should exist new_fields = set() field_links_to_create = [] widget_display_type = widget.display_type span.set_data( "linked_dashboards", [ {"field": ld.get("field"), "dashboard_id": ld.get("dashboard_id")} for ld in linked_dashboards ], ) span.set_data("widget_display_type", widget_display_type) span.set_data("query_id", query.id) span.set_data("widget_id", widget.id) if ( widget_display_type is not DashboardWidgetDisplayTypes.TABLE and len(linked_dashboards) > 0 ): raise serializers.ValidationError( "Field links are only supported for table widgets" ) if ( widget_display_type is not DashboardWidgetDisplayTypes.TABLE and len(linked_dashboards) < 1 ): return # check if the linked dashboard appears in the fields of the query if not all( field in query.fields for field in [ linked_dashboard.get("field") for linked_dashboard in linked_dashboards ] ): raise serializers.ValidationError( "Linked dashboard does not appear in the fields of the query" ) for link_data in linked_dashboards: field = link_data.get("field") dashboard_id = link_data.get("dashboard_id") if field and dashboard_id: new_fields.add(field) field_links_to_create.append( DashboardFieldLink( dashboard_widget_query=query, field=field, dashboard_id=int(dashboard_id), ) ) # Delete field links that are no longer in the request DashboardFieldLink.objects.filter(dashboard_widget_query=query).exclude( field__in=new_fields ).delete() with sentry_sdk.start_span( op="db.bulk_create", name="dashboard.update_or_create_field_links.bulk_create" ) as span: span.set_data("new_fields", list(new_fields)) span.set_data("query_id", query.id) span.set_data("widget_id", widget.id) span.set_data("widget_display_type", widget.display_type) span.set_data( "linked_dashboards", [ {"field": ld.get("field"), "dashboard_id": ld.get("dashboard_id")} for ld in linked_dashboards ], ) span.set_data("field_links_count", len(field_links_to_create)) # Use bulk_create with update_conflicts to effectively upsert (i.e bulk update or create) if field_links_to_create: DashboardFieldLink.objects.bulk_create( field_links_to_create, update_conflicts=True, unique_fields=["dashboard_widget_query", "field"], update_fields=["dashboard_id"], ) def update_widget(self, widget, data): prev_layout = widget.detail.get("layout") if widget.detail else None widget.title = data.get("title", widget.title) widget.description = data.get("description", widget.description) widget.thresholds = data.get("thresholds", widget.thresholds) widget.display_type = data.get("display_type", widget.display_type) widget.interval = data.get("interval", widget.interval) widget.widget_type = data.get("widget_type", widget.widget_type) widget.discover_widget_split = data.get( "discover_widget_split", widget.discover_widget_split ) widget.limit = data.get("limit", widget.limit) new_dataset_source = data.get("dataset_source", widget.dataset_source) widget.dataset_source = new_dataset_source widget.detail = {"layout": data.get("layout", prev_layout)} if widget.widget_type == DashboardWidgetTypes.SPANS: if new_dataset_source == DatasetSourcesTypes.USER.value: widget.changed_reason = None # we don't want to reset dataset source for spans widgets in case they are part of the migration elif widget.widget_type not in [ DashboardWidgetTypes.DISCOVER, DashboardWidgetTypes.TRANSACTION_LIKE, DashboardWidgetTypes.ERROR_EVENTS, ]: # Reset the discover split fields if the widget type is no longer # a discover/errors/transactions widget widget.discover_widget_split = None widget.dataset_source = DatasetSourcesTypes.UNKNOWN.value widget.save() if "queries" in data: self.update_widget_queries(widget, data["queries"]) def update_widget_queries(self, widget, data): query_ids = [query["id"] for query in data if "id" in query] all_query_array = [] self.remove_missing_queries(widget.id, query_ids) existing = DashboardWidgetQuery.objects.filter(widget=widget, id__in=query_ids) existing_map = {query.id: query for query in existing} # Get new ordering start point to avoid constraint errors next_order = get_next_query_order(widget.id) new_queries = [] update_queries = [] for i, query_data in enumerate(data): query_id = query_data.get("id") if query_id and query_id in existing_map: update_query = self.update_widget_query( existing_map[query_id], query_data, next_order + i ) all_query_array.append({"query_obj": update_query, "query_data": query_data}) update_queries.append(update_query) elif not query_id: new_query = DashboardWidgetQuery( widget=widget, fields=query_data["fields"], aggregates=query_data.get("aggregates"), columns=query_data.get("columns"), field_aliases=query_data.get("field_aliases"), conditions=query_data["conditions"], name=query_data.get("name", ""), is_hidden=query_data.get("is_hidden", False), orderby=query_data.get("orderby", ""), order=next_order + i, selected_aggregate=query_data.get("selected_aggregate"), ) new_queries.append(new_query) all_query_array.append({"query_obj": new_query, "query_data": query_data}) else: raise serializers.ValidationError("You cannot use a query not owned by this widget") DashboardWidgetQuery.objects.bulk_create(new_queries) for query_data in all_query_array: if "linked_dashboards" in query_data["query_data"]: self._update_or_create_field_links( query_data["query_obj"], query_data["query_data"].get("linked_dashboards", []), widget, ) if widget.widget_type in [ DashboardWidgetTypes.DISCOVER, DashboardWidgetTypes.TRANSACTION_LIKE, ]: self._check_query_cardinality(new_queries + update_queries) def update_widget_query(self, query, data, order): query.name = data.get("name", query.name) query.fields = data.get("fields", query.fields) query.conditions = data.get("conditions", query.conditions) query.orderby = data.get("orderby", query.orderby) query.aggregates = data.get("aggregates", query.aggregates) query.columns = data.get("columns", query.columns) query.field_aliases = data.get("field_aliases", query.field_aliases) query.is_hidden = data.get("is_hidden", query.is_hidden) query.selected_aggregate = data.get("selected_aggregate", query.selected_aggregate) query.order = order query.save() return query def remove_missing_queries(self, widget_id, keep_ids): DashboardWidgetQuery.objects.filter(widget_id=widget_id).exclude(id__in=keep_ids).delete()
DashboardDetailsSerializer
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/ranges.py
{ "start": 31104, "end": 31248 }
class ____(AbstractMultiRange[int]): """Represent the PostgreSQL INT4MULTIRANGE type.""" __visit_name__ = "INT4MULTIRANGE"
INT4MULTIRANGE
python
cython__cython
runtests.py
{ "start": 18791, "end": 19353 }
class ____(_build_ext): def build_extension(self, ext): try: compiler_obj = self.compiler if ext.language == 'c++': compiler_obj.compiler_so.remove('-Wstrict-prototypes') if CCACHE: compiler_obj.compiler_so = CCACHE + compiler_obj.compiler_so if getattr(ext, 'openmp', None) and compiler_obj.compiler_type == 'msvc': ext.extra_compile_args.append('/openmp') except Exception: pass _build_ext.build_extension(self, ext)
build_ext
python
realpython__materials
python-protocol/contents.py
{ "start": 105, "end": 232 }
class ____(ContentCreator, Protocol): posts: list[str] def add_post(self, title: str, content: str) -> None: ...
Blogger
python
psf__requests
tests/test_structures.py
{ "start": 81, "end": 1572 }
class ____: @pytest.fixture(autouse=True) def setup(self): """CaseInsensitiveDict instance with "Accept" header.""" self.case_insensitive_dict = CaseInsensitiveDict() self.case_insensitive_dict["Accept"] = "application/json" def test_list(self): assert list(self.case_insensitive_dict) == ["Accept"] possible_keys = pytest.mark.parametrize( "key", ("accept", "ACCEPT", "aCcEpT", "Accept") ) @possible_keys def test_getitem(self, key): assert self.case_insensitive_dict[key] == "application/json" @possible_keys def test_delitem(self, key): del self.case_insensitive_dict[key] assert key not in self.case_insensitive_dict def test_lower_items(self): assert list(self.case_insensitive_dict.lower_items()) == [ ("accept", "application/json") ] def test_repr(self): assert repr(self.case_insensitive_dict) == "{'Accept': 'application/json'}" def test_copy(self): copy = self.case_insensitive_dict.copy() assert copy is not self.case_insensitive_dict assert copy == self.case_insensitive_dict @pytest.mark.parametrize( "other, result", ( ({"AccePT": "application/json"}, True), ({}, False), (None, False), ), ) def test_instance_equality(self, other, result): assert (self.case_insensitive_dict == other) is result
TestCaseInsensitiveDict
python
huggingface__transformers
src/transformers/debug_utils.py
{ "start": 774, "end": 12768 }
class ____: """ This debug class helps detect and understand where the model starts getting very large or very small, and more importantly `nan` or `inf` weight and activation elements. There are 2 working modes: 1. Underflow/overflow detection (default) 2. Specific batch absolute min/max tracing without detection Mode 1: Underflow/overflow detection To activate the underflow/overflow detection, initialize the object with the model : ```python debug_overflow = DebugUnderflowOverflow(model) ``` then run the training as normal and if `nan` or `inf` gets detected in at least one of the weight, input or output elements this module will throw an exception and will print `max_frames_to_save` frames that lead to this event, each frame reporting 1. the fully qualified module name plus the class name whose `forward` was run 2. the absolute min and max value of all elements for each module weights, and the inputs and output For example, here is the header and the last few frames in detection report for `google/mt5-small` run in fp16 mixed precision : ``` Detected inf/nan during batch_number=0 Last 21 forward frames: abs min abs max metadata [...] encoder.block.2.layer.1.DenseReluDense.wi_0 Linear 2.17e-07 4.50e+00 weight 1.79e-06 4.65e+00 input[0] 2.68e-06 3.70e+01 output encoder.block.2.layer.1.DenseReluDense.wi_1 Linear 8.08e-07 2.66e+01 weight 1.79e-06 4.65e+00 input[0] 1.27e-04 2.37e+02 output encoder.block.2.layer.1.DenseReluDense.wo Linear 1.01e-06 6.44e+00 weight 0.00e+00 9.74e+03 input[0] 3.18e-04 6.27e+04 output encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense 1.79e-06 4.65e+00 input[0] 3.18e-04 6.27e+04 output encoder.block.2.layer.1.dropout Dropout 3.18e-04 6.27e+04 input[0] 0.00e+00 inf output ``` You can see here, that `T5DenseGatedGeluDense.forward` resulted in output activations, whose absolute max value was around 62.7K, which is very close to fp16's top limit of 64K. In the next frame we have `Dropout` which renormalizes the weights, after it zeroed some of the elements, which pushes the absolute max value to more than 64K, and we get an overflow. As you can see it's the previous frames that we need to look into when the numbers start going into very large for fp16 numbers. The tracking is done in a forward hook, which gets invoked immediately after `forward` has completed. By default the last 21 frames are printed. You can change the default to adjust for your needs. For example : ```python debug_overflow = DebugUnderflowOverflow(model, max_frames_to_save=100) ``` To validate that you have set up this debugging feature correctly, and you intend to use it in a training that may take hours to complete, first run it with normal tracing enabled for one of a few batches as explained in the next section. Mode 2. Specific batch absolute min/max tracing without detection The second work mode is per-batch tracing with the underflow/overflow detection feature turned off. Let's say you want to watch the absolute min and max values for all the ingredients of each `forward` call of a given batch, and only do that for batches 1 and 3. Then you instantiate this class as : ```python debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3]) ``` And now full batches 1 and 3 will be traced using the same format as explained above. Batches are 0-indexed. This is helpful if you know that the program starts misbehaving after a certain batch number, so you can fast-forward right to that area. Early stopping: You can also specify the batch number after which to stop the training, with : ```python debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3], abort_after_batch_num=3) ``` This feature is mainly useful in the tracing mode, but you can use it for any mode. **Performance**: As this module measures absolute `min`/``max` of each weight of the model on every forward it'll slow the training down. Therefore remember to turn it off once the debugging needs have been met. Args: model (`nn.Module`): The model to debug. max_frames_to_save (`int`, *optional*, defaults to 21): How many frames back to record trace_batch_nums(`list[int]`, *optional*, defaults to `[]`): Which batch numbers to trace (turns detection off) abort_after_batch_num (`int``, *optional*): Whether to abort after a certain batch number has finished """ def __init__(self, model, max_frames_to_save=21, trace_batch_nums=[], abort_after_batch_num=None): self.model = model self.trace_batch_nums = trace_batch_nums self.abort_after_batch_num = abort_after_batch_num # keep a LIFO buffer of frames to dump as soon as inf/nan is encountered to give context to the problem emergence self.frames = collections.deque([], max_frames_to_save) self.frame = [] self.batch_number = 0 self.total_calls = 0 self.detected_overflow = False self.prefix = " " self.analyse_model() self.register_forward_hook() def save_frame(self, frame=None): if frame is not None: self.expand_frame(frame) self.frames.append("\n".join(self.frame)) self.frame = [] # start a new frame def expand_frame(self, line): self.frame.append(line) def trace_frames(self): print("\n".join(self.frames)) self.frames = [] def reset_saved_frames(self): self.frames = [] def dump_saved_frames(self): print(f"\nDetected inf/nan during batch_number={self.batch_number}") print(f"Last {len(self.frames)} forward frames:") print(f"{'abs min':8} {'abs max':8} metadata") print("\n".join(self.frames)) print("\n\n") self.frames = [] def analyse_model(self): # extract the fully qualified module names, to be able to report at run time. e.g.: # encoder.block.2.layer.0.SelfAttention.o # # for shared weights only the first shared module name will be registered self.module_names = {m: name for name, m in self.model.named_modules()} # self.longest_module_name = max(len(v) for v in self.module_names.values()) def analyse_variable(self, var, ctx): if torch.is_tensor(var): self.expand_frame(get_abs_min_max(var, ctx)) if detect_overflow(var, ctx): self.detected_overflow = True elif var is None: self.expand_frame(f"{'None':>17} {ctx}") else: self.expand_frame(f"{'not a tensor':>17} {ctx}") def batch_start_frame(self): self.expand_frame(f"\n\n{self.prefix} *** Starting batch number={self.batch_number} ***") self.expand_frame(f"{'abs min':8} {'abs max':8} metadata") def batch_end_frame(self): self.expand_frame(f"{self.prefix} *** Finished batch number={self.batch_number - 1} ***\n\n") def create_frame(self, module, input, output): self.expand_frame(f"{self.prefix} {self.module_names[module]} {module.__class__.__name__}") # params for name, p in module.named_parameters(recurse=False): self.analyse_variable(p, name) # inputs if isinstance(input, tuple): for i, x in enumerate(input): self.analyse_variable(x, f"input[{i}]") else: self.analyse_variable(input, "input") # outputs if isinstance(output, tuple): for i, x in enumerate(output): # possibly a tuple of tuples if isinstance(x, tuple): for j, y in enumerate(x): self.analyse_variable(y, f"output[{i}][{j}]") else: self.analyse_variable(x, f"output[{i}]") else: self.analyse_variable(output, "output") self.save_frame() def register_forward_hook(self): self.model.apply(self._register_forward_hook) def _register_forward_hook(self, module): module.register_forward_hook(self.forward_hook) def forward_hook(self, module, input, output): # - input is a tuple of packed inputs (could be non-Tensors) # - output could be a Tensor or a tuple of Tensors and non-Tensors last_frame_of_batch = False trace_mode = self.batch_number in self.trace_batch_nums if trace_mode: self.reset_saved_frames() if self.total_calls == 0: self.batch_start_frame() self.total_calls += 1 # count batch numbers - the very first forward hook of the batch will be called when the # batch completes - i.e. it gets called very last - we know this batch has finished if module == self.model: self.batch_number += 1 last_frame_of_batch = True self.create_frame(module, input, output) # if last_frame_of_batch: # self.batch_end_frame() if trace_mode: self.trace_frames() if last_frame_of_batch: self.batch_start_frame() if self.detected_overflow and not trace_mode: self.dump_saved_frames() # now we can abort, as it's pointless to continue running raise ValueError( "DebugUnderflowOverflow: inf/nan detected, aborting as there is no point running further. " "Please scroll up above this traceback to see the activation values prior to this event." ) # abort after certain batch if requested to do so if self.abort_after_batch_num is not None and self.batch_number > self.abort_after_batch_num: raise ValueError( f"DebugUnderflowOverflow: aborting after {self.batch_number} batches due to" f" `abort_after_batch_num={self.abort_after_batch_num}` arg" ) def get_abs_min_max(var, ctx): abs_var = var.abs() return f"{abs_var.min():8.2e} {abs_var.max():8.2e} {ctx}" def detect_overflow(var, ctx): """ Report whether the tensor contains any `nan` or `inf` entries. This is useful for detecting overflows/underflows and best to call right after the function that did some math that modified the tensor in question. This function contains a few other helper features that you can enable and tweak directly if you want to track various other things. Args: var: the tensor variable to check ctx: the message to print as a context Return: `True` if `inf` or `nan` was detected, `False` otherwise """ detected = False if torch.isnan(var).any().item(): detected = True print(f"{ctx} has nans") if torch.isinf(var).any().item(): detected = True print(f"{ctx} has infs") # if needed to monitor large elements can enable the following if 0: # and detected: n100 = var[torch.ge(var.abs(), 100)] if n100.numel() > 0: print(f"{ctx}: n100={n100.numel()}") n1000 = var[torch.ge(var.abs(), 1000)] if n1000.numel() > 0: print(f"{ctx}: n1000={n1000.numel()}") n10000 = var[torch.ge(var.abs(), 10000)] if n10000.numel() > 0: print(f"{ctx}: n10000={n10000.numel()}") if 0: print(f"min={var.min():9.2e} max={var.max():9.2e}") if 0: print(f"min={var.min():9.2e} max={var.max():9.2e} var={var.var():9.2e} mean={var.mean():9.2e} ({ctx})") return detected
DebugUnderflowOverflow
python
kamyu104__LeetCode-Solutions
Python/check-if-digits-are-equal-in-string-after-operations-i.py
{ "start": 1000, "end": 2153 }
class ____(object): def hasSameDigits(self, s): """ :type s: str :rtype: bool """ def nCr(n, r): if n-r < r: r = n-r if LOOKUP[n][r] == -1: c = 1 for k in xrange(1, r+1): c *= n-k+1 c //= k LOOKUP[n][r] = c return LOOKUP[n][r] # https://en.wikipedia.org/wiki/Lucas%27s_theorem def nCr_mod(n, r, mod): result = 1 while n > 0 or r > 0: n, ni = divmod(n, mod) r, ri = divmod(r, mod) if ni < ri: return 0 result = (result*nCr(ni, ri))%mod return result def nC10(n, k): return lookup[nCr_mod(n, k, 2)][nCr_mod(n, k, 5)] lookup = [[0]*5 for _ in xrange(2)] for i in xrange(10): lookup[i%2][i%5] = i total = 0 for i in xrange(len(s)-1): total = (total+nC10(len(s)-2, i)*(ord(s[i])-ord(s[i+1])))%10 return total == 0 # Time: O(n^2) # Space: O(1)
Solution2
python
huggingface__transformers
src/transformers/models/qwen3_vl/modular_qwen3_vl.py
{ "start": 19989, "end": 21010 }
class ____(Qwen3DecoderLayer): def __init__(self, config: Qwen3VLTextConfig, layer_idx: int): super().__init__(config, layer_idx) del self.attention_type def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, use_cache: Optional[bool] = False, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> torch.Tensor: return super().forward( hidden_states=hidden_states, position_embeddings=position_embeddings, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, use_cache=use_cache, cache_position=cache_position, **kwargs, )
Qwen3VLTextDecoderLayer
python
walkccc__LeetCode
solutions/3453. Separate Squares I/3453.py
{ "start": 0, "end": 532 }
class ____: def separateSquares(self, squares: list[list[int]]) -> float: halfArea = sum((l**2 for _, _, l in squares)) / 2 events = sorted([(y, True, l) for _, y, l in squares] + [(y + l, False, l) for _, y, l in squares]) area = 0 width = 0 prevY = 0 for y, isStart, l in events: areaGain = width * (y - prevY) if area + areaGain >= halfArea: return prevY + (halfArea - area) / width area += areaGain width += l if isStart else -l prevY = y
Solution
python
django__django
django/core/checks/messages.py
{ "start": 1654, "end": 1773 }
class ____(CheckMessage): def __init__(self, *args, **kwargs): super().__init__(DEBUG, *args, **kwargs)
Debug
python
cython__cython
Demos/benchmarks/bm_chaos.py
{ "start": 1921, "end": 4636 }
class ____(object): """Class for representing B-Splines and NURBS of arbitrary degree""" def __init__(self, points, degree = 3, knots = None): """Creates a Spline. points is a list of GVector, degree is the degree of the Spline.""" if knots is None: self.knots = GetKnots(points, degree) else: if len(points) > len(knots) - degree + 1: raise ValueError("too many control points") elif len(points) < len(knots) - degree + 1: raise ValueError("not enough control points") last = knots[0] for cur in knots[1:]: if cur < last: raise ValueError("knots not strictly increasing") last = cur self.knots = knots self.points = points self.degree = degree def GetDomain(self) -> tuple[cython.long, cython.long]: """Returns the domain of the B-Spline""" return (self.knots[self.degree - 1], self.knots[len(self.knots) - self.degree]) @cython.locals(ik=cython.long, ii=cython.long, I=cython.long, ua=cython.long, ub=cython.long, index=cython.Py_ssize_t) def __call__(self, u: float): """Calculates a point of the B-Spline using de Boors Algorithm""" dom: tuple[cython.long, cython.long] = self.GetDomain() if u < dom[0] or u > dom[1]: raise ValueError("Function value not in domain") if u == dom[0]: return self.points[0] if u == dom[1]: return self.points[-1] I: cython.long = self.GetIndex(u) d = [self.points[I - self.degree + 1 + ii] for ii in range(self.degree + 1)] U = self.knots for ik in range(1, self.degree + 1): for ii in range(I - self.degree + ik + 1, I + 2): ua = U[ii + self.degree - ik] ub = U[ii - 1] co1 = (ua - u) / (ua - ub) co2 = (u - ub) / (ua - ub) index = ii - I + self.degree - ik - 1 d[index] = d[index].linear_combination(d[index + 1], co1, co2) return d[0] @cython.locals(ii=cython.long, I=cython.long, dom=(cython.long, cython.long)) def GetIndex(self, u): dom = self.GetDomain() for ii in range(self.degree - 1, len(self.knots) - self.degree): if self.knots[ii] <= u < self.knots[ii + 1]: I = ii break else: I = dom[1] - 1 return I def __len__(self): return len(self.points) def __repr__(self): return "Spline(%r, %r, %r)" % (self.points, self.degree, self.knots)
Spline
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/hitl.py
{ "start": 1112, "end": 1338 }
class ____(BaseModel): """Schema for updating the content of a Human-in-the-loop detail.""" chosen_options: list[str] = Field(min_length=1) params_input: Mapping = Field(default_factory=dict)
UpdateHITLDetailPayload
python
astropy__astropy
astropy/coordinates/polarization.py
{ "start": 4550, "end": 8107 }
class ____(ShapedLikeNDArray): """ A representation of stokes coordinates with helpers for converting to profile names. Parameters ---------- stokes : array-like The numeric values representing stokes coordinates. """ info = StokesCoordInfo() def __init__(self, stokes, copy=False): if isinstance(stokes, type(self)): data = stokes._data.copy() if copy else stokes._data self.info = stokes.info else: data = np.asanyarray(stokes) if data.dtype.kind == "O": msg = "StokesCoord objects cannot be initialised with an object array." raise ValueError(msg) if data.dtype.kind == "U": data = self._from_symbols(data) else: data = data.copy() if copy and data is stokes else data self._data = data @property def shape(self): return self._data.shape @property def value(self): return self._data @property def dtype(self): return self._data.dtype def __array__(self, dtype=None, copy=COPY_IF_NEEDED): return self._data.astype(dtype, copy=copy) def _apply(self, method, *args, **kwargs): cls = type(self) if callable(method): new = cls(method(self._data, *args, **kwargs)) else: new = cls(getattr(self._data, method)(*args, **kwargs)) # Copy other 'info' attr only if it has actually been defined. # See PR #3898 for further explanation and justification, along # with Quantity.__array_finalize__ if "info" in self.__dict__: new.info = self.info return new @staticmethod def _from_symbols(symbols): """ Convert an array of symbols to an array of values """ values_array = np.full_like( symbols, UNKNOWN_STOKES_VALUE, dtype=int, subok=False ) for stokes_value, symbol in STOKES_VALUE_SYMBOL_MAP.items(): values_array[symbols == symbol.symbol] = stokes_value if (unknown_values := np.equal(values_array, UNKNOWN_STOKES_VALUE)).any(): raise ValueError( f"Unknown stokes symbols present in the input array: {np.unique(symbols[unknown_values])}" ) return values_array @property def symbol(self): """The coordinate represented as strings.""" known_symbols = tuple( ["?"] + [s.symbol for s in STOKES_VALUE_SYMBOL_MAP.values()] ) max_len = np.max([len(s) for s in known_symbols]) # Note we unbroadcast and re-broadcast here to prevent the new array # using more memory than the old one. unbroadcasted = np.round(unbroadcast(self.value)) symbolarr = np.full(unbroadcasted.shape, "?", dtype=f"<U{max_len}") for value, symbol in STOKES_VALUE_SYMBOL_MAP.items(): symbolarr[unbroadcasted == value] = symbol.symbol return np.broadcast_to(symbolarr, self.shape) def __setitem__(self, item, value): self._data[item] = type(self)(value)._data def __eq__(self, other): try: other = self.__class__(other) except Exception: return NotImplemented return self._data == other._data def __str__(self): arrstr = np.array2string(self.symbol, separator=", ", prefix=" ") return f"{type(self).__name__}({arrstr})" def __repr__(self): return self.__str__()
StokesCoord
python
walkccc__LeetCode
solutions/1669. Merge In Between Linked Lists/1669.py
{ "start": 0, "end": 525 }
class ____: def mergeInBetween( self, list1: ListNode, a: int, b: int, list2: ListNode, ) -> ListNode: nodeBeforeA = list1 for i in range(a - 1): nodeBeforeA = nodeBeforeA.next nodeB = nodeBeforeA.next for i in range(b - a): nodeB = nodeB.next nodeBeforeA.next = list2 lastNodeInList2 = list2 while lastNodeInList2.next: lastNodeInList2 = lastNodeInList2.next lastNodeInList2.next = nodeB.next nodeB.next = None return list1
Solution
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_pretty.py
{ "start": 3465, "end": 3519 }
class ____: def somemethod(self): pass
MyObj
python
plotly__plotly.py
plotly/graph_objs/parcoords/line/colorbar/_title.py
{ "start": 233, "end": 4021 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "parcoords.line.colorbar" _path_str = "parcoords.line.colorbar.title" _valid_props = {"font", "side", "text"} @property def font(self): """ Sets this color bar's title font. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.parcoords.line.colorbar.title.Font` - A dict of string/value properties that will be passed to the Font constructor Returns ------- plotly.graph_objs.parcoords.line.colorbar.title.Font """ return self["font"] @font.setter def font(self, val): self["font"] = val @property def side(self): """ Determines the location of color bar's title with respect to the color bar. Defaults to "top" when `orientation` if "v" and defaults to "right" when `orientation` if "h". The 'side' property is an enumeration that may be specified as: - One of the following enumeration values: ['right', 'top', 'bottom'] Returns ------- Any """ return self["side"] @side.setter def side(self, val): self["side"] = val @property def text(self): """ Sets the title of the color bar. The 'text' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["text"] @text.setter def text(self, val): self["text"] = val @property def _prop_descriptions(self): return """\ font Sets this color bar's title font. side Determines the location of color bar's title with respect to the color bar. Defaults to "top" when `orientation` if "v" and defaults to "right" when `orientation` if "h". text Sets the title of the color bar. """ def __init__(self, arg=None, font=None, side=None, text=None, **kwargs): """ Construct a new Title object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.parcoords.line .colorbar.Title` font Sets this color bar's title font. side Determines the location of color bar's title with respect to the color bar. Defaults to "top" when `orientation` if "v" and defaults to "right" when `orientation` if "h". text Sets the title of the color bar. Returns ------- Title """ super().__init__("title") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.parcoords.line.colorbar.Title constructor must be a dict or an instance of :class:`plotly.graph_objs.parcoords.line.colorbar.Title`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("font", arg, font) self._set_property("side", arg, side) self._set_property("text", arg, text) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Title
python
pyca__cryptography
src/cryptography/hazmat/_oid.py
{ "start": 10822, "end": 17240 }
class ____: CHALLENGE_PASSWORD = ObjectIdentifier("1.2.840.113549.1.9.7") UNSTRUCTURED_NAME = ObjectIdentifier("1.2.840.113549.1.9.2") _OID_NAMES = { NameOID.COMMON_NAME: "commonName", NameOID.COUNTRY_NAME: "countryName", NameOID.LOCALITY_NAME: "localityName", NameOID.STATE_OR_PROVINCE_NAME: "stateOrProvinceName", NameOID.STREET_ADDRESS: "streetAddress", NameOID.ORGANIZATION_NAME: "organizationName", NameOID.ORGANIZATIONAL_UNIT_NAME: "organizationalUnitName", NameOID.SERIAL_NUMBER: "serialNumber", NameOID.SURNAME: "surname", NameOID.GIVEN_NAME: "givenName", NameOID.TITLE: "title", NameOID.GENERATION_QUALIFIER: "generationQualifier", NameOID.X500_UNIQUE_IDENTIFIER: "x500UniqueIdentifier", NameOID.DN_QUALIFIER: "dnQualifier", NameOID.PSEUDONYM: "pseudonym", NameOID.USER_ID: "userID", NameOID.DOMAIN_COMPONENT: "domainComponent", NameOID.EMAIL_ADDRESS: "emailAddress", NameOID.JURISDICTION_COUNTRY_NAME: "jurisdictionCountryName", NameOID.JURISDICTION_LOCALITY_NAME: "jurisdictionLocalityName", NameOID.JURISDICTION_STATE_OR_PROVINCE_NAME: ( "jurisdictionStateOrProvinceName" ), NameOID.BUSINESS_CATEGORY: "businessCategory", NameOID.POSTAL_ADDRESS: "postalAddress", NameOID.POSTAL_CODE: "postalCode", NameOID.INN: "INN", NameOID.OGRN: "OGRN", NameOID.SNILS: "SNILS", NameOID.UNSTRUCTURED_NAME: "unstructuredName", SignatureAlgorithmOID.RSA_WITH_MD5: "md5WithRSAEncryption", SignatureAlgorithmOID.RSA_WITH_SHA1: "sha1WithRSAEncryption", SignatureAlgorithmOID.RSA_WITH_SHA224: "sha224WithRSAEncryption", SignatureAlgorithmOID.RSA_WITH_SHA256: "sha256WithRSAEncryption", SignatureAlgorithmOID.RSA_WITH_SHA384: "sha384WithRSAEncryption", SignatureAlgorithmOID.RSA_WITH_SHA512: "sha512WithRSAEncryption", SignatureAlgorithmOID.RSASSA_PSS: "rsassaPss", SignatureAlgorithmOID.ECDSA_WITH_SHA1: "ecdsa-with-SHA1", SignatureAlgorithmOID.ECDSA_WITH_SHA224: "ecdsa-with-SHA224", SignatureAlgorithmOID.ECDSA_WITH_SHA256: "ecdsa-with-SHA256", SignatureAlgorithmOID.ECDSA_WITH_SHA384: "ecdsa-with-SHA384", SignatureAlgorithmOID.ECDSA_WITH_SHA512: "ecdsa-with-SHA512", SignatureAlgorithmOID.DSA_WITH_SHA1: "dsa-with-sha1", SignatureAlgorithmOID.DSA_WITH_SHA224: "dsa-with-sha224", SignatureAlgorithmOID.DSA_WITH_SHA256: "dsa-with-sha256", SignatureAlgorithmOID.ED25519: "ed25519", SignatureAlgorithmOID.ED448: "ed448", SignatureAlgorithmOID.GOSTR3411_94_WITH_3410_2001: ( "GOST R 34.11-94 with GOST R 34.10-2001" ), SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_256: ( "GOST R 34.10-2012 with GOST R 34.11-2012 (256 bit)" ), SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_512: ( "GOST R 34.10-2012 with GOST R 34.11-2012 (512 bit)" ), HashAlgorithmOID.SHA1: "sha1", HashAlgorithmOID.SHA224: "sha224", HashAlgorithmOID.SHA256: "sha256", HashAlgorithmOID.SHA384: "sha384", HashAlgorithmOID.SHA512: "sha512", HashAlgorithmOID.SHA3_224: "sha3_224", HashAlgorithmOID.SHA3_256: "sha3_256", HashAlgorithmOID.SHA3_384: "sha3_384", HashAlgorithmOID.SHA3_512: "sha3_512", HashAlgorithmOID.SHA3_224_NIST: "sha3_224", HashAlgorithmOID.SHA3_256_NIST: "sha3_256", HashAlgorithmOID.SHA3_384_NIST: "sha3_384", HashAlgorithmOID.SHA3_512_NIST: "sha3_512", PublicKeyAlgorithmOID.DSA: "dsaEncryption", PublicKeyAlgorithmOID.EC_PUBLIC_KEY: "id-ecPublicKey", PublicKeyAlgorithmOID.RSAES_PKCS1_v1_5: "rsaEncryption", PublicKeyAlgorithmOID.X25519: "X25519", PublicKeyAlgorithmOID.X448: "X448", ExtendedKeyUsageOID.SERVER_AUTH: "serverAuth", ExtendedKeyUsageOID.CLIENT_AUTH: "clientAuth", ExtendedKeyUsageOID.CODE_SIGNING: "codeSigning", ExtendedKeyUsageOID.EMAIL_PROTECTION: "emailProtection", ExtendedKeyUsageOID.TIME_STAMPING: "timeStamping", ExtendedKeyUsageOID.OCSP_SIGNING: "OCSPSigning", ExtendedKeyUsageOID.SMARTCARD_LOGON: "msSmartcardLogin", ExtendedKeyUsageOID.KERBEROS_PKINIT_KDC: "pkInitKDC", ExtensionOID.SUBJECT_DIRECTORY_ATTRIBUTES: "subjectDirectoryAttributes", ExtensionOID.SUBJECT_KEY_IDENTIFIER: "subjectKeyIdentifier", ExtensionOID.KEY_USAGE: "keyUsage", ExtensionOID.PRIVATE_KEY_USAGE_PERIOD: "privateKeyUsagePeriod", ExtensionOID.SUBJECT_ALTERNATIVE_NAME: "subjectAltName", ExtensionOID.ISSUER_ALTERNATIVE_NAME: "issuerAltName", ExtensionOID.BASIC_CONSTRAINTS: "basicConstraints", ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS: ( "signedCertificateTimestampList" ), ExtensionOID.SIGNED_CERTIFICATE_TIMESTAMPS: ( "signedCertificateTimestampList" ), ExtensionOID.PRECERT_POISON: "ctPoison", ExtensionOID.MS_CERTIFICATE_TEMPLATE: "msCertificateTemplate", ExtensionOID.ADMISSIONS: "Admissions", CRLEntryExtensionOID.CRL_REASON: "cRLReason", CRLEntryExtensionOID.INVALIDITY_DATE: "invalidityDate", CRLEntryExtensionOID.CERTIFICATE_ISSUER: "certificateIssuer", ExtensionOID.NAME_CONSTRAINTS: "nameConstraints", ExtensionOID.CRL_DISTRIBUTION_POINTS: "cRLDistributionPoints", ExtensionOID.CERTIFICATE_POLICIES: "certificatePolicies", ExtensionOID.POLICY_MAPPINGS: "policyMappings", ExtensionOID.AUTHORITY_KEY_IDENTIFIER: "authorityKeyIdentifier", ExtensionOID.POLICY_CONSTRAINTS: "policyConstraints", ExtensionOID.EXTENDED_KEY_USAGE: "extendedKeyUsage", ExtensionOID.FRESHEST_CRL: "freshestCRL", ExtensionOID.INHIBIT_ANY_POLICY: "inhibitAnyPolicy", ExtensionOID.ISSUING_DISTRIBUTION_POINT: "issuingDistributionPoint", ExtensionOID.AUTHORITY_INFORMATION_ACCESS: "authorityInfoAccess", ExtensionOID.SUBJECT_INFORMATION_ACCESS: "subjectInfoAccess", ExtensionOID.OCSP_NO_CHECK: "OCSPNoCheck", ExtensionOID.CRL_NUMBER: "cRLNumber", ExtensionOID.DELTA_CRL_INDICATOR: "deltaCRLIndicator", ExtensionOID.TLS_FEATURE: "TLSFeature", AuthorityInformationAccessOID.OCSP: "OCSP", AuthorityInformationAccessOID.CA_ISSUERS: "caIssuers", SubjectInformationAccessOID.CA_REPOSITORY: "caRepository", CertificatePoliciesOID.CPS_QUALIFIER: "id-qt-cps", CertificatePoliciesOID.CPS_USER_NOTICE: "id-qt-unotice", OCSPExtensionOID.NONCE: "OCSPNonce", AttributeOID.CHALLENGE_PASSWORD: "challengePassword", }
AttributeOID
python
catalyst-team__catalyst
catalyst/metrics/_functional_metric.py
{ "start": 3582, "end": 6579 }
class ____(ICallbackLoaderMetric): """Class for custom **loader-based** metrics in a functional way. Args: metric_fn: metric function, that get outputs, targets and return score as torch.Tensor metric_key: metric name accumulative_fields: list of keys to accumulate data from batch compute_on_call: if True, allows compute metric's value on call prefix: metric prefix suffix: metric suffix .. note:: Metrics are calculated over all samples. Examples: .. code-block:: python from functools import partial import torch from catalyst import metrics import sklearn.metrics targets = torch.tensor([3, 0, 2, 2, 1]) outputs = torch.rand((len(targets), targets.max()+1)).softmax(1) metric = metrics.FunctionalLoaderMetric( metric_fn=partial( sklearn.metrics.roc_auc_score, average="macro", multi_class="ovr" ), metric_key="sk_auc", accumulative_fields=['y_score','y_true'], ) metric.reset(len(outputs), len(outputs)) metric.update(y_score=outputs, y_true=targets) metric.compute() # ... metric.compute_key_value() # {'sk_auc': ...} """ def __init__( self, metric_fn: Callable, metric_key: str, accumulative_fields: Iterable[str] = None, compute_on_call: bool = True, prefix: str = None, suffix: str = None, ): """Init""" super().__init__(compute_on_call=compute_on_call, prefix=prefix, suffix=suffix) self.metric_fn = metric_fn self.metric_name = f"{self.prefix}{metric_key}{self.suffix}" self.accumulative_metric = AccumulativeMetric( keys=accumulative_fields, compute_on_call=compute_on_call ) def reset(self, num_batches: int, num_samples: int) -> None: """ Reset metrics fields Args: num_batches: expected number of batches num_samples: expected number of samples to accumulate """ self.accumulative_metric.reset(num_batches, num_samples) def update(self, **kwargs) -> None: """ Update storage Args: **kwargs: ``self.metric_fn`` inputs to store """ self.accumulative_metric.update(**kwargs) def compute(self) -> torch.Tensor: """ Get metric for the whole loader Returns: custom metric """ stored_values = self.accumulative_metric.compute() return self.metric_fn(**stored_values) def compute_key_value(self) -> Dict[str, torch.Tensor]: """ Get metric for the whole loader Returns: Dict with one element-custom metric """ return {self.metric_name: self.compute()} __all__ = ["FunctionalBatchMetric", "FunctionalLoaderMetric"]
FunctionalLoaderMetric
python
jazzband__django-oauth-toolkit
tests/test_oidc_views.py
{ "start": 971, "end": 7160 }
class ____(TestCase): def test_get_connect_discovery_info(self): expected_response = { "issuer": "http://localhost/o", "authorization_endpoint": "http://localhost/o/authorize/", "token_endpoint": "http://localhost/o/token/", "userinfo_endpoint": "http://localhost/o/userinfo/", "jwks_uri": "http://localhost/o/.well-known/jwks.json", "scopes_supported": ["read", "write", "openid"], "response_types_supported": [ "code", "token", "id_token", "id_token token", "code token", "code id_token", "code id_token token", ], "subject_types_supported": ["public"], "id_token_signing_alg_values_supported": ["RS256", "HS256"], "token_endpoint_auth_methods_supported": ["client_secret_post", "client_secret_basic"], "code_challenge_methods_supported": ["plain", "S256"], "claims_supported": ["sub"], } response = self.client.get("/o/.well-known/openid-configuration") self.assertEqual(response.status_code, 200) assert response.json() == expected_response def test_get_connect_discovery_info_deprecated(self): expected_response = { "issuer": "http://localhost/o", "authorization_endpoint": "http://localhost/o/authorize/", "token_endpoint": "http://localhost/o/token/", "userinfo_endpoint": "http://localhost/o/userinfo/", "jwks_uri": "http://localhost/o/.well-known/jwks.json", "scopes_supported": ["read", "write", "openid"], "response_types_supported": [ "code", "token", "id_token", "id_token token", "code token", "code id_token", "code id_token token", ], "subject_types_supported": ["public"], "id_token_signing_alg_values_supported": ["RS256", "HS256"], "token_endpoint_auth_methods_supported": ["client_secret_post", "client_secret_basic"], "code_challenge_methods_supported": ["plain", "S256"], "claims_supported": ["sub"], } response = self.client.get("/o/.well-known/openid-configuration/") self.assertEqual(response.status_code, 200) assert response.json() == expected_response def expect_json_response_with_rp_logout(self, base): expected_response = { "issuer": f"{base}", "authorization_endpoint": f"{base}/authorize/", "token_endpoint": f"{base}/token/", "userinfo_endpoint": f"{base}/userinfo/", "jwks_uri": f"{base}/.well-known/jwks.json", "scopes_supported": ["read", "write", "openid"], "response_types_supported": [ "code", "token", "id_token", "id_token token", "code token", "code id_token", "code id_token token", ], "subject_types_supported": ["public"], "id_token_signing_alg_values_supported": ["RS256", "HS256"], "token_endpoint_auth_methods_supported": ["client_secret_post", "client_secret_basic"], "code_challenge_methods_supported": ["plain", "S256"], "claims_supported": ["sub"], "end_session_endpoint": f"{base}/logout/", } response = self.client.get(reverse("oauth2_provider:oidc-connect-discovery-info")) self.assertEqual(response.status_code, 200) assert response.json() == expected_response def test_get_connect_discovery_info_with_rp_logout(self): self.oauth2_settings.OIDC_RP_INITIATED_LOGOUT_ENABLED = True self.expect_json_response_with_rp_logout(self.oauth2_settings.OIDC_ISS_ENDPOINT) def test_get_connect_discovery_info_without_issuer_url(self): self.oauth2_settings.OIDC_ISS_ENDPOINT = None self.oauth2_settings.OIDC_USERINFO_ENDPOINT = None expected_response = { "issuer": "http://testserver/o", "authorization_endpoint": "http://testserver/o/authorize/", "token_endpoint": "http://testserver/o/token/", "userinfo_endpoint": "http://testserver/o/userinfo/", "jwks_uri": "http://testserver/o/.well-known/jwks.json", "scopes_supported": ["read", "write", "openid"], "response_types_supported": [ "code", "token", "id_token", "id_token token", "code token", "code id_token", "code id_token token", ], "subject_types_supported": ["public"], "id_token_signing_alg_values_supported": ["RS256", "HS256"], "token_endpoint_auth_methods_supported": ["client_secret_post", "client_secret_basic"], "code_challenge_methods_supported": ["plain", "S256"], "claims_supported": ["sub"], } response = self.client.get(reverse("oauth2_provider:oidc-connect-discovery-info")) self.assertEqual(response.status_code, 200) assert response.json() == expected_response def test_get_connect_discovery_info_without_issuer_url_with_rp_logout(self): self.oauth2_settings.OIDC_RP_INITIATED_LOGOUT_ENABLED = True self.oauth2_settings.OIDC_ISS_ENDPOINT = None self.oauth2_settings.OIDC_USERINFO_ENDPOINT = None self.expect_json_response_with_rp_logout("http://testserver/o") def test_get_connect_discovery_info_without_rsa_key(self): self.oauth2_settings.OIDC_RSA_PRIVATE_KEY = None response = self.client.get(reverse("oauth2_provider:oidc-connect-discovery-info")) self.assertEqual(response.status_code, 200) assert response.json()["id_token_signing_alg_values_supported"] == ["HS256"] @pytest.mark.usefixtures("oauth2_settings") @pytest.mark.oauth2_settings(presets.OIDC_SETTINGS_RW)
TestConnectDiscoveryInfoView
python
apache__airflow
providers/google/tests/unit/google/cloud/sensors/test_bigquery.py
{ "start": 5549, "end": 10580 }
class ____: @mock.patch("airflow.providers.google.cloud.sensors.bigquery.BigQueryHook") def test_passing_arguments_to_hook(self, mock_hook): task = BigQueryTablePartitionExistenceSensor( task_id="task-id", project_id=TEST_PROJECT_ID, dataset_id=TEST_DATASET_ID, table_id=TEST_TABLE_ID, partition_id=TEST_PARTITION_ID, gcp_conn_id=TEST_GCP_CONN_ID, impersonation_chain=TEST_IMPERSONATION_CHAIN, ) mock_hook.return_value.table_partition_exists.return_value = True results = task.poke(mock.MagicMock()) assert results is True mock_hook.assert_called_once_with( gcp_conn_id=TEST_GCP_CONN_ID, impersonation_chain=TEST_IMPERSONATION_CHAIN, ) mock_hook.return_value.table_partition_exists.assert_called_once_with( project_id=TEST_PROJECT_ID, dataset_id=TEST_DATASET_ID, table_id=TEST_TABLE_ID, partition_id=TEST_PARTITION_ID, ) @mock.patch("airflow.providers.google.cloud.sensors.bigquery.BigQueryHook") @mock.patch("airflow.providers.google.cloud.sensors.bigquery.BigQueryTablePartitionExistenceSensor.defer") def test_table_partition_existence_sensor_finish_before_deferred(self, mock_defer, mock_hook): """ Asserts that a task is deferred and a BigQueryTablePartitionExistenceTrigger will be fired when the BigQueryTablePartitionExistenceSensor is executed and deferrable is set to True. """ task = BigQueryTablePartitionExistenceSensor( task_id="test_task_id", project_id=TEST_PROJECT_ID, dataset_id=TEST_DATASET_ID, table_id=TEST_TABLE_ID, partition_id=TEST_PARTITION_ID, deferrable=True, ) mock_hook.return_value.table_partition_exists.return_value = True task.execute(mock.MagicMock()) assert not mock_defer.called @mock.patch("airflow.providers.google.cloud.sensors.bigquery.BigQueryHook") def test_execute_with_deferrable_mode(self, mock_hook): """ Asserts that a task is deferred and a BigQueryTablePartitionExistenceTrigger will be fired when the BigQueryTablePartitionExistenceSensor is executed and deferrable is set to True. """ task = BigQueryTablePartitionExistenceSensor( task_id="test_task_id", project_id=TEST_PROJECT_ID, dataset_id=TEST_DATASET_ID, table_id=TEST_TABLE_ID, partition_id=TEST_PARTITION_ID, deferrable=True, ) mock_hook.return_value.table_partition_exists.return_value = False with pytest.raises(TaskDeferred) as exc: task.execute(context={}) assert isinstance(exc.value.trigger, BigQueryTablePartitionExistenceTrigger), ( "Trigger is not a BigQueryTablePartitionExistenceTrigger" ) def test_execute_with_deferrable_mode_execute_failure(self): """Tests that an AirflowException is raised in case of error event""" task = BigQueryTablePartitionExistenceSensor( task_id="test_task_id", project_id=TEST_PROJECT_ID, dataset_id=TEST_DATASET_ID, table_id=TEST_TABLE_ID, partition_id=TEST_PARTITION_ID, deferrable=True, ) with pytest.raises(AirflowException): task.execute_complete(context={}, event={"status": "error", "message": "test failure message"}) def test_execute_complete_event_none(self): """Asserts that logging occurs as expected""" task = BigQueryTablePartitionExistenceSensor( task_id="task-id", project_id=TEST_PROJECT_ID, dataset_id=TEST_DATASET_ID, table_id=TEST_TABLE_ID, partition_id=TEST_PARTITION_ID, deferrable=True, ) with pytest.raises(AirflowException, match="No event received in trigger callback"): task.execute_complete(context={}, event=None) def test_execute_complete(self): """Asserts that logging occurs as expected""" task = BigQueryTablePartitionExistenceSensor( task_id="task-id", project_id=TEST_PROJECT_ID, dataset_id=TEST_DATASET_ID, table_id=TEST_TABLE_ID, partition_id=TEST_PARTITION_ID, deferrable=True, ) table_uri = f"{TEST_PROJECT_ID}:{TEST_DATASET_ID}.{TEST_TABLE_ID}" with mock.patch.object(task.log, "info") as mock_log_info: task.execute_complete(context={}, event={"status": "success", "message": "test"}) mock_log_info.assert_called_with( 'Sensor checks existence of partition: "%s" in table: %s', TEST_PARTITION_ID, table_uri ) @pytest.fixture def context(): """ Creates an empty context. """ context = {} return context
TestBigqueryTablePartitionExistenceSensor
python
dagster-io__dagster
python_modules/dagster/dagster/components/component/component.py
{ "start": 1339, "end": 2982 }
class ____(IHaveNew): """Specifies the core attributes of a component. Used when defining custom components. Args: description (Optional[str]): Human-readable description of this component. metadata (Optional[Dict[str, Any]]): A dict of static metadata for this component. For example, users can provide information about the database table this component corresponds to. owners (Optional[Sequence[str]]): A list of strings representing owners of the component. Each string can be a user's email address, or a team name prefixed with `team:`, e.g. `team:finops`. tags (Optional[Sequence[str]]): Tags for filtering and organizing. """ description: PublicAttr[Optional[str]] tags: PublicAttr[Sequence[str]] owners: PublicAttr[Sequence[str]] metadata: PublicAttr[Mapping[str, Any]] def __new__( cls, description: Optional[str] = None, tags: Optional[Sequence[str]] = None, owners: Optional[Sequence[str]] = None, metadata: Optional[Mapping[str, Any]] = None, ): owners = check.opt_sequence_param(owners, "owners", of_type=str) for owner in owners: validate_component_owner(owner) return super().__new__( cls, description=check.opt_str_param(description, "description"), tags=check.opt_sequence_param(tags, "tags", of_type=str), owners=owners, metadata=check.opt_mapping_param(metadata, "metadata", key_type=str), ) @public @scaffold_with(DefaultComponentScaffolder)
ComponentTypeSpec
python
donnemartin__interactive-coding-challenges
stacks_queues/n_stacks/test_n_stacks.py
{ "start": 18, "end": 1356 }
class ____(unittest.TestCase): def test_pop_on_empty(self, num_stacks, stack_size): print('Test: Pop on empty stack') stacks = Stacks(num_stacks, stack_size) stacks.pop(0) def test_push_on_full(self, num_stacks, stack_size): print('Test: Push to full stack') stacks = Stacks(num_stacks, stack_size) for i in range(0, stack_size): stacks.push(2, i) stacks.push(2, stack_size) def test_stacks(self, num_stacks, stack_size): print('Test: Push to non-full stack') stacks = Stacks(num_stacks, stack_size) stacks.push(0, 1) stacks.push(0, 2) stacks.push(1, 3) stacks.push(2, 4) print('Test: Pop on non-empty stack') self.assertEqual(stacks.pop(0), 2) self.assertEqual(stacks.pop(0), 1) self.assertEqual(stacks.pop(1), 3) self.assertEqual(stacks.pop(2), 4) print('Success: test_stacks\n') def main(): num_stacks = 3 stack_size = 100 test = TestStacks() test.assertRaises(Exception, test.test_pop_on_empty, num_stacks, stack_size) test.assertRaises(Exception, test.test_push_on_full, num_stacks, stack_size) test.test_stacks(num_stacks, stack_size) if __name__ == '__main__': main()
TestStacks
python
ray-project__ray
python/ray/train/tensorflow/tensorflow_checkpoint.py
{ "start": 380, "end": 5524 }
class ____(FrameworkCheckpoint): """A :py:class:`~ray.train.Checkpoint` with TensorFlow-specific functionality.""" MODEL_FILENAME_KEY = "_model_filename" @classmethod def from_model( cls, model: keras.Model, *, preprocessor: Optional["Preprocessor"] = None, ) -> "TensorflowCheckpoint": """Create a :py:class:`~ray.train.Checkpoint` that stores a Keras model. The checkpoint created with this method needs to be paired with `model` when used. Args: model: The Keras model, whose weights are stored in the checkpoint. preprocessor: A fitted preprocessor to be applied before inference. Returns: A :py:class:`TensorflowCheckpoint` containing the specified model. Examples: .. testcode:: from ray.train.tensorflow import TensorflowCheckpoint import tensorflow as tf model = tf.keras.applications.resnet.ResNet101() checkpoint = TensorflowCheckpoint.from_model(model) .. testoutput:: :options: +MOCK :hide: ... # Model may or may not be downloaded """ tempdir = tempfile.mkdtemp() filename = "model.keras" model.save(Path(tempdir, filename).as_posix()) checkpoint = cls.from_directory(tempdir) if preprocessor: checkpoint.set_preprocessor(preprocessor) checkpoint.update_metadata({cls.MODEL_FILENAME_KEY: filename}) return checkpoint @classmethod def from_h5( cls, file_path: str, *, preprocessor: Optional["Preprocessor"] = None ) -> "TensorflowCheckpoint": """Create a :py:class:`~ray.train.Checkpoint` that stores a Keras model from H5 format. The checkpoint generated by this method contains all the information needed. Thus no `model` is needed to be supplied when using this checkpoint. Args: file_path: The path to the .h5 file to load model from. This is the same path that is used for ``model.save(path)``. preprocessor: A fitted preprocessor to be applied before inference. Returns: A :py:class:`TensorflowCheckpoint` converted from h5 format. """ if not os.path.isfile(file_path) or not file_path.endswith(".h5"): raise ValueError( "Please supply a h5 file path to `TensorflowCheckpoint.from_h5()`." ) tempdir = tempfile.mkdtemp() filename = os.path.basename(file_path) new_checkpoint_file = Path(tempdir, filename).as_posix() shutil.copy(file_path, new_checkpoint_file) checkpoint = cls.from_directory(tempdir) if preprocessor: checkpoint.set_preprocessor(preprocessor) checkpoint.update_metadata({cls.MODEL_FILENAME_KEY: filename}) return checkpoint @classmethod def from_saved_model( cls, dir_path: str, *, preprocessor: Optional["Preprocessor"] = None ) -> "TensorflowCheckpoint": """Create a :py:class:`~ray.train.Checkpoint` that stores a Keras model from SavedModel format. The checkpoint generated by this method contains all the information needed. Thus no `model` is needed to be supplied when using this checkpoint. Args: dir_path: The directory containing the saved model. This is the same directory as used by ``model.save(dir_path)``. preprocessor: A fitted preprocessor to be applied before inference. Returns: A :py:class:`TensorflowCheckpoint` converted from SavedModel format. """ if not os.path.isdir(dir_path): raise ValueError( "Please supply a directory to `TensorflowCheckpoint.from_saved_model`" ) tempdir = tempfile.mkdtemp() # TODO(ml-team): Replace this with copytree() os.rmdir(tempdir) shutil.copytree(dir_path, tempdir) checkpoint = cls.from_directory(tempdir) if preprocessor: checkpoint.set_preprocessor(preprocessor) # NOTE: The entire directory is the checkpoint. checkpoint.update_metadata({cls.MODEL_FILENAME_KEY: "."}) return checkpoint def get_model( self, ) -> tf.keras.Model: """Retrieve the model stored in this checkpoint. Returns: The Tensorflow Keras model stored in the checkpoint. """ metadata = self.get_metadata() if self.MODEL_FILENAME_KEY not in metadata: raise ValueError( "`TensorflowCheckpoint` cannot retrieve the model if you override the " "checkpoint metadata. Please use `Checkpoint.update_metadata` instead." ) model_filename = metadata[self.MODEL_FILENAME_KEY] with self.as_directory() as checkpoint_dir: model_path = Path(checkpoint_dir, model_filename).as_posix() return keras.models.load_model(model_path)
TensorflowCheckpoint
python
jmcnamara__XlsxWriter
xlsxwriter/test/workbook/test_custom_sheet.py
{ "start": 404, "end": 447 }
class ____(Chartsheet): pass
MyChartsheet
python
getsentry__sentry
src/sentry/search/events/types.py
{ "start": 9265, "end": 9720 }
class ____: op: str group: str @staticmethod def from_str(s: str) -> Span: parts = s.rsplit(":", 1) if len(parts) != 2: raise ValueError( "span must consist of of a span op and a valid 16 character hex delimited by a colon (:)" ) if not is_span_id(parts[1]): raise ValueError(INVALID_SPAN_ID.format("spanGroup")) return Span(op=parts[0], group=parts[1])
Span
python
ansible__ansible
test/lib/ansible_test/_internal/commands/sanity/__init__.py
{ "start": 24801, "end": 25008 }
class ____(TestSuccess): """Sanity test success.""" def __init__(self, test: str, python_version: t.Optional[str] = None) -> None: super().__init__(COMMAND, test, python_version)
SanitySuccess
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 734454, "end": 735255 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "actor", "created_at", "database_id", "deployment", "pull_request", "ref", ) actor = sgqlc.types.Field(Actor, graphql_name="actor") created_at = sgqlc.types.Field( sgqlc.types.non_null(DateTime), graphql_name="createdAt" ) database_id = sgqlc.types.Field(Int, graphql_name="databaseId") deployment = sgqlc.types.Field( sgqlc.types.non_null("Deployment"), graphql_name="deployment" ) pull_request = sgqlc.types.Field( sgqlc.types.non_null("PullRequest"), graphql_name="pullRequest" ) ref = sgqlc.types.Field("Ref", graphql_name="ref")
DeployedEvent
python
MorvanZhou__Reinforcement-learning-with-tensorflow
contents/5.2_Prioritized_Replay_DQN/RL_brain.py
{ "start": 2873, "end": 4777 }
class ____(object): # stored as ( s, a, r, s_ ) in SumTree """ This Memory class is modified based on the original code from: https://github.com/jaara/AI-blog/blob/master/Seaquest-DDQN-PER.py """ epsilon = 0.01 # small amount to avoid zero priority alpha = 0.6 # [0~1] convert the importance of TD error to priority beta = 0.4 # importance-sampling, from initial value increasing to 1 beta_increment_per_sampling = 0.001 abs_err_upper = 1. # clipped abs error def __init__(self, capacity): self.tree = SumTree(capacity) def store(self, transition): max_p = np.max(self.tree.tree[-self.tree.capacity:]) if max_p == 0: max_p = self.abs_err_upper self.tree.add(max_p, transition) # set the max p for new p def sample(self, n): b_idx, b_memory, ISWeights = np.empty((n,), dtype=np.int32), np.empty((n, self.tree.data[0].size)), np.empty((n, 1)) pri_seg = self.tree.total_p / n # priority segment self.beta = np.min([1., self.beta + self.beta_increment_per_sampling]) # max = 1 min_prob = np.min(self.tree.tree[-self.tree.capacity:]) / self.tree.total_p # for later calculate ISweight for i in range(n): a, b = pri_seg * i, pri_seg * (i + 1) v = np.random.uniform(a, b) idx, p, data = self.tree.get_leaf(v) prob = p / self.tree.total_p ISWeights[i, 0] = np.power(prob/min_prob, -self.beta) b_idx[i], b_memory[i, :] = idx, data return b_idx, b_memory, ISWeights def batch_update(self, tree_idx, abs_errors): abs_errors += self.epsilon # convert to abs and avoid 0 clipped_errors = np.minimum(abs_errors, self.abs_err_upper) ps = np.power(clipped_errors, self.alpha) for ti, p in zip(tree_idx, ps): self.tree.update(ti, p)
Memory
python
django__django
tests/queries/tests.py
{ "start": 137492, "end": 138475 }
class ____(TestCase): """ Filtering on non-null character fields works as expected. The reason for these tests is that Oracle treats '' as NULL, and this can cause problems in query construction. Refs #17957. """ @classmethod def setUpTestData(cls): cls.nc = NamedCategory.objects.create(name="") def test_direct_exclude(self): self.assertQuerySetEqual( NamedCategory.objects.exclude(name__in=["nonexistent"]), [self.nc.pk], attrgetter("pk"), ) def test_joined_exclude(self): self.assertQuerySetEqual( DumbCategory.objects.exclude(namedcategory__name__in=["nonexistent"]), [self.nc.pk], attrgetter("pk"), ) def test_21001(self): foo = NamedCategory.objects.create(name="foo") self.assertQuerySetEqual( NamedCategory.objects.exclude(name=""), [foo.pk], attrgetter("pk") )
EmptyStringsAsNullTest
python
huggingface__transformers
src/transformers/models/mobilebert/modeling_mobilebert.py
{ "start": 12241, "end": 13297 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.use_bottleneck = config.use_bottleneck self.dense = nn.Linear(config.intermediate_size, config.true_hidden_size) self.LayerNorm = NORM2FN[config.normalization_type](config.true_hidden_size) if not self.use_bottleneck: self.dropout = nn.Dropout(config.hidden_dropout_prob) else: self.bottleneck = OutputBottleneck(config) def forward( self, intermediate_states: torch.Tensor, residual_tensor_1: torch.Tensor, residual_tensor_2: torch.Tensor ) -> torch.Tensor: layer_output = self.dense(intermediate_states) if not self.use_bottleneck: layer_output = self.dropout(layer_output) layer_output = self.LayerNorm(layer_output + residual_tensor_1) else: layer_output = self.LayerNorm(layer_output + residual_tensor_1) layer_output = self.bottleneck(layer_output, residual_tensor_2) return layer_output
MobileBertOutput
python
huggingface__transformers
src/transformers/models/gpt_bigcode/modeling_gpt_bigcode.py
{ "start": 23887, "end": 28868 }
class ____(GPTBigCodePreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "transformer.wte.weight"} def __init__(self, config): super().__init__(config) self.transformer = GPTBigCodeModel(config) self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) # Initialize weights and apply final processing self.post_init() @auto_docstring def forward( self, input_ids: Optional[torch.Tensor] = None, past_key_values: Optional[Cache] = None, attention_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.Tensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs, ) -> Union[tuple, CausalLMOutputWithCrossAttentions]: r""" input_ids (`torch.Tensor` of shape `(batch_size, input_ids_length)`): `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()` (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary. If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as `input_ids`. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) labels (`torch.Tensor` of shape `(batch_size, input_ids_length)`, *optional*): Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]` """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict transformer_outputs = self.transformer( input_ids, past_key_values=past_key_values, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, cache_position=cache_position, ) hidden_states = transformer_outputs[0] # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :]) loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs) if not return_dict: output = (logits,) + transformer_outputs[1:] return ((loss,) + output) if loss is not None else output return CausalLMOutputWithCrossAttentions( loss=loss, logits=logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, cross_attentions=transformer_outputs.cross_attentions, ) @auto_docstring( custom_intro=""" The GPTBigCode Model transformer with a sequence classification head on top (linear layer). [`GPTBigCodeForSequenceClassification`] uses the last token in order to do the classification, as other causal models (e.g. GPT-1) do. Since it does classification on the last token, it requires to know the position of the last token. If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in each row of the batch). """ )
GPTBigCodeForCausalLM
python
django__django
tests/admin_views/models.py
{ "start": 15307, "end": 15489 }
class ____(models.Model): name = models.CharField(max_length=25) two = models.ForeignKey("CyclicTwo", models.CASCADE) def __str__(self): return self.name
CyclicOne
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/graphql_context_test_suite.py
{ "start": 19008, "end": 30822 }
class ____: """An instance of this class represents a context variant that will be run against *every* method in the test class, defined as a class created by inheriting from make_graphql_context_test_suite. It comes with a number of static methods with prebuilt context variants. e.g. in_memory_in_process_start One can also make bespoke context variants, provided you configure it properly with MarkedMembers that produce its members. Args: marked_instance_mgr (MarkedManager): The manager_fn within it must be a contextmanager that takes zero arguments and yields a DagsterInstance See InstanceManagers for examples marked_environment_mgr (MarkedManager): The manager_fn with in must be a contextmanager takes a default ReconstructableRepo and yields a list of RepositoryLocation. See EnvironmentManagers for examples test_id [Optional] (str): This assigns a test_id to test parameterized with this variant. This is highly convenient for running a particular variant across the entire test suite, without running all the other variants. e.g. pytest python_modules/dagster-graphql/dagster_graphql_tests/ -s -k in_memory_in_process_start Will run all tests that use the in_memory_in_process_start, which will get a lot of code coverage while being very fast to run. All tests managed by this system are marked with "graphql_context_test_suite". """ def __init__(self, marked_instance_mgr, marked_environment_mgr, read_only=False, test_id=None): self.marked_instance_mgr = check.inst_param( marked_instance_mgr, "marked_instance_mgr", MarkedManager ) self.marked_environment_mgr = check.inst_param( marked_environment_mgr, "marked_environment_mgr", MarkedManager ) self.read_only = check.bool_param(read_only, "read_only") self.test_id = check.opt_str_param(test_id, "test_id") self.marks = ( marked_instance_mgr.marks + marked_environment_mgr.marks + ([Marks.read_only] if read_only else []) ) @property def instance_mgr(self): return self.marked_instance_mgr.manager_fn @property def environment_mgr(self): return self.marked_environment_mgr.manager_fn @staticmethod def sqlite_with_queued_run_coordinator_managed_grpc_env(): return GraphQLContextVariant( InstanceManagers.sqlite_instance_with_queued_run_coordinator(), EnvironmentManagers.managed_grpc(), test_id="sqlite_with_queued_run_coordinator_managed_grpc_env", ) @staticmethod def sqlite_with_default_run_launcher_managed_grpc_env( target=None, location_name="test_location" ): return GraphQLContextVariant( InstanceManagers.sqlite_instance_with_default_run_launcher(), EnvironmentManagers.managed_grpc(target, location_name), test_id="sqlite_with_default_run_launcher_managed_grpc_env", ) @staticmethod def sqlite_read_only_with_default_run_launcher_managed_grpc_env(): return GraphQLContextVariant( InstanceManagers.sqlite_instance_with_default_run_launcher(), EnvironmentManagers.managed_grpc(), read_only=True, test_id="sqlite_read_only_with_default_run_launcher_managed_grpc_env", ) @staticmethod def sqlite_with_default_run_launcher_deployed_grpc_env( target=None, location_name="test_location" ): return GraphQLContextVariant( InstanceManagers.sqlite_instance_with_default_run_launcher(), EnvironmentManagers.deployed_grpc(target, location_name), test_id="sqlite_with_default_run_launcher_deployed_grpc_env", ) @staticmethod def sqlite_with_default_run_launcher_code_server_cli_env( target=None, location_name="test_location" ): return GraphQLContextVariant( InstanceManagers.sqlite_instance_with_default_run_launcher(), EnvironmentManagers.code_server_cli_grpc(target, location_name), test_id="sqlite_with_default_run_launcher_code_server_cli_env", ) @staticmethod def sqlite_with_default_concurrency_managed_grpc_env( target=None, location_name="test_location" ): return GraphQLContextVariant( InstanceManagers.default_concurrency_sqlite_instance(), EnvironmentManagers.managed_grpc(target, location_name), test_id="sqlite_with_default_concurrency_managed_grpc_env", ) @staticmethod def postgres_with_default_run_launcher_managed_grpc_env( target=None, location_name="test_location" ): return GraphQLContextVariant( InstanceManagers.postgres_instance_with_default_run_launcher(), EnvironmentManagers.managed_grpc(target, location_name), test_id="postgres_with_default_run_launcher_managed_grpc_env", ) @staticmethod def postgres_with_default_run_launcher_deployed_grpc_env( target=None, location_name="test_location" ): return GraphQLContextVariant( InstanceManagers.postgres_instance_with_default_run_launcher(), EnvironmentManagers.deployed_grpc(target, location_name), test_id="postgres_with_default_run_launcher_deployed_grpc_env", ) @staticmethod def non_launchable_sqlite_instance_multi_location(): return GraphQLContextVariant( InstanceManagers.non_launchable_sqlite_instance(), EnvironmentManagers.multi_location(), test_id="non_launchable_sqlite_instance_multi_location", ) @staticmethod def non_launchable_sqlite_instance_lazy_repository(): return GraphQLContextVariant( InstanceManagers.non_launchable_sqlite_instance(), EnvironmentManagers.lazy_repository(), test_id="non_launchable_sqlite_instance_lazy_repository", ) @staticmethod def non_launchable_sqlite_instance_managed_grpc_env(): return GraphQLContextVariant( InstanceManagers.non_launchable_sqlite_instance(), EnvironmentManagers.managed_grpc(), test_id="non_launchable_sqlite_instance_managed_grpc_env", ) @staticmethod def non_launchable_sqlite_instance_deployed_grpc_env(): return GraphQLContextVariant( InstanceManagers.non_launchable_sqlite_instance(), EnvironmentManagers.deployed_grpc(), test_id="non_launchable_sqlite_instance_deployed_grpc_env", ) @staticmethod def non_launchable_postgres_instance_multi_location(): return GraphQLContextVariant( InstanceManagers.non_launchable_postgres_instance(), EnvironmentManagers.multi_location(), test_id="non_launchable_postgres_instance_multi_location", ) @staticmethod def non_launchable_postgres_instance_lazy_repository(): return GraphQLContextVariant( InstanceManagers.non_launchable_postgres_instance(), EnvironmentManagers.lazy_repository(), test_id="non_launchable_postgres_instance_lazy_repository", ) @staticmethod def non_launchable_postgres_instance_managed_grpc_env(): return GraphQLContextVariant( InstanceManagers.non_launchable_postgres_instance(), EnvironmentManagers.managed_grpc(), test_id="non_launchable_postgres_instance_managed_grpc_env", ) @staticmethod def consolidated_sqlite_instance_managed_grpc_env(): return GraphQLContextVariant( InstanceManagers.consolidated_sqlite_instance(), EnvironmentManagers.managed_grpc(), test_id="asset_aware_instance_in_process_env", ) @staticmethod def all_variants(): """There is a test case that keeps this up-to-date. If you add a static method that returns a GraphQLContextVariant you have to add it to this list in order for tests to pass. """ return [ GraphQLContextVariant.sqlite_with_default_run_launcher_managed_grpc_env(), GraphQLContextVariant.sqlite_read_only_with_default_run_launcher_managed_grpc_env(), GraphQLContextVariant.sqlite_with_default_run_launcher_deployed_grpc_env(), GraphQLContextVariant.sqlite_with_default_run_launcher_code_server_cli_env(), GraphQLContextVariant.sqlite_with_queued_run_coordinator_managed_grpc_env(), GraphQLContextVariant.postgres_with_default_run_launcher_managed_grpc_env(), GraphQLContextVariant.postgres_with_default_run_launcher_deployed_grpc_env(), GraphQLContextVariant.non_launchable_sqlite_instance_multi_location(), GraphQLContextVariant.non_launchable_sqlite_instance_managed_grpc_env(), GraphQLContextVariant.non_launchable_sqlite_instance_deployed_grpc_env(), GraphQLContextVariant.non_launchable_sqlite_instance_lazy_repository(), GraphQLContextVariant.non_launchable_postgres_instance_multi_location(), GraphQLContextVariant.non_launchable_postgres_instance_managed_grpc_env(), GraphQLContextVariant.non_launchable_postgres_instance_lazy_repository(), GraphQLContextVariant.consolidated_sqlite_instance_managed_grpc_env(), GraphQLContextVariant.sqlite_with_default_concurrency_managed_grpc_env(), ] @staticmethod def all_executing_variants(target=None, location_name="test_location"): return [ GraphQLContextVariant.sqlite_with_default_run_launcher_managed_grpc_env( target, location_name ), GraphQLContextVariant.sqlite_with_default_run_launcher_deployed_grpc_env( target, location_name ), GraphQLContextVariant.sqlite_with_default_run_launcher_code_server_cli_env( target, location_name ), GraphQLContextVariant.postgres_with_default_run_launcher_managed_grpc_env( target, location_name ), GraphQLContextVariant.postgres_with_default_run_launcher_deployed_grpc_env( target, location_name ), ] @staticmethod def all_readonly_variants(): """Return all read only variants. If you try to run any mutation these will error.""" return _variants_with_mark(GraphQLContextVariant.all_variants(), pytest.mark.read_only) @staticmethod def all_non_launchable_variants(): """Return all non_launchable variants. If you try to start or launch these will error.""" return _variants_with_mark(GraphQLContextVariant.all_variants(), pytest.mark.non_launchable) @staticmethod def all_multi_location_variants(): return _variants_with_mark(GraphQLContextVariant.all_variants(), pytest.mark.multi_location) def _variants_with_mark(variants, mark): def _yield_all(): for variant in variants: if mark in variant.marks: yield variant return list(_yield_all()) def _variants_without_marks(variants, marks): def _yield_all(): for variant in variants: if all(mark not in variant.marks for mark in marks): yield variant return list(_yield_all()) @contextmanager def manage_graphql_context(context_variant): with context_variant.instance_mgr() as instance: with context_variant.environment_mgr( instance, context_variant.read_only ) as workspace_process_context: yield workspace_process_context
GraphQLContextVariant
python
walkccc__LeetCode
solutions/1057. Campus Bikes/1057.py
{ "start": 0, "end": 706 }
class ____: def assignBikes( self, workers: list[list[int]], bikes: list[list[int]], ) -> list[int]: ans = [-1] * len(workers) usedBikes = [False] * len(bikes) # buckets[k] := (i, j), where k = dist(workers[i], bikes[j]) buckets = [[] for _ in range(2001)] def dist(p1: list[int], p2: list[int]) -> int: return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]) for i, worker in enumerate(workers): for j, bike in enumerate(bikes): buckets[dist(worker, bike)].append((i, j)) for k in range(2001): for i, j in buckets[k]: if ans[i] == -1 and not usedBikes[j]: ans[i] = j usedBikes[j] = True return ans
Solution
python
anthropics__anthropic-sdk-python
src/anthropic/types/thinking_config_disabled_param.py
{ "start": 227, "end": 326 }
class ____(TypedDict, total=False): type: Required[Literal["disabled"]]
ThinkingConfigDisabledParam
python
getsentry__sentry
src/sentry/workflow_engine/handlers/condition/latest_adopted_release_handler.py
{ "start": 838, "end": 2918 }
class ____(DataConditionHandler[WorkflowEventData]): group = DataConditionHandler.Group.ACTION_FILTER subgroup = DataConditionHandler.Subgroup.EVENT_ATTRIBUTES comparison_json_schema = { "type": "object", "properties": { "release_age_type": {"type": "string", "enum": [*ModelAgeType]}, "age_comparison": {"type": "string", "enum": [*AgeComparisonType]}, "environment": {"type": "string"}, }, "required": ["release_age_type", "age_comparison", "environment"], "additionalProperties": False, } @staticmethod def evaluate_value(event_data: WorkflowEventData, comparison: Any) -> bool: release_age_type = comparison["release_age_type"] age_comparison = comparison["age_comparison"] environment_name = comparison["environment"] event = event_data.event if isinstance(event, Activity): # If the event is an Activity, we cannot determine the latest adopted release return False if follows_semver_versioning_scheme(event.organization.id, event.project.id): order_type = LatestReleaseOrders.SEMVER else: order_type = LatestReleaseOrders.DATE try: environment = Environment.get_for_organization_id( event.project.organization_id, environment_name ) except Environment.DoesNotExist: return False latest_project_release = get_latest_adopted_release_for_env(environment, event) if not latest_project_release: return False release = get_first_last_release_for_event(event, release_age_type, order_type) if not release: return False if age_comparison == AgeComparisonType.NEWER: return is_newer_release(release, latest_project_release, order_type) elif age_comparison == AgeComparisonType.OLDER: return is_newer_release(latest_project_release, release, order_type) return False
LatestAdoptedReleaseConditionHandler
python
Lightning-AI__lightning
tests/tests_pytorch/trainer/test_dataloaders.py
{ "start": 2255, "end": 2550 }
class ____(BoringModel): def test_dataloader(self): return [DataLoader(RandomDataset(32, 64)), DataLoader(RandomDataset(32, 64), batch_size=8)] def test_step(self, batch, batch_idx, dataloader_idx): return super().test_step(batch, batch_idx)
MultiTestDataLoaderBoringModel
python
matplotlib__matplotlib
lib/matplotlib/tests/test_cbook.py
{ "start": 2000, "end": 6336 }
class ____: def setup_method(self): np.random.seed(937) self.nrows = 37 self.ncols = 4 self.data = np.random.lognormal(size=(self.nrows, self.ncols), mean=1.5, sigma=1.75) self.known_keys = sorted([ 'mean', 'med', 'q1', 'q3', 'iqr', 'cilo', 'cihi', 'whislo', 'whishi', 'fliers', 'label' ]) self.std_results = cbook.boxplot_stats(self.data) self.known_nonbootstrapped_res = { 'cihi': 6.8161283264444847, 'cilo': -0.1489815330368689, 'iqr': 13.492709959447094, 'mean': 13.00447442387868, 'med': 3.3335733967038079, 'fliers': np.array([ 92.55467075, 87.03819018, 42.23204914, 39.29390996 ]), 'q1': 1.3597529879465153, 'q3': 14.85246294739361, 'whishi': 27.899688243699629, 'whislo': 0.042143774965502923 } self.known_bootstrapped_ci = { 'cihi': 8.939577523357828, 'cilo': 1.8692703958676578, } self.known_whis3_res = { 'whishi': 42.232049135969874, 'whislo': 0.042143774965502923, 'fliers': np.array([92.55467075, 87.03819018]), } self.known_res_percentiles = { 'whislo': 0.1933685896907924, 'whishi': 42.232049135969874 } self.known_res_range = { 'whislo': 0.042143774965502923, 'whishi': 92.554670752188699 } def test_form_main_list(self): assert isinstance(self.std_results, list) def test_form_each_dict(self): for res in self.std_results: assert isinstance(res, dict) def test_form_dict_keys(self): for res in self.std_results: assert set(res) <= set(self.known_keys) def test_results_baseline(self): res = self.std_results[0] for key, value in self.known_nonbootstrapped_res.items(): assert_array_almost_equal(res[key], value) def test_results_bootstrapped(self): results = cbook.boxplot_stats(self.data, bootstrap=10000) res = results[0] for key, value in self.known_bootstrapped_ci.items(): assert_approx_equal(res[key], value) def test_results_whiskers_float(self): results = cbook.boxplot_stats(self.data, whis=3) res = results[0] for key, value in self.known_whis3_res.items(): assert_array_almost_equal(res[key], value) def test_results_whiskers_range(self): results = cbook.boxplot_stats(self.data, whis=[0, 100]) res = results[0] for key, value in self.known_res_range.items(): assert_array_almost_equal(res[key], value) def test_results_whiskers_percentiles(self): results = cbook.boxplot_stats(self.data, whis=[5, 95]) res = results[0] for key, value in self.known_res_percentiles.items(): assert_array_almost_equal(res[key], value) def test_results_withlabels(self): labels = ['Test1', 2, 'Aardvark', 4] results = cbook.boxplot_stats(self.data, labels=labels) for lab, res in zip(labels, results): assert res['label'] == lab results = cbook.boxplot_stats(self.data) for res in results: assert 'label' not in res def test_label_error(self): labels = [1, 2] with pytest.raises(ValueError): cbook.boxplot_stats(self.data, labels=labels) def test_bad_dims(self): data = np.random.normal(size=(34, 34, 34)) with pytest.raises(ValueError): cbook.boxplot_stats(data) def test_boxplot_stats_autorange_false(self): x = np.zeros(shape=140) x = np.hstack([-25, x, 25]) bstats_false = cbook.boxplot_stats(x, autorange=False) bstats_true = cbook.boxplot_stats(x, autorange=True) assert bstats_false[0]['whislo'] == 0 assert bstats_false[0]['whishi'] == 0 assert_array_almost_equal(bstats_false[0]['fliers'], [-25, 25]) assert bstats_true[0]['whislo'] == -25 assert bstats_true[0]['whishi'] == 25 assert_array_almost_equal(bstats_true[0]['fliers'], [])
Test_boxplot_stats
python
lxml__lxml
src/lxml/tests/common_imports.py
{ "start": 3048, "end": 3638 }
class ____(unittest.TestCase): def tearDown(self): if DEBUG_PROXY_ISSUES: gc.collect() def parse(self, text, parser=None): f = BytesIO(text) if isinstance(text, bytes) else StringIO(text) return etree.parse(f, parser=parser) def _rootstring(self, tree): return etree.tostring(tree.getroot()).replace( b' ', b'').replace(b'\n', b'') try: unittest.TestCase.assertRegex except AttributeError: def assertRegex(self, *args, **kwargs): return self.assertRegex(*args, **kwargs)
HelperTestCase
python
pytorch__pytorch
test/test_autocast.py
{ "start": 7016, "end": 7910 }
class ____(TorchDispatchMode): def __init__(self, weight): super().__init__() self.dtype_cast_counter = 0 self.weight = weight def __torch_dispatch__(self, func, types, args=(), kwargs=None): if ( func is torch.ops.aten._to_copy.default and args[0] is self.weight and kwargs["dtype"] is torch.float16 ): self.dtype_cast_counter += 1 return func(*args, **kwargs) def __enter__(self): self.old_clear_cache = torch.clear_autocast_cache torch.clear_autocast_cache = lambda: None return super().__enter__() def __exit__(self, exc_type, exc_val, exc_tb): torch.clear_autocast_cache = self.old_clear_cache return super().__exit__(exc_type, exc_val, exc_tb) @unittest.skipIf(not torch.cuda.is_available(), "requires cuda")
WeightDTypeCastCounterMode
python
kamyu104__LeetCode-Solutions
Python/number-of-sets-of-k-non-overlapping-line-segments.py
{ "start": 1176, "end": 2026 }
class ____(object): def numberOfSets(self, n, k): """ :type n: int :type k: int :rtype: int """ MOD = 10**9+7 def nCr(n, r): # Time: O(n), Space: O(1) if n-r < r: return nCr(n, n-r) c = 1 for k in xrange(1, r+1): c *= n-k+1 c //= k return c # find k segments with 1+ length and (k+1) spaces with 0+ length s.t. total length is n-1 # => find k segments with 0+ length and (k+1) spaces with 0+ length s.t. total length is n-k-1 # => find the number of combinations of 2k+1 variables with total sum n-k-1 # => H(2k+1, n-k-1) # => C((2k+1) + (n-k-1) - 1, n-k-1) # => C(n+k-1, n-k-1) = C(n+k-1, 2k) return nCr(n+k-1, 2*k) % MOD
Solution2
python
giampaolo__psutil
tests/test_misc.py
{ "start": 15487, "end": 20451 }
class ____(PsutilTestCase): def test_memoize_when_activated(self): class Foo: @memoize_when_activated def foo(self): calls.append(None) f = Foo() calls = [] f.foo() f.foo() assert len(calls) == 2 # activate calls = [] f.foo.cache_activate(f) f.foo() f.foo() assert len(calls) == 1 # deactivate calls = [] f.foo.cache_deactivate(f) f.foo() f.foo() assert len(calls) == 2 def test_parse_environ_block(self): def k(s): return s.upper() if WINDOWS else s assert parse_environ_block("a=1\0") == {k("a"): "1"} assert parse_environ_block("a=1\0b=2\0\0") == { k("a"): "1", k("b"): "2", } assert parse_environ_block("a=1\0b=\0\0") == {k("a"): "1", k("b"): ""} # ignore everything after \0\0 assert parse_environ_block("a=1\0b=2\0\0c=3\0") == { k("a"): "1", k("b"): "2", } # ignore everything that is not an assignment assert parse_environ_block("xxx\0a=1\0") == {k("a"): "1"} assert parse_environ_block("a=1\0=b=2\0") == {k("a"): "1"} # do not fail if the block is incomplete assert parse_environ_block("a=1\0b=2") == {k("a"): "1"} def test_supports_ipv6(self): if supports_ipv6(): with mock.patch('psutil._common.socket') as s: s.has_ipv6 = False assert not supports_ipv6() with mock.patch( 'psutil._common.socket.socket', side_effect=OSError ) as s: assert not supports_ipv6() assert s.called with mock.patch( 'psutil._common.socket.socket', side_effect=socket.gaierror ) as s: assert not supports_ipv6() assert s.called with mock.patch( 'psutil._common.socket.socket.bind', side_effect=socket.gaierror, ) as s: assert not supports_ipv6() assert s.called else: with pytest.raises(OSError): sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) try: sock.bind(("::1", 0)) finally: sock.close() def test_isfile_strict(self): this_file = os.path.abspath(__file__) assert isfile_strict(this_file) assert not isfile_strict(os.path.dirname(this_file)) with mock.patch('psutil._common.os.stat', side_effect=PermissionError): with pytest.raises(OSError): isfile_strict(this_file) with mock.patch( 'psutil._common.os.stat', side_effect=FileNotFoundError ): assert not isfile_strict(this_file) with mock.patch('psutil._common.stat.S_ISREG', return_value=False): assert not isfile_strict(this_file) def test_debug(self): with mock.patch.object(psutil._common, "PSUTIL_DEBUG", True): with contextlib.redirect_stderr(io.StringIO()) as f: debug("hello") sys.stderr.flush() msg = f.getvalue() assert msg.startswith("psutil-debug"), msg assert "hello" in msg assert __file__.replace('.pyc', '.py') in msg # supposed to use repr(exc) with mock.patch.object(psutil._common, "PSUTIL_DEBUG", True): with contextlib.redirect_stderr(io.StringIO()) as f: debug(ValueError("this is an error")) msg = f.getvalue() assert "ignoring ValueError" in msg assert "'this is an error'" in msg # supposed to use str(exc), because of extra info about file name with mock.patch.object(psutil._common, "PSUTIL_DEBUG", True): with contextlib.redirect_stderr(io.StringIO()) as f: exc = OSError(2, "no such file") exc.filename = "/foo" debug(exc) msg = f.getvalue() assert "no such file" in msg assert "/foo" in msg def test_cat_bcat(self): testfn = self.get_testfn() with open(testfn, "w") as f: f.write("foo") assert cat(testfn) == "foo" assert bcat(testfn) == b"foo" with pytest.raises(FileNotFoundError): cat(testfn + '-invalid') with pytest.raises(FileNotFoundError): bcat(testfn + '-invalid') assert cat(testfn + '-invalid', fallback="bar") == "bar" assert bcat(testfn + '-invalid', fallback="bar") == "bar" # =================================================================== # --- Tests for wrap_numbers() function. # =================================================================== nt = collections.namedtuple('foo', 'a b c')
TestCommonModule
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 682369, "end": 682694 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") node = sgqlc.types.Field("UserContentEdit", graphql_name="node")
UserContentEditEdge
python
keras-team__keras
integration_tests/dataset_tests/cifar10_test.py
{ "start": 91, "end": 1195 }
class ____(testing.TestCase): def test_x_train_shape(self): (x_train, _), _ = cifar10.load_data() self.assertEqual(x_train.shape, (50000, 32, 32, 3)) def test_y_train_shape(self): (_, y_train), _ = cifar10.load_data() self.assertEqual(y_train.shape, (50000, 1)) def test_x_test_shape(self): _, (x_test, _) = cifar10.load_data() self.assertEqual(x_test.shape, (10000, 32, 32, 3)) def test_y_test_shape(self): _, (_, y_test) = cifar10.load_data() self.assertEqual(y_test.shape, (10000, 1)) def test_x_train_dtype(self): (x_train, _), _ = cifar10.load_data() self.assertEqual(x_train.dtype, np.uint8) def test_y_train_dtype(self): (_, y_train), _ = cifar10.load_data() self.assertEqual(y_train.dtype, np.uint8) def test_x_test_dtype(self): _, (x_test, _) = cifar10.load_data() self.assertEqual(x_test.dtype, np.uint8) def test_y_test_dtype(self): _, (_, y_test) = cifar10.load_data() self.assertEqual(y_test.dtype, np.uint8)
Cifar10LoadDataTest
python
getsentry__sentry
tests/sentry/preprod/vcs/status_checks/size/test_templates.py
{ "start": 9619, "end": 13684 }
class ____(StatusCheckTestBase): """Tests for formatting artifacts in error/failure states.""" def test_failed_state_formatting(self): """Test formatting for failed state.""" artifact = PreprodArtifact.objects.create( project=self.project, state=PreprodArtifact.ArtifactState.FAILED, app_id="com.example.app", build_version="1.0.0", build_number=1, error_message="Build timeout", ) title, subtitle, summary = format_status_check_messages( [artifact], {}, StatusCheckStatus.FAILURE ) assert title == "Size Analysis" assert subtitle == "1 app errored" assert "Build timeout" in summary assert "com.example.app" in summary assert "1.0.0 (1)" in summary assert "Error" in summary # Column header def test_error_message_handling(self): """Test error message handling including None case.""" test_cases = [ ("Custom error message", "Custom error message"), (None, "Unknown error"), ("", "Unknown error"), ] for input_error, expected_error in test_cases: with self.subTest(input_error=input_error): artifact = PreprodArtifact.objects.create( project=self.project, state=PreprodArtifact.ArtifactState.FAILED, app_id="com.example.app", error_message=input_error, ) title, subtitle, summary = format_status_check_messages( [artifact], {}, StatusCheckStatus.FAILURE ) assert expected_error in summary def test_multiple_artifacts_mixed_states(self): """Test formatting for mixed states (some analyzed, some processing, some failed).""" artifacts = [] size_metrics_map = {} processed_artifact = PreprodArtifact.objects.create( project=self.project, state=PreprodArtifact.ArtifactState.PROCESSED, app_id="com.example.processed", build_version="1.0.0", build_number=1, ) artifacts.append(processed_artifact) size_metrics = PreprodArtifactSizeMetrics.objects.create( preprod_artifact=processed_artifact, metrics_artifact_type=PreprodArtifactSizeMetrics.MetricsArtifactType.MAIN_ARTIFACT, state=PreprodArtifactSizeMetrics.SizeAnalysisState.COMPLETED, min_download_size=1024 * 1024, max_download_size=1024 * 1024, min_install_size=2 * 1024 * 1024, max_install_size=2 * 1024 * 1024, ) size_metrics_map[processed_artifact.id] = [size_metrics] uploading_artifact = PreprodArtifact.objects.create( project=self.project, state=PreprodArtifact.ArtifactState.UPLOADING, app_id="com.example.uploading", build_version="1.0.0", build_number=2, ) artifacts.append(uploading_artifact) failed_artifact = PreprodArtifact.objects.create( project=self.project, state=PreprodArtifact.ArtifactState.FAILED, app_id="com.example.failed", build_version="1.0.0", build_number=3, error_message="Upload timeout", ) artifacts.append(failed_artifact) title, subtitle, summary = format_status_check_messages( artifacts, size_metrics_map, StatusCheckStatus.FAILURE ) assert title == "Size Analysis" assert subtitle == "1 app analyzed, 1 app processing, 1 app errored" assert "Processing..." in summary # Non-failed artifacts show as processing assert "Upload timeout" in summary # Failed artifact error assert "com.example.processed" in summary assert "com.example.uploading" in summary assert "com.example.failed" in summary @region_silo_test
ErrorStateFormattingTest
python
lazyprogrammer__machine_learning_examples
unsupervised_class3/dcgan_tf.py
{ "start": 2129, "end": 3672 }
class ____: def __init__(self, name, mi, mo, output_shape, apply_batch_norm, filtersz=5, stride=2, f=tf.nn.relu): # mi = input feature map size # mo = output feature map size # NOTE!!! shape is specified in the OPPOSITE way from regular conv # self.W = tf.Variable(0.02*tf.random_normal(shape=(filtersz, filtersz, mo, mi))) # self.b = tf.Variable(np.zeros(mo, dtype=np.float32)) self.W = tf.get_variable( "W_%s" % name, shape=(filtersz, filtersz, mo, mi), # initializer=tf.contrib.layers.xavier_initializer(), initializer=tf.random_normal_initializer(stddev=0.02), ) self.b = tf.get_variable( "b_%s" % name, shape=(mo,), initializer=tf.zeros_initializer(), ) self.f = f self.stride = stride self.name = name self.output_shape = output_shape self.apply_batch_norm = apply_batch_norm self.params = [self.W, self.b] def forward(self, X, reuse, is_training): conv_out = tf.nn.conv2d_transpose( value=X, filter=self.W, output_shape=self.output_shape, strides=[1, self.stride, self.stride, 1], ) conv_out = tf.nn.bias_add(conv_out, self.b) # apply batch normalization if self.apply_batch_norm: conv_out = tf.contrib.layers.batch_norm( conv_out, decay=0.9, updates_collections=None, epsilon=1e-5, scale=True, is_training=is_training, reuse=reuse, scope=self.name, ) return self.f(conv_out)
FractionallyStridedConvLayer