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
|
apache__airflow
|
dev/breeze/src/airflow_breeze/utils/projects_google_spreadsheet.py
|
{
"start": 1395,
"end": 9678
}
|
class ____(Enum):
KNOWN_REPUTABLE_FOUNDATIONS = auto()
KNOWN_STRONG_COMMUNITIES = auto()
KNOWN_COMPANIES = auto()
KNOWN_STABLE_PROJECTS = auto()
KNOWN_LOW_IMPORTANCE_PROJECTS = auto()
KNOWN_MEDIUM_IMPORTANCE_PROJECTS = auto()
KNOWN_HIGH_IMPORTANCE_PROJECTS = auto()
RELATIONSHIP_PROJECTS = auto()
CONTACTED_PROJECTS = auto()
metadata_from_spreadsheet: dict[MetadataFromSpreadsheet, list[str]] = {}
def get_project_metadata(metadata_type: MetadataFromSpreadsheet) -> list[str]:
return metadata_from_spreadsheet[metadata_type]
# This is a spreadsheet where we store metadata about projects that we want to use in our analysis
METADATA_SPREADSHEET_ID = "1Hg6_B_irfnqNltnu1OUmt7Ph-K6x-DTWF7GZ5t-G0iI"
# This is the named range where we keep metadata
METADATA_RANGE_NAME = "SpreadsheetMetadata"
def read_metadata_from_google_spreadsheet(sheets: Resource):
get_console().print(
"[info]Reading metadata from Google Spreadsheet: "
f"https://docs.google.com/spreadsheets/d/{METADATA_SPREADSHEET_ID}"
)
range = sheets.values().get(spreadsheetId=METADATA_SPREADSHEET_ID, range=METADATA_RANGE_NAME).execute()
metadata_types: list[MetadataFromSpreadsheet] = []
for metadata_field in range["values"][0]:
metadata_types.append(MetadataFromSpreadsheet[metadata_field])
metadata_from_spreadsheet[MetadataFromSpreadsheet[metadata_field]] = []
for row in range["values"][1:]:
for index, value_raw in enumerate(row):
value = value_raw.strip()
if value:
metadata_from_spreadsheet[metadata_types[index]].append(value)
get_console().print("[success]Metadata read from Google Spreadsheet.")
def authorize_google_spreadsheets(json_credentials_file: Path, token_path: Path) -> Resource:
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
SCOPES = ["https://www.googleapis.com/auth/spreadsheets"]
creds = None
if token_path.exists():
creds = Credentials.from_authorized_user_file(token_path.as_posix(), SCOPES)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(json_credentials_file.as_posix(), SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
token_path.write_text(creds.to_json())
service = build("sheets", "v4", credentials=creds)
sheets = service.spreadsheets()
return sheets
def get_sheets(json_credentials_file: Path) -> Resource:
token_path = Path.home() / ".config" / "gsheet" / "token.json"
sheets = authorize_google_spreadsheets(json_credentials_file, token_path)
return sheets
def write_sbom_information_to_google_spreadsheet(
sheets: Resource,
docs: dict[str, str],
google_spreadsheet_id: str,
all_dependencies: list[dict[str, Any]],
fieldnames: list[str],
include_opsf_scorecard: bool = False,
):
# Use only interesting values from the scorecard
cell_field_names = [
fieldname
for fieldname in fieldnames
if fieldname in INTERESTING_OPSF_SCORES or not fieldname.startswith("OPSF-")
]
num_rows = update_field_values(all_dependencies, cell_field_names, google_spreadsheet_id, sheets)
if include_opsf_scorecard:
get_console().print("[info]Updating OPSF detailed comments.")
update_opsf_detailed_comments(
all_dependencies, fieldnames, num_rows, google_spreadsheet_id, docs, sheets
)
def update_opsf_detailed_comments(
all_dependencies: list[dict[str, Any]],
fieldnames: list[str],
num_rows: int,
google_spreadsheet_id: str,
docs: dict[str, str],
sheets: Resource,
):
opsf_details_field_names = [
fieldname for fieldname in fieldnames if fieldname in INTERESTING_OPSF_DETAILS
]
start_opsf_column = fieldnames.index(opsf_details_field_names[0]) - 1
opsf_details = []
opsf_details.append(
{
"values": [
{"note": docs[check]}
for check in INTERESTING_OPSF_FIELDS
if check != INTERESTING_OPSF_FIELDS[0]
]
}
)
get_console().print("[info]Adding notes to all cells.")
for dependency in all_dependencies:
note_row = convert_sbom_dict_to_spreadsheet_data(opsf_details_field_names, dependency)
opsf_details.append({"values": [{"note": note} for note in note_row]})
notes = {
"updateCells": {
"range": {
"startRowIndex": 1,
"endRowIndex": num_rows + 1,
"startColumnIndex": start_opsf_column,
"endColumnIndex": start_opsf_column + len(opsf_details_field_names) + 1,
},
"rows": opsf_details,
"fields": "note",
},
}
update_note_body = {"requests": [notes]}
get_console().print("[info]Updating notes in google spreadsheet.")
sheets.batchUpdate(spreadsheetId=google_spreadsheet_id, body=update_note_body).execute()
def calculate_range(num_columns: int, row: int) -> str:
# Generate column letters
columns = list(string.ascii_uppercase)
if num_columns > 26:
columns += [f"{a}{b}" for a in string.ascii_uppercase for b in string.ascii_uppercase]
# Calculate the range
end_column = columns[num_columns - 1]
return f"A{row}:{end_column}{row}"
def convert_sbom_dict_to_spreadsheet_data(headers: list[str], value_dict: dict[str, Any]):
return [value_dict.get(header, "") for header in headers]
def update_field_values(
all_dependencies: list[dict[str, Any]],
cell_field_names: list[str],
google_spreadsheet_id: str,
sheets: Resource,
) -> int:
get_console().print(f"[info]Updating {len(all_dependencies)} dependencies in the Google spreadsheet.")
num_fields = len(cell_field_names)
data = []
top_header = []
top_opsf_header_added = False
top_actions_header_added = False
possible_action_fields = [field[1] for field in ACTIONS.values()]
for field in cell_field_names:
if field.startswith("OPSF-") and not top_opsf_header_added:
top_header.append("Relevant OPSF Scores and details")
top_opsf_header_added = True
elif field in possible_action_fields and not top_actions_header_added:
top_header.append("Recommended actions")
top_actions_header_added = True
else:
top_header.append("")
simplified_cell_field_names = [simplify_field_names(field) for field in cell_field_names]
get_console().print("[info]Adding top header.")
data.append({"range": calculate_range(num_fields, 1), "values": [top_header]})
get_console().print("[info]Adding second header.")
data.append({"range": calculate_range(num_fields, 2), "values": [simplified_cell_field_names]})
row = 3
get_console().print("[info]Adding all rows.")
for dependency in all_dependencies:
spreadsheet_row = convert_sbom_dict_to_spreadsheet_data(cell_field_names, dependency)
data.append({"range": calculate_range(num_fields, row), "values": [spreadsheet_row]})
row += 1
get_console().print("[info]Writing data.")
body = {"valueInputOption": "RAW", "data": data}
result = sheets.values().batchUpdate(spreadsheetId=google_spreadsheet_id, body=body).execute()
get_console().print(
f"[info]Updated {result.get('totalUpdatedCells')} cells values in the Google spreadsheet."
)
return row
def simplify_field_names(fieldname: str):
if fieldname.startswith("OPSF-"):
return fieldname[5:]
return fieldname
ACTIONS: dict[str, tuple[int, str]] = {
"Security-Policy": (9, "Add Security Policy to the repository"),
"Vulnerabilities": (10, "Follow up with vulnerabilities"),
"Packaging": (10, "Propose Trusted Publishing"),
"Dangerous-Workflow": (10, "Follow up with dangerous workflow"),
"Code-Review": (7, "Propose mandatory code review"),
}
|
MetadataFromSpreadsheet
|
python
|
mlflow__mlflow
|
dev/clint/tests/rules/test_redundant_test_docstring.py
|
{
"start": 2262,
"end": 2637
}
|
class ____:
"""Test."""
pass
'''
config = Config(select={RedundantTestDocstring.name})
violations = lint_file(Path("regular_module.py"), code, config, index_path)
assert len(violations) == 0
def test_supports_test_suffix_files(index_path: Path) -> None:
code = '''
def test_feature_implementation():
"""Test feature."""
assert True
|
TestFeature
|
python
|
huggingface__transformers
|
src/transformers/models/plbart/modular_plbart.py
|
{
"start": 1818,
"end": 1863
}
|
class ____(BartEncoder):
pass
|
PLBartEncoder
|
python
|
realpython__materials
|
python-dict-attribute/salary.py
|
{
"start": 0,
"end": 371
}
|
class ____:
def __init__(self, name, department, salary):
self.name = name
self.department = department
self.salary = salary
def give_raise(self, amount):
self.salery = self.salary + amount # Typo here: self.salery
john = Employee("John", "Engineering", 70000)
john.give_raise(5000)
print(john.salary)
print(john.__dict__)
|
Employee
|
python
|
getsentry__sentry
|
src/sentry/plugins/sentry_webhooks/client.py
|
{
"start": 46,
"end": 541
}
|
class ____(ApiClient):
plugin_name = "webhook"
allow_redirects = False
metrics_prefix = "integrations.webhook"
def __init__(self, data):
self.data = data
super().__init__(verify_ssl=False)
def request(self, url):
return self._request(
path=url,
method="post",
data=self.data,
json=True,
timeout=5,
allow_text=True,
ignore_webhook_errors=True,
)
|
WebhookApiClient
|
python
|
mlflow__mlflow
|
mlflow/server/graphql/autogenerated_graphql_schema.py
|
{
"start": 7006,
"end": 7335
}
|
class ____(graphene.ObjectType):
experiment_id = graphene.String()
name = graphene.String()
artifact_location = graphene.String()
lifecycle_stage = graphene.String()
last_update_time = LongString()
creation_time = LongString()
tags = graphene.List(graphene.NonNull(MlflowExperimentTag))
|
MlflowExperiment
|
python
|
PrefectHQ__prefect
|
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
|
{
"start": 615059,
"end": 616090
}
|
class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"advisory",
"first_patched_version",
"package",
"severity",
"updated_at",
"vulnerable_version_range",
)
advisory = sgqlc.types.Field(
sgqlc.types.non_null("SecurityAdvisory"), graphql_name="advisory"
)
first_patched_version = sgqlc.types.Field(
SecurityAdvisoryPackageVersion, graphql_name="firstPatchedVersion"
)
package = sgqlc.types.Field(
sgqlc.types.non_null(SecurityAdvisoryPackage), graphql_name="package"
)
severity = sgqlc.types.Field(
sgqlc.types.non_null(SecurityAdvisorySeverity), graphql_name="severity"
)
updated_at = sgqlc.types.Field(
sgqlc.types.non_null(DateTime), graphql_name="updatedAt"
)
vulnerable_version_range = sgqlc.types.Field(
sgqlc.types.non_null(String), graphql_name="vulnerableVersionRange"
)
|
SecurityVulnerability
|
python
|
apache__airflow
|
task-sdk/src/airflow/sdk/definitions/_internal/contextmanager.py
|
{
"start": 2506,
"end": 2914
}
|
class ____(Generic[T], metaclass=ContextStackMeta):
_context: deque[T]
@classmethod
def push(cls, obj: T):
cls._context.appendleft(obj)
@classmethod
def pop(cls) -> T | None:
return cls._context.popleft()
@classmethod
def get_current(cls) -> T | None:
try:
return cls._context[0]
except IndexError:
return None
|
ContextStack
|
python
|
django__django
|
tests/forms_tests/tests/test_forms.py
|
{
"start": 1475,
"end": 1631
}
|
class ____(Form):
first_name = CharField(widget=TextInput(attrs={"id": "first_name_id"}))
last_name = CharField()
birthday = DateField()
|
PersonNew
|
python
|
huggingface__transformers
|
src/transformers/models/llava_onevision/image_processing_llava_onevision.py
|
{
"start": 3866,
"end": 38631
}
|
class ____(BaseImageProcessor):
r"""
Constructs a LLaVa-Onevision image processor. Based on [`SiglipImageProcessor`] with incorporation of processing each video frame.
Args:
do_resize (`bool`, *optional*, defaults to `True`):
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
`do_resize` in the `preprocess` method.
size (`dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
Size of the image after resizing. The shortest edge of the image is resized to size["shortest_edge"], with
the longest edge resized to keep the input aspect ratio. Can be overridden by `size` in the `preprocess`
method.
image_grid_pinpoints (`List` *optional*, defaults to `[[672, 336], [336, 672], [672, 672], [336, 1008], [1008, 336]]`):
A list of possible resolutions to use for processing high resolution images. The best resolution is selected
based on the original size of the image. Can be overridden by `image_grid_pinpoints` in the `preprocess`
method. Not used for processing videos.
resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
do_rescale (`bool`, *optional*, defaults to `True`):
Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
the `preprocess` method.
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
method.
do_normalize (`bool`, *optional*, defaults to `True`):
Whether to normalize the image. Can be overridden by `do_normalize` in the `preprocess` method.
image_mean (`float` or `list[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
image_std (`float` or `list[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
Can be overridden by the `image_std` parameter in the `preprocess` method.
do_pad (`bool`, *optional*, defaults to `True`):
Whether to pad the image. If `True`, will pad the patch dimension of the images in the batch to the largest
number of patches in the batch. Padding will be applied to the bottom and right with zeros.
do_convert_rgb (`bool`, *optional*, defaults to `True`):
Whether to convert the image to RGB.
"""
model_input_names = ["pixel_values", "image_sizes", "batch_num_images"]
valid_kwargs = LlavaOnevisionImageProcessorKwargs
def __init__(
self,
do_resize: bool = True,
size: Optional[dict[str, int]] = None,
image_grid_pinpoints: Optional[list] = None,
resample: PILImageResampling = PILImageResampling.BICUBIC,
do_rescale: bool = True,
rescale_factor: Union[int, float] = 1 / 255,
do_normalize: bool = True,
image_mean: Optional[Union[float, list[float]]] = None,
image_std: Optional[Union[float, list[float]]] = None,
do_pad: Optional[bool] = True,
do_convert_rgb: bool = True,
**kwargs,
) -> None:
super().__init__(**kwargs)
size = size if size is not None else {"height": 384, "width": 384}
size = get_size_dict(size, default_to_square=False)
image_grid_pinpoints = (
image_grid_pinpoints
if image_grid_pinpoints is not None
else [
[384, 384],
[384, 768],
[384, 1152],
[384, 1536],
[384, 1920],
[384, 2304],
[768, 384],
[768, 768],
[768, 1152],
[768, 1536],
[768, 1920],
[768, 2304],
[1152, 384],
[1152, 768],
[1152, 1152],
[1152, 1536],
[1152, 1920],
[1152, 2304],
[1536, 384],
[1536, 768],
[1536, 1152],
[1536, 1536],
[1536, 1920],
[1536, 2304],
[1920, 384],
[1920, 768],
[1920, 1152],
[1920, 1536],
[1920, 1920],
[1920, 2304],
[2304, 384],
[2304, 768],
[2304, 1152],
[2304, 1536],
[2304, 1920],
[2304, 2304],
]
)
self.do_resize = do_resize
self.size = size
self.image_grid_pinpoints = image_grid_pinpoints
self.resample = resample
self.do_rescale = do_rescale
self.rescale_factor = rescale_factor
self.do_normalize = do_normalize
self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
self.do_pad = do_pad
self.do_convert_rgb = do_convert_rgb
# Copied from transformers.models.llava_next.image_processing_llava_next.LlavaNextImageProcessor.pad
def pad(
self,
image: np.ndarray,
padding: Union[int, tuple[int, int], Iterable[tuple[int, int]]],
mode: PaddingMode = PaddingMode.CONSTANT,
constant_values: Union[float, Iterable[float]] = 0.0,
data_format: Optional[Union[str, ChannelDimension]] = None,
input_data_format: Optional[Union[str, ChannelDimension]] = None,
) -> np.ndarray:
"""
Pads the `image` with the specified `padding` and `mode`. Padding can be in the (`height`, `width`)
dimension of in the (`num_patches`) dimension. In the second case an iterable if tuples is expected
as input.
Args:
image (`np.ndarray`):
The image to pad.
padding (`int` or `tuple[int, int]` or `Iterable[tuple[int, int]]`):
Padding to apply to the edges of the height, width axes. Can be one of three formats:
- `((before_height, after_height), (before_width, after_width))` unique pad widths for each axis.
- `((before, after),)` yields same before and after pad for height and width.
- `(pad,)` or int is a shortcut for before = after = pad width for all axes.
mode (`PaddingMode`):
The padding mode to use. Can be one of:
- `"constant"`: pads with a constant value.
- `"reflect"`: pads with the reflection of the vector mirrored on the first and last values of the
vector along each axis.
- `"replicate"`: pads with the replication of the last value on the edge of the array along each axis.
- `"symmetric"`: pads with the reflection of the vector mirrored along the edge of the array.
constant_values (`float` or `Iterable[float]`, *optional*):
The value to use for the padding if `mode` is `"constant"`.
data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format for the output image. Can be one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
If unset, will use same as the input image.
input_data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format for the input image. Can be one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
If unset, will use the inferred format of the input image.
Returns:
`np.ndarray`: The padded image.
"""
# call the general `pad` if padding on `height/width`, otherwise it's the `num_patched` dim
if isinstance(padding, int) or len(padding) != 4:
return pad(image, padding, mode, constant_values, data_format, input_data_format)
if input_data_format is None:
input_data_format = infer_channel_dimension_format(image)
if mode == PaddingMode.CONSTANT:
image = np.pad(image, padding, mode="constant", constant_values=constant_values)
elif mode == PaddingMode.REFLECT:
image = np.pad(image, padding, mode="reflect")
elif mode == PaddingMode.REPLICATE:
image = np.pad(image, padding, mode="edge")
elif mode == PaddingMode.SYMMETRIC:
image = np.pad(image, padding, mode="symmetric")
else:
raise ValueError(f"Invalid padding mode: {mode}")
image = (
to_channel_dimension_format(image, data_format, input_data_format) if data_format is not None else image
)
return image
# Copied from transformers.models.llava_next.image_processing_llava_next.LlavaNextImageProcessor._resize_for_patching
def _resize_for_patching(
self, image: np.ndarray, target_resolution: tuple, resample, input_data_format: ChannelDimension
) -> np.ndarray:
"""
Resizes an image to a target resolution while maintaining aspect ratio.
Args:
image (np.ndarray):
The input image.
target_resolution (tuple):
The target resolution (height, width) of the image.
resample (`PILImageResampling`):
Resampling filter to use if resizing the image.
input_data_format (`ChannelDimension` or `str`):
The channel dimension format of the input image.
Returns:
np.ndarray: The resized and padded image.
"""
new_height, new_width = get_patch_output_size(image, target_resolution, input_data_format)
# Resize the image
resized_image = resize(image, (new_height, new_width), resample=resample, input_data_format=input_data_format)
return resized_image
# Copied from transformers.models.llava_next.image_processing_llava_next.LlavaNextImageProcessor._get_padding_size
def _get_padding_size(self, original_resolution: tuple, target_resolution: tuple):
original_height, original_width = original_resolution
target_height, target_width = target_resolution
paste_x, r_x = divmod(target_width - original_width, 2)
paste_y, r_y = divmod(target_height - original_height, 2)
return (paste_y, paste_y + r_y), (paste_x, paste_x + r_x)
# Copied from transformers.models.llava_next.image_processing_llava_next.LlavaNextImageProcessor._pad_for_patching
def _pad_for_patching(
self, image: np.ndarray, target_resolution: tuple, input_data_format: ChannelDimension
) -> np.ndarray:
"""
Pad an image to a target resolution while maintaining aspect ratio.
"""
new_resolution = get_patch_output_size(image, target_resolution, input_data_format)
padding = self._get_padding_size(new_resolution, target_resolution)
padded_image = self.pad(image, padding=padding)
return padded_image
# Copied from transformers.models.llava_next.image_processing_llava_next.LlavaNextImageProcessor.get_image_patches
def get_image_patches(
self,
image: np.ndarray,
grid_pinpoints,
size: tuple,
patch_size: int,
resample: PILImageResampling,
data_format: ChannelDimension,
input_data_format: ChannelDimension,
) -> list[np.ndarray]:
"""
Process an image with variable resolutions by dividing it into patches.
Args:
image (np.ndarray):
The input image to be processed.
grid_pinpoints (List):
A string representation of a list of possible resolutions.
size (`tuple`):
Size to resize the original image to.
patch_size (`int`):
Size of the patches to divide the image into.
resample (`PILImageResampling`):
Resampling filter to use if resizing the image.
data_format (`ChannelDimension` or `str`):
The channel dimension format for the output image.
input_data_format (`ChannelDimension` or `str`):
The channel dimension format of the input image.
Returns:
list[np.ndarray]: A list of NumPy arrays containing the processed image patches.
"""
if not isinstance(grid_pinpoints, list):
raise TypeError("grid_pinpoints must be a list of possible resolutions.")
possible_resolutions = grid_pinpoints
image_size = get_image_size(image, channel_dim=input_data_format)
best_resolution = select_best_resolution(image_size, possible_resolutions)
resized_image = self._resize_for_patching(
image, best_resolution, resample=resample, input_data_format=input_data_format
)
padded_image = self._pad_for_patching(resized_image, best_resolution, input_data_format=input_data_format)
patches = divide_to_patches(padded_image, patch_size=patch_size, input_data_format=input_data_format)
# make sure that all patches are in the input data format
patches = [
to_channel_dimension_format(patch, channel_dim=data_format, input_channel_dim=input_data_format)
for patch in patches
]
resized_original_image = resize(
image,
size=size,
resample=resample,
data_format=data_format,
input_data_format=input_data_format,
)
image_patches = [resized_original_image] + patches
return image_patches
# Copied from transformers.models.llava_next.image_processing_llava_next.LlavaNextImageProcessor._pad_for_batching
def _pad_for_batching(
self,
pixel_values: list[np.ndarray],
data_format: Optional[Union[str, ChannelDimension]] = None,
input_data_format: Optional[Union[str, ChannelDimension]] = None,
):
"""
Pads images on the `num_of_patches` dimension with zeros to form a batch of same number of patches.
Args:
pixel_values (`list[np.ndarray]`):
An array of pixel values of each images of shape (`batch_size`, `num_patches`, `image_in_3D`)
data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format for the output image. Can be one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
If unset, will use same as the input image.
input_data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format for the input image. Can be one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
If unset, will use the inferred format of the input image.
Returns:
list[`np.ndarray`]: The padded images.
"""
max_patch = max(len(x) for x in pixel_values)
pixel_values = [
self.pad(
image,
padding=((0, max_patch - image.shape[0]), (0, 0), (0, 0), (0, 0)),
data_format=data_format,
input_data_format=input_data_format,
)
for image in pixel_values
]
return pixel_values
# Copied from transformers.models.llava.image_processing_llava.LlavaImageProcessor.pad_to_square
def pad_to_square(
self,
image: np.ndarray,
background_color: Union[int, tuple[int, int, int]] = 0,
data_format: Optional[Union[str, ChannelDimension]] = None,
input_data_format: Optional[Union[str, ChannelDimension]] = None,
) -> np.ndarray:
"""
Pads an image to a square based on the longest edge.
Args:
image (`np.ndarray`):
The image to pad.
background_color (`int` or `tuple[int, int, int]`, *optional*, defaults to 0):
The color to use for the padding. Can be an integer for single channel or a
tuple of integers representing for multi-channel images. If passed as integer
in multi-channel mode, it will default to `0` in subsequent channels.
data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format for the output image. Can be one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
If unset, will use same as the input image.
input_data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format for the input image. Can be one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
If unset, will use the inferred format of the input image.
Returns:
`np.ndarray`: The padded image.
"""
height, width = get_image_size(image, input_data_format)
num_channels = image.shape[0] if input_data_format == ChannelDimension.FIRST else image.shape[-1]
if height == width:
image = (
to_channel_dimension_format(image, data_format, input_data_format)
if data_format is not None
else image
)
return image
max_dim = max(height, width)
# Ensure background_color is the correct shape
if isinstance(background_color, int):
background_color = [background_color]
elif len(background_color) != num_channels:
raise ValueError(
f"background_color must have no more than {num_channels} elements to match the number of channels"
)
if input_data_format == ChannelDimension.FIRST:
result = np.zeros((num_channels, max_dim, max_dim), dtype=image.dtype)
for i, color in enumerate(background_color):
result[i, :, :] = color
if width > height:
start = (max_dim - height) // 2
result[:, start : start + height, :] = image
else:
start = (max_dim - width) // 2
result[:, :, start : start + width] = image
else:
result = np.zeros((max_dim, max_dim, num_channels), dtype=image.dtype)
for i, color in enumerate(background_color):
result[:, :, i] = color
if width > height:
start = (max_dim - height) // 2
result[start : start + height, :, :] = image
else:
start = (max_dim - width) // 2
result[:, start : start + width, :] = image
image = (
to_channel_dimension_format(result, data_format, input_data_format) if data_format is not None else result
)
return image
def _preprocess(
self,
images: ImageInput,
do_resize: Optional[bool] = None,
size: Optional[dict[str, int]] = None,
resample: Optional[PILImageResampling] = None,
do_rescale: Optional[bool] = None,
rescale_factor: Optional[float] = None,
do_normalize: Optional[bool] = None,
image_mean: Optional[Union[float, list[float]]] = None,
image_std: Optional[Union[float, list[float]]] = None,
do_convert_rgb: Optional[bool] = None,
data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
input_data_format: Optional[Union[str, ChannelDimension]] = None,
) -> Image.Image:
"""
Args:
images (`ImageInput`):
Batch of frames (one video) to preprocess. Expects a batch of frames with pixel values ranging from 0 to 255. If
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
Whether to resize the image.
size (`dict[str, int]`, *optional*, defaults to `self.size`):
Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
the longest edge resized to keep the input aspect ratio.
resample (`int`, *optional*, defaults to `self.resample`):
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
has an effect if `do_resize` is set to `True`.
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
Whether to rescale the image.
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
Whether to normalize the image.
image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
`True`.
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
The channel dimension format for the output image. Can be one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
- Unset: Use the channel dimension format of the input image.
input_data_format (`ChannelDimension` or `str`, *optional*):
The channel dimension format for the input image. If unset, the channel dimension format is inferred
from the input image. Can be one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
"""
if do_resize:
images = [
resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
for image in images
]
if do_rescale:
images = [
self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
for image in images
]
if do_normalize:
images = [
self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
for image in images
]
images = [
to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
]
return images
def preprocess(
self,
images: ImageInput,
do_resize: Optional[bool] = None,
size: Optional[dict[str, int]] = None,
image_grid_pinpoints: Optional[list] = None,
resample: Optional[PILImageResampling] = None,
do_rescale: Optional[bool] = None,
rescale_factor: Optional[float] = None,
do_normalize: Optional[bool] = None,
image_mean: Optional[Union[float, list[float]]] = None,
image_std: Optional[Union[float, list[float]]] = None,
do_pad: Optional[bool] = None,
do_convert_rgb: Optional[bool] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
input_data_format: Optional[Union[str, ChannelDimension]] = None,
):
"""
Args:
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
tensor. Both channels-first and channels-last formats are supported.
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
Whether to resize the image.
size (`dict[str, int]`, *optional*, defaults to `self.size`):
Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
the longest edge resized to keep the input aspect ratio.
image_grid_pinpoints (`List` *optional*, defaults to `self.image_grid_pinpoints`):
A list of possible resolutions to use for processing high resolution images. The best resolution is
selected based on the original size of the image.
resample (`int`, *optional*, defaults to `self.resample`):
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
has an effect if `do_resize` is set to `True`.
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
Whether to rescale the image.
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
Whether to normalize the image.
image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
`True`.
do_pad (`bool`, *optional*, defaults to `self.do_pad`):
Whether to pad the image. If `True`, will pad the patch dimension of the images in the batch to the largest
number of patches in the batch. Padding will be applied to the bottom and right with zeros.
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
Whether to convert the image to RGB.
return_tensors (`str` or `TensorType`, *optional*):
The type of tensors to return. Can be one of:
- Unset: Return a list of `np.ndarray`.
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
The channel dimension format for the output image. Can be one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
- Unset: Use the channel dimension format of the input image.
input_data_format (`ChannelDimension` or `str`, *optional*):
The channel dimension format for the input image. If unset, the channel dimension format is inferred
from the input image. Can be one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
"""
do_resize = do_resize if do_resize is not None else self.do_resize
size = size if size is not None else self.size
size = get_size_dict(size, default_to_square=False)
image_grid_pinpoints = image_grid_pinpoints if image_grid_pinpoints is not None else self.image_grid_pinpoints
resample = resample if resample is not None else self.resample
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
image_mean = image_mean if image_mean is not None else self.image_mean
image_std = image_std if image_std is not None else self.image_std
do_pad = do_pad if do_pad is not None else self.do_pad
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
if isinstance(images, (tuple, list)) and isinstance(images[0], (tuple, list)):
# if the first element is a list, we assume that all elements are lists
images = [x for x in images if x] # handle text-only case
batch_num_images = [len(x) for x in images]
elif isinstance(images, (tuple, list)):
# treat this as a single-image case for backward compatibility
batch_num_images = [1] * len(images)
else:
batch_num_images = [1]
# only single image patching is supported
need_patching = [n == 1 for n in batch_num_images for _ in range(n)]
images = self.fetch_images(images)
images = make_flat_list_of_images(images)
if not valid_images(images):
raise ValueError("Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, or torch.Tensor")
validate_preprocess_arguments(
do_rescale=do_rescale,
rescale_factor=rescale_factor,
do_normalize=do_normalize,
image_mean=image_mean,
image_std=image_std,
do_resize=do_resize,
size=size,
resample=resample,
)
if do_convert_rgb:
images = [convert_to_rgb(image) for image in images]
# All transformations expect numpy arrays.
images = [to_numpy_array(image) for image in images]
if do_rescale and is_scaled_image(images[0]):
logger.warning_once(
"It looks like you are trying to rescale already rescaled images. If the input"
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
)
if input_data_format is None:
# We assume that all images have the same channel dimension format.
input_data_format = infer_channel_dimension_format(images[0])
size_tuple = (
(size["height"], size["width"])
if "height" in size and "width" in size
else (size["shortest_edge"], size["shortest_edge"])
)
processed_images = []
image_sizes = [get_image_size(image, channel_dim=input_data_format) for image in images]
for i, image in enumerate(images):
if need_patching[i]:
# convert image into a list of patches
# we intentionally use the same data format as the input data format
image_patches = self.get_image_patches(
image,
image_grid_pinpoints,
size=size_tuple,
patch_size=size_tuple[0],
resample=resample,
data_format=input_data_format,
input_data_format=input_data_format,
)
else:
padded_image = self.pad_to_square(
image=image,
background_color=tuple(int(x * 255) for x in self.image_mean),
input_data_format=input_data_format,
)
image_patches = [padded_image]
# preprocess patches
pixel_values = self._preprocess(
image_patches,
do_resize=do_resize,
size=size_tuple,
resample=resample,
do_rescale=do_rescale,
rescale_factor=rescale_factor,
do_normalize=do_normalize,
image_mean=image_mean,
image_std=image_std,
data_format=data_format,
input_data_format=input_data_format,
)
pixel_values = np.array(pixel_values)
processed_images.append(pixel_values)
if do_pad:
processed_images = self._pad_for_batching(processed_images)
return BatchFeature(
data={"pixel_values": processed_images, "image_sizes": image_sizes, "batch_num_images": batch_num_images},
tensor_type=return_tensors,
)
__all__ = ["LlavaOnevisionImageProcessor"]
|
LlavaOnevisionImageProcessor
|
python
|
pytorch__pytorch
|
torch/distributed/algorithms/join.py
|
{
"start": 1396,
"end": 2842
}
|
class ____(ABC):
r"""
This defines an abstract base class for joinable classes.
A joinable class
(inheriting from :class:`Joinable`) should implement :meth:`join_hook`,
which returns a :class:`JoinHook` instance, in addition to
:meth:`join_device` and :meth:`join_process_group` that return device and
process group information, respectively.
"""
@abstractmethod
def __init__(self) -> None:
super().__init__()
self._join_config = _JoinConfig.construct_disabled_join_config()
@abstractmethod
def join_hook(self, **kwargs) -> JoinHook:
r"""
Return a :class:`JoinHook` instance for the given :class:`Joinable`.
Arguments:
kwargs (dict): a :class:`dict` containing any keyword arguments
to modify the behavior of the join hook at run time; all
:class:`Joinable` instances sharing the same join context
manager are forwarded the same value for ``kwargs``.
"""
...
@property
@abstractmethod
def join_device(self) -> torch.device:
r"""Return the device from which to perform collective communications needed by the join context manager."""
...
@property
@abstractmethod
def join_process_group(self) -> Any:
r"""Returns the process group for the collective communications needed by the join context manager itself."""
...
|
Joinable
|
python
|
joke2k__faker
|
faker/providers/internet/ar_AA/__init__.py
|
{
"start": 46,
"end": 1047
}
|
class ____(InternetProvider):
replacements = (
("س", "s"),
("ق", "q"),
("ب", "b"),
("خ", "x"),
("ش", "$"),
("َ", "a"),
("ئ", "}"),
("إ", "<"),
("ل", "l"),
("ٰ", "`"),
("ف", "f"),
("و", "w"),
("ض", "D"),
("ي", "y"),
("ُ", "u"),
("ة", "p"),
("ظ", "Z"),
("ث", "v"),
("ـ", "_"),
("ج", "j"),
("د", "d"),
("ح", "H"),
("ا", "A"),
("أ", ">"),
("ر", "r"),
("ى", "Y"),
("ذ", "*"),
("ْ", "o"),
("ن", "n"),
("ّ", "~"),
("ك", "k"),
("ء", "'"),
("ط", "T"),
("ت", "t"),
("ه", "h"),
("ً", "F"),
("ؤ", "&"),
("ٍ", "K"),
("ِ", "i"),
("ص", "S"),
("ٱ", "{"),
("ٌ", "N"),
("م", "m"),
("ز", "z"),
("ع", "E"),
("آ", "|"),
("غ", "g"),
)
|
Provider
|
python
|
walkccc__LeetCode
|
solutions/173. Binary Search Tree Iterator/173-2.py
|
{
"start": 0,
"end": 420
}
|
class ____:
def __init__(self, root: TreeNode | None):
self.stack = []
self._pushLeftsUntilNull(root)
def next(self) -> int:
root = self.stack.pop()
self._pushLeftsUntilNull(root.right)
return root.val
def hasNext(self) -> bool:
return self.stack
def _pushLeftsUntilNull(self, root: TreeNode | None) -> None:
while root:
self.stack.append(root)
root = root.left
|
BSTIterator
|
python
|
Lightning-AI__lightning
|
tests/tests_pytorch/helpers/advanced_models.py
|
{
"start": 5426,
"end": 6262
}
|
class ____(LightningModule):
def __init__(self):
super().__init__()
self.rnn = nn.LSTM(10, 20, batch_first=True)
self.linear_out = nn.Linear(in_features=20, out_features=5)
self.example_input_array = torch.rand(2, 3, 10)
self._loss = [] # needed for checking if the loss is the same as vanilla torch
def forward(self, x):
seq, _ = self.rnn(x)
return self.linear_out(seq)
def training_step(self, batch, batch_nb):
x, y = batch
y_hat = self(x)
loss = F.mse_loss(y_hat, y)
self._loss.append(loss.item())
return {"loss": loss}
def configure_optimizers(self):
return torch.optim.Adam(self.parameters(), lr=0.02)
def train_dataloader(self):
return DataLoader(AverageDataset(), batch_size=30)
|
ParityModuleRNN
|
python
|
airbytehq__airbyte
|
airbyte-integrations/connectors/source-bing-ads/unit_tests/integrations/test_hourly_reports.py
|
{
"start": 76579,
"end": 82109
}
|
class ____(HourlyReportsTestWithStateChangesAfterMigration):
stream_name = "account_performance_report_hourly"
report_file = "account_performance_report_hourly"
records_number = 24
state_file = "hourly_reports_state"
incremental_report_file = "account_performance_report_hourly_incremental"
report_file_with_records_further_start_date = "account_performance_report_hourly_with_records_further_config_start_date"
state_file_legacy = "hourly_reports_state_legacy"
state_file_after_migration = "hourly_reports_state_after_migration"
state_file_after_migration_with_cursor_further_config_start_date = (
"hourly_reports_state_after_migration_with_cursor_further_config_start_date"
)
incremental_report_file_with_records_further_cursor = "account_performance_report_hourly_incremental_with_records_further_cursor"
def mock_report_apis(self):
self.mock_user_query_api(response_template="user_query")
self.mock_accounts_search_api(
response_template="accounts_search_for_report",
body=b'{"PageInfo": {"Index": 0, "Size": 1000}, "Predicates": [{"Field": "UserId", "Operator": "Equals", "Value": "123456789"}], "ReturnAdditionalFields": "TaxCertificate,AccountMode"}',
)
self.mock_generate_report_api(
endpoint="Submit",
response_template="generate_report",
body=b'{"ReportRequest": {"ExcludeColumnHeaders": false, "ExcludeReportFooter": true, "ExcludeReportHeader": true, "Format": "Csv", "FormatVersion": "2.0", "ReportName": "AccountPerformanceReport", "ReturnOnlyCompleteData": false, "Type": "AccountPerformanceReportRequest", "Aggregation": "Hourly", "Columns": ["AccountId", "TimePeriod", "CurrencyCode", "AdDistribution", "DeviceType", "Network", "DeliveredMatchType", "DeviceOS", "TopVsOther", "BidMatchType", "AccountName", "AccountNumber", "PhoneImpressions", "PhoneCalls", "Clicks", "Ctr", "Spend", "Impressions", "Assists", "ReturnOnAdSpend", "AverageCpc", "AveragePosition", "AverageCpm", "Conversions", "ConversionsQualified", "ConversionRate", "CostPerAssist", "CostPerConversion", "LowQualityClicks", "LowQualityClicksPercent", "LowQualityImpressions", "LowQualitySophisticatedClicks", "LowQualityConversions", "LowQualityConversionRate", "Revenue", "RevenuePerAssist", "RevenuePerConversion", "Ptr"], "Scope": {"AccountIds": [180535609]}, "Time": {"CustomDateRangeStart": {"Day": 1, "Month": 1, "Year": 2024}, "CustomDateRangeEnd": {"Day": 6, "Month": 5, "Year": 2024}, "ReportTimeZone": "GreenwichMeanTimeDublinEdinburghLisbonLondon"}}}',
)
# for second read
self.mock_generate_report_api(
endpoint="Submit",
response_template="generate_report",
body=b'{"ReportRequest": {"ExcludeColumnHeaders": false, "ExcludeReportFooter": true, "ExcludeReportHeader": true, "Format": "Csv", "FormatVersion": "2.0", "ReportName": "AccountPerformanceReport", "ReturnOnlyCompleteData": false, "Type": "AccountPerformanceReportRequest", "Aggregation": "Hourly", "Columns": ["AccountId", "TimePeriod", "CurrencyCode", "AdDistribution", "DeviceType", "Network", "DeliveredMatchType", "DeviceOS", "TopVsOther", "BidMatchType", "AccountName", "AccountNumber", "PhoneImpressions", "PhoneCalls", "Clicks", "Ctr", "Spend", "Impressions", "Assists", "ReturnOnAdSpend", "AverageCpc", "AveragePosition", "AverageCpm", "Conversions", "ConversionsQualified", "ConversionRate", "CostPerAssist", "CostPerConversion", "LowQualityClicks", "LowQualityClicksPercent", "LowQualityImpressions", "LowQualitySophisticatedClicks", "LowQualityConversions", "LowQualityConversionRate", "Revenue", "RevenuePerAssist", "RevenuePerConversion", "Ptr"], "Scope": {"AccountIds": [180535609]}, "Time": {"CustomDateRangeStart": {"Day": 6, "Month": 5, "Year": 2024}, "CustomDateRangeEnd": {"Day": 8, "Month": 5, "Year": 2024}, "ReportTimeZone": "GreenwichMeanTimeDublinEdinburghLisbonLondon"}}}',
)
self.mock_generate_report_api(
endpoint="Submit",
response_template="generate_report",
body=b'{"ReportRequest": {"ExcludeColumnHeaders": false, "ExcludeReportFooter": true, "ExcludeReportHeader": true, "Format": "Csv", "FormatVersion": "2.0", "ReportName": "AccountPerformanceReport", "ReturnOnlyCompleteData": false, "Type": "AccountPerformanceReportRequest", "Aggregation": "Hourly", "Columns": ["AccountId", "TimePeriod", "CurrencyCode", "AdDistribution", "DeviceType", "Network", "DeliveredMatchType", "DeviceOS", "TopVsOther", "BidMatchType", "AccountName", "AccountNumber", "PhoneImpressions", "PhoneCalls", "Clicks", "Ctr", "Spend", "Impressions", "Assists", "ReturnOnAdSpend", "AverageCpc", "AveragePosition", "AverageCpm", "Conversions", "ConversionsQualified", "ConversionRate", "CostPerAssist", "CostPerConversion", "LowQualityClicks", "LowQualityClicksPercent", "LowQualityImpressions", "LowQualitySophisticatedClicks", "LowQualityConversions", "LowQualityConversionRate", "Revenue", "RevenuePerAssist", "RevenuePerConversion", "Ptr"], "Scope": {"AccountIds": [180535609]}, "Time": {"CustomDateRangeStart": {"Day": 1, "Month": 1, "Year": 2023}, "CustomDateRangeEnd": {"Day": 6, "Month": 5, "Year": 2024}, "ReportTimeZone": "GreenwichMeanTimeDublinEdinburghLisbonLondon"}}}',
)
self.mock_generate_report_api(
endpoint="Poll", response_template="generate_report_poll", body=b'{"ReportRequestId": "thisisthereport_requestid"}'
)
|
TestAccountPerformanceReportHourlyStream
|
python
|
HypothesisWorks__hypothesis
|
hypothesis-python/tests/attrs/test_inference.py
|
{
"start": 3942,
"end": 4164
}
|
class ____:
x: int = attr.ib(alias="crazyname")
@pytest.mark.parametrize("s", [st.just(42)])
def test_aliased_attribute(s):
check_can_generate_examples(st.builds(HasAliasedAttribute, crazyname=s))
|
HasAliasedAttribute
|
python
|
GoogleCloudPlatform__python-docs-samples
|
healthcare/api-client/v1/fhir/fhir_resources_test.py
|
{
"start": 2240,
"end": 12015
}
|
class ____(Exception):
"""Operation is not yet complete"""
pass
@retry.Retry(predicate=retry.if_exception_type(OperationNotComplete))
def wait_for_operation(operation_name: str):
operation = (
client.projects()
.locations()
.datasets()
.operations()
.get(name=operation_name)
.execute()
)
if not operation.get("done", False):
raise OperationNotComplete(operation)
@pytest.fixture(scope="module")
def test_dataset():
operation = create_dataset(project_id, location, dataset_id)
# Wait for the dataset to be created
wait_for_operation(operation["name"])
yield
# Clean up
@backoff.on_exception(backoff.expo, HttpError, max_time=BACKOFF_MAX_TIME)
def clean_up():
try:
delete_dataset(project_id, location, dataset_id)
except HttpError as err:
# The API returns 403 when the dataset doesn't exist.
if err.resp.status == 404 or err.resp.status == 403:
print(f"Got exception {err.resp.status} while deleting dataset")
else:
raise
clean_up()
@pytest.fixture(scope="module")
def test_fhir_store():
@backoff.on_exception(backoff.expo, HttpError, max_time=BACKOFF_MAX_TIME)
def create():
try:
fhir_stores.create_fhir_store(
project_id, location, dataset_id, fhir_store_id, version
)
except HttpError as err:
# We ignore 409 conflict here, because we know it's most
# likely the first request failed on the client side, but
# the creation suceeded on the server side.
if err.resp.status == 409:
print(f"Got exception {err.resp.status} while creating FHIR store")
else:
raise
create()
yield
# Clean up
@backoff.on_exception(backoff.expo, HttpError, max_time=BACKOFF_MAX_TIME)
def clean_up():
try:
fhir_stores.delete_fhir_store(
project_id, location, dataset_id, fhir_store_id
)
except HttpError as err:
# The API returns 404 when the FHIR store doesn't exist.
# The API returns 403 when the dataset doesn't exist, so
# if we try to delete a FHIR store when the parent dataset
# doesn't exist, the server will return a 403.
if err.resp.status == 404 or err.resp.status == 403:
print(f"Got exception {err.resp.status} while deleting FHIR store")
else:
raise
clean_up()
# Fixture that creates/deletes a Patient resource for various tests.
@pytest.fixture(scope="module")
def test_patient():
patient_response = fhir_resources.create_patient(
project_id,
location,
dataset_id,
fhir_store_id,
)
patient_resource = patient_response
patient_resource_id = patient_resource["id"]
yield patient_resource_id
@backoff.on_exception(backoff.expo, HttpError, max_time=BACKOFF_MAX_TIME)
# Clean up
def clean_up():
try:
fhir_resources.delete_resource(
project_id,
location,
dataset_id,
fhir_store_id,
resource_type,
patient_resource_id,
)
except HttpError as err:
# The API returns 200 whether the resource exists or was
# successfully deleted or not.
if err.resp.status > 200:
print(f"Got exception {err.resp.status} while deleting FHIR store")
else:
raise
clean_up()
# This test also creates a CodeSystem resource in the FHIR store, which is
# required because it serves as a reference resource to
# ImplementationGuideExample.json when calling
# test_create_implementation_guide.
def test_create_resource_from_file(test_dataset, test_fhir_store, capsys):
fhir_resources.create_resource_from_file(
project_id,
location,
dataset_id,
fhir_store_id,
resource_type_from_file,
code_system_file,
)
out, _ = capsys.readouterr()
assert f"Created {resource_type_from_file} resource" in out
def test_create_patient(test_dataset, test_fhir_store, capsys):
fhir_resources.create_patient(
project_id,
location,
dataset_id,
fhir_store_id,
)
out, _ = capsys.readouterr()
assert "Created Patient" in out
def test_validate_resource(test_dataset, test_fhir_store, test_patient, capsys):
fhir_resources.validate_resource(
project_id, location, dataset_id, fhir_store_id, resource_type
)
out, _ = capsys.readouterr()
# Should succeed because we are validating a standard Patient resource
# against the base FHIR store profile without any customization
assert '{"text": "success"}' in out
def test_validate_resource_profile_url(
test_dataset, test_fhir_store, test_patient, capsys
):
# Create a StructureDefinition resource that only exists in the FHIR store
# to ensure that the validate_resource_profile_url method fails, because the
# validation does not adhere to the constraints in the StructureDefinition.
fhir_resources.create_structure_definition(
project_id,
location,
dataset_id,
fhir_store_id,
structure_definition_profile_url_file,
)
fhir_resources.validate_resource_profile_url(
project_id,
location,
dataset_id,
fhir_store_id,
resource_type,
profile_url,
)
out, _ = capsys.readouterr()
# Should fail because we are purposefully validating a resource against a
# profile that it does not match
assert '"severity": "error"' in out
def test_get_patient(test_dataset, test_fhir_store, test_patient, capsys):
fhir_resources.get_resource(
project_id,
location,
dataset_id,
fhir_store_id,
resource_type,
test_patient,
)
out, _ = capsys.readouterr()
assert "Got contents of Patient resource with ID" in out
def test_update_patient(test_dataset, test_fhir_store, test_patient, capsys):
fhir_resources.update_resource(
project_id,
location,
dataset_id,
fhir_store_id,
resource_type,
test_patient,
)
out, _ = capsys.readouterr()
assert "Updated Patient resource" in out
def test_patch_patient(test_dataset, test_fhir_store, test_patient, capsys):
fhir_resources.patch_resource(
project_id,
location,
dataset_id,
fhir_store_id,
resource_type,
test_patient,
)
out, _ = capsys.readouterr()
assert "Patched Patient resource" in out
def test_resource_versions(test_dataset, test_fhir_store, test_patient, capsys):
# We have to update the resource so that different versions of it are
# created, then we test to see if we can get/delete those versions.
fhir_resources.update_resource(
project_id,
location,
dataset_id,
fhir_store_id,
resource_type,
test_patient,
)
history = fhir_resources.list_resource_history(
project_id,
location,
dataset_id,
fhir_store_id,
resource_type,
test_patient,
)
fhir_resources.get_resource_history(
project_id,
location,
dataset_id,
fhir_store_id,
resource_type,
test_patient,
history["entry"][-1]["resource"]["meta"]["versionId"],
)
out, _ = capsys.readouterr()
# list_resource_history test
assert "History for Patient resource with ID" in out
# get_resource_history test
assert "Got contents of Patient resource with ID" in out
def test_search_resources_post(test_dataset, test_fhir_store, test_patient, capsys):
fhir_resources.search_resources_post(
project_id, location, dataset_id, fhir_store_id
)
out, _ = capsys.readouterr()
assert "Using POST request" in out
def test_execute_bundle(test_dataset, test_fhir_store, capsys):
fhir_resources.execute_bundle(
project_id,
location,
dataset_id,
fhir_store_id,
bundle,
)
out, _ = capsys.readouterr()
assert "Executed bundle from file" in out
def test_create_structure_definition(test_dataset, test_fhir_store, capsys):
fhir_resources.create_structure_definition(
project_id,
location,
dataset_id,
fhir_store_id,
structure_definition_file,
)
out, _ = capsys.readouterr()
assert "Created StructureDefinition resource" in out
def test_create_implementation_guide(test_dataset, test_fhir_store, capsys):
fhir_resources.create_implementation_guide(
project_id,
location,
dataset_id,
fhir_store_id,
implementation_guide_file,
)
out, _ = capsys.readouterr()
assert "Created ImplementationGuide resource" in out
def test_enable_implementation_guide(test_dataset, test_fhir_store, capsys):
fhir_resources.enable_implementation_guide(
project_id,
location,
dataset_id,
fhir_store_id,
implementation_guide_url,
)
out, _ = capsys.readouterr()
assert "Enabled ImplementationGuide" in out
def test_delete_patient(test_dataset, test_fhir_store, test_patient, capsys):
fhir_resources.delete_resource(
project_id,
location,
dataset_id,
fhir_store_id,
resource_type,
test_patient,
)
out, _ = capsys.readouterr()
assert "Deleted Patient resource" in out
|
OperationNotComplete
|
python
|
fluentpython__example-code-2e
|
10-dp-1class-func/untyped/strategy_param2.py
|
{
"start": 2316,
"end": 2616
}
|
class ____(Promotion):
"""discount for each LineItem with 20 or more units"""
def __call__(self, order):
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * self.percent / 100
return discount
|
BulkItemPromo
|
python
|
dask__dask
|
dask/tests/test_tokenize.py
|
{
"start": 26556,
"end": 41373
}
|
class ____:
def __init__(self, val) -> None:
self.val = val
def test_local_objects():
class LocalType:
foo = "bar"
class LocalReducible:
def __reduce__(self):
return LocalReducible, ()
class LocalDaskTokenize:
def __dask_tokenize__(self):
return "foo"
class LocalChild(GlobalClass):
pass
check_tokenize(GlobalClass(1))
assert check_tokenize(GlobalClass(1)) != check_tokenize(GlobalClass(2))
check_tokenize(LocalType())
check_tokenize(LocalChild(1))
assert check_tokenize(LocalDaskTokenize()) != check_tokenize(LocalReducible())
@pytest.mark.skipif(
PY_VERSION >= Version("3.13"), reason="https://github.com/dask/dask/issues/11457"
)
def test_tokenize_dataclass():
a1 = ADataClass(1)
a2 = ADataClass(2)
check_tokenize(a1)
assert check_tokenize(a1) != check_tokenize(a2)
# Same field names and values, but dataclass types are different
b1 = BDataClass(1)
assert check_tokenize(ADataClass) != check_tokenize(BDataClass)
assert check_tokenize(a1) != check_tokenize(b1)
class SubA(ADataClass):
pass
assert dataclasses.is_dataclass(SubA)
assert check_tokenize(ADataClass) != check_tokenize(SubA)
assert check_tokenize(SubA(1)) != check_tokenize(a1)
# Same name, same values, new definition: tokenize differently
ADataClassRedefinedDifferently = dataclasses.make_dataclass(
"ADataClass", [("a", int | str)]
)
assert check_tokenize(a1) != check_tokenize(ADataClassRedefinedDifferently(1))
# Dataclass with unpopulated value
nv = NoValueDataClass()
check_tokenize(nv)
@pytest.mark.parametrize(
"other",
[
(1, 10, 2), # Different start
(5, 15, 2), # Different stop
(5, 10, 1), # Different step
],
)
def test_tokenize_range(other):
assert check_tokenize(range(5, 10, 2)) != check_tokenize(range(*other))
@pytest.mark.skipif("not np")
def test_tokenize_numpy_array():
x = np.arange(2000) # long enough to drop information in repr
y = np.arange(2000)
y[1000] = 0 # middle isn't printed in repr
assert check_tokenize([x]) != check_tokenize([y])
@pytest.mark.skipif("not np")
def test_tokenize_object_array_with_nans():
a = np.array(["foo", "Jos\xe9", np.nan], dtype="O")
check_tokenize(a)
@pytest.mark.parametrize(
"x", [1, True, "a", b"a", 1.0, 1j, 1.0j, [], (), {}, None, str, int]
)
def test_tokenize_base_types(x):
check_tokenize(x)
def test_tokenize_literal():
assert check_tokenize(literal(["x", 1])) != check_tokenize(literal(["x", 2]))
@pytest.mark.skipif("not np")
@pytest.mark.filterwarnings("ignore:the matrix:PendingDeprecationWarning")
def test_tokenize_numpy_matrix():
rng = np.random.RandomState(1234)
a = np.asmatrix(rng.rand(100))
b = a.copy()
assert check_tokenize(a) == check_tokenize(b)
b[:10] = 1
assert check_tokenize(a) != check_tokenize(b)
@pytest.mark.skipif("not sp")
@pytest.mark.parametrize("cls_name", ("dok",))
def test_tokenize_dense_sparse_array(cls_name):
rng = np.random.RandomState(1234)
a = sp.rand(10, 100, random_state=rng).asformat(cls_name)
b = a.copy()
assert check_tokenize(a) == check_tokenize(b)
# modifying the data values
if hasattr(b, "data"):
b.data[:10] = 1
elif cls_name == "dok":
b[3, 3] = 1
else:
raise ValueError
check_tokenize(b)
assert check_tokenize(a) != check_tokenize(b)
# modifying the data indices
b = a.copy().asformat("coo")
b.row[:10] = np.arange(10)
b = b.asformat(cls_name)
assert check_tokenize(a) != check_tokenize(b)
def test_tokenize_circular_recursion():
a = [1, 2]
a[0] = a
# Test that tokenization doesn't stop as soon as you hit the circular recursion
b = [1, 3]
b[0] = b
assert check_tokenize(a) != check_tokenize(b)
# Different circular recursions tokenize differently
c = [[], []]
c[0].append(c[0])
c[1].append(c[1])
d = [[], []]
d[0].append(d[1])
d[1].append(d[0])
assert check_tokenize(c) != check_tokenize(d)
# For dicts, the dict itself is not passed to _normalize_seq_func
e = {}
e[0] = e
check_tokenize(e)
@pytest.mark.parametrize(
"other",
[
(2002, 6, 25), # Different year
(2021, 7, 25), # Different month
(2021, 6, 26), # Different day
],
)
def test_tokenize_datetime_date(other):
a = datetime.date(2021, 6, 25)
b = datetime.date(*other)
assert check_tokenize(a) != check_tokenize(b)
def test_tokenize_datetime_time():
# Same time
check_tokenize(datetime.time(1, 2, 3, 4, datetime.timezone.utc))
check_tokenize(datetime.time(1, 2, 3, 4))
check_tokenize(datetime.time(1, 2, 3))
check_tokenize(datetime.time(1, 2))
# Different hour
assert check_tokenize(
datetime.time(1, 2, 3, 4, datetime.timezone.utc)
) != check_tokenize(datetime.time(2, 2, 3, 4, datetime.timezone.utc))
# Different minute
assert check_tokenize(
datetime.time(1, 2, 3, 4, datetime.timezone.utc)
) != check_tokenize(datetime.time(1, 3, 3, 4, datetime.timezone.utc))
# Different second
assert check_tokenize(
datetime.time(1, 2, 3, 4, datetime.timezone.utc)
) != check_tokenize(datetime.time(1, 2, 4, 4, datetime.timezone.utc))
# Different micros
assert check_tokenize(
datetime.time(1, 2, 3, 4, datetime.timezone.utc)
) != check_tokenize(datetime.time(1, 2, 3, 5, datetime.timezone.utc))
# Different tz
assert check_tokenize(
datetime.time(1, 2, 3, 4, datetime.timezone.utc)
) != check_tokenize(datetime.time(1, 2, 3, 4))
def test_tokenize_datetime_datetime():
# Same datetime
required = [1, 2, 3] # year, month, day
optional = [4, 5, 6, 7, datetime.timezone.utc]
for i in range(len(optional) + 1):
args = required + optional[:i]
check_tokenize(datetime.datetime(*args))
# Different year
assert check_tokenize(
datetime.datetime(1, 2, 3, 4, 5, 6, 7, datetime.timezone.utc)
) != check_tokenize(datetime.datetime(2, 2, 3, 4, 5, 6, 7, datetime.timezone.utc))
# Different month
assert check_tokenize(
datetime.datetime(1, 2, 3, 4, 5, 6, 7, datetime.timezone.utc)
) != check_tokenize(datetime.datetime(1, 1, 3, 4, 5, 6, 7, datetime.timezone.utc))
# Different day
assert check_tokenize(
datetime.datetime(1, 2, 3, 4, 5, 6, 7, datetime.timezone.utc)
) != check_tokenize(datetime.datetime(1, 2, 2, 4, 5, 6, 7, datetime.timezone.utc))
# Different hour
assert check_tokenize(
datetime.datetime(1, 2, 3, 4, 5, 6, 7, datetime.timezone.utc)
) != check_tokenize(datetime.datetime(1, 2, 3, 3, 5, 6, 7, datetime.timezone.utc))
# Different minute
assert check_tokenize(
datetime.datetime(1, 2, 3, 4, 5, 6, 7, datetime.timezone.utc)
) != check_tokenize(datetime.datetime(1, 2, 3, 4, 4, 6, 7, datetime.timezone.utc))
# Different second
assert check_tokenize(
datetime.datetime(1, 2, 3, 4, 5, 6, 7, datetime.timezone.utc)
) != check_tokenize(datetime.datetime(1, 2, 3, 4, 5, 5, 7, datetime.timezone.utc))
# Different micros
assert check_tokenize(
datetime.datetime(1, 2, 3, 4, 5, 6, 7, datetime.timezone.utc)
) != check_tokenize(datetime.datetime(1, 2, 3, 4, 5, 6, 6, datetime.timezone.utc))
# Different tz
assert check_tokenize(
datetime.datetime(1, 2, 3, 4, 5, 6, 7, datetime.timezone.utc)
) != check_tokenize(datetime.datetime(1, 2, 3, 4, 5, 6, 7, None))
def test_tokenize_functions_main():
script = """
def inc(x):
return x + 1
inc2 = inc
def sum(x, y):
return x + y
from dask.base import tokenize
assert tokenize(inc) != tokenize(sum)
# That this is an alias shouldn't matter
assert tokenize(inc) == tokenize(inc2)
def inc(x):
return x + 1
assert tokenize(inc2) != tokenize(inc)
def inc(y):
return y + 1
assert tokenize(inc2) != tokenize(inc)
def inc(x):
y = x
return y + 1
assert tokenize(inc2) != tokenize(inc)
# Test that redefining a function changes the token
def func(x):
return x + 1
result = tokenize(func)
def func(x):
return x + 2
result2 = tokenize(func)
assert result != result2
"""
proc = subprocess.run([sys.executable, "-c", textwrap.dedent(script)])
proc.check_returncode()
def test_tokenize_dataclass_field_no_repr():
A = dataclasses.make_dataclass(
"A",
[("param", float, dataclasses.field(repr=False))],
namespace={"__dask_tokenize__": lambda self: self.param},
)
a1, a2 = A(1), A(2)
assert check_tokenize(a1) != check_tokenize(a2)
def test_tokenize_operator():
"""Top-level functions in the operator module have a __self__ attribute, which is
the module itself
"""
assert check_tokenize(operator.add) != check_tokenize(operator.mul)
def test_tokenize_random_state():
a = random.Random(123)
b = random.Random(123)
c = random.Random(456)
assert check_tokenize(a) == check_tokenize(b)
assert check_tokenize(a) != check_tokenize(c)
a.random()
assert check_tokenize(a) != check_tokenize(b)
@pytest.mark.skipif("not np")
def test_tokenize_random_state_numpy():
a = np.random.RandomState(123)
b = np.random.RandomState(123)
c = np.random.RandomState(456)
assert check_tokenize(a) == check_tokenize(b)
assert check_tokenize(a) != check_tokenize(c)
a.random()
assert check_tokenize(a) != check_tokenize(b)
@pytest.mark.parametrize(
"module",
["random", pytest.param("np.random", marks=pytest.mark.skipif("not np"))],
)
def test_tokenize_random_functions(module):
"""random.random() and other methods of the global random state do not compare as
equal to themselves after a pickle roundtrip"""
module = eval(module)
module.seed(2)
a = module.random
b = pickle.loads(pickle.dumps(a))
assert check_tokenize(a) == check_tokenize(b)
# Drawing elements or reseeding changes the global state
a()
c = pickle.loads(pickle.dumps(a))
assert check_tokenize(a) == check_tokenize(c)
assert check_tokenize(a) != check_tokenize(b)
module.seed(123)
d = pickle.loads(pickle.dumps(a))
assert check_tokenize(a) == check_tokenize(d)
assert check_tokenize(a) != check_tokenize(c)
def test_tokenize_random_functions_with_state():
a = random.Random(123).random
b = random.Random(456).random
assert check_tokenize(a) != check_tokenize(b)
@pytest.mark.skipif("not np")
def test_tokenize_random_functions_with_state_numpy():
a = np.random.RandomState(123).random
b = np.random.RandomState(456).random
assert check_tokenize(a) != check_tokenize(b)
@pytest.mark.skipif("not pa")
def test_tokenize_pyarrow_datatypes_simple():
a = pa.int64()
b = pa.float64()
assert check_tokenize(a) != check_tokenize(b)
@pytest.mark.skipif("not pa")
def test_tokenize_pyarrow_datatypes_complex():
a = pa.struct({"x": pa.int32(), "y": pa.string()})
b = pa.struct({"x": pa.float64(), "y": pa.int16()})
assert check_tokenize(a) != check_tokenize(b)
@pytest.mark.skipif("not pa")
def test_pyarrow_table():
a = pa.table({"x": [1, 2, 3], "y": ["a", "b", "c"]})
b = pa.table({"x": [1, 2, 3], "y": ["a", "b", "c"]})
c = pa.table({"x": [1, 2, 3], "y": ["a", "b", "d"]})
assert check_tokenize(a) == check_tokenize(b)
assert check_tokenize(a) != check_tokenize(c)
@pytest.mark.skipif("not np")
def test_tokenize_opaque_object_with_buffers():
# pickle will extract PickleBuffer objects out of this
class C:
def __init__(self, x):
self.x = np.array(x)
assert check_tokenize(C([1, 2])) != check_tokenize(C([1, 3]))
if not numba:
class NumbaDummy:
def __bool__(self):
return False
def _dummy_decorator(self, *args, **kwargs):
def wrapper(func):
return func
return wrapper
jit = vectorize = guvectorize = _dummy_decorator
numba = NumbaDummy()
@numba.jit(nopython=True)
def numba_jit(x, y):
return x + y
@numba.jit("f8(f8, f8)", nopython=True)
def numba_jit_with_signature(x, y):
return x + y
@numba.vectorize(nopython=True)
def numba_vectorize(x, y):
return x + y
@numba.vectorize("f8(f8, f8)", nopython=True)
def numba_vectorize_with_signature(x, y):
return x + y
@numba.guvectorize(["f8,f8,f8[:]"], "(),()->()")
def numba_guvectorize(x, y, out):
out[0] = x + y
all_numba_funcs = [
numba_jit,
numba_jit_with_signature,
numba_vectorize,
numba_vectorize_with_signature,
numba_guvectorize,
]
@pytest.mark.skipif("not numba")
@pytest.mark.parametrize("func", all_numba_funcs)
def test_tokenize_numba(func):
assert func(1, 2) == 3
check_tokenize(func)
for func in all_numba_funcs:
tokens = normalize_token(func)
# Ensure that we attempt to tokenize it instead of dumping it into pickle
assert isinstance(tokens, tuple)
assert isinstance(tokens[1], tuple)
@pytest.mark.skipif("not numba")
def test_tokenize_numba_unique_token():
tokens = [check_tokenize(func) for func in all_numba_funcs]
assert len(tokens) == len(set(tokens))
@pytest.mark.skipif("not numba")
def test_numba_local():
@numba.jit(nopython=True)
def local_jit(x, y):
return x + y
@numba.jit("f8(f8, f8)", nopython=True)
def local_jit_with_signature(x, y):
return x + y
@numba.vectorize(nopython=True)
def local_vectorize(x, y):
return x + y
@numba.vectorize("f8(f8, f8)", nopython=True)
def local_vectorize_with_signature(x, y):
return x + y
@numba.guvectorize(["f8,f8,f8[:]"], "(),()->()")
def local_guvectorize(x, y, out):
out[0] = x + y
all_funcs = [
local_jit,
local_jit_with_signature,
local_vectorize,
local_vectorize_with_signature,
local_guvectorize,
]
tokens = [check_tokenize(func) for func in all_funcs]
assert len(tokens) == len(set(tokens))
@pytest.mark.skipif("not np")
def test_tokenize_np_dtype():
arr = np.array([1, 2, 3], dtype=np.int64)
arr2 = np.array([1, 2, 3], dtype=np.int32)
assert check_tokenize(arr.dtype) != check_tokenize(arr2.dtype)
@pytest.mark.skipif("not pd")
def test_tokenize_pandas_arrow_strings():
ser = pd.Series(["a", "b"], dtype="string[pyarrow]")
check_tokenize(ser)
tokens = normalize_token(ser)
# Maybe a little brittle but will do for now
assert any(str(tok) == "string" for tok in flatten(tokens))
|
GlobalClass
|
python
|
spyder-ide__spyder
|
spyder/api/widgets/comboboxes.py
|
{
"start": 11966,
"end": 13053
}
|
class ____(_SpyderComboBoxMixin, QFontComboBox):
def __init__(self, parent=None):
QFontComboBox.__init__(self, parent)
_SpyderComboBoxMixin.__init__(self)
# Avoid font name eliding because it confuses users.
# Fixes spyder-ide/spyder#22683
self.setItemDelegate(
_SpyderComboBoxDelegate(self, elide_mode=Qt.ElideNone)
)
# Elide selected font name in case it's too long
self.setLineEdit(
_SpyderComboBoxLineEdit(
self, editable=True, elide_mode=Qt.ElideMiddle
)
)
# Adjust popup width to contents.
self.setSizeAdjustPolicy(
QComboBox.AdjustToMinimumContentsLengthWithIcon
)
def showPopup(self):
"""Adjustments when the popup is shown."""
super().showPopup()
if sys.platform == "darwin":
popup = self.findChild(QFrame)
popup.move(popup.x() - 3, popup.y() + 4)
def hidePopup(self):
super().hidePopup()
self.sig_popup_is_hidden.emit()
|
SpyderFontComboBox
|
python
|
wandb__wandb
|
wandb/vendor/pygments/lexers/python.py
|
{
"start": 805,
"end": 11159
}
|
class ____(RegexLexer):
"""
For `Python <http://www.python.org>`_ source code.
"""
name = 'Python'
aliases = ['python', 'py', 'sage']
filenames = ['*.py', '*.pyw', '*.sc', 'SConstruct', 'SConscript', '*.tac', '*.sage']
mimetypes = ['text/x-python', 'application/x-python']
def innerstring_rules(ttype):
return [
# the old style '%s' % (...) string formatting
(r'%(\(\w+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?'
'[hlL]?[E-GXc-giorsux%]', String.Interpol),
# backslashes, quotes and formatting signs must be parsed one at a time
(r'[^\\\'"%\n]+', ttype),
(r'[\'"\\]', ttype),
# unhandled string formatting sign
(r'%', ttype),
# newlines are an error (use "nl" state)
]
tokens = {
'root': [
(r'\n', Text),
(r'^(\s*)([rRuUbB]{,2})("""(?:.|\n)*?""")',
bygroups(Text, String.Affix, String.Doc)),
(r"^(\s*)([rRuUbB]{,2})('''(?:.|\n)*?''')",
bygroups(Text, String.Affix, String.Doc)),
(r'[^\S\n]+', Text),
(r'\A#!.+$', Comment.Hashbang),
(r'#.*$', Comment.Single),
(r'[]{}:(),;[]', Punctuation),
(r'\\\n', Text),
(r'\\', Text),
(r'(in|is|and|or|not)\b', Operator.Word),
(r'!=|==|<<|>>|[-~+/*%=<>&^|.]', Operator),
include('keywords'),
(r'(def)((?:\s|\\\s)+)', bygroups(Keyword, Text), 'funcname'),
(r'(class)((?:\s|\\\s)+)', bygroups(Keyword, Text), 'classname'),
(r'(from)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Text),
'fromimport'),
(r'(import)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Text),
'import'),
include('builtins'),
include('magicfuncs'),
include('magicvars'),
include('backtick'),
('([rR]|[uUbB][rR]|[rR][uUbB])(""")',
bygroups(String.Affix, String.Double), 'tdqs'),
("([rR]|[uUbB][rR]|[rR][uUbB])(''')",
bygroups(String.Affix, String.Single), 'tsqs'),
('([rR]|[uUbB][rR]|[rR][uUbB])(")',
bygroups(String.Affix, String.Double), 'dqs'),
("([rR]|[uUbB][rR]|[rR][uUbB])(')",
bygroups(String.Affix, String.Single), 'sqs'),
('([uUbB]?)(""")', bygroups(String.Affix, String.Double),
combined('stringescape', 'tdqs')),
("([uUbB]?)(''')", bygroups(String.Affix, String.Single),
combined('stringescape', 'tsqs')),
('([uUbB]?)(")', bygroups(String.Affix, String.Double),
combined('stringescape', 'dqs')),
("([uUbB]?)(')", bygroups(String.Affix, String.Single),
combined('stringescape', 'sqs')),
include('name'),
include('numbers'),
],
'keywords': [
(words((
'assert', 'break', 'continue', 'del', 'elif', 'else', 'except',
'exec', 'finally', 'for', 'global', 'if', 'lambda', 'pass',
'print', 'raise', 'return', 'try', 'while', 'yield',
'yield from', 'as', 'with'), suffix=r'\b'),
Keyword),
],
'builtins': [
(words((
'__import__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin',
'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod',
'cmp', 'coerce', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod',
'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',
'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'hex', 'id',
'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len',
'list', 'locals', 'long', 'map', 'max', 'min', 'next', 'object',
'oct', 'open', 'ord', 'pow', 'property', 'range', 'raw_input', 'reduce',
'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type',
'unichr', 'unicode', 'vars', 'xrange', 'zip'),
prefix=r'(?<!\.)', suffix=r'\b'),
Name.Builtin),
(r'(?<!\.)(self|None|Ellipsis|NotImplemented|False|True|cls'
r')\b', Name.Builtin.Pseudo),
(words((
'ArithmeticError', 'AssertionError', 'AttributeError',
'BaseException', 'DeprecationWarning', 'EOFError', 'EnvironmentError',
'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit',
'IOError', 'ImportError', 'ImportWarning', 'IndentationError',
'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError',
'MemoryError', 'NameError', 'NotImplemented', 'NotImplementedError',
'OSError', 'OverflowError', 'OverflowWarning', 'PendingDeprecationWarning',
'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError',
'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',
'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError',
'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError',
'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',
'ValueError', 'VMSError', 'Warning', 'WindowsError',
'ZeroDivisionError'), prefix=r'(?<!\.)', suffix=r'\b'),
Name.Exception),
],
'magicfuncs': [
(words((
'__abs__', '__add__', '__and__', '__call__', '__cmp__', '__coerce__',
'__complex__', '__contains__', '__del__', '__delattr__', '__delete__',
'__delitem__', '__delslice__', '__div__', '__divmod__', '__enter__',
'__eq__', '__exit__', '__float__', '__floordiv__', '__ge__', '__get__',
'__getattr__', '__getattribute__', '__getitem__', '__getslice__', '__gt__',
'__hash__', '__hex__', '__iadd__', '__iand__', '__idiv__', '__ifloordiv__',
'__ilshift__', '__imod__', '__imul__', '__index__', '__init__',
'__instancecheck__', '__int__', '__invert__', '__iop__', '__ior__',
'__ipow__', '__irshift__', '__isub__', '__iter__', '__itruediv__',
'__ixor__', '__le__', '__len__', '__long__', '__lshift__', '__lt__',
'__missing__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__',
'__nonzero__', '__oct__', '__op__', '__or__', '__pos__', '__pow__',
'__radd__', '__rand__', '__rcmp__', '__rdiv__', '__rdivmod__', '__repr__',
'__reversed__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__',
'__rop__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__',
'__rtruediv__', '__rxor__', '__set__', '__setattr__', '__setitem__',
'__setslice__', '__str__', '__sub__', '__subclasscheck__', '__truediv__',
'__unicode__', '__xor__'), suffix=r'\b'),
Name.Function.Magic),
],
'magicvars': [
(words((
'__bases__', '__class__', '__closure__', '__code__', '__defaults__',
'__dict__', '__doc__', '__file__', '__func__', '__globals__',
'__metaclass__', '__module__', '__mro__', '__name__', '__self__',
'__slots__', '__weakref__'),
suffix=r'\b'),
Name.Variable.Magic),
],
'numbers': [
(r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?j?', Number.Float),
(r'\d+[eE][+-]?[0-9]+j?', Number.Float),
(r'0[0-7]+j?', Number.Oct),
(r'0[bB][01]+', Number.Bin),
(r'0[xX][a-fA-F0-9]+', Number.Hex),
(r'\d+L', Number.Integer.Long),
(r'\d+j?', Number.Integer)
],
'backtick': [
('`.*?`', String.Backtick),
],
'name': [
(r'@[\w.]+', Name.Decorator),
('[a-zA-Z_]\w*', Name),
],
'funcname': [
include('magicfuncs'),
('[a-zA-Z_]\w*', Name.Function, '#pop'),
default('#pop'),
],
'classname': [
('[a-zA-Z_]\w*', Name.Class, '#pop')
],
'import': [
(r'(?:[ \t]|\\\n)+', Text),
(r'as\b', Keyword.Namespace),
(r',', Operator),
(r'[a-zA-Z_][\w.]*', Name.Namespace),
default('#pop') # all else: go back
],
'fromimport': [
(r'(?:[ \t]|\\\n)+', Text),
(r'import\b', Keyword.Namespace, '#pop'),
# if None occurs here, it's "raise x from None", since None can
# never be a module name
(r'None\b', Name.Builtin.Pseudo, '#pop'),
# sadly, in "raise x from y" y will be highlighted as namespace too
(r'[a-zA-Z_.][\w.]*', Name.Namespace),
# anything else here also means "raise x from y" and is therefore
# not an error
default('#pop'),
],
'stringescape': [
(r'\\([\\abfnrtv"\']|\n|N\{.*?\}|u[a-fA-F0-9]{4}|'
r'U[a-fA-F0-9]{8}|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape)
],
'strings-single': innerstring_rules(String.Single),
'strings-double': innerstring_rules(String.Double),
'dqs': [
(r'"', String.Double, '#pop'),
(r'\\\\|\\"|\\\n', String.Escape), # included here for raw strings
include('strings-double')
],
'sqs': [
(r"'", String.Single, '#pop'),
(r"\\\\|\\'|\\\n", String.Escape), # included here for raw strings
include('strings-single')
],
'tdqs': [
(r'"""', String.Double, '#pop'),
include('strings-double'),
(r'\n', String.Double)
],
'tsqs': [
(r"'''", String.Single, '#pop'),
include('strings-single'),
(r'\n', String.Single)
],
}
def analyse_text(text):
return shebang_matches(text, r'pythonw?(2(\.\d)?)?') or \
'import ' in text[:1000]
|
PythonLexer
|
python
|
ansible__ansible
|
test/integration/targets/loop-connection/collections/ansible_collections/ns/name/plugins/connection/dummy.py
|
{
"start": 361,
"end": 1209
}
|
class ____(ConnectionBase):
transport = 'ns.name.dummy'
def __init__(self, *args, **kwargs):
self._cmds_run = 0
super().__init__(*args, **kwargs)
@property
def connected(self):
return True
def _connect(self):
return
def exec_command(self, cmd, in_data=None, sudoable=True):
if 'become_test' in cmd:
stderr = f"become - {self.become.name if self.become else None}"
elif 'connected_test' in cmd:
self._cmds_run += 1
stderr = f"ran - {self._cmds_run}"
else:
raise AnsibleError(f"Unknown test cmd {cmd}")
return 0, cmd.encode(), stderr.encode()
def put_file(self, in_path, out_path):
return
def fetch_file(self, in_path, out_path):
return
def close(self):
return
|
Connection
|
python
|
getsentry__sentry
|
src/social_auth/exceptions.py
|
{
"start": 509,
"end": 742
}
|
class ____(SocialAuthBaseException):
"""Stop pipeline process exception.
Raise this exception to stop the rest of the pipeline process.
"""
def __str__(self) -> str:
return gettext("Stop pipeline")
|
StopPipeline
|
python
|
numpy__numpy
|
numpy/polynomial/tests/test_legendre.py
|
{
"start": 16132,
"end": 16539
}
|
class ____:
def test_raises(self):
assert_raises(ValueError, leg.legcompanion, [])
assert_raises(ValueError, leg.legcompanion, [1])
def test_dimensions(self):
for i in range(1, 5):
coef = [0] * i + [1]
assert_(leg.legcompanion(coef).shape == (i, i))
def test_linear_root(self):
assert_(leg.legcompanion([1, 2])[0, 0] == -.5)
|
TestCompanion
|
python
|
getsentry__sentry
|
src/sentry/debug/utils/exception_reporter_filter.py
|
{
"start": 121,
"end": 260
}
|
class ____(SafeExceptionReporterFilter):
def get_safe_settings(self) -> dict[str, Any]:
return {}
|
NoSettingsExceptionReporterFilter
|
python
|
kubernetes-client__python
|
kubernetes/client/api/events_v1_api.py
|
{
"start": 543,
"end": 120463
}
|
class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def create_namespaced_event(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_event # noqa: E501
create an Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_event(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param EventsV1Event body: (required)
:param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: EventsV1Event
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.create_namespaced_event_with_http_info(namespace, body, **kwargs) # noqa: E501
def create_namespaced_event_with_http_info(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_event # noqa: E501
create an Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_event_with_http_info(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param EventsV1Event body: (required)
:param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(EventsV1Event, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_event" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_event`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_event`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/apis/events.k8s.io/v1/namespaces/{namespace}/events', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='EventsV1Event', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_namespaced_event(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_event # noqa: E501
delete collection of Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespaced_event(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_collection_namespaced_event_with_http_info(namespace, **kwargs) # noqa: E501
def delete_collection_namespaced_event_with_http_info(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_event # noqa: E501
delete collection of Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespaced_event_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'_continue',
'dry_run',
'field_selector',
'grace_period_seconds',
'ignore_store_read_error_with_cluster_breaking_potential',
'label_selector',
'limit',
'orphan_dependents',
'propagation_policy',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_collection_namespaced_event" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_event`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501
query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/apis/events.k8s.io/v1/namespaces/{namespace}/events', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_namespaced_event(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_event # noqa: E501
delete an Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_event(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Event (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_namespaced_event_with_http_info(name, namespace, **kwargs) # noqa: E501
def delete_namespaced_event_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_event # noqa: E501
delete an Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_event_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Event (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty',
'dry_run',
'grace_period_seconds',
'ignore_store_read_error_with_cluster_breaking_potential',
'orphan_dependents',
'propagation_policy',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_event" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `delete_namespaced_event`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_namespaced_event`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501
query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/apis/events.k8s.io/v1/namespaces/{namespace}/events/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def get_api_resources(self, **kwargs): # noqa: E501
"""get_api_resources # noqa: E501
get available resources # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_api_resources(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1APIResourceList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.get_api_resources_with_http_info(**kwargs) # noqa: E501
def get_api_resources_with_http_info(self, **kwargs): # noqa: E501
"""get_api_resources # noqa: E501
get available resources # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_api_resources_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1APIResourceList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method get_api_resources" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/apis/events.k8s.io/v1/', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1APIResourceList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_event_for_all_namespaces(self, **kwargs): # noqa: E501
"""list_event_for_all_namespaces # noqa: E501
list or watch objects of kind Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_event_for_all_namespaces(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: EventsV1EventList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_event_for_all_namespaces_with_http_info(**kwargs) # noqa: E501
def list_event_for_all_namespaces_with_http_info(self, **kwargs): # noqa: E501
"""list_event_for_all_namespaces # noqa: E501
list or watch objects of kind Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_event_for_all_namespaces_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(EventsV1EventList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'pretty',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_event_for_all_namespaces" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch', 'application/cbor-seq']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/apis/events.k8s.io/v1/events', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='EventsV1EventList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_namespaced_event(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_event # noqa: E501
list or watch objects of kind Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_event(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: EventsV1EventList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_namespaced_event_with_http_info(namespace, **kwargs) # noqa: E501
def list_namespaced_event_with_http_info(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_event # noqa: E501
list or watch objects of kind Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_event_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(EventsV1EventList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_event" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `list_namespaced_event`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch', 'application/cbor-seq']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/apis/events.k8s.io/v1/namespaces/{namespace}/events', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='EventsV1EventList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_event(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_event # noqa: E501
partially update the specified Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_event(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Event (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: EventsV1Event
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespaced_event_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def patch_namespaced_event_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_event # noqa: E501
partially update the specified Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_event_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Event (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(EventsV1Event, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_event" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_event`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_event`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_event`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml', 'application/apply-patch+cbor']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/apis/events.k8s.io/v1/namespaces/{namespace}/events/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='EventsV1Event', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_event(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_event # noqa: E501
read the specified Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_event(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Event (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: EventsV1Event
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespaced_event_with_http_info(name, namespace, **kwargs) # noqa: E501
def read_namespaced_event_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_event # noqa: E501
read the specified Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_event_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Event (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(EventsV1Event, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_event" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_event`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_event`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/apis/events.k8s.io/v1/namespaces/{namespace}/events/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='EventsV1Event', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_event(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_event # noqa: E501
replace the specified Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_event(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Event (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param EventsV1Event body: (required)
:param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: EventsV1Event
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespaced_event_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def replace_namespaced_event_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_event # noqa: E501
replace the specified Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_event_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Event (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param EventsV1Event body: (required)
:param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(EventsV1Event, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_event" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_event`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_event`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_event`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/apis/events.k8s.io/v1/namespaces/{namespace}/events/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='EventsV1Event', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
|
EventsV1Api
|
python
|
scipy__scipy
|
benchmarks/benchmarks/go_benchmark_functions/go_funcs_H.py
|
{
"start": 135,
"end": 1364
}
|
class ____(Benchmark):
r"""
Hansen objective function.
This class defines the Hansen [1]_ global optimization problem. This is a
multimodal minimization problem defined as follows:
.. math::
f_{\text{Hansen}}(x) = \left[ \sum_{i=0}^4(i+1)\cos(ix_1+i+1)\right ]
\left[\sum_{j=0}^4(j+1)\cos[(j+2)x_2+j+1])\right ]
with :math:`x_i \in [-10, 10]` for :math:`i = 1, 2`.
*Global optimum*: :math:`f(x) = -176.54179` for
:math:`x = [-7.58989583, -7.70831466]`.
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
TODO Jamil #61 is missing the starting value of i.
"""
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip([-10.0] * self.N, [10.0] * self.N))
self.global_optimum = [[-7.58989583, -7.70831466]]
self.fglob = -176.54179
def fun(self, x, *args):
self.nfev += 1
i = arange(5.)
a = (i + 1) * cos(i * x[0] + i + 1)
b = (i + 1) * cos((i + 2) * x[1] + i + 1)
return sum(a) * sum(b)
|
Hansen
|
python
|
jazzband__django-simple-history
|
simple_history/tests/models.py
|
{
"start": 21975,
"end": 22149
}
|
class ____(models.Model):
history = HistoricalRecords(inherit=True, custom_model_name=lambda x: f"Audit{x}")
class Meta:
abstract = True
|
AbstractModelCallable1
|
python
|
ray-project__ray
|
python/ray/data/aggregate.py
|
{
"start": 26962,
"end": 29371
}
|
class ____(AggregateFnV2[SupportsRichComparisonType, SupportsRichComparisonType]):
"""Defines absolute max aggregation.
Example:
.. testcode::
import ray
from ray.data.aggregate import AbsMax
ds = ray.data.range(100)
# Schema: {'id': int64}
ds = ds.add_column("group_key", lambda x: x % 3)
# Schema: {'id': int64, 'group_key': int64}
# Calculating the absolute maximum value per group:
result = ds.groupby("group_key").aggregate(AbsMax(on="id")).take_all()
# result: [{'group_key': 0, 'abs_max(id)': ...},
# {'group_key': 1, 'abs_max(id)': ...},
# {'group_key': 2, 'abs_max(id)': ...}]
Args:
on: The name of the column to calculate absolute maximum on. Must be provided.
ignore_nulls: Whether to ignore null values. Default is True.
alias_name: Optional name for the resulting column.
zero_factory: A callable that returns the initial "zero" value for the
accumulator. For example, for a float column, this would be
`lambda: 0`. Default is `lambda: 0`.
"""
def __init__(
self,
on: Optional[str] = None,
ignore_nulls: bool = True,
alias_name: Optional[str] = None,
zero_factory: Callable[[], SupportsRichComparisonType] = lambda: 0,
):
if on is None or not isinstance(on, str):
raise ValueError(f"Column to aggregate on has to be provided (got {on})")
super().__init__(
alias_name if alias_name else f"abs_max({str(on)})",
on=on,
ignore_nulls=ignore_nulls,
zero_factory=zero_factory,
)
def aggregate_block(self, block: Block) -> Optional[SupportsRichComparisonType]:
block_accessor = BlockAccessor.for_block(block)
max_ = block_accessor.max(self._target_col_name, self._ignore_nulls)
min_ = block_accessor.min(self._target_col_name, self._ignore_nulls)
if is_null(max_) or is_null(min_):
return None
return max(abs(max_), abs(min_))
def combine(
self,
current_accumulator: SupportsRichComparisonType,
new: SupportsRichComparisonType,
) -> SupportsRichComparisonType:
return max(current_accumulator, new)
@PublicAPI
|
AbsMax
|
python
|
django__django
|
tests/db_functions/text/test_left.py
|
{
"start": 164,
"end": 1313
}
|
class ____(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="Rhonda")
def test_basic(self):
authors = Author.objects.annotate(name_part=Left("name", 5))
self.assertQuerySetEqual(
authors.order_by("name"), ["John ", "Rhond"], lambda a: a.name_part
)
# If alias is null, set it to the first 2 lower characters of the name.
Author.objects.filter(alias__isnull=True).update(alias=Lower(Left("name", 2)))
self.assertQuerySetEqual(
authors.order_by("name"), ["smithj", "rh"], lambda a: a.alias
)
def test_invalid_length(self):
with self.assertRaisesMessage(ValueError, "'length' must be greater than 0"):
Author.objects.annotate(raises=Left("name", 0))
def test_expressions(self):
authors = Author.objects.annotate(
name_part=Left("name", Value(3, output_field=IntegerField()))
)
self.assertQuerySetEqual(
authors.order_by("name"), ["Joh", "Rho"], lambda a: a.name_part
)
|
LeftTests
|
python
|
jazzband__django-simple-history
|
simple_history/tests/models.py
|
{
"start": 21296,
"end": 21428
}
|
class ____(models.Model):
greeting = models.CharField(max_length=100)
history = HistoricalRecords()
|
CharFieldChangeReasonModel
|
python
|
pytorch__pytorch
|
torch/_higher_order_ops/foreach_map.py
|
{
"start": 200,
"end": 690
}
|
class ____(BaseHOP):
def __init__(self):
super().__init__("foreach_map")
def __call__(self, fn, *operands, **kwargs): # type: ignore[override]
fn = FunctionWithNoFreeVars(fn)
return super().__call__(fn, *operands, **kwargs)
_foreach_map = ForeachMap()
def foreach_map(op: Callable, *operands: Any, **kwargs: dict[str, Any]):
from torch._dynamo.polyfills import foreach_map_fn
return _foreach_map(foreach_map_fn, op, *operands, **kwargs)
|
ForeachMap
|
python
|
airbytehq__airbyte
|
airbyte-integrations/connectors/source-surveymonkey/source_surveymonkey/streams.py
|
{
"start": 4495,
"end": 5974
}
|
class ____(SurveymonkeyStream, CheckpointMixin, ABC):
state_checkpoint_interval = 1000
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._state = None
@property
@abstractmethod
def cursor_field(self) -> str:
pass
@property
def state(self) -> MutableMapping[str, Any]:
return self._state
@state.setter
def state(self, value: MutableMapping[str, Any]):
self._state = value
def read_records(
self,
sync_mode: SyncMode,
cursor_field: List[str] = None,
stream_slice: Mapping[str, Any] = None,
stream_state: Mapping[str, Any] = None,
) -> Iterable[Mapping[str, Any]]:
for record in super().read_records(sync_mode, cursor_field, stream_slice, stream_state):
self.state = self._get_updated_state(self.state, record)
yield record
def _get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]) -> Mapping[str, Any]:
"""
Return the latest state by comparing the cursor value in the latest record with the stream's most recent state object
and returning an updated state object.
"""
current_stream_state = current_stream_state or {}
state_value = max(current_stream_state.get(self.cursor_field, ""), latest_record.get(self.cursor_field, ""))
return {self.cursor_field: state_value}
|
IncrementalSurveymonkeyStream
|
python
|
microsoft__pyright
|
packages/pyright-internal/src/tests/samples/genericType28.py
|
{
"start": 2236,
"end": 2270
}
|
class ____(Co[Co[T_co]]): ...
|
CoToCo
|
python
|
ray-project__ray
|
python/ray/_private/thirdparty/pynvml/pynvml.py
|
{
"start": 65785,
"end": 66218
}
|
class ____(_PrintableStructure):
_fields_ = [
('processName', c_char * NVML_VGPU_NAME_BUFFER_SIZE),
('timeStamp', c_ulonglong),
('vgpuInstance', _nvmlVgpuInstance_t),
('pid', c_uint),
('smUtil', c_uint),
('memUtil', c_uint),
('encUtil', c_uint),
('decUtil', c_uint),
('jpgUtil', c_uint),
('ofaUtil', c_uint),
]
|
c_nvmlVgpuProcessUtilizationInfo_v1_t
|
python
|
tox-dev__tox
|
src/tox/report.py
|
{
"start": 2980,
"end": 3111
}
|
class ____(BytesIO):
def __init__(self, name: str) -> None:
super().__init__()
self.name: str = name
|
NamedBytesIO
|
python
|
getsentry__sentry
|
src/sentry/preprod/api/endpoints/project_preprod_artifact_download.py
|
{
"start": 1654,
"end": 6414
}
|
class ____(PreprodArtifactEndpoint):
owner = ApiOwner.EMERGE_TOOLS
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
"HEAD": ApiPublishStatus.PRIVATE,
}
authentication_classes = (
LaunchpadRpcSignatureAuthentication,
SessionAuthentication,
UserAuthTokenAuthentication,
)
permission_classes = (LaunchpadServiceOrStaffPermission,)
def _get_file_object(self, head_artifact: PreprodArtifact) -> File:
if head_artifact.file_id is None:
raise ResourceDoesNotExist
try:
return File.objects.get(id=head_artifact.file_id)
except File.DoesNotExist:
raise ResourceDoesNotExist
def _get_filename(self, head_artifact: PreprodArtifact) -> str:
return f"preprod_artifact_{head_artifact.id}.zip"
def head(
self,
request: Request,
project: Project,
head_artifact_id: int,
head_artifact: PreprodArtifact,
) -> HttpResponseBase:
file_obj = self._get_file_object(head_artifact)
filename = self._get_filename(head_artifact)
file_size = file_obj.size
if file_size is None or file_size < 0:
return Response({"error": "File size unavailable"}, status=500)
response = HttpResponse()
response["Content-Length"] = file_size
response["Content-Type"] = "application/octet-stream"
response["Content-Disposition"] = f'attachment; filename="{filename}"'
response["Accept-Ranges"] = "bytes"
return response
def get(
self,
request: Request,
project: Project,
head_artifact_id: int,
head_artifact: PreprodArtifact,
) -> HttpResponseBase:
"""
Download a preprod artifact file
```````````````````````````````
Download the actual file contents of a preprod artifact.
Supports HTTP Range requests for resumable downloads.
:pparam string organization_id_or_slug: the id or slug of the organization the
artifact belongs to.
:pparam string project_id_or_slug: the id or slug of the project to retrieve the
artifact from.
:pparam string head_artifact_id: the ID of the preprod artifact to download.
:auth: required
"""
file_obj = self._get_file_object(head_artifact)
filename = self._get_filename(head_artifact)
file_size = file_obj.size
if file_size is None or file_size < 0:
return Response({"error": "File size unavailable"}, status=500)
range_header = request.META.get("HTTP_RANGE")
if range_header:
try:
ranges = parse_range_header(range_header)
if not ranges:
return HttpResponse(status=400)
if len(ranges) > 1:
raise MalformedRangeHeader("Too many ranges specified.")
range_obj = ranges[0]
if file_size == 0:
return HttpResponse(status=416)
start, end = range_obj.make_range(file_size - 1)
with file_obj.getfile() as fp:
fp.seek(start)
content_length = end - start + 1
file_content = fp.read(content_length)
response = HttpResponse(
file_content,
content_type="application/octet-stream",
status=206,
)
response["Content-Length"] = content_length
response["Content-Range"] = f"bytes {start}-{end}/{file_size}"
response["Accept-Ranges"] = "bytes"
response["Content-Disposition"] = f'attachment; filename="{filename}"'
return response
except (MalformedRangeHeader, UnsatisfiableRange):
return HttpResponse(status=416)
except (ValueError, IndexError):
return HttpResponse(status=400)
def file_iterator() -> Iterator[bytes]:
with file_obj.getfile() as fp:
while True:
chunk = fp.read(4096)
if not chunk:
break
yield chunk
streaming_response = StreamingHttpResponse(
file_iterator(),
content_type="application/octet-stream",
)
streaming_response["Content-Length"] = file_size
streaming_response["Content-Disposition"] = f'attachment; filename="{filename}"'
streaming_response["Accept-Ranges"] = "bytes"
return streaming_response
|
ProjectPreprodArtifactDownloadEndpoint
|
python
|
allegroai__clearml
|
examples/distributed/pytorch_distributed_example.py
|
{
"start": 1527,
"end": 6655
}
|
class ____(object):
def __init__(self, data, sizes=(0.7, 0.2, 0.1), seed=1234):
self.data = data
self.partitions = []
rng = Random()
rng.seed(seed)
data_len = len(data)
indexes = [x for x in range(0, data_len)]
rng.shuffle(indexes)
for frac in sizes:
part_len = int(frac * data_len)
self.partitions.append(indexes[0:part_len])
indexes = indexes[part_len:]
def use(self, partition):
return Partition(self.data, self.partitions[partition])
def partition_dataset(num_workers=4):
""" Partitioning MNIST """
dataset = datasets.MNIST(root=local_dataset_path, train=True, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
]))
size = dist.get_world_size()
bsz = int(128 / float(size))
partition_sizes = [1.0 / size for _ in range(size)]
partition = DataPartitioner(dataset, partition_sizes)
partition = partition.use(dist.get_rank())
train_set = th.utils.data.DataLoader(
partition, num_workers=num_workers, batch_size=bsz, shuffle=True)
return train_set, bsz
def run(num_workers):
""" Distributed Synchronous SGD Example """
th.manual_seed(1234)
train_set, bsz = partition_dataset(num_workers)
model = Net()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
num_batches = ceil(len(train_set.dataset) / float(bsz))
from random import randint
param = {'worker_{}_stuff'.format(dist.get_rank()): 'some stuff ' + str(randint(0, 100))}
Task.current_task().connect(param)
Task.current_task().upload_artifact(
'temp {:02d}'.format(dist.get_rank()), artifact_object={'worker_rank': dist.get_rank()})
for epoch in range(2):
epoch_loss = 0.0
for i, (data, target) in enumerate(train_set):
optimizer.zero_grad()
output = model(data)
loss = F.nll_loss(output, target)
epoch_loss += loss.item()
loss.backward()
average_gradients(model)
optimizer.step()
if i % 10 == 0:
print('{}] Train Epoch {} - {} \tLoss {:.6f}'.format(dist.get_rank(), epoch, i, loss))
Task.current_task().get_logger().report_scalar(
'loss', 'worker {:02d}'.format(dist.get_rank()), value=loss.item(), iteration=i)
if i > 100:
break
print('Rank ', dist.get_rank(), ', epoch ',
epoch, ': ', epoch_loss / num_batches)
def average_gradients(model):
""" Gradient averaging. """
size = float(dist.get_world_size())
for param in model.parameters():
dist.all_reduce(param.grad.data, op=dist.reduce_op.SUM)
param.grad.data /= size
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument('--nodes', help='number of nodes', type=int, default=10)
parser.add_argument('--workers_in_node', help='number of workers per node', type=int, default=3)
# this argument we will not be logging, see below Task.init
parser.add_argument('--rank', help='current rank', type=int)
args = parser.parse_args()
# We have to initialize the task in the master process,
# it will make sure that any sub-process calling Task.init will get the master task object
# notice that we exclude the `rank` argument, so we can launch multiple sub-processes with clearml-agent
# otherwise, the `rank` will always be set to the original value.
task = Task.init("examples", "test torch distributed", auto_connect_arg_parser={'rank': False})
if not dist.is_available():
print("torch.distributed is not supported for this platform")
exit(0)
if os.environ.get('MASTER_ADDR'):
# Use a large timeout value since in Windows timeout issues may cause
# pg = ProcessGroupGloo(prefix_store, rank, world_size, timeout=timeout)
# RuntimeError: Socket TimeoutSocket
dist.init_process_group(
backend='gloo', rank=args.rank, world_size=args.nodes, timeout=timedelta(days=1)
)
run(args.workers_in_node)
else:
# first let's download the dataset, if we have multiple machines,
# they will take care of it when they get there
datasets.MNIST(root=local_dataset_path, train=True, download=True)
os.environ['MASTER_ADDR'] = '127.0.0.1'
os.environ['MASTER_PORT'] = '29500'
print(os.getpid(), 'ARGS:', args)
processes = []
for rank in range(args.nodes):
cmd = [sys.executable, sys.argv[0],
'--nodes', str(args.nodes),
'--workers_in_node', str(args.workers_in_node),
'--rank', str(rank)]
print(cmd)
p = subprocess.Popen(cmd, cwd=os.getcwd(), pass_fds=[], close_fds=True)
processes.append(p)
for p in processes:
p.wait()
|
DataPartitioner
|
python
|
wandb__wandb
|
wandb/apis/importers/internals/protocols.py
|
{
"start": 327,
"end": 2885
}
|
class ____(Protocol):
def run_id(self) -> str: ... # pragma: no cover
def entity(self) -> str: ... # pragma: no cover
def project(self) -> str: ... # pragma: no cover
def config(self) -> Dict[str, Any]: ... # pragma: no cover
def summary(self) -> Dict[str, float]: ... # pragma: no cover
def metrics(self) -> Iterable[Dict[str, float]]:
"""Metrics for the run.
We expect metrics in this shape:
[
{'metric1': 1, 'metric2': 1, '_step': 0},
{'metric1': 2, 'metric2': 4, '_step': 1},
{'metric1': 3, 'metric2': 9, '_step': 2},
...
]
You can also submit metrics in this shape:
[
{'metric1': 1, '_step': 0},
{'metric2': 1, '_step': 0},
{'metric1': 2, '_step': 1},
{'metric2': 4, '_step': 1},
...
]
"""
... # pragma: no cover
def run_group(self) -> Optional[str]: ... # pragma: no cover
def job_type(self) -> Optional[str]: ... # pragma: no cover
def display_name(self) -> str: ... # pragma: no cover
def notes(self) -> Optional[str]: ... # pragma: no cover
def tags(self) -> Optional[List[str]]: ... # pragma: no cover
def artifacts(self) -> Optional[Iterable[Artifact]]: ... # pragma: no cover
def used_artifacts(self) -> Optional[Iterable[Artifact]]: ... # pragma: no cover
def os_version(self) -> Optional[str]: ... # pragma: no cover
def python_version(self) -> Optional[str]: ... # pragma: no cover
def cuda_version(self) -> Optional[str]: ... # pragma: no cover
def program(self) -> Optional[str]: ... # pragma: no cover
def host(self) -> Optional[str]: ... # pragma: no cover
def username(self) -> Optional[str]: ... # pragma: no cover
def executable(self) -> Optional[str]: ... # pragma: no cover
def gpus_used(self) -> Optional[str]: ... # pragma: no cover
def cpus_used(self) -> Optional[int]: ... # pragma: no cover
def memory_used(self) -> Optional[int]: ... # pragma: no cover
def runtime(self) -> Optional[int]: ... # pragma: no cover
def start_time(self) -> Optional[int]: ... # pragma: no cover
def code_path(self) -> Optional[str]: ... # pragma: no cover
def cli_version(self) -> Optional[str]: ... # pragma: no cover
def files(
self,
) -> Optional[Iterable[Tuple[PathStr, Policy]]]: ... # pragma: no cover
def logs(self) -> Optional[Iterable[str]]: ... # pragma: no cover
|
ImporterRun
|
python
|
ansible__ansible
|
lib/ansible/modules/hostname.py
|
{
"start": 26645,
"end": 26758
}
|
class ____(Hostname):
platform = 'Linux'
distribution = 'Pop'
strategy_class = FileStrategy
|
PopHostname
|
python
|
pytorch__pytorch
|
benchmarks/operator_benchmark/pt/unary_test.py
|
{
"start": 483,
"end": 4237
}
|
class ____(op_bench.TorchBenchmarkBase):
def init(self, M, N, device, op_func):
self.inputs = {"input": torch.rand(M, N, device=device)}
self.op_func = op_func
def forward(self, input):
return self.op_func(input)
def bernoulli_(input):
return input.bernoulli_()
def cauchy_(input):
return input.cauchy_()
def digamma_(input):
return input.digamma_()
def exponential_(input):
return input.exponential_()
def normal_(input):
return input.normal_()
def random_(input):
return input.random_()
def sign_(input):
return input.sign_()
def uniform_(input):
return input.uniform_()
def half_(input):
return input.half()
def long_(input):
return input.long()
def clamp(input):
return torch.clamp(input, min=0.25, max=0.75)
unary_ops_list = op_bench.op_list(
attr_names=["op_name", "op_func"],
attrs=[
["abs", torch.abs],
["abs_", torch.abs_],
["acos", torch.acos],
["acos_", torch.acos_],
["argsort", torch.argsort],
["asin", torch.asin],
["asin_", torch.asin_],
["atan", torch.atan],
["atan_", torch.atan_],
["ceil", torch.ceil],
["ceil_", torch.ceil_],
["clamp", clamp],
["clone", torch.clone],
["cos", torch.cos],
["cos_", torch.cos_],
["cosh", torch.cosh],
["digamma", torch.digamma],
["erf", torch.erf],
["erf_", torch.erf_],
["erfc", torch.erfc],
["erfc_", torch.erfc_],
["erfinv", torch.erfinv],
["exp", torch.exp],
["exp_", torch.exp_],
["expm1", torch.expm1],
["expm1_", torch.expm1_],
["floor", torch.floor],
["floor_", torch.floor_],
["frac", torch.frac],
["frac_", torch.frac_],
["gelu", torch.nn.functional.gelu],
["hardshrink", torch.hardshrink],
["lgamma", torch.lgamma],
["log", torch.log],
["log10", torch.log10],
["log10_", torch.log10_],
["log1p", torch.log1p],
["log1p_", torch.log1p_],
["log2", torch.log2],
["log2_", torch.log2_],
["log_", torch.log_],
["logit", torch.logit],
["logit_", torch.logit_],
["neg", torch.neg],
["neg_", torch.neg_],
["reciprocal", torch.reciprocal],
["reciprocal_", torch.reciprocal_],
["relu", torch.relu],
["relu_", torch.relu_],
["round", torch.round],
["round_", torch.round_],
["rsqrt", torch.rsqrt],
["rsqrt_", torch.rsqrt_],
["sigmoid", torch.sigmoid],
["sigmoid_", torch.sigmoid_],
["sign", torch.sign],
["sgn", torch.sgn],
["sin", torch.sin],
["sin_", torch.sin_],
["sinh", torch.sinh],
["sqrt", torch.sqrt],
["sqrt_", torch.sqrt_],
["square", torch.square],
["square_", torch.square_],
["tan", torch.tan],
["tan_", torch.tan_],
["tanh", torch.tanh],
["tanh_", torch.tanh_],
["trunc", torch.trunc],
["trunc_", torch.trunc_],
["unique", torch.functional._return_output],
["zero_", torch.zero_],
["bernoulli_", bernoulli_],
["cauchy_", cauchy_],
["digamma_", digamma_],
["exponential_", exponential_],
["normal_", normal_],
["random_", random_],
["sign_", sign_],
["uniform_", uniform_],
["half", half_],
["long", long_],
],
)
op_bench.generate_pt_tests_from_op_list(
unary_ops_list, unary_ops_configs_short + unary_ops_configs_long, UnaryOpBenchmark
)
if __name__ == "__main__":
op_bench.benchmark_runner.main()
|
UnaryOpBenchmark
|
python
|
getsentry__sentry-python
|
tests/integrations/grpc/test_grpc_aio.py
|
{
"start": 8911,
"end": 10019
}
|
class ____(gRPCTestServiceServicer):
class TestException(Exception):
__test__ = False
def __init__(self):
super().__init__("test")
@classmethod
async def TestServe(cls, request, context): # noqa: N802
with start_span(
op="test",
name="test",
origin="auto.grpc.grpc.TestService.aio",
):
pass
if request.text == "exception":
raise cls.TestException()
if request.text == "abort":
await context.abort(grpc.StatusCode.ABORTED, "Aborted!")
return gRPCTestMessage(text=request.text)
@classmethod
async def TestUnaryStream(cls, request, context): # noqa: N802
for _ in range(3):
yield gRPCTestMessage(text=request.text)
@classmethod
async def TestStreamStream(cls, request, context): # noqa: N802
async for r in request:
yield r
@classmethod
async def TestStreamUnary(cls, request, context): # noqa: N802
requests = [r async for r in request]
return requests.pop()
|
TestService
|
python
|
huggingface__transformers
|
src/transformers/models/whisper/modeling_whisper.py
|
{
"start": 30116,
"end": 40000
}
|
class ____(WhisperPreTrainedModel):
"""
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`WhisperDecoderLayer`]
Args:
config: WhisperConfig
"""
main_input_name = "input_ids"
def __init__(self, config: WhisperConfig):
super().__init__(config)
self.dropout = config.dropout
self.layerdrop = config.decoder_layerdrop
self.padding_idx = config.pad_token_id
self.max_target_positions = config.max_target_positions
self.max_source_positions = config.max_source_positions
self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
self.embed_positions = WhisperPositionalEmbedding(self.max_target_positions, config.d_model)
self.layers = nn.ModuleList(
[WhisperDecoderLayer(config, layer_idx) for layer_idx in range(config.decoder_layers)]
)
self.layer_norm = nn.LayerNorm(config.d_model)
self.gradient_checkpointing = False
# Initialize weights and apply final processing
self.post_init()
def forward(
self,
input_ids=None,
attention_mask=None,
encoder_hidden_states=None,
past_key_values=None,
inputs_embeds=None,
position_ids=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
cache_position=None,
):
r"""
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
provide it.
Indices can be obtained using [`WhisperTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
of the decoder.
past_key_values (`EncoderDecoderCache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
inputs_embeds (`torch.FloatTensor` of
shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing
`input_ids` you can choose to directly pass an embedded representation. This is useful if you want more
control over how to convert `input_ids` indices into associated vectors than the model's internal
embedding lookup matrix.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
for more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
Indices depicting the position of the input sequence tokens in the sequence. It is used to update the
cache in the correct position and to infer the complete sequence length.
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# retrieve input_ids and inputs_embeds
if input_ids is not None and inputs_embeds is not None:
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
elif input_ids is not None:
input_shape = input_ids.size()
input_ids = input_ids.view(-1, input_shape[-1])
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
else:
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
if use_cache and past_key_values is None:
past_key_values = (
EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
if encoder_hidden_states is not None or self.config.is_encoder_decoder
else DynamicCache(config=self.config)
)
past_key_values_length = 0
if cache_position is not None:
past_key_values_length = cache_position[0]
elif past_key_values is not None:
past_key_values_length = past_key_values.get_seq_length()
if cache_position is None:
cache_position = torch.arange(
past_key_values_length, past_key_values_length + input_shape[1], device=inputs_embeds.device
)
if position_ids is None:
position_ids = cache_position.unsqueeze(0).repeat(input_shape[0], 1)
# embed positions
if input_ids is not None:
positions = self.embed_positions(
input_ids, past_key_values_length=past_key_values_length, position_ids=position_ids
)
else:
positions = self.embed_positions(
inputs_embeds, past_key_values_length=past_key_values_length, position_ids=position_ids
)
hidden_states = inputs_embeds + positions.to(inputs_embeds.device)
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
causal_mask = create_causal_mask(
config=self.config,
input_embeds=inputs_embeds,
attention_mask=attention_mask,
cache_position=cache_position,
past_key_values=past_key_values,
position_ids=position_ids,
)
if self.gradient_checkpointing and self.training:
if use_cache:
logger.warning_once(
"`use_cache = True` is incompatible with gradient checkpointing. Setting `use_cache = False`..."
)
use_cache = False
# decoder layers
all_hidden_states = () if output_hidden_states else None
all_self_attns = () if output_attentions else None
all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
for idx, decoder_layer in enumerate(self.layers):
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
if output_hidden_states:
all_hidden_states += (hidden_states,)
if self.training:
dropout_probability = torch.rand([])
if dropout_probability < self.layerdrop:
continue
layer_outputs = decoder_layer(
hidden_states,
attention_mask=causal_mask,
encoder_hidden_states=encoder_hidden_states,
past_key_values=past_key_values if use_cache else None,
output_attentions=output_attentions,
use_cache=use_cache,
cache_position=cache_position,
)
hidden_states = layer_outputs[0]
if output_attentions:
all_self_attns += (layer_outputs[1],)
if encoder_hidden_states is not None:
all_cross_attentions += (layer_outputs[2],)
hidden_states = self.layer_norm(hidden_states)
# add hidden states from the last decoder layer
if output_hidden_states:
all_hidden_states += (hidden_states,)
next_cache = past_key_values if use_cache else None
if not return_dict:
return tuple(
v
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
if v is not None
)
return BaseModelOutputWithPastAndCrossAttentions(
last_hidden_state=hidden_states,
past_key_values=next_cache,
hidden_states=all_hidden_states,
attentions=all_self_attns,
cross_attentions=all_cross_attentions,
)
@auto_docstring
|
WhisperDecoder
|
python
|
apache__thrift
|
tutorial/php/runserver.py
|
{
"start": 976,
"end": 1124
}
|
class ____(CGIHTTPServer.CGIHTTPRequestHandler):
cgi_directories = ['/php']
BaseHTTPServer.HTTPServer(('', 8080), Handler).serve_forever()
|
Handler
|
python
|
Pylons__pyramid
|
src/pyramid/authorization.py
|
{
"start": 2665,
"end": 8419
}
|
class ____:
"""A helper for use with constructing a :term:`security policy` which
consults an :term:`ACL` object attached to a :term:`context` to determine
authorization information about a :term:`principal` or multiple principals.
If the context is part of a :term:`lineage`, the context's parents are
consulted for ACL information too.
"""
def permits(self, context, principals, permission):
"""Return an instance of :class:`pyramid.authorization.ACLAllowed` if
the ACL allows access a user with the given principals, return an
instance of :class:`pyramid.authorization.ACLDenied` if not.
When checking if principals are allowed, the security policy consults
the ``context`` for an ACL first. If no ACL exists on the context, or
one does exist but the ACL does not explicitly allow or deny access for
any of the effective principals, consult the context's parent ACL, and
so on, until the lineage is exhausted or we determine that the policy
permits or denies.
During this processing, if any :data:`pyramid.authorization.Deny`
ACE is found matching any principal in ``principals``, stop
processing by returning an
:class:`pyramid.authorization.ACLDenied` instance (equals
``False``) immediately. If any
:data:`pyramid.authorization.Allow` ACE is found matching any
principal, stop processing by returning an
:class:`pyramid.authorization.ACLAllowed` instance (equals
``True``) immediately. If we exhaust the context's
:term:`lineage`, and no ACE has explicitly permitted or denied
access, return an instance of
:class:`pyramid.authorization.ACLDenied` (equals ``False``).
"""
acl = '<No ACL found on any object in resource lineage>'
for location in lineage(context):
try:
acl = location.__acl__
except AttributeError:
continue
if acl and callable(acl):
acl = acl()
for ace in acl:
ace_action, ace_principal, ace_permissions = ace
if ace_principal in principals:
if not is_nonstr_iter(ace_permissions):
ace_permissions = [ace_permissions]
if permission in ace_permissions:
if ace_action == Allow:
return ACLAllowed(
ace, acl, permission, principals, location
)
else:
return ACLDenied(
ace, acl, permission, principals, location
)
# default deny (if no ACL in lineage at all, or if none of the
# principals were mentioned in any ACE we found)
return ACLDenied(
'<default deny>', acl, permission, principals, context
)
def principals_allowed_by_permission(self, context, permission):
"""Return the set of principals explicitly granted the permission
named ``permission`` according to the ACL directly attached to the
``context`` as well as inherited ACLs based on the :term:`lineage`.
When computing principals allowed by a permission, we compute the set
of principals that are explicitly granted the ``permission`` in the
provided ``context``. We do this by walking 'up' the object graph
*from the root* to the context. During this walking process, if we
find an explicit :data:`pyramid.authorization.Allow` ACE for a
principal that matches the ``permission``, the principal is included in
the allow list. However, if later in the walking process that
principal is mentioned in any :data:`pyramid.authorization.Deny` ACE
for the permission, the principal is removed from the allow list. If
a :data:`pyramid.authorization.Deny` to the principal
:data:`pyramid.authorization.Everyone` is encountered during the
walking process that matches the ``permission``, the allow list is
cleared for all principals encountered in previous ACLs. The walking
process ends after we've processed the any ACL directly attached to
``context``; a set of principals is returned.
"""
allowed = set()
for location in reversed(list(lineage(context))):
# NB: we're walking *up* the object graph from the root
try:
acl = location.__acl__
except AttributeError:
continue
allowed_here = set()
denied_here = set()
if acl and callable(acl):
acl = acl()
for ace_action, ace_principal, ace_permissions in acl:
if not is_nonstr_iter(ace_permissions):
ace_permissions = [ace_permissions]
if (ace_action == Allow) and (permission in ace_permissions):
if ace_principal not in denied_here:
allowed_here.add(ace_principal)
if (ace_action == Deny) and (permission in ace_permissions):
denied_here.add(ace_principal)
if ace_principal == Everyone:
# clear the entire allowed set, as we've hit a
# deny of Everyone ala (Deny, Everyone, ALL)
allowed = set()
break
elif ace_principal in allowed:
allowed.remove(ace_principal)
allowed.update(allowed_here)
return allowed
|
ACLHelper
|
python
|
PrefectHQ__prefect
|
src/prefect/cli/transfer/_migratable_resources/work_pools.py
|
{
"start": 709,
"end": 5691
}
|
class ____(MigratableResource[WorkPool]):
_instances: dict[uuid.UUID, Self] = {}
def __init__(self, work_pool: WorkPool, default_queue: WorkQueue):
self.source_work_pool = work_pool
self.source_default_queue = default_queue
self.destination_work_pool: WorkPool | None = None
self._dependencies: list[MigratableProtocol] = []
@property
def source_id(self) -> uuid.UUID:
return self.source_work_pool.id
@property
def destination_id(self) -> uuid.UUID | None:
return self.destination_work_pool.id if self.destination_work_pool else None
@classmethod
async def construct(cls, obj: WorkPool) -> Self:
if obj.id in cls._instances:
return cls._instances[obj.id]
async with get_client() as client:
default_queue = await client.read_work_queue(obj.default_queue_id)
instance = cls(obj, default_queue)
cls._instances[obj.id] = instance
return instance
@classmethod
async def get_instance(cls, id: uuid.UUID) -> "MigratableResource[WorkPool] | None":
if id in cls._instances:
return cls._instances[id]
return None
@classmethod
async def get_instance_by_name(
cls, name: str
) -> "MigratableResource[WorkPool] | None":
for instance in cls._instances.values():
if instance.source_work_pool.name == name:
return instance
return None
async def get_dependencies(self) -> "list[MigratableProtocol]":
if self._dependencies:
return self._dependencies
async with get_client() as client:
if (
self.source_work_pool.storage_configuration.default_result_storage_block_id
is not None
):
if dependency := await MigratableBlockDocument.get_instance(
id=self.source_work_pool.storage_configuration.default_result_storage_block_id
):
self._dependencies.append(dependency)
else:
result_storage_block = await client.read_block_document(
self.source_work_pool.storage_configuration.default_result_storage_block_id
)
self._dependencies.append(
await construct_migratable_resource(result_storage_block)
)
if (
self.source_work_pool.storage_configuration.bundle_upload_step
is not None
):
# TODO: Figure out how to find block document references in bundle upload step
pass
if (
self.source_work_pool.storage_configuration.bundle_execution_step
is not None
):
# TODO: Figure out how to find block document references in bundle download step
pass
return self._dependencies
async def migrate(self) -> None:
async with get_client() as client:
# Skip managed pools always - they're cloud-specific infrastructure
if self.source_work_pool.is_managed_pool:
raise TransferSkipped("Skipped managed pool (cloud-specific)")
# Allow push pools only if destination is Cloud
if self.source_work_pool.is_push_pool:
from prefect.client.base import ServerType
if client.server_type != ServerType.CLOUD:
raise TransferSkipped("Skipped push pool (requires Prefect Cloud)")
try:
self.destination_work_pool = await client.create_work_pool(
work_pool=WorkPoolCreate(
name=self.source_work_pool.name,
type=self.source_work_pool.type,
base_job_template=self.source_work_pool.base_job_template,
is_paused=self.source_work_pool.is_paused,
concurrency_limit=self.source_work_pool.concurrency_limit,
storage_configuration=self.source_work_pool.storage_configuration,
),
)
except ObjectUnsupported:
raise TransferSkipped("Destination requires Standard/Pro tier")
except ObjectAlreadyExists:
self.destination_work_pool = await client.read_work_pool(
self.source_work_pool.name
)
raise TransferSkipped("Already exists")
# Update the default queue after successful creation
await client.update_work_queue(
id=self.destination_work_pool.default_queue_id,
description=self.source_default_queue.description,
priority=self.source_default_queue.priority,
concurrency_limit=self.source_default_queue.concurrency_limit,
)
|
MigratableWorkPool
|
python
|
mozilla__bleach
|
bleach/_vendor/html5lib/html5parser.py
|
{
"start": 2675,
"end": 117091
}
|
class ____(object):
"""HTML parser
Generates a tree structure from a stream of (possibly malformed) HTML.
"""
def __init__(self, tree=None, strict=False, namespaceHTMLElements=True, debug=False):
"""
:arg tree: a treebuilder class controlling the type of tree that will be
returned. Built in treebuilders can be accessed through
html5lib.treebuilders.getTreeBuilder(treeType)
:arg strict: raise an exception when a parse error is encountered
:arg namespaceHTMLElements: whether or not to namespace HTML elements
:arg debug: whether or not to enable debug mode which logs things
Example:
>>> from html5lib.html5parser import HTMLParser
>>> parser = HTMLParser() # generates parser with etree builder
>>> parser = HTMLParser('lxml', strict=True) # generates parser with lxml builder which is strict
"""
# Raise an exception on the first error encountered
self.strict = strict
if tree is None:
tree = treebuilders.getTreeBuilder("etree")
self.tree = tree(namespaceHTMLElements)
self.errors = []
self.phases = {name: cls(self, self.tree) for name, cls in
getPhases(debug).items()}
def _parse(self, stream, innerHTML=False, container="div", scripting=False, **kwargs):
self.innerHTMLMode = innerHTML
self.container = container
self.scripting = scripting
self.tokenizer = _tokenizer.HTMLTokenizer(stream, parser=self, **kwargs)
self.reset()
try:
self.mainLoop()
except _ReparseException:
self.reset()
self.mainLoop()
def reset(self):
self.tree.reset()
self.firstStartTag = False
self.errors = []
self.log = [] # only used with debug mode
# "quirks" / "limited quirks" / "no quirks"
self.compatMode = "no quirks"
if self.innerHTMLMode:
self.innerHTML = self.container.lower()
if self.innerHTML in cdataElements:
self.tokenizer.state = self.tokenizer.rcdataState
elif self.innerHTML in rcdataElements:
self.tokenizer.state = self.tokenizer.rawtextState
elif self.innerHTML == 'plaintext':
self.tokenizer.state = self.tokenizer.plaintextState
else:
# state already is data state
# self.tokenizer.state = self.tokenizer.dataState
pass
self.phase = self.phases["beforeHtml"]
self.phase.insertHtmlElement()
self.resetInsertionMode()
else:
self.innerHTML = False # pylint:disable=redefined-variable-type
self.phase = self.phases["initial"]
self.lastPhase = None
self.beforeRCDataPhase = None
self.framesetOK = True
@property
def documentEncoding(self):
"""Name of the character encoding that was used to decode the input stream, or
:obj:`None` if that is not determined yet
"""
if not hasattr(self, 'tokenizer'):
return None
return self.tokenizer.stream.charEncoding[0].name
def isHTMLIntegrationPoint(self, element):
if (element.name == "annotation-xml" and
element.namespace == namespaces["mathml"]):
return ("encoding" in element.attributes and
element.attributes["encoding"].translate(
asciiUpper2Lower) in
("text/html", "application/xhtml+xml"))
else:
return (element.namespace, element.name) in htmlIntegrationPointElements
def isMathMLTextIntegrationPoint(self, element):
return (element.namespace, element.name) in mathmlTextIntegrationPointElements
def mainLoop(self):
CharactersToken = tokenTypes["Characters"]
SpaceCharactersToken = tokenTypes["SpaceCharacters"]
StartTagToken = tokenTypes["StartTag"]
EndTagToken = tokenTypes["EndTag"]
CommentToken = tokenTypes["Comment"]
DoctypeToken = tokenTypes["Doctype"]
ParseErrorToken = tokenTypes["ParseError"]
for token in self.tokenizer:
prev_token = None
new_token = token
while new_token is not None:
prev_token = new_token
currentNode = self.tree.openElements[-1] if self.tree.openElements else None
currentNodeNamespace = currentNode.namespace if currentNode else None
currentNodeName = currentNode.name if currentNode else None
type = new_token["type"]
if type == ParseErrorToken:
self.parseError(new_token["data"], new_token.get("datavars", {}))
new_token = None
else:
if (len(self.tree.openElements) == 0 or
currentNodeNamespace == self.tree.defaultNamespace or
(self.isMathMLTextIntegrationPoint(currentNode) and
((type == StartTagToken and
token["name"] not in frozenset(["mglyph", "malignmark"])) or
type in (CharactersToken, SpaceCharactersToken))) or
(currentNodeNamespace == namespaces["mathml"] and
currentNodeName == "annotation-xml" and
type == StartTagToken and
token["name"] == "svg") or
(self.isHTMLIntegrationPoint(currentNode) and
type in (StartTagToken, CharactersToken, SpaceCharactersToken))):
phase = self.phase
else:
phase = self.phases["inForeignContent"]
if type == CharactersToken:
new_token = phase.processCharacters(new_token)
elif type == SpaceCharactersToken:
new_token = phase.processSpaceCharacters(new_token)
elif type == StartTagToken:
new_token = phase.processStartTag(new_token)
elif type == EndTagToken:
new_token = phase.processEndTag(new_token)
elif type == CommentToken:
new_token = phase.processComment(new_token)
elif type == DoctypeToken:
new_token = phase.processDoctype(new_token)
if (type == StartTagToken and prev_token["selfClosing"] and
not prev_token["selfClosingAcknowledged"]):
self.parseError("non-void-element-with-trailing-solidus",
{"name": prev_token["name"]})
# When the loop finishes it's EOF
reprocess = True
phases = []
while reprocess:
phases.append(self.phase)
reprocess = self.phase.processEOF()
if reprocess:
assert self.phase not in phases
def parse(self, stream, *args, **kwargs):
"""Parse a HTML document into a well-formed tree
:arg stream: a file-like object or string containing the HTML to be parsed
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless of any BOM or later declaration (such as in a meta
element).
:arg scripting: treat noscript elements as if JavaScript was turned on
:returns: parsed tree
Example:
>>> from html5lib.html5parser import HTMLParser
>>> parser = HTMLParser()
>>> parser.parse('<html><body><p>This is a doc</p></body></html>')
<Element u'{http://www.w3.org/1999/xhtml}html' at 0x7feac4909db0>
"""
self._parse(stream, False, None, *args, **kwargs)
return self.tree.getDocument()
def parseFragment(self, stream, *args, **kwargs):
"""Parse a HTML fragment into a well-formed tree fragment
:arg container: name of the element we're setting the innerHTML
property if set to None, default to 'div'
:arg stream: a file-like object or string containing the HTML to be parsed
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless of any BOM or later declaration (such as in a meta
element)
:arg scripting: treat noscript elements as if JavaScript was turned on
:returns: parsed tree
Example:
>>> from html5lib.html5libparser import HTMLParser
>>> parser = HTMLParser()
>>> parser.parseFragment('<b>this is a fragment</b>')
<Element u'DOCUMENT_FRAGMENT' at 0x7feac484b090>
"""
self._parse(stream, True, *args, **kwargs)
return self.tree.getFragment()
def parseError(self, errorcode="XXX-undefined-error", datavars=None):
# XXX The idea is to make errorcode mandatory.
if datavars is None:
datavars = {}
self.errors.append((self.tokenizer.stream.position(), errorcode, datavars))
if self.strict:
raise ParseError(E[errorcode] % datavars)
def adjustMathMLAttributes(self, token):
adjust_attributes(token, adjustMathMLAttributes)
def adjustSVGAttributes(self, token):
adjust_attributes(token, adjustSVGAttributes)
def adjustForeignAttributes(self, token):
adjust_attributes(token, adjustForeignAttributesMap)
def reparseTokenNormal(self, token):
# pylint:disable=unused-argument
self.parser.phase()
def resetInsertionMode(self):
# The name of this method is mostly historical. (It's also used in the
# specification.)
last = False
newModes = {
"select": "inSelect",
"td": "inCell",
"th": "inCell",
"tr": "inRow",
"tbody": "inTableBody",
"thead": "inTableBody",
"tfoot": "inTableBody",
"caption": "inCaption",
"colgroup": "inColumnGroup",
"table": "inTable",
"head": "inBody",
"body": "inBody",
"frameset": "inFrameset",
"html": "beforeHead"
}
for node in self.tree.openElements[::-1]:
nodeName = node.name
new_phase = None
if node == self.tree.openElements[0]:
assert self.innerHTML
last = True
nodeName = self.innerHTML
# Check for conditions that should only happen in the innerHTML
# case
if nodeName in ("select", "colgroup", "head", "html"):
assert self.innerHTML
if not last and node.namespace != self.tree.defaultNamespace:
continue
if nodeName in newModes:
new_phase = self.phases[newModes[nodeName]]
break
elif last:
new_phase = self.phases["inBody"]
break
self.phase = new_phase
def parseRCDataRawtext(self, token, contentType):
# Generic RCDATA/RAWTEXT Parsing algorithm
assert contentType in ("RAWTEXT", "RCDATA")
self.tree.insertElement(token)
if contentType == "RAWTEXT":
self.tokenizer.state = self.tokenizer.rawtextState
else:
self.tokenizer.state = self.tokenizer.rcdataState
self.originalPhase = self.phase
self.phase = self.phases["text"]
@_utils.memoize
def getPhases(debug):
def log(function):
"""Logger that records which phase processes each token"""
type_names = {value: key for key, value in tokenTypes.items()}
def wrapped(self, *args, **kwargs):
if function.__name__.startswith("process") and len(args) > 0:
token = args[0]
info = {"type": type_names[token['type']]}
if token['type'] in tagTokenTypes:
info["name"] = token['name']
self.parser.log.append((self.parser.tokenizer.state.__name__,
self.parser.phase.__class__.__name__,
self.__class__.__name__,
function.__name__,
info))
return function(self, *args, **kwargs)
else:
return function(self, *args, **kwargs)
return wrapped
def getMetaclass(use_metaclass, metaclass_func):
if use_metaclass:
return method_decorator_metaclass(metaclass_func)
else:
return type
# pylint:disable=unused-argument
class Phase(metaclass=getMetaclass(debug, log)):
"""Base class for helper object that implements each phase of processing
"""
__slots__ = ("parser", "tree", "__startTagCache", "__endTagCache")
def __init__(self, parser, tree):
self.parser = parser
self.tree = tree
self.__startTagCache = {}
self.__endTagCache = {}
def processEOF(self):
raise NotImplementedError
def processComment(self, token):
# For most phases the following is correct. Where it's not it will be
# overridden.
self.tree.insertComment(token, self.tree.openElements[-1])
def processDoctype(self, token):
self.parser.parseError("unexpected-doctype")
def processCharacters(self, token):
self.tree.insertText(token["data"])
def processSpaceCharacters(self, token):
self.tree.insertText(token["data"])
def processStartTag(self, token):
# Note the caching is done here rather than BoundMethodDispatcher as doing it there
# requires a circular reference to the Phase, and this ends up with a significant
# (CPython 2.7, 3.8) GC cost when parsing many short inputs
name = token["name"]
# In Py2, using `in` is quicker in general than try/except KeyError
# In Py3, `in` is quicker when there are few cache hits (typically short inputs)
if name in self.__startTagCache:
func = self.__startTagCache[name]
else:
func = self.__startTagCache[name] = self.startTagHandler[name]
# bound the cache size in case we get loads of unknown tags
while len(self.__startTagCache) > len(self.startTagHandler) * 1.1:
# this makes the eviction policy random on Py < 3.7 and FIFO >= 3.7
self.__startTagCache.pop(next(iter(self.__startTagCache)))
return func(token)
def startTagHtml(self, token):
if not self.parser.firstStartTag and token["name"] == "html":
self.parser.parseError("non-html-root")
# XXX Need a check here to see if the first start tag token emitted is
# this token... If it's not, invoke self.parser.parseError().
for attr, value in token["data"].items():
if attr not in self.tree.openElements[0].attributes:
self.tree.openElements[0].attributes[attr] = value
self.parser.firstStartTag = False
def processEndTag(self, token):
# Note the caching is done here rather than BoundMethodDispatcher as doing it there
# requires a circular reference to the Phase, and this ends up with a significant
# (CPython 2.7, 3.8) GC cost when parsing many short inputs
name = token["name"]
# In Py2, using `in` is quicker in general than try/except KeyError
# In Py3, `in` is quicker when there are few cache hits (typically short inputs)
if name in self.__endTagCache:
func = self.__endTagCache[name]
else:
func = self.__endTagCache[name] = self.endTagHandler[name]
# bound the cache size in case we get loads of unknown tags
while len(self.__endTagCache) > len(self.endTagHandler) * 1.1:
# this makes the eviction policy random on Py < 3.7 and FIFO >= 3.7
self.__endTagCache.pop(next(iter(self.__endTagCache)))
return func(token)
class InitialPhase(Phase):
__slots__ = tuple()
def processSpaceCharacters(self, token):
pass
def processComment(self, token):
self.tree.insertComment(token, self.tree.document)
def processDoctype(self, token):
name = token["name"]
publicId = token["publicId"]
systemId = token["systemId"]
correct = token["correct"]
if (name != "html" or publicId is not None or
systemId is not None and systemId != "about:legacy-compat"):
self.parser.parseError("unknown-doctype")
if publicId is None:
publicId = ""
self.tree.insertDoctype(token)
if publicId != "":
publicId = publicId.translate(asciiUpper2Lower)
if (not correct or token["name"] != "html" or
publicId.startswith(
("+//silmaril//dtd html pro v0r11 19970101//",
"-//advasoft ltd//dtd html 3.0 aswedit + extensions//",
"-//as//dtd html 3.0 aswedit + extensions//",
"-//ietf//dtd html 2.0 level 1//",
"-//ietf//dtd html 2.0 level 2//",
"-//ietf//dtd html 2.0 strict level 1//",
"-//ietf//dtd html 2.0 strict level 2//",
"-//ietf//dtd html 2.0 strict//",
"-//ietf//dtd html 2.0//",
"-//ietf//dtd html 2.1e//",
"-//ietf//dtd html 3.0//",
"-//ietf//dtd html 3.2 final//",
"-//ietf//dtd html 3.2//",
"-//ietf//dtd html 3//",
"-//ietf//dtd html level 0//",
"-//ietf//dtd html level 1//",
"-//ietf//dtd html level 2//",
"-//ietf//dtd html level 3//",
"-//ietf//dtd html strict level 0//",
"-//ietf//dtd html strict level 1//",
"-//ietf//dtd html strict level 2//",
"-//ietf//dtd html strict level 3//",
"-//ietf//dtd html strict//",
"-//ietf//dtd html//",
"-//metrius//dtd metrius presentational//",
"-//microsoft//dtd internet explorer 2.0 html strict//",
"-//microsoft//dtd internet explorer 2.0 html//",
"-//microsoft//dtd internet explorer 2.0 tables//",
"-//microsoft//dtd internet explorer 3.0 html strict//",
"-//microsoft//dtd internet explorer 3.0 html//",
"-//microsoft//dtd internet explorer 3.0 tables//",
"-//netscape comm. corp.//dtd html//",
"-//netscape comm. corp.//dtd strict html//",
"-//o'reilly and associates//dtd html 2.0//",
"-//o'reilly and associates//dtd html extended 1.0//",
"-//o'reilly and associates//dtd html extended relaxed 1.0//",
"-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//",
"-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//",
"-//spyglass//dtd html 2.0 extended//",
"-//sq//dtd html 2.0 hotmetal + extensions//",
"-//sun microsystems corp.//dtd hotjava html//",
"-//sun microsystems corp.//dtd hotjava strict html//",
"-//w3c//dtd html 3 1995-03-24//",
"-//w3c//dtd html 3.2 draft//",
"-//w3c//dtd html 3.2 final//",
"-//w3c//dtd html 3.2//",
"-//w3c//dtd html 3.2s draft//",
"-//w3c//dtd html 4.0 frameset//",
"-//w3c//dtd html 4.0 transitional//",
"-//w3c//dtd html experimental 19960712//",
"-//w3c//dtd html experimental 970421//",
"-//w3c//dtd w3 html//",
"-//w3o//dtd w3 html 3.0//",
"-//webtechs//dtd mozilla html 2.0//",
"-//webtechs//dtd mozilla html//")) or
publicId in ("-//w3o//dtd w3 html strict 3.0//en//",
"-/w3c/dtd html 4.0 transitional/en",
"html") or
publicId.startswith(
("-//w3c//dtd html 4.01 frameset//",
"-//w3c//dtd html 4.01 transitional//")) and
systemId is None or
systemId and systemId.lower() == "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd"):
self.parser.compatMode = "quirks"
elif (publicId.startswith(
("-//w3c//dtd xhtml 1.0 frameset//",
"-//w3c//dtd xhtml 1.0 transitional//")) or
publicId.startswith(
("-//w3c//dtd html 4.01 frameset//",
"-//w3c//dtd html 4.01 transitional//")) and
systemId is not None):
self.parser.compatMode = "limited quirks"
self.parser.phase = self.parser.phases["beforeHtml"]
def anythingElse(self):
self.parser.compatMode = "quirks"
self.parser.phase = self.parser.phases["beforeHtml"]
def processCharacters(self, token):
self.parser.parseError("expected-doctype-but-got-chars")
self.anythingElse()
return token
def processStartTag(self, token):
self.parser.parseError("expected-doctype-but-got-start-tag",
{"name": token["name"]})
self.anythingElse()
return token
def processEndTag(self, token):
self.parser.parseError("expected-doctype-but-got-end-tag",
{"name": token["name"]})
self.anythingElse()
return token
def processEOF(self):
self.parser.parseError("expected-doctype-but-got-eof")
self.anythingElse()
return True
class BeforeHtmlPhase(Phase):
__slots__ = tuple()
# helper methods
def insertHtmlElement(self):
self.tree.insertRoot(impliedTagToken("html", "StartTag"))
self.parser.phase = self.parser.phases["beforeHead"]
# other
def processEOF(self):
self.insertHtmlElement()
return True
def processComment(self, token):
self.tree.insertComment(token, self.tree.document)
def processSpaceCharacters(self, token):
pass
def processCharacters(self, token):
self.insertHtmlElement()
return token
def processStartTag(self, token):
if token["name"] == "html":
self.parser.firstStartTag = True
self.insertHtmlElement()
return token
def processEndTag(self, token):
if token["name"] not in ("head", "body", "html", "br"):
self.parser.parseError("unexpected-end-tag-before-html",
{"name": token["name"]})
else:
self.insertHtmlElement()
return token
class BeforeHeadPhase(Phase):
__slots__ = tuple()
def processEOF(self):
self.startTagHead(impliedTagToken("head", "StartTag"))
return True
def processSpaceCharacters(self, token):
pass
def processCharacters(self, token):
self.startTagHead(impliedTagToken("head", "StartTag"))
return token
def startTagHtml(self, token):
return self.parser.phases["inBody"].processStartTag(token)
def startTagHead(self, token):
self.tree.insertElement(token)
self.tree.headPointer = self.tree.openElements[-1]
self.parser.phase = self.parser.phases["inHead"]
def startTagOther(self, token):
self.startTagHead(impliedTagToken("head", "StartTag"))
return token
def endTagImplyHead(self, token):
self.startTagHead(impliedTagToken("head", "StartTag"))
return token
def endTagOther(self, token):
self.parser.parseError("end-tag-after-implied-root",
{"name": token["name"]})
startTagHandler = _utils.MethodDispatcher([
("html", startTagHtml),
("head", startTagHead)
])
startTagHandler.default = startTagOther
endTagHandler = _utils.MethodDispatcher([
(("head", "body", "html", "br"), endTagImplyHead)
])
endTagHandler.default = endTagOther
class InHeadPhase(Phase):
__slots__ = tuple()
# the real thing
def processEOF(self):
self.anythingElse()
return True
def processCharacters(self, token):
self.anythingElse()
return token
def startTagHtml(self, token):
return self.parser.phases["inBody"].processStartTag(token)
def startTagHead(self, token):
self.parser.parseError("two-heads-are-not-better-than-one")
def startTagBaseLinkCommand(self, token):
self.tree.insertElement(token)
self.tree.openElements.pop()
token["selfClosingAcknowledged"] = True
def startTagMeta(self, token):
self.tree.insertElement(token)
self.tree.openElements.pop()
token["selfClosingAcknowledged"] = True
attributes = token["data"]
if self.parser.tokenizer.stream.charEncoding[1] == "tentative":
if "charset" in attributes:
self.parser.tokenizer.stream.changeEncoding(attributes["charset"])
elif ("content" in attributes and
"http-equiv" in attributes and
attributes["http-equiv"].lower() == "content-type"):
# Encoding it as UTF-8 here is a hack, as really we should pass
# the abstract Unicode string, and just use the
# ContentAttrParser on that, but using UTF-8 allows all chars
# to be encoded and as a ASCII-superset works.
data = _inputstream.EncodingBytes(attributes["content"].encode("utf-8"))
parser = _inputstream.ContentAttrParser(data)
codec = parser.parse()
self.parser.tokenizer.stream.changeEncoding(codec)
def startTagTitle(self, token):
self.parser.parseRCDataRawtext(token, "RCDATA")
def startTagNoFramesStyle(self, token):
# Need to decide whether to implement the scripting-disabled case
self.parser.parseRCDataRawtext(token, "RAWTEXT")
def startTagNoscript(self, token):
if self.parser.scripting:
self.parser.parseRCDataRawtext(token, "RAWTEXT")
else:
self.tree.insertElement(token)
self.parser.phase = self.parser.phases["inHeadNoscript"]
def startTagScript(self, token):
self.tree.insertElement(token)
self.parser.tokenizer.state = self.parser.tokenizer.scriptDataState
self.parser.originalPhase = self.parser.phase
self.parser.phase = self.parser.phases["text"]
def startTagOther(self, token):
self.anythingElse()
return token
def endTagHead(self, token):
node = self.parser.tree.openElements.pop()
assert node.name == "head", "Expected head got %s" % node.name
self.parser.phase = self.parser.phases["afterHead"]
def endTagHtmlBodyBr(self, token):
self.anythingElse()
return token
def endTagOther(self, token):
self.parser.parseError("unexpected-end-tag", {"name": token["name"]})
def anythingElse(self):
self.endTagHead(impliedTagToken("head"))
startTagHandler = _utils.MethodDispatcher([
("html", startTagHtml),
("title", startTagTitle),
(("noframes", "style"), startTagNoFramesStyle),
("noscript", startTagNoscript),
("script", startTagScript),
(("base", "basefont", "bgsound", "command", "link"),
startTagBaseLinkCommand),
("meta", startTagMeta),
("head", startTagHead)
])
startTagHandler.default = startTagOther
endTagHandler = _utils.MethodDispatcher([
("head", endTagHead),
(("br", "html", "body"), endTagHtmlBodyBr)
])
endTagHandler.default = endTagOther
class InHeadNoscriptPhase(Phase):
__slots__ = tuple()
def processEOF(self):
self.parser.parseError("eof-in-head-noscript")
self.anythingElse()
return True
def processComment(self, token):
return self.parser.phases["inHead"].processComment(token)
def processCharacters(self, token):
self.parser.parseError("char-in-head-noscript")
self.anythingElse()
return token
def processSpaceCharacters(self, token):
return self.parser.phases["inHead"].processSpaceCharacters(token)
def startTagHtml(self, token):
return self.parser.phases["inBody"].processStartTag(token)
def startTagBaseLinkCommand(self, token):
return self.parser.phases["inHead"].processStartTag(token)
def startTagHeadNoscript(self, token):
self.parser.parseError("unexpected-start-tag", {"name": token["name"]})
def startTagOther(self, token):
self.parser.parseError("unexpected-inhead-noscript-tag", {"name": token["name"]})
self.anythingElse()
return token
def endTagNoscript(self, token):
node = self.parser.tree.openElements.pop()
assert node.name == "noscript", "Expected noscript got %s" % node.name
self.parser.phase = self.parser.phases["inHead"]
def endTagBr(self, token):
self.parser.parseError("unexpected-inhead-noscript-tag", {"name": token["name"]})
self.anythingElse()
return token
def endTagOther(self, token):
self.parser.parseError("unexpected-end-tag", {"name": token["name"]})
def anythingElse(self):
# Caller must raise parse error first!
self.endTagNoscript(impliedTagToken("noscript"))
startTagHandler = _utils.MethodDispatcher([
("html", startTagHtml),
(("basefont", "bgsound", "link", "meta", "noframes", "style"), startTagBaseLinkCommand),
(("head", "noscript"), startTagHeadNoscript),
])
startTagHandler.default = startTagOther
endTagHandler = _utils.MethodDispatcher([
("noscript", endTagNoscript),
("br", endTagBr),
])
endTagHandler.default = endTagOther
class AfterHeadPhase(Phase):
__slots__ = tuple()
def processEOF(self):
self.anythingElse()
return True
def processCharacters(self, token):
self.anythingElse()
return token
def startTagHtml(self, token):
return self.parser.phases["inBody"].processStartTag(token)
def startTagBody(self, token):
self.parser.framesetOK = False
self.tree.insertElement(token)
self.parser.phase = self.parser.phases["inBody"]
def startTagFrameset(self, token):
self.tree.insertElement(token)
self.parser.phase = self.parser.phases["inFrameset"]
def startTagFromHead(self, token):
self.parser.parseError("unexpected-start-tag-out-of-my-head",
{"name": token["name"]})
self.tree.openElements.append(self.tree.headPointer)
self.parser.phases["inHead"].processStartTag(token)
for node in self.tree.openElements[::-1]:
if node.name == "head":
self.tree.openElements.remove(node)
break
def startTagHead(self, token):
self.parser.parseError("unexpected-start-tag", {"name": token["name"]})
def startTagOther(self, token):
self.anythingElse()
return token
def endTagHtmlBodyBr(self, token):
self.anythingElse()
return token
def endTagOther(self, token):
self.parser.parseError("unexpected-end-tag", {"name": token["name"]})
def anythingElse(self):
self.tree.insertElement(impliedTagToken("body", "StartTag"))
self.parser.phase = self.parser.phases["inBody"]
self.parser.framesetOK = True
startTagHandler = _utils.MethodDispatcher([
("html", startTagHtml),
("body", startTagBody),
("frameset", startTagFrameset),
(("base", "basefont", "bgsound", "link", "meta", "noframes", "script",
"style", "title"),
startTagFromHead),
("head", startTagHead)
])
startTagHandler.default = startTagOther
endTagHandler = _utils.MethodDispatcher([(("body", "html", "br"),
endTagHtmlBodyBr)])
endTagHandler.default = endTagOther
class InBodyPhase(Phase):
# http://www.whatwg.org/specs/web-apps/current-work/#parsing-main-inbody
# the really-really-really-very crazy mode
__slots__ = ("processSpaceCharacters",)
def __init__(self, *args, **kwargs):
super(InBodyPhase, self).__init__(*args, **kwargs)
# Set this to the default handler
self.processSpaceCharacters = self.processSpaceCharactersNonPre
def isMatchingFormattingElement(self, node1, node2):
return (node1.name == node2.name and
node1.namespace == node2.namespace and
node1.attributes == node2.attributes)
# helper
def addFormattingElement(self, token):
self.tree.insertElement(token)
element = self.tree.openElements[-1]
matchingElements = []
for node in self.tree.activeFormattingElements[::-1]:
if node is Marker:
break
elif self.isMatchingFormattingElement(node, element):
matchingElements.append(node)
assert len(matchingElements) <= 3
if len(matchingElements) == 3:
self.tree.activeFormattingElements.remove(matchingElements[-1])
self.tree.activeFormattingElements.append(element)
# the real deal
def processEOF(self):
allowed_elements = frozenset(("dd", "dt", "li", "p", "tbody", "td",
"tfoot", "th", "thead", "tr", "body",
"html"))
for node in self.tree.openElements[::-1]:
if node.name not in allowed_elements:
self.parser.parseError("expected-closing-tag-but-got-eof")
break
# Stop parsing
def processSpaceCharactersDropNewline(self, token):
# Sometimes (start of <pre>, <listing>, and <textarea> blocks) we
# want to drop leading newlines
data = token["data"]
self.processSpaceCharacters = self.processSpaceCharactersNonPre
if (data.startswith("\n") and
self.tree.openElements[-1].name in ("pre", "listing", "textarea") and
not self.tree.openElements[-1].hasContent()):
data = data[1:]
if data:
self.tree.reconstructActiveFormattingElements()
self.tree.insertText(data)
def processCharacters(self, token):
if token["data"] == "\u0000":
# The tokenizer should always emit null on its own
return
self.tree.reconstructActiveFormattingElements()
self.tree.insertText(token["data"])
# This must be bad for performance
if (self.parser.framesetOK and
any([char not in spaceCharacters
for char in token["data"]])):
self.parser.framesetOK = False
def processSpaceCharactersNonPre(self, token):
self.tree.reconstructActiveFormattingElements()
self.tree.insertText(token["data"])
def startTagProcessInHead(self, token):
return self.parser.phases["inHead"].processStartTag(token)
def startTagBody(self, token):
self.parser.parseError("unexpected-start-tag", {"name": "body"})
if (len(self.tree.openElements) == 1 or
self.tree.openElements[1].name != "body"):
assert self.parser.innerHTML
else:
self.parser.framesetOK = False
for attr, value in token["data"].items():
if attr not in self.tree.openElements[1].attributes:
self.tree.openElements[1].attributes[attr] = value
def startTagFrameset(self, token):
self.parser.parseError("unexpected-start-tag", {"name": "frameset"})
if (len(self.tree.openElements) == 1 or self.tree.openElements[1].name != "body"):
assert self.parser.innerHTML
elif not self.parser.framesetOK:
pass
else:
if self.tree.openElements[1].parent:
self.tree.openElements[1].parent.removeChild(self.tree.openElements[1])
while self.tree.openElements[-1].name != "html":
self.tree.openElements.pop()
self.tree.insertElement(token)
self.parser.phase = self.parser.phases["inFrameset"]
def startTagCloseP(self, token):
if self.tree.elementInScope("p", variant="button"):
self.endTagP(impliedTagToken("p"))
self.tree.insertElement(token)
def startTagPreListing(self, token):
if self.tree.elementInScope("p", variant="button"):
self.endTagP(impliedTagToken("p"))
self.tree.insertElement(token)
self.parser.framesetOK = False
self.processSpaceCharacters = self.processSpaceCharactersDropNewline
def startTagForm(self, token):
if self.tree.formPointer:
self.parser.parseError("unexpected-start-tag", {"name": "form"})
else:
if self.tree.elementInScope("p", variant="button"):
self.endTagP(impliedTagToken("p"))
self.tree.insertElement(token)
self.tree.formPointer = self.tree.openElements[-1]
def startTagListItem(self, token):
self.parser.framesetOK = False
stopNamesMap = {"li": ["li"],
"dt": ["dt", "dd"],
"dd": ["dt", "dd"]}
stopNames = stopNamesMap[token["name"]]
for node in reversed(self.tree.openElements):
if node.name in stopNames:
self.parser.phase.processEndTag(
impliedTagToken(node.name, "EndTag"))
break
if (node.nameTuple in specialElements and
node.name not in ("address", "div", "p")):
break
if self.tree.elementInScope("p", variant="button"):
self.parser.phase.processEndTag(
impliedTagToken("p", "EndTag"))
self.tree.insertElement(token)
def startTagPlaintext(self, token):
if self.tree.elementInScope("p", variant="button"):
self.endTagP(impliedTagToken("p"))
self.tree.insertElement(token)
self.parser.tokenizer.state = self.parser.tokenizer.plaintextState
def startTagHeading(self, token):
if self.tree.elementInScope("p", variant="button"):
self.endTagP(impliedTagToken("p"))
if self.tree.openElements[-1].name in headingElements:
self.parser.parseError("unexpected-start-tag", {"name": token["name"]})
self.tree.openElements.pop()
self.tree.insertElement(token)
def startTagA(self, token):
afeAElement = self.tree.elementInActiveFormattingElements("a")
if afeAElement:
self.parser.parseError("unexpected-start-tag-implies-end-tag",
{"startName": "a", "endName": "a"})
self.endTagFormatting(impliedTagToken("a"))
if afeAElement in self.tree.openElements:
self.tree.openElements.remove(afeAElement)
if afeAElement in self.tree.activeFormattingElements:
self.tree.activeFormattingElements.remove(afeAElement)
self.tree.reconstructActiveFormattingElements()
self.addFormattingElement(token)
def startTagFormatting(self, token):
self.tree.reconstructActiveFormattingElements()
self.addFormattingElement(token)
def startTagNobr(self, token):
self.tree.reconstructActiveFormattingElements()
if self.tree.elementInScope("nobr"):
self.parser.parseError("unexpected-start-tag-implies-end-tag",
{"startName": "nobr", "endName": "nobr"})
self.processEndTag(impliedTagToken("nobr"))
# XXX Need tests that trigger the following
self.tree.reconstructActiveFormattingElements()
self.addFormattingElement(token)
def startTagButton(self, token):
if self.tree.elementInScope("button"):
self.parser.parseError("unexpected-start-tag-implies-end-tag",
{"startName": "button", "endName": "button"})
self.processEndTag(impliedTagToken("button"))
return token
else:
self.tree.reconstructActiveFormattingElements()
self.tree.insertElement(token)
self.parser.framesetOK = False
def startTagAppletMarqueeObject(self, token):
self.tree.reconstructActiveFormattingElements()
self.tree.insertElement(token)
self.tree.activeFormattingElements.append(Marker)
self.parser.framesetOK = False
def startTagXmp(self, token):
if self.tree.elementInScope("p", variant="button"):
self.endTagP(impliedTagToken("p"))
self.tree.reconstructActiveFormattingElements()
self.parser.framesetOK = False
self.parser.parseRCDataRawtext(token, "RAWTEXT")
def startTagTable(self, token):
if self.parser.compatMode != "quirks":
if self.tree.elementInScope("p", variant="button"):
self.processEndTag(impliedTagToken("p"))
self.tree.insertElement(token)
self.parser.framesetOK = False
self.parser.phase = self.parser.phases["inTable"]
def startTagVoidFormatting(self, token):
self.tree.reconstructActiveFormattingElements()
self.tree.insertElement(token)
self.tree.openElements.pop()
token["selfClosingAcknowledged"] = True
self.parser.framesetOK = False
def startTagInput(self, token):
framesetOK = self.parser.framesetOK
self.startTagVoidFormatting(token)
if ("type" in token["data"] and
token["data"]["type"].translate(asciiUpper2Lower) == "hidden"):
# input type=hidden doesn't change framesetOK
self.parser.framesetOK = framesetOK
def startTagParamSource(self, token):
self.tree.insertElement(token)
self.tree.openElements.pop()
token["selfClosingAcknowledged"] = True
def startTagHr(self, token):
if self.tree.elementInScope("p", variant="button"):
self.endTagP(impliedTagToken("p"))
self.tree.insertElement(token)
self.tree.openElements.pop()
token["selfClosingAcknowledged"] = True
self.parser.framesetOK = False
def startTagImage(self, token):
# No really...
self.parser.parseError("unexpected-start-tag-treated-as",
{"originalName": "image", "newName": "img"})
self.processStartTag(impliedTagToken("img", "StartTag",
attributes=token["data"],
selfClosing=token["selfClosing"]))
def startTagIsIndex(self, token):
self.parser.parseError("deprecated-tag", {"name": "isindex"})
if self.tree.formPointer:
return
form_attrs = {}
if "action" in token["data"]:
form_attrs["action"] = token["data"]["action"]
self.processStartTag(impliedTagToken("form", "StartTag",
attributes=form_attrs))
self.processStartTag(impliedTagToken("hr", "StartTag"))
self.processStartTag(impliedTagToken("label", "StartTag"))
# XXX Localization ...
if "prompt" in token["data"]:
prompt = token["data"]["prompt"]
else:
prompt = "This is a searchable index. Enter search keywords: "
self.processCharacters(
{"type": tokenTypes["Characters"], "data": prompt})
attributes = token["data"].copy()
if "action" in attributes:
del attributes["action"]
if "prompt" in attributes:
del attributes["prompt"]
attributes["name"] = "isindex"
self.processStartTag(impliedTagToken("input", "StartTag",
attributes=attributes,
selfClosing=token["selfClosing"]))
self.processEndTag(impliedTagToken("label"))
self.processStartTag(impliedTagToken("hr", "StartTag"))
self.processEndTag(impliedTagToken("form"))
def startTagTextarea(self, token):
self.tree.insertElement(token)
self.parser.tokenizer.state = self.parser.tokenizer.rcdataState
self.processSpaceCharacters = self.processSpaceCharactersDropNewline
self.parser.framesetOK = False
def startTagIFrame(self, token):
self.parser.framesetOK = False
self.startTagRawtext(token)
def startTagNoscript(self, token):
if self.parser.scripting:
self.startTagRawtext(token)
else:
self.startTagOther(token)
def startTagRawtext(self, token):
"""iframe, noembed noframes, noscript(if scripting enabled)"""
self.parser.parseRCDataRawtext(token, "RAWTEXT")
def startTagOpt(self, token):
if self.tree.openElements[-1].name == "option":
self.parser.phase.processEndTag(impliedTagToken("option"))
self.tree.reconstructActiveFormattingElements()
self.parser.tree.insertElement(token)
def startTagSelect(self, token):
self.tree.reconstructActiveFormattingElements()
self.tree.insertElement(token)
self.parser.framesetOK = False
if self.parser.phase in (self.parser.phases["inTable"],
self.parser.phases["inCaption"],
self.parser.phases["inColumnGroup"],
self.parser.phases["inTableBody"],
self.parser.phases["inRow"],
self.parser.phases["inCell"]):
self.parser.phase = self.parser.phases["inSelectInTable"]
else:
self.parser.phase = self.parser.phases["inSelect"]
def startTagRpRt(self, token):
if self.tree.elementInScope("ruby"):
self.tree.generateImpliedEndTags()
if self.tree.openElements[-1].name != "ruby":
self.parser.parseError()
self.tree.insertElement(token)
def startTagMath(self, token):
self.tree.reconstructActiveFormattingElements()
self.parser.adjustMathMLAttributes(token)
self.parser.adjustForeignAttributes(token)
token["namespace"] = namespaces["mathml"]
self.tree.insertElement(token)
# Need to get the parse error right for the case where the token
# has a namespace not equal to the xmlns attribute
if token["selfClosing"]:
self.tree.openElements.pop()
token["selfClosingAcknowledged"] = True
def startTagSvg(self, token):
self.tree.reconstructActiveFormattingElements()
self.parser.adjustSVGAttributes(token)
self.parser.adjustForeignAttributes(token)
token["namespace"] = namespaces["svg"]
self.tree.insertElement(token)
# Need to get the parse error right for the case where the token
# has a namespace not equal to the xmlns attribute
if token["selfClosing"]:
self.tree.openElements.pop()
token["selfClosingAcknowledged"] = True
def startTagMisplaced(self, token):
""" Elements that should be children of other elements that have a
different insertion mode; here they are ignored
"caption", "col", "colgroup", "frame", "frameset", "head",
"option", "optgroup", "tbody", "td", "tfoot", "th", "thead",
"tr", "noscript"
"""
self.parser.parseError("unexpected-start-tag-ignored", {"name": token["name"]})
def startTagOther(self, token):
self.tree.reconstructActiveFormattingElements()
self.tree.insertElement(token)
def endTagP(self, token):
if not self.tree.elementInScope("p", variant="button"):
self.startTagCloseP(impliedTagToken("p", "StartTag"))
self.parser.parseError("unexpected-end-tag", {"name": "p"})
self.endTagP(impliedTagToken("p", "EndTag"))
else:
self.tree.generateImpliedEndTags("p")
if self.tree.openElements[-1].name != "p":
self.parser.parseError("unexpected-end-tag", {"name": "p"})
node = self.tree.openElements.pop()
while node.name != "p":
node = self.tree.openElements.pop()
def endTagBody(self, token):
if not self.tree.elementInScope("body"):
self.parser.parseError()
return
elif self.tree.openElements[-1].name != "body":
for node in self.tree.openElements[2:]:
if node.name not in frozenset(("dd", "dt", "li", "optgroup",
"option", "p", "rp", "rt",
"tbody", "td", "tfoot",
"th", "thead", "tr", "body",
"html")):
# Not sure this is the correct name for the parse error
self.parser.parseError(
"expected-one-end-tag-but-got-another",
{"gotName": "body", "expectedName": node.name})
break
self.parser.phase = self.parser.phases["afterBody"]
def endTagHtml(self, token):
# We repeat the test for the body end tag token being ignored here
if self.tree.elementInScope("body"):
self.endTagBody(impliedTagToken("body"))
return token
def endTagBlock(self, token):
# Put us back in the right whitespace handling mode
if token["name"] == "pre":
self.processSpaceCharacters = self.processSpaceCharactersNonPre
inScope = self.tree.elementInScope(token["name"])
if inScope:
self.tree.generateImpliedEndTags()
if self.tree.openElements[-1].name != token["name"]:
self.parser.parseError("end-tag-too-early", {"name": token["name"]})
if inScope:
node = self.tree.openElements.pop()
while node.name != token["name"]:
node = self.tree.openElements.pop()
def endTagForm(self, token):
node = self.tree.formPointer
self.tree.formPointer = None
if node is None or not self.tree.elementInScope(node):
self.parser.parseError("unexpected-end-tag",
{"name": "form"})
else:
self.tree.generateImpliedEndTags()
if self.tree.openElements[-1] != node:
self.parser.parseError("end-tag-too-early-ignored",
{"name": "form"})
self.tree.openElements.remove(node)
def endTagListItem(self, token):
if token["name"] == "li":
variant = "list"
else:
variant = None
if not self.tree.elementInScope(token["name"], variant=variant):
self.parser.parseError("unexpected-end-tag", {"name": token["name"]})
else:
self.tree.generateImpliedEndTags(exclude=token["name"])
if self.tree.openElements[-1].name != token["name"]:
self.parser.parseError(
"end-tag-too-early",
{"name": token["name"]})
node = self.tree.openElements.pop()
while node.name != token["name"]:
node = self.tree.openElements.pop()
def endTagHeading(self, token):
for item in headingElements:
if self.tree.elementInScope(item):
self.tree.generateImpliedEndTags()
break
if self.tree.openElements[-1].name != token["name"]:
self.parser.parseError("end-tag-too-early", {"name": token["name"]})
for item in headingElements:
if self.tree.elementInScope(item):
item = self.tree.openElements.pop()
while item.name not in headingElements:
item = self.tree.openElements.pop()
break
def endTagFormatting(self, token):
"""The much-feared adoption agency algorithm"""
# http://svn.whatwg.org/webapps/complete.html#adoptionAgency revision 7867
# XXX Better parseError messages appreciated.
# Step 1
outerLoopCounter = 0
# Step 2
while outerLoopCounter < 8:
# Step 3
outerLoopCounter += 1
# Step 4:
# Let the formatting element be the last element in
# the list of active formatting elements that:
# - is between the end of the list and the last scope
# marker in the list, if any, or the start of the list
# otherwise, and
# - has the same tag name as the token.
formattingElement = self.tree.elementInActiveFormattingElements(
token["name"])
if (not formattingElement or
(formattingElement in self.tree.openElements and
not self.tree.elementInScope(formattingElement.name))):
# If there is no such node, then abort these steps
# and instead act as described in the "any other
# end tag" entry below.
self.endTagOther(token)
return
# Otherwise, if there is such a node, but that node is
# not in the stack of open elements, then this is a
# parse error; remove the element from the list, and
# abort these steps.
elif formattingElement not in self.tree.openElements:
self.parser.parseError("adoption-agency-1.2", {"name": token["name"]})
self.tree.activeFormattingElements.remove(formattingElement)
return
# Otherwise, if there is such a node, and that node is
# also in the stack of open elements, but the element
# is not in scope, then this is a parse error; ignore
# the token, and abort these steps.
elif not self.tree.elementInScope(formattingElement.name):
self.parser.parseError("adoption-agency-4.4", {"name": token["name"]})
return
# Otherwise, there is a formatting element and that
# element is in the stack and is in scope. If the
# element is not the current node, this is a parse
# error. In any case, proceed with the algorithm as
# written in the following steps.
else:
if formattingElement != self.tree.openElements[-1]:
self.parser.parseError("adoption-agency-1.3", {"name": token["name"]})
# Step 5:
# Let the furthest block be the topmost node in the
# stack of open elements that is lower in the stack
# than the formatting element, and is an element in
# the special category. There might not be one.
afeIndex = self.tree.openElements.index(formattingElement)
furthestBlock = None
for element in self.tree.openElements[afeIndex:]:
if element.nameTuple in specialElements:
furthestBlock = element
break
# Step 6:
# If there is no furthest block, then the UA must
# first pop all the nodes from the bottom of the stack
# of open elements, from the current node up to and
# including the formatting element, then remove the
# formatting element from the list of active
# formatting elements, and finally abort these steps.
if furthestBlock is None:
element = self.tree.openElements.pop()
while element != formattingElement:
element = self.tree.openElements.pop()
self.tree.activeFormattingElements.remove(element)
return
# Step 7
commonAncestor = self.tree.openElements[afeIndex - 1]
# Step 8:
# The bookmark is supposed to help us identify where to reinsert
# nodes in step 15. We have to ensure that we reinsert nodes after
# the node before the active formatting element. Note the bookmark
# can move in step 9.7
bookmark = self.tree.activeFormattingElements.index(formattingElement)
# Step 9
lastNode = node = furthestBlock
innerLoopCounter = 0
index = self.tree.openElements.index(node)
while innerLoopCounter < 3:
innerLoopCounter += 1
# Node is element before node in open elements
index -= 1
node = self.tree.openElements[index]
if node not in self.tree.activeFormattingElements:
self.tree.openElements.remove(node)
continue
# Step 9.6
if node == formattingElement:
break
# Step 9.7
if lastNode == furthestBlock:
bookmark = self.tree.activeFormattingElements.index(node) + 1
# Step 9.8
clone = node.cloneNode()
# Replace node with clone
self.tree.activeFormattingElements[
self.tree.activeFormattingElements.index(node)] = clone
self.tree.openElements[
self.tree.openElements.index(node)] = clone
node = clone
# Step 9.9
# Remove lastNode from its parents, if any
if lastNode.parent:
lastNode.parent.removeChild(lastNode)
node.appendChild(lastNode)
# Step 9.10
lastNode = node
# Step 10
# Foster parent lastNode if commonAncestor is a
# table, tbody, tfoot, thead, or tr we need to foster
# parent the lastNode
if lastNode.parent:
lastNode.parent.removeChild(lastNode)
if commonAncestor.name in frozenset(("table", "tbody", "tfoot", "thead", "tr")):
parent, insertBefore = self.tree.getTableMisnestedNodePosition()
parent.insertBefore(lastNode, insertBefore)
else:
commonAncestor.appendChild(lastNode)
# Step 11
clone = formattingElement.cloneNode()
# Step 12
furthestBlock.reparentChildren(clone)
# Step 13
furthestBlock.appendChild(clone)
# Step 14
self.tree.activeFormattingElements.remove(formattingElement)
self.tree.activeFormattingElements.insert(bookmark, clone)
# Step 15
self.tree.openElements.remove(formattingElement)
self.tree.openElements.insert(
self.tree.openElements.index(furthestBlock) + 1, clone)
def endTagAppletMarqueeObject(self, token):
if self.tree.elementInScope(token["name"]):
self.tree.generateImpliedEndTags()
if self.tree.openElements[-1].name != token["name"]:
self.parser.parseError("end-tag-too-early", {"name": token["name"]})
if self.tree.elementInScope(token["name"]):
element = self.tree.openElements.pop()
while element.name != token["name"]:
element = self.tree.openElements.pop()
self.tree.clearActiveFormattingElements()
def endTagBr(self, token):
self.parser.parseError("unexpected-end-tag-treated-as",
{"originalName": "br", "newName": "br element"})
self.tree.reconstructActiveFormattingElements()
self.tree.insertElement(impliedTagToken("br", "StartTag"))
self.tree.openElements.pop()
def endTagOther(self, token):
for node in self.tree.openElements[::-1]:
if node.name == token["name"]:
self.tree.generateImpliedEndTags(exclude=token["name"])
if self.tree.openElements[-1].name != token["name"]:
self.parser.parseError("unexpected-end-tag", {"name": token["name"]})
while self.tree.openElements.pop() != node:
pass
break
else:
if node.nameTuple in specialElements:
self.parser.parseError("unexpected-end-tag", {"name": token["name"]})
break
startTagHandler = _utils.MethodDispatcher([
("html", Phase.startTagHtml),
(("base", "basefont", "bgsound", "command", "link", "meta",
"script", "style", "title"),
startTagProcessInHead),
("body", startTagBody),
("frameset", startTagFrameset),
(("address", "article", "aside", "blockquote", "center", "details",
"dir", "div", "dl", "fieldset", "figcaption", "figure",
"footer", "header", "hgroup", "main", "menu", "nav", "ol", "p",
"section", "summary", "ul"),
startTagCloseP),
(headingElements, startTagHeading),
(("pre", "listing"), startTagPreListing),
("form", startTagForm),
(("li", "dd", "dt"), startTagListItem),
("plaintext", startTagPlaintext),
("a", startTagA),
(("b", "big", "code", "em", "font", "i", "s", "small", "strike",
"strong", "tt", "u"), startTagFormatting),
("nobr", startTagNobr),
("button", startTagButton),
(("applet", "marquee", "object"), startTagAppletMarqueeObject),
("xmp", startTagXmp),
("table", startTagTable),
(("area", "br", "embed", "img", "keygen", "wbr"),
startTagVoidFormatting),
(("param", "source", "track"), startTagParamSource),
("input", startTagInput),
("hr", startTagHr),
("image", startTagImage),
("isindex", startTagIsIndex),
("textarea", startTagTextarea),
("iframe", startTagIFrame),
("noscript", startTagNoscript),
(("noembed", "noframes"), startTagRawtext),
("select", startTagSelect),
(("rp", "rt"), startTagRpRt),
(("option", "optgroup"), startTagOpt),
(("math"), startTagMath),
(("svg"), startTagSvg),
(("caption", "col", "colgroup", "frame", "head",
"tbody", "td", "tfoot", "th", "thead",
"tr"), startTagMisplaced)
])
startTagHandler.default = startTagOther
endTagHandler = _utils.MethodDispatcher([
("body", endTagBody),
("html", endTagHtml),
(("address", "article", "aside", "blockquote", "button", "center",
"details", "dialog", "dir", "div", "dl", "fieldset", "figcaption", "figure",
"footer", "header", "hgroup", "listing", "main", "menu", "nav", "ol", "pre",
"section", "summary", "ul"), endTagBlock),
("form", endTagForm),
("p", endTagP),
(("dd", "dt", "li"), endTagListItem),
(headingElements, endTagHeading),
(("a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small",
"strike", "strong", "tt", "u"), endTagFormatting),
(("applet", "marquee", "object"), endTagAppletMarqueeObject),
("br", endTagBr),
])
endTagHandler.default = endTagOther
class TextPhase(Phase):
__slots__ = tuple()
def processCharacters(self, token):
self.tree.insertText(token["data"])
def processEOF(self):
self.parser.parseError("expected-named-closing-tag-but-got-eof",
{"name": self.tree.openElements[-1].name})
self.tree.openElements.pop()
self.parser.phase = self.parser.originalPhase
return True
def startTagOther(self, token):
assert False, "Tried to process start tag %s in RCDATA/RAWTEXT mode" % token['name']
def endTagScript(self, token):
node = self.tree.openElements.pop()
assert node.name == "script"
self.parser.phase = self.parser.originalPhase
# The rest of this method is all stuff that only happens if
# document.write works
def endTagOther(self, token):
self.tree.openElements.pop()
self.parser.phase = self.parser.originalPhase
startTagHandler = _utils.MethodDispatcher([])
startTagHandler.default = startTagOther
endTagHandler = _utils.MethodDispatcher([
("script", endTagScript)])
endTagHandler.default = endTagOther
class InTablePhase(Phase):
# http://www.whatwg.org/specs/web-apps/current-work/#in-table
__slots__ = tuple()
# helper methods
def clearStackToTableContext(self):
# "clear the stack back to a table context"
while self.tree.openElements[-1].name not in ("table", "html"):
# self.parser.parseError("unexpected-implied-end-tag-in-table",
# {"name": self.tree.openElements[-1].name})
self.tree.openElements.pop()
# When the current node is <html> it's an innerHTML case
# processing methods
def processEOF(self):
if self.tree.openElements[-1].name != "html":
self.parser.parseError("eof-in-table")
else:
assert self.parser.innerHTML
# Stop parsing
def processSpaceCharacters(self, token):
originalPhase = self.parser.phase
self.parser.phase = self.parser.phases["inTableText"]
self.parser.phase.originalPhase = originalPhase
self.parser.phase.processSpaceCharacters(token)
def processCharacters(self, token):
originalPhase = self.parser.phase
self.parser.phase = self.parser.phases["inTableText"]
self.parser.phase.originalPhase = originalPhase
self.parser.phase.processCharacters(token)
def insertText(self, token):
# If we get here there must be at least one non-whitespace character
# Do the table magic!
self.tree.insertFromTable = True
self.parser.phases["inBody"].processCharacters(token)
self.tree.insertFromTable = False
def startTagCaption(self, token):
self.clearStackToTableContext()
self.tree.activeFormattingElements.append(Marker)
self.tree.insertElement(token)
self.parser.phase = self.parser.phases["inCaption"]
def startTagColgroup(self, token):
self.clearStackToTableContext()
self.tree.insertElement(token)
self.parser.phase = self.parser.phases["inColumnGroup"]
def startTagCol(self, token):
self.startTagColgroup(impliedTagToken("colgroup", "StartTag"))
return token
def startTagRowGroup(self, token):
self.clearStackToTableContext()
self.tree.insertElement(token)
self.parser.phase = self.parser.phases["inTableBody"]
def startTagImplyTbody(self, token):
self.startTagRowGroup(impliedTagToken("tbody", "StartTag"))
return token
def startTagTable(self, token):
self.parser.parseError("unexpected-start-tag-implies-end-tag",
{"startName": "table", "endName": "table"})
self.parser.phase.processEndTag(impliedTagToken("table"))
if not self.parser.innerHTML:
return token
def startTagStyleScript(self, token):
return self.parser.phases["inHead"].processStartTag(token)
def startTagInput(self, token):
if ("type" in token["data"] and
token["data"]["type"].translate(asciiUpper2Lower) == "hidden"):
self.parser.parseError("unexpected-hidden-input-in-table")
self.tree.insertElement(token)
# XXX associate with form
self.tree.openElements.pop()
else:
self.startTagOther(token)
def startTagForm(self, token):
self.parser.parseError("unexpected-form-in-table")
if self.tree.formPointer is None:
self.tree.insertElement(token)
self.tree.formPointer = self.tree.openElements[-1]
self.tree.openElements.pop()
def startTagOther(self, token):
self.parser.parseError("unexpected-start-tag-implies-table-voodoo", {"name": token["name"]})
# Do the table magic!
self.tree.insertFromTable = True
self.parser.phases["inBody"].processStartTag(token)
self.tree.insertFromTable = False
def endTagTable(self, token):
if self.tree.elementInScope("table", variant="table"):
self.tree.generateImpliedEndTags()
if self.tree.openElements[-1].name != "table":
self.parser.parseError("end-tag-too-early-named",
{"gotName": "table",
"expectedName": self.tree.openElements[-1].name})
while self.tree.openElements[-1].name != "table":
self.tree.openElements.pop()
self.tree.openElements.pop()
self.parser.resetInsertionMode()
else:
# innerHTML case
assert self.parser.innerHTML
self.parser.parseError()
def endTagIgnore(self, token):
self.parser.parseError("unexpected-end-tag", {"name": token["name"]})
def endTagOther(self, token):
self.parser.parseError("unexpected-end-tag-implies-table-voodoo", {"name": token["name"]})
# Do the table magic!
self.tree.insertFromTable = True
self.parser.phases["inBody"].processEndTag(token)
self.tree.insertFromTable = False
startTagHandler = _utils.MethodDispatcher([
("html", Phase.startTagHtml),
("caption", startTagCaption),
("colgroup", startTagColgroup),
("col", startTagCol),
(("tbody", "tfoot", "thead"), startTagRowGroup),
(("td", "th", "tr"), startTagImplyTbody),
("table", startTagTable),
(("style", "script"), startTagStyleScript),
("input", startTagInput),
("form", startTagForm)
])
startTagHandler.default = startTagOther
endTagHandler = _utils.MethodDispatcher([
("table", endTagTable),
(("body", "caption", "col", "colgroup", "html", "tbody", "td",
"tfoot", "th", "thead", "tr"), endTagIgnore)
])
endTagHandler.default = endTagOther
class InTableTextPhase(Phase):
__slots__ = ("originalPhase", "characterTokens")
def __init__(self, *args, **kwargs):
super(InTableTextPhase, self).__init__(*args, **kwargs)
self.originalPhase = None
self.characterTokens = []
def flushCharacters(self):
data = "".join([item["data"] for item in self.characterTokens])
if any([item not in spaceCharacters for item in data]):
token = {"type": tokenTypes["Characters"], "data": data}
self.parser.phases["inTable"].insertText(token)
elif data:
self.tree.insertText(data)
self.characterTokens = []
def processComment(self, token):
self.flushCharacters()
self.parser.phase = self.originalPhase
return token
def processEOF(self):
self.flushCharacters()
self.parser.phase = self.originalPhase
return True
def processCharacters(self, token):
if token["data"] == "\u0000":
return
self.characterTokens.append(token)
def processSpaceCharacters(self, token):
# pretty sure we should never reach here
self.characterTokens.append(token)
# assert False
def processStartTag(self, token):
self.flushCharacters()
self.parser.phase = self.originalPhase
return token
def processEndTag(self, token):
self.flushCharacters()
self.parser.phase = self.originalPhase
return token
class InCaptionPhase(Phase):
# http://www.whatwg.org/specs/web-apps/current-work/#in-caption
__slots__ = tuple()
def ignoreEndTagCaption(self):
return not self.tree.elementInScope("caption", variant="table")
def processEOF(self):
self.parser.phases["inBody"].processEOF()
def processCharacters(self, token):
return self.parser.phases["inBody"].processCharacters(token)
def startTagTableElement(self, token):
self.parser.parseError()
# XXX Have to duplicate logic here to find out if the tag is ignored
ignoreEndTag = self.ignoreEndTagCaption()
self.parser.phase.processEndTag(impliedTagToken("caption"))
if not ignoreEndTag:
return token
def startTagOther(self, token):
return self.parser.phases["inBody"].processStartTag(token)
def endTagCaption(self, token):
if not self.ignoreEndTagCaption():
# AT this code is quite similar to endTagTable in "InTable"
self.tree.generateImpliedEndTags()
if self.tree.openElements[-1].name != "caption":
self.parser.parseError("expected-one-end-tag-but-got-another",
{"gotName": "caption",
"expectedName": self.tree.openElements[-1].name})
while self.tree.openElements[-1].name != "caption":
self.tree.openElements.pop()
self.tree.openElements.pop()
self.tree.clearActiveFormattingElements()
self.parser.phase = self.parser.phases["inTable"]
else:
# innerHTML case
assert self.parser.innerHTML
self.parser.parseError()
def endTagTable(self, token):
self.parser.parseError()
ignoreEndTag = self.ignoreEndTagCaption()
self.parser.phase.processEndTag(impliedTagToken("caption"))
if not ignoreEndTag:
return token
def endTagIgnore(self, token):
self.parser.parseError("unexpected-end-tag", {"name": token["name"]})
def endTagOther(self, token):
return self.parser.phases["inBody"].processEndTag(token)
startTagHandler = _utils.MethodDispatcher([
("html", Phase.startTagHtml),
(("caption", "col", "colgroup", "tbody", "td", "tfoot", "th",
"thead", "tr"), startTagTableElement)
])
startTagHandler.default = startTagOther
endTagHandler = _utils.MethodDispatcher([
("caption", endTagCaption),
("table", endTagTable),
(("body", "col", "colgroup", "html", "tbody", "td", "tfoot", "th",
"thead", "tr"), endTagIgnore)
])
endTagHandler.default = endTagOther
class InColumnGroupPhase(Phase):
# http://www.whatwg.org/specs/web-apps/current-work/#in-column
__slots__ = tuple()
def ignoreEndTagColgroup(self):
return self.tree.openElements[-1].name == "html"
def processEOF(self):
if self.tree.openElements[-1].name == "html":
assert self.parser.innerHTML
return
else:
ignoreEndTag = self.ignoreEndTagColgroup()
self.endTagColgroup(impliedTagToken("colgroup"))
if not ignoreEndTag:
return True
def processCharacters(self, token):
ignoreEndTag = self.ignoreEndTagColgroup()
self.endTagColgroup(impliedTagToken("colgroup"))
if not ignoreEndTag:
return token
def startTagCol(self, token):
self.tree.insertElement(token)
self.tree.openElements.pop()
token["selfClosingAcknowledged"] = True
def startTagOther(self, token):
ignoreEndTag = self.ignoreEndTagColgroup()
self.endTagColgroup(impliedTagToken("colgroup"))
if not ignoreEndTag:
return token
def endTagColgroup(self, token):
if self.ignoreEndTagColgroup():
# innerHTML case
assert self.parser.innerHTML
self.parser.parseError()
else:
self.tree.openElements.pop()
self.parser.phase = self.parser.phases["inTable"]
def endTagCol(self, token):
self.parser.parseError("no-end-tag", {"name": "col"})
def endTagOther(self, token):
ignoreEndTag = self.ignoreEndTagColgroup()
self.endTagColgroup(impliedTagToken("colgroup"))
if not ignoreEndTag:
return token
startTagHandler = _utils.MethodDispatcher([
("html", Phase.startTagHtml),
("col", startTagCol)
])
startTagHandler.default = startTagOther
endTagHandler = _utils.MethodDispatcher([
("colgroup", endTagColgroup),
("col", endTagCol)
])
endTagHandler.default = endTagOther
class InTableBodyPhase(Phase):
# http://www.whatwg.org/specs/web-apps/current-work/#in-table0
__slots__ = tuple()
# helper methods
def clearStackToTableBodyContext(self):
while self.tree.openElements[-1].name not in ("tbody", "tfoot",
"thead", "html"):
# self.parser.parseError("unexpected-implied-end-tag-in-table",
# {"name": self.tree.openElements[-1].name})
self.tree.openElements.pop()
if self.tree.openElements[-1].name == "html":
assert self.parser.innerHTML
# the rest
def processEOF(self):
self.parser.phases["inTable"].processEOF()
def processSpaceCharacters(self, token):
return self.parser.phases["inTable"].processSpaceCharacters(token)
def processCharacters(self, token):
return self.parser.phases["inTable"].processCharacters(token)
def startTagTr(self, token):
self.clearStackToTableBodyContext()
self.tree.insertElement(token)
self.parser.phase = self.parser.phases["inRow"]
def startTagTableCell(self, token):
self.parser.parseError("unexpected-cell-in-table-body",
{"name": token["name"]})
self.startTagTr(impliedTagToken("tr", "StartTag"))
return token
def startTagTableOther(self, token):
# XXX AT Any ideas on how to share this with endTagTable?
if (self.tree.elementInScope("tbody", variant="table") or
self.tree.elementInScope("thead", variant="table") or
self.tree.elementInScope("tfoot", variant="table")):
self.clearStackToTableBodyContext()
self.endTagTableRowGroup(
impliedTagToken(self.tree.openElements[-1].name))
return token
else:
# innerHTML case
assert self.parser.innerHTML
self.parser.parseError()
def startTagOther(self, token):
return self.parser.phases["inTable"].processStartTag(token)
def endTagTableRowGroup(self, token):
if self.tree.elementInScope(token["name"], variant="table"):
self.clearStackToTableBodyContext()
self.tree.openElements.pop()
self.parser.phase = self.parser.phases["inTable"]
else:
self.parser.parseError("unexpected-end-tag-in-table-body",
{"name": token["name"]})
def endTagTable(self, token):
if (self.tree.elementInScope("tbody", variant="table") or
self.tree.elementInScope("thead", variant="table") or
self.tree.elementInScope("tfoot", variant="table")):
self.clearStackToTableBodyContext()
self.endTagTableRowGroup(
impliedTagToken(self.tree.openElements[-1].name))
return token
else:
# innerHTML case
assert self.parser.innerHTML
self.parser.parseError()
def endTagIgnore(self, token):
self.parser.parseError("unexpected-end-tag-in-table-body",
{"name": token["name"]})
def endTagOther(self, token):
return self.parser.phases["inTable"].processEndTag(token)
startTagHandler = _utils.MethodDispatcher([
("html", Phase.startTagHtml),
("tr", startTagTr),
(("td", "th"), startTagTableCell),
(("caption", "col", "colgroup", "tbody", "tfoot", "thead"),
startTagTableOther)
])
startTagHandler.default = startTagOther
endTagHandler = _utils.MethodDispatcher([
(("tbody", "tfoot", "thead"), endTagTableRowGroup),
("table", endTagTable),
(("body", "caption", "col", "colgroup", "html", "td", "th",
"tr"), endTagIgnore)
])
endTagHandler.default = endTagOther
class InRowPhase(Phase):
# http://www.whatwg.org/specs/web-apps/current-work/#in-row
__slots__ = tuple()
# helper methods (XXX unify this with other table helper methods)
def clearStackToTableRowContext(self):
while self.tree.openElements[-1].name not in ("tr", "html"):
self.parser.parseError("unexpected-implied-end-tag-in-table-row",
{"name": self.tree.openElements[-1].name})
self.tree.openElements.pop()
def ignoreEndTagTr(self):
return not self.tree.elementInScope("tr", variant="table")
# the rest
def processEOF(self):
self.parser.phases["inTable"].processEOF()
def processSpaceCharacters(self, token):
return self.parser.phases["inTable"].processSpaceCharacters(token)
def processCharacters(self, token):
return self.parser.phases["inTable"].processCharacters(token)
def startTagTableCell(self, token):
self.clearStackToTableRowContext()
self.tree.insertElement(token)
self.parser.phase = self.parser.phases["inCell"]
self.tree.activeFormattingElements.append(Marker)
def startTagTableOther(self, token):
ignoreEndTag = self.ignoreEndTagTr()
self.endTagTr(impliedTagToken("tr"))
# XXX how are we sure it's always ignored in the innerHTML case?
if not ignoreEndTag:
return token
def startTagOther(self, token):
return self.parser.phases["inTable"].processStartTag(token)
def endTagTr(self, token):
if not self.ignoreEndTagTr():
self.clearStackToTableRowContext()
self.tree.openElements.pop()
self.parser.phase = self.parser.phases["inTableBody"]
else:
# innerHTML case
assert self.parser.innerHTML
self.parser.parseError()
def endTagTable(self, token):
ignoreEndTag = self.ignoreEndTagTr()
self.endTagTr(impliedTagToken("tr"))
# Reprocess the current tag if the tr end tag was not ignored
# XXX how are we sure it's always ignored in the innerHTML case?
if not ignoreEndTag:
return token
def endTagTableRowGroup(self, token):
if self.tree.elementInScope(token["name"], variant="table"):
self.endTagTr(impliedTagToken("tr"))
return token
else:
self.parser.parseError()
def endTagIgnore(self, token):
self.parser.parseError("unexpected-end-tag-in-table-row",
{"name": token["name"]})
def endTagOther(self, token):
return self.parser.phases["inTable"].processEndTag(token)
startTagHandler = _utils.MethodDispatcher([
("html", Phase.startTagHtml),
(("td", "th"), startTagTableCell),
(("caption", "col", "colgroup", "tbody", "tfoot", "thead",
"tr"), startTagTableOther)
])
startTagHandler.default = startTagOther
endTagHandler = _utils.MethodDispatcher([
("tr", endTagTr),
("table", endTagTable),
(("tbody", "tfoot", "thead"), endTagTableRowGroup),
(("body", "caption", "col", "colgroup", "html", "td", "th"),
endTagIgnore)
])
endTagHandler.default = endTagOther
class InCellPhase(Phase):
# http://www.whatwg.org/specs/web-apps/current-work/#in-cell
__slots__ = tuple()
# helper
def closeCell(self):
if self.tree.elementInScope("td", variant="table"):
self.endTagTableCell(impliedTagToken("td"))
elif self.tree.elementInScope("th", variant="table"):
self.endTagTableCell(impliedTagToken("th"))
# the rest
def processEOF(self):
self.parser.phases["inBody"].processEOF()
def processCharacters(self, token):
return self.parser.phases["inBody"].processCharacters(token)
def startTagTableOther(self, token):
if (self.tree.elementInScope("td", variant="table") or
self.tree.elementInScope("th", variant="table")):
self.closeCell()
return token
else:
# innerHTML case
assert self.parser.innerHTML
self.parser.parseError()
def startTagOther(self, token):
return self.parser.phases["inBody"].processStartTag(token)
def endTagTableCell(self, token):
if self.tree.elementInScope(token["name"], variant="table"):
self.tree.generateImpliedEndTags(token["name"])
if self.tree.openElements[-1].name != token["name"]:
self.parser.parseError("unexpected-cell-end-tag",
{"name": token["name"]})
while True:
node = self.tree.openElements.pop()
if node.name == token["name"]:
break
else:
self.tree.openElements.pop()
self.tree.clearActiveFormattingElements()
self.parser.phase = self.parser.phases["inRow"]
else:
self.parser.parseError("unexpected-end-tag", {"name": token["name"]})
def endTagIgnore(self, token):
self.parser.parseError("unexpected-end-tag", {"name": token["name"]})
def endTagImply(self, token):
if self.tree.elementInScope(token["name"], variant="table"):
self.closeCell()
return token
else:
# sometimes innerHTML case
self.parser.parseError()
def endTagOther(self, token):
return self.parser.phases["inBody"].processEndTag(token)
startTagHandler = _utils.MethodDispatcher([
("html", Phase.startTagHtml),
(("caption", "col", "colgroup", "tbody", "td", "tfoot", "th",
"thead", "tr"), startTagTableOther)
])
startTagHandler.default = startTagOther
endTagHandler = _utils.MethodDispatcher([
(("td", "th"), endTagTableCell),
(("body", "caption", "col", "colgroup", "html"), endTagIgnore),
(("table", "tbody", "tfoot", "thead", "tr"), endTagImply)
])
endTagHandler.default = endTagOther
class InSelectPhase(Phase):
__slots__ = tuple()
# http://www.whatwg.org/specs/web-apps/current-work/#in-select
def processEOF(self):
if self.tree.openElements[-1].name != "html":
self.parser.parseError("eof-in-select")
else:
assert self.parser.innerHTML
def processCharacters(self, token):
if token["data"] == "\u0000":
return
self.tree.insertText(token["data"])
def startTagOption(self, token):
# We need to imply </option> if <option> is the current node.
if self.tree.openElements[-1].name == "option":
self.tree.openElements.pop()
self.tree.insertElement(token)
def startTagOptgroup(self, token):
if self.tree.openElements[-1].name == "option":
self.tree.openElements.pop()
if self.tree.openElements[-1].name == "optgroup":
self.tree.openElements.pop()
self.tree.insertElement(token)
def startTagSelect(self, token):
self.parser.parseError("unexpected-select-in-select")
self.endTagSelect(impliedTagToken("select"))
def startTagInput(self, token):
self.parser.parseError("unexpected-input-in-select")
if self.tree.elementInScope("select", variant="select"):
self.endTagSelect(impliedTagToken("select"))
return token
else:
assert self.parser.innerHTML
def startTagScript(self, token):
return self.parser.phases["inHead"].processStartTag(token)
def startTagOther(self, token):
self.parser.parseError("unexpected-start-tag-in-select",
{"name": token["name"]})
def endTagOption(self, token):
if self.tree.openElements[-1].name == "option":
self.tree.openElements.pop()
else:
self.parser.parseError("unexpected-end-tag-in-select",
{"name": "option"})
def endTagOptgroup(self, token):
# </optgroup> implicitly closes <option>
if (self.tree.openElements[-1].name == "option" and
self.tree.openElements[-2].name == "optgroup"):
self.tree.openElements.pop()
# It also closes </optgroup>
if self.tree.openElements[-1].name == "optgroup":
self.tree.openElements.pop()
# But nothing else
else:
self.parser.parseError("unexpected-end-tag-in-select",
{"name": "optgroup"})
def endTagSelect(self, token):
if self.tree.elementInScope("select", variant="select"):
node = self.tree.openElements.pop()
while node.name != "select":
node = self.tree.openElements.pop()
self.parser.resetInsertionMode()
else:
# innerHTML case
assert self.parser.innerHTML
self.parser.parseError()
def endTagOther(self, token):
self.parser.parseError("unexpected-end-tag-in-select",
{"name": token["name"]})
startTagHandler = _utils.MethodDispatcher([
("html", Phase.startTagHtml),
("option", startTagOption),
("optgroup", startTagOptgroup),
("select", startTagSelect),
(("input", "keygen", "textarea"), startTagInput),
("script", startTagScript)
])
startTagHandler.default = startTagOther
endTagHandler = _utils.MethodDispatcher([
("option", endTagOption),
("optgroup", endTagOptgroup),
("select", endTagSelect)
])
endTagHandler.default = endTagOther
class InSelectInTablePhase(Phase):
__slots__ = tuple()
def processEOF(self):
self.parser.phases["inSelect"].processEOF()
def processCharacters(self, token):
return self.parser.phases["inSelect"].processCharacters(token)
def startTagTable(self, token):
self.parser.parseError("unexpected-table-element-start-tag-in-select-in-table", {"name": token["name"]})
self.endTagOther(impliedTagToken("select"))
return token
def startTagOther(self, token):
return self.parser.phases["inSelect"].processStartTag(token)
def endTagTable(self, token):
self.parser.parseError("unexpected-table-element-end-tag-in-select-in-table", {"name": token["name"]})
if self.tree.elementInScope(token["name"], variant="table"):
self.endTagOther(impliedTagToken("select"))
return token
def endTagOther(self, token):
return self.parser.phases["inSelect"].processEndTag(token)
startTagHandler = _utils.MethodDispatcher([
(("caption", "table", "tbody", "tfoot", "thead", "tr", "td", "th"),
startTagTable)
])
startTagHandler.default = startTagOther
endTagHandler = _utils.MethodDispatcher([
(("caption", "table", "tbody", "tfoot", "thead", "tr", "td", "th"),
endTagTable)
])
endTagHandler.default = endTagOther
class InForeignContentPhase(Phase):
__slots__ = tuple()
breakoutElements = frozenset(["b", "big", "blockquote", "body", "br",
"center", "code", "dd", "div", "dl", "dt",
"em", "embed", "h1", "h2", "h3",
"h4", "h5", "h6", "head", "hr", "i", "img",
"li", "listing", "menu", "meta", "nobr",
"ol", "p", "pre", "ruby", "s", "small",
"span", "strong", "strike", "sub", "sup",
"table", "tt", "u", "ul", "var"])
def adjustSVGTagNames(self, token):
replacements = {"altglyph": "altGlyph",
"altglyphdef": "altGlyphDef",
"altglyphitem": "altGlyphItem",
"animatecolor": "animateColor",
"animatemotion": "animateMotion",
"animatetransform": "animateTransform",
"clippath": "clipPath",
"feblend": "feBlend",
"fecolormatrix": "feColorMatrix",
"fecomponenttransfer": "feComponentTransfer",
"fecomposite": "feComposite",
"feconvolvematrix": "feConvolveMatrix",
"fediffuselighting": "feDiffuseLighting",
"fedisplacementmap": "feDisplacementMap",
"fedistantlight": "feDistantLight",
"feflood": "feFlood",
"fefunca": "feFuncA",
"fefuncb": "feFuncB",
"fefuncg": "feFuncG",
"fefuncr": "feFuncR",
"fegaussianblur": "feGaussianBlur",
"feimage": "feImage",
"femerge": "feMerge",
"femergenode": "feMergeNode",
"femorphology": "feMorphology",
"feoffset": "feOffset",
"fepointlight": "fePointLight",
"fespecularlighting": "feSpecularLighting",
"fespotlight": "feSpotLight",
"fetile": "feTile",
"feturbulence": "feTurbulence",
"foreignobject": "foreignObject",
"glyphref": "glyphRef",
"lineargradient": "linearGradient",
"radialgradient": "radialGradient",
"textpath": "textPath"}
if token["name"] in replacements:
token["name"] = replacements[token["name"]]
def processCharacters(self, token):
if token["data"] == "\u0000":
token["data"] = "\uFFFD"
elif (self.parser.framesetOK and
any(char not in spaceCharacters for char in token["data"])):
self.parser.framesetOK = False
Phase.processCharacters(self, token)
def processStartTag(self, token):
currentNode = self.tree.openElements[-1]
if (token["name"] in self.breakoutElements or
(token["name"] == "font" and
set(token["data"].keys()) & {"color", "face", "size"})):
self.parser.parseError("unexpected-html-element-in-foreign-content",
{"name": token["name"]})
while (self.tree.openElements[-1].namespace !=
self.tree.defaultNamespace and
not self.parser.isHTMLIntegrationPoint(self.tree.openElements[-1]) and
not self.parser.isMathMLTextIntegrationPoint(self.tree.openElements[-1])):
self.tree.openElements.pop()
return token
else:
if currentNode.namespace == namespaces["mathml"]:
self.parser.adjustMathMLAttributes(token)
elif currentNode.namespace == namespaces["svg"]:
self.adjustSVGTagNames(token)
self.parser.adjustSVGAttributes(token)
self.parser.adjustForeignAttributes(token)
token["namespace"] = currentNode.namespace
self.tree.insertElement(token)
if token["selfClosing"]:
self.tree.openElements.pop()
token["selfClosingAcknowledged"] = True
def processEndTag(self, token):
nodeIndex = len(self.tree.openElements) - 1
node = self.tree.openElements[-1]
if node.name.translate(asciiUpper2Lower) != token["name"]:
self.parser.parseError("unexpected-end-tag", {"name": token["name"]})
while True:
if node.name.translate(asciiUpper2Lower) == token["name"]:
# XXX this isn't in the spec but it seems necessary
if self.parser.phase == self.parser.phases["inTableText"]:
self.parser.phase.flushCharacters()
self.parser.phase = self.parser.phase.originalPhase
while self.tree.openElements.pop() != node:
assert self.tree.openElements
new_token = None
break
nodeIndex -= 1
node = self.tree.openElements[nodeIndex]
if node.namespace != self.tree.defaultNamespace:
continue
else:
new_token = self.parser.phase.processEndTag(token)
break
return new_token
class AfterBodyPhase(Phase):
__slots__ = tuple()
def processEOF(self):
# Stop parsing
pass
def processComment(self, token):
# This is needed because data is to be appended to the <html> element
# here and not to whatever is currently open.
self.tree.insertComment(token, self.tree.openElements[0])
def processCharacters(self, token):
self.parser.parseError("unexpected-char-after-body")
self.parser.phase = self.parser.phases["inBody"]
return token
def startTagHtml(self, token):
return self.parser.phases["inBody"].processStartTag(token)
def startTagOther(self, token):
self.parser.parseError("unexpected-start-tag-after-body",
{"name": token["name"]})
self.parser.phase = self.parser.phases["inBody"]
return token
def endTagHtml(self, name):
if self.parser.innerHTML:
self.parser.parseError("unexpected-end-tag-after-body-innerhtml")
else:
self.parser.phase = self.parser.phases["afterAfterBody"]
def endTagOther(self, token):
self.parser.parseError("unexpected-end-tag-after-body",
{"name": token["name"]})
self.parser.phase = self.parser.phases["inBody"]
return token
startTagHandler = _utils.MethodDispatcher([
("html", startTagHtml)
])
startTagHandler.default = startTagOther
endTagHandler = _utils.MethodDispatcher([("html", endTagHtml)])
endTagHandler.default = endTagOther
class InFramesetPhase(Phase):
# http://www.whatwg.org/specs/web-apps/current-work/#in-frameset
__slots__ = tuple()
def processEOF(self):
if self.tree.openElements[-1].name != "html":
self.parser.parseError("eof-in-frameset")
else:
assert self.parser.innerHTML
def processCharacters(self, token):
self.parser.parseError("unexpected-char-in-frameset")
def startTagFrameset(self, token):
self.tree.insertElement(token)
def startTagFrame(self, token):
self.tree.insertElement(token)
self.tree.openElements.pop()
def startTagNoframes(self, token):
return self.parser.phases["inBody"].processStartTag(token)
def startTagOther(self, token):
self.parser.parseError("unexpected-start-tag-in-frameset",
{"name": token["name"]})
def endTagFrameset(self, token):
if self.tree.openElements[-1].name == "html":
# innerHTML case
self.parser.parseError("unexpected-frameset-in-frameset-innerhtml")
else:
self.tree.openElements.pop()
if (not self.parser.innerHTML and
self.tree.openElements[-1].name != "frameset"):
# If we're not in innerHTML mode and the current node is not a
# "frameset" element (anymore) then switch.
self.parser.phase = self.parser.phases["afterFrameset"]
def endTagOther(self, token):
self.parser.parseError("unexpected-end-tag-in-frameset",
{"name": token["name"]})
startTagHandler = _utils.MethodDispatcher([
("html", Phase.startTagHtml),
("frameset", startTagFrameset),
("frame", startTagFrame),
("noframes", startTagNoframes)
])
startTagHandler.default = startTagOther
endTagHandler = _utils.MethodDispatcher([
("frameset", endTagFrameset)
])
endTagHandler.default = endTagOther
class AfterFramesetPhase(Phase):
# http://www.whatwg.org/specs/web-apps/current-work/#after3
__slots__ = tuple()
def processEOF(self):
# Stop parsing
pass
def processCharacters(self, token):
self.parser.parseError("unexpected-char-after-frameset")
def startTagNoframes(self, token):
return self.parser.phases["inHead"].processStartTag(token)
def startTagOther(self, token):
self.parser.parseError("unexpected-start-tag-after-frameset",
{"name": token["name"]})
def endTagHtml(self, token):
self.parser.phase = self.parser.phases["afterAfterFrameset"]
def endTagOther(self, token):
self.parser.parseError("unexpected-end-tag-after-frameset",
{"name": token["name"]})
startTagHandler = _utils.MethodDispatcher([
("html", Phase.startTagHtml),
("noframes", startTagNoframes)
])
startTagHandler.default = startTagOther
endTagHandler = _utils.MethodDispatcher([
("html", endTagHtml)
])
endTagHandler.default = endTagOther
class AfterAfterBodyPhase(Phase):
__slots__ = tuple()
def processEOF(self):
pass
def processComment(self, token):
self.tree.insertComment(token, self.tree.document)
def processSpaceCharacters(self, token):
return self.parser.phases["inBody"].processSpaceCharacters(token)
def processCharacters(self, token):
self.parser.parseError("expected-eof-but-got-char")
self.parser.phase = self.parser.phases["inBody"]
return token
def startTagHtml(self, token):
return self.parser.phases["inBody"].processStartTag(token)
def startTagOther(self, token):
self.parser.parseError("expected-eof-but-got-start-tag",
{"name": token["name"]})
self.parser.phase = self.parser.phases["inBody"]
return token
def processEndTag(self, token):
self.parser.parseError("expected-eof-but-got-end-tag",
{"name": token["name"]})
self.parser.phase = self.parser.phases["inBody"]
return token
startTagHandler = _utils.MethodDispatcher([
("html", startTagHtml)
])
startTagHandler.default = startTagOther
class AfterAfterFramesetPhase(Phase):
__slots__ = tuple()
def processEOF(self):
pass
def processComment(self, token):
self.tree.insertComment(token, self.tree.document)
def processSpaceCharacters(self, token):
return self.parser.phases["inBody"].processSpaceCharacters(token)
def processCharacters(self, token):
self.parser.parseError("expected-eof-but-got-char")
def startTagHtml(self, token):
return self.parser.phases["inBody"].processStartTag(token)
def startTagNoFrames(self, token):
return self.parser.phases["inHead"].processStartTag(token)
def startTagOther(self, token):
self.parser.parseError("expected-eof-but-got-start-tag",
{"name": token["name"]})
def processEndTag(self, token):
self.parser.parseError("expected-eof-but-got-end-tag",
{"name": token["name"]})
startTagHandler = _utils.MethodDispatcher([
("html", startTagHtml),
("noframes", startTagNoFrames)
])
startTagHandler.default = startTagOther
# pylint:enable=unused-argument
return {
"initial": InitialPhase,
"beforeHtml": BeforeHtmlPhase,
"beforeHead": BeforeHeadPhase,
"inHead": InHeadPhase,
"inHeadNoscript": InHeadNoscriptPhase,
"afterHead": AfterHeadPhase,
"inBody": InBodyPhase,
"text": TextPhase,
"inTable": InTablePhase,
"inTableText": InTableTextPhase,
"inCaption": InCaptionPhase,
"inColumnGroup": InColumnGroupPhase,
"inTableBody": InTableBodyPhase,
"inRow": InRowPhase,
"inCell": InCellPhase,
"inSelect": InSelectPhase,
"inSelectInTable": InSelectInTablePhase,
"inForeignContent": InForeignContentPhase,
"afterBody": AfterBodyPhase,
"inFrameset": InFramesetPhase,
"afterFrameset": AfterFramesetPhase,
"afterAfterBody": AfterAfterBodyPhase,
"afterAfterFrameset": AfterAfterFramesetPhase,
# XXX after after frameset
}
def adjust_attributes(token, replacements):
needs_adjustment = viewkeys(token['data']) & viewkeys(replacements)
if needs_adjustment:
token['data'] = type(token['data'])((replacements.get(k, k), v)
for k, v in token['data'].items())
def impliedTagToken(name, type="EndTag", attributes=None,
selfClosing=False):
if attributes is None:
attributes = {}
return {"type": tokenTypes[type], "name": name, "data": attributes,
"selfClosing": selfClosing}
|
HTMLParser
|
python
|
charliermarsh__ruff
|
crates/ruff_linter/resources/test/fixtures/flake8_type_checking/runtime_evaluated_decorators_1.py
|
{
"start": 454,
"end": 489
}
|
class ____:
x: array
@dataclass
|
D
|
python
|
spyder-ide__spyder
|
spyder/api/plugins/enum.py
|
{
"start": 1811,
"end": 1872
}
|
class ____:
EnvManager = "spyder_env_manager"
|
OptionalPlugins
|
python
|
tensorflow__tensorflow
|
tensorflow/python/kernel_tests/quantization_ops/quantization_ops_test.py
|
{
"start": 13138,
"end": 13685
}
|
class ____(test_util.TensorFlowTestCase):
@test_util.run_in_graph_and_eager_modes
def test_invalid_inputs(self):
inputs = constant_op.constant(
np.int8(0), shape=[3, 3, 3, 3], dtype=dtypes.quint8)
with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
"must be rank 0"):
self.evaluate(
nn_ops.quantized_relu(
features=inputs,
min_features=[],
max_features=127.0,
out_type=dtypes.quint8))
|
QuantizedReluOpTest
|
python
|
walkccc__LeetCode
|
solutions/3258. Count Substrings That Satisfy K-Constraint I/3258.py
|
{
"start": 0,
"end": 288
}
|
class ____:
def countKConstraintSubstrings(self, s: str, k: int) -> int:
ans = 0
count = [0, 0]
l = 0
for r, c in enumerate(s):
count[int(c)] += 1
while min(count) > k:
count[int(s[l])] -= 1
l += 1
ans += r - l + 1
return ans
|
Solution
|
python
|
django__django
|
tests/raw_query/models.py
|
{
"start": 31,
"end": 627
}
|
class ____(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
dob = models.DateField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Protect against annotations being passed to __init__ --
# this'll make the test suite get angry if annotations aren't
# treated differently than fields.
for k in kwargs:
assert k in [f.attname for f in self._meta.fields], (
"Author.__init__ got an unexpected parameter: %s" % k
)
|
Author
|
python
|
arrow-py__arrow
|
tests/test_locales.py
|
{
"start": 156261,
"end": 158624
}
|
class ____:
def test_describe(self):
assert self.locale.describe("now", only_distance=True) == "no nettopp"
assert self.locale.describe("now", only_distance=False) == "no nettopp"
def test_plurals(self):
assert self.locale._format_timeframe("now", 0) == "no nettopp"
assert self.locale._format_timeframe("second", 1) == "eitt sekund"
assert self.locale._format_timeframe("seconds", 30) == "30 sekund"
assert self.locale._format_timeframe("minute", 1) == "eitt minutt"
assert self.locale._format_timeframe("minutes", 40) == "40 minutt"
assert self.locale._format_timeframe("hour", 1) == "ein time"
assert self.locale._format_timeframe("hours", 23) == "23 timar"
assert self.locale._format_timeframe("day", 1) == "ein dag"
assert self.locale._format_timeframe("days", 12) == "12 dagar"
assert self.locale._format_timeframe("week", 1) == "ei veke"
assert self.locale._format_timeframe("weeks", 38) == "38 veker"
assert self.locale._format_timeframe("month", 1) == "ein månad"
assert self.locale._format_timeframe("months", 11) == "11 månader"
assert self.locale._format_timeframe("year", 1) == "eitt år"
assert self.locale._format_timeframe("years", 12) == "12 år"
def test_ordinal_number(self):
assert self.locale.ordinal_number(0) == "0."
assert self.locale.ordinal_number(1) == "1."
def test_format_timeframe(self):
assert self.locale._format_timeframe("hours", 2) == "2 timar"
assert self.locale._format_timeframe("hour", 0) == "ein time"
def test_format_relative_now(self):
result = self.locale._format_relative("no nettopp", "now", 0)
assert result == "no nettopp"
def test_format_relative_past(self):
result = self.locale._format_relative("ein time", "hour", 1)
assert result == "om ein time"
def test_format_relative_future(self):
result = self.locale._format_relative("ein time", "hour", -1)
assert result == "for ein time sidan"
def test_weekday(self):
dt = arrow.Arrow(2015, 4, 11, 17, 30, 00)
assert self.locale.day_name(dt.isoweekday()) == "laurdag"
assert self.locale.day_abbreviation(dt.isoweekday()) == "la"
@pytest.mark.usefixtures("lang_locale")
|
TestNewNorwegianLocale
|
python
|
pytorch__pytorch
|
torch/distributions/transforms.py
|
{
"start": 18767,
"end": 20225
}
|
class ____(Transform):
r"""
Transform via the mapping :math:`y = x^{\text{exponent}}`.
"""
domain = constraints.positive
codomain = constraints.positive
bijective = True
def __init__(self, exponent: Tensor, cache_size: int = 0) -> None:
super().__init__(cache_size=cache_size)
(self.exponent,) = broadcast_all(exponent)
def with_cache(self, cache_size=1):
if self._cache_size == cache_size:
return self
return PowerTransform(self.exponent, cache_size=cache_size)
@lazy_property
def sign(self) -> int: # type: ignore[override]
return self.exponent.sign() # type: ignore[return-value]
def __eq__(self, other):
if not isinstance(other, PowerTransform):
return False
return self.exponent.eq(other.exponent).all().item()
def _call(self, x):
return x.pow(self.exponent)
def _inverse(self, y):
return y.pow(1 / self.exponent)
def log_abs_det_jacobian(self, x, y):
return (self.exponent * y / x).abs().log()
def forward_shape(self, shape):
return torch.broadcast_shapes(shape, getattr(self.exponent, "shape", ()))
def inverse_shape(self, shape):
return torch.broadcast_shapes(shape, getattr(self.exponent, "shape", ()))
def _clipped_sigmoid(x):
finfo = torch.finfo(x.dtype)
return torch.clamp(torch.sigmoid(x), min=finfo.tiny, max=1.0 - finfo.eps)
|
PowerTransform
|
python
|
pytorch__pytorch
|
torch/testing/_internal/autograd_function_db.py
|
{
"start": 7644,
"end": 9113
}
|
class ____(torch.autograd.Function):
generate_vmap_rule = True
@staticmethod
def forward(x, dim):
ind = torch.argsort(x, dim=dim)
ind_inv = torch.argsort(ind, axis=dim)
result = torch.take_along_dim(x, ind, dim=dim)
return result, ind, ind_inv
@staticmethod
def setup_context(ctx, inputs, outputs):
x, dim = inputs
_, ind, ind_inv = outputs
ctx.mark_non_differentiable(ind, ind_inv)
ctx.save_for_backward(ind, ind_inv)
ctx.save_for_forward(ind, ind_inv)
ctx.dim = dim
@staticmethod
def backward(ctx, grad_output, _0, _1):
ind, ind_inv = ctx.saved_tensors
return TakeGenVmap.apply(grad_output, ind_inv, ind, ctx.dim), None
@staticmethod
def jvp(ctx, x_tangent, _):
ind, ind_inv = ctx.saved_tensors
return TakeGenVmap.apply(x_tangent, ind, ind_inv, ctx.dim), None, None
def sample_inputs_numpy_sort(opinfo, device, dtype, requires_grad, **kwargs):
make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
yield SampleInput(make_arg(3, 5), args=(1,))
def sample_inputs_numpy_take(opinfo, device, dtype, requires_grad, **kwargs):
make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
tensor = make_arg(3, 5)
dim = 1
_, ind, ind_inv = NumpySort.apply(tensor, 1)
yield SampleInput(tensor, args=(ind, ind_inv, dim))
|
SortGenVmap
|
python
|
huggingface__transformers
|
tests/models/dpr/test_modeling_dpr.py
|
{
"start": 6660,
"end": 9059
}
|
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(
DPRContextEncoder,
DPRQuestionEncoder,
DPRReader,
)
if is_torch_available()
else ()
)
pipeline_model_mapping = {"feature-extraction": DPRQuestionEncoder} if is_torch_available() else {}
test_resize_embeddings = False
test_missing_keys = False # why?
def setUp(self):
self.model_tester = DPRModelTester(self)
self.config_tester = ConfigTester(self, config_class=DPRConfig, hidden_size=37)
def test_config(self):
self.config_tester.run_common_tests()
def test_context_encoder_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_context_encoder(*config_and_inputs)
def test_question_encoder_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_question_encoder(*config_and_inputs)
def test_reader_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_reader(*config_and_inputs)
def test_init_changed_config(self):
config = self.model_tester.prepare_config_and_inputs()[0]
model = DPRQuestionEncoder(config=config)
model.to(torch_device)
model.eval()
with tempfile.TemporaryDirectory() as tmp_dirname:
model.save_pretrained(tmp_dirname)
model = DPRQuestionEncoder.from_pretrained(tmp_dirname, projection_dim=512)
self.assertIsNotNone(model)
@slow
def test_model_from_pretrained(self):
model_name = "facebook/dpr-ctx_encoder-single-nq-base"
model = DPRContextEncoder.from_pretrained(model_name)
self.assertIsNotNone(model)
model_name = "facebook/dpr-ctx_encoder-single-nq-base"
model = DPRContextEncoder.from_pretrained(model_name)
self.assertIsNotNone(model)
model_name = "facebook/dpr-ctx_encoder-single-nq-base"
model = DPRQuestionEncoder.from_pretrained(model_name)
self.assertIsNotNone(model)
model_name = "facebook/dpr-ctx_encoder-single-nq-base"
model = DPRReader.from_pretrained(model_name)
self.assertIsNotNone(model)
@require_torch
|
DPRModelTest
|
python
|
facelessuser__pymdown-extensions
|
tests/test_extensions/test_legacy_slugs.py
|
{
"start": 2513,
"end": 3080
}
|
class ____(util.MdCase):
"""Test GitHub Flavored Markdown style slugs."""
extension = ['markdown.extensions.toc']
extension_configs = {
'markdown.extensions.toc': {
"slugify": slugs.gfm
}
}
def test_slug(self):
"""Test the slug output."""
with pytest.warns(DeprecationWarning):
self.check_markdown(
r'# Testing GFM unicode-slugs_headers ±♠Ωℑ',
r'<h1 id="testing-gfm-unicode-slugs_headers-Ωℑ">Testing GFM unicode-slugs_headers ±♠Ωℑ</h1>'
)
|
TestGFM
|
python
|
tensorflow__tensorflow
|
tensorflow/python/keras/layers/advanced_activations.py
|
{
"start": 5826,
"end": 6926
}
|
class ____(Layer):
"""Exponential Linear Unit.
It follows:
```
f(x) = alpha * (exp(x) - 1.) for x < 0
f(x) = x for x >= 0
```
Input shape:
Arbitrary. Use the keyword argument `input_shape`
(tuple of integers, does not include the samples axis)
when using this layer as the first layer in a model.
Output shape:
Same shape as the input.
Args:
alpha: Scale for the negative factor.
"""
def __init__(self, alpha=1.0, **kwargs):
super(ELU, self).__init__(**kwargs)
if alpha is None:
raise ValueError('Alpha of an ELU layer cannot be None, '
'requires a float. Got %s' % alpha)
self.supports_masking = True
self.alpha = backend.cast_to_floatx(alpha)
def call(self, inputs):
return backend.elu(inputs, self.alpha)
def get_config(self):
config = {'alpha': float(self.alpha)}
base_config = super(ELU, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
@tf_utils.shape_type_conversion
def compute_output_shape(self, input_shape):
return input_shape
|
ELU
|
python
|
PrefectHQ__prefect
|
src/prefect/client/orchestration/_artifacts/client.py
|
{
"start": 1514,
"end": 4912
}
|
class ____(BaseClient):
def create_artifact(self, artifact: "ArtifactCreate") -> "Artifact":
response = self.request(
"POST",
"/artifacts/",
json=artifact.model_dump(mode="json", exclude_unset=True),
)
from prefect.client.schemas.objects import Artifact
from prefect.events.utilities import emit_event
created = Artifact.model_validate(response.json())
# Emit an event for artifact creation
resource = {
"prefect.resource.id": f"prefect.artifact.{created.id}",
}
if created.key:
resource["prefect.resource.name"] = created.key
payload = {
k: v
for k, v in {
"key": created.key,
"type": created.type,
"description": created.description,
}.items()
}
emit_event(
event="prefect.artifact.created",
resource=resource,
payload=payload,
)
return created
def update_artifact(self, artifact_id: "UUID", artifact: "ArtifactUpdate") -> None:
from prefect.events.utilities import emit_event
self.request(
"PATCH",
"/artifacts/{id}",
json=artifact.model_dump(mode="json", exclude_unset=True),
path_params={"id": artifact_id},
)
# Emit an event for artifact update
resource = {
"prefect.resource.id": f"prefect.artifact.{artifact_id}",
}
payload = artifact.model_dump(mode="json", exclude_unset=True)
emit_event(
event="prefect.artifact.updated",
resource=resource,
payload=payload,
)
return None
def delete_artifact(self, artifact_id: "UUID") -> None:
try:
self.request(
"DELETE",
"/artifacts/{id}",
path_params={"id": artifact_id},
)
except HTTPStatusError as e:
if e.response.status_code == 404:
raise ObjectNotFound(http_exc=e) from e
else:
raise
return None
def read_artifacts(
self, **kwargs: Unpack["ArtifactReadParams"]
) -> list["Artifact"]:
response = self.request(
"POST",
"/artifacts/filter",
json={
"artifacts": (
artifact_filter.model_dump(mode="json", exclude_unset=True)
if (artifact_filter := kwargs.get("artifact_filter"))
else None
),
"flow_runs": (
flow_run_filter.model_dump(mode="json", exclude_unset=True)
if (flow_run_filter := kwargs.get("flow_run_filter"))
else None
),
"task_runs": (
task_run_filter.model_dump(mode="json", exclude_unset=True)
if (task_run_filter := kwargs.get("task_run_filter"))
else None
),
"limit": kwargs.get("limit"),
"offset": kwargs.get("offset"),
"sort": kwargs.get("sort"),
},
)
from prefect.client.schemas.objects import Artifact
return Artifact.model_validate_list(response.json())
|
ArtifactClient
|
python
|
instagram__MonkeyType
|
monkeytype/stubs.py
|
{
"start": 17915,
"end": 19451
}
|
class ____(Stub):
def __init__(
self,
name: str,
signature: inspect.Signature,
kind: FunctionKind,
strip_modules: Optional[Iterable[str]] = None,
is_async: bool = False,
) -> None:
self.name = name
self.signature = signature
self.kind = kind
self.strip_modules = strip_modules or []
self.is_async = is_async
def render(self, prefix: str = "") -> str:
s = prefix
if self.is_async:
s += "async "
s += "def " + self.name
s += render_signature(self.signature, 120 - len(s), prefix) + ": ..."
# Yes, this is a horrible hack, but inspect.py gives us no way to
# specify the function that should be used to format annotations.
for module in self.strip_modules:
s = s.replace(module + ".", "")
if self.kind == FunctionKind.CLASS:
s = prefix + "@classmethod\n" + s
elif self.kind == FunctionKind.STATIC:
s = prefix + "@staticmethod\n" + s
elif self.kind == FunctionKind.PROPERTY:
s = prefix + "@property\n" + s
elif self.kind == FunctionKind.DJANGO_CACHED_PROPERTY:
s = prefix + "@cached_property\n" + s
return s
def __repr__(self) -> str:
return "FunctionStub(%s, %s, %s, %s, %s)" % (
repr(self.name),
repr(self.signature),
repr(self.kind),
repr(self.strip_modules),
self.is_async,
)
|
FunctionStub
|
python
|
pandas-dev__pandas
|
pandas/core/indexes/multi.py
|
{
"start": 3580,
"end": 3904
}
|
class ____(libindex.BaseMultiIndexCodesEngine, libindex.UInt8Engine):
"""Manages a MultiIndex by mapping label combinations to positive integers.
The number of possible label combinations must not overflow the 8 bits integers.
"""
_base = libindex.UInt8Engine
_codes_dtype = "uint8"
|
MultiIndexUInt8Engine
|
python
|
Lightning-AI__lightning
|
src/lightning/pytorch/core/mixins/hparams_mixin.py
|
{
"start": 1466,
"end": 6980
}
|
class ____:
__jit_unused_properties__: list[str] = ["hparams", "hparams_initial"]
def __init__(self) -> None:
super().__init__()
self._log_hyperparams = False
def save_hyperparameters(
self,
*args: Any,
ignore: Optional[Union[Sequence[str], str]] = None,
frame: Optional[types.FrameType] = None,
logger: bool = True,
) -> None:
"""Save arguments to ``hparams`` attribute.
Args:
args: single object of `dict`, `NameSpace` or `OmegaConf`
or string names or arguments from class ``__init__``
ignore: an argument name or a list of argument names from
class ``__init__`` to be ignored
frame: a frame object. Default is None
logger: Whether to send the hyperparameters to the logger. Default: True
Example::
>>> from lightning.pytorch.core.mixins import HyperparametersMixin
>>> class ManuallyArgsModel(HyperparametersMixin):
... def __init__(self, arg1, arg2, arg3):
... super().__init__()
... # manually assign arguments
... self.save_hyperparameters('arg1', 'arg3')
... def forward(self, *args, **kwargs):
... ...
>>> model = ManuallyArgsModel(1, 'abc', 3.14)
>>> model.hparams
"arg1": 1
"arg3": 3.14
>>> from lightning.pytorch.core.mixins import HyperparametersMixin
>>> class AutomaticArgsModel(HyperparametersMixin):
... def __init__(self, arg1, arg2, arg3):
... super().__init__()
... # equivalent automatic
... self.save_hyperparameters()
... def forward(self, *args, **kwargs):
... ...
>>> model = AutomaticArgsModel(1, 'abc', 3.14)
>>> model.hparams
"arg1": 1
"arg2": abc
"arg3": 3.14
>>> from lightning.pytorch.core.mixins import HyperparametersMixin
>>> class SingleArgModel(HyperparametersMixin):
... def __init__(self, params):
... super().__init__()
... # manually assign single argument
... self.save_hyperparameters(params)
... def forward(self, *args, **kwargs):
... ...
>>> model = SingleArgModel(Namespace(p1=1, p2='abc', p3=3.14))
>>> model.hparams
"p1": 1
"p2": abc
"p3": 3.14
>>> from lightning.pytorch.core.mixins import HyperparametersMixin
>>> class ManuallyArgsModel(HyperparametersMixin):
... def __init__(self, arg1, arg2, arg3):
... super().__init__()
... # pass argument(s) to ignore as a string or in a list
... self.save_hyperparameters(ignore='arg2')
... def forward(self, *args, **kwargs):
... ...
>>> model = ManuallyArgsModel(1, 'abc', 3.14)
>>> model.hparams
"arg1": 1
"arg3": 3.14
"""
self._log_hyperparams = logger
given_hparams = _given_hyperparameters.get()
# the frame needs to be created in this file.
if given_hparams is None and not frame:
current_frame = inspect.currentframe()
if current_frame:
frame = current_frame.f_back
save_hyperparameters(self, *args, ignore=ignore, frame=frame, given_hparams=given_hparams)
def _set_hparams(self, hp: Union[MutableMapping, Namespace, str]) -> None:
hp = self._to_hparams_dict(hp)
if isinstance(hp, dict) and isinstance(self.hparams, dict):
self.hparams.update(hp)
else:
self._hparams = hp
@staticmethod
def _to_hparams_dict(hp: Union[MutableMapping, Namespace, str]) -> Union[MutableMapping, AttributeDict]:
if isinstance(hp, Namespace):
hp = vars(hp)
if isinstance(hp, dict):
hp = AttributeDict(hp)
elif isinstance(hp, _PRIMITIVE_TYPES):
raise ValueError(f"Primitives {_PRIMITIVE_TYPES} are not allowed.")
elif not isinstance(hp, _ALLOWED_CONFIG_TYPES):
raise ValueError(f"Unsupported config type of {type(hp)}.")
return hp
@property
def hparams(self) -> Union[AttributeDict, MutableMapping]:
"""The collection of hyperparameters saved with :meth:`save_hyperparameters`. It is mutable by the user. For
the frozen set of initial hyperparameters, use :attr:`hparams_initial`.
Returns:
Mutable hyperparameters dictionary
"""
if not hasattr(self, "_hparams"):
self._hparams = AttributeDict()
return self._hparams
@property
def hparams_initial(self) -> AttributeDict:
"""The collection of hyperparameters saved with :meth:`save_hyperparameters`. These contents are read-only.
Manual updates to the saved hyperparameters can instead be performed through :attr:`hparams`.
Returns:
AttributeDict: immutable initial hyperparameters
"""
if not hasattr(self, "_hparams_initial"):
return AttributeDict()
# prevent any change
return copy.deepcopy(self._hparams_initial)
|
HyperparametersMixin
|
python
|
doocs__leetcode
|
solution/0600-0699/0650.2 Keys Keyboard/Solution2.py
|
{
"start": 0,
"end": 318
}
|
class ____:
def minSteps(self, n: int) -> int:
dp = list(range(n + 1))
dp[1] = 0
for i in range(2, n + 1):
j = 2
while j * j <= i:
if i % j == 0:
dp[i] = min(dp[i], dp[i // j] + j)
j += 1
return dp[-1]
|
Solution
|
python
|
doocs__leetcode
|
lcci/05.02.Binary Number to String/Solution.py
|
{
"start": 0,
"end": 247
}
|
class ____:
def printBin(self, num: float) -> str:
ans = '0.'
while len(ans) < 32 and num:
num *= 2
x = int(num)
ans += str(x)
num -= x
return 'ERROR' if num else ans
|
Solution
|
python
|
pytorch__pytorch
|
test/test_multiprocessing_spawn.py
|
{
"start": 9929,
"end": 10158
}
|
class ____:
SLEEP_SECS = 5
# Simulate startup overhead such as large imports
time.sleep(SLEEP_SECS)
def __init__(self):
self.config: str = "*" * 1000000
def my_call(self, *args):
pass
|
Expensive
|
python
|
astropy__astropy
|
astropy/io/votable/exceptions.py
|
{
"start": 49618,
"end": 49836
}
|
class ____(VOTableSpecWarning):
"""
A VOTable cannot have a DATA section without any defined FIELD; DATA will be ignored.
"""
message_template = "No FIELDs are defined; DATA section will be ignored."
|
E25
|
python
|
dagster-io__dagster
|
python_modules/dagster-graphql/dagster_graphql/schema/metadata.py
|
{
"start": 1476,
"end": 1719
}
|
class ____(graphene.ObjectType):
lineage = non_null_list(GrapheneTableColumnLineageEntry)
class Meta:
interfaces = (GrapheneMetadataEntry,)
name = "TableColumnLineageMetadataEntry"
|
GrapheneTableColumnLineageMetadataEntry
|
python
|
getsentry__sentry
|
tests/sentry/workflow_engine/test_integration.py
|
{
"start": 20386,
"end": 21651
}
|
class ____(BaseWorkflowIntegrationTest):
@override_options({"workflow_engine.issue_alert.group.type_id.rollout": [6001]})
@with_feature("organizations:workflow-engine-single-process-workflows")
def test_workflow_engine(self) -> None:
occurrence_data = self.build_occurrence_data(
type=FeedbackGroup.type_id,
event_id=self.event.event_id,
project_id=self.project.id,
evidence_data={
"contact_email": "test@test.com",
"message": "test",
"name": "Name Test",
"source": "new_feedback_envelope",
"summary": "test",
},
)
self.occurrence, group_info = save_issue_occurrence(occurrence_data, self.event)
assert group_info is not None
self.group = Group.objects.get(grouphash__hash=self.occurrence.fingerprint[0])
assert self.group.type == FeedbackGroup.type_id
with mock.patch(
"sentry.workflow_engine.tasks.workflows.process_workflows_event.apply_async"
) as mock_process_workflow:
self.call_post_process_group(self.group.id)
mock_process_workflow.assert_called_once()
|
TestWorkflowEngineIntegrationFromFeedbackPostProcess
|
python
|
hynek__structlog
|
src/structlog/twisted.py
|
{
"start": 3564,
"end": 4224
}
|
class ____:
"""
Wrap a string and return it as the ``__repr__``.
This is needed for ``twisted.python.log.err`` that calls `repr` on
``_stuff``:
>>> repr("foo")
"'foo'"
>>> repr(ReprWrapper("foo"))
'foo'
Note the extra quotes in the unwrapped example.
"""
def __init__(self, string: str) -> None:
self.string = string
def __eq__(self, other: object) -> bool:
"""
Check for equality, just for tests.
"""
return (
isinstance(other, self.__class__) and self.string == other.string
)
def __repr__(self) -> str:
return self.string
|
ReprWrapper
|
python
|
plotly__plotly.py
|
plotly/graph_objs/splom/_legendgrouptitle.py
|
{
"start": 233,
"end": 2925
}
|
class ____(_BaseTraceHierarchyType):
_parent_path_str = "splom"
_path_str = "splom.legendgrouptitle"
_valid_props = {"font", "text"}
@property
def font(self):
"""
Sets this legend group's title font.
The 'font' property is an instance of Font
that may be specified as:
- An instance of :class:`plotly.graph_objs.splom.legendgrouptitle.Font`
- A dict of string/value properties that will be passed
to the Font constructor
Returns
-------
plotly.graph_objs.splom.legendgrouptitle.Font
"""
return self["font"]
@font.setter
def font(self, val):
self["font"] = val
@property
def text(self):
"""
Sets the title of the legend group.
The 'text' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["text"]
@text.setter
def text(self, val):
self["text"] = val
@property
def _prop_descriptions(self):
return """\
font
Sets this legend group's title font.
text
Sets the title of the legend group.
"""
def __init__(self, arg=None, font=None, text=None, **kwargs):
"""
Construct a new Legendgrouptitle object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.splom.Legendgrouptitle`
font
Sets this legend group's title font.
text
Sets the title of the legend group.
Returns
-------
Legendgrouptitle
"""
super().__init__("legendgrouptitle")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.splom.Legendgrouptitle
constructor must be a dict or
an instance of :class:`plotly.graph_objs.splom.Legendgrouptitle`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("font", arg, font)
self._set_property("text", arg, text)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
|
Legendgrouptitle
|
python
|
tiangolo__fastapi
|
fastapi/params.py
|
{
"start": 10929,
"end": 14078
}
|
class ____(Param): # type: ignore[misc]
in_ = ParamTypes.header
def __init__(
self,
default: Any = Undefined,
*,
default_factory: Union[Callable[[], Any], None] = _Unset,
annotation: Optional[Any] = None,
alias: Optional[str] = None,
alias_priority: Union[int, None] = _Unset,
# TODO: update when deprecating Pydantic v1, import these types
# validation_alias: str | AliasPath | AliasChoices | None
validation_alias: Union[str, None] = None,
serialization_alias: Union[str, None] = None,
convert_underscores: bool = True,
title: Optional[str] = None,
description: Optional[str] = None,
gt: Optional[float] = None,
ge: Optional[float] = None,
lt: Optional[float] = None,
le: Optional[float] = None,
min_length: Optional[int] = None,
max_length: Optional[int] = None,
pattern: Optional[str] = None,
regex: Annotated[
Optional[str],
deprecated(
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
),
] = None,
discriminator: Union[str, None] = None,
strict: Union[bool, None] = _Unset,
multiple_of: Union[float, None] = _Unset,
allow_inf_nan: Union[bool, None] = _Unset,
max_digits: Union[int, None] = _Unset,
decimal_places: Union[int, None] = _Unset,
examples: Optional[List[Any]] = None,
example: Annotated[
Optional[Any],
deprecated(
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
"although still supported. Use examples instead."
),
] = _Unset,
openapi_examples: Optional[Dict[str, Example]] = None,
deprecated: Union[deprecated, str, bool, None] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], None] = None,
**extra: Any,
):
self.convert_underscores = convert_underscores
super().__init__(
default=default,
default_factory=default_factory,
annotation=annotation,
alias=alias,
alias_priority=alias_priority,
validation_alias=validation_alias,
serialization_alias=serialization_alias,
title=title,
description=description,
gt=gt,
ge=ge,
lt=lt,
le=le,
min_length=min_length,
max_length=max_length,
pattern=pattern,
regex=regex,
discriminator=discriminator,
strict=strict,
multiple_of=multiple_of,
allow_inf_nan=allow_inf_nan,
max_digits=max_digits,
decimal_places=decimal_places,
deprecated=deprecated,
example=example,
examples=examples,
openapi_examples=openapi_examples,
include_in_schema=include_in_schema,
json_schema_extra=json_schema_extra,
**extra,
)
|
Header
|
python
|
Unity-Technologies__ml-agents
|
ml-agents/mlagents/trainers/training_status.py
|
{
"start": 1709,
"end": 4323
}
|
class ____:
"""
GlobalTrainingStatus class that contains static methods to save global training status and
load it on a resume. These are values that might be needed for the training resume that
cannot/should not be captured in a model checkpoint, such as curriclum lesson.
"""
saved_state: Dict[str, Dict[str, Any]] = defaultdict(lambda: {})
@staticmethod
def load_state(path: str) -> None:
"""
Load a JSON file that contains saved state.
:param path: Path to the JSON file containing the state.
"""
try:
with open(path) as f:
loaded_dict = json.load(f)
# Compare the metadata
_metadata = loaded_dict[StatusType.STATS_METADATA.value]
StatusMetaData.from_dict(_metadata).check_compatibility(StatusMetaData())
# Update saved state.
GlobalTrainingStatus.saved_state.update(loaded_dict)
except FileNotFoundError:
logger.warning(
"Training status file not found. Not all functions will resume properly."
)
except KeyError:
raise TrainerError(
"Metadata not found, resuming from an incompatible version of ML-Agents."
)
@staticmethod
def save_state(path: str) -> None:
"""
Save a JSON file that contains saved state.
:param path: Path to the JSON file containing the state.
"""
GlobalTrainingStatus.saved_state[
StatusType.STATS_METADATA.value
] = StatusMetaData().to_dict()
with open(path, "w") as f:
json.dump(GlobalTrainingStatus.saved_state, f, indent=4)
@staticmethod
def set_parameter_state(category: str, key: StatusType, value: Any) -> None:
"""
Stores an arbitrary-named parameter in the global saved state.
:param category: The category (usually behavior name) of the parameter.
:param key: The parameter, e.g. lesson number.
:param value: The value.
"""
GlobalTrainingStatus.saved_state[category][key.value] = value
@staticmethod
def get_parameter_state(category: str, key: StatusType) -> Any:
"""
Loads an arbitrary-named parameter from training_status.json.
If not found, returns None.
:param category: The category (usually behavior name) of the parameter.
:param key: The statistic, e.g. lesson number.
:param value: The value.
"""
return GlobalTrainingStatus.saved_state[category].get(key.value, None)
|
GlobalTrainingStatus
|
python
|
pydata__xarray
|
asv_bench/benchmarks/dataset_io.py
|
{
"start": 10696,
"end": 11284
}
|
class ____(IOMultipleNetCDF):
def setup(self):
# TODO: Lazily skipped in CI as it is very demanding and slow.
# Improve times and remove errors.
_skip_slow()
requires_dask()
self.make_ds()
self.format = "NETCDF4"
xr.save_mfdataset(self.ds_list, self.filenames_list, format=self.format)
def time_load_dataset_netcdf4(self):
xr.open_mfdataset(self.filenames_list, engine="netcdf4").load()
def time_open_dataset_netcdf4(self):
xr.open_mfdataset(self.filenames_list, engine="netcdf4")
|
IOReadMultipleNetCDF4
|
python
|
django__django
|
tests/queries/tests.py
|
{
"start": 77630,
"end": 77767
}
|
class ____(TestCase):
def test_ticket7371(self):
self.assertQuerySetEqual(Related.objects.order_by("custom"), [])
|
CustomPkTests
|
python
|
tornadoweb__tornado
|
tornado/test/curl_httpclient_test.py
|
{
"start": 2495,
"end": 2671
}
|
class ____(RequestHandler):
def get(self):
self.set_status(400, "Custom reason")
@unittest.skipIf(pycurl is None, "pycurl module not present")
|
CustomFailReasonHandler
|
python
|
sympy__sympy
|
sympy/stats/joint_rv.py
|
{
"start": 10602,
"end": 12655
}
|
class ____(Distribution, NamedArgsMixin):
"""
Represented by the random variables part of the joint distribution.
Contains methods for PDF, CDF, sampling, marginal densities, etc.
"""
_argnames = ('pdf', )
def __new__(cls, *args):
args = list(map(sympify, args))
for i in range(len(args)):
if isinstance(args[i], list):
args[i] = ImmutableMatrix(args[i])
return Basic.__new__(cls, *args)
@property
def domain(self):
return ProductDomain(self.symbols)
@property
def pdf(self):
return self.density.args[1]
def cdf(self, other):
if not isinstance(other, dict):
raise ValueError("%s should be of type dict, got %s"%(other, type(other)))
rvs = other.keys()
_set = self.domain.set.sets
expr = self.pdf(tuple(i.args[0] for i in self.symbols))
for i in range(len(other)):
if rvs[i].is_Continuous:
density = Integral(expr, (rvs[i], _set[i].inf,
other[rvs[i]]))
elif rvs[i].is_Discrete:
density = Sum(expr, (rvs[i], _set[i].inf,
other[rvs[i]]))
return density
def sample(self, size=(), library='scipy', seed=None):
""" A random realization from the distribution """
libraries = ('scipy', 'numpy', 'pymc3', 'pymc')
if library not in libraries:
raise NotImplementedError("Sampling from %s is not supported yet."
% str(library))
if not import_module(library):
raise ValueError("Failed to import %s" % library)
samps = _get_sample_class_jrv[library](self, size, seed=seed)
if samps is not None:
return samps
raise NotImplementedError(
"Sampling for %s is not currently implemented from %s"
% (self.__class__.__name__, library)
)
def __call__(self, *args):
return self.pdf(*args)
|
JointDistribution
|
python
|
getsentry__sentry
|
src/sentry/new_migrations/monkey/special.py
|
{
"start": 94,
"end": 1263
}
|
class ____(RunSQL):
def __init__(self, *args, use_statement_timeout=True, **kwargs):
super().__init__(*args, **kwargs)
self.use_statement_timeout = use_statement_timeout
def _run_sql(self, schema_editor, sqls):
use_statement_timeout = (
settings.ZERO_DOWNTIME_MIGRATIONS_STATEMENT_TIMEOUT is not None
and self.use_statement_timeout
)
use_lock_timeout = settings.ZERO_DOWNTIME_MIGRATIONS_LOCK_TIMEOUT is not None
if use_statement_timeout:
schema_editor.execute(
"SET statement_timeout TO %s;",
params=(settings.ZERO_DOWNTIME_MIGRATIONS_STATEMENT_TIMEOUT,),
)
if use_lock_timeout:
schema_editor.execute(
"SET lock_timeout TO %s;", params=(settings.ZERO_DOWNTIME_MIGRATIONS_LOCK_TIMEOUT,)
)
super()._run_sql(schema_editor, sqls) # type: ignore[misc]
if use_lock_timeout:
schema_editor.execute("SET lock_timeout TO '0ms';", params=None)
if use_statement_timeout:
schema_editor.execute("SET statement_timeout TO '0ms';", params=None)
|
SafeRunSQL
|
python
|
lepture__authlib
|
authlib/integrations/base_client/sync_app.py
|
{
"start": 2560,
"end": 3938
}
|
class ____:
client_cls = None
def __init__(
self,
framework,
name=None,
fetch_token=None,
client_id=None,
client_secret=None,
request_token_url=None,
request_token_params=None,
access_token_url=None,
access_token_params=None,
authorize_url=None,
authorize_params=None,
api_base_url=None,
client_kwargs=None,
user_agent=None,
**kwargs,
):
self.framework = framework
self.name = name
self.client_id = client_id
self.client_secret = client_secret
self.request_token_url = request_token_url
self.request_token_params = request_token_params
self.access_token_url = access_token_url
self.access_token_params = access_token_params
self.authorize_url = authorize_url
self.authorize_params = authorize_params
self.api_base_url = api_base_url
self.client_kwargs = client_kwargs or {}
self._fetch_token = fetch_token
self._user_agent = user_agent or default_user_agent
self._kwargs = kwargs
def _get_oauth_client(self):
session = self.client_cls(
self.client_id, self.client_secret, **self.client_kwargs
)
session.headers["User-Agent"] = self._user_agent
return session
|
OAuth1Base
|
python
|
fastai__fastai
|
fastai/learner.py
|
{
"start": 3426,
"end": 3618
}
|
class ____():
"Returns a function that returns `o`"
def __init__(self, o): self.o = o
def __call__(self, *args, **kwargs): return self.o
# %% ../nbs/13a_learner.ipynb 22
|
_ConstantFunc
|
python
|
PrefectHQ__prefect
|
tests/cli/transfer/test_work_pools.py
|
{
"start": 464,
"end": 23380
}
|
class ____:
async def test_construct_creates_new_instance_and_reads_default_queue(
self, transfer_work_pool: WorkPool
):
"""Test that construct creates a new MigratableWorkPool instance and reads default queue."""
# Clear any existing instances
MigratableWorkPool._instances.clear()
# Mock the client to return a default queue
with patch(
"prefect.cli.transfer._migratable_resources.work_pools.get_client"
) as mock_get_client:
mock_client = AsyncMock()
mock_get_client.return_value.__aenter__.return_value = mock_client
# Mock default queue
default_queue = WorkQueue(
id=transfer_work_pool.default_queue_id,
name="default",
description="Default queue",
priority=1,
concurrency_limit=None,
filter=None,
is_paused=False,
last_polled=None,
status=None,
work_pool_id=transfer_work_pool.id,
)
mock_client.read_work_queue.return_value = default_queue
migratable = await MigratableWorkPool.construct(transfer_work_pool)
assert isinstance(migratable, MigratableWorkPool)
assert migratable.source_work_pool == transfer_work_pool
assert migratable.source_default_queue == default_queue
assert migratable.source_id == transfer_work_pool.id
assert migratable.destination_work_pool is None
assert migratable.destination_id is None
assert migratable._dependencies == []
mock_client.read_work_queue.assert_called_once_with(
transfer_work_pool.default_queue_id
)
async def test_construct_returns_cached_instance(
self, transfer_work_pool: WorkPool
):
"""Test that construct returns cached instance for same ID."""
# Clear any existing instances
MigratableWorkPool._instances.clear()
# Mock the client for both calls
with patch(
"prefect.cli.transfer._migratable_resources.work_pools.get_client"
) as mock_get_client:
mock_client = AsyncMock()
mock_get_client.return_value.__aenter__.return_value = mock_client
# Mock default queue
default_queue = WorkQueue(
id=transfer_work_pool.default_queue_id,
name="default",
description="Default queue",
priority=1,
concurrency_limit=None,
filter=None,
is_paused=False,
last_polled=None,
status=None,
work_pool_id=transfer_work_pool.id,
)
mock_client.read_work_queue.return_value = default_queue
# Create first instance
migratable1 = await MigratableWorkPool.construct(transfer_work_pool)
# Create second instance with same work pool
migratable2 = await MigratableWorkPool.construct(transfer_work_pool)
# Should be the same instance
assert migratable1 is migratable2
assert len(MigratableWorkPool._instances) == 1
# Client should only be called once due to caching
mock_client.read_work_queue.assert_called_once()
async def test_get_instance_returns_cached_instance(
self, transfer_work_pool: WorkPool
):
"""Test that get_instance returns cached instance."""
# Clear any existing instances
MigratableWorkPool._instances.clear()
# Mock the client
with patch(
"prefect.cli.transfer._migratable_resources.work_pools.get_client"
) as mock_get_client:
mock_client = AsyncMock()
mock_get_client.return_value.__aenter__.return_value = mock_client
default_queue = WorkQueue(
id=transfer_work_pool.default_queue_id,
name="default",
description="Default queue",
priority=1,
concurrency_limit=None,
filter=None,
is_paused=False,
last_polled=None,
status=None,
work_pool_id=transfer_work_pool.id,
)
mock_client.read_work_queue.return_value = default_queue
# Create instance
migratable = await MigratableWorkPool.construct(transfer_work_pool)
# Retrieve instance
retrieved = await MigratableWorkPool.get_instance(transfer_work_pool.id)
assert retrieved is migratable
async def test_get_instance_returns_none_for_unknown_id(self):
"""Test that get_instance returns None for unknown ID."""
# Clear any existing instances
MigratableWorkPool._instances.clear()
unknown_id = uuid.uuid4()
retrieved = await MigratableWorkPool.get_instance(unknown_id)
assert retrieved is None
async def test_get_instance_by_name_returns_instance(
self, transfer_work_pool: WorkPool
):
"""Test that get_instance_by_name returns cached instance."""
# Clear any existing instances
MigratableWorkPool._instances.clear()
# Mock the client
with patch(
"prefect.cli.transfer._migratable_resources.work_pools.get_client"
) as mock_get_client:
mock_client = AsyncMock()
mock_get_client.return_value.__aenter__.return_value = mock_client
default_queue = WorkQueue(
id=transfer_work_pool.default_queue_id,
name="default",
description="Default queue",
priority=1,
concurrency_limit=None,
filter=None,
is_paused=False,
last_polled=None,
status=None,
work_pool_id=transfer_work_pool.id,
)
mock_client.read_work_queue.return_value = default_queue
# Create instance
migratable = await MigratableWorkPool.construct(transfer_work_pool)
# Retrieve instance by name
retrieved = await MigratableWorkPool.get_instance_by_name(
transfer_work_pool.name
)
assert retrieved is migratable
async def test_get_instance_by_name_returns_none_for_unknown_name(self):
"""Test that get_instance_by_name returns None for unknown name."""
# Clear any existing instances
MigratableWorkPool._instances.clear()
retrieved = await MigratableWorkPool.get_instance_by_name("unknown-work-pool")
assert retrieved is None
@patch(
"prefect.cli.transfer._migratable_resources.work_pools.construct_migratable_resource"
)
@patch("prefect.cli.transfer._migratable_resources.work_pools.get_client")
async def test_get_dependencies_with_result_storage_block(
self, mock_get_client: MagicMock, mock_construct_resource: AsyncMock
):
"""Test get_dependencies with result storage block dependency."""
from prefect.client.schemas.objects import WorkPoolStorageConfiguration
# Create work pool with result storage block
storage_block_id = uuid.uuid4()
work_pool = WorkPool(
id=uuid.uuid4(),
name="test-work-pool",
type="test-type",
base_job_template={},
is_paused=False,
concurrency_limit=None,
storage_configuration=WorkPoolStorageConfiguration(
default_result_storage_block_id=storage_block_id
),
default_queue_id=uuid.uuid4(),
)
# Mock the client for construct
mock_client = AsyncMock()
mock_get_client.return_value.__aenter__.return_value = mock_client
default_queue = WorkQueue(
id=work_pool.default_queue_id,
name="default",
description="Default queue",
priority=1,
concurrency_limit=None,
filter=None,
is_paused=False,
last_polled=None,
status=None,
work_pool_id=work_pool.id,
)
# Mock for construct call
mock_client.read_work_queue.return_value = default_queue
# Mock for get_dependencies call
mock_block_document = MagicMock()
mock_block_document.id = storage_block_id
mock_client.read_block_document.return_value = mock_block_document
mock_migratable_block = MagicMock()
mock_construct_resource.return_value = mock_migratable_block
# Clear instances
MigratableWorkPool._instances.clear()
migratable = await MigratableWorkPool.construct(work_pool)
dependencies = await migratable.get_dependencies()
assert len(dependencies) == 1
assert dependencies[0] == mock_migratable_block
mock_client.read_block_document.assert_called_once_with(storage_block_id)
mock_construct_resource.assert_called_once_with(mock_block_document)
async def test_get_dependencies_with_no_storage_configuration(
self, transfer_work_pool: WorkPool
):
"""Test get_dependencies with no storage configuration dependencies."""
# Mock the client
with patch(
"prefect.cli.transfer._migratable_resources.work_pools.get_client"
) as mock_get_client:
mock_client = AsyncMock()
mock_get_client.return_value.__aenter__.return_value = mock_client
default_queue = WorkQueue(
id=transfer_work_pool.default_queue_id,
name="default",
description="Default queue",
priority=1,
concurrency_limit=None,
filter=None,
is_paused=False,
last_polled=None,
status=None,
work_pool_id=transfer_work_pool.id,
)
mock_client.read_work_queue.return_value = default_queue
# Clear instances
MigratableWorkPool._instances.clear()
migratable = await MigratableWorkPool.construct(transfer_work_pool)
dependencies = await migratable.get_dependencies()
assert dependencies == []
async def test_get_dependencies_cached(self, transfer_work_pool: WorkPool):
"""Test that dependencies are cached after first call."""
# Mock the client
with patch(
"prefect.cli.transfer._migratable_resources.work_pools.get_client"
) as mock_get_client:
mock_client = AsyncMock()
mock_get_client.return_value.__aenter__.return_value = mock_client
default_queue = WorkQueue(
id=transfer_work_pool.default_queue_id,
name="default",
description="Default queue",
priority=1,
concurrency_limit=None,
filter=None,
is_paused=False,
last_polled=None,
status=None,
work_pool_id=transfer_work_pool.id,
)
mock_client.read_work_queue.return_value = default_queue
# Clear instances
MigratableWorkPool._instances.clear()
migratable = await MigratableWorkPool.construct(transfer_work_pool)
# Set up some mock dependencies
mock_dependency = MagicMock()
migratable._dependencies = [mock_dependency]
dependencies1 = await migratable.get_dependencies()
dependencies2 = await migratable.get_dependencies()
# Should return the same cached result
assert dependencies1 == dependencies2
assert dependencies1 == [mock_dependency]
@patch("prefect.cli.transfer._migratable_resources.work_pools.get_client")
async def test_migrate_success_regular_pool(
self, mock_get_client: MagicMock, transfer_work_pool: WorkPool
):
"""Test successful migration of regular work pool."""
# Mock the client for construct
mock_client = AsyncMock()
mock_get_client.return_value.__aenter__.return_value = mock_client
default_queue = WorkQueue(
id=transfer_work_pool.default_queue_id,
name="default",
description="Default queue",
priority=1,
concurrency_limit=None,
is_paused=False,
last_polled=None,
status=None,
work_pool_id=transfer_work_pool.id,
)
mock_client.read_work_queue.return_value = default_queue
# Mock successful work pool creation
destination_work_pool = WorkPool(
id=uuid.uuid4(),
name=transfer_work_pool.name,
type=transfer_work_pool.type,
base_job_template=transfer_work_pool.base_job_template,
is_paused=transfer_work_pool.is_paused,
concurrency_limit=transfer_work_pool.concurrency_limit,
storage_configuration=transfer_work_pool.storage_configuration,
default_queue_id=uuid.uuid4(),
)
mock_client.create_work_pool.return_value = destination_work_pool
# Clear instances
MigratableWorkPool._instances.clear()
migratable = await MigratableWorkPool.construct(transfer_work_pool)
await migratable.migrate()
# Verify client calls
mock_client.create_work_pool.assert_called_once_with(
work_pool=WorkPoolCreate(
name=transfer_work_pool.name,
type=transfer_work_pool.type,
base_job_template=transfer_work_pool.base_job_template,
is_paused=transfer_work_pool.is_paused,
concurrency_limit=transfer_work_pool.concurrency_limit,
storage_configuration=transfer_work_pool.storage_configuration,
)
)
mock_client.update_work_queue.assert_called_once_with(
id=destination_work_pool.default_queue_id,
description=default_queue.description,
priority=default_queue.priority,
concurrency_limit=default_queue.concurrency_limit,
)
# Verify destination_work_pool is set
assert migratable.destination_work_pool == destination_work_pool
assert migratable.destination_id == destination_work_pool.id
@patch("prefect.cli.transfer._migratable_resources.work_pools.get_client")
async def test_migrate_managed_pool_skipped(
self, mock_get_client: MagicMock, transfer_managed_work_pool: WorkPool
):
"""Test that managed pools are skipped."""
# Mock the client for construct
mock_client = AsyncMock()
mock_get_client.return_value.__aenter__.return_value = mock_client
default_queue = WorkQueue(
id=transfer_managed_work_pool.default_queue_id,
name="default",
description="Default queue",
priority=1,
concurrency_limit=None,
filter=None,
is_paused=False,
last_polled=None,
status=None,
work_pool_id=transfer_managed_work_pool.id,
)
mock_client.read_work_queue.return_value = default_queue
# Clear instances
MigratableWorkPool._instances.clear()
migratable = await MigratableWorkPool.construct(transfer_managed_work_pool)
# Should raise TransferSkipped
with pytest.raises(TransferSkipped, match="Skipped managed pool"):
await migratable.migrate()
# Should not try to create work pool
mock_client.create_work_pool.assert_not_called()
@patch("prefect.cli.transfer._migratable_resources.work_pools.get_client")
async def test_migrate_push_pool_with_cloud_server(
self, mock_get_client: MagicMock, transfer_push_work_pool: WorkPool
):
"""Test that push pools work with cloud server."""
# Mock the client for construct
mock_client = AsyncMock()
mock_get_client.return_value.__aenter__.return_value = mock_client
mock_client.server_type = ServerType.CLOUD # Set server type to cloud
default_queue = WorkQueue(
id=transfer_push_work_pool.default_queue_id,
name="default",
description="Default queue",
priority=1,
concurrency_limit=None,
is_paused=False,
last_polled=None,
status=None,
work_pool_id=transfer_push_work_pool.id,
)
mock_client.read_work_queue.return_value = default_queue
# Mock successful work pool creation
destination_work_pool = WorkPool(
id=uuid.uuid4(),
name=transfer_push_work_pool.name,
type=transfer_push_work_pool.type,
base_job_template=transfer_push_work_pool.base_job_template,
is_paused=transfer_push_work_pool.is_paused,
concurrency_limit=transfer_push_work_pool.concurrency_limit,
storage_configuration=transfer_push_work_pool.storage_configuration,
default_queue_id=uuid.uuid4(),
)
mock_client.create_work_pool.return_value = destination_work_pool
# Clear instances
MigratableWorkPool._instances.clear()
migratable = await MigratableWorkPool.construct(transfer_push_work_pool)
await migratable.migrate()
# Should successfully create work pool
mock_client.create_work_pool.assert_called_once()
assert migratable.destination_work_pool == destination_work_pool
@patch("prefect.cli.transfer._migratable_resources.work_pools.get_client")
async def test_migrate_push_pool_without_cloud_server_skipped(
self, mock_get_client: MagicMock, transfer_push_work_pool: WorkPool
):
"""Test that push pools are skipped without cloud server."""
# Mock the client for construct
mock_client = AsyncMock()
mock_get_client.return_value.__aenter__.return_value = mock_client
mock_client.server_type = ServerType.EPHEMERAL # Set server type to non-cloud
default_queue = WorkQueue(
id=transfer_push_work_pool.default_queue_id,
name="default",
description="Default queue",
priority=1,
concurrency_limit=None,
filter=None,
is_paused=False,
last_polled=None,
status=None,
work_pool_id=transfer_push_work_pool.id,
)
mock_client.read_work_queue.return_value = default_queue
# Clear instances
MigratableWorkPool._instances.clear()
migratable = await MigratableWorkPool.construct(transfer_push_work_pool)
# Should raise TransferSkipped
with pytest.raises(TransferSkipped, match="Skipped push pool"):
await migratable.migrate()
# Should not try to create work pool
mock_client.create_work_pool.assert_not_called()
@patch("prefect.cli.transfer._migratable_resources.work_pools.get_client")
async def test_migrate_unsupported_work_pool_skipped(
self, mock_get_client: MagicMock, transfer_work_pool: WorkPool
):
"""Test that unsupported work pools are skipped."""
# Mock the client for construct
mock_client = AsyncMock()
mock_get_client.return_value.__aenter__.return_value = mock_client
default_queue = WorkQueue(
id=transfer_work_pool.default_queue_id,
name="default",
description="Default queue",
priority=1,
concurrency_limit=None,
filter=None,
is_paused=False,
last_polled=None,
status=None,
work_pool_id=transfer_work_pool.id,
)
mock_client.read_work_queue.return_value = default_queue
# Mock ObjectUnsupported exception on create
mock_client.create_work_pool.side_effect = ObjectUnsupported("Unsupported")
# Clear instances
MigratableWorkPool._instances.clear()
migratable = await MigratableWorkPool.construct(transfer_work_pool)
# Should raise TransferSkipped
with pytest.raises(
TransferSkipped, match="Destination requires Standard/Pro tier"
):
await migratable.migrate()
# Verify client calls
mock_client.create_work_pool.assert_called_once()
@patch("prefect.cli.transfer._migratable_resources.work_pools.get_client")
async def test_migrate_already_exists(
self, mock_get_client: MagicMock, transfer_work_pool: WorkPool
):
"""Test migration when work pool already exists."""
# Mock the client for construct
mock_client = AsyncMock()
mock_get_client.return_value.__aenter__.return_value = mock_client
default_queue = WorkQueue(
id=transfer_work_pool.default_queue_id,
name="default",
description="Default queue",
priority=1,
concurrency_limit=None,
filter=None,
is_paused=False,
last_polled=None,
status=None,
work_pool_id=transfer_work_pool.id,
)
mock_client.read_work_queue.return_value = default_queue
# Mock ObjectAlreadyExists exception on create
mock_http_exc = Exception("Conflict")
mock_client.create_work_pool.side_effect = ObjectAlreadyExists(mock_http_exc)
# Mock successful read of existing work pool
existing_work_pool = WorkPool(
id=uuid.uuid4(),
name=transfer_work_pool.name,
type="existing-type", # Different to show it reads existing
base_job_template={"existing": "template"},
is_paused=True,
concurrency_limit=10,
storage_configuration=transfer_work_pool.storage_configuration,
default_queue_id=uuid.uuid4(),
)
mock_client.read_work_pool.return_value = existing_work_pool
# Clear instances
MigratableWorkPool._instances.clear()
migratable = await MigratableWorkPool.construct(transfer_work_pool)
# Should raise TransferSkipped
with pytest.raises(TransferSkipped, match="Already exists"):
await migratable.migrate()
# Verify client calls
mock_client.create_work_pool.assert_called_once()
mock_client.read_work_pool.assert_called_once_with(transfer_work_pool.name)
# Verify destination_work_pool is set to existing
assert migratable.destination_work_pool == existing_work_pool
assert migratable.destination_id == existing_work_pool.id
|
TestMigratableWorkPool
|
python
|
apache__airflow
|
providers/amazon/tests/unit/amazon/aws/waiters/test_kinesis_analytics.py
|
{
"start": 1416,
"end": 1667
}
|
class ____:
@pytest.fixture(autouse=True)
def mock_conn(self, monkeypatch):
self.client = boto3.client("kinesisanalyticsv2")
monkeypatch.setattr(KinesisAnalyticsV2Hook, "conn", self.client)
|
TestKinesisAnalyticsV2CustomWaitersBase
|
python
|
pytorch__pytorch
|
torch/_inductor/mkldnn_ir.py
|
{
"start": 34106,
"end": 38077
}
|
class ____(ExternKernelAlloc):
def __init__(
self,
layout,
inputs,
constant_args=(),
has_bias=True,
) -> None:
"""
if bias is not None
- inputs = [x, w, x_scale, x_zp, weight_scale, weight_zp, x2, bias]
- const_args is: [o_scale, o_zp,
fp32_output, binary_attr, alpha, unary_attr, unary_scalars, unary_algorithm]
else
- inputs = [x, w, x_scale, x_zp, weight_scale, weight_zp, x2]
- const_args is: [bias, o_scale, o_zp,
fp32_output, binary_attr, alpha, unary_attr, unary_scalars, unary_algorithm]
"""
self.device_type = get_device_type(inputs[0])
self.has_bias = has_bias
self.idx_for_inplace_sum = 6
super().__init__(
layout,
inputs,
constant_args,
None,
op_overload=(torch.ops.onednn.qlinear_pointwise.binary_tensor),
cpp_kernel_name=f"aoti_torch_{self.device_type}__qlinear_pointwise_binary_tensor",
)
def codegen(self, wrapper):
wrapper.include_extra_header(
f"torch/csrc/inductor/aoti_torch/c/shim_{self.device_type}.h"
)
super().codegen(wrapper)
if isinstance(self.layout, Layout):
self.codegen_size_asserts(wrapper)
def get_mutation_names(self) -> Sequence[str]:
binary_post_op = self.constant_args[-5]
if binary_post_op == "sum":
input = self.inputs[self.idx_for_inplace_sum]
assert isinstance(input, IRNode)
return [input.get_name()]
else:
return []
@classmethod
def create(
cls,
qx: "TensorBox",
x_scale: "TensorBox",
x_zero_point: "TensorBox",
qw: "TensorBox", # packed_weight
w_scale: "TensorBox",
w_zero_point: "TensorBox",
other: "TensorBox",
bias: "TensorBox",
output_scale: float,
output_zero_point: int,
output_dtype,
other_scale,
other_zp,
binary_post_op,
binary_alpha,
unary_post_op,
unary_post_op_args,
unary_post_op_algorithm,
):
(
inputs,
constant_args,
kernel_layout,
req_stride_order,
other,
) = _prepare_linear_fusion_create(
cls,
qx,
qw,
bias,
[x_scale, x_zero_point, w_scale, w_zero_point],
other,
binary_post_op == "sum",
)
constant_args = constant_args + [
output_scale,
output_zero_point,
output_dtype,
other_scale,
other_zp,
binary_post_op,
binary_alpha,
unary_post_op,
may_convert_to_optional(unary_post_op_args),
unary_post_op_algorithm,
]
if binary_post_op == "sum":
V.graph.mark_buffer_mutated(other.get_name())
packed = QLinearPointwiseBinaryPT2E(
layout=NoneLayout(device=other.get_device()),
inputs=inputs,
constant_args=constant_args,
has_bias=(bias is not None),
)
# Return other since it has been inplace changed.
return packed.inputs[packed.idx_for_inplace_sum]
assert output_dtype is not None
if output_dtype in [torch.float32, torch.bfloat16]:
# in _prepare_linear_fusion_create, we use x.dtype (uint8) to create kernel_layout
# if we set fp32_output, the output buf should be dtype float32 instead of uint8.
kernel_layout.dtype = output_dtype
return QLinearPointwiseBinaryPT2E(
layout=kernel_layout,
inputs=inputs,
constant_args=constant_args,
has_bias=(bias is not None),
)
|
QLinearPointwiseBinaryPT2E
|
python
|
pennersr__django-allauth
|
allauth/socialaccount/providers/telegram/views.py
|
{
"start": 892,
"end": 2857
}
|
class ____(View):
def get(self, request):
return render(request, "telegram/callback.html")
def post(self, request):
adapter = get_adapter()
provider = adapter.get_provider(request, TelegramProvider.id)
state_id = request.GET.get("state")
if not state_id:
return render_authentication_error(
request,
provider=provider,
)
try:
result = request.POST.get("tgAuthResult")
padding = "=" * (4 - (len(result) % 4))
data = json.loads(base64.b64decode(result + padding))
if not isinstance(data, dict) or "hash" not in data:
raise ValueError("Invalid tgAuthResult")
except (binascii.Error, json.JSONDecodeError, ValueError) as e:
return render_authentication_error(
request,
provider=provider,
exception=e,
extra_context={"state_id": state_id},
)
hash = data.pop("hash")
payload = "\n".join(sorted(["{}={}".format(k, v) for k, v in data.items()]))
token = provider.app.secret
token_sha256 = hashlib.sha256(token.encode()).digest()
expected_hash = hmac.new(
token_sha256, payload.encode(), hashlib.sha256
).hexdigest()
auth_date = int(data.pop("auth_date"))
auth_date_validity = provider.get_auth_date_validity()
if hash != expected_hash or time.time() - auth_date > auth_date_validity:
return render_authentication_error(
request,
provider=provider,
extra_context={"response": data, "state_id": state_id},
)
login = provider.sociallogin_from_response(request, data)
login.state = provider.unstash_redirect_state(request, state_id)
return complete_social_login(request, login)
callback = CallbackView.as_view()
|
CallbackView
|
python
|
skorch-dev__skorch
|
skorch/llm/classifier.py
|
{
"start": 9362,
"end": 21564
}
|
class ____(ClassifierMixin, BaseEstimator):
"""Base class for LLM models
This class handles a few of the checks, as well as the whole prediction
machinery.
Required attributes are:
- model_name
- model
- tokenizer
- prompt
- probas_sum_to_1
- device
- error_low_prob
- threshold_low_prob
- use_caching
"""
def check_X_y(self, X, y, **fit_params):
raise NotImplementedError
def check_prompt(self, prompt):
raise NotImplementedError
def get_prompt(self, text):
raise NotImplementedError
def fit(self, X, y, **fit_params):
# note: should call _fit
raise NotImplementedError
def check_classes(self, y):
return np.unique(y)
def check_is_fitted(self):
required_attrs = ['model_', 'tokenizer_', 'prompt_', 'classes_', 'label_ids_']
check_is_fitted(self, required_attrs)
@property
def device_(self):
# Use whatever device the model is on, not self.device. If a user
# initializes with a model that is on GPU, we don't want to require them
# to adjust the device argument, which would be annoying
return self.model_.device
def check_args(self):
# users should either pass the model name, or the model and tokenizer,
# but not both
cls_name = self.__class__.__name__
msg = (
f"{cls_name} needs to be initialized with either a model name, "
"or a model & tokenizer, but not both."
)
if self.model_name is not None:
if (self.model is not None) or (self.tokenizer is not None):
raise ValueError(msg)
else:
if (self.model is None) or (self.tokenizer is None):
raise ValueError(msg)
possible_values_error_low_prob = ['ignore', 'raise', 'warn', 'return_none']
if self.error_low_prob not in possible_values_error_low_prob:
raise ValueError(
"error_low_prob must be one of "
f"{', '.join(possible_values_error_low_prob)}; "
f"got {self.error_low_prob} instead"
)
if (self.threshold_low_prob < 0) or (self.threshold_low_prob > 1):
raise ValueError(
"threshold_low_prob must be between 0 and 1, "
f"got {self.threshold_low_prob} instead"
)
def _is_encoder_decoder(self, model):
return hasattr(model, 'get_encoder')
def _fit(self, X, y, **fit_params):
"""Prepare everything to enable predictions."""
self.check_args()
self.check_X_y(X, y)
if self.model_name is not None:
self.model_, self.tokenizer_ = _load_model_and_tokenizer(
self.model_name, device=self.device
)
else:
self.model_, self.tokenizer_ = self.model, self.tokenizer
if self._is_encoder_decoder(self.model_) and self.use_caching:
# Explanation: When we have a prompt [1, 2, 3] and label [4, 5], and
# if the model is an encoder-decoder architecture (seq2seq), then
# [1, 2, 3] is encoded and [4, 5] are generated by the decoder. If
# we wanted to cache, we would store the result (among others) for
# [1, 2, 3, 4]. However, encoding [1, 2, 3, 4] and generating [5] is
# not the same operation as encoding [1, 2, 3] and generating [4,
# 5]. Granted, the logits could be very close, but we cannot be sure
# and it will depend on the model. Therefore, for the time being, we
# don't allow caching for encoder-decoder models.
raise ValueError(
"Caching is not supported for encoder-decoder models, "
"initialize the model with use_caching=False."
)
self.classes_ = self.check_classes(y)
self.prompt_ = self.check_prompt(self.prompt)
classes = [str(c) for c in self.classes_]
self.label_ids_ = self.tokenizer_(classes)['input_ids']
self.cached_model_ = _CacheModelWrapper(
self.model_, self.tokenizer_, use_caching=self.use_caching
)
return self
def _predict_one(self, text):
"""Make a prediction for a single sample
The returned probabilites are *not normalized* yet.
Raises a ``LowProbabilityError`` if the total probability of all labels
is 0, or, assuming ``error_low_prob`` is ``'raise'``, when it is below
``threshold_low_prob``. This check is done here because we want to raise
eagerly instead of going through all samples and then raise.
"""
inputs = self.tokenizer_(text, return_tensors='pt').to(self.device_)
probas_all_labels = []
for label_id in self.label_ids_:
logits = self.cached_model_.generate_logits(label_id=label_id, **inputs)
logits = torch.vstack(logits)
probas = torch.nn.functional.softmax(logits, dim=-1)
# in case we deal with BFloats which are not supported on CPU
probas = probas.to(torch.float)
n = len(logits)
label_id = label_id[:n] # don't need EOS, PAD, etc.
probas_at_idx = probas[torch.arange(n), label_id]
# multiplying the probabilities for token A, B, C, ... This is
# because we are interested in P(A) AND P(B|A) AND P(C|A,B), etc.
# p(A) * P(B|A) =
# p(A) * p(AnB) / p(A) =
# p(A) * p(A) * p(B) / p(A) =
# p(A) * p(B)
# thus the product of individual probalities is correct
probas_all_labels.append(torch.prod(probas_at_idx).item())
prob_sum = sum(probas_all_labels)
if prob_sum == 0.0:
raise LowProbabilityError("The sum of all probabilities is zero.")
probs_are_low = prob_sum < self.threshold_low_prob
if probs_are_low and (self.error_low_prob == 'raise'):
raise LowProbabilityError(
f"The sum of all probabilities is {prob_sum:.3f}, "
f"which is below the minimum threshold of {self.threshold_low_prob:.3f}"
)
y_prob = np.array(probas_all_labels).astype(np.float64)
return y_prob
def _predict_proba(self, X):
"""Return the unnormalized y_proba
Warns if the total probability for a sample is below the threshold and
``error_low_prob`` is ``'warn'``.
"""
self.check_is_fitted()
y_proba = []
for xi in X:
text = self.get_prompt(xi)
proba = self._predict_one(text)
y_proba.append(proba)
y_proba = np.vstack(y_proba)
if self.error_low_prob == 'warn':
total_low_probas = (y_proba.sum(1) < self.threshold_low_prob).sum()
if total_low_probas:
warnings.warn(
f"Found {total_low_probas} samples to have a total probability "
f"below the threshold of {self.threshold_low_prob:.3f}."
)
return y_proba
def predict_proba(self, X):
"""Return the probabilities predicted by the LLM.
Predictions will be forced to be one of the labels the model learned
during ``fit``. Each column in ``y_proba`` corresponds to one class. The
order of the classes can be checked in the ``.classes_`` attribute. In
general, it is alphabetic. So the first column is the probability for
the first class in ``.classes_``, the second column is the probability
for the second class in ``.classes_``, etc.
If ``error_low_prob`` is set to ``'warn'``, then a warning is given if,
for at least one sample, the sum of the probabilities for all classes is
below the threshold set in ``threshold_low_prob``. If ``error_low_prob``
is set to ``'raise'``, then an error is raised instead.
Parameters
----------
X : input data
Typically, this is a list/array of strings. E.g., this could be a list
of reviews and the target is the sentiment. Technically, however, this
can also contain numerical or categorical data, although it is
unlikely that the LLM will generate good predictions for those.
Returns
-------
y_proba : numpy ndarray
The probabilities for each class. If ``probas_sum_to_1`` is set to
``False``, then the sum of the probabilities for each sample will not
add up to 1
"""
# y_proba not normalized here
y_proba = self._predict_proba(X)
if self.probas_sum_to_1:
# normalizing here is okay because we already checked earlier that
# the sum is not 0
y_proba /= y_proba.sum(1, keepdims=True)
return y_proba
def predict(self, X):
"""Return the classes predicted by the LLM.
Predictions will be forced to be one of the labels the model learned
during ``fit`` (see the ``classes_`` attribute). The model will never
predict a different label.
If ``error_low_prob`` is set to ``'warn'``, then a warning is given if,
for at least one sample, the sum of the probabilities for all classes is
below the threshold set in ``threshold_low_prob``. If ``error_low_prob``
is set to ``'raise'``, then an error is raised instead.
If ``error_low_prob`` is set to ``'return_none'``, then the predicted
class will be replaced by ``None`` if the sum of the probabilities is
below the threshold set in ``threshold_low_prob``.
Parameters
----------
X : input data
Typically, this is a list/array of strings. E.g., this could be a list
of reviews and the target is the sentiment. Technically, however, this
can also contain numerical or categorical data, although it is
unlikely that the LLM will generate good predictions for those.
Returns
-------
y_pred : numpy ndarray
The label for each class.
"""
# y_proba not normalized but it's not neeeded here
y_proba = self._predict_proba(X)
pred_ids = y_proba.argmax(1)
y_pred = self.classes_[pred_ids]
if self.error_low_prob == 'return_none':
y_pred = y_pred.astype(object) # prevents None from being cast to str
mask_low_probas = y_proba.sum(1) < self.threshold_low_prob
y_pred[mask_low_probas] = None
return y_pred
def clear_model_cache(self):
"""Clear the cache of the model
Call this to free some memory.
"""
if self.use_caching and hasattr(self, 'cached_model_'):
# caching is used and model cache has been initialized
self.cached_model_.clear()
def __repr__(self):
# The issue is that the repr for the transformer model can be quite huge
# and the repr for the tokenizer quite ugly. We solve this by
# temporarily replacing them by their class names. We should, however,
# not completely rewrite the repr code because sklearn does some special
# magic with the repr. This is why super().__repr__() should be used.
if (self.model is None) and (self.tokenizer is None):
# the user initialized the class with model name, the repr should be
# fine
return super().__repr__()
model_prev = self.model
tokenizer_prev = self.tokenizer
rep = None
# we are very defensive, making sure to restore the temporarily made
# change in case of an error
try:
self.model = self.model.__class__.__name__
self.tokenizer = self.tokenizer.__class__.__name__
rep = super().__repr__()
finally:
self.model = model_prev
self.tokenizer = tokenizer_prev
if rep is None:
# if the repr could not be generated, fall back to using the ugly
# repr
rep = super().__repr__()
return rep
|
_LlmBase
|
python
|
apache__airflow
|
providers/amazon/src/airflow/providers/amazon/aws/transfers/ftp_to_s3.py
|
{
"start": 1171,
"end": 6414
}
|
class ____(BaseOperator):
"""
Transfer of one or more files from an FTP server to S3.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:FTPToS3Operator`
:param ftp_path: The ftp remote path. For one file it is mandatory to include the file as well.
For multiple files, it is the route where the files will be found.
:param s3_bucket: The targeted s3 bucket in which to upload the file(s).
:param s3_key: The targeted s3 key. For one file it must include the file path. For several,
it must end with "/".
:param ftp_filenames: Only used if you want to move multiple files. You can pass a list
with exact filenames present in the ftp path, or a prefix that all files must meet. It
can also be the string '*' for moving all the files within the ftp path.
:param s3_filenames: Only used if you want to move multiple files and name them different from
the originals from the ftp. It can be a list of filenames or file prefix (that will replace
the ftp prefix).
:param ftp_conn_id: The ftp connection id. The name or identifier for
establishing a connection to the FTP server.
:param aws_conn_id: The s3 connection id. The name or identifier for
establishing a connection to S3.
:param replace: A flag to decide whether or not to overwrite the key
if it already exists. If replace is False and the key exists, an
error will be raised.
:param encrypt: If True, the file will be encrypted on the server-side
by S3 and will be stored in an encrypted form while at rest in S3.
:param gzip: If True, the file will be compressed locally
:param acl_policy: String specifying the canned ACL policy for the file being
uploaded to the S3 bucket.
"""
template_fields: Sequence[str] = ("ftp_path", "s3_bucket", "s3_key", "ftp_filenames", "s3_filenames")
def __init__(
self,
*,
ftp_path: str,
s3_bucket: str,
s3_key: str,
ftp_filenames: str | list[str] | None = None,
s3_filenames: str | list[str] | None = None,
ftp_conn_id: str = "ftp_default",
aws_conn_id: str | None = "aws_default",
replace: bool = False,
encrypt: bool = False,
gzip: bool = False,
acl_policy: str | None = None,
**kwargs,
):
super().__init__(**kwargs)
self.ftp_path = ftp_path
self.s3_bucket = s3_bucket
self.s3_key = s3_key
self.ftp_filenames = ftp_filenames
self.s3_filenames = s3_filenames
self.aws_conn_id = aws_conn_id
self.ftp_conn_id = ftp_conn_id
self.replace = replace
self.encrypt = encrypt
self.gzip = gzip
self.acl_policy = acl_policy
self.s3_hook: S3Hook | None = None
self.ftp_hook: FTPHook | None = None
def __upload_to_s3_from_ftp(self, remote_filename, s3_file_key):
with NamedTemporaryFile() as local_tmp_file:
self.ftp_hook.retrieve_file(
remote_full_path=remote_filename, local_full_path_or_buffer=local_tmp_file.name
)
self.s3_hook.load_file(
filename=local_tmp_file.name,
key=s3_file_key,
bucket_name=self.s3_bucket,
replace=self.replace,
encrypt=self.encrypt,
gzip=self.gzip,
acl_policy=self.acl_policy,
)
self.log.info("File upload to %s", s3_file_key)
def execute(self, context: Context):
self.ftp_hook = FTPHook(ftp_conn_id=self.ftp_conn_id)
self.s3_hook = S3Hook(self.aws_conn_id)
if self.ftp_filenames:
if isinstance(self.ftp_filenames, str):
self.log.info("Getting files in %s", self.ftp_path)
list_dir = self.ftp_hook.list_directory(
path=self.ftp_path,
)
if self.ftp_filenames == "*":
files = list_dir
else:
ftp_filename: str = self.ftp_filenames
files = [f for f in list_dir if ftp_filename in f]
for file in files:
self.log.info("Moving file %s", file)
if self.s3_filenames and isinstance(self.s3_filenames, str):
filename = file.replace(self.ftp_filenames, self.s3_filenames)
else:
filename = file
s3_file_key = f"{self.s3_key}{filename}"
self.__upload_to_s3_from_ftp(file, s3_file_key)
else:
if self.s3_filenames:
for ftp_file, s3_file in zip(self.ftp_filenames, self.s3_filenames):
self.__upload_to_s3_from_ftp(self.ftp_path + ftp_file, self.s3_key + s3_file)
else:
for ftp_file in self.ftp_filenames:
self.__upload_to_s3_from_ftp(self.ftp_path + ftp_file, self.s3_key + ftp_file)
else:
self.__upload_to_s3_from_ftp(self.ftp_path, self.s3_key)
|
FTPToS3Operator
|
python
|
wandb__wandb
|
wandb/vendor/pygments/lexers/templates.py
|
{
"start": 36381,
"end": 37050
}
|
class ____(DelegatingLexer):
"""
Subclass of `ErbLexer` which highlights unlexed data with the
`JavascriptLexer`.
"""
name = 'JavaScript+Ruby'
aliases = ['js+erb', 'javascript+erb', 'js+ruby', 'javascript+ruby']
alias_filenames = ['*.js']
mimetypes = ['application/x-javascript+ruby',
'text/x-javascript+ruby',
'text/javascript+ruby']
def __init__(self, **options):
super(JavascriptErbLexer, self).__init__(JavascriptLexer, ErbLexer,
**options)
def analyse_text(text):
return ErbLexer.analyse_text(text) - 0.05
|
JavascriptErbLexer
|
python
|
apache__airflow
|
shared/configuration/tests/configuration/test_parser.py
|
{
"start": 1217,
"end": 2666
}
|
class ____(_SharedAirflowConfigParser):
"""Test parser that extends shared parser for testing."""
def __init__(self, default_config: str | None = None, *args, **kwargs):
configuration_description = {
"test": {
"options": {
"key1": {"default": "default_value"},
"key2": {"default": 123},
}
}
}
_default_values = ConfigParser()
_default_values.add_section("test")
_default_values.set("test", "key1", "default_value")
_default_values.set("test", "key2", "123")
super().__init__(configuration_description, _default_values, *args, **kwargs)
self.configuration_description = configuration_description
self._default_values = _default_values
self._suppress_future_warnings = False
if default_config is not None:
self._update_defaults_from_string(default_config)
def _update_defaults_from_string(self, config_string: str):
"""Update defaults from string for testing."""
parser = ConfigParser()
parser.read_string(config_string)
for section in parser.sections():
if section not in self._default_values.sections():
self._default_values.add_section(section)
for key, value in parser.items(section):
self._default_values.set(section, key, value)
|
AirflowConfigParser
|
python
|
gevent__gevent
|
src/gevent/_ffi/watcher.py
|
{
"start": 15862,
"end": 17143
}
|
class ____(object):
_watcher_type = 'timer'
def __init__(self, loop, after=0.0, repeat=0.0, ref=True, priority=None):
if repeat < 0.0:
raise ValueError("repeat must be positive or zero: %r" % repeat)
self._after = after
self._repeat = repeat
super(TimerMixin, self).__init__(loop, ref=ref, priority=priority, args=(after, repeat))
def start(self, callback, *args, **kw):
update = kw.get("update", self.loop.starting_timer_may_update_loop_time)
if update:
# Quoth the libev doc: "This is a costly operation and is
# usually done automatically within ev_run(). This
# function is rarely useful, but when some event callback
# runs for a very long time without entering the event
# loop, updating libev's idea of the current time is a
# good idea."
# 1.3 changed the default for this to False *unless* the loop is
# running a callback; see libuv for details. Note that
# starting Timeout objects still sets this to true.
self.loop.update_now()
super(TimerMixin, self).start(callback, *args)
def again(self, callback, *args, **kw):
raise NotImplementedError()
|
TimerMixin
|
python
|
celery__celery
|
celery/utils/collections.py
|
{
"start": 12761,
"end": 20274
}
|
class ____:
"""Kind-of Set (or priority queue) with limitations.
Good for when you need to test for membership (`a in set`),
but the set should not grow unbounded.
``maxlen`` is enforced at all times, so if the limit is reached
we'll also remove non-expired items.
You can also configure ``minlen``: this is the minimal residual size
of the set.
All arguments are optional, and no limits are enabled by default.
Arguments:
maxlen (int): Optional max number of items.
Adding more items than ``maxlen`` will result in immediate
removal of items sorted by oldest insertion time.
expires (float): TTL for all items.
Expired items are purged as keys are inserted.
minlen (int): Minimal residual size of this set.
.. versionadded:: 4.0
Value must be less than ``maxlen`` if both are configured.
Older expired items will be deleted, only after the set
exceeds ``minlen`` number of items.
data (Sequence): Initial data to initialize set with.
Can be an iterable of ``(key, value)`` pairs,
a dict (``{key: insertion_time}``), or another instance
of :class:`LimitedSet`.
Example:
>>> s = LimitedSet(maxlen=50000, expires=3600, minlen=4000)
>>> for i in range(60000):
... s.add(i)
... s.add(str(i))
...
>>> 57000 in s # last 50k inserted values are kept
True
>>> '10' in s # '10' did expire and was purged from set.
False
>>> len(s) # maxlen is reached
50000
>>> s.purge(now=time.monotonic() + 7200) # clock + 2 hours
>>> len(s) # now only minlen items are cached
4000
>>>> 57000 in s # even this item is gone now
False
"""
max_heap_percent_overload = 15
def __init__(self, maxlen=0, expires=0, data=None, minlen=0):
# type: (int, float, Mapping, int) -> None
self.maxlen = 0 if maxlen is None else maxlen
self.minlen = 0 if minlen is None else minlen
self.expires = 0 if expires is None else expires
self._data = {}
self._heap = []
if data:
# import items from data
self.update(data)
if not self.maxlen >= self.minlen >= 0:
raise ValueError(
'minlen must be a positive number, less or equal to maxlen.')
if self.expires < 0:
raise ValueError('expires cannot be negative!')
def _refresh_heap(self):
# type: () -> None
"""Time consuming recreating of heap. Don't run this too often."""
self._heap[:] = [entry for entry in self._data.values()]
heapify(self._heap)
def _maybe_refresh_heap(self):
# type: () -> None
if self._heap_overload >= self.max_heap_percent_overload:
self._refresh_heap()
def clear(self):
# type: () -> None
"""Clear all data, start from scratch again."""
self._data.clear()
self._heap[:] = []
def add(self, item, now=None):
# type: (Any, float) -> None
"""Add a new item, or reset the expiry time of an existing item."""
now = now or time.monotonic()
if item in self._data:
self.discard(item)
entry = (now, item)
self._data[item] = entry
heappush(self._heap, entry)
if self.maxlen and len(self._data) >= self.maxlen:
self.purge()
def update(self, other):
# type: (Iterable) -> None
"""Update this set from other LimitedSet, dict or iterable."""
if not other:
return
if isinstance(other, LimitedSet):
self._data.update(other._data)
self._refresh_heap()
self.purge()
elif isinstance(other, dict):
# revokes are sent as a dict
for key, inserted in other.items():
if isinstance(inserted, (tuple, list)):
# in case someone uses ._data directly for sending update
inserted = inserted[0]
if not isinstance(inserted, float):
raise ValueError(
'Expecting float timestamp, got type '
f'{type(inserted)!r} with value: {inserted}')
self.add(key, inserted)
else:
# XXX AVOID THIS, it could keep old data if more parties
# exchange them all over and over again
for obj in other:
self.add(obj)
def discard(self, item):
# type: (Any) -> None
# mark an existing item as removed. If KeyError is not found, pass.
self._data.pop(item, None)
self._maybe_refresh_heap()
pop_value = discard
def purge(self, now=None):
# type: (float) -> None
"""Check oldest items and remove them if needed.
Arguments:
now (float): Time of purging -- by default right now.
This can be useful for unit testing.
"""
now = now or time.monotonic()
now = now() if isinstance(now, Callable) else now
if self.maxlen:
while len(self._data) > self.maxlen:
self.pop()
# time based expiring:
if self.expires:
while len(self._data) > self.minlen >= 0:
inserted_time, _ = self._heap[0]
if inserted_time + self.expires > now:
break # oldest item hasn't expired yet
self.pop()
def pop(self, default: Any = None) -> Any:
"""Remove and return the oldest item, or :const:`None` when empty."""
while self._heap:
_, item = heappop(self._heap)
try:
self._data.pop(item)
except KeyError:
pass
else:
return item
return default
def as_dict(self):
# type: () -> Dict
"""Whole set as serializable dictionary.
Example:
>>> s = LimitedSet(maxlen=200)
>>> r = LimitedSet(maxlen=200)
>>> for i in range(500):
... s.add(i)
...
>>> r.update(s.as_dict())
>>> r == s
True
"""
return {key: inserted for inserted, key in self._data.values()}
def __eq__(self, other):
# type: (Any) -> bool
return self._data == other._data
def __repr__(self):
# type: () -> str
return REPR_LIMITED_SET.format(
self, name=type(self).__name__, size=len(self),
)
def __iter__(self):
# type: () -> Iterable
return (i for _, i in sorted(self._data.values()))
def __len__(self):
# type: () -> int
return len(self._data)
def __contains__(self, key):
# type: (Any) -> bool
return key in self._data
def __reduce__(self):
# type: () -> Any
return self.__class__, (
self.maxlen, self.expires, self.as_dict(), self.minlen)
def __bool__(self):
# type: () -> bool
return bool(self._data)
__nonzero__ = __bool__ # Py2
@property
def _heap_overload(self):
# type: () -> float
"""Compute how much is heap bigger than data [percents]."""
return len(self._heap) * 100 / max(len(self._data), 1) - 100
MutableSet.register(LimitedSet)
|
LimitedSet
|
python
|
agronholm__apscheduler
|
src/apscheduler/triggers/cron/fields.py
|
{
"start": 1030,
"end": 3039
}
|
class ____:
__slots__ = "expressions", "name"
real: ClassVar[bool] = True
compilers: ClassVar[Any] = (AllExpression, RangeExpression)
def __init_subclass__(cls, real: bool = True, extra_compilers: Sequence = ()):
cls.real = real
if extra_compilers:
cls.compilers += extra_compilers
def __init__(self, name: str, exprs: int | str):
self.name = name
self.expressions: list = []
for expr in SEPARATOR.split(str(exprs).strip()):
self.append_expression(expr)
def get_min(self, dateval: datetime) -> int:
return MIN_VALUES[self.name]
def get_max(self, dateval: datetime) -> int:
return MAX_VALUES[self.name]
def get_value(self, dateval: datetime) -> int:
return getattr(dateval, self.name)
def get_next_value(self, dateval: datetime) -> int | None:
smallest = None
for expr in self.expressions:
value = expr.get_next_value(dateval, self)
if smallest is None or (value is not None and value < smallest):
smallest = value
return smallest
def append_expression(self, expr: str) -> None:
for compiler in self.compilers:
match = compiler.value_re.match(expr)
if match:
compiled_expr = compiler(**match.groupdict())
try:
compiled_expr.validate_range(
self.name, MIN_VALUES[self.name], MAX_VALUES[self.name]
)
except ValueError as exc:
raise ValueError(
f"Error validating expression {expr!r}: {exc}"
) from exc
self.expressions.append(compiled_expr)
return
raise ValueError(f"Unrecognized expression {expr!r} for field {self.name!r}")
def __str__(self) -> str:
expr_strings = (str(e) for e in self.expressions)
return ",".join(expr_strings)
|
BaseField
|
python
|
facelessuser__pymdown-extensions
|
tests/test_extensions/test_tabbed.py
|
{
"start": 16767,
"end": 17905
}
|
class ____(util.MdCase):
"""Test legacy tab slug separator cases."""
extension = ['pymdownx.tabbed', 'toc']
extension_configs = {'pymdownx.tabbed': {'slugify': slugify(case='lower'), 'separator': '_'}}
MD = """
### Here is some text
=== "Here is some text"
content
=== "Here is some text"
content
"""
def test_slug_with_separator(self):
"""Test tab slugs with separator."""
self.check_markdown(
self.MD,
'''
<h3 id="here-is-some-text">Here is some text</h3>
<div class="tabbed-set" data-tabs="1:2"><input checked="checked" id="here_is_some_text" name="__tabbed_1" type="radio" /><label for="here_is_some_text">Here is some text</label><div class="tabbed-content">
<p>content</p>
</div>
<input id="here_is_some_text_1" name="__tabbed_1" type="radio" /><label for="here_is_some_text_1">Here is some text</label><div class="tabbed-content">
<p>content</p>
</div>
</div>
''', # noqa: E501
True
)
|
TestLegacyTabSlugsSep
|
python
|
pallets__flask
|
tests/test_json.py
|
{
"start": 3617,
"end": 8741
}
|
class ____(datetime.tzinfo):
"""Fixed offset in hours east from UTC.
This is a slight adaptation of the ``FixedOffset`` example found in
https://docs.python.org/2.7/library/datetime.html.
"""
def __init__(self, hours, name):
self.__offset = datetime.timedelta(hours=hours)
self.__name = name
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return self.__name
def dst(self, dt):
return datetime.timedelta()
@pytest.mark.parametrize("tz", (("UTC", 0), ("PST", -8), ("KST", 9)))
def test_jsonify_aware_datetimes(tz):
"""Test if aware datetime.datetime objects are converted into GMT."""
tzinfo = FixedOffset(hours=tz[1], name=tz[0])
dt = datetime.datetime(2017, 1, 1, 12, 34, 56, tzinfo=tzinfo)
gmt = FixedOffset(hours=0, name="GMT")
expected = dt.astimezone(gmt).strftime('"%a, %d %b %Y %H:%M:%S %Z"')
assert flask.json.dumps(dt) == expected
def test_jsonify_uuid_types(app, client):
"""Test jsonify with uuid.UUID types"""
test_uuid = uuid.UUID(bytes=b"\xde\xad\xbe\xef" * 4)
url = "/uuid_test"
app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid))
rv = client.get(url)
rv_x = flask.json.loads(rv.data)["x"]
assert rv_x == str(test_uuid)
rv_uuid = uuid.UUID(rv_x)
assert rv_uuid == test_uuid
def test_json_decimal():
rv = flask.json.dumps(decimal.Decimal("0.003"))
assert rv == '"0.003"'
def test_json_attr(app, client):
@app.route("/add", methods=["POST"])
def add():
json = flask.request.get_json()
return str(json["a"] + json["b"])
rv = client.post(
"/add",
data=flask.json.dumps({"a": 1, "b": 2}),
content_type="application/json",
)
assert rv.data == b"3"
def test_tojson_filter(app, req_ctx):
# The tojson filter is tested in Jinja, this confirms that it's
# using Flask's dumps.
rv = flask.render_template_string(
"const data = {{ data|tojson }};",
data={"name": "</script>", "time": datetime.datetime(2021, 2, 1, 7, 15)},
)
assert rv == (
'const data = {"name": "\\u003c/script\\u003e",'
' "time": "Mon, 01 Feb 2021 07:15:00 GMT"};'
)
def test_json_customization(app, client):
class X: # noqa: B903, for Python2 compatibility
def __init__(self, val):
self.val = val
def default(o):
if isinstance(o, X):
return f"<{o.val}>"
return DefaultJSONProvider.default(o)
class CustomProvider(DefaultJSONProvider):
def object_hook(self, obj):
if len(obj) == 1 and "_foo" in obj:
return X(obj["_foo"])
return obj
def loads(self, s, **kwargs):
kwargs.setdefault("object_hook", self.object_hook)
return super().loads(s, **kwargs)
app.json = CustomProvider(app)
app.json.default = default
@app.route("/", methods=["POST"])
def index():
return flask.json.dumps(flask.request.get_json()["x"])
rv = client.post(
"/",
data=flask.json.dumps({"x": {"_foo": 42}}),
content_type="application/json",
)
assert rv.data == b'"<42>"'
def _has_encoding(name):
try:
import codecs
codecs.lookup(name)
return True
except LookupError:
return False
def test_json_key_sorting(app, client):
app.debug = True
assert app.json.sort_keys
d = dict.fromkeys(range(20), "foo")
@app.route("/")
def index():
return flask.jsonify(values=d)
rv = client.get("/")
lines = [x.strip() for x in rv.data.strip().decode("utf-8").splitlines()]
sorted_by_str = [
"{",
'"values": {',
'"0": "foo",',
'"1": "foo",',
'"10": "foo",',
'"11": "foo",',
'"12": "foo",',
'"13": "foo",',
'"14": "foo",',
'"15": "foo",',
'"16": "foo",',
'"17": "foo",',
'"18": "foo",',
'"19": "foo",',
'"2": "foo",',
'"3": "foo",',
'"4": "foo",',
'"5": "foo",',
'"6": "foo",',
'"7": "foo",',
'"8": "foo",',
'"9": "foo"',
"}",
"}",
]
sorted_by_int = [
"{",
'"values": {',
'"0": "foo",',
'"1": "foo",',
'"2": "foo",',
'"3": "foo",',
'"4": "foo",',
'"5": "foo",',
'"6": "foo",',
'"7": "foo",',
'"8": "foo",',
'"9": "foo",',
'"10": "foo",',
'"11": "foo",',
'"12": "foo",',
'"13": "foo",',
'"14": "foo",',
'"15": "foo",',
'"16": "foo",',
'"17": "foo",',
'"18": "foo",',
'"19": "foo"',
"}",
"}",
]
try:
assert lines == sorted_by_int
except AssertionError:
assert lines == sorted_by_str
def test_html_method():
class ObjectWithHTML:
def __html__(self):
return "<p>test</p>"
result = json.dumps(ObjectWithHTML())
assert result == '"<p>test</p>"'
|
FixedOffset
|
python
|
walkccc__LeetCode
|
solutions/1595. Minimum Cost to Connect Two Groups of Points/1595.py
|
{
"start": 0,
"end": 830
}
|
class ____:
def connectTwoGroups(self, cost: list[list[int]]) -> int:
# minCosts[j] := the minimum cost of connecting group2's point j
minCosts = [min(col) for col in zip(*cost)]
@functools.lru_cache(None)
def dp(i: int, mask: int) -> int:
"""
Returns the minimum cost to connect group1's points[i..n) with group2's
points, where `mask` is the bitmask of the connected points in group2.
"""
if i == len(cost):
# All the points in group 1 are connected, so greedily assign the
# minimum cost for the unconnected points of group2.
return sum(minCost for j, minCost in enumerate(minCosts)
if (mask >> j & 1) == 0)
return min(cost[i][j] + dp(i + 1, mask | 1 << j)
for j in range(len(cost[0])))
return dp(0, 0)
|
Solution
|
python
|
django__django
|
django/db/migrations/operations/models.py
|
{
"start": 40703,
"end": 42754
}
|
class ____(IndexOperation):
category = OperationCategory.ADDITION
option_name = "constraints"
def __init__(self, model_name, constraint):
self.model_name = model_name
self.constraint = constraint
def state_forwards(self, app_label, state):
state.add_constraint(app_label, self.model_name_lower, self.constraint)
def database_forwards(self, app_label, schema_editor, from_state, to_state):
model = to_state.apps.get_model(app_label, self.model_name)
if self.allow_migrate_model(schema_editor.connection.alias, model):
schema_editor.add_constraint(model, self.constraint)
def database_backwards(self, app_label, schema_editor, from_state, to_state):
model = to_state.apps.get_model(app_label, self.model_name)
if self.allow_migrate_model(schema_editor.connection.alias, model):
schema_editor.remove_constraint(model, self.constraint)
def deconstruct(self):
return (
self.__class__.__name__,
[],
{
"model_name": self.model_name,
"constraint": self.constraint,
},
)
def describe(self):
return "Create constraint %s on model %s" % (
self.constraint.name,
self.model_name,
)
@property
def migration_name_fragment(self):
return "%s_%s" % (self.model_name_lower, self.constraint.name.lower())
def reduce(self, operation, app_label):
if (
isinstance(operation, RemoveConstraint)
and self.model_name_lower == operation.model_name_lower
and self.constraint.name == operation.name
):
return []
if (
isinstance(operation, AlterConstraint)
and self.model_name_lower == operation.model_name_lower
and self.constraint.name == operation.name
):
return [replace(self, constraint=operation.constraint)]
return super().reduce(operation, app_label)
|
AddConstraint
|
python
|
PrefectHQ__prefect
|
src/prefect/server/utilities/database.py
|
{
"start": 2184,
"end": 3473
}
|
class ____(functions.FunctionElement[uuid.UUID]):
"""
Platform-independent UUID default generator.
Note the actual functionality for this class is specified in the
`compiles`-decorated functions below
"""
name = "uuid_default"
@compiles(GenerateUUID, "postgresql")
def generate_uuid_postgresql(
element: GenerateUUID, compiler: SQLCompiler, **kwargs: Any
) -> str:
"""
Generates a random UUID in Postgres; requires the pgcrypto extension.
"""
return "(GEN_RANDOM_UUID())"
@compiles(GenerateUUID, "sqlite")
def generate_uuid_sqlite(
element: GenerateUUID, compiler: SQLCompiler, **kwargs: Any
) -> str:
"""
Generates a random UUID in other databases (SQLite) by concatenating
bytes in a way that approximates a UUID hex representation. This is
sufficient for our purposes of having a random client-generated ID
that is compatible with a UUID spec.
"""
return """
(
lower(hex(randomblob(4)))
|| '-'
|| lower(hex(randomblob(2)))
|| '-4'
|| substr(lower(hex(randomblob(2))),2)
|| '-'
|| substr('89ab',abs(random()) % 4 + 1, 1)
|| substr(lower(hex(randomblob(2))),2)
|| '-'
|| lower(hex(randomblob(6)))
)
"""
|
GenerateUUID
|
python
|
huggingface__transformers
|
src/transformers/models/longformer/modeling_longformer.py
|
{
"start": 26290,
"end": 54984
}
|
class ____(nn.Module):
def __init__(self, config, layer_id):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0:
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
f"heads ({config.num_attention_heads})"
)
self.num_heads = config.num_attention_heads
self.head_dim = int(config.hidden_size / config.num_attention_heads)
self.embed_dim = config.hidden_size
self.query = nn.Linear(config.hidden_size, self.embed_dim)
self.key = nn.Linear(config.hidden_size, self.embed_dim)
self.value = nn.Linear(config.hidden_size, self.embed_dim)
# separate projection layers for tokens with global attention
self.query_global = nn.Linear(config.hidden_size, self.embed_dim)
self.key_global = nn.Linear(config.hidden_size, self.embed_dim)
self.value_global = nn.Linear(config.hidden_size, self.embed_dim)
self.dropout = config.attention_probs_dropout_prob
self.layer_id = layer_id
attention_window = config.attention_window[self.layer_id]
assert attention_window % 2 == 0, (
f"`attention_window` for layer {self.layer_id} has to be an even value. Given {attention_window}"
)
assert attention_window > 0, (
f"`attention_window` for layer {self.layer_id} has to be positive. Given {attention_window}"
)
self.one_sided_attn_window_size = attention_window // 2
self.config = config
def forward(
self,
hidden_states,
attention_mask=None,
is_index_masked=None,
is_index_global_attn=None,
is_global_attn=None,
output_attentions=False,
):
"""
[`LongformerSelfAttention`] expects *len(hidden_states)* to be multiple of *attention_window*. Padding to
*attention_window* happens in [`LongformerModel.forward`] to avoid redoing the padding on each layer.
The *attention_mask* is changed in [`LongformerModel.forward`] from 0, 1, 2 to:
- -10000: no attention
- 0: local attention
- +10000: global attention
"""
hidden_states = hidden_states.transpose(0, 1)
# project hidden states
query_vectors = self.query(hidden_states)
key_vectors = self.key(hidden_states)
value_vectors = self.value(hidden_states)
seq_len, batch_size, embed_dim = hidden_states.size()
assert embed_dim == self.embed_dim, (
f"hidden_states should have embed_dim = {self.embed_dim}, but has {embed_dim}"
)
# normalize query
query_vectors /= math.sqrt(self.head_dim)
query_vectors = query_vectors.view(seq_len, batch_size, self.num_heads, self.head_dim).transpose(0, 1)
key_vectors = key_vectors.view(seq_len, batch_size, self.num_heads, self.head_dim).transpose(0, 1)
attn_scores = self._sliding_chunks_query_key_matmul(
query_vectors, key_vectors, self.one_sided_attn_window_size
)
# values to pad for attention probs
remove_from_windowed_attention_mask = (attention_mask != 0)[:, :, None, None]
# cast to fp32/fp16 then replace 1's with -inf
float_mask = remove_from_windowed_attention_mask.type_as(query_vectors).masked_fill(
remove_from_windowed_attention_mask, torch.finfo(query_vectors.dtype).min
)
# diagonal mask with zeros everywhere and -inf inplace of padding
diagonal_mask = self._sliding_chunks_query_key_matmul(
float_mask.new_ones(size=float_mask.size()), float_mask, self.one_sided_attn_window_size
)
# pad local attention probs
attn_scores += diagonal_mask
assert list(attn_scores.size()) == [
batch_size,
seq_len,
self.num_heads,
self.one_sided_attn_window_size * 2 + 1,
], (
f"local_attn_probs should be of size ({batch_size}, {seq_len}, {self.num_heads},"
f" {self.one_sided_attn_window_size * 2 + 1}), but is of size {attn_scores.size()}"
)
# compute local attention probs from global attention keys and contact over window dim
if is_global_attn:
# compute global attn indices required through out forward fn
(
max_num_global_attn_indices,
is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero,
) = self._get_global_attn_indices(is_index_global_attn)
# calculate global attn probs from global key
global_key_attn_scores = self._concat_with_global_key_attn_probs(
query_vectors=query_vectors,
key_vectors=key_vectors,
max_num_global_attn_indices=max_num_global_attn_indices,
is_index_global_attn_nonzero=is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero=is_local_index_no_global_attn_nonzero,
)
# concat to local_attn_probs
# (batch_size, seq_len, num_heads, extra attention count + 2*window+1)
attn_scores = torch.cat((global_key_attn_scores, attn_scores), dim=-1)
# free memory
del global_key_attn_scores
attn_probs = nn.functional.softmax(
attn_scores, dim=-1, dtype=torch.float32
) # use fp32 for numerical stability
# softmax sometimes inserts NaN if all positions are masked, replace them with 0
attn_probs = torch.masked_fill(attn_probs, is_index_masked[:, :, None, None], 0.0)
attn_probs = attn_probs.type_as(attn_scores)
# free memory
del attn_scores
# apply dropout
attn_probs = nn.functional.dropout(attn_probs, p=self.dropout, training=self.training)
value_vectors = value_vectors.view(seq_len, batch_size, self.num_heads, self.head_dim).transpose(0, 1)
# compute local attention output with global attention value and add
if is_global_attn:
# compute sum of global and local attn
attn_output = self._compute_attn_output_with_global_indices(
value_vectors=value_vectors,
attn_probs=attn_probs,
max_num_global_attn_indices=max_num_global_attn_indices,
is_index_global_attn_nonzero=is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero,
)
else:
# compute local attn only
attn_output = self._sliding_chunks_matmul_attn_probs_value(
attn_probs, value_vectors, self.one_sided_attn_window_size
)
assert attn_output.size() == (batch_size, seq_len, self.num_heads, self.head_dim), "Unexpected size"
attn_output = attn_output.transpose(0, 1).reshape(seq_len, batch_size, embed_dim).contiguous()
# compute value for global attention and overwrite to attention output
# TODO: remove the redundant computation
if is_global_attn:
global_attn_output, global_attn_probs = self._compute_global_attn_output_from_hidden(
hidden_states=hidden_states,
max_num_global_attn_indices=max_num_global_attn_indices,
is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero,
is_index_global_attn_nonzero=is_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero=is_local_index_no_global_attn_nonzero,
is_index_masked=is_index_masked,
)
# get only non zero global attn output
nonzero_global_attn_output = global_attn_output[
is_local_index_global_attn_nonzero[0], :, is_local_index_global_attn_nonzero[1]
]
# overwrite values with global attention
attn_output[is_index_global_attn_nonzero[::-1]] = nonzero_global_attn_output.view(
len(is_local_index_global_attn_nonzero[0]), -1
)
# The attention weights for tokens with global attention are
# just filler values, they were never used to compute the output.
# Fill with 0 now, the correct values are in 'global_attn_probs'.
attn_probs[is_index_global_attn_nonzero] = 0
outputs = (attn_output.transpose(0, 1),)
if output_attentions:
outputs += (attn_probs,)
return outputs + (global_attn_probs,) if (is_global_attn and output_attentions) else outputs
@staticmethod
def _pad_and_transpose_last_two_dims(hidden_states_padded, padding):
"""pads rows and then flips rows and columns"""
hidden_states_padded = nn.functional.pad(
hidden_states_padded, padding
) # padding value is not important because it will be overwritten
hidden_states_padded = hidden_states_padded.view(
*hidden_states_padded.size()[:-2], hidden_states_padded.size(-1), hidden_states_padded.size(-2)
)
return hidden_states_padded
@staticmethod
def _pad_and_diagonalize(chunked_hidden_states):
"""
shift every row 1 step right, converting columns into diagonals.
Example:
```python
chunked_hidden_states: [
0.4983,
2.6918,
-0.0071,
1.0492,
-1.8348,
0.7672,
0.2986,
0.0285,
-0.7584,
0.4206,
-0.0405,
0.1599,
2.0514,
-1.1600,
0.5372,
0.2629,
]
window_overlap = num_rows = 4
```
(pad & diagonalize) => [ 0.4983, 2.6918, -0.0071, 1.0492, 0.0000, 0.0000, 0.0000
0.0000, -1.8348, 0.7672, 0.2986, 0.0285, 0.0000, 0.0000 0.0000, 0.0000, -0.7584, 0.4206,
-0.0405, 0.1599, 0.0000 0.0000, 0.0000, 0.0000, 2.0514, -1.1600, 0.5372, 0.2629 ]
"""
total_num_heads, num_chunks, window_overlap, hidden_dim = chunked_hidden_states.size()
chunked_hidden_states = nn.functional.pad(
chunked_hidden_states, (0, window_overlap + 1)
) # total_num_heads x num_chunks x window_overlap x (hidden_dim+window_overlap+1). Padding value is not important because it'll be overwritten
chunked_hidden_states = chunked_hidden_states.view(
total_num_heads, num_chunks, -1
) # total_num_heads x num_chunks x window_overlap*window_overlap+window_overlap
chunked_hidden_states = chunked_hidden_states[
:, :, :-window_overlap
] # total_num_heads x num_chunks x window_overlap*window_overlap
chunked_hidden_states = chunked_hidden_states.view(
total_num_heads, num_chunks, window_overlap, window_overlap + hidden_dim
)
chunked_hidden_states = chunked_hidden_states[:, :, :, :-1]
return chunked_hidden_states
@staticmethod
def _chunk(hidden_states, window_overlap, onnx_export: bool = False):
"""convert into overlapping chunks. Chunk size = 2w, overlap size = w"""
if not onnx_export:
# non-overlapping chunks of size = 2w
hidden_states = hidden_states.view(
hidden_states.size(0),
torch.div(hidden_states.size(1), (window_overlap * 2), rounding_mode="trunc"),
window_overlap * 2,
hidden_states.size(2),
)
# use `as_strided` to make the chunks overlap with an overlap size = window_overlap
chunk_size = list(hidden_states.size())
chunk_size[1] = chunk_size[1] * 2 - 1
chunk_stride = list(hidden_states.stride())
chunk_stride[1] = chunk_stride[1] // 2
return hidden_states.as_strided(size=chunk_size, stride=chunk_stride)
# When exporting to ONNX, use this separate logic
# have to use slow implementation since as_strided, unfold and 2d-tensor indexing aren't supported (yet) in ONNX export
# TODO replace this with
# > return hidden_states.unfold(dimension=1, size=window_overlap * 2, step=window_overlap).transpose(2, 3)
# once `unfold` is supported
# the case hidden_states.size(1) == window_overlap * 2 can also simply return hidden_states.unsqueeze(1), but that's control flow
chunk_size = [
hidden_states.size(0),
torch.div(hidden_states.size(1), window_overlap, rounding_mode="trunc") - 1,
window_overlap * 2,
hidden_states.size(2),
]
overlapping_chunks = torch.empty(chunk_size, device=hidden_states.device)
for chunk in range(chunk_size[1]):
overlapping_chunks[:, chunk, :, :] = hidden_states[
:, chunk * window_overlap : chunk * window_overlap + 2 * window_overlap, :
]
return overlapping_chunks
@staticmethod
def _mask_invalid_locations(input_tensor, affected_seq_len) -> torch.Tensor:
beginning_mask_2d = input_tensor.new_ones(affected_seq_len, affected_seq_len + 1).tril().flip(dims=[0])
beginning_mask = beginning_mask_2d[None, :, None, :]
ending_mask = beginning_mask.flip(dims=(1, 3))
beginning_input = input_tensor[:, :affected_seq_len, :, : affected_seq_len + 1]
beginning_mask = beginning_mask.expand(beginning_input.size())
input_tensor[:, :affected_seq_len, :, : affected_seq_len + 1] = torch.full_like(
beginning_input, -float("inf")
).where(beginning_mask.bool(), beginning_input)
ending_input = input_tensor[:, -affected_seq_len:, :, -(affected_seq_len + 1) :]
ending_mask = ending_mask.expand(ending_input.size())
input_tensor[:, -affected_seq_len:, :, -(affected_seq_len + 1) :] = torch.full_like(
ending_input, -float("inf")
).where(ending_mask.bool(), ending_input)
def _sliding_chunks_query_key_matmul(self, query: torch.Tensor, key: torch.Tensor, window_overlap: int):
"""
Matrix multiplication of query and key tensors using with a sliding window attention pattern. This
implementation splits the input into overlapping chunks of size 2w (e.g. 512 for pretrained Longformer) with an
overlap of size window_overlap
"""
batch_size, seq_len, num_heads, head_dim = query.size()
assert seq_len % (window_overlap * 2) == 0, (
f"Sequence length should be multiple of {window_overlap * 2}. Given {seq_len}"
)
assert query.size() == key.size()
chunks_count = torch.div(seq_len, window_overlap, rounding_mode="trunc") - 1
# group batch_size and num_heads dimensions into one, then chunk seq_len into chunks of size window_overlap * 2
query = query.transpose(1, 2).reshape(batch_size * num_heads, seq_len, head_dim)
key = key.transpose(1, 2).reshape(batch_size * num_heads, seq_len, head_dim)
query = self._chunk(query, window_overlap, getattr(self.config, "onnx_export", False))
key = self._chunk(key, window_overlap, getattr(self.config, "onnx_export", False))
# matrix multiplication
# bcxd: batch_size * num_heads x chunks x 2window_overlap x head_dim
# bcyd: batch_size * num_heads x chunks x 2window_overlap x head_dim
# bcxy: batch_size * num_heads x chunks x 2window_overlap x 2window_overlap
diagonal_chunked_attention_scores = torch.einsum("bcxd,bcyd->bcxy", (query, key)) # multiply
# convert diagonals into columns
diagonal_chunked_attention_scores = self._pad_and_transpose_last_two_dims(
diagonal_chunked_attention_scores, padding=(0, 0, 0, 1)
)
# allocate space for the overall attention matrix where the chunks are combined. The last dimension
# has (window_overlap * 2 + 1) columns. The first (window_overlap) columns are the window_overlap lower triangles (attention from a word to
# window_overlap previous words). The following column is attention score from each word to itself, then
# followed by window_overlap columns for the upper triangle.
diagonal_attention_scores = diagonal_chunked_attention_scores.new_zeros(
(batch_size * num_heads, chunks_count + 1, window_overlap, window_overlap * 2 + 1)
)
# copy parts from diagonal_chunked_attention_scores into the combined matrix of attentions
# - copying the main diagonal and the upper triangle
diagonal_attention_scores[:, :-1, :, window_overlap:] = diagonal_chunked_attention_scores[
:, :, :window_overlap, : window_overlap + 1
]
diagonal_attention_scores[:, -1, :, window_overlap:] = diagonal_chunked_attention_scores[
:, -1, window_overlap:, : window_overlap + 1
]
# - copying the lower triangle
diagonal_attention_scores[:, 1:, :, :window_overlap] = diagonal_chunked_attention_scores[
:, :, -(window_overlap + 1) : -1, window_overlap + 1 :
]
diagonal_attention_scores[:, 0, 1:window_overlap, 1:window_overlap] = diagonal_chunked_attention_scores[
:, 0, : window_overlap - 1, 1 - window_overlap :
]
# separate batch_size and num_heads dimensions again
diagonal_attention_scores = diagonal_attention_scores.view(
batch_size, num_heads, seq_len, 2 * window_overlap + 1
).transpose(2, 1)
self._mask_invalid_locations(diagonal_attention_scores, window_overlap)
return diagonal_attention_scores
def _sliding_chunks_matmul_attn_probs_value(
self, attn_probs: torch.Tensor, value: torch.Tensor, window_overlap: int
):
"""
Same as _sliding_chunks_query_key_matmul but for attn_probs and value tensors. Returned tensor will be of the
same shape as `attn_probs`
"""
batch_size, seq_len, num_heads, head_dim = value.size()
assert seq_len % (window_overlap * 2) == 0
assert attn_probs.size()[:3] == value.size()[:3]
assert attn_probs.size(3) == 2 * window_overlap + 1
chunks_count = torch.div(seq_len, window_overlap, rounding_mode="trunc") - 1
# group batch_size and num_heads dimensions into one, then chunk seq_len into chunks of size 2 window overlap
chunked_attn_probs = attn_probs.transpose(1, 2).reshape(
batch_size * num_heads,
torch.div(seq_len, window_overlap, rounding_mode="trunc"),
window_overlap,
2 * window_overlap + 1,
)
# group batch_size and num_heads dimensions into one
value = value.transpose(1, 2).reshape(batch_size * num_heads, seq_len, head_dim)
# pad seq_len with w at the beginning of the sequence and another window overlap at the end
padded_value = nn.functional.pad(value, (0, 0, window_overlap, window_overlap), value=-1)
# chunk padded_value into chunks of size 3 window overlap and an overlap of size window overlap
chunked_value_size = (batch_size * num_heads, chunks_count + 1, 3 * window_overlap, head_dim)
chunked_value_stride = padded_value.stride()
chunked_value_stride = (
chunked_value_stride[0],
window_overlap * chunked_value_stride[1],
chunked_value_stride[1],
chunked_value_stride[2],
)
chunked_value = padded_value.as_strided(size=chunked_value_size, stride=chunked_value_stride)
chunked_attn_probs = self._pad_and_diagonalize(chunked_attn_probs)
context = torch.einsum("bcwd,bcdh->bcwh", (chunked_attn_probs, chunked_value))
return context.view(batch_size, num_heads, seq_len, head_dim).transpose(1, 2)
@staticmethod
def _get_global_attn_indices(is_index_global_attn):
"""compute global attn indices required throughout forward pass"""
# helper variable
num_global_attn_indices = is_index_global_attn.long().sum(dim=1)
# max number of global attn indices in batch
max_num_global_attn_indices = num_global_attn_indices.max()
# indices of global attn
is_index_global_attn_nonzero = is_index_global_attn.nonzero(as_tuple=True)
# helper variable
is_local_index_global_attn = torch.arange(
max_num_global_attn_indices, device=is_index_global_attn.device
) < num_global_attn_indices.unsqueeze(dim=-1)
# location of the non-padding values within global attention indices
is_local_index_global_attn_nonzero = is_local_index_global_attn.nonzero(as_tuple=True)
# location of the padding values within global attention indices
is_local_index_no_global_attn_nonzero = (is_local_index_global_attn == 0).nonzero(as_tuple=True)
return (
max_num_global_attn_indices,
is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero,
)
def _concat_with_global_key_attn_probs(
self,
key_vectors,
query_vectors,
max_num_global_attn_indices,
is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero,
):
batch_size = key_vectors.shape[0]
# create only global key vectors
key_vectors_only_global = key_vectors.new_zeros(
batch_size, max_num_global_attn_indices, self.num_heads, self.head_dim
)
key_vectors_only_global[is_local_index_global_attn_nonzero] = key_vectors[is_index_global_attn_nonzero]
# (batch_size, seq_len, num_heads, max_num_global_attn_indices)
attn_probs_from_global_key = torch.einsum("blhd,bshd->blhs", (query_vectors, key_vectors_only_global))
# need to transpose since ONNX export only supports consecutive indexing: https://pytorch.org/docs/stable/onnx.html#writes-sets
attn_probs_from_global_key = attn_probs_from_global_key.transpose(1, 3)
attn_probs_from_global_key[
is_local_index_no_global_attn_nonzero[0], is_local_index_no_global_attn_nonzero[1], :, :
] = torch.finfo(attn_probs_from_global_key.dtype).min
attn_probs_from_global_key = attn_probs_from_global_key.transpose(1, 3)
return attn_probs_from_global_key
def _compute_attn_output_with_global_indices(
self,
value_vectors,
attn_probs,
max_num_global_attn_indices,
is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero,
):
batch_size = attn_probs.shape[0]
# cut local attn probs to global only
attn_probs_only_global = attn_probs.narrow(-1, 0, max_num_global_attn_indices)
# get value vectors for global only
value_vectors_only_global = value_vectors.new_zeros(
batch_size, max_num_global_attn_indices, self.num_heads, self.head_dim
)
value_vectors_only_global[is_local_index_global_attn_nonzero] = value_vectors[is_index_global_attn_nonzero]
# use `matmul` because `einsum` crashes sometimes with fp16
# attn = torch.einsum('blhs,bshd->blhd', (selected_attn_probs, selected_v))
# compute attn output only global
attn_output_only_global = torch.matmul(
attn_probs_only_global.transpose(1, 2).clone(), value_vectors_only_global.transpose(1, 2).clone()
).transpose(1, 2)
# reshape attn probs
attn_probs_without_global = attn_probs.narrow(
-1, max_num_global_attn_indices, attn_probs.size(-1) - max_num_global_attn_indices
).contiguous()
# compute attn output with global
attn_output_without_global = self._sliding_chunks_matmul_attn_probs_value(
attn_probs_without_global, value_vectors, self.one_sided_attn_window_size
)
return attn_output_only_global + attn_output_without_global
def _compute_global_attn_output_from_hidden(
self,
hidden_states,
max_num_global_attn_indices,
is_local_index_global_attn_nonzero,
is_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero,
is_index_masked,
):
seq_len, batch_size = hidden_states.shape[:2]
# prepare global hidden states
global_attn_hidden_states = hidden_states.new_zeros(max_num_global_attn_indices, batch_size, self.embed_dim)
global_attn_hidden_states[is_local_index_global_attn_nonzero[::-1]] = hidden_states[
is_index_global_attn_nonzero[::-1]
]
# global key, query, value
global_query_vectors_only_global = self.query_global(global_attn_hidden_states)
global_key_vectors = self.key_global(hidden_states)
global_value_vectors = self.value_global(hidden_states)
# normalize
global_query_vectors_only_global /= math.sqrt(self.head_dim)
# reshape
global_query_vectors_only_global = (
global_query_vectors_only_global.contiguous()
.view(max_num_global_attn_indices, batch_size * self.num_heads, self.head_dim)
.transpose(0, 1)
) # (batch_size * self.num_heads, max_num_global_attn_indices, head_dim)
global_key_vectors = (
global_key_vectors.contiguous().view(-1, batch_size * self.num_heads, self.head_dim).transpose(0, 1)
) # batch_size * self.num_heads, seq_len, head_dim)
global_value_vectors = (
global_value_vectors.contiguous().view(-1, batch_size * self.num_heads, self.head_dim).transpose(0, 1)
) # batch_size * self.num_heads, seq_len, head_dim)
# compute attn scores
global_attn_scores = torch.bmm(global_query_vectors_only_global, global_key_vectors.transpose(1, 2))
assert list(global_attn_scores.size()) == [
batch_size * self.num_heads,
max_num_global_attn_indices,
seq_len,
], (
"global_attn_scores have the wrong size. Size should be"
f" {(batch_size * self.num_heads, max_num_global_attn_indices, seq_len)}, but is"
f" {global_attn_scores.size()}."
)
global_attn_scores = global_attn_scores.view(batch_size, self.num_heads, max_num_global_attn_indices, seq_len)
# need to transpose since ONNX export only supports consecutive indexing: https://pytorch.org/docs/stable/onnx.html#writes-sets
global_attn_scores = global_attn_scores.transpose(1, 2)
global_attn_scores[
is_local_index_no_global_attn_nonzero[0], is_local_index_no_global_attn_nonzero[1], :, :
] = torch.finfo(global_attn_scores.dtype).min
global_attn_scores = global_attn_scores.transpose(1, 2)
global_attn_scores = global_attn_scores.masked_fill(
is_index_masked[:, None, None, :],
torch.finfo(global_attn_scores.dtype).min,
)
global_attn_scores = global_attn_scores.view(batch_size * self.num_heads, max_num_global_attn_indices, seq_len)
# compute global attn probs
global_attn_probs_float = nn.functional.softmax(
global_attn_scores, dim=-1, dtype=torch.float32
) # use fp32 for numerical stability
global_attn_probs = nn.functional.dropout(
global_attn_probs_float.type_as(global_attn_scores), p=self.dropout, training=self.training
)
# global attn output
global_attn_output = torch.bmm(global_attn_probs, global_value_vectors)
assert list(global_attn_output.size()) == [
batch_size * self.num_heads,
max_num_global_attn_indices,
self.head_dim,
], (
"global_attn_output tensor has the wrong size. Size should be"
f" {(batch_size * self.num_heads, max_num_global_attn_indices, self.head_dim)}, but is"
f" {global_attn_output.size()}."
)
global_attn_probs = global_attn_probs.view(batch_size, self.num_heads, max_num_global_attn_indices, seq_len)
global_attn_output = global_attn_output.view(
batch_size, self.num_heads, max_num_global_attn_indices, self.head_dim
)
return global_attn_output, global_attn_probs
# Copied from transformers.models.bert.modeling_bert.BertSelfOutput
|
LongformerSelfAttention
|
python
|
sqlalchemy__sqlalchemy
|
test/orm/test_options.py
|
{
"start": 41430,
"end": 42927
}
|
class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"users",
metadata,
Column("id", Integer, primary_key=True),
Column("name", String(30), nullable=False),
)
Table(
"addresses",
metadata,
Column("id", Integer, primary_key=True),
Column("user_id", None, ForeignKey("users.id")),
Column("email_address", String(50), nullable=False),
)
@testing.fixture
def user_address_fixture(self, registry):
registry.map_imperatively(
User,
self.tables.users,
properties={"addresses": relationship(Address)},
)
registry.map_imperatively(Address, self.tables.addresses)
return User, Address
def test_slots(self, user_address_fixture):
User, Address = user_address_fixture
opt = joinedload(User.addresses)
assert not hasattr(opt, "__dict__")
assert not hasattr(opt.context[0], "__dict__")
def test_pickle_relationship_loader(self, user_address_fixture):
User, Address = user_address_fixture
opt = joinedload(User.addresses)
pickled = pickle.dumps(opt)
opt2 = pickle.loads(pickled)
is_not(opt, opt2)
assert isinstance(opt, Load)
assert isinstance(opt2, Load)
for k in opt.__slots__:
eq_(getattr(opt, k), getattr(opt2, k))
|
PickleTest
|
python
|
ray-project__ray
|
python/ray/_private/thirdparty/pynvml/pynvml.py
|
{
"start": 262714,
"end": 264045
}
|
class ____(_PrintableStructure):
_fields_ = [
('version', c_uint),
('entryCount', c_uint),
('entries', POINTER(c_nvmlEccSramUniqueUncorrectedErrorEntry_v1_t))
]
def __init__(self):
super(c_nvmlEccSramUniqueUncorrectedErrorCounts_v1_t, self).__init__(version=nvmlEccSramUniqueUncorrectedErrorCounts_v1)
nvmlEccSramUniqueUncorrectedErrorCounts_v1 = 0x1000010
def nvmlDeviceGetSramUniqueUncorrectedEccErrorCounts(device, counts):
fn = _nvmlGetFunctionPointer("nvmlDeviceGetSramUniqueUncorrectedEccErrorCounts")
ret = fn(device, counts)
_nvmlCheckReturn(ret)
return NVML_SUCCESS
def nvmlDeviceGetPdi(device):
c_pdi = c_nvmlPdi_t()
fn = _nvmlGetFunctionPointer("nvmlDeviceGetPdi")
ret = fn(device, byref(c_pdi))
_nvmlCheckReturn(ret)
return c_pdi.value
def nvmlDeviceGetNvLinkInfo(device, info):
fn = _nvmlGetFunctionPointer("nvmlDeviceGetNvLinkInfo");
ret = fn(device, info)
_nvmlCheckReturn(ret)
return NVML_SUCCESS
def nvmlDeviceGetRepairStatus(device):
c_status = c_nvmlRepairStatus_t()
fn = _nvmlGetFunctionPointer("nvmlDeviceGetRepairStatus")
ret = fn(device, byref(c_status))
_nvmlCheckReturn(ret)
return [c_status.bChannelRepairPending, c_status.bTpcRepairPending]
|
c_nvmlEccSramUniqueUncorrectedErrorCounts_v1_t
|
python
|
apache__avro
|
lang/py/avro/schema.py
|
{
"start": 10288,
"end": 12003
}
|
class ____(Schema):
"""Named Schemas specified in NAMED_TYPES."""
def __init__(
self,
type_: str,
name: str,
namespace: Optional[str] = None,
names: Optional[Names] = None,
other_props: Optional[Mapping[str, object]] = None,
validate_names: bool = True,
) -> None:
super().__init__(type_, other_props, validate_names=validate_names)
if not name:
raise avro.errors.SchemaParseException("Named Schemas must have a non-empty name.")
if not isinstance(name, str):
raise avro.errors.SchemaParseException("The name property must be a string.")
if namespace is not None and not isinstance(namespace, str):
raise avro.errors.SchemaParseException("The namespace property must be a string.")
namespace = namespace or None # Empty string -> None
names = names or Names(validate_names=self.validate_names)
new_name = names.add_name(name, namespace, self)
# Store name and namespace as they were read in origin schema
self.set_prop("name", new_name.name)
if new_name.space:
self.set_prop("namespace", new_name.space)
# Store full name as calculated from name, namespace
self._fullname = new_name.fullname
def name_ref(self, names):
return self.name if self.namespace == names.default_namespace else self.fullname
# read-only properties
@property
def name(self):
return self.get_prop("name")
@property
def namespace(self):
return self.get_prop("namespace")
@property
def fullname(self):
return self._fullname
#
# Logical type class
#
|
NamedSchema
|
python
|
pypa__pipenv
|
pipenv/patched/pip/_vendor/rich/align.py
|
{
"start": 7941,
"end": 10529
}
|
class ____(JupyterMixin):
"""Vertically aligns a renderable.
Warn:
This class is deprecated and may be removed in a future version. Use Align class with
`vertical="middle"`.
Args:
renderable (RenderableType): A renderable object.
style (StyleType, optional): An optional style to apply to the background. Defaults to None.
"""
def __init__(
self,
renderable: "RenderableType",
style: Optional[StyleType] = None,
) -> None:
self.renderable = renderable
self.style = style
def __repr__(self) -> str:
return f"VerticalCenter({self.renderable!r})"
def __rich_console__(
self, console: "Console", options: "ConsoleOptions"
) -> "RenderResult":
style = console.get_style(self.style) if self.style is not None else None
lines = console.render_lines(
self.renderable, options.update(height=None), pad=False
)
width, _height = Segment.get_shape(lines)
new_line = Segment.line()
height = options.height or options.size.height
top_space = (height - len(lines)) // 2
bottom_space = height - top_space - len(lines)
blank_line = Segment(f"{' ' * width}", style)
def blank_lines(count: int) -> Iterable[Segment]:
for _ in range(count):
yield blank_line
yield new_line
if top_space > 0:
yield from blank_lines(top_space)
for line in lines:
yield from line
yield new_line
if bottom_space > 0:
yield from blank_lines(bottom_space)
def __rich_measure__(
self, console: "Console", options: "ConsoleOptions"
) -> Measurement:
measurement = Measurement.get(console, options, self.renderable)
return measurement
if __name__ == "__main__": # pragma: no cover
from pipenv.patched.pip._vendor.rich.console import Console, Group
from pipenv.patched.pip._vendor.rich.highlighter import ReprHighlighter
from pipenv.patched.pip._vendor.rich.panel import Panel
highlighter = ReprHighlighter()
console = Console()
panel = Panel(
Group(
Align.left(highlighter("align='left'")),
Align.center(highlighter("align='center'")),
Align.right(highlighter("align='right'")),
),
width=60,
style="on dark_blue",
title="Align",
)
console.print(
Align.center(panel, vertical="middle", style="on red", height=console.height)
)
|
VerticalCenter
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.