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 | rapidsai__cudf | python/cudf/cudf/tests/options/test_options.py | {
"start": 1177,
"end": 3947
} | class ____:
def test_option_get_set(odd_option):
assert cudf.get_option("odd_option") == 1
cudf.set_option("odd_option", 101)
assert cudf.get_option("odd_option") == 101
def test_option_set_invalid(odd_option):
with pytest.raises(ValueError, match="Invalid option value 0"):
cudf.set_option("odd_option", 0)
def test_option_description(odd_option):
s = StringIO()
with redirect_stdout(s):
cudf.describe_option("odd_option")
s.seek(0)
expected = (
"odd_option:\n\tAn odd option.\n\t[Default: 1] [Current: 1]\n"
)
assert expected == s.read()
def test_option_description_all(odd_option, even_option):
s = StringIO()
with redirect_stdout(s):
cudf.describe_option()
s.seek(0)
expected = (
"odd_option:\n\tAn odd option.\n\t[Default: 1] [Current: 1]\n"
"even_option:\n\tAn even option.\n\t[Default: 0] [Current: 0]\n"
)
assert expected == s.read()
@pytest.mark.parametrize("default_integer_bitwidth", [32, 64, None])
def test_empty_option_context(default_integer_bitwidth):
with cudf.option_context(
"default_integer_bitwidth", default_integer_bitwidth
):
with cudf.option_context():
assert (
cudf.get_option("default_integer_bitwidth")
== default_integer_bitwidth
)
assert (
cudf.get_option("default_integer_bitwidth")
== default_integer_bitwidth
)
@pytest.mark.parametrize("pandas_compatible", [True, False])
@pytest.mark.parametrize("default_integer_bitwidth", [32, 64])
def test_option_context(pandas_compatible, default_integer_bitwidth):
prev_pandas_compatible_setting = cudf.get_option("mode.pandas_compatible")
prev_width_setting = cudf.get_option("default_integer_bitwidth")
with cudf.option_context(
"mode.pandas_compatible",
pandas_compatible,
"default_integer_bitwidth",
default_integer_bitwidth,
):
assert cudf.get_option("mode.pandas_compatible") is pandas_compatible
assert (
cudf.get_option("default_integer_bitwidth")
is default_integer_bitwidth
)
assert (
cudf.get_option("mode.pandas_compatible")
is prev_pandas_compatible_setting
)
assert cudf.get_option("default_integer_bitwidth") is prev_width_setting
def test_options_context_error():
with pytest.raises(ValueError):
with cudf.option_context("mode.pandas_compatible"):
pass
with pytest.raises(ValueError):
with cudf.option_context("mode.pandas_compatible", 1, 2):
pass
| TestCleanOptions |
python | django__django | django/contrib/staticfiles/management/commands/findstatic.py | {
"start": 113,
"end": 1643
} | class ____(LabelCommand):
help = "Finds the absolute paths for the given static file(s)."
label = "staticfile"
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
"--first",
action="store_false",
dest="all",
help="Only return the first match for each static file.",
)
def handle_label(self, path, **options):
verbosity = options["verbosity"]
result = finders.find(path, find_all=options["all"])
if verbosity >= 2:
searched_locations = (
"\nLooking in the following locations:\n %s"
% "\n ".join([str(loc) for loc in finders.searched_locations])
)
else:
searched_locations = ""
if result:
if not isinstance(result, (list, tuple)):
result = [result]
result = (os.path.realpath(path) for path in result)
if verbosity >= 1:
file_list = "\n ".join(result)
return "Found '%s' here:\n %s%s" % (
path,
file_list,
searched_locations,
)
else:
return "\n".join(result)
else:
message = ["No matching file found for '%s'." % path]
if verbosity >= 2:
message.append(searched_locations)
if verbosity >= 1:
self.stderr.write("\n".join(message))
| Command |
python | django__django | tests/decorators/test_cache.py | {
"start": 525,
"end": 4115
} | class ____(SimpleTestCase):
def test_wrapped_sync_function_is_not_coroutine_function(self):
def sync_view(request):
return HttpResponse()
wrapped_view = cache_control()(sync_view)
self.assertIs(iscoroutinefunction(wrapped_view), False)
def test_wrapped_async_function_is_coroutine_function(self):
async def async_view(request):
return HttpResponse()
wrapped_view = cache_control()(async_view)
self.assertIs(iscoroutinefunction(wrapped_view), True)
def test_cache_control_decorator_http_request(self):
class MyClass:
@cache_control(a="b")
def a_view(self, request):
return HttpResponse()
msg = (
"cache_control didn't receive an HttpRequest. If you are "
"decorating a classmethod, be sure to use @method_decorator."
)
request = HttpRequest()
with self.assertRaisesMessage(TypeError, msg):
MyClass().a_view(request)
with self.assertRaisesMessage(TypeError, msg):
MyClass().a_view(HttpRequestProxy(request))
async def test_cache_control_decorator_http_request_async_view(self):
class MyClass:
@cache_control(a="b")
async def async_view(self, request):
return HttpResponse()
msg = (
"cache_control didn't receive an HttpRequest. If you are decorating a "
"classmethod, be sure to use @method_decorator."
)
request = HttpRequest()
with self.assertRaisesMessage(TypeError, msg):
await MyClass().async_view(request)
with self.assertRaisesMessage(TypeError, msg):
await MyClass().async_view(HttpRequestProxy(request))
def test_cache_control_decorator_http_request_proxy(self):
class MyClass:
@method_decorator(cache_control(a="b"))
def a_view(self, request):
return HttpResponse()
request = HttpRequest()
response = MyClass().a_view(HttpRequestProxy(request))
self.assertEqual(response.headers["Cache-Control"], "a=b")
def test_cache_control_empty_decorator(self):
@cache_control()
def a_view(request):
return HttpResponse()
response = a_view(HttpRequest())
self.assertEqual(response.get("Cache-Control"), "")
async def test_cache_control_empty_decorator_async_view(self):
@cache_control()
async def async_view(request):
return HttpResponse()
response = await async_view(HttpRequest())
self.assertEqual(response.get("Cache-Control"), "")
def test_cache_control_full_decorator(self):
@cache_control(max_age=123, private=True, public=True, custom=456)
def a_view(request):
return HttpResponse()
response = a_view(HttpRequest())
cache_control_items = response.get("Cache-Control").split(", ")
self.assertEqual(
set(cache_control_items), {"max-age=123", "private", "public", "custom=456"}
)
async def test_cache_control_full_decorator_async_view(self):
@cache_control(max_age=123, private=True, public=True, custom=456)
async def async_view(request):
return HttpResponse()
response = await async_view(HttpRequest())
cache_control_items = response.get("Cache-Control").split(", ")
self.assertEqual(
set(cache_control_items), {"max-age=123", "private", "public", "custom=456"}
)
| CacheControlDecoratorTest |
python | weaviate__weaviate-python-client | integration/conftest.py | {
"start": 11977,
"end": 13654
} | class ____(Protocol):
"""Typing for fixture."""
def __call__(
self,
name: str = "",
vectorizer_config: Optional[
Union[_VectorizerConfigCreate, List[_NamedVectorConfigCreate]]
] = None,
vector_config: Optional[
Optional[Union[_VectorConfigCreate, List[_VectorConfigCreate]]]
] = None,
) -> Collection[Any, Any]:
"""Typing for fixture."""
...
@pytest.fixture
def openai_collection(
collection_factory: CollectionFactory,
) -> Generator[OpenAICollection, None, None]:
def _factory(
name: str = "",
vectorizer_config: Optional[
Union[_VectorizerConfigCreate, List[_NamedVectorConfigCreate]]
] = None,
vector_config: Optional[
Optional[Union[_VectorConfigCreate, List[_VectorConfigCreate]]]
] = None,
) -> Collection[Any, Any]:
api_key = os.environ.get("OPENAI_APIKEY")
if api_key is None:
pytest.skip("No OpenAI API key found.")
collection = collection_factory(
name=name,
vectorizer_config=vectorizer_config,
vector_config=vector_config or Configure.Vectors.self_provided(),
properties=[
Property(name="text", data_type=DataType.TEXT),
Property(name="content", data_type=DataType.TEXT),
Property(name="extra", data_type=DataType.TEXT),
],
generative_config=Configure.Generative.openai(),
ports=(8086, 50057),
headers={"X-OpenAI-Api-Key": api_key},
)
return collection
yield _factory
| OpenAICollection |
python | pypa__pip | src/pip/_vendor/rich/tree.py | {
"start": 8371,
"end": 9394
} | class ____(NamedTuple):
text: str = ""
style: Optional[Style] = None
is_control: bool = False
"""
syntax = Syntax(code, "python", theme="monokai", line_numbers=True)
markdown = Markdown(
"""\
### example.md
> Hello, World!
>
> Markdown _all_ the things
"""
)
root = Tree("π² [b green]Rich Tree", highlight=True, hide_root=True)
node = root.add(":file_folder: Renderables", guide_style="red")
simple_node = node.add(":file_folder: [bold yellow]Atomic", guide_style="uu green")
simple_node.add(Group("π Syntax", syntax))
simple_node.add(Group("π Markdown", Panel(markdown, border_style="green")))
containers_node = node.add(
":file_folder: [bold magenta]Containers", guide_style="bold magenta"
)
containers_node.expanded = True
panel = Panel.fit("Just a panel", border_style="red")
containers_node.add(Group("π Panels", panel))
containers_node.add(Group("π [b magenta]Table", table))
console = Console()
console.print(root)
| Segment |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/origin.py | {
"start": 2894,
"end": 3641
} | class ____(
NamedTuple(
"_JobPythonOrigin",
[
("job_name", str),
("repository_origin", RepositoryPythonOrigin),
],
)
):
def __new__(cls, job_name: str, repository_origin: RepositoryPythonOrigin):
return super().__new__(
cls,
check.str_param(job_name, "job_name"),
check.inst_param(repository_origin, "repository_origin", RepositoryPythonOrigin),
)
def get_id(self) -> str:
return create_snapshot_id(self)
@property
def executable_path(self) -> str:
return self.repository_origin.executable_path
def get_repo_pointer(self) -> CodePointer:
return self.repository_origin.code_pointer
| JobPythonOrigin |
python | ethereum__web3.py | tests/integration/go_ethereum/test_goethereum_http.py | {
"start": 2768,
"end": 3412
} | class ____(GoEthereumEthModuleTest):
def test_auto_provider_batching(self, auto_w3: "Web3") -> None:
with auto_w3.batch_requests() as batch:
assert isinstance(auto_w3.provider, AutoProvider)
assert auto_w3.provider._is_batching
assert auto_w3.provider._batching_context is not None
batch.add(auto_w3.eth.get_block("latest"))
batch.add(auto_w3.eth.get_block("earliest"))
batch.add(auto_w3.eth.get_block("pending"))
results = batch.execute()
assert not auto_w3.provider._is_batching
assert len(results) == 3
| TestGoEthereumEthModuleTest |
python | eventlet__eventlet | benchmarks/context.py | {
"start": 597,
"end": 2241
} | class ____(threading.Thread):
def __init__(self, event, wait_event):
threading.Thread.__init__(self)
self.counter = 0
self.event = event
self.wait_event = wait_event
def run(self):
while self.counter <= CONTEXT_SWITCHES:
self.wait_event.wait()
self.wait_event.clear()
self.counter += 1
self.event.set()
def test_thread():
event1 = threading.Event()
event2 = threading.Event()
event1.set()
thread1 = BenchThread(event1, event2)
thread2 = BenchThread(event2, event1)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("Testing with %d context switches" % CONTEXT_SWITCHES)
start = time.time()
test_thread()
print("threading: %.02f seconds" % (time.time() - start))
try:
eventlet.hubs.use_hub("eventlet.hubs.epolls")
start = time.time()
test_eventlet()
print("epoll: %.02f seconds" % (time.time() - start))
except:
print("epoll hub unavailable")
try:
eventlet.hubs.use_hub("eventlet.hubs.kqueue")
start = time.time()
test_eventlet()
print("kqueue: %.02f seconds" % (time.time() - start))
except:
print("kqueue hub unavailable")
try:
eventlet.hubs.use_hub("eventlet.hubs.poll")
start = time.time()
test_eventlet()
print("poll: %.02f seconds" % (time.time() - start))
except:
print("poll hub unavailable")
try:
eventlet.hubs.use_hub("eventlet.hubs.selects")
start = time.time()
test_eventlet()
print("select: %.02f seconds" % (time.time() - start))
except:
print("select hub unavailable")
| BenchThread |
python | apache__airflow | providers/smtp/src/airflow/providers/smtp/operators/smtp.py | {
"start": 1169,
"end": 5332
} | class ____(BaseOperator):
"""
Sends an email.
:param to: list of emails to send the email to. (templated)
:param from_email: email to send from. (templated)
:param subject: subject line for the email. (templated)
:param html_content: content of the email, html markup
is allowed. (templated)
:param files: file names to attach in email (templated)
:param cc: list of recipients to be added in CC field (templated)
:param bcc: list of recipients to be added in BCC field (templated)
:param mime_subtype: MIME sub content type
:param mime_charset: character set parameter added to the Content-Type
header.
:param custom_headers: additional headers to add to the MIME message.
"""
template_fields: Sequence[str] = (
"to",
"subject",
"html_content",
"from_email",
"files",
"cc",
"bcc",
"mime_subtype",
"mime_charset",
"conn_id",
"custom_headers",
)
template_fields_renderers = {"html_content": "html"}
template_ext: Sequence[str] = (".html",)
ui_color = "#e6faf9"
def __init__(
self,
*,
to: list[str] | str,
subject: str | None = None,
html_content: str | None = None,
from_email: str | None = None,
files: list | None = None,
cc: list[str] | str | None = None,
bcc: list[str] | str | None = None,
mime_subtype: str = "mixed",
mime_charset: str = "utf-8",
conn_id: str = "smtp_default",
custom_headers: dict[str, Any] | None = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.to = to
self.subject = subject
self.html_content = html_content
self.from_email = from_email
self.files = files or []
self.cc = cc
self.bcc = bcc
self.mime_subtype = mime_subtype
self.mime_charset = mime_charset
self.conn_id = conn_id
self.custom_headers = custom_headers
@staticmethod
def _read_template(template_path: str) -> str:
return Path(template_path).read_text().replace("\n", "").strip()
def execute(self, context: Context):
with SmtpHook(smtp_conn_id=self.conn_id) as smtp_hook:
fields_to_re_render = []
if self.from_email is None:
if smtp_hook.from_email is None:
raise AirflowException("You should provide `from_email` or define it in the connection.")
self.from_email = smtp_hook.from_email
fields_to_re_render.append("from_email")
if self.subject is None:
if smtp_hook.subject_template is None:
raise AirflowException(
"You should provide `subject` or define `subject_template` in the connection."
)
self.subject = self._read_template(smtp_hook.subject_template)
fields_to_re_render.append("subject")
if self.html_content is None:
if smtp_hook.html_content_template is None:
raise AirflowException(
"You should provide `html_content` or define `html_content_template` in the connection."
)
self.html_content = self._read_template(smtp_hook.html_content_template)
fields_to_re_render.append("html_content")
if fields_to_re_render:
self._do_render_template_fields(
self, fields_to_re_render, context, self.get_template_env(), set()
)
return smtp_hook.send_email_smtp(
to=self.to,
subject=self.subject,
html_content=self.html_content,
from_email=self.from_email,
files=self.files,
cc=self.cc,
bcc=self.bcc,
mime_subtype=self.mime_subtype,
mime_charset=self.mime_charset,
conn_id=self.conn_id,
custom_headers=self.custom_headers,
)
| EmailOperator |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/partitions/mapping/multi/multi_to_multi.py | {
"start": 712,
"end": 7766
} | class ____(
BaseMultiPartitionMapping,
PartitionMapping,
NamedTuple(
"_MultiPartitionMapping",
[("downstream_mappings_by_upstream_dimension", Mapping[str, DimensionPartitionMapping])],
),
):
"""Defines a correspondence between two MultiPartitionsDefinitions.
Accepts a mapping of upstream dimension name to downstream DimensionPartitionMapping, representing
the explicit correspondence between the upstream and downstream MultiPartitions dimensions
and the partition mapping used to calculate the downstream partitions.
Examples:
.. code-block:: python
weekly_abc = MultiPartitionsDefinition(
{
"abc": StaticPartitionsDefinition(["a", "b", "c"]),
"weekly": WeeklyPartitionsDefinition("2023-01-01"),
}
)
daily_123 = MultiPartitionsDefinition(
{
"123": StaticPartitionsDefinition(["1", "2", "3"]),
"daily": DailyPartitionsDefinition("2023-01-01"),
}
)
MultiPartitionMapping(
{
"abc": DimensionPartitionMapping(
dimension_name="123",
partition_mapping=StaticPartitionMapping({"a": "1", "b": "2", "c": "3"}),
),
"weekly": DimensionPartitionMapping(
dimension_name="daily",
partition_mapping=TimeWindowPartitionMapping(),
)
}
)
For upstream or downstream dimensions not explicitly defined in the mapping, Dagster will
assume an `AllPartitionsMapping`, meaning that all upstream partitions in those dimensions
will be mapped to all downstream partitions in those dimensions.
Examples:
.. code-block:: python
weekly_abc = MultiPartitionsDefinition(
{
"abc": StaticPartitionsDefinition(["a", "b", "c"]),
"daily": DailyPartitionsDefinition("2023-01-01"),
}
)
daily_123 = MultiPartitionsDefinition(
{
"123": StaticPartitionsDefinition(["1", "2", "3"]),
"daily": DailyPartitionsDefinition("2023-01-01"),
}
)
MultiPartitionMapping(
{
"daily": DimensionPartitionMapping(
dimension_name="daily",
partition_mapping=IdentityPartitionMapping(),
)
}
)
# Will map `daily_123` partition key {"123": "1", "daily": "2023-01-01"} to the upstream:
# {"abc": "a", "daily": "2023-01-01"}
# {"abc": "b", "daily": "2023-01-01"}
# {"abc": "c", "daily": "2023-01-01"}
Args:
downstream_mappings_by_upstream_dimension (Mapping[str, DimensionPartitionMapping]): A
mapping that defines an explicit correspondence between one dimension of the upstream
MultiPartitionsDefinition and one dimension of the downstream MultiPartitionsDefinition.
Maps a string representing upstream dimension name to downstream DimensionPartitionMapping,
containing the downstream dimension name and partition mapping.
"""
def __new__(
cls, downstream_mappings_by_upstream_dimension: Mapping[str, DimensionPartitionMapping]
):
return super().__new__(
cls,
downstream_mappings_by_upstream_dimension=check.mapping_param(
downstream_mappings_by_upstream_dimension,
"downstream_mappings_by_upstream_dimension",
key_type=str,
value_type=DimensionPartitionMapping,
),
)
@property
def description(self) -> str:
return "\n ".join(
[
(
f"Upstream dimension '{upstream_dim}' mapped to downstream dimension "
f"'{downstream_mapping.dimension_name}' using {type(downstream_mapping.partition_mapping).__name__}."
)
for upstream_dim, downstream_mapping in self.downstream_mappings_by_upstream_dimension.items()
]
)
def validate_partition_mapping(
self,
upstream_partitions_def: PartitionsDefinition,
downstream_partitions_def: Optional[PartitionsDefinition],
):
self._check_all_dimensions_accounted_for(
upstream_partitions_def,
downstream_partitions_def,
)
def get_dimension_dependencies(
self,
upstream_partitions_def: PartitionsDefinition,
downstream_partitions_def: PartitionsDefinition,
) -> Sequence[DimensionDependency]:
self._check_all_dimensions_accounted_for(
upstream_partitions_def,
downstream_partitions_def,
)
return [
DimensionDependency(
mapping.partition_mapping,
upstream_dimension_name=upstream_dimension,
downstream_dimension_name=mapping.dimension_name,
)
for upstream_dimension, mapping in self.downstream_mappings_by_upstream_dimension.items()
]
def _check_all_dimensions_accounted_for(
self,
upstream_partitions_def: PartitionsDefinition,
downstream_partitions_def: Optional[PartitionsDefinition],
) -> None:
if any(
not isinstance(partitions_def, MultiPartitionsDefinition)
for partitions_def in (upstream_partitions_def, downstream_partitions_def)
):
check.failed(
"Both partitions defs provided to a MultiPartitionMapping must be multi-partitioned"
)
upstream_dimension_names = {
dim.name
for dim in cast("MultiPartitionsDefinition", upstream_partitions_def).partitions_defs
}
dimension_names = {
dim.name
for dim in cast("MultiPartitionsDefinition", downstream_partitions_def).partitions_defs
}
for (
upstream_dimension_name,
dimension_mapping,
) in self.downstream_mappings_by_upstream_dimension.items():
if upstream_dimension_name not in upstream_dimension_names:
check.failed(
"Dimension mapping has an upstream dimension name that is not in the upstream "
"partitions def"
)
if dimension_mapping.dimension_name not in dimension_names:
check.failed(
"Dimension mapping has a downstream dimension name that is not in the"
" downstream partitions def"
)
upstream_dimension_names.remove(upstream_dimension_name)
dimension_names.remove(dimension_mapping.dimension_name)
| MultiPartitionMapping |
python | getsentry__sentry | tests/sentry/notifications/notification_action/test_issue_alert_registry_handlers.py | {
"start": 20508,
"end": 20883
} | class ____(TestTicketingIssueAlertHandlerBase):
def setUp(self) -> None:
super().setUp()
self.handler = AzureDevopsIssueAlertHandler()
def test_build_rule_action_blob(self) -> None:
for expected in AZURE_DEVOPS_ACTION_DATA_BLOBS:
self._test_build_rule_action_blob(expected, Action.Type.AZURE_DEVOPS)
| TestAzureDevopsIssueAlertHandler |
python | jazzband__django-formtools | tests/wizard/test_forms.py | {
"start": 367,
"end": 852
} | class ____(http.HttpRequest):
def __init__(self, POST=None):
super().__init__()
self.method = "POST" if POST else "GET"
if POST is not None:
self.POST.update(POST)
self.session = {}
self._dont_enforce_csrf_checks = True
def get_request(*args, **kwargs):
request = DummyRequest(*args, **kwargs)
engine = import_module(settings.SESSION_ENGINE)
request.session = engine.SessionStore(None)
return request
| DummyRequest |
python | dask__dask | dask/array/tests/test_slicing.py | {
"start": 11899,
"end": 34507
} | class ____:
def __getitem__(self, key):
return key
@pytest.mark.skip(reason="really long test")
def test_slicing_exhaustively():
x = np.random.default_rng().random(6, 7, 8)
a = da.from_array(x, chunks=(3, 3, 3))
I = ReturnItem()
# independent indexing along different axes
indexers = [0, -2, I[:], I[:5], [0, 1], [0, 1, 2], [4, 2], I[::-1], None, I[:0], []]
for i in indexers:
assert_eq(x[i], a[i])
for j in indexers:
assert_eq(x[i][:, j], a[i][:, j])
assert_eq(x[:, i][j], a[:, i][j])
for k in indexers:
assert_eq(x[..., i][:, j][k], a[..., i][:, j][k])
# repeated indexing along the first axis
first_indexers = [I[:], I[:5], np.arange(5), [3, 1, 4, 5, 0], np.arange(6) < 6]
second_indexers = [0, -1, 3, I[:], I[:3], I[2:-1], [2, 4], [], I[:0]]
for i in first_indexers:
for j in second_indexers:
assert_eq(x[i][j], a[i][j])
def test_slicing_with_negative_step_flops_keys():
x = da.arange(10, chunks=5)
y = x[:1:-1]
assert (x.name, 1) in y.dask[(y.name, 0)].dependencies
assert (x.name, 0) in y.dask[(y.name, 1)].dependencies
assert_eq(y, np.arange(10)[:1:-1])
assert y.chunks == ((5, 3),)
assert y.dask[(y.name, 0)] == Task(
(y.name, 0), getitem, TaskRef((x.name, 1)), (slice(-1, -6, -1),)
)
assert y.dask[(y.name, 1)] == Task(
(y.name, 1), getitem, TaskRef((x.name, 0)), (slice(-1, -4, -1),)
)
def test_empty_slice():
x = da.ones((5, 5), chunks=(2, 2), dtype="i4")
y = x[:0]
assert_eq(y, np.ones((5, 5), dtype="i4")[:0])
def test_multiple_list_slicing():
x = np.random.default_rng().random((6, 7, 8))
a = da.from_array(x, chunks=(3, 3, 3))
assert_eq(x[:, [0, 1, 2]][[0, 1]], a[:, [0, 1, 2]][[0, 1]])
def test_boolean_list_slicing():
with pytest.raises(IndexError):
da.asarray(range(2))[[True]]
with pytest.raises(IndexError):
da.asarray(range(2))[[False, False, False]]
x = np.arange(5)
ind = [True, False, False, False, True]
assert_eq(da.asarray(x)[ind], x[ind])
# https://github.com/dask/dask/issues/3706
ind = [True]
assert_eq(da.asarray([0])[ind], np.arange(1)[ind])
def test_boolean_numpy_array_slicing():
with pytest.raises(IndexError):
da.asarray(range(2))[np.array([True])]
with pytest.raises(IndexError):
da.asarray(range(2))[np.array([False, False, False])]
x = np.arange(5)
ind = np.array([True, False, False, False, True])
assert_eq(da.asarray(x)[ind], x[ind])
# https://github.com/dask/dask/issues/3706
ind = np.array([True])
assert_eq(da.asarray([0])[ind], np.arange(1)[ind])
def test_empty_list():
x = np.ones((5, 5, 5), dtype="i4")
dx = da.from_array(x, chunks=2)
assert_eq(dx[[], :3, :2], x[[], :3, :2])
assert_eq(dx[:3, [], :2], x[:3, [], :2])
assert_eq(dx[:3, :2, []], x[:3, :2, []])
def test_uneven_chunks():
assert da.ones(20, chunks=5)[::2].chunks == ((3, 2, 3, 2),)
def test_new_blockdim():
assert new_blockdim(20, [5, 5, 5, 5], slice(0, None, 2)) == [3, 2, 3, 2]
def test_slicing_consistent_names():
x = np.arange(100).reshape((10, 10))
a = da.from_array(x, chunks=(5, 5))
assert same_keys(a[0], a[0])
assert same_keys(a[:, [1, 2, 3]], a[:, [1, 2, 3]])
assert same_keys(a[:, 5:2:-1], a[:, 5:2:-1])
assert same_keys(a[0, ...], a[0, ...])
assert same_keys(a[...], a[...])
assert same_keys(a[[1, 3, 5]], a[[1, 3, 5]])
assert same_keys(a[-11:11], a[:])
assert same_keys(a[-11:-9], a[:1])
assert same_keys(a[-1], a[9])
assert same_keys(a[0::-1], a[0:-11:-1])
def test_slicing_consistent_names_after_normalization():
x = da.zeros(10, chunks=(5,))
assert same_keys(x[0:], x[:10])
assert same_keys(x[0:], x[0:10])
assert same_keys(x[0:], x[0:10:1])
assert same_keys(x[:], x[0:10:1])
def test_sanitize_index_element():
with pytest.raises(TypeError):
_sanitize_index_element("Hello!")
def test_sanitize_index():
pd = pytest.importorskip("pandas")
with pytest.raises(TypeError):
sanitize_index("Hello!")
np.testing.assert_equal(sanitize_index(pd.Series([1, 2, 3])), [1, 2, 3])
np.testing.assert_equal(sanitize_index((1, 2, 3)), [1, 2, 3])
def test_uneven_blockdims():
blockdims = ((31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30), (100,))
index = (slice(240, 270), slice(None))
dsk_out, bd_out = slice_array("in", "out", blockdims, index)
sol = {
("in", 0, 0): Task(
("in", 0, 0),
getitem,
TaskRef(("out", 7, 0)),
(slice(28, 31, 1), slice(None)),
),
("in", 1, 0): Task(
("in", 1, 0),
getitem,
TaskRef(("out", 8, 0)),
(slice(0, 27, 1), slice(None)),
),
}
assert dsk_out == sol
assert bd_out == ((3, 27), (100,))
blockdims = ((31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30),) * 2
index = (slice(240, 270), slice(180, 230))
dsk_out, bd_out = slice_array("in", "out", blockdims, index)
sol = {
("in", 0, 0): Task(
("in", 0, 0),
getitem,
TaskRef(("out", 7, 5)),
(slice(28, 31, 1), slice(29, 30, 1)),
),
("in", 0, 1): Task(
("in", 0, 0),
getitem,
TaskRef(("out", 7, 6)),
(slice(28, 31, 1), slice(None)),
),
("in", 0, 2): Task(
("in", 0, 0),
getitem,
TaskRef(("out", 7, 7)),
(slice(28, 31, 1), slice(0, 18, 1)),
),
("in", 1, 0): Task(
("in", 0, 0),
getitem,
TaskRef(("out", 8, 5)),
(slice(0, 27, 1), slice(29, 30, 1)),
),
("in", 1, 1): Task(
("in", 0, 0),
getitem,
TaskRef(("out", 8, 6)),
(slice(0, 27, 1), slice(None)),
),
("in", 1, 2): Task(
("in", 0, 0),
getitem,
TaskRef(("out", 8, 7)),
(slice(0, 27, 1), slice(0, 18, 1)),
),
}
assert dsk_out == sol
assert bd_out == ((3, 27), (1, 31, 18))
def test_oob_check():
x = da.ones(5, chunks=(2,))
with pytest.raises(IndexError):
x[6]
with pytest.raises(IndexError):
x[[6]]
with pytest.raises(IndexError):
x[-10]
with pytest.raises(IndexError):
x[[-10]]
with pytest.raises(IndexError):
x[0, 0]
@pytest.mark.parametrize("idx_chunks", [None, 3, 2, 1])
@pytest.mark.parametrize("x_chunks", [None, (3, 5), (2, 3), (1, 2), (1, 1)])
def test_index_with_int_dask_array(x_chunks, idx_chunks):
# test data is crafted to stress use cases:
# - pick from different chunks of x out of order
# - a chunk of x contains no matches
# - only one chunk of x
x = np.array(
[[10, 20, 30, 40, 50], [60, 70, 80, 90, 100], [110, 120, 130, 140, 150]]
)
idx = np.array([3, 0, 1])
expect = np.array([[40, 10, 20], [90, 60, 70], [140, 110, 120]])
if x_chunks is not None:
x = da.from_array(x, chunks=x_chunks)
if idx_chunks is not None:
idx = da.from_array(idx, chunks=idx_chunks)
assert_eq(x[:, idx], expect)
assert_eq(x.T[idx, :], expect.T)
@pytest.mark.parametrize("chunks", [1, 2, 3])
def test_index_with_int_dask_array_0d(chunks):
# Slice by 0-dimensional array
x = da.from_array([[10, 20, 30], [40, 50, 60]], chunks=chunks)
idx0 = da.from_array(1, chunks=1)
assert_eq(x[idx0, :], x[1, :])
assert_eq(x[:, idx0], x[:, 1])
@pytest.mark.parametrize("chunks", [1, 2, 3, 4, 5])
def test_index_with_int_dask_array_nanchunks(chunks):
# Slice by array with nan-sized chunks
a = da.arange(-2, 3, chunks=chunks)
assert_eq(a[a.nonzero()], np.array([-2, -1, 1, 2]))
# Edge case: the nan-sized chunks resolve to size 0
a = da.zeros(5, chunks=chunks)
assert_eq(a[a.nonzero()], np.array([]))
@pytest.mark.parametrize("chunks", [2, 4])
def test_index_with_int_dask_array_negindex(chunks):
a = da.arange(4, chunks=chunks)
idx = da.from_array([-1, -4], chunks=1)
assert_eq(a[idx], np.array([3, 0]))
@pytest.mark.parametrize("chunks", [2, 4])
def test_index_with_int_dask_array_indexerror(chunks):
a = da.arange(4, chunks=chunks)
idx = da.from_array([4], chunks=1)
with pytest.raises(IndexError):
a[idx].compute()
idx = da.from_array([-5], chunks=1)
with pytest.raises(IndexError):
a[idx].compute()
@pytest.mark.parametrize(
"dtype", ["int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64"]
)
def test_index_with_int_dask_array_dtypes(dtype):
a = da.from_array([10, 20, 30, 40], chunks=-1)
idx = da.from_array(np.array([1, 2]).astype(dtype), chunks=1)
assert_eq(a[idx], np.array([20, 30]))
def test_index_with_int_dask_array_nocompute():
"""Test that when the indices are a dask array
they are not accidentally computed
"""
def crash():
raise NotImplementedError()
x = da.arange(5, chunks=-1)
idx = da.Array({("x", 0): (crash,)}, name="x", chunks=((2,),), dtype=np.int64)
result = x[idx]
with pytest.raises(NotImplementedError):
result.compute()
def test_index_with_bool_dask_array():
x = np.arange(36).reshape((6, 6))
d = da.from_array(x, chunks=(3, 3))
ind = np.asarray([True, True, False, True, False, False], dtype=bool)
ind = da.from_array(ind, chunks=2)
for index in [ind, (slice(1, 9, 2), ind), (ind, slice(2, 8, 1))]:
x_index = dask.compute(index)[0]
assert_eq(x[x_index], d[index])
def test_index_with_bool_dask_array_2():
rng = np.random.default_rng()
x = rng.random((10, 10, 10))
ind = rng.random(10) > 0.5
d = da.from_array(x, chunks=(3, 4, 5))
dind = da.from_array(ind, chunks=4)
index = [slice(1, 9, 1), slice(None)]
for i in range(x.ndim):
index2 = index[:]
index2.insert(i, dind)
index3 = index[:]
index3.insert(i, ind)
assert_eq(x[tuple(index3)], d[tuple(index2)])
@pytest.mark.xfail
def test_cull():
x = da.ones(1000, chunks=(10,))
for slc in [1, slice(0, 30), slice(0, None, 100)]:
y = x[slc]
assert len(y.dask) < len(x.dask)
@pytest.mark.parametrize("shape", [(2,), (2, 3), (2, 3, 5)])
@pytest.mark.parametrize(
"index", [(Ellipsis,), (None, Ellipsis), (Ellipsis, None), (None, Ellipsis, None)]
)
def test_slicing_with_Nones(shape, index):
x = np.random.default_rng().random(shape)
d = da.from_array(x, chunks=shape)
assert_eq(x[index], d[index])
indexers = [Ellipsis, slice(2), 0, 1, -2, -1, slice(-2, None), None]
"""
# We comment this out because it is 4096 tests
@pytest.mark.parametrize('a', indexers)
@pytest.mark.parametrize('b', indexers)
@pytest.mark.parametrize('c', indexers)
@pytest.mark.parametrize('d', indexers)
def test_slicing_none_int_ellipses(a, b, c, d):
if (a, b, c, d).count(Ellipsis) > 1:
return
shape = (2,3,5,7,11)
x = np.arange(np.prod(shape)).reshape(shape)
y = da.core.asarray(x)
xx = x[a, b, c, d]
yy = y[a, b, c, d]
assert_eq(xx, yy)
"""
def test_slicing_integer_no_warnings():
# https://github.com/dask/dask/pull/2457/
X = da.random.default_rng().random(size=(100, 2), chunks=(2, 2))
idx = np.array([0, 0, 1, 1])
with warnings.catch_warnings(record=True) as record:
X[idx].compute()
assert not record
@pytest.mark.slow
def test_slicing_none_int_ellipes():
shape = (2, 3, 5, 7, 11)
x = np.arange(np.prod(shape)).reshape(shape)
y = da.core.asarray(x)
for ind in itertools.product(indexers, indexers, indexers, indexers):
if ind.count(Ellipsis) > 1:
continue
assert_eq(x[ind], y[ind])
def test_None_overlap_int():
a, b, c, d = (0, slice(None, 2, None), None, Ellipsis)
shape = (2, 3, 5, 7, 11)
x = np.arange(np.prod(shape)).reshape(shape)
y = da.core.asarray(x)
xx = x[a, b, c, d]
yy = y[a, b, c, d]
assert_eq(xx, yy)
def test_negative_n_slicing():
assert_eq(da.ones(2, chunks=2)[-2], np.ones(2)[-2])
def test_negative_list_slicing():
x = np.arange(5)
dx = da.from_array(x, chunks=2)
assert_eq(dx[[0, -5]], x[[0, -5]])
assert_eq(dx[[4, -1]], x[[4, -1]])
def test_permit_oob_slices():
x = np.arange(5)
dx = da.from_array(x, chunks=2)
assert_eq(x[-102:], dx[-102:])
assert_eq(x[102:], dx[102:])
assert_eq(x[:102], dx[:102])
assert_eq(x[:-102], dx[:-102])
def test_normalize_index():
assert normalize_index((Ellipsis, None), (10,)) == (slice(None), None)
assert normalize_index(5, (np.nan,)) == (5,)
assert normalize_index(-5, (np.nan,)) == (-5,)
(result,) = normalize_index([-5, -2, 1], (np.nan,))
assert result.tolist() == [-5, -2, 1]
assert normalize_index(slice(-5, -2), (np.nan,)) == (slice(-5, -2),)
def test_take_semi_sorted():
x = da.ones(10, chunks=(5,))
index = np.arange(15) % 10
y = x[index]
assert y.chunks == ((5, 5, 5),)
def test_getitem_avoids_large_chunks():
with dask.config.set({"array.chunk-size": "0.1Mb"}):
a = np.arange(2 * 128 * 128, dtype="int64").reshape(2, 128, 128)
indexer = [0] + [1] * 11
arr = da.from_array(a, chunks=(1, 8, 8))
result = arr[
indexer
] # small chunks within the chunk-size limit should NOT raise PerformanceWarning
expected = a[indexer]
assert_eq(result, expected)
arr = da.from_array(a, chunks=(1, 128, 128)) # large chunks
expected = a[indexer]
result = arr[indexer]
assert_eq(result, expected)
assert result.chunks == ((1,) * 12, (128,), (128,))
# Users can silence the warning
with dask.config.set({"array.slicing.split-large-chunks": False}):
with warnings.catch_warnings(record=True) as record:
result = arr[indexer]
assert_eq(result, expected)
assert not record
# Users can silence the warning
with dask.config.set({"array.slicing.split-large-chunks": True}):
with warnings.catch_warnings(record=True) as record:
result = arr[indexer]
assert_eq(result, expected)
assert not record
assert result.chunks == ((1,) * 12, (128,), (128,))
def test_getitem_avoids_large_chunks_missing():
# We cannot apply the "avoid large chunks" optimization when
# the chunks have unknown sizes.
with dask.config.set({"array.chunk-size": "0.1Mb"}):
a = np.arange(4 * 500 * 500).reshape(4, 500, 500)
arr = da.from_array(a, chunks=(1, 500, 500))
arr._chunks = ((1, 1, 1, 1), (np.nan,), (np.nan,))
indexer = [0, 1] + [2] * 100 + [3]
expected = a[indexer]
result = arr[indexer]
assert_eq(result, expected)
def test_take_avoids_large_chunks():
# unit test for https://github.com/dask/dask/issues/6270
with dask.config.set({"array.slicing.split-large-chunks": True}):
chunks = ((1, 1, 1, 1), (500,), (500,))
index = np.array([0, 1] + [2] * 101 + [3])
chunks2, dsk = take("a", "b", chunks, index)
assert chunks2 == ((1,) * 104, (500,), (500,))
assert len(dsk) == 105
index = np.array([0] * 101 + [1, 2, 3])
chunks2, dsk = take("a", "b", chunks, index)
assert chunks2 == ((1,) * 104, (500,), (500,))
assert len(dsk) == 105
index = np.array([0, 1, 2] + [3] * 101)
chunks2, dsk = take("a", "b", chunks, index)
assert chunks2 == ((1,) * 104, (500,), (500,))
assert len(dsk) == 105
chunks = ((500,), (1, 1, 1, 1), (500,))
index = np.array([0, 1, 2] + [3] * 101)
chunks2, dsk = take("a", "b", chunks, index, axis=1)
assert chunks2 == ((500,), (1,) * 104, (500,))
assert len(dsk) == 105
def test_pathological_unsorted_slicing():
x = da.ones(100, chunks=10)
# [0, 10, 20, ... 90, 1, 11, 21, ... 91, ...]
index = np.arange(100).reshape(10, 10).ravel(order="F")
assert_eq(x[index], x.compute()[index])
@pytest.mark.parametrize("params", [(2, 2, 1), (5, 3, 2)])
def test_setitem_with_different_chunks_preserves_shape(params):
"""Reproducer for https://github.com/dask/dask/issues/3730.
Mutating based on an array with different chunks can cause new chunks to be
used. We need to ensure those new chunk sizes are applied to the mutated
array, otherwise the array won't generate the correct keys.
"""
array_size, chunk_size1, chunk_size2 = params
x = da.zeros(array_size, chunks=chunk_size1)
mask = da.zeros(array_size, chunks=chunk_size2)
x[mask] = 1
result = x.compute()
assert x.shape == result.shape
def test_gh3579():
assert_eq(np.arange(10)[0::-1], da.arange(10, chunks=3)[0::-1])
assert_eq(np.arange(10)[::-1], da.arange(10, chunks=3)[::-1])
def test_make_blockwise_sorted_slice():
x = da.arange(8, chunks=4)
index = np.array([6, 0, 4, 2, 7, 1, 5, 3])
a, b = make_block_sorted_slices(index, x.chunks)
index2 = np.array([0, 2, 4, 6, 1, 3, 5, 7])
index3 = np.array([3, 0, 2, 1, 7, 4, 6, 5])
np.testing.assert_array_equal(a, index2)
np.testing.assert_array_equal(b, index3)
@pytest.mark.filterwarnings("ignore:Slicing:dask.array.core.PerformanceWarning")
@pytest.mark.parametrize(
"size, chunks", [((100, 2), (50, 2)), ((100, 2), (37, 1)), ((100,), (55,))]
)
def test_shuffle_slice(size, chunks):
x = da.random.default_rng().integers(0, 1000, size=size, chunks=chunks)
index = np.arange(len(x))
np.random.default_rng().shuffle(index)
a = x[index]
b = shuffle_slice(x, index)
assert_eq(a, b)
index = np.arange(1, len(x)).tolist()
index.append(0)
index = np.array(index)
a = x[index]
b = shuffle_slice(x, index)
assert_eq(a, b)
def test_unknown_chunks_length_one():
a = np.arange(256, dtype=int)
arr = da.from_array(a, chunks=(256,))
# np.flatnonzero dispatches
result = np.flatnonzero(arr)
assert_eq(result[[0, -1]], np.flatnonzero(a)[[0, -1]])
result = da.flatnonzero(arr)
assert_eq(result[[0, -1]], np.flatnonzero(a)[[0, -1]])
a = a.reshape(16, 16)
arr = da.from_array(a, chunks=(8, 16))
arr._chunks = ((8, 8), (np.nan,))
result = arr[:, [0, -1]]
expected = a[:, [0, -1]]
assert_eq(result, expected)
arr = da.from_array(a, chunks=(8, 8))
arr._chunks = ((8, 8), (np.nan, np.nan))
with pytest.raises(ValueError, match="Array chunk size or shape"):
arr[:, [0, -1]]
@pytest.mark.parametrize("lock", [True, False])
@pytest.mark.parametrize("asarray", [True, False])
@pytest.mark.parametrize("fancy", [True, False])
def test_gh4043(lock, asarray, fancy):
a1 = da.from_array(np.zeros(3), chunks=1, asarray=asarray, lock=lock, fancy=fancy)
a2 = da.from_array(np.ones(3), chunks=1, asarray=asarray, lock=lock, fancy=fancy)
al = da.stack([a1, a2])
assert_eq(al, al)
def test_slice_array_3d_with_bool_numpy_array():
# https://github.com/dask/dask/issues/6089
array = da.arange(0, 24).reshape((4, 3, 2))
mask = np.arange(0, 24).reshape((4, 3, 2)) > 12
actual = array[mask].compute()
expected = np.arange(13, 24)
assert_eq(actual, expected)
def test_slice_masked_arrays():
arr = np.ma.array(range(8), mask=[0, 0, 1, 0, 0, 1, 0, 1])
darr = da.from_array(arr, chunks=(4, 4))
assert_eq(darr[[2, 6]], arr[[2, 6]])
def test_slice_array_null_dimension():
array = da.from_array(np.zeros((3, 0)))
expected = np.zeros((3, 0))[[0]]
assert_eq(array[[0]], expected)
def test_take_sorted_indexer():
arr = da.ones((250, 100), chunks=((50, 100, 33, 67), 100))
indexer = list(range(0, 250))
result = arr[indexer, :]
assert_eq(arr, result)
assert {
**dict(arr.dask),
**{
k: Alias(k, k2)
for k, k2 in zip(
[k for k in dict(result.dask) if "getitem" in k[0]],
dict(arr.dask).keys(),
)
},
} == dict(result.dask)
def test_all_none_slices_just_mappings():
arr = da.ones((10, 10), chunks=(1, 5))
result = arr[slice(None, 6), slice(None)]
dsk = dict(result.dask)
assert len([k for k in dsk if "getitem" in k[0]]) == 12
# check that we are just mapping the keys
assert all(isinstance(v, Alias) for k, v in dsk.items() if "getitem" in k[0])
assert_eq(result, np.ones((6, 10)))
def test_minimal_dtype_doesnt_overflow():
x = np.arange(1980)
dx = dask.array.from_array(x, chunks=[248])
ib = np.zeros(1980, dtype=bool)
ib[1560:1860] = True
assert_eq(dx[ib], x[ib])
def test_vindex_with_dask_array():
arr = np.array([0.2, 0.4, 0.6])
darr = da.from_array(arr, chunks=-1)
indexer = np.random.randint(0, 3, 8).reshape(4, 2).astype(int)
dindexer = da.from_array(indexer, chunks=(2, 2))
assert_eq(darr.vindex[dindexer], arr[indexer])
msg = "vindex does not support indexing"
with pytest.raises(IndexError, match=msg):
darr.rechunk((1, 1)).vindex[dindexer]
with pytest.raises(IndexError, match=msg):
darr.reshape((3, 1)).vindex[dindexer]
with pytest.raises(IndexError, match=msg):
darr.vindex[(dindexer, None)]
def test_positional_indexer_newaxis():
arr = da.array([0, 1, 2])
new = arr[[True, True, False], np.newaxis]
assert_eq(new, arr.compute()[[True, True, False], np.newaxis])
@pytest.mark.parametrize(
"shapes",
[
(10, 10),
(np.nan, np.nan),
pytest.param(
(10, np.nan), marks=pytest.mark.xfail(reason="Not implemented", strict=True)
),
pytest.param(
(np.nan, 10), marks=pytest.mark.xfail(reason="Not implemented", strict=True)
),
],
)
def test_boolean_mask_with_unknown_shape(
shapes: tuple[float | int, float | int],
) -> None:
x_shape, mask_shape = shapes
arr = delayed(np.ones(10))
x = da.concatenate(
[
da.from_delayed(arr, shape=(x_shape,), dtype=float),
da.from_delayed(arr, shape=(x_shape,), dtype=float),
]
)
mask = da.concatenate(
[
da.from_delayed(arr, shape=(mask_shape,), dtype=bool),
da.from_delayed(arr, shape=(mask_shape,), dtype=bool),
]
)
x[mask] = 2
expected = np.full(20, 2.0)
assert_eq(x, expected)
| ReturnItem |
python | pytorch__pytorch | torch/_export/serde/schema.py | {
"start": 4346,
"end": 4475
} | class ____(_Union):
as_tensor: Annotated[TensorArgument, 20]
as_none: Annotated[bool, 10]
@dataclass
| OptionalTensorArgument |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 2385,
"end": 2831
} | class ____(str, BaseEnum):
"""The consistency levels when writing to Weaviate with replication enabled.
Attributes:
ALL: Wait for confirmation of write success from all, `N`, replicas.
ONE: Wait for confirmation of write success from only one replica.
QUORUM: Wait for confirmation of write success from a quorum: `N/2+1`, of replicas.
"""
ALL = "ALL"
ONE = "ONE"
QUORUM = "QUORUM"
| ConsistencyLevel |
python | huggingface__transformers | src/transformers/models/seamless_m4t/modeling_seamless_m4t.py | {
"start": 12840,
"end": 15390
} | class ____(nn.Module):
"""Relative positional encoding module."""
def __init__(self, config):
super().__init__()
self.max_len = config.max_source_positions
self.d_model = config.hidden_size
self.pe = None
self.extend_pe(torch.tensor(0.0).expand(1, self.max_len))
def extend_pe(self, x):
# Reset the positional encodings
if self.pe is not None:
# self.pe contains both positive and negative parts
# the length of self.pe is 2 * input_len - 1
if self.pe.size(1) >= x.size(1) * 2 - 1:
if self.pe.dtype != x.dtype or self.pe.device != x.device:
self.pe = self.pe.to(dtype=x.dtype, device=x.device)
return
# Suppose `i` is the position of query vector and `j` is the
# position of key vector. We use positive relative positions when keys
# are to the left (i>j) and negative relative positions otherwise (i<j).
pe_positive = torch.zeros(x.size(1), self.d_model)
pe_negative = torch.zeros(x.size(1), self.d_model)
position = torch.arange(0, x.size(1), dtype=torch.int64).float().unsqueeze(1)
div_term = torch.exp(
torch.arange(0, self.d_model, 2, dtype=torch.int64).float() * -(math.log(10000.0) / self.d_model)
)
pe_positive[:, 0::2] = torch.sin(position * div_term)
pe_positive[:, 1::2] = torch.cos(position * div_term)
pe_negative[:, 0::2] = torch.sin(-1 * position * div_term)
pe_negative[:, 1::2] = torch.cos(-1 * position * div_term)
# Reverse the order of positive indices and concat both positive and
# negative indices. This is used to support the shifting trick
# as in https://huggingface.co/papers/1901.02860
pe_positive = torch.flip(pe_positive, [0]).unsqueeze(0)
pe_negative = pe_negative[1:].unsqueeze(0)
pe = torch.cat([pe_positive, pe_negative], dim=1)
self.pe = pe.to(device=x.device, dtype=x.dtype)
def forward(self, hidden_states: torch.Tensor):
self.extend_pe(hidden_states)
start_idx = self.pe.size(1) // 2 - hidden_states.size(1) + 1
end_idx = self.pe.size(1) // 2 + hidden_states.size(1)
relative_position_embeddings = self.pe[:, start_idx:end_idx]
return relative_position_embeddings
# Copied from transformers.models.wav2vec2_conformer.modeling_wav2vec2_conformer.Wav2Vec2ConformerSamePadLayer with Wav2Vec2->SeamlessM4T
| SeamlessM4TConformerRelPositionalEmbedding |
python | kamyu104__LeetCode-Solutions | Python/maximum-strong-pair-xor-ii.py | {
"start": 4077,
"end": 4896
} | class ____(object):
def maximumStrongPairXor(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 0
for i in reversed(xrange(max(nums).bit_length())):
prefix_min, prefix_max = {}, {}
for x in nums:
y = x>>i
if y not in prefix_min:
prefix_min[y] = prefix_max[y] = x
prefix_min[y] = min(prefix_min[y], x)
prefix_max[y] = max(prefix_max[y], x)
result <<= 1
for x in prefix_min.iterkeys():
y = (result|1)^x
assert(x != y)
if y in prefix_max and prefix_min[max(x, y)] <= 2*prefix_max[min(x, y)]:
result |= 1
break
return result
| Solution3 |
python | tensorflow__tensorflow | tensorflow/python/summary/writer/event_file_writer.py | {
"start": 5622,
"end": 8225
} | class ____(threading.Thread):
"""Thread that logs events."""
def __init__(self, queue, ev_writer, flush_secs, flush_complete,
flush_sentinel, close_sentinel):
"""Creates an _EventLoggerThread.
Args:
queue: A CloseableQueue from which to dequeue events. The queue will be
closed just before the thread exits, whether due to `close_sentinel` or
any exception raised in the writing loop.
ev_writer: An event writer. Used to log brain events for
the visualizer.
flush_secs: How often, in seconds, to flush the
pending file to disk.
flush_complete: A threading.Event that will be set whenever a flush
operation requested via `flush_sentinel` has been completed.
flush_sentinel: A sentinel element in queue that tells this thread to
flush the writer and mark the current flush operation complete.
close_sentinel: A sentinel element in queue that tells this thread to
terminate and close the queue.
"""
threading.Thread.__init__(self, name="EventLoggerThread")
self.daemon = True
self._queue = queue
self._ev_writer = ev_writer
self._flush_secs = flush_secs
# The first event will be flushed immediately.
self._next_event_flush_time = 0
self._flush_complete = flush_complete
self._flush_sentinel = flush_sentinel
self._close_sentinel = close_sentinel
# Populated when writing logic raises an exception and kills the thread.
self.failure_exc_info = ()
def run(self):
try:
while True:
event = self._queue.get()
if event is self._close_sentinel:
return
elif event is self._flush_sentinel:
self._ev_writer.Flush()
self._flush_complete.set()
else:
self._ev_writer.WriteEvent(event)
# Flush the event writer every so often.
now = time.time()
if now > self._next_event_flush_time:
self._ev_writer.Flush()
self._next_event_flush_time = now + self._flush_secs
except Exception as e:
logging.error("EventFileWriter writer thread error: %s", e)
self.failure_exc_info = sys.exc_info()
raise
finally:
# When exiting the thread, always complete any pending flush operation
# (to unblock flush() calls) and close the queue (to unblock add_event()
# calls, including those used by flush() and close()), which ensures that
# code using EventFileWriter doesn't deadlock if this thread dies.
self._flush_complete.set()
self._queue.close()
| _EventLoggerThread |
python | PrefectHQ__prefect | tests/utilities/schema_tools/test_validation.py | {
"start": 29272,
"end": 31481
} | class ____:
def test_non_error_placeholder(self):
class ValidPlaceholder(Placeholder):
pass
placeholder = ValidPlaceholder()
assert not placeholder.is_error
errors = [
MockValidationError(
message="'object at XXX is not of type 'string'",
relative_path=["param"],
instance=placeholder,
)
]
error_obj = build_error_obj(errors)
assert error_obj == {"valid": True, "errors": []}
def test_invalid_json(self):
errors = [
MockValidationError(
message=InvalidJSON().message,
relative_path=["param"],
instance=InvalidJSON(),
)
]
error_obj = build_error_obj(errors)
assert error_obj == {
"valid": False,
"errors": [
{
"property": "param",
"errors": ["Invalid JSON"],
}
],
}
def test_invalid_json_with_detail(self):
errors = [
MockValidationError(
message=InvalidJSON(detail="error at char 5").message,
relative_path=["param"],
instance=InvalidJSON(detail="error at char 5"),
)
]
error_obj = build_error_obj(errors)
assert error_obj == {
"valid": False,
"errors": [
{
"property": "param",
"errors": ["Invalid JSON: error at char 5"],
}
],
}
def test_value_not_found(self):
errors = [
MockValidationError(
message=ValueNotFound().message,
relative_path=["param"],
instance=ValueNotFound(),
)
]
error_obj = build_error_obj(errors)
assert error_obj == {
"valid": False,
"errors": [
{
"property": "param",
"errors": ["Missing 'value' key in __prefect object"],
}
],
}
| TestBuildErrorObjectWithPlaceholders |
python | run-llama__llama_index | llama-index-core/llama_index/core/evaluation/retrieval/metrics_base.py | {
"start": 168,
"end": 789
} | class ____(BaseModel):
"""
Metric result.
Attributes:
score (float): Score for the metric
metadata (Dict[str, Any]): Metadata for the metric result
"""
score: float = Field(..., description="Score for the metric")
metadata: Dict[str, Any] = Field(
default_factory=dict, description="Metadata for the metric result"
)
def __str__(self) -> str:
"""String representation."""
return f"Score: {self.score}\nMetadata: {self.metadata}"
def __float__(self) -> float:
"""Float representation."""
return self.score
| RetrievalMetricResult |
python | ray-project__ray | python/ray/experimental/tqdm_ray.py | {
"start": 6458,
"end": 8663
} | class ____:
"""Manages a group of virtual progress bar produced by a single worker.
All the progress bars in the group have the same `pos_offset` determined by the
BarManager for the process.
"""
def __init__(self, ip, pid, pos_offset):
self.ip = ip
self.pid = pid
self.pos_offset = pos_offset
self.bars_by_uuid: Dict[str, _Bar] = {}
def has_bar(self, bar_uuid) -> bool:
"""Return whether this bar exists."""
return bar_uuid in self.bars_by_uuid
def allocate_bar(self, state: ProgressBarState) -> None:
"""Add a new bar to this group."""
self.bars_by_uuid[state["uuid"]] = _Bar(state, self.pos_offset)
def update_bar(self, state: ProgressBarState) -> None:
"""Update the state of a managed bar in this group."""
bar = self.bars_by_uuid[state["uuid"]]
bar.update(state)
def close_bar(self, state: ProgressBarState) -> None:
"""Remove a bar from this group."""
bar = self.bars_by_uuid[state["uuid"]]
# Note: Hide and then unhide bars to prevent flashing of the
# last bar when we are closing multiple bars sequentially.
instance().hide_bars()
bar.close()
del self.bars_by_uuid[state["uuid"]]
instance().unhide_bars()
def slots_required(self):
"""Return the number of pos slots we need to accommodate bars in this group."""
if not self.bars_by_uuid:
return 0
return 1 + max(bar.state["pos"] for bar in self.bars_by_uuid.values())
def update_offset(self, offset: int) -> None:
"""Update the position offset assigned by the BarManager."""
if offset != self.pos_offset:
self.pos_offset = offset
for bar in self.bars_by_uuid.values():
bar.update_offset(offset)
def hide_bars(self) -> None:
"""Temporarily hide visible bars to avoid conflict with other log messages."""
for bar in self.bars_by_uuid.values():
bar.bar.clear()
def unhide_bars(self) -> None:
"""Opposite of hide_bars()."""
for bar in self.bars_by_uuid.values():
bar.bar.refresh()
| _BarGroup |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py | {
"start": 34740,
"end": 34888
} | class ____(Enum):
request_parameter = "request_parameter"
header = "header"
body_data = "body_data"
body_json = "body_json"
| InjectInto |
python | psf__black | tests/data/cases/docstring_no_extra_empty_line_before_eof.py | {
"start": 91,
"end": 140
} | class ____:
"""A docstring."""
| ClassWithDocstring |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess12.py | {
"start": 551,
"end": 652
} | class ____:
a = A
reveal_type(B.a, expected_text="type[A]")
reveal_type(B().a, expected_text="A")
| B |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-elasticsearch/llama_index/readers/elasticsearch/base.py | {
"start": 356,
"end": 3376
} | class ____(BasePydanticReader):
"""
Read documents from an Elasticsearch/Opensearch index.
These documents can then be used in a downstream Llama Index data structure.
Args:
endpoint (str): URL (http/https) of cluster
index (str): Name of the index (required)
httpx_client_args (dict): Optional additional args to pass to the `httpx.Client`
"""
is_remote: bool = True
endpoint: str
index: str
httpx_client_args: Optional[dict] = None
_client: Any = PrivateAttr()
def __init__(
self, endpoint: str, index: str, httpx_client_args: Optional[dict] = None
):
"""Initialize with parameters."""
super().__init__(
endpoint=endpoint, index=index, httpx_client_args=httpx_client_args
)
import_err_msg = """
`httpx` package not found. Install via `pip install httpx`
"""
try:
import httpx
except ImportError:
raise ImportError(import_err_msg)
self._client = httpx.Client(base_url=endpoint, **(httpx_client_args or {}))
@classmethod
def class_name(cls) -> str:
return "ElasticsearchReader"
def load_data(
self,
field: str,
query: Optional[dict] = None,
embedding_field: Optional[str] = None,
metadata_fields: Optional[List[str]] = None,
) -> List[Document]:
"""
Read data from the Elasticsearch index.
Args:
field (str): Field in the document to retrieve text from
query (Optional[dict]): Elasticsearch JSON query DSL object.
For example:
{"query": {"match": {"message": {"query": "this is a test"}}}}
embedding_field (Optional[str]): If there are embeddings stored in
this index, this field can be used
to set the embedding field on the returned Document list.
metadata_fields (Optional[List[str]]): Fields used as metadata. Default
is all fields in the document except those specified by the
field and embedding_field parameters.
Returns:
List[Document]: A list of documents.
"""
res = self._client.post(f"{self.index}/_search", json=query).json()
documents = []
for hit in res["hits"]["hits"]:
doc_id = hit["_id"]
value = hit["_source"][field]
embedding = hit["_source"].get(embedding_field or "", None)
if metadata_fields:
metadata = {
k: v for k, v in hit["_source"].items() if k in metadata_fields
}
else:
hit["_source"].pop(field)
hit["_source"].pop(embedding_field or "", None)
metadata = hit["_source"]
documents.append(
Document(id_=doc_id, text=value, metadata=metadata, embedding=embedding)
)
return documents
| ElasticsearchReader |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 127444,
"end": 127604
} | class ____:
xlCommand = 2 # from enum XlXLMMacroType
xlFunction = 1 # from enum XlXLMMacroType
xlNotXLM = 3 # from enum XlXLMMacroType
| XlmMacroType |
python | getsentry__sentry | src/sentry/models/options/project_template_option.py | {
"start": 541,
"end": 3378
} | class ____(OptionManager["ProjectTemplateOption"]):
def get_value_bulk(
self, instance: Sequence[ProjectTemplate], key: str
) -> Mapping[ProjectTemplate, Value]:
result = cache.get_many([self._make_key(i.id) for i in instance])
if not result:
return {}
return {i: result.get(self._make_key(i.id), {}).get(key) for i in instance}
def get_value(
self,
project_template: ProjectTemplate | int,
key: str,
default: Value = None,
validate: Callable[[object], bool] | None = None,
) -> Value:
result = self.get_all_values(project_template)
if key in result:
if validate is None or validate(result[key]):
return result[key]
return default
def unset_value(self, project_template: ProjectTemplate, key: str) -> None:
self.filter(project_template=project_template, key=key).delete()
self.reload_cache(project_template.id, "projecttemplateoption.unset_value")
def set_value(self, project_template: ProjectTemplate, key: str, value: Value) -> bool:
project_template_id = project_template.id
inst, created = self.create_or_update(
project_template_id=project_template_id, key=key, values={"value": value}
)
self.reload_cache(project_template_id, "projectoption.set_value")
return created or inst > 0
def get_all_values(self, project_template: ProjectTemplate | int) -> TProjectOptions:
if isinstance(project_template, models.Model):
project_template_id = project_template.id
else:
project_template_id = project_template
cache_key = self._make_key(project_template_id)
if cache_key not in self._option_cache:
result = cache.get(cache_key)
if result is None:
self.reload_cache(project_template_id, "projecttemplateoption.get_all_values")
else:
self._option_cache[cache_key] = result
return self._option_cache.get(cache_key, {})
def reload_cache(self, project_template_id: int, update_reason: str) -> None:
cache_key = self._make_key(project_template_id)
result = {i.key: i.value for i in self.filter(project_template=project_template_id)}
cache.set(cache_key, result)
self._option_cache[cache_key] = result
def post_save(
self, *, instance: ProjectTemplateOption, created: bool, **kwargs: object
) -> None:
self.reload_cache(instance.project_template_id, "projecttemplateoption.post_save")
def post_delete(self, instance: ProjectTemplateOption, **kwargs: Any) -> None:
self.reload_cache(instance.project_template_id, "projecttemplateoption.post_delete")
@region_silo_model
| ProjectTemplateOptionManager |
python | apache__airflow | providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/executors/kubernetes_executor_utils.py | {
"start": 19948,
"end": 31503
} | class ____(LoggingMixin):
"""Airflow Scheduler for Kubernetes."""
def __init__(
self,
kube_config: Any,
result_queue: Queue[KubernetesResults],
kube_client: client.CoreV1Api,
scheduler_job_id: str,
):
super().__init__()
self.log.debug("Creating Kubernetes executor")
self.kube_config = kube_config
self.result_queue = result_queue
self.namespace = self.kube_config.kube_namespace
self.log.debug("Kubernetes using namespace %s", self.namespace)
self.kube_client = kube_client
self._manager = multiprocessing.Manager()
self.watcher_queue = self._manager.Queue()
self.scheduler_job_id = scheduler_job_id
self.kube_watchers = self._make_kube_watchers()
def run_pod_async(self, pod: k8s.V1Pod, **kwargs):
"""Run POD asynchronously."""
sanitized_pod = self.kube_client.api_client.sanitize_for_serialization(pod)
json_pod = json.dumps(sanitized_pod, indent=2)
self.log.debug("Pod Creation Request: \n%s", json_pod)
try:
resp = self.kube_client.create_namespaced_pod(
body=sanitized_pod, namespace=pod.metadata.namespace, **kwargs
)
self.log.debug("Pod Creation Response: %s", resp)
except Exception as e:
self.log.exception("Exception when attempting to create Namespaced Pod: %s", json_pod)
raise e
return resp
def _make_kube_watcher(self, namespace) -> KubernetesJobWatcher:
resource_version = ResourceVersion().resource_version.get(namespace, "0")
watcher = KubernetesJobWatcher(
watcher_queue=self.watcher_queue,
namespace=namespace,
resource_version=resource_version,
scheduler_job_id=self.scheduler_job_id,
kube_config=self.kube_config,
)
watcher.start()
return watcher
def _make_kube_watchers(self) -> dict[str, KubernetesJobWatcher]:
watchers = {}
if self.kube_config.multi_namespace_mode:
namespaces_to_watch = (
self.kube_config.multi_namespace_mode_namespace_list
if self.kube_config.multi_namespace_mode_namespace_list
else [ALL_NAMESPACES]
)
else:
namespaces_to_watch = [self.kube_config.kube_namespace]
for namespace in namespaces_to_watch:
watchers[namespace] = self._make_kube_watcher(namespace)
return watchers
def _health_check_kube_watchers(self):
for namespace, kube_watcher in self.kube_watchers.items():
if kube_watcher.is_alive():
self.log.debug("KubeJobWatcher for namespace %s alive, continuing", namespace)
else:
self.log.error(
(
"Error while health checking kube watcher process for namespace %s. "
"Process died for unknown reasons"
),
namespace,
)
ResourceVersion().resource_version[namespace] = "0"
self.kube_watchers[namespace] = self._make_kube_watcher(namespace)
def run_next(self, next_job: KubernetesJob) -> None:
"""Receives the next job to run, builds the pod, and creates it."""
key = next_job.key
command = next_job.command
kube_executor_config = next_job.kube_executor_config
pod_template_file = next_job.pod_template_file
dag_id, task_id, run_id, try_number, map_index = key
if len(command) == 1:
from airflow.executors.workloads import ExecuteTask
if isinstance(command[0], ExecuteTask):
workload = command[0]
command = workload_to_command_args(workload)
else:
raise ValueError(
f"KubernetesExecutor doesn't know how to handle workload of type: {type(command[0])}"
)
elif command[0:3] != ["airflow", "tasks", "run"]:
raise ValueError('The command must start with ["airflow", "tasks", "run"].')
base_worker_pod = get_base_pod_from_template(pod_template_file, self.kube_config)
if not base_worker_pod:
raise AirflowException(
f"could not find a valid worker template yaml at {self.kube_config.pod_template_file}"
)
pod = PodGenerator.construct_pod(
namespace=self.namespace,
scheduler_job_id=self.scheduler_job_id,
pod_id=create_unique_id(dag_id, task_id),
dag_id=dag_id,
task_id=task_id,
kube_image=self.kube_config.kube_image,
try_number=try_number,
map_index=map_index,
date=None,
run_id=run_id,
args=list(command),
pod_override_object=kube_executor_config,
base_worker_pod=base_worker_pod,
with_mutation_hook=True,
)
# Reconcile the pod generated by the Operator and the Pod
# generated by the .cfg file
self.log.info(
"Creating kubernetes pod for job is %s, with pod name %s, annotations: %s",
key,
pod.metadata.name,
annotations_for_logging_task_metadata(pod.metadata.annotations),
)
self.log.debug("Kubernetes running for command %s", command)
self.log.debug("Kubernetes launching image %s", pod.spec.containers[0].image)
# the watcher will monitor pods, so we do not block.
self.run_pod_async(pod, **self.kube_config.kube_client_request_args)
self.log.debug("Kubernetes Job created!")
def delete_pod(self, pod_name: str, namespace: str) -> None:
"""Delete Pod from a namespace; does not raise if it does not exist."""
try:
self.log.info("Deleting pod %s in namespace %s", pod_name, namespace)
self.kube_client.delete_namespaced_pod(
pod_name,
namespace,
body=client.V1DeleteOptions(**self.kube_config.delete_option_kwargs),
**self.kube_config.kube_client_request_args,
)
except ApiException as e:
# If the pod is already deleted
if str(e.status) != "404":
raise
def patch_pod_revoked(self, *, pod_name: str, namespace: str):
"""
Patch the pod with a label that ensures it's ignored by the kubernetes watcher.
:meta private:
"""
self.log.info(
"Patching pod %s in namespace %s to note that we are revoking the task.",
pod_name,
namespace,
)
try:
self.kube_client.patch_namespaced_pod(
name=pod_name,
namespace=namespace,
body={"metadata": {"labels": {POD_REVOKED_KEY: "True"}}},
)
except ApiException:
self.log.warning("Failed to patch pod %s with pod revoked key.", pod_name, exc_info=True)
def patch_pod_executor_done(self, *, pod_name: str, namespace: str):
"""Add a "done" annotation to ensure we don't continually adopt pods."""
self.log.debug("Patching pod %s in namespace %s to mark it as done", pod_name, namespace)
try:
self.kube_client.patch_namespaced_pod(
name=pod_name,
namespace=namespace,
body={"metadata": {"labels": {POD_EXECUTOR_DONE_KEY: "True"}}},
)
except ApiException as e:
self.log.info("Failed to patch pod %s with done annotation. Reason: %s", pod_name, e)
def sync(self) -> None:
"""
Check the status of all currently running kubernetes jobs.
If a job is completed, its status is placed in the result queue to be sent back to the scheduler.
"""
self.log.debug("Syncing KubernetesExecutor")
self._health_check_kube_watchers()
with contextlib.suppress(Empty):
while True:
task = self.watcher_queue.get_nowait()
try:
self.log.debug("Processing task %s", task)
self.process_watcher_task(task)
finally:
self.watcher_queue.task_done()
def process_watcher_task(self, task: KubernetesWatch) -> None:
"""Process the task by watcher."""
self.log.debug(
"Attempting to finish pod; pod_name: %s; state: %s; annotations: %s",
task.pod_name,
task.state,
annotations_for_logging_task_metadata(task.annotations),
)
key = annotations_to_key(annotations=task.annotations)
if key:
self.log.debug("finishing job %s - %s (%s)", key, task.state, task.pod_name)
self.result_queue.put(
KubernetesResults(
key,
task.state,
task.pod_name,
task.namespace,
task.resource_version,
task.failure_details,
)
)
def _flush_watcher_queue(self) -> None:
self.log.debug("Executor shutting down, watcher_queue approx. size=%d", self.watcher_queue.qsize())
with contextlib.suppress(Empty):
while True:
task = self.watcher_queue.get_nowait()
# Ignoring it since it can only have either FAILED or SUCCEEDED pods
self.log.warning("Executor shutting down, IGNORING watcher task=%s", task)
self.watcher_queue.task_done()
def terminate(self) -> None:
"""Terminates the watcher."""
self.log.debug("Terminating kube_watchers...")
for kube_watcher in self.kube_watchers.values():
kube_watcher.terminate()
self.log.debug("kube_watcher=%s", kube_watcher)
# for now 20 seconds is max wait time for kube watchers to terminate.
max_wait_time = 20
start_time = time.time()
for kube_watcher in self.kube_watchers.values():
kube_watcher.join(timeout=max(int(max_wait_time - (time.time() - start_time)), 0))
if kube_watcher.is_alive():
self.log.warning("kube_watcher didn't terminate in time=%s", kube_watcher)
kube_watcher.kill()
kube_watcher.join()
self.log.debug("kube_watcher=%s", kube_watcher)
self.log.debug("Flushing watcher_queue...")
self._flush_watcher_queue()
# Queue should be empty...
self.watcher_queue.join()
self.log.debug("Shutting down manager...")
self._manager.shutdown()
def get_base_pod_from_template(pod_template_file: str | None, kube_config: Any) -> k8s.V1Pod:
"""
Get base pod from template.
Reads either the pod_template_file set in the executor_config or the base pod_template_file
set in the airflow.cfg to craft a "base pod" that will be used by the KubernetesExecutor
:param pod_template_file: absolute path to a pod_template_file.yaml or None
:param kube_config: The KubeConfig class generated by airflow that contains all kube metadata
:return: a V1Pod that can be used as the base pod for k8s tasks
"""
if pod_template_file:
return PodGenerator.deserialize_model_file(pod_template_file)
return PodGenerator.deserialize_model_file(kube_config.pod_template_file)
| AirflowKubernetesScheduler |
python | getsentry__sentry | tests/sentry/api/test_authentication.py | {
"start": 9791,
"end": 10837
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.auth = DSNAuthentication()
self.org = self.create_organization(owner=self.user)
self.project = self.create_project(organization=self.org)
self.project_key = self.create_project_key(project=self.project)
def test_authenticate(self) -> None:
request = _drf_request()
request.META["HTTP_AUTHORIZATION"] = f"DSN {self.project_key.dsn_public}"
result = self.auth.authenticate(request)
assert result is not None
user, auth = result
assert user.is_anonymous
assert auth == AuthenticatedToken.from_token(self.project_key)
def test_inactive_key(self) -> None:
self.project_key.update(status=ProjectKeyStatus.INACTIVE)
request = _drf_request()
request.META["HTTP_AUTHORIZATION"] = f"DSN {self.project_key.dsn_public}"
with pytest.raises(AuthenticationFailed):
self.auth.authenticate(request)
@control_silo_test
| TestDSNAuthentication |
python | pytorch__pytorch | torch/distributed/algorithms/ddp_comm_hooks/optimizer_overlap_hooks.py | {
"start": 328,
"end": 1252
} | class ____:
"""
Holds state for running optimizer in-line after DDP communication hook.
Currently contains only optimizer class which must have a method `step_param`.
"""
__slots__ = ["functional_optimizer", "params_to_optimize"]
def __init__(self, functional_optim, params=None):
self.functional_optimizer = functional_optim
self._check_valid_functional_optim()
self._set_params_to_optimize(params)
def _set_params_to_optimize(self, params):
if params is not None:
self.params_to_optimize = set(params)
def _check_valid_functional_optim(self):
if not hasattr(self.functional_optimizer, _FUNCTIONAL_OPTIM_STEP_METHOD_NAME):
raise ValueError(
f"Class {type(self.functional_optimizer)} must implement method "
f"{_FUNCTIONAL_OPTIM_STEP_METHOD_NAME}."
)
@dataclass
| _OptimizerHookState |
python | huggingface__transformers | src/transformers/models/bloom/modeling_bloom.py | {
"start": 29614,
"end": 37979
} | class ____(BloomPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "transformer.word_embeddings.weight"}
def __init__(self, config: BloomConfig):
super().__init__(config)
self.transformer = BloomModel(config)
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# Initialize weights and apply final processing
self.post_init()
def set_output_embeddings(self, new_embeddings: torch.Tensor):
self.lm_head = new_embeddings
def prepare_inputs_for_generation(
self,
input_ids,
past_key_values=None,
attention_mask=None,
inputs_embeds=None,
cache_position=None,
use_cache=True,
**kwargs,
):
# Overwritten because of the fixed-shape attention mask creation
# If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
# Exception 1: when passing input_embeds, input_ids may be missing entries
# Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
# Exception 3: with synced GPUs cache_position may go out of bounds, but we only want dummy token in that case.
# (we can't check exception 3 while compiling)
# Exception 4: If input_embeds are passed then slice it through `cache_position`, to keep only the unprocessed tokens and
# generate the first token for each sequence. Later use the generated Input ids for continuation.
if past_key_values is not None:
if inputs_embeds is not None and input_ids.shape[1] == 0: # Exception 4
inputs_embeds = inputs_embeds[:, -cache_position.shape[0] :]
elif (
inputs_embeds is not None # Exception 1
or cache_position[-1] >= input_ids.shape[1] # Exception 3
):
input_ids = input_ids[:, -cache_position.shape[0] :]
elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
input_ids = input_ids[:, cache_position]
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
if inputs_embeds is not None and len(cache_position) == inputs_embeds.shape[1]:
model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None}
else:
# This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s `mode="reduce-overhead`, as otherwise the
# input `position_ids` would have various stride during the decoding. Here, simply using `.contiguous()` is not sufficient as in
# the batch size = 1 case, `position_ids` is already contiguous but with varying stride which retriggers a capture.
model_inputs = {"input_ids": input_ids.clone(memory_format=torch.contiguous_format), "inputs_embeds": None}
# This part differs from other models because BLOOM needs a 2D mask to construct alibi tensor
# The only difference is the usage of 2D instead of 4D mask, but the shape will be static
if isinstance(past_key_values, StaticCache) and attention_mask is not None:
target_length = past_key_values.get_max_cache_shape()
batch_size, seq_length = attention_mask.shape
diff = target_length - seq_length
new_attn_mask = torch.zeros(batch_size, diff, device=attention_mask.device, dtype=attention_mask.dtype)
attention_mask = torch.cat(
[attention_mask, new_attn_mask],
dim=-1,
)
model_inputs.update(
{
"cache_position": cache_position,
"past_key_values": past_key_values,
"use_cache": use_cache,
"attention_mask": attention_mask,
}
)
# Forward ALL kwargs that are uninitialized (e.g. `use_cache`).
for key, value in kwargs.items():
if key not in model_inputs:
model_inputs[key] = value
return model_inputs
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
attention_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
**kwargs,
) -> Union[tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
r"""
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
`input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
(`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
`input_ids`.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
`labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
transformer_outputs = self.transformer(
input_ids,
past_key_values=past_key_values,
attention_mask=attention_mask,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
cache_position=cache_position,
)
hidden_states = transformer_outputs[0]
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
logits = self.lm_head(hidden_states[:, slice_indices, :])
loss = None
if labels is not None:
loss = self.loss_function(
logits,
labels,
vocab_size=self.config.vocab_size,
num_items_in_batch=kwargs.get("num_items_in_batch"),
)
if not return_dict:
output = (logits,) + transformer_outputs[1:]
return ((loss,) + output) if loss is not None else output
return CausalLMOutputWithCrossAttentions(
loss=loss,
logits=logits,
past_key_values=transformer_outputs.past_key_values,
hidden_states=transformer_outputs.hidden_states,
attentions=transformer_outputs.attentions,
)
@auto_docstring(
custom_intro="""
The Bloom Model transformer with a sequence classification head on top (linear layer).
[`BloomForSequenceClassification`] uses the last token in order to do the classification, as other causal models
(e.g. GPT-1) do.
Since it does classification on the last token, it requires to know the position of the last token. If a
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
each row of the batch).
"""
)
| BloomForCausalLM |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_univariate.py | {
"start": 11252,
"end": 12135
} | class ____(Benchmark):
"""
Univariate Problem14 objective function.
This class defines the Univariate Problem14 global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\\text{Problem14}}(x) = -e^{-x} \\sin(2\\pi x)
Bound constraints: :math:`x \\in [0, 4]`
.. figure:: figures/Problem14.png
:alt: Univariate Problem14 function
:align: center
**Univariate Problem14 function**
*Global optimum*: :math:`f(x)=-0.788685` for :math:`x = 0.224885`
"""
def __init__(self, dimensions=1):
Benchmark.__init__(self, dimensions)
self._bounds = [(0.0, 4.0)]
self.global_optimum = 0.224885
self.fglob = -0.788685
def fun(self, x, *args):
self.nfev += 1
x = x[0]
return -exp(-x) * sin(2.0 * pi * x)
| Problem14 |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/psycopg.py | {
"start": 8731,
"end": 9556
} | class ____(ranges.AbstractSingleRangeImpl):
def bind_processor(self, dialect):
psycopg_Range = cast(PGDialect_psycopg, dialect)._psycopg_Range
def to_range(value):
if isinstance(value, ranges.Range):
value = psycopg_Range(
value.lower, value.upper, value.bounds, value.empty
)
return value
return to_range
def result_processor(self, dialect, coltype):
def to_range(value):
if value is not None:
value = ranges.Range(
value._lower,
value._upper,
bounds=value._bounds if value._bounds else "[)",
empty=not value._bounds,
)
return value
return to_range
| _PsycopgRange |
python | pandas-dev__pandas | pandas/tests/indexes/numeric/test_numeric.py | {
"start": 131,
"end": 7679
} | class ____:
@pytest.fixture(params=[np.float64, np.float32])
def dtype(self, request):
return request.param
@pytest.fixture
def mixed_index(self, dtype):
return Index([1.5, 2, 3, 4, 5], dtype=dtype)
@pytest.fixture
def float_index(self, dtype):
return Index([0.0, 2.5, 5.0, 7.5, 10.0], dtype=dtype)
@pytest.mark.parametrize(
"index_data",
[
[1.5, 2, 3, 4, 5],
[0.0, 2.5, 5.0, 7.5, 10.0],
[5, 4, 3, 2, 1.5],
[10.0, 7.5, 5.0, 2.5, 0.0],
],
ids=["mixed", "float", "mixed_dec", "float_dec"],
)
def test_repr_roundtrip(self, index_data, dtype):
index = Index(index_data, dtype=dtype)
tm.assert_index_equal(eval(repr(index)), index, exact=True)
def check_coerce(self, a, b, is_float_index=True):
assert a.equals(b)
tm.assert_index_equal(a, b, exact=False)
if is_float_index:
assert isinstance(b, Index)
else:
assert type(b) is Index
def test_constructor_from_list_no_dtype(self):
index = Index([1.5, 2.5, 3.5])
assert index.dtype == np.float64
def test_constructor(self, dtype):
index_cls = Index
# explicit construction
index = index_cls([1, 2, 3, 4, 5], dtype=dtype)
assert isinstance(index, index_cls)
assert index.dtype == dtype
expected = np.array([1, 2, 3, 4, 5], dtype=dtype)
tm.assert_numpy_array_equal(index.values, expected)
index = index_cls(np.array([1, 2, 3, 4, 5]), dtype=dtype)
assert isinstance(index, index_cls)
assert index.dtype == dtype
index = index_cls([1.0, 2, 3, 4, 5], dtype=dtype)
assert isinstance(index, index_cls)
assert index.dtype == dtype
index = index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype)
assert isinstance(index, index_cls)
assert index.dtype == dtype
index = index_cls([1.0, 2, 3, 4, 5], dtype=dtype)
assert isinstance(index, index_cls)
assert index.dtype == dtype
index = index_cls(np.array([1.0, 2, 3, 4, 5]), dtype=dtype)
assert isinstance(index, index_cls)
assert index.dtype == dtype
# nan handling
result = index_cls([np.nan, np.nan], dtype=dtype)
assert pd.isna(result.values).all()
result = index_cls(np.array([np.nan]), dtype=dtype)
assert pd.isna(result.values).all()
def test_constructor_invalid(self):
index_cls = Index
cls_name = index_cls.__name__
# invalid
msg = (
rf"{cls_name}\(\.\.\.\) must be called with a collection of "
r"some kind, 0\.0 was passed"
)
with pytest.raises(TypeError, match=msg):
index_cls(0.0)
def test_constructor_coerce(self, mixed_index, float_index):
self.check_coerce(mixed_index, Index([1.5, 2, 3, 4, 5]))
self.check_coerce(float_index, Index(np.arange(5) * 2.5))
result = Index(np.array(np.arange(5) * 2.5, dtype=object))
assert result.dtype == object # as of 2.0 to match Series
self.check_coerce(float_index, result.astype("float64"))
def test_constructor_explicit(self, mixed_index, float_index):
# these don't auto convert
self.check_coerce(
float_index, Index((np.arange(5) * 2.5), dtype=object), is_float_index=False
)
self.check_coerce(
mixed_index, Index([1.5, 2, 3, 4, 5], dtype=object), is_float_index=False
)
def test_type_coercion_fail(self, any_int_numpy_dtype):
# see gh-15832
msg = "Trying to coerce float values to integers"
with pytest.raises(ValueError, match=msg):
Index([1, 2, 3.5], dtype=any_int_numpy_dtype)
def test_equals_numeric(self):
index_cls = Index
idx = index_cls([1.0, 2.0])
assert idx.equals(idx)
assert idx.identical(idx)
idx2 = index_cls([1.0, 2.0])
assert idx.equals(idx2)
idx = index_cls([1.0, np.nan])
assert idx.equals(idx)
assert idx.identical(idx)
idx2 = index_cls([1.0, np.nan])
assert idx.equals(idx2)
@pytest.mark.parametrize(
"other",
(
Index([1, 2], dtype=np.int64),
Index([1.0, 2.0], dtype=object),
Index([1, 2], dtype=object),
),
)
def test_equals_numeric_other_index_type(self, other):
idx = Index([1.0, 2.0])
assert idx.equals(other)
assert other.equals(idx)
@pytest.mark.parametrize(
"vals",
[
pd.date_range("2016-01-01", periods=3),
pd.timedelta_range("1 Day", periods=3),
],
)
def test_lookups_datetimelike_values(self, vals, dtype):
# If we have datetime64 or timedelta64 values, make sure they are
# wrapped correctly GH#31163
ser = Series(vals, index=range(3, 6))
ser.index = ser.index.astype(dtype)
expected = vals[1]
result = ser[4.0]
assert isinstance(result, type(expected)) and result == expected
result = ser[4]
assert isinstance(result, type(expected)) and result == expected
result = ser.loc[4.0]
assert isinstance(result, type(expected)) and result == expected
result = ser.loc[4]
assert isinstance(result, type(expected)) and result == expected
result = ser.at[4.0]
assert isinstance(result, type(expected)) and result == expected
# GH#31329 .at[4] should cast to 4.0, matching .loc behavior
result = ser.at[4]
assert isinstance(result, type(expected)) and result == expected
result = ser.iloc[1]
assert isinstance(result, type(expected)) and result == expected
result = ser.iat[1]
assert isinstance(result, type(expected)) and result == expected
def test_doesnt_contain_all_the_things(self):
idx = Index([np.nan])
assert not idx.isin([0]).item()
assert not idx.isin([1]).item()
assert idx.isin([np.nan]).item()
def test_nan_multiple_containment(self):
index_cls = Index
idx = index_cls([1.0, np.nan])
tm.assert_numpy_array_equal(idx.isin([1.0]), np.array([True, False]))
tm.assert_numpy_array_equal(idx.isin([2.0, np.pi]), np.array([False, False]))
tm.assert_numpy_array_equal(idx.isin([np.nan]), np.array([False, True]))
tm.assert_numpy_array_equal(idx.isin([1.0, np.nan]), np.array([True, True]))
idx = index_cls([1.0, 2.0])
tm.assert_numpy_array_equal(idx.isin([np.nan]), np.array([False, False]))
def test_fillna_float64(self):
index_cls = Index
# GH 11343
idx = Index([1.0, np.nan, 3.0], dtype=float, name="x")
# can't downcast
exp = Index([1.0, 0.1, 3.0], name="x")
tm.assert_index_equal(idx.fillna(0.1), exp, exact=True)
# downcast
exp = index_cls([1.0, 2.0, 3.0], name="x")
tm.assert_index_equal(idx.fillna(2), exp)
# object
exp = Index([1.0, "obj", 3.0], name="x")
tm.assert_index_equal(idx.fillna("obj"), exp, exact=True)
def test_logical_compat(self, dtype):
idx = Index(np.arange(5, dtype=dtype))
assert idx.all() == idx.values.all()
assert idx.any() == idx.values.any()
assert idx.all() == idx.to_series().all()
assert idx.any() == idx.to_series().any()
| TestFloatNumericIndex |
python | huggingface__transformers | src/transformers/models/mllama/modeling_mllama.py | {
"start": 52116,
"end": 58777
} | class ____(MllamaPreTrainedModel):
config: MllamaTextConfig
base_model_prefix = "language_model.model"
input_modalities = ("text",)
def __init__(self, config: MllamaTextConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size + 8, config.hidden_size, self.padding_idx)
self.cross_attention_layers = config.cross_attention_layers
layers = []
for layer_idx in range(config.num_hidden_layers):
if layer_idx in self.cross_attention_layers:
layers.append(MllamaCrossAttentionDecoderLayer(config, layer_idx))
else:
layers.append(MllamaSelfAttentionDecoderLayer(config, layer_idx))
self.layers = nn.ModuleList(layers)
self.norm = MllamaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.rotary_emb = MllamaRotaryEmbedding(config=config)
self.gradient_checkpointing = False
self.post_init()
@check_model_inputs()
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
cross_attention_states: Optional[torch.FloatTensor] = None,
cross_attention_mask: Optional[torch.Tensor] = None,
full_text_row_masked_out_mask: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[FlashAttentionKwargs],
) -> BaseModelOutputWithPast:
r"""
cross_attention_states (`torch.FloatTensor`, *optional*):
Output of the vision model, used for cross-attention. This tensor contains the processed image features that
the language model will attend to.
cross_attention_mask (`torch.Tensor` of shape `(batch_size, seq_length, max_num_images, max_num_tiles)`, *optional*):
Cross-attention mask to control the interaction between text tokens and image tiles.
This 4D tensor defines which image tiles each text token should attend to.
For each text token (in seq_length):
- 1 indicates the token **should attend** to the corresponding image tile
- 0 indicates the token **should not attend** to the corresponding image tile
full_text_row_masked_out_mask (`tuple[torch.Tensor, torch.Tensor]`, *optional*):
A tuple containing two tensors that mask out rows in the cross-attention mechanism:
- The first tensor has shape `(batch_size, 1, seq_length, 1)` and contains values of 0 or 1.
A value of 0 indicates that the corresponding text token's entire row in the cross-attention
matrix should be masked out (all image tokens ignored).
- The second tensor has the same shape and is used internally to apply the masking during
the forward pass of cross-attention layers.
This mask is derived from the cross_attention_mask and is used to handle cases where a text token
should not attend to any image token.
Example:
```python
>>> from transformers import AutoProcessor, MllamaTextModel
>>> checkpoint = "meta-llama/Llama-3.2-11B-Vision"
>>> model = MllamaTextModel.from_pretrained(checkpoint)
>>> processor = AutoProcessor.from_pretrained(checkpoint)
>>> text = "<|image|>If I had to write a haiku for this one"
>>> inputs = processor(text=text, return_tensors="pt")
>>> output = model(**inputs)
>>> print(output.last_hidden_state.shape)
torch.Size([1, 13, 4096])
```
"""
use_cache = use_cache if use_cache is not None else self.config.use_cache
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
hidden_states = inputs_embeds
if use_cache and past_key_values is None:
past_key_values = DynamicCache(config=self.config)
if cache_position is None:
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
cache_position = torch.arange(
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
)
if position_ids is None:
position_ids = cache_position.unsqueeze(0)
causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, cache_position, past_key_values)
position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
# decoder layers
for idx, decoder_layer in enumerate(self.layers):
# For text-only path we should skip cross attention layers.
# Let's check if the layer is cross attention layer and if we have cross attention states
# or cached cross attention states.
is_cross_attention_layer = idx in self.cross_attention_layers
is_cross_attention_cache_empty = past_key_values is None or (
past_key_values is not None and past_key_values.get_seq_length(idx) == 0
)
if is_cross_attention_layer and cross_attention_states is None and is_cross_attention_cache_empty:
continue
hidden_states = decoder_layer(
hidden_states,
cross_attention_states=cross_attention_states,
cross_attention_mask=cross_attention_mask,
attention_mask=causal_mask,
full_text_row_masked_out_mask=full_text_row_masked_out_mask,
position_ids=position_ids,
past_key_values=past_key_values,
use_cache=use_cache,
cache_position=cache_position,
position_embeddings=position_embeddings,
**kwargs,
)
hidden_states = self.norm(hidden_states)
return BaseModelOutputWithPast(
last_hidden_state=hidden_states,
past_key_values=past_key_values,
)
@auto_docstring(
custom_intro="""
The Mllama Text Model with a language modeling head on top.
"""
)
| MllamaTextModel |
python | scipy__scipy | benchmarks/benchmarks/spatial.py | {
"start": 1450,
"end": 2175
} | class ____(Benchmark):
params = [
[(3, 10 ** 4, 1000), (8, 10 ** 4, 1000), (16, 10 ** 4, 1000)],
[True, False],
['random', 'sorted'],
[0.5]
]
param_names = ['(m, n, r)', 'balanced', 'order', 'radius']
def setup(self, mnr, balanced, order, radius):
m, n, r = mnr
rng = np.random.default_rng(1234)
self.data = {
'random': rng.uniform(size=(n, m)),
'sorted': np.repeat(np.arange(n, 0, -1)[:, np.newaxis],
m,
axis=1) / n
}
self.queries = rng.uniform(size=(r, m))
self.T = cKDTree(self.data.get(order), balanced_tree=balanced)
| PresortedDataSetup |
python | getsentry__sentry | src/sentry/dynamic_sampling/rules/biases/minimum_sample_rate_bias.py | {
"start": 191,
"end": 759
} | class ____(Bias):
"""
Sets the minimum sample rate for the project.
"""
def generate_rules(self, project: Project, base_sample_rate: float) -> list[PolymorphicRule]:
return [
{
"samplingValue": {"type": "minimumSampleRate", "value": base_sample_rate},
"type": "project",
"condition": {
"inner": [],
"op": "and",
},
"id": RESERVED_IDS[RuleType.MINIMUM_SAMPLE_RATE_RULE],
}
]
| MinimumSampleRateBias |
python | huggingface__transformers | src/transformers/models/convnextv2/modeling_convnextv2.py | {
"start": 11306,
"end": 13150
} | class ____(ConvNextV2PreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.config = config
self.embeddings = ConvNextV2Embeddings(config)
self.encoder = ConvNextV2Encoder(config)
# final layernorm layer
self.layernorm = nn.LayerNorm(config.hidden_sizes[-1], eps=config.layer_norm_eps)
# Initialize weights and apply final processing
self.post_init()
@can_return_tuple
@auto_docstring
def forward(
self, pixel_values: Optional[torch.FloatTensor] = None, output_hidden_states: Optional[bool] = None
) -> BaseModelOutputWithPoolingAndNoAttention:
if output_hidden_states is None:
output_hidden_states = self.config.output_hidden_states
if pixel_values is None:
raise ValueError("You have to specify pixel_values")
embedding_output = self.embeddings(pixel_values)
encoder_outputs: BaseModelOutputWithNoAttention = self.encoder(
embedding_output, output_hidden_states=output_hidden_states
)
last_hidden_state = encoder_outputs.last_hidden_state
# global average pooling, (N, C, H, W) -> (N, C)
pooled_output = self.layernorm(last_hidden_state.mean([-2, -1]))
return BaseModelOutputWithPoolingAndNoAttention(
last_hidden_state=last_hidden_state,
pooler_output=pooled_output,
hidden_states=encoder_outputs.hidden_states,
)
@auto_docstring(
custom_intro="""
ConvNextV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
ImageNet.
"""
)
# Copied from transformers.models.convnext.modeling_convnext.ConvNextForImageClassification with CONVNEXT->CONVNEXTV2,ConvNext->ConvNextV2,convnext->convnextv2
| ConvNextV2Model |
python | tornadoweb__tornado | tornado/test/asyncio_test.py | {
"start": 1117,
"end": 4070
} | class ____(AsyncTestCase):
@property
def asyncio_loop(self):
return self.io_loop.asyncio_loop # type: ignore
def test_asyncio_callback(self):
# Basic test that the asyncio loop is set up correctly.
async def add_callback():
asyncio.get_event_loop().call_soon(self.stop)
self.asyncio_loop.run_until_complete(add_callback())
self.wait()
@gen_test
def test_asyncio_future(self):
# Test that we can yield an asyncio future from a tornado coroutine.
# Without 'yield from', we must wrap coroutines in ensure_future.
x = yield asyncio.ensure_future(
asyncio.get_event_loop().run_in_executor(None, lambda: 42)
)
self.assertEqual(x, 42)
@gen_test
def test_asyncio_yield_from(self):
@gen.coroutine
def f():
event_loop = asyncio.get_event_loop()
x = yield from event_loop.run_in_executor(None, lambda: 42)
return x
result = yield f()
self.assertEqual(result, 42)
def test_asyncio_adapter(self):
# This test demonstrates that when using the asyncio coroutine
# runner (i.e. run_until_complete), the to_asyncio_future
# adapter is needed. No adapter is needed in the other direction,
# as demonstrated by other tests in the package.
@gen.coroutine
def tornado_coroutine():
yield gen.moment
raise gen.Return(42)
async def native_coroutine_without_adapter():
return await tornado_coroutine()
async def native_coroutine_with_adapter():
return await to_asyncio_future(tornado_coroutine())
# Use the adapter, but two degrees from the tornado coroutine.
async def native_coroutine_with_adapter2():
return await to_asyncio_future(native_coroutine_without_adapter())
# Tornado supports native coroutines both with and without adapters
self.assertEqual(self.io_loop.run_sync(native_coroutine_without_adapter), 42)
self.assertEqual(self.io_loop.run_sync(native_coroutine_with_adapter), 42)
self.assertEqual(self.io_loop.run_sync(native_coroutine_with_adapter2), 42)
# Asyncio only supports coroutines that yield asyncio-compatible
# Futures (which our Future is since 5.0).
self.assertEqual(
self.asyncio_loop.run_until_complete(native_coroutine_without_adapter()),
42,
)
self.assertEqual(
self.asyncio_loop.run_until_complete(native_coroutine_with_adapter()),
42,
)
self.assertEqual(
self.asyncio_loop.run_until_complete(native_coroutine_with_adapter2()),
42,
)
def test_add_thread_close_idempotent(self):
loop = AddThreadSelectorEventLoop(asyncio.get_event_loop()) # type: ignore
loop.close()
loop.close()
| AsyncIOLoopTest |
python | jazzband__django-waffle | waffle/tests/test_management.py | {
"start": 274,
"end": 7643
} | class ____(TestCase):
def test_create(self):
""" The command should create a new flag. """
name = 'test'
percent = 20
Group.objects.create(name='waffle_group')
call_command('waffle_flag', name, percent=percent, testing=True,
superusers=True, staff=True, authenticated=True,
rollout=True, create=True, group=['waffle_group'])
flag = get_waffle_flag_model().objects.get(name=name)
self.assertEqual(flag.percent, percent)
self.assertIsNone(flag.everyone)
self.assertTrue(flag.testing)
self.assertTrue(flag.superusers)
self.assertTrue(flag.staff)
self.assertTrue(flag.authenticated)
self.assertTrue(flag.rollout)
self.assertEqual(list(flag.groups.values_list('name', flat=True)),
['waffle_group'])
def test_not_create(self):
""" The command shouldn't create a new flag if the create flag is
not set.
"""
name = 'test'
with self.assertRaisesRegex(CommandError, 'This flag does not exist.'):
call_command('waffle_flag', name, everyone=True, percent=20,
superusers=True, staff=True, authenticated=True,
rollout=True)
self.assertFalse(get_waffle_flag_model().objects.filter(name=name).exists())
def test_update(self):
""" The command should update an existing flag. """
name = 'test'
flag = get_waffle_flag_model().objects.create(name=name)
self.assertIsNone(flag.percent)
self.assertIsNone(flag.everyone)
self.assertTrue(flag.superusers)
self.assertFalse(flag.staff)
self.assertFalse(flag.authenticated)
self.assertFalse(flag.rollout)
percent = 30
call_command('waffle_flag', name, percent=percent,
superusers=False, staff=True, authenticated=True,
rollout=True)
flag.refresh_from_db()
self.assertEqual(flag.percent, percent)
self.assertIsNone(flag.everyone)
self.assertFalse(flag.superusers)
self.assertTrue(flag.staff)
self.assertTrue(flag.authenticated)
self.assertTrue(flag.rollout)
def test_update_activate_everyone(self):
""" The command should update everyone field to True """
name = 'test'
flag = get_waffle_flag_model().objects.create(name=name)
self.assertIsNone(flag.percent)
self.assertIsNone(flag.everyone)
self.assertTrue(flag.superusers)
self.assertFalse(flag.staff)
self.assertFalse(flag.authenticated)
self.assertFalse(flag.rollout)
percent = 30
call_command('waffle_flag', name, everyone=True, percent=percent,
superusers=False, staff=True, authenticated=True,
rollout=True)
flag.refresh_from_db()
self.assertEqual(flag.percent, percent)
self.assertTrue(flag.everyone)
self.assertFalse(flag.superusers)
self.assertTrue(flag.staff)
self.assertTrue(flag.authenticated)
self.assertTrue(flag.rollout)
def test_update_deactivate_everyone(self):
""" The command should update everyone field to False"""
name = 'test'
flag = get_waffle_flag_model().objects.create(name=name)
self.assertIsNone(flag.percent)
self.assertIsNone(flag.everyone)
self.assertTrue(flag.superusers)
self.assertFalse(flag.staff)
self.assertFalse(flag.authenticated)
self.assertFalse(flag.rollout)
percent = 30
call_command('waffle_flag', name, everyone=False, percent=percent,
superusers=False, staff=True, authenticated=True,
rollout=True)
flag.refresh_from_db()
self.assertEqual(flag.percent, percent)
self.assertFalse(flag.everyone)
self.assertFalse(flag.superusers)
self.assertTrue(flag.staff)
self.assertTrue(flag.authenticated)
self.assertTrue(flag.rollout)
def test_list(self):
""" The command should list all flags."""
stdout = io.StringIO()
get_waffle_flag_model().objects.create(name='test')
call_command('waffle_flag', list_flags=True, stdout=stdout)
expected = 'Flags:\nNAME: test\nSUPERUSERS: True\nEVERYONE: None\n' \
'AUTHENTICATED: False\nPERCENT: None\nTESTING: False\n' \
'ROLLOUT: False\nSTAFF: False\nGROUPS: []\nUSERS: []'
actual = stdout.getvalue().strip()
self.assertEqual(actual, expected)
def test_group_append(self):
""" The command should append a group to a flag."""
original_group = Group.objects.create(name='waffle_group')
Group.objects.create(name='append_group')
flag = get_waffle_flag_model().objects.create(name='test')
flag.groups.add(original_group)
flag.refresh_from_db()
self.assertEqual(list(flag.groups.values_list('name', flat=True)),
['waffle_group'])
call_command('waffle_flag', 'test', group=['append_group'],
append=True)
flag.refresh_from_db()
self.assertEqual(list(flag.groups.values_list('name', flat=True)),
['waffle_group', 'append_group'])
self.assertIsNone(flag.everyone)
def test_user(self):
""" The command should replace a user to a flag."""
original_user = User.objects.create_user('waffle_test')
User.objects.create_user('add_user')
flag = get_waffle_flag_model().objects.create(name='test')
flag.users.add(original_user)
flag.refresh_from_db()
self.assertEqual(list(flag.users.values_list('username', flat=True)),
['waffle_test'])
call_command('waffle_flag', 'test', user=['add_user'])
flag.refresh_from_db()
self.assertEqual(list(flag.users.values_list('username', flat=True)),
['add_user'])
self.assertIsNone(flag.everyone)
def test_user_append(self):
""" The command should append a user to a flag."""
original_user = User.objects.create_user('waffle_test')
User.objects.create_user('append_user')
User.objects.create_user('append_user_email', email='test@example.com')
flag = get_waffle_flag_model().objects.create(name='test')
flag.users.add(original_user)
flag.refresh_from_db()
self.assertEqual(list(flag.users.values_list('username', flat=True)),
['waffle_test'])
call_command('waffle_flag', 'test', user=['append_user'],
append=True)
flag.refresh_from_db()
self.assertEqual(list(flag.users.values_list('username', flat=True)),
['waffle_test', 'append_user'])
self.assertIsNone(flag.everyone)
call_command('waffle_flag', 'test', user=['test@example.com'],
append=True)
flag.refresh_from_db()
self.assertEqual(list(flag.users.values_list('username', flat=True)),
['waffle_test', 'append_user', 'append_user_email'])
self.assertIsNone(flag.everyone)
| WaffleFlagManagementCommandTests |
python | PrefectHQ__prefect | src/prefect/server/events/schemas/automations.py | {
"start": 22294,
"end": 22498
} | class ____(AutoEnum):
"""Defines automations sorting options."""
CREATED_DESC = "CREATED_DESC"
UPDATED_DESC = "UPDATED_DESC"
NAME_ASC = "NAME_ASC"
NAME_DESC = "NAME_DESC"
| AutomationSort |
python | ray-project__ray | release/ray_release/file_manager/file_manager.py | {
"start": 113,
"end": 600
} | class ____(abc.ABC):
def __init__(self, cluster_manager: ClusterManager):
self.cluster_manager = cluster_manager
def upload(self, source: Optional[str] = None, target: Optional[str] = None):
"""Upload source to target.
Infers target dir from basename if not stated.
"""
raise NotImplementedError
def download(self, source: str, target: str):
"""Download source_dir to target_dir."""
raise NotImplementedError
| FileManager |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_print_options07.py | {
"start": 315,
"end": 1052
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("print_options07.xlsx")
self.ignore_elements = {
"xl/worksheets/sheet1.xml": ["<pageMargins", "<pageSetup"]
}
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with print options."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
worksheet.write(0, 0, "Foo")
worksheet.set_paper(9)
worksheet.vertical_dpi = 200
worksheet.print_black_and_white()
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | google__jax | tests/mosaic/gpu_test.py | {
"start": 165755,
"end": 166153
} | class ____:
"""Defines a Transpose transform in a TestCaseInput.
Note that we cannot simply alias mgpu_dialect.TransposeTransformAttr.get,
because we do not have an MLIR context at the point we define the
TestCaseInput.
"""
permutation: tuple[int, ...]
def attr(self):
return mgpu_dialect.TransposeTransformAttr.get(self.permutation)
@dataclasses.dataclass(frozen=True)
| Transpose |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_run_launcher.py | {
"start": 4075,
"end": 7424
} | class ____(BaseTestSuite):
def test_multiple_run_launcher_same_job(self, graphql_context: WorkspaceRequestContext):
selector = infer_job_selector(graphql_context, "no_config_job")
# test with multiple of the same job
executionParamsList = [
{"selector": selector, "mode": "default"},
{"selector": selector, "mode": "default"},
{"selector": selector, "mode": "default"},
]
result = execute_dagster_graphql(
context=graphql_context,
query=LAUNCH_MULTIPLE_RUNS_MUTATION,
variables={"executionParamsList": executionParamsList},
)
assert "launchMultipleRuns" in result.data
launches = result.data["launchMultipleRuns"]
assert launches["__typename"] == "LaunchMultipleRunsResult"
assert "launchMultipleRunsResult" in launches
results = launches["launchMultipleRunsResult"]
for result in results:
assert result["__typename"] == "LaunchRunSuccess"
def test_multiple_run_launcher_multiple_jobs(self, graphql_context: WorkspaceRequestContext):
selectors = [
infer_job_selector(graphql_context, "no_config_job"),
infer_job_selector(graphql_context, "more_complicated_config", ["noop_op"]),
]
# test with multiple of the same job
executionParamsList = [
{"selector": selectors[0], "mode": "default"},
{"selector": selectors[1], "mode": "default"},
{"selector": selectors[0], "mode": "default"},
{"selector": selectors[1], "mode": "default"},
]
result = execute_dagster_graphql(
context=graphql_context,
query=LAUNCH_MULTIPLE_RUNS_MUTATION,
variables={"executionParamsList": executionParamsList},
)
assert "launchMultipleRuns" in result.data
launches = result.data["launchMultipleRuns"]
assert launches["__typename"] == "LaunchMultipleRunsResult"
assert "launchMultipleRunsResult" in launches
results = launches["launchMultipleRunsResult"]
for result in results:
assert result["__typename"] == "LaunchRunSuccess"
def test_multiple_launch_failure_unauthorized(self, graphql_context: WorkspaceRequestContext):
executionParamsList = [
{"selector": infer_job_selector(graphql_context, "no_config_job"), "mode": "default"},
{"selector": infer_job_selector(graphql_context, "no_config_job"), "mode": "default"},
]
# mock no permissions
with patch.object(graphql_context, "has_permission_for_selector", return_value=False):
result = execute_dagster_graphql(
context=graphql_context,
query=LAUNCH_MULTIPLE_RUNS_MUTATION,
variables={"executionParamsList": executionParamsList},
)
assert "launchMultipleRuns" in result.data
result_data = result.data["launchMultipleRuns"]
assert result_data["__typename"] == "LaunchMultipleRunsResult"
assert "launchMultipleRunsResult" in result_data
results = result_data["launchMultipleRunsResult"]
for result in results:
assert result["__typename"] == "UnauthorizedError"
| TestMultipleLaunch |
python | bokeh__bokeh | src/bokeh/models/glyphs.py | {
"start": 9698,
"end": 11168
} | class ____(Glyph, LineGlyph):
''' Render Bezier curves.
For more information consult the `Wikipedia article for Bezier curve`_.
.. _Wikipedia article for Bezier curve: http://en.wikipedia.org/wiki/Bezier_curve
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
__example__ = "examples/reference/models/Bezier.py"
_args = ("x0", "y0", "x1", "y1", "cx0", "cy0", "cx1", "cy1")
x0 = NumberSpec(default=field("x0"), help="""
The x-coordinates of the starting points.
""")
y0 = NumberSpec(default=field("y0"), help="""
The y-coordinates of the starting points.
""")
x1 = NumberSpec(default=field("x1"), help="""
The x-coordinates of the ending points.
""")
y1 = NumberSpec(default=field("y1"), help="""
The y-coordinates of the ending points.
""")
cx0 = NumberSpec(default=field("cx0"), help="""
The x-coordinates of first control points.
""")
cy0 = NumberSpec(default=field("cy0"), help="""
The y-coordinates of first control points.
""")
cx1 = NumberSpec(default=field("cx1"), help="""
The x-coordinates of second control points.
""")
cy1 = NumberSpec(default=field("cy1"), help="""
The y-coordinates of second control points.
""")
line_props = Include(LineProps, help="""
The {prop} values for the Bezier curves.
""")
| Bezier |
python | ray-project__ray | ci/ray_ci/doc/module.py | {
"start": 148,
"end": 2750
} | class ____:
"""
Module class represents the top level module to walk through and find annotated
APIs.
"""
def __init__(self, module: str):
self._module = importlib.import_module(module)
self._visited = set()
self._apis = []
def walk(self) -> None:
self._walk(self._module)
def get_apis(self) -> List[API]:
self.walk()
return self._apis
def _walk(self, module: ModuleType) -> None:
"""
Depth-first search through the module and its children to find annotated classes
and functions.
"""
if module.__hash__ in self._visited:
return
self._visited.add(module.__hash__)
if not self._is_valid_child(module):
return
for child in dir(module):
attribute = getattr(module, child)
if inspect.ismodule(attribute):
self._walk(attribute)
if inspect.isclass(attribute):
if self._is_api(attribute):
self._apis.append(
API(
name=self._fullname(attribute),
annotation_type=self._get_annotation_type(attribute),
code_type=CodeType.CLASS,
)
)
self._walk(attribute)
if inspect.isfunction(attribute):
if self._is_api(attribute):
self._apis.append(
API(
name=self._fullname(attribute),
annotation_type=self._get_annotation_type(attribute),
code_type=CodeType.FUNCTION,
)
)
return
def _fullname(self, module: ModuleType) -> str:
return f"{module.__module__}.{module.__qualname__}"
def _is_valid_child(self, module: ModuleType) -> bool:
"""
This module is a valid child of the top level module if it is the top level
module itself, or its module name starts with the top level module name.
"""
module = inspect.getmodule(module)
if not hasattr(module, "__name__"):
return False
return module.__name__.startswith(self._module.__name__)
def _is_api(self, module: ModuleType) -> bool:
return self._is_valid_child(module) and hasattr(module, "_annotated")
def _get_annotation_type(self, module: ModuleType) -> AnnotationType:
return AnnotationType(module._annotated_type.value)
| Module |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/sqltypes.py | {
"start": 122988,
"end": 123075
} | class ____(_Binary):
"""The SQL BINARY type."""
__visit_name__ = "BINARY"
| BINARY |
python | ansible__ansible | lib/ansible/galaxy/dependency_resolution/dataclasses.py | {
"start": 23319,
"end": 23712
} | class ____(
_ComputedReqKindsMixin,
RequirementNamedTuple,
):
"""An abstract requirement request."""
def __new__(cls, *args: object, **kwargs: object) -> t.Self:
self = RequirementNamedTuple.__new__(cls, *args, **kwargs)
return self
def __init__(self, *args: object, **kwargs: object) -> None:
super(Requirement, self).__init__()
| Requirement |
python | Lightning-AI__lightning | tests/tests_pytorch/models/test_hooks.py | {
"start": 7462,
"end": 8097
} | class ____(Callback):
def __init__(self, called):
def call(hook, fn, *args, **kwargs):
out = fn(*args, **kwargs)
d = {"name": f"Callback.{hook}"}
if args:
d["args"] = args
if kwargs:
d["kwargs"] = kwargs
called.append(d)
return out
for h in get_members(Callback):
attr = getattr(self, h)
partial_h = partial(call, h, attr)
update_wrapper(partial_h, attr)
setattr(self, h, partial_h)
def state_dict(*args, **kwargs):
return {"foo": True}
| HookedCallback |
python | python__mypy | mypy/test/testtypes.py | {
"start": 24309,
"end": 41656
} | class ____(Suite):
def setUp(self) -> None:
self.fx = TypeFixture(INVARIANT)
self.fx_co = TypeFixture(COVARIANT)
self.fx_contra = TypeFixture(CONTRAVARIANT)
def test_trivial_cases(self) -> None:
for simple in self.fx.a, self.fx.o, self.fx.b:
self.assert_join(simple, simple, simple)
def test_class_subtyping(self) -> None:
self.assert_join(self.fx.a, self.fx.o, self.fx.o)
self.assert_join(self.fx.b, self.fx.o, self.fx.o)
self.assert_join(self.fx.a, self.fx.d, self.fx.o)
self.assert_join(self.fx.b, self.fx.c, self.fx.a)
self.assert_join(self.fx.b, self.fx.d, self.fx.o)
def test_tuples(self) -> None:
self.assert_join(self.tuple(), self.tuple(), self.tuple())
self.assert_join(self.tuple(self.fx.a), self.tuple(self.fx.a), self.tuple(self.fx.a))
self.assert_join(
self.tuple(self.fx.b, self.fx.c),
self.tuple(self.fx.a, self.fx.d),
self.tuple(self.fx.a, self.fx.o),
)
self.assert_join(
self.tuple(self.fx.a, self.fx.a), self.fx.std_tuple, self.var_tuple(self.fx.anyt)
)
self.assert_join(
self.tuple(self.fx.a), self.tuple(self.fx.a, self.fx.a), self.var_tuple(self.fx.a)
)
self.assert_join(
self.tuple(self.fx.b), self.tuple(self.fx.a, self.fx.c), self.var_tuple(self.fx.a)
)
self.assert_join(self.tuple(), self.tuple(self.fx.a), self.var_tuple(self.fx.a))
def test_var_tuples(self) -> None:
self.assert_join(
self.tuple(self.fx.a), self.var_tuple(self.fx.a), self.var_tuple(self.fx.a)
)
self.assert_join(
self.var_tuple(self.fx.a), self.tuple(self.fx.a), self.var_tuple(self.fx.a)
)
self.assert_join(self.var_tuple(self.fx.a), self.tuple(), self.var_tuple(self.fx.a))
def test_function_types(self) -> None:
self.assert_join(
self.callable(self.fx.a, self.fx.b),
self.callable(self.fx.a, self.fx.b),
self.callable(self.fx.a, self.fx.b),
)
self.assert_join(
self.callable(self.fx.a, self.fx.b),
self.callable(self.fx.b, self.fx.b),
self.callable(self.fx.b, self.fx.b),
)
self.assert_join(
self.callable(self.fx.a, self.fx.b),
self.callable(self.fx.a, self.fx.a),
self.callable(self.fx.a, self.fx.a),
)
self.assert_join(self.callable(self.fx.a, self.fx.b), self.fx.function, self.fx.function)
self.assert_join(
self.callable(self.fx.a, self.fx.b),
self.callable(self.fx.d, self.fx.b),
self.fx.function,
)
def test_type_vars(self) -> None:
self.assert_join(self.fx.t, self.fx.t, self.fx.t)
self.assert_join(self.fx.s, self.fx.s, self.fx.s)
self.assert_join(self.fx.t, self.fx.s, self.fx.o)
def test_none(self) -> None:
with state.strict_optional_set(False):
# Any type t joined with None results in t.
for t in [
NoneType(),
self.fx.a,
self.fx.o,
UnboundType("x"),
self.fx.t,
self.tuple(),
self.callable(self.fx.a, self.fx.b),
self.fx.anyt,
]:
self.assert_join(t, NoneType(), t)
def test_unbound_type(self) -> None:
self.assert_join(UnboundType("x"), UnboundType("x"), self.fx.anyt)
self.assert_join(UnboundType("x"), UnboundType("y"), self.fx.anyt)
# Any type t joined with an unbound type results in dynamic. Unbound
# type means that there is an error somewhere in the program, so this
# does not affect type safety (whatever the result).
for t in [
self.fx.a,
self.fx.o,
self.fx.ga,
self.fx.t,
self.tuple(),
self.callable(self.fx.a, self.fx.b),
]:
self.assert_join(t, UnboundType("X"), self.fx.anyt)
def test_any_type(self) -> None:
# Join against 'Any' type always results in 'Any'.
with state.strict_optional_set(False):
self.assert_join(NoneType(), self.fx.anyt, self.fx.anyt)
for t in [
self.fx.anyt,
self.fx.a,
self.fx.o,
NoneType(),
UnboundType("x"),
self.fx.t,
self.tuple(),
self.callable(self.fx.a, self.fx.b),
]:
self.assert_join(t, self.fx.anyt, self.fx.anyt)
def test_mixed_truth_restricted_type_simple(self) -> None:
# make_simplified_union against differently restricted truthiness types drops restrictions.
true_a = true_only(self.fx.a)
false_o = false_only(self.fx.o)
u = make_simplified_union([true_a, false_o])
assert u.can_be_true
assert u.can_be_false
def test_mixed_truth_restricted_type(self) -> None:
# join_types against differently restricted truthiness types drops restrictions.
true_any = true_only(AnyType(TypeOfAny.special_form))
false_o = false_only(self.fx.o)
j = join_types(true_any, false_o)
assert j.can_be_true
assert j.can_be_false
def test_other_mixed_types(self) -> None:
# In general, joining unrelated types produces object.
for t1 in [self.fx.a, self.fx.t, self.tuple(), self.callable(self.fx.a, self.fx.b)]:
for t2 in [self.fx.a, self.fx.t, self.tuple(), self.callable(self.fx.a, self.fx.b)]:
if str(t1) != str(t2):
self.assert_join(t1, t2, self.fx.o)
def test_simple_generics(self) -> None:
with state.strict_optional_set(False):
self.assert_join(self.fx.ga, self.fx.nonet, self.fx.ga)
with state.strict_optional_set(True):
self.assert_join(self.fx.ga, self.fx.nonet, UnionType([self.fx.ga, NoneType()]))
self.assert_join(self.fx.ga, self.fx.anyt, self.fx.anyt)
for t in [
self.fx.a,
self.fx.o,
self.fx.t,
self.tuple(),
self.callable(self.fx.a, self.fx.b),
]:
self.assert_join(t, self.fx.ga, self.fx.o)
def test_generics_invariant(self) -> None:
self.assert_join(self.fx.ga, self.fx.ga, self.fx.ga)
self.assert_join(self.fx.ga, self.fx.gb, self.fx.o)
self.assert_join(self.fx.ga, self.fx.gd, self.fx.o)
self.assert_join(self.fx.ga, self.fx.g2a, self.fx.o)
def test_generics_covariant(self) -> None:
self.assert_join(self.fx_co.ga, self.fx_co.ga, self.fx_co.ga)
self.assert_join(self.fx_co.ga, self.fx_co.gb, self.fx_co.ga)
self.assert_join(self.fx_co.ga, self.fx_co.gd, self.fx_co.go)
self.assert_join(self.fx_co.ga, self.fx_co.g2a, self.fx_co.o)
def test_generics_contravariant(self) -> None:
self.assert_join(self.fx_contra.ga, self.fx_contra.ga, self.fx_contra.ga)
# TODO: this can be more precise than "object", see a comment in mypy/join.py
self.assert_join(self.fx_contra.ga, self.fx_contra.gb, self.fx_contra.o)
self.assert_join(self.fx_contra.ga, self.fx_contra.g2a, self.fx_contra.o)
def test_generics_with_multiple_args(self) -> None:
self.assert_join(self.fx_co.hab, self.fx_co.hab, self.fx_co.hab)
self.assert_join(self.fx_co.hab, self.fx_co.hbb, self.fx_co.hab)
self.assert_join(self.fx_co.had, self.fx_co.haa, self.fx_co.hao)
def test_generics_with_inheritance(self) -> None:
self.assert_join(self.fx_co.gsab, self.fx_co.gb, self.fx_co.gb)
self.assert_join(self.fx_co.gsba, self.fx_co.gb, self.fx_co.ga)
self.assert_join(self.fx_co.gsab, self.fx_co.gd, self.fx_co.go)
def test_generics_with_inheritance_and_shared_supertype(self) -> None:
self.assert_join(self.fx_co.gsba, self.fx_co.gs2a, self.fx_co.ga)
self.assert_join(self.fx_co.gsab, self.fx_co.gs2a, self.fx_co.ga)
self.assert_join(self.fx_co.gsab, self.fx_co.gs2d, self.fx_co.go)
def test_generic_types_and_any(self) -> None:
self.assert_join(self.fx.gdyn, self.fx.ga, self.fx.gdyn)
self.assert_join(self.fx_co.gdyn, self.fx_co.ga, self.fx_co.gdyn)
self.assert_join(self.fx_contra.gdyn, self.fx_contra.ga, self.fx_contra.gdyn)
def test_callables_with_any(self) -> None:
self.assert_join(
self.callable(self.fx.a, self.fx.a, self.fx.anyt, self.fx.a),
self.callable(self.fx.a, self.fx.anyt, self.fx.a, self.fx.anyt),
self.callable(self.fx.a, self.fx.anyt, self.fx.anyt, self.fx.anyt),
)
def test_overloaded(self) -> None:
c = self.callable
def ov(*items: CallableType) -> Overloaded:
return Overloaded(list(items))
fx = self.fx
func = fx.function
c1 = c(fx.a, fx.a)
c2 = c(fx.b, fx.b)
c3 = c(fx.c, fx.c)
self.assert_join(ov(c1, c2), c1, c1)
self.assert_join(ov(c1, c2), c2, c2)
self.assert_join(ov(c1, c2), ov(c1, c2), ov(c1, c2))
self.assert_join(ov(c1, c2), ov(c1, c3), c1)
self.assert_join(ov(c2, c1), ov(c3, c1), c1)
self.assert_join(ov(c1, c2), c3, func)
def test_overloaded_with_any(self) -> None:
c = self.callable
def ov(*items: CallableType) -> Overloaded:
return Overloaded(list(items))
fx = self.fx
any = fx.anyt
self.assert_join(ov(c(fx.a, fx.a), c(fx.b, fx.b)), c(any, fx.b), c(any, fx.b))
self.assert_join(ov(c(fx.a, fx.a), c(any, fx.b)), c(fx.b, fx.b), c(any, fx.b))
def test_join_interface_types(self) -> None:
self.assert_join(self.fx.f, self.fx.f, self.fx.f)
self.assert_join(self.fx.f, self.fx.f2, self.fx.o)
self.assert_join(self.fx.f, self.fx.f3, self.fx.f)
def test_join_interface_and_class_types(self) -> None:
self.assert_join(self.fx.o, self.fx.f, self.fx.o)
self.assert_join(self.fx.a, self.fx.f, self.fx.o)
self.assert_join(self.fx.e, self.fx.f, self.fx.f)
@skip
def test_join_class_types_with_interface_result(self) -> None:
# Unique result
self.assert_join(self.fx.e, self.fx.e2, self.fx.f)
# Ambiguous result
self.assert_join(self.fx.e2, self.fx.e3, self.fx.anyt)
@skip
def test_generic_interfaces(self) -> None:
fx = InterfaceTypeFixture()
self.assert_join(fx.gfa, fx.gfa, fx.gfa)
self.assert_join(fx.gfa, fx.gfb, fx.o)
self.assert_join(fx.m1, fx.gfa, fx.gfa)
self.assert_join(fx.m1, fx.gfb, fx.o)
def test_simple_type_objects(self) -> None:
t1 = self.type_callable(self.fx.a, self.fx.a)
t2 = self.type_callable(self.fx.b, self.fx.b)
tr = self.type_callable(self.fx.b, self.fx.a)
self.assert_join(t1, t1, t1)
j = join_types(t1, t1)
assert isinstance(j, CallableType)
assert j.is_type_obj()
self.assert_join(t1, t2, tr)
self.assert_join(t1, self.fx.type_type, self.fx.type_type)
self.assert_join(self.fx.type_type, self.fx.type_type, self.fx.type_type)
def test_type_type(self) -> None:
self.assert_join(self.fx.type_a, self.fx.type_b, self.fx.type_a)
self.assert_join(self.fx.type_b, self.fx.type_any, self.fx.type_any)
self.assert_join(self.fx.type_b, self.fx.type_type, self.fx.type_type)
self.assert_join(self.fx.type_b, self.fx.type_c, self.fx.type_a)
self.assert_join(self.fx.type_c, self.fx.type_d, TypeType.make_normalized(self.fx.o))
self.assert_join(self.fx.type_type, self.fx.type_any, self.fx.type_type)
self.assert_join(self.fx.type_b, self.fx.anyt, self.fx.anyt)
def test_literal_type(self) -> None:
a = self.fx.a
d = self.fx.d
lit1 = self.fx.lit1
lit2 = self.fx.lit2
lit3 = self.fx.lit3
self.assert_join(lit1, lit1, lit1)
self.assert_join(lit1, a, a)
self.assert_join(lit1, d, self.fx.o)
self.assert_join(lit1, lit2, a)
self.assert_join(lit1, lit3, self.fx.o)
self.assert_join(lit1, self.fx.anyt, self.fx.anyt)
self.assert_join(UnionType([lit1, lit2]), lit2, UnionType([lit1, lit2]))
self.assert_join(UnionType([lit1, lit2]), a, a)
self.assert_join(UnionType([lit1, lit3]), a, UnionType([a, lit3]))
self.assert_join(UnionType([d, lit3]), lit3, d)
self.assert_join(UnionType([d, lit3]), d, UnionType([d, lit3]))
self.assert_join(UnionType([a, lit1]), lit1, a)
self.assert_join(UnionType([a, lit1]), lit2, a)
self.assert_join(UnionType([lit1, lit2]), UnionType([lit1, lit2]), UnionType([lit1, lit2]))
# The order in which we try joining two unions influences the
# ordering of the items in the final produced unions. So, we
# manually call 'assert_simple_join' and tune the output
# after swapping the arguments here.
self.assert_simple_join(
UnionType([lit1, lit2]), UnionType([lit2, lit3]), UnionType([lit1, lit2, lit3])
)
self.assert_simple_join(
UnionType([lit2, lit3]), UnionType([lit1, lit2]), UnionType([lit2, lit3, lit1])
)
def test_variadic_tuple_joins(self) -> None:
# These tests really test just the "arity", to be sure it is handled correctly.
self.assert_join(
self.tuple(self.fx.a, self.fx.a),
self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a]))),
Instance(self.fx.std_tuplei, [self.fx.a]),
)
self.assert_join(
self.tuple(self.fx.a, self.fx.a),
self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a])), self.fx.a),
self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a])), self.fx.a),
)
self.assert_join(
self.tuple(self.fx.a, self.fx.a),
self.tuple(self.fx.a, UnpackType(Instance(self.fx.std_tuplei, [self.fx.a]))),
self.tuple(self.fx.a, UnpackType(Instance(self.fx.std_tuplei, [self.fx.a]))),
)
self.assert_join(
self.tuple(
self.fx.a, UnpackType(Instance(self.fx.std_tuplei, [self.fx.a])), self.fx.a
),
self.tuple(
self.fx.a, UnpackType(Instance(self.fx.std_tuplei, [self.fx.a])), self.fx.a
),
self.tuple(
self.fx.a, UnpackType(Instance(self.fx.std_tuplei, [self.fx.a])), self.fx.a
),
)
self.assert_join(
self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a]))),
self.tuple(
self.fx.a, UnpackType(Instance(self.fx.std_tuplei, [self.fx.a])), self.fx.a
),
Instance(self.fx.std_tuplei, [self.fx.a]),
)
self.assert_join(
self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a]))),
self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a]))),
Instance(self.fx.std_tuplei, [self.fx.a]),
)
self.assert_join(
self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a])), self.fx.a),
self.tuple(
self.fx.b, UnpackType(Instance(self.fx.std_tuplei, [self.fx.b])), self.fx.b
),
self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a])), self.fx.a),
)
def test_join_type_type_type_var(self) -> None:
self.assert_join(self.fx.type_a, self.fx.t, self.fx.o)
self.assert_join(self.fx.t, self.fx.type_a, self.fx.o)
# There are additional test cases in check-inference.test.
# TODO: Function types + varargs and default args.
def assert_join(self, s: Type, t: Type, join: Type) -> None:
self.assert_simple_join(s, t, join)
self.assert_simple_join(t, s, join)
def assert_simple_join(self, s: Type, t: Type, join: Type) -> None:
result = join_types(s, t)
actual = str(result)
expected = str(join)
assert_equal(actual, expected, f"join({s}, {t}) == {{}} ({{}} expected)")
assert is_subtype(s, result), f"{s} not subtype of {result}"
assert is_subtype(t, result), f"{t} not subtype of {result}"
def tuple(self, *a: Type) -> TupleType:
return TupleType(list(a), self.fx.std_tuple)
def var_tuple(self, t: Type) -> Instance:
"""Construct a variable-length tuple type"""
return Instance(self.fx.std_tuplei, [t])
def callable(self, *a: Type) -> CallableType:
"""callable(a1, ..., an, r) constructs a callable with argument types
a1, ... an and return type r.
"""
n = len(a) - 1
return CallableType(list(a[:-1]), [ARG_POS] * n, [None] * n, a[-1], self.fx.function)
def type_callable(self, *a: Type) -> CallableType:
"""type_callable(a1, ..., an, r) constructs a callable with
argument types a1, ... an and return type r, and which
represents a type.
"""
n = len(a) - 1
return CallableType(list(a[:-1]), [ARG_POS] * n, [None] * n, a[-1], self.fx.type_type)
| JoinSuite |
python | huggingface__transformers | tests/models/gemma3n/test_modeling_gemma3n.py | {
"start": 29645,
"end": 33380
} | class ____:
text_config = {"activation_sparsity_pattern": None}
forced_config_args = ["text_config"]
def __init__(
self,
parent,
mm_tokens_per_image=2,
image_token_index=1,
boi_token_index=2,
eoi_token_index=3,
seq_length=25,
is_training=True,
vision_config={
"use_labels": True,
"image_size": 20,
"patch_size": 5,
"num_channels": 3,
"is_training": True,
"hidden_size": 32,
"num_key_value_heads": 1,
"num_hidden_layers": 2,
"num_attention_heads": 4,
"intermediate_size": 37,
"dropout": 0.1,
"attention_dropout": 0.1,
"initializer_range": 0.02,
},
use_cache=False,
):
self.parent = parent
# `image_token_index` is set to 0 to pass "resize_embeddings" test, do not modify
self.mm_tokens_per_image = mm_tokens_per_image
self.image_token_index = image_token_index
self.boi_token_index = boi_token_index
self.eoi_token_index = eoi_token_index
self.llm_tester = Gemma3nTextModelTester(self.parent)
self.text_config = self.llm_tester.get_config()
self.vision_config = vision_config
self.seq_length = seq_length
self.pad_token_id = self.text_config.pad_token_id
self.num_hidden_layers = self.text_config.num_hidden_layers
self.vocab_size = self.text_config.vocab_size
self.hidden_size = self.text_config.hidden_size
self.num_attention_heads = self.text_config.num_attention_heads
self.is_training = is_training
self.batch_size = 3
self.num_channels = vision_config["num_channels"]
self.image_size = vision_config["image_size"]
self.encoder_seq_length = seq_length
self.use_cache = use_cache
def get_config(self):
return Gemma3nConfig(
text_config=self.text_config,
vision_config=self.vision_config,
image_token_index=self.image_token_index,
boi_token_index=self.boi_token_index,
eoi_token_index=self.eoi_token_index,
mm_tokens_per_image=self.mm_tokens_per_image,
)
def prepare_config_and_inputs(self):
pixel_values = floats_tensor(
[
self.batch_size,
self.vision_config["num_channels"],
self.vision_config["image_size"],
self.vision_config["image_size"],
]
)
config = self.get_config()
return config, pixel_values
def prepare_config_and_inputs_for_common(self):
config_and_inputs = self.prepare_config_and_inputs()
config, pixel_values = config_and_inputs
input_ids = ids_tensor([self.batch_size, self.seq_length], config.text_config.vocab_size - 1) + 1
attention_mask = input_ids.ne(self.pad_token_id).to(torch_device)
# set the 3 first tokens to be image, and ensure that no other tokens are image tokens
# do not change this unless you modified image size or patch size
input_ids[input_ids == config.image_token_index] = self.pad_token_id
input_ids[:, :1] = config.image_token_index
token_type_ids = torch.zeros_like(input_ids)
token_type_ids[input_ids == config.image_token_index] = 1
inputs_dict = {
"pixel_values": pixel_values,
"input_ids": input_ids,
"attention_mask": attention_mask,
"token_type_ids": token_type_ids,
}
return config, inputs_dict
@unittest.skip("Skipped for now!")
@require_torch
| Gemma3nVision2TextModelTester |
python | wandb__wandb | wandb/sdk/artifacts/artifact_download_logger.py | {
"start": 179,
"end": 1537
} | class ____:
def __init__(
self,
nfiles: int,
clock_for_testing: Callable[[], float] = time.monotonic,
termlog_for_testing: Callable[..., None] = termlog,
) -> None:
self._nfiles = nfiles
self._clock = clock_for_testing
self._termlog = termlog_for_testing
self._n_files_downloaded = 0
self._spinner_index = 0
self._last_log_time = self._clock()
self._lock = multiprocessing.dummy.Lock()
def notify_downloaded(self) -> None:
with self._lock:
self._n_files_downloaded += 1
if self._n_files_downloaded == self._nfiles:
self._termlog(
f" {self._nfiles} of {self._nfiles} files downloaded. ",
# ^ trailing spaces to wipe out ellipsis from previous logs
newline=True,
)
self._last_log_time = self._clock()
elif self._clock() - self._last_log_time > 0.1:
self._spinner_index += 1
spinner = r"-\|/"[self._spinner_index % 4]
self._termlog(
f"{spinner} {self._n_files_downloaded} of {self._nfiles} files downloaded...\r",
newline=False,
)
self._last_log_time = self._clock()
| ArtifactDownloadLogger |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/comparison1.py | {
"start": 736,
"end": 1548
} | class ____: ...
_T1 = TypeVar("_T1")
_T2 = TypeVar("_T2", bound=ClassB)
def func2(a: ClassA, b: ClassB, c: _T1, d: _T2, e: ClassA | ClassB) -> None | _T1 | _T2:
# This should generate an error because there is no overlap in types.
if a == b:
return
# This should generate an error because there is no overlap in types.
if a != b:
return
if a != c:
return
# This should generate an error because there is no overlap in types.
if a != d:
return
if a == e:
return
if b == e:
return
def func3(base: type) -> None:
if base == ClassA:
...
if ClassA == base:
...
def func4(val: str | None):
# This should generate an error because there is no overlap in types.
if val == 42:
...
| ClassB |
python | qdrant__qdrant-client | qdrant_client/http/api/distributed_api.py | {
"start": 8366,
"end": 10577
} | class ____(_DistributedApi):
def cluster_status(
self,
) -> m.InlineResponse2002:
"""
Get information about the current state and composition of the cluster
"""
return self._build_for_cluster_status()
def collection_cluster_info(
self,
collection_name: str,
) -> m.InlineResponse2007:
"""
Get cluster information for a collection
"""
return self._build_for_collection_cluster_info(
collection_name=collection_name,
)
def create_shard_key(
self,
collection_name: str,
timeout: int = None,
create_sharding_key: m.CreateShardingKey = None,
) -> m.InlineResponse200:
return self._build_for_create_shard_key(
collection_name=collection_name,
timeout=timeout,
create_sharding_key=create_sharding_key,
)
def delete_shard_key(
self,
collection_name: str,
timeout: int = None,
drop_sharding_key: m.DropShardingKey = None,
) -> m.InlineResponse200:
return self._build_for_delete_shard_key(
collection_name=collection_name,
timeout=timeout,
drop_sharding_key=drop_sharding_key,
)
def recover_current_peer(
self,
) -> m.InlineResponse200:
return self._build_for_recover_current_peer()
def remove_peer(
self,
peer_id: int,
timeout: int = None,
force: bool = None,
) -> m.InlineResponse200:
"""
Tries to remove peer from the cluster. Will return an error if peer has shards on it.
"""
return self._build_for_remove_peer(
peer_id=peer_id,
timeout=timeout,
force=force,
)
def update_collection_cluster(
self,
collection_name: str,
timeout: int = None,
cluster_operations: m.ClusterOperations = None,
) -> m.InlineResponse200:
return self._build_for_update_collection_cluster(
collection_name=collection_name,
timeout=timeout,
cluster_operations=cluster_operations,
)
| SyncDistributedApi |
python | spack__spack | lib/spack/spack/llnl/util/link_tree.py | {
"start": 11994,
"end": 14892
} | class ____(fs.BaseDirectoryVisitor):
"""DestinationMergeVisitor takes a SourceMergeVisitor and:
a. registers additional conflicts when merging to the destination prefix
b. removes redundant mkdir operations when directories already exist in the destination prefix.
This also makes sure that symlinked directories in the target prefix will never be merged with
directories in the sources directories.
"""
def __init__(self, source_merge_visitor: SourceMergeVisitor):
self.src = source_merge_visitor
def before_visit_dir(self, root: str, rel_path: str, depth: int) -> bool:
# If destination dir is a file in a src dir, add a conflict,
# and don't traverse deeper
if self.src._in_files(rel_path):
_, src_a_root, src_a_relpath = self.src._file(rel_path)
self.src.fatal_conflicts.append(
MergeConflict(
rel_path, os.path.join(src_a_root, src_a_relpath), os.path.join(root, rel_path)
)
)
return False
# If destination dir was also a src dir, remove the mkdir
# action, and traverse deeper.
if self.src._in_directories(rel_path):
existing_proj_rel_path, _, _ = self.src._directory(rel_path)
self.src._del_directory(existing_proj_rel_path)
return True
# If the destination dir does not appear in the src dir,
# don't descend into it.
return False
def before_visit_symlinked_dir(self, root: str, rel_path: str, depth: int) -> bool:
"""
Symlinked directories in the destination prefix should
be seen as files; we should not accidentally merge
source dir with a symlinked dest dir.
"""
self.visit_file(root, rel_path, depth)
# Never descend into symlinked target dirs.
return False
def visit_file(self, root: str, rel_path: str, depth: int) -> None:
# Can't merge a file if target already exists
if self.src._in_directories(rel_path):
_, src_a_root, src_a_relpath = self.src._directory(rel_path)
self.src.fatal_conflicts.append(
MergeConflict(
rel_path, os.path.join(src_a_root, src_a_relpath), os.path.join(root, rel_path)
)
)
elif self.src._in_files(rel_path):
_, src_a_root, src_a_relpath = self.src._file(rel_path)
self.src.fatal_conflicts.append(
MergeConflict(
rel_path, os.path.join(src_a_root, src_a_relpath), os.path.join(root, rel_path)
)
)
def visit_symlinked_file(self, root: str, rel_path: str, depth: int) -> None:
# Treat symlinked files as ordinary files (without "dereferencing")
self.visit_file(root, rel_path, depth)
| DestinationMergeVisitor |
python | django__django | tests/utils_tests/test_http.py | {
"start": 9991,
"end": 10759
} | class ____(unittest.TestCase):
def test_good(self):
for pair in (
("example.com", "example.com"),
("example.com", ".example.com"),
("foo.example.com", ".example.com"),
("example.com:8888", "example.com:8888"),
("example.com:8888", ".example.com:8888"),
("foo.example.com:8888", ".example.com:8888"),
):
self.assertIs(is_same_domain(*pair), True)
def test_bad(self):
for pair in (
("example2.com", "example.com"),
("foo.example.com", "example.com"),
("example.com:9999", "example.com:8888"),
("foo.example.com:8888", ""),
):
self.assertIs(is_same_domain(*pair), False)
| IsSameDomainTests |
python | spyder-ide__spyder | spyder/plugins/completion/providers/languageserver/conftabs/otherlanguages.py | {
"start": 759,
"end": 4106
} | class ____(SpyderPreferencesTab):
"""LSP server configuration for other languages."""
TITLE = _('Other languages')
def __init__(self, parent):
super().__init__(parent)
servers_label = QLabel(
_("Spyder uses the <a href=\"{lsp_url}\">Language Server "
"Protocol</a> to provide code completion and linting "
"for its Editor. Here, you can setup and configure LSP servers "
"for languages other than Python, so Spyder can provide such "
"features for those languages as well."
).format(lsp_url=LSP_URL))
servers_label.setOpenExternalLinks(True)
servers_label.setWordWrap(True)
servers_label.setAlignment(Qt.AlignJustify)
# Servers table
table_label = QLabel(_('Available servers:'))
self.table = LSPServerTable(self)
self.table.setMaximumHeight(200)
table_layout = QHBoxLayout()
table_layout.addSpacing(2 * AppStyle.MarginSize)
table_layout.addWidget(self.table)
table_layout.addSpacing(2 * AppStyle.MarginSize)
# Buttons
self.new_btn = QPushButton(icon=ima.icon("edit_add"))
self.new_btn.setToolTip(_("Set up a new server"))
self.delete_btn = QPushButton(icon=ima.icon("editclear"))
self.delete_btn.setToolTip(_("Delete currently selected server"))
self.reset_btn = QPushButton(icon=ima.icon("restart"))
self.reset_btn.setToolTip(_("Reset to default values"))
self.delete_btn.setEnabled(False)
# Slots connected to buttons
self.new_btn.clicked.connect(self.create_new_server)
self.reset_btn.clicked.connect(self.reset_to_default)
self.delete_btn.clicked.connect(self.delete_server)
# Buttons layout
btns = [self.new_btn, self.delete_btn, self.reset_btn]
buttons_layout = QHBoxLayout()
buttons_layout.addStretch()
for btn in btns:
btn.setIconSize(
QSize(AppStyle.ConfigPageIconSize, AppStyle.ConfigPageIconSize)
)
buttons_layout.addWidget(btn)
buttons_layout.addStretch()
# Combined layout
servers_layout = QVBoxLayout()
servers_layout.addWidget(servers_label)
servers_layout.addSpacing(3 * AppStyle.MarginSize)
servers_layout.addWidget(table_label)
servers_layout.addLayout(table_layout)
servers_layout.addSpacing(AppStyle.MarginSize)
servers_layout.addLayout(buttons_layout)
self.setLayout(servers_layout)
def create_new_server(self):
self.table.show_editor(new_server=True)
def delete_server(self):
idx = self.table.currentIndex().row()
self.table.delete_server(idx)
self.set_modified(True)
self.delete_btn.setEnabled(False)
def reset_to_default(self):
# TODO: Improve this logic when more languages are added on the
# configuration
# Remove all non-Python servers
for language in SUPPORTED_LANGUAGES:
language = language.lower()
conf = self.get_option(language, default=None)
if conf is not None:
self.table.delete_server_by_lang(language)
def apply_settings(self):
return self.table.save_servers()
| OtherLanguagesConfigTab |
python | kamyu104__LeetCode-Solutions | Python/maximum-difference-between-increasing-elements.py | {
"start": 29,
"end": 350
} | class ____(object):
def maximumDifference(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result, prefix = 0, float("inf")
for x in nums:
result = max(result, x-prefix)
prefix = min(prefix, x)
return result if result else -1
| Solution |
python | run-llama__llama_index | llama-index-core/llama_index/core/multi_modal_llms/base.py | {
"start": 2615,
"end": 5836
} | class ____(BaseComponent, DispatcherSpanMixin):
"""Multi-Modal LLM interface."""
model_config = ConfigDict(arbitrary_types_allowed=True)
callback_manager: CallbackManager = Field(
default_factory=CallbackManager, exclude=True
)
def __init__(self, *args: Any, **kwargs: Any) -> None:
# Help static checkers understand this class hierarchy
super().__init__(*args, **kwargs)
@property
@abstractmethod
def metadata(self) -> MultiModalLLMMetadata:
"""Multi-Modal LLM metadata."""
@abstractmethod
def complete(
self,
prompt: str,
image_documents: List[Union[ImageNode, ImageBlock]],
**kwargs: Any,
) -> CompletionResponse:
"""Completion endpoint for Multi-Modal LLM."""
@abstractmethod
def stream_complete(
self,
prompt: str,
image_documents: List[Union[ImageNode, ImageBlock]],
**kwargs: Any,
) -> CompletionResponseGen:
"""Streaming completion endpoint for Multi-Modal LLM."""
@abstractmethod
def chat(
self,
messages: Sequence[ChatMessage],
**kwargs: Any,
) -> ChatResponse:
"""Chat endpoint for Multi-Modal LLM."""
@abstractmethod
def stream_chat(
self,
messages: Sequence[ChatMessage],
**kwargs: Any,
) -> ChatResponseGen:
"""Stream chat endpoint for Multi-Modal LLM."""
# ===== Async Endpoints =====
@abstractmethod
async def acomplete(
self,
prompt: str,
image_documents: List[Union[ImageNode, ImageBlock]],
**kwargs: Any,
) -> CompletionResponse:
"""Async completion endpoint for Multi-Modal LLM."""
@abstractmethod
async def astream_complete(
self,
prompt: str,
image_documents: List[Union[ImageNode, ImageBlock]],
**kwargs: Any,
) -> CompletionResponseAsyncGen:
"""Async streaming completion endpoint for Multi-Modal LLM."""
@abstractmethod
async def achat(
self,
messages: Sequence[ChatMessage],
**kwargs: Any,
) -> ChatResponse:
"""Async chat endpoint for Multi-Modal LLM."""
@abstractmethod
async def astream_chat(
self,
messages: Sequence[ChatMessage],
**kwargs: Any,
) -> ChatResponseAsyncGen:
"""Async streaming chat endpoint for Multi-Modal LLM."""
def __init_subclass__(cls, **kwargs: Any) -> None:
"""
The callback decorators installs events, so they must be applied before
the span decorators, otherwise the spans wouldn't contain the events.
"""
for attr in (
"complete",
"acomplete",
"stream_complete",
"astream_complete",
"chat",
"achat",
"stream_chat",
"astream_chat",
):
if callable(method := cls.__dict__.get(attr)):
if attr.endswith("chat"):
setattr(cls, attr, llm_chat_callback()(method))
else:
setattr(cls, attr, llm_completion_callback()(method))
super().__init_subclass__(**kwargs)
| MultiModalLLM |
python | python-openxml__python-docx | tests/test_section.py | {
"start": 859,
"end": 3759
} | class ____:
"""Unit-test suite for `docx.section.Sections`."""
def it_knows_how_many_sections_it_contains(self, document_part_: Mock):
document_elm = cast(
CT_Document, element("w:document/w:body/(w:p/w:pPr/w:sectPr, w:sectPr)")
)
sections = Sections(document_elm, document_part_)
assert len(sections) == 2
def it_can_iterate_over_its_Section_instances(
self, Section_: Mock, section_: Mock, document_part_: Mock
):
document_elm = cast(
CT_Document, element("w:document/w:body/(w:p/w:pPr/w:sectPr, w:sectPr)")
)
sectPrs = document_elm.xpath("//w:sectPr")
Section_.return_value = section_
sections = Sections(document_elm, document_part_)
section_lst = list(sections)
assert Section_.call_args_list == [
call(sectPrs[0], document_part_),
call(sectPrs[1], document_part_),
]
assert section_lst == [section_, section_]
def it_can_access_its_Section_instances_by_index(
self, Section_: Mock, section_: Mock, document_part_: Mock
):
document_elm = cast(
CT_Document,
element("w:document/w:body/(w:p/w:pPr/w:sectPr,w:p/w:pPr/w:sectPr,w:sectPr)"),
)
sectPrs = document_elm.xpath("//w:sectPr")
Section_.return_value = section_
sections = Sections(document_elm, document_part_)
section_lst = [sections[idx] for idx in range(3)]
assert Section_.call_args_list == [
call(sectPrs[0], document_part_),
call(sectPrs[1], document_part_),
call(sectPrs[2], document_part_),
]
assert section_lst == [section_, section_, section_]
def it_can_access_its_Section_instances_by_slice(
self, Section_: Mock, section_: Mock, document_part_: Mock
):
document_elm = cast(
CT_Document,
element("w:document/w:body/(w:p/w:pPr/w:sectPr,w:p/w:pPr/w:sectPr,w:sectPr)"),
)
sectPrs = document_elm.xpath("//w:sectPr")
Section_.return_value = section_
sections = Sections(document_elm, document_part_)
section_lst = sections[1:9]
assert Section_.call_args_list == [
call(sectPrs[1], document_part_),
call(sectPrs[2], document_part_),
]
assert section_lst == [section_, section_]
# -- fixtures---------------------------------------------------------------------------------
@pytest.fixture
def document_part_(self, request: FixtureRequest):
return instance_mock(request, DocumentPart)
@pytest.fixture
def Section_(self, request: FixtureRequest):
return class_mock(request, "docx.section.Section")
@pytest.fixture
def section_(self, request: FixtureRequest):
return instance_mock(request, Section)
| DescribeSections |
python | huggingface__transformers | src/transformers/models/starcoder2/modular_starcoder2.py | {
"start": 9148,
"end": 9208
} | class ____(MistralForCausalLM):
pass
| Starcoder2ForCausalLM |
python | falconry__falcon | falcon/util/reader.py | {
"start": 874,
"end": 14642
} | class ____:
def __init__(
self,
read: Callable[[int], bytes],
max_stream_len: int,
chunk_size: int | None = None,
):
self._read_func = read
self._chunk_size = chunk_size or DEFAULT_CHUNK_SIZE
self._max_join_size = self._chunk_size * _MAX_JOIN_CHUNKS
self._buffer = b''
self._buffer_len = 0
self._buffer_pos = 0
self._max_bytes_remaining = max_stream_len
def _perform_read(self, size: int) -> bytes:
# PERF(vytas): In Cython, bind types:
# cdef bytes chunk
# cdef Py_ssize_t chunk_len
# cdef result
size = min(size, self._max_bytes_remaining)
if size <= 0:
return b''
chunk = self._read_func(size)
chunk_len = len(chunk)
self._max_bytes_remaining -= chunk_len
if chunk_len == size:
return chunk
if chunk_len == 0:
# NOTE(vytas): The EOF.
self._max_bytes_remaining = 0
return b''
result = io.BytesIO(chunk)
result.seek(chunk_len)
while True:
size -= chunk_len
if size <= 0:
return result.getvalue()
chunk = self._read_func(size)
chunk_len = len(chunk)
if chunk_len == 0:
# NOTE(vytas): The EOF.
self._max_bytes_remaining = 0
return result.getvalue()
self._max_bytes_remaining -= chunk_len
result.write(chunk)
def _fill_buffer(self) -> None:
# PERF(vytas): In Cython, bind types:
# cdef Py_ssize_t read_size
if self._buffer_len - self._buffer_pos < self._chunk_size:
read_size = self._chunk_size - (self._buffer_len - self._buffer_pos)
if self._buffer_pos == 0:
self._buffer += self._perform_read(read_size)
else:
self._buffer = self._buffer[self._buffer_pos :] + self._perform_read(
read_size
)
self._buffer_pos = 0
self._buffer_len = len(self._buffer)
def peek(self, size: int = -1) -> bytes:
if size < 0 or size > self._chunk_size:
size = self._chunk_size
if self._buffer_len - self._buffer_pos < size:
self._fill_buffer()
return self._buffer[self._buffer_pos : self._buffer_pos + size]
def _normalize_size(self, size: int | None) -> int:
# PERF(vytas): In Cython, bind types:
# cdef Py_ssize_t result
# cdef Py_ssize_t max_size
max_size = self._max_bytes_remaining + self._buffer_len - self._buffer_pos
if size is None or size == -1 or size > max_size:
return max_size
return size
def read(self, size: int | None = -1) -> bytes:
return self._read(self._normalize_size(size))
def _read(self, size: int) -> bytes:
# PERF(vytas): In Cython, bind types:
# cdef Py_ssize_t read_size
# cdef bytes result
# NOTE(vytas): Dish directly from the buffer, if possible.
if size <= self._buffer_len - self._buffer_pos:
if size == self._buffer_len and self._buffer_pos == 0:
result = self._buffer
self._buffer_len = 0
self._buffer = b''
return result
self._buffer_pos += size
return self._buffer[self._buffer_pos - size : self._buffer_pos]
# NOTE(vytas): Pass through large reads.
if self._buffer_len == 0 and size >= self._chunk_size:
return self._perform_read(size)
# NOTE(vytas): if size > self._buffer_len - self._buffer_pos
read_size = size - (self._buffer_len - self._buffer_pos)
result = self._buffer[self._buffer_pos :]
if read_size >= self._chunk_size:
self._buffer_len = 0
self._buffer_pos = 0
self._buffer = b''
return result + self._perform_read(read_size)
self._buffer = self._perform_read(self._chunk_size)
self._buffer_len = len(self._buffer)
self._buffer_pos = read_size
return result + self._buffer[:read_size]
def read_until(
self, delimiter: bytes, size: int = -1, consume_delimiter: bool = False
) -> bytes:
# PERF(vytas): In Cython, bind types:
# cdef Py_ssize_t read_size
# cdef result
read_size = self._normalize_size(size)
if read_size <= self._max_join_size:
return self._read_until(delimiter, read_size, consume_delimiter)
# NOTE(vytas): A large size was requested, optimize for memory
# consumption by avoiding to momentarily keep both the chunks and the
# joint result in memory at the same time.
result = io.BytesIO()
self.pipe_until(delimiter, result, consume_delimiter, read_size)
return result.getvalue()
def _finalize_read_until(
self,
size: int,
backlog: list[bytes],
have_bytes: int,
consume_bytes: int,
delimiter: bytes | None = None,
delimiter_pos: int = -1,
next_chunk: bytes | None = None,
next_chunk_len: int = 0,
) -> bytes:
if delimiter_pos < 0 and delimiter is not None:
delimiter_pos = self._buffer.find(delimiter, self._buffer_pos)
if delimiter_pos >= 0:
size = min(size, have_bytes + delimiter_pos - self._buffer_pos)
if have_bytes == 0:
# PERF(vytas): Do not join bytes unless needed.
ret_value = self._read(size)
else:
backlog.append(self._read(size - have_bytes))
ret_value = b''.join(backlog)
if next_chunk_len > 0:
assert next_chunk
if self._buffer_len == 0:
self._buffer = next_chunk
self._buffer_len = next_chunk_len
else:
self._buffer = self._buffer[self._buffer_pos :] + next_chunk
self._buffer_len = self._buffer_len - self._buffer_pos + next_chunk_len
self._buffer_pos = 0
if consume_bytes:
if delimiter_pos < 0:
if self.peek(consume_bytes) != delimiter:
raise DelimiterError('expected delimiter missing')
elif self._buffer_pos != delimiter_pos:
# NOTE(vytas): If we are going to consume the delimiter the
# quick way (i.e., skipping the above peek() check), we must
# make sure it is directly succeeding the result.
raise DelimiterError('expected delimiter missing')
self._buffer_pos += consume_bytes
return ret_value
def _read_until(
self, delimiter: bytes, size: int, consume_delimiter: bool
) -> bytes:
# PERF(vytas): In Cython, bind types:
# cdef list result = []
# cdef Py_ssize_t have_bytes = 0
# cdef Py_ssize_t delimiter_len_1 = len(delimiter) - 1
# cdef Py_ssize_t delimiter_pos = -1
# cdef Py_ssize_t consume_bytes
# cdef Py_ssize_t offset
result: list[bytes] = []
have_bytes = 0
delimiter_len_1 = len(delimiter) - 1
delimiter_pos = -1
consume_bytes = (delimiter_len_1 + 1) if consume_delimiter else 0
if not 0 <= delimiter_len_1 < self._chunk_size:
raise ValueError('delimiter length must be within [1, chunk_size]')
# PERF(vytas): If the requested size is equal to the chunk size (or is
# a multiple of it), align the buffer.
# This can often nearly *double* the performance if one is reading in
# chunks.
if size % self._chunk_size == 0:
self._fill_buffer()
while True:
if self._buffer_len > self._buffer_pos:
delimiter_pos = self._buffer.find(delimiter, self._buffer_pos)
if delimiter_pos >= 0:
# NOTE(vytas): Delimiter was found in the current buffer.
# We can now return to the caller.
return self._finalize_read_until(
size,
result,
have_bytes,
consume_bytes,
delimiter_pos=delimiter_pos,
)
if size < (
have_bytes + self._buffer_len - self._buffer_pos - delimiter_len_1
):
# NOTE(vytas): We now have enough data in the buffer to return
# to the caller.
return self._finalize_read_until(
size, result, have_bytes, consume_bytes, delimiter
)
next_chunk = self._perform_read(self._chunk_size)
next_chunk_len = len(next_chunk)
if self._max_bytes_remaining == 0:
# NOTE(vytas): We have reached the EOF.
self._buffer_len += next_chunk_len
self._buffer += next_chunk
return self._finalize_read_until(
size, result, have_bytes, consume_bytes, delimiter
)
# NOTE(vytas): The buffer was empty before, skip straight to the
# next chunk.
if self._buffer_len <= self._buffer_pos:
self._buffer_len = next_chunk_len
self._buffer_pos = 0
self._buffer = next_chunk
continue
# NOTE(vytas): We must check there is no delimiter in the chunk
# boundary before we can safely splice them.
if delimiter_len_1 > 0:
offset = max(self._buffer_len - delimiter_len_1, self._buffer_pos)
fragment = self._buffer[offset:] + next_chunk[:delimiter_len_1]
delimiter_pos = fragment.find(delimiter)
if delimiter_pos >= 0:
self._buffer_len += next_chunk_len
self._buffer += next_chunk
return self._finalize_read_until(
size,
result,
have_bytes,
consume_bytes,
delimiter,
delimiter_pos + offset,
)
if have_bytes + self._buffer_len - self._buffer_pos >= size:
# NOTE(vytas): we have now verified that all bytes currently in
# the buffer are delimiter-free, including the border of the
# upcoming chunk
return self._finalize_read_until(
size,
result,
have_bytes,
consume_bytes,
delimiter,
next_chunk=next_chunk,
next_chunk_len=next_chunk_len,
)
have_bytes += self._buffer_len - self._buffer_pos
if self._buffer_pos > 0:
result.append(self._buffer[self._buffer_pos :])
else:
result.append(self._buffer)
self._buffer_len = next_chunk_len
self._buffer_pos = 0
self._buffer = next_chunk
def pipe(self, destination: IO | None = None) -> None:
while True:
chunk = self.read(self._chunk_size)
if not chunk:
break
if destination is not None:
destination.write(chunk)
def pipe_until(
self,
delimiter: bytes,
destination: IO | None = None,
consume_delimiter: bool = False,
_size: int | None = None,
) -> None:
# PERF(vytas): In Cython, bind types:
# cdef Py_ssize_t remaining
remaining = self._normalize_size(_size)
while remaining > 0:
chunk = self._read_until(delimiter, min(self._chunk_size, remaining), False)
if not chunk:
break
if destination is not None:
destination.write(chunk)
remaining -= self._chunk_size
if consume_delimiter:
delimiter_len = len(delimiter)
if self.peek(delimiter_len) != delimiter:
raise DelimiterError('expected delimiter missing')
self._buffer_pos += delimiter_len
def exhaust(self) -> None:
self.pipe()
def delimit(self, delimiter: bytes) -> BufferedReader:
read = functools.partial(self.read_until, delimiter)
return type(self)(read, self._normalize_size(None), self._chunk_size)
def readline(self, size: int = -1) -> bytes:
size = self._normalize_size(size)
result = self.read_until(b'\n', size)
if len(result) < size:
return result + self.read(1)
return result
def readlines(self, hint: int = -1) -> list[bytes]:
# PERF(vytas): In Cython, bind types:
# cdef Py_ssize_t read
# cdef list result = []
read = 0
result = []
while True:
line = self.readline()
if not line:
break
result.append(line)
if hint >= 0:
read += len(line)
if read >= hint:
break
return result
# --- implementing IOBase methods, the duck-typing way ---
def readable(self) -> bool:
"""Return ``True`` always."""
return True
def seekable(self) -> bool:
"""Return ``False`` always."""
return False
def writeable(self) -> bool:
"""Return ``False`` always."""
return False
| BufferedReader |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 492689,
"end": 498776
} | class ____(VegaLiteSchema):
"""
IntervalSelectionConfigWithoutType schema wrapper.
Parameters
----------
clear : str, bool, dict, :class:`Stream`, :class:`EventStream`, :class:`MergedStream`, :class:`DerivedStream`
Clears the selection, emptying it of all values. This property can be a `Event
Stream <https://vega.github.io/vega/docs/event-streams/>`__ or ``false`` to disable
clear.
**Default value:** ``dblclick``.
**See also:** `clear examples
<https://vega.github.io/vega-lite/docs/selection.html#clear>`__ in the
documentation.
encodings : Sequence[:class:`SingleDefUnitChannel`, Literal['text', 'shape', 'x', 'y', 'xOffset', 'yOffset', 'x2', 'y2', 'longitude', 'latitude', 'longitude2', 'latitude2', 'theta', 'theta2', 'radius', 'radius2', 'time', 'color', 'fill', 'stroke', 'opacity', 'fillOpacity', 'strokeOpacity', 'strokeWidth', 'strokeDash', 'size', 'angle', 'key', 'href', 'url', 'description']]
An array of encoding channels. The corresponding data field values must match for a
data tuple to fall within the selection.
**See also:** The `projection with encodings and fields section
<https://vega.github.io/vega-lite/docs/selection.html#project>`__ in the
documentation.
fields : Sequence[str, :class:`FieldName`]
An array of field names whose values must match for a data tuple to fall within the
selection.
**See also:** The `projection with encodings and fields section
<https://vega.github.io/vega-lite/docs/selection.html#project>`__ in the
documentation.
mark : dict, :class:`BrushConfig`
An interval selection also adds a rectangle mark to depict the extents of the
interval. The ``mark`` property can be used to customize the appearance of the mark.
**See also:** `mark examples
<https://vega.github.io/vega-lite/docs/selection.html#mark>`__ in the documentation.
on : str, dict, :class:`Stream`, :class:`EventStream`, :class:`MergedStream`, :class:`DerivedStream`
A `Vega event stream <https://vega.github.io/vega/docs/event-streams/>`__ (object or
selector) that triggers the selection. For interval selections, the event stream
must specify a `start and end
<https://vega.github.io/vega/docs/event-streams/#between-filters>`__.
**See also:** `on examples
<https://vega.github.io/vega-lite/docs/selection.html#on>`__ in the documentation.
resolve : :class:`SelectionResolution`, Literal['global', 'union', 'intersect']
With layered and multi-view displays, a strategy that determines how selections'
data queries are resolved when applied in a filter transform, conditional encoding
rule, or scale domain.
One of:
* ``"global"`` -- only one brush exists for the entire SPLOM. When the user begins
to drag, any previous brushes are cleared, and a new one is constructed.
* ``"union"`` -- each cell contains its own brush, and points are highlighted if
they lie within *any* of these individual brushes.
* ``"intersect"`` -- each cell contains its own brush, and points are highlighted
only if they fall within *all* of these individual brushes.
**Default value:** ``global``.
**See also:** `resolve examples
<https://vega.github.io/vega-lite/docs/selection.html#resolve>`__ in the
documentation.
translate : str, bool
When truthy, allows a user to interactively move an interval selection
back-and-forth. Can be ``true``, ``false`` (to disable panning), or a `Vega event
stream definition <https://vega.github.io/vega/docs/event-streams/>`__ which must
include a start and end event to trigger continuous panning. Discrete panning (e.g.,
pressing the left/right arrow keys) will be supported in future versions.
**Default value:** ``true``, which corresponds to ``[pointerdown, window:pointerup]
> window:pointermove!``. This default allows users to clicks and drags within an
interval selection to reposition it.
**See also:** `translate examples
<https://vega.github.io/vega-lite/docs/selection.html#translate>`__ in the
documentation.
zoom : str, bool
When truthy, allows a user to interactively resize an interval selection. Can be
``true``, ``false`` (to disable zooming), or a `Vega event stream definition
<https://vega.github.io/vega/docs/event-streams/>`__. Currently, only ``wheel``
events are supported, but custom event streams can still be used to specify filters,
debouncing, and throttling. Future versions will expand the set of events that can
trigger this transformation.
**Default value:** ``true``, which corresponds to ``wheel!``. This default allows
users to use the mouse wheel to resize an interval selection.
**See also:** `zoom examples
<https://vega.github.io/vega-lite/docs/selection.html#zoom>`__ in the documentation.
"""
_schema = {"$ref": "#/definitions/IntervalSelectionConfigWithoutType"}
def __init__(
self,
clear: Optional[str | bool | SchemaBase | Map] = Undefined,
encodings: Optional[Sequence[SchemaBase | SingleDefUnitChannel_T]] = Undefined,
fields: Optional[Sequence[str | SchemaBase]] = Undefined,
mark: Optional[SchemaBase | Map] = Undefined,
on: Optional[str | SchemaBase | Map] = Undefined,
resolve: Optional[SchemaBase | SelectionResolution_T] = Undefined,
translate: Optional[str | bool] = Undefined,
zoom: Optional[str | bool] = Undefined,
**kwds,
):
super().__init__(
clear=clear,
encodings=encodings,
fields=fields,
mark=mark,
on=on,
resolve=resolve,
translate=translate,
zoom=zoom,
**kwds,
)
| IntervalSelectionConfigWithoutType |
python | numpy__numpy | numpy/linalg/tests/test_linalg.py | {
"start": 30571,
"end": 30960
} | class ____(PinvHermitianCases):
pass
def test_pinv_rtol_arg():
a = np.array([[1, 2, 3], [4, 1, 1], [2, 3, 1]])
assert_almost_equal(
np.linalg.pinv(a, rcond=0.5),
np.linalg.pinv(a, rtol=0.5),
)
with pytest.raises(
ValueError, match=r"`rtol` and `rcond` can't be both set."
):
np.linalg.pinv(a, rcond=0.5, rtol=0.5)
| TestPinvHermitian |
python | pytorch__pytorch | test/test_fx_passes.py | {
"start": 14654,
"end": 15190
} | class ____:
@staticmethod
def forward(x, w1, w2):
m1 = torch.cat([w1, w2]).sum()
m2 = torch.cat([w2, w1]).sum()
m3 = torch.cat([m1, m2]).sum()
return x + torch.max(m1) + torch.max(m2) + m3
@staticmethod
def pattern(a, b):
return torch.cat([a, b]).sum()
test_cases = [
# match_output, match_placeholder, num_matches
TestCase(False, False, 3),
TestCase(True, False, 0),
TestCase(False, True, 2),
TestCase(True, True, 0)
]
| SimplePattern |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/streams.py | {
"start": 27586,
"end": 28246
} | class ____(SemiIncrementalMixin, GithubStream):
"""
API docs: https://docs.github.com/en/rest/projects/projects?apiVersion=2022-11-28#list-repository-projects
"""
use_cache = True
stream_base_params = {
"state": "all",
}
def request_headers(self, **kwargs) -> Mapping[str, Any]:
base_headers = super().request_headers(**kwargs)
# Projects stream requires sending following `Accept` header. If we won't sent it
# we'll get `415 Client Error: Unsupported Media Type` error.
headers = {"Accept": "application/vnd.github.inertia-preview+json"}
return {**base_headers, **headers}
| Projects |
python | vyperlang__vyper | vyper/semantics/types/primitives.py | {
"start": 12212,
"end": 13250
} | class ____(_PrimT):
_id = "address"
_valid_literal = (vy_ast.Hex,)
_type_members = {
"balance": UINT(256),
"codehash": BytesM_T(32),
"codesize": UINT(256),
"is_contract": BoolT(),
"code": BytesT(),
}
@cached_property
def abi_type(self) -> ABIType:
return ABI_Address()
def validate_literal(self, node: vy_ast.Constant) -> None:
super().validate_literal(node)
assert isinstance(node, vy_ast.Hex) # keep mypy happy
if node.n_bytes != 20:
raise InvalidLiteral(f"Invalid address. Expected 20 bytes, got {node.n_bytes}.", node)
addr = node.value
if not is_checksum_encoded(addr):
raise InvalidLiteral(
"Address checksum mismatch. If you are sure this is the right "
f"address, the correct checksummed form is: {checksum_encode(addr)}",
node,
)
# type for "self"
# refactoring note: it might be best for this to be a ModuleT actually
| AddressT |
python | getsentry__sentry | tests/sentry/api/endpoints/test_project_artifact_bundle_files.py | {
"start": 328,
"end": 14890
} | class ____(APITestCase):
def test_get_artifact_bundle_files_with_multiple_files(self) -> None:
project = self.create_project(name="foo")
artifact_bundle = self.create_artifact_bundle(
self.organization,
artifact_count=6,
fixture_path="artifact_bundle_debug_ids",
date_last_modified=(timezone.now() + timedelta(hours=1)),
)
ProjectArtifactBundle.objects.create(
organization_id=self.organization.id,
project_id=project.id,
artifact_bundle=artifact_bundle,
)
# We simulate the existence of multiple release/dist pairs for this specific bundle.
ReleaseArtifactBundle.objects.create(
organization_id=self.organization.id,
release_name="1.0",
dist_name="android",
artifact_bundle=artifact_bundle,
)
ReleaseArtifactBundle.objects.create(
organization_id=self.organization.id,
release_name="2.0",
dist_name="android",
artifact_bundle=artifact_bundle,
)
url = reverse(
"sentry-api-0-project-artifact-bundle-files",
kwargs={
"organization_id_or_slug": project.organization.slug,
"project_id_or_slug": project.slug,
"bundle_id": artifact_bundle.bundle_id,
},
)
self.login_as(user=self.user)
response = self.client.get(url)
assert response.status_code == 200, response.content
assert response.data == {
"bundleId": str(artifact_bundle.bundle_id),
"associations": [
{"release": "2.0", "dist": "android"},
{"release": "1.0", "dist": "android"},
],
"date": "2023-03-15T00:00:00Z",
"dateModified": "2023-03-15T01:00:00Z",
"fileCount": 6,
"files": [
{
"debugId": None,
"filePath": "~/bundle1.js",
"id": "ZmlsZXMvXy9fL2J1bmRsZTEuanM=",
"fileSize": 71,
"fileType": 0,
"sourcemap": None,
},
{
"debugId": None,
"filePath": "~/bundle1.min.js",
"id": "ZmlsZXMvXy9fL2J1bmRsZTEubWluLmpz",
"fileSize": 63,
"fileType": 2,
"sourcemap": "bundle1.js.map",
},
{
"debugId": None,
"filePath": "~/bundle1.min.js.map",
"fileSize": 139,
"fileType": 0,
"id": "ZmlsZXMvXy9fL2J1bmRsZTEubWluLmpzLm1hcA==",
"sourcemap": None,
},
{
"debugId": None,
"filePath": "~/index.js",
"id": "ZmlsZXMvXy9fL2luZGV4Lmpz",
"fileSize": 3706,
"fileType": 1,
"sourcemap": None,
},
{
"debugId": "eb6e60f1-65ff-4f6f-adff-f1bbeded627b",
"filePath": "~/index.js.map",
"id": "ZmlsZXMvXy9fL2luZGV4LmpzLm1hcA==",
"fileSize": 1804,
"fileType": 3,
"sourcemap": None,
},
{
"debugId": "eb6e60f1-65ff-4f6f-adff-f1bbeded627b",
"filePath": "~/index.min.js",
"id": "ZmlsZXMvXy9fL2luZGV4Lm1pbi5qcw==",
"fileSize": 1676,
"fileType": 2,
"sourcemap": "index.js.map",
},
],
}
def test_get_artifact_bundle_files_pagination_with_multiple_files(self) -> None:
project = self.create_project(name="foo")
artifact_bundle = self.create_artifact_bundle(
self.organization, artifact_count=6, fixture_path="artifact_bundle_debug_ids"
)
ProjectArtifactBundle.objects.create(
organization_id=self.organization.id,
project_id=project.id,
artifact_bundle=artifact_bundle,
)
ReleaseArtifactBundle.objects.create(
organization_id=self.organization.id,
release_name="1.0",
artifact_bundle=artifact_bundle,
)
url = reverse(
"sentry-api-0-project-artifact-bundle-files",
kwargs={
"organization_id_or_slug": project.organization.slug,
"project_id_or_slug": project.slug,
"bundle_id": artifact_bundle.bundle_id,
},
)
expected = [
{
"bundleId": str(artifact_bundle.bundle_id),
"associations": [{"release": "1.0", "dist": None}],
"date": "2023-03-15T00:00:00Z",
"dateModified": None,
"fileCount": 6,
"files": [
{
"debugId": None,
"filePath": "~/bundle1.js",
"id": "ZmlsZXMvXy9fL2J1bmRsZTEuanM=",
"fileSize": 71,
"fileType": 0,
"sourcemap": None,
},
{
"debugId": None,
"filePath": "~/bundle1.min.js",
"id": "ZmlsZXMvXy9fL2J1bmRsZTEubWluLmpz",
"fileSize": 63,
"fileType": 2,
"sourcemap": "bundle1.js.map",
},
],
},
{
"bundleId": str(artifact_bundle.bundle_id),
"associations": [{"release": "1.0", "dist": None}],
"date": "2023-03-15T00:00:00Z",
"dateModified": None,
"fileCount": 6,
"files": [
{
"debugId": None,
"filePath": "~/bundle1.min.js.map",
"fileSize": 139,
"fileType": 0,
"id": "ZmlsZXMvXy9fL2J1bmRsZTEubWluLmpzLm1hcA==",
"sourcemap": None,
},
{
"debugId": None,
"filePath": "~/index.js",
"id": "ZmlsZXMvXy9fL2luZGV4Lmpz",
"fileSize": 3706,
"fileType": 1,
"sourcemap": None,
},
],
},
{
"bundleId": str(artifact_bundle.bundle_id),
"associations": [{"release": "1.0", "dist": None}],
"date": "2023-03-15T00:00:00Z",
"dateModified": None,
"fileCount": 6,
"files": [
{
"debugId": "eb6e60f1-65ff-4f6f-adff-f1bbeded627b",
"filePath": "~/index.js.map",
"id": "ZmlsZXMvXy9fL2luZGV4LmpzLm1hcA==",
"fileSize": 1804,
"fileType": 3,
"sourcemap": None,
},
{
"debugId": "eb6e60f1-65ff-4f6f-adff-f1bbeded627b",
"filePath": "~/index.min.js",
"id": "ZmlsZXMvXy9fL2luZGV4Lm1pbi5qcw==",
"fileSize": 1676,
"fileType": 2,
"sourcemap": "index.js.map",
},
],
},
]
for index, cursor in enumerate(["2:0:1", "2:1:0", "2:2:0"]):
self.login_as(user=self.user)
response = self.client.get(url + f"?cursor={cursor}&per_page=2")
assert response.status_code == 200, response.content
assert response.data == expected[index]
def test_get_artifact_bundle_files_with_multiple_files_and_search_query(self) -> None:
project = self.create_project(name="foo")
artifact_bundle = self.create_artifact_bundle(
self.organization, artifact_count=6, fixture_path="artifact_bundle_debug_ids"
)
ProjectArtifactBundle.objects.create(
organization_id=self.organization.id,
project_id=project.id,
artifact_bundle=artifact_bundle,
)
url = reverse(
"sentry-api-0-project-artifact-bundle-files",
kwargs={
"organization_id_or_slug": project.organization.slug,
"project_id_or_slug": project.slug,
"bundle_id": artifact_bundle.bundle_id,
},
)
self.login_as(user=self.user)
# file_path match with single file.
query = "bundle1.js"
response = self.client.get(url + f"?query={query}")
assert response.status_code == 200, response.content
assert response.data == {
"bundleId": str(artifact_bundle.bundle_id),
"associations": [],
"date": "2023-03-15T00:00:00Z",
"dateModified": None,
"fileCount": 6,
"files": [
{
"debugId": None,
"filePath": "~/bundle1.js",
"id": "ZmlsZXMvXy9fL2J1bmRsZTEuanM=",
"fileSize": 71,
"fileType": 0,
"sourcemap": None,
},
],
}
# file_path match across multiple files.
query = "bundle"
response = self.client.get(url + f"?query={query}")
assert response.status_code == 200, response.content
assert response.data == {
"bundleId": str(artifact_bundle.bundle_id),
"associations": [],
"date": "2023-03-15T00:00:00Z",
"dateModified": None,
"fileCount": 6,
"files": [
{
"debugId": None,
"filePath": "~/bundle1.js",
"id": "ZmlsZXMvXy9fL2J1bmRsZTEuanM=",
"fileSize": 71,
"fileType": 0,
"sourcemap": None,
},
{
"debugId": None,
"filePath": "~/bundle1.min.js",
"id": "ZmlsZXMvXy9fL2J1bmRsZTEubWluLmpz",
"fileSize": 63,
"fileType": 2,
"sourcemap": "bundle1.js.map",
},
{
"debugId": None,
"filePath": "~/bundle1.min.js.map",
"fileSize": 139,
"fileType": 0,
"id": "ZmlsZXMvXy9fL2J1bmRsZTEubWluLmpzLm1hcA==",
"sourcemap": None,
},
],
}
# debug_id match.
query = "eb6e60f1-65ff-"
response = self.client.get(url + f"?query={query}")
assert response.status_code == 200, response.content
assert response.data == {
"bundleId": str(artifact_bundle.bundle_id),
"associations": [],
"date": "2023-03-15T00:00:00Z",
"dateModified": None,
"fileCount": 6,
"files": [
{
"debugId": "eb6e60f1-65ff-4f6f-adff-f1bbeded627b",
"filePath": "~/index.js.map",
"id": "ZmlsZXMvXy9fL2luZGV4LmpzLm1hcA==",
"fileSize": 1804,
"fileType": 3,
"sourcemap": None,
},
{
"debugId": "eb6e60f1-65ff-4f6f-adff-f1bbeded627b",
"filePath": "~/index.min.js",
"id": "ZmlsZXMvXy9fL2luZGV4Lm1pbi5qcw==",
"fileSize": 1676,
"fileType": 2,
"sourcemap": "index.js.map",
},
],
}
query = "eb6e60f165ff4f6fadfff1bbeded627b"
response = self.client.get(url + f"?query={query}")
assert response.status_code == 200, response.content
assert response.data == {
"bundleId": str(artifact_bundle.bundle_id),
"associations": [],
"date": "2023-03-15T00:00:00Z",
"dateModified": None,
"fileCount": 6,
"files": [
{
"debugId": "eb6e60f1-65ff-4f6f-adff-f1bbeded627b",
"filePath": "~/index.js.map",
"id": "ZmlsZXMvXy9fL2luZGV4LmpzLm1hcA==",
"fileSize": 1804,
"fileType": 3,
"sourcemap": None,
},
{
"debugId": "eb6e60f1-65ff-4f6f-adff-f1bbeded627b",
"filePath": "~/index.min.js",
"id": "ZmlsZXMvXy9fL2luZGV4Lm1pbi5qcw==",
"fileSize": 1676,
"fileType": 2,
"sourcemap": "index.js.map",
},
],
}
query = "EB6e60f165ff4f6fadfff1BBEded627b"
response = self.client.get(url + f"?query={query}")
assert response.status_code == 200, response.content
assert response.data == {
"bundleId": str(artifact_bundle.bundle_id),
"associations": [],
"date": "2023-03-15T00:00:00Z",
"dateModified": None,
"fileCount": 6,
"files": [
{
"debugId": "eb6e60f1-65ff-4f6f-adff-f1bbeded627b",
"filePath": "~/index.js.map",
"id": "ZmlsZXMvXy9fL2luZGV4LmpzLm1hcA==",
"fileSize": 1804,
"fileType": 3,
"sourcemap": None,
},
{
"debugId": "eb6e60f1-65ff-4f6f-adff-f1bbeded627b",
"filePath": "~/index.min.js",
"id": "ZmlsZXMvXy9fL2luZGV4Lm1pbi5qcw==",
"fileSize": 1676,
"fileType": 2,
"sourcemap": "index.js.map",
},
],
}
| ProjectArtifactBundleFilesEndpointTest |
python | dask__dask | dask/dataframe/dask_expr/_reductions.py | {
"start": 33869,
"end": 35685
} | class ____(ArrayReduction):
# Uses the parallel version of Welford's online algorithm (Chan 79')
# (http://i.stanford.edu/pub/cstr/reports/cs/tr/79/773/CS-TR-79-773.pdf)
_parameters = ["frame", "skipna", "ddof", "numeric_only", "split_every"]
_defaults = {"skipna": True, "ddof": 1, "numeric_only": False, "split_every": False}
@functools.cached_property
def _meta(self):
return make_meta(
meta_nonempty(self.frame._meta).var(
skipna=self.skipna, numeric_only=self.numeric_only
)
)
@property
def chunk_kwargs(self):
return dict(skipna=self.skipna)
@property
def combine_kwargs(self):
return {"skipna": self.skipna}
@property
def aggregate_kwargs(self):
cols = self.frame.columns if self.frame.ndim == 1 else self.frame._meta.columns
return dict(
ddof=self.ddof,
skipna=self.skipna,
meta=self._meta,
index=cols,
)
@classmethod
def reduction_chunk(cls, x, skipna):
values = x.values.astype("f8")
if skipna:
return moment_chunk(
values, sum=chunk.nansum, numel=nannumel, keepdims=True, axis=(0,)
)
else:
return moment_chunk(values, keepdims=True, axis=(0,))
@classmethod
def reduction_combine(cls, parts, skipna):
if skipna:
return moment_combine(parts, sum=np.nansum, axis=(0,))
else:
return moment_combine(parts, axis=(0,))
@classmethod
def reduction_aggregate(cls, vals, ddof, skipna):
if skipna:
result = moment_agg(vals, sum=np.nansum, ddof=ddof, axis=(0,))
else:
result = moment_agg(vals, ddof=ddof, axis=(0,))
return result
| Var |
python | pola-rs__polars | py-polars/src/polars/series/utils.py | {
"start": 4761,
"end": 6303
} | class ____:
def __init__(self) -> None:
# generate bytecode for empty functions with/without a docstring
def _empty_with_docstring() -> None:
"""""" # noqa: D419
def _empty_without_docstring() -> None:
pass
self.empty_bytecode = (
_empty_with_docstring.__code__.co_code,
_empty_without_docstring.__code__.co_code,
)
def __contains__(self, item: bytes) -> bool:
return item in self.empty_bytecode
_EMPTY_BYTECODE = _EmptyBytecodeHelper()
def get_ffi_func(
name: str, dtype: PolarsDataType, obj: PySeries
) -> Callable[..., Any] | None:
"""
Dynamically obtain the proper FFI function/ method.
Parameters
----------
name
function or method name where dtype is replaced by <>
for example
"call_foo_<>"
dtype
polars dtype.
obj
Object to find the method for.
Returns
-------
callable or None
FFI function, or None if not found.
"""
ffi_name = dtype_to_ffiname(dtype)
fname = name.replace("<>", ffi_name)
return getattr(obj, fname, None)
def _with_no_check_length(func: Callable[..., Any]) -> Any:
from polars._plr import check_length
# Catch any error so that we can be sure that we always restore length checks
try:
check_length(False)
result = func()
check_length(True)
except Exception:
check_length(True)
raise
else:
return result
| _EmptyBytecodeHelper |
python | redis__redis-py | redis/commands/search/aggregation.py | {
"start": 2034,
"end": 2174
} | class ____(SortDirection):
"""
Indicate that the given field should be sorted in descending order
"""
DIRSTRING = "DESC"
| Desc |
python | facebook__pyre-check | client/coverage_data.py | {
"start": 7218,
"end": 7611
} | class ____(libcst.CSTVisitor):
"""
Checks for explicit Any usage in code.
"""
def __init__(self) -> None:
self.has_explicit_any: bool = False
def visit_Name(self, node: libcst.Name) -> None:
if node.value == "Any":
self.has_explicit_any = True
def contains_explicit_any(self) -> bool:
return self.has_explicit_any
| ExplicitAnyChecker |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/sagemaker.py | {
"start": 29136,
"end": 41738
} | class ____(SageMakerBaseOperator):
"""
Starts a transform job.
A transform job uses a trained model to get inferences on a dataset
and saves these results to an Amazon S3 location that you specify.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:SageMakerTransformOperator`
:param config: The configuration necessary to start a transform job (templated).
If you need to create a SageMaker transform job based on an existed SageMaker model::
config = transform_config
If you need to create both SageMaker model and SageMaker Transform job::
config = {"Model": model_config, "Transform": transform_config}
For details of the configuration parameter of transform_config see
:py:meth:`SageMaker.Client.create_transform_job`
For details of the configuration parameter of model_config, See:
:py:meth:`SageMaker.Client.create_model`
:param aws_conn_id: The Airflow connection used for AWS credentials.
If this is ``None`` or empty then the default boto3 behaviour is used. If
running Airflow in a distributed manner and aws_conn_id is None or
empty, then default boto3 configuration would be used (and must be
maintained on each worker node).
:param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
:param verify: Whether or not to verify SSL certificates. See:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
:param wait_for_completion: Set to True to wait until the transform job finishes.
:param check_interval: If wait is set to True, the time interval, in seconds,
that this operation waits to check the status of the transform job.
:param max_attempts: Number of times to poll for query state before returning the current state,
defaults to None.
:param max_ingestion_time: If wait is set to True, the operation fails
if the transform job doesn't finish within max_ingestion_time seconds. If you
set this parameter to None, the operation does not timeout.
:param check_if_job_exists: If set to true, then the operator will check whether a transform job
already exists for the name in the config.
:param action_if_job_exists: Behaviour if the job name already exists. Possible options are "timestamp"
(default) and "fail".
This is only relevant if check_if_job_exists is True.
:return Dict: Returns The ARN of the model created in Amazon SageMaker.
"""
operator_extra_links = (SageMakerTransformJobLink(),)
def __init__(
self,
*,
config: dict,
wait_for_completion: bool = True,
check_interval: int = CHECK_INTERVAL_SECOND,
max_attempts: int | None = None,
max_ingestion_time: int | None = None,
check_if_job_exists: bool = True,
action_if_job_exists: str = "timestamp",
check_if_model_exists: bool = True,
action_if_model_exists: str = "timestamp",
deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
**kwargs,
):
super().__init__(config=config, **kwargs)
self.wait_for_completion = wait_for_completion
self.check_interval = check_interval
self.max_attempts = max_attempts or 60
self.max_ingestion_time = max_ingestion_time
self.check_if_job_exists = check_if_job_exists
if action_if_job_exists in ("fail", "timestamp"):
self.action_if_job_exists = action_if_job_exists
else:
raise AirflowException(
f"Argument action_if_job_exists accepts only 'timestamp' and 'fail'. \
Provided value: '{action_if_job_exists}'."
)
self.check_if_model_exists = check_if_model_exists
if action_if_model_exists in ("fail", "timestamp"):
self.action_if_model_exists = action_if_model_exists
else:
raise AirflowException(
f"Argument action_if_model_exists accepts only 'timestamp' and 'fail'. \
Provided value: '{action_if_model_exists}'."
)
self.deferrable = deferrable
self.serialized_model: dict
self.serialized_transform: dict
def _create_integer_fields(self) -> None:
"""Set fields which should be cast to integers."""
self.integer_fields: list[list[str]] = [
["Transform", "TransformResources", "InstanceCount"],
["Transform", "MaxConcurrentTransforms"],
["Transform", "MaxPayloadInMB"],
]
if "Transform" not in self.config:
for field in self.integer_fields:
field.pop(0)
def expand_role(self) -> None:
"""Expand an IAM role name into an ARN."""
if "Model" not in self.config:
return
config = self.config["Model"]
if "ExecutionRoleArn" in config:
hook = AwsBaseHook(self.aws_conn_id, client_type="iam")
config["ExecutionRoleArn"] = hook.expand_role(config["ExecutionRoleArn"])
def execute(self, context: Context) -> dict:
self.preprocess_config()
transform_config = self.config.get("Transform", self.config)
if self.check_if_job_exists:
transform_config["TransformJobName"] = self._get_unique_job_name(
transform_config["TransformJobName"],
self.action_if_job_exists == "fail",
self.hook.describe_transform_job,
)
model_config = self.config.get("Model")
if model_config:
if self.check_if_model_exists:
model_config["ModelName"] = self._get_unique_model_name(
model_config["ModelName"],
self.action_if_model_exists == "fail",
self.hook.describe_model,
)
if "ModelName" in self.config["Transform"].keys():
self.config["Transform"]["ModelName"] = model_config["ModelName"]
self.log.info("Creating SageMaker Model %s for transform job", model_config["ModelName"])
self.hook.create_model(model_config)
self.log.info("Creating SageMaker transform Job %s.", transform_config["TransformJobName"])
if self.deferrable and not self.wait_for_completion:
self.log.warning(
"Setting deferrable to True does not have effect when wait_for_completion is set to False."
)
wait_for_completion = self.wait_for_completion
if self.deferrable and self.wait_for_completion:
# Set wait_for_completion to False so that it waits for the status in the deferred task.
wait_for_completion = False
response = self.hook.create_transform_job(
transform_config,
wait_for_completion=wait_for_completion,
check_interval=self.check_interval,
max_ingestion_time=self.max_ingestion_time,
)
if response["ResponseMetadata"]["HTTPStatusCode"] != 200:
raise AirflowException(f"Sagemaker transform Job creation failed: {response}")
transform_job_url = SageMakerTransformJobLink.format_str.format(
aws_domain=SageMakerTransformJobLink.get_aws_domain(self.hook.conn_partition),
region_name=self.hook.conn_region_name,
job_name=urllib.parse.quote(transform_config["TransformJobName"], safe=""),
)
SageMakerTransformJobLink.persist(
context=context,
operator=self,
region_name=self.hook.conn_region_name,
aws_partition=self.hook.conn_partition,
job_name=urllib.parse.quote(transform_config["TransformJobName"], safe=""),
)
self.log.info("You can monitor this SageMaker Transform job at %s", transform_job_url)
if self.deferrable and self.wait_for_completion:
response = self.hook.describe_transform_job(transform_config["TransformJobName"])
status = response["TransformJobStatus"]
if status in self.hook.failed_states:
raise AirflowException(f"SageMaker job failed because {response['FailureReason']}")
if status == "Completed":
self.log.info("%s completed successfully.", self.task_id)
return {
"Model": serialize(self.hook.describe_model(transform_config["ModelName"])),
"Transform": serialize(response),
}
timeout = self.execution_timeout
if self.max_ingestion_time:
timeout = datetime.timedelta(seconds=self.max_ingestion_time)
self.defer(
timeout=timeout,
trigger=SageMakerTrigger(
job_name=transform_config["TransformJobName"],
job_type="Transform",
poke_interval=self.check_interval,
max_attempts=self.max_attempts,
aws_conn_id=self.aws_conn_id,
),
method_name="execute_complete",
)
return self.serialize_result(transform_config["TransformJobName"])
def _get_unique_model_name(
self, proposed_name: str, fail_if_exists: bool, describe_func: Callable[[str], Any]
) -> str:
return self._get_unique_name(
proposed_name, fail_if_exists, describe_func, self._check_if_model_exists, "model"
)
def _check_if_model_exists(self, model_name: str, describe_func: Callable[[str], Any]) -> bool:
"""Return True if model exists, False otherwise."""
return self._check_if_resource_exists(model_name, "model", describe_func)
def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> dict[str, dict]:
validated_event = validate_execute_complete_event(event)
self.log.info(validated_event["message"])
return self.serialize_result(validated_event["job_name"])
def serialize_result(self, job_name: str) -> dict[str, dict]:
job_description = self.hook.describe_transform_job(job_name)
self.serialized_model = serialize(self.hook.describe_model(job_description["ModelName"]))
self.serialized_transform = serialize(job_description)
return {"Model": self.serialized_model, "Transform": self.serialized_transform}
def get_openlineage_facets_on_complete(self, task_instance) -> OperatorLineage:
"""Return OpenLineage data gathered from SageMaker's API response saved by transform job."""
from airflow.providers.openlineage.extractors import OperatorLineage
model_package_arn = None
transform_input = None
transform_output = None
try:
model_package_arn = self.serialized_model["PrimaryContainer"]["ModelPackageName"]
except KeyError:
self.log.exception("Cannot find Model Package Name.")
try:
transform_input = self.serialized_transform["TransformInput"]["DataSource"]["S3DataSource"][
"S3Uri"
]
transform_output = self.serialized_transform["TransformOutput"]["S3OutputPath"]
except KeyError:
self.log.exception("Cannot find some required input/output details.")
inputs = []
if transform_input is not None:
inputs.append(self.path_to_s3_dataset(transform_input))
if model_package_arn is not None:
model_data_urls = self._get_model_data_urls(model_package_arn)
for model_data_url in model_data_urls:
inputs.append(self.path_to_s3_dataset(model_data_url))
outputs = []
if transform_output is not None:
outputs.append(self.path_to_s3_dataset(transform_output))
return OperatorLineage(inputs=inputs, outputs=outputs)
def _get_model_data_urls(self, model_package_arn) -> list:
model_data_urls = []
try:
model_containers = self.hook.get_conn().describe_model_package(
ModelPackageName=model_package_arn
)["InferenceSpecification"]["Containers"]
for container in model_containers:
model_data_urls.append(container["ModelDataUrl"])
except KeyError:
self.log.exception("Cannot retrieve model details.")
return model_data_urls
| SageMakerTransformOperator |
python | networkx__networkx | networkx/classes/tests/test_coreviews.py | {
"start": 9171,
"end": 10381
} | class ____(TestUnionAdjacency):
# node->nbr->key->data
def setup_method(self):
dd = {"color": "blue", "weight": 1.2}
self.kd = {7: {}, 8: {}, 9: {"color": 1}}
self.nd = {3: self.kd, 0: {9: dd}, 1: {8: {}}, 2: {9: {"color": 1}}}
self.s = {3: self.nd, 0: {3: {7: dd}}, 1: {}, 2: {3: {8: {}}}}
self.p = {3: {}, 0: {3: {9: dd}}, 1: {}, 2: {1: {8: {}}}}
self.adjview = nx.classes.coreviews.UnionMultiAdjacency(self.s, self.p)
def test_getitem(self):
assert self.adjview[1] is not self.s[1]
assert self.adjview[3][0][9] is self.adjview[0][3][9]
assert self.adjview[3][2][9]["color"] == 1
pytest.raises(KeyError, self.adjview.__getitem__, 4)
def test_copy(self):
avcopy = self.adjview.copy()
assert avcopy[0] == self.adjview[0]
assert avcopy[0] is not self.adjview[0]
avcopy[2][3][8]["ht"] = 4
assert avcopy[2] != self.adjview[2]
self.adjview[2][3][8]["ht"] = 4
assert avcopy[2] == self.adjview[2]
del self.adjview[2][3][8]["ht"]
assert not hasattr(self.adjview, "__setitem__")
assert hasattr(avcopy, "__setitem__")
| TestUnionMultiAdjacency |
python | mkdocstrings__mkdocstrings | src/mkdocstrings/_internal/debug.py | {
"start": 479,
"end": 2861
} | class ____:
"""Dataclass to store environment information."""
interpreter_name: str
"""Python interpreter name."""
interpreter_version: str
"""Python interpreter version."""
interpreter_path: str
"""Path to Python executable."""
platform: str
"""Operating System."""
packages: list[_Package]
"""Installed packages."""
variables: list[_Variable]
"""Environment variables."""
def _interpreter_name_version() -> tuple[str, str]:
if hasattr(sys, "implementation"):
impl = sys.implementation.version
version = f"{impl.major}.{impl.minor}.{impl.micro}"
kind = impl.releaselevel
if kind != "final":
version += kind[0] + str(impl.serial)
return sys.implementation.name, version
return "", "0.0.0"
def _get_version(dist: str = "mkdocstrings") -> str:
"""Get version of the given distribution.
Parameters:
dist: A distribution name.
Returns:
A version number.
"""
try:
return metadata.version(dist)
except metadata.PackageNotFoundError:
return "0.0.0"
def _get_debug_info() -> _Environment:
"""Get debug/environment information.
Returns:
Environment information.
"""
py_name, py_version = _interpreter_name_version()
packages = ["mkdocstrings"]
variables = ["PYTHONPATH", *[var for var in os.environ if var.startswith("MKDOCSTRINGS")]]
return _Environment(
interpreter_name=py_name,
interpreter_version=py_version,
interpreter_path=sys.executable,
platform=platform.platform(),
variables=[_Variable(var, val) for var in variables if (val := os.getenv(var))], # ty: ignore[invalid-argument-type]
packages=[_Package(pkg, _get_version(pkg)) for pkg in packages],
)
def _print_debug_info() -> None:
"""Print debug/environment information."""
info = _get_debug_info()
print(f"- __System__: {info.platform}")
print(f"- __Python__: {info.interpreter_name} {info.interpreter_version} ({info.interpreter_path})")
print("- __Environment variables__:")
for var in info.variables:
print(f" - `{var.name}`: `{var.value}`")
print("- __Installed packages__:")
for pkg in info.packages:
print(f" - `{pkg.name}` v{pkg.version}")
if __name__ == "__main__":
_print_debug_info()
| _Environment |
python | django__django | django/db/models/lookups.py | {
"start": 22995,
"end": 23206
} | class ____(FieldGetDbPrepValueIterableMixin, BuiltinLookup):
lookup_name = "range"
def get_rhs_op(self, connection, rhs):
return "BETWEEN %s AND %s" % (rhs[0], rhs[1])
@Field.register_lookup
| Range |
python | walkccc__LeetCode | solutions/902. Numbers At Most N Given Digit Set/902.py | {
"start": 0,
"end": 465
} | class ____:
def atMostNGivenDigitSet(self, digits: list[str], n: int) -> int:
ans = 0
num = str(n)
for i in range(1, len(num)):
ans += pow(len(digits), i)
for i, c in enumerate(num):
dHasSameNum = False
for digit in digits:
if digit[0] < c:
ans += pow(len(digits), len(num) - i - 1)
elif digit[0] == c:
dHasSameNum = True
if not dHasSameNum:
return ans
return ans + 1
| Solution |
python | huggingface__transformers | src/transformers/models/visual_bert/modeling_visual_bert.py | {
"start": 52118,
"end": 57500
} | class ____(VisualBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.visual_bert = VisualBertModel(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.cls = nn.Linear(config.hidden_size, config.num_labels) # 2
# Initialize weights and apply final processing
self.post_init()
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.LongTensor] = None,
token_type_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
visual_embeds: Optional[torch.FloatTensor] = None,
visual_attention_mask: Optional[torch.LongTensor] = None,
visual_token_type_ids: Optional[torch.LongTensor] = None,
image_text_alignment: Optional[torch.LongTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
labels: Optional[torch.LongTensor] = None,
) -> Union[tuple[torch.Tensor], SequenceClassifierOutput]:
r"""
visual_embeds (`torch.FloatTensor` of shape `(batch_size, visual_seq_length, visual_embedding_dim)`, *optional*):
The embedded representation of the visual inputs, generally derived using using an object detector.
visual_attention_mask (`torch.FloatTensor` of shape `(batch_size, visual_seq_length)`, *optional*):
Mask to avoid performing attention on visual embeddings. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
visual_token_type_ids (`torch.LongTensor` of shape `(batch_size, visual_seq_length)`, *optional*):
Segment token indices to indicate different portions of the visual embeds.
[What are token type IDs?](../glossary#token-type-ids) The authors of VisualBERT set the
*visual_token_type_ids* to *1* for all tokens.
image_text_alignment (`torch.LongTensor` of shape `(batch_size, visual_seq_length, alignment_number)`, *optional*):
Image-Text alignment uses to decide the position IDs of the visual embeddings.
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. A classification loss is computed (Cross-Entropy) against these labels.
Example:
```python
# Assumption: *get_visual_embeddings(image)* gets the visual embeddings of the image in the batch.
from transformers import AutoTokenizer, VisualBertForVisualReasoning
import torch
tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
model = VisualBertForVisualReasoning.from_pretrained("uclanlp/visualbert-nlvr2")
text = "Who is eating the apple?"
inputs = tokenizer(text, return_tensors="pt")
visual_embeds = get_visual_embeddings(image).unsqueeze(0)
visual_token_type_ids = torch.ones(visual_embeds.shape[:-1], dtype=torch.long)
visual_attention_mask = torch.ones(visual_embeds.shape[:-1], dtype=torch.float)
inputs.update(
{
"visual_embeds": visual_embeds,
"visual_token_type_ids": visual_token_type_ids,
"visual_attention_mask": visual_attention_mask,
}
)
labels = torch.tensor(1).unsqueeze(0) # Batch size 1, Num choices 2
outputs = model(**inputs, labels=labels)
loss = outputs.loss
scores = outputs.logits
```"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.visual_bert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
visual_embeds=visual_embeds,
visual_attention_mask=visual_attention_mask,
visual_token_type_ids=visual_token_type_ids,
image_text_alignment=image_text_alignment,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
# sequence_output = outputs[0]
pooled_output = outputs[1]
pooled_output = self.dropout(pooled_output)
logits = self.cls(pooled_output)
reshaped_logits = logits.contiguous()
loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
loss = loss_fct(reshaped_logits, labels.view(-1))
if not return_dict:
output = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return SequenceClassifierOutput(
loss=loss,
logits=reshaped_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
| VisualBertForVisualReasoning |
python | huggingface__transformers | src/transformers/models/ibert/modeling_ibert.py | {
"start": 18350,
"end": 20531
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.quant_mode = config.quant_mode
self.act_bit = 8
self.seq_len_dim = 1
self.attention = IBertAttention(config)
self.intermediate = IBertIntermediate(config)
self.output = IBertOutput(config)
self.pre_intermediate_act = QuantAct(self.act_bit, quant_mode=self.quant_mode)
self.pre_output_act = QuantAct(self.act_bit, quant_mode=self.quant_mode)
def forward(
self,
hidden_states,
hidden_states_scaling_factor,
attention_mask=None,
output_attentions=False,
):
self_attention_outputs, self_attention_outputs_scaling_factor = self.attention(
hidden_states,
hidden_states_scaling_factor,
attention_mask,
output_attentions=output_attentions,
)
attention_output = self_attention_outputs[0]
attention_output_scaling_factor = self_attention_outputs_scaling_factor[0]
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
layer_output, layer_output_scaling_factor = self.feed_forward_chunk(
attention_output, attention_output_scaling_factor
)
outputs = (layer_output,) + outputs
return outputs
def feed_forward_chunk(self, attention_output, attention_output_scaling_factor):
attention_output, attention_output_scaling_factor = self.pre_intermediate_act(
attention_output, attention_output_scaling_factor
)
intermediate_output, intermediate_output_scaling_factor = self.intermediate(
attention_output, attention_output_scaling_factor
)
intermediate_output, intermediate_output_scaling_factor = self.pre_output_act(
intermediate_output, intermediate_output_scaling_factor
)
layer_output, layer_output_scaling_factor = self.output(
intermediate_output, intermediate_output_scaling_factor, attention_output, attention_output_scaling_factor
)
return layer_output, layer_output_scaling_factor
| IBertLayer |
python | lepture__authlib | authlib/oauth1/rfc5849/base_server.py | {
"start": 484,
"end": 3972
} | class ____:
SIGNATURE_METHODS = {
SIGNATURE_HMAC_SHA1: verify_hmac_sha1,
SIGNATURE_RSA_SHA1: verify_rsa_sha1,
SIGNATURE_PLAINTEXT: verify_plaintext,
}
SUPPORTED_SIGNATURE_METHODS = [SIGNATURE_HMAC_SHA1]
EXPIRY_TIME = 300
@classmethod
def register_signature_method(cls, name, verify):
"""Extend signature method verification.
:param name: A string to represent signature method.
:param verify: A function to verify signature.
The ``verify`` method accept ``OAuth1Request`` as parameter::
def verify_custom_method(request):
# verify this request, return True or False
return True
Server.register_signature_method("custom-name", verify_custom_method)
"""
cls.SIGNATURE_METHODS[name] = verify
def validate_timestamp_and_nonce(self, request):
"""Validate ``oauth_timestamp`` and ``oauth_nonce`` in HTTP request.
:param request: OAuth1Request instance
"""
timestamp = request.oauth_params.get("oauth_timestamp")
nonce = request.oauth_params.get("oauth_nonce")
if request.signature_method == SIGNATURE_PLAINTEXT:
# The parameters MAY be omitted when using the "PLAINTEXT"
# signature method
if not timestamp and not nonce:
return
if not timestamp:
raise MissingRequiredParameterError("oauth_timestamp")
try:
# The timestamp value MUST be a positive integer
timestamp = int(timestamp)
if timestamp < 0:
raise InvalidRequestError('Invalid "oauth_timestamp" value')
if self.EXPIRY_TIME and time.time() - timestamp > self.EXPIRY_TIME:
raise InvalidRequestError('Invalid "oauth_timestamp" value')
except (ValueError, TypeError) as exc:
raise InvalidRequestError('Invalid "oauth_timestamp" value') from exc
if not nonce:
raise MissingRequiredParameterError("oauth_nonce")
if self.exists_nonce(nonce, request):
raise InvalidNonceError()
def validate_oauth_signature(self, request):
"""Validate ``oauth_signature`` from HTTP request.
:param request: OAuth1Request instance
"""
method = request.signature_method
if not method:
raise MissingRequiredParameterError("oauth_signature_method")
if method not in self.SUPPORTED_SIGNATURE_METHODS:
raise UnsupportedSignatureMethodError()
if not request.signature:
raise MissingRequiredParameterError("oauth_signature")
verify = self.SIGNATURE_METHODS.get(method)
if not verify:
raise UnsupportedSignatureMethodError()
if not verify(request):
raise InvalidSignatureError()
def get_client_by_id(self, client_id):
"""Get client instance with the given ``client_id``.
:param client_id: A string of client_id
:return: Client instance
"""
raise NotImplementedError()
def exists_nonce(self, nonce, request):
"""The nonce value MUST be unique across all requests with the same
timestamp, client credentials, and token combinations.
:param nonce: A string value of ``oauth_nonce``
:param request: OAuth1Request instance
:return: Boolean
"""
raise NotImplementedError()
| BaseServer |
python | h5py__h5py | h5py/tests/test_file.py | {
"start": 27388,
"end": 28146
} | class ____(TestCase):
"""
Check that h5py doesn't break on pathlib
"""
def test_pathlib_accepted_file(self):
""" Check that pathlib is accepted by h5py.File """
with closed_tempfile() as f:
path = pathlib.Path(f)
with File(path, 'w') as f2:
self.assertTrue(True)
def test_pathlib_name_match(self):
""" Check that using pathlib does not affect naming """
with closed_tempfile() as f:
path = pathlib.Path(f)
with File(path, 'w') as h5f1:
pathlib_name = h5f1.filename
with File(f, 'w') as h5f2:
normal_name = h5f2.filename
self.assertEqual(pathlib_name, normal_name)
| TestPathlibSupport |
python | numpy__numpy | benchmarks/benchmarks/bench_ufunc.py | {
"start": 14403,
"end": 14899
} | class ____(Benchmark):
params = (np._core.sctypes['int'] + np._core.sctypes['uint'],
[100, 10000, 1000000])
param_names = ['dtype', 'size']
def setup(self, dtype, size):
iinfo = np.iinfo(dtype)
self.x = np.random.randint(
iinfo.min, iinfo.max, size=size, dtype=dtype)
self.y = np.random.randint(2, 32, size=size, dtype=dtype)
def time_floor_divide_int(self, dtype, size):
self.x // self.y
| CustomArrayFloorDivideInt |
python | tensorflow__tensorflow | third_party/xla/xla/backends/cpu/testlib/elemental_kernel_emitter_test.py | {
"start": 4403,
"end": 6971
} | class ____(parameterized.TestCase):
def test_elemental_kernel_emitter(
self,
op_def: ElementalHloOpcodeDef,
shape: tuple[int, ...],
dtype: np.dtype,
):
[op, np_op, input_ranges, decimal_precision] = op_def
num_inputs = opcode_arity(op)
self.assertIsNotNone(num_inputs)
np_inputs = [
create_input(input_ranges, shape, dtype) for _ in range(num_inputs)
]
input_literals = [create_literal(input_array) for input_array in np_inputs]
expected_output = np_op(*np_inputs)
output_literal = create_literal(
np.ndarray(shape, dtype=expected_output.dtype)
)
hlo_parameters = [
HloInstruction.create_parameter(idx, literal.shape(), f"input_{idx}")
for [idx, literal] in enumerate(input_literals)
]
hlo_op = HloInstruction.create_variadic(
output_literal.shape(), op, hlo_parameters
)
hlo_module, buffer_assignment = utilities.build_hlo_module(
hlo_op, *hlo_parameters
)
jit_compiler = testlib_cpu.JitCompiler(hlo_module.get_config())
emitter = testlib_cpu.ElementalKernelEmitter(
hlo_module.get_root_instruction(),
buffer_assignment,
jit_compiler.get_target_machine(),
)
kernel_definition = emitter.emit_kernel_definition()
self.assertIsNotNone(kernel_definition)
# kernel_definition is consumed by the runner, so we need to save the IR
# string before passing it to the runner.
ir_string = str(kernel_definition.source())
runner = testlib_cpu.KernelRunner.create(kernel_definition, jit_compiler)
runner.call(list(itertools.chain(input_literals, [output_literal])))
np.testing.assert_array_almost_equal(
np.asarray(output_literal),
expected_output,
decimal=decimal_precision,
err_msg=ir_string,
)
@parameterized.product(
op_def=[
(ComparisonDirection.kEq, np.equal),
(ComparisonDirection.kNe, np.not_equal),
(ComparisonDirection.kGe, np.greater_equal),
(ComparisonDirection.kGt, np.greater),
(ComparisonDirection.kLe, np.less_equal),
(ComparisonDirection.kLt, np.less),
],
shape=[(4,), (4, 3), (4, 3, 10)],
dtype=[
np.dtype(np.uint8),
np.dtype(np.uint16),
np.dtype(np.uint32),
np.dtype(np.uint64),
np.dtype(np.int8),
np.dtype(np.int16),
np.dtype(np.int32),
np.dtype(np.int64),
np.dtype(np.float16),
np.dtype(np.float32),
np.dtype(np.float64),
],
)
| ElementalKernelRunnerTest |
python | spyder-ide__spyder | spyder/plugins/completion/providers/languageserver/providers/__init__.py | {
"start": 369,
"end": 506
} | class ____(DocumentProvider, WindowProvider,
WorkspaceProvider, ClientProvider):
pass
| LSPMethodProviderMixIn |
python | getsentry__sentry | tests/sentry/api/serializers/test_group.py | {
"start": 1279,
"end": 18530
} | class ____(TestCase, PerformanceIssueTestCase):
def test_project(self) -> None:
user = self.create_user()
group = self.create_group()
result = serialize(group, user)
assert result["project"]
assert "id" in result["project"]
assert "name" in result["project"]
assert "slug" in result["project"]
assert "platform" in result["project"]
def test_is_ignored_with_expired_snooze(self) -> None:
now = timezone.now()
user = self.create_user()
group = self.create_group(status=GroupStatus.IGNORED)
GroupSnooze.objects.create(group=group, until=now - timedelta(minutes=1))
result = serialize(group, user)
assert result["status"] == "unresolved"
assert result["statusDetails"] == {}
def test_is_ignored_with_valid_snooze(self) -> None:
now = timezone.now()
user = self.create_user()
group = self.create_group(status=GroupStatus.IGNORED)
snooze = GroupSnooze.objects.create(group=group, until=now + timedelta(minutes=1))
result = serialize(group, user)
assert result["status"] == "ignored"
assert result["statusDetails"]["ignoreCount"] == snooze.count
assert result["statusDetails"]["ignoreWindow"] == snooze.window
assert result["statusDetails"]["ignoreUserCount"] == snooze.user_count
assert result["statusDetails"]["ignoreUserWindow"] == snooze.user_window
assert result["statusDetails"]["ignoreUntil"] == snooze.until
assert result["statusDetails"]["actor"] is None
def test_is_ignored_with_valid_snooze_and_actor(self) -> None:
now = timezone.now()
user = self.create_user()
group = self.create_group(status=GroupStatus.IGNORED)
GroupSnooze.objects.create(group=group, until=now + timedelta(minutes=1), actor_id=user.id)
result = serialize(group, user)
assert result["status"] == "ignored"
assert result["statusDetails"]["actor"]["id"] == str(user.id)
def test_manually_unresolved_after_auto_resolve(self) -> None:
now = timezone.now()
self.project.update_option("sentry:resolve_age", 168) # 7 days
user = self.create_user()
group = self.create_group(
status=GroupStatus.UNRESOLVED,
last_seen=now - timedelta(days=10), # Last seen 10 days ago (past auto-resolve age)
)
group.resolved_at = now - timedelta(days=1)
group.save()
result = serialize(group, user)
assert result["status"] == "unresolved"
assert result["statusDetails"] == {}
def test_auto_resolve_not_yet_resolved(self) -> None:
now = timezone.now()
self.project.update_option("sentry:resolve_age", 168) # 7 days
user = self.create_user()
group = self.create_group(
status=GroupStatus.UNRESOLVED,
last_seen=now - timedelta(days=10), # Last seen 10 days ago (past auto-resolve age)
)
assert group.resolved_at is None
result = serialize(group, user)
assert result["status"] == "resolved"
assert result["statusDetails"]["autoResolved"] is True
def test_resolved_in_next_release(self) -> None:
release = self.create_release(project=self.project, version="a")
user = self.create_user()
group = self.create_group(status=GroupStatus.RESOLVED)
GroupResolution.objects.create(
group=group, release=release, type=GroupResolution.Type.in_next_release
)
result = serialize(group, user)
assert result["status"] == "resolved"
assert result["statusDetails"] == {"inNextRelease": True, "actor": None}
def test_resolved_in_release(self) -> None:
release = self.create_release(project=self.project, version="a")
user = self.create_user()
group = self.create_group(status=GroupStatus.RESOLVED)
GroupResolution.objects.create(
group=group, release=release, type=GroupResolution.Type.in_release
)
result = serialize(group, user)
assert result["status"] == "resolved"
assert result["statusDetails"] == {"inRelease": "a", "actor": None}
def test_resolved_with_actor(self) -> None:
release = self.create_release(project=self.project, version="a")
user = self.create_user()
group = self.create_group(status=GroupStatus.RESOLVED)
GroupResolution.objects.create(
group=group, release=release, type=GroupResolution.Type.in_release, actor_id=user.id
)
result = serialize(group, user)
assert result["status"] == "resolved"
assert result["statusDetails"]["actor"]["id"] == str(user.id)
def test_resolved_in_commit(self) -> None:
repo = self.create_repo(project=self.project)
commit = self.create_commit(repo=repo)
user = self.create_user()
group = self.create_group(status=GroupStatus.RESOLVED)
GroupLink.objects.create(
group_id=group.id,
project_id=group.project_id,
linked_id=commit.id,
linked_type=GroupLink.LinkedType.commit,
relationship=GroupLink.Relationship.resolves,
)
result = serialize(group, user)
assert result["status"] == "resolved"
assert result["statusDetails"]["inCommit"]["id"] == commit.key
@patch("sentry.models.Group.is_over_resolve_age")
def test_auto_resolved(self, mock_is_over_resolve_age: MagicMock) -> None:
mock_is_over_resolve_age.return_value = True
user = self.create_user()
group = self.create_group(status=GroupStatus.UNRESOLVED)
result = serialize(group, user)
assert result["status"] == "resolved"
assert result["statusDetails"] == {"autoResolved": True}
@patch("sentry.models.Group.is_over_resolve_age")
def test_auto_resolved_respects_enable_auto_resolve_flag(
self, mock_is_over_resolve_age: MagicMock
) -> None:
mock_is_over_resolve_age.return_value = True
user = self.create_user()
# Test with a group type that has auto-resolve enabled
error_type_id = ErrorGroupType.type_id
group_error = self.create_group(status=GroupStatus.UNRESOLVED, type=error_type_id)
result_error = serialize(group_error, user)
assert result_error["status"] == "resolved"
assert result_error["statusDetails"] == {"autoResolved": True}
# Test with a group type that has auto-resolve disabled (feedback)
feedback_type_id = FeedbackGroup.type_id
group_feedback = self.create_group(status=GroupStatus.UNRESOLVED, type=feedback_type_id)
result_feedback = serialize(group_feedback, user)
assert result_feedback["status"] == "unresolved"
assert "autoResolved" not in result_feedback.get("statusDetails", {})
def test_subscribed(self) -> None:
user = self.create_user()
group = self.create_group()
GroupSubscription.objects.create(
user_id=user.id, group=group, project=group.project, is_active=True
)
result = serialize(group, user)
assert result["isSubscribed"]
assert result["subscriptionDetails"] == {"reason": "unknown"}
def test_explicit_unsubscribed(self) -> None:
user = self.create_user()
group = self.create_group()
GroupSubscription.objects.create(
user_id=user.id, group=group, project=group.project, is_active=False
)
result = serialize(group, user)
assert not result["isSubscribed"]
assert not result["subscriptionDetails"]
def test_implicit_subscribed(self) -> None:
user = self.create_user()
group = self.create_group()
combinations = (
# (default, project, subscribed, has_details)
(
NotificationSettingsOptionEnum.ALWAYS,
None,
True,
False,
),
(
NotificationSettingsOptionEnum.ALWAYS,
NotificationSettingsOptionEnum.ALWAYS,
True,
False,
),
(
NotificationSettingsOptionEnum.ALWAYS,
NotificationSettingsOptionEnum.SUBSCRIBE_ONLY,
False,
False,
),
(
NotificationSettingsOptionEnum.ALWAYS,
NotificationSettingsOptionEnum.NEVER,
False,
True,
),
(
None,
None,
False,
False,
),
(
NotificationSettingsOptionEnum.SUBSCRIBE_ONLY,
None,
False,
False,
),
(
NotificationSettingsOptionEnum.SUBSCRIBE_ONLY,
NotificationSettingsOptionEnum.ALWAYS,
True,
False,
),
(
NotificationSettingsOptionEnum.SUBSCRIBE_ONLY,
NotificationSettingsOptionEnum.SUBSCRIBE_ONLY,
False,
False,
),
(
NotificationSettingsOptionEnum.SUBSCRIBE_ONLY,
NotificationSettingsOptionEnum.NEVER,
False,
True,
),
(
NotificationSettingsOptionEnum.NEVER,
None,
False,
True,
),
(
NotificationSettingsOptionEnum.NEVER,
NotificationSettingsOptionEnum.ALWAYS,
True,
False,
),
(
NotificationSettingsOptionEnum.NEVER,
NotificationSettingsOptionEnum.SUBSCRIBE_ONLY,
False,
False,
),
(
NotificationSettingsOptionEnum.NEVER,
NotificationSettingsOptionEnum.NEVER,
False,
True,
),
)
for default_value, project_value, is_subscribed, has_details in combinations:
UserOption.objects.clear_local_cache()
with assume_test_silo_mode(SiloMode.CONTROL):
for provider in [
ExternalProviderEnum.EMAIL.value,
ExternalProviderEnum.SLACK.value,
]:
if default_value is None:
NotificationSettingOption.objects.filter(
scope_type=NotificationScopeEnum.USER.value,
scope_identifier=user.id,
user_id=user.id,
type=NotificationSettingEnum.WORKFLOW.value,
).delete()
NotificationSettingProvider.objects.filter(
type=NotificationSettingEnum.WORKFLOW.value,
user_id=user.id,
scope_type=NotificationScopeEnum.USER.value,
scope_identifier=user.id,
provider=provider,
).delete()
else:
NotificationSettingOption.objects.update_or_create(
scope_type=NotificationScopeEnum.USER.value,
scope_identifier=user.id,
user_id=user.id,
type=NotificationSettingEnum.WORKFLOW.value,
defaults={"value": default_value.value},
)
NotificationSettingProvider.objects.update_or_create(
provider=provider,
type=NotificationSettingEnum.WORKFLOW.value,
user_id=user.id,
scope_type=NotificationScopeEnum.USER.value,
scope_identifier=user.id,
defaults={"value": NotificationSettingsOptionEnum.ALWAYS.value},
)
if project_value is None:
NotificationSettingOption.objects.filter(
scope_type=NotificationScopeEnum.PROJECT.value,
scope_identifier=group.project.id,
type=NotificationSettingEnum.WORKFLOW.value,
user_id=user.id,
).delete()
NotificationSettingProvider.objects.filter(
scope_type=NotificationScopeEnum.PROJECT.value,
scope_identifier=group.project.id,
type=NotificationSettingEnum.WORKFLOW.value,
user_id=user.id,
provider=provider,
).delete()
else:
NotificationSettingOption.objects.update_or_create(
scope_type=NotificationScopeEnum.PROJECT.value,
scope_identifier=group.project.id,
user_id=user.id,
type=NotificationSettingEnum.WORKFLOW.value,
defaults={"value": project_value.value},
)
NotificationSettingProvider.objects.update_or_create(
provider=provider,
type=NotificationSettingEnum.WORKFLOW.value,
user_id=user.id,
scope_type=NotificationScopeEnum.PROJECT.value,
scope_identifier=group.project.id,
defaults={"value": NotificationSettingsOptionEnum.ALWAYS.value},
)
result = serialize(group, user)
subscription_details = result.get("subscriptionDetails")
assert result["isSubscribed"] is is_subscribed
assert (
subscription_details == {"disabled": True}
if has_details
else subscription_details is None
)
def test_global_no_conversations_overrides_group_subscription(self) -> None:
user = self.create_user()
group = self.create_group()
GroupSubscription.objects.create(
user_id=user.id, group=group, project=group.project, is_active=True
)
with assume_test_silo_mode(SiloMode.CONTROL):
NotificationSettingOption.objects.create_or_update(
scope_type=NotificationScopeEnum.USER.value,
scope_identifier=user.id,
type=NotificationSettingEnum.WORKFLOW.value,
value=NotificationSettingsOptionEnum.NEVER.value,
user_id=user.id,
)
result = serialize(group, user)
assert not result["isSubscribed"]
assert result["subscriptionDetails"] == {"disabled": True}
def test_project_no_conversations_overrides_group_subscription(self) -> None:
user = self.create_user()
group = self.create_group()
GroupSubscription.objects.create(
user_id=user.id, group=group, project=group.project, is_active=True
)
with assume_test_silo_mode(SiloMode.CONTROL):
NotificationSettingOption.objects.create_or_update(
scope_type=NotificationScopeEnum.PROJECT.value,
scope_identifier=group.project.id,
type=NotificationSettingEnum.WORKFLOW.value,
value=NotificationSettingsOptionEnum.NEVER.value,
user_id=user.id,
)
result = serialize(group, user)
assert not result["isSubscribed"]
assert result["subscriptionDetails"] == {"disabled": True}
def test_no_user_unsubscribed(self) -> None:
group = self.create_group()
result = serialize(group)
assert not result["isSubscribed"]
def test_reprocessing(self) -> None:
from sentry.reprocessing2 import start_group_reprocessing
group = self.create_group()
start_group_reprocessing(
project_id=group.project_id, group_id=group.id, remaining_events="delete"
)
result = serialize(Group.objects.get(id=group.id))
assert result["status"] == "reprocessing"
assert result["statusDetails"] == {
"pendingEvents": 0,
"info": {
"syncCount": 0,
"totalEvents": 0,
"dateCreated": result["statusDetails"]["info"]["dateCreated"],
},
}
def test_perf_issue(self) -> None:
event = self.create_performance_issue()
perf_group = event.group
serialized = serialize(perf_group)
assert serialized["count"] == "1"
assert serialized["issueCategory"] == "db_query"
assert serialized["issueType"] == "performance_n_plus_one_db_queries"
| GroupSerializerTest |
python | pytorch__pytorch | torch/ao/nn/intrinsic/qat/modules/conv_fused.py | {
"start": 28203,
"end": 30432
} | class ____(nnqat.Conv3d, nni._FusedModule):
r"""A ConvReLU3d module is a fused module of Conv3d and ReLU, attached with
FakeQuantize modules for weight for
quantization aware training.
We combined the interface of :class:`~torch.nn.Conv3d` and
:class:`~torch.nn.BatchNorm3d`.
Attributes:
weight_fake_quant: fake quant module for weight
"""
_FLOAT_MODULE: ClassVar[type[nni.ConvReLU3d]] = nni.ConvReLU3d # type: ignore[assignment]
_FLOAT_CONV_MODULE: ClassVar[type[nn.Conv3d]] = nn.Conv3d
_FLOAT_BN_MODULE: ClassVar[type[nn.Module] | None] = None
_FLOAT_RELU_MODULE: ClassVar[type[nn.Module] | None] = nn.ReLU
def __init__(
self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
dilation=1,
groups=1,
bias=True,
padding_mode="zeros",
qconfig=None,
):
super().__init__(
in_channels,
out_channels,
kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
groups=groups,
bias=bias,
# pyrefly: ignore [bad-argument-type]
padding_mode=padding_mode,
qconfig=qconfig,
)
assert qconfig, "qconfig must be provided for QAT module"
self.qconfig = qconfig
self.weight_fake_quant = self.qconfig.weight()
def forward(self, input):
return F.relu(
self._conv_forward(input, self.weight_fake_quant(self.weight), self.bias)
)
@classmethod
def from_float(cls, mod, use_precomputed_fake_quant=False): # type: ignore[override]
return super().from_float(
mod, use_precomputed_fake_quant=use_precomputed_fake_quant
)
def update_bn_stats(mod):
if type(mod) in {
ConvBnReLU1d,
ConvBnReLU2d,
ConvBnReLU3d,
ConvBn1d,
ConvBn2d,
ConvBn3d,
}:
mod.update_bn_stats()
def freeze_bn_stats(mod):
if type(mod) in {
ConvBnReLU1d,
ConvBnReLU2d,
ConvBnReLU3d,
ConvBn1d,
ConvBn2d,
ConvBn3d,
}:
mod.freeze_bn_stats()
| ConvReLU3d |
python | sympy__sympy | sympy/assumptions/relation/equality.py | {
"start": 3988,
"end": 5042
} | class ____(BinaryRelation):
"""
Binary predicate for $>=$.
The purpose of this class is to provide the instance which represent
the ">=" predicate in order to allow the logical inference.
This class must remain internal to assumptions module and user must
use :obj:`~.Ge()` instead to construct the equality expression.
Evaluating this predicate to ``True`` or ``False`` is done by
:func:`~.core.relational.is_ge`
Examples
========
>>> from sympy import ask, Q
>>> Q.ge(0, 0)
Q.ge(0, 0)
>>> ask(_)
True
See Also
========
sympy.core.relational.Ge
"""
is_reflexive = True
is_symmetric = False
name = 'ge'
handler = None
@property
def reversed(self):
return Q.le
@property
def negated(self):
return Q.lt
def eval(self, args, assumptions=True):
if assumptions == True:
# default assumptions for is_ge is None
assumptions = None
return is_ge(*args, assumptions)
| GreaterThanPredicate |
python | pytorch__pytorch | .github/scripts/github_utils.py | {
"start": 346,
"end": 7279
} | class ____:
body_text: str
created_at: str
author_login: str
author_url: Optional[str]
author_association: str
editor_login: Optional[str]
database_id: int
url: str
def gh_fetch_url_and_headers(
url: str,
*,
headers: Optional[dict[str, str]] = None,
data: Union[Optional[dict[str, Any]], str] = None,
method: Optional[str] = None,
reader: Callable[[Any], Any] = lambda x: x.read(),
) -> tuple[Any, Any]:
if headers is None:
headers = {}
token = os.environ.get("GITHUB_TOKEN")
if token is not None and url.startswith(f"{GITHUB_API_URL}/"):
headers["Authorization"] = f"token {token}"
data_ = None
if data is not None:
data_ = data.encode() if isinstance(data, str) else json.dumps(data).encode()
try:
with urlopen(Request(url, headers=headers, data=data_, method=method)) as conn:
return conn.headers, reader(conn)
except HTTPError as err:
if (
err.code == 403
and all(
key in err.headers
for key in ["X-RateLimit-Limit", "X-RateLimit-Remaining"]
)
and int(err.headers["X-RateLimit-Remaining"]) == 0
):
print(
f"""{url}
Rate limit exceeded:
Used: {err.headers["X-RateLimit-Used"]}
Limit: {err.headers["X-RateLimit-Limit"]}
Remaining: {err.headers["X-RateLimit-Remaining"]}
Resets at: {err.headers["x-RateLimit-Reset"]}"""
)
else:
print(f"Error fetching {url} {err}")
raise
def gh_fetch_url(
url: str,
*,
headers: Optional[dict[str, str]] = None,
data: Union[Optional[dict[str, Any]], str] = None,
method: Optional[str] = None,
reader: Callable[[Any], Any] = json.load,
) -> Any:
return gh_fetch_url_and_headers(
url, headers=headers, data=data, reader=reader, method=method
)[1]
def gh_fetch_json(
url: str,
params: Optional[dict[str, Any]] = None,
data: Optional[dict[str, Any]] = None,
method: Optional[str] = None,
) -> list[dict[str, Any]]:
headers = {"Accept": "application/vnd.github.v3+json"}
if params is not None and len(params) > 0:
url += "?" + "&".join(
f"{name}={quote(str(val))}" for name, val in params.items()
)
return cast(
list[dict[str, Any]],
gh_fetch_url(url, headers=headers, data=data, reader=json.load, method=method),
)
def _gh_fetch_json_any(
url: str,
params: Optional[dict[str, Any]] = None,
data: Optional[dict[str, Any]] = None,
) -> Any:
headers = {"Accept": "application/vnd.github.v3+json"}
if params is not None and len(params) > 0:
url += "?" + "&".join(
f"{name}={quote(str(val))}" for name, val in params.items()
)
return gh_fetch_url(url, headers=headers, data=data, reader=json.load)
def gh_fetch_json_list(
url: str,
params: Optional[dict[str, Any]] = None,
data: Optional[dict[str, Any]] = None,
) -> list[dict[str, Any]]:
return cast(list[dict[str, Any]], _gh_fetch_json_any(url, params, data))
def gh_fetch_json_dict(
url: str,
params: Optional[dict[str, Any]] = None,
data: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
return cast(dict[str, Any], _gh_fetch_json_any(url, params, data))
def gh_graphql(query: str, **kwargs: Any) -> dict[str, Any]:
rc = gh_fetch_url(
"https://api.github.com/graphql", # @lint-ignore
data={"query": query, "variables": kwargs},
reader=json.load,
)
if "errors" in rc:
raise RuntimeError(
f"GraphQL query {query}, args {kwargs} failed: {rc['errors']}"
)
return cast(dict[str, Any], rc)
def _gh_post_comment(
url: str, comment: str, dry_run: bool = False
) -> list[dict[str, Any]]:
if dry_run:
print(comment)
return []
return gh_fetch_json_list(url, data={"body": comment})
def gh_post_pr_comment(
org: str, repo: str, pr_num: int, comment: str, dry_run: bool = False
) -> list[dict[str, Any]]:
return _gh_post_comment(
f"{GITHUB_API_URL}/repos/{org}/{repo}/issues/{pr_num}/comments",
comment,
dry_run,
)
def gh_post_commit_comment(
org: str, repo: str, sha: str, comment: str, dry_run: bool = False
) -> list[dict[str, Any]]:
return _gh_post_comment(
f"{GITHUB_API_URL}/repos/{org}/{repo}/commits/{sha}/comments",
comment,
dry_run,
)
def gh_close_pr(org: str, repo: str, pr_num: int, dry_run: bool = False) -> None:
url = f"{GITHUB_API_URL}/repos/{org}/{repo}/pulls/{pr_num}"
if dry_run:
print(f"Dry run closing PR {pr_num}")
else:
gh_fetch_url(url, method="PATCH", data={"state": "closed"})
def gh_delete_comment(org: str, repo: str, comment_id: int) -> None:
url = f"{GITHUB_API_URL}/repos/{org}/{repo}/issues/comments/{comment_id}"
gh_fetch_url(url, method="DELETE", reader=lambda x: x.read())
def gh_fetch_merge_base(org: str, repo: str, base: str, head: str) -> str:
merge_base = ""
# Get the merge base using the GitHub REST API. This is the same as using
# git merge-base without the need to have git. The API doc can be found at
# https://docs.github.com/en/rest/commits/commits?apiVersion=2022-11-28#compare-two-commits
try:
json_data = gh_fetch_url(
f"{GITHUB_API_URL}/repos/{org}/{repo}/compare/{base}...{head}",
headers={"Accept": "application/vnd.github.v3+json"},
reader=json.load,
)
if json_data:
merge_base = json_data.get("merge_base_commit", {}).get("sha", "")
else:
warnings.warn(
f"Failed to get merge base for {base}...{head}: Empty response"
)
except Exception as error:
warnings.warn(f"Failed to get merge base for {base}...{head}: {error}")
return merge_base
def gh_update_pr_state(org: str, repo: str, pr_num: int, state: str = "open") -> None:
url = f"{GITHUB_API_URL}/repos/{org}/{repo}/pulls/{pr_num}"
try:
gh_fetch_url(url, method="PATCH", data={"state": state})
except HTTPError as err:
# When trying to open the pull request, error 422 means that the branch
# has been deleted and the API couldn't re-open it
if err.code == 422 and state == "open":
warnings.warn(
f"Failed to open {pr_num} because its head branch has been deleted: {err}"
)
else:
raise
def gh_query_issues_by_labels(
org: str, repo: str, labels: list[str], state: str = "open"
) -> list[dict[str, Any]]:
url = f"{GITHUB_API_URL}/repos/{org}/{repo}/issues"
return gh_fetch_json(
url, method="GET", params={"labels": ",".join(labels), "state": state}
)
| GitHubComment |
python | getsentry__sentry | src/sentry/issues/endpoints/team_all_unresolved_issues.py | {
"start": 6012,
"end": 7405
} | class ____(TeamEndpoint):
owner = ApiOwner.ISSUES
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
def get(self, request: Request, team: Team) -> Response:
"""
Returns cumulative counts of unresolved groups per day within the stats period time range.
Response:
{
<project_id>: {
<isoformat_date>: {"unresolved": <unresolved_count>},
...
}
...
}
"""
if not features.has("organizations:team-insights", team.organization, actor=request.user):
return Response({"detail": "You do not have the insights feature enabled"}, status=400)
# Team has no projects
project_list = Project.objects.get_for_team_ids(team_ids=[team.id])
if len(project_list) == 0:
return Response({})
start, end = get_date_range_from_params(request.GET)
end = end.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)
start = start.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)
environments = [e.id for e in get_environments(request, team.organization)]
environment_id = environments[0] if environments else None
return Response(calculate_unresolved_counts(team, project_list, start, end, environment_id))
| TeamAllUnresolvedIssuesEndpoint |
python | openai__openai-python | src/openai/types/responses/response_custom_tool_call_input_done_event.py | {
"start": 213,
"end": 681
} | class ____(BaseModel):
input: str
"""The complete input data for the custom tool call."""
item_id: str
"""Unique identifier for the API item associated with this event."""
output_index: int
"""The index of the output this event applies to."""
sequence_number: int
"""The sequence number of this event."""
type: Literal["response.custom_tool_call_input.done"]
"""The event type identifier."""
| ResponseCustomToolCallInputDoneEvent |
python | pandas-dev__pandas | pandas/tests/series/methods/test_sort_values.py | {
"start": 132,
"end": 7984
} | class ____:
def test_sort_values(self, datetime_series):
# check indexes are reordered corresponding with the values
ser = Series([3, 2, 4, 1], ["A", "B", "C", "D"])
expected = Series([1, 2, 3, 4], ["D", "B", "A", "C"])
result = ser.sort_values()
tm.assert_series_equal(expected, result)
ts = datetime_series.copy()
ts[:5] = np.nan
vals = ts.values
result = ts.sort_values()
assert np.isnan(result[-5:]).all()
tm.assert_numpy_array_equal(result[:-5].values, np.sort(vals[5:]))
# na_position
result = ts.sort_values(na_position="first")
assert np.isnan(result[:5]).all()
tm.assert_numpy_array_equal(result[5:].values, np.sort(vals[5:]))
# something object-type
ser = Series(["A", "B"], [1, 2])
# no failure
ser.sort_values()
# ascending=False
ordered = ts.sort_values(ascending=False)
expected = np.sort(ts.dropna().values)[::-1]
tm.assert_almost_equal(expected, ordered.dropna().values)
ordered = ts.sort_values(ascending=False, na_position="first")
tm.assert_almost_equal(expected, ordered.dropna().values)
# ascending=[False] should behave the same as ascending=False
ordered = ts.sort_values(ascending=[False])
expected = ts.sort_values(ascending=False)
tm.assert_series_equal(expected, ordered)
ordered = ts.sort_values(ascending=[False], na_position="first")
expected = ts.sort_values(ascending=False, na_position="first")
tm.assert_series_equal(expected, ordered)
msg = 'For argument "ascending" expected type bool, received type NoneType.'
with pytest.raises(ValueError, match=msg):
ts.sort_values(ascending=None)
msg = r"Length of ascending \(0\) must be 1 for Series"
with pytest.raises(ValueError, match=msg):
ts.sort_values(ascending=[])
msg = r"Length of ascending \(3\) must be 1 for Series"
with pytest.raises(ValueError, match=msg):
ts.sort_values(ascending=[1, 2, 3])
msg = r"Length of ascending \(2\) must be 1 for Series"
with pytest.raises(ValueError, match=msg):
ts.sort_values(ascending=[False, False])
msg = 'For argument "ascending" expected type bool, received type str.'
with pytest.raises(ValueError, match=msg):
ts.sort_values(ascending="foobar")
# inplace=True
ts = datetime_series.copy()
return_value = ts.sort_values(ascending=False, inplace=True)
assert return_value is None
tm.assert_series_equal(ts, datetime_series.sort_values(ascending=False))
tm.assert_index_equal(
ts.index, datetime_series.sort_values(ascending=False).index
)
# GH#5856/5853
# Series.sort_values operating on a view
df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)))
s = df.iloc[:, 0]
s.sort_values(inplace=True)
tm.assert_series_equal(s, df.iloc[:, 0].sort_values())
def test_sort_values_categorical(self):
cat = Series(Categorical(["a", "b", "b", "a"], ordered=False))
# sort in the categories order
expected = Series(
Categorical(["a", "a", "b", "b"], ordered=False), index=[0, 3, 1, 2]
)
result = cat.sort_values()
tm.assert_series_equal(result, expected)
cat = Series(Categorical(["a", "c", "b", "d"], ordered=True))
res = cat.sort_values()
exp = np.array(["a", "b", "c", "d"], dtype=np.object_)
tm.assert_numpy_array_equal(res.__array__(), exp)
cat = Series(
Categorical(
["a", "c", "b", "d"], categories=["a", "b", "c", "d"], ordered=True
)
)
res = cat.sort_values()
exp = np.array(["a", "b", "c", "d"], dtype=np.object_)
tm.assert_numpy_array_equal(res.__array__(), exp)
res = cat.sort_values(ascending=False)
exp = np.array(["d", "c", "b", "a"], dtype=np.object_)
tm.assert_numpy_array_equal(res.__array__(), exp)
raw_cat1 = Categorical(
["a", "b", "c", "d"], categories=["a", "b", "c", "d"], ordered=False
)
raw_cat2 = Categorical(
["a", "b", "c", "d"], categories=["d", "c", "b", "a"], ordered=True
)
s = ["a", "b", "c", "d"]
df = DataFrame(
{"unsort": raw_cat1, "sort": raw_cat2, "string": s, "values": [1, 2, 3, 4]}
)
# Cats must be sorted in a dataframe
res = df.sort_values(by=["string"], ascending=False)
exp = np.array(["d", "c", "b", "a"], dtype=np.object_)
tm.assert_numpy_array_equal(res["sort"].values.__array__(), exp)
assert res["sort"].dtype == "category"
res = df.sort_values(by=["sort"], ascending=False)
exp = df.sort_values(by=["string"], ascending=True)
tm.assert_series_equal(res["values"], exp["values"])
assert res["sort"].dtype == "category"
assert res["unsort"].dtype == "category"
# unordered cat, but we allow this
df.sort_values(by=["unsort"], ascending=False)
# multi-columns sort
# GH#7848
df = DataFrame(
{"id": [6, 5, 4, 3, 2, 1], "raw_grade": ["a", "b", "b", "a", "a", "e"]}
)
df["grade"] = Categorical(df["raw_grade"], ordered=True)
df["grade"] = df["grade"].cat.set_categories(["b", "e", "a"])
# sorts 'grade' according to the order of the categories
result = df.sort_values(by=["grade"])
expected = df.iloc[[1, 2, 5, 0, 3, 4]]
tm.assert_frame_equal(result, expected)
# multi
result = df.sort_values(by=["grade", "id"])
expected = df.iloc[[2, 1, 5, 4, 3, 0]]
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("inplace", [True, False])
@pytest.mark.parametrize(
"original_list, sorted_list, ignore_index, output_index",
[
([2, 3, 6, 1], [6, 3, 2, 1], True, [0, 1, 2, 3]),
([2, 3, 6, 1], [6, 3, 2, 1], False, [2, 1, 0, 3]),
],
)
def test_sort_values_ignore_index(
self, inplace, original_list, sorted_list, ignore_index, output_index
):
# GH 30114
ser = Series(original_list)
expected = Series(sorted_list, index=output_index)
kwargs = {"ignore_index": ignore_index, "inplace": inplace}
if inplace:
result_ser = ser.copy()
result_ser.sort_values(ascending=False, **kwargs)
else:
result_ser = ser.sort_values(ascending=False, **kwargs)
tm.assert_series_equal(result_ser, expected)
tm.assert_series_equal(ser, Series(original_list))
def test_mergesort_descending_stability(self):
# GH 28697
s = Series([1, 2, 1, 3], ["first", "b", "second", "c"])
result = s.sort_values(ascending=False, kind="mergesort")
expected = Series([3, 2, 1, 1], ["c", "b", "first", "second"])
tm.assert_series_equal(result, expected)
def test_sort_values_validate_ascending_for_value_error(self):
# GH41634
ser = Series([23, 7, 21])
msg = 'For argument "ascending" expected type bool, received type str.'
with pytest.raises(ValueError, match=msg):
ser.sort_values(ascending="False")
def test_sort_values_validate_ascending_functional(self, ascending):
# GH41634
ser = Series([23, 7, 21])
expected = np.sort(ser.values)
sorted_ser = ser.sort_values(ascending=ascending)
if not ascending:
expected = expected[::-1]
result = sorted_ser.values
tm.assert_numpy_array_equal(result, expected)
| TestSeriesSortValues |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/aiomysql.py | {
"start": 5614,
"end": 7160
} | class ____(MySQLDialect_pymysql):
driver = "aiomysql"
supports_statement_cache = True
supports_server_side_cursors = True
_sscursor = AsyncAdapt_aiomysql_ss_cursor
is_async = True
has_terminate = True
@classmethod
def import_dbapi(cls) -> AsyncAdapt_aiomysql_dbapi:
return AsyncAdapt_aiomysql_dbapi(
__import__("aiomysql"), __import__("pymysql")
)
def do_terminate(self, dbapi_connection: DBAPIConnection) -> None:
dbapi_connection.terminate()
def create_connect_args(
self, url: URL, _translate_args: Optional[dict[str, Any]] = None
) -> ConnectArgsType:
return super().create_connect_args(
url, _translate_args=dict(username="user", database="db")
)
def is_disconnect(
self,
e: DBAPIModule.Error,
connection: Optional[Union[PoolProxiedConnection, DBAPIConnection]],
cursor: Optional[DBAPICursor],
) -> bool:
if super().is_disconnect(e, connection, cursor):
return True
else:
str_e = str(e).lower()
return "not connected" in str_e
def _found_rows_client_flag(self) -> int:
from pymysql.constants import CLIENT # type: ignore
return CLIENT.FOUND_ROWS # type: ignore[no-any-return]
def get_driver_connection(
self, connection: DBAPIConnection
) -> AsyncIODBAPIConnection:
return connection._connection # type: ignore[no-any-return]
dialect = MySQLDialect_aiomysql
| MySQLDialect_aiomysql |
python | matplotlib__matplotlib | lib/matplotlib/colors.py | {
"start": 50478,
"end": 60350
} | class ____:
"""
Class for holding multiple `~matplotlib.colors.Colormap` for use in a
`~matplotlib.cm.ScalarMappable` object
"""
def __init__(self, colormaps, combination_mode, name='multivariate colormap'):
"""
Parameters
----------
colormaps: list or tuple of `~matplotlib.colors.Colormap` objects
The individual colormaps that are combined
combination_mode: str, 'sRGB_add' or 'sRGB_sub'
Describe how colormaps are combined in sRGB space
- If 'sRGB_add' -> Mixing produces brighter colors
`sRGB = sum(colors)`
- If 'sRGB_sub' -> Mixing produces darker colors
`sRGB = 1 - sum(1 - colors)`
name : str, optional
The name of the colormap family.
"""
self.name = name
if not np.iterable(colormaps) \
or len(colormaps) == 1 \
or isinstance(colormaps, str):
raise ValueError("A MultivarColormap must have more than one colormap.")
colormaps = list(colormaps) # ensure cmaps is a list, i.e. not a tuple
for i, cmap in enumerate(colormaps):
if isinstance(cmap, str):
colormaps[i] = mpl.colormaps[cmap]
elif not isinstance(cmap, Colormap):
raise ValueError("colormaps must be a list of objects that subclass"
" Colormap or a name found in the colormap registry.")
self._colormaps = colormaps
_api.check_in_list(['sRGB_add', 'sRGB_sub'], combination_mode=combination_mode)
self._combination_mode = combination_mode
self.n_variates = len(colormaps)
self._rgba_bad = (0.0, 0.0, 0.0, 0.0) # If bad, don't paint anything.
def __call__(self, X, alpha=None, bytes=False, clip=True):
r"""
Parameters
----------
X : tuple (X0, X1, ...) of length equal to the number of colormaps
X0, X1 ...:
float or int, `~numpy.ndarray` or scalar
The data value(s) to convert to RGBA.
For floats, *Xi...* should be in the interval ``[0.0, 1.0]`` to
return the RGBA values ``X*100`` percent along the Colormap line.
For integers, *Xi...* should be in the interval ``[0, self[i].N)`` to
return RGBA values *indexed* from colormap [i] with index ``Xi``, where
self[i] is colormap i.
alpha : float or array-like or None
Alpha must be a scalar between 0 and 1, a sequence of such
floats with shape matching *Xi*, or None.
bytes : bool, default: False
If False (default), the returned RGBA values will be floats in the
interval ``[0, 1]`` otherwise they will be `numpy.uint8`\s in the
interval ``[0, 255]``.
clip : bool, default: True
If True, clip output to 0 to 1
Returns
-------
Tuple of RGBA values if X[0] is scalar, otherwise an array of
RGBA values with a shape of ``X.shape + (4, )``.
"""
if len(X) != len(self):
raise ValueError(
f'For the selected colormap the data must have a first dimension '
f'{len(self)}, not {len(X)}')
rgba, mask_bad = self[0]._get_rgba_and_mask(X[0], bytes=False)
for c, xx in zip(self[1:], X[1:]):
sub_rgba, sub_mask_bad = c._get_rgba_and_mask(xx, bytes=False)
rgba[..., :3] += sub_rgba[..., :3] # add colors
rgba[..., 3] *= sub_rgba[..., 3] # multiply alpha
mask_bad |= sub_mask_bad
if self.combination_mode == 'sRGB_sub':
rgba[..., :3] -= len(self) - 1
rgba[mask_bad] = self.get_bad()
if clip:
rgba = np.clip(rgba, 0, 1)
if alpha is not None:
if clip:
alpha = np.clip(alpha, 0, 1)
if np.shape(alpha) not in [(), np.shape(X[0])]:
raise ValueError(
f"alpha is array-like but its shape {np.shape(alpha)} does "
f"not match that of X[0] {np.shape(X[0])}")
rgba[..., -1] *= alpha
if bytes:
if not clip:
raise ValueError(
"clip cannot be false while bytes is true"
" as uint8 does not support values below 0"
" or above 255.")
rgba = (rgba * 255).astype('uint8')
if not np.iterable(X[0]):
rgba = tuple(rgba)
return rgba
def copy(self):
"""Return a copy of the multivarcolormap."""
return self.__copy__()
def __copy__(self):
cls = self.__class__
cmapobject = cls.__new__(cls)
cmapobject.__dict__.update(self.__dict__)
cmapobject._colormaps = [cm.copy() for cm in self._colormaps]
cmapobject._rgba_bad = np.copy(self._rgba_bad)
return cmapobject
def __eq__(self, other):
if not isinstance(other, MultivarColormap):
return False
if len(self) != len(other):
return False
for c0, c1 in zip(self, other):
if c0 != c1:
return False
if not all(self._rgba_bad == other._rgba_bad):
return False
if self.combination_mode != other.combination_mode:
return False
return True
def __getitem__(self, item):
return self._colormaps[item]
def __iter__(self):
for c in self._colormaps:
yield c
def __len__(self):
return len(self._colormaps)
def __str__(self):
return self.name
def get_bad(self):
"""Get the color for masked values."""
return np.array(self._rgba_bad)
def resampled(self, lutshape):
"""
Return a new colormap with *lutshape* entries.
Parameters
----------
lutshape : tuple of (`int`, `None`)
The tuple must have a length matching the number of variates.
For each element in the tuple, if `int`, the corresponding colorbar
is resampled, if `None`, the corresponding colorbar is not resampled.
Returns
-------
MultivarColormap
"""
if not np.iterable(lutshape) or len(lutshape) != len(self):
raise ValueError(f"lutshape must be of length {len(self)}")
new_cmap = self.copy()
for i, s in enumerate(lutshape):
if s is not None:
new_cmap._colormaps[i] = self[i].resampled(s)
return new_cmap
def with_extremes(self, *, bad=None, under=None, over=None):
"""
Return a copy of the `MultivarColormap` with modified out-of-range attributes.
The *bad* keyword modifies the copied `MultivarColormap` while *under* and
*over* modifies the attributes of the copied component colormaps.
Note that *under* and *over* colors are subject to the mixing rules determined
by the *combination_mode*.
Parameters
----------
bad: :mpltype:`color`, default: None
If Matplotlib color, the bad value is set accordingly in the copy
under tuple of :mpltype:`color`, default: None
If tuple, the `under` value of each component is set with the values
from the tuple.
over tuple of :mpltype:`color`, default: None
If tuple, the `over` value of each component is set with the values
from the tuple.
Returns
-------
MultivarColormap
copy of self with attributes set
"""
new_cm = self.copy()
if bad is not None:
new_cm._rgba_bad = to_rgba(bad)
if under is not None:
if not np.iterable(under) or len(under) != len(new_cm):
raise ValueError("*under* must contain a color for each scalar colormap"
f" i.e. be of length {len(new_cm)}.")
else:
for c, b in zip(new_cm, under):
# in-place change is ok, since we've just created c as a copy
c._set_extremes(under=b)
if over is not None:
if not np.iterable(over) or len(over) != len(new_cm):
raise ValueError("*over* must contain a color for each scalar colormap"
f" i.e. be of length {len(new_cm)}.")
else:
for c, b in zip(new_cm, over):
# in-place change is ok, since we've just created c as a copy
c._set_extremes(over=b)
return new_cm
@property
def combination_mode(self):
return self._combination_mode
def _repr_png_(self):
"""Generate a PNG representation of the Colormap."""
X = np.tile(np.linspace(0, 1, _REPR_PNG_SIZE[0]),
(_REPR_PNG_SIZE[1], 1))
pixels = np.zeros((_REPR_PNG_SIZE[1]*len(self), _REPR_PNG_SIZE[0], 4),
dtype=np.uint8)
for i, c in enumerate(self):
pixels[i*_REPR_PNG_SIZE[1]:(i+1)*_REPR_PNG_SIZE[1], :] = c(X, bytes=True)
png_bytes = io.BytesIO()
title = self.name + ' multivariate colormap'
author = f'Matplotlib v{mpl.__version__}, https://matplotlib.org'
pnginfo = PngInfo()
pnginfo.add_text('Title', title)
pnginfo.add_text('Description', title)
pnginfo.add_text('Author', author)
pnginfo.add_text('Software', author)
Image.fromarray(pixels).save(png_bytes, format='png', pnginfo=pnginfo)
return png_bytes.getvalue()
def _repr_html_(self):
"""Generate an HTML representation of the MultivarColormap."""
return ''.join([c._repr_html_() for c in self._colormaps])
| MultivarColormap |
python | ray-project__ray | doc/source/ray-core/doc_code/actor_creator_failure.py | {
"start": 137,
"end": 206
} | class ____:
def ping(self):
return "hello"
@ray.remote
| Actor |
python | django__django | tests/dispatch/tests.py | {
"start": 551,
"end": 9117
} | class ____(SimpleTestCase):
def assertTestIsClean(self, signal):
"""Assert that everything has been cleaned up automatically"""
# Note that dead weakref cleanup happens as side effect of using
# the signal's receivers through the signals API. So, first do a
# call to an API method to force cleanup.
self.assertFalse(signal.has_listeners())
self.assertEqual(signal.receivers, [])
@override_settings(DEBUG=True)
def test_cannot_connect_no_kwargs(self):
def receiver_no_kwargs(sender):
pass
msg = "Signal receivers must accept keyword arguments (**kwargs)."
with self.assertRaisesMessage(ValueError, msg):
a_signal.connect(receiver_no_kwargs)
self.assertTestIsClean(a_signal)
@override_settings(DEBUG=True)
def test_cannot_connect_non_callable(self):
msg = "Signal receivers must be callable."
with self.assertRaisesMessage(TypeError, msg):
a_signal.connect(object())
self.assertTestIsClean(a_signal)
def test_send(self):
a_signal.connect(receiver_1_arg, sender=self)
result = a_signal.send(sender=self, val="test")
self.assertEqual(result, [(receiver_1_arg, "test")])
a_signal.disconnect(receiver_1_arg, sender=self)
self.assertTestIsClean(a_signal)
def test_send_no_receivers(self):
result = a_signal.send(sender=self, val="test")
self.assertEqual(result, [])
def test_send_connected_no_sender(self):
a_signal.connect(receiver_1_arg)
result = a_signal.send(sender=self, val="test")
self.assertEqual(result, [(receiver_1_arg, "test")])
a_signal.disconnect(receiver_1_arg)
self.assertTestIsClean(a_signal)
def test_send_different_no_sender(self):
a_signal.connect(receiver_1_arg, sender=object)
result = a_signal.send(sender=self, val="test")
self.assertEqual(result, [])
a_signal.disconnect(receiver_1_arg, sender=object)
self.assertTestIsClean(a_signal)
def test_unweakrefable_sender(self):
sender = object()
a_signal.connect(receiver_1_arg, sender=sender)
result = a_signal.send(sender=sender, val="test")
self.assertEqual(result, [(receiver_1_arg, "test")])
a_signal.disconnect(receiver_1_arg, sender=sender)
self.assertTestIsClean(a_signal)
def test_garbage_collected_receiver(self):
a = Callable()
a_signal.connect(a.a, sender=self)
del a
garbage_collect()
result = a_signal.send(sender=self, val="test")
self.assertEqual(result, [])
self.assertTestIsClean(a_signal)
def test_garbage_collected_sender(self):
signal = Signal()
class Sender:
pass
def make_id(target):
"""
Simulate id() reuse for distinct senders with non-overlapping
lifetimes that would require memory contention to reproduce.
"""
if isinstance(target, Sender):
return 0
return _make_id(target)
def first_receiver(attempt, **kwargs):
return attempt
def second_receiver(attempt, **kwargs):
return attempt
with mock.patch("django.dispatch.dispatcher._make_id", make_id):
sender = Sender()
signal.connect(first_receiver, sender)
result = signal.send(sender, attempt="first")
self.assertEqual(result, [(first_receiver, "first")])
del sender
garbage_collect()
sender = Sender()
signal.connect(second_receiver, sender)
result = signal.send(sender, attempt="second")
self.assertEqual(result, [(second_receiver, "second")])
def test_cached_garbaged_collected(self):
"""
Make sure signal caching sender receivers don't prevent garbage
collection of senders.
"""
class sender:
pass
wref = weakref.ref(sender)
d_signal.connect(receiver_1_arg)
d_signal.send(sender, val="garbage")
del sender
garbage_collect()
try:
self.assertIsNone(wref())
finally:
# Disconnect after reference check since it flushes the tested
# cache.
d_signal.disconnect(receiver_1_arg)
def test_multiple_registration(self):
a = Callable()
a_signal.connect(a)
a_signal.connect(a)
a_signal.connect(a)
a_signal.connect(a)
a_signal.connect(a)
a_signal.connect(a)
result = a_signal.send(sender=self, val="test")
self.assertEqual(len(result), 1)
self.assertEqual(len(a_signal.receivers), 1)
del a
del result
garbage_collect()
self.assertTestIsClean(a_signal)
def test_uid_registration(self):
def uid_based_receiver_1(**kwargs):
pass
def uid_based_receiver_2(**kwargs):
pass
a_signal.connect(uid_based_receiver_1, dispatch_uid="uid")
a_signal.connect(uid_based_receiver_2, dispatch_uid="uid")
self.assertEqual(len(a_signal.receivers), 1)
a_signal.disconnect(dispatch_uid="uid")
self.assertTestIsClean(a_signal)
def test_send_robust_success(self):
a_signal.connect(receiver_1_arg)
result = a_signal.send_robust(sender=self, val="test")
self.assertEqual(result, [(receiver_1_arg, "test")])
a_signal.disconnect(receiver_1_arg)
self.assertTestIsClean(a_signal)
def test_send_robust_no_receivers(self):
result = a_signal.send_robust(sender=self, val="test")
self.assertEqual(result, [])
def test_send_robust_ignored_sender(self):
a_signal.connect(receiver_1_arg)
result = a_signal.send_robust(sender=self, val="test")
self.assertEqual(result, [(receiver_1_arg, "test")])
a_signal.disconnect(receiver_1_arg)
self.assertTestIsClean(a_signal)
def test_send_robust_fail(self):
def fails(val, **kwargs):
raise ValueError("this")
a_signal.connect(fails)
try:
with self.assertLogs("django.dispatch", "ERROR") as cm:
result = a_signal.send_robust(sender=self, val="test")
err = result[0][1]
self.assertIsInstance(err, ValueError)
self.assertEqual(err.args, ("this",))
self.assertIs(hasattr(err, "__traceback__"), True)
self.assertIsInstance(err.__traceback__, TracebackType)
log_record = cm.records[0]
self.assertEqual(
log_record.getMessage(),
"Error calling "
"DispatcherTests.test_send_robust_fail.<locals>.fails in "
"Signal.send_robust() (this)",
)
self.assertIsNotNone(log_record.exc_info)
_, exc_value, _ = log_record.exc_info
self.assertIsInstance(exc_value, ValueError)
self.assertEqual(str(exc_value), "this")
finally:
a_signal.disconnect(fails)
self.assertTestIsClean(a_signal)
def test_disconnection(self):
receiver_1 = Callable()
receiver_2 = Callable()
receiver_3 = Callable()
a_signal.connect(receiver_1)
a_signal.connect(receiver_2)
a_signal.connect(receiver_3)
a_signal.disconnect(receiver_1)
del receiver_2
garbage_collect()
a_signal.disconnect(receiver_3)
self.assertTestIsClean(a_signal)
def test_values_returned_by_disconnection(self):
receiver_1 = Callable()
receiver_2 = Callable()
a_signal.connect(receiver_1)
receiver_1_disconnected = a_signal.disconnect(receiver_1)
receiver_2_disconnected = a_signal.disconnect(receiver_2)
self.assertTrue(receiver_1_disconnected)
self.assertFalse(receiver_2_disconnected)
self.assertTestIsClean(a_signal)
def test_has_listeners(self):
self.assertFalse(a_signal.has_listeners())
self.assertFalse(a_signal.has_listeners(sender=object()))
receiver_1 = Callable()
a_signal.connect(receiver_1)
self.assertTrue(a_signal.has_listeners())
self.assertTrue(a_signal.has_listeners(sender=object()))
a_signal.disconnect(receiver_1)
self.assertFalse(a_signal.has_listeners())
self.assertFalse(a_signal.has_listeners(sender=object()))
| DispatcherTests |
python | allegroai__clearml | clearml/backend_api/services/v2_9/events.py | {
"start": 83035,
"end": 85459
} | class ____(Request):
"""
Get all 'plot' events for this task
:param task: Task ID
:type task: str
:param iters: Max number of latest iterations for which to return debug images
:type iters: int
:param scroll_id: Scroll ID of previous call (used for getting more results)
:type scroll_id: str
"""
_service = "events"
_action = "get_task_plots"
_version = "2.9"
_schema = {
"definitions": {},
"properties": {
"iters": {
"description": "Max number of latest iterations for which to return debug images",
"type": "integer",
},
"scroll_id": {
"description": "Scroll ID of previous call (used for getting more results)",
"type": "string",
},
"task": {"description": "Task ID", "type": "string"},
},
"required": ["task"],
"type": "object",
}
def __init__(self, task: str, iters: Optional[int] = None, scroll_id: Optional[str] = None, **kwargs: Any) -> None:
super(GetTaskPlotsRequest, self).__init__(**kwargs)
self.task = task
self.iters = iters
self.scroll_id = scroll_id
@schema_property("task")
def task(self) -> str:
return self._property_task
@task.setter
def task(self, value: str) -> None:
if value is None:
self._property_task = None
return
self.assert_isinstance(value, "task", six.string_types)
self._property_task = value
@schema_property("iters")
def iters(self) -> Optional[int]:
return self._property_iters
@iters.setter
def iters(self, value: Optional[int]) -> None:
if value is None:
self._property_iters = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "iters", six.integer_types)
self._property_iters = value
@schema_property("scroll_id")
def scroll_id(self) -> Optional[str]:
return self._property_scroll_id
@scroll_id.setter
def scroll_id(self, value: Optional[str]) -> None:
if value is None:
self._property_scroll_id = None
return
self.assert_isinstance(value, "scroll_id", six.string_types)
self._property_scroll_id = value
| GetTaskPlotsRequest |
python | doocs__leetcode | solution/0000-0099/0099.Recover Binary Search Tree/Solution.py | {
"start": 192,
"end": 803
} | class ____:
def recoverTree(self, root: Optional[TreeNode]) -> None:
"""
Do not return anything, modify root in-place instead.
"""
def dfs(root):
if root is None:
return
nonlocal prev, first, second
dfs(root.left)
if prev and prev.val > root.val:
if first is None:
first = prev
second = root
prev = root
dfs(root.right)
prev = first = second = None
dfs(root)
first.val, second.val = second.val, first.val
| Solution |
python | apache__airflow | providers/apache/hive/tests/unit/apache/hive/sensors/test_named_hive_partition.py | {
"start": 4891,
"end": 7656
} | class ____(TestHiveEnvironment):
def test_succeeds_on_one_partition(self):
mock_hive_metastore_hook = MockHiveMetastoreHook()
mock_hive_metastore_hook.check_for_named_partition = mock.MagicMock(return_value=True)
op = NamedHivePartitionSensor(
task_id="hive_partition_check",
partition_names=["airflow.static_babynames_partitioned/ds={{ds}}"],
dag=self.dag,
hook=mock_hive_metastore_hook,
)
op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
mock_hive_metastore_hook.check_for_named_partition.assert_called_once_with(
"airflow", "static_babynames_partitioned", "ds=2015-01-01"
)
def test_succeeds_on_multiple_partitions(self):
mock_hive_metastore_hook = MockHiveMetastoreHook()
mock_hive_metastore_hook.check_for_named_partition = mock.MagicMock(return_value=True)
op = NamedHivePartitionSensor(
task_id="hive_partition_check",
partition_names=[
"airflow.static_babynames_partitioned/ds={{ds}}",
"airflow.static_babynames_partitioned2/ds={{ds}}",
],
dag=self.dag,
hook=mock_hive_metastore_hook,
)
op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
mock_hive_metastore_hook.check_for_named_partition.assert_any_call(
"airflow", "static_babynames_partitioned", "ds=2015-01-01"
)
mock_hive_metastore_hook.check_for_named_partition.assert_any_call(
"airflow", "static_babynames_partitioned2", "ds=2015-01-01"
)
def test_parses_partitions_with_periods(self):
name = NamedHivePartitionSensor.parse_partition_name(
partition="schema.table/part1=this.can.be.an.issue/part2=ok"
)
assert name[0] == "schema"
assert name[1] == "table"
assert name[2] == "part1=this.can.be.an.issue/part2=ok"
def test_times_out_on_nonexistent_partition(self):
mock_hive_metastore_hook = MockHiveMetastoreHook()
mock_hive_metastore_hook.check_for_named_partition = mock.MagicMock(return_value=False)
op = NamedHivePartitionSensor(
task_id="hive_partition_check",
partition_names=[
"airflow.static_babynames_partitioned/ds={{ds}}",
"airflow.static_babynames_partitioned/ds=nonexistent",
],
poke_interval=0.1,
timeout=1,
dag=self.dag,
hook=mock_hive_metastore_hook,
)
with pytest.raises(AirflowSensorTimeout):
op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
| TestPartitions |
python | pallets__werkzeug | src/werkzeug/utils.py | {
"start": 905,
"end": 3236
} | class ____(property, t.Generic[_T]):
"""A :func:`property` that is only evaluated once. Subsequent access
returns the cached value. Setting the property sets the cached
value. Deleting the property clears the cached value, accessing it
again will evaluate it again.
.. code-block:: python
class Example:
@cached_property
def value(self):
# calculate something important here
return 42
e = Example()
e.value # evaluates
e.value # uses cache
e.value = 16 # sets cache
del e.value # clears cache
If the class defines ``__slots__``, it must add ``_cache_{name}`` as
a slot. Alternatively, it can add ``__dict__``, but that's usually
not desirable.
.. versionchanged:: 2.1
Works with ``__slots__``.
.. versionchanged:: 2.0
``del obj.name`` clears the cached value.
"""
def __init__(
self,
fget: t.Callable[[t.Any], _T],
name: str | None = None,
doc: str | None = None,
) -> None:
super().__init__(fget, doc=doc)
self.__name__ = name or fget.__name__
self.slot_name = f"_cache_{self.__name__}"
self.__module__ = fget.__module__
def __set__(self, obj: object, value: _T) -> None:
if hasattr(obj, "__dict__"):
obj.__dict__[self.__name__] = value
else:
setattr(obj, self.slot_name, value)
def __get__(self, obj: object, type: type = None) -> _T: # type: ignore
if obj is None:
return self # type: ignore
obj_dict = getattr(obj, "__dict__", None)
if obj_dict is not None:
value: _T = obj_dict.get(self.__name__, _missing)
else:
value = getattr(obj, self.slot_name, _missing) # type: ignore[arg-type]
if value is _missing:
value = self.fget(obj) # type: ignore
if obj_dict is not None:
obj.__dict__[self.__name__] = value
else:
setattr(obj, self.slot_name, value)
return value
def __delete__(self, obj: object) -> None:
if hasattr(obj, "__dict__"):
del obj.__dict__[self.__name__]
else:
setattr(obj, self.slot_name, _missing)
| cached_property |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.