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 | Netflix__metaflow | test/core/tests/switch_nested.py | {
"start": 82,
"end": 1024
} | class ____(MetaflowTest):
"""
Tests a switch that leads to another switch.
"""
PRIORITY = 2
ONLY_GRAPHS = ["nested_switch"]
@steps(0, ["start-nested"], required=True)
def step_start(self):
self.condition1 = "case1"
self.condition2 = "case2_2"
@steps(0, ["switch-nested"], required=True)
def step_switch2(self):
pass
@steps(0, ["path-b"], required=True)
def step_b(self):
self.result = "Direct path B"
@steps(0, ["path-c-nested"], required=True)
def step_c(self):
self.result = "Nested path C"
@steps(0, ["path-d-nested"], required=True)
def step_d(self):
self.result = "Nested path D"
@steps(1, ["end-nested"], required=True)
def step_end(self):
assert_equals("Nested path D", self.result)
def check_results(self, flow, checker):
checker.assert_artifact("d", "result", "Nested path D")
| NestedSwitchTest |
python | readthedocs__readthedocs.org | readthedocs/search/tests/test_parsers.py | {
"start": 500,
"end": 14255
} | class ____:
def setup_method(self):
self.project = get(
Project,
slug="test",
main_language_project=None,
)
self.version = self.project.versions.first()
def _mock_open(self, content):
@contextmanager
def f(*args, **kwargs):
read_mock = mock.MagicMock()
read_mock.read.return_value = content
yield read_mock
return f
@mock.patch.object(BuildMediaFileSystemStorage, "exists")
@mock.patch.object(BuildMediaFileSystemStorage, "open")
def test_mkdocs_default_theme(self, storage_open, storage_exists):
local_path = data_path / "mkdocs/in/mkdocs-1.1/"
storage_exists.return_value = True
self.version.documentation_type = MKDOCS
self.version.save()
parsed_json = []
all_files = [
"index.html",
"404.html",
"configuration.html",
"no-title.html",
"no-main-header.html",
]
for file_name in all_files:
file = local_path / file_name
storage_open.reset_mock()
storage_open.side_effect = self._mock_open(file.open().read())
file = get(
HTMLFile,
project=self.project,
version=self.version,
path=file_name,
)
parsed_json.append(file.processed_json)
expected_json = json.load(open(data_path / "mkdocs/out/mkdocs-1.1.json"))
assert parsed_json == expected_json
@mock.patch.object(BuildMediaFileSystemStorage, "exists")
@mock.patch.object(BuildMediaFileSystemStorage, "open")
def test_mkdocs_gitbook_theme(self, storage_open, storage_exists):
file = data_path / "mkdocs/in/gitbook/index.html"
storage_exists.return_value = True
self.version.documentation_type = MKDOCS
self.version.save()
storage_open.side_effect = self._mock_open(file.open().read())
file = get(
HTMLFile,
project=self.project,
version=self.version,
path="index.html",
)
parsed_json = [file.processed_json]
expected_json = json.load(open(data_path / "mkdocs/out/gitbook.json"))
assert parsed_json == expected_json
@mock.patch.object(BuildMediaFileSystemStorage, "exists")
@mock.patch.object(BuildMediaFileSystemStorage, "open")
def test_mkdocs_material_theme(self, storage_open, storage_exists):
file = data_path / "mkdocs/in/material/index.html"
storage_exists.return_value = True
self.version.documentation_type = MKDOCS
self.version.save()
storage_open.side_effect = self._mock_open(file.open().read())
file = get(
HTMLFile,
project=self.project,
version=self.version,
path="index.html",
)
parsed_json = [file.processed_json]
expected_json = json.load(open(data_path / "mkdocs/out/material.json"))
assert parsed_json == expected_json
@mock.patch.object(BuildMediaFileSystemStorage, "exists")
@mock.patch.object(BuildMediaFileSystemStorage, "open")
def test_mkdocs_windmill_theme(self, storage_open, storage_exists):
file = data_path / "mkdocs/in/windmill/index.html"
storage_exists.return_value = True
self.version.documentation_type = MKDOCS
self.version.save()
storage_open.side_effect = self._mock_open(file.open().read())
file = get(
HTMLFile,
project=self.project,
version=self.version,
path="index.html",
)
parsed_json = [file.processed_json]
expected_json = json.load(open(data_path / "mkdocs/out/windmill.json"))
assert parsed_json == expected_json
@mock.patch.object(BuildMediaFileSystemStorage, "exists")
@mock.patch.object(BuildMediaFileSystemStorage, "open")
def test_mkdocs_readthedocs_theme(self, storage_open, storage_exists):
storage_exists.return_value = True
self.version.documentation_type = MKDOCS
self.version.save()
local_path = data_path / "mkdocs/in/readthedocs-1.1/"
parsed_json = []
for file_name in ["index.html", "404.html", "versions.html"]:
file = local_path / file_name
storage_open.reset_mock()
storage_open.side_effect = self._mock_open(file.open().read())
file = get(
HTMLFile,
project=self.project,
version=self.version,
path=file_name,
)
parsed_json.append(file.processed_json)
expected_json = json.load(open(data_path / "mkdocs/out/readthedocs-1.1.json"))
assert parsed_json == expected_json
@mock.patch.object(BuildMediaFileSystemStorage, "exists")
@mock.patch.object(BuildMediaFileSystemStorage, "open")
def test_sphinx(self, storage_open, storage_exists):
html_content = data_path / "sphinx/in/page.html"
storage_open.side_effect = self._mock_open(html_content.open().read())
storage_exists.return_value = True
self.version.documentation_type = SPHINX
self.version.save()
page_file = get(
HTMLFile,
project=self.project,
version=self.version,
path="page.html",
)
parsed_json = page_file.processed_json
expected_json = json.load(open(data_path / "sphinx/out/page.json"))
assert parsed_json == expected_json
@mock.patch.object(BuildMediaFileSystemStorage, "exists")
@mock.patch.object(BuildMediaFileSystemStorage, "open")
def test_sphinx_page_without_title(self, storage_open, storage_exists):
html_content = data_path / "sphinx/in/no-title.html"
storage_open.side_effect = self._mock_open(html_content.open().read())
storage_exists.return_value = True
self.version.documentation_type = SPHINX
self.version.save()
page_file = get(
HTMLFile,
project=self.project,
version=self.version,
path="no-title.html",
)
parsed_json = page_file.processed_json
expected_json = json.load(open(data_path / "sphinx/out/no-title.json"))
assert parsed_json == expected_json
@mock.patch.object(BuildMediaFileSystemStorage, "exists")
@mock.patch.object(BuildMediaFileSystemStorage, "open")
def test_sphinx_httpdomain(self, storage_open, storage_exists):
html_content = data_path / "sphinx/in/httpdomain.html"
storage_open.side_effect = self._mock_open(html_content.open().read())
storage_exists.return_value = True
self.version.save()
page_file = get(
HTMLFile,
project=self.project,
version=self.version,
path="httpdomain.html",
)
parsed_json = page_file.processed_json
expected_json = json.load(open(data_path / "sphinx/out/httpdomain.json"))
assert parsed_json == expected_json
@mock.patch.object(BuildMediaFileSystemStorage, "exists")
@mock.patch.object(BuildMediaFileSystemStorage, "open")
def test_sphinx_autodoc(self, storage_open, storage_exists):
# Source:
# https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#directive-automodule
html_content = data_path / "sphinx/in/autodoc.html"
storage_open.side_effect = self._mock_open(html_content.open().read())
storage_exists.return_value = True
self.version.save()
page_file = get(
HTMLFile,
project=self.project,
version=self.version,
path="autodoc.html",
)
parsed_json = page_file.processed_json
expected_json = json.load(open(data_path / "sphinx/out/autodoc.json"))
assert parsed_json == expected_json
@mock.patch.object(BuildMediaFileSystemStorage, "exists")
@mock.patch.object(BuildMediaFileSystemStorage, "open")
def test_sphinx_local_toc(self, storage_open, storage_exists):
"""
Test that the local table of contents from the ``contents``
directive is not included in the indexed content.
"""
# Source:
# https://docs.readthedocs.io/en/stable/security.html
html_content = data_path / "sphinx/in/local-toc.html"
storage_open.side_effect = self._mock_open(html_content.open().read())
storage_exists.return_value = True
self.version.documentation_type = SPHINX
self.version.save()
page_file = get(
HTMLFile,
project=self.project,
version=self.version,
path="local-toc.html",
)
parsed_json = page_file.processed_json
expected_json = json.load(open(data_path / "sphinx/out/local-toc.json"))
assert parsed_json == expected_json
@mock.patch.object(BuildMediaFileSystemStorage, "exists")
@mock.patch.object(BuildMediaFileSystemStorage, "open")
def test_sphinx_toctree(self, storage_open, storage_exists):
"""
Test that the table of contents from the ``toctree``
directive is not included in the indexed content.
"""
# Source:
# https://docs.readthedocs.io/en/stable/api/index.html
html_content = data_path / "sphinx/in/toctree.html"
storage_open.side_effect = self._mock_open(html_content.open().read())
storage_exists.return_value = True
self.version.documentation_type = SPHINX
self.version.save()
page_file = get(
HTMLFile,
project=self.project,
version=self.version,
path="toctree.html",
)
parsed_json = page_file.processed_json
expected_json = json.load(open(data_path / "sphinx/out/toctree.json"))
assert parsed_json == expected_json
@mock.patch.object(BuildMediaFileSystemStorage, "exists")
@mock.patch.object(BuildMediaFileSystemStorage, "open")
def test_sphinx_requests(self, storage_open, storage_exists):
# Source:
# https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#directive-automodule
html_content = data_path / "sphinx/in/requests.html"
storage_open.side_effect = self._mock_open(html_content.open().read())
storage_exists.return_value = True
self.version.save()
page_file = get(
HTMLFile,
project=self.project,
version=self.version,
path="requests.html",
)
parsed_json = page_file.processed_json
expected_json = json.load(open(data_path / "sphinx/out/requests.json"))
assert parsed_json == expected_json
@mock.patch.object(BuildMediaFileSystemStorage, "exists")
@mock.patch.object(BuildMediaFileSystemStorage, "open")
def test_generic_simple_page(self, storage_open, storage_exists):
file = data_path / "generic/in/basic.html"
storage_exists.return_value = True
self.version.documentation_type = GENERIC
self.version.save()
storage_open.side_effect = self._mock_open(file.open().read())
file = get(
HTMLFile,
project=self.project,
version=self.version,
path="basic.html",
)
parsed_json = [file.processed_json]
expected_json = json.load(open(data_path / "generic/out/basic.json"))
assert parsed_json == expected_json
@mock.patch.object(BuildMediaFileSystemStorage, "exists")
@mock.patch.object(BuildMediaFileSystemStorage, "open")
def test_generic_pelican_default_theme(self, storage_open, storage_exists):
file = data_path / "pelican/in/default/index.html"
storage_exists.return_value = True
self.version.documentation_type = GENERIC
self.version.save()
storage_open.side_effect = self._mock_open(file.open().read())
file = get(
HTMLFile,
project=self.project,
version=self.version,
path="index.html",
)
parsed_json = [file.processed_json]
expected_json = json.load(open(data_path / "pelican/out/default.json"))
assert parsed_json == expected_json
@mock.patch.object(BuildMediaFileSystemStorage, "exists")
@mock.patch.object(BuildMediaFileSystemStorage, "open")
def test_truncate_content(self, storage_open, storage_exists):
html_content = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Title of the page</title>
</head>
<body>
"""
# More than ~1.5 MB of content
html_content += "A" * (GenericParser.max_content_length + 100) + "!" + "B" * 1000
html_content += "</body></html>"
storage_open.side_effect = self._mock_open(html_content)
storage_exists.return_value = True
self.version.save()
page_file = get(
HTMLFile,
project=self.project,
version=self.version,
path="page.html",
)
parsed_json = page_file.processed_json
assert parsed_json["path"] == "page.html"
assert parsed_json["title"] == "Title of the page"
assert len(parsed_json["sections"]) == 1
section = parsed_json["sections"][0]
assert section["title"] == "Title of the page"
assert len(section["content"]) <= GenericParser.max_content_length
assert section["content"].startswith("A")
assert not section["content"].endswith("B")
| TestParsers |
python | sympy__sympy | sympy/assumptions/predicates/sets.py | {
"start": 4428,
"end": 5201
} | class ____(Predicate):
r"""
Extended real predicate.
Explanation
===========
``Q.extended_real(x)`` is true iff ``x`` is a real number or
`\{-\infty, \infty\}`.
See documentation of ``Q.real`` for more information about related
facts.
Examples
========
>>> from sympy import ask, Q, oo, I
>>> ask(Q.extended_real(1))
True
>>> ask(Q.extended_real(I))
False
>>> ask(Q.extended_real(oo))
True
"""
name = 'extended_real'
handler = Dispatcher(
"ExtendedRealHandler",
doc=("Handler for Q.extended_real.\n\n"
"Test that an expression belongs to the field of extended real\n"
"numbers, that is real numbers union {Infinity, -Infinity}.")
)
| ExtendedRealPredicate |
python | ray-project__ray | release/train_tests/benchmark/image_classification/parquet/parquet_iterable_dataset.py | {
"start": 670,
"end": 9397
} | class ____(S3ParquetReader, IterableDataset):
"""An iterable dataset that loads images from S3-stored Parquet files.
This dataset:
1. Reads Parquet files from S3 one row group at a time
2. Processes images with optional random transforms
3. Yields (image, label) tensors
4. Supports row limits per worker for controlled data processing
"""
LOG_FREQUENCY = 1000 # Log progress every 1000 rows
def __init__(
self,
file_urls: List[str],
random_transforms: bool = True,
limit_rows_per_worker: Optional[int] = None,
):
"""Initialize the dataset.
Args:
file_urls: List of S3 URLs to load
random_transforms: Whether to use random transforms for training
limit_rows_per_worker: Maximum number of rows to process per worker (None for all rows)
"""
super().__init__()
self.file_urls = file_urls
self.limit_rows_per_worker = limit_rows_per_worker
self.random_transforms = random_transforms
worker_rank = ray.train.get_context().get_world_rank()
logger.info(
f"Worker {worker_rank}: Initialized with {len(file_urls)} files"
f"{f' (limit: {limit_rows_per_worker} rows)' if limit_rows_per_worker else ''}"
)
def _get_worker_info(self) -> Tuple[int, int]:
"""Get current worker information.
Returns:
Tuple of (worker_id, num_workers)
"""
worker_info = torch.utils.data.get_worker_info()
worker_id = worker_info.id if worker_info else 0
num_workers = worker_info.num_workers if worker_info else 1
return worker_id, num_workers
def _has_reached_row_limit(self, rows_processed: int) -> bool:
"""Check if we've reached the row limit per worker.
Args:
rows_processed: Number of rows processed so far
Returns:
True if we've reached the limit, False otherwise
"""
return (
self.limit_rows_per_worker is not None
and rows_processed >= self.limit_rows_per_worker
)
def _log_progress(
self, worker_id: int, rows_processed: int, last_log_time: float
) -> float:
"""Log processing progress and return updated last_log_time.
Args:
worker_id: ID of the current worker
rows_processed: Number of rows processed so far
last_log_time: Time of last progress log
Returns:
Updated last_log_time
"""
if rows_processed % self.LOG_FREQUENCY == 0:
current_time = time.time()
elapsed_time = current_time - last_log_time
rows_per_second = (
self.LOG_FREQUENCY / elapsed_time if elapsed_time > 0 else 0
)
logger.info(
f"Worker {worker_id}: Processed {rows_processed} rows "
f"({rows_per_second:.2f} rows/sec)"
)
return current_time
return last_log_time
def _read_parquet_file(self, file_url: str) -> Iterator[pd.DataFrame]:
"""Read a Parquet file from S3 one row group at a time.
This method:
1. Fetches the Parquet file from S3
2. Reads it row group by row group
3. Converts each row group to a pandas DataFrame
Args:
file_url: S3 URL of the Parquet file
Yields:
DataFrame containing one row group at a time
Raises:
Exception: If there's an error reading the file
"""
try:
start_time = time.time()
worker_id, _ = self._get_worker_info()
logger.info(f"Worker {worker_id}: Reading Parquet file: {file_url}")
# Get parquet file metadata
bucket, key = self._parse_s3_url(file_url)
response = self.s3_client.get_object(Bucket=bucket, Key=key)
parquet_file = pq.ParquetFile(io.BytesIO(response["Body"].read()))
num_row_groups = parquet_file.num_row_groups
logger.info(
f"Worker {worker_id}: Found {num_row_groups} row groups in {file_url}"
)
for row_group in range(num_row_groups):
# Read row group and convert to pandas
table = parquet_file.read_row_group(row_group)
df = table.to_pandas()
yield df
total_time = time.time() - start_time
logger.info(
f"Worker {worker_id}: Completed reading {file_url} in {total_time:.2f}s"
)
except Exception as e:
worker_id, _ = self._get_worker_info()
logger.error(
f"Worker {worker_id}: Error reading file {file_url}: {str(e)}",
exc_info=True,
)
raise
def _process_file(
self,
file_url: str,
preprocess_fn: Callable,
) -> Iterator[Tuple[torch.Tensor, torch.Tensor]]:
"""Process a single file and yield processed rows.
Args:
file_url: URL of the file to process
preprocess_fn: Preprocessing function to apply
Yields:
Tuple of (image_tensor, label_tensor)
"""
for df in self._read_parquet_file(file_url):
for _, row in df.iterrows():
try:
# Process row and convert to tensors
processed = preprocess_fn(row)
image = torch.as_tensor(processed["image"], dtype=torch.float32)
label = torch.as_tensor(processed["label"], dtype=torch.int64)
yield image, label
except Exception:
continue
def _process_files(
self, files_to_read: List[str], preprocess_fn: Callable, worker_id: int
) -> Iterator[Tuple[torch.Tensor, torch.Tensor]]:
"""Process multiple files and yield processed rows.
Args:
files_to_read: List of file URLs to process
preprocess_fn: Preprocessing function to apply
worker_id: ID of the current worker
Yields:
Tuple of (image_tensor, label_tensor)
"""
rows_processed = 0
last_log_time = time.time()
total_start_time = time.time()
for file_url in files_to_read:
if self._has_reached_row_limit(rows_processed):
logger.info(f"Worker {worker_id}: Reached row limit: {rows_processed}")
break
for image, label in self._process_file(file_url, preprocess_fn):
if self._has_reached_row_limit(rows_processed):
break
rows_processed += 1
last_log_time = self._log_progress(
worker_id, rows_processed, last_log_time
)
yield image, label
# Log final statistics
total_time = time.time() - total_start_time
logger.info(
f"Worker {worker_id}: Finished: {rows_processed} rows in {total_time:.2f}s "
f"({rows_processed/total_time:.2f} rows/sec)"
)
def __iter__(self) -> Iterator[Tuple[torch.Tensor, torch.Tensor]]:
"""Main iteration method that processes files and yields (image, label) tensors.
This method:
1. Distributes files among workers
2. Processes rows with image transforms
3. Converts to tensors
4. Respects row limits per worker
Yields:
Tuple of (image_tensor, label_tensor)
Raises:
Exception: If there's a fatal error during processing
"""
try:
# Get worker info for file distribution
worker_id, num_workers = self._get_worker_info()
logger.info(f"Worker {worker_id}/{num_workers}: Starting")
# Initialize preprocessing function
preprocess_fn = get_preprocess_map_fn(
decode_image=True, random_transforms=self.random_transforms
)
# Distribute files among workers
files_to_read = (
self.file_urls
if num_workers == 1
else self.file_urls[worker_id::num_workers]
)
logger.info(f"Worker {worker_id}: Processing {len(files_to_read)} files")
# Process files and yield results
yield from self._process_files(files_to_read, preprocess_fn, worker_id)
except Exception as e:
logger.error(
f"Worker {worker_id}: Fatal error: {str(e)}",
exc_info=True,
)
raise
| S3ParquetImageIterableDataset |
python | doocs__leetcode | solution/1700-1799/1773.Count Items Matching a Rule/Solution.py | {
"start": 0,
"end": 230
} | class ____:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
i = 0 if ruleKey[0] == 't' else (1 if ruleKey[0] == 'c' else 2)
return sum(v[i] == ruleValue for v in items)
| Solution |
python | google__jax | jax/_src/pallas/mosaic_gpu/core.py | {
"start": 41462,
"end": 42040
} | class ____:
collective_axes: tuple[str | tuple[str, ...], ...]
num_barriers: int = 1
num_arrivals: int = 1
orders_tensor_core: bool = False
def get_array_aval(self) -> jax_core.ShapedArray:
raise ValueError("Cluster barriers are not arrays")
def get_ref_aval(self) -> state.AbstractRef:
aval = jax_core.ShapedArray(
[self.num_barriers],
ClusterBarrierType(
self.collective_axes, self.num_arrivals, self.orders_tensor_core
),
)
return state.AbstractRef(aval, SMEM)
@dataclasses.dataclass(frozen=True)
| ClusterBarrier |
python | getsentry__sentry | src/sentry/integrations/msteams/webhook.py | {
"start": 26463,
"end": 28837
} | class ____(MessagingIntegrationCommandDispatcher[AdaptiveCard]):
data: dict[str, Any]
@property
def integration_spec(self) -> MessagingIntegrationSpec:
return MsTeamsMessagingSpec()
@property
def conversation_id(self) -> str:
return self.data["conversation"]["id"]
@property
def teams_user_id(self) -> str:
return self.data["from"]["id"]
def help_handler(self, input: CommandInput) -> IntegrationResponse[AdaptiveCard]:
return IntegrationResponse(
interaction_result=EventLifecycleOutcome.SUCCESS,
response=build_help_command_card(),
)
def link_user_handler(self, input: CommandInput) -> IntegrationResponse[AdaptiveCard]:
linked_identity = identity_service.get_identity(
filter={"identity_ext_id": self.teams_user_id}
)
has_linked_identity = linked_identity is not None
if has_linked_identity:
return IntegrationResponse(
interaction_result=EventLifecycleOutcome.SUCCESS,
response=build_already_linked_identity_command_card(),
outcome_reason=str(MessageCommandHaltReason.ALREADY_LINKED),
context_data={
"user_id": self.teams_user_id,
"identity_id": linked_identity.id if linked_identity else None,
},
)
else:
return IntegrationResponse(
interaction_result=EventLifecycleOutcome.SUCCESS,
response=build_link_identity_command_card(),
)
def unlink_user_handler(self, input: CommandInput) -> IntegrationResponse[AdaptiveCard]:
unlink_url = build_unlinking_url(
self.conversation_id, self.data["serviceUrl"], self.teams_user_id
)
# TODO: check if the user is already unlinked
return IntegrationResponse(
response=build_unlink_identity_card(unlink_url),
interaction_result=EventLifecycleOutcome.SUCCESS,
)
@property
def command_handlers(
self,
) -> Iterable[tuple[MessagingIntegrationCommand, CommandHandler[AdaptiveCard]]]:
yield commands.HELP, self.help_handler
yield commands.LINK_IDENTITY, self.link_user_handler
yield commands.UNLINK_IDENTITY, self.unlink_user_handler
| MsTeamsCommandDispatcher |
python | allegroai__clearml | examples/router/simple_webserver.py | {
"start": 476,
"end": 994
} | class ____(BaseModel):
name: str
description: str
@app.get("/")
def read_root():
return {"message": "Welcome to the FastAPI application!"}
@app.get("/serve/{action}", response_model=Item)
def read_item(action: str):
if action in actions:
return actions[action]
else:
raise HTTPException(status_code=404, detail="Item not found")
if __name__ == "__main__":
uvicorn.run(
"simple_webserver:app",
host="127.0.0.1",
port=8000,
reload=True
)
| Item |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_s3.py | {
"start": 37746,
"end": 39896
} | class ____:
@mock.patch.object(S3Hook, "load_string")
def test_execute_if_data_is_string(self, mock_load_string):
data = "data"
operator = S3CreateObjectOperator(
task_id="test-s3-operator",
s3_bucket=BUCKET_NAME,
s3_key=S3_KEY,
data=data,
)
operator.execute(None)
mock_load_string.assert_called_once_with(data, S3_KEY, BUCKET_NAME, False, False, None, None, None)
@mock.patch.object(S3Hook, "load_bytes")
def test_execute_if_data_is_bytes(self, mock_load_bytes):
data = b"data"
operator = S3CreateObjectOperator(
task_id="test-s3-create-object-operator",
s3_bucket=BUCKET_NAME,
s3_key=S3_KEY,
data=data,
)
operator.execute(None)
mock_load_bytes.assert_called_once_with(data, S3_KEY, BUCKET_NAME, False, False, None)
@mock.patch.object(S3Hook, "load_string")
def test_execute_if_s3_bucket_not_provided(self, mock_load_string):
data = "data"
operator = S3CreateObjectOperator(
task_id="test-s3-create-object-operator",
s3_key=f"s3://{BUCKET_NAME}/{S3_KEY}",
data=data,
)
operator.execute(None)
mock_load_string.assert_called_once_with(data, S3_KEY, BUCKET_NAME, False, False, None, None, None)
@pytest.mark.parametrize(("bucket", "key"), (("bucket", "file.txt"), (None, "s3://bucket/file.txt")))
def test_get_openlineage_facets_on_start(self, bucket, key):
expected_output = Dataset(
namespace="s3://bucket",
name="file.txt",
)
op = S3CreateObjectOperator(task_id="test", s3_bucket=bucket, s3_key=key, data="test")
lineage = op.get_openlineage_facets_on_start()
assert len(lineage.inputs) == 0
assert len(lineage.outputs) == 1
assert lineage.outputs[0] == expected_output
def test_template_fields(self):
operator = S3CreateObjectOperator(task_id="test", s3_bucket="bucket", s3_key="key", data="test")
validate_template_fields(operator)
| TestS3CreateObjectOperator |
python | tiangolo__fastapi | tests/test_custom_schema_fields.py | {
"start": 286,
"end": 1725
} | class ____(BaseModel):
name: str
if PYDANTIC_V2:
description: Annotated[
Optional[str], WithJsonSchema({"type": ["string", "null"]})
] = None
model_config = {
"json_schema_extra": {
"x-something-internal": {"level": 4},
}
}
else:
description: Optional[str] = None # type: ignore[no-redef]
class Config:
schema_extra = {
"x-something-internal": {"level": 4},
}
@app.get("/foo", response_model=Item)
def foo():
return {"name": "Foo item"}
client = TestClient(app)
item_schema = {
"title": "Item",
"required": ["name"],
"type": "object",
"x-something-internal": {
"level": 4,
},
"properties": {
"name": {
"title": "Name",
"type": "string",
},
"description": {
"title": "Description",
"type": ["string", "null"] if PYDANTIC_V2 else "string",
},
},
}
def test_custom_response_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json()["components"]["schemas"]["Item"] == item_schema
def test_response():
# For coverage
response = client.get("/foo")
assert response.status_code == 200, response.text
assert response.json() == {"name": "Foo item", "description": None}
| Item |
python | numba__numba | numba/tests/test_datamodel.py | {
"start": 1417,
"end": 1520
} | class ____(test_factory()):
fe_type = types.Tuple([types.int32, types.float32])
| TestTupleInt32Float32 |
python | keras-team__keras | integration_tests/dataset_tests/imdb_test.py | {
"start": 88,
"end": 1831
} | class ____(testing.TestCase):
def test_load_data_default(self):
(x_train, y_train), (x_test, y_test) = imdb.load_data()
self.assertIsInstance(x_train, np.ndarray)
self.assertIsInstance(y_train, np.ndarray)
self.assertIsInstance(x_test, np.ndarray)
self.assertIsInstance(y_test, np.ndarray)
# Check lengths
self.assertEqual(len(x_train), 25000)
self.assertEqual(len(y_train), 25000)
self.assertEqual(len(x_test), 25000)
self.assertEqual(len(y_test), 25000)
# Check types within lists for x
self.assertIsInstance(x_train[0], list)
self.assertIsInstance(x_test[0], list)
def test_num_words(self):
# Only consider the top 1000 words
(x_train, _), _ = imdb.load_data(num_words=1000)
# Ensure that no word index exceeds 999 (0-based indexing)
max_index = max(max(sequence) for sequence in x_train if sequence)
self.assertLessEqual(max_index, 999)
def test_skip_top(self):
# Skip the top 10 most frequent words
(x_train, _), _ = imdb.load_data(skip_top=10, num_words=1000)
# Check if top 10 words are skipped properly
self.assertNotIn(1, x_train[0]) # Assuming 1 is among top 10
def test_maxlen(self):
# Only consider sequences shorter than 100
(x_train, _), _ = imdb.load_data(maxlen=100)
self.assertTrue(all(len(seq) <= 100 for seq in x_train))
def test_get_word_index(self):
word_index = imdb.get_word_index()
self.assertIsInstance(word_index, dict)
# Check if word_index contains specific known words
self.assertIn("the", word_index)
self.assertIn("and", word_index)
| ImdbLoadDataTest |
python | google__pytype | pytype/tests/test_utils.py | {
"start": 6833,
"end": 7287
} | class ____:
"""Mixin providing utils for tests on the collections module."""
_HAS_DYNAMIC_ATTRIBUTES = True
def _testCollectionsObject(self, obj, good_arg, bad_arg, error): # pylint: disable=invalid-name
result = self.CheckWithErrors(f"""
import collections
def f(x: collections.{obj}): ...
f({good_arg})
f({bad_arg}) # wrong-arg-types[e]
""")
self.assertErrorRegexes(result, {"e": error})
| TestCollectionsMixin |
python | kamyu104__LeetCode-Solutions | Python/maximum-and-sum-of-array.py | {
"start": 2199,
"end": 2656
} | class ____(object):
def maximumANDSum(self, nums, numSlots):
"""
:type nums: List[int]
:type numSlots: int
:rtype: int
"""
adj = [[-((nums[i] if i < len(nums) else 0) & (1+x//2)) for x in xrange(2*numSlots)] for i in xrange(2*numSlots)]
return -sum(adj[i][j] for i, j in itertools.izip(*hungarian(adj)))
# Time: O(n * 3^n)
# Space: O(3^n)
# bottom-up dp (hard to implement but faster)
| Solution2 |
python | pola-rs__polars | py-polars/tests/unit/interchange/test_from_dataframe.py | {
"start": 8322,
"end": 20391
} | class ____(PolarsColumn):
"""Helper class that allows patching certain PolarsColumn properties."""
describe_null: tuple[ColumnNullType, Any] = (ColumnNullType.USE_BITMASK, 0)
describe_categorical: dict[str, Any] = {} # type: ignore[assignment] # noqa: RUF012
null_count = 0
def test_column_to_series_use_sentinel_i64_min() -> None:
I64_MIN = -9223372036854775808
dtype = pl.Datetime("us")
physical = pl.Series([0, I64_MIN])
logical = physical.cast(dtype)
col = PatchableColumn(logical)
col.describe_null = (ColumnNullType.USE_SENTINEL, I64_MIN)
col.null_count = 1
result = _column_to_series(col, dtype, allow_copy=True)
expected = pl.Series([datetime(1970, 1, 1), None])
assert_series_equal(result, expected)
def test_column_to_series_duration() -> None:
s = pl.Series([timedelta(seconds=10), timedelta(days=5), None])
col = PolarsColumn(s)
result = _column_to_series(col, s.dtype, allow_copy=True)
assert_series_equal(result, s)
def test_column_to_series_time() -> None:
s = pl.Series([time(10, 0), time(23, 59, 59), None])
col = PolarsColumn(s)
result = _column_to_series(col, s.dtype, allow_copy=True)
assert_series_equal(result, s)
def test_column_to_series_use_sentinel_date() -> None:
mask_value = date(1900, 1, 1)
s = pl.Series([date(1970, 1, 1), mask_value, date(2000, 1, 1)])
col = PatchableColumn(s)
col.describe_null = (ColumnNullType.USE_SENTINEL, mask_value)
col.null_count = 1
result = _column_to_series(col, pl.Date, allow_copy=True)
expected = pl.Series([date(1970, 1, 1), None, date(2000, 1, 1)])
assert_series_equal(result, expected)
def test_column_to_series_use_sentinel_datetime() -> None:
dtype = pl.Datetime("ns")
mask_value = datetime(1900, 1, 1)
s = pl.Series([datetime(1970, 1, 1), mask_value, datetime(2000, 1, 1)], dtype=dtype)
col = PatchableColumn(s)
col.describe_null = (ColumnNullType.USE_SENTINEL, mask_value)
col.null_count = 1
result = _column_to_series(col, dtype, allow_copy=True)
expected = pl.Series(
[datetime(1970, 1, 1), None, datetime(2000, 1, 1)], dtype=dtype
)
assert_series_equal(result, expected)
def test_column_to_series_use_sentinel_invalid_value() -> None:
dtype = pl.Datetime("ns")
mask_value = "invalid"
s = pl.Series([datetime(1970, 1, 1), None, datetime(2000, 1, 1)], dtype=dtype)
col = PatchableColumn(s)
col.describe_null = (ColumnNullType.USE_SENTINEL, mask_value)
col.null_count = 1
with pytest.raises(
TypeError,
match=r"invalid sentinel value for column of type Datetime\(time_unit='ns', time_zone=None\): 'invalid'",
):
_column_to_series(col, dtype, allow_copy=True)
def test_string_column_to_series_no_offsets() -> None:
s = pl.Series([97, 98, 99])
col = PolarsColumn(s)
with pytest.raises(
RuntimeError,
match="cannot create String column without an offsets buffer",
):
_string_column_to_series(col, allow_copy=True)
def test_categorical_column_to_series_non_dictionary() -> None:
s = pl.Series(["a", "b", None, "a"], dtype=pl.Categorical)
col = PatchableColumn(s)
col.describe_categorical = {"is_dictionary": False}
with pytest.raises(
NotImplementedError, match="non-dictionary categoricals are not yet supported"
):
_categorical_column_to_series(col, allow_copy=True)
def test_construct_data_buffer() -> None:
data = pl.Series([0, 1, 3, 3, 9], dtype=pl.Int64)
buffer = PolarsBuffer(data)
dtype = (DtypeKind.INT, 64, "l", NE)
result = _construct_data_buffer(buffer, dtype, length=5, allow_copy=True)
assert_series_equal(result, data)
def test_construct_data_buffer_boolean_sliced() -> None:
data = pl.Series([False, True, True, False])
data_sliced = data[2:]
buffer = PolarsBuffer(data_sliced)
dtype = (DtypeKind.BOOL, 1, "b", NE)
result = _construct_data_buffer(buffer, dtype, length=2, offset=2, allow_copy=True)
assert_series_equal(result, data_sliced)
def test_construct_data_buffer_logical_dtype() -> None:
data = pl.Series([100, 200, 300], dtype=pl.Int32)
buffer = PolarsBuffer(data)
dtype = (DtypeKind.DATETIME, 32, "tdD", NE)
result = _construct_data_buffer(buffer, dtype, length=3, allow_copy=True)
assert_series_equal(result, data)
def test_construct_offsets_buffer() -> None:
data = pl.Series([0, 1, 3, 3, 9], dtype=pl.Int64)
buffer = PolarsBuffer(data)
dtype = (DtypeKind.INT, 64, "l", NE)
result = _construct_offsets_buffer(buffer, dtype, offset=0, allow_copy=True)
assert_series_equal(result, data)
def test_construct_offsets_buffer_offset() -> None:
data = pl.Series([0, 1, 3, 3, 9], dtype=pl.Int64)
buffer = PolarsBuffer(data)
dtype = (DtypeKind.INT, 64, "l", NE)
offset = 2
result = _construct_offsets_buffer(buffer, dtype, offset=offset, allow_copy=True)
assert_series_equal(result, data[offset:])
def test_construct_offsets_buffer_copy() -> None:
data = pl.Series([0, 1, 3, 3, 9], dtype=pl.UInt32)
buffer = PolarsBuffer(data)
dtype = (DtypeKind.UINT, 32, "I", NE)
with pytest.raises(CopyNotAllowedError):
_construct_offsets_buffer(buffer, dtype, offset=0, allow_copy=False)
result = _construct_offsets_buffer(buffer, dtype, offset=0, allow_copy=True)
expected = pl.Series([0, 1, 3, 3, 9], dtype=pl.Int64)
assert_series_equal(result, expected)
@pytest.fixture
def bitmask() -> PolarsBuffer:
data = pl.Series([False, True, True, False])
return PolarsBuffer(data)
@pytest.fixture
def bytemask() -> PolarsBuffer:
data = pl.Series([0, 1, 1, 0], dtype=pl.UInt8)
return PolarsBuffer(data)
def test_construct_validity_buffer_non_nullable() -> None:
s = pl.Series([1, 2, 3])
col = PatchableColumn(s)
col.describe_null = (ColumnNullType.NON_NULLABLE, None)
col.null_count = 1
result = _construct_validity_buffer(None, col, s.dtype, s, allow_copy=True)
assert result is None
def test_construct_validity_buffer_null_count() -> None:
s = pl.Series([1, 2, 3])
col = PatchableColumn(s)
col.describe_null = (ColumnNullType.USE_SENTINEL, -1)
col.null_count = 0
result = _construct_validity_buffer(None, col, s.dtype, s, allow_copy=True)
assert result is None
def test_construct_validity_buffer_use_bitmask(bitmask: PolarsBuffer) -> None:
s = pl.Series([1, 2, 3, 4])
col = PatchableColumn(s)
col.describe_null = (ColumnNullType.USE_BITMASK, 0)
col.null_count = 2
dtype = (DtypeKind.BOOL, 1, "b", NE)
validity_buffer_info = (bitmask, dtype)
result = _construct_validity_buffer(
validity_buffer_info, col, s.dtype, s, allow_copy=True
)
expected = pl.Series([False, True, True, False])
assert_series_equal(result, expected) # type: ignore[arg-type]
result = _construct_validity_buffer(None, col, s.dtype, s, allow_copy=True)
assert result is None
def test_construct_validity_buffer_use_bytemask(bytemask: PolarsBuffer) -> None:
s = pl.Series([1, 2, 3, 4])
col = PatchableColumn(s)
col.describe_null = (ColumnNullType.USE_BYTEMASK, 0)
col.null_count = 2
dtype = (DtypeKind.UINT, 8, "C", NE)
validity_buffer_info = (bytemask, dtype)
result = _construct_validity_buffer(
validity_buffer_info, col, s.dtype, s, allow_copy=True
)
expected = pl.Series([False, True, True, False])
assert_series_equal(result, expected) # type: ignore[arg-type]
result = _construct_validity_buffer(None, col, s.dtype, s, allow_copy=True)
assert result is None
def test_construct_validity_buffer_use_nan() -> None:
s = pl.Series([1.0, 2.0, float("nan")])
col = PatchableColumn(s)
col.describe_null = (ColumnNullType.USE_NAN, None)
col.null_count = 1
result = _construct_validity_buffer(None, col, s.dtype, s, allow_copy=True)
expected = pl.Series([True, True, False])
assert_series_equal(result, expected) # type: ignore[arg-type]
with pytest.raises(CopyNotAllowedError, match="bitmask must be constructed"):
_construct_validity_buffer(None, col, s.dtype, s, allow_copy=False)
def test_construct_validity_buffer_use_sentinel() -> None:
s = pl.Series(["a", "bc", "NULL"])
col = PatchableColumn(s)
col.describe_null = (ColumnNullType.USE_SENTINEL, "NULL")
col.null_count = 1
result = _construct_validity_buffer(None, col, s.dtype, s, allow_copy=True)
expected = pl.Series([True, True, False])
assert_series_equal(result, expected) # type: ignore[arg-type]
with pytest.raises(CopyNotAllowedError, match="bitmask must be constructed"):
_construct_validity_buffer(None, col, s.dtype, s, allow_copy=False)
def test_construct_validity_buffer_unsupported() -> None:
s = pl.Series([1, 2, 3])
col = PatchableColumn(s)
col.describe_null = (100, None) # type: ignore[assignment]
col.null_count = 1
with pytest.raises(NotImplementedError, match="unsupported null type: 100"):
_construct_validity_buffer(None, col, s.dtype, s, allow_copy=True)
@pytest.mark.parametrize("allow_copy", [True, False])
def test_construct_validity_buffer_from_bitmask(
allow_copy: bool, bitmask: PolarsBuffer
) -> None:
result = _construct_validity_buffer_from_bitmask(
bitmask, null_value=0, offset=0, length=4, allow_copy=allow_copy
)
expected = pl.Series([False, True, True, False])
assert_series_equal(result, expected)
def test_construct_validity_buffer_from_bitmask_inverted(bitmask: PolarsBuffer) -> None:
result = _construct_validity_buffer_from_bitmask(
bitmask, null_value=1, offset=0, length=4, allow_copy=True
)
expected = pl.Series([True, False, False, True])
assert_series_equal(result, expected)
def test_construct_validity_buffer_from_bitmask_zero_copy_fails(
bitmask: PolarsBuffer,
) -> None:
with pytest.raises(CopyNotAllowedError):
_construct_validity_buffer_from_bitmask(
bitmask, null_value=1, offset=0, length=4, allow_copy=False
)
def test_construct_validity_buffer_from_bitmask_sliced() -> None:
data = pl.Series([False, True, True, False])
data_sliced = data[2:]
bitmask = PolarsBuffer(data_sliced)
result = _construct_validity_buffer_from_bitmask(
bitmask, null_value=0, offset=2, length=2, allow_copy=True
)
assert_series_equal(result, data_sliced)
def test_construct_validity_buffer_from_bytemask(bytemask: PolarsBuffer) -> None:
result = _construct_validity_buffer_from_bytemask(
bytemask, null_value=0, allow_copy=True
)
expected = pl.Series([False, True, True, False])
assert_series_equal(result, expected)
def test_construct_validity_buffer_from_bytemask_inverted(
bytemask: PolarsBuffer,
) -> None:
result = _construct_validity_buffer_from_bytemask(
bytemask, null_value=1, allow_copy=True
)
expected = pl.Series([True, False, False, True])
assert_series_equal(result, expected)
def test_construct_validity_buffer_from_bytemask_zero_copy_fails(
bytemask: PolarsBuffer,
) -> None:
with pytest.raises(CopyNotAllowedError):
_construct_validity_buffer_from_bytemask(
bytemask, null_value=0, allow_copy=False
)
def test_interchange_protocol_fallback(monkeypatch: pytest.MonkeyPatch) -> None:
df_pd = pd.DataFrame({"a": [1, 2, 3]})
monkeypatch.setattr(df_pd, "__arrow_c_stream__", lambda *args, **kwargs: 1 / 0)
with pytest.warns(
UserWarning, match="Falling back to Dataframe Interchange Protocol"
):
result = pl.from_dataframe(df_pd)
expected = pl.DataFrame({"a": [1, 2, 3]})
assert_frame_equal(result, expected)
def test_to_pandas_int8_20316() -> None:
df = pl.Series("a", [None], pl.Int8).to_frame()
df_pd = df.to_pandas(use_pyarrow_extension_array=True)
result = pl.from_dataframe(df_pd)
assert_frame_equal(result, df)
| PatchableColumn |
python | donnemartin__interactive-coding-challenges | bit_manipulation/bits_to_flip/test_bits_to_flip.py | {
"start": 18,
"end": 405
} | class ____(unittest.TestCase):
def test_bits_to_flip(self):
bits = Bits()
a = int('11101', base=2)
b = int('01111', base=2)
expected = 2
self.assertEqual(bits.bits_to_flip(a, b), expected)
print('Success: test_bits_to_flip')
def main():
test = TestBits()
test.test_bits_to_flip()
if __name__ == '__main__':
main()
| TestBits |
python | getsentry__sentry | src/sentry/core/endpoints/organization_member_requests_invite_index.py | {
"start": 1353,
"end": 4927
} | class ____(OrganizationEndpoint):
publish_status = {
"GET": ApiPublishStatus.UNKNOWN,
"POST": ApiPublishStatus.UNKNOWN,
}
permission_classes = (InviteRequestPermissions,)
def get(self, request: Request, organization: Organization) -> Response:
queryset = OrganizationMember.objects.filter(
Q(user_id__isnull=True),
Q(invite_status=InviteStatus.REQUESTED_TO_BE_INVITED.value)
| Q(invite_status=InviteStatus.REQUESTED_TO_JOIN.value),
organization=organization,
).order_by("invite_status", "email")
if organization.get_option("sentry:join_requests") is False:
queryset = queryset.filter(invite_status=InviteStatus.REQUESTED_TO_BE_INVITED.value)
return self.paginate(
request=request,
queryset=queryset,
on_results=lambda x: serialize(
x, request.user, OrganizationMemberWithTeamsSerializer()
),
paginator_cls=OffsetPaginator,
)
def post(self, request: Request, organization: Organization) -> Response:
"""
Add a invite request to Organization
````````````````````````````````````
Creates an invite request given an email and suggested role / teams.
:pparam string organization_id_or_slug: the id or slug of the organization the member will belong to
:param string email: the email address to invite
:param string role: the suggested role of the new member
:param string orgRole: the suggested org-role of the new member
:param array teams: the teams which the member should belong to.
:param array teamRoles: the teams and team-roles assigned to the member
:auth: required
"""
serializer = OrganizationMemberRequestSerializer(
data=request.data,
context={"organization": organization, "allowed_roles": roles.get_all()},
)
if not serializer.is_valid():
return Response(serializer.errors, status=400)
if request.access.requires_sso:
return Response(
{
"detail": "Your organization must use its single sign-on provider to register new members."
},
status=400,
)
result = serializer.validated_data
with outbox_context(
transaction.atomic(router.db_for_write(OrganizationMember)), flush=False
):
om = OrganizationMember.objects.create(
organization_id=organization.id,
role=result["role"] or organization.default_role,
email=result["email"],
inviter_id=request.user.id,
invite_status=InviteStatus.REQUESTED_TO_BE_INVITED.value,
)
# Do not set team-roles when inviting a member
if "teams" in result or "teamRoles" in result:
teams = result.get("teams") or [
item["teamSlug"] for item in result.get("teamRoles", [])
]
save_team_assignments(om, teams)
self.create_audit_entry(
request=request,
organization_id=organization.id,
target_object=om.id,
data=om.get_audit_log_data(),
event=audit_log.get_event_id("INVITE_REQUEST_ADD"),
)
async_send_notification(InviteRequestNotification, om, request.user)
return Response(serialize(om), status=201)
| OrganizationInviteRequestIndexEndpoint |
python | django__django | tests/admin_scripts/tests.py | {
"start": 51369,
"end": 53722
} | class ____(AdminScriptTestCase):
"""
Tests for manage.py when using the default settings.py file containing
runtime errors.
"""
def write_settings_with_import_error(self, filename):
settings_file_path = os.path.join(self.test_dir, filename)
with open(settings_file_path, "w") as settings_file:
settings_file.write(
"# Settings file automatically generated by admin_scripts test case\n"
)
settings_file.write(
"# The next line will cause an import error:\nimport foo42bar\n"
)
def test_import_error(self):
"""
import error: manage.py builtin commands shows useful diagnostic info
when settings with import errors is provided (#14130).
"""
self.write_settings_with_import_error("settings.py")
args = ["check", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named")
self.assertOutput(err, "foo42bar")
def test_attribute_error(self):
"""
manage.py builtin commands does not swallow attribute error due to bad
settings (#18845).
"""
self.write_settings("settings.py", sdict={"BAD_VAR": "INSTALLED_APPS.crash"})
args = ["collectstatic", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "AttributeError: 'list' object has no attribute 'crash'")
def test_key_error(self):
self.write_settings("settings.py", sdict={"BAD_VAR": 'DATABASES["blah"]'})
args = ["collectstatic", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "KeyError: 'blah'")
def test_help(self):
"""
Test listing available commands output note when only core commands are
available.
"""
self.write_settings(
"settings.py",
extra="from django.core.exceptions import ImproperlyConfigured\n"
"raise ImproperlyConfigured()",
)
args = ["help"]
out, err = self.run_manage(args)
self.assertOutput(out, "only Django core commands are listed")
self.assertNoOutput(err)
| ManageSettingsWithSettingsErrors |
python | ansible__ansible | lib/ansible/modules/hostname.py | {
"start": 25686,
"end": 25812
} | class ____(Hostname):
platform = 'Linux'
distribution = 'Alpine'
strategy_class = AlpineStrategy
| AlpineLinuxHostname |
python | pypa__setuptools | setuptools/config/_apply_pyprojecttoml.py | {
"start": 18087,
"end": 19120
} | class ____(SetuptoolsWarning):
_SUMMARY = "`{field}` defined outside of `pyproject.toml` is ignored."
_DETAILS = """
The following seems to be defined outside of `pyproject.toml`:
`{field} = {value!r}`
According to the spec (see the link below), however, setuptools CANNOT
consider this value unless `{field}` is listed as `dynamic`.
https://packaging.python.org/en/latest/specifications/pyproject-toml/#declaring-project-metadata-the-project-table
To prevent this problem, you can list `{field}` under `dynamic` or alternatively
remove the `[project]` table from your file and rely entirely on other means of
configuration.
"""
# TODO: Consider removing this check in the future?
# There is a trade-off here between improving "debug-ability" and the cost
# of running/testing/maintaining these unnecessary checks...
@classmethod
def details(cls, field: str, value: Any) -> str:
return cls._DETAILS.format(field=field, value=value)
| _MissingDynamic |
python | apache__airflow | providers/google/tests/unit/google/common/hooks/test_base_google.py | {
"start": 14931,
"end": 31582
} | class ____:
def setup_method(self):
self.instance = hook.GoogleBaseHook()
@mock.patch(MODULE_NAME + ".get_credentials_and_project_id", return_value=("CREDENTIALS", "PROJECT_ID"))
def test_get_credentials_and_project_id_with_default_auth(self, mock_get_creds_and_proj_id):
self.instance.extras = {}
result = self.instance.get_credentials_and_project_id()
mock_get_creds_and_proj_id.assert_called_once_with(
key_path=None,
keyfile_dict=None,
credential_config_file=None,
key_secret_name=None,
key_secret_project_id=None,
scopes=self.instance.scopes,
target_principal=None,
delegates=None,
is_anonymous=None,
idp_issuer_url=None,
client_id=None,
client_secret=None,
idp_extra_params_dict=None,
)
assert result == ("CREDENTIALS", "PROJECT_ID")
@mock.patch("requests.post")
@mock.patch(MODULE_NAME + ".get_credentials_and_project_id")
def test_connection_success(self, mock_get_creds_and_proj_id, requests_post):
requests_post.return_value.status_code = 200
credentials = mock.MagicMock()
type(credentials).token = mock.PropertyMock(return_value="TOKEN")
mock_get_creds_and_proj_id.return_value = (credentials, "PROJECT_ID")
self.instance.extras = {}
result = self.instance.test_connection()
assert result == (True, "Connection successfully tested")
@mock.patch(MODULE_NAME + ".get_credentials_and_project_id")
def test_connection_failure(self, mock_get_creds_and_proj_id):
mock_get_creds_and_proj_id.side_effect = AirflowException("Invalid key JSON.")
self.instance.extras = {}
result = self.instance.test_connection()
assert result == (False, "Invalid key JSON.")
@mock.patch(MODULE_NAME + ".get_credentials_and_project_id")
def test_get_credentials_and_project_id_with_service_account_file(self, mock_get_creds_and_proj_id):
mock_credentials = mock.MagicMock()
mock_get_creds_and_proj_id.return_value = (mock_credentials, "PROJECT_ID")
self.instance.extras = {"key_path": "KEY_PATH.json"}
result = self.instance.get_credentials_and_project_id()
mock_get_creds_and_proj_id.assert_called_once_with(
key_path="KEY_PATH.json",
keyfile_dict=None,
credential_config_file=None,
key_secret_name=None,
key_secret_project_id=None,
scopes=self.instance.scopes,
target_principal=None,
delegates=None,
is_anonymous=None,
idp_issuer_url=None,
client_id=None,
client_secret=None,
idp_extra_params_dict=None,
)
assert (mock_credentials, "PROJECT_ID") == result
def test_get_credentials_and_project_id_with_service_account_file_and_p12_key(self):
self.instance.extras = {"key_path": "KEY_PATH.p12"}
with pytest.raises(AirflowException):
self.instance.get_credentials_and_project_id()
def test_get_credentials_and_project_id_with_service_account_file_and_unknown_key(self):
self.instance.extras = {"key_path": "KEY_PATH.unknown"}
with pytest.raises(AirflowException):
self.instance.get_credentials_and_project_id()
@mock.patch(MODULE_NAME + ".get_credentials_and_project_id")
def test_get_credentials_and_project_id_with_service_account_info(self, mock_get_creds_and_proj_id):
mock_credentials = mock.MagicMock()
mock_get_creds_and_proj_id.return_value = (mock_credentials, "PROJECT_ID")
service_account = {"private_key": "PRIVATE_KEY"}
self.instance.extras = {"keyfile_dict": json.dumps(service_account)}
result = self.instance.get_credentials_and_project_id()
mock_get_creds_and_proj_id.assert_called_once_with(
key_path=None,
keyfile_dict=service_account,
credential_config_file=None,
key_secret_name=None,
key_secret_project_id=None,
scopes=self.instance.scopes,
target_principal=None,
delegates=None,
is_anonymous=None,
idp_issuer_url=None,
client_id=None,
client_secret=None,
idp_extra_params_dict=None,
)
assert (mock_credentials, "PROJECT_ID") == result
@mock.patch(MODULE_NAME + ".get_credentials_and_project_id")
def test_get_credentials_and_project_id_with_default_auth_and_delegate(self, mock_get_creds_and_proj_id):
mock_credentials = mock.MagicMock()
mock_get_creds_and_proj_id.return_value = (mock_credentials, "PROJECT_ID")
self.instance.extras = {}
result = self.instance.get_credentials_and_project_id()
mock_get_creds_and_proj_id.assert_called_once_with(
key_path=None,
keyfile_dict=None,
credential_config_file=None,
key_secret_name=None,
key_secret_project_id=None,
scopes=self.instance.scopes,
target_principal=None,
delegates=None,
is_anonymous=None,
idp_issuer_url=None,
client_id=None,
client_secret=None,
idp_extra_params_dict=None,
)
assert (mock_credentials, "PROJECT_ID") == result
@mock.patch(MODULE_NAME + ".get_credentials_and_project_id", return_value=("CREDENTIALS", "PROJECT_ID"))
def test_get_credentials_and_project_id_with_default_auth_and_overridden_project_id(
self, mock_get_creds_and_proj_id
):
self.instance.extras = {"project": "SECOND_PROJECT_ID"}
result = self.instance.get_credentials_and_project_id()
mock_get_creds_and_proj_id.assert_called_once_with(
key_path=None,
keyfile_dict=None,
credential_config_file=None,
key_secret_name=None,
key_secret_project_id=None,
scopes=self.instance.scopes,
target_principal=None,
delegates=None,
is_anonymous=None,
idp_issuer_url=None,
client_id=None,
client_secret=None,
idp_extra_params_dict=None,
)
assert result == ("CREDENTIALS", "SECOND_PROJECT_ID")
def test_get_credentials_and_project_id_with_mutually_exclusive_configuration(self):
self.instance.extras = {
"project": "PROJECT_ID",
"key_path": "KEY_PATH",
"keyfile_dict": '{"KEY": "VALUE"}',
}
with pytest.raises(AirflowException, match="mutually exclusive"):
self.instance.get_credentials_and_project_id()
def test_get_credentials_and_project_id_with_invalid_keyfile_dict(self):
self.instance.extras = {
"keyfile_dict": "INVALID_DICT",
}
with pytest.raises(AirflowException, match=re.escape("Invalid key JSON.")):
self.instance.get_credentials_and_project_id()
@mock.patch(MODULE_NAME + ".get_credentials_and_project_id", return_value=("CREDENTIALS", ""))
def test_get_credentials_and_project_id_with_is_anonymous(self, mock_get_creds_and_proj_id):
self.instance.extras = {
"is_anonymous": True,
}
self.instance.get_credentials_and_project_id()
mock_get_creds_and_proj_id.assert_called_once_with(
key_path=None,
keyfile_dict=None,
credential_config_file=None,
key_secret_name=None,
key_secret_project_id=None,
scopes=self.instance.scopes,
target_principal=None,
delegates=None,
is_anonymous=True,
idp_issuer_url=None,
client_id=None,
client_secret=None,
idp_extra_params_dict=None,
)
@pytest.mark.skipif(
not default_creds_available, reason="Default Google Cloud credentials not available to run tests"
)
def test_default_creds_with_scopes(self):
self.instance.extras = {
"project": default_project,
"scope": (
"https://www.googleapis.com/auth/bigquery,https://www.googleapis.com/auth/devstorage.read_only"
),
}
credentials = self.instance.get_credentials()
if not hasattr(credentials, "scopes") or credentials.scopes is None:
# Some default credentials don't have any scopes associated with
# them, and that's okay.
return
scopes = credentials.scopes
assert "https://www.googleapis.com/auth/bigquery" in scopes
assert "https://www.googleapis.com/auth/devstorage.read_only" in scopes
@pytest.mark.skipif(
not default_creds_available, reason="Default Google Cloud credentials not available to run tests"
)
def test_default_creds_no_scopes(self):
self.instance.extras = {"project": default_project}
credentials = self.instance.get_credentials()
if not hasattr(credentials, "scopes") or credentials.scopes is None:
# Some default credentials don't have any scopes associated with
# them, and that's okay.
return
scopes = credentials.scopes
assert tuple(_DEFAULT_SCOPES) == tuple(scopes)
def test_provide_gcp_credential_file_decorator_key_path(self):
key_path = "/test/key-path"
self.instance.extras = {"key_path": key_path}
@hook.GoogleBaseHook.provide_gcp_credential_file
def assert_gcp_credential_file_in_env(hook_instance):
assert os.environ[CREDENTIALS] == key_path
assert_gcp_credential_file_in_env(self.instance)
@mock.patch("tempfile.NamedTemporaryFile")
def test_provide_gcp_credential_file_decorator_key_content(self, mock_file):
string_file = StringIO()
file_content = '{"foo": "bar"}'
file_name = "/test/mock-file"
self.instance.extras = {"keyfile_dict": file_content}
mock_file_handler = mock_file.return_value.__enter__.return_value
mock_file_handler.name = file_name
mock_file_handler.write = string_file.write
@hook.GoogleBaseHook.provide_gcp_credential_file
def assert_gcp_credential_file_in_env(hook_instance):
assert os.environ[CREDENTIALS] == file_name
assert file_content == string_file.getvalue()
assert_gcp_credential_file_in_env(self.instance)
def test_provided_scopes(self):
self.instance.extras = {
"project": default_project,
"scope": (
"https://www.googleapis.com/auth/bigquery,https://www.googleapis.com/auth/devstorage.read_only"
),
}
assert self.instance.scopes == [
"https://www.googleapis.com/auth/bigquery",
"https://www.googleapis.com/auth/devstorage.read_only",
]
def test_default_scopes(self):
self.instance.extras = {"project": default_project}
assert self.instance.scopes == ("https://www.googleapis.com/auth/cloud-platform",)
@mock.patch("airflow.providers.google.common.hooks.base_google.GoogleBaseHook.get_connection")
def test_num_retries_is_not_none_by_default(self, get_con_mock):
"""
Verify that if 'num_retries' in extras is not set, the default value
should not be None
"""
get_con_mock.return_value.extra_dejson = {"num_retries": None}
assert self.instance.num_retries == 5
@mock.patch("airflow.providers.google.common.hooks.base_google.build_http")
@mock.patch("airflow.providers.google.common.hooks.base_google.GoogleBaseHook.get_credentials")
def test_authorize_assert_user_agent_is_sent(self, mock_get_credentials, mock_http):
"""
Verify that if 'num_retires' in extras is not set, the default value
should not be None
"""
request = mock_http.return_value.request
response = mock.MagicMock(status_code=200)
content = "CONTENT"
mock_http.return_value.request.return_value = response, content
new_response, new_content = self.instance._authorize().request("/test-action")
request.assert_called_once_with(
"/test-action",
body=None,
connection_type=None,
headers={"user-agent": "airflow/" + version.version},
method="GET",
redirections=5,
)
assert response == new_response
assert content == new_content
@mock.patch("airflow.providers.google.common.hooks.base_google.GoogleBaseHook.get_credentials")
def test_authorize_assert_http_308_is_excluded(self, mock_get_credentials):
"""
Verify that 308 status code is excluded from httplib2's redirect codes
"""
http_authorized = self.instance._authorize().http
assert 308 not in http_authorized.redirect_codes
@mock.patch("airflow.providers.google.common.hooks.base_google.GoogleBaseHook.get_credentials")
def test_authorize_assert_http_timeout_is_present(self, mock_get_credentials):
"""
Verify that http client has a timeout set
"""
http_authorized = self.instance._authorize().http
assert http_authorized.timeout is not None
@pytest.mark.parametrize(
("impersonation_chain", "impersonation_chain_from_conn", "target_principal", "delegates"),
[
pytest.param("ACCOUNT_1", None, "ACCOUNT_1", None, id="string"),
pytest.param(None, "ACCOUNT_1", "ACCOUNT_1", None, id="string_in_conn"),
pytest.param("ACCOUNT_2", "ACCOUNT_1", "ACCOUNT_2", None, id="string_with_override"),
pytest.param(["ACCOUNT_1"], None, "ACCOUNT_1", [], id="single_element_list"),
pytest.param(None, ["ACCOUNT_1"], "ACCOUNT_1", [], id="single_element_list_in_conn"),
pytest.param(
["ACCOUNT_1"], ["ACCOUNT_2"], "ACCOUNT_1", [], id="single_element_list_with_override"
),
pytest.param(
["ACCOUNT_1", "ACCOUNT_2", "ACCOUNT_3"],
None,
"ACCOUNT_3",
["ACCOUNT_1", "ACCOUNT_2"],
id="multiple_elements_list",
),
pytest.param(
None,
["ACCOUNT_1", "ACCOUNT_2", "ACCOUNT_3"],
"ACCOUNT_3",
["ACCOUNT_1", "ACCOUNT_2"],
id="multiple_elements_list_in_conn",
),
pytest.param(
["ACCOUNT_2", "ACCOUNT_3", "ACCOUNT_4"],
["ACCOUNT_1", "ACCOUNT_2", "ACCOUNT_3"],
"ACCOUNT_4",
["ACCOUNT_2", "ACCOUNT_3"],
id="multiple_elements_list_with_override",
),
pytest.param(
None,
"ACCOUNT_1,ACCOUNT_2,ACCOUNT_3",
"ACCOUNT_3",
["ACCOUNT_1", "ACCOUNT_2"],
id="multiple_elements_list_as_string",
),
pytest.param(
None,
"ACCOUNT_1, ACCOUNT_2, ACCOUNT_3",
"ACCOUNT_3",
["ACCOUNT_1", "ACCOUNT_2"],
id="multiple_elements_list_as_string_with_space",
),
],
)
@mock.patch(MODULE_NAME + ".get_credentials_and_project_id")
def test_get_credentials_and_project_id_with_impersonation_chain(
self,
mock_get_creds_and_proj_id,
impersonation_chain,
impersonation_chain_from_conn,
target_principal,
delegates,
):
mock_credentials = mock.MagicMock()
mock_get_creds_and_proj_id.return_value = (mock_credentials, PROJECT_ID)
self.instance.impersonation_chain = impersonation_chain
self.instance.extras = {"impersonation_chain": impersonation_chain_from_conn}
result = self.instance.get_credentials_and_project_id()
mock_get_creds_and_proj_id.assert_called_once_with(
key_path=None,
keyfile_dict=None,
credential_config_file=None,
key_secret_name=None,
key_secret_project_id=None,
scopes=self.instance.scopes,
target_principal=target_principal,
delegates=delegates,
is_anonymous=None,
idp_issuer_url=None,
client_id=None,
client_secret=None,
idp_extra_params_dict=None,
)
assert (mock_credentials, PROJECT_ID) == result
| TestGoogleBaseHook |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/comms.py | {
"start": 25678,
"end": 25950
} | class ____(BaseModel):
key: str
dag_id: str
run_id: str
task_id: str
start: int | None
stop: int | None
step: int | None
include_prior_dates: bool = False
type: Literal["GetXComSequenceSlice"] = "GetXComSequenceSlice"
| GetXComSequenceSlice |
python | bokeh__bokeh | src/bokeh/core/property_mixins.py | {
"start": 7421,
"end": 7993
} | class ____(HasProps):
''' Properties relevant to rendering fill regions.
Mirrors the BokehJS ``properties.HatchVector`` class.
'''
hatch_color = ColorSpec(default="black", help=_color_help % "hatching")
hatch_alpha = AlphaSpec(help=_alpha_help % "hatching")
hatch_scale = FloatSpec(default=12.0, help=_hatch_scale_help)
hatch_pattern = HatchPatternSpec(default=None, help=_hatch_pattern_help)
hatch_weight = FloatSpec(default=1.0, help=_hatch_weight_help)
hatch_extra = Dict(String, Instance("bokeh.models.textures.Texture"))
| HatchProps |
python | jazzband__django-pipeline | pipeline/storage.py | {
"start": 3030,
"end": 3077
} | class ____:
packing = False
| NonPackagingMixin |
python | google__jax | tests/pallas/triton_pallas_test.py | {
"start": 1864,
"end": 17089
} | class ____(PallasBaseTest):
INTERPRET = False
@parameterized.product(src_dtype=DTYPE_LIST, dst_dtype=DTYPE_LIST)
def test_fp_dtype_cast(self, src_dtype, dst_dtype):
if src_dtype == dst_dtype:
self.skipTest("No need to test the same dtype")
if dtypes.itemsize_bits(src_dtype) == 8 and dtypes.itemsize_bits(dst_dtype) == 8:
self.skipTest("Not casting between 8-bit types")
def body(x_ref, y_ref):
y_ref[...] = x_ref[...].astype(dst_dtype)
x = 10 * jax.random.normal(jax.random.key(0), (64, 64), dtype=src_dtype)
y = self.pallas_call(body,
in_specs=[pl.BlockSpec((64, 64), lambda i: (0, 0))],
out_specs=pl.BlockSpec((64, 64), lambda i: (0, 0)),
out_shape=jax.ShapeDtypeStruct((64, 64), dst_dtype),
grid=(1,),
)(x)
self.assertEqual(y.dtype, dst_dtype)
self.assertArraysEqual(y, x.astype(dst_dtype))
@parameterized.named_parameters(
("add_i32", "atomic_add", np.array([1, 2, 3, 4], np.int32), np.sum),
("max_i32", "atomic_max", np.array([1, 2, 3, 4], np.int32), np.max),
("min_i32", "atomic_min", np.array([1, 2, 3, 4], np.int32), np.min),
("add_f16", "atomic_add", np.array([1, 2, 3, 4], np.float16), np.sum),
("add_f32", "atomic_add", np.array([1, 2, 3, 4], np.float32), np.sum),
("max_f32", "atomic_max", np.array([1, 2, 3, 4], np.float32), np.max),
("min_f32", "atomic_min", np.array([1, 2, 3, 4], np.float32), np.min),
)
def test_scalar_atomic(self, op, value, numpy_op):
if plgpu is None:
self.skipTest("plgpu not available on this platform.")
op = getattr(plgpu, op)
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct((), value.dtype),
grid=value.shape[0],
input_output_aliases={1: 0},
)
def atomic_kernel(x_ref, _, o_ref):
pid = pl.program_id(axis=0)
op(o_ref, (), x_ref[pid])
if op == plgpu.atomic_add:
neutral = np.array(0, dtype=value.dtype)
elif op == plgpu.atomic_max:
if np.issubdtype(value.dtype, np.integer):
neutral = np.array(np.iinfo(value.dtype).min, value.dtype)
else:
neutral = np.array(-float("inf"), value.dtype)
elif op == plgpu.atomic_min:
if np.issubdtype(value.dtype, np.integer):
neutral = np.array(np.iinfo(value.dtype).max, value.dtype)
else:
neutral = np.array(float("inf"), value.dtype)
elif op == plgpu.atomic_or:
neutral = np.array(False, value.dtype)
else:
raise NotImplementedError()
out = atomic_kernel(value, neutral)
np.testing.assert_allclose(out, numpy_op(value))
@parameterized.parameters((0,), (1,))
def test_array_atomic_add(self, axis):
m, n = 32, 8
if axis == 0:
grid = m
else:
grid = n
out_shape = jax.ShapeDtypeStruct((n if axis == 0 else m,), floatx)
@functools.partial(
self.pallas_call,
out_shape=out_shape,
grid=grid,
input_output_aliases={1: 0},
)
def reduce(x_ref, _, y_ref):
i = pl.program_id(axis=0)
if axis == 0:
idx = (i, jnp.arange(n))
else:
idx = (jnp.arange(m), i)
x = x_ref[idx]
plgpu.atomic_add(y_ref, (jnp.arange(y.shape[0]),), x)
x = jax.random.normal(jax.random.key(0), (m, n))
y = jnp.zeros(out_shape.shape, out_shape.dtype)
y = reduce(x, y)
y_ref = np.sum(x, axis=axis)
np.testing.assert_allclose(y, y_ref, atol=1e-2, rtol=1e-2)
@parameterized.parameters(
(0, 0, 1),
(0, 1, 1),
(1, 0, 1),
(1, 1, 1),
(2, 1, 1),
(2, 1, 1),
)
def test_atomic_cas(self, init_value, cmp, new_value):
if jax.config.x64_enabled:
self.skipTest("Not supported in 64-bit mode")
@functools.partial(
self.pallas_call,
out_shape=(
jax.ShapeDtypeStruct((), intx),
jax.ShapeDtypeStruct((), intx),
),
input_output_aliases={0: 0},
)
def swap(_, lock_ref, out_ref):
out_ref[()] = plgpu.atomic_cas(lock_ref, cmp, new_value)
lock, out = swap(init_value)
np.testing.assert_allclose(
lock, new_value if cmp == init_value else init_value
)
np.testing.assert_allclose(out, init_value)
@parameterized.parameters(1, 2, 3, 4, 8)
def test_atomic_counter(self, num_threads):
if self.INTERPRET:
self.skipTest("While loop not supported in interpret mode.")
if jax.config.x64_enabled:
self.skipTest("Not supported in 64-bit mode")
@functools.partial(
self.pallas_call,
out_shape=(
jax.ShapeDtypeStruct((), intx),
jax.ShapeDtypeStruct((), intx),
),
input_output_aliases={0: 0, 1: 1},
grid=(num_threads,),
)
def increment(_, __, lock_ref, counter_ref):
def _cond(_):
return plgpu.atomic_cas(lock_ref, 0, 1) == 1
lax.while_loop(_cond, lambda a: a, 0)
counter_ref[...] += 1
plgpu.atomic_xchg(lock_ref, (), 0)
lock, count = increment(0, 0)
np.testing.assert_allclose(lock, 0)
np.testing.assert_allclose(count, num_threads)
@parameterized.product(
size=[1, 2, 64, 129, 1021],
block_size=[1, 2, 32, 64, 128],
)
def test_masked_load_store(self, size, block_size):
@functools.partial(
self.pallas_call,
out_shape=(jax.ShapeDtypeStruct((size,), floatx)),
grid=pl.cdiv(size, block_size),
)
def kernel(x_ref, o_ref):
idx = pl.program_id(0) * block_size + jnp.arange(
block_size, dtype=jnp.int32
)
mask = idx < x_ref.shape[0]
x = plgpu.load(x_ref.at[idx], mask=mask)
plgpu.store(o_ref.at[idx], x + 1.0, mask=mask)
key = jax.random.key(0)
x = jax.random.normal(key, (size,))
np.testing.assert_allclose(kernel(x), x + 1.0, atol=1e-5, rtol=1e-5)
def test_masked_oob_load_store_slice(self):
n = 16
@functools.partial(
self.pallas_call,
out_shape=(jax.ShapeDtypeStruct((n,), floatx)),
)
def masked_oob_load_store_slice(x_ref, mask_ref, start_idx_ref, o_ref):
x = plgpu.load(
x_ref.at[pl.ds(start_idx_ref[()], n)], mask=mask_ref[:], other=-1.0
)
o_ref[...] = x
x = jax.random.normal(jax.random.key(0), (n,))
slice_start = jax.random.randint(jax.random.key(2), (), 1, n)
indices = jnp.arange(n) + slice_start
mask = indices < n
out = masked_oob_load_store_slice(x, mask, slice_start)
o_new = jnp.where(mask, x[indices], jnp.full_like(x, -1.0))
np.testing.assert_array_equal(out, o_new)
@parameterized.parameters(
((16, 32), (16,)),
((16, 32), (32,)),
((16, 32), (16, 16)),
)
def test_invalid_broadcasted_load(self, x_shape, mask_shape):
if self.INTERPRET:
self.skipTest("No broadcasting checks in pl.load in interpret mode")
@functools.partial(
self.pallas_call, out_shape=jax.ShapeDtypeStruct((), jnp.float32)
)
def kernel(x_ref, mask_ref, o_ref):
del o_ref # Unused.
plgpu.load(x_ref, mask=mask_ref[:])
x = jnp.ones(x_shape, dtype=jnp.float32)
mask = jnp.ones(mask_shape, dtype=jnp.bool_)
# assertRaises* methods do not support inspecting the __cause__, so
# we have to check it manually.
try:
kernel(x, mask)
except Exception as e:
self.assertIn("Cannot broadcast", str(e.__cause__))
else:
self.fail("Expected exception due to invalid broadcasting")
@parameterized.parameters("float16", "bfloat16", "float32")
def test_approx_tanh(self, dtype):
if self.INTERPRET:
self.skipTest("approx_tanh is not supported in interpret mode")
if (dtype == "bfloat16" and
not jtu.is_cuda_compute_capability_at_least("9.0")):
self.skipTest("tanh.approx.bf16 requires a GPU with capability >= sm90")
@functools.partial(
self.pallas_call, out_shape=jax.ShapeDtypeStruct((4,), dtype),
)
def kernel(x_ref, o_ref):
o_ref[...] = plgpu.approx_tanh(x_ref[...])
x = jnp.asarray([-1, 0.42, 0.24, 1]).astype(dtype)
# We upcast to float32 because NumPy <2.0 does not handle custom dtypes
# properly. See https://github.com/jax-ml/jax/issues/11014.
np.testing.assert_allclose(
kernel(x).astype(jnp.float32),
jnp.tanh(x).astype(jnp.float32),
atol=5e-3,
rtol=5e-3,
)
def test_elementwise_inline_asm(self):
if self.INTERPRET:
self.skipTest(
"elementwise_inline_asm is not supported in interpret mode"
)
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct((256,), jnp.float16),
)
def kernel(x_ref, o_ref):
[o_ref[...]] = plgpu.elementwise_inline_asm(
"tanh.approx.f16x2 $0, $1;",
args=[x_ref[...]],
constraints="=r,r",
pack=2,
result_shape_dtypes=[jax.ShapeDtypeStruct(x_ref.shape, x_ref.dtype)],
)
x = jnp.arange(256).astype(jnp.float16)
np.testing.assert_allclose(kernel(x), jnp.tanh(x), atol=5e-3, rtol=5e-3)
def test_debug_barrier(self):
if self.INTERPRET:
self.skipTest("debug_barrier is not supported in interpret mode")
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct((2,), jnp.float32),
)
def kernel(x_ref, o_ref):
o_ref[...] = x_ref[...]
plgpu.debug_barrier()
x = jnp.array([4.2, 2.4]).astype(jnp.float32)
np.testing.assert_array_equal(kernel(x), x)
@unittest.skipIf(
sys.platform == "win32",
"plgpu.CompilerParams unavailable on Windows",
)
def test_debug_print(self):
if jtu.test_device_matches(["gpu"]):
self.skipTest("This test flakes on gpu")
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct((2,), jnp.float32),
compiler_params=plgpu.CompilerParams(
num_warps=1, num_stages=1
),
)
def kernel(x_ref, o_ref):
pl.debug_print("It works!")
x = jnp.array([4.2, 2.4]).astype(jnp.float32)
with jtu.capture_stdout() as output:
jax.block_until_ready(kernel(x))
jax.effects_barrier()
self.assertIn("It works!", output())
@unittest.skipIf(
sys.platform == "win32",
"plgpu.CompilerParams unavailable on Windows",
)
def test_debug_print_with_values(self):
if jtu.test_device_matches(["gpu"]):
self.skipTest("This test flakes on gpu")
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct((2,), jnp.float32),
compiler_params=plgpu.CompilerParams(
num_warps=1, num_stages=1
),
)
def kernel(x_ref, o_ref):
pl.debug_print("x[0] =", x_ref[0])
x = jnp.array([4.2, 2.4]).astype(jnp.float32)
with jtu.capture_stdout() as output:
jax.block_until_ready(kernel(x))
jax.effects_barrier()
self.assertIn("x[0] = 4.2", output())
@parameterized.named_parameters(*[
(f"m_{m}_n_{n}_k_{k}_dtype_{dtype}_bm_{block_size_m}_"
f"bn_{block_size_n}_bk_{block_size_k}_gm_{group_size_m}", m, n, k, dtype,
block_size_m, block_size_n, block_size_k, group_size_m)
for m in [512, 1024]
for k in [512]
for n in [512, 1024]
for dtype in ["float32", "float16"]
for block_size_m in [64, 128]
for block_size_n in [64, 128]
for block_size_k in [32]
for group_size_m in [8]
if block_size_m <= m and block_size_n <= n and block_size_k <= k
])
def test_matmul(self, m, n, k, dtype, bm, bn, bk, gm):
if jtu.test_device_matches(["tpu"]) and not self.INTERPRET:
self.skipTest("On TPU the test works only in interpret mode")
k1, k2 = jax.random.split(jax.random.key(0))
x = jax.random.normal(k1, (m, k), dtype=dtype)
y = jax.random.normal(k2, (k, n), dtype=dtype)
out = matmul(x, y, bm=bm, bn=bn, bk=bk, gm=gm,
interpret=self.INTERPRET)
expected = jnp.matmul(
x, y, preferred_element_type=jnp.float32).astype(dtype)
np.testing.assert_allclose(out, expected, atol=0.05, rtol=0.05)
@parameterized.named_parameters(*(
dict(
testcase_name=f"{batch_size}_{size}_{block_size}_{dtype}",
batch_size=batch_size,
size=size,
block_size=block_size,
dtype=dtype,
)
for batch_size in [1, 2, 4, 23]
for size in [1, 2, 129, 255, 256]
for block_size in [1, 2, 32, 64, 128, 256]
for dtype in ["float32"]
if size < block_size
))
def test_softmax(self, batch_size, size, block_size, dtype):
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct((batch_size, size), dtype),
grid=batch_size,
)
def softmax(x_ref, o_ref):
row_idx = pl.program_id(0)
x_idx = jnp.arange(block_size)
row_idxs = (row_idx, x_idx)
mask = x_idx < x_ref.shape[1]
row = plgpu.load(x_ref.at[row_idxs], mask=mask, other=-float("inf"))
row_minus_max = row - jnp.max(row, axis=0)
numerator = jnp.exp(row_minus_max)
denominator = jnp.sum(numerator, axis=0)
softmax_output = numerator / denominator
plgpu.store(o_ref.at[row_idxs], softmax_output, mask=mask)
key = jax.random.key(0)
x = jax.random.normal(key, [batch_size, size], dtype=dtype)
np.testing.assert_allclose(
softmax(x), jax.nn.softmax(x, axis=-1), atol=1e-5, rtol=1e-5
)
@functools.partial(
jax.jit, static_argnames=["bm", "bn", "gm", "bk", "interpret", "debug"]
)
def matmul(x, y, *, bm, bn, gm, bk, interpret, debug=False):
m, n, k = x.shape[0], y.shape[1], x.shape[1]
@functools.partial(
pl.pallas_call,
out_shape=jax.ShapeDtypeStruct((m, n), jnp.float32),
interpret=interpret,
debug=debug,
grid=pl.cdiv(m, bm) * pl.cdiv(n, bn),
)
def matmul_kernel(x_ref, y_ref, o_ref):
pid = pl.program_id(axis=0).astype(intx)
num_pid_m = m // bm
num_pid_n = n // bn
num_pid_in_group = gm * num_pid_n
group_id = lax.div(pid, num_pid_in_group)
first_pid_m = group_id * gm
group_size_m = jnp.minimum(num_pid_m - first_pid_m, gm)
pid_m = first_pid_m + lax.rem(pid, group_size_m)
pid_n = lax.div(lax.rem(pid, num_pid_in_group), group_size_m)
idx_m = pid_m * bm + jnp.arange(bm)
idx_n = pid_n * bn + jnp.arange(bn)
idx_m = plgpu.max_contiguous(pl.multiple_of(idx_m, bm), bm)
idx_n = plgpu.max_contiguous(pl.multiple_of(idx_n, bn), bn)
acc = jnp.zeros((bm, bn), dtype=jnp.float32)
def body(i, acc):
idx_k = i * bk + jnp.arange(bk)
x_idx = (
lax.broadcast_in_dim(idx_m, (bm, bk), (0,)),
lax.broadcast_in_dim(idx_k, (bm, bk), (1,)),
)
y_idx = (
lax.broadcast_in_dim(idx_k, (bk, bn), (0,)),
lax.broadcast_in_dim(idx_n, (bk, bn), (1,)),
)
x_block, y_block = x_ref[x_idx], y_ref[y_idx]
out = pl.dot(x_block, y_block)
return acc + out
acc = lax.fori_loop(0, k // bk, body, acc).astype(o_ref.dtype)
o_idx = (
lax.broadcast_in_dim(idx_m, (bm, bn), (0,)),
lax.broadcast_in_dim(idx_n, (bm, bn), (1,)),
)
o_ref[o_idx] = acc
return matmul_kernel(x, y)
if __name__ == "__main__":
absltest.main()
| TritonPallasTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/isinstance5.py | {
"start": 292,
"end": 392
} | class ____(Protocol):
name: str
def method1(self) -> int: ...
@runtime_checkable
| DataProtocol |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/rich/traceback.py | {
"start": 6878,
"end": 7070
} | class ____:
exc_type: str
exc_value: str
syntax_error: Optional[_SyntaxError] = None
is_cause: bool = False
frames: List[Frame] = field(default_factory=list)
@dataclass
| Stack |
python | cython__cython | Demos/benchmarks/bm_richards_cclass.py | {
"start": 1106,
"end": 1189
} | class ____(TaskRec):
def __init__(self):
self.pending = None
| DeviceTaskRec |
python | mkdocstrings__mkdocstrings | src/mkdocstrings/_internal/plugin.py | {
"start": 2970,
"end": 12397
} | class ____(BasePlugin[PluginConfig]):
"""An `mkdocs` plugin.
This plugin defines the following event hooks:
- `on_config`
- `on_env`
- `on_post_build`
Check the [Developing Plugins](https://www.mkdocs.org/user-guide/plugins/#developing-plugins) page of `mkdocs`
for more information about its plugin system.
"""
css_filename: str = "assets/_mkdocstrings.css"
"""The path of the CSS file to write in the site directory."""
def __init__(self) -> None:
"""Initialize the object."""
super().__init__()
self._handlers: Handlers | None = None
@property
def handlers(self) -> Handlers:
"""Get the instance of [mkdocstrings.Handlers][] for this plugin/build.
Raises:
RuntimeError: If the plugin hasn't been initialized with a config.
Returns:
An instance of [mkdocstrings.Handlers][] (the same throughout the build).
"""
if not self._handlers:
raise RuntimeError("The plugin hasn't been initialized with a config yet")
return self._handlers
def on_config(self, config: MkDocsConfig) -> MkDocsConfig | None:
"""Instantiate our Markdown extension.
Hook for the [`on_config` event](https://www.mkdocs.org/user-guide/plugins/#on_config).
In this hook, we instantiate our [`MkdocstringsExtension`][mkdocstrings.MkdocstringsExtension]
and add it to the list of Markdown extensions used by `mkdocs`.
We pass this plugin's configuration dictionary to the extension when instantiating it (it will need it
later when processing markdown to get handlers and their global configurations).
Arguments:
config: The MkDocs config object.
Returns:
The modified config.
"""
if not self.plugin_enabled:
_logger.debug("Plugin is not enabled. Skipping.")
return config
_logger.debug("Adding extension to the list")
locale = self.config.locale or config.theme.get("language") or config.theme.get("locale") or "en"
locale = str(locale).replace("_", "-")
handlers = Handlers(
default=self.config.default_handler,
handlers_config=self.config.handlers,
theme=config.theme.name or os.path.dirname(config.theme.dirs[0]),
custom_templates=self.config.custom_templates,
mdx=config.markdown_extensions,
mdx_config=config.mdx_configs,
inventory_project=config.site_name,
inventory_version="0.0.0", # TODO: Find a way to get actual version.
locale=locale,
tool_config=config,
)
handlers._download_inventories()
AutorefsPlugin.record_backlinks = True
autorefs: AutorefsPlugin
try:
# If autorefs plugin is explicitly enabled, just use it.
autorefs = config.plugins["autorefs"] # type: ignore[assignment]
_logger.debug("Picked up existing autorefs instance %r", autorefs)
except KeyError:
# Otherwise, add a limited instance of it that acts only on what's added through `register_anchor`.
autorefs = AutorefsPlugin()
autorefs.config = AutorefsConfig()
autorefs.scan_toc = False
config.plugins["autorefs"] = autorefs
_logger.debug("Added a subdued autorefs instance %r", autorefs)
mkdocstrings_extension = MkdocstringsExtension(handlers, autorefs)
config.markdown_extensions.append(mkdocstrings_extension) # type: ignore[arg-type]
config.extra_css.insert(0, self.css_filename) # So that it has lower priority than user files.
self._autorefs = autorefs
self._handlers = handlers
return config
@property
def inventory_enabled(self) -> bool:
"""Tell if the inventory is enabled or not.
Returns:
Whether the inventory is enabled.
"""
inventory_enabled = self.config.enable_inventory
if inventory_enabled is None:
inventory_enabled = any(handler.enable_inventory for handler in self.handlers.seen_handlers)
return inventory_enabled
@property
def plugin_enabled(self) -> bool:
"""Tell if the plugin is enabled or not.
Returns:
Whether the plugin is enabled.
"""
return self.config.enabled
@event_priority(50) # Early, before autorefs' starts applying cross-refs and collecting backlinks.
def _on_env_load_inventories(self, env: Environment, config: MkDocsConfig, *args: Any, **kwargs: Any) -> None: # noqa: ARG002
if self.plugin_enabled and self._handlers:
register = config.plugins["autorefs"].register_url # type: ignore[attr-defined]
for identifier, url in self._handlers._yield_inventory_items():
register(identifier, url)
@event_priority(-20) # Late, not important.
def _on_env_add_css(self, env: Environment, config: MkDocsConfig, *args: Any, **kwargs: Any) -> None: # noqa: ARG002
if self.plugin_enabled and self._handlers:
css_content = "\n".join(handler.extra_css for handler in self.handlers.seen_handlers)
write_file(css_content.encode("utf-8"), os.path.join(config.site_dir, self.css_filename))
@event_priority(-20) # Late, not important.
def _on_env_write_inventory(self, env: Environment, config: MkDocsConfig, *args: Any, **kwargs: Any) -> None: # noqa: ARG002
if self.plugin_enabled and self._handlers and self.inventory_enabled:
_logger.debug("Creating inventory file objects.inv")
inv_contents = self.handlers.inventory.format_sphinx()
write_file(inv_contents, os.path.join(config.site_dir, "objects.inv"))
@event_priority(-100) # Last, after autorefs has finished applying cross-refs and collecting backlinks.
def _on_env_apply_backlinks(self, env: Environment, /, *, config: MkDocsConfig, files: Files) -> Environment: # noqa: ARG002
regex = re.compile(r"<backlinks\s+identifier=\"([^\"]+)\"\s+handler=\"([^\"]+)\"\s*/?>")
def repl(match: Match) -> str:
handler_name = match.group(2)
handler = self.handlers.get_handler(handler_name)
# The handler doesn't implement backlinks,
# return early to avoid computing them.
if handler.render_backlinks.__func__ is BaseHandler.render_backlinks: # type: ignore[attr-defined]
return ""
identifier = match.group(1)
aliases = handler.get_aliases(identifier)
backlinks = self._autorefs.get_backlinks(identifier, *aliases, from_url=file.page.url) # type: ignore[union-attr]
# No backlinks, avoid calling the handler's method.
if not backlinks:
return ""
if "locale" in signature(handler.render_backlinks).parameters:
render_backlinks = partial(handler.render_backlinks, locale=self.handlers._locale)
else:
render_backlinks = handler.render_backlinks # type: ignore[assignment]
return render_backlinks(backlinks)
for file in files:
if file.page and file.page.content:
_logger.debug("Applying backlinks in page %s", file.page.file.src_path)
file.page.content = regex.sub(repl, file.page.content)
return env
on_env = CombinedEvent(_on_env_load_inventories, _on_env_add_css, _on_env_write_inventory, _on_env_apply_backlinks)
"""Extra actions that need to happen after all Markdown-to-HTML page rendering.
Hook for the [`on_env` event](https://www.mkdocs.org/user-guide/plugins/#on_env).
- Gather results from background inventory download tasks.
- Write mkdocstrings' extra files (CSS, inventory) into the site directory.
- Apply backlinks to the HTML output of each page.
"""
def on_post_build(
self,
config: MkDocsConfig, # noqa: ARG002
**kwargs: Any, # noqa: ARG002
) -> None:
"""Teardown the handlers.
Hook for the [`on_post_build` event](https://www.mkdocs.org/user-guide/plugins/#on_post_build).
This hook is used to teardown all the handlers that were instantiated and cached during documentation buildup.
For example, a handler could open a subprocess in the background and keep it open
to feed it "autodoc" instructions and get back JSON data. If so, it should then close the subprocess at some point:
the proper place to do this is in the handler's `teardown` method, which is indirectly called by this hook.
Arguments:
config: The MkDocs config object.
**kwargs: Additional arguments passed by MkDocs.
"""
if not self.plugin_enabled:
return
if self._handlers:
_logger.debug("Tearing handlers down")
self.handlers.teardown()
def get_handler(self, handler_name: str) -> BaseHandler:
"""Get a handler by its name. See [mkdocstrings.Handlers.get_handler][].
Arguments:
handler_name: The name of the handler.
Returns:
An instance of a subclass of [`BaseHandler`][mkdocstrings.BaseHandler].
"""
return self.handlers.get_handler(handler_name)
| MkdocstringsPlugin |
python | PyCQA__pylint | pylint/reporters/progress_reporters.py | {
"start": 233,
"end": 1083
} | class ____:
"""Progress reporter."""
def __init__(self, is_verbose: bool = True) -> None:
self._is_verbose = is_verbose
self._ast_count = 0
self._lint_counter = 0
def start_get_asts(self) -> None:
self._print_message("Get ASTs.")
def get_ast_for_file(self, filename: str) -> None:
self._ast_count += 1
self._print_message(f"AST for {filename}")
def start_linting(self) -> None:
self._print_message(f"Linting {self._ast_count} modules.")
def lint_file(self, filename: str) -> None:
self._lint_counter += 1
self._print_message(f"{filename} ({self._lint_counter} of {self._ast_count})")
def _print_message(self, msg: str) -> None:
"""Display progress message."""
if self._is_verbose:
print(msg, flush=True)
| ProgressReporter |
python | vyperlang__vyper | vyper/venom/basicblock.py | {
"start": 2874,
"end": 3617
} | class ____:
"""
IROperand represents an IR operand. An operand is anything that can be
operated by instructions. It can be a literal, a variable, or a label.
"""
value: Any
_hash: Optional[int] = None
def __init__(self, value: Any) -> None:
self.value = value
self._hash = None
@property
def name(self) -> str:
return self.value
def __hash__(self) -> int:
if self._hash is None:
self._hash = hash(self.value)
return self._hash
def __eq__(self, other) -> bool:
if not isinstance(other, type(self)):
return False
return self.value == other.value
def __repr__(self) -> str:
return str(self.value)
| IROperand |
python | huggingface__transformers | src/transformers/models/cohere2/modular_cohere2.py | {
"start": 10126,
"end": 11070
} | class ____(CohereRotaryEmbedding):
@torch.no_grad()
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
def forward(self, x, position_ids):
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
position_ids_expanded = position_ids[:, None, :].float()
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
with torch.autocast(device_type=device_type, enabled=False): # Force float32
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
emb = torch.repeat_interleave(freqs, 2, dim=-1) # diff from Llama: we interleave() instead of cat()
cos = emb.cos() * self.attention_scaling
sin = emb.sin() * self.attention_scaling
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
| Cohere2RotaryEmbedding |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/transfers/s3_to_sftp.py | {
"start": 1205,
"end": 3857
} | class ____(BaseOperator):
"""
This operator enables the transferring of files from S3 to a SFTP server.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:S3ToSFTPOperator`
:param sftp_conn_id: The sftp connection id. The name or identifier for
establishing a connection to the SFTP server.
:param sftp_path: The sftp remote path. This is the specified file path for
uploading file to the SFTP server.
: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 s3_bucket: The targeted s3 bucket. This is the S3 bucket from
where the file is downloaded.
:param s3_key: The targeted s3 key. This is the specified file path for
downloading the file from S3.
:param confirm: specify if the SFTP operation should be confirmed, defaults to True.
When True, a stat will be performed on the remote file after upload to verify
the file size matches and confirm successful transfer.
"""
template_fields: Sequence[str] = ("s3_key", "sftp_path", "s3_bucket")
def __init__(
self,
*,
s3_bucket: str,
s3_key: str,
sftp_path: str,
sftp_conn_id: str = "ssh_default",
aws_conn_id: str | None = "aws_default",
confirm: bool = True,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.sftp_conn_id = sftp_conn_id
self.sftp_path = sftp_path
self.s3_bucket = s3_bucket
self.s3_key = s3_key
self.aws_conn_id = aws_conn_id
self.confirm = confirm
@staticmethod
def get_s3_key(s3_key: str) -> str:
"""Parse the correct format for S3 keys regardless of how the S3 url is passed."""
parsed_s3_key = urlsplit(s3_key)
return parsed_s3_key.path.lstrip("/")
def execute(self, context: Context) -> None:
self.s3_key = self.get_s3_key(self.s3_key)
ssh_hook = SSHHook(ssh_conn_id=self.sftp_conn_id)
s3_hook = S3Hook(self.aws_conn_id)
s3_client = s3_hook.get_conn()
sftp_client = ssh_hook.get_conn().open_sftp()
with NamedTemporaryFile("w") as f:
s3_client.download_file(self.s3_bucket, self.s3_key, f.name)
sftp_client.put(f.name, self.sftp_path, confirm=self.confirm)
| S3ToSFTPOperator |
python | walkccc__LeetCode | solutions/3508. Implement Router/3508.py | {
"start": 126,
"end": 1715
} | class ____:
def __init__(self, memoryLimit: int):
self.memoryLimit = memoryLimit
self.uniquePackets: set[Packet] = set()
self.packetQueue: collections.deque[Packet] = collections.deque()
self.destinationTimestamps = collections.defaultdict(list)
self.processedPacketIndex = collections.Counter()
def addPacket(self, source: int, destination: int, timestamp: int) -> bool:
packet = Packet(source, destination, timestamp)
if packet in self.uniquePackets:
return False
if len(self.packetQueue) == self.memoryLimit:
self.forwardPacket()
self.packetQueue.append(packet)
self.uniquePackets.add(packet)
if destination not in self.destinationTimestamps:
self.destinationTimestamps[destination] = []
self.destinationTimestamps[destination].append(timestamp)
return True
def forwardPacket(self) -> list[int]:
if not self.packetQueue:
return []
nextPacket = self.packetQueue.popleft()
self.uniquePackets.remove(nextPacket)
self.processedPacketIndex[nextPacket.destination] += 1
return [nextPacket.source, nextPacket.destination, nextPacket.timestamp]
def getCount(self, destination: int, startTime: int, endTime: int) -> int:
if destination not in self.destinationTimestamps:
return 0
timestamps = self.destinationTimestamps[destination]
startIndex = self.processedPacketIndex.get(destination, 0)
lowerBound = bisect.bisect_left(timestamps, startTime, startIndex)
upperBound = bisect.bisect_right(timestamps, endTime, startIndex)
return upperBound - lowerBound
| Router |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI034.py | {
"start": 10052,
"end": 10213
} | class ____(tuple):
def __new__(cls: type[NonGeneric1], *args, **kwargs) -> NonGeneric1: ...
def __enter__(self: NonGeneric1) -> NonGeneric1: ...
| NonGeneric1 |
python | numpy__numpy | benchmarks/benchmarks/bench_lib.py | {
"start": 2455,
"end": 4309
} | class ____(Benchmark):
"""Benchmarks for nan functions"""
param_names = ["array_size", "percent_nans"]
params = [
# sizes of the 1D arrays
[200, int(2e5)],
# percent of np.nan in arrays
[0, 0.1, 2., 50., 90.],
]
def setup(self, array_size, percent_nans):
rnd = np.random.RandomState(1819780348)
# produce a randomly shuffled array with the
# approximate desired percentage np.nan content
base_array = rnd.uniform(size=array_size)
base_array[base_array < percent_nans / 100.] = np.nan
self.arr = base_array
def time_nanmin(self, array_size, percent_nans):
np.nanmin(self.arr)
def time_nanmax(self, array_size, percent_nans):
np.nanmax(self.arr)
def time_nanargmin(self, array_size, percent_nans):
np.nanargmin(self.arr)
def time_nanargmax(self, array_size, percent_nans):
np.nanargmax(self.arr)
def time_nansum(self, array_size, percent_nans):
np.nansum(self.arr)
def time_nanprod(self, array_size, percent_nans):
np.nanprod(self.arr)
def time_nancumsum(self, array_size, percent_nans):
np.nancumsum(self.arr)
def time_nancumprod(self, array_size, percent_nans):
np.nancumprod(self.arr)
def time_nanmean(self, array_size, percent_nans):
np.nanmean(self.arr)
def time_nanvar(self, array_size, percent_nans):
np.nanvar(self.arr)
def time_nanstd(self, array_size, percent_nans):
np.nanstd(self.arr)
def time_nanmedian(self, array_size, percent_nans):
np.nanmedian(self.arr)
def time_nanquantile(self, array_size, percent_nans):
np.nanquantile(self.arr, q=0.2)
def time_nanpercentile(self, array_size, percent_nans):
np.nanpercentile(self.arr, q=50)
| Nan |
python | keras-team__keras | keras/src/legacy/layers.py | {
"start": 316,
"end": 1923
} | class ____(Layer):
"""DEPRECATED."""
def __init__(self, rate, noise_shape=None, seed=None, **kwargs):
super().__init__(**kwargs)
self.rate = rate
self.seed = seed
self.noise_shape = noise_shape
self.seed_generator = backend.random.SeedGenerator(seed)
self.supports_masking = True
self.built = True
def call(self, inputs, training=False):
if training and self.rate > 0:
alpha = 1.6732632423543772848170429916717
scale = 1.0507009873554804934193349852946
alpha_p = -alpha * scale
if self.noise_shape is None:
noise_shape = tf.shape(inputs)
else:
noise_shape = self.noise_shape
kept_idx = tf.greater_equal(
backend.random.uniform(noise_shape, seed=self.seed_generator),
self.rate,
)
kept_idx = tf.cast(kept_idx, inputs.dtype)
# Get affine transformation params
a = ((1 - self.rate) * (1 + self.rate * alpha_p**2)) ** -0.5
b = -a * alpha_p * self.rate
# Apply mask
x = inputs * kept_idx + alpha_p * (1 - kept_idx)
# Do affine transformation
return a * x + b
return inputs
def get_config(self):
config = {"rate": self.rate, "seed": self.seed}
base_config = super().get_config()
return {**base_config, **config}
def compute_output_shape(self, input_shape):
return input_shape
@keras_export("keras._legacy.layers.RandomHeight")
| AlphaDropout |
python | ray-project__ray | release/train_tests/benchmark/image_classification/factory.py | {
"start": 11696,
"end": 14220
} | class ____(BenchmarkFactory):
def get_dataloader_factory(self) -> BaseDataLoaderFactory:
dataloader_type = self.benchmark_config.dataloader_type
task_config = self.benchmark_config.task_config
assert isinstance(task_config, ImageClassificationConfig)
data_dirs = get_imagenet_data_dirs(task_config)
data_format = task_config.image_classification_data_format
if dataloader_type == DataloaderType.MOCK:
return ImageClassificationMockDataLoaderFactory(self.benchmark_config)
elif dataloader_type == DataloaderType.RAY_DATA:
if data_format == ImageClassificationConfig.ImageFormat.JPEG:
from image_classification.jpeg.factory import (
ImageClassificationJpegRayDataLoaderFactory,
)
return ImageClassificationJpegRayDataLoaderFactory(
self.benchmark_config, data_dirs
)
elif data_format == ImageClassificationConfig.ImageFormat.PARQUET:
from image_classification.parquet.factory import (
ImageClassificationParquetRayDataLoaderFactory,
)
return ImageClassificationParquetRayDataLoaderFactory(
self.benchmark_config, data_dirs
)
elif dataloader_type == DataloaderType.TORCH:
if data_format == ImageClassificationConfig.ImageFormat.JPEG:
from image_classification.jpeg.factory import (
ImageClassificationJpegTorchDataLoaderFactory,
)
return ImageClassificationJpegTorchDataLoaderFactory(
self.benchmark_config, data_dirs
)
elif data_format == ImageClassificationConfig.ImageFormat.PARQUET:
from image_classification.parquet.factory import (
ImageClassificationParquetTorchDataLoaderFactory,
)
return ImageClassificationParquetTorchDataLoaderFactory(
self.benchmark_config, data_dirs
)
raise ValueError(
f"Invalid dataloader configuration: {dataloader_type}\n"
f"{task_config}\n{self.benchmark_config.dataloader_config}"
)
def get_model(self) -> torch.nn.Module:
return torchvision.models.resnet50(weights=None)
def get_loss_fn(self) -> torch.nn.Module:
return torch.nn.CrossEntropyLoss()
| ImageClassificationFactory |
python | getsentry__sentry | tests/sentry/rules/conditions/test_event_attribute.py | {
"start": 387,
"end": 35899
} | class ____(RuleTestCase):
rule_cls = EventAttributeCondition
def get_event(self, **kwargs):
data = {
"message": "hello world",
"request": {"method": "GET", "url": "http://example.com/"},
"user": {
"id": "1",
"ip_address": "127.0.0.1",
"email": "foo@example.com",
"username": "foo",
},
"exception": {
"values": [
{
"type": "SyntaxError",
"value": "hello world",
"stacktrace": {
"frames": [
{
"filename": "example.php",
"module": "example",
"context_line": 'echo "hello";',
"abs_path": "path/to/example.php",
}
]
},
"thread_id": 1,
}
]
},
"tags": [("environment", "production")],
"extra": {"foo": {"bar": "baz"}, "biz": ["baz"], "bar": "foo"},
"platform": "php",
"sdk": {"name": "sentry.javascript.react", "version": "6.16.1"},
"contexts": {
"response": {
"type": "response",
"status_code": 500,
},
"device": {
"screen_width_pixels": 1920,
"screen_height_pixels": 1080,
"screen_dpi": 123,
"screen_density": 2.5,
},
"app": {
"in_foreground": True,
},
"unreal": {
"crash_type": "crash",
},
"os": {"distribution_name": "ubuntu", "distribution_version": "22.04"},
"ota_updates": {
"channel": "production",
"runtime_version": "1.0.0",
"update_id": "12345678-1234-1234-1234-1234567890ab",
},
},
"threads": {
"values": [
{
"id": 1,
"main": True,
},
],
},
}
data.update(kwargs)
event = self.store_event(data, project_id=self.project.id)
return event
def test_render_label(self) -> None:
rule = self.get_rule(data={"match": MatchType.EQUAL, "attribute": "\xc3", "value": "\xc4"})
assert rule.render_label() == "The event's \xc3 value equals \xc4"
def test_not_in_registry(self) -> None:
with pytest.raises(NoRegistrationExistsError):
attribute_registry.get("transaction")
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "transaction", "value": "asdf"}
)
self.assertDoesNotPass(rule, event)
def test_equals(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "platform", "value": "php"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "platform", "value": "python"}
)
self.assertDoesNotPass(rule, event)
def test_does_not_equal(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.NOT_EQUAL, "attribute": "platform", "value": "php"}
)
self.assertDoesNotPass(rule, event)
rule = self.get_rule(
data={"match": MatchType.NOT_EQUAL, "attribute": "platform", "value": "python"}
)
self.assertPasses(rule, event)
def test_starts_with(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.STARTS_WITH, "attribute": "platform", "value": "ph"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.STARTS_WITH, "attribute": "platform", "value": "py"}
)
self.assertDoesNotPass(rule, event)
def test_does_not_start_with(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.NOT_STARTS_WITH, "attribute": "platform", "value": "ph"}
)
self.assertDoesNotPass(rule, event)
rule = self.get_rule(
data={"match": MatchType.NOT_STARTS_WITH, "attribute": "platform", "value": "py"}
)
self.assertPasses(rule, event)
def test_ends_with(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.ENDS_WITH, "attribute": "platform", "value": "hp"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.ENDS_WITH, "attribute": "platform", "value": "thon"}
)
self.assertDoesNotPass(rule, event)
def test_does_not_end_with(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.NOT_ENDS_WITH, "attribute": "platform", "value": "hp"}
)
self.assertDoesNotPass(rule, event)
rule = self.get_rule(
data={"match": MatchType.NOT_ENDS_WITH, "attribute": "platform", "value": "thon"}
)
self.assertPasses(rule, event)
def test_contains(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.CONTAINS, "attribute": "platform", "value": "p"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.CONTAINS, "attribute": "platform", "value": "z"}
)
self.assertDoesNotPass(rule, event)
def test_contains_message(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.CONTAINS, "attribute": "message", "value": "hello"}
)
self.assertPasses(rule, event)
# Validate that this searches message in the same way that snuba does
event = self.get_event(message="")
# This should still pass, even though the message is now empty
rule = self.get_rule(
data={"match": MatchType.CONTAINS, "attribute": "message", "value": "hello"}
)
self.assertPasses(rule, event)
# The search should also include info from the exception if present
rule = self.get_rule(
data={"match": MatchType.CONTAINS, "attribute": "message", "value": "SyntaxError"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.CONTAINS, "attribute": "message", "value": "not present"}
)
self.assertDoesNotPass(rule, event)
def test_does_not_contain(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.NOT_CONTAINS, "attribute": "platform", "value": "p"}
)
self.assertDoesNotPass(rule, event)
rule = self.get_rule(
data={"match": MatchType.NOT_CONTAINS, "attribute": "platform", "value": "z"}
)
self.assertPasses(rule, event)
def test_message(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "message", "value": "hello world"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "message", "value": "php"}
)
self.assertDoesNotPass(rule, event)
def test_environment(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "environment", "value": "production"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "environment", "value": "staging"}
)
self.assertDoesNotPass(rule, event)
def test_compares_case_insensitive(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "environment", "value": "PRODUCTION"}
)
self.assertPasses(rule, event)
def test_compare_int_value(self) -> None:
event = self.get_event()
event.data["extra"]["number"] = 1
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "extra.number", "value": "1"}
)
self.assertPasses(rule, event)
def test_http_method(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "http.method", "value": "get"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "http.method", "value": "post"}
)
self.assertDoesNotPass(rule, event)
def test_http_url(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "http.url", "value": "http://example.com/"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "http.url", "value": "http://foo.com"}
)
self.assertDoesNotPass(rule, event)
def test_http_status_code(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "http.status_code", "value": "500"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "http.status_code", "value": "400"}
)
self.assertDoesNotPass(rule, event)
def test_user_id(self) -> None:
event = self.get_event()
rule = self.get_rule(data={"match": MatchType.EQUAL, "attribute": "user.id", "value": "1"})
self.assertPasses(rule, event)
rule = self.get_rule(data={"match": MatchType.EQUAL, "attribute": "user.id", "value": "2"})
self.assertDoesNotPass(rule, event)
def test_user_ip_address(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "user.ip_address", "value": "127.0.0.1"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "user.ip_address", "value": "2"}
)
self.assertDoesNotPass(rule, event)
def test_user_email(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "user.email", "value": "foo@example.com"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "user.email", "value": "2"}
)
self.assertDoesNotPass(rule, event)
def test_user_username(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "user.username", "value": "foo"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "user.username", "value": "2"}
)
self.assertDoesNotPass(rule, event)
def test_exception_type(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "exception.type", "value": "SyntaxError"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "exception.type", "value": "TypeError"}
)
self.assertDoesNotPass(rule, event)
@patch("sentry.services.eventstore.models.get_interfaces", return_value={})
def test_exception_type_keyerror(self, mock_interface: MagicMock) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "exception.type", "value": "SyntaxError"}
)
self.assertDoesNotPass(rule, event)
def test_error_handled(self) -> None:
event = self.get_event(
exception={
"values": [
{
"type": "Generic",
"value": "hello world",
"mechanism": {"type": "UncaughtExceptionHandler", "handled": False},
}
]
}
)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "error.handled", "value": "False"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "error.handled", "value": "True"}
)
self.assertDoesNotPass(rule, event)
def test_error_handled_not_defined(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "error.handled", "value": "True"}
)
self.assertDoesNotPass(rule, event)
@patch("sentry.services.eventstore.models.get_interfaces", return_value={})
def test_error_handled_keyerror(self, mock_interface: MagicMock) -> None:
event = self.get_event(
exception={
"values": [
{
"type": "Generic",
"value": "hello world",
"mechanism": {"type": "UncaughtExceptionHandler", "handled": False},
}
]
}
)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "error.handled", "value": "False"}
)
self.assertDoesNotPass(rule, event)
def test_error_unhandled(self) -> None:
event = self.get_event(
exception={
"values": [
{
"type": "Generic",
"value": "hello world",
"mechanism": {"type": "UncaughtExceptionHandler", "handled": False},
}
],
}
)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "error.unhandled", "value": "True"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "error.unhandled", "value": "False"}
)
self.assertDoesNotPass(rule, event)
def test_exception_value(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "exception.value", "value": "hello world"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "exception.value", "value": "foo bar"}
)
self.assertDoesNotPass(rule, event)
def test_sdk_name(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={
"match": MatchType.EQUAL,
"attribute": "sdk.name",
"value": "sentry.javascript.react",
}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "sdk.name", "value": "sentry.python"}
)
self.assertDoesNotPass(rule, event)
def test_stacktrace_filename(self) -> None:
"""Stacktrace.filename should match frames anywhere in the stack."""
event = self.get_event(
exception={
"values": [
{
"type": "SyntaxError",
"value": "hello world",
"stacktrace": {
"frames": [
{"filename": "example.php", "module": "example"},
{"filename": "somecode.php", "module": "somecode"},
{"filename": "othercode.php", "module": "othercode"},
]
},
}
]
}
)
# correctly matching filenames, at various locations in the stacktrace
for value in ["example.php", "somecode.php", "othercode.php"]:
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "stacktrace.filename", "value": value}
)
self.assertPasses(rule, event)
# non-matching filename
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "stacktrace.filename", "value": "foo.php"}
)
self.assertDoesNotPass(rule, event)
def test_stacktrace_attributeerror(self) -> None:
event = self.get_event(
exception={
"values": [
{
"type": "SyntaxError",
"value": "hello world",
}
]
}
)
# hack to trigger attributeerror
event.interfaces["exception"]._data["values"][0] = None
for value in ["example.php", "somecode.php", "othercode.php"]:
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "stacktrace.filename", "value": value}
)
self.assertDoesNotPass(rule, event)
def test_stacktrace_module(self) -> None:
"""Stacktrace.module should match frames anywhere in the stack."""
event = self.get_event(
exception={
"values": [
{
"type": "SyntaxError",
"value": "hello world",
"stacktrace": {
"frames": [
{"filename": "example.php", "module": "example"},
{"filename": "somecode.php", "module": "somecode"},
{"filename": "othercode.php", "module": "othercode"},
]
},
}
]
}
)
# correctly matching modules, at various locations in the stacktrace
for value in ["example", "somecode", "othercode"]:
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "stacktrace.module", "value": value}
)
self.assertPasses(rule, event)
# non-matching module
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "stacktrace.module", "value": "foo"}
)
self.assertDoesNotPass(rule, event)
def test_stacktrace_code(self) -> None:
"""Stacktrace.code should match frames anywhere in the stack."""
event = self.get_event(
exception={
"values": [
{
"type": "NameError",
"value": "name 'hi' is not defined",
"stacktrace": {
"frames": [
{
"filename": "example.py",
"module": "example",
"function": "foo",
"context_line": "somecode.bar()",
},
{
"filename": "somecode.py",
"module": "somecode",
"function": "bar",
"context_line": "othercode.baz()",
},
{
"filename": "othercode.py",
"module": "othercode",
"function": "baz",
"context_line": "hi()",
},
]
},
}
]
}
)
# correctly matching code, at various locations in the stacktrace
for value in ["somecode.bar()", "othercode.baz()", "hi()"]:
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "stacktrace.code", "value": value}
)
self.assertPasses(rule, event)
# non-matching code
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "stacktrace.code", "value": "foo"}
)
self.assertDoesNotPass(rule, event)
def test_extra_simple_value(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "extra.bar", "value": "foo"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "extra.bar", "value": "bar"}
)
self.assertDoesNotPass(rule, event)
def test_extra_nested_value(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "extra.foo.bar", "value": "baz"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "extra.foo.bar", "value": "bar"}
)
self.assertDoesNotPass(rule, event)
def test_extra_nested_list(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "extra.biz", "value": "baz"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "extra.biz", "value": "bar"}
)
self.assertDoesNotPass(rule, event)
def test_event_type(self) -> None:
event = self.get_event()
event.data["type"] = "error"
rule = self.get_rule(data={"match": MatchType.EQUAL, "attribute": "type", "value": "error"})
self.assertPasses(rule, event)
rule = self.get_rule(data={"match": MatchType.EQUAL, "attribute": "type", "value": "csp"})
self.assertDoesNotPass(rule, event)
def test_stacktrace_abs_path(self) -> None:
"""Stacktrace.abs_path should match frames anywhere in the stack."""
event = self.get_event(
exception={
"values": [
{
"type": "SyntaxError",
"value": "hello world",
"stacktrace": {
"frames": [
{
"filename": "example.php",
"module": "example",
"abs_path": "path/to/example.php",
},
{
"filename": "somecode.php",
"module": "somecode",
"abs_path": "path/to/somecode.php",
},
{
"filename": "othercode.php",
"module": "othercode",
"abs_path": "path/to/othercode.php",
},
]
},
}
]
}
)
# correctly matching filenames, at various locations in the stacktrace
for value in ["path/to/example.php", "path/to/somecode.php", "path/to/othercode.php"]:
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "stacktrace.abs_path", "value": value}
)
self.assertPasses(rule, event)
# non-matching filename
rule = self.get_rule(
data={
"match": MatchType.EQUAL,
"attribute": "stacktrace.abs_path",
"value": "path/to/foo.php",
}
)
self.assertDoesNotPass(rule, event)
def test_stacktrace_package(self) -> None:
"""Stacktrace.package should match frames anywhere in the stack."""
event = self.get_event(
exception={
"values": [
{
"type": "SyntaxError",
"value": "hello world",
"stacktrace": {
"frames": [
{"filename": "example.php", "package": "package/example.lib"},
{
"filename": "somecode.php",
"package": "package/otherpackage.lib",
},
{
"filename": "othercode.php",
"package": "package/somepackage.lib",
},
]
},
}
]
}
)
# correctly matching filenames, at various locations in the stacktrace
for value in ["package/example.lib", "package/otherpackage.lib", "package/somepackage.lib"]:
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "stacktrace.package", "value": value}
)
self.assertPasses(rule, event)
# non-matching filename
rule = self.get_rule(
data={
"match": MatchType.EQUAL,
"attribute": "stacktrace.package",
"value": "package/otherotherpackage.lib",
}
)
self.assertDoesNotPass(rule, event)
def test_device_screen_width_pixels(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={
"match": MatchType.EQUAL,
"attribute": "device.screen_width_pixels",
"value": "1920",
}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={
"match": MatchType.EQUAL,
"attribute": "device.screen_width_pixels",
"value": "400",
}
)
self.assertDoesNotPass(rule, event)
def test_device_screen_height_pixels(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={
"match": MatchType.EQUAL,
"attribute": "device.screen_height_pixels",
"value": "1080",
}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={
"match": MatchType.EQUAL,
"attribute": "device.screen_height_pixels",
"value": "400",
}
)
self.assertDoesNotPass(rule, event)
def test_device_screen_dpi(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={
"match": MatchType.EQUAL,
"attribute": "device.screen_dpi",
"value": "123",
}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={
"match": MatchType.EQUAL,
"attribute": "device.screen_dpi",
"value": "400",
}
)
self.assertDoesNotPass(rule, event)
def test_device_screen_density(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={
"match": MatchType.EQUAL,
"attribute": "device.screen_density",
"value": "2.5",
}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={
"match": MatchType.EQUAL,
"attribute": "device.screen_density",
"value": "400",
}
)
self.assertDoesNotPass(rule, event)
def test_app_in_foreground(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "app.in_foreground", "value": "True"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "app.in_foreground", "value": "False"}
)
self.assertDoesNotPass(rule, event)
def test_os_distribution_name_and_version(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={
"match": MatchType.EQUAL,
"attribute": "os.distribution_name",
"value": "ubuntu",
}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={
"match": MatchType.EQUAL,
"attribute": "os.distribution_version",
"value": "22.04",
}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={
"match": MatchType.EQUAL,
"attribute": "os.distribution_name",
"value": "slackware",
}
)
self.assertDoesNotPass(rule, event)
rule = self.get_rule(
data={
"match": MatchType.EQUAL,
"attribute": "os.distribution_version",
"value": "20.04",
}
)
self.assertDoesNotPass(rule, event)
def test_ota_updates_channel_and_runtime_version_and_update_id(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={
"match": MatchType.EQUAL,
"attribute": "ota_updates.channel",
"value": "production",
}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={
"match": MatchType.EQUAL,
"attribute": "ota_updates.runtime_version",
"value": "1.0.0",
}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={
"match": MatchType.EQUAL,
"attribute": "ota_updates.update_id",
"value": "12345678-1234-1234-1234-1234567890ab",
}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={
"match": MatchType.EQUAL,
"attribute": "ota_updates.channel",
"value": "does-not-exist",
}
)
self.assertDoesNotPass(rule, event)
rule = self.get_rule(
data={
"match": MatchType.EQUAL,
"attribute": "ota_updates.runtime_version",
"value": "1.0.0-does-not-exist",
}
)
self.assertDoesNotPass(rule, event)
rule = self.get_rule(
data={
"match": MatchType.EQUAL,
"attribute": "ota_updates.update_id",
"value": "123-does-not-exist",
}
)
self.assertDoesNotPass(rule, event)
def test_unreal_crash_type(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "unreal.crash_type", "value": "Crash"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "unreal.crash_type", "value": "NoCrash"}
)
self.assertDoesNotPass(rule, event)
def test_does_not_error_with_none(self) -> None:
exception = {
"values": [
None,
{
"type": "SyntaxError",
"value": "hello world",
"stacktrace": {
"frames": [
{
"filename": "example.php",
"module": "example",
"context_line": 'echo "hello";',
"abs_path": "path/to/example.php",
}
]
},
"thread_id": 1,
},
]
}
event = self.get_event(exception=exception)
rule = self.get_rule(
data={"match": MatchType.EQUAL, "attribute": "exception.type", "value": "SyntaxError"}
)
self.assertPasses(rule, event)
def test_attr_is_in(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.IS_IN, "attribute": "platform", "value": "php, python"}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.IS_IN, "attribute": "platform", "value": "python"}
)
self.assertDoesNotPass(rule, event)
def test_attr_is_in_with_spaces(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={
"match": MatchType.IS_IN,
"attribute": "exception.value",
"value": "hello world, foo bar",
}
)
self.assertPasses(rule, event)
rule = self.get_rule(
data={"match": MatchType.IS_IN, "attribute": "exception.value", "value": "foo bar"}
)
self.assertDoesNotPass(rule, event)
def test_attr_not_in(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={"match": MatchType.NOT_IN, "attribute": "platform", "value": "php, python"}
)
self.assertDoesNotPass(rule, event)
rule = self.get_rule(
data={"match": MatchType.NOT_IN, "attribute": "platform", "value": "python"}
)
self.assertPasses(rule, event)
def test_attr_not_in_with_spaces(self) -> None:
event = self.get_event()
rule = self.get_rule(
data={
"match": MatchType.NOT_IN,
"attribute": "exception.value",
"value": "hello world, foo bar",
}
)
self.assertDoesNotPass(rule, event)
rule = self.get_rule(
data={"match": MatchType.NOT_IN, "attribute": "exception.value", "value": "foo bar"}
)
self.assertPasses(rule, event)
| EventAttributeConditionTest |
python | apache__airflow | airflow-core/tests/unit/serialization/test_serde.py | {
"start": 5638,
"end": 5727
} | class ____:
x: int
y: Y
u: tuple
w: W
__version__: ClassVar[int] = 1
| T |
python | pennersr__django-allauth | allauth/socialaccount/providers/wahoo/provider.py | {
"start": 434,
"end": 1498
} | class ____(OAuth2Provider):
id = "wahoo"
name = "Wahoo"
account_class = WahooAccount
oauth2_adapter_class = WahooOAuth2Adapter
def extract_uid(self, data):
return str(data["id"])
def extract_common_fields(self, data):
extra_common = super(WahooProvider, self).extract_common_fields(data)
extra_common.update(
# Additional properties we ignore: gender, created_at, updated_at
height=data.get("height"),
weight=data.get("weight"),
first=data.get("first"),
last=data.get("last"),
birth=data.get("birth"),
)
return extra_common
def extract_email_addresses(self, data):
email = EmailAddress(
email=data.get("email"),
primary=True,
verified=False,
)
return [email]
def get_default_scope(self):
scope = ["user_read"]
if app_settings.QUERY_EMAIL:
scope.append("email")
return scope
provider_classes = [WahooProvider]
| WahooProvider |
python | getsentry__sentry | src/sentry/exceptions.py | {
"start": 98,
"end": 146
} | class ____(InvalidData):
pass
| InvalidInterface |
python | jazzband__django-simple-history | simple_history/tests/view.py | {
"start": 1018,
"end": 1643
} | class ____(View):
def post(self, request, *args, **kwargs):
default_user = CustomUser.objects.create_superuser(
"test_user", "test_user@example.com", "pass"
)
# Bulk create objects with history
poll_info_list = [
{"question": "1", "pub_date": date(2020, 1, 1)},
{"question": "2", "pub_date": date(2020, 1, 2)},
]
polls_to_create = [Poll(**poll_info) for poll_info in poll_info_list]
bulk_create_with_history(polls_to_create, Poll, default_user=default_user)
return HttpResponse(status=200)
| PollBulkCreateWithDefaultUserView |
python | google__jax | jax/_src/interpreters/pxla.py | {
"start": 39830,
"end": 40850
} | class ____(stages.Lowering):
_hlo: ir.Module
_executable: PmapExecutable | None
def __init__(self, hlo: ir.Module, const_args: list[ArrayLike],
**compile_args):
self._executable = None
self._hlo = hlo
self.const_args = const_args
self.compile_args = compile_args
# -- stages.Lowering overrides
def stablehlo(self) -> ir.Module:
return self._hlo
@profiler.annotate_function
def compile(self, compiler_options=None, *, device_assignment=None
) -> PmapExecutable:
if self._executable is None or compiler_options is not None:
executable = UnloadedPmapExecutable.from_hlo(
self._hlo, **self.compile_args,
compiler_options=compiler_options)
if compiler_options is None:
self._executable = executable
return executable
return self._executable
def _cast_to_shaped_array(aval: core.AbstractValue) -> ShapedArray:
assert isinstance(aval, ShapedArray), aval
return aval
@dataclasses.dataclass
| PmapComputation |
python | gevent__gevent | src/greentest/3.10/test_signal.py | {
"start": 48919,
"end": 49967
} | class ____(unittest.TestCase):
@unittest.skipUnless(
hasattr(signal, "pidfd_send_signal"),
"pidfd support not built in",
)
def test_pidfd_send_signal(self):
with self.assertRaises(OSError) as cm:
signal.pidfd_send_signal(0, signal.SIGINT)
if cm.exception.errno == errno.ENOSYS:
self.skipTest("kernel does not support pidfds")
elif cm.exception.errno == errno.EPERM:
self.skipTest("Not enough privileges to use pidfs")
self.assertEqual(cm.exception.errno, errno.EBADF)
my_pidfd = os.open(f'/proc/{os.getpid()}', os.O_DIRECTORY)
self.addCleanup(os.close, my_pidfd)
with self.assertRaisesRegex(TypeError, "^siginfo must be None$"):
signal.pidfd_send_signal(my_pidfd, signal.SIGINT, object(), 0)
with self.assertRaises(KeyboardInterrupt):
signal.pidfd_send_signal(my_pidfd, signal.SIGINT)
def tearDownModule():
support.reap_children()
if __name__ == "__main__":
unittest.main()
| PidfdSignalTest |
python | getsentry__sentry | src/sentry/utils/sdk_crashes/event_stripper.py | {
"start": 266,
"end": 8606
} | class ____(Enum):
def __init__(self, explanation: str = "") -> None:
self.explanation = explanation
"""Keeps the event data if it is of type str, int, float, bool."""
SIMPLE_TYPE = auto()
"""Keeps the event data if it is a mapping with string keys and string values."""
MAP_WITH_STRINGS = auto()
"""
Doesn't keep the event data no matter the type. This can be used to explicitly
specify that data should be removed with an explanation.
"""
NEVER = auto()
def with_explanation(self, explanation: str) -> "Allow":
self.explanation = explanation
return self
EVENT_DATA_ALLOWLIST = {
"type": Allow.SIMPLE_TYPE,
"datetime": Allow.SIMPLE_TYPE,
"timestamp": Allow.SIMPLE_TYPE,
"platform": Allow.SIMPLE_TYPE,
"sdk": {
"name": Allow.SIMPLE_TYPE,
"version": Allow.SIMPLE_TYPE,
"integrations": Allow.NEVER.with_explanation("Users can add their own integrations."),
},
"exception": {
"values": {
"stacktrace": {
"frames": {
"filename": Allow.SIMPLE_TYPE.with_explanation(
"We overwrite the filename for SDK frames and it's acceptable to keep it for system library frames."
),
"function": Allow.SIMPLE_TYPE,
"raw_function": Allow.SIMPLE_TYPE,
"module": Allow.SIMPLE_TYPE,
"abs_path": Allow.SIMPLE_TYPE,
"in_app": Allow.SIMPLE_TYPE,
"instruction_addr": Allow.SIMPLE_TYPE,
"addr_mode": Allow.SIMPLE_TYPE,
"symbol": Allow.SIMPLE_TYPE,
"symbol_addr": Allow.SIMPLE_TYPE,
"image_addr": Allow.SIMPLE_TYPE,
"package": Allow.SIMPLE_TYPE,
"platform": Allow.SIMPLE_TYPE,
"lineno": Allow.SIMPLE_TYPE,
},
"registers": Allow.MAP_WITH_STRINGS.with_explanation(
"Registers contain memory addresses, which isn't PII."
),
},
"value": Allow.NEVER.with_explanation("The exception value could contain PII."),
"type": Allow.SIMPLE_TYPE,
"mechanism": {
"handled": Allow.SIMPLE_TYPE,
"synthetic": Allow.SIMPLE_TYPE,
"type": Allow.SIMPLE_TYPE,
"meta": {
"signal": {
"number": Allow.SIMPLE_TYPE,
"code": Allow.SIMPLE_TYPE,
"name": Allow.SIMPLE_TYPE,
"code_name": Allow.SIMPLE_TYPE,
},
"mach_exception": {
"exception": Allow.SIMPLE_TYPE,
"code": Allow.SIMPLE_TYPE,
"subcode": Allow.SIMPLE_TYPE,
"name": Allow.SIMPLE_TYPE,
},
"errno": {
"number": Allow.SIMPLE_TYPE,
"name": Allow.SIMPLE_TYPE,
},
},
},
}
},
"contexts": {
"device": {
"family": Allow.SIMPLE_TYPE,
"model": Allow.SIMPLE_TYPE,
"arch": Allow.SIMPLE_TYPE,
"simulator": Allow.SIMPLE_TYPE,
},
"os": {
"name": Allow.SIMPLE_TYPE,
"version": Allow.SIMPLE_TYPE,
"build": Allow.SIMPLE_TYPE,
},
},
}
def strip_event_data(
event_data: NodeData, sdk_crash_detector: SDKCrashDetector
) -> Mapping[str, Any]:
"""
This method keeps only properties based on the ALLOW_LIST. For frames, both the allow list applies,
and the method only keeps SDK frames and system library frames.
"""
last_exception = get_path(
event_data,
"exception",
"values",
-1,
)
if not last_exception:
return {}
# The SDK crash detector only detects crashes based on the last exception value.
# Therefore, if the last exception doesn't contain a stacktrace something is off and
# we can drop the whole event.
last_exception_frames = get_path(last_exception, "stacktrace", "frames")
if not last_exception_frames:
return {}
event_data_copy = dict(event_data)
# We strip the frames first because applying the allowlist removes fields that are needed
# for deciding wether to keep a frame or not.
stripped_frames = _strip_frames(last_exception_frames, sdk_crash_detector)
last_exception["stacktrace"]["frames"] = stripped_frames
# We only keep the last exception. We need to adopt the allowlist and stripping event data logic
# to support multiple exceptions.
event_data_copy["exception"]["values"] = [last_exception]
stripped_event_data = _strip_event_data_with_allowlist(event_data_copy, EVENT_DATA_ALLOWLIST)
if not stripped_event_data:
return {}
return stripped_event_data
def _strip_event_data_with_allowlist(
data: Mapping[str, Any], allowlist: Mapping[str, Any] | None
) -> Mapping[str, Any] | None:
"""
Recursively traverses the data and only keeps values based on the allowlist.
"""
if allowlist is None:
return None
stripped_data: dict[str, Any] = {}
for data_key, data_value in data.items():
allowlist_for_data = allowlist.get(data_key)
if allowlist_for_data is None:
continue
if isinstance(allowlist_for_data, Allow):
allowed = allowlist_for_data
if allowed is Allow.SIMPLE_TYPE and isinstance(data_value, (str, int, float, bool)):
stripped_data[data_key] = data_value
elif allowed is Allow.MAP_WITH_STRINGS and isinstance(data_value, Mapping):
map_with_hex_values = {}
for key, value in data_value.items():
if isinstance(key, str) and isinstance(value, str):
map_with_hex_values[key] = value
if len(map_with_hex_values) > 0:
stripped_data[data_key] = map_with_hex_values
continue
else:
continue
elif isinstance(data_value, Mapping):
stripped_data[data_key] = _strip_event_data_with_allowlist(
data_value, allowlist_for_data
)
elif isinstance(data_value, Sequence):
stripped_data[data_key] = [
_strip_event_data_with_allowlist(item, allowlist_for_data) for item in data_value
]
return stripped_data
def _strip_frames(
frames: Sequence[MutableMapping[str, Any]], sdk_crash_detector: SDKCrashDetector
) -> Sequence[Mapping[str, Any]]:
"""
Only keep SDK and system libraries frames.
This method sets in_app to True for SDK frames for grouping. The grouping config
will set in_app false for all SDK frames. To not change the grouping logic, we must
add a stacktrace rule for each path configured in
`SDKCrashDetectorConfig.sdk_frame_config.path_replacer` and
`SDKCrashDetectorConfig.sdk_frame_path_default_replacement_name`.
For example, Cocoa only uses `Sentry.framework` as a replacement path, so we must add the rule `stack.abs_path:Sentry.framework +app +group` to it's project in Sentry.
"""
def strip_frame(frame: MutableMapping[str, Any]) -> MutableMapping[str, Any]:
if sdk_crash_detector.is_sdk_frame(frame):
frame["in_app"] = True
# The path field usually contains the name of the application, which we can't keep.
for path_field_key in sdk_crash_detector.fields_containing_paths:
path_field_value: str = frame.get(path_field_key, "")
if path_field_value:
frame[path_field_key] = sdk_crash_detector.replace_sdk_frame_path(
path_field_key, path_field_value
)
else:
frame["in_app"] = False
return frame
return [
strip_frame(frame)
for frame in frames
if sdk_crash_detector.is_sdk_frame(frame)
or sdk_crash_detector.is_system_library_frame(frame)
]
| Allow |
python | django-extensions__django-extensions | django_extensions/templatetags/indent_text.py | {
"start": 61,
"end": 1726
} | class ____(template.Node):
def __init__(self, nodelist, indent_level, if_statement):
self.nodelist = nodelist
self.indent_level = template.Variable(indent_level)
if if_statement:
self.if_statement = template.Variable(if_statement)
else:
self.if_statement = None
def render(self, context):
indent_level = self.indent_level.resolve(context)
if self.if_statement:
try:
if_statement = bool(self.if_statement.resolve(context))
except template.VariableDoesNotExist:
if_statement = False
else:
if_statement = True
output = self.nodelist.render(context)
if if_statement:
indent = " " * indent_level
output = indent + indent.join(output.splitlines(True))
return output
@register.tag
def indentby(parser, token):
"""
Add indentation to text between the tags by the given indentation level.
{% indentby <indent_level> [if <statement>] %}
...
{% endindentby %}
Arguments:
indent_level - Number of spaces to indent text with.
statement - Only apply indent_level if the boolean statement evalutates to True.
"""
args = token.split_contents()
largs = len(args)
if largs not in (2, 4):
raise template.TemplateSyntaxError("indentby tag requires 1 or 3 arguments")
indent_level = args[1]
if_statement = None
if largs == 4:
if_statement = args[3]
nodelist = parser.parse(("endindentby",))
parser.delete_first_token()
return IndentByNode(nodelist, indent_level, if_statement)
| IndentByNode |
python | aio-libs__aiohttp | aiohttp/client_exceptions.py | {
"start": 4892,
"end": 5099
} | class ____(ClientConnectorError):
"""Proxy connection error.
Raised in :class:`aiohttp.connector.TCPConnector` if
connection to proxy can not be established.
"""
| ClientProxyConnectionError |
python | FactoryBoy__factory_boy | tests/test_django.py | {
"start": 4274,
"end": 4650
} | class ____(django_test.TestCase):
def reset_database_sequences(self, *models):
using = factory.django.DEFAULT_DB_ALIAS
with connections[using].cursor() as cursor:
sequence_sql = connections[using].ops.sequence_reset_sql(color.no_style(), models)
for command in sequence_sql:
cursor.execute(command)
| DjangoResetTestCase |
python | ray-project__ray | rllib/evaluation/env_runner_v2.py | {
"start": 1718,
"end": 4634
} | class ____:
"""Sampler perf stats that will be included in rollout metrics."""
def __init__(self, ema_coef: Optional[float] = None):
# If not None, enable Exponential Moving Average mode.
# The way we update stats is by:
# updated = (1 - ema_coef) * old + ema_coef * new
# In general provides more responsive stats about sampler performance.
# TODO(jungong) : make ema the default (only) mode if it works well.
self.ema_coef = ema_coef
self.iters = 0
self.raw_obs_processing_time = 0.0
self.inference_time = 0.0
self.action_processing_time = 0.0
self.env_wait_time = 0.0
self.env_render_time = 0.0
def incr(self, field: str, value: Union[int, float]):
if field == "iters":
self.iters += value
return
# All the other fields support either global average or ema mode.
if self.ema_coef is None:
# Global average.
self.__dict__[field] += value
else:
self.__dict__[field] = (1.0 - self.ema_coef) * self.__dict__[
field
] + self.ema_coef * value
def _get_avg(self):
# Mean multiplicator (1000 = sec -> ms).
factor = MS_TO_SEC / self.iters
return {
# Raw observation preprocessing.
"mean_raw_obs_processing_ms": self.raw_obs_processing_time * factor,
# Computing actions through policy.
"mean_inference_ms": self.inference_time * factor,
# Processing actions (to be sent to env, e.g. clipping).
"mean_action_processing_ms": self.action_processing_time * factor,
# Waiting for environment (during poll).
"mean_env_wait_ms": self.env_wait_time * factor,
# Environment rendering (False by default).
"mean_env_render_ms": self.env_render_time * factor,
}
def _get_ema(self):
# In EMA mode, stats are already (exponentially) averaged,
# hence we only need to do the sec -> ms conversion here.
return {
# Raw observation preprocessing.
"mean_raw_obs_processing_ms": self.raw_obs_processing_time * MS_TO_SEC,
# Computing actions through policy.
"mean_inference_ms": self.inference_time * MS_TO_SEC,
# Processing actions (to be sent to env, e.g. clipping).
"mean_action_processing_ms": self.action_processing_time * MS_TO_SEC,
# Waiting for environment (during poll).
"mean_env_wait_ms": self.env_wait_time * MS_TO_SEC,
# Environment rendering (False by default).
"mean_env_render_ms": self.env_render_time * MS_TO_SEC,
}
def get(self):
if self.ema_coef is None:
return self._get_avg()
else:
return self._get_ema()
@OldAPIStack
| _PerfStats |
python | kamyu104__LeetCode-Solutions | Python/power-of-four.py | {
"start": 525,
"end": 811
} | class ____(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
num = bin(num)
return True if num[2:].startswith('1') and len(num[2:]) == num.count('0') and num.count('0') % 2 and '-' not in num else False
| Solution3 |
python | davidhalter__parso | parso/python/errors.py | {
"start": 31947,
"end": 34252
} | class ____(SyntaxRule):
@property
def message(self):
if self._normalizer.version < (3, 7):
return "Generator expression must be parenthesized if not sole argument"
else:
return "Generator expression must be parenthesized"
def is_issue(self, node):
arg_set = set()
kw_only = False
kw_unpacking_only = False
for argument in node.children:
if argument == ',':
continue
if argument.type == 'argument':
first = argument.children[0]
if _is_argument_comprehension(argument) and len(node.children) >= 2:
# a(a, b for b in c)
return True
if first in ('*', '**'):
if first == '*':
if kw_unpacking_only:
# foo(**kwargs, *args)
message = "iterable argument unpacking " \
"follows keyword argument unpacking"
self.add_issue(argument, message=message)
else:
kw_unpacking_only = True
else: # Is a keyword argument.
kw_only = True
if first.type == 'name':
if first.value in arg_set:
# f(x=1, x=2)
message = "keyword argument repeated"
if self._normalizer.version >= (3, 9):
message += ": {}".format(first.value)
self.add_issue(first, message=message)
else:
arg_set.add(first.value)
else:
if kw_unpacking_only:
# f(**x, y)
message = "positional argument follows keyword argument unpacking"
self.add_issue(argument, message=message)
elif kw_only:
# f(x=2, y)
message = "positional argument follows keyword argument"
self.add_issue(argument, message=message)
@ErrorFinder.register_rule(type='parameters')
@ErrorFinder.register_rule(type='lambdef')
| _ArglistRule |
python | numba__numba | numba/np/arrayobj.py | {
"start": 24990,
"end": 25647
} | class ____(Indexer):
"""
Compute indices from a single integer.
"""
def __init__(self, context, builder, idx):
self.context = context
self.builder = builder
self.idx = idx
self.ll_intp = self.context.get_value_type(types.intp)
def prepare(self):
pass
def get_size(self):
return Constant(self.ll_intp, 1)
def get_shape(self):
return ()
def get_index_bounds(self):
# [idx, idx+1)
return (self.idx, self.builder.add(self.idx, self.get_size()))
def loop_head(self):
return self.idx, None
def loop_tail(self):
pass
| IntegerIndexer |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 234312,
"end": 235082
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"color",
"contribution_count",
"contribution_level",
"date",
"weekday",
)
color = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="color")
contribution_count = sgqlc.types.Field(
sgqlc.types.non_null(Int), graphql_name="contributionCount"
)
contribution_level = sgqlc.types.Field(
sgqlc.types.non_null(ContributionLevel), graphql_name="contributionLevel"
)
date = sgqlc.types.Field(sgqlc.types.non_null(Date), graphql_name="date")
weekday = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="weekday")
| ContributionCalendarDay |
python | langchain-ai__langchain | libs/langchain/langchain_classic/chains/prompt_selector.py | {
"start": 589,
"end": 2001
} | class ____(BasePromptSelector):
"""Prompt collection that goes through conditionals."""
default_prompt: BasePromptTemplate
"""Default prompt to use if no conditionals match."""
conditionals: list[
tuple[Callable[[BaseLanguageModel], bool], BasePromptTemplate]
] = Field(default_factory=list)
"""List of conditionals and prompts to use if the conditionals match."""
def get_prompt(self, llm: BaseLanguageModel) -> BasePromptTemplate:
"""Get default prompt for a language model.
Args:
llm: Language model to get prompt for.
Returns:
Prompt to use for the language model.
"""
for condition, prompt in self.conditionals:
if condition(llm):
return prompt
return self.default_prompt
def is_llm(llm: BaseLanguageModel) -> bool:
"""Check if the language model is a LLM.
Args:
llm: Language model to check.
Returns:
`True` if the language model is a BaseLLM model, `False` otherwise.
"""
return isinstance(llm, BaseLLM)
def is_chat_model(llm: BaseLanguageModel) -> bool:
"""Check if the language model is a chat model.
Args:
llm: Language model to check.
Returns:
`True` if the language model is a BaseChatModel model, `False` otherwise.
"""
return isinstance(llm, BaseChatModel)
| ConditionalPromptSelector |
python | spyder-ide__spyder | spyder/utils/syntaxhighlighters.py | {
"start": 69012,
"end": 72178
} | class ____(BaseSH):
"""Base class for CSS and HTML syntax highlighters"""
NORMAL = 0
COMMENT = 1
def __init__(self, parent, font=None, color_scheme=None):
BaseSH.__init__(self, parent, font, color_scheme)
def highlight_block(self, text):
"""Implement highlight specific for CSS and HTML."""
text = str(text)
previous_state = tbh.get_state(self.currentBlock().previous())
if previous_state == self.COMMENT:
self.setFormat(0, qstring_length(text), self.formats["comment"])
else:
previous_state = self.NORMAL
self.setFormat(0, qstring_length(text), self.formats["normal"])
tbh.set_state(self.currentBlock(), previous_state)
match_count = 0
n_characters = qstring_length(text)
# There should never be more matches than characters in the text.
for match in self.PROG.finditer(text):
match_dict = match.groupdict()
for key, value in list(match_dict.items()):
if value:
start, end = get_span(match, key)
if previous_state == self.COMMENT:
if key == "multiline_comment_end":
tbh.set_state(self.currentBlock(), self.NORMAL)
self.setFormat(end, qstring_length(text),
self.formats["normal"])
else:
tbh.set_state(self.currentBlock(), self.COMMENT)
self.setFormat(0, qstring_length(text),
self.formats["comment"])
else:
if key == "multiline_comment_start":
tbh.set_state(self.currentBlock(), self.COMMENT)
self.setFormat(start, qstring_length(text),
self.formats["comment"])
else:
tbh.set_state(self.currentBlock(), self.NORMAL)
try:
self.setFormat(start, end-start,
self.formats[key])
except KeyError:
# Happens with unmatched end-of-comment.
# See spyder-ide/spyder#1462.
pass
match_count += 1
if match_count >= n_characters:
break
self.highlight_extras(text)
def make_html_patterns():
"""Strongly inspired from idlelib.ColorDelegator.make_pat """
tags = any("builtin", [r"<", r"[\?/]?>", r"(?<=<).*?(?=[ >])"])
keywords = any("keyword", [r" [\w:-]*?(?==)"])
string = any("string", [r'".*?"'])
comment = any("comment", [r"<!--.*?-->"])
multiline_comment_start = any("multiline_comment_start", [r"<!--"])
multiline_comment_end = any("multiline_comment_end", [r"-->"])
return "|".join([comment, multiline_comment_start,
multiline_comment_end, tags, keywords, string])
| BaseWebSH |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/roots/pipeline.py | {
"start": 275,
"end": 547
} | class ____(graphene.Union):
class Meta:
types = (
GraphenePipeline,
GraphenePipelineNotFoundError,
GrapheneInvalidSubsetError,
GraphenePythonError,
)
name = "PipelineOrError"
| GraphenePipelineOrError |
python | pypa__warehouse | warehouse/organizations/models.py | {
"start": 4399,
"end": 5159
} | class ____(db.Model):
__tablename__ = "organization_terms_of_service_engagements"
__table_args__ = (
Index(
"organization_terms_of_service_engagements_org_id_revision_idx",
"organization_id",
"revision",
),
)
__repr__ = make_repr("organization_id")
organization_id: Mapped[UUID] = mapped_column(
ForeignKey("organizations.id", onupdate="CASCADE", ondelete="CASCADE"),
)
revision: Mapped[str]
created: Mapped[datetime.datetime] = mapped_column(TZDateTime)
engagement: Mapped[TermsOfServiceEngagement]
organization: Mapped[Organization] = relationship(
lazy=False, back_populates="terms_of_service_engagements"
)
| OrganizationTermsOfServiceEngagement |
python | kamyu104__LeetCode-Solutions | Python/bulls-and-cows.py | {
"start": 156,
"end": 651
} | class ____(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
A, B = 0, 0
lookup = defaultdict(int)
for s, g in izip(secret, guess):
if s == g:
A += 1
else:
B += int(lookup[s] < 0) + int(lookup[g] > 0)
lookup[s] += 1
lookup[g] -= 1
return "%dA%dB" % (A, B)
# Two pass solution.
| Solution |
python | keras-team__keras | keras/src/utils/dataset_utils_test.py | {
"start": 2207,
"end": 6061
} | class ____(test_case.TestCase):
@parameterized.named_parameters(
named_product(
dataset_type=["list", "tuple", "tensorflow", "torch"],
features_shape=[(2,), (100, 2), (10, 10, 2)],
preferred_backend=[None, "tensorflow", "torch"],
)
)
def test_split_dataset(
self, dataset_type, features_shape, preferred_backend
):
n_sample, left_size, right_size = 100, 0.2, 0.8
features = np.random.sample((n_sample,) + features_shape)
labels = np.random.sample((n_sample, 1))
cardinality_function = (
tf.data.Dataset.cardinality
if (backend.backend() != "torch" and preferred_backend != "torch")
else len
)
if dataset_type == "list":
dataset = [features, labels]
elif dataset_type == "tuple":
dataset = (features, labels)
elif dataset_type == "tensorflow":
dataset = tf.data.Dataset.from_tensor_slices((features, labels))
elif dataset_type == "torch":
dataset = MyTorchDataset(features, labels)
cardinality_function = len
else:
raise ValueError(f"Unknown dataset_type: {dataset_type}")
dataset_left, dataset_right = split_dataset(
dataset,
left_size=left_size,
right_size=right_size,
preferred_backend=preferred_backend,
)
self.assertEqual(
int(cardinality_function(dataset_left)), int(n_sample * left_size)
)
self.assertEqual(
int(cardinality_function(dataset_right)), int(n_sample * right_size)
)
for sample in itertools.chain(dataset_left, dataset_right):
self.assertEqual(sample[0].shape, features_shape)
self.assertEqual(sample[1].shape, (1,))
@parameterized.named_parameters(
named_product(structure_type=["tuple", "dict", "OrderedDict"])
)
def test_split_dataset_nested_structures(self, structure_type):
n_sample, left_size, right_size = 100, 0.2, 0.8
features1 = np.random.sample((n_sample, 2))
features2 = np.random.sample((n_sample, 10, 2))
labels = np.random.sample((n_sample, 1))
if backend.backend() != "torch":
create_dataset_function = tf.data.Dataset.from_tensor_slices
cardinality_function = tf.data.Dataset.cardinality
else:
create_dataset_function = MyTorchDataset
cardinality_function = len
if structure_type == "tuple":
dataset = create_dataset_function(((features1, features2), labels))
if structure_type == "dict":
dataset = create_dataset_function(
{"y": features2, "x": features1, "labels": labels}
)
if structure_type == "OrderedDict":
dataset = create_dataset_function(
collections.OrderedDict(
[("y", features2), ("x", features1), ("labels", labels)]
)
)
dataset_left, dataset_right = split_dataset(
dataset, left_size=left_size, right_size=right_size
)
self.assertEqual(
int(cardinality_function(dataset_left)), int(n_sample * left_size)
)
self.assertEqual(
int(cardinality_function(dataset_right)), int(n_sample * right_size)
)
for sample in itertools.chain(dataset_left, dataset_right):
if structure_type in ("dict", "OrderedDict"):
x, y, labels = sample["x"], sample["y"], sample["labels"]
elif structure_type == "tuple":
(x, y), labels = sample
self.assertEqual(x.shape, (2,))
self.assertEqual(y.shape, (10, 2))
self.assertEqual(labels.shape, (1,))
| DatasetUtilsTest |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/utils/test_connection_wrapper.py | {
"start": 2787,
"end": 20554
} | class ____:
@pytest.mark.parametrize("extra", [{"foo": "bar", "spam": "egg"}, '{"foo": "bar", "spam": "egg"}', None])
def test_values_from_connection(self, extra):
mock_conn = mock_connection_factory(
login="mock-login",
password="mock-password",
extra=extra,
# AwsBaseHook never use this attributes from airflow.models.Connection
host=None,
schema="mock-schema",
port=42,
)
wrap_conn = AwsConnectionWrapper(conn=mock_conn)
assert wrap_conn.conn_id == mock_conn.conn_id
assert wrap_conn.conn_type == mock_conn.conn_type
assert wrap_conn.login == mock_conn.login
assert wrap_conn.password == mock_conn.password
# Check that original extra config from connection persists in wrapper
assert wrap_conn.extra_config == mock_conn.extra_dejson
assert wrap_conn.extra_config is not mock_conn.extra_dejson
# `extra_config` is a same object that return by `extra_dejson`
assert wrap_conn.extra_config is wrap_conn.extra_dejson
assert wrap_conn.schema == "mock-schema"
# Check that not assigned other attributes from airflow.models.Connection to wrapper
assert not hasattr(wrap_conn, "host")
assert not hasattr(wrap_conn, "port")
# Check that Wrapper is True if assign connection
assert wrap_conn
def test_no_connection(self):
assert not AwsConnectionWrapper(conn=None)
@pytest.mark.parametrize("conn_type", ["aws", None])
def test_expected_aws_connection_type(self, conn_type):
wrap_conn = AwsConnectionWrapper(conn=mock_connection_factory(conn_type=conn_type))
assert wrap_conn.conn_type == "aws"
@pytest.mark.parametrize("conn_type", ["AWS", "boto3", "emr", "google", "google-cloud-platform"])
def test_unexpected_aws_connection_type(self, conn_type):
warning_message = f"expected connection type 'aws', got '{conn_type}'"
with pytest.warns(UserWarning, match=warning_message):
wrap_conn = AwsConnectionWrapper(conn=mock_connection_factory(conn_type=conn_type))
assert wrap_conn.conn_type == conn_type
@pytest.mark.parametrize("aws_session_token", [None, "mock-aws-session-token"])
@pytest.mark.parametrize("aws_secret_access_key", ["mock-aws-secret-access-key"])
@pytest.mark.parametrize("aws_access_key_id", ["mock-aws-access-key-id"])
def test_get_credentials_from_login(self, aws_access_key_id, aws_secret_access_key, aws_session_token):
mock_conn = mock_connection_factory(
login=aws_access_key_id,
password=aws_secret_access_key,
extra={"aws_session_token": aws_session_token} if aws_session_token else None,
)
wrap_conn = AwsConnectionWrapper(conn=mock_conn)
assert wrap_conn.aws_access_key_id == aws_access_key_id
assert wrap_conn.aws_secret_access_key == aws_secret_access_key
assert wrap_conn.aws_session_token == aws_session_token
@pytest.mark.parametrize("aws_session_token", [None, "mock-aws-session-token"])
@pytest.mark.parametrize("aws_secret_access_key", ["mock-aws-secret-access-key"])
@pytest.mark.parametrize("aws_access_key_id", ["mock-aws-access-key-id"])
def test_get_credentials_from_extra(self, aws_access_key_id, aws_secret_access_key, aws_session_token):
mock_conn_extra = {
"aws_access_key_id": aws_access_key_id,
"aws_secret_access_key": aws_secret_access_key,
}
if aws_session_token:
mock_conn_extra["aws_session_token"] = aws_session_token
mock_conn = mock_connection_factory(login=None, password=None, extra=mock_conn_extra)
wrap_conn = AwsConnectionWrapper(conn=mock_conn)
assert wrap_conn.aws_access_key_id == aws_access_key_id
assert wrap_conn.aws_secret_access_key == aws_secret_access_key
assert wrap_conn.aws_session_token == aws_session_token
@pytest.mark.parametrize("aws_access_key_id", [None, "mock-aws-access-key-id"])
@pytest.mark.parametrize("aws_secret_access_key", [None, "mock-aws-secret-access-key"])
@pytest.mark.parametrize("aws_session_token", [None, "mock-aws-session-token"])
@pytest.mark.parametrize("profile_name", [None, "mock-profile"])
@pytest.mark.parametrize("region_name", [None, "mock-region-name"])
def test_get_session_kwargs_from_wrapper(
self, aws_access_key_id, aws_secret_access_key, aws_session_token, profile_name, region_name
):
mock_conn_extra = {
"aws_access_key_id": aws_access_key_id,
"aws_secret_access_key": aws_secret_access_key,
"aws_session_token": aws_session_token,
"profile_name": profile_name,
"region_name": region_name,
}
mock_conn = mock_connection_factory(extra=mock_conn_extra)
expected = {}
if aws_access_key_id:
expected["aws_access_key_id"] = aws_access_key_id
if aws_secret_access_key:
expected["aws_secret_access_key"] = aws_secret_access_key
if aws_session_token:
expected["aws_session_token"] = aws_session_token
if profile_name:
expected["profile_name"] = profile_name
if region_name:
expected["region_name"] = region_name
with warnings.catch_warnings():
warnings.simplefilter("error") # Not expected any warnings here
wrap_conn = AwsConnectionWrapper(conn=mock_conn)
session_kwargs = wrap_conn.session_kwargs
assert session_kwargs == expected
# Test that session parameters immutable
session_kwargs["botocore_session"] = "foo.bar"
assert wrap_conn.session_kwargs == expected
assert wrap_conn.session_kwargs != session_kwargs
@pytest.mark.parametrize(
("region_name", "conn_region_name"),
[
("mock-region-name", None),
("mock-region-name", "mock-connection-region-name"),
(None, "mock-connection-region-name"),
(None, None),
],
)
def test_get_region_name(self, region_name, conn_region_name):
mock_conn = mock_connection_factory(
extra={"region_name": conn_region_name} if conn_region_name else None
)
wrap_conn = AwsConnectionWrapper(conn=mock_conn, region_name=region_name)
if region_name:
assert wrap_conn.region_name == region_name, "Expected provided region_name"
else:
assert wrap_conn.region_name == conn_region_name, "Expected connection region_name"
def test_warn_wrong_profile_param_used(self):
mock_conn = mock_connection_factory(extra={"profile": "mock-profile"})
warning_message = "Found 'profile' without specifying 's3_config_file' in .* set 'profile_name' in"
with pytest.warns(UserWarning, match=warning_message):
wrap_conn = AwsConnectionWrapper(conn=mock_conn)
assert "profile_name" not in wrap_conn.session_kwargs
@mock.patch("airflow.providers.amazon.aws.utils.connection_wrapper.Config")
@pytest.mark.parametrize(
("botocore_config", "botocore_config_kwargs"),
[
(Config(s3={"us_east_1_regional_endpoint": "regional"}), None),
(Config(region_name="ap-southeast-1"), {"user_agent": "Airflow Amazon Provider"}),
(None, {"user_agent": "Airflow Amazon Provider"}),
(None, {"signature_version": "unsigned"}),
(None, None),
],
)
def test_get_botocore_config(self, mock_botocore_config, botocore_config, botocore_config_kwargs):
mock_conn = mock_connection_factory(
extra={"config_kwargs": botocore_config_kwargs} if botocore_config_kwargs else None
)
wrap_conn = AwsConnectionWrapper(conn=mock_conn, botocore_config=botocore_config)
if botocore_config:
assert wrap_conn.botocore_config == botocore_config, "Expected provided botocore_config"
assert mock_botocore_config.assert_not_called
elif not botocore_config_kwargs:
assert wrap_conn.botocore_config is None, "Expected default botocore_config"
assert mock_botocore_config.assert_not_called
else:
assert mock_botocore_config.assert_called_once
if botocore_config_kwargs.get("signature_version") == "unsigned":
botocore_config_kwargs["signature_version"] = UNSIGNED
assert mock.call(**botocore_config_kwargs) in mock_botocore_config.mock_calls
@pytest.mark.parametrize(
("aws_account_id", "aws_iam_role"), [(None, None), ("111111111111", "another-role")]
)
def test_get_role_arn(self, aws_account_id, aws_iam_role):
mock_conn = mock_connection_factory(
extra={
"role_arn": MOCK_ROLE_ARN,
"aws_account_id": aws_account_id,
"aws_iam_role": aws_iam_role,
}
)
wrap_conn = AwsConnectionWrapper(conn=mock_conn)
assert wrap_conn.role_arn == MOCK_ROLE_ARN
def test_empty_role_arn(self):
wrap_conn = AwsConnectionWrapper(conn=mock_connection_factory())
assert wrap_conn.role_arn is None
assert wrap_conn.assume_role_method is None
assert wrap_conn.assume_role_kwargs == {}
@pytest.mark.parametrize(
"assume_role_method", ["assume_role", "assume_role_with_saml", "assume_role_with_web_identity"]
)
def test_get_assume_role_method(self, assume_role_method):
mock_conn = mock_connection_factory(
extra={"role_arn": MOCK_ROLE_ARN, "assume_role_method": assume_role_method}
)
wrap_conn = AwsConnectionWrapper(conn=mock_conn)
assert wrap_conn.assume_role_method == assume_role_method
def test_default_assume_role_method(self):
mock_conn = mock_connection_factory(
extra={
"role_arn": MOCK_ROLE_ARN,
}
)
wrap_conn = AwsConnectionWrapper(conn=mock_conn)
assert wrap_conn.assume_role_method == "assume_role"
def test_unsupported_assume_role_method(self):
mock_conn = mock_connection_factory(
extra={"role_arn": MOCK_ROLE_ARN, "assume_role_method": "dummy_method"}
)
with pytest.raises(NotImplementedError, match="Found assume_role_method='dummy_method' in .* extra"):
AwsConnectionWrapper(conn=mock_conn)
@pytest.mark.parametrize("assume_role_kwargs", [None, {"DurationSeconds": 42}])
def test_get_assume_role_kwargs(self, assume_role_kwargs):
mock_conn_extra = {"role_arn": MOCK_ROLE_ARN}
if assume_role_kwargs:
mock_conn_extra["assume_role_kwargs"] = assume_role_kwargs
mock_conn = mock_connection_factory(extra=mock_conn_extra)
wrap_conn = AwsConnectionWrapper(conn=mock_conn)
expected = assume_role_kwargs or {}
assert wrap_conn.assume_role_kwargs == expected
@pytest.mark.parametrize("external_id_in_extra", [None, "mock-external-id-in-extra"])
def test_get_assume_role_kwargs_external_id_in_kwargs(self, external_id_in_extra):
mock_external_id_in_kwargs = "mock-external-id-in-kwargs"
mock_conn_extra = {
"role_arn": MOCK_ROLE_ARN,
"assume_role_kwargs": {"ExternalId": mock_external_id_in_kwargs},
}
if external_id_in_extra:
mock_conn_extra["external_id"] = external_id_in_extra
mock_conn = mock_connection_factory(extra=mock_conn_extra)
wrap_conn = AwsConnectionWrapper(conn=mock_conn)
assert "ExternalId" in wrap_conn.assume_role_kwargs
assert wrap_conn.assume_role_kwargs["ExternalId"] == mock_external_id_in_kwargs
assert wrap_conn.assume_role_kwargs["ExternalId"] != external_id_in_extra
@pytest.mark.parametrize(
"orig_wrapper",
[
AwsConnectionWrapper(
conn=mock_connection_factory(
login="mock-login",
password="mock-password",
extra={
"region_name": "mock-region",
"botocore_kwargs": {"user_agent": "Airflow Amazon Provider"},
"role_arn": MOCK_ROLE_ARN,
"aws_session_token": "mock-aws-session-token",
},
),
),
AwsConnectionWrapper(conn=mock_connection_factory()),
AwsConnectionWrapper(conn=None),
AwsConnectionWrapper(
conn=None,
region_name="mock-region",
botocore_config=Config(user_agent="Airflow Amazon Provider"),
),
],
)
@pytest.mark.parametrize("region_name", [None, "ca-central-1"])
@pytest.mark.parametrize("botocore_config", [None, Config(region_name="ap-southeast-1")])
def test_wrap_wrapper(self, orig_wrapper, region_name, botocore_config):
wrap_kwargs = {}
if region_name:
wrap_kwargs["region_name"] = region_name
if botocore_config:
wrap_kwargs["botocore_config"] = botocore_config
wrap_conn = AwsConnectionWrapper(conn=orig_wrapper, **wrap_kwargs)
# Non init fields should be same in orig_wrapper and child wrapper
wrap_non_init_fields = [f.name for f in fields(wrap_conn) if not f.init]
for field in wrap_non_init_fields:
assert getattr(wrap_conn, field) == getattr(orig_wrapper, field), (
"Expected no changes in non-init values"
)
# Test overwrite/inherit init fields
assert wrap_conn.region_name == (region_name or orig_wrapper.region_name)
assert wrap_conn.botocore_config == (botocore_config or orig_wrapper.botocore_config)
@pytest.mark.parametrize("conn_id", [None, "mock-conn-id"])
@pytest.mark.parametrize("profile_name", [None, "mock-profile"])
@pytest.mark.parametrize("role_arn", [None, MOCK_ROLE_ARN])
def test_get_wrapper_from_metadata(self, conn_id, profile_name, role_arn):
mock_conn = mock_connection_factory(
conn_id=conn_id,
extra={
"role_arn": role_arn,
"profile_name": profile_name,
},
)
wrap_conn = AwsConnectionWrapper(conn=mock_conn)
assert wrap_conn
assert wrap_conn.conn_id == conn_id
assert wrap_conn.role_arn == role_arn
assert wrap_conn.profile_name == profile_name
def test_get_service_config(self):
mock_conn = mock_connection_factory(
conn_id="foo-bar",
extra={
"service_config": {
"sns": {"foo": "bar"},
"s3": {"spam": "egg", "baz": "qux"},
"dynamodb": None,
},
},
)
wrap_conn = AwsConnectionWrapper(conn=mock_conn)
assert wrap_conn.get_service_config("sns") == {"foo": "bar"}
assert wrap_conn.get_service_config("s3") == {"spam": "egg", "baz": "qux"}
assert wrap_conn.get_service_config("ec2") == {}
assert wrap_conn.get_service_config("dynamodb") is None
def test_get_service_endpoint_url(self):
fake_conn = mock_connection_factory(
conn_id="foo-bar",
extra={
"endpoint_url": "https://spam.egg",
"service_config": {
"sns": {"endpoint_url": "https://foo.bar"},
"ec2": {"endpoint_url": None}, # Enforce to boto3
},
},
)
wrap_conn = AwsConnectionWrapper(conn=fake_conn)
assert wrap_conn.get_service_endpoint_url("sns") == "https://foo.bar"
assert wrap_conn.get_service_endpoint_url("sts") == "https://spam.egg"
assert wrap_conn.get_service_endpoint_url("ec2") is None
@pytest.mark.parametrize(
("global_endpoint_url", "sts_service_endpoint_url", "expected_endpoint_url"),
[
pytest.param(None, None, None, id="not-set"),
pytest.param("https://global.service", None, None, id="global-only"),
pytest.param(None, "https://sts.service:1234", "https://sts.service:1234", id="service-only"),
pytest.param(
"https://global.service", "https://sts.service:1234", "https://sts.service:1234", id="mixin"
),
],
)
def test_get_service_endpoint_url_sts(
self, global_endpoint_url, sts_service_endpoint_url, expected_endpoint_url
):
fake_extra = {}
if global_endpoint_url:
fake_extra["endpoint_url"] = global_endpoint_url
if sts_service_endpoint_url:
fake_extra["service_config"] = {"sts": {"endpoint_url": sts_service_endpoint_url}}
fake_conn = mock_connection_factory(conn_id="foo-bar", extra=fake_extra)
wrap_conn = AwsConnectionWrapper(conn=fake_conn)
assert wrap_conn.get_service_endpoint_url("sts", sts_connection_assume=True) == expected_endpoint_url
assert wrap_conn.get_service_endpoint_url("sts", sts_test_connection=True) == expected_endpoint_url
def test_get_service_endpoint_url_sts_unsupported(self):
wrap_conn = AwsConnectionWrapper(conn=mock_connection_factory())
with pytest.raises(AirflowException, match=r"Can't resolve STS endpoint when both"):
wrap_conn.get_service_endpoint_url("sts", sts_test_connection=True, sts_connection_assume=True)
# This check is only affects STS service endpoints
wrap_conn.get_service_endpoint_url("s3", sts_test_connection=True, sts_connection_assume=True)
| TestAwsConnectionWrapper |
python | pypa__setuptools | setuptools/_distutils/tests/test_dist.py | {
"start": 8721,
"end": 18793
} | class ____(support.TempdirManager):
def format_metadata(self, dist):
sio = io.StringIO()
dist.metadata.write_pkg_file(sio)
return sio.getvalue()
def test_simple_metadata(self):
attrs = {"name": "package", "version": "1.0"}
dist = Distribution(attrs)
meta = self.format_metadata(dist)
assert "Metadata-Version: 1.0" in meta
assert "provides:" not in meta.lower()
assert "requires:" not in meta.lower()
assert "obsoletes:" not in meta.lower()
def test_provides(self):
attrs = {
"name": "package",
"version": "1.0",
"provides": ["package", "package.sub"],
}
dist = Distribution(attrs)
assert dist.metadata.get_provides() == ["package", "package.sub"]
assert dist.get_provides() == ["package", "package.sub"]
meta = self.format_metadata(dist)
assert "Metadata-Version: 1.1" in meta
assert "requires:" not in meta.lower()
assert "obsoletes:" not in meta.lower()
def test_provides_illegal(self):
with pytest.raises(ValueError):
Distribution(
{"name": "package", "version": "1.0", "provides": ["my.pkg (splat)"]},
)
def test_requires(self):
attrs = {
"name": "package",
"version": "1.0",
"requires": ["other", "another (==1.0)"],
}
dist = Distribution(attrs)
assert dist.metadata.get_requires() == ["other", "another (==1.0)"]
assert dist.get_requires() == ["other", "another (==1.0)"]
meta = self.format_metadata(dist)
assert "Metadata-Version: 1.1" in meta
assert "provides:" not in meta.lower()
assert "Requires: other" in meta
assert "Requires: another (==1.0)" in meta
assert "obsoletes:" not in meta.lower()
def test_requires_illegal(self):
with pytest.raises(ValueError):
Distribution(
{"name": "package", "version": "1.0", "requires": ["my.pkg (splat)"]},
)
def test_requires_to_list(self):
attrs = {"name": "package", "requires": iter(["other"])}
dist = Distribution(attrs)
assert isinstance(dist.metadata.requires, list)
def test_obsoletes(self):
attrs = {
"name": "package",
"version": "1.0",
"obsoletes": ["other", "another (<1.0)"],
}
dist = Distribution(attrs)
assert dist.metadata.get_obsoletes() == ["other", "another (<1.0)"]
assert dist.get_obsoletes() == ["other", "another (<1.0)"]
meta = self.format_metadata(dist)
assert "Metadata-Version: 1.1" in meta
assert "provides:" not in meta.lower()
assert "requires:" not in meta.lower()
assert "Obsoletes: other" in meta
assert "Obsoletes: another (<1.0)" in meta
def test_obsoletes_illegal(self):
with pytest.raises(ValueError):
Distribution(
{"name": "package", "version": "1.0", "obsoletes": ["my.pkg (splat)"]},
)
def test_obsoletes_to_list(self):
attrs = {"name": "package", "obsoletes": iter(["other"])}
dist = Distribution(attrs)
assert isinstance(dist.metadata.obsoletes, list)
def test_classifier(self):
attrs = {
'name': 'Boa',
'version': '3.0',
'classifiers': ['Programming Language :: Python :: 3'],
}
dist = Distribution(attrs)
assert dist.get_classifiers() == ['Programming Language :: Python :: 3']
meta = self.format_metadata(dist)
assert 'Metadata-Version: 1.1' in meta
def test_classifier_invalid_type(self, caplog):
attrs = {
'name': 'Boa',
'version': '3.0',
'classifiers': ('Programming Language :: Python :: 3',),
}
d = Distribution(attrs)
# should have warning about passing a non-list
assert 'should be a list' in caplog.messages[0]
# should be converted to a list
assert isinstance(d.metadata.classifiers, list)
assert d.metadata.classifiers == list(attrs['classifiers'])
def test_keywords(self):
attrs = {
'name': 'Monty',
'version': '1.0',
'keywords': ['spam', 'eggs', 'life of brian'],
}
dist = Distribution(attrs)
assert dist.get_keywords() == ['spam', 'eggs', 'life of brian']
def test_keywords_invalid_type(self, caplog):
attrs = {
'name': 'Monty',
'version': '1.0',
'keywords': ('spam', 'eggs', 'life of brian'),
}
d = Distribution(attrs)
# should have warning about passing a non-list
assert 'should be a list' in caplog.messages[0]
# should be converted to a list
assert isinstance(d.metadata.keywords, list)
assert d.metadata.keywords == list(attrs['keywords'])
def test_platforms(self):
attrs = {
'name': 'Monty',
'version': '1.0',
'platforms': ['GNU/Linux', 'Some Evil Platform'],
}
dist = Distribution(attrs)
assert dist.get_platforms() == ['GNU/Linux', 'Some Evil Platform']
def test_platforms_invalid_types(self, caplog):
attrs = {
'name': 'Monty',
'version': '1.0',
'platforms': ('GNU/Linux', 'Some Evil Platform'),
}
d = Distribution(attrs)
# should have warning about passing a non-list
assert 'should be a list' in caplog.messages[0]
# should be converted to a list
assert isinstance(d.metadata.platforms, list)
assert d.metadata.platforms == list(attrs['platforms'])
def test_download_url(self):
attrs = {
'name': 'Boa',
'version': '3.0',
'download_url': 'http://example.org/boa',
}
dist = Distribution(attrs)
meta = self.format_metadata(dist)
assert 'Metadata-Version: 1.1' in meta
def test_long_description(self):
long_desc = textwrap.dedent(
"""\
example::
We start here
and continue here
and end here."""
)
attrs = {"name": "package", "version": "1.0", "long_description": long_desc}
dist = Distribution(attrs)
meta = self.format_metadata(dist)
meta = meta.replace('\n' + 8 * ' ', '\n')
assert long_desc in meta
def test_custom_pydistutils(self, temp_home):
"""
pydistutils.cfg is found
"""
jaraco.path.build({pydistutils_cfg: ''}, temp_home)
config_path = temp_home / pydistutils_cfg
assert str(config_path) in Distribution().find_config_files()
def test_extra_pydistutils(self, monkeypatch, tmp_path):
jaraco.path.build({'overrides.cfg': ''}, tmp_path)
filename = tmp_path / 'overrides.cfg'
monkeypatch.setenv('DIST_EXTRA_CONFIG', str(filename))
assert str(filename) in Distribution().find_config_files()
def test_fix_help_options(self):
help_tuples = [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
fancy_options = fix_help_options(help_tuples)
assert fancy_options[0] == ('a', 'b', 'c')
assert fancy_options[1] == (1, 2, 3)
def test_show_help(self, request, capsys):
# smoke test, just makes sure some help is displayed
dist = Distribution()
sys.argv = []
dist.help = True
dist.script_name = 'setup.py'
dist.parse_command_line()
output = [
line for line in capsys.readouterr().out.split('\n') if line.strip() != ''
]
assert output
def test_read_metadata(self):
attrs = {
"name": "package",
"version": "1.0",
"long_description": "desc",
"description": "xxx",
"download_url": "http://example.com",
"keywords": ['one', 'two'],
"requires": ['foo'],
}
dist = Distribution(attrs)
metadata = dist.metadata
# write it then reloads it
PKG_INFO = io.StringIO()
metadata.write_pkg_file(PKG_INFO)
PKG_INFO.seek(0)
metadata.read_pkg_file(PKG_INFO)
assert metadata.name == "package"
assert metadata.version == "1.0"
assert metadata.description == "xxx"
assert metadata.download_url == 'http://example.com'
assert metadata.keywords == ['one', 'two']
assert metadata.platforms is None
assert metadata.obsoletes is None
assert metadata.requires == ['foo']
def test_round_trip_through_email_generator(self):
"""
In pypa/setuptools#4033, it was shown that once PKG-INFO is
re-generated using ``email.generator.Generator``, some control
characters might cause problems.
"""
# Given a PKG-INFO file ...
attrs = {
"name": "package",
"version": "1.0",
"long_description": "hello\x0b\nworld\n",
}
dist = Distribution(attrs)
metadata = dist.metadata
with io.StringIO() as buffer:
metadata.write_pkg_file(buffer)
msg = buffer.getvalue()
# ... when it is read and re-written using stdlib's email library,
orig = email.message_from_string(msg)
policy = email.policy.EmailPolicy(
utf8=True,
mangle_from_=False,
max_line_length=0,
)
with io.StringIO() as buffer:
email.generator.Generator(buffer, policy=policy).flatten(orig)
buffer.seek(0)
regen = email.message_from_file(buffer)
# ... then it should be the same as the original
# (except for the specific line break characters)
orig_desc = set(orig["Description"].splitlines())
regen_desc = set(regen["Description"].splitlines())
assert regen_desc == orig_desc
| TestMetadata |
python | walkccc__LeetCode | solutions/2959. Number of Possible Sets of Closing Branches/2959.py | {
"start": 0,
"end": 1257
} | class ____:
def numberOfSets(
self,
n: int,
maxDistance: int,
roads: list[list[int]],
) -> int:
return sum(self._floydWarshall(n, maxDistance, roads, mask) <= maxDistance
for mask in range(1 << n))
def _floydWarshall(
self,
n: int,
maxDistanceThreshold: int,
roads: list[list[int]],
mask: int,
) -> list[list[int]]:
"""
Returns the maximum distance between any two branches, where the mask
represents the selected branches.
"""
maxDistance = 0
dist = [[maxDistanceThreshold + 1] * n for _ in range(n)]
for i in range(n):
if mask >> i & 1:
dist[i][i] = 0
for u, v, w in roads:
if mask >> u & 1 and mask >> v & 1:
dist[u][v] = min(dist[u][v], w)
dist[v][u] = min(dist[v][u], w)
for k in range(n):
if mask >> k & 1:
for i in range(n):
if mask >> i & 1:
for j in range(n):
if mask >> j & 1:
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
for i in range(n):
if mask >> i & 1:
for j in range(i + 1, n):
if mask >> j & 1:
maxDistance = max(maxDistance, dist[i][j])
return maxDistance
| Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/plan/state.py | {
"start": 1096,
"end": 2466
} | class ____(
NamedTuple(
"_PastExecutionState",
[
("run_id", str),
("produced_outputs", set[StepOutputHandle]),
# PastExecutionState, but no cycles allowed in NT
("parent_state", Optional[object]),
],
)
):
"""Information relevant to execution about the parent run, notably which outputs
were produced by which run ids, allowing for the proper ones to be loaded.
"""
def __new__(
cls,
run_id: str,
produced_outputs: set[StepOutputHandle],
parent_state: Optional["PastExecutionState"],
):
return super().__new__(
cls,
check.str_param(run_id, "run_id"),
check.set_param(produced_outputs, "produced_outputs", StepOutputHandle),
check.opt_inst_param(parent_state, "parent_state", PastExecutionState),
)
def get_parent_state(self) -> Optional["PastExecutionState"]:
return cast("Optional[PastExecutionState]", self.parent_state)
# Previously, step_output_versions was stored as a list of StepOutputVersionData objects. It
# would have to be converted to a dict for use. The sole purpose of the `StepOutputVersion` objects
# was to make the dict key-value pairs serializable. Using a custom field serializer allows us to
# avoid this extra complexity.
| PastExecutionState |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/env_manager.py | {
"start": 719,
"end": 1170
} | class ____(NamedTuple):
current_all_step_result: AllStepResult
worker_id: int
brain_name_to_action_info: Dict[BehaviorName, ActionInfo]
environment_stats: EnvironmentStats
@property
def name_behavior_ids(self) -> Iterable[BehaviorName]:
return self.current_all_step_result.keys()
@staticmethod
def empty(worker_id: int) -> "EnvironmentStep":
return EnvironmentStep({}, worker_id, {}, {})
| EnvironmentStep |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/databricks_sql_datasource.py | {
"start": 1716,
"end": 1914
} | class ____(pydantic.UrlError):
"""
Custom Pydantic error for missing query in DatabricksDsn.
"""
code = "url.query"
msg_template = "URL query is invalid or missing"
| _UrlQueryError |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 756799,
"end": 757615
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"created_at",
"email",
"enterprise",
"invitee",
"inviter",
"role",
)
created_at = sgqlc.types.Field(
sgqlc.types.non_null(DateTime), graphql_name="createdAt"
)
email = sgqlc.types.Field(String, graphql_name="email")
enterprise = sgqlc.types.Field(
sgqlc.types.non_null(Enterprise), graphql_name="enterprise"
)
invitee = sgqlc.types.Field("User", graphql_name="invitee")
inviter = sgqlc.types.Field("User", graphql_name="inviter")
role = sgqlc.types.Field(
sgqlc.types.non_null(EnterpriseAdministratorRole), graphql_name="role"
)
| EnterpriseAdministratorInvitation |
python | ray-project__ray | python/ray/serve/tests/test_config_files/test_dag/dir/subdir/a/add_and_sub.py | {
"start": 889,
"end": 1445
} | class ____:
def __init__(self, adder: DeploymentHandle, subtractor: DeploymentHandle):
self.adder = adder
self.subtractor = subtractor
async def __call__(self, request: starlette.requests.Request) -> int:
op, input = await request.json()
if op == Operation.ADD:
return await self.adder.add.remote(input)
elif op == Operation.SUBTRACT:
return await self.subtractor.subtract.remote(input)
adder = Add.bind()
subtractor = Subtract.bind()
serve_dag = Router.bind(adder, subtractor)
| Router |
python | sympy__sympy | sympy/physics/quantum/hilbert.py | {
"start": 16499,
"end": 19632
} | class ____(HilbertSpace):
"""An exponentiated Hilbert space [1]_.
Tensor powers (repeated tensor products) are represented by the
operator ``**`` Identical Hilbert spaces that are multiplied together
will be automatically combined into a single tensor power object.
Any Hilbert space, product, or sum may be raised to a tensor power. The
``TensorPowerHilbertSpace`` takes two arguments: the Hilbert space; and the
tensor power (number).
Examples
========
>>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
>>> from sympy import symbols
>>> n = symbols('n')
>>> c = ComplexSpace(2)
>>> hs = c**n
>>> hs
C(2)**n
>>> hs.dimension
2**n
>>> c = ComplexSpace(2)
>>> c*c
C(2)**2
>>> f = FockSpace()
>>> c*f*f
C(2)*F**2
References
==========
.. [1] https://en.wikipedia.org/wiki/Hilbert_space#Tensor_products
"""
def __new__(cls, *args):
r = cls.eval(args)
if isinstance(r, Basic):
return r
return Basic.__new__(cls, *r)
@classmethod
def eval(cls, args):
new_args = args[0], sympify(args[1])
exp = new_args[1]
#simplify hs**1 -> hs
if exp is S.One:
return args[0]
#simplify hs**0 -> 1
if exp is S.Zero:
return S.One
#check (and allow) for hs**(x+42+y...) case
if len(exp.atoms()) == 1:
if not (exp.is_Integer and exp >= 0 or exp.is_Symbol):
raise ValueError('Hilbert spaces can only be raised to \
positive integers or Symbols: %r' % exp)
else:
for power in exp.atoms():
if not (power.is_Integer or power.is_Symbol):
raise ValueError('Tensor powers can only contain integers \
or Symbols: %r' % power)
return new_args
@property
def base(self):
return self.args[0]
@property
def exp(self):
return self.args[1]
@property
def dimension(self):
if self.base.dimension is S.Infinity:
return S.Infinity
else:
return self.base.dimension**self.exp
def _sympyrepr(self, printer, *args):
return "TensorPowerHilbertSpace(%s,%s)" % (printer._print(self.base,
*args), printer._print(self.exp, *args))
def _sympystr(self, printer, *args):
return "%s**%s" % (printer._print(self.base, *args),
printer._print(self.exp, *args))
def _pretty(self, printer, *args):
pform_exp = printer._print(self.exp, *args)
if printer._use_unicode:
pform_exp = prettyForm(*pform_exp.left(prettyForm('\N{N-ARY CIRCLED TIMES OPERATOR}')))
else:
pform_exp = prettyForm(*pform_exp.left(prettyForm('x')))
pform_base = printer._print(self.base, *args)
return pform_base**pform_exp
def _latex(self, printer, *args):
base = printer._print(self.base, *args)
exp = printer._print(self.exp, *args)
return r'{%s}^{\otimes %s}' % (base, exp)
| TensorPowerHilbertSpace |
python | pyinstaller__pyinstaller | bootloader/waflib/Tools/fc.py | {
"start": 1771,
"end": 4173
} | class ____(Task.Task):
color = 'GREEN'
run_str = '${FC} ${FCFLAGS} ${FCINCPATH_ST:INCPATHS} ${FCDEFINES_ST:DEFINES} ${_FCMODOUTFLAGS} ${FC_TGT_F}${TGT[0].abspath()} ${FC_SRC_F}${SRC[0].abspath()} ${FCPPFLAGS}'
vars = ["FORTRANMODPATHFLAG"]
def scan(self):
tmp = fc_scan.fortran_parser(self.generator.includes_nodes)
tmp.task = self
tmp.start(self.inputs[0])
return (tmp.nodes, tmp.names)
def runnable_status(self):
if getattr(self, 'mod_fortran_done', None):
return super(fc, self).runnable_status()
bld = self.generator.bld
lst = get_fortran_tasks(self)
for tsk in lst:
tsk.mod_fortran_done = True
for tsk in lst:
ret = tsk.runnable_status()
if ret == Task.ASK_LATER:
for x in lst:
x.mod_fortran_done = None
return Task.ASK_LATER
ins = Utils.defaultdict(set)
outs = Utils.defaultdict(set)
for tsk in lst:
key = tsk.uid()
for x in bld.raw_deps[key]:
if x.startswith('MOD@'):
name = bld.modfile(x.replace('MOD@', ''))
node = bld.srcnode.find_or_declare(name)
tsk.set_outputs(node)
outs[node].add(tsk)
for tsk in lst:
key = tsk.uid()
for x in bld.raw_deps[key]:
if x.startswith('USE@'):
name = bld.modfile(x.replace('USE@', ''))
node = bld.srcnode.find_resource(name)
if node and node not in tsk.outputs:
if not node in bld.node_deps[key]:
bld.node_deps[key].append(node)
ins[node].add(tsk)
for k in ins.keys():
for a in ins[k]:
a.run_after.update(outs[k])
for x in outs[k]:
self.generator.bld.producer.revdeps[x].add(a)
tmp = []
for t in outs[k]:
tmp.extend(t.outputs)
a.dep_nodes.extend(tmp)
a.dep_nodes.sort(key=lambda x: x.abspath())
for tsk in lst:
try:
delattr(tsk, 'cache_sig')
except AttributeError:
pass
return super(fc, self).runnable_status()
| fc |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 89047,
"end": 91631
} | class ____(Request):
"""
Archive tasks
:param ids: Entities to move
:type ids: Sequence[str]
:param status_reason: Reason for status change
:type status_reason: str
:param status_message: Extra information regarding status change
:type status_message: str
"""
_service = "tasks"
_action = "archive_many"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"ids": {
"description": "Entities to move",
"items": {"type": "string"},
"type": "array",
},
"status_message": {
"description": "Extra information regarding status change",
"type": "string",
},
"status_reason": {
"description": "Reason for status change",
"type": "string",
},
},
"required": ["ids"],
"type": "object",
}
def __init__(
self, ids: List[str], status_reason: Optional[str] = None, status_message: Optional[str] = None, **kwargs: Any
) -> None:
super(ArchiveManyRequest, self).__init__(**kwargs)
self.ids = ids
self.status_reason = status_reason
self.status_message = status_message
@schema_property("ids")
def ids(self) -> List[str]:
return self._property_ids
@ids.setter
def ids(self, value: List[str]) -> None:
if value is None:
self._property_ids = None
return
self.assert_isinstance(value, "ids", (list, tuple))
self.assert_isinstance(value, "ids", six.string_types, is_array=True)
self._property_ids = value
@schema_property("status_reason")
def status_reason(self) -> Optional[str]:
return self._property_status_reason
@status_reason.setter
def status_reason(self, value: Optional[str]) -> None:
if value is None:
self._property_status_reason = None
return
self.assert_isinstance(value, "status_reason", six.string_types)
self._property_status_reason = value
@schema_property("status_message")
def status_message(self) -> Optional[str]:
return self._property_status_message
@status_message.setter
def status_message(self, value: Optional[str]) -> None:
if value is None:
self._property_status_message = None
return
self.assert_isinstance(value, "status_message", six.string_types)
self._property_status_message = value
| ArchiveManyRequest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1293286,
"end": 1295840
} | class ____(sgqlc.types.Type, Node):
"""Information for an uploaded package."""
__schema__ = github_schema
__field_names__ = ("latest_version", "name", "package_type", "repository", "statistics", "version", "versions")
latest_version = sgqlc.types.Field("PackageVersion", graphql_name="latestVersion")
"""Find the latest version for the package."""
name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name")
"""Identifies the name of the package."""
package_type = sgqlc.types.Field(sgqlc.types.non_null(PackageType), graphql_name="packageType")
"""Identifies the type of the package."""
repository = sgqlc.types.Field("Repository", graphql_name="repository")
"""The repository this package belongs to."""
statistics = sgqlc.types.Field(PackageStatistics, graphql_name="statistics")
"""Statistics about package activity."""
version = sgqlc.types.Field(
"PackageVersion",
graphql_name="version",
args=sgqlc.types.ArgDict((("version", sgqlc.types.Arg(sgqlc.types.non_null(String), graphql_name="version", default=None)),)),
)
"""Find package version by version string.
Arguments:
* `version` (`String!`): The package version.
"""
versions = sgqlc.types.Field(
sgqlc.types.non_null(PackageVersionConnection),
graphql_name="versions",
args=sgqlc.types.ArgDict(
(
(
"order_by",
sgqlc.types.Arg(PackageVersionOrder, graphql_name="orderBy", default={"field": "CREATED_AT", "direction": "DESC"}),
),
("after", sgqlc.types.Arg(String, graphql_name="after", default=None)),
("before", sgqlc.types.Arg(String, graphql_name="before", default=None)),
("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)),
("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)),
)
),
)
"""list of versions for this package
Arguments:
* `order_by` (`PackageVersionOrder`): Ordering of the returned
packages. (default: `{field: CREATED_AT, direction: DESC}`)
* `after` (`String`): Returns the elements in the list that come
after the specified cursor.
* `before` (`String`): Returns the elements in the list that come
before the specified cursor.
* `first` (`Int`): Returns the first _n_ elements from the list.
* `last` (`Int`): Returns the last _n_ elements from the list.
"""
| Package |
python | readthedocs__readthedocs.org | readthedocs/audit/migrations/0004_change_ip_field_type.py | {
"start": 149,
"end": 547
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("audit", "0003_update_ordering"),
]
operations = [
migrations.AlterField(
model_name="auditlog",
name="ip",
field=models.CharField(
blank=True, max_length=250, null=True, verbose_name="IP address"
),
),
]
| Migration |
python | bokeh__bokeh | tests/unit/bokeh/embed/test_wrappers__embed.py | {
"start": 1796,
"end": 2661
} | class ____:
def test_render(self) -> None:
assert bew.wrap_in_script_tag("code\nmorecode") == """
<script type="text/javascript">
code
morecode
</script>\
"""
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
def test__ONLOAD() -> None:
assert bew._ONLOAD == """\
(function() {
const fn = function() {
%(code)s
};
if (document.readyState != "loading") fn();
else document.addEventListener("DOMContentLoaded", fn);
})();\
"""
def test__SAFELY() -> None:
assert bew._SAFELY == """\
Bokeh.safely(function() {
%(code)s
});"""\
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
| Test_wrap_in_script_tag |
python | zarr-developers__zarr-python | tests/test_dtype/test_npy/test_time.py | {
"start": 300,
"end": 950
} | class ____(BaseTestZDType):
def json_scalar_equals(self, scalar1: object, scalar2: object) -> bool:
# This method gets overridden here to support the equivalency between NaT and
# -9223372036854775808 fill values
nat_scalars = (-9223372036854775808, "NaT")
if scalar1 in nat_scalars and scalar2 in nat_scalars:
return True
return scalar1 == scalar2
def scalar_equals(self, scalar1: object, scalar2: object) -> bool:
if np.isnan(scalar1) and np.isnan(scalar2): # type: ignore[call-overload]
return True
return super().scalar_equals(scalar1, scalar2)
| _TestTimeBase |
python | readthedocs__readthedocs.org | readthedocs/integrations/migrations/0015_add_github_app_integration.py | {
"start": 149,
"end": 1227
} | class ____(migrations.Migration):
safe = Safe.always()
dependencies = [
("integrations", "0014_add_index_speedup"),
]
operations = [
migrations.CreateModel(
name="GitHubAppIntegration",
fields=[],
options={
"proxy": True,
"indexes": [],
"constraints": [],
},
bases=("integrations.integration",),
),
migrations.AlterField(
model_name="integration",
name="integration_type",
field=models.CharField(
choices=[
("github_webhook", "GitHub incoming webhook"),
("bitbucket_webhook", "Bitbucket incoming webhook"),
("gitlab_webhook", "GitLab incoming webhook"),
("api_webhook", "Generic API incoming webhook"),
("githubapp", "GitHub App"),
],
max_length=32,
verbose_name="Integration type",
),
),
]
| Migration |
python | getsentry__sentry | tests/sentry/workflow_engine/endpoints/validators/actions/test_ticketing.py | {
"start": 1501,
"end": 1643
} | class ____(BaseTicketingActionValidatorTest):
__test__ = True
provider = Action.Type.GITHUB_ENTERPRISE
| TestGithubEnterpriseActionValidator |
python | tensorflow__tensorflow | tensorflow/python/training/basic_session_run_hooks.py | {
"start": 3024,
"end": 5229
} | class ____(_HookTimer):
"""Timer that triggers at most once every N seconds or once every N steps.
This symbol is also exported to v2 in tf.estimator namespace. See
https://github.com/tensorflow/estimator/blob/master/tensorflow_estimator/python/estimator/hooks/basic_session_run_hooks.py
"""
def __init__(self, every_secs=None, every_steps=None):
self.reset()
self._every_secs = every_secs
self._every_steps = every_steps
if self._every_secs is None and self._every_steps is None:
raise ValueError("Either every_secs or every_steps should be provided.")
if (self._every_secs is not None) and (self._every_steps is not None):
raise ValueError("Can not provide both every_secs and every_steps.")
super(SecondOrStepTimer, self).__init__()
def reset(self):
self._last_triggered_step = None
self._last_triggered_time = None
def should_trigger_for_step(self, step):
"""Return true if the timer should trigger for the specified step.
Args:
step: Training step to trigger on.
Returns:
True if the difference between the current time and the time of the last
trigger exceeds `every_secs`, or if the difference between the current
step and the last triggered step exceeds `every_steps`. False otherwise.
"""
if self._last_triggered_step is None:
return True
if self._last_triggered_step == step:
return False
if self._every_secs is not None:
if time.time() >= self._last_triggered_time + self._every_secs:
return True
if self._every_steps is not None:
if step >= self._last_triggered_step + self._every_steps:
return True
return False
def update_last_triggered_step(self, step):
current_time = time.time()
if self._last_triggered_time is None:
elapsed_secs = None
elapsed_steps = None
else:
elapsed_secs = current_time - self._last_triggered_time
elapsed_steps = step - self._last_triggered_step
self._last_triggered_time = current_time
self._last_triggered_step = step
return (elapsed_secs, elapsed_steps)
def last_triggered_step(self):
return self._last_triggered_step
| SecondOrStepTimer |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 60837,
"end": 61180
} | class ____(BaseModel):
usage: Optional["Usage"] = Field(default=None, description="")
time: Optional[float] = Field(default=None, description="Time spent to process this request")
status: Optional[str] = Field(default=None, description="")
result: Optional["UpdateResult"] = Field(default=None, description="")
| InlineResponse2005 |
python | jazzband__django-oauth-toolkit | tests/migrations/0001_initial.py | {
"start": 92,
"end": 1448
} | class ____(migrations.Migration):
initial = True
dependencies = [
]
run_before = [
('oauth2_provider', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='BaseTestApplication',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
),
migrations.CreateModel(
name='SampleAccessToken',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
),
migrations.CreateModel(
name='SampleApplication',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
),
migrations.CreateModel(
name='SampleGrant',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
),
migrations.CreateModel(
name='SampleRefreshToken',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
),
]
| Migration |
python | astropy__astropy | astropy/cosmology/_src/tests/io/base.py | {
"start": 6036,
"end": 7433
} | class ____(IODirectTestBase, ToFromTestMixinBase):
"""Directly test ``read/write_<format>``.
These functions are not public API and are discouraged from public use, in
favor of ``Cosmology.read/write(..., format="<format>")``. They are tested
because they are used internally and because some tests for the
methods on |Cosmology| don't need to be run in the |Cosmology| class's
large test matrix.
This class will not be directly called by :mod:`pytest` since its name does
not begin with ``Test``. To activate the contained tests this class must
be inherited in a subclass.
Subclasses should have an attribute ``functions`` which is a dictionary
containing two items: ``"read"=<function for read>`` and
``"write"=<function for write>``.
"""
@pytest.fixture(scope="class")
def read(self):
"""Read Cosmology from file using function ``read``."""
def use_read(*args, **kwargs):
kwargs.pop("format", None) # specific to Cosmology.from_format
return self.functions["read"](*args, **kwargs)
return use_read
@pytest.fixture(scope="class")
def write(self, cosmo):
"""Write Cosmology to file using function ``write``."""
def use_write(*args, **kwargs):
return self.functions["write"](cosmo, *args, **kwargs)
return use_write
| ReadWriteDirectTestBase |
python | readthedocs__readthedocs.org | readthedocs/organizations/forms.py | {
"start": 7969,
"end": 8492
} | class ____(forms.ModelForm):
"""Form to manage access of teams to projects."""
class Meta:
model = Team
fields = ["projects"]
def __init__(self, *args, **kwargs):
self.organization = kwargs.pop("organization", None)
super().__init__(*args, **kwargs)
self.fields["projects"] = forms.ModelMultipleChoiceField(
queryset=self.organization.projects,
widget=forms.CheckboxSelectMultiple,
required=False,
)
| OrganizationTeamProjectForm |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 14038,
"end": 14559
} | class ____(VOTableSpecWarning):
"""Invalid astroYear.
As astro year field is a Besselian or Julian year matching the
regular expression::
^[JB]?[0-9]+([.][0-9]*)?$
Defined in this XML Schema snippet::
<xs:simpleType name="astroYear">
<xs:restriction base="xs:token">
<xs:pattern value="[JB]?[0-9]+([.][0-9]*)?"/>
</xs:restriction>
</xs:simpleType>
"""
message_template = "Invalid astroYear in {}: '{}'"
default_args = ("x", "y")
| W07 |
python | kamyu104__LeetCode-Solutions | Python/minimum-size-subarray-in-infinite-array.py | {
"start": 60,
"end": 801
} | class ____(object):
def minSizeSubarray(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
INF = float("inf")
q, target = divmod(target, sum(nums))
if not target:
return q*len(nums)
result = INF
curr = left = 0
for right in xrange((len(nums)-1)+(len(nums)-1)):
curr += nums[right%len(nums)]
while curr > target:
curr -= nums[left%len(nums)]
left += 1
if curr == target:
result = min(result, right-left+1)
return result+q*len(nums) if result != INF else -1
# Time: O(n)
# Space: O(n)
# prefix sum, hash table
| Solution |
python | pyinstaller__pyinstaller | bootloader/waflib/Tools/javaw.py | {
"start": 8881,
"end": 13193
} | class ____(Task.Task):
color = 'BLUE'
def __str__(self):
return '%s: %s -> %s\n' % (self.__class__.__name__, self.generator.srcdir, self.generator.javadoc_output)
def run(self):
env = self.env
bld = self.generator.bld
wd = bld.bldnode
srcpath = self.generator.path.abspath() + os.sep + self.generator.srcdir
srcpath += os.pathsep
srcpath += self.generator.path.get_bld().abspath() + os.sep + self.generator.srcdir
classpath = env.CLASSPATH
classpath += os.pathsep
classpath += os.pathsep.join(self.classpath)
classpath = "".join(classpath)
self.last_cmd = lst = []
lst.extend(Utils.to_list(env.JAVADOC))
lst.extend(['-d', self.generator.javadoc_output.abspath()])
lst.extend(['-sourcepath', srcpath])
lst.extend(['-classpath', classpath])
lst.extend(['-subpackages'])
lst.extend(self.generator.javadoc_package)
lst = [x for x in lst if x]
self.generator.bld.cmd_and_log(lst, cwd=wd, env=env.env or None, quiet=0)
def post_run(self):
nodes = self.generator.javadoc_output.ant_glob('**', quiet=True)
for node in nodes:
self.generator.bld.node_sigs[node] = self.uid()
self.generator.bld.task_sigs[self.uid()] = self.cache_sig
def configure(self):
java_path = self.environ['PATH'].split(os.pathsep)
v = self.env
if 'JAVA_HOME' in self.environ:
java_path = [os.path.join(self.environ['JAVA_HOME'], 'bin')] + java_path
self.env.JAVA_HOME = [self.environ['JAVA_HOME']]
for x in 'javac java jar javadoc'.split():
self.find_program(x, var=x.upper(), path_list=java_path, mandatory=(x not in ('javadoc')))
if 'CLASSPATH' in self.environ:
v.CLASSPATH = self.environ['CLASSPATH']
if not v.JAR:
self.fatal('jar is required for making java packages')
if not v.JAVAC:
self.fatal('javac is required for compiling java classes')
v.JARCREATE = 'cf'
v.JAVACFLAGS = []
@conf
def check_java_class(self, classname, with_classpath=None):
javatestdir = '.waf-javatest'
classpath = javatestdir
if self.env.CLASSPATH:
classpath += os.pathsep + self.env.CLASSPATH
if isinstance(with_classpath, str):
classpath += os.pathsep + with_classpath
shutil.rmtree(javatestdir, True)
os.mkdir(javatestdir)
Utils.writef(os.path.join(javatestdir, 'Test.java'), class_check_source)
self.exec_command(self.env.JAVAC + [os.path.join(javatestdir, 'Test.java')], shell=False)
cmd = self.env.JAVA + ['-cp', classpath, 'Test', classname]
self.to_log("%s\n" % str(cmd))
found = self.exec_command(cmd, shell=False)
self.msg('Checking for java class %s' % classname, not found)
shutil.rmtree(javatestdir, True)
return found
@conf
def check_jni_headers(conf):
if not conf.env.CC_NAME and not conf.env.CXX_NAME:
conf.fatal('load a compiler first (gcc, g++, ..)')
if not conf.env.JAVA_HOME:
conf.fatal('set JAVA_HOME in the system environment')
javaHome = conf.env.JAVA_HOME[0]
dir = conf.root.find_dir(conf.env.JAVA_HOME[0] + '/include')
if dir is None:
dir = conf.root.find_dir(conf.env.JAVA_HOME[0] + '/../Headers')
if dir is None:
conf.fatal('JAVA_HOME does not seem to be set properly')
f = dir.ant_glob('**/(jni|jni_md).h')
incDirs = [x.parent.abspath() for x in f]
dir = conf.root.find_dir(conf.env.JAVA_HOME[0])
f = dir.ant_glob('**/*jvm.(so|dll|dylib)')
libDirs = [x.parent.abspath() for x in f] or [javaHome]
f = dir.ant_glob('**/*jvm.(lib)')
if f:
libDirs = [[x, y.parent.abspath()] for x in libDirs for y in f]
if conf.env.DEST_OS == 'freebsd':
conf.env.append_unique('LINKFLAGS_JAVA', '-pthread')
for d in libDirs:
try:
conf.check(
header_name='jni.h',
define_name='HAVE_JNI_H',
lib='jvm',
libpath=d,
includes=incDirs,
uselib_store='JAVA',
uselib='JAVA'
)
except Exception:
pass
else:
break
else:
conf.fatal('could not find lib jvm in %r (see config.log)' % libDirs)
| javadoc |
python | tensorflow__tensorflow | tensorflow/python/tpu/tpu_optimizer.py | {
"start": 1158,
"end": 8642
} | class ____(optimizer.Optimizer):
"""An optimizer that averages gradients across TPU shards."""
def __init__(self,
opt,
reduction=losses.Reduction.MEAN,
name="CrossShardOptimizer",
group_assignment=None):
"""Construct a new cross-shard optimizer.
Args:
opt: An existing `Optimizer` to encapsulate.
reduction: The reduction to apply to the shard losses.
name: Optional name prefix for the operations created when applying
gradients. Defaults to "CrossShardOptimizer".
group_assignment: Optional 2d int32 lists with shape
[num_groups, num_replicas_per_group] which describles how to apply
optimizer to subgroups.
Raises:
ValueError: If reduction is not a valid cross-shard reduction.
"""
accepted_reductions = (losses.Reduction.SUM, losses.Reduction.MEAN)
if reduction not in accepted_reductions:
raise ValueError(
f"Argument `reduction` should be one of {accepted_reductions}. "
f"Received: {reduction}")
if not isinstance(opt, optimizer.Optimizer):
raise TypeError(
"CrossShardOptimizer only works with tf.training.Optimizer and not "
f"Keras Optimizer. Received: {opt}. "
"If you are using TPUStrategy, "
"Keras Optimizer will sum gradients across replicas."
"If you want to average your gradients, rescale your loss with: "
"`loss /= global_batch_size`")
super(CrossShardOptimizer, self).__init__(False, name)
self._opt = opt
self._reduction = reduction
self._group_assignment = group_assignment
def _verify_and_get_subgroup_size(self, group_assignment, num_shards):
"""Verify group_assignment and get the subgroup size".
Args:
group_assignment: list of group ids for applying the optimizer
to subgroups.
num_shards: The number of TPU shards.
Returns:
The size of one subgroup in group_assignment.
Raises:
ValueError: If group_assignment is invalid.
"""
if not group_assignment:
return None
if not (isinstance(group_assignment, list) and
all(isinstance(i, list) for i in group_assignment)):
raise ValueError(
f"Argument `group_assignment` must be a list of lists. "
f"Received: {group_assignment}")
replica_ids = set()
for g in group_assignment:
for i in g:
replica_ids.add(i)
if set(range(num_shards)) != replica_ids:
raise ValueError(
f"Argument `group_assignment` must be a permutation of "
f"range({num_shards}). Received: {group_assignment}")
subgroup_size_list = [len(group) for group in group_assignment]
if all(subgroup_size_list[0] == size for size in subgroup_size_list):
return subgroup_size_list[0]
else:
raise ValueError("The size of each subgroup in `group_assignment` must "
f"be equal. Received: {group_assignment}")
def compute_gradients(self, loss, var_list=None, **kwargs):
"""Compute gradients of "loss" for the variables in "var_list".
This simply wraps `compute_gradients()` from the real optimizer. The
gradients will be aggregated in `apply_gradients()` so that user can
modify the gradients like clipping with per replica global norm if needed.
The global norm with aggregated gradients can be bad as one replica's huge
gradients can hurt the gradients from other replicas.
When the CrossShardOptimizer is constructed with
`reduction == losses.Reduction.MEAN` (default), this function scales the
loss by `1.0 / num_shards` before computing the gradients. Assuming the
optimizer uses the default implementation of `compute_gradients()`, the
gradients of the scaled loss are scaled by `1.0 / num_shards` compared to
the gradients of the original loss. This scaling factor is important because
`apply_gradients()` sums gradients across shards, rather than averaging
them. However, the scaling factor must be taken into account when clipping
the norm of the gradients or performing other postprocessing.
Args:
loss: A Tensor containing the value to minimize.
var_list: Optional list or tuple of `tf.Variable` to update to minimize
`loss`. Defaults to the list of variables collected in the graph
under the key `GraphKey.TRAINABLE_VARIABLES`.
**kwargs: Keyword arguments for compute_gradients().
Returns:
A list of (gradient, variable) pairs.
Raises:
ValueError: If not within a tpu_shard_context or group_assignment is
invalid.
"""
num_shards = tpu_function.get_tpu_context().number_of_shards
if num_shards is None:
logging.warning(
"CrossShardOptimizer should be used within a tpu_shard_context, but "
"got unset number_of_shards. Assuming 1.")
num_shards = 1
subgroup_size = self._verify_and_get_subgroup_size(self._group_assignment,
num_shards)
if num_shards > 1 and self._reduction == losses.Reduction.MEAN:
if self._group_assignment:
scale = 1.0 / subgroup_size
else:
scale = 1.0 / num_shards
loss *= scale
return self._opt.compute_gradients(loss, var_list=var_list, **kwargs)
def apply_gradients(self, grads_and_vars, global_step=None, name=None):
"""Apply gradients to variables.
Calls tpu_ops.cross_replica_sum() to sum gradient contributions across
replicas, and then applies the real optimizer.
Args:
grads_and_vars: List of (gradient, variable) pairs as returned by
compute_gradients().
global_step: Optional Variable to increment by one after the
variables have been updated.
name: Optional name for the returned operation. Default to the
name passed to the Optimizer constructor.
Returns:
An `Operation` that applies the gradients. If `global_step` was not None,
that operation also increments `global_step`.
Raises:
ValueError: If the grads_and_vars is malformed.
"""
summed_grads_and_vars = []
for (grad, var) in grads_and_vars:
if grad is None:
summed_grads_and_vars.append((grad, var))
else:
with ops.colocate_with(grad):
summed_grads_and_vars.append((tpu_ops.cross_replica_sum(
grad, self._group_assignment), var))
return self._opt.apply_gradients(summed_grads_and_vars, global_step, name)
def get_slot(self, *args, **kwargs):
"""Return a slot named "name" created for "var" by the Optimizer.
This simply wraps the get_slot() from the actual optimizer.
Args:
*args: Arguments for get_slot().
**kwargs: Keyword arguments for get_slot().
Returns:
The `Variable` for the slot if it was created, `None` otherwise.
"""
return self._opt.get_slot(*args, **kwargs)
def get_slot_names(self, *args, **kwargs):
"""Return a list of the names of slots created by the `Optimizer`.
This simply wraps the get_slot_names() from the actual optimizer.
Args:
*args: Arguments for get_slot().
**kwargs: Keyword arguments for get_slot().
Returns:
A list of strings.
"""
return self._opt.get_slot_names(*args, **kwargs)
def variables(self):
"""Forwarding the variables from the underlying optimizer."""
return self._opt.variables()
| CrossShardOptimizer |
python | apache__airflow | providers/apache/hive/src/airflow/providers/apache/hive/plugins/hive.py | {
"start": 964,
"end": 1146
} | class ____(AirflowPlugin):
"""Hive plugin - delivering macros used by users that use the provider."""
name = "hive"
macros = [max_partition, closest_ds_partition]
| HivePlugin |
python | scipy__scipy | scipy/optimize/tests/test_trustregion_krylov.py | {
"start": 520,
"end": 6571
} | class ____:
def test_for_the_easy_case(self):
# `H` is chosen such that `g` is not orthogonal to the
# eigenvector associated with the smallest eigenvalue.
H = np.array([[1.0, 0.0, 4.0],
[0.0, 2.0, 0.0],
[4.0, 0.0, 3.0]])
g = np.array([5.0, 0.0, 4.0])
# Trust Radius
trust_radius = 1.0
# Solve Subproblem
subprob = KrylovQP(x=0,
fun=lambda x: 0,
jac=lambda x: g,
hess=lambda x: None,
hessp=lambda x, y: H.dot(y))
p, hits_boundary = subprob.solve(trust_radius)
assert_array_almost_equal(p, np.array([-1.0, 0.0, 0.0]))
assert_equal(hits_boundary, True)
# check kkt satisfaction
assert_almost_equal(
np.linalg.norm(H.dot(p) + subprob.lam * p + g),
0.0)
# check trust region constraint
assert_almost_equal(np.linalg.norm(p), trust_radius)
trust_radius = 0.5
p, hits_boundary = subprob.solve(trust_radius)
assert_array_almost_equal(p,
np.array([-0.46125446, 0., -0.19298788]))
assert_equal(hits_boundary, True)
# check kkt satisfaction
assert_almost_equal(
np.linalg.norm(H.dot(p) + subprob.lam * p + g),
0.0)
# check trust region constraint
assert_almost_equal(np.linalg.norm(p), trust_radius)
def test_for_the_hard_case(self):
# `H` is chosen such that `g` is orthogonal to the
# eigenvector associated with the smallest eigenvalue.
H = np.array([[1.0, 0.0, 4.0],
[0.0, 2.0, 0.0],
[4.0, 0.0, 3.0]])
g = np.array([0.0, 2.0, 0.0])
# Trust Radius
trust_radius = 1.0
# Solve Subproblem
subprob = KrylovQP(x=0,
fun=lambda x: 0,
jac=lambda x: g,
hess=lambda x: None,
hessp=lambda x, y: H.dot(y))
p, hits_boundary = subprob.solve(trust_radius)
assert_array_almost_equal(p, np.array([0.0, -1.0, 0.0]))
# check kkt satisfaction
assert_almost_equal(
np.linalg.norm(H.dot(p) + subprob.lam * p + g),
0.0)
# check trust region constraint
assert_almost_equal(np.linalg.norm(p), trust_radius)
trust_radius = 0.5
p, hits_boundary = subprob.solve(trust_radius)
assert_array_almost_equal(p, np.array([0.0, -0.5, 0.0]))
# check kkt satisfaction
assert_almost_equal(
np.linalg.norm(H.dot(p) + subprob.lam * p + g),
0.0)
# check trust region constraint
assert_almost_equal(np.linalg.norm(p), trust_radius)
def test_for_interior_convergence(self):
H = np.array([[1.812159, 0.82687265, 0.21838879, -0.52487006, 0.25436988],
[0.82687265, 2.66380283, 0.31508988, -0.40144163, 0.08811588],
[0.21838879, 0.31508988, 2.38020726, -0.3166346, 0.27363867],
[-0.52487006, -0.40144163, -0.3166346, 1.61927182, -0.42140166],
[0.25436988, 0.08811588, 0.27363867, -0.42140166, 1.33243101]])
g = np.array([0.75798952, 0.01421945, 0.33847612, 0.83725004, -0.47909534])
trust_radius = 1.1
# Solve Subproblem
subprob = KrylovQP(x=0,
fun=lambda x: 0,
jac=lambda x: g,
hess=lambda x: None,
hessp=lambda x, y: H.dot(y))
p, hits_boundary = subprob.solve(trust_radius)
# check kkt satisfaction
assert_almost_equal(
np.linalg.norm(H.dot(p) + subprob.lam * p + g),
0.0)
assert_array_almost_equal(p, [-0.68585435, 0.1222621, -0.22090999,
-0.67005053, 0.31586769])
assert_array_almost_equal(hits_boundary, False)
def test_for_very_close_to_zero(self):
H = np.array([[0.88547534, 2.90692271, 0.98440885, -0.78911503, -0.28035809],
[2.90692271, -0.04618819, 0.32867263, -0.83737945, 0.17116396],
[0.98440885, 0.32867263, -0.87355957, -0.06521957, -1.43030957],
[-0.78911503, -0.83737945, -0.06521957, -1.645709, -0.33887298],
[-0.28035809, 0.17116396, -1.43030957, -0.33887298, -1.68586978]])
g = np.array([0, 0, 0, 0, 1e-6])
trust_radius = 1.1
# Solve Subproblem
subprob = KrylovQP(x=0,
fun=lambda x: 0,
jac=lambda x: g,
hess=lambda x: None,
hessp=lambda x, y: H.dot(y))
p, hits_boundary = subprob.solve(trust_radius)
# check kkt satisfaction
assert_almost_equal(
np.linalg.norm(H.dot(p) + subprob.lam * p + g),
0.0)
# check trust region constraint
assert_almost_equal(np.linalg.norm(p), trust_radius)
assert_array_almost_equal(p, [0.06910534, -0.01432721,
-0.65311947, -0.23815972,
-0.84954934])
assert_array_almost_equal(hits_boundary, True)
def test_disp(self, capsys):
H = -np.eye(5)
g = np.array([0, 0, 0, 0, 1e-6])
trust_radius = 1.1
subprob = KrylovQP_disp(x=0,
fun=lambda x: 0,
jac=lambda x: g,
hess=lambda x: None,
hessp=lambda x, y: H.dot(y))
p, hits_boundary = subprob.solve(trust_radius)
out, err = capsys.readouterr()
assert_(out.startswith(' TR Solving trust region problem'), repr(out))
| TestKrylovQuadraticSubproblem |
python | apache__thrift | lib/py/setup.py | {
"start": 1528,
"end": 4544
} | class ____(build_ext):
def run(self):
try:
build_ext.run(self)
except DistutilsPlatformError:
raise BuildFailed()
def build_extension(self, ext):
try:
build_ext.build_extension(self, ext)
except ext_errors:
raise BuildFailed()
def read_file(path):
"""
Return the contents of a file
Arguments:
- path: path to the file
Returns:
- contents of the file
"""
with open(path, "r") as desc_file:
return desc_file.read().rstrip()
def run_setup(with_binary):
if with_binary:
extensions = dict(
ext_modules=[
Extension('thrift.protocol.fastbinary',
extra_compile_args=['-std=c++11'],
sources=[
'src/ext/module.cpp',
'src/ext/types.cpp',
'src/ext/binary.cpp',
'src/ext/compact.cpp',
],
include_dirs=include_dirs,
)
],
cmdclass=dict(build_ext=ve_build_ext)
)
else:
extensions = dict()
ssl_deps = []
if sys.hexversion < 0x03050000:
ssl_deps.append('backports.ssl_match_hostname>=3.5')
tornado_deps = ['tornado>=4.0']
twisted_deps = ['twisted']
setup(name='thrift',
version='0.23.0',
description='Python bindings for the Apache Thrift RPC system',
long_description=read_file("README.md"),
long_description_content_type="text/markdown",
author='Apache Thrift Developers',
author_email='dev@thrift.apache.org',
url='http://thrift.apache.org',
license='Apache License 2.0',
extras_require={
'ssl': ssl_deps,
'tornado': tornado_deps,
'twisted': twisted_deps,
'all': ssl_deps + tornado_deps + twisted_deps,
},
packages=[
'thrift',
'thrift.protocol',
'thrift.transport',
'thrift.server',
],
package_dir={'thrift': 'src'},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries',
'Topic :: System :: Networking'
],
zip_safe=False,
**extensions
)
try:
with_binary = True
run_setup(with_binary)
except BuildFailed:
print()
print('*' * 80)
print("An error occurred while trying to compile with the C extension enabled")
print("Attempting to build without the extension now")
print('*' * 80)
print()
run_setup(False)
| ve_build_ext |
python | faif__python-patterns | patterns/behavioral/specification.py | {
"start": 2113,
"end": 2222
} | class ____:
def __init__(self, super_user: bool = False) -> None:
self.super_user = super_user
| User |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 664769,
"end": 665479
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for Gist."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("GistEdge"), graphql_name="edges")
"""A list of edges."""
nodes = sgqlc.types.Field(sgqlc.types.list_of("Gist"), graphql_name="nodes")
"""A list of nodes."""
page_info = sgqlc.types.Field(sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo")
"""Information to aid in pagination."""
total_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="totalCount")
"""Identifies the total count of items in the connection."""
| GistConnection |
python | pyinstaller__pyinstaller | bootloader/waflib/Tools/winres.py | {
"start": 1392,
"end": 2097
} | class ____(Task.Task):
run_str = '${WINRC} ${WINRCFLAGS} ${CPPPATH_ST:INCPATHS} ${DEFINES_ST:DEFINES} ${WINRC_TGT_F} ${TGT} ${WINRC_SRC_F} ${SRC}'
color = 'BLUE'
def scan(self):
tmp = rc_parser(self.generator.includes_nodes)
tmp.start(self.inputs[0], self.env)
return (tmp.nodes, tmp.names)
def configure(conf):
v = conf.env
if not v.WINRC:
if v.CC_NAME == 'msvc':
conf.find_program('RC', var='WINRC', path_list=v.PATH)
v.WINRC_TGT_F = '/fo'
v.WINRC_SRC_F = ''
else:
conf.find_program('windres', var='WINRC', path_list=v.PATH)
v.WINRC_TGT_F = '-o'
v.WINRC_SRC_F = '-i'
| winrc |
python | django__django | tests/utils_tests/test_autoreload.py | {
"start": 6470,
"end": 10801
} | class ____(SimpleTestCase):
@mock.patch.dict(sys.modules, {"__main__": django.__main__})
@mock.patch("sys.argv", [django.__main__.__file__, "runserver"])
@mock.patch("sys.warnoptions", [])
@mock.patch("sys._xoptions", {})
def test_run_as_module(self):
self.assertEqual(
autoreload.get_child_arguments(),
[sys.executable, "-m", "django", "runserver"],
)
@mock.patch.dict(sys.modules, {"__main__": test_main})
@mock.patch("sys.argv", [test_main.__file__, "runserver"])
@mock.patch("sys.warnoptions", [])
@mock.patch("sys._xoptions", {})
def test_run_as_non_django_module(self):
self.assertEqual(
autoreload.get_child_arguments(),
[sys.executable, "-m", "utils_tests.test_module", "runserver"],
)
@mock.patch.dict(sys.modules, {"__main__": test_main_module})
@mock.patch("sys.argv", [test_main.__file__, "runserver"])
@mock.patch("sys.warnoptions", [])
@mock.patch("sys._xoptions", {})
def test_run_as_non_django_module_non_package(self):
self.assertEqual(
autoreload.get_child_arguments(),
[sys.executable, "-m", "utils_tests.test_module.main_module", "runserver"],
)
@mock.patch("__main__.__spec__", None)
@mock.patch("sys.argv", [__file__, "runserver"])
@mock.patch("sys.warnoptions", ["error"])
@mock.patch("sys._xoptions", {})
def test_warnoptions(self):
self.assertEqual(
autoreload.get_child_arguments(),
[sys.executable, "-Werror", __file__, "runserver"],
)
@mock.patch("sys.argv", [__file__, "runserver"])
@mock.patch("sys.warnoptions", [])
@mock.patch("sys._xoptions", {"utf8": True, "a": "b"})
def test_xoptions(self):
self.assertEqual(
autoreload.get_child_arguments(),
[sys.executable, "-Xutf8", "-Xa=b", __file__, "runserver"],
)
@mock.patch("__main__.__spec__", None)
@mock.patch("sys.warnoptions", [])
def test_exe_fallback(self):
with tempfile.TemporaryDirectory() as tmpdir:
exe_path = Path(tmpdir) / "django-admin.exe"
exe_path.touch()
with mock.patch("sys.argv", [exe_path.with_suffix(""), "runserver"]):
self.assertEqual(
autoreload.get_child_arguments(), [exe_path, "runserver"]
)
@mock.patch("sys.warnoptions", [])
@mock.patch.dict(sys.modules, {"__main__": django.__main__})
def test_use_exe_when_main_spec(self):
with tempfile.TemporaryDirectory() as tmpdir:
exe_path = Path(tmpdir) / "django-admin.exe"
exe_path.touch()
with mock.patch("sys.argv", [exe_path.with_suffix(""), "runserver"]):
self.assertEqual(
autoreload.get_child_arguments(), [exe_path, "runserver"]
)
@mock.patch("__main__.__spec__", None)
@mock.patch("sys.warnoptions", [])
@mock.patch("sys._xoptions", {})
def test_entrypoint_fallback(self):
with tempfile.TemporaryDirectory() as tmpdir:
script_path = Path(tmpdir) / "django-admin-script.py"
script_path.touch()
with mock.patch(
"sys.argv", [script_path.with_name("django-admin"), "runserver"]
):
self.assertEqual(
autoreload.get_child_arguments(),
[sys.executable, script_path, "runserver"],
)
@mock.patch("__main__.__spec__", None)
@mock.patch("sys.argv", ["does-not-exist", "runserver"])
@mock.patch("sys.warnoptions", [])
def test_raises_runtimeerror(self):
msg = "Script does-not-exist does not exist."
with self.assertRaisesMessage(RuntimeError, msg):
autoreload.get_child_arguments()
@mock.patch("sys.argv", [__file__, "runserver"])
@mock.patch("sys.warnoptions", [])
@mock.patch("sys._xoptions", {})
def test_module_no_spec(self):
module = types.ModuleType("test_module")
del module.__spec__
with mock.patch.dict(sys.modules, {"__main__": module}):
self.assertEqual(
autoreload.get_child_arguments(),
[sys.executable, __file__, "runserver"],
)
| TestChildArguments |
python | pallets__werkzeug | src/werkzeug/routing/converters.py | {
"start": 340,
"end": 1287
} | class ____:
"""Base class for all converters.
.. versionchanged:: 2.3
``part_isolating`` defaults to ``False`` if ``regex`` contains a ``/``.
"""
regex = "[^/]+"
weight = 100
part_isolating = True
def __init_subclass__(cls, **kwargs: t.Any) -> None:
super().__init_subclass__(**kwargs)
# If the converter isn't inheriting its regex, disable part_isolating by default
# if the regex contains a / character.
if "regex" in cls.__dict__ and "part_isolating" not in cls.__dict__:
cls.part_isolating = "/" not in cls.regex
def __init__(self, map: Map, *args: t.Any, **kwargs: t.Any) -> None:
self.map = map
def to_python(self, value: str) -> t.Any:
return value
def to_url(self, value: t.Any) -> str:
# safe = https://url.spec.whatwg.org/#url-path-segment-string
return quote(str(value), safe="!$&'()*+,/:;=@")
| BaseConverter |
python | graphql-python__graphene | graphene/tests/issues/test_720.py | {
"start": 694,
"end": 795
} | class ____(MyInputClass):
class Meta:
fields = dict(x=graphene.Field(graphene.Int))
| MyInput |
python | miyuchina__mistletoe | mistletoe/span_token.py | {
"start": 7527,
"end": 8941
} | class ____(SpanToken):
"""
Raw text token.
This is an inline token without children.
RawText is the only token that accepts a string for its constructor,
instead of a match object. Also, all recursions should bottom out here.
"""
def __init__(self, content):
self.content = content
_tags = {'address', 'article', 'aside', 'base', 'basefont', 'blockquote',
'body', 'caption', 'center', 'col', 'colgroup', 'dd', 'details',
'dialog', 'dir', 'div', 'dl', 'dt', 'fieldset', 'figcaption', 'figure',
'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5',
'h6', 'head', 'header', 'hr', 'html', 'iframe', 'legend', 'li', 'link',
'main', 'menu', 'menuitem', 'meta', 'nav', 'noframes', 'ol',
'optgroup', 'option', 'p', 'param', 'section', 'source', 'summary',
'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'title', 'tr', 'track',
'ul'}
_tag = r'[A-Za-z][A-Za-z0-9-]*' # noqa: E221
_attrs = r'(?:\s+[A-Za-z_:][A-Za-z0-9_.:-]*(?:\s*=\s*(?:[^\s"\'=<>`]+|\'[^\']*?\'|"[^\"]*?"))?)*'
_open_tag = r'(?<!\\)<' + _tag + _attrs + r'\s*/?>' # noqa: E221
_closing_tag = r'(?<!\\)</' + _tag + r'\s*>'
_comment = r'(?<!\\)<!--(?!>|->)(?:(?!--).)+?(?<!-)-->' # noqa: E221
_instruction = r'(?<!\\)<\?.+?\?>'
_declaration = r'(?<!\\)<![A-Z].+?>'
_cdata = r'(?<!\\)<!\[CDATA.+?\]\]>' # noqa: E221
| RawText |
python | viewflow__viewflow | viewflow/fsm/viewset.py | {
"start": 711,
"end": 3089
} | class ____(UpdateModelView):
template_name_suffix = "_transition"
def get_transition_fields(self, request, obj, slug):
return self.viewset.get_transition_fields(request, obj, slug)
def get_object_data(self):
"""List of object fields to display.
Choice fields values are expanded to readable choice label.
"""
return get_object_data(self.object)
def get_template_names(self):
"""
List of templates for the view.
If no `self.template_name` defined, uses::
[<app_label>/<model_label>_<suffix>.html,
<app_label>/<model_label>_transition.html,
'viewflow/views/transition.html']
"""
if self.template_name is None:
opts = self.model._meta
return [
"{}/{}{}.html".format(
opts.app_label, opts.model_name, self.template_name_suffix
),
"{}/{}_transition.html".format(opts.app_label, opts.model_name),
"viewflow/views/transition.html",
]
return [self.template_name]
def get_form_class(self):
if self.form_class is None:
return modelform_factory(
self.model,
form=ModelForm,
fields=self.get_transition_fields(
self.request, self.object, self.kwargs["slug"]
),
)
else:
return super().get_form_class()
@transaction.atomic
def form_valid(self, form):
self.object = form.save()
self.transition()
return HttpResponseRedirect(self.get_success_url())
def get_object(self, *args, **kwargs):
obj = super().get_object(*args, **kwargs)
flow = self.viewset.get_object_flow(self.request, obj)
slug = self.kwargs["slug"]
self.transition = (
getattr(flow, slug, None) if not slug.startswith("_") else None
)
if not self.transition or not isinstance(
self.transition, TransitionBoundMethod
):
raise SuspiciousOperation
if not self.transition.has_perm(self.request.user):
raise PermissionDenied
if not self.transition.can_proceed():
raise PermissionDenied(_("Transition is not allowed"))
return obj
| ModelTransitionView |
python | jazzband__django-simple-history | simple_history/tests/tests/test_utils.py | {
"start": 19021,
"end": 21589
} | class ____(TestCase):
def setUp(self):
self.data = [
PollWithAlternativeManager(
id=1, question="Question 1", pub_date=timezone.now()
),
PollWithAlternativeManager(
id=2, question="Question 2", pub_date=timezone.now()
),
PollWithAlternativeManager(
id=3, question="Question 3", pub_date=timezone.now()
),
PollWithAlternativeManager(
id=4, question="Question 4", pub_date=timezone.now()
),
PollWithAlternativeManager(
id=5, question="Question 5", pub_date=timezone.now()
),
]
bulk_create_with_history(
self.data,
PollWithAlternativeManager,
)
def test_bulk_update_history_default_manager(self):
self.data[3].question = "Updated question"
bulk_update_with_history(
self.data,
PollWithAlternativeManager,
fields=["question"],
)
self.assertEqual(PollWithAlternativeManager.all_objects.count(), 5)
self.assertEqual(
PollWithAlternativeManager.all_objects.get(id=4).question,
"Updated question",
)
self.assertEqual(PollWithAlternativeManager.history.count(), 10)
self.assertEqual(
PollWithAlternativeManager.history.filter(history_type="~").count(), 5
)
def test_bulk_update_history_other_manager(self):
# filtered by default manager
self.data[0].question = "Updated question"
bulk_update_with_history(
self.data,
PollWithAlternativeManager,
fields=["question"],
manager=PollWithAlternativeManager.all_objects,
)
self.assertEqual(PollWithAlternativeManager.all_objects.count(), 5)
self.assertEqual(
PollWithAlternativeManager.all_objects.get(id=1).question,
"Updated question",
)
self.assertEqual(PollWithAlternativeManager.history.count(), 10)
self.assertEqual(
PollWithAlternativeManager.history.filter(history_type="~").count(), 5
)
def test_bulk_update_history_wrong_manager(self):
with self.assertRaises(AlternativeManagerError):
bulk_update_with_history(
self.data,
PollWithAlternativeManager,
fields=["question"],
manager=Poll.objects,
)
| BulkUpdateWithHistoryAlternativeManagersTestCase |
python | aio-libs__aiohttp | aiohttp/web_urldispatcher.py | {
"start": 3273,
"end": 5352
} | class ____(abc.ABC):
def __init__(
self,
method: str,
handler: Handler | type[AbstractView],
*,
expect_handler: _ExpectHandler | None = None,
resource: AbstractResource | None = None,
) -> None:
if expect_handler is None:
expect_handler = _default_expect_handler
assert inspect.iscoroutinefunction(expect_handler) or (
sys.version_info < (3, 14) and asyncio.iscoroutinefunction(expect_handler)
), f"Coroutine is expected, got {expect_handler!r}"
method = method.upper()
if not HTTP_METHOD_RE.match(method):
raise ValueError(f"{method} is not allowed HTTP method")
if inspect.iscoroutinefunction(handler) or (
sys.version_info < (3, 14) and asyncio.iscoroutinefunction(handler)
):
pass
elif isinstance(handler, type) and issubclass(handler, AbstractView):
pass
else:
raise TypeError(
f"Only async functions are allowed as web-handlers, got {handler!r}"
)
self._method = method
self._handler = handler
self._expect_handler = expect_handler
self._resource = resource
@property
def method(self) -> str:
return self._method
@property
def handler(self) -> Handler:
return self._handler
@property
@abc.abstractmethod
def name(self) -> str | None:
"""Optional route's name, always equals to resource's name."""
@property
def resource(self) -> AbstractResource | None:
return self._resource
@abc.abstractmethod
def get_info(self) -> _InfoDict:
"""Return a dict with additional info useful for introspection"""
@abc.abstractmethod # pragma: no branch
def url_for(self, *args: str, **kwargs: str) -> URL:
"""Construct url for route with additional params."""
async def handle_expect_header(self, request: Request) -> StreamResponse | None:
return await self._expect_handler(request)
| AbstractRoute |
python | python-excel__xlwt | xlwt/BIFFRecords.py | {
"start": 7898,
"end": 8012
} | class ____(BiffRecord):
_REC_ID = 0x00E2
def __init__(self):
self._rec_data = b''
| InteraceEndRecord |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.