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 | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_axis43.py | {
"start": 315,
"end": 1396
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_axis43.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "column"})
chart.axis_ids = [61296640, 61298560]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
chart.add_series({"values": "=Sheet1!$A$1:$A$5"})
chart.add_series({"values": "=Sheet1!$B$1:$B$5"})
chart.add_series({"values": "=Sheet1!$C$1:$C$5"})
chart.set_x_axis({"label_align": "left"})
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | tensorflow__tensorflow | tensorflow/python/framework/errors_impl.py | {
"start": 9389,
"end": 9942
} | class ____(OpError):
"""Unknown error.
An example of where this error may be returned is if a Status value
received from another address space belongs to an error-space that
is not known to this address space. Also, errors raised by APIs that
do not return enough error information may be converted to this
error.
"""
def __init__(self, node_def, op, message, *args):
"""Creates an `UnknownError`."""
super(UnknownError, self).__init__(node_def, op, message, UNKNOWN, *args)
@tf_export("errors.InvalidArgumentError")
| UnknownError |
python | getsentry__sentry | src/sentry/snuba/sessions_v2.py | {
"start": 14580,
"end": 19163
} | class ____(InvalidParams):
"""
An exception that is raised when parsing orderBy, to indicate that this is only an exception
in the case where we don't run a preflight query on an accepted pre-flight query field
"""
...
def get_now():
"""Wrapper function to make it mockable in unit tests"""
return datetime.now(tz=timezone.utc)
def get_constrained_date_range(
params,
allowed_resolution: AllowedResolution = AllowedResolution.one_hour,
max_points=MAX_POINTS,
restrict_date_range=True,
) -> tuple[datetime, datetime, int]:
interval_td = parse_stats_period(params.get("interval", "1h"))
interval = int(3600 if interval_td is None else interval_td.total_seconds())
smallest_interval, interval_str = allowed_resolution.value
if interval % smallest_interval != 0 or interval < smallest_interval:
raise InvalidParams(
f"The interval has to be a multiple of the minimum interval of {interval_str}."
)
if interval > ONE_DAY:
raise InvalidParams("The interval has to be less than one day.")
if ONE_DAY % interval != 0:
raise InvalidParams("The interval should divide one day without a remainder.")
start, end = get_date_range_from_params(params)
now = get_now()
if start > now:
start = now
adjusted_start, adjusted_end, _num_intervals = to_intervals(start, end, interval)
date_range = adjusted_end - adjusted_start
if date_range.total_seconds() / interval > max_points:
raise InvalidParams(
"Your interval and date range would create too many results. "
"Use a larger interval, or a smaller date range."
)
return adjusted_start, adjusted_end, interval
TS_COL = "bucketed_started"
def massage_sessions_result(
query, result_totals, result_timeseries, ts_col=TS_COL
) -> dict[str, list[Any]]:
"""
Post-processes the query result.
Given the `query` as defined by [`QueryDefinition`] and its totals and
timeseries results from snuba, groups and transforms the result into the
expected format.
For example:
```json
{
"intervals": [
"2020-12-16T00:00:00Z",
"2020-12-16T12:00:00Z",
"2020-12-17T00:00:00Z"
],
"groups": [
{
"by": { "release": "99b8edc5a3bb49d01d16426d7bb9c511ec41f81e" },
"series": { "sum(session)": [0, 1, 0] },
"totals": { "sum(session)": 1 }
},
{
"by": { "release": "test-example-release" },
"series": { "sum(session)": [0, 10, 20] },
"totals": { "sum(session)": 30 }
}
]
}
```
"""
timestamps = get_timestamps(query)
total_groups = _split_rows_groupby(result_totals, query.groupby)
timeseries_groups = _split_rows_groupby(result_timeseries, query.groupby)
def make_timeseries(rows, group):
for row in rows:
row[ts_col] = row[ts_col][:19] + "Z"
rows.sort(key=lambda row: row[ts_col])
fields: list[tuple[str, _Field, list[float | None]]]
fields = [(name, field, []) for name, field in query.fields.items()]
group_index = 0
while group_index < len(rows):
row = rows[group_index]
if row[ts_col] < timestamps[0]:
group_index += 1
else:
break
for ts in timestamps:
row = rows[group_index] if group_index < len(rows) else None
if row is not None and row[ts_col] == ts:
group_index += 1
else:
row = None
for name, field, series in fields:
series.append(field.extract_from_row(row, group))
return {name: series for (name, field, series) in fields}
def make_totals(totals, group):
return {
name: field.extract_from_row(totals[0], group) for name, field in query.fields.items()
}
groups = []
keys = set(total_groups.keys()) | set(timeseries_groups.keys())
for key in keys:
by = dict(key)
group = {
"by": by,
"totals": make_totals(total_groups.get(key, [None]), by),
}
if result_timeseries is not None:
group["series"] = make_timeseries(timeseries_groups.get(key, []), by)
groups.append(group)
return {
"start": isoformat_z(query.start),
"end": isoformat_z(query.end),
"query": query.query,
"intervals": timestamps,
"groups": groups,
}
| NonPreflightOrderByException |
python | sqlalchemy__sqlalchemy | test/ext/test_associationproxy.py | {
"start": 6200,
"end": 15263
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"Parent",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("name", String(128)),
)
Table(
"Children",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("parent_id", Integer, ForeignKey("Parent.id")),
Column("foo", String(128)),
Column("name", String(128)),
)
@classmethod
def setup_mappers(cls):
collection_class = cls.collection_class
class Parent(cls.Basic):
children = association_proxy("_children", "name")
def __init__(self, name):
self.name = name
class Child(cls.Basic):
if collection_class and issubclass(collection_class, dict):
def __init__(self, foo, name):
self.foo = foo
self.name = name
else:
def __init__(self, name):
self.name = name
parents_table, children_table = cls.tables("Parent", "Children")
cls.mapper_registry.map_imperatively(
Parent,
parents_table,
properties={
"_children": relationship(
Child,
lazy="joined",
backref="parent",
collection_class=collection_class,
)
},
)
cls.mapper_registry.map_imperatively(Child, children_table)
def test_abc(self):
Parent = self.classes.Parent
p1 = Parent("x")
collection_class = self.collection_class or list
for abc_ in (abc.Set, abc.MutableMapping, abc.MutableSequence):
if issubclass(collection_class, abc_):
break
else:
abc_ = None
if abc_:
p1 = Parent("x")
assert isinstance(p1.children, abc_)
def roundtrip(self, obj):
if obj not in self.session:
self.session.add(obj)
self.session.flush()
id_, type_ = obj.id, type(obj)
self.session.expunge_all()
return self.session.get(type_, id_)
def _test_sequence_ops(self):
Parent, Child = self.classes("Parent", "Child")
self.session = fixture_session()
p1 = Parent("P1")
def assert_index(expected, value, *args):
"""Assert index of child value is equal to expected.
If expected is None, assert that index raises ValueError.
"""
try:
index = p1.children.index(value, *args)
except ValueError:
self.assert_(expected is None)
else:
self.assert_(expected is not None)
self.assert_(index == expected)
self.assert_(not p1._children)
self.assert_(not p1.children)
ch = Child("regular")
p1._children.append(ch)
self.assert_(ch in p1._children)
self.assert_(len(p1._children) == 1)
self.assert_(p1.children)
self.assert_(len(p1.children) == 1)
self.assert_(ch not in p1.children)
self.assert_("regular" in p1.children)
assert_index(0, "regular")
assert_index(None, "regular", 1)
p1.children.append("proxied")
self.assert_("proxied" in p1.children)
self.assert_("proxied" not in p1._children)
self.assert_(len(p1.children) == 2)
self.assert_(len(p1._children) == 2)
self.assert_(p1._children[0].name == "regular")
self.assert_(p1._children[1].name == "proxied")
assert_index(0, "regular")
assert_index(1, "proxied")
assert_index(1, "proxied", 1)
assert_index(None, "proxied", 0, 1)
del p1._children[1]
self.assert_(len(p1._children) == 1)
self.assert_(len(p1.children) == 1)
self.assert_(p1._children[0] == ch)
assert_index(None, "proxied")
del p1.children[0]
self.assert_(len(p1._children) == 0)
self.assert_(len(p1.children) == 0)
assert_index(None, "regular")
p1.children = ["a", "b", "c"]
self.assert_(len(p1._children) == 3)
self.assert_(len(p1.children) == 3)
assert_index(0, "a")
assert_index(1, "b")
assert_index(2, "c")
del ch
p1 = self.roundtrip(p1)
self.assert_(len(p1._children) == 3)
self.assert_(len(p1.children) == 3)
assert_index(0, "a")
assert_index(1, "b")
assert_index(2, "c")
popped = p1.children.pop()
self.assert_(len(p1.children) == 2)
self.assert_(popped not in p1.children)
assert_index(None, popped)
p1 = self.roundtrip(p1)
self.assert_(len(p1.children) == 2)
self.assert_(popped not in p1.children)
assert_index(None, popped)
p1.children[1] = "changed-in-place"
self.assert_(p1.children[1] == "changed-in-place")
assert_index(1, "changed-in-place")
assert_index(None, "b")
inplace_id = p1._children[1].id
p1 = self.roundtrip(p1)
self.assert_(p1.children[1] == "changed-in-place")
assert p1._children[1].id == inplace_id
p1.children.append("changed-in-place")
self.assert_(p1.children.count("changed-in-place") == 2)
assert_index(1, "changed-in-place")
p1.children.remove("changed-in-place")
self.assert_(p1.children.count("changed-in-place") == 1)
assert_index(1, "changed-in-place")
p1 = self.roundtrip(p1)
self.assert_(p1.children.count("changed-in-place") == 1)
assert_index(1, "changed-in-place")
p1._children = []
self.assert_(len(p1.children) == 0)
assert_index(None, "changed-in-place")
after = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
p1.children = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
self.assert_(len(p1.children) == 10)
self.assert_([c.name for c in p1._children] == after)
for i, val in enumerate(after):
assert_index(i, val)
p1.children[2:6] = ["x"] * 4
after = ["a", "b", "x", "x", "x", "x", "g", "h", "i", "j"]
self.assert_(p1.children == after)
self.assert_([c.name for c in p1._children] == after)
assert_index(2, "x")
assert_index(3, "x", 3)
assert_index(None, "x", 6)
p1.children[2:6] = ["y"]
after = ["a", "b", "y", "g", "h", "i", "j"]
self.assert_(p1.children == after)
self.assert_([c.name for c in p1._children] == after)
assert_index(2, "y")
assert_index(None, "y", 3)
p1.children[2:3] = ["z"] * 4
after = ["a", "b", "z", "z", "z", "z", "g", "h", "i", "j"]
self.assert_(p1.children == after)
self.assert_([c.name for c in p1._children] == after)
p1.children[2::2] = ["O"] * 4
after = ["a", "b", "O", "z", "O", "z", "O", "h", "O", "j"]
self.assert_(p1.children == after)
self.assert_([c.name for c in p1._children] == after)
assert_raises(TypeError, set, [p1.children])
p1.children *= 0
after = []
self.assert_(p1.children == after)
self.assert_([c.name for c in p1._children] == after)
p1.children += ["a", "b"]
after = ["a", "b"]
self.assert_(p1.children == after)
self.assert_([c.name for c in p1._children] == after)
p1.children[:] = ["d", "e"]
after = ["d", "e"]
self.assert_(p1.children == after)
self.assert_([c.name for c in p1._children] == after)
p1.children[:] = ["a", "b"]
p1.children += ["c"]
after = ["a", "b", "c"]
self.assert_(p1.children == after)
self.assert_([c.name for c in p1._children] == after)
p1.children *= 1
after = ["a", "b", "c"]
self.assert_(p1.children == after)
self.assert_([c.name for c in p1._children] == after)
p1.children *= 2
after = ["a", "b", "c", "a", "b", "c"]
self.assert_(p1.children == after)
self.assert_([c.name for c in p1._children] == after)
p1.children = ["a"]
after = ["a"]
self.assert_(p1.children == after)
self.assert_([c.name for c in p1._children] == after)
self.assert_((p1.children * 2) == ["a", "a"])
self.assert_((2 * p1.children) == ["a", "a"])
self.assert_((p1.children * 0) == [])
self.assert_((0 * p1.children) == [])
self.assert_((p1.children + ["b"]) == ["a", "b"])
self.assert_((["b"] + p1.children) == ["b", "a"])
try:
p1.children + 123
assert False
except TypeError:
assert True
| _CollectionOperations |
python | allegroai__clearml | clearml/backend_api/services/v2_20/events.py | {
"start": 50407,
"end": 50655
} | class ____(BatchRequest):
"""
Adds a batch of events in a single call (json-lines format, stream-friendly)
"""
_service = "events"
_action = "add_batch"
_version = "2.20"
_batched_request_cls = AddRequest
| AddBatchRequest |
python | jazzband__django-model-utils | tests/fields.py | {
"start": 576,
"end": 1026
} | class ____(models.TextField):
def to_python(self, value: object) -> Any:
return mutable_from_db(value)
def from_db_value(self, value: object, expression: object, connection: BaseDatabaseWrapper) -> Any:
return mutable_from_db(value)
def get_db_prep_save(self, value: object, connection: BaseDatabaseWrapper) -> str:
value = super().get_db_prep_save(value, connection)
return mutable_to_db(value)
| MutableField |
python | falconry__falcon | tests/asgi/test_hello_asgi.py | {
"start": 4546,
"end": 4624
} | class ____:
async def on_get(self, req, resp):
pass
| NoStatusResource |
python | google__pytype | pytype/overlays/metaclass.py | {
"start": 1475,
"end": 2025
} | class ____(abstract.PyTDFunction):
"""Implements the add_metaclass decorator."""
@classmethod
def make(cls, ctx, module):
return super().make("add_metaclass", ctx, module)
def call(self, node, func, args, alias_map=None):
"""Adds a metaclass."""
del func, alias_map # unused
self.match_args(node, args)
meta = abstract_utils.get_atomic_value(
args.posargs[0], default=self.ctx.convert.unsolvable
)
return node, AddMetaclassInstance(meta, self.ctx, self.module).to_variable(
node
)
| AddMetaclass |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/vertex_ai/test_generative_model.py | {
"start": 8296,
"end": 14763
} | class ____:
def dummy_get_credentials(self):
pass
def setup_method(self):
with mock.patch(
BASE_STRING.format("GoogleBaseHook.__init__"), new=mock_base_gcp_hook_default_project_id
):
self.hook = GenerativeModelHook(gcp_conn_id=TEST_GCP_CONN_ID)
self.hook.get_credentials = self.dummy_get_credentials
@mock.patch(GENERATIVE_MODEL_STRING.format("GenerativeModelHook.get_text_embedding_model"))
def test_text_embedding_model_get_embeddings(self, mock_model) -> None:
with pytest.warns(AirflowProviderDeprecationWarning):
self.hook.text_embedding_model_get_embeddings(
project_id=GCP_PROJECT,
location=GCP_LOCATION,
prompt=TEST_PROMPT,
pretrained_model=TEST_TEXT_EMBEDDING_MODEL,
)
mock_model.assert_called_once_with(TEST_TEXT_EMBEDDING_MODEL)
mock_model.return_value.get_embeddings.assert_called_once_with([TEST_PROMPT])
@mock.patch(GENERATIVE_MODEL_STRING.format("GenerativeModelHook.get_generative_model"))
def test_generative_model_generate_content(self, mock_model) -> None:
with pytest.warns(AirflowProviderDeprecationWarning):
self.hook.generative_model_generate_content(
project_id=GCP_PROJECT,
contents=TEST_CONTENTS,
location=GCP_LOCATION,
tools=TEST_TOOLS,
generation_config=TEST_GENERATION_CONFIG,
safety_settings=TEST_SAFETY_SETTINGS,
pretrained_model=TEST_MULTIMODAL_PRETRAINED_MODEL,
)
mock_model.assert_called_once_with(
pretrained_model=TEST_MULTIMODAL_PRETRAINED_MODEL,
system_instruction=None,
)
mock_model.return_value.generate_content.assert_called_once_with(
contents=TEST_CONTENTS,
tools=TEST_TOOLS,
generation_config=TEST_GENERATION_CONFIG,
safety_settings=TEST_SAFETY_SETTINGS,
)
@mock.patch("vertexai.preview.tuning.sft.train")
def test_supervised_fine_tuning_train(self, mock_sft_train) -> None:
with pytest.warns(AirflowProviderDeprecationWarning):
self.hook.supervised_fine_tuning_train(
project_id=GCP_PROJECT,
location=GCP_LOCATION,
source_model=SOURCE_MODEL,
train_dataset=TRAIN_DATASET,
)
mock_sft_train.assert_called_once_with(
source_model=SOURCE_MODEL,
train_dataset=TRAIN_DATASET,
validation_dataset=None,
epochs=None,
adapter_size=None,
learning_rate_multiplier=None,
tuned_model_display_name=None,
)
@mock.patch(GENERATIVE_MODEL_STRING.format("GenerativeModelHook.get_generative_model"))
def test_count_tokens(self, mock_model) -> None:
with pytest.warns(AirflowProviderDeprecationWarning):
self.hook.count_tokens(
project_id=GCP_PROJECT,
contents=TEST_CONTENTS,
location=GCP_LOCATION,
pretrained_model=TEST_MULTIMODAL_PRETRAINED_MODEL,
)
mock_model.assert_called_once_with(
pretrained_model=TEST_MULTIMODAL_PRETRAINED_MODEL,
)
mock_model.return_value.count_tokens.assert_called_once_with(
contents=TEST_CONTENTS,
)
@mock.patch(GENERATIVE_MODEL_STRING.format("GenerativeModelHook.get_generative_model"))
@mock.patch(GENERATIVE_MODEL_STRING.format("GenerativeModelHook.get_eval_task"))
def test_run_evaluation(self, mock_eval_task, mock_model) -> None:
self.hook.run_evaluation(
project_id=GCP_PROJECT,
location=GCP_LOCATION,
pretrained_model=TEST_MULTIMODAL_PRETRAINED_MODEL,
eval_dataset=TEST_EVAL_DATASET,
metrics=TEST_METRICS,
experiment_name=TEST_EXPERIMENT_NAME,
experiment_run_name=TEST_EXPERIMENT_RUN_NAME,
prompt_template=TEST_PROMPT_TEMPLATE,
)
mock_model.assert_called_once_with(
pretrained_model=TEST_MULTIMODAL_PRETRAINED_MODEL,
system_instruction=None,
generation_config=None,
safety_settings=None,
tools=None,
)
mock_eval_task.assert_called_once_with(
dataset=TEST_EVAL_DATASET,
metrics=TEST_METRICS,
experiment=TEST_EXPERIMENT_NAME,
)
mock_eval_task.return_value.evaluate.assert_called_once_with(
model=mock_model.return_value,
prompt_template=TEST_PROMPT_TEMPLATE,
experiment_run_name=TEST_EXPERIMENT_RUN_NAME,
)
@mock.patch("vertexai.preview.caching.CachedContent.create")
def test_create_cached_content(self, mock_cached_content_create) -> None:
with pytest.warns(AirflowProviderDeprecationWarning):
self.hook.create_cached_content(
project_id=GCP_PROJECT,
location=GCP_LOCATION,
model_name=TEST_CACHED_MODEL,
system_instruction=TEST_CACHED_SYSTEM_INSTRUCTION,
contents=TEST_CACHED_CONTENTS,
ttl_hours=TEST_CACHED_TTL,
display_name=TEST_CACHED_DISPLAY_NAME,
)
mock_cached_content_create.assert_called_once_with(
model_name=TEST_CACHED_MODEL,
system_instruction=TEST_CACHED_SYSTEM_INSTRUCTION,
contents=TEST_CACHED_CONTENTS,
ttl=timedelta(hours=TEST_CACHED_TTL),
display_name=TEST_CACHED_DISPLAY_NAME,
)
@mock.patch(GENERATIVE_MODEL_STRING.format("GenerativeModelHook.get_cached_context_model"))
def test_generate_from_cached_content(self, mock_cached_context_model) -> None:
with pytest.warns(AirflowProviderDeprecationWarning):
self.hook.generate_from_cached_content(
project_id=GCP_PROJECT,
location=GCP_LOCATION,
cached_content_name=TEST_CACHED_CONTENT_NAME,
contents=TEST_CACHED_CONTENT_PROMPT,
)
mock_cached_context_model.return_value.generate_content.assert_called_once_with(
contents=TEST_CACHED_CONTENT_PROMPT,
generation_config=None,
safety_settings=None,
)
| TestGenerativeModelWithDefaultProjectIdHook |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-scrapegraph/tests/test_integration.py | {
"start": 8587,
"end": 12023
} | class ____:
"""Test parameter validation and handling."""
@pytest.fixture
def mock_tool_spec(self):
"""Create a mocked tool spec for parameter testing."""
with patch("llama_index.tools.scrapegraph.base.Client") as mock_client_class:
mock_client = Mock()
mock_client_class.from_env.return_value = mock_client
tool_spec = ScrapegraphToolSpec()
tool_spec.client = mock_client
return tool_spec, mock_client
def test_url_parameter_validation(self, mock_tool_spec):
"""Test that URL parameters are handled correctly."""
tool_spec, mock_client = mock_tool_spec
# Test various URL formats
test_urls = [
"https://example.com",
"http://example.com",
"https://example.com/path",
"https://example.com/path?param=value",
"https://subdomain.example.com",
]
mock_client.scrape.return_value = {"html": "test"}
for url in test_urls:
mock_client.scrape.reset_mock()
tool_spec.scrapegraph_scrape(url=url)
mock_client.scrape.assert_called_once_with(
website_url=url, render_heavy_js=False
)
def test_headers_parameter_handling(self, mock_tool_spec):
"""Test custom headers parameter handling."""
tool_spec, mock_client = mock_tool_spec
headers = {
"User-Agent": "Test Agent",
"Accept": "text/html",
"Authorization": "Bearer token",
"Custom-Header": "custom-value",
}
mock_client.scrape.return_value = {"html": "test"}
tool_spec.scrapegraph_scrape(url="https://example.com", headers=headers)
mock_client.scrape.assert_called_once_with(
website_url="https://example.com", render_heavy_js=False, headers=headers
)
def test_boolean_parameter_handling(self, mock_tool_spec):
"""Test boolean parameter handling."""
tool_spec, mock_client = mock_tool_spec
mock_client.scrape.return_value = {"html": "test"}
# Test with render_heavy_js=True
tool_spec.scrapegraph_scrape(url="https://example.com", render_heavy_js=True)
mock_client.scrape.assert_called_with(
website_url="https://example.com", render_heavy_js=True
)
# Test with render_heavy_js=False
mock_client.scrape.reset_mock()
tool_spec.scrapegraph_scrape(url="https://example.com", render_heavy_js=False)
mock_client.scrape.assert_called_with(
website_url="https://example.com", render_heavy_js=False
)
def test_kwargs_parameter_passing(self, mock_tool_spec):
"""Test that kwargs are passed through correctly."""
tool_spec, mock_client = mock_tool_spec
mock_client.smartscraper.return_value = {"result": "test"}
# Test kwargs with SmartScraper
tool_spec.scrapegraph_smartscraper(
prompt="test",
url="https://example.com",
timeout=30,
retries=3,
custom_param="value",
)
mock_client.smartscraper.assert_called_once_with(
website_url="https://example.com",
user_prompt="test",
output_schema=None,
timeout=30,
retries=3,
custom_param="value",
)
| TestParameterValidation |
python | matplotlib__matplotlib | lib/matplotlib/transforms.py | {
"start": 77453,
"end": 79963
} | class ____(_BlendedMixin, Affine2DBase):
"""
A "blended" transform uses one transform for the *x*-direction, and
another transform for the *y*-direction.
This version is an optimization for the case where both child
transforms are of type `Affine2DBase`.
"""
is_separable = True
def __init__(self, x_transform, y_transform, **kwargs):
"""
Create a new "blended" transform using *x_transform* to transform the
*x*-axis and *y_transform* to transform the *y*-axis.
Both *x_transform* and *y_transform* must be 2D affine transforms.
You will generally not call this constructor directly but use the
`blended_transform_factory` function instead, which can determine
automatically which kind of blended transform to create.
"""
is_affine = x_transform.is_affine and y_transform.is_affine
is_separable = x_transform.is_separable and y_transform.is_separable
is_correct = is_affine and is_separable
if not is_correct:
raise ValueError("Both *x_transform* and *y_transform* must be 2D "
"affine transforms")
Transform.__init__(self, **kwargs)
self._x = x_transform
self._y = y_transform
self.set_children(x_transform, y_transform)
Affine2DBase.__init__(self)
self._mtx = None
def get_matrix(self):
# docstring inherited
if self._invalid:
if self._x == self._y:
self._mtx = self._x.get_matrix()
else:
x_mtx = self._x.get_matrix()
y_mtx = self._y.get_matrix()
# We already know the transforms are separable, so we can skip
# setting b and c to zero.
self._mtx = np.array([x_mtx[0], y_mtx[1], [0.0, 0.0, 1.0]])
self._inverted = None
self._invalid = 0
return self._mtx
def blended_transform_factory(x_transform, y_transform):
"""
Create a new "blended" transform using *x_transform* to transform
the *x*-axis and *y_transform* to transform the *y*-axis.
A faster version of the blended transform is returned for the case
where both child transforms are affine.
"""
if (isinstance(x_transform, Affine2DBase) and
isinstance(y_transform, Affine2DBase)):
return BlendedAffine2D(x_transform, y_transform)
return BlendedGenericTransform(x_transform, y_transform)
| BlendedAffine2D |
python | huggingface__transformers | src/transformers/models/luke/modeling_luke.py | {
"start": 1389,
"end": 2636
} | class ____(BaseModelOutputWithPooling):
r"""
pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`):
Last layer hidden-state of the first token of the sequence (classification token) further processed by a
Linear layer and a Tanh activation function.
entity_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, entity_length, hidden_size)`):
Sequence of entity hidden-states at the output of the last layer of the model.
entity_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
shape `(batch_size, entity_length, hidden_size)`. Entity hidden-states of the model at the output of each
layer plus the initial entity embedding outputs.
"""
entity_last_hidden_state: Optional[torch.FloatTensor] = None
entity_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
@dataclass
@auto_docstring(
custom_intro="""
Base class for model's outputs, with potential hidden states and attentions.
"""
)
| BaseLukeModelOutputWithPooling |
python | prabhupant__python-ds | data_structures/linked_list/merge_list_of_linked_lists.py | {
"start": 0,
"end": 754
} | class ____:
def __init__(self, x):
self.val = x
self.next = None
def merge_two_lists(l1, l2):
if not l1 and not l2:
return
elif not l2:
return l1
elif not l1:
return l2
if (l1.val < l2.val):
l1.next = merge_two_lists(l1.next, l2)
return l1
l2.next = merge_two_lists(l1, l2.next)
return l2
def merge_k_lists(lists):
length = len(lists)
if length == 0:
return;
elif length == 1:
return lists[0]
elif length == 2:
return merge_two_lists(lists[0], lists[1])
mid = length // 2
left_half = lists[:mid]
right_half = lists[mid:]
return merge_two_lists(merge_k_lists(left_half), merge_k_lists(right_half))
| Node |
python | streamlit__streamlit | lib/tests/streamlit/file_uploader_utils_test.py | {
"start": 1007,
"end": 1918
} | class ____(unittest.TestCase):
@parameterized.expand(
[
("png", [".png"]),
(["png", ".svg", "foo"], [".png", ".svg", ".foo"]),
(["jpeg"], [".jpeg", ".jpg"]),
(["png", ".jpg"], [".png", ".jpg", ".jpeg"]),
([".JpG"], [".jpg", ".jpeg"]),
]
)
def test_file_type(self, file_type: str | Sequence[str], expected: Sequence[str]):
"""Test that it can be called using string(s) for type parameter."""
normalized = normalize_upload_file_type(file_type=file_type)
assert normalized == expected
def is_filename_valid(filename: str, allowed_types: Sequence[str]) -> bool:
"""Return True if the filename passes validation, False otherwise."""
try:
enforce_filename_restriction(filename, allowed_types)
return True
except StreamlitAPIException:
return False
| FileUploaderUtilsTest |
python | faif__python-patterns | patterns/behavioral/chain_of_responsibility.py | {
"start": 2010,
"end": 2423
} | class ____(Handler):
"""... With helper methods."""
def check_range(self, request: int) -> Optional[bool]:
start, end = self.get_interval_from_db()
if start <= request < end:
print(f"request {request} handled in handler 2")
return True
return None
@staticmethod
def get_interval_from_db() -> Tuple[int, int]:
return (20, 30)
| ConcreteHandler2 |
python | google__jax | tests/multiprocess/tpu_device_test.py | {
"start": 719,
"end": 3068
} | class ____(jt_multiprocess.MultiProcessTest):
def test_coords(self):
for device in jax.local_devices():
coords = device.coords
self.assertIsInstance(coords, list)
self.assertLen(coords, 3)
for coord in coords:
self.assertIsInstance(coord, int)
def test_core(self):
for device in jax.local_devices():
core = device.core_on_chip
self.assertIsInstance(core, int)
self.assertGreaterEqual(core, 0)
self.assertLess(core, 2)
def test_missing_attribute(self):
for device in jax.local_devices():
with self.assertRaises(AttributeError):
device.gpu_type # pylint: disable=pointless-statement
def test_memory(self):
for device in jax.devices():
device_is_local = device.process_index == jax.process_index()
self.assertLen(device.addressable_memories(), 3)
hbm = device.addressable_memories()[0]
self.assertEqual(
hbm.process_index == device.process_index, device_is_local)
self.assertEqual(hbm.platform, device.platform)
self.assertEqual(hbm.kind, 'device')
self.assertEqual(hbm, device.memory(hbm.kind))
self.assertListEqual(hbm.addressable_by_devices(), [device])
host = device.addressable_memories()[1]
self.assertEqual(
host.process_index == device.process_index, device_is_local)
self.assertEqual(host.platform, device.platform)
self.assertEqual(host.kind, 'pinned_host')
self.assertEqual(host, device.memory(host.kind))
self.assertListEqual(host.addressable_by_devices(), [device])
with self.assertRaisesRegex(
jax.errors.JaxRuntimeError,
'INVALID_ARGUMENT: Could not find memory addressable by device TPU'
' v.* Device TPU v.* can address the following memory kinds: device,'
' pinned_host, unpinned_host. Got memory kind: gpu_hbm',
):
device.memory('gpu_hbm')
def test_host_memory_id(self):
if jax.local_device_count() < 2:
raise unittest.SkipTest('test requires 2 devices per process')
self.assertGreaterEqual(len(jax.local_devices()), 2)
host_0 = jax.local_devices()[0].memory('unpinned_host')
host_1 = jax.local_devices()[1].memory('unpinned_host')
self.assertNotEqual(id(host_0), id(host_1))
if __name__ == '__main__':
jt_multiprocess.main()
| TpuDeviceTest |
python | huggingface__transformers | tests/models/speecht5/test_modeling_speecht5.py | {
"start": 31393,
"end": 35045
} | class ____:
def __init__(
self,
parent,
batch_size=13,
encoder_seq_length=7,
decoder_seq_length=1024, # speech is longer
is_training=False,
hidden_size=24,
num_hidden_layers=2,
num_attention_heads=2,
intermediate_size=4,
vocab_size=81,
num_mel_bins=20,
reduction_factor=2,
speech_decoder_postnet_layers=2,
speech_decoder_postnet_units=32,
speech_decoder_prenet_units=32,
):
self.parent = parent
self.batch_size = batch_size
self.encoder_seq_length = encoder_seq_length
self.decoder_seq_length = decoder_seq_length
self.is_training = is_training
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.intermediate_size = intermediate_size
self.vocab_size = vocab_size
self.num_mel_bins = num_mel_bins
self.reduction_factor = reduction_factor
self.speech_decoder_postnet_layers = speech_decoder_postnet_layers
self.speech_decoder_postnet_units = speech_decoder_postnet_units
self.speech_decoder_prenet_units = speech_decoder_prenet_units
def prepare_config_and_inputs(self):
input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size).clamp(2)
attention_mask = random_attention_mask([self.batch_size, self.encoder_seq_length])
decoder_input_values = floats_tensor([self.batch_size, self.decoder_seq_length, self.num_mel_bins], scale=1.0)
decoder_attention_mask = random_attention_mask([self.batch_size, self.decoder_seq_length])
config = self.get_config()
inputs_dict = prepare_inputs_dict(
config,
input_ids=input_ids,
decoder_input_values=decoder_input_values,
attention_mask=attention_mask,
decoder_attention_mask=decoder_attention_mask,
)
return config, inputs_dict
def prepare_config_and_inputs_for_common(self):
config, inputs_dict = self.prepare_config_and_inputs()
return config, inputs_dict
def get_config(self):
return SpeechT5Config(
hidden_size=self.hidden_size,
encoder_layers=self.num_hidden_layers,
decoder_layers=self.num_hidden_layers,
encoder_attention_heads=self.num_attention_heads,
decoder_attention_heads=self.num_attention_heads,
encoder_ffn_dim=self.intermediate_size,
decoder_ffn_dim=self.intermediate_size,
vocab_size=self.vocab_size,
num_mel_bins=self.num_mel_bins,
reduction_factor=self.reduction_factor,
speech_decoder_postnet_layers=self.speech_decoder_postnet_layers,
speech_decoder_postnet_units=self.speech_decoder_postnet_units,
speech_decoder_prenet_units=self.speech_decoder_prenet_units,
)
def create_and_check_model_forward(self, config, inputs_dict):
model = SpeechT5ForTextToSpeech(config=config).to(torch_device).eval()
input_ids = inputs_dict["input_ids"]
attention_mask = inputs_dict["attention_mask"]
decoder_input_values = inputs_dict["decoder_input_values"]
result = model(input_ids, attention_mask=attention_mask, decoder_input_values=decoder_input_values)
self.parent.assertEqual(
result.spectrogram.shape,
(self.batch_size, self.decoder_seq_length * self.reduction_factor, self.num_mel_bins),
)
@require_torch
| SpeechT5ForTextToSpeechTester |
python | getsentry__sentry | src/sentry/auth/authenticators/totp.py | {
"start": 85,
"end": 1066
} | class ____(OtpMixin):
"""This interface uses TOTP with an authenticator."""
type = 1
interface_id = "totp"
name = _("Authenticator App")
allow_rotation_in_place = True
description = _(
"An authenticator application that supports TOTP (like "
"Google Authenticator or 1Password) can be used to "
"access your account securely using a token and secret key. "
"A new token is generated every 30 seconds."
)
rotation_warning = _(
"Your account is currently linked to an authenticator "
"application. To link to a new device or application, "
'or to update your secret key, click "Confirm" below. By '
'clicking "Confirm", your existing secret key will be '
"replaced and will no longer work to access your account."
)
def get_provision_url(self, user: str, issuer: str | None = None) -> str:
return self.make_otp().get_provision_url(user, issuer=issuer)
| TotpInterface |
python | apache__airflow | providers/arangodb/src/airflow/providers/arangodb/sensors/arangodb.py | {
"start": 1109,
"end": 2234
} | class ____(BaseSensorOperator):
"""
Checks for the existence of a document which matches the given query in ArangoDB.
:param collection: Target DB collection.
:param query: The query to poke, or you can provide .sql file having the query
:param arangodb_conn_id: The :ref:`ArangoDB connection id <howto/connection:arangodb>` to use
when connecting to ArangoDB.
:param arangodb_db: Target ArangoDB name.
"""
template_fields: Sequence[str] = ("query",)
template_ext: Sequence[str] = (".sql",)
template_fields_renderers = {"query": "sql"}
def __init__(self, *, query: str, arangodb_conn_id: str = "arangodb_default", **kwargs) -> None:
super().__init__(**kwargs)
self.arangodb_conn_id = arangodb_conn_id
self.query = query
def poke(self, context: Context) -> bool:
self.log.info("Sensor running the following query: %s", self.query)
hook = ArangoDBHook(self.arangodb_conn_id)
records = hook.query(self.query, count=True).count()
self.log.info("Total records found: %d", records)
return records != 0
| AQLSensor |
python | Lightning-AI__lightning | tests/tests_pytorch/callbacks/test_weight_averaging.py | {
"start": 5124,
"end": 17370
} | class ____(WeightAveraging):
def __init__(self, **kwargs: Any) -> None:
super().__init__(avg_fn=get_swa_avg_fn(), **kwargs)
self.swap_calls = 0
self.copy_calls = 0
# Record the first epoch, as if we are resuming from a checkpoint this may not be equal to 0.
self.first_epoch: Optional[int] = None
def should_update(self, step_idx: Optional[int] = None, epoch_idx: Optional[int] = None) -> bool:
return epoch_idx in (3, 5, 7)
def _swap_models(self, *args: Any, **kwargs: Any):
self.swap_calls += 1
return super()._swap_models(*args, **kwargs)
def _copy_average_to_current(self, *args: Any, **kwargs: Any):
self.copy_calls += 1
return super()._copy_average_to_current(*args, **kwargs)
def on_train_start(self, trainer: Trainer, pl_module: LightningModule) -> None:
super().on_train_start(trainer, pl_module)
assert self.swap_calls == 0
assert self.copy_calls == 0
def on_train_epoch_start(self, trainer: Trainer, *args: Any) -> None:
super().on_train_epoch_start(trainer, *args)
# Since the checkpoint loaded was saved `on_train_epoch_end`, the first `FitLoop` iteration will not update the
# model and will just call the epoch-level hooks. For that reason, we check that we are not restarting before
# choosing the first epoch.
if self.first_epoch is None and not trainer.fit_loop.restarting:
self.first_epoch = trainer.current_epoch
def on_train_epoch_end(self, trainer: Trainer, *args: Any) -> None:
super().on_train_epoch_end(trainer, *args)
if trainer.current_epoch < 3:
assert self._average_model.n_averaged == 0
elif trainer.current_epoch < 5:
assert self._average_model.n_averaged == 1
elif trainer.current_epoch < 7:
assert self._average_model.n_averaged == 2
else:
assert self._average_model.n_averaged == 3
assert self.swap_calls == (trainer.current_epoch + 1 - self.first_epoch) * 2
assert self.copy_calls == 0
def on_train_end(self, trainer: Trainer, pl_module: LightningModule) -> None:
super().on_train_end(trainer, pl_module)
assert self._average_model.n_averaged == 3
assert self.swap_calls == (trainer.max_epochs - self.first_epoch) * 2
assert self.copy_calls == 1
def test_weight_averaging_deepcopy(tmp_path):
"""Ensure that WeightAveraging callback doesn't deepcopy the data loaders or the data module and consume memory
more than necessary."""
class TestCallback(WeightAveraging):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setup_called = False
def setup(self, trainer, pl_module, stage) -> None:
super().setup(trainer, pl_module, stage)
assert self._average_model.module.train_dataloader is not pl_module.train_dataloader
assert self._average_model.module.train_dataloader.__self__ == self._average_model.module
assert self._average_model.module._trainer is None
self.setup_called = True
callback = TestCallback()
trainer = Trainer(default_root_dir=tmp_path, callbacks=callback, fast_dev_run=True)
trainer.fit(BoringModel(), train_dataloaders=DataLoader(RandomDataset(32, 2)))
assert callback.setup_called
@pytest.mark.parametrize("batch_norm", [True, False])
@pytest.mark.parametrize("iterable_dataset", [True, False])
def test_ema(tmp_path, batch_norm: bool, iterable_dataset: bool):
model = TestModel(batch_norm=batch_norm)
dataset = RandomIterableDataset(32, 32) if iterable_dataset else RandomDataset(32, 32)
_train(model, dataset, tmp_path, EMATestCallback())
@pytest.mark.parametrize(
"accelerator", [pytest.param("gpu", marks=RunIf(min_cuda_gpus=1)), pytest.param("mps", marks=RunIf(mps=True))]
)
def test_ema_accelerator(tmp_path, accelerator):
model = TestModel()
dataset = RandomDataset(32, 32)
_train(model, dataset, tmp_path, EMATestCallback(), accelerator=accelerator, devices=1)
@RunIf(min_cuda_gpus=2, standalone=True)
def test_ema_ddp(tmp_path):
model = TestModel()
dataset = RandomDataset(32, 32)
_train(model, dataset, tmp_path, EMATestCallback(devices=2), strategy="ddp", accelerator="gpu", devices=2)
@RunIf(min_cuda_gpus=2)
def test_ema_ddp_spawn(tmp_path):
model = TestModel()
dataset = RandomDataset(32, 32)
_train(model, dataset, tmp_path, EMATestCallback(devices=2), strategy="ddp_spawn", accelerator="gpu", devices=2)
@RunIf(skip_windows=True)
def test_ema_ddp_spawn_cpu(tmp_path):
model = TestModel()
dataset = RandomDataset(32, 32)
_train(model, dataset, tmp_path, EMATestCallback(devices=2), strategy="ddp_spawn", accelerator="cpu", devices=2)
@pytest.mark.parametrize("crash_on_epoch", [1, 3, 5])
def test_ema_resume(tmp_path, crash_on_epoch):
dataset = RandomDataset(32, 32)
model1 = TestModel()
model2 = deepcopy(model1)
_train(model1, dataset, tmp_path, EMATestCallback())
model2.crash_on_epoch = crash_on_epoch
model2 = _train_and_resume(model2, dataset, tmp_path)
for param1, param2 in zip(model1.parameters(), model2.parameters()):
assert torch.allclose(param1, param2)
@RunIf(skip_windows=True)
def test_ema_resume_ddp(tmp_path):
model = TestModel()
model.crash_on_epoch = 3
dataset = RandomDataset(32, 32)
_train_and_resume(model, dataset, tmp_path, strategy="ddp_spawn", devices=2)
def test_swa(tmp_path):
model = TestModel()
dataset = RandomDataset(32, 32)
_train(model, dataset, tmp_path, SWATestCallback())
@pytest.mark.parametrize(
("strategy", "accelerator", "devices"),
[
("auto", "cpu", 1),
pytest.param("auto", "gpu", 1, marks=RunIf(min_cuda_gpus=1)),
pytest.param("fsdp", "gpu", 1, marks=RunIf(min_cuda_gpus=1)),
],
)
def test_ema_configure_model(tmp_path, strategy, accelerator, devices):
model = LargeTestModel()
dataset = RandomDataset(32, 32)
callback = EMATestCallback()
_train(model, dataset, tmp_path, callback, strategy=strategy, accelerator=accelerator, devices=devices)
assert isinstance(callback._average_model.module.layer, nn.Sequential)
def _train(
model: BoringModel,
dataset: Dataset,
tmp_path: str,
callback: WeightAveraging,
strategy: str = "auto",
accelerator: str = "cpu",
devices: int = 1,
checkpoint_path: Optional[str] = None,
will_crash: bool = False,
) -> None:
deterministic = accelerator == "cpu"
trainer = Trainer(
accelerator=accelerator,
strategy=strategy,
devices=devices,
logger=False,
callbacks=callback,
max_epochs=8,
num_sanity_val_steps=0,
enable_checkpointing=will_crash,
enable_progress_bar=False,
enable_model_summary=False,
accumulate_grad_batches=2,
deterministic=deterministic,
default_root_dir=tmp_path,
)
dataloader = DataLoader(dataset, batch_size=4, shuffle=False)
if will_crash:
with pytest.raises(Exception, match="CRASH"):
trainer.fit(model, dataloader, ckpt_path=checkpoint_path)
else:
trainer.fit(model, dataloader, ckpt_path=checkpoint_path)
assert trainer.lightning_module == model
def _train_and_resume(model: TestModel, dataset: Dataset, tmp_path: str, devices: int = 1, **kwargs) -> TestModel:
_train(model, dataset, tmp_path, EMATestCallback(devices=devices), devices=devices, will_crash=True, **kwargs)
checkpoint_dir = Path(tmp_path) / "checkpoints"
checkpoint_names = os.listdir(checkpoint_dir)
assert len(checkpoint_names) == 1
checkpoint_path = str(checkpoint_dir / checkpoint_names[0])
model = TestModel.load_from_checkpoint(checkpoint_path)
callback = EMATestCallback(devices=devices)
_train(model, dataset, tmp_path, callback, devices=devices, checkpoint_path=checkpoint_path, **kwargs)
return model
@pytest.mark.parametrize(
("strategy", "accelerator", "devices"),
[
("auto", "cpu", 1),
pytest.param("auto", "gpu", 1, marks=RunIf(min_cuda_gpus=1)),
],
)
def test_ema_weight_averaging(tmp_path, strategy, accelerator, devices):
"""Test EMAWeightAveraging callback with various update configurations."""
model = TestModel()
dataset = RandomDataset(32, 32)
# Test with default settings (update every step)
callback = EMAWeightAveraging(decay=0.999, update_every_n_steps=1)
_train(model, dataset, tmp_path, callback, strategy=strategy, accelerator=accelerator, devices=devices)
# Verify the average model was created and updated
assert callback._average_model is not None
assert callback._average_model.n_averaged > 0
def test_ema_weight_averaging_step_frequency(tmp_path):
"""Test EMAWeightAveraging with custom step update frequency."""
model = TestModel()
dataset = RandomDataset(32, 32)
# Update every 5 steps
callback = EMAWeightAveraging(decay=0.95, update_every_n_steps=5)
_train(model, dataset, tmp_path, callback)
assert callback._average_model is not None
def test_ema_weight_averaging_starting_step(tmp_path):
"""Test EMAWeightAveraging with delayed start based on steps."""
model = TestModel()
dataset = RandomDataset(32, 32)
# Start updating after step 10
callback = EMAWeightAveraging(decay=0.999, update_every_n_steps=1, update_starting_at_step=10)
_train(model, dataset, tmp_path, callback)
assert callback._average_model is not None
def test_ema_weight_averaging_starting_epoch(tmp_path):
"""Test EMAWeightAveraging with delayed start based on epochs."""
model = TestModel()
dataset = RandomDataset(32, 32)
# Start updating after epoch 3
callback = EMAWeightAveraging(decay=0.999, update_every_n_steps=1, update_starting_at_epoch=3)
_train(model, dataset, tmp_path, callback)
assert callback._average_model is not None
def test_ema_weight_averaging_should_update(tmp_path):
"""Test the should_update logic of EMAWeightAveraging."""
# Test with step-based updates
callback = EMAWeightAveraging(update_every_n_steps=5, update_starting_at_step=10)
# Before starting step
assert not callback.should_update(step_idx=5)
assert not callback.should_update(step_idx=9)
# At and after starting step, but not on update frequency
assert callback.should_update(step_idx=10) # First update
assert not callback.should_update(step_idx=11)
assert not callback.should_update(step_idx=14)
assert callback.should_update(step_idx=15) # Second update
# Test with epoch-based updates
callback = EMAWeightAveraging(update_starting_at_epoch=2)
assert not callback.should_update(epoch_idx=0)
assert not callback.should_update(epoch_idx=1)
assert callback.should_update(epoch_idx=2)
assert callback.should_update(epoch_idx=3)
def test_ema_weight_averaging_checkpoint_save_load(tmp_path):
"""Test that EMAWeightAveraging correctly saves and loads checkpoints."""
model = TestModel()
model.crash_on_epoch = 2
dataset = RandomDataset(32, 32)
callback = EMAWeightAveraging(decay=0.99, update_every_n_steps=2)
# Train and create checkpoint
_train(model, dataset, tmp_path, callback, will_crash=True)
# Resume from checkpoint
model2 = TestModel()
callback2 = EMAWeightAveraging(decay=0.99, update_every_n_steps=2)
import glob # should be at the top
_train(
model2,
dataset,
tmp_path,
callback2,
checkpoint_path=glob.glob((tmp_path / "checkpoints" / "*.ckpt").as_posix())[0],
)
assert callback2._average_model is not None
@pytest.mark.parametrize("decay", [0.9, 0.99, 0.999, 0.9999])
def test_ema_weight_averaging_decay_values(tmp_path, decay):
"""Test EMAWeightAveraging with different decay values."""
model = TestModel()
dataset = RandomDataset(32, 32)
callback = EMAWeightAveraging(decay=decay, update_every_n_steps=1)
_train(model, dataset, tmp_path, callback)
assert callback._average_model is not None
| SWATestCallback |
python | jazzband__django-redis | tests/test_client.py | {
"start": 5198,
"end": 7164
} | class ____:
@patch("test_client.DefaultClient.make_pattern")
@patch("test_client.ShardClient.__init__", return_value=None)
def test_delete_pattern_calls_scan_iter_with_count_if_itersize_given(
self,
init_mock,
make_pattern_mock,
):
client = ShardClient()
client._backend = Mock()
client._backend.key_prefix = ""
connection = Mock()
connection.scan_iter.return_value = []
client._serverdict = {"test": connection}
client.delete_pattern(pattern="foo*", itersize=10)
connection.scan_iter.assert_called_once_with(
count=10,
match=make_pattern_mock.return_value,
)
@patch("test_client.DefaultClient.make_pattern")
@patch("test_client.ShardClient.__init__", return_value=None)
def test_delete_pattern_calls_scan_iter(self, init_mock, make_pattern_mock):
client = ShardClient()
client._backend = Mock()
client._backend.key_prefix = ""
connection = Mock()
connection.scan_iter.return_value = []
client._serverdict = {"test": connection}
client.delete_pattern(pattern="foo*")
connection.scan_iter.assert_called_once_with(
match=make_pattern_mock.return_value,
)
@patch("test_client.DefaultClient.make_pattern")
@patch("test_client.ShardClient.__init__", return_value=None)
def test_delete_pattern_calls_delete_for_given_keys(
self,
init_mock,
make_pattern_mock,
):
client = ShardClient()
client._backend = Mock()
client._backend.key_prefix = ""
connection = Mock()
connection.scan_iter.return_value = [Mock(), Mock()]
connection.delete.return_value = 0
client._serverdict = {"test": connection}
client.delete_pattern(pattern="foo*")
connection.delete.assert_called_once_with(*connection.scan_iter.return_value)
| TestShardClient |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/string_ngrams_op_test.py | {
"start": 1192,
"end": 13956
} | class ____(test_util.TensorFlowTestCase, parameterized.TestCase):
def test_unpadded_ngrams(self):
data = [[b"aa", b"bb", b"cc", b"dd"], [b"ee", b"ff"]]
data_tensor = ragged_factory_ops.constant(data)
ngram_op = ragged_string_ops.ngrams(
data_tensor, ngram_width=3, separator=b"|")
result = self.evaluate(ngram_op)
expected_ngrams = [[b"aa|bb|cc", b"bb|cc|dd"], []]
self.assertAllEqual(expected_ngrams, result)
def test_tuple_multi_ngrams(self):
data = [[b"aa", b"bb", b"cc", b"dd"], [b"ee", b"ff"]]
data_tensor = ragged_factory_ops.constant(data)
ngram_op = ragged_string_ops.ngrams(
data_tensor, ngram_width=(2, 3), separator=b"|")
result = self.evaluate(ngram_op)
expected_ngrams = [[b"aa|bb", b"bb|cc", b"cc|dd", b"aa|bb|cc", b"bb|cc|dd"],
[b"ee|ff"]]
self.assertAllEqual(expected_ngrams, result)
def test_tuple_multi_ngrams_inverted_order(self):
data = [[b"aa", b"bb", b"cc", b"dd"], [b"ee", b"ff"]]
data_tensor = ragged_factory_ops.constant(data)
ngram_op = ragged_string_ops.ngrams(
data_tensor, ngram_width=(3, 2), separator=b"|")
result = self.evaluate(ngram_op)
expected_ngrams = [[b"aa|bb|cc", b"bb|cc|dd", b"aa|bb", b"bb|cc", b"cc|dd"],
[b"ee|ff"]]
self.assertAllEqual(expected_ngrams, result)
def test_list_multi_ngrams(self):
data = [[b"aa", b"bb", b"cc", b"dd"], [b"ee", b"ff"]]
data_tensor = ragged_factory_ops.constant(data)
ngram_op = ragged_string_ops.ngrams(
data_tensor, ngram_width=[2, 3], separator=b"|")
result = self.evaluate(ngram_op)
expected_ngrams = [[b"aa|bb", b"bb|cc", b"cc|dd", b"aa|bb|cc", b"bb|cc|dd"],
[b"ee|ff"]]
self.assertAllEqual(expected_ngrams, result)
def test_multi_ngram_ordering(self):
data = [[b"aa", b"bb", b"cc", b"dd"], [b"ee", b"ff"]]
data_tensor = ragged_factory_ops.constant(data)
ngram_op = ragged_string_ops.ngrams(
data_tensor, ngram_width=[3, 2], separator=b"|")
result = self.evaluate(ngram_op)
expected_ngrams = [[b"aa|bb|cc", b"bb|cc|dd", b"aa|bb", b"bb|cc", b"cc|dd"],
[b"ee|ff"]]
self.assertAllEqual(expected_ngrams, result)
def test_fully_padded_ngrams(self):
data = [[b"a"], [b"b", b"c", b"d"], [b"e", b"f"]]
data_tensor = ragged_factory_ops.constant(data)
ngram_op = ragged_string_ops.ngrams(
data_tensor, ngram_width=3, separator=b"|", pad_values=(b"LP", b"RP"))
result = self.evaluate(ngram_op)
expected_ngrams = [
[b"LP|LP|a", b"LP|a|RP", b"a|RP|RP"], # 0
[b"LP|LP|b", b"LP|b|c", b"b|c|d", b"c|d|RP", b"d|RP|RP"], # 1
[b"LP|LP|e", b"LP|e|f", b"e|f|RP", b"f|RP|RP"] # 2
]
self.assertAllEqual(expected_ngrams, result)
def test_ngram_padding_size_cap(self):
# Validate that the padding size is never greater than ngram_size - 1.
data = [[b"a"], [b"b", b"c", b"d"], [b"e", b"f"]]
data_tensor = ragged_factory_ops.constant(data)
ngram_op = ragged_string_ops.ngrams(
data_tensor,
ngram_width=3,
separator=b"|",
pad_values=(b"LP", b"RP"),
padding_width=10)
result = self.evaluate(ngram_op)
expected_ngrams = [
[b"LP|LP|a", b"LP|a|RP", b"a|RP|RP"], # 0
[b"LP|LP|b", b"LP|b|c", b"b|c|d", b"c|d|RP", b"d|RP|RP"], # 1
[b"LP|LP|e", b"LP|e|f", b"e|f|RP", b"f|RP|RP"] # 2
]
self.assertAllEqual(expected_ngrams, result)
def test_singly_padded_ngrams(self):
data = [[b"a"], [b"b", b"c", b"d"], [b"e", b"f"]]
data_tensor = ragged_factory_ops.constant(data)
ngram_op = ragged_string_ops.ngrams(
data_tensor,
ngram_width=5,
separator=b"|",
pad_values=(b"LP", b"RP"),
padding_width=1)
result = self.evaluate(ngram_op)
expected_ngrams = [[], [b"LP|b|c|d|RP"], []]
self.assertAllEqual(expected_ngrams, result)
def test_singly_padded_ngrams_with_preserve_short(self):
data = [[b"a"], [b"b", b"c", b"d"], [b"e", b"f"]]
data_tensor = ragged_factory_ops.constant(data)
ngram_op = ragged_string_ops.ngrams(
data_tensor,
ngram_width=5,
separator=b"|",
pad_values=(b"LP", b"RP"),
padding_width=1,
preserve_short_sequences=True)
result = self.evaluate(ngram_op)
expected_ngrams = [[b"LP|a|RP"], [b"LP|b|c|d|RP"], [b"LP|e|f|RP"]]
self.assertAllEqual(expected_ngrams, result)
def test_singly_padded_multiple_ngrams(self):
data = [[b"a"], [b"b", b"c", b"d"], [b"e", b"f"]]
data_tensor = ragged_factory_ops.constant(data)
ngram_op = ragged_string_ops.ngrams(
data_tensor,
ngram_width=(1, 5),
separator=b"|",
pad_values=(b"LP", b"RP"),
padding_width=1)
result = self.evaluate(ngram_op)
expected_ngrams = [[b"a"], [b"b", b"c", b"d", b"LP|b|c|d|RP"], [b"e", b"f"]]
self.assertAllEqual(expected_ngrams, result)
def test_single_padding_string(self):
data = [[b"a"], [b"b", b"c", b"d"], [b"e", b"f"]]
data_tensor = ragged_factory_ops.constant(data)
ngram_op = ragged_string_ops.ngrams(
data_tensor,
ngram_width=5,
separator=b"|",
pad_values=b"[PAD]",
padding_width=1)
result = self.evaluate(ngram_op)
expected_ngrams = [[], [b"[PAD]|b|c|d|[PAD]"], []]
self.assertAllEqual(expected_ngrams, result)
def test_explicit_multiply_padded_ngrams(self):
data = [[b"a"]]
data_tensor = ragged_factory_ops.constant(data)
ngram_op = ragged_string_ops.ngrams(
data_tensor,
ngram_width=5,
separator=b"|",
pad_values=(b"LP", b"RP"),
padding_width=2)
result = self.evaluate(ngram_op)
expected_ngrams = [[b"LP|LP|a|RP|RP"]]
self.assertAllEqual(expected_ngrams, result)
def test_ragged_inputs_with_multiple_ragged_dimensions(self):
data = [[[[b"aa", b"bb", b"cc", b"dd"]], [[b"ee", b"ff"]]]]
data_tensor = ragged_factory_ops.constant(data)
ngram_op = ragged_string_ops.ngrams(
data_tensor, ngram_width=3, separator=b"|")
result = self.evaluate(ngram_op)
expected_ngrams = [[[[b"aa|bb|cc", b"bb|cc|dd"]], [[]]]]
self.assertAllEqual(expected_ngrams, result)
def test_ragged_inputs_with_multiple_ragged_dimensions_and_preserve(self):
data = [[[[b"aa", b"bb", b"cc", b"dd"]], [[b"ee", b"ff"]]]]
data_tensor = ragged_factory_ops.constant(data)
ngram_op = ragged_string_ops.ngrams(
data_tensor,
ngram_width=3,
separator=b"|",
preserve_short_sequences=True)
result = self.evaluate(ngram_op)
expected_ngrams = [[[[b"aa|bb|cc", b"bb|cc|dd"]], [[b"ee|ff"]]]]
self.assertAllEqual(expected_ngrams, result)
def test_ragged_inputs_with_multiple_ragged_dimensions_bigrams(self):
data = [[[[b"aa", b"bb", b"cc", b"dd"]], [[b"ee", b"ff"]]]]
data_tensor = ragged_factory_ops.constant(data)
ngram_op = ragged_string_ops.ngrams(
data_tensor, ngram_width=2, separator=b"|")
result = self.evaluate(ngram_op)
expected_ngrams = [[[[b"aa|bb", b"bb|cc", b"cc|dd"]], [[b"ee|ff"]]]]
self.assertAllEqual(expected_ngrams, result)
def test_ragged_inputs_with_multiple_ragged_dimensions_and_multiple_ngrams(
self):
data = [[[[b"aa", b"bb", b"cc", b"dd"]], [[b"ee", b"ff"]]]]
data_tensor = ragged_factory_ops.constant(data)
ngram_op = ragged_string_ops.ngrams(
data_tensor, ngram_width=(3, 4), separator=b"|")
result = self.evaluate(ngram_op)
expected_ngrams = [[[[b"aa|bb|cc", b"bb|cc|dd", b"aa|bb|cc|dd"]], [[]]]]
self.assertAllEqual(expected_ngrams, result)
def test_dense_input_rank_3(self):
data = [[[b"a", b"z"], [b"b", b""]], [[b"b", b""], [b"e", b"f"]]]
data_tensor = constant_op.constant(data)
ngram_op = ragged_string_ops.ngrams(
data_tensor, ngram_width=3, separator=b"|", pad_values=(b"LP", b"RP"))
result = self.evaluate(ngram_op)
expected_ngrams = [[[b"LP|LP|a", b"LP|a|z", b"a|z|RP", b"z|RP|RP"],
[b"LP|LP|b", b"LP|b|", b"b||RP", b"|RP|RP"]],
[[b"LP|LP|b", b"LP|b|", b"b||RP", b"|RP|RP"],
[b"LP|LP|e", b"LP|e|f", b"e|f|RP", b"f|RP|RP"]]]
self.assertIsInstance(ngram_op, tensor.Tensor)
self.assertAllEqual(expected_ngrams, result)
def test_dense_input(self):
data = [[b"a", b"z"], [b"b", b""], [b"e", b"f"]]
data_tensor = constant_op.constant(data)
ngram_op = ragged_string_ops.ngrams(
data_tensor, ngram_width=3, separator=b"|", pad_values=(b"LP", b"RP"))
result = self.evaluate(ngram_op)
expected_ngrams = [
[b"LP|LP|a", b"LP|a|z", b"a|z|RP", b"z|RP|RP"],
[b"LP|LP|b", b"LP|b|", b"b||RP", b"|RP|RP"],
[b"LP|LP|e", b"LP|e|f", b"e|f|RP", b"f|RP|RP"],
]
self.assertIsInstance(ngram_op, tensor.Tensor)
self.assertAllEqual(expected_ngrams, result)
def test_input_list_input(self):
data = [[b"a", b"z"], [b"b", b""], [b"e", b"f"]]
ngram_op = ragged_string_ops.ngrams(
data, ngram_width=3, separator=b"|", pad_values=(b"LP", b"RP"))
result = self.evaluate(ngram_op)
expected_ngrams = [
[b"LP|LP|a", b"LP|a|z", b"a|z|RP", b"z|RP|RP"],
[b"LP|LP|b", b"LP|b|", b"b||RP", b"|RP|RP"],
[b"LP|LP|e", b"LP|e|f", b"e|f|RP", b"f|RP|RP"],
]
self.assertAllEqual(expected_ngrams, result)
def test_vector_input(self):
data = [b"a", b"z"]
data_tensor = ragged_factory_ops.constant(data)
ngram_op = ragged_string_ops.ngrams(
data_tensor, ngram_width=3, separator=b"|", pad_values=(b"LP", b"RP"))
result = self.evaluate(ngram_op)
expected_ngrams = [b"LP|LP|a", b"LP|a|z", b"a|z|RP", b"z|RP|RP"]
self.assertAllEqual(expected_ngrams, result)
def test_dense_input_with_multiple_ngrams(self):
data = [[b"a", b"b", b"c", b"d"], [b"e", b"f", b"g", b"h"]]
data_tensor = ragged_factory_ops.constant(data)
ngram_op = ragged_string_ops.ngrams(
data_tensor, ngram_width=(1, 2, 3), separator=b"|")
result = self.evaluate(ngram_op)
expected_ngrams = [[
b"a", b"b", b"c", b"d", b"a|b", b"b|c", b"c|d", b"a|b|c", b"b|c|d"
], [b"e", b"f", b"g", b"h", b"e|f", b"f|g", b"g|h", b"e|f|g", b"f|g|h"]]
self.assertAllEqual(expected_ngrams, result)
def test_input_with_no_values(self):
data = ragged_factory_ops.constant([[], [], []], dtype=dtypes.string)
ngram_op = ragged_string_ops.ngrams(data, (1, 2))
result = self.evaluate(ngram_op)
self.assertAllEqual([0, 0, 0, 0], result.row_splits)
self.assertAllEqual(constant_op.constant([], dtype=dtypes.string),
result.values)
@parameterized.parameters([
dict(
data=[b"a", b"z"],
ngram_width=2,
pad_values=5,
exception=TypeError,
error="pad_values must be a string, tuple of strings, or None."),
dict(
data=[b"a", b"z"],
ngram_width=2,
pad_values=[5, 3],
exception=TypeError,
error="pad_values must be a string, tuple of strings, or None."),
dict(
data=[b"a", b"z"],
ngram_width=2,
padding_width=0,
pad_values="X",
error="padding_width must be greater than 0."),
dict(
data=[b"a", b"z"],
ngram_width=2,
padding_width=1,
error="pad_values must be provided if padding_width is set."),
dict(
data=b"hello",
ngram_width=2,
padding_width=1,
pad_values="X",
error="Data must have rank>0"),
dict(
data=[b"hello", b"world"],
ngram_width=[1, 2, -1],
padding_width=1,
pad_values="X",
error="All ngram_widths must be greater than 0. Got .*"),
])
def test_error(self,
data,
ngram_width,
separator=" ",
pad_values=None,
padding_width=None,
preserve_short_sequences=False,
error=None,
exception=ValueError):
with self.assertRaisesRegex(exception, error):
ragged_string_ops.ngrams(data, ngram_width, separator, pad_values,
padding_width, preserve_short_sequences)
def test_unknown_rank_error(self):
# Use a tf.function that erases shape information.
@def_function.function(
input_signature=[tensor.TensorSpec(None, dtypes.string)])
def f(v):
return ragged_string_ops.ngrams(v, 2)
with self.assertRaisesRegex(ValueError, "Rank of data must be known."):
f([b"foo", b"bar"])
if __name__ == "__main__":
test.main()
| StringNgramsTest |
python | kamyu104__LeetCode-Solutions | Python/find-distance-in-a-binary-tree.py | {
"start": 159,
"end": 1595
} | class ____(object):
def findDistance(self, root, p, q):
"""
:type root: TreeNode
:type p: int
:type q: int
:rtype: int
"""
def iter_dfs(root, p, q):
result = 0
dist = [-1]
stk = [(1, [root, dist])]
while stk:
step, params = stk.pop()
if step == 1:
node, ret = params
if not node:
continue
ret1, ret2 = [-1], [-1]
stk.append((2, [node, ret1, ret2, ret]))
stk.append((1, [node.right, ret2]))
stk.append((1, [node.left, ret1]))
elif step == 2:
node, ret1, ret2, ret = params
if node.val in (p, q):
if ret1[0] == ret2[0] == -1:
ret[0] = 0
else:
result = ret1[0]+1 if ret1[0] != -1 else ret2[0]+1
elif ret1[0] != -1 and ret2[0] != -1:
result = ret1[0]+ret2[0]+2
elif ret1[0] != -1:
ret[0] = ret1[0]+1
elif ret2[0] != -1:
ret[0] = ret2[0]+1
return result
return iter_dfs(root, p, q)
# Time: O(n)
# Space: O(h)
| Solution |
python | django__django | django/forms/models.py | {
"start": 53126,
"end": 58197
} | class ____(ChoiceField):
"""A ChoiceField whose choices are a model QuerySet."""
# This class is a subclass of ChoiceField for purity, but it doesn't
# actually use any of ChoiceField's implementation.
default_error_messages = {
"invalid_choice": _(
"Select a valid choice. That choice is not one of the available choices."
),
}
iterator = ModelChoiceIterator
def __init__(
self,
queryset,
*,
empty_label="---------",
required=True,
widget=None,
label=None,
initial=None,
help_text="",
to_field_name=None,
limit_choices_to=None,
blank=False,
**kwargs,
):
# Call Field instead of ChoiceField __init__() because we don't need
# ChoiceField.__init__().
Field.__init__(
self,
required=required,
widget=widget,
label=label,
initial=initial,
help_text=help_text,
**kwargs,
)
if (required and initial is not None) or (
isinstance(self.widget, RadioSelect) and not blank
):
self.empty_label = None
else:
self.empty_label = empty_label
self.queryset = queryset
self.limit_choices_to = limit_choices_to # limit the queryset later.
self.to_field_name = to_field_name
def validate_no_null_characters(self, value):
non_null_character_validator = ProhibitNullCharactersValidator()
return non_null_character_validator(value)
def get_limit_choices_to(self):
"""
Return ``limit_choices_to`` for this form field.
If it is a callable, invoke it and return the result.
"""
if callable(self.limit_choices_to):
return self.limit_choices_to()
return self.limit_choices_to
def __deepcopy__(self, memo):
result = super(ChoiceField, self).__deepcopy__(memo)
# Need to force a new ModelChoiceIterator to be created, bug #11183
if self.queryset is not None:
result.queryset = self.queryset.all()
return result
def _get_queryset(self):
return self._queryset
def _set_queryset(self, queryset):
self._queryset = None if queryset is None else queryset.all()
self.widget.choices = self.choices
queryset = property(_get_queryset, _set_queryset)
# this method will be used to create object labels by the QuerySetIterator.
# Override it to customize the label.
def label_from_instance(self, obj):
"""
Convert objects into strings and generate the labels for the choices
presented by this object. Subclasses can override this method to
customize the display of the choices.
"""
return str(obj)
def _get_choices(self):
# If self._choices is set, then somebody must have manually set
# the property self.choices. In this case, just return self._choices.
if hasattr(self, "_choices"):
return self._choices
# Otherwise, execute the QuerySet in self.queryset to determine the
# choices dynamically. Return a fresh ModelChoiceIterator that has not
# been consumed. Note that we're instantiating a new
# ModelChoiceIterator *each* time _get_choices() is called (and, thus,
# each time self.choices is accessed) so that we can ensure the
# QuerySet has not been consumed. This construct might look complicated
# but it allows for lazy evaluation of the queryset.
return self.iterator(self)
choices = property(_get_choices, ChoiceField.choices.fset)
def prepare_value(self, value):
if hasattr(value, "_meta"):
if self.to_field_name:
return value.serializable_value(self.to_field_name)
else:
return value.pk
return super().prepare_value(value)
def to_python(self, value):
if value in self.empty_values:
return None
self.validate_no_null_characters(value)
try:
key = self.to_field_name or "pk"
if isinstance(value, self.queryset.model):
value = getattr(value, key)
value = self.queryset.get(**{key: value})
except (
ValueError,
TypeError,
self.queryset.model.DoesNotExist,
ValidationError,
):
raise ValidationError(
self.error_messages["invalid_choice"],
code="invalid_choice",
params={"value": value},
)
return value
def validate(self, value):
return Field.validate(self, value)
def has_changed(self, initial, data):
if self.disabled:
return False
initial_value = initial if initial is not None else ""
data_value = data if data is not None else ""
return str(self.prepare_value(initial_value)) != str(data_value)
| ModelChoiceField |
python | getsentry__sentry | src/sentry/workflow_engine/migrations/0093_add_action_config_index.py | {
"start": 191,
"end": 1785
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# of a table.
# Here are some things that make sense to mark as post deployment:
# - Large data migrations. Typically we want these to be run manually so that they can be
# monitored and not block the deploy for a long period of time while they run.
# - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to
# run this outside deployments so that we don't block them. Note that while adding an index
# is a schema change, it's completely safe to run the operation after the code has deployed.
# Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment
is_post_deployment = True
dependencies = [
("workflow_engine", "0092_repair_workflow_cron_conditions"),
]
operations = [
migrations.AddIndex(
model_name="action",
index=models.Index(
models.F("type"),
django.db.models.expressions.RawSQL("config->>'sentry_app_identifier'", []),
django.db.models.expressions.RawSQL("config->>'target_identifier'", []),
condition=models.Q(("type", "sentry_app")),
name="action_sentry_app_lookup",
),
),
]
| Migration |
python | pdm-project__pdm | src/pdm/cli/commands/update.py | {
"start": 722,
"end": 8416
} | class ____(BaseCommand):
"""Update package(s) in pyproject.toml"""
arguments = (
*BaseCommand.arguments,
groups_group,
install_group,
lockfile_option,
frozen_lockfile_option,
save_strategy_group,
override_option,
update_strategy_group,
prerelease_option,
unconstrained_option,
skip_option,
venv_option,
)
def add_arguments(self, parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"-t",
"--top",
action="store_true",
help="Only update those listed in pyproject.toml",
)
parser.add_argument(
"--dry-run",
"--outdated",
action="store_true",
dest="dry_run",
help="Show the difference only without modifying the lockfile content",
)
parser.add_argument(
"--no-sync",
dest="sync",
default=True,
action="store_false",
help="Only update lock file but do not sync packages",
)
parser.add_argument("packages", nargs="*", help="If packages are given, only update them")
parser.set_defaults(dev=None)
def handle(self, project: Project, options: argparse.Namespace) -> None:
self.do_update(
project,
selection=GroupSelection.from_options(project, options),
save=options.save_strategy or project.config["strategy.save"],
strategy=options.update_strategy or project.config["strategy.update"],
unconstrained=options.unconstrained,
top=options.top,
dry_run=options.dry_run,
packages=options.packages,
sync=options.sync,
no_editable=options.no_editable,
no_self=options.no_self,
prerelease=options.prerelease,
fail_fast=options.fail_fast,
hooks=HookManager(project, options.skip),
)
@staticmethod
def do_update(
project: Project,
*,
selection: GroupSelection,
strategy: str = "reuse",
save: str = "compatible",
unconstrained: bool = False,
top: bool = False,
dry_run: bool = False,
packages: Collection[str] = (),
sync: bool = True,
no_editable: bool = False,
no_self: bool = False,
prerelease: bool | None = None,
fail_fast: bool = False,
hooks: HookManager | None = None,
) -> None:
"""Update specified packages or all packages"""
from itertools import chain
from pdm.cli.actions import do_lock, do_sync
from pdm.cli.utils import check_project_file, save_version_specifiers
from pdm.models.specifiers import get_specifier
from pdm.utils import normalize_name
hooks = hooks or HookManager(project)
check_project_file(project)
if len(packages) > 0 and (top or len(selection.groups) > 1 or not selection.default):
raise PdmUsageError("packages argument can't be used together with multiple -G or --no-default or --top.")
all_dependencies = project.all_dependencies
updated_deps: dict[str, list[Requirement]] = defaultdict(list)
locked_groups = project.lockfile.groups
tracked_names: set[str] = set()
if not packages:
if prerelease is not None:
raise PdmUsageError("--prerelease/--stable must be used with packages given")
selection.validate()
for group in selection:
updated_deps[group] = list(all_dependencies[group])
tracked_names.update(r.identify() for deps in updated_deps.values() for r in deps)
else:
group = selection.one()
if locked_groups and group not in locked_groups:
raise ProjectError(f"Requested group not in lockfile: {group}")
dependencies = all_dependencies[group]
for name in packages:
normalized_name = normalize_name(name)
matched_reqs = [d for d in dependencies if (d.key or "") == normalized_name]
if not matched_reqs:
candidates = project.get_locked_repository().all_candidates
if normalized_name not in candidates:
raise ProjectError(
f"[req]{name}[/] does not exist in [primary]{group}[/] "
f"{'dev-' if selection.dev else ''}dependencies nor is a transitive dependency."
)
look_in_other_group = next(
(
g
for g, deps in all_dependencies.items()
if any(normalized_name == d.key for d in deps) and g != group
),
None,
)
if look_in_other_group is not None:
raise ProjectError(
f"[req]{name}[/] does not exist in [primary]{group}[/], but exists in [primary]{look_in_other_group}[/]."
" Please specify the correct group with `-G/--group`."
)
tracked_names.add(normalized_name)
else:
for req in matched_reqs:
req.prerelease = prerelease
updated_deps[group].extend(matched_reqs)
tracked_names.update(r.identify() for deps in updated_deps.values() for r in deps)
project.core.ui.echo(
f"Updating {'[bold]global[/] ' if project.is_global else ''}packages: {', '.join(f'[req]{v}[/]' for v in tracked_names)}."
)
if unconstrained:
for deps in updated_deps.values():
for dep in deps:
dep.specifier = get_specifier("")
reqs = [r for g, deps in all_dependencies.items() for r in deps if locked_groups is None or g in locked_groups]
# Since dry run is always true in the locking,
# we need to emit the hook manually with the real dry_run value
hooks.try_emit("pre_lock", requirements=reqs, dry_run=dry_run)
with hooks.skipping("pre_lock", "post_lock"):
resolved = do_lock(
project,
strategy=strategy,
tracked_names=tracked_names,
requirements=reqs,
dry_run=True,
hooks=hooks,
groups=locked_groups,
)
if unconstrained:
# Need to update version constraints
save_version_specifiers(chain.from_iterable(updated_deps.values()), resolved, save)
if not dry_run:
if unconstrained:
for group, deps in updated_deps.items():
project.add_dependencies(deps, group, selection.dev or False)
project.write_lockfile(show_message=False)
hooks.try_emit("post_lock", resolution=resolved, dry_run=dry_run)
if sync or dry_run:
do_sync(
project,
selection=selection,
clean=False,
dry_run=dry_run,
requirements=[r for deps in updated_deps.values() for r in deps],
tracked_names=[r.identify() for deps in updated_deps.values() for r in deps] if top else None,
no_editable=no_editable,
no_self=no_self or "default" not in selection,
fail_fast=fail_fast,
hooks=hooks,
)
| Command |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 586047,
"end": 586679
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("RepositoryCollaboratorEdge"), graphql_name="edges"
)
nodes = sgqlc.types.Field(sgqlc.types.list_of("User"), graphql_name="nodes")
page_info = sgqlc.types.Field(
sgqlc.types.non_null(PageInfo), graphql_name="pageInfo"
)
total_count = sgqlc.types.Field(
sgqlc.types.non_null(Int), graphql_name="totalCount"
)
| RepositoryCollaboratorConnection |
python | pypa__setuptools | setuptools/_vendor/wheel/vendored/packaging/specifiers.py | {
"start": 1149,
"end": 2843
} | class ____(metaclass=abc.ABCMeta):
@abc.abstractmethod
def __str__(self) -> str:
"""
Returns the str representation of this Specifier-like object. This
should be representative of the Specifier itself.
"""
@abc.abstractmethod
def __hash__(self) -> int:
"""
Returns a hash value for this Specifier-like object.
"""
@abc.abstractmethod
def __eq__(self, other: object) -> bool:
"""
Returns a boolean representing whether or not the two Specifier-like
objects are equal.
:param other: The other object to check against.
"""
@property
@abc.abstractmethod
def prereleases(self) -> Optional[bool]:
"""Whether or not pre-releases as a whole are allowed.
This can be set to either ``True`` or ``False`` to explicitly enable or disable
prereleases or it can be set to ``None`` (the default) to use default semantics.
"""
@prereleases.setter
def prereleases(self, value: bool) -> None:
"""Setter for :attr:`prereleases`.
:param value: The value to set.
"""
@abc.abstractmethod
def contains(self, item: str, prereleases: Optional[bool] = None) -> bool:
"""
Determines if the given item is contained within this specifier.
"""
@abc.abstractmethod
def filter(
self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None
) -> Iterator[UnparsedVersionVar]:
"""
Takes an iterable of items and filters them so that only items which
are contained within this specifier are allowed in it.
"""
| BaseSpecifier |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/strategies.py | {
"start": 19373,
"end": 19791
} | class ____(LoaderStrategy):
"""Relationship loader that makes no change to the object's state.
Compared to NoLoader, this loader does not initialize the
collection/attribute to empty/none; the usual default LazyLoader will
take effect.
"""
@log.class_logger
@relationships.RelationshipProperty.strategy_for(lazy="noload")
@relationships.RelationshipProperty.strategy_for(lazy=None)
| _DoNothingLoader |
python | ray-project__ray | python/ray/tune/search/searcher.py | {
"start": 520,
"end": 15583
} | class ____:
"""Abstract class for wrapping suggesting algorithms.
Custom algorithms can extend this class easily by overriding the
`suggest` method provide generated parameters for the trials.
Any subclass that implements ``__init__`` must also call the
constructor of this class: ``super(Subclass, self).__init__(...)``.
To track suggestions and their corresponding evaluations, the method
`suggest` will be passed a trial_id, which will be used in
subsequent notifications.
Not all implementations support multi objectives.
Note to Tune developers: If a new searcher is added, please update
`air/_internal/usage.py`.
Args:
metric: The training result objective value attribute. If
list then list of training result objective value attributes
mode: If string One of {min, max}. If list then
list of max and min, determines whether objective is minimizing
or maximizing the metric attribute. Must match type of metric.
.. code-block:: python
class ExampleSearch(Searcher):
def __init__(self, metric="mean_loss", mode="min", **kwargs):
super(ExampleSearch, self).__init__(
metric=metric, mode=mode, **kwargs)
self.optimizer = Optimizer()
self.configurations = {}
def suggest(self, trial_id):
configuration = self.optimizer.query()
self.configurations[trial_id] = configuration
def on_trial_complete(self, trial_id, result, **kwargs):
configuration = self.configurations[trial_id]
if result and self.metric in result:
self.optimizer.update(configuration, result[self.metric])
tuner = tune.Tuner(
trainable_function,
tune_config=tune.TuneConfig(
search_alg=ExampleSearch()
)
)
tuner.fit()
"""
FINISHED = "FINISHED"
CKPT_FILE_TMPL = "searcher-state-{}.pkl"
def __init__(
self,
metric: Optional[str] = None,
mode: Optional[str] = None,
):
tag_searcher(self)
self._metric = metric
self._mode = mode
if not mode or not metric:
# Early return to avoid assertions
return
assert isinstance(
metric, type(mode)
), "metric and mode must be of the same type"
if isinstance(mode, str):
assert mode in ["min", "max"], "if `mode` is a str must be 'min' or 'max'!"
elif isinstance(mode, list):
assert len(mode) == len(metric), "Metric and mode must be the same length"
assert all(
mod in ["min", "max", "obs"] for mod in mode
), "All of mode must be 'min' or 'max' or 'obs'!"
else:
raise ValueError("Mode most either be a list or string")
def set_search_properties(
self, metric: Optional[str], mode: Optional[str], config: Dict, **spec
) -> bool:
"""Pass search properties to searcher.
This method acts as an alternative to instantiating search algorithms
with their own specific search spaces. Instead they can accept a
Tune config through this method. A searcher should return ``True``
if setting the config was successful, or ``False`` if it was
unsuccessful, e.g. when the search space has already been set.
Args:
metric: Metric to optimize
mode: One of ["min", "max"]. Direction to optimize.
config: Tune config dict.
**spec: Any kwargs for forward compatiblity.
Info like Experiment.PUBLIC_KEYS is provided through here.
"""
return False
def on_trial_result(self, trial_id: str, result: Dict) -> None:
"""Optional notification for result during training.
Note that by default, the result dict may include NaNs or
may not include the optimization metric. It is up to the
subclass implementation to preprocess the result to
avoid breaking the optimization process.
Args:
trial_id: A unique string ID for the trial.
result: Dictionary of metrics for current training progress.
Note that the result dict may include NaNs or
may not include the optimization metric. It is up to the
subclass implementation to preprocess the result to
avoid breaking the optimization process.
"""
pass
def on_trial_complete(
self, trial_id: str, result: Optional[Dict] = None, error: bool = False
) -> None:
"""Notification for the completion of trial.
Typically, this method is used for notifying the underlying
optimizer of the result.
Args:
trial_id: A unique string ID for the trial.
result: Dictionary of metrics for current training progress.
Note that the result dict may include NaNs or
may not include the optimization metric. It is up to the
subclass implementation to preprocess the result to
avoid breaking the optimization process. Upon errors, this
may also be None.
error: True if the training process raised an error.
"""
raise NotImplementedError
def suggest(self, trial_id: str) -> Optional[Dict]:
"""Queries the algorithm to retrieve the next set of parameters.
Arguments:
trial_id: Trial ID used for subsequent notifications.
Returns:
dict | FINISHED | None: Configuration for a trial, if possible.
If FINISHED is returned, Tune will be notified that
no more suggestions/configurations will be provided.
If None is returned, Tune will skip the querying of the
searcher for this step.
"""
raise NotImplementedError
def add_evaluated_point(
self,
parameters: Dict,
value: float,
error: bool = False,
pruned: bool = False,
intermediate_values: Optional[List[float]] = None,
):
"""Pass results from a point that has been evaluated separately.
This method allows for information from outside the
suggest - on_trial_complete loop to be passed to the search
algorithm.
This functionality depends on the underlying search algorithm
and may not be always available.
Args:
parameters: Parameters used for the trial.
value: Metric value obtained in the trial.
error: True if the training process raised an error.
pruned: True if trial was pruned.
intermediate_values: List of metric values for
intermediate iterations of the result. None if not
applicable.
"""
raise NotImplementedError
def add_evaluated_trials(
self,
trials_or_analysis: Union["Trial", List["Trial"], "ExperimentAnalysis"],
metric: str,
):
"""Pass results from trials that have been evaluated separately.
This method allows for information from outside the
suggest - on_trial_complete loop to be passed to the search
algorithm.
This functionality depends on the underlying search algorithm
and may not be always available (same as ``add_evaluated_point``.)
Args:
trials_or_analysis: Trials to pass results form to the searcher.
metric: Metric name reported by trials used for
determining the objective value.
"""
if self.add_evaluated_point == Searcher.add_evaluated_point:
raise NotImplementedError
# lazy imports to avoid circular dependencies
from ray.tune.analysis import ExperimentAnalysis
from ray.tune.experiment import Trial
from ray.tune.result import DONE
if isinstance(trials_or_analysis, (list, tuple)):
trials = trials_or_analysis
elif isinstance(trials_or_analysis, Trial):
trials = [trials_or_analysis]
elif isinstance(trials_or_analysis, ExperimentAnalysis):
trials = trials_or_analysis.trials
else:
raise NotImplementedError(
"Expected input to be a `Trial`, a list of `Trial`s, or "
f"`ExperimentAnalysis`, got: {trials_or_analysis}"
)
any_trial_had_metric = False
def trial_to_points(trial: Trial) -> Dict[str, Any]:
nonlocal any_trial_had_metric
has_trial_been_pruned = (
trial.status == Trial.TERMINATED
and not trial.last_result.get(DONE, False)
)
has_trial_finished = (
trial.status == Trial.TERMINATED and trial.last_result.get(DONE, False)
)
if not any_trial_had_metric:
any_trial_had_metric = (
metric in trial.last_result and has_trial_finished
)
if Trial.TERMINATED and metric not in trial.last_result:
return None
return dict(
parameters=trial.config,
value=trial.last_result.get(metric, None),
error=trial.status == Trial.ERROR,
pruned=has_trial_been_pruned,
intermediate_values=None, # we do not save those
)
for trial in trials:
kwargs = trial_to_points(trial)
if kwargs:
self.add_evaluated_point(**kwargs)
if not any_trial_had_metric:
warnings.warn(
"No completed trial returned the specified metric. "
"Make sure the name you have passed is correct. "
)
def save(self, checkpoint_path: str):
"""Save state to path for this search algorithm.
Args:
checkpoint_path: File where the search algorithm
state is saved. This path should be used later when
restoring from file.
Example:
.. code-block:: python
search_alg = Searcher(...)
tuner = tune.Tuner(
cost,
tune_config=tune.TuneConfig(
search_alg=search_alg,
num_samples=5
),
param_space=config
)
results = tuner.fit()
search_alg.save("./my_favorite_path.pkl")
.. versionchanged:: 0.8.7
Save is automatically called by `Tuner().fit()`. You can use
`Tuner().restore()` to restore from an experiment directory
such as `~/ray_results/trainable`.
"""
raise NotImplementedError
def restore(self, checkpoint_path: str):
"""Restore state for this search algorithm
Args:
checkpoint_path: File where the search algorithm
state is saved. This path should be the same
as the one provided to "save".
Example:
.. code-block:: python
search_alg.save("./my_favorite_path.pkl")
search_alg2 = Searcher(...)
search_alg2 = ConcurrencyLimiter(search_alg2, 1)
search_alg2.restore(checkpoint_path)
tuner = tune.Tuner(
cost,
tune_config=tune.TuneConfig(
search_alg=search_alg2,
num_samples=5
),
)
tuner.fit()
"""
raise NotImplementedError
def set_max_concurrency(self, max_concurrent: int) -> bool:
"""Set max concurrent trials this searcher can run.
This method will be called on the wrapped searcher by the
``ConcurrencyLimiter``. It is intended to allow for searchers
which have custom, internal logic handling max concurrent trials
to inherit the value passed to ``ConcurrencyLimiter``.
If this method returns False, it signifies that no special
logic for handling this case is present in the searcher.
Args:
max_concurrent: Number of maximum concurrent trials.
"""
return False
def get_state(self) -> Dict:
raise NotImplementedError
def set_state(self, state: Dict):
raise NotImplementedError
def save_to_dir(self, checkpoint_dir: str, session_str: str = "default"):
"""Automatically saves the given searcher to the checkpoint_dir.
This is automatically used by Tuner().fit() during a Tune job.
Args:
checkpoint_dir: Filepath to experiment dir.
session_str: Unique identifier of the current run
session.
"""
tmp_search_ckpt_path = os.path.join(checkpoint_dir, ".tmp_searcher_ckpt")
success = True
try:
self.save(tmp_search_ckpt_path)
except NotImplementedError:
if log_once("suggest:save_to_dir"):
logger.warning("save not implemented for Searcher. Skipping save.")
success = False
if success and os.path.exists(tmp_search_ckpt_path):
os.replace(
tmp_search_ckpt_path,
os.path.join(checkpoint_dir, self.CKPT_FILE_TMPL.format(session_str)),
)
def restore_from_dir(self, checkpoint_dir: str):
"""Restores the state of a searcher from a given checkpoint_dir.
Typically, you should use this function to restore from an
experiment directory such as `~/ray_results/trainable`.
.. code-block:: python
tuner = tune.Tuner(
cost,
run_config=tune.RunConfig(
name=self.experiment_name,
storage_path="~/my_results",
),
tune_config=tune.TuneConfig(
search_alg=search_alg,
num_samples=5
),
param_space=config
)
tuner.fit()
search_alg2 = Searcher()
search_alg2.restore_from_dir(
os.path.join("~/my_results", self.experiment_name)
"""
pattern = self.CKPT_FILE_TMPL.format("*")
full_paths = glob.glob(os.path.join(checkpoint_dir, pattern))
if not full_paths:
raise RuntimeError(
"Searcher unable to find checkpoint in {}".format(checkpoint_dir)
) # TODO
most_recent_checkpoint = max(full_paths)
self.restore(most_recent_checkpoint)
@property
def metric(self) -> str:
"""The training result objective value attribute."""
return self._metric
@property
def mode(self) -> str:
"""Specifies if minimizing or maximizing the metric."""
return self._mode
@PublicAPI
| Searcher |
python | pyinstaller__pyinstaller | bootloader/waflib/Runner.py | {
"start": 680,
"end": 1486
} | class ____(object):
def __init__(self):
self.lst = []
def __len__(self):
return len(self.lst)
def __iter__(self):
return iter(self.lst)
def __str__(self):
return 'PriorityTasks: [%s]' % '\n '.join(str(x) for x in self.lst)
def clear(self):
self.lst = []
def append(self, task):
heapq.heappush(self.lst, task)
def appendleft(self, task):
heapq.heappush(self.lst, task)
def pop(self):
return heapq.heappop(self.lst)
def extend(self, lst):
if self.lst:
for x in lst:
self.append(x)
else:
if isinstance(lst, list):
self.lst = lst
heapq.heapify(lst)
else:
self.lst = lst.lst
| PriorityTasks |
python | dask__distributed | distributed/comm/core.py | {
"start": 8146,
"end": 8695
} | class ____(Listener):
def __init__(self) -> None:
self.__comms: set[Comm] = set()
async def on_connection(
self, comm: Comm, handshake_overrides: dict[str, Any] | None = None
) -> None:
self.__comms.add(comm)
try:
return await super().on_connection(comm, handshake_overrides)
finally:
self.__comms.discard(comm)
def abort_handshaking_comms(self) -> None:
comms, self.__comms = self.__comms, set()
for comm in comms:
comm.abort()
| BaseListener |
python | allegroai__clearml | clearml/backend_api/services/v2_23/workers.py | {
"start": 90386,
"end": 90963
} | class ____(Response):
"""
Response of workers.unregister endpoint.
"""
_service = "workers"
_action = "unregister"
_version = "2.23"
_schema = {"definitions": {}, "properties": {}, "type": "object"}
response_mapping = {
GetAllRequest: GetAllResponse,
RegisterRequest: RegisterResponse,
UnregisterRequest: UnregisterResponse,
StatusReportRequest: StatusReportResponse,
GetMetricKeysRequest: GetMetricKeysResponse,
GetStatsRequest: GetStatsResponse,
GetActivityReportRequest: GetActivityReportResponse,
}
| UnregisterResponse |
python | numba__numba | numba/tests/test_typeinfer.py | {
"start": 1033,
"end": 2200
} | class ____(unittest.TestCase):
def test_arg_ret_casting(self):
def foo(x):
return x
args = (i32,)
return_type = f32
cfunc = njit(return_type(*args))(foo)
cres = cfunc.overloads[args]
self.assertTrue(isinstance(cfunc(123), float))
self.assertEqual(cres.signature.args, args)
self.assertEqual(cres.signature.return_type, return_type)
def test_arg_ret_mismatch(self):
def foo(x):
return x
args = (types.Array(i32, 1, 'C'),)
return_type = f32
try:
njit(return_type(*args))(foo)
except errors.TypingError as e:
pass
else:
self.fail("Should complain about array casting to float32")
def test_invalid_arg_type_forcing(self):
def foo(iters):
a = range(iters)
return iters
args = (u32,)
return_type = u8
cfunc = njit(return_type(*args))(foo)
cres = cfunc.overloads[args]
typemap = cres.type_annotation.typemap
# Argument "iters" must be uint32
self.assertEqual(typemap['iters'], u32)
| TestArgRetCasting |
python | getsentry__sentry-python | sentry_sdk/integrations/ariadne.py | {
"start": 1081,
"end": 5834
} | class ____(Integration):
identifier = "ariadne"
@staticmethod
def setup_once():
# type: () -> None
version = package_version("ariadne")
_check_minimum_version(AriadneIntegration, version)
ignore_logger("ariadne")
_patch_graphql()
def _patch_graphql():
# type: () -> None
old_parse_query = ariadne_graphql.parse_query
old_handle_errors = ariadne_graphql.handle_graphql_errors
old_handle_query_result = ariadne_graphql.handle_query_result
@ensure_integration_enabled(AriadneIntegration, old_parse_query)
def _sentry_patched_parse_query(context_value, query_parser, data):
# type: (Optional[Any], Optional[QueryParser], Any) -> DocumentNode
event_processor = _make_request_event_processor(data)
sentry_sdk.get_isolation_scope().add_event_processor(event_processor)
result = old_parse_query(context_value, query_parser, data)
return result
@ensure_integration_enabled(AriadneIntegration, old_handle_errors)
def _sentry_patched_handle_graphql_errors(errors, *args, **kwargs):
# type: (List[GraphQLError], Any, Any) -> GraphQLResult
result = old_handle_errors(errors, *args, **kwargs)
event_processor = _make_response_event_processor(result[1])
sentry_sdk.get_isolation_scope().add_event_processor(event_processor)
client = get_client()
if client.is_active():
with capture_internal_exceptions():
for error in errors:
event, hint = event_from_exception(
error,
client_options=client.options,
mechanism={
"type": AriadneIntegration.identifier,
"handled": False,
},
)
capture_event(event, hint=hint)
return result
@ensure_integration_enabled(AriadneIntegration, old_handle_query_result)
def _sentry_patched_handle_query_result(result, *args, **kwargs):
# type: (Any, Any, Any) -> GraphQLResult
query_result = old_handle_query_result(result, *args, **kwargs)
event_processor = _make_response_event_processor(query_result[1])
sentry_sdk.get_isolation_scope().add_event_processor(event_processor)
client = get_client()
if client.is_active():
with capture_internal_exceptions():
for error in result.errors or []:
event, hint = event_from_exception(
error,
client_options=client.options,
mechanism={
"type": AriadneIntegration.identifier,
"handled": False,
},
)
capture_event(event, hint=hint)
return query_result
ariadne_graphql.parse_query = _sentry_patched_parse_query # type: ignore
ariadne_graphql.handle_graphql_errors = _sentry_patched_handle_graphql_errors # type: ignore
ariadne_graphql.handle_query_result = _sentry_patched_handle_query_result # type: ignore
def _make_request_event_processor(data):
# type: (GraphQLSchema) -> EventProcessor
"""Add request data and api_target to events."""
def inner(event, hint):
# type: (Event, dict[str, Any]) -> Event
if not isinstance(data, dict):
return event
with capture_internal_exceptions():
try:
content_length = int(
(data.get("headers") or {}).get("Content-Length", 0)
)
except (TypeError, ValueError):
return event
if should_send_default_pii() and request_body_within_bounds(
get_client(), content_length
):
request_info = event.setdefault("request", {})
request_info["api_target"] = "graphql"
request_info["data"] = data
elif event.get("request", {}).get("data"):
del event["request"]["data"]
return event
return inner
def _make_response_event_processor(response):
# type: (Dict[str, Any]) -> EventProcessor
"""Add response data to the event's response context."""
def inner(event, hint):
# type: (Event, dict[str, Any]) -> Event
with capture_internal_exceptions():
if should_send_default_pii() and response.get("errors"):
contexts = event.setdefault("contexts", {})
contexts["response"] = {
"data": response,
}
return event
return inner
| AriadneIntegration |
python | getsentry__sentry | tests/sentry/web/frontend/test_auth_channel_login.py | {
"start": 2932,
"end": 3838
} | class ____(TestCase):
def create_auth_provider(self, partner_org_id, sentry_org_id):
config_data = FlyOAuth2Provider.build_config(resource={"id": partner_org_id})
AuthProvider.objects.create(
organization_id=sentry_org_id, provider="fly-non-partner", config=config_data
)
def setUp(self) -> None:
self.organization = self.create_organization(name="test org", owner=self.user)
self.create_auth_provider("fly-test-org", self.organization.id)
self.path = reverse("sentry-auth-channel", args=["fly", "fly-test-org"])
def test_with_next_uri(self) -> None:
self.login_as(self.user)
response = self.client.get(self.path + "?next=/projects/", follow=True)
assert response.status_code == 200
assert response.redirect_chain == [
("/projects/", 302),
]
| AuthNonPartnerOrganizationChannelLoginTest |
python | PrefectHQ__prefect | src/prefect/server/schemas/responses.py | {
"start": 21641,
"end": 21781
} | class ____(BaseModel):
results: list[FlowRunResponse]
count: int
limit: int
pages: int
page: int
| FlowRunPaginationResponse |
python | openai__openai-python | src/openai/types/responses/response_output_refusal.py | {
"start": 198,
"end": 388
} | class ____(BaseModel):
refusal: str
"""The refusal explanation from the model."""
type: Literal["refusal"]
"""The type of the refusal. Always `refusal`."""
| ResponseOutputRefusal |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1405396,
"end": 1405994
} | class ____(sgqlc.types.Type, Node, AuditEntry, RepositoryAuditEntryData, OrganizationAuditEntryData):
"""Audit log entry for a repo.change_merge_setting event."""
__schema__ = github_schema
__field_names__ = ("is_enabled", "merge_type")
is_enabled = sgqlc.types.Field(Boolean, graphql_name="isEnabled")
"""Whether the change was to enable (true) or disable (false) the
merge type
"""
merge_type = sgqlc.types.Field(RepoChangeMergeSettingAuditEntryMergeType, graphql_name="mergeType")
"""The merge method affected by the change"""
| RepoChangeMergeSettingAuditEntry |
python | doocs__leetcode | solution/1100-1199/1185.Day of the Week/Solution.py | {
"start": 0,
"end": 146
} | class ____:
def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
return datetime.date(year, month, day).strftime('%A')
| Solution |
python | PrefectHQ__prefect | tests/cli/test_work_queues.py | {
"start": 343,
"end": 3056
} | class ____:
def test_create_work_queue(self):
invoke_and_assert(
command="work-queue create q-name",
expected_output_contains=[
"Created work queue with properties:",
"name - 'q-name'",
],
expected_code=0,
)
def test_create_work_queue_with_limit(self):
invoke_and_assert(
command="work-queue create q-name -l 3",
expected_output_contains=[
"Created work queue with properties:",
"concurrency limit - 3",
],
expected_code=0,
)
async def test_create_work_queue_with_pool(
self,
prefect_client,
work_pool,
):
queue_name = "q-name"
await run_sync_in_worker_thread(
invoke_and_assert,
command=f"work-queue create {queue_name} -p {work_pool.name}",
expected_code=0,
)
queue = await read_queue(
prefect_client,
name=queue_name,
pool=work_pool.name,
)
assert queue.work_pool_id == work_pool.id
assert queue.name == queue_name
async def test_create_work_queue_with_priority(
self,
prefect_client,
work_pool,
):
queue_name = "q-name"
queue_priority = 1
await run_sync_in_worker_thread(
invoke_and_assert,
command=(
f"work-queue create {queue_name} -p {work_pool.name} -q"
f" {queue_priority}"
),
expected_code=0,
)
queue = await read_queue(
prefect_client,
name=queue_name,
pool=work_pool.name,
)
assert queue.work_pool_id == work_pool.id
assert queue.name == queue_name
assert queue.priority == queue_priority
async def test_create_work_queue_without_pool_uses_default_pool(
self, prefect_client
):
queue_name = "q-name"
await run_sync_in_worker_thread(
invoke_and_assert,
command=f"work-queue create {queue_name}",
expected_code=0,
)
queue = await read_queue(
prefect_client,
name=queue_name,
)
assert queue.name == queue_name
assert queue.work_pool_id is not None
def test_create_work_queue_with_bad_pool_name(
self,
prefect_client,
):
queue_name = "q-name"
invoke_and_assert(
command=f"work-queue create {queue_name} -p bad-pool",
expected_code=1,
)
assert "Work pool with name: 'bad-pool' not found."
| TestCreateWorkQueue |
python | sphinx-doc__sphinx | tests/test_markup/test_markup.py | {
"start": 2503,
"end": 2583
} | class ____(HTML5Translator, ForgivingTranslator):
pass
| ForgivingHTMLTranslator |
python | numba__numba | numba/core/ir.py | {
"start": 51901,
"end": 52254
} | class ____(EqualityCheckMixin):
_singleton = None
def __new__(cls):
obj = cls._singleton
if obj is not None:
return obj
else:
obj = object.__new__(cls)
cls._singleton = obj
return obj
def __repr__(self):
return "Undefined"
UNDEFINED = UndefinedType()
| UndefinedType |
python | Lightning-AI__lightning | src/lightning/pytorch/plugins/precision/bitsandbytes.py | {
"start": 755,
"end": 1592
} | class ____(Precision, FabricBNBPrecision):
"""Plugin for quantizing weights with `bitsandbytes <https://github.com/bitsandbytes-foundation/bitsandbytes>`__.
.. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature.
.. note::
The optimizer is not automatically replaced with ``bitsandbytes.optim.Adam8bit`` or equivalent 8-bit optimizers.
Args:
mode: The quantization mode to use.
dtype: The compute dtype to use.
ignore_modules: The submodules whose Linear layers should not be replaced, for example. ``{"lm_head"}``.
This might be desirable for numerical stability. The string will be checked in as a prefix, so a value like
"transformer.blocks" will ignore all linear layers in all of the transformer blocks.
"""
| BitsandbytesPrecision |
python | dask__dask | dask/dataframe/dask_expr/_indexing.py | {
"start": 997,
"end": 1066
} | class ____:
def __init__(self, obj):
self.obj = obj
| Indexer |
python | getsentry__sentry | tests/sentry/seer/fetch_issues/test_by_error_type.py | {
"start": 408,
"end": 21410
} | class ____(APITestCase, SnubaTestCase):
def test_simple(self) -> None:
release = self.create_release(project=self.project, version="1.0.0")
repo = self.create_repo(
project=self.project,
name="getsentry/sentryA",
provider="integrations:github",
external_id="1",
)
self.create_code_mapping(project=self.project, repo=repo)
data = load_data("python", timestamp=before_now(minutes=1))
event = self.store_event(
data={
**data,
"release": release.version,
"exception": {
"values": [
{"type": "KeyError", "value": "This a bad error", "data": {"values": []}}
]
},
},
project_id=self.project.id,
)
group = event.group
group.message = "Message to the error"
assert group is not None
group.save()
# Assert only 1 Group object in the database
assert Group.objects.count() == 1
group = Group.objects.get()
# Assert that KeyError matched the exception type
seer_response = fetch_issues(
organization_id=self.organization.id,
provider="integrations:github",
external_id="1",
exception_type="KeyError",
)
assert "error" not in seer_response
assert seer_response["issues"][0] == group.id
full_issues = seer_response["issues_full"][0]
assert full_issues["metadata"]["filename"] == "raven/scripts/runner.py"
assert full_issues["metadata"]["function"] == "main"
assert full_issues["metadata"]["in_app_frame_mix"] == "system-only"
assert full_issues["metadata"]["initial_priority"] == 75
assert full_issues["metadata"]["type"] == "KeyError"
assert full_issues["metadata"]["value"] == "This a bad error"
assert full_issues["message"] == "Message to the error"
assert full_issues["title"] == "KeyError: This a bad error"
# Assert that ValueError did not match the exception type
seer_response = fetch_issues(
organization_id=self.organization.id,
provider="integrations:github",
external_id="1",
exception_type="ValueError",
)
assert seer_response == {"issues": [], "issues_full": []}
# Assert latest event is returned
issue_details = utils.get_latest_issue_event(group.id, self.organization.id)
assert issue_details["id"] == group.id
assert issue_details["title"] == "KeyError: This a bad error"
assert len(issue_details["events"]) == 1
assert "entries" in issue_details["events"][0]
def test_multiple_projects(self) -> None:
release = self.create_release(project=self.project, version="1.0.0")
# Part of the queried results
queried_repo = self.create_repo(
project=self.project,
name="getsentry/sentryA",
provider="integrations:github",
external_id="1",
)
self.create_code_mapping(project=self.project, repo=queried_repo)
data = load_data("python", timestamp=before_now(minutes=1))
event = self.store_event(
data={
**data,
"release": release.version,
"exception": {
"values": [
{"type": "KeyError", "value": "This a bad error", "data": {"values": []}}
]
},
},
project_id=self.project.id,
)
group_1 = event.group
group_1.save()
# Part of the queried results
project_2 = self.create_project(
name="Project2", slug="Project2", teams=[self.team], fire_project_created=True
)
self.create_code_mapping(project=project_2, repo=queried_repo)
data = load_data("python", timestamp=before_now(minutes=2))
event = self.store_event(
data={
**data,
"release": release.version,
"exception": {"values": [{"type": "KeyError", "data": {"values": []}}]},
},
project_id=project_2.id,
)
group_2 = event.group
group_2.save()
# NOT part of the queried results
organization_3 = self.create_organization(name="Organization3")
team_3 = self.create_team(organization=organization_3)
project_3 = self.create_project(
name="Project3", slug="Project3", teams=[team_3], fire_project_created=True
)
not_queried_repo = self.create_repo(
project=project_3,
name="getsentry/sentryB",
provider="integrations:github",
external_id="2",
)
self.create_code_mapping(project=project_3, repo=not_queried_repo)
data = load_data("python", timestamp=before_now(minutes=3))
event = self.store_event(
data={
**data,
"release": release.version,
"exception": {
"values": [
{"type": "KeyError", "value": "This a bad error", "data": {"values": []}}
]
},
},
project_id=project_3.id,
)
group_3 = event.group
group_3.save()
# Assert there's 3 Group objects in the database
assert Group.objects.count() == 3
# Assert there's 2 Group objects from the results
seer_response = fetch_issues(
organization_id=self.organization.id,
provider="integrations:github",
external_id="1",
exception_type="KeyError",
)
assert "error" not in seer_response
assert {group_1.id, group_2.id} == set(seer_response["issues"])
assert group_3.id not in seer_response["issues"]
assert group_3.id not in [int(issue["id"]) for issue in seer_response["issues_full"]]
# Assert latest event is returned
issue_details = utils.get_latest_issue_event(group_1.id, self.organization.id)
assert issue_details["id"] == group_1.id
assert issue_details["title"] == "KeyError: This a bad error"
assert len(issue_details["events"]) == 1
assert "entries" in issue_details["events"][0]
def test_last_seen_filter(self) -> None:
release = self.create_release(project=self.project, version="1.0.0")
repo = self.create_repo(
project=self.project,
name="getsentry/sentryA",
provider="integrations:github",
external_id="1",
)
self.create_code_mapping(project=self.project, repo=repo)
data = load_data("python", timestamp=before_now(minutes=1 * 60 * 24 * 10)) # 10 days ago
event = self.store_event(
data={
**data,
"release": release.version,
"exception": {
"values": [
{"type": "KeyError", "value": "This a bad error", "data": {"values": []}}
]
},
},
project_id=self.project.id,
)
group = event.group
assert group is not None
group.save()
# Assert only 1 Group object in the database
assert Group.objects.count() == 1
group = Group.objects.get()
# Assert that KeyError matched the exception type (within default 90 days)
seer_response = fetch_issues(
organization_id=self.organization.id,
provider="integrations:github",
external_id="1",
exception_type="KeyError",
)
assert "error" not in seer_response
assert seer_response["issues"] == [group.id]
assert seer_response["issues_full"][0]["id"] == str(group.id)
assert seer_response["issues_full"][0]["title"] == "KeyError: This a bad error"
# Assert that KeyError did not match when filtered to 9 days
seer_response = fetch_issues(
organization_id=self.organization.id,
provider="integrations:github",
external_id="1",
exception_type="KeyError",
num_days_ago=9,
)
assert seer_response == {"issues": [], "issues_full": []}
# Assert latest event is returned
issue_details = utils.get_latest_issue_event(group.id, self.organization.id)
assert issue_details["id"] == group.id
assert issue_details["title"] == "KeyError: This a bad error"
assert len(issue_details["events"]) == 1
assert "entries" in issue_details["events"][0]
def test_multiple_exception_types(self) -> None:
release = self.create_release(project=self.project, version="1.0.0")
repo = self.create_repo(
project=self.project,
name="getsentry/sentryA",
provider="integrations:github",
external_id="1",
)
self.create_code_mapping(project=self.project, repo=repo)
data = load_data("python", timestamp=before_now(minutes=1 * 60 * 24 * 10)) # 10 days ago
event = self.store_event(
data={
**data,
"release": release.version,
"exception": {
"values": [
{"type": "KeyError", "value": "voodoo curse", "data": {"values": []}}
]
},
},
project_id=self.project.id,
)
group_1 = event.group
assert group_1 is not None
group_1.save()
data = load_data("python", timestamp=before_now(minutes=1 * 60 * 24 * 10)) # 10 days ago
event = self.store_event(
data={
**data,
"release": release.version,
"exception": {
"values": [
{"type": "ValueError", "value": "This a bad error", "data": {"values": []}}
]
},
},
project_id=self.project.id,
)
group_2 = event.group
assert group_2 is not None
group_2.save()
# Assert only 2 Group objects in the database
assert Group.objects.count() == 2
# Assert that KeyError matched the exception type
seer_response = fetch_issues(
organization_id=self.organization.id,
provider="integrations:github",
external_id="1",
exception_type="KeyError",
)
assert "error" not in seer_response
assert seer_response["issues"] == [group_1.id]
assert len(seer_response["issues_full"]) == 1
assert seer_response["issues_full"][0]["id"] == str(group_1.id)
assert seer_response["issues_full"][0]["title"] == "KeyError: voodoo curse"
# Assert that ValueError matched the exception type
seer_response = fetch_issues(
organization_id=self.organization.id,
provider="integrations:github",
external_id="1",
exception_type="ValueError",
)
assert "error" not in seer_response
assert seer_response["issues"] == [group_2.id]
assert len(seer_response["issues_full"]) == 1
assert seer_response["issues_full"][0]["id"] == str(group_2.id)
assert seer_response["issues_full"][0]["title"] == "ValueError: This a bad error"
def test_fetch_issues_from_repo_projects_returns_groups(self) -> None:
"""Test that _fetch_issues_from_repo_projects returns a list of Group objects."""
release = self.create_release(project=self.project, version="1.0.0")
repo = self.create_repo(
project=self.project,
name="getsentry/sentryA",
provider="integrations:github",
external_id="1",
)
self.create_code_mapping(project=self.project, repo=repo)
data = load_data("python", timestamp=before_now(minutes=1))
event = self.store_event(
data={
**data,
"release": release.version,
"exception": {
"values": [
{"type": "KeyError", "value": "This a bad error", "data": {"values": []}}
]
},
},
project_id=self.project.id,
)
expected_group = event.group
assert expected_group is not None
expected_group.save()
# Get repo projects
repo_projects = get_repo_and_projects(
organization_id=self.organization.id, provider="integrations:github", external_id="1"
)
# Test the internal function directly
groups = _fetch_issues_from_repo_projects(
repo_projects=repo_projects, exception_type="KeyError"
)
# Verify it returns a list of Group objects
assert isinstance(groups, list)
assert len(groups) == 1
assert isinstance(groups[0], Group)
assert groups[0].id == expected_group.id
def test_fetch_issues_from_repo_projects_empty_result(self) -> None:
"""Test that _fetch_issues_from_repo_projects returns empty list when no matches."""
repo = self.create_repo(
project=self.project,
name="getsentry/sentryA",
provider="integrations:github",
external_id="1",
)
self.create_code_mapping(project=self.project, repo=repo)
# Get repo projects but don't create any matching events
repo_projects = get_repo_and_projects(
organization_id=self.organization.id, provider="integrations:github", external_id="1"
)
# Test the internal function directly
results = _fetch_issues_from_repo_projects(
repo_projects=repo_projects, exception_type="NonExistentError"
)
# Verify it returns an empty list
assert isinstance(results, list)
assert len(results) == 0
def _setup_test_environment(
self, exception_type: str, exception_value: str = "Test error"
) -> Group:
"""Helper to set up test environment with a group containing the specified exception type."""
release = self.create_release(project=self.project, version="1.0.0")
repo = self.create_repo(
project=self.project,
name="getsentry/sentryA",
provider="integrations:github",
external_id="1",
)
self.create_code_mapping(project=self.project, repo=repo)
data = load_data("python", timestamp=before_now(minutes=1))
event = self.store_event(
data={
**data,
"release": release.version,
"exception": {
"values": [
{"type": exception_type, "value": exception_value, "data": {"values": []}}
]
},
},
project_id=self.project.id,
)
group = event.group
assert group is not None
group.save()
return group
def _assert_exception_type_matches(
self, search_exception_type: str, expected_group: Group
) -> None:
"""Helper to assert that a search exception type returns the expected group."""
seer_response = fetch_issues(
organization_id=self.organization.id,
provider="integrations:github",
external_id="1",
exception_type=search_exception_type,
)
assert "error" not in seer_response
assert seer_response["issues"] == [expected_group.id]
assert len(seer_response["issues_full"]) == 1
def _test_exception_type_variants(
self, stored_exception_type: str, search_variants: list[str]
) -> None:
"""Helper to test multiple search variants against a stored exception type."""
group = self._setup_test_environment(stored_exception_type)
for search_exception_type in search_variants:
with self.subTest(search_exception_type=search_exception_type):
self._assert_exception_type_matches(search_exception_type, group)
def test_case_insensitive_matching(self) -> None:
"""Test that exception type matching is case insensitive."""
search_variants = ["TypeError", "typeerror", "TYPEERROR", "TypeERROR", "tYpEeRrOr"]
self._test_exception_type_variants("TypeError", search_variants)
def test_normalized_matching_spaces(self) -> None:
"""Test that exception type matching normalizes spaces and special characters."""
search_variants = [
"Runtime Error",
"RuntimeError",
"runtime error",
"runtimeerror",
"RUNTIME ERROR",
"RUNTIMEERROR",
"runtime_error",
"runtime-error",
]
self._test_exception_type_variants("Runtime Error", search_variants)
def test_normalized_matching_special_characters(self) -> None:
"""Test that exception type matching normalizes various special characters."""
search_variants = [
"HTTP-404-Error",
"HTTP 404 Error",
"HTTP_404_Error",
"HTTP.404.Error",
"HTTP404Error",
"http404error",
"HTTP 404 Error", # multiple spaces
"HTTP__404__Error", # multiple underscores
]
self._test_exception_type_variants("HTTP-404-Error", search_variants)
def test_normalized_matching_multiple_groups(self) -> None:
"""Test normalized matching works correctly with multiple different exception types."""
release = self.create_release(project=self.project, version="1.0.0")
repo = self.create_repo(
project=self.project,
name="getsentry/sentryA",
provider="integrations:github",
external_id="1",
)
self.create_code_mapping(project=self.project, repo=repo)
# Create first group with "Value Error"
data1 = load_data("python", timestamp=before_now(minutes=1))
event1 = self.store_event(
data={
**data1,
"release": release.version,
"exception": {
"values": [
{"type": "Value Error", "value": "Bad value", "data": {"values": []}}
]
},
},
project_id=self.project.id,
)
group1 = event1.group
assert group1 is not None
group1.save()
# Create second group with "Type-Error"
data2 = load_data("python", timestamp=before_now(minutes=2))
event2 = self.store_event(
data={
**data2,
"release": release.version,
"exception": {
"values": [{"type": "Type-Error", "value": "Bad type", "data": {"values": []}}]
},
},
project_id=self.project.id,
)
group2 = event2.group
assert group2 is not None
group2.save()
# Test that "valueerror" matches only the first group
seer_response = fetch_issues(
organization_id=self.organization.id,
provider="integrations:github",
external_id="1",
exception_type="valueerror",
)
assert "error" not in seer_response
assert seer_response["issues"] == [group1.id]
assert len(seer_response["issues_full"]) == 1
# Test that "type error" matches only the second group
seer_response = fetch_issues(
organization_id=self.organization.id,
provider="integrations:github",
external_id="1",
exception_type="type error",
)
assert "error" not in seer_response
assert seer_response["issues"] == [group2.id]
assert len(seer_response["issues_full"]) == 1
# Test that "runtimeerror" matches neither
seer_response = fetch_issues(
organization_id=self.organization.id,
provider="integrations:github",
external_id="1",
exception_type="runtimeerror",
)
assert seer_response == {"issues": [], "issues_full": []}
def test_unicode_normalization_consistency(self) -> None:
"""Test that Unicode characters are handled consistently between Python and SQL."""
search_variants = [
"ValueError测试", # Same Unicode as stored
"ValueError", # Just ASCII part
"ValueError测试αβ", # Different Unicode chars that normalize to same ASCII
]
self._test_exception_type_variants("ValueError测试", search_variants)
| TestFetchIssuesByErrorType |
python | numba__llvmlite | llvmlite/ir/types.py | {
"start": 15625,
"end": 17716
} | class ____(Aggregate):
"""
The base type for heterogenous struct types.
"""
_packed = False
@property
def packed(self):
"""
A boolean attribute that indicates whether the structure uses
packed layout.
"""
return self._packed
@packed.setter
def packed(self, val):
self._packed = bool(val)
def __len__(self):
assert self.elements is not None
return len(self.elements)
def __iter__(self):
assert self.elements is not None
return iter(self.elements)
@property
def is_opaque(self):
return self.elements is None
def structure_repr(self):
"""
Return the LLVM IR for the structure representation
"""
ret = '{%s}' % ', '.join([str(x) for x in self.elements])
return self._wrap_packed(ret)
def format_constant(self, value):
itemstring = ", " .join(["{0} {1}".format(x.type, x.get_reference())
for x in value])
ret = "{{{0}}}".format(itemstring)
return self._wrap_packed(ret)
def gep(self, i):
"""
Resolve the type of the i-th element (for getelementptr lookups).
*i* needs to be a LLVM constant, so that the type can be determined
at compile-time.
"""
if not isinstance(i.type, IntType):
raise TypeError(i.type)
return self.elements[i.constant]
def _wrap_packed(self, textrepr):
"""
Internal helper to wrap textual repr of struct type into packed struct
"""
if self.packed:
return '<{}>'.format(textrepr)
else:
return textrepr
@classmethod
def from_llvm(cls, typeref, ir_ctx):
"""
Create from a llvmlite.binding.TypeRef
"""
if typeref.is_literal_struct:
elems = [el.as_ir(ir_ctx=ir_ctx) for el in typeref.elements]
return cls(elems, typeref.is_packed_struct)
else:
return ir_ctx.get_identified_type(typeref.name)
| BaseStructType |
python | joke2k__faker | tests/providers/test_currency.py | {
"start": 15517,
"end": 15942
} | class ____:
"""Test pt_BR currency provider"""
num_samples = 100
@classmethod
def setup_class(cls):
from faker.providers.currency.pt_BR import Provider as PtBrCurrencyProvider
cls.provider = PtBrCurrencyProvider
def test_pricetag(self, faker, num_samples):
for _ in range(num_samples):
pricetag = faker.pricetag()
assert isinstance(pricetag, str)
| TestPtBr |
python | sympy__sympy | sympy/sets/sets.py | {
"start": 37855,
"end": 44098
} | class ____(Set, LatticeOp):
"""
Represents a union of sets as a :class:`Set`.
Parameters
==========
args : iterable[Set]
The input sets to be united.
evaluate : bool, optional
If True (default from sympy.core.parameters.global_parameters.evaluate),
the constructor simplifies the union.
Examples
========
>>> from sympy import Union, Interval
>>> Union(Interval(1, 2), Interval(3, 4))
Union(Interval(1, 2), Interval(3, 4))
The Union constructor will always try to merge overlapping intervals,
if possible. For example:
>>> Union(Interval(1, 2), Interval(2, 3))
Interval(1, 3)
See Also
========
Intersection
References
==========
.. [1] https://en.wikipedia.org/wiki/Union_%28set_theory%29
"""
is_Union = True
@property
def identity(self):
return S.EmptySet
@property
def zero(self):
return S.UniversalSet
def __new__(cls, *args, **kwargs):
evaluate = kwargs.get('evaluate', global_parameters.evaluate)
# flatten inputs to merge intersections and iterables
args = _sympify(args)
# Reduce sets using known rules
if evaluate:
args = list(cls._new_args_filter(args))
return simplify_union(args)
args = list(ordered(args, Set._infimum_key))
obj = Basic.__new__(cls, *args)
obj._argset = frozenset(args)
return obj
@property
def args(self):
return self._args
def _complement(self, universe):
# DeMorgan's Law
return Intersection(s.complement(universe) for s in self.args)
@property
def _inf(self):
# We use Min so that sup is meaningful in combination with symbolic
# interval end points.
return Min(*[set.inf for set in self.args])
@property
def _sup(self):
# We use Max so that sup is meaningful in combination with symbolic
# end points.
return Max(*[set.sup for set in self.args])
@property
def is_empty(self):
return fuzzy_and(set.is_empty for set in self.args)
@property
def is_finite_set(self):
return fuzzy_and(set.is_finite_set for set in self.args)
@property
def _measure(self):
# Measure of a union is the sum of the measures of the sets minus
# the sum of their pairwise intersections plus the sum of their
# triple-wise intersections minus ... etc...
# Sets is a collection of intersections and a set of elementary
# sets which made up those intersections (called "sos" for set of sets)
# An example element might of this list might be:
# ( {A,B,C}, A.intersect(B).intersect(C) )
# Start with just elementary sets ( ({A}, A), ({B}, B), ... )
# Then get and subtract ( ({A,B}, (A int B), ... ) while non-zero
sets = [(FiniteSet(s), s) for s in self.args]
measure = 0
parity = 1
while sets:
# Add up the measure of these sets and add or subtract it to total
measure += parity * sum(inter.measure for sos, inter in sets)
# For each intersection in sets, compute the intersection with every
# other set not already part of the intersection.
sets = ((sos + FiniteSet(newset), newset.intersect(intersection))
for sos, intersection in sets for newset in self.args
if newset not in sos)
# Clear out sets with no measure
sets = [(sos, inter) for sos, inter in sets if inter.measure != 0]
# Clear out duplicates
sos_list = []
sets_list = []
for _set in sets:
if _set[0] in sos_list:
continue
else:
sos_list.append(_set[0])
sets_list.append(_set)
sets = sets_list
# Flip Parity - next time subtract/add if we added/subtracted here
parity *= -1
return measure
def _kind(self):
kinds = tuple(arg.kind for arg in self.args if arg is not S.EmptySet)
if not kinds:
return SetKind()
elif all(i == kinds[0] for i in kinds):
return kinds[0]
else:
return SetKind(UndefinedKind)
@property
def _boundary(self):
def boundary_of_set(i):
""" The boundary of set i minus interior of all other sets """
b = self.args[i].boundary
for j, a in enumerate(self.args):
if j != i:
b = b - a.interior
return b
return Union(*map(boundary_of_set, range(len(self.args))))
def _contains(self, other):
return Or(*[s.contains(other) for s in self.args])
def _eval_is_subset(self, other):
return fuzzy_and(arg.is_subset(other) for arg in self.args)
def _eval_is_superset(self, other):
if fuzzy_or(arg.is_superset(other) for arg in self.args):
return True
def as_relational(self, symbol):
"""Rewrite a Union in terms of equalities and logic operators. """
if (len(self.args) == 2 and
all(isinstance(i, Interval) for i in self.args)):
# optimization to give 3 args as (x > 1) & (x < 5) & Ne(x, 3)
# instead of as 4, ((1 <= x) & (x < 3)) | ((x <= 5) & (3 < x))
# XXX: This should be ideally be improved to handle any number of
# intervals and also not to assume that the intervals are in any
# particular sorted order.
a, b = self.args
if a.sup == b.inf and a.right_open and b.left_open:
mincond = symbol > a.inf if a.left_open else symbol >= a.inf
maxcond = symbol < b.sup if b.right_open else symbol <= b.sup
necond = Ne(symbol, a.sup)
return And(necond, mincond, maxcond)
return Or(*[i.as_relational(symbol) for i in self.args])
@property
def is_iterable(self):
return all(arg.is_iterable for arg in self.args)
def __iter__(self):
return roundrobin(*(iter(arg) for arg in self.args))
| Union |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/elements.py | {
"start": 113710,
"end": 116539
} | class ____(ColumnElement[_T]):
"""Represent a ``CASE`` expression.
:class:`.Case` is produced using the :func:`.case` factory function,
as in::
from sqlalchemy import case
stmt = select(users_table).where(
case(
(users_table.c.name == "wendy", "W"),
(users_table.c.name == "jack", "J"),
else_="E",
)
)
Details on :class:`.Case` usage is at :func:`.case`.
.. seealso::
:func:`.case`
"""
__visit_name__ = "case"
_traverse_internals: _TraverseInternalsType = [
("value", InternalTraversal.dp_clauseelement),
("whens", InternalTraversal.dp_clauseelement_tuples),
("else_", InternalTraversal.dp_clauseelement),
]
# for case(), the type is derived from the whens. so for the moment
# users would have to cast() the case to get a specific type
whens: List[typing_Tuple[ColumnElement[bool], ColumnElement[_T]]]
else_: Optional[ColumnElement[_T]]
value: Optional[ColumnElement[Any]]
def __init__(
self,
*whens: Union[
typing_Tuple[_ColumnExpressionArgument[bool], Any],
Mapping[Any, Any],
],
value: Optional[Any] = None,
else_: Optional[Any] = None,
):
new_whens: Iterable[Any] = coercions._expression_collection_was_a_list(
"whens", "case", whens
)
try:
new_whens = util.dictlike_iteritems(new_whens)
except TypeError:
pass
self.whens = [
(
coercions.expect(
roles.ExpressionElementRole,
c,
apply_propagate_attrs=self,
).self_group(),
coercions.expect(roles.ExpressionElementRole, r),
)
for (c, r) in new_whens
]
if value is None:
self.value = None
else:
self.value = coercions.expect(roles.ExpressionElementRole, value)
if else_ is not None:
self.else_ = coercions.expect(roles.ExpressionElementRole, else_)
else:
self.else_ = None
type_ = next(
(
then.type
# Iterate `whens` in reverse to match previous behaviour
# where type of final element took priority
for *_, then in reversed(self.whens)
if not then.type._isnull
),
self.else_.type if self.else_ is not None else type_api.NULLTYPE,
)
self.type = cast(_T, type_)
@util.ro_non_memoized_property
def _from_objects(self) -> List[FromClause]:
return list(
itertools.chain(*[x._from_objects for x in self.get_children()])
)
| Case |
python | skorch-dev__skorch | skorch/callbacks/logging.py | {
"start": 34232,
"end": 40915
} | class ____(Callback):
"""Logs results from history and artifact to Mlflow
"MLflow is an open source platform for managing
the end-to-end machine learning lifecycle" (:doc:`mlflow:index`)
Use this callback to automatically log your metrics
and create/log artifacts to mlflow.
The best way to log additional information is to log directly to the
experiment object or subclass the ``on_*`` methods.
To use this logger, you first have to install Mlflow:
.. code-block::
$ python -m pip install mlflow
Examples
--------
Mlflow :doc:`fluent API <mlflow:python_api/mlflow>`:
>>> import mlflow
>>> net = NeuralNetClassifier(net, callbacks=[MLflowLogger()])
>>> with mlflow.start_run():
... net.fit(X, y)
Custom :py:class:`run <mlflow.entities.Run>` and
:py:class:`client <mlflow.tracking.MlflowClient>`:
>>> from mlflow.tracking import MlflowClient
>>> client = MlflowClient()
>>> experiment = client.get_experiment_by_name('Default')
>>> run = client.create_run(experiment.experiment_id)
>>> net = NeuralNetClassifier(..., callbacks=[MlflowLogger(run, client)])
>>> net.fit(X, y)
Parameters
----------
run : mlflow.entities.Run (default=None)
Instantiated :py:class:`mlflow.entities.Run` class.
By default (if set to ``None``),
:py:func:`mlflow.active_run` is used to get the current run.
client : mlflow.tracking.MlflowClient (default=None)
Instantiated :py:class:`mlflow.tracking.MlflowClient` class.
By default (if set to ``None``),
``MlflowClient()`` is used, which by default has:
- the tracking URI set by :py:func:`mlflow.set_tracking_uri`
- the registry URI set by :py:func:`mlflow.set_registry_uri`
create_artifact : bool (default=True)
Whether to create artifacts for the network's
params, optimizer, criterion and history.
See :ref:`save_load`
terminate_after_train : bool (default=True)
Whether to terminate the ``Run`` object once training finishes.
log_on_batch_end : bool (default=False)
Whether to log loss and other metrics on batch level.
log_on_epoch_end : bool (default=True)
Whether to log loss and other metrics on epoch level.
batch_suffix : str (default=None)
A string that will be appended to all logged keys. By default (if set to
``None``) ``'_batch'`` is used if batch and epoch logging are both enabled
and no suffix is used otherwise.
epoch_suffix : str (default=None)
A string that will be appended to all logged keys. By default (if set to
``None``) ``'_epoch'`` is used if batch and epoch logging are both enabled
and no suffix is used otherwise.
keys_ignored : str or list of str (default=None)
Key or list of keys that should not be logged to Mlflow. Note that in
addition to the keys provided by the user, keys such as those starting
with ``'event_'`` or ending on ``'_best'`` are ignored by default.
"""
def __init__(
self,
run=None,
client=None,
create_artifact=True,
terminate_after_train=True,
log_on_batch_end=False,
log_on_epoch_end=True,
batch_suffix=None,
epoch_suffix=None,
keys_ignored=None,
):
self.run = run
self.client = client
self.create_artifact = create_artifact
self.terminate_after_train = terminate_after_train
self.log_on_batch_end = log_on_batch_end
self.log_on_epoch_end = log_on_epoch_end
self.batch_suffix = batch_suffix
self.epoch_suffix = epoch_suffix
self.keys_ignored = keys_ignored
def initialize(self):
self.run_ = self.run
if self.run_ is None:
import mlflow
self.run_ = mlflow.active_run()
self.client_ = self.client
if self.client_ is None:
from mlflow.tracking import MlflowClient
self.client_ = MlflowClient()
keys_ignored = self.keys_ignored
if isinstance(keys_ignored, str):
keys_ignored = [keys_ignored]
self.keys_ignored_ = set(keys_ignored or [])
self.keys_ignored_.add('batches')
self.batch_suffix_ = self._init_suffix(self.batch_suffix, '_batch')
self.epoch_suffix_ = self._init_suffix(self.epoch_suffix, '_epoch')
return self
def _init_suffix(self, suffix, default):
if suffix is not None:
return suffix
return default if self.log_on_batch_end and self.log_on_epoch_end else ''
def on_train_begin(self, net, **kwargs):
self._batch_count = 0
def on_batch_end(self, net, training, **kwargs):
if not self.log_on_batch_end:
return
self._batch_count += 1
batch_logs = net.history[-1]['batches'][-1]
self._iteration_log(batch_logs, self.batch_suffix_, self._batch_count)
def on_epoch_end(self, net, **kwargs):
if not self.log_on_epoch_end:
return
epoch_logs = net.history[-1]
self._iteration_log(epoch_logs, self.epoch_suffix_, len(net.history))
def _iteration_log(self, logs, suffix, step):
for key in filter_log_keys(logs.keys(), self.keys_ignored_):
self.client_.log_metric(
self.run_.info.run_id,
key + suffix,
logs[key],
step=step,
)
def on_train_end(self, net, **kwargs):
try:
self._log_artifacts(net)
finally:
if self.terminate_after_train:
self.client_.set_terminated(self.run_.info.run_id)
def _log_artifacts(self, net):
if not self.create_artifact:
return
with tempfile.TemporaryDirectory(prefix='skorch_mlflow_logger_') as dirpath:
dirpath = Path(dirpath)
params_filepath = dirpath / 'params.pth'
optimizer_filepath = dirpath / 'optimizer.pth'
criterion_filepath = dirpath / 'criterion.pth'
history_filepath = dirpath / 'history.json'
net.save_params(
f_params=params_filepath,
f_optimizer=optimizer_filepath,
f_criterion=criterion_filepath,
f_history=history_filepath,
)
self.client_.log_artifact(self.run_.info.run_id, params_filepath)
self.client_.log_artifact(self.run_.info.run_id, optimizer_filepath)
self.client_.log_artifact(self.run_.info.run_id, criterion_filepath)
self.client_.log_artifact(self.run_.info.run_id, history_filepath)
| MlflowLogger |
python | getsentry__sentry | src/sentry/workflow_engine/migrations/0075_add_index_to_dcg_action.py | {
"start": 155,
"end": 1493
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# of a table.
# Here are some things that make sense to mark as post deployment:
# - Large data migrations. Typically we want these to be run manually so that they can be
# monitored and not block the deploy for a long period of time while they run.
# - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to
# run this outside deployments so that we don't block them. Note that while adding an index
# is a schema change, it's completely safe to run the operation after the code has deployed.
# Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment
is_post_deployment = True
dependencies = [
("workflow_engine", "0074_safe_delete_actiongroupstatus"),
]
operations = [
migrations.AddIndex(
model_name="dataconditiongroupaction",
index=models.Index(fields=["condition_group", "action"], name="cond_group_action_idx"),
),
]
| Migration |
python | getsentry__sentry | tests/sentry/workflow_engine/handlers/detector/test_stateful.py | {
"start": 510,
"end": 3736
} | class ____(TestCase):
def setUp(self) -> None:
self.detector = self.create_detector(
name="Stateful Detector",
project=self.project,
)
def _get_full_detector(self) -> Detector:
"""
Fetches the full detector with its workflow condition group and conditions.
This is useful to ensure that the detector is fully populated for testing.
"""
detector = (
Detector.objects.filter(id=self.detector.id)
.select_related("workflow_condition_group")
.prefetch_related("workflow_condition_group__conditions")
.first()
)
assert detector is not None
return detector
def test__init_creates_default_thresholds(self) -> None:
handler = MockDetectorStateHandler(detector=self.detector)
# Only the OK threshold is set by default
assert handler._thresholds == {Level.OK: 1}
def test_init__override_thresholds(self) -> None:
handler = MockDetectorStateHandler(
detector=self.detector,
thresholds={Level.LOW: 2},
)
# Setting the thresholds on the detector allow to override the defaults
assert handler._thresholds == {Level.OK: 1, Level.LOW: 2}
def test_init__creates_correct_state_counters(self) -> None:
handler = MockDetectorStateHandler(detector=self.detector)
assert handler.state_manager.counter_names == [Level.OK]
def test_init__threshold_query(self) -> None:
self.detector.workflow_condition_group = self.create_data_condition_group()
self.detector.save()
self.create_data_condition(
type="eq",
comparison="HIGH",
condition_group=self.detector.workflow_condition_group,
condition_result=Level.HIGH,
)
fetched_detector = self._get_full_detector()
with self.assertNumQueries(0):
handler = MockDetectorStateHandler(detector=fetched_detector)
assert handler._thresholds == {Level.OK: 1, Level.HIGH: 1}
def test_init__threshold_query_no_conditions(self) -> None:
self.detector.workflow_condition_group = self.create_data_condition_group()
self.detector.save()
fetched_detector = self._get_full_detector()
with self.assertNumQueries(0):
handler = MockDetectorStateHandler(detector=fetched_detector)
assert handler._thresholds == {Level.OK: 1}
def test_init__threshold_makes_query(self) -> None:
self.detector.workflow_condition_group = self.create_data_condition_group()
self.detector.save()
self.create_data_condition(
type="eq",
comparison="HIGH",
condition_group=self.detector.workflow_condition_group,
condition_result=Level.HIGH,
)
fetched_detector = Detector.objects.get(id=self.detector.id)
with self.assertNumQueries(1):
# Should make a query since we don't know the detector conditions
handler = MockDetectorStateHandler(detector=fetched_detector)
assert handler._thresholds == {Level.OK: 1, Level.HIGH: 1}
| TestStatefulDetectorHandler |
python | pytorch__pytorch | torch/testing/_internal/distributed/ddp_under_dist_autograd_test.py | {
"start": 3249,
"end": 3643
} | class ____(nn.Module):
def __init__(self, d_in: int, d_out: int):
gLogger.info("Initing RemoteNet with %s %s", d_in, d_out)
super().__init__()
self.fc = getLinear(d_in, d_out)
self.relu = nn.ReLU()
def forward(self, input: torch.Tensor):
gLogger.debug("Running RemoteNet.forward() on: %s", input)
return self.relu(self.fc(input))
| RemoteNet |
python | python__mypy | mypyc/irbuild/for_helpers.py | {
"start": 30926,
"end": 34848
} | class ____(ForGenerator):
"""Generate optimized IR for a for loop over a sequence.
Supports iterating in both forward and reverse.
"""
length_reg: Value | AssignmentTarget | None
def init(
self, expr_reg: Value, target_type: RType, reverse: bool, length: Value | None = None
) -> None:
assert is_sequence_rprimitive(expr_reg.type), (expr_reg, expr_reg.type)
builder = self.builder
# Record a Value indicating the length of the sequence, if known at compile time.
self.length = length
self.reverse = reverse
# Define target to contain the expression, along with the index that will be used
# for the for-loop. If we are inside of a generator function, spill these into the
# environment class.
self.expr_target = builder.maybe_spill(expr_reg)
if is_immutable_rprimitive(expr_reg.type):
# If the expression is an immutable type, we can load the length just once.
self.length_reg = builder.maybe_spill(self.length or self.load_len(self.expr_target))
else:
# Otherwise, even if the length is known, we must recalculate the length
# at every iteration for compatibility with python semantics.
self.length_reg = None
if not reverse:
index_reg: Value = Integer(0, c_pyssize_t_rprimitive)
else:
if self.length_reg is not None:
len_val = builder.read(self.length_reg)
else:
len_val = self.load_len(self.expr_target)
index_reg = builder.builder.int_sub(len_val, 1)
self.index_target = builder.maybe_spill_assignable(index_reg)
self.target_type = target_type
def gen_condition(self) -> None:
builder = self.builder
line = self.line
if self.reverse:
# If we are iterating in reverse order, we obviously need
# to check that the index is still positive. Somewhat less
# obviously we still need to check against the length,
# since it could shrink out from under us.
comparison = builder.binary_op(
builder.read(self.index_target, line), Integer(0), ">=", line
)
second_check = BasicBlock()
builder.add_bool_branch(comparison, second_check, self.loop_exit)
builder.activate_block(second_check)
if self.length_reg is None:
# For compatibility with python semantics we recalculate the length
# at every iteration.
len_reg = self.load_len(self.expr_target)
else:
# (unless input is immutable type).
len_reg = builder.read(self.length_reg, line)
comparison = builder.binary_op(builder.read(self.index_target, line), len_reg, "<", line)
builder.add_bool_branch(comparison, self.body_block, self.loop_exit)
def begin_body(self) -> None:
builder = self.builder
line = self.line
# Read the next list item.
value_box = unsafe_index(
builder,
builder.read(self.expr_target, line),
builder.read(self.index_target, line),
line,
)
assert value_box
# We coerce to the type of list elements here so that
# iterating with tuple unpacking generates a tuple based
# unpack instead of an iterator based one.
builder.assign(
builder.get_assignment_target(self.index),
builder.coerce(value_box, self.target_type, line),
line,
)
def gen_step(self) -> None:
# Step to the next item.
builder = self.builder
line = self.line
step = 1 if not self.reverse else -1
add = builder.builder.int_add(builder.read(self.index_target, line), step)
builder.assign(self.index_target, add, line)
| ForSequence |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 382647,
"end": 384367
} | class ____(Response):
"""
Response of tasks.stop_many endpoint.
:param stopped: Number of tasks stopped
:type stopped: int
"""
_service = "tasks"
_action = "stop_many"
_version = "2.13"
_schema = {
"definitions": {},
"failures": {
"item": {
"error": {
"description": "Error info",
"properties": {
"codes": {"item": {"type": "integer"}, "type": "array"},
"data": {"additionalProperties": True, "type": "object"},
"msg": {"type": "string"},
},
"type": "object",
},
"id": {"description": "ID of the failed entity", "type": "string"},
"type": "object",
},
"type": "array",
},
"properties": {
"stopped": {
"description": "Number of tasks stopped",
"type": ["integer", "null"],
}
},
}
def __init__(self, stopped: Optional[int] = None, **kwargs: Any) -> None:
super(StopManyResponse, self).__init__(**kwargs)
self.stopped = stopped
@schema_property("stopped")
def stopped(self) -> Optional[int]:
return self._property_stopped
@stopped.setter
def stopped(self, value: Optional[int]) -> None:
if value is None:
self._property_stopped = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "stopped", six.integer_types)
self._property_stopped = value
| StopManyResponse |
python | getsentry__sentry | tests/sentry/integrations/aws_lambda/test_utils.py | {
"start": 620,
"end": 985
} | class ____(TestCase):
def test_simple(self) -> None:
arn = (
"arn:aws:cloudformation:us-east-2:599817902985:stack/"
"Sentry-Monitoring-Stack/e42083d0-3e3f-11eb-b66a-0ac9b5db7f30"
)
parsed = parse_arn(arn)
assert parsed["account"] == "599817902985"
assert parsed["region"] == "us-east-2"
| ParseArnTest |
python | kamyu104__LeetCode-Solutions | Python/count-the-number-of-houses-at-a-certain-distance-i.py | {
"start": 66,
"end": 1194
} | class ____(object):
def countOfPairs(self, n, x, y):
"""
:type n: int
:type x: int
:type y: int
:rtype: List[int]
"""
x, y = x-1, y-1
if x > y:
x, y = y, x
diff = [0]*n
for i in xrange(n):
diff[0] += 1+1 # i -> two routes begin
diff[min(abs(i-x), abs(i-y)+1)] += 1 # i -> x -> y, fork one route at x to y
diff[min(abs(i-y), abs(i-x)+1)] += 1 # i -> y -> x, fork one route at y to x
diff[min(abs(i-0), abs(i-y)+1+abs(x-0))] -= 1 # i -> 0, one route ends
diff[min(abs(i-(n-1)), abs(i-x)+1+abs(y-(n-1)))] -= 1 # i -> n-1, one route ends
diff[max(x-i, 0)+max(i-y, 0)+((y-x)+0)//2] -= 1 # i -> x -> ((y-x)+0)//2 <- x, one route ends
diff[max(x-i, 0)+max(i-y, 0)+((y-x)+1)//2] -= 1 # i -> y -> ((y-x)+1)//2 <- y, one route ends
for i in xrange(n-1):
diff[i+1] += diff[i]
return diff
# Time: O(n^2)
# Space: O(1)
# math
| Solution |
python | pypa__pipenv | pipenv/vendor/click/_textwrap.py | {
"start": 75,
"end": 1353
} | class ____(textwrap.TextWrapper):
def _handle_long_word(
self,
reversed_chunks: t.List[str],
cur_line: t.List[str],
cur_len: int,
width: int,
) -> None:
space_left = max(width - cur_len, 1)
if self.break_long_words:
last = reversed_chunks[-1]
cut = last[:space_left]
res = last[space_left:]
cur_line.append(cut)
reversed_chunks[-1] = res
elif not cur_line:
cur_line.append(reversed_chunks.pop())
@contextmanager
def extra_indent(self, indent: str) -> t.Iterator[None]:
old_initial_indent = self.initial_indent
old_subsequent_indent = self.subsequent_indent
self.initial_indent += indent
self.subsequent_indent += indent
try:
yield
finally:
self.initial_indent = old_initial_indent
self.subsequent_indent = old_subsequent_indent
def indent_only(self, text: str) -> str:
rv = []
for idx, line in enumerate(text.splitlines()):
indent = self.initial_indent
if idx > 0:
indent = self.subsequent_indent
rv.append(f"{indent}{line}")
return "\n".join(rv)
| TextWrapper |
python | ansible__ansible | test/integration/targets/lookup-option-name/lookup_plugins/non_terms_posargs.py | {
"start": 84,
"end": 514
} | class ____(LookupBase):
"""Test plugin whose run method has a kwarg named terms that is not the first positional arg."""
def run(self, not_terms, variables=None, terms=None, **kwargs): # pylint:disable=arguments-renamed
"""Echo back a dictionary with the first posarg and the terms kwarg to ensure we didn't conflate posarg 0 and the terms kwarg"""
return [dict(not_terms=not_terms, terms=terms)]
| LookupModule |
python | huggingface__transformers | src/transformers/models/granitemoehybrid/modeling_granitemoehybrid.py | {
"start": 42401,
"end": 45431
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: GraniteMoeHybridConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.config = config
self.rope_type = self.config.rope_parameters["rope_type"]
rope_init_fn: Callable = self.compute_default_rope_parameters
if self.rope_type != "default":
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
self.register_buffer("inv_freq", inv_freq, persistent=False)
self.original_inv_freq = inv_freq
@staticmethod
def compute_default_rope_parameters(
config: Optional[GraniteMoeHybridConfig] = None,
device: Optional["torch.device"] = None,
seq_len: Optional[int] = None,
) -> tuple["torch.Tensor", float]:
"""
Computes the inverse frequencies according to the original RoPE implementation
Args:
config ([`~transformers.PreTrainedConfig`]):
The model configuration.
device (`torch.device`):
The device to use for initialization of the inverse frequencies.
seq_len (`int`, *optional*):
The current sequence length. Unused for this type of RoPE.
Returns:
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
"""
base = config.rope_parameters["rope_theta"]
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
attention_factor = 1.0 # Unused in this type of RoPE
# Compute the inverse frequencies
inv_freq = 1.0 / (
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
)
return inv_freq, attention_factor
@torch.no_grad()
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
def forward(self, x, position_ids):
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
position_ids_expanded = position_ids[:, None, :].float()
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
with torch.autocast(device_type=device_type, enabled=False): # Force float32
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
emb = torch.cat((freqs, freqs), dim=-1)
cos = emb.cos() * self.attention_scaling
sin = emb.sin() * self.attention_scaling
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
| GraniteMoeHybridRotaryEmbedding |
python | ansible__ansible | test/units/plugins/inventory/test_inventory.py | {
"start": 1095,
"end": 3857
} | class ____(unittest.TestCase):
patterns = {
'a': ['a'],
'a, b': ['a', 'b'],
'a , b': ['a', 'b'],
' a,b ,c[1:2] ': ['a', 'b', 'c[1:2]'],
'9a01:7f8:191:7701::9': ['9a01:7f8:191:7701::9'],
'9a01:7f8:191:7701::9,9a01:7f8:191:7701::9': ['9a01:7f8:191:7701::9', '9a01:7f8:191:7701::9'],
'9a01:7f8:191:7701::9,9a01:7f8:191:7701::9,foo': ['9a01:7f8:191:7701::9', '9a01:7f8:191:7701::9', 'foo'],
'foo[1:2]': ['foo[1:2]'],
'a::b': ['a::b'],
'a:b': ['a', 'b'],
' a : b ': ['a', 'b'],
'foo:bar:baz[1:2]': ['foo', 'bar', 'baz[1:2]'],
'a,,b': ['a', 'b'],
'a, ,b,,c, ,': ['a', 'b', 'c'],
',': [],
'': [],
}
pattern_lists = [
[['a'], ['a']],
[['a', 'b'], ['a', 'b']],
[['a, b'], ['a', 'b']],
[['9a01:7f8:191:7701::9', '9a01:7f8:191:7701::9,foo'],
['9a01:7f8:191:7701::9', '9a01:7f8:191:7701::9', 'foo']]
]
# pattern_string: [ ('base_pattern', (a,b)), ['x','y','z'] ]
# a,b are the bounds of the subscript; x..z are the results of the subscript
# when applied to string.ascii_letters.
subscripts = {
'a': [('a', None), list(string.ascii_letters)],
'a[0]': [('a', (0, None)), ['a']],
'a[1]': [('a', (1, None)), ['b']],
'a[2:3]': [('a', (2, 3)), ['c', 'd']],
'a[-1]': [('a', (-1, None)), ['Z']],
'a[-2]': [('a', (-2, None)), ['Y']],
'a[48:]': [('a', (48, -1)), ['W', 'X', 'Y', 'Z']],
'a[49:]': [('a', (49, -1)), ['X', 'Y', 'Z']],
'a[1:]': [('a', (1, -1)), list(string.ascii_letters[1:])],
}
ranges_to_expand = {
'a[1:2]': ['a1', 'a2'],
'a[1:10:2]': ['a1', 'a3', 'a5', 'a7', 'a9'],
'a[a:b]': ['aa', 'ab'],
'a[a:i:3]': ['aa', 'ad', 'ag'],
'a[a:b][c:d]': ['aac', 'aad', 'abc', 'abd'],
'a[0:1][2:3]': ['a02', 'a03', 'a12', 'a13'],
'a[a:b][2:3]': ['aa2', 'aa3', 'ab2', 'ab3'],
}
def setUp(self):
fake_loader = DictDataLoader({})
self.i = InventoryManager(loader=fake_loader, sources=[None])
def test_split_patterns(self):
for p in self.patterns:
r = self.patterns[p]
self.assertEqual(r, split_host_pattern(p))
for p, r in self.pattern_lists:
self.assertEqual(r, split_host_pattern(p))
def test_ranges(self):
for s in self.subscripts:
r = self.subscripts[s]
self.assertEqual(r[0], self.i._split_subscript(s))
self.assertEqual(
r[1],
self.i._apply_subscript(
list(string.ascii_letters),
r[0][1]
)
)
| TestInventory |
python | PyCQA__pylint | tests/functional/a/arguments_differ.py | {
"start": 3213,
"end": 3282
} | class ____:
def test(self, first, second):
pass
| Positional |
python | ray-project__ray | python/ray/llm/_internal/batch/stages/sglang_engine_stage.py | {
"start": 488,
"end": 631
} | class ____(str, Enum):
"""The type of task to run on the SGLang engine."""
"""Generate text."""
GENERATE = "generate"
| SGLangTaskType |
python | PyCQA__pylint | tests/functional/r/redefined/redefined_outer_name_type_checking.py | {
"start": 225,
"end": 809
} | class ____:
def func(self, stuff: defaultdict, my_deque: deque):
# These imports make the definition work.
# pylint: disable=import-outside-toplevel
from collections import defaultdict
from collections import deque
obj = defaultdict()
obj2 = deque()
obj.update(stuff)
obj2.append(my_deque)
return obj
if TYPE_CHECKING:
# This import makes the annotations work.
from collections import defaultdict
if t.TYPE_CHECKING:
# This import makes the annotations work.
from collections import deque
| Cls |
python | pytest-dev__pytest | src/_pytest/recwarn.py | {
"start": 8650,
"end": 13386
} | class ____(WarningsRecorder):
def __init__(
self,
expected_warning: type[Warning] | tuple[type[Warning], ...] = Warning,
match_expr: str | re.Pattern[str] | None = None,
*,
_ispytest: bool = False,
) -> None:
check_ispytest(_ispytest)
super().__init__(_ispytest=True)
msg = "exceptions must be derived from Warning, not %s"
if isinstance(expected_warning, tuple):
for exc in expected_warning:
if not issubclass(exc, Warning):
raise TypeError(msg % type(exc))
expected_warning_tup = expected_warning
elif isinstance(expected_warning, type) and issubclass(
expected_warning, Warning
):
expected_warning_tup = (expected_warning,)
else:
raise TypeError(msg % type(expected_warning))
self.expected_warning = expected_warning_tup
self.match_expr = match_expr
def matches(self, warning: warnings.WarningMessage) -> bool:
assert self.expected_warning is not None
return issubclass(warning.category, self.expected_warning) and bool(
self.match_expr is None or re.search(self.match_expr, str(warning.message))
)
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
super().__exit__(exc_type, exc_val, exc_tb)
__tracebackhide__ = True
# BaseExceptions like pytest.{skip,fail,xfail,exit} or Ctrl-C within
# pytest.warns should *not* trigger "DID NOT WARN" and get suppressed
# when the warning doesn't happen. Control-flow exceptions should always
# propagate.
if exc_val is not None and (
not isinstance(exc_val, Exception)
# Exit is an Exception, not a BaseException, for some reason.
or isinstance(exc_val, Exit)
):
return
def found_str() -> str:
return pformat([record.message for record in self], indent=2)
try:
if not any(issubclass(w.category, self.expected_warning) for w in self):
fail(
f"DID NOT WARN. No warnings of type {self.expected_warning} were emitted.\n"
f" Emitted warnings: {found_str()}."
)
elif not any(self.matches(w) for w in self):
fail(
f"DID NOT WARN. No warnings of type {self.expected_warning} matching the regex were emitted.\n"
f" Regex: {self.match_expr}\n"
f" Emitted warnings: {found_str()}."
)
finally:
# Whether or not any warnings matched, we want to re-emit all unmatched warnings.
for w in self:
if not self.matches(w):
warnings.warn_explicit(
message=w.message,
category=w.category,
filename=w.filename,
lineno=w.lineno,
module=w.__module__,
source=w.source,
)
# Currently in Python it is possible to pass other types than an
# `str` message when creating `Warning` instances, however this
# causes an exception when :func:`warnings.filterwarnings` is used
# to filter those warnings. See
# https://github.com/python/cpython/issues/103577 for a discussion.
# While this can be considered a bug in CPython, we put guards in
# pytest as the error message produced without this check in place
# is confusing (#10865).
for w in self:
if type(w.message) is not UserWarning:
# If the warning was of an incorrect type then `warnings.warn()`
# creates a UserWarning. Any other warning must have been specified
# explicitly.
continue
if not w.message.args:
# UserWarning() without arguments must have been specified explicitly.
continue
msg = w.message.args[0]
if isinstance(msg, str):
continue
# It's possible that UserWarning was explicitly specified, and
# its first argument was not a string. But that case can't be
# distinguished from an invalid type.
raise TypeError(
f"Warning must be str or Warning, got {msg!r} (type {type(msg).__name__})"
)
| WarningsChecker |
python | tensorflow__tensorflow | tensorflow/python/profiler/internal/flops_registry_test.py | {
"start": 1058,
"end": 2093
} | class ____(test.TestCase):
@test_util.run_v1_only('Test requires a Graph and NodeDef inspection')
def testSimpleStatistics(self):
a = variables.Variable(random_ops.random_normal([25, 16]))
b = variables.Variable(random_ops.random_normal([16, 9]))
math_ops.matmul(a, b)
g = ops.get_default_graph()
for op in g.get_operations():
flops = ops.get_stats_for_node_def(g, op.node_def, 'flops').value
if op.name == 'MatMul':
self.assertEqual(7200, flops)
@test_util.run_v1_only('Test requires a Graph and NodeDef inspection')
def testTransposedStatistics(self):
a = variables.Variable(random_ops.random_normal([16, 25]))
b = variables.Variable(random_ops.random_normal([16, 9]))
math_ops.matmul(a, b, transpose_a=True)
g = ops.get_default_graph()
for op in g.get_operations():
flops = ops.get_stats_for_node_def(g, op.node_def, 'flops').value
if op.name == 'MatMul':
self.assertEqual(7200, flops)
if __name__ == '__main__':
test.main()
| FlopsRegistryTest |
python | kamyu104__LeetCode-Solutions | Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py | {
"start": 30,
"end": 382
} | class ____(object):
def maxProfit(self, prices, fee):
"""
:type prices: List[int]
:type fee: int
:rtype: int
"""
cash, hold = 0, -prices[0]
for i in xrange(1, len(prices)):
cash = max(cash, hold+prices[i]-fee)
hold = max(hold, cash-prices[i])
return cash
| Solution |
python | getsentry__sentry | src/sentry/replays/endpoints/project_replay_jobs_delete.py | {
"start": 1921,
"end": 2102
} | class ____(serializers.Serializer):
data = ReplayDeletionJobCreateDataSerializer(required=True) # type: ignore[assignment]
@region_silo_endpoint
| ReplayDeletionJobCreateSerializer |
python | plotly__plotly.py | plotly/graph_objs/violin/selected/_marker.py | {
"start": 233,
"end": 3579
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "violin.selected"
_path_str = "violin.selected.marker"
_valid_props = {"color", "opacity", "size"}
@property
def color(self):
"""
Sets the marker color of selected points.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def opacity(self):
"""
Sets the marker opacity of selected points.
The 'opacity' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
int|float
"""
return self["opacity"]
@opacity.setter
def opacity(self, val):
self["opacity"] = val
@property
def size(self):
"""
Sets the marker size of selected points.
The 'size' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
@property
def _prop_descriptions(self):
return """\
color
Sets the marker color of selected points.
opacity
Sets the marker opacity of selected points.
size
Sets the marker size of selected points.
"""
def __init__(self, arg=None, color=None, opacity=None, size=None, **kwargs):
"""
Construct a new Marker object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.violin.selected.Marker`
color
Sets the marker color of selected points.
opacity
Sets the marker opacity of selected points.
size
Sets the marker size of selected points.
Returns
-------
Marker
"""
super().__init__("marker")
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.violin.selected.Marker
constructor must be a dict or
an instance of :class:`plotly.graph_objs.violin.selected.Marker`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("opacity", arg, opacity)
self._set_property("size", arg, size)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Marker |
python | conda__conda | conda/plugins/types.py | {
"start": 1549,
"end": 1989
} | class ____:
"""
Base class for all conda plugins.
"""
#: User-facing name of the plugin used for selecting & filtering plugins and error messages.
name: str
def __post_init__(self):
try:
self.name = self.name.lower().strip()
except AttributeError:
# AttributeError: name is not a string
raise PluginError(f"Invalid plugin name for {self!r}")
@dataclass
| CondaPlugin |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_table01.py | {
"start": 315,
"end": 857
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("table01.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with tables."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
worksheet.set_column("C:F", 10.288)
worksheet.add_table("C3:F13")
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/remote_representation/code_location.py | {
"start": 12826,
"end": 24239
} | class ____(CodeLocation):
def __init__(self, origin: InProcessCodeLocationOrigin, instance: DagsterInstance):
from dagster._grpc.server import LoadedRepositories
self._origin = check.inst_param(origin, "origin", InProcessCodeLocationOrigin)
self._instance = instance
loadable_target_origin = self._origin.loadable_target_origin
self._loaded_repositories = LoadedRepositories(
loadable_target_origin,
entry_point=self._origin.entry_point,
container_image=self._origin.container_image,
container_context=self._origin.container_context,
# for InProcessCodeLocations, we always use the latest available state versions
defs_state_info=self._instance.defs_state_storage.get_latest_defs_state_info()
if self._instance.defs_state_storage
else None,
)
self._repository_code_pointer_dict = self._loaded_repositories.code_pointers_by_repo_name
self._repositories: dict[str, RemoteRepository] = {}
for (
repo_name,
repo_def,
) in self._loaded_repositories.definitions_by_name.items():
self._repositories[repo_name] = RemoteRepository(
RepositorySnap.from_def(repo_def),
RepositoryHandle.from_location(repository_name=repo_name, code_location=self),
auto_materialize_use_sensors=instance.auto_materialize_use_sensors,
)
@property
def is_reload_supported(self) -> bool:
return False
@property
def origin(self) -> InProcessCodeLocationOrigin:
return self._origin
@property
def executable_path(self) -> Optional[str]:
return self._origin.loadable_target_origin.executable_path
@property
def container_image(self) -> Optional[str]:
return self._origin.container_image
@cached_property
def container_context(self) -> Optional[Mapping[str, Any]]:
return self._origin.container_context
@property
def entry_point(self) -> Optional[Sequence[str]]:
return self._origin.entry_point
@property
def repository_code_pointer_dict(self) -> Mapping[str, Optional[CodePointer]]:
return self._repository_code_pointer_dict
def _get_reconstructable_repository(self, repository_name: str) -> ReconstructableRepository:
return self._loaded_repositories.reconstructables_by_name[repository_name]
def get_reconstructable_job(self, repository_name: str, name: str) -> ReconstructableJob:
return self._get_reconstructable_repository(repository_name).get_reconstructable_job(name)
def _get_repo_def(self, name: str) -> RepositoryDefinition:
return self._loaded_repositories.definitions_by_name[name]
def get_repository(self, name: str) -> RemoteRepository:
return self._repositories[name]
def has_repository(self, name: str) -> bool:
return name in self._repositories
def get_repositories(self) -> Mapping[str, RemoteRepository]:
return self._repositories
async def _gen_subset_remote_job_result(
self, selector: JobSubsetSelector, get_full_job: Callable[[JobSubsetSelector], RemoteJob]
) -> RemoteJobSubsetResult:
return self._get_subset_remote_job_result(selector, get_full_job)
def _get_subset_remote_job_result(
self, selector: JobSubsetSelector, get_full_job: Callable[[JobSubsetSelector], RemoteJob]
) -> RemoteJobSubsetResult:
check.inst_param(selector, "selector", JobSubsetSelector)
check.invariant(
selector.location_name == self.name,
f"PipelineSelector location_name mismatch, got {selector.location_name} expected"
f" {self.name}",
)
from dagster._grpc.impl import get_external_pipeline_subset_result
return get_external_pipeline_subset_result(
self._get_repo_def(selector.repository_name),
self._get_reconstructable_repository(selector.repository_name),
selector.job_name,
selector.op_selection,
selector.asset_selection,
selector.asset_check_selection,
include_parent_snapshot=True,
)
async def gen_execution_plan(
self,
remote_job: RemoteJob,
run_config: Mapping[str, object],
step_keys_to_execute: Optional[Sequence[str]],
known_state: Optional[KnownExecutionState],
instance: Optional[DagsterInstance] = None,
) -> RemoteExecutionPlan:
return self.get_execution_plan(
remote_job,
run_config,
step_keys_to_execute,
known_state,
instance,
)
def get_execution_plan(
self,
remote_job: RemoteJob,
run_config: Mapping[str, object],
step_keys_to_execute: Optional[Sequence[str]],
known_state: Optional[KnownExecutionState],
instance: Optional[DagsterInstance] = None,
) -> RemoteExecutionPlan:
check.inst_param(remote_job, "remote_job", RemoteJob)
check.mapping_param(run_config, "run_config")
step_keys_to_execute = check.opt_nullable_sequence_param(
step_keys_to_execute, "step_keys_to_execute", of_type=str
)
check.opt_inst_param(known_state, "known_state", KnownExecutionState)
check.opt_inst_param(instance, "instance", DagsterInstance)
execution_plan = create_execution_plan(
job=self.get_reconstructable_job(
remote_job.repository_handle.repository_name, remote_job.name
).get_subset(
op_selection=remote_job.resolved_op_selection,
asset_selection=remote_job.asset_selection,
asset_check_selection=remote_job.asset_check_selection,
),
run_config=run_config,
step_keys_to_execute=step_keys_to_execute,
known_state=known_state,
instance_ref=instance.get_ref() if instance and instance.is_persistent else None,
)
return RemoteExecutionPlan(
execution_plan_snapshot=snapshot_from_execution_plan(
execution_plan,
remote_job.identifying_job_snapshot_id,
)
)
def get_partition_config(
self,
repository_handle: RepositoryHandle,
job_name: str,
partition_name: str,
instance: DagsterInstance,
) -> Union["PartitionConfigSnap", "PartitionExecutionErrorSnap"]:
check.inst_param(repository_handle, "repository_handle", RepositoryHandle)
check.str_param(job_name, "job_name")
check.str_param(partition_name, "partition_name")
return get_partition_config(
self._get_repo_def(repository_handle.repository_name),
job_name=job_name,
partition_key=partition_name,
instance_ref=instance.get_ref(),
)
def get_partition_tags_from_repo(
self,
repository_handle: RepositoryHandle,
job_name: str,
partition_name: str,
instance: DagsterInstance,
) -> Union["PartitionTagsSnap", "PartitionExecutionErrorSnap"]:
check.inst_param(repository_handle, "repository_handle", RepositoryHandle)
check.str_param(job_name, "job_name")
check.str_param(partition_name, "partition_name")
check.inst_param(instance, "instance", DagsterInstance)
return get_partition_tags(
self._get_repo_def(repository_handle.repository_name),
job_name=job_name,
partition_name=partition_name,
instance_ref=instance.get_ref(),
)
def get_partition_names_from_repo(
self,
repository_handle: RepositoryHandle,
job_name: str,
) -> Union["PartitionNamesSnap", "PartitionExecutionErrorSnap"]:
return get_partition_names(
self._get_repo_def(repository_handle.repository_name),
job_name=job_name,
)
def get_schedule_execution_data(
self,
instance: DagsterInstance,
repository_handle: RepositoryHandle,
schedule_name: str,
scheduled_execution_time: Optional[TimestampWithTimezone],
log_key: Optional[Sequence[str]],
) -> "ScheduleExecutionData":
check.inst_param(instance, "instance", DagsterInstance)
check.inst_param(repository_handle, "repository_handle", RepositoryHandle)
check.str_param(schedule_name, "schedule_name")
check.opt_inst_param(
scheduled_execution_time, "scheduled_execution_time", TimestampWithTimezone
)
check.opt_list_param(log_key, "log_key", of_type=str)
result = get_external_schedule_execution(
self._get_repo_def(repository_handle.repository_name),
instance_ref=instance.get_ref(),
schedule_name=schedule_name,
scheduled_execution_timestamp=(
scheduled_execution_time.timestamp if scheduled_execution_time else None
),
scheduled_execution_timezone=(
scheduled_execution_time.timezone if scheduled_execution_time else None
),
log_key=log_key,
)
if isinstance(result, ScheduleExecutionErrorSnap):
raise DagsterUserCodeProcessError.from_error_info(result.error)
return result
def get_sensor_execution_data(
self,
instance: DagsterInstance,
repository_handle: RepositoryHandle,
name: str,
last_tick_completion_time: Optional[float],
last_run_key: Optional[str],
cursor: Optional[str],
log_key: Optional[Sequence[str]],
last_sensor_start_time: Optional[float],
) -> "SensorExecutionData":
result = get_external_sensor_execution(
self._get_repo_def(repository_handle.repository_name),
self.origin,
instance.get_ref(),
name,
last_tick_completion_time,
last_run_key,
cursor,
log_key,
last_sensor_start_time,
)
if isinstance(result, SensorExecutionErrorSnap):
raise DagsterUserCodeProcessError.from_error_info(result.error)
return result
def get_partition_set_execution_params(
self,
repository_handle: RepositoryHandle,
partition_set_name: str,
partition_names: Sequence[str],
instance: DagsterInstance,
) -> Union["PartitionSetExecutionParamSnap", "PartitionExecutionErrorSnap"]:
check.inst_param(repository_handle, "repository_handle", RepositoryHandle)
check.str_param(partition_set_name, "partition_set_name")
check.sequence_param(partition_names, "partition_names", of_type=str)
return get_partition_set_execution_param_data(
self._get_repo_def(repository_handle.repository_name),
partition_set_name=partition_set_name,
partition_names=partition_names,
instance_ref=instance.get_ref(),
)
def get_notebook_data(self, notebook_path: str) -> bytes:
check.str_param(notebook_path, "notebook_path")
return get_notebook_data(notebook_path)
def get_dagster_library_versions(self) -> Mapping[str, str]:
return DagsterLibraryRegistry.get()
| InProcessCodeLocation |
python | eventlet__eventlet | tests/timeout_with_statement_test.py | {
"start": 254,
"end": 4136
} | class ____(LimitedTestCase):
def test_cancellation(self):
# Nothing happens if with-block finishes before the timeout expires
t = Timeout(DELAY * 2)
sleep(0) # make it pending
assert t.pending, repr(t)
with t:
assert t.pending, repr(t)
sleep(DELAY)
# check if timer was actually cancelled
assert not t.pending, repr(t)
sleep(DELAY * 2)
def test_raising_self(self):
# An exception will be raised if it's not
try:
with Timeout(DELAY) as t:
sleep(DELAY * 2)
except Timeout as ex:
assert ex is t, (ex, t)
else:
raise AssertionError('must raise Timeout')
def test_raising_self_true(self):
# specifying True as the exception raises self as well
try:
with Timeout(DELAY, True) as t:
sleep(DELAY * 2)
except Timeout as ex:
assert ex is t, (ex, t)
else:
raise AssertionError('must raise Timeout')
def test_raising_custom_exception(self):
# You can customize the exception raised:
try:
with Timeout(DELAY, OSError("Operation takes way too long")):
sleep(DELAY * 2)
except OSError as ex:
assert str(ex) == "Operation takes way too long", repr(ex)
def test_raising_exception_class(self):
# Providing classes instead of values should be possible too:
try:
with Timeout(DELAY, ValueError):
sleep(DELAY * 2)
except ValueError:
pass
def test_raising_exc_tuple(self):
try:
1 // 0
except:
try:
with Timeout(DELAY, sys.exc_info()[0]):
sleep(DELAY * 2)
raise AssertionError('should not get there')
raise AssertionError('should not get there')
except ZeroDivisionError:
pass
else:
raise AssertionError('should not get there')
def test_cancel_timer_inside_block(self):
# It's possible to cancel the timer inside the block:
with Timeout(DELAY) as timer:
timer.cancel()
sleep(DELAY * 2)
def test_silent_block(self):
# To silence the exception before exiting the block, pass
# False as second parameter.
XDELAY = 0.1
start = time.time()
with Timeout(XDELAY, False):
sleep(XDELAY * 2)
delta = (time.time() - start)
assert delta < XDELAY * 2, delta
def test_dummy_timer(self):
# passing None as seconds disables the timer
with Timeout(None):
sleep(DELAY)
sleep(DELAY)
def test_ref(self):
err = Error()
err_ref = weakref.ref(err)
with Timeout(DELAY * 2, err):
sleep(DELAY)
del err
gc.collect()
assert not err_ref(), repr(err_ref())
def test_nested_timeout(self):
with Timeout(DELAY, False):
with Timeout(DELAY * 2, False):
sleep(DELAY * 3)
raise AssertionError('should not get there')
with Timeout(DELAY) as t1:
with Timeout(DELAY * 2) as t2:
try:
sleep(DELAY * 3)
except Timeout as ex:
assert ex is t1, (ex, t1)
assert not t1.pending, t1
assert t2.pending, t2
assert not t2.pending, t2
with Timeout(DELAY * 2) as t1:
with Timeout(DELAY) as t2:
try:
sleep(DELAY * 3)
except Timeout as ex:
assert ex is t2, (ex, t2)
assert t1.pending, t1
assert not t2.pending, t2
assert not t1.pending, t1
| Test |
python | walkccc__LeetCode | solutions/684. Redundant Connection/684.py | {
"start": 540,
"end": 762
} | class ____:
def findRedundantConnection(self, edges: list[list[int]]) -> list[int]:
uf = UnionFind(len(edges) + 1)
for edge in edges:
u, v = edge
if not uf.unionByRank(u, v):
return edge
| Solution |
python | pikepdf__pikepdf | src/pikepdf/models/_content_stream.py | {
"start": 873,
"end": 5147
} | class ____(Exception):
"""Error when parsing a PDF content stream."""
def __init__(self, message=None, line=None):
if not message:
message = f"Error encoding content stream at line {line}"
super().__init__(message)
self.line = line
def parse_content_stream(
page_or_stream: Object | Page, operators: str = ''
) -> list[ContentStreamInstructions]:
"""Parse a PDF content stream into a sequence of instructions.
A PDF content stream is list of instructions that describe where to render
the text and graphics in a PDF. This is the starting point for analyzing
PDFs.
If the input is a page and page.Contents is an array, then the content
stream is automatically treated as one coalesced stream.
Each instruction contains at least one operator and zero or more operands.
This function does not have anything to do with opening a PDF file itself or
processing data from a whole PDF. It is for processing a specific object inside
a PDF that is already opened.
Args:
page_or_stream: A page object, or the content
stream attached to another object such as a Form XObject.
operators: A space-separated string of operators to whitelist.
For example 'q Q cm Do' will return only operators
that pertain to drawing images. Use 'BI ID EI' for inline images.
All other operators and associated tokens are ignored. If blank,
all tokens are accepted.
Example:
>>> with pikepdf.Pdf.open("../tests/resources/pal-1bit-trivial.pdf") as pdf:
... page = pdf.pages[0]
... for operands, command in pikepdf.parse_content_stream(page):
... print(command)
q
cm
Do
Q
.. versionchanged:: 3.0
Returns a list of ``ContentStreamInstructions`` instead of a list
of (operand, operator) tuples. The returned items are duck-type compatible
with the previous returned items.
"""
if not isinstance(page_or_stream, Object | Page):
raise TypeError("stream must be a pikepdf.Object or pikepdf.Page")
if (
isinstance(page_or_stream, Object)
and page_or_stream._type_code != ObjectType.stream
and page_or_stream.get('/Type') != '/Page'
):
raise TypeError("parse_content_stream called on page or stream object")
if isinstance(page_or_stream, Page):
page_or_stream = page_or_stream.obj
try:
if page_or_stream.get('/Type') == '/Page':
page = page_or_stream
instructions = cast(
list[ContentStreamInstructions],
page._parse_page_contents_grouped(operators),
)
else:
stream = page_or_stream
instructions = cast(
list[ContentStreamInstructions],
Object._parse_stream_grouped(stream, operators),
)
except PdfError as e:
if 'supposed to be a stream or an array' in str(e):
raise TypeError("parse_content_stream called on non-stream Object") from e
raise e from e
return instructions
def unparse_content_stream(
instructions: Collection[UnparseableContentStreamInstructions],
) -> bytes:
"""Convert collection of instructions to bytes suitable for storing in PDF.
Given a parsed list of instructions/operand-operators, convert to bytes suitable
for embedding in a PDF. In PDF the operator always follows the operands.
Args:
instructions: collection of instructions such as is returned
by :func:`parse_content_stream()`
Returns:
A binary content stream, suitable for attaching to a Pdf.
To attach to a Pdf, use :meth:`Pdf.make_stream()``.
.. versionchanged:: 3.0
Now accept collections that contain any mixture of
``ContentStreamInstruction``, ``ContentStreamInlineImage``, and the older
operand-operator tuples from pikepdf 2.x.
"""
try:
return _unparse_content_stream(instructions)
except (ValueError, TypeError, RuntimeError) as e:
raise PdfParsingError(
"While unparsing a content stream, an error occurred"
) from e
| PdfParsingError |
python | google__pytype | pytype/tests/test_calls1.py | {
"start": 145,
"end": 2802
} | class ____(test_base.BaseTest):
"""Tests for checking function calls."""
def test_optional(self):
with test_utils.Tempdir() as d:
d.create_file(
"mod.pyi",
"""
def foo(x: int, y: int = ..., z: int = ...) -> int: ...
""",
)
self.Check(
"""
import mod
mod.foo(1)
mod.foo(1, 2)
mod.foo(1, 2, 3)
""",
pythonpath=[d.path],
)
def test_missing(self):
with test_utils.Tempdir() as d:
d.create_file(
"mod.pyi",
"""
def foo(x, y) -> int: ...
""",
)
self.InferWithErrors(
"""
import mod
mod.foo(1) # missing-parameter
""",
pythonpath=[d.path],
)
def test_extraneous(self):
with test_utils.Tempdir() as d:
d.create_file(
"mod.pyi",
"""
def foo(x, y) -> int: ...
""",
)
self.InferWithErrors(
"""
import mod
mod.foo(1, 2, 3) # wrong-arg-count
""",
pythonpath=[d.path],
)
def test_missing_kwonly(self):
with test_utils.Tempdir() as d:
d.create_file(
"mod.pyi",
"""
def foo(x, y, *, z) -> int: ...
""",
)
_, errors = self.InferWithErrors(
"""
import mod
mod.foo(1, 2) # missing-parameter[e]
""",
pythonpath=[d.path],
)
self.assertErrorRegexes(errors, {"e": r"\bz\b"})
def test_extra_keyword(self):
with test_utils.Tempdir() as d:
d.create_file(
"mod.pyi",
"""
def foo(x, y) -> int: ...
""",
)
self.InferWithErrors(
"""
import mod
mod.foo(1, 2, z=3) # wrong-keyword-args
""",
pythonpath=[d.path],
)
def test_varargs_with_kwonly(self):
with test_utils.Tempdir() as d:
d.create_file(
"mod.pyi",
"""
def foo(*args: int, z: int) -> int: ...
""",
)
self.Check(
"""
import mod
mod.foo(1, 2, z=3)
""",
pythonpath=[d.path],
)
def test_varargs_with_missing_kwonly(self):
with test_utils.Tempdir() as d:
d.create_file(
"mod.pyi",
"""
def foo(*args: int, z: int) -> int: ...
""",
)
_, errors = self.InferWithErrors(
"""
import mod
mod.foo(1, 2, 3) # missing-parameter[e]
""",
pythonpath=[d.path],
)
self.assertErrorRegexes(errors, {"e": r"\bz\b"})
if __name__ == "__main__":
test_base.main()
| CallsTest |
python | tox-dev__tox | src/tox/execute/api.py | {
"start": 2923,
"end": 5004
} | class ____(ABC):
"""Abstract API for execution of a tox environment."""
_option_class: type[ExecuteOptions] = ExecuteOptions
def __init__(self, colored: bool) -> None: # noqa: FBT001
self._colored = colored
@contextmanager
def call(
self,
request: ExecuteRequest,
show: bool, # noqa: FBT001
out_err: OutErr,
env: ToxEnv,
) -> Iterator[ExecuteStatus]:
start = time.monotonic()
stderr_color = None
if self._colored:
try:
cfg_color = env.conf._conf.options.stderr_color # noqa: SLF001
stderr_color = getattr(Fore, cfg_color)
except (AttributeError, KeyError, TypeError): # many tests have a mocked 'env'
stderr_color = Fore.RED
try:
# collector is what forwards the content from the file streams to the standard streams
out, err = out_err[0].buffer, out_err[1].buffer
out_sync = SyncWrite(out.name, out if show else None) # type: ignore[arg-type]
err_sync = SyncWrite(err.name, err if show else None, stderr_color) # type: ignore[arg-type]
with out_sync, err_sync:
instance = self.build_instance(request, self._option_class(env), out_sync, err_sync)
with instance as status:
yield status
exit_code = status.exit_code
finally:
end = time.monotonic()
status.outcome = Outcome(
request,
show,
exit_code,
out_sync.text,
err_sync.text,
start,
end,
instance.cmd,
status.metadata,
)
@abstractmethod
def build_instance(
self,
request: ExecuteRequest,
options: ExecuteOptions,
out: SyncWrite,
err: SyncWrite,
) -> ExecuteInstance:
raise NotImplementedError
@classmethod
def register_conf(cls, env: ToxEnv) -> None:
cls._option_class.register_conf(env)
| Execute |
python | django__django | tests/admin_inlines/admin.py | {
"start": 8227,
"end": 8377
} | class ____(admin.TabularInline):
model = SomeChildModel
form = SomeChildModelForm
readonly_fields = ("readonly_field",)
| SomeChildModelInline |
python | MorvanZhou__Reinforcement-learning-with-tensorflow | experiments/2D_car/DDPG.py | {
"start": 6811,
"end": 9793
} | class ____(object):
def __init__(self, capacity, dims):
self.capacity = capacity
self.data = np.zeros((capacity, dims))
self.pointer = 0
def store_transition(self, s, a, r, s_):
transition = np.hstack((s, a, [r], s_))
index = self.pointer % self.capacity # replace the old memory with new memory
self.data[index, :] = transition
self.pointer += 1
def sample(self, n):
assert self.pointer >= self.capacity, 'Memory has not been fulfilled'
indices = np.random.choice(self.capacity, size=n)
return self.data[indices, :]
sess = tf.Session()
# Create actor and critic.
actor = Actor(sess, ACTION_DIM, ACTION_BOUND[1], LR_A, REPLACE_ITER_A)
critic = Critic(sess, STATE_DIM, ACTION_DIM, LR_C, GAMMA, REPLACE_ITER_C, actor.a, actor.a_)
actor.add_grad_to_graph(critic.a_grads)
M = Memory(MEMORY_CAPACITY, dims=2 * STATE_DIM + ACTION_DIM + 1)
saver = tf.train.Saver()
path = './discrete' if DISCRETE_ACTION else './continuous'
if LOAD:
saver.restore(sess, tf.train.latest_checkpoint(path))
else:
sess.run(tf.global_variables_initializer())
def train():
var = 2. # control exploration
for ep in range(MAX_EPISODES):
s = env.reset()
ep_step = 0
for t in range(MAX_EP_STEPS):
# while True:
if RENDER:
env.render()
# Added exploration noise
a = actor.choose_action(s)
a = np.clip(np.random.normal(a, var), *ACTION_BOUND) # add randomness to action selection for exploration
s_, r, done = env.step(a)
M.store_transition(s, a, r, s_)
if M.pointer > MEMORY_CAPACITY:
var = max([var*.9995, VAR_MIN]) # decay the action randomness
b_M = M.sample(BATCH_SIZE)
b_s = b_M[:, :STATE_DIM]
b_a = b_M[:, STATE_DIM: STATE_DIM + ACTION_DIM]
b_r = b_M[:, -STATE_DIM - 1: -STATE_DIM]
b_s_ = b_M[:, -STATE_DIM:]
critic.learn(b_s, b_a, b_r, b_s_)
actor.learn(b_s)
s = s_
ep_step += 1
if done or t == MAX_EP_STEPS - 1:
# if done:
print('Ep:', ep,
'| Steps: %i' % int(ep_step),
'| Explore: %.2f' % var,
)
break
if os.path.isdir(path): shutil.rmtree(path)
os.mkdir(path)
ckpt_path = os.path.join(path, 'DDPG.ckpt')
save_path = saver.save(sess, ckpt_path, write_meta_graph=False)
print("\nSave Model %s\n" % save_path)
def eval():
env.set_fps(30)
while True:
s = env.reset()
while True:
env.render()
a = actor.choose_action(s)
s_, r, done = env.step(a)
s = s_
if done:
break
if __name__ == '__main__':
if LOAD:
eval()
else:
train() | Memory |
python | doocs__leetcode | solution/3600-3699/3613.Minimize Maximum Component Cost/Solution.py | {
"start": 0,
"end": 546
} | class ____:
def minCost(self, n: int, edges: List[List[int]], k: int) -> int:
def find(x: int) -> int:
if p[x] != x:
p[x] = find(p[x])
return p[x]
if k == n:
return 0
edges.sort(key=lambda x: x[2])
cnt = n
p = list(range(n))
for u, v, w in edges:
pu, pv = find(u), find(v)
if pu != pv:
p[pu] = pv
cnt -= 1
if cnt <= k:
return w
return 0
| Solution |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataplex.py | {
"start": 55291,
"end": 59816
} | class ____(GoogleCloudBaseOperator):
"""
Creates a DataScan Data Profile resource.
:param project_id: Required. The ID of the Google Cloud project that the lake belongs to.
:param region: Required. The ID of the Google Cloud region that the lake belongs to.
:param body: Required. The Request body contains an instance of DataScan.
:param data_scan_id: Required. Data Profile scan identifier.
:param update_mask: Mask of fields to update.
:param api_version: The version of the api that will be requested for example 'v1'.
:param retry: A retry object used to retry requests. If `None` is specified, requests
will not be retried.
:param timeout: The amount of time, in seconds, to wait for the request to complete.
Note that if `retry` is specified, the timeout applies to each individual attempt.
:param metadata: Additional metadata that is provided to the method.
:param gcp_conn_id: The connection ID to use when fetching connection info.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
:return: Dataplex data profile id
"""
template_fields = ("project_id", "data_scan_id", "body", "impersonation_chain")
template_fields_renderers = {"body": "json"}
def __init__(
self,
project_id: str,
region: str,
data_scan_id: str,
body: dict[str, Any] | DataScan,
api_version: str = "v1",
retry: Retry | _MethodDefault = DEFAULT,
timeout: float | None = None,
update_mask: dict | FieldMask | None = None,
metadata: Sequence[tuple[str, str]] = (),
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
*args,
**kwargs,
) -> None:
super().__init__(*args, **kwargs)
self.project_id = project_id
self.region = region
self.data_scan_id = data_scan_id
self.body = body
self.update_mask = update_mask
self.api_version = api_version
self.retry = retry
self.timeout = timeout
self.metadata = metadata
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
def execute(self, context: Context):
hook = DataplexHook(
gcp_conn_id=self.gcp_conn_id,
api_version=self.api_version,
impersonation_chain=self.impersonation_chain,
)
self.log.info("Creating Dataplex Data Profile scan %s", self.data_scan_id)
try:
operation = hook.create_data_scan(
project_id=self.project_id,
region=self.region,
data_scan_id=self.data_scan_id,
body=self.body,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
hook.wait_for_operation(timeout=self.timeout, operation=operation)
self.log.info("Dataplex Data Profile scan %s created successfully!", self.data_scan_id)
except AlreadyExists:
self.log.info("Dataplex Data Profile scan already exists: %s", {self.data_scan_id})
operation = hook.update_data_scan(
project_id=self.project_id,
region=self.region,
data_scan_id=self.data_scan_id,
body=self.body,
update_mask=self.update_mask,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
hook.wait_for_operation(timeout=self.timeout, operation=operation)
self.log.info("Dataplex Data Profile scan %s updated successfully!", self.data_scan_id)
except GoogleAPICallError as e:
raise AirflowException(f"Error creating Data Profile scan {self.data_scan_id}", e)
return self.data_scan_id
| DataplexCreateOrUpdateDataProfileScanOperator |
python | dagster-io__dagster | python_modules/libraries/dagster-powerbi/dagster_powerbi/translator.py | {
"start": 2212,
"end": 2509
} | class ____(Enum):
"""Enum representing each object in PowerBI's ontology, generically referred to as "content" by the API."""
DASHBOARD = "dashboard"
REPORT = "report"
SEMANTIC_MODEL = "semantic_model"
DATA_SOURCE = "data_source"
@whitelist_for_serdes
@record
| PowerBIContentType |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/patching/callables.py | {
"start": 760,
"end": 1291
} | class ____:
@example(n=0, label="whatever")
@given(st.integers(), st.text())
def mth(self, n, label):
"""Indented method with existing example decorator."""
@given(st.integers())
@example(x=2).via("not a literal when repeated " * 2)
@example(x=1).via("covering example")
def covered(x):
"""A test function with a removable explicit example."""
@given(npst.arrays(np.int8, 1))
def undef_name(array):
assert sum(array) < 100
# TODO: test function for insertion-order logic, once I get that set up.
| Cases |
python | dask__distributed | distributed/_async_taskgroup.py | {
"start": 830,
"end": 1239
} | class ____(RuntimeError):
pass
def _delayed(corofunc: Callable[P, Coro[T]], delay: float) -> Callable[P, Coro[T]]:
"""Decorator to delay the evaluation of a coroutine function by the given delay in seconds."""
async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
await asyncio.sleep(delay)
return await corofunc(*args, **kwargs)
return wrapper
| AsyncTaskGroupClosedError |
python | mlflow__mlflow | mlflow/sentence_transformers/__init__.py | {
"start": 19716,
"end": 21696
} | class ____:
def __init__(self, model, task=None):
self.model = model
self.task = task
def get_raw_model(self):
"""
Returns the underlying model.
"""
return self.model
def predict(self, sentences, params: dict[str, Any] | None = None):
"""
Args:
sentences: Model input data.
params: Additional parameters to pass to the model for inference.
Returns:
Model predictions.
"""
# When the input is a single string or a dictionary, it is transformed into a DataFrame
# with one column and row, but the encode function does not accept DataFrame input
convert_output_to_llm_v1_format = False
if type(sentences) == pd.DataFrame:
# Wrap the output to OpenAI format only when the input is dict `{"input": ... }`
if self.task and list(sentences.columns)[0] == _LLM_V1_EMBEDDING_INPUT_KEY:
convert_output_to_llm_v1_format = True
sentences = sentences.iloc[:, 0]
if type(sentences[0]) == list:
sentences = sentences[0]
# The encode API has additional parameters that we can add as kwargs.
# See https://www.sbert.net/docs/package_reference/SentenceTransformer.html#sentence_transformers.SentenceTransformer.encode
if params:
try:
output_data = self.model.encode(sentences, **params)
except TypeError as e:
raise MlflowException.invalid_parameter_value(
"Received invalid parameter value for `params` argument"
) from e
else:
output_data = self.model.encode(sentences)
if convert_output_to_llm_v1_format:
output_data = postprocess_output_for_llm_v1_embedding_task(
sentences, output_data, self.model.tokenizer
)
return output_data
| _SentenceTransformerModelWrapper |
python | redis__redis-py | tests/test_asyncio/test_multidb/test_command_executor.py | {
"start": 600,
"end": 7084
} | class ____:
@pytest.mark.asyncio
@pytest.mark.parametrize(
"mock_db,mock_db1,mock_db2",
[
(
{"weight": 0.2, "circuit": {"state": CBState.CLOSED}},
{"weight": 0.7, "circuit": {"state": CBState.CLOSED}},
{"weight": 0.5, "circuit": {"state": CBState.CLOSED}},
),
],
indirect=True,
)
async def test_execute_command_on_active_database(
self, mock_db, mock_db1, mock_db2, mock_fd, mock_fs, mock_ed
):
mock_db1.client.execute_command = AsyncMock(return_value="OK1")
mock_db2.client.execute_command = AsyncMock(return_value="OK2")
databases = create_weighted_list(mock_db, mock_db1, mock_db2)
executor = DefaultCommandExecutor(
failure_detectors=[mock_fd],
databases=databases,
failover_strategy=mock_fs,
event_dispatcher=mock_ed,
command_retry=Retry(NoBackoff(), 0),
)
await executor.set_active_database(mock_db1)
assert await executor.execute_command("SET", "key", "value") == "OK1"
await executor.set_active_database(mock_db2)
assert await executor.execute_command("SET", "key", "value") == "OK2"
assert mock_ed.register_listeners.call_count == 1
assert mock_fd.register_command_execution.call_count == 2
@pytest.mark.asyncio
@pytest.mark.parametrize(
"mock_db,mock_db1,mock_db2",
[
(
{"weight": 0.2, "circuit": {"state": CBState.CLOSED}},
{"weight": 0.7, "circuit": {"state": CBState.CLOSED}},
{"weight": 0.5, "circuit": {"state": CBState.CLOSED}},
),
],
indirect=True,
)
async def test_execute_command_automatically_select_active_database(
self, mock_db, mock_db1, mock_db2, mock_fd, mock_fs, mock_ed
):
mock_db1.client.execute_command = AsyncMock(return_value="OK1")
mock_db2.client.execute_command = AsyncMock(return_value="OK2")
mock_selector = AsyncMock(side_effect=[mock_db1, mock_db2])
type(mock_fs).database = mock_selector
databases = create_weighted_list(mock_db, mock_db1, mock_db2)
executor = DefaultCommandExecutor(
failure_detectors=[mock_fd],
databases=databases,
failover_strategy=mock_fs,
event_dispatcher=mock_ed,
command_retry=Retry(NoBackoff(), 0),
)
assert await executor.execute_command("SET", "key", "value") == "OK1"
mock_db1.circuit.state = CBState.OPEN
assert await executor.execute_command("SET", "key", "value") == "OK2"
assert mock_ed.register_listeners.call_count == 1
assert mock_selector.call_count == 2
assert mock_fd.register_command_execution.call_count == 2
@pytest.mark.asyncio
@pytest.mark.parametrize(
"mock_db,mock_db1,mock_db2",
[
(
{"weight": 0.2, "circuit": {"state": CBState.CLOSED}},
{"weight": 0.7, "circuit": {"state": CBState.CLOSED}},
{"weight": 0.5, "circuit": {"state": CBState.CLOSED}},
),
],
indirect=True,
)
async def test_execute_command_fallback_to_another_db_after_fallback_interval(
self, mock_db, mock_db1, mock_db2, mock_fd, mock_fs, mock_ed
):
mock_db1.client.execute_command = AsyncMock(return_value="OK1")
mock_db2.client.execute_command = AsyncMock(return_value="OK2")
mock_selector = AsyncMock(side_effect=[mock_db1, mock_db2, mock_db1])
type(mock_fs).database = mock_selector
databases = create_weighted_list(mock_db, mock_db1, mock_db2)
executor = DefaultCommandExecutor(
failure_detectors=[mock_fd],
databases=databases,
failover_strategy=mock_fs,
event_dispatcher=mock_ed,
auto_fallback_interval=0.1,
command_retry=Retry(NoBackoff(), 0),
)
assert await executor.execute_command("SET", "key", "value") == "OK1"
mock_db1.weight = 0.1
await asyncio.sleep(0.15)
assert await executor.execute_command("SET", "key", "value") == "OK2"
mock_db1.weight = 0.7
await asyncio.sleep(0.15)
assert await executor.execute_command("SET", "key", "value") == "OK1"
assert mock_ed.register_listeners.call_count == 1
assert mock_selector.call_count == 3
assert mock_fd.register_command_execution.call_count == 3
@pytest.mark.asyncio
@pytest.mark.parametrize(
"mock_db,mock_db1,mock_db2",
[
(
{"weight": 0.2, "circuit": {"state": CBState.CLOSED}},
{"weight": 0.7, "circuit": {"state": CBState.CLOSED}},
{"weight": 0.5, "circuit": {"state": CBState.CLOSED}},
),
],
indirect=True,
)
async def test_execute_command_fallback_to_another_db_after_failure_detection(
self, mock_db, mock_db1, mock_db2, mock_fs
):
mock_db1.client.execute_command = AsyncMock(
side_effect=[
"OK1",
ConnectionError,
ConnectionError,
ConnectionError,
"OK1",
]
)
mock_db2.client.execute_command = AsyncMock(
side_effect=["OK2", ConnectionError, ConnectionError, ConnectionError]
)
mock_selector = AsyncMock(side_effect=[mock_db1, mock_db2, mock_db1])
type(mock_fs).database = mock_selector
threshold = 3
fd = FailureDetectorAsyncWrapper(CommandFailureDetector(threshold, 1))
ed = EventDispatcher()
databases = create_weighted_list(mock_db, mock_db1, mock_db2)
executor = DefaultCommandExecutor(
failure_detectors=[fd],
databases=databases,
failover_strategy=mock_fs,
event_dispatcher=ed,
auto_fallback_interval=0.1,
command_retry=Retry(NoBackoff(), threshold),
)
fd.set_command_executor(command_executor=executor)
assert await executor.execute_command("SET", "key", "value") == "OK1"
assert await executor.execute_command("SET", "key", "value") == "OK2"
assert await executor.execute_command("SET", "key", "value") == "OK1"
assert mock_selector.call_count == 3
| TestDefaultCommandExecutor |
python | django__django | django/contrib/messages/views.py | {
"start": 38,
"end": 524
} | class ____:
"""
Add a success message on successful form submission.
"""
success_message = ""
def form_valid(self, form):
response = super().form_valid(form)
success_message = self.get_success_message(form.cleaned_data)
if success_message:
messages.success(self.request, success_message)
return response
def get_success_message(self, cleaned_data):
return self.success_message % cleaned_data
| SuccessMessageMixin |
python | pytorch__pytorch | test/onnx/internal/test_registration.py | {
"start": 6581,
"end": 9823
} | class ____(common_utils.TestCase):
def tearDown(self) -> None:
registration.registry._registry.pop("test::test_op", None)
def test_onnx_symbolic_registers_function(self):
self.assertFalse(registration.registry.is_registered_op("test::test_op", 9))
@registration.onnx_symbolic("test::test_op", opset=9)
def test(g, x):
return g.op("test", x)
self.assertTrue(registration.registry.is_registered_op("test::test_op", 9))
function_group = registration.registry.get_function_group("test::test_op")
assert function_group is not None
self.assertEqual(function_group.get(9), test)
def test_onnx_symbolic_registers_function_applied_decorator_when_provided(self):
wrapper_called = False
def decorator(func):
def wrapper(*args, **kwargs):
nonlocal wrapper_called
wrapper_called = True
return func(*args, **kwargs)
return wrapper
@registration.onnx_symbolic("test::test_op", opset=9, decorate=[decorator])
def test():
return
function_group = registration.registry.get_function_group("test::test_op")
assert function_group is not None
registered_function = function_group[9]
self.assertFalse(wrapper_called)
registered_function()
self.assertTrue(wrapper_called)
def test_onnx_symbolic_raises_warning_when_overriding_function(self):
self.assertFalse(registration.registry.is_registered_op("test::test_op", 9))
@registration.onnx_symbolic("test::test_op", opset=9)
def test1():
return
with self.assertWarnsRegex(
errors.OnnxExporterWarning,
"Symbolic function 'test::test_op' already registered",
):
@registration.onnx_symbolic("test::test_op", opset=9)
def test2():
return
def test_custom_onnx_symbolic_registers_custom_function(self):
self.assertFalse(registration.registry.is_registered_op("test::test_op", 9))
@registration.custom_onnx_symbolic("test::test_op", opset=9)
def test(g, x):
return g.op("test", x)
self.assertTrue(registration.registry.is_registered_op("test::test_op", 9))
function_group = registration.registry.get_function_group("test::test_op")
assert function_group is not None
self.assertEqual(function_group.get(9), test)
def test_custom_onnx_symbolic_overrides_existing_function(self):
self.assertFalse(registration.registry.is_registered_op("test::test_op", 9))
@registration.onnx_symbolic("test::test_op", opset=9)
def test_original():
return "original"
self.assertTrue(registration.registry.is_registered_op("test::test_op", 9))
@registration.custom_onnx_symbolic("test::test_op", opset=9)
def test_custom():
return "custom"
function_group = registration.registry.get_function_group("test::test_op")
assert function_group is not None
self.assertEqual(function_group.get(9), test_custom)
if __name__ == "__main__":
common_utils.run_tests()
| TestRegistrationDecorators |
python | davidhalter__jedi | jedi/inference/cache.py | {
"start": 2216,
"end": 4191
} | class ____(type):
"""
This is basically almost the same than the decorator above, it just caches
class initializations. Either you do it this way or with decorators, but
with decorators you lose class access (isinstance, etc).
"""
@inference_state_as_method_param_cache()
def __call__(self, *args, **kwargs):
return super().__call__(*args, **kwargs)
def inference_state_method_generator_cache():
"""
This is a special memoizer. It memoizes generators and also checks for
recursion errors and returns no further iterator elemends in that case.
"""
def func(function):
@wraps(function)
def wrapper(obj, *args, **kwargs):
cache = obj.inference_state.memoize_cache
try:
memo = cache[function]
except KeyError:
cache[function] = memo = {}
key = (obj, args, frozenset(kwargs.items()))
if key in memo:
actual_generator, cached_lst = memo[key]
else:
actual_generator = function(obj, *args, **kwargs)
cached_lst = []
memo[key] = actual_generator, cached_lst
i = 0
while True:
try:
next_element = cached_lst[i]
if next_element is _RECURSION_SENTINEL:
debug.warning('Found a generator recursion for %s' % obj)
# This means we have hit a recursion.
return
except IndexError:
cached_lst.append(_RECURSION_SENTINEL)
next_element = next(actual_generator, None)
if next_element is None:
cached_lst.pop()
return
cached_lst[-1] = next_element
yield next_element
i += 1
return wrapper
return func
| CachedMetaClass |
python | allegroai__clearml | clearml/backend_api/session/request.py | {
"start": 1667,
"end": 3460
} | class ____(Request):
_batched_request_cls = abc.abstractproperty()
_schema_errors = (SchemaError, ValidationError, FormatError, Unresolvable)
def __init__(
self,
requests: Union[List[Request], Tuple[Request]],
validate_requests: bool = False,
allow_raw_requests: bool = True,
**kwargs: Any
) -> None:
super(BatchRequest, self).__init__(**kwargs)
self._validate_requests = validate_requests
self._allow_raw_requests = allow_raw_requests
self._property_requests = None
self.requests = requests
@property
def requests(self) -> List[Request]:
return self._property_requests
@requests.setter
def requests(
self,
value: Union[List[Union[Dict, Request]], Tuple[Union[Dict, Request]]],
) -> None:
assert issubclass(self._batched_request_cls, Request)
assert isinstance(value, (list, tuple))
if not self._allow_raw_requests:
if any(isinstance(x, dict) for x in value):
value = [self._batched_request_cls(**x) if isinstance(x, dict) else x for x in value]
assert all(isinstance(x, self._batched_request_cls) for x in value)
self._property_requests = value
def validate(self) -> None:
if not self._validate_requests or self._allow_raw_requests:
return
for i, req in enumerate(self.requests):
try:
req.validate()
except (SchemaError, ValidationError, FormatError, Unresolvable) as e:
raise Exception("Validation error in batch item #%d: %s" % (i, str(e)))
def get_json(self) -> List[Union[Dict, Any]]:
return [r if isinstance(r, dict) else r.to_dict() for r in self.requests]
| BatchRequest |
python | doocs__leetcode | solution/2300-2399/2398.Maximum Number of Robots Within Budget/Solution.py | {
"start": 0,
"end": 605
} | class ____:
def maximumRobots(
self, chargeTimes: List[int], runningCosts: List[int], budget: int
) -> int:
q = deque()
ans = s = l = 0
for r, (t, c) in enumerate(zip(chargeTimes, runningCosts)):
s += c
while q and chargeTimes[q[-1]] <= t:
q.pop()
q.append(r)
while q and (r - l + 1) * s + chargeTimes[q[0]] > budget:
if q[0] == l:
q.popleft()
s -= runningCosts[l]
l += 1
ans = max(ans, r - l + 1)
return ans
| Solution |
python | openai__openai-python | src/openai/types/graders/label_model_grader_param.py | {
"start": 1311,
"end": 1715
} | class ____(TypedDict, total=False):
content: Required[InputContent]
"""Inputs to the model - can contain template strings."""
role: Required[Literal["user", "assistant", "system", "developer"]]
"""The role of the message input.
One of `user`, `assistant`, `system`, or `developer`.
"""
type: Literal["message"]
"""The type of the message input. Always `message`."""
| Input |
python | ray-project__ray | rllib/connectors/common/agent_to_module_mapping.py | {
"start": 480,
"end": 12048
} | class ____(ConnectorV2):
"""ConnectorV2 that performs mapping of data from AgentID based to ModuleID based.
Note: This is one of the default env-to-module or Learner ConnectorV2 pieces that
are added automatically by RLlib into every env-to-module/Learner connector
pipeline, unless `config.add_default_connectors_to_env_to_module_pipeline` or
`config.add_default_connectors_to_learner_pipeline ` are set to
False.
The default env-to-module connector pipeline is:
[
[0 or more user defined ConnectorV2 pieces],
AddObservationsFromEpisodesToBatch,
AddTimeDimToBatchAndZeroPad,
AddStatesFromEpisodesToBatch,
AgentToModuleMapping, # only in multi-agent setups!
BatchIndividualItems,
NumpyToTensor,
]
The default Learner connector pipeline is:
[
[0 or more user defined ConnectorV2 pieces],
AddObservationsFromEpisodesToBatch,
AddColumnsFromEpisodesToTrainBatch,
AddTimeDimToBatchAndZeroPad,
AddStatesFromEpisodesToBatch,
AgentToModuleMapping, # only in multi-agent setups!
BatchIndividualItems,
NumpyToTensor,
]
This connector piece is only used by RLlib (as a default connector piece) in a
multi-agent setup.
Note that before the mapping, `data` is expected to have the following
structure:
[col0]:
(eps_id0, ag0, mod0): [list of individual batch items]
(eps_id0, ag1, mod2): [list of individual batch items]
(eps_id1, ag0, mod1): [list of individual batch items]
[col1]:
etc..
The target structure of the above `data` would then be:
[mod0]:
[col0]: [batched data -> batch_size_B will be the number of all items in the
input data under col0 that have mod0 as their ModuleID]
[col1]: [batched data]
[mod1]:
[col0]: etc.
Mapping happens in the following stages:
1) Under each column name, sort keys first by EpisodeID, then AgentID.
2) Add ModuleID keys under each column name (no cost/extra memory) and map these
new keys to empty lists.
[col0] -> [mod0] -> []: Then push items that belong to mod0 into these lists.
3) Perform batching on the per-module lists under each column:
[col0] -> [mod0]: [...] <- now batched data (numpy array or struct of numpy
arrays).
4) Flip column names with ModuleIDs (no cost/extra memory):
[mod0]:
[col0]: [batched data]
etc..
Note that in order to unmap the resulting batch back into an AgentID based one,
we have to store the env vector index AND AgentID of each module's batch item
in an additionally returned `memorized_map_structure`.
.. testcode::
from ray.rllib.connectors.env_to_module import AgentToModuleMapping
from ray.rllib.utils.test_utils import check
batch = {
"obs": {
("MA-EPS0", "agent0", "module0"): [0, 1, 2],
("MA-EPS0", "agent1", "module1"): [3, 4, 5],
},
"actions": {
("MA-EPS1", "agent2", "module0"): [8],
("MA-EPS0", "agent1", "module1"): [9],
},
}
# Create our connector piece.
connector = AgentToModuleMapping(
rl_module_specs={"module0", "module1"},
agent_to_module_mapping_fn=(
lambda agent_id, eps: "module1" if agent_id == "agent1" else "module0"
),
)
# Call the connector (and thereby flip from AgentID based to ModuleID based
# structure..
output_batch = connector(
rl_module=None, # This particular connector works without an RLModule.
batch=batch,
episodes=[], # This particular connector works without a list of episodes.
explore=True,
shared_data={},
)
# `data` should now be mapped from ModuleIDs to module data.
check(
output_batch,
{
"module0": {
"obs": [0, 1, 2],
"actions": [8],
},
"module1": {
"obs": [3, 4, 5],
"actions": [9],
},
},
)
"""
@override(ConnectorV2)
def recompute_output_observation_space(
self,
input_observation_space: gym.Space,
input_action_space: gym.Space,
) -> gym.Space:
return self._map_space_if_necessary(input_observation_space, "obs")
@override(ConnectorV2)
def recompute_output_action_space(
self,
input_observation_space: gym.Space,
input_action_space: gym.Space,
) -> gym.Space:
return self._map_space_if_necessary(input_action_space, "act")
def __init__(
self,
input_observation_space: Optional[gym.Space] = None,
input_action_space: Optional[gym.Space] = None,
*,
rl_module_specs: Dict[ModuleID, RLModuleSpec],
agent_to_module_mapping_fn,
):
super().__init__(input_observation_space, input_action_space)
self._rl_module_specs = rl_module_specs
self._agent_to_module_mapping_fn = agent_to_module_mapping_fn
@override(ConnectorV2)
def __call__(
self,
*,
rl_module: RLModule,
batch: Dict[str, Any],
episodes: List[EpisodeType],
explore: Optional[bool] = None,
shared_data: Optional[dict] = None,
**kwargs,
) -> Any:
# Current agent to module mapping function.
# agent_to_module_mapping_fn = shared_data.get("agent_to_module_mapping_fn")
# Store in shared data, which module IDs map to which episode/agent, such
# that the module-to-env pipeline can map the data back to agents.
memorized_map_structure = defaultdict(list)
for column, agent_data in batch.items():
if rl_module is not None and column in rl_module:
continue
for eps_id, agent_id, module_id in agent_data.keys():
memorized_map_structure[module_id].append((eps_id, agent_id))
# TODO (sven): We should check that all columns have the same struct.
break
shared_data["memorized_map_structure"] = dict(memorized_map_structure)
# Mapping from ModuleID to column data.
data_by_module = {}
# Iterating over each column in the original data:
for column, agent_data in batch.items():
if rl_module is not None and column in rl_module:
if column in data_by_module:
data_by_module[column].update(agent_data)
else:
data_by_module[column] = agent_data
continue
for (
eps_id,
agent_id,
module_id,
), values_batch_or_list in agent_data.items():
assert isinstance(values_batch_or_list, list)
for value in values_batch_or_list:
if module_id not in data_by_module:
data_by_module[module_id] = {column: []}
elif column not in data_by_module[module_id]:
data_by_module[module_id][column] = []
# Append the data.
data_by_module[module_id][column].append(value)
return data_by_module
def _map_space_if_necessary(self, space: gym.Space, which: str = "obs"):
# Analyze input observation space to check, whether the user has already taken
# care of the agent to module mapping.
if set(self._rl_module_specs) == set(space.spaces.keys()):
return space
# We need to take care of agent to module mapping. Figure out the resulting
# observation space here.
dummy_eps = MultiAgentEpisode()
ret_space = {}
for module_id in self._rl_module_specs:
# Easy way out, user has provided space in the RLModule spec dict.
if (
isinstance(self._rl_module_specs, dict)
and module_id in self._rl_module_specs
):
if (
which == "obs"
and self._rl_module_specs[module_id].observation_space
):
ret_space[module_id] = self._rl_module_specs[
module_id
].observation_space
continue
elif which == "act" and self._rl_module_specs[module_id].action_space:
ret_space[module_id] = self._rl_module_specs[module_id].action_space
continue
# Need to reverse map spaces (for the different agents) to certain
# module IDs (using a dummy MultiAgentEpisode).
one_space = next(iter(space.spaces.values()))
# If all obs spaces are the same anyway, just use the first
# single-agent space.
if all(s == one_space for s in space.spaces.values()):
ret_space[module_id] = one_space
# Otherwise, we have to compare the ModuleID with all possible
# AgentIDs and find the agent ID that matches.
else:
match_aid = None
one_agent_for_module_found = False
for aid in space.spaces.keys():
# Match: Assign spaces for this agentID to the PolicyID.
if self._agent_to_module_mapping_fn(aid, dummy_eps) == module_id:
# Make sure, different agents that map to the same
# policy don't have different spaces.
if (
module_id in ret_space
and space[aid] != ret_space[module_id]
):
raise ValueError(
f"Two agents ({aid} and {match_aid}) in your "
"environment map to the same ModuleID (as per your "
"`agent_to_module_mapping_fn`), however, these agents "
"also have different observation spaces as per the env!"
)
ret_space[module_id] = space[aid]
match_aid = aid
one_agent_for_module_found = True
# Still no space found for this module ID -> Error out.
if not one_agent_for_module_found:
raise ValueError(
f"Could not find or derive any {which}-space for RLModule "
f"{module_id}! This can happen if your `config.rl_module(rl_"
f"module_spec=...)` does NOT contain space information for this"
" particular single-agent module AND your agent-to-module-"
"mapping function is stochastic (such that for some agent A, "
"more than one ModuleID might be returned somewhat randomly). "
f"Fix this error by providing {which}-space information using "
"`config.rl_module(rl_module_spec=MultiRLModuleSpec("
f"rl_module_specs={{'{module_id}': RLModuleSpec("
"observation_space=..., action_space=...)}}))"
)
return gym.spaces.Dict(ret_space)
| AgentToModuleMapping |
python | coleifer__peewee | peewee.py | {
"start": 160775,
"end": 161070
} | class ____(AutoField):
field_type = 'INT GENERATED BY DEFAULT AS IDENTITY'
def __init__(self, generate_always=False, **kwargs):
if generate_always:
self.field_type = 'INT GENERATED ALWAYS AS IDENTITY'
super(IdentityField, self).__init__(**kwargs)
| IdentityField |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-cerebras/llama_index/llms/cerebras/base.py | {
"start": 98,
"end": 1347
} | class ____(OpenAILike):
"""
Cerebras LLM.
Examples:
`pip install llama-index-llms-cerebras`
```python
from llama_index.llms.cerebras import Cerebras
# Set up the Cerebras class with the required model and API key
llm = Cerebras(model="llama-3.3-70b", api_key="your_api_key")
# Call the complete method with a query
response = llm.complete("Why is fast inference important?")
print(response)
```
"""
def __init__(
self,
model: str,
api_key: Optional[str] = None,
api_base: str = os.environ.get("CEREBRAS_BASE_URL", None)
or "https://api.cerebras.ai/v1/",
is_chat_model: bool = True,
**kwargs: Any,
) -> None:
api_key = api_key or os.environ.get("CEREBRAS_API_KEY", None)
assert api_key is not None, (
"API Key not specified! Please set `CEREBRAS_API_KEY`!"
)
super().__init__(
model=model,
api_key=api_key,
api_base=api_base,
is_chat_model=is_chat_model,
**kwargs,
)
@classmethod
def class_name(cls) -> str:
"""Get class name."""
return "Cerebras"
| Cerebras |
python | tensorflow__tensorflow | tensorflow/python/ops/resource_variable_ops.py | {
"start": 92050,
"end": 97005
} | class ____(BaseResourceVariable):
"""A variable with no initializer."""
def __init__( # pylint: disable=super-init-not-called
self,
trainable=None,
caching_device=None,
name=None,
shape=None,
dtype=None,
constraint=None,
synchronization=None,
aggregation=None,
extra_handle_data=None,
distribute_strategy=None,
**unused_kwargs):
"""Creates the variable handle.
Args:
trainable: If `True`, GradientTapes automatically watch uses of this
Variable.
caching_device: Optional device string or function describing where the
Variable should be cached for reading. Defaults to the Variable's
device. If not `None`, caches on another device. Typical use is to
cache on the device where the Ops using the Variable reside, to
deduplicate copying through `Switch` and other conditional statements.
name: Optional name for the variable. Defaults to `'Variable'` and gets
uniquified automatically.
shape: The variable's shape.
dtype: The variable's dtype.
constraint: An optional projection function to be applied to the variable
after being updated by an `Optimizer` (e.g. used to implement norm
constraints or value constraints for layer weights). The function must
take as input the unprojected Tensor representing the value of the
variable and return the Tensor for the projected value (which must have
the same shape). Constraints are not safe to use when doing asynchronous
distributed training.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
`tf.VariableSynchronization`. By default the synchronization is set to
`AUTO` and the current `DistributionStrategy` chooses when to
synchronize.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
`tf.VariableAggregation`.
extra_handle_data: Optional, another resource handle or Tensor with handle
data to merge with `shape` and `dtype`.
distribute_strategy: The tf.distribute.Strategy this variable is being
created inside of.
"""
with ops.init_scope():
# Here we are detecting eagerness within an init_scope, so this will only
# be true when we are running in TF1 graph mode.
self._in_graph_mode = not context.executing_eagerly()
with ops.name_scope(name, "Variable", skip_on_eager=False) as name:
handle_name = ops.name_from_scope_name(name)
if self._in_graph_mode:
shared_name = handle_name
unique_id = shared_name
else:
unique_id = "%s_%d" % (handle_name, ops.uid())
shared_name = None # Never shared
handle = _variable_handle_from_shape_and_dtype(
shape=shape,
dtype=dtype,
shared_name=shared_name,
name=name,
graph_mode=self._in_graph_mode,
initial_value=extra_handle_data)
handle._parent_trackable = weakref.ref(self)
handle._name = handle_name + ":0"
handle._unique_id = unique_id
if self._in_graph_mode:
# We only need to add the read_variable_op in TF1.
with ops.name_scope("Read"):
# Manually assign reads to the handle's device to avoid log
# messages.
with ops.device(handle.device):
value = gen_resource_variable_ops.read_variable_op(handle, dtype)
_maybe_set_handle_data(dtype, handle, value)
graph_element = value
ops.add_to_collection(ops.GraphKeys.GLOBAL_VARIABLES, self)
# Do *not* add to TRAINABLE_VARIABLES here, even if self._trainable,
# because retraining or frozen use of imported SavedModels is
# controlled at higher levels of model building.
else:
graph_element = None
super(UninitializedVariable, self).__init__(
distribute_strategy=distribute_strategy,
shape=shape,
dtype=dtype,
unique_id=unique_id,
handle_name=handle_name,
constraint=constraint,
handle=handle,
graph_element=graph_element,
trainable=trainable,
synchronization=synchronization,
aggregation=aggregation,
in_graph_mode=self._in_graph_mode, **unused_kwargs)
def _dense_var_to_tensor(var, dtype=None, name=None, as_ref=False):
return var._dense_var_to_tensor(dtype=dtype, name=name, as_ref=as_ref) # pylint: disable=protected-access
# Register a conversion function which reads the value of the variable,
# allowing instances of the class to be used as tensors.
tensor_conversion_registry.register_tensor_conversion_function(
BaseResourceVariable, _dense_var_to_tensor)
| UninitializedVariable |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_axis12.py | {
"start": 315,
"end": 1394
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_axis12.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "column"})
chart.axis_ids = [45705088, 54517760]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
chart.add_series({"values": "=Sheet1!$A$1:$A$5"})
chart.add_series({"values": "=Sheet1!$B$1:$B$5"})
chart.add_series({"values": "=Sheet1!$C$1:$C$5"})
chart.set_y_axis({"min": 0, "max": 16})
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | weaviate__weaviate-python-client | weaviate/collections/classes/grpc.py | {
"start": 4720,
"end": 5001
} | class ____(_WeaviateInput):
"""Define how the query's RAG capabilities should be performed."""
single_prompt: Optional[str] = Field(default=None)
grouped_task: Optional[str] = Field(default=None)
grouped_properties: Optional[List[str]] = Field(default=None)
| Generate |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 639642,
"end": 641086
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"check_run_count",
"check_run_counts_by_state",
"edges",
"nodes",
"page_info",
"status_context_count",
"status_context_counts_by_state",
"total_count",
)
check_run_count = sgqlc.types.Field(
sgqlc.types.non_null(Int), graphql_name="checkRunCount"
)
check_run_counts_by_state = sgqlc.types.Field(
sgqlc.types.list_of(sgqlc.types.non_null(CheckRunStateCount)),
graphql_name="checkRunCountsByState",
)
edges = sgqlc.types.Field(
sgqlc.types.list_of("StatusCheckRollupContextEdge"), graphql_name="edges"
)
nodes = sgqlc.types.Field(
sgqlc.types.list_of("StatusCheckRollupContext"), graphql_name="nodes"
)
page_info = sgqlc.types.Field(
sgqlc.types.non_null(PageInfo), graphql_name="pageInfo"
)
status_context_count = sgqlc.types.Field(
sgqlc.types.non_null(Int), graphql_name="statusContextCount"
)
status_context_counts_by_state = sgqlc.types.Field(
sgqlc.types.list_of(sgqlc.types.non_null("StatusContextStateCount")),
graphql_name="statusContextCountsByState",
)
total_count = sgqlc.types.Field(
sgqlc.types.non_null(Int), graphql_name="totalCount"
)
| StatusCheckRollupContextConnection |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.