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 | chardet__chardet | chardet/enums.py | {
"start": 712,
"end": 873
} | class ____(Enum):
"""
This enum represents the different states a prober can be in.
"""
DETECTING = 0
FOUND_IT = 1
NOT_ME = 2
| ProbingState |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/solver30.py | {
"start": 276,
"end": 409
} | class ____:
foo: bool
items = [Item()]
def func1(a: Iterable[X]) -> X: ...
def func2(a: Iterable[Y]) -> Iterable[Y]: ...
| Item |
python | huggingface__transformers | src/transformers/models/funnel/modeling_funnel.py | {
"start": 2110,
"end": 15563
} | class ____(nn.Module):
"""
Contains helpers for `FunnelRelMultiheadAttention `.
"""
cls_token_type_id: int = 2
def __init__(self, config: FunnelConfig) -> None:
super().__init__()
self.config = config
self.sin_dropout = nn.Dropout(config.hidden_dropout)
self.cos_dropout = nn.Dropout(config.hidden_dropout)
# Track where we are at in terms of pooling from the original input, e.g., by how much the sequence length was
# divided.
self.pooling_mult = None
def init_attention_inputs(
self,
inputs_embeds: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
) -> tuple[torch.Tensor]:
"""Returns the attention inputs associated to the inputs of the model."""
# inputs_embeds has shape batch_size x seq_len x d_model
# attention_mask and token_type_ids have shape batch_size x seq_len
self.pooling_mult = 1
self.seq_len = seq_len = inputs_embeds.size(1)
position_embeds = self.get_position_embeds(seq_len, inputs_embeds.dtype, inputs_embeds.device)
token_type_mat = self.token_type_ids_to_mat(token_type_ids) if token_type_ids is not None else None
cls_mask = (
nn.functional.pad(inputs_embeds.new_ones([seq_len - 1, seq_len - 1]), (1, 0, 1, 0))
if self.config.separate_cls
else None
)
return (position_embeds, token_type_mat, attention_mask, cls_mask)
def token_type_ids_to_mat(self, token_type_ids: torch.Tensor) -> torch.Tensor:
"""Convert `token_type_ids` to `token_type_mat`."""
token_type_mat = token_type_ids[:, :, None] == token_type_ids[:, None]
# Treat <cls> as in the same segment as both A & B
cls_ids = token_type_ids == self.cls_token_type_id
cls_mat = cls_ids[:, :, None] | cls_ids[:, None]
return cls_mat | token_type_mat
def get_position_embeds(
self, seq_len: int, dtype: torch.dtype, device: torch.device
) -> Union[tuple[torch.Tensor], list[list[torch.Tensor]]]:
"""
Create and cache inputs related to relative position encoding. Those are very different depending on whether we
are using the factorized or the relative shift attention:
For the factorized attention, it returns the matrices (phi, pi, psi, omega) used in the paper, appendix A.2.2,
final formula.
For the relative shift attention, it returns all possible vectors R used in the paper, appendix A.2.1, final
formula.
Paper link: https://huggingface.co/papers/2006.03236
"""
d_model = self.config.d_model
if self.config.attention_type == "factorized":
# Notations from the paper, appending A.2.2, final formula.
# We need to create and return the matrices phi, psi, pi and omega.
pos_seq = torch.arange(0, seq_len, 1.0, dtype=torch.int64, device=device).to(dtype)
freq_seq = torch.arange(0, d_model // 2, 1.0, dtype=torch.int64, device=device).to(dtype)
inv_freq = 1 / (10000 ** (freq_seq / (d_model // 2)))
sinusoid = pos_seq[:, None] * inv_freq[None]
sin_embed = torch.sin(sinusoid)
sin_embed_d = self.sin_dropout(sin_embed)
cos_embed = torch.cos(sinusoid)
cos_embed_d = self.cos_dropout(cos_embed)
# This is different from the formula on the paper...
phi = torch.cat([sin_embed_d, sin_embed_d], dim=-1)
psi = torch.cat([cos_embed, sin_embed], dim=-1)
pi = torch.cat([cos_embed_d, cos_embed_d], dim=-1)
omega = torch.cat([-sin_embed, cos_embed], dim=-1)
return (phi, pi, psi, omega)
else:
# Notations from the paper, appending A.2.1, final formula.
# We need to create and return all the possible vectors R for all blocks and shifts.
freq_seq = torch.arange(0, d_model // 2, 1.0, dtype=torch.int64, device=device).to(dtype)
inv_freq = 1 / (10000 ** (freq_seq / (d_model // 2)))
# Maximum relative positions for the first input
rel_pos_id = torch.arange(-seq_len * 2, seq_len * 2, 1.0, dtype=torch.int64, device=device).to(dtype)
zero_offset = seq_len * 2
sinusoid = rel_pos_id[:, None] * inv_freq[None]
sin_embed = self.sin_dropout(torch.sin(sinusoid))
cos_embed = self.cos_dropout(torch.cos(sinusoid))
pos_embed = torch.cat([sin_embed, cos_embed], dim=-1)
pos = torch.arange(0, seq_len, dtype=torch.int64, device=device).to(dtype)
pooled_pos = pos
position_embeds_list = []
for block_index in range(0, self.config.num_blocks):
# For each block with block_index > 0, we need two types position embeddings:
# - Attention(pooled-q, unpooled-kv)
# - Attention(pooled-q, pooled-kv)
# For block_index = 0 we only need the second one and leave the first one as None.
# First type
if block_index == 0:
position_embeds_pooling = None
else:
pooled_pos = self.stride_pool_pos(pos, block_index)
# construct rel_pos_id
stride = 2 ** (block_index - 1)
rel_pos = self.relative_pos(pos, stride, pooled_pos, shift=2)
rel_pos = rel_pos[:, None] + zero_offset
rel_pos = rel_pos.expand(rel_pos.size(0), d_model)
position_embeds_pooling = torch.gather(pos_embed, 0, rel_pos)
# Second type
pos = pooled_pos
stride = 2**block_index
rel_pos = self.relative_pos(pos, stride)
rel_pos = rel_pos[:, None] + zero_offset
rel_pos = rel_pos.expand(rel_pos.size(0), d_model)
position_embeds_no_pooling = torch.gather(pos_embed, 0, rel_pos)
position_embeds_list.append([position_embeds_no_pooling, position_embeds_pooling])
return position_embeds_list
def stride_pool_pos(self, pos_id: torch.Tensor, block_index: int):
"""
Pool `pos_id` while keeping the cls token separate (if `config.separate_cls=True`).
"""
if self.config.separate_cls:
# Under separate <cls>, we treat the <cls> as the first token in
# the previous block of the 1st real block. Since the 1st real
# block always has position 1, the position of the previous block
# will be at `1 - 2 ** block_index`.
cls_pos = pos_id.new_tensor([-(2**block_index) + 1])
pooled_pos_id = pos_id[1:-1] if self.config.truncate_seq else pos_id[1:]
return torch.cat([cls_pos, pooled_pos_id[::2]], 0)
else:
return pos_id[::2]
def relative_pos(self, pos: torch.Tensor, stride: int, pooled_pos=None, shift: int = 1) -> torch.Tensor:
"""
Build the relative positional vector between `pos` and `pooled_pos`.
"""
if pooled_pos is None:
pooled_pos = pos
ref_point = pooled_pos[0] - pos[0]
num_remove = shift * len(pooled_pos)
max_dist = ref_point + num_remove * stride
min_dist = pooled_pos[0] - pos[-1]
return torch.arange(max_dist, min_dist - 1, -stride, dtype=torch.long, device=pos.device)
def stride_pool(
self,
tensor: Union[torch.Tensor, tuple[torch.Tensor], list[torch.Tensor]],
axis: Union[int, tuple[int], list[int]],
) -> torch.Tensor:
"""
Perform pooling by stride slicing the tensor along the given axis.
"""
if tensor is None:
return None
# Do the stride pool recursively if axis is a list or a tuple of ints.
if isinstance(axis, (list, tuple)):
for ax in axis:
tensor = self.stride_pool(tensor, ax)
return tensor
# Do the stride pool recursively if tensor is a list or tuple of tensors.
if isinstance(tensor, (tuple, list)):
return type(tensor)(self.stride_pool(x, axis) for x in tensor)
# Deal with negative axis
axis %= tensor.ndim
axis_slice = (
slice(None, -1, 2) if self.config.separate_cls and self.config.truncate_seq else slice(None, None, 2)
)
enc_slice = [slice(None)] * axis + [axis_slice]
if self.config.separate_cls:
cls_slice = [slice(None)] * axis + [slice(None, 1)]
tensor = torch.cat([tensor[cls_slice], tensor], axis=axis)
return tensor[enc_slice]
def pool_tensor(
self, tensor: Union[torch.Tensor, tuple[torch.Tensor], list[torch.Tensor]], mode: str = "mean", stride: int = 2
) -> torch.Tensor:
"""Apply 1D pooling to a tensor of size [B x T (x H)]."""
if tensor is None:
return None
# Do the pool recursively if tensor is a list or tuple of tensors.
if isinstance(tensor, (tuple, list)):
return type(tensor)(self.pool_tensor(tensor, mode=mode, stride=stride) for x in tensor)
if self.config.separate_cls:
suffix = tensor[:, :-1] if self.config.truncate_seq else tensor
tensor = torch.cat([tensor[:, :1], suffix], dim=1)
ndim = tensor.ndim
if ndim == 2:
tensor = tensor[:, None, :, None]
elif ndim == 3:
tensor = tensor[:, None, :, :]
# Stride is applied on the second-to-last dimension.
stride = (stride, 1)
if mode == "mean":
tensor = nn.functional.avg_pool2d(tensor, stride, stride=stride, ceil_mode=True)
elif mode == "max":
tensor = nn.functional.max_pool2d(tensor, stride, stride=stride, ceil_mode=True)
elif mode == "min":
tensor = -nn.functional.max_pool2d(-tensor, stride, stride=stride, ceil_mode=True)
else:
raise NotImplementedError("The supported modes are 'mean', 'max' and 'min'.")
if ndim == 2:
return tensor[:, 0, :, 0]
elif ndim == 3:
return tensor[:, 0]
return tensor
def pre_attention_pooling(
self, output, attention_inputs: tuple[torch.Tensor]
) -> tuple[torch.Tensor, tuple[torch.Tensor]]:
"""Pool `output` and the proper parts of `attention_inputs` before the attention layer."""
position_embeds, token_type_mat, attention_mask, cls_mask = attention_inputs
if self.config.pool_q_only:
if self.config.attention_type == "factorized":
position_embeds = self.stride_pool(position_embeds[:2], 0) + position_embeds[2:]
token_type_mat = self.stride_pool(token_type_mat, 1)
cls_mask = self.stride_pool(cls_mask, 0)
output = self.pool_tensor(output, mode=self.config.pooling_type)
else:
self.pooling_mult *= 2
if self.config.attention_type == "factorized":
position_embeds = self.stride_pool(position_embeds, 0)
token_type_mat = self.stride_pool(token_type_mat, [1, 2])
cls_mask = self.stride_pool(cls_mask, [1, 2])
attention_mask = self.pool_tensor(attention_mask, mode="min")
output = self.pool_tensor(output, mode=self.config.pooling_type)
attention_inputs = (position_embeds, token_type_mat, attention_mask, cls_mask)
return output, attention_inputs
def post_attention_pooling(self, attention_inputs: tuple[torch.Tensor]) -> tuple[torch.Tensor]:
"""Pool the proper parts of `attention_inputs` after the attention layer."""
position_embeds, token_type_mat, attention_mask, cls_mask = attention_inputs
if self.config.pool_q_only:
self.pooling_mult *= 2
if self.config.attention_type == "factorized":
position_embeds = position_embeds[:2] + self.stride_pool(position_embeds[2:], 0)
token_type_mat = self.stride_pool(token_type_mat, 2)
cls_mask = self.stride_pool(cls_mask, 1)
attention_mask = self.pool_tensor(attention_mask, mode="min")
attention_inputs = (position_embeds, token_type_mat, attention_mask, cls_mask)
return attention_inputs
def _relative_shift_gather(positional_attn: torch.Tensor, context_len: int, shift: int) -> torch.Tensor:
batch_size, n_head, seq_len, max_rel_len = positional_attn.shape
# max_rel_len = 2 * context_len + shift -1 is the numbers of possible relative positions i-j
# What's next is the same as doing the following gather, which might be clearer code but less efficient.
# idxs = context_len + torch.arange(0, context_len).unsqueeze(0) - torch.arange(0, seq_len).unsqueeze(1)
# # matrix of context_len + i-j
# return positional_attn.gather(3, idxs.expand([batch_size, n_head, context_len, context_len]))
positional_attn = torch.reshape(positional_attn, [batch_size, n_head, max_rel_len, seq_len])
positional_attn = positional_attn[:, :, shift:, :]
positional_attn = torch.reshape(positional_attn, [batch_size, n_head, seq_len, max_rel_len - shift])
positional_attn = positional_attn[..., :context_len]
return positional_attn
| FunnelAttentionStructure |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-llama-api/llama_index/llms/llama_api/base.py | {
"start": 171,
"end": 1356
} | class ____(OpenAILike):
"""
LlamaAPI LLM.
Examples:
`pip install llama-index-llms-llama-api`
```python
from llama_index.llms.llama_api import LlamaAPI
# Obtain an API key from https://www.llama-api.com/
api_key = "your-api-key"
llm = LlamaAPI(model="llama3.1-8b", context_window=128000, is_function_calling_model=True, api_key=api_key)
# Call the complete method with a prompt
resp = llm.complete("Paul Graham is ")
print(resp)
```
"""
model: str = Field(
default="llama3.1-8b",
description=LLMMetadata.model_fields["model_name"].description,
)
api_base: str = Field(
default="https://api.llmapi.com/",
description="The base URL for OpenAI API.",
)
is_chat_model: bool = Field(
default=True,
description=LLMMetadata.model_fields["is_chat_model"].description,
)
is_function_calling_model: bool = Field(
default=False,
description=LLMMetadata.model_fields["is_function_calling_model"].description,
)
@classmethod
def class_name(cls) -> str:
return "llama_api_llm"
| LlamaAPI |
python | tensorflow__tensorflow | tensorflow/python/data/ops/dataset_ops.py | {
"start": 186050,
"end": 186466
} | class ____(UnaryDataset):
"""Represents a unary dataset with the same input and output structure."""
def __init__(self, input_dataset: DatasetV2, variant_tensor):
self._input_dataset = input_dataset
super(UnaryUnchangedStructureDataset, self).__init__(
input_dataset, variant_tensor)
@property
def element_spec(self):
return self._input_dataset.element_spec
| UnaryUnchangedStructureDataset |
python | sympy__sympy | sympy/printing/lambdarepr.py | {
"start": 426,
"end": 2114
} | class ____(PythonCodePrinter):
"""
This printer converts expressions into strings that can be used by
lambdify.
"""
printmethod = "_lambdacode"
def _print_And(self, expr):
result = ['(']
for arg in sorted(expr.args, key=default_sort_key):
result.extend(['(', self._print(arg), ')'])
result.append(' and ')
result = result[:-1]
result.append(')')
return ''.join(result)
def _print_Or(self, expr):
result = ['(']
for arg in sorted(expr.args, key=default_sort_key):
result.extend(['(', self._print(arg), ')'])
result.append(' or ')
result = result[:-1]
result.append(')')
return ''.join(result)
def _print_Not(self, expr):
result = ['(', 'not (', self._print(expr.args[0]), '))']
return ''.join(result)
def _print_BooleanTrue(self, expr):
return "True"
def _print_BooleanFalse(self, expr):
return "False"
def _print_ITE(self, expr):
result = [
'((', self._print(expr.args[1]),
') if (', self._print(expr.args[0]),
') else (', self._print(expr.args[2]), '))'
]
return ''.join(result)
def _print_NumberSymbol(self, expr):
return str(expr)
def _print_Pow(self, expr, **kwargs):
# XXX Temporary workaround. Should Python math printer be
# isolated from PythonCodePrinter?
return super(PythonCodePrinter, self)._print_Pow(expr, **kwargs)
# numexpr works by altering the string passed to numexpr.evaluate
# rather than by populating a namespace. Thus a special printer...
| LambdaPrinter |
python | pytorch__pytorch | torch/testing/_internal/common_device_type.py | {
"start": 24079,
"end": 24948
} | class ____(DeviceTypeTestBase):
device_type = "xpu"
primary_device: ClassVar[str]
@classmethod
def get_primary_device(cls):
return cls.primary_device
@classmethod
def get_all_devices(cls):
# currently only one device is supported on MPS backend
primary_device_idx = int(cls.get_primary_device().split(":")[1])
num_devices = torch.xpu.device_count()
prim_device = cls.get_primary_device()
xpu_str = "xpu:{0}"
non_primary_devices = [
xpu_str.format(idx)
for idx in range(num_devices)
if idx != primary_device_idx
]
return [prim_device] + non_primary_devices
@classmethod
def setUpClass(cls):
cls.primary_device = f"xpu:{torch.xpu.current_device()}"
def _should_stop_test_suite(self):
return False
| XPUTestBase |
python | PrefectHQ__prefect | src/prefect/artifacts.py | {
"start": 8639,
"end": 9096
} | class ____(Artifact):
link: str
link_text: Optional[str] = None
type: Optional[str] = "markdown"
def _format(self) -> str:
return (
f"[{self.link_text}]({self.link})"
if self.link_text
else f"[{self.link}]({self.link})"
)
async def aformat(self) -> str:
return self._format()
@async_dispatch(aformat)
def format(self) -> str:
return self._format()
| LinkArtifact |
python | OmkarPathak__pygorithm | tests/test_sorting.py | {
"start": 3780,
"end": 3961
} | class ____(unittest.TestCase, TestSortingAlgorithm):
inplace = True
alph_support = True
@staticmethod
def sort(arr):
return shell_sort.sort(arr)
| TestShellSort |
python | wandb__wandb | wandb/apis/public/artifacts.py | {
"start": 8630,
"end": 11183
} | class ____(
SizedRelayPaginator["ArtifactCollectionFragment", "ArtifactCollection"]
):
"""Artifact collections of a specific type in a project.
Args:
client: The client instance to use for querying W&B.
entity: The entity (user or team) that owns the project.
project: The name of the project to query for artifact collections.
type_name: The name of the artifact type for which to fetch collections.
per_page: The number of artifact collections to fetch per page. Default is 50.
<!-- lazydoc-ignore-init: internal -->
"""
QUERY: ClassVar[Document | None] = None
last_response: ArtifactCollectionConnection | None
def __init__(
self,
client: Client,
entity: str,
project: str,
type_name: str,
per_page: int = 50,
):
if self.QUERY is None:
from wandb.sdk.artifacts._generated import PROJECT_ARTIFACT_COLLECTIONS_GQL
type(self).QUERY = gql(PROJECT_ARTIFACT_COLLECTIONS_GQL)
self.entity = entity
self.project = project
self.type_name = type_name
variables = {"entity": entity, "project": project, "artifactType": type_name}
super().__init__(client, variables=variables, per_page=per_page)
@override
def _update_response(self) -> None:
"""Fetch and validate the response data for the current page."""
from wandb.sdk.artifacts._generated import ProjectArtifactCollections
from wandb.sdk.artifacts._models.pagination import ArtifactCollectionConnection
data = self.client.execute(self.QUERY, variable_values=self.variables)
result = ProjectArtifactCollections.model_validate(data)
# Extract the inner `*Connection` result for faster/easier access.
if not (
(proj := result.project)
and (artifact_type := proj.artifact_type)
and (conn := artifact_type.artifact_collections)
):
raise ValueError(f"Unable to parse {nameof(type(self))!r} response data")
self.last_response = ArtifactCollectionConnection.model_validate(conn)
def _convert(self, node: ArtifactCollectionFragment) -> ArtifactCollection | None:
if not node.project:
return None
return ArtifactCollection(
client=self.client,
entity=node.project.entity.name,
project=node.project.name,
name=node.name,
type=node.type.name,
attrs=node,
)
| ArtifactCollections |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/transfers/test_s3_to_wasb.py | {
"start": 2610,
"end": 12973
} | class ____:
def test__init__(self):
# Create a mock operator with a single set of parameters that are used to test the __init__()
# constructor. Not every parameter needs to be provided, as this code will also be used to test the
# default parameters that are configured
operator = S3ToAzureBlobStorageOperator(
task_id=TASK_ID,
s3_bucket=S3_BUCKET,
s3_prefix=PREFIX,
container_name=CONTAINER_NAME,
blob_prefix=PREFIX,
replace=True,
)
# ... is None is used to validate if a value is None, while not ... is used to evaluate if a value
# is False
assert operator.task_id == TASK_ID
assert operator.aws_conn_id == "aws_default"
assert operator.wasb_conn_id == "wasb_default"
assert operator.s3_bucket == S3_BUCKET
assert operator.container_name == CONTAINER_NAME
assert operator.s3_prefix == PREFIX
assert operator.s3_key is None
assert operator.blob_prefix == PREFIX
assert operator.blob_name is None
assert not operator.create_container # Should be false (match default value in constructor)
assert operator.replace
assert not operator.s3_verify # Should be false (match default value in constructor)
assert operator.s3_extra_args == {}
assert operator.wasb_extra_args == {}
@mock.patch("airflow.providers.microsoft.azure.transfers.s3_to_wasb.S3Hook")
@mock.patch("airflow.providers.microsoft.azure.transfers.s3_to_wasb.WasbHook")
@mock.patch("tempfile.NamedTemporaryFile")
def test__execute__prefix_without_replace_empty_destination(
self, tempfile_mock, wasb_mock_hook, s3_mock_hook
):
# Set the list files that the S3Hook should return, along with an empty list of files in the Azure
# Blob storage container. This scenario was picked for testing, as it's most likely the most common
# setting the operator will be used in
s3_mock_hook.return_value.list_keys.return_value = MOCK_FILES
wasb_mock_hook.return_value.get_blobs_list_recursive.return_value = []
s3_mock_hook.return_value.download_file.return_value = BytesIO().write(b"test file contents")
tempfile_mock.return_value.__enter__.return_value.name = TEMPFILE_NAME
operator = S3ToAzureBlobStorageOperator(
task_id=TASK_ID,
s3_bucket=S3_BUCKET,
s3_prefix=PREFIX,
container_name=CONTAINER_NAME,
blob_prefix=PREFIX,
)
# Placing an empty "context" object here (using None)
uploaded_files = operator.execute(None)
assert sorted(uploaded_files) == sorted(MOCK_FILES)
# Using the default connection ID, along with the default value of verify (for the S3 hook)
s3_mock_hook.assert_called_once_with(aws_conn_id="aws_default", verify=False)
wasb_mock_hook.assert_called_once_with(wasb_conn_id="wasb_default")
# There are a number of very similar tests that use the same mocking, and for the most part, the same
# logic. These tests are used to validate the records being returned by the get_files_to_move() method,
# which heavily drives the successful execution of the operator
@mock.patch("airflow.providers.microsoft.azure.transfers.s3_to_wasb.S3Hook")
@mock.patch("airflow.providers.microsoft.azure.transfers.s3_to_wasb.WasbHook")
@pytest.mark.parametrize( # Please see line 37 above for args used for parametrization
("s3_existing_files", "wasb_existing_files", "returned_files", "s3_prefix", "blob_prefix", "replace"),
[
# s3_existing files, wasb_existing_files, returned_files, s3_prefix, wasb_prefix, replace
(MOCK_FILES, [], MOCK_FILES, PREFIX, PREFIX, False), # Task 1 from above
(MOCK_FILES, MOCK_FILES[1:], [MOCK_FILES[0]], PREFIX, PREFIX, False), # Task 2 from above
(MOCK_FILES, MOCK_FILES[1:], MOCK_FILES, PREFIX, PREFIX, True), # Task 3 from above
],
)
def test_get_files_to_move__both_prefix(
self,
wasb_mock_hook,
s3_mock_hook,
s3_existing_files,
wasb_existing_files,
returned_files,
s3_prefix,
blob_prefix,
replace,
):
# Set the list files that the S3Hook should return
s3_mock_hook.return_value.list_keys.return_value = s3_existing_files
wasb_mock_hook.return_value.get_blobs_list_recursive.return_value = wasb_existing_files
operator = S3ToAzureBlobStorageOperator(
task_id=TASK_ID,
s3_bucket=S3_BUCKET,
s3_prefix=s3_prefix,
container_name=CONTAINER_NAME,
blob_prefix=blob_prefix,
replace=replace,
)
# Placing an empty "context" object here (using None)
uploaded_files = operator.get_files_to_move()
assert sorted(uploaded_files) == sorted(returned_files)
@mock.patch("airflow.providers.microsoft.azure.transfers.s3_to_wasb.WasbHook")
@pytest.mark.parametrize(
("azure_file_exists", "returned_files", "replace"),
[
# azure_file_exists, returned_files, replace
(False, ["TEST1.csv"], False), # Task 4 from above
(True, [], False), # Task 5 from above
(True, ["TEST1.csv"], True), # Task 6 from above
],
)
def test_get_file_to_move__both_key(self, wasb_mock_hook, azure_file_exists, returned_files, replace):
# Different than above, able to remove the mocking of the list_keys method for the S3 hook (since a
# single key is being passed, rather than a prefix). Testing when a single S3 key is being moved to
# a deterministic Blob name in the operator
wasb_mock_hook.return_value.check_for_blob.return_value = azure_file_exists
operator = S3ToAzureBlobStorageOperator(
task_id=TASK_ID,
s3_bucket=S3_BUCKET,
s3_key="TEST/TEST1.csv",
container_name=CONTAINER_NAME,
blob_name="TEST/TEST1.csv",
replace=replace,
)
uploaded_files = operator.get_files_to_move()
# Only the file name should be returned, rather than the entire blob name
assert sorted(uploaded_files) == sorted(returned_files)
@mock.patch("airflow.providers.microsoft.azure.transfers.s3_to_wasb.WasbHook")
@pytest.mark.parametrize(
("wasb_existing_files", "returned_files"),
[
# wasb_existing_files, returned_files
([], ["TEST1.csv"]), # Task 8 from above
(["TEST1.csv"], []), # Task 9 from above
],
)
def test_get_files_to_move__s3_key_wasb_prefix(self, wasb_mock_hook, wasb_existing_files, returned_files):
# A single S3 key is being used to move to a file to a container using a prefix. The files being
# returned should take the same name as the file key that was passed to s3_key
wasb_mock_hook.return_value.get_blobs_list_recursive.return_value = wasb_existing_files
operator = S3ToAzureBlobStorageOperator(
task_id=TASK_ID,
s3_bucket=S3_BUCKET,
s3_key="TEST/TEST1.csv",
container_name=CONTAINER_NAME,
blob_prefix=PREFIX,
)
uploaded_files = operator.get_files_to_move()
assert sorted(uploaded_files) == sorted(returned_files)
@mock.patch("airflow.providers.microsoft.azure.transfers.s3_to_wasb.S3Hook")
@mock.patch("airflow.providers.microsoft.azure.transfers.s3_to_wasb.WasbHook")
def test__get_files_to_move__s3_prefix_blob_name_without_replace_empty_destination(
self, wasb_mock_hook, s3_mock_hook
):
# Set the list files that the S3Hook should return
s3_mock_hook.return_value.list_keys.return_value = MOCK_FILES
wasb_mock_hook.return_value.get_blobs_list_recursive.return_value = []
operator = S3ToAzureBlobStorageOperator(
task_id=TASK_ID,
s3_bucket=S3_BUCKET,
s3_prefix=PREFIX,
container_name=CONTAINER_NAME,
blob_name="TEST/TEST1.csv",
)
# This should throw an exception, since more than a single S3 object is attempted to move to a single
# Azure blob
with pytest.raises(TooManyFilesToMoveException):
operator.get_files_to_move()
@mock.patch("airflow.providers.microsoft.azure.transfers.s3_to_wasb.S3Hook")
@mock.patch("airflow.providers.microsoft.azure.transfers.s3_to_wasb.WasbHook")
def test__move_file(self, wasb_mock_hook, s3_mock_hook):
# Only a single S3 key is provided, and there are no blobs in the container. This means that this file
# should be moved, and the move_file method will be executed
wasb_mock_hook.return_value.get_blobs_list_recursive.return_value = []
s3_mock_hook.return_value.download_file.return_value = BytesIO().write(b"test file contents")
operator = S3ToAzureBlobStorageOperator(
task_id=TASK_ID,
s3_bucket=S3_BUCKET,
s3_key="TEST/TEST1.csv",
container_name=CONTAINER_NAME,
blob_prefix=PREFIX,
)
# Call the move_file method
operator.move_file("TEST1.csv")
# Test that the s3_hook has been called once (to create the client), and the wasb_hook has been called
# to load the file to WASB
operator.s3_hook.get_conn.assert_called_once()
operator.wasb_hook.load_file.assert_called_once_with(
file_path=mock.ANY,
container_name=CONTAINER_NAME,
blob_name=f"{PREFIX}/TEST1.csv",
create_container=False,
)
def test__create_key(self):
# There are three tests that will be run:
# 1. Test will a full path
# 2. Test with a prefix and a file name
# 3. Test with no full path, and a missing file name
assert S3ToAzureBlobStorageOperator._create_key("TEST/TEST1.csv", None, None) == "TEST/TEST1.csv"
assert S3ToAzureBlobStorageOperator._create_key(None, "TEST", "TEST1.csv") == "TEST/TEST1.csv"
with pytest.raises(InvalidKeyComponents):
S3ToAzureBlobStorageOperator._create_key(None, "TEST", None)
| TestS3ToAzureBlobStorageOperator |
python | google__jax | tests/pallas/tpu_sparsecore_pallas_test.py | {
"start": 57168,
"end": 60745
} | class ____(PallasSCTest):
def test_copy(self):
x = jnp.arange(16)
@self.kernel(
out_shape=x,
mesh=plsc.ScalarSubcoreMesh(
axis_name="core", num_cores=self.sc_info.num_cores
),
)
def kernel(x_ref, o_ref):
lax.cond(
lax.axis_index("core") == lax.axis_size("core") - 1,
lambda: pltpu.sync_copy(x_ref, o_ref),
lambda: None,
)
np.testing.assert_array_equal(kernel(x), x)
def test_sliced_copy(self):
self.skip_if_tc_tiling()
x = jnp.arange(self.sc_info.num_cores * 8).reshape(
self.sc_info.num_cores, -1
)
@self.kernel(
out_shape=x,
mesh=plsc.ScalarSubcoreMesh(
axis_name="core", num_cores=self.sc_info.num_cores
),
)
def kernel(x_ref, o_ref):
@functools.partial(pl.run_scoped, sems=pltpu.SemaphoreType.DMA(4))
def _(sems):
core_id = lax.axis_index("core")
pltpu.async_copy(
x_ref.at[core_id], o_ref.at[core_id], sems.at[core_id]
).wait()
np.testing.assert_array_equal(kernel(x), x)
def test_scalar_load_store(self):
x = jnp.arange(8)
@self.kernel(
out_shape=x, mesh=plsc.ScalarSubcoreMesh(axis_name="core", num_cores=1)
)
def kernel(x_ref, o_ref):
@functools.partial(
pl.run_scoped,
tmp_ref=pltpu.SMEM(x.shape, x.dtype),
sem=pltpu.SemaphoreType.DMA,
)
def _(tmp_ref, sem):
pltpu.async_copy(x_ref, tmp_ref, sem).wait()
@pl.loop(1, *x.shape)
def _(i):
tmp_ref[i] += tmp_ref[i - 1]
pltpu.async_copy(tmp_ref, o_ref, sem).wait()
np.testing.assert_array_equal(kernel(x), jnp.cumsum(x))
@parameterized.product(
first_parallel=[False, True], second_parallel=[False, True]
)
def test_parallel_loop(self, first_parallel, second_parallel):
self.skip_if_tc_tiling()
x = jnp.arange(8*8).reshape(8, 8)
loop = lambda start, end, parallel, **kwargs: (
plsc.parallel_loop(start, end, **kwargs)
if parallel
else pl.loop(start, end, **kwargs)
)
@self.kernel(
out_shape=x,
mesh=plsc.ScalarSubcoreMesh(axis_name="core", num_cores=1),
scratch_shapes=(
pltpu.SMEM(x.shape, x.dtype),
pltpu.SemaphoreType.DMA,
),
)
def kernel(x_ref, o_ref, tmp_ref, sem):
pltpu.async_copy(x_ref, tmp_ref, sem).wait()
@loop(0, tmp_ref.shape[0], first_parallel)
def _(i):
@loop(0, tmp_ref.shape[1], second_parallel, unroll=tmp_ref.shape[1])
def _(j):
tmp_ref[i, j] += 1
pltpu.async_copy(tmp_ref, o_ref, sem).wait()
np.testing.assert_array_equal(kernel(x), x + 1)
def test_parallel_loop_with_carry(self):
self.skip_if_tc_tiling()
x = jnp.arange(8*8).reshape(8, 8)
@self.kernel(
out_shape=x,
mesh=plsc.ScalarSubcoreMesh(axis_name="core", num_cores=1),
scratch_shapes=(
pltpu.SMEM(x.shape, x.dtype),
pltpu.SemaphoreType.DMA,
),
)
def kernel(x_ref, o_ref, tmp_ref, sem):
pltpu.async_copy(x_ref, tmp_ref, sem).wait()
@plsc.parallel_loop(0, tmp_ref.shape[0], carry=jnp.zeros([], x.dtype))
def _(i, carry):
carry += 1
@plsc.parallel_loop(0, tmp_ref.shape[1], unroll=2)
def _(j):
tmp_ref[i, j] += carry
return carry
pltpu.async_copy(tmp_ref, o_ref, sem).wait()
np.testing.assert_array_equal(kernel(x), x + jnp.arange(1, 9)[:, None])
| ScalarSubcoreTest |
python | astropy__astropy | astropy/samp/utils.py | {
"start": 934,
"end": 1677
} | class ____:
# some magic to bind an XML-RPC method to an RPC server.
# supports "nested" methods (e.g. examples.getStateName)
def __init__(self, proxies, name):
self.__proxies = proxies
self.__name = name
def __getattr__(self, name):
return _ServerProxyPoolMethod(self.__proxies, f"{self.__name}.{name}")
def __call__(self, *args, **kwrds):
proxy = self.__proxies.get()
function = getattr_recursive(proxy, self.__name)
try:
response = function(*args, **kwrds)
except xmlrpc.Fault as exc:
raise SAMPProxyError(exc.faultCode, exc.faultString)
finally:
self.__proxies.put(proxy)
return response
| _ServerProxyPoolMethod |
python | eth-brownie__brownie | brownie/typing.py | {
"start": 1876,
"end": 2272
} | class ____(_BuildJsonBase):
source: str
sourcePath: str
natspec: NotRequired[Dict[str, Any]]
allSourcePaths: Dict[str, Any]
offset: Offset
bytecode: HexStr
bytecodeSha1: HexStr
deployedBytecode: HexStr
coverageMap: CoverageMap
pcMap: Dict[int, "ProgramCounter"]
compiler: NotRequired["CompilerConfig"]
ast: NotRequired[List]
@final
| _ContractBuildJson |
python | spyder-ide__spyder | spyder/plugins/console/api.py | {
"start": 388,
"end": 458
} | class ____:
SpyderReportAction = "spyder_report_action"
| ConsoleActions |
python | pytorch__pytorch | torch/_inductor/codegen/wrapper.py | {
"start": 31843,
"end": 32220
} | class ____(CommBufferLine):
def codegen(self, code: IndentedBuffer) -> None:
line = self.wrapper.make_buffer_free(self.node)
code.writeline(f"{line} # {self.comm_buffer_type.value} buffer free")
def codegen_fx(self, converter: FxConverter) -> FxConversionFunc:
return converter._generate_comm_buffer_free
@dataclasses.dataclass
| CommBufferFreeLine |
python | airbytehq__airbyte | airbyte-integrations/bases/connector-acceptance-test/unit_tests/test_plugin.py | {
"start": 393,
"end": 5484
} | class ____:
def dumb_test_function(self):
assert 2 > 1
@pytest.mark.parametrize(
"parametrize_skip_or_fail_return",
[(PARAMETRIZE_ACTION, "parametrize reason"), (SKIP_ACTION, "skip reason"), (FAIL_ACTION, "fail_reason")],
)
def test_pytest_generate_tests(mocker, parametrize_skip_or_fail_return):
test_config = config.Config(
connector_image="foo",
acceptance_tests=config.AcceptanceTestConfigurations(spec=config.GenericTestConfig(tests=[config.SpecTestConfig()])),
)
mocker.patch.object(plugin.pytest, "skip")
mocker.patch.object(plugin.pytest, "fail")
mocker.patch.object(plugin, "parametrize_skip_or_fail", mocker.Mock(return_value=parametrize_skip_or_fail_return))
mocker.patch.object(plugin, "load_config", mocker.Mock(return_value=test_config))
metafunc_mock = mocker.Mock(
fixturenames=["inputs"],
function=mocker.Mock(__name__="test_function"),
cls=mocker.Mock(config_key=mocker.Mock(return_value="spec"), __name__="MyTest"),
)
plugin.pytest_generate_tests(metafunc_mock)
action, reason = parametrize_skip_or_fail_return
if action == PARAMETRIZE_ACTION:
metafunc_mock.parametrize.assert_called_once_with("inputs", test_config.acceptance_tests.spec.tests)
if action == SKIP_ACTION:
plugin.pytest.skip.assert_called_once_with(reason)
if action == FAIL_ACTION:
plugin.pytest.fail.assert_called_once_with(reason)
@pytest.mark.parametrize(
"TestClass, test_class_MANDATORY_FOR_TEST_STRICTNESS_LEVELS, global_test_mode, test_configuration, expected_action, expected_reason",
[
pytest.param(
MyTestClass,
(HIGH_TEST_STRICTNESS_LEVEL),
HIGH_TEST_STRICTNESS_LEVEL,
None,
FAIL_ACTION,
f"MyTestClass.dumb_test_function failed: it was not configured but must be according to the current TestStrictnessLevel.high test strictness level.",
id="Discovered test is mandatory in high test strictness level, we're in high test strictness level, it was not configured: FAIL",
),
pytest.param(
MyTestClass,
(HIGH_TEST_STRICTNESS_LEVEL),
LOW_TEST_STRICTNESS_LEVEL,
None,
SKIP_ACTION,
"Skipping MyTestClass.dumb_test_function: not found in the config.",
id="Discovered test is mandatory in high test strictness level, we are in low strictness level, it is not configured: SKIP",
),
pytest.param(
MyTestClass,
set(),
HIGH_TEST_STRICTNESS_LEVEL,
None,
SKIP_ACTION,
"Skipping MyTestClass.dumb_test_function: not found in the config.",
id="Discovered test is not mandatory in any test strictness level, it was not configured: SKIP",
),
pytest.param(
MyTestClass,
(HIGH_TEST_STRICTNESS_LEVEL),
HIGH_TEST_STRICTNESS_LEVEL,
config.GenericTestConfig(bypass_reason="A good reason."),
SKIP_ACTION,
"Skipping MyTestClass.dumb_test_function: A good reason.",
id="Discovered test is mandatory in high test strictness level, a bypass reason was provided: SKIP",
),
pytest.param(
MyTestClass,
(HIGH_TEST_STRICTNESS_LEVEL),
LOW_TEST_STRICTNESS_LEVEL,
config.GenericTestConfig(bypass_reason="A good reason."),
SKIP_ACTION,
"Skipping MyTestClass.dumb_test_function: A good reason.",
id="Discovered test is mandatory in high test strictness level, we are in low test strictness level, a bypass reason was provided: SKIP (with bypass reason shown)",
),
pytest.param(
MyTestClass,
(HIGH_TEST_STRICTNESS_LEVEL),
HIGH_TEST_STRICTNESS_LEVEL,
config.GenericTestConfig(tests=[config.SpecTestConfig()]),
PARAMETRIZE_ACTION,
"Parametrize MyTestClass.dumb_test_function: tests are configured.",
id="[High test strictness level] Discovered test is configured: PARAMETRIZE",
),
pytest.param(
MyTestClass,
(HIGH_TEST_STRICTNESS_LEVEL),
LOW_TEST_STRICTNESS_LEVEL,
config.GenericTestConfig(tests=[config.SpecTestConfig()]),
PARAMETRIZE_ACTION,
"Parametrize MyTestClass.dumb_test_function: tests are configured.",
id="[Low test strictness level] Discovered test is configured: PARAMETRIZE",
),
],
)
def test_parametrize_skip_or_fail(
TestClass, test_class_MANDATORY_FOR_TEST_STRICTNESS_LEVELS, global_test_mode, test_configuration, expected_action, expected_reason
):
TestClass.MANDATORY_FOR_TEST_STRICTNESS_LEVELS = test_class_MANDATORY_FOR_TEST_STRICTNESS_LEVELS
test_action, reason = plugin.parametrize_skip_or_fail(TestClass, TestClass.dumb_test_function, global_test_mode, test_configuration)
assert (test_action, reason) == (expected_action, expected_reason)
| MyTestClass |
python | joke2k__faker | faker/providers/ssn/nl_NL/__init__.py | {
"start": 41,
"end": 1623
} | class ____(SsnProvider):
def ssn(self) -> str:
"""
Returns a 9 digits Dutch SSN called "burgerservicenummer (BSN)".
the Dutch "burgerservicenummer (BSN)" needs to pass the "11-proef",
which is a check digit approach; this function essentially reverses
the checksum steps to create a random valid BSN (which is 9 digits).
"""
# see http://nl.wikipedia.org/wiki/Burgerservicenummer (in Dutch)
def _checksum(digits):
factors = (9, 8, 7, 6, 5, 4, 3, 2, -1)
s = 0
for i in range(len(digits)):
s += digits[i] * factors[i]
return s
while True:
# create an array of first 8 elements initialized randomly
digits = self.generator.random.sample(range(10), 8)
# sum those 8 digits according to (part of) the "11-proef"
s = _checksum(digits)
# determine the last digit to make it qualify the test
digits.append((s % 11) % 10)
# repeat steps until it does qualify the test
if 0 == (_checksum(digits) % 11):
break
# build the resulting BSN
bsn = "".join([str(e) for e in digits])
# finally return our random but valid BSN
return bsn
vat_id_formats = ("NL#########B##",)
def vat_id(self) -> str:
"""
http://ec.europa.eu/taxation_customs/vies/faq.html#item_11
:return: A random Dutch VAT ID
"""
return self.bothify(self.random_element(self.vat_id_formats))
| Provider |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_datastore.py | {
"start": 5073,
"end": 5578
} | class ____:
@mock.patch(HOOK_PATH)
def test_execute(self, mock_hook):
op = CloudDatastoreCommitOperator(
task_id="test_task", gcp_conn_id=CONN_ID, project_id=PROJECT_ID, body=BODY
)
op.execute(context={"ti": mock.MagicMock(), "task": mock.MagicMock()})
mock_hook.assert_called_once_with(gcp_conn_id=CONN_ID, impersonation_chain=None)
mock_hook.return_value.commit.assert_called_once_with(project_id=PROJECT_ID, body=BODY)
| TestCloudDatastoreCommit |
python | gevent__gevent | src/gevent/tests/test__pywsgi.py | {
"start": 46445,
"end": 46958
} | class ____(TestCase):
@staticmethod
def application(env, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
yield b""
yield b"hello"
def test_err(self):
chunks = [b'hello']
with self.makefile() as fd:
fd.write('GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n')
read_http(fd, body='hello', chunks=chunks)
garbage = fd.read()
self.assertEqual(garbage, b"")
| TestFirstEmptyYield |
python | cython__cython | Cython/Debugger/libpython.py | {
"start": 81086,
"end": 82701
} | class ____(LanguageInfo):
def pyframe(self, frame):
pyframe = Frame(frame).get_pyop()
if pyframe:
return pyframe
else:
raise gdb.RuntimeError(
"Unable to find the Python frame, run your code with a debug "
"build (configure with --with-pydebug or compile with -g).")
def lineno(self, frame):
return self.pyframe(frame).current_line_num()
def is_relevant_function(self, frame):
return Frame(frame).is_evalframeex()
def get_source_line(self, frame):
try:
pyframe = self.pyframe(frame)
return '%4d %s' % (pyframe.current_line_num(),
pyframe.current_line().rstrip())
except OSError:
return None
def exc_info(self, frame):
try:
tstate = frame.read_var('tstate').dereference()
if gdb.parse_and_eval('tstate->frame == f'):
# tstate local variable initialized, check for an exception
if sys.version_info >= (3, 12, 0, 'alpha', 6):
inf_type = inf_value = tstate['current_exception']
else:
inf_type = tstate['curexc_type']
inf_value = tstate['curexc_value']
if inf_type:
return 'An exception was raised: %s' % (inf_value,)
except (ValueError, RuntimeError):
# Could not read the variable tstate or it's memory, it's ok
pass
def static_break_functions(self):
yield 'PyEval_EvalFrameEx'
| PythonInfo |
python | spyder-ide__spyder | spyder/plugins/layout/widgets/dialog.py | {
"start": 4387,
"end": 6058
} | class ____(QDialog):
"""Dialog to save a custom layout with a given name."""
def __init__(self, parent, order):
super().__init__(parent)
# variables
self._parent = parent
# widgets
self.combo_box = SpyderComboBox(self)
self.combo_box.addItems(order)
self.combo_box.setEditable(True)
self.combo_box.clearEditText()
self.combo_box.lineEdit().setPlaceholderText(
_("Give a name to your layout")
)
self.button_box = SpyderDialogButtonBox(
QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self
)
self.button_ok = self.button_box.button(QDialogButtonBox.Ok)
self.button_cancel = self.button_box.button(QDialogButtonBox.Cancel)
# widget setup
self.button_ok.setEnabled(False)
self.dialog_size = QSize(350, 100)
self.setWindowTitle(_('Save layout as'))
self.setModal(True)
self.setMinimumSize(self.dialog_size)
self.setFixedSize(self.dialog_size)
# layouts
self.layout = QVBoxLayout()
self.layout.addWidget(self.combo_box)
self.layout.addWidget(self.button_box)
self.setLayout(self.layout)
# signals and slots
self.button_box.accepted.connect(self.accept)
self.button_box.rejected.connect(self.close)
self.combo_box.editTextChanged.connect(self.check_text)
def check_text(self, text):
"""Disable empty layout name possibility"""
if str(text) == '':
self.button_ok.setEnabled(False)
else:
self.button_ok.setEnabled(True)
| LayoutSaveDialog |
python | pydantic__pydantic | tests/test_main.py | {
"start": 21731,
"end": 23108
} | class ____(Enum):
FOO = 'foo'
BAR = 'bar'
@pytest.mark.parametrize('value', [Foo.FOO, Foo.FOO.value, 'foo'])
def test_enum_values(value: Any) -> None:
class Model(BaseModel):
foo: Foo
model_config = ConfigDict(use_enum_values=True)
m = Model(foo=value)
foo = m.foo
assert type(foo) is str, type(foo)
assert foo == 'foo'
foo = m.model_dump()['foo']
assert type(foo) is str, type(foo)
assert foo == 'foo'
def test_literal_enum_values():
FooEnum = Enum('FooEnum', {'foo': 'foo_value', 'bar': 'bar_value'})
class Model(BaseModel):
baz: Literal[FooEnum.foo]
boo: str = 'hoo'
model_config = ConfigDict(use_enum_values=True)
m = Model(baz=FooEnum.foo)
assert m.model_dump() == {'baz': 'foo_value', 'boo': 'hoo'}
assert m.model_dump(mode='json') == {'baz': 'foo_value', 'boo': 'hoo'}
assert m.baz == 'foo_value'
with pytest.raises(ValidationError) as exc_info:
Model(baz=FooEnum.bar)
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'literal_error',
'loc': ('baz',),
'msg': "Input should be <FooEnum.foo: 'foo_value'>",
'input': FooEnum.bar,
'ctx': {'expected': "<FooEnum.foo: 'foo_value'>"},
}
]
| Foo |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/types/dagster_type.py | {
"start": 13194,
"end": 13563
} | class ____(BuiltinScalarDagsterType):
def __init__(self):
super(_Int, self).__init__(
name="Int",
loader=BuiltinSchemas.INT_INPUT,
type_check_fn=self.type_check_fn,
typing_type=int,
)
def type_check_scalar_value(self, value) -> TypeCheck:
return _fail_if_not_of_type(value, int, "int")
| _Int |
python | getsentry__sentry | src/sentry/integrations/api/serializers/models/integration.py | {
"start": 2327,
"end": 3884
} | class ____(IntegrationSerializer):
def __init__(
self, organization_id: int | None = None, params: Mapping[str, Any] | None = None
) -> None:
self.organization_id = organization_id
self.params = params or {}
def serialize(
self,
obj: RpcIntegration | Integration,
attrs: Mapping[str, Any],
user: User | RpcUser | AnonymousUser,
include_config: bool = True,
**kwargs: Any,
) -> MutableMapping[str, Any]:
data = super().serialize(obj, attrs, user)
if not include_config:
return data
data.update({"configOrganization": []})
if not self.organization_id:
return data
try:
install = obj.get_installation(organization_id=self.organization_id)
except NotImplementedError:
# The integration may not implement a Installed Integration object
# representation.
pass
else:
data.update({"configOrganization": install.get_organization_config()})
# Query param "action" only attached in TicketRuleForm modal.
if self.params.get("action") == "create":
# This method comes from IssueBasicIntegration within the integration's installation class
data["createIssueConfig"] = install.get_create_issue_config( # type: ignore[attr-defined]
None, user, params=self.params
)
return data
@register(OrganizationIntegration)
| IntegrationConfigSerializer |
python | kamyu104__LeetCode-Solutions | Python/minimum-flips-in-binary-tree-to-get-result.py | {
"start": 29,
"end": 164
} | class ____(object):
def __init__(self, val=0, left=None, right=None):
pass
import collections
# tree dp with stack
| TreeNode |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 209581,
"end": 210453
} | class ____(unittest.TestCase):
def testExceptionTree(self):
self.assertTrue(issubclass(OSError, Exception))
self.assertTrue(issubclass(socket.herror, OSError))
self.assertTrue(issubclass(socket.gaierror, OSError))
self.assertTrue(issubclass(socket.timeout, OSError))
self.assertIs(socket.error, OSError)
self.assertIs(socket.timeout, TimeoutError)
def test_setblocking_invalidfd(self):
# Regression test for issue #28471
sock0 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
sock = socket.socket(
socket.AF_INET, socket.SOCK_STREAM, 0, sock0.fileno())
sock0.close()
self.addCleanup(sock.detach)
with self.assertRaises(OSError):
sock.setblocking(False)
@unittest.skipUnless(sys.platform == 'linux', 'Linux specific test')
| TestExceptions |
python | davidhalter__jedi | test/refactor/extract_function.py | {
"start": 1916,
"end": 2121
} | class ____:
def g(self): pass
def f(self, b, c):
#? 11 text {'new_name': 'ab'}
return self.g() or self.f(b) ^ glob1 & b
# ++++++++++++++++++++++++++++++++++++++++++++++++++
glob1 = 1
| X |
python | getsentry__sentry | src/sentry/relocation/services/relocation_export/model.py | {
"start": 18,
"end": 230
} | class ____(pydantic.BaseModel):
relocation_uuid: str
requesting_region_name: str
replying_region_name: str
org_slug: str
encrypt_with_public_key: bytes
| RelocationExportRequestNewExportParameters |
python | apache__airflow | providers/apache/hive/src/airflow/providers/apache/hive/sensors/hive_partition.py | {
"start": 1118,
"end": 3095
} | class ____(BaseSensorOperator):
"""
Waits for a partition to show up in Hive.
Note: Because ``partition`` supports general logical operators, it
can be inefficient. Consider using NamedHivePartitionSensor instead if
you don't need the full flexibility of HivePartitionSensor.
:param table: The name of the table to wait for, supports the dot
notation (my_database.my_table)
:param partition: The partition clause to wait for. This is passed as
is to the metastore Thrift client ``get_partitions_by_filter`` method,
and apparently supports SQL like notation as in ``ds='2015-01-01'
AND type='value'`` and comparison operators as in ``"ds>=2015-01-01"``
:param metastore_conn_id: reference to the
:ref: `metastore thrift service connection id <howto/connection:hive_metastore>`
"""
template_fields: Sequence[str] = (
"schema",
"table",
"partition",
)
ui_color = "#C5CAE9"
def __init__(
self,
*,
table: str,
partition: str | None = "ds='{{ ds }}'",
metastore_conn_id: str = "metastore_default",
schema: str = "default",
poke_interval: int = 60 * 3,
**kwargs: Any,
):
super().__init__(poke_interval=poke_interval, **kwargs)
if not partition:
partition = "ds='{{ ds }}'"
self.metastore_conn_id = metastore_conn_id
self.table = table
self.partition = partition
self.schema = schema
def poke(self, context: Context) -> bool:
if "." in self.table:
self.schema, self.table = self.table.split(".")
self.log.info("Poking for table %s.%s, partition %s", self.schema, self.table, self.partition)
if not hasattr(self, "hook"):
hook = HiveMetastoreHook(metastore_conn_id=self.metastore_conn_id)
return hook.check_for_partition(self.schema, self.table, self.partition)
| HivePartitionSensor |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarTuple16.py | {
"start": 292,
"end": 462
} | class ____(Generic[Unpack[T2]]):
@classmethod
def method1(cls, *args: Unpack[T2]) -> int: ...
@staticmethod
def method2(*args: Unpack[T2]) -> int: ...
| Base |
python | kamyu104__LeetCode-Solutions | Python/subtract-the-product-and-sum-of-digits-of-an-integer.py | {
"start": 372,
"end": 579
} | class ____(object):
def subtractProductAndSum(self, n):
"""
:type n: int
:rtype: int
"""
A = map(int, str(n))
return reduce(operator.mul, A) - sum(A)
| Solution2 |
python | marshmallow-code__apispec | tests/test_ext_marshmallow.py | {
"start": 49402,
"end": 49996
} | class ____:
def test_field_order_preserved(self, spec):
class OrderedSchema(Schema):
if (MA_VERSION.major == 3) and (MA_VERSION.minor < 26):
class Meta:
ordered = True
field1 = Int()
field2 = Int()
field3 = Int()
field4 = Int()
field5 = Int()
spec.components.schema("Ordered", schema=OrderedSchema)
result = get_schemas(spec)["Ordered"]["properties"]
assert list(result.keys()) == ["field1", "field2", "field3", "field4", "field5"]
| TestFieldOrdering |
python | getsentry__sentry | src/social_auth/exceptions.py | {
"start": 279,
"end": 509
} | class ____(BackendError):
def __init__(self, backend_name):
self.backend_name = backend_name
def __str__(self) -> str:
return gettext('Incorrect authentication service "%s"') % self.backend_name
| WrongBackend |
python | matplotlib__matplotlib | lib/mpl_toolkits/axisartist/floating_axes.py | {
"start": 4371,
"end": 8341
} | class ____(grid_helper_curvelinear.GridHelperCurveLinear):
def __init__(self, aux_trans, extremes,
grid_locator1=None,
grid_locator2=None,
tick_formatter1=None,
tick_formatter2=None):
# docstring inherited
super().__init__(aux_trans,
extreme_finder=ExtremeFinderFixed(extremes),
grid_locator1=grid_locator1,
grid_locator2=grid_locator2,
tick_formatter1=tick_formatter1,
tick_formatter2=tick_formatter2)
def new_fixed_axis(
self, loc, nth_coord=None, axis_direction=None, offset=None, axes=None):
if axes is None:
axes = self.axes
if axis_direction is None:
axis_direction = loc
# This is not the same as the FixedAxisArtistHelper class used by
# grid_helper_curvelinear.GridHelperCurveLinear.new_fixed_axis!
helper = FixedAxisArtistHelper(
self, loc, nth_coord_ticks=nth_coord)
axisline = AxisArtist(axes, helper, axis_direction=axis_direction)
# Perhaps should be moved to the base class?
axisline.line.set_clip_on(True)
axisline.line.set_clip_box(axisline.axes.bbox)
return axisline
# new_floating_axis will inherit the grid_helper's extremes.
# def new_floating_axis(self, nth_coord, value, axes=None, axis_direction="bottom"):
# axis = super(GridHelperCurveLinear,
# self).new_floating_axis(nth_coord,
# value, axes=axes,
# axis_direction=axis_direction)
# # set extreme values of the axis helper
# if nth_coord == 1:
# axis.get_helper().set_extremes(*self._extremes[:2])
# elif nth_coord == 0:
# axis.get_helper().set_extremes(*self._extremes[2:])
# return axis
def _update_grid(self, bbox):
if self._grid_info is None:
self._grid_info = dict()
grid_info = self._grid_info
grid_finder = self.grid_finder
tbbox = grid_finder.extreme_finder._find_transformed_bbox(
grid_finder.get_transform().inverted(), bbox)
lon_min, lat_min, lon_max, lat_max = tbbox.extents
grid_info["extremes"] = tbbox
lon_levs, lon_n, lon_factor = grid_finder.grid_locator1(lon_min, lon_max)
lon_levs = np.asarray(lon_levs)
lat_levs, lat_n, lat_factor = grid_finder.grid_locator2(lat_min, lat_max)
lat_levs = np.asarray(lat_levs)
grid_info["lon_info"] = lon_levs, lon_n, lon_factor
grid_info["lat_info"] = lat_levs, lat_n, lat_factor
grid_info["lon_labels"] = grid_finder._format_ticks(
1, "bottom", lon_factor, lon_levs)
grid_info["lat_labels"] = grid_finder._format_ticks(
2, "bottom", lat_factor, lat_levs)
lon_values = lon_levs[:lon_n] / lon_factor
lat_values = lat_levs[:lat_n] / lat_factor
lon_lines, lat_lines = grid_finder._get_raw_grid_lines(
lon_values[(lon_min < lon_values) & (lon_values < lon_max)],
lat_values[(lat_min < lat_values) & (lat_values < lat_max)],
tbbox)
grid_info["lon_lines"] = lon_lines
grid_info["lat_lines"] = lat_lines
lon_lines, lat_lines = grid_finder._get_raw_grid_lines(
tbbox.intervalx, tbbox.intervaly, tbbox)
grid_info["lon_lines0"] = lon_lines
grid_info["lat_lines0"] = lat_lines
def get_gridlines(self, which="major", axis="both"):
grid_lines = []
if axis in ["both", "x"]:
grid_lines.extend(map(np.transpose, self._grid_info["lon_lines"]))
if axis in ["both", "y"]:
grid_lines.extend(map(np.transpose, self._grid_info["lat_lines"]))
return grid_lines
| GridHelperCurveLinear |
python | getsentry__sentry | src/sentry/workflow_engine/endpoints/validators/alertrule_workflow.py | {
"start": 41,
"end": 652
} | class ____(serializers.Serializer):
rule_id = serializers.CharField(required=False)
alert_rule_id = serializers.CharField(required=False)
workflow_id = serializers.CharField(required=False)
def validate(self, attrs):
super().validate(attrs)
if (
not attrs.get("rule_id")
and not attrs.get("alert_rule_id")
and not attrs.get("workflow_id")
):
raise serializers.ValidationError(
"One of 'rule_id', 'alert_rule_id', or 'workflow_id' must be provided."
)
return attrs
| AlertRuleWorkflowValidator |
python | getsentry__sentry | src/sentry/models/groupowner.py | {
"start": 1280,
"end": 1551
} | class ____(Enum):
OWNERSHIP_RULE = "ownership_rule"
CODEOWNERS = "codeowners"
GROUP_OWNER_TYPE = {
GroupOwnerType.SUSPECT_COMMIT: "suspectCommit",
GroupOwnerType.OWNERSHIP_RULE: "ownershipRule",
GroupOwnerType.CODEOWNERS: "codeowners",
}
| OwnerRuleType |
python | walkccc__LeetCode | solutions/2076. Process Restricted Friend Requests/2076.py | {
"start": 514,
"end": 1083
} | class ____:
def friendRequests(
self,
n: int,
restrictions: list[list[int]],
requests: list[list[int]],
) -> list[bool]:
ans = []
uf = UnionFind(n)
for u, v in requests:
pu = uf.find(u)
pv = uf.find(v)
isValid = True
if pu != pv:
for x, y in restrictions:
px = uf.find(x)
py = uf.find(y)
if (pu, pv) in [(px, py), (py, px)]:
isValid = False
break
ans.append(isValid)
if isValid:
uf.unionByRank(pu, pv)
return ans
| Solution |
python | sqlalchemy__sqlalchemy | test/orm/test_relationships.py | {
"start": 119007,
"end": 121265
} | class ____(fixtures.DeclarativeMappedTest):
"""test a complex annotation using between().
Using declarative here as an integration test for the local()
and remote() annotations in conjunction with already annotated
instrumented attributes, etc.
"""
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class Network(ComparableEntity, Base):
__tablename__ = "network"
id = Column(
sa.Integer, primary_key=True, test_needs_autoincrement=True
)
ip_net_addr = Column(Integer)
ip_broadcast_addr = Column(Integer)
addresses = relationship(
"Address",
primaryjoin="remote(foreign(Address.ip_addr)).between("
"Network.ip_net_addr,"
"Network.ip_broadcast_addr)",
viewonly=True,
)
class Address(ComparableEntity, Base):
__tablename__ = "address"
ip_addr = Column(Integer, primary_key=True)
@classmethod
def insert_data(cls, connection):
Network, Address = cls.classes.Network, cls.classes.Address
s = Session(connection)
s.add_all(
[
Network(ip_net_addr=5, ip_broadcast_addr=10),
Network(ip_net_addr=15, ip_broadcast_addr=25),
Network(ip_net_addr=30, ip_broadcast_addr=35),
Address(ip_addr=17),
Address(ip_addr=18),
Address(ip_addr=9),
Address(ip_addr=27),
]
)
s.commit()
def test_col_query(self):
Network, Address = self.classes.Network, self.classes.Address
session = Session(testing.db)
eq_(
session.query(Address.ip_addr)
.select_from(Network)
.join(Network.addresses)
.filter(Network.ip_net_addr == 15)
.all(),
[(17,), (18,)],
)
def test_lazyload(self):
Network = self.classes.Network
session = Session(testing.db)
n3 = session.query(Network).filter(Network.ip_net_addr == 5).one()
eq_([a.ip_addr for a in n3.addresses], [9])
| RemoteForeignBetweenColsTest |
python | weaviate__weaviate-python-client | weaviate/collections/iterator.py | {
"start": 588,
"end": 1014
} | class ____(Generic[TProperties, TReferences]):
include_vector: bool
return_metadata: Optional[METADATA]
return_properties: Optional[ReturnProperties[TProperties]]
return_references: Optional[ReturnReferences[TReferences]]
after: Optional[UUIDorStr]
def _parse_after(after: Optional[UUIDorStr]) -> Optional[UUID]:
return after if after is None or isinstance(after, UUID) else UUID(after)
| _IteratorInputs |
python | pytorch__pytorch | torch/ao/ns/_numeric_suite.py | {
"start": 6102,
"end": 6632
} | class ____(nn.Module):
r"""Base class for stats logging"""
def __init__(self):
super().__init__()
self.stats = {}
# We only insert observer if the op is quantized with static quantization,
# which is identified by activation_observer.dtype == quint8. This is needed
# when attaching Logger as observer for FX mode
self.dtype = torch.quint8
def forward(self, x):
# fmt: off
"""
""" # blank docblock to make autodoc happy
# fmt: on
| Logger |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 976028,
"end": 979130
} | class ____(sgqlc.types.Type):
"""SponsorsTier information only visible to users that can administer
the associated Sponsors listing.
"""
__schema__ = github_schema
__field_names__ = ("is_draft", "is_published", "is_retired", "sponsorships")
is_draft = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="isDraft")
"""Indicates whether this tier is still a work in progress by the
sponsorable and not yet published to the associated GitHub
Sponsors profile. Draft tiers cannot be used for new sponsorships
and will not be in use on existing sponsorships. Draft tiers
cannot be seen by anyone but the admins of the GitHub Sponsors
profile.
"""
is_published = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="isPublished")
"""Indicates whether this tier is published to the associated GitHub
Sponsors profile. Published tiers are visible to anyone who can
see the GitHub Sponsors profile, and are available for use in
sponsorships if the GitHub Sponsors profile is publicly visible.
"""
is_retired = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="isRetired")
"""Indicates whether this tier has been retired from the associated
GitHub Sponsors profile. Retired tiers are no longer shown on the
GitHub Sponsors profile and cannot be chosen for new sponsorships.
Existing sponsorships may still use retired tiers if the sponsor
selected the tier before it was retired.
"""
sponsorships = sgqlc.types.Field(
sgqlc.types.non_null("SponsorshipConnection"),
graphql_name="sponsorships",
args=sgqlc.types.ArgDict(
(
("after", sgqlc.types.Arg(String, graphql_name="after", default=None)),
("before", sgqlc.types.Arg(String, graphql_name="before", default=None)),
("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)),
("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)),
("include_private", sgqlc.types.Arg(Boolean, graphql_name="includePrivate", default=False)),
("order_by", sgqlc.types.Arg(SponsorshipOrder, graphql_name="orderBy", default=None)),
)
),
)
"""The sponsorships using this tier.
Arguments:
* `after` (`String`): Returns the elements in the list that come
after the specified cursor.
* `before` (`String`): Returns the elements in the list that come
before the specified cursor.
* `first` (`Int`): Returns the first _n_ elements from the list.
* `last` (`Int`): Returns the last _n_ elements from the list.
* `include_private` (`Boolean`): Whether or not to return private
sponsorships using this tier. Defaults to only returning public
sponsorships on this tier. (default: `false`)
* `order_by` (`SponsorshipOrder`): Ordering options for
sponsorships returned from this connection. If left blank, the
sponsorships will be ordered based on relevancy to the viewer.
"""
| SponsorsTierAdminInfo |
python | facelessuser__soupsieve | soupsieve/css_types.py | {
"start": 6302,
"end": 6447
} | class ____(Immutable):
"""Null Selector."""
def __init__(self) -> None:
"""Initialize."""
super().__init__()
| SelectorNull |
python | pytorch__pytorch | torch/distributed/checkpoint/quantized_hf_storage.py | {
"start": 479,
"end": 12702
} | class ____(HuggingFaceStorageReader):
"""
Extension of HuggingFaceStorageReader that handles quantized tensors.
Checkpoint should have the full tensor in a SafeTensor file. The quantized
tensor should not be sharded across multiple files.
This reader handles the dequantization of tensors during the read process,
converting them from quantized blocks to full dequantized tensors before
copying to the target tensor.
"""
def __init__(
self,
path: str,
thread_count: int = 1,
target_dtype: torch.dtype = torch.float32,
block_size: int = 128,
):
"""
Initialize the HuggingFace storage reader to load quantized checkpoints
Args:
path: directory where the checkpoint will be read from.
thread_count: Number of threads to use to read distributed checkpoint. Defaults to 1.
target_dtype: Target dtype for dequantized tensor. Defaults to torch.float32.
block_size: Fixed block size for dequantization. Defaults to 128.
"""
super().__init__(path=path, thread_count=thread_count)
self.target_dtype: torch.dtype = target_dtype
self.block_size: int = block_size
self._weight_scale_mapping: dict[str, str] = {}
# Track which file contains each tensor
self._weight_map: dict[str, str] = {}
# Cache for full tensor shapes (fqn -> shape)
self._tensor_full_shapes: dict[str, torch.Size] = {}
def read_metadata(self) -> Any:
metadata = super().read_metadata()
# Build a cache of FQN -> full tensor shape for faster lookups.
for fqn, tensor_metadata in metadata.state_dict_metadata.items():
# Only process TensorStorageMetadata which has size attribute
if isinstance(tensor_metadata, TensorStorageMetadata):
self._tensor_full_shapes[fqn] = tensor_metadata.size
self._load_quantization_metadata()
return metadata
def _load_quantization_metadata(self):
"""Load quantization metadata from the checkpoint."""
checkpoint_path = Path(self.path)
# Load weight mapping from index file
index_file = checkpoint_path / _metadata_fn
with open(index_file) as f:
index_data = json.load(f)
weight_map = index_data.get("weight_map", {})
self._build_weight_scale_mapping(weight_map)
def _build_weight_scale_mapping(self, weight_map: dict[str, str]):
"""Analyze and build weight-scale tensor pairs from weight mapping."""
# Store the complete weight map for file location lookups
self._weight_map = weight_map
for tensor_name in weight_map:
if tensor_name.endswith(".weight_scale_inv"):
weight_name = tensor_name.replace(".weight_scale_inv", ".weight")
if weight_name in weight_map:
self._weight_scale_mapping[weight_name] = tensor_name
def _process_read_request(
self, f: Any, req: ReadItem, planner: LoadPlanner
) -> None:
"""Override the Helper function that processes a single read request."""
tensor_fqn = req.storage_index.fqn
# Check if this is a quantized tensor that needs dequantization
if self._is_tensor_quantized(tensor_fqn):
tensor = self._read_quantized_tensor_with_block_alignment(req, f)
else:
# Standard tensor reading
slices = tuple(
slice(offset, offset + length)
for offset, length in zip(req.storage_offsets, req.lengths)
)
tensor = f.get_slice(tensor_fqn)[slices]
target_tensor = planner.resolve_tensor(req).detach()
if target_tensor.size() != tensor.size():
raise AssertionError(
f"req {req.storage_index} mismatch sizes {target_tensor.size()} vs {tensor.size()}"
)
target_tensor.copy_(tensor)
planner.commit_tensor(req, target_tensor)
def _get_slice_to_block_mapping(
self, req: ReadItem
) -> tuple[tuple[int, int], tuple[int, int], slice, slice]:
"""
Calculate which blocks correspond to the requested slice.
Args:
req: Read request containing tensor info and required slices
Returns:
Tuple of (row_block_range, col_block_range, row_slice, col_slice)
"""
# Get the slice information
row_slice = slice(
req.storage_offsets[0], req.storage_offsets[0] + req.lengths[0]
)
col_slice = slice(
req.storage_offsets[1], req.storage_offsets[1] + req.lengths[1]
)
# Calculate which blocks this slice spans
row_start_block = row_slice.start // self.block_size
row_end_block = (row_slice.stop - 1) // self.block_size + 1 # Inclusive end
col_start_block = col_slice.start // self.block_size
col_end_block = (col_slice.stop - 1) // self.block_size + 1 # Inclusive end
return (
(row_start_block, row_end_block),
(col_start_block, col_end_block),
row_slice,
col_slice,
)
def _dequantize_tensor(
self,
weight: torch.Tensor,
scale_inv: torch.Tensor,
full_tensor_shape: torch.Size,
slice_info: tuple[tuple[int, int], tuple[int, int], slice, slice],
) -> torch.Tensor:
"""
Dequantize a sliced tensor using the appropriate portion of the scale tensor.
Args:
weight: Sliced quantized weight tensor
scale_inv: Full scale inverse tensor for dequantization
full_tensor_shape: Shape of the original full tensor
slice_info: Block mapping information from _get_slice_to_block_mapping
Returns:
Dequantized tensor
"""
(row_block_range, col_block_range, row_slice, col_slice) = slice_info
# Convert to float32 for computation
# Certain quantized dtypes like Float8_e4m3fn
# don't support multiplication on CPU yet in PyTorch.
upcasted_weight = weight.to(torch.float32)
# Create output tensor in target dtype
dequantized = weight.detach().to(dtype=self.target_dtype, copy=True)
# Get the actual slice boundaries
row_start_global = row_slice.start
row_end_global = row_slice.stop
col_start_global = col_slice.start
col_end_global = col_slice.stop
# Apply scaling factors to each block that intersects with our slice
for block_i in range(row_block_range[0], row_block_range[1]):
for block_j in range(col_block_range[0], col_block_range[1]):
# Calculate the block boundaries in global coordinates
block_row_start_global = block_i * self.block_size
block_row_end_global = min(
block_row_start_global + self.block_size, full_tensor_shape[0]
)
block_col_start_global = block_j * self.block_size
block_col_end_global = min(
block_col_start_global + self.block_size, full_tensor_shape[1]
)
# Find the intersection of the block with our slice
intersect_row_start = max(block_row_start_global, row_start_global)
intersect_row_end = min(block_row_end_global, row_end_global)
intersect_col_start = max(block_col_start_global, col_start_global)
intersect_col_end = min(block_col_end_global, col_end_global)
# Skip if no intersection
if (
intersect_row_start >= intersect_row_end
or intersect_col_start >= intersect_col_end
):
continue
# Convert global coordinates to local coordinates in the sliced tensor
local_row_start = intersect_row_start - row_start_global
local_row_end = intersect_row_end - row_start_global
local_col_start = intersect_col_start - col_start_global
local_col_end = intersect_col_end - col_start_global
# Get the block from the sliced tensor
block = upcasted_weight[
local_row_start:local_row_end, local_col_start:local_col_end
]
# Apply the scale factor
scale = scale_inv[block_i, block_j]
block = block * scale
# Convert block to target dtype and store
block_converted = block.to(dtype=self.target_dtype)
dequantized[
local_row_start:local_row_end, local_col_start:local_col_end
] = block_converted
return dequantized
def _is_tensor_quantized(self, tensor_fqn: str) -> bool:
"""
Check if a tensor is a quantized.
Args:
tensor_fqn: Fully qualified name of the tensor
Returns:
True if tensor is quantized and has a corresponding scale tensor,
False otherwise
"""
# Skip scale tensors themselves
if tensor_fqn.endswith(".weight_scale_inv"):
return False
# Check if this weight tensor has a corresponding scale tensor
if tensor_fqn not in self._weight_scale_mapping:
return False
return True
def _read_quantized_tensor_with_block_alignment(
self, req: ReadItem, safetensor_file: Any
) -> torch.Tensor:
"""
Read a quantized tensor with block alignment.
Args:
req: Read request containing tensor info and required slices
safetensor_file: Open safetensors file handle
Returns:
Dequantized tensor ready for use
"""
tensor_fqn = req.storage_index.fqn
scale_fqn = self._weight_scale_mapping[tensor_fqn]
try:
# Load the sliced quantized weight
weight_slices = tuple(
slice(offset, offset + length)
for offset, length in zip(req.storage_offsets, req.lengths)
)
quantized_tensor = safetensor_file.get_slice(tensor_fqn)[weight_slices]
# Load the corresponding scale inverse tensor (full tensor)
scale_file_name = self._weight_map.get(scale_fqn)
if scale_file_name is None:
raise ValueError(f"Scale tensor {scale_fqn} not found in weight_map")
# Check if scale tensor is in the same file as the weight tensor
weight_file_name = self._weight_map.get(tensor_fqn)
if scale_file_name == weight_file_name:
# Scale tensor is in the same file, use current handle
scale_inv = safetensor_file.get_tensor(scale_fqn)
else:
# Scale tensor is in a different file, need to open it
from safetensors import safe_open # type: ignore[import]
scale_file_path = Path(self.path) / scale_file_name
with safe_open(
scale_file_path, framework="pt", device="cpu"
) as scale_file:
scale_inv = scale_file.get_tensor(scale_fqn)
# Get the full tensor shape from our O(1) lookup cache
full_tensor_shape = self._tensor_full_shapes.get(tensor_fqn)
if full_tensor_shape is None:
raise ValueError(f"Could not find full tensor shape for {tensor_fqn}")
# Get slice to block mapping
slice_info = self._get_slice_to_block_mapping(req)
# Perform dequantization with proper block alignment
dequantized_tensor = self._dequantize_tensor(
weight=quantized_tensor,
scale_inv=scale_inv,
full_tensor_shape=full_tensor_shape,
slice_info=slice_info,
)
return dequantized_tensor
except Exception as e:
logger.error("Failed to read the quantized tensor!!")
raise e
| QuantizedHuggingFaceStorageReader |
python | getsentry__sentry | src/sentry/testutils/cases.py | {
"start": 143667,
"end": 149056
} | class ____(BaseTestCase):
"""Test case for creating and storing EAP uptime results."""
def create_eap_uptime_result(
self,
*,
organization=None,
project=None,
scheduled_check_time=None,
trace_id=None,
guid=None,
subscription_id=None,
check_id=None,
check_status="success",
incident_status=None,
region="default",
http_status_code=200,
request_type="GET",
request_url="https://example.com",
original_url=None,
request_sequence=0,
check_duration_us=150000,
request_duration_us=125000,
dns_lookup_duration_us=None,
tcp_connection_duration_us=None,
tls_handshake_duration_us=None,
time_to_first_byte_duration_us=None,
send_request_duration_us=None,
receive_response_duration_us=None,
request_body_size_bytes=None,
response_body_size_bytes=None,
status_reason_type=None,
status_reason_description=None,
span_id=None,
):
from datetime import datetime, timedelta, timezone
from uuid import uuid4
from google.protobuf.timestamp_pb2 import Timestamp
from sentry_protos.snuba.v1.request_common_pb2 import TraceItemType
from sentry_protos.snuba.v1.trace_item_pb2 import AnyValue, TraceItem
if organization is None:
organization = self.organization
if project is None:
project = self.project
if scheduled_check_time is None:
scheduled_check_time = datetime.now(timezone.utc) - timedelta(minutes=1)
if trace_id is None:
trace_id = uuid4().hex
if guid is None:
guid = uuid4().hex
if subscription_id is None:
subscription_id = f"sub-{uuid4().hex[:8]}"
if span_id is None:
span_id = uuid4().hex[:16]
attributes_data = {
"guid": guid,
"subscription_id": subscription_id,
"check_status": check_status,
"region": region,
"http_status_code": http_status_code,
"request_type": request_type,
"request_url": request_url,
"request_sequence": request_sequence,
"check_duration_us": check_duration_us,
"request_duration_us": request_duration_us,
"span_id": span_id,
}
if check_id is not None:
attributes_data["check_id"] = check_id
optional_fields = {
"dns_lookup_duration_us": dns_lookup_duration_us,
"tcp_connection_duration_us": tcp_connection_duration_us,
"tls_handshake_duration_us": tls_handshake_duration_us,
"time_to_first_byte_duration_us": time_to_first_byte_duration_us,
"send_request_duration_us": send_request_duration_us,
"receive_response_duration_us": receive_response_duration_us,
"request_body_size_bytes": request_body_size_bytes,
"response_body_size_bytes": response_body_size_bytes,
}
for field, value in optional_fields.items():
if value is not None:
attributes_data[field] = value
if status_reason_type is not None:
attributes_data["status_reason_type"] = status_reason_type
if status_reason_description is not None:
attributes_data["status_reason_description"] = status_reason_description
if incident_status is not None:
attributes_data["incident_status"] = incident_status.value
if original_url is None:
original_url = request_url
attributes_data["original_url"] = original_url
attributes_proto = {}
for k, v in attributes_data.items():
if v is not None:
attributes_proto[k] = scalar_to_any_value(v)
timestamp_proto = Timestamp()
timestamp_proto.FromDatetime(scheduled_check_time)
attributes_proto["scheduled_check_time_us"] = AnyValue(
int_value=int(scheduled_check_time.timestamp() * 1_000_000)
)
attributes_proto["actual_check_time_us"] = AnyValue(
int_value=int(scheduled_check_time.timestamp() * 1_000_000) + 5000
)
return TraceItem(
organization_id=organization.id,
project_id=project.id,
item_type=TraceItemType.TRACE_ITEM_TYPE_UPTIME_RESULT,
timestamp=timestamp_proto,
trace_id=trace_id,
item_id=uuid4().bytes,
received=timestamp_proto,
retention_days=90,
attributes=attributes_proto,
)
def store_uptime_results(self, uptime_results):
"""Store uptime results in the EAP dataset."""
import requests
from django.conf import settings
files = {
f"uptime_{i}": result.SerializeToString() for i, result in enumerate(uptime_results)
}
response = requests.post(
settings.SENTRY_SNUBA + EAP_ITEMS_INSERT_ENDPOINT,
files=files,
)
assert response.status_code == 200
for result in uptime_results:
# Reverse the ids here since these are stored in little endian in Clickhouse
# and end up reversed.
result.item_id = result.item_id[::-1]
| UptimeResultEAPTestCase |
python | jschneier__django-storages | storages/backends/s3.py | {
"start": 26761,
"end": 26914
} | class ____(S3Storage):
"""Querystring auth must be disabled so that url() returns a consistent output."""
querystring_auth = False
| S3StaticStorage |
python | pytorch__pytorch | .ci/lumen_cli/tests/test_utils.py | {
"start": 1510,
"end": 2981
} | class ____(EnvIsolatedTestCase):
def test_sets_and_restores_new_var(self):
var = "TEST_TMP_ENV_NEW"
self.assertNotIn(var, os.environ)
with temp_environ({var: "123"}):
self.assertEqual(os.environ[var], "123")
self.assertNotIn(var, os.environ) # removed after exit
def test_overwrites_and_restores_existing_var(self):
var = "TEST_TMP_ENV_OVERWRITE"
os.environ[var] = "orig"
with temp_environ({var: "override"}):
self.assertEqual(os.environ[var], "override")
self.assertEqual(os.environ[var], "orig") # restored
def test_multiple_vars_and_missing_cleanup(self):
v1, v2 = "TEST_ENV_V1", "TEST_ENV_V2"
os.environ.pop(v1, None)
os.environ[v2] = "keep"
with temp_environ({v1: "a", v2: "b"}):
self.assertEqual(os.environ[v1], "a")
self.assertEqual(os.environ[v2], "b")
self.assertNotIn(v1, os.environ) # newly-added -> removed
self.assertEqual(os.environ[v2], "keep") # pre-existing -> restored
def test_restores_even_on_exception(self):
var = "TEST_TMP_ENV_EXCEPTION"
self.assertNotIn(var, os.environ)
with self.assertRaises(RuntimeError):
with temp_environ({var: "x"}):
self.assertEqual(os.environ[var], "x")
raise RuntimeError("boom")
self.assertNotIn(var, os.environ) # removed after exception
| TestTempEnviron |
python | crytic__slither | slither/detectors/compiler_bugs/multiple_constructor_schemes.py | {
"start": 188,
"end": 2560
} | class ____(AbstractDetector):
"""
Module detecting multiple constructors in the same contract.
(This was possible prior to Solidity 0.4.23, using old and new constructor schemes).
"""
ARGUMENT = "multiple-constructors"
HELP = "Multiple constructor schemes"
IMPACT = DetectorClassification.HIGH
CONFIDENCE = DetectorClassification.HIGH
WIKI = (
"https://github.com/crytic/slither/wiki/Detector-Documentation#multiple-constructor-schemes"
)
WIKI_TITLE = "Multiple constructor schemes"
WIKI_DESCRIPTION = (
"Detect multiple constructor definitions in the same contract (using new and old schemes)."
)
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract A {
uint x;
constructor() public {
x = 0;
}
function A() public {
x = 1;
}
function test() public returns(uint) {
return x;
}
}
```
In Solidity [0.4.22](https://github.com/ethereum/solidity/releases/tag/v0.4.23), a contract with both constructor schemes will compile. The first constructor will take precedence over the second, which may be unintended."""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Only declare one constructor, preferably using the new scheme `constructor(...)` instead of `function <contractName>(...)`."
def _detect(self) -> List[Output]:
"""
Detect multiple constructor schemes in the same contract
:return: Returns a list of contract JSON result, where each result contains all constructor definitions.
"""
results = []
for contract in self.contracts:
# Obtain any constructors defined in this contract
constructors = [f for f in contract.constructors if f.contract_declarer == contract]
# If there is more than one, we encountered the described issue occurring.
if constructors and len(constructors) > 1:
info: DETECTOR_INFO = [
contract,
" contains multiple constructors in the same contract:\n",
]
for constructor in constructors:
info += ["\t- ", constructor, "\n"]
res = self.generate_result(info)
results.append(res)
return results
| MultipleConstructorSchemes |
python | tensorflow__tensorflow | tensorflow/python/framework/smart_cond_test.py | {
"start": 1234,
"end": 3711
} | class ____(test_util.TensorFlowTestCase):
def testTrue(self):
with ops.Graph().as_default():
with session.Session():
x = constant_op.constant(2)
y = constant_op.constant(5)
z = smart_cond.smart_cond(True, lambda: math_ops.multiply(x, 16),
lambda: math_ops.multiply(y, 5))
self.assertEqual(self.evaluate(z), 32)
def testFalse(self):
with ops.Graph().as_default():
with session.Session():
x = constant_op.constant(4)
y = constant_op.constant(3)
z = smart_cond.smart_cond(False, lambda: math_ops.multiply(x, 16),
lambda: math_ops.multiply(y, 3))
self.assertEqual(self.evaluate(z), 9)
def testUnknown(self):
with ops.Graph().as_default():
with session.Session():
x = array_ops.placeholder(dtype=dtypes.int32)
y = smart_cond.smart_cond(x > 0, lambda: constant_op.constant(1),
lambda: constant_op.constant(2))
self.assertEqual(y.eval(feed_dict={x: 1}), 1)
self.assertEqual(y.eval(feed_dict={x: -1}), 2)
def testEval(self):
with ops.Graph().as_default():
with session.Session():
x = constant_op.constant(1)
y = constant_op.constant(2)
# x * y > 0 can be evaluated at graph construction time, so the false
# branch shouldn't be evaluated at all.
z = smart_cond.smart_cond(x * y > 0, lambda: constant_op.constant(1),
raise_exception)
self.assertEqual(z.eval(feed_dict={x: 1}), 1)
def testPlaceholderWithDefault(self):
with ops.Graph().as_default():
with session.Session():
x = array_ops.placeholder_with_default(1, shape=())
y = smart_cond.smart_cond(x > 0, lambda: constant_op.constant(1),
lambda: constant_op.constant(2))
self.assertEqual(self.evaluate(y), 1)
self.assertEqual(y.eval(feed_dict={x: -1}), 2)
def testMissingArg1(self):
with ops.Graph().as_default():
with session.Session():
x = constant_op.constant(1)
with self.assertRaises(TypeError):
smart_cond.smart_cond(True, false_fn=lambda: x)
def testMissingArg2(self):
with ops.Graph().as_default():
with session.Session():
x = constant_op.constant(1)
with self.assertRaises(TypeError):
smart_cond.smart_cond(True, lambda: x)
| SmartCondTest |
python | streamlit__streamlit | lib/streamlit/testing/v1/element_tree.py | {
"start": 23254,
"end": 26228
} | class ____(Widget, Generic[T]):
"""A representation of ``st.multiselect``."""
_value: list[T] | None
proto: MultiSelectProto = field(repr=False)
label: str
options: list[str]
max_selections: int
help: str
form_id: str
def __init__(self, proto: MultiSelectProto, root: ElementTree) -> None:
super().__init__(proto, root)
self.type = "multiselect"
self.options = list(proto.options)
@property
def _widget_state(self) -> WidgetState:
"""Protobuf message representing the state of the widget, including
any interactions that have happened.
Should be the same as the frontend would produce for those interactions.
"""
ws = WidgetState()
ws.id = self.id
ws.string_array_value.data[:] = self.values
return ws
@property
def value(self) -> list[T]:
"""The currently selected values from the options. (list)""" # noqa: D400
if self._value is not None:
return self._value
state = self.root.session_state
assert state
return cast("list[T]", state[self.id])
@property
def indices(self) -> Sequence[int]:
"""The indices of the currently selected values from the options. (list)""" # noqa: D400
return [self.options.index(self.format_func(v)) for v in self.value]
@property
def values(self) -> Sequence[str]:
"""The currently selected values from the options. (list)""" # noqa: D400
return [self.format_func(v) for v in self.value]
@property
def format_func(self) -> Callable[[Any], Any]:
"""The widget's formatting function for displaying options. (callable)""" # noqa: D400
ss = self.root.session_state
return cast("Callable[[Any], Any]", ss[TESTING_KEY][self.id])
def set_value(self, v: list[T]) -> Multiselect[T]:
"""Set the value of the multiselect widget. (list)""" # noqa: D400
self._value = v
return self
def select(self, v: T) -> Multiselect[T]:
"""
Add a selection to the widget. Do nothing if the value is already selected.\
If testing a multiselect widget with repeated options, use ``set_value``\
instead.
"""
current = self.value
if v in current:
return self
new = current.copy()
new.append(v)
self.set_value(new)
return self
def unselect(self, v: T) -> Multiselect[T]:
"""
Remove a selection from the widget. Do nothing if the value is not\
already selected. If a value is selected multiple times, the first\
instance is removed.
"""
current = self.value
if v not in current:
return self
new = current.copy()
while v in new:
new.remove(v)
self.set_value(new)
return self
Number: TypeAlias = int | float
@dataclass(repr=False)
| Multiselect |
python | dagster-io__dagster | python_modules/libraries/dagster-dbt/dagster_dbt/metadata_set.py | {
"start": 113,
"end": 512
} | class ____(NamespacedMetadataSet):
"""Metadata entries that apply to dbt objects.
Args:
materialization_type (Optional[str]): The materialization type, like "table" or "view". See
https://docs.getdbt.com/docs/build/materializations.
"""
materialization_type: Optional[str]
@classmethod
def namespace(cls) -> str:
return "dagster-dbt"
| DbtMetadataSet |
python | fluentpython__example-code-2e | 13-protocol-abc/double/double_protocol.py | {
"start": 63,
"end": 247
} | class ____(Protocol):
def __mul__(self: T, repeat_count: int) -> T: ... # <2>
RT = TypeVar('RT', bound=Repeatable) # <3>
def double(x: RT) -> RT: # <4>
return x * 2
| Repeatable |
python | mwaskom__seaborn | seaborn/_core/properties.py | {
"start": 19534,
"end": 19592
} | class ____(ObjectProperty):
legend = False
| TextAlignment |
python | huggingface__transformers | src/transformers/models/oneformer/modeling_oneformer.py | {
"start": 115295,
"end": 116994
} | class ____(nn.Module):
def __init__(
self,
context_length: int,
width: int,
layers: int,
vocab_size,
use_checkpoint=False,
layer_norm_eps=1e-05,
):
super().__init__()
heads = width // 64
self.context_length = context_length
self.width = width
self.transformer = OneFormerTextTransformer(
width=width,
layers=layers,
heads=heads,
attn_mask=self.build_attention_mask(),
use_checkpoint=use_checkpoint,
layer_norm_eps=layer_norm_eps,
)
self.positional_embedding = nn.Parameter(torch.empty(self.context_length, width))
self.ln_final = nn.LayerNorm(width, eps=layer_norm_eps)
self.token_embedding = nn.Embedding(vocab_size, width)
def build_attention_mask(self):
# lazily create causal attention mask, with full attention between the vision tokens
# pytorch uses additive attention mask; fill with -inf
mask = torch.empty(self.context_length, self.context_length)
mask.fill_(float("-inf"))
mask.triu_(1) # zero out the lower diagonal
return mask
def forward(self, text):
hidden_state = self.token_embedding(text)
hidden_state = hidden_state + self.positional_embedding
hidden_state = hidden_state.permute(1, 0, 2)
hidden_state = self.transformer(hidden_state)
hidden_state = hidden_state.permute(1, 0, 2)
hidden_state = self.ln_final(hidden_state)
hidden_state = hidden_state[torch.arange(hidden_state.shape[0]), text.argmax(dim=-1)]
return hidden_state
| OneFormerTextEncoder |
python | viewflow__viewflow | viewflow/workflow/nodes/split.py | {
"start": 1718,
"end": 4484
} | class ____(
Node,
):
"""
Represents a parallel split gateway in a workflow, allowing branching into multiple parallel paths.
Methods:
- `Next(node, case=None, data_source=None)`: Defines the subsequent node in the workflow.
- `node`: The next node to execute.
- `case` (optional): A callable that takes an activation and returns `True` if the node should be activated.
- `data_source` (optional): A callable that takes an activation and returns a list of data items, creating an instance of the node for each item, with `task.data` set to the item.
- `Always(node)`: A shortcut to define a subsequent node that is always executed.
Example:
```python
flow.Split()
.Next(
this.approve,
case=act.process.approved,
data_source=lambda activation: [{"sample": "test task 1"}, {"sample": "test task 2"}],
)
.Always(this.required)
```
In this example:
- The `approve` node is executed multiple times based on the `data_source` list.
- The `required` node is always executed unconditionally in parallel.
Notes:
- If `case` is not provided, the node is always activated.
- If `data_source` is not provided, the node is created only once.
"""
activation_class = SplitActivation
task_type = "PARALLEL_GATEWAY"
shape = {
"width": 50,
"height": 50,
"svg": """
<path class="gateway" d="M25,0L50,25L25,50L0,25L25,0"/>
<text class="gateway-marker" font-size="32px" x="25" y="35">+</text>
""",
}
bpmn_element = "parallelGateway"
def __init__(self, **kwargs): # noqa D102
super(Split, self).__init__(**kwargs)
self._activate_next = []
def _outgoing(self):
for next_node, cond, _ in self._activate_next:
edge_class = "cond_true" if cond else "default"
yield Edge(src=self, dst=next_node, edge_class=edge_class)
def _resolve(self, instance):
super()._resolve(instance)
self._activate_next = [
(
this.resolve(instance, node),
this.resolve(instance, cond),
this.resolve(instance, data_source),
)
for node, cond, data_source in self._activate_next
]
@property
def _branches(self):
return self._activate_next
def Next(self, node, case=None):
"""Node to activate if condition is true.
:param cond: Callable[activation] -> bool
"""
self._activate_next.append((node, case, None))
return self
def Always(self, node):
return self.Next(node)
| Split |
python | pdm-project__pdm | src/pdm/models/working_set.py | {
"start": 308,
"end": 2165
} | class ____(im.DistributionFinder):
@classmethod
def find_distributions(cls, context: im.DistributionFinder.Context = default_context) -> Iterable[im.Distribution]:
found_links = cls._search_paths(context.name, context.path)
# For Py3.7 compatibility, handle both classmethod and instance method
meta_finder = im.MetadataPathFinder()
for link in found_links:
name = link.stem
with link.open("rb") as file_link:
link_pointer = Path(file_link.readline().decode().strip())
dist = next(
iter(
meta_finder.find_distributions(im.DistributionFinder.Context(name=name, path=[str(link_pointer)]))
),
None,
)
if not dist:
continue
dist.link_file = link.absolute() # type: ignore[attr-defined]
yield dist
@classmethod
def _search_paths(cls, name: str | None, paths: list[str]) -> Iterable[Path]:
for path in paths:
if name:
if Path(path).joinpath(f"{name}.egg-link").is_file():
yield Path(path).joinpath(f"{name}.egg-link")
else:
yield from Path(path).glob("*.egg-link")
def distributions(path: list[str]) -> Iterable[im.Distribution]:
"""Find distributions in the paths. Similar to `importlib.metadata`'s
implementation but with the ability to discover egg-links.
"""
context = im.DistributionFinder.Context(path=path)
resolvers = itertools.chain(
filter(
None,
(getattr(finder, "find_distributions", None) for finder in sys.meta_path),
),
(EgglinkFinder.find_distributions,),
)
return itertools.chain.from_iterable(resolver(context) for resolver in resolvers)
| EgglinkFinder |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typePrinter1.py | {
"start": 203,
"end": 445
} | class ____:
class Inner: ...
def func1(v: A.Inner | None):
reveal_type(v, expected_text="Inner | None")
def func2(v: A.Inner | B.Inner | None):
reveal_type(v, expected_text="typePrinter1.A.Inner | typePrinter1.B.Inner | None")
| B |
python | plotly__plotly.py | plotly/graph_objs/scatterpolargl/marker/_line.py | {
"start": 233,
"end": 20964
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatterpolargl.marker"
_path_str = "scatterpolargl.marker.line"
_valid_props = {
"autocolorscale",
"cauto",
"cmax",
"cmid",
"cmin",
"color",
"coloraxis",
"colorscale",
"colorsrc",
"reversescale",
"width",
"widthsrc",
}
@property
def autocolorscale(self):
"""
Determines whether the colorscale is a default palette
(`autocolorscale: true`) or the palette determined by
`marker.line.colorscale`. Has an effect only if in
`marker.line.color` is set to a numerical array. In case
`colorscale` is unspecified or `autocolorscale` is true, the
default palette will be chosen according to whether numbers in
the `color` array are all positive, all negative or mixed.
The 'autocolorscale' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["autocolorscale"]
@autocolorscale.setter
def autocolorscale(self, val):
self["autocolorscale"] = val
@property
def cauto(self):
"""
Determines whether or not the color domain is computed with
respect to the input data (here in `marker.line.color`) or the
bounds set in `marker.line.cmin` and `marker.line.cmax` Has an
effect only if in `marker.line.color` is set to a numerical
array. Defaults to `false` when `marker.line.cmin` and
`marker.line.cmax` are set by the user.
The 'cauto' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["cauto"]
@cauto.setter
def cauto(self, val):
self["cauto"] = val
@property
def cmax(self):
"""
Sets the upper bound of the color domain. Has an effect only if
in `marker.line.color` is set to a numerical array. Value
should have the same units as in `marker.line.color` and if
set, `marker.line.cmin` must be set as well.
The 'cmax' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["cmax"]
@cmax.setter
def cmax(self, val):
self["cmax"] = val
@property
def cmid(self):
"""
Sets the mid-point of the color domain by scaling
`marker.line.cmin` and/or `marker.line.cmax` to be equidistant
to this point. Has an effect only if in `marker.line.color` is
set to a numerical array. Value should have the same units as
in `marker.line.color`. Has no effect when `marker.line.cauto`
is `false`.
The 'cmid' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["cmid"]
@cmid.setter
def cmid(self, val):
self["cmid"] = val
@property
def cmin(self):
"""
Sets the lower bound of the color domain. Has an effect only if
in `marker.line.color` is set to a numerical array. Value
should have the same units as in `marker.line.color` and if
set, `marker.line.cmax` must be set as well.
The 'cmin' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["cmin"]
@cmin.setter
def cmin(self, val):
self["cmin"] = val
@property
def color(self):
"""
Sets the marker.line color. It accepts either a specific color
or an array of numbers that are mapped to the colorscale
relative to the max and min values of the array or relative to
`marker.line.cmin` and `marker.line.cmax` if set.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
- A number that will be interpreted as a color
according to scatterpolargl.marker.line.colorscale
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def coloraxis(self):
"""
Sets a reference to a shared color axis. References to these
shared color axes are "coloraxis", "coloraxis2", "coloraxis3",
etc. Settings for these shared color axes are set in the
layout, under `layout.coloraxis`, `layout.coloraxis2`, etc.
Note that multiple color scales can be linked to the same color
axis.
The 'coloraxis' property is an identifier of a particular
subplot, of type 'coloraxis', that may be specified as the string 'coloraxis'
optionally followed by an integer >= 1
(e.g. 'coloraxis', 'coloraxis1', 'coloraxis2', 'coloraxis3', etc.)
Returns
-------
str
"""
return self["coloraxis"]
@coloraxis.setter
def coloraxis(self, val):
self["coloraxis"] = val
@property
def colorscale(self):
"""
Sets the colorscale. Has an effect only if in
`marker.line.color` is set to a numerical array. The colorscale
must be an array containing arrays mapping a normalized value
to an rgb, rgba, hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and highest (1) values
are required. For example, `[[0, 'rgb(0,0,255)'], [1,
'rgb(255,0,0)']]`. To control the bounds of the colorscale in
color space, use `marker.line.cmin` and `marker.line.cmax`.
Alternatively, `colorscale` may be a palette name string of the
following list: Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,RdBu,Reds,Viridis,
YlGnBu,YlOrRd.
The 'colorscale' property is a colorscale and may be
specified as:
- A list of colors that will be spaced evenly to create the colorscale.
Many predefined colorscale lists are included in the sequential, diverging,
and cyclical modules in the plotly.colors package.
- A list of 2-element lists where the first element is the
normalized color level value (starting at 0 and ending at 1),
and the second item is a valid color string.
(e.g. [[0, 'green'], [0.5, 'red'], [1.0, 'rgb(0, 0, 255)']])
- One of the following named colorscales:
['aggrnyl', 'agsunset', 'algae', 'amp', 'armyrose', 'balance',
'blackbody', 'bluered', 'blues', 'blugrn', 'bluyl', 'brbg',
'brwnyl', 'bugn', 'bupu', 'burg', 'burgyl', 'cividis', 'curl',
'darkmint', 'deep', 'delta', 'dense', 'earth', 'edge', 'electric',
'emrld', 'fall', 'geyser', 'gnbu', 'gray', 'greens', 'greys',
'haline', 'hot', 'hsv', 'ice', 'icefire', 'inferno', 'jet',
'magenta', 'magma', 'matter', 'mint', 'mrybm', 'mygbm', 'oranges',
'orrd', 'oryel', 'oxy', 'peach', 'phase', 'picnic', 'pinkyl',
'piyg', 'plasma', 'plotly3', 'portland', 'prgn', 'pubu', 'pubugn',
'puor', 'purd', 'purp', 'purples', 'purpor', 'rainbow', 'rdbu',
'rdgy', 'rdpu', 'rdylbu', 'rdylgn', 'redor', 'reds', 'solar',
'spectral', 'speed', 'sunset', 'sunsetdark', 'teal', 'tealgrn',
'tealrose', 'tempo', 'temps', 'thermal', 'tropic', 'turbid',
'turbo', 'twilight', 'viridis', 'ylgn', 'ylgnbu', 'ylorbr',
'ylorrd'].
Appending '_r' to a named colorscale reverses it.
Returns
-------
str
"""
return self["colorscale"]
@colorscale.setter
def colorscale(self, val):
self["colorscale"] = val
@property
def colorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `color`.
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["colorsrc"]
@colorsrc.setter
def colorsrc(self, val):
self["colorsrc"] = val
@property
def reversescale(self):
"""
Reverses the color mapping if true. Has an effect only if in
`marker.line.color` is set to a numerical array. If true,
`marker.line.cmin` will correspond to the last color in the
array and `marker.line.cmax` will correspond to the first
color.
The 'reversescale' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["reversescale"]
@reversescale.setter
def reversescale(self, val):
self["reversescale"] = val
@property
def width(self):
"""
Sets the width (in px) of the lines bounding the marker points.
The 'width' property is a number and may be specified as:
- An int or float in the interval [0, inf]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|float|numpy.ndarray
"""
return self["width"]
@width.setter
def width(self, val):
self["width"] = val
@property
def widthsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `width`.
The 'widthsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["widthsrc"]
@widthsrc.setter
def widthsrc(self, val):
self["widthsrc"] = val
@property
def _prop_descriptions(self):
return """\
autocolorscale
Determines whether the colorscale is a default palette
(`autocolorscale: true`) or the palette determined by
`marker.line.colorscale`. Has an effect only if in
`marker.line.color` is set to a numerical array. In
case `colorscale` is unspecified or `autocolorscale` is
true, the default palette will be chosen according to
whether numbers in the `color` array are all positive,
all negative or mixed.
cauto
Determines whether or not the color domain is computed
with respect to the input data (here in
`marker.line.color`) or the bounds set in
`marker.line.cmin` and `marker.line.cmax` Has an effect
only if in `marker.line.color` is set to a numerical
array. Defaults to `false` when `marker.line.cmin` and
`marker.line.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has an effect
only if in `marker.line.color` is set to a numerical
array. Value should have the same units as in
`marker.line.color` and if set, `marker.line.cmin` must
be set as well.
cmid
Sets the mid-point of the color domain by scaling
`marker.line.cmin` and/or `marker.line.cmax` to be
equidistant to this point. Has an effect only if in
`marker.line.color` is set to a numerical array. Value
should have the same units as in `marker.line.color`.
Has no effect when `marker.line.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has an effect
only if in `marker.line.color` is set to a numerical
array. Value should have the same units as in
`marker.line.color` and if set, `marker.line.cmax` must
be set as well.
color
Sets the marker.line color. It accepts either a
specific color or an array of numbers that are mapped
to the colorscale relative to the max and min values of
the array or relative to `marker.line.cmin` and
`marker.line.cmax` if set.
coloraxis
Sets a reference to a shared color axis. References to
these shared color axes are "coloraxis", "coloraxis2",
"coloraxis3", etc. Settings for these shared color axes
are set in the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple color
scales can be linked to the same color axis.
colorscale
Sets the colorscale. Has an effect only if in
`marker.line.color` is set to a numerical array. The
colorscale must be an array containing arrays mapping a
normalized value to an rgb, rgba, hex, hsl, hsv, or
named color string. At minimum, a mapping for the
lowest (0) and highest (1) values are required. For
example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in color space,
use `marker.line.cmin` and `marker.line.cmax`.
Alternatively, `colorscale` may be a palette name
string of the following list: Blackbody,Bluered,Blues,C
ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl
and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
reversescale
Reverses the color mapping if true. Has an effect only
if in `marker.line.color` is set to a numerical array.
If true, `marker.line.cmin` will correspond to the last
color in the array and `marker.line.cmax` will
correspond to the first color.
width
Sets the width (in px) of the lines bounding the marker
points.
widthsrc
Sets the source reference on Chart Studio Cloud for
`width`.
"""
def __init__(
self,
arg=None,
autocolorscale=None,
cauto=None,
cmax=None,
cmid=None,
cmin=None,
color=None,
coloraxis=None,
colorscale=None,
colorsrc=None,
reversescale=None,
width=None,
widthsrc=None,
**kwargs,
):
"""
Construct a new Line object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatterpolargl.marker.Line`
autocolorscale
Determines whether the colorscale is a default palette
(`autocolorscale: true`) or the palette determined by
`marker.line.colorscale`. Has an effect only if in
`marker.line.color` is set to a numerical array. In
case `colorscale` is unspecified or `autocolorscale` is
true, the default palette will be chosen according to
whether numbers in the `color` array are all positive,
all negative or mixed.
cauto
Determines whether or not the color domain is computed
with respect to the input data (here in
`marker.line.color`) or the bounds set in
`marker.line.cmin` and `marker.line.cmax` Has an effect
only if in `marker.line.color` is set to a numerical
array. Defaults to `false` when `marker.line.cmin` and
`marker.line.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has an effect
only if in `marker.line.color` is set to a numerical
array. Value should have the same units as in
`marker.line.color` and if set, `marker.line.cmin` must
be set as well.
cmid
Sets the mid-point of the color domain by scaling
`marker.line.cmin` and/or `marker.line.cmax` to be
equidistant to this point. Has an effect only if in
`marker.line.color` is set to a numerical array. Value
should have the same units as in `marker.line.color`.
Has no effect when `marker.line.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has an effect
only if in `marker.line.color` is set to a numerical
array. Value should have the same units as in
`marker.line.color` and if set, `marker.line.cmax` must
be set as well.
color
Sets the marker.line color. It accepts either a
specific color or an array of numbers that are mapped
to the colorscale relative to the max and min values of
the array or relative to `marker.line.cmin` and
`marker.line.cmax` if set.
coloraxis
Sets a reference to a shared color axis. References to
these shared color axes are "coloraxis", "coloraxis2",
"coloraxis3", etc. Settings for these shared color axes
are set in the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple color
scales can be linked to the same color axis.
colorscale
Sets the colorscale. Has an effect only if in
`marker.line.color` is set to a numerical array. The
colorscale must be an array containing arrays mapping a
normalized value to an rgb, rgba, hex, hsl, hsv, or
named color string. At minimum, a mapping for the
lowest (0) and highest (1) values are required. For
example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in color space,
use `marker.line.cmin` and `marker.line.cmax`.
Alternatively, `colorscale` may be a palette name
string of the following list: Blackbody,Bluered,Blues,C
ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl
and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
reversescale
Reverses the color mapping if true. Has an effect only
if in `marker.line.color` is set to a numerical array.
If true, `marker.line.cmin` will correspond to the last
color in the array and `marker.line.cmax` will
correspond to the first color.
width
Sets the width (in px) of the lines bounding the marker
points.
widthsrc
Sets the source reference on Chart Studio Cloud for
`width`.
Returns
-------
Line
"""
super().__init__("line")
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.scatterpolargl.marker.Line
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scatterpolargl.marker.Line`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("autocolorscale", arg, autocolorscale)
self._set_property("cauto", arg, cauto)
self._set_property("cmax", arg, cmax)
self._set_property("cmid", arg, cmid)
self._set_property("cmin", arg, cmin)
self._set_property("color", arg, color)
self._set_property("coloraxis", arg, coloraxis)
self._set_property("colorscale", arg, colorscale)
self._set_property("colorsrc", arg, colorsrc)
self._set_property("reversescale", arg, reversescale)
self._set_property("width", arg, width)
self._set_property("widthsrc", arg, widthsrc)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Line |
python | huggingface__transformers | src/transformers/models/sam/modeling_sam.py | {
"start": 24395,
"end": 25648
} | class ____(nn.Module):
def __init__(self, config: SamPromptEncoderConfig):
super().__init__()
self.mask_input_channels = config.mask_input_channels // 4
self.activation = ACT2FN[config.hidden_act]
self.conv1 = nn.Conv2d(1, self.mask_input_channels, kernel_size=2, stride=2)
self.conv2 = nn.Conv2d(self.mask_input_channels, config.mask_input_channels, kernel_size=2, stride=2)
self.conv3 = nn.Conv2d(config.mask_input_channels, config.hidden_size, kernel_size=1)
self.layer_norm1 = SamLayerNorm(
self.mask_input_channels, eps=config.layer_norm_eps, data_format="channels_first"
)
self.layer_norm2 = SamLayerNorm(
self.mask_input_channels * 4, eps=config.layer_norm_eps, data_format="channels_first"
)
def forward(self, masks):
hidden_states = self.conv1(masks)
hidden_states = self.layer_norm1(hidden_states)
hidden_states = self.activation(hidden_states)
hidden_states = self.conv2(hidden_states)
hidden_states = self.layer_norm2(hidden_states)
hidden_states = self.activation(hidden_states)
dense_embeddings = self.conv3(hidden_states)
return dense_embeddings
| SamMaskEmbedding |
python | ray-project__ray | python/ray/serve/_private/exceptions.py | {
"start": 0,
"end": 147
} | class ____(Exception):
"""Raised when an operation is attempted on a deployment that is being deleted."""
pass
| DeploymentIsBeingDeletedError |
python | encode__django-rest-framework | tests/test_pagination.py | {
"start": 5477,
"end": 10531
} | class ____:
"""
Unit tests for `pagination.PageNumberPagination`.
"""
def setup_method(self):
class ExamplePagination(pagination.PageNumberPagination):
page_size = 5
self.pagination = ExamplePagination()
self.queryset = range(1, 101)
def paginate_queryset(self, request):
return list(self.pagination.paginate_queryset(self.queryset, request))
def get_paginated_content(self, queryset):
response = self.pagination.get_paginated_response(queryset)
return response.data
def get_html_context(self):
return self.pagination.get_html_context()
@pytest.mark.parametrize('url', ['/', '/?page='])
def test_no_page_number(self, url):
request = Request(factory.get(url))
queryset = self.paginate_queryset(request)
content = self.get_paginated_content(queryset)
context = self.get_html_context()
assert queryset == [1, 2, 3, 4, 5]
assert content == {
'results': [1, 2, 3, 4, 5],
'previous': None,
'next': 'http://testserver/?page=2',
'count': 100
}
assert context == {
'previous_url': None,
'next_url': 'http://testserver/?page=2',
'page_links': [
PageLink('http://testserver/', 1, True, False),
PageLink('http://testserver/?page=2', 2, False, False),
PageLink('http://testserver/?page=3', 3, False, False),
PAGE_BREAK,
PageLink('http://testserver/?page=20', 20, False, False),
]
}
assert self.pagination.display_page_controls
assert isinstance(self.pagination.to_html(), str)
def test_second_page(self):
request = Request(factory.get('/', {'page': 2}))
queryset = self.paginate_queryset(request)
content = self.get_paginated_content(queryset)
context = self.get_html_context()
assert queryset == [6, 7, 8, 9, 10]
assert content == {
'results': [6, 7, 8, 9, 10],
'previous': 'http://testserver/',
'next': 'http://testserver/?page=3',
'count': 100
}
assert context == {
'previous_url': 'http://testserver/',
'next_url': 'http://testserver/?page=3',
'page_links': [
PageLink('http://testserver/', 1, False, False),
PageLink('http://testserver/?page=2', 2, True, False),
PageLink('http://testserver/?page=3', 3, False, False),
PAGE_BREAK,
PageLink('http://testserver/?page=20', 20, False, False),
]
}
def test_last_page(self):
request = Request(factory.get('/', {'page': 'last'}))
queryset = self.paginate_queryset(request)
content = self.get_paginated_content(queryset)
context = self.get_html_context()
assert queryset == [96, 97, 98, 99, 100]
assert content == {
'results': [96, 97, 98, 99, 100],
'previous': 'http://testserver/?page=19',
'next': None,
'count': 100
}
assert context == {
'previous_url': 'http://testserver/?page=19',
'next_url': None,
'page_links': [
PageLink('http://testserver/', 1, False, False),
PAGE_BREAK,
PageLink('http://testserver/?page=18', 18, False, False),
PageLink('http://testserver/?page=19', 19, False, False),
PageLink('http://testserver/?page=20', 20, True, False),
]
}
def test_invalid_page(self):
request = Request(factory.get('/', {'page': 'invalid'}))
with pytest.raises(exceptions.NotFound):
self.paginate_queryset(request)
def test_get_paginated_response_schema(self):
unpaginated_schema = {
'type': 'object',
'item': {
'properties': {
'test-property': {
'type': 'integer',
},
},
},
}
assert self.pagination.get_paginated_response_schema(unpaginated_schema) == {
'type': 'object',
'required': ['count', 'results'],
'properties': {
'count': {
'type': 'integer',
'example': 123,
},
'next': {
'type': 'string',
'nullable': True,
'format': 'uri',
'example': 'http://api.example.org/accounts/?page=4',
},
'previous': {
'type': 'string',
'nullable': True,
'format': 'uri',
'example': 'http://api.example.org/accounts/?page=2',
},
'results': unpaginated_schema,
},
}
| TestPageNumberPagination |
python | django__django | django/db/models/lookups.py | {
"start": 15094,
"end": 15431
} | class ____(BuiltinLookup):
lookup_name = "iexact"
prepare_rhs = False
def process_rhs(self, qn, connection):
rhs, params = super().process_rhs(qn, connection)
if params:
params = (connection.ops.prep_for_iexact_query(params[0]), *params[1:])
return rhs, params
@Field.register_lookup
| IExact |
python | python-attrs__attrs | src/attr/exceptions.py | {
"start": 601,
"end": 748
} | class ____(FrozenError):
"""
A frozen attribute has been attempted to be modified.
.. versionadded:: 20.1.0
"""
| FrozenAttributeError |
python | ray-project__ray | python/ray/tune/search/bohb/bohb_search.py | {
"start": 1140,
"end": 13730
} | class ____(Searcher):
"""BOHB suggestion component.
Requires HpBandSter and ConfigSpace to be installed. You can install
HpBandSter and ConfigSpace with: ``pip install hpbandster ConfigSpace``.
This should be used in conjunction with HyperBandForBOHB.
Args:
space: Continuous ConfigSpace search space.
Parameters will be sampled from this space which will be used
to run trials.
bohb_config: configuration for HpBandSter BOHB algorithm
metric: The training result objective value attribute. If None
but a mode was passed, the anonymous metric `_metric` will be used
per default.
mode: One of {min, max}. Determines whether objective is
minimizing or maximizing the metric attribute.
points_to_evaluate: Initial parameter suggestions to be run
first. This is for when you already have some good parameters
you want to run first to help the algorithm make better suggestions
for future parameters. Needs to be a list of dicts containing the
configurations.
seed: Optional random seed to initialize the random number
generator. Setting this should lead to identical initial
configurations at each run.
max_concurrent: Number of maximum concurrent trials.
If this Searcher is used in a ``ConcurrencyLimiter``, the
``max_concurrent`` value passed to it will override the
value passed here. Set to <= 0 for no limit on concurrency.
Tune automatically converts search spaces to TuneBOHB's format:
.. code-block:: python
config = {
"width": tune.uniform(0, 20),
"height": tune.uniform(-100, 100),
"activation": tune.choice(["relu", "tanh"])
}
algo = TuneBOHB(metric="mean_loss", mode="min")
bohb = HyperBandForBOHB(
time_attr="training_iteration",
metric="mean_loss",
mode="min",
max_t=100)
run(my_trainable, config=config, scheduler=bohb, search_alg=algo)
If you would like to pass the search space manually, the code would
look like this:
.. code-block:: python
import ConfigSpace as CS
config_space = CS.ConfigurationSpace()
config_space.add_hyperparameter(
CS.UniformFloatHyperparameter("width", lower=0, upper=20))
config_space.add_hyperparameter(
CS.UniformFloatHyperparameter("height", lower=-100, upper=100))
config_space.add_hyperparameter(
CS.CategoricalHyperparameter(
name="activation", choices=["relu", "tanh"]))
algo = TuneBOHB(
config_space, metric="mean_loss", mode="min")
bohb = HyperBandForBOHB(
time_attr="training_iteration",
metric="mean_loss",
mode="min",
max_t=100)
run(my_trainable, scheduler=bohb, search_alg=algo)
"""
def __init__(
self,
space: Optional[Union[Dict, "ConfigSpace.ConfigurationSpace"]] = None,
bohb_config: Optional[Dict] = None,
metric: Optional[str] = None,
mode: Optional[str] = None,
points_to_evaluate: Optional[List[Dict]] = None,
seed: Optional[int] = None,
max_concurrent: int = 0,
):
assert (
BOHB is not None
), """HpBandSter must be installed!
You can install HpBandSter with the command:
`pip install hpbandster ConfigSpace`."""
if mode:
assert mode in ["min", "max"], "`mode` must be 'min' or 'max'."
self.trial_to_params = {}
self._metric = metric
self._bohb_config = bohb_config
if isinstance(space, dict) and space:
resolved_vars, domain_vars, grid_vars = parse_spec_vars(space)
if domain_vars or grid_vars:
logger.warning(
UNRESOLVED_SEARCH_SPACE.format(par="space", cls=type(self))
)
space = self.convert_search_space(space)
self._space = space
self._seed = seed
self.running = set()
self.paused = set()
self._max_concurrent = max_concurrent
self._points_to_evaluate = points_to_evaluate
super(TuneBOHB, self).__init__(
metric=self._metric,
mode=mode,
)
if self._space:
self._setup_bohb()
def set_max_concurrency(self, max_concurrent: int) -> bool:
self._max_concurrent = max_concurrent
return True
def _setup_bohb(self):
from hpbandster.optimizers.config_generators.bohb import BOHB
if self._metric is None and self._mode:
# If only a mode was passed, use anonymous metric
self._metric = DEFAULT_METRIC
if self._mode == "max":
self._metric_op = -1.0
elif self._mode == "min":
self._metric_op = 1.0
if self._seed is not None:
self._space.seed(self._seed)
self.running = set()
self.paused = set()
bohb_config = self._bohb_config or {}
self.bohber = BOHB(self._space, **bohb_config)
def set_search_properties(
self, metric: Optional[str], mode: Optional[str], config: Dict, **spec
) -> bool:
if self._space:
return False
space = self.convert_search_space(config)
self._space = space
if metric:
self._metric = metric
if mode:
self._mode = mode
self._setup_bohb()
return True
def suggest(self, trial_id: str) -> Optional[Dict]:
if not self._space:
raise RuntimeError(
UNDEFINED_SEARCH_SPACE.format(
cls=self.__class__.__name__, space="space"
)
)
if not self._metric or not self._mode:
raise RuntimeError(
UNDEFINED_METRIC_MODE.format(
cls=self.__class__.__name__, metric=self._metric, mode=self._mode
)
)
max_concurrent = (
self._max_concurrent if self._max_concurrent > 0 else float("inf")
)
if len(self.running) >= max_concurrent:
return None
if self._points_to_evaluate:
config = self._points_to_evaluate.pop(0)
else:
# This parameter is not used in hpbandster implementation.
config, _ = self.bohber.get_config(None)
self.trial_to_params[trial_id] = copy.deepcopy(config)
self.running.add(trial_id)
return unflatten_list_dict(config)
def on_trial_result(self, trial_id: str, result: Dict):
if trial_id not in self.paused:
self.running.add(trial_id)
if "hyperband_info" not in result:
logger.warning(
"BOHB Info not detected in result. Are you using "
"HyperBandForBOHB as a scheduler?"
)
elif "budget" in result.get("hyperband_info", {}):
hbs_wrapper = self.to_wrapper(trial_id, result)
self.bohber.new_result(hbs_wrapper)
def on_trial_complete(
self, trial_id: str, result: Optional[Dict] = None, error: bool = False
):
del self.trial_to_params[trial_id]
self.paused.discard(trial_id)
self.running.discard(trial_id)
def to_wrapper(self, trial_id: str, result: Dict) -> _BOHBJobWrapper:
return _BOHBJobWrapper(
self._metric_op * result[self.metric],
result["hyperband_info"]["budget"],
self.trial_to_params[trial_id],
)
# BOHB Specific.
# TODO(team-ml): Refactor alongside HyperBandForBOHB
def on_pause(self, trial_id: str):
self.paused.add(trial_id)
self.running.discard(trial_id)
def on_unpause(self, trial_id: str):
self.paused.discard(trial_id)
self.running.add(trial_id)
@staticmethod
def convert_search_space(spec: Dict) -> "ConfigSpace.ConfigurationSpace":
resolved_vars, domain_vars, grid_vars = parse_spec_vars(spec)
if grid_vars:
raise ValueError(
"Grid search parameters cannot be automatically converted "
"to a TuneBOHB search space."
)
# Flatten and resolve again after checking for grid search.
spec = flatten_dict(spec, prevent_delimiter=True)
resolved_vars, domain_vars, grid_vars = parse_spec_vars(spec)
def resolve_value(
par: str, domain: Domain
) -> ConfigSpace.hyperparameters.Hyperparameter:
quantize = None
sampler = domain.get_sampler()
if isinstance(sampler, Quantized):
quantize = sampler.q
sampler = sampler.sampler
if isinstance(domain, Float):
if isinstance(sampler, LogUniform):
lower = domain.lower
upper = domain.upper
if quantize:
lower = math.ceil(domain.lower / quantize) * quantize
upper = math.floor(domain.upper / quantize) * quantize
return ConfigSpace.UniformFloatHyperparameter(
par, lower=lower, upper=upper, q=quantize, log=True
)
elif isinstance(sampler, Uniform):
lower = domain.lower
upper = domain.upper
if quantize:
lower = math.ceil(domain.lower / quantize) * quantize
upper = math.floor(domain.upper / quantize) * quantize
return ConfigSpace.UniformFloatHyperparameter(
par, lower=lower, upper=upper, q=quantize, log=False
)
elif isinstance(sampler, Normal):
return ConfigSpace.hyperparameters.NormalFloatHyperparameter(
par, mu=sampler.mean, sigma=sampler.sd, q=quantize, log=False
)
elif isinstance(domain, Integer):
if isinstance(sampler, LogUniform):
lower = domain.lower
upper = domain.upper
if quantize:
lower = math.ceil(domain.lower / quantize) * quantize
upper = math.floor(domain.upper / quantize) * quantize
else:
# Tune search space integers are exclusive
upper -= 1
return ConfigSpace.UniformIntegerHyperparameter(
par, lower=lower, upper=upper, q=quantize, log=True
)
elif isinstance(sampler, Uniform):
lower = domain.lower
upper = domain.upper
if quantize:
lower = math.ceil(domain.lower / quantize) * quantize
upper = math.floor(domain.upper / quantize) * quantize
else:
# Tune search space integers are exclusive
upper -= 1
return ConfigSpace.UniformIntegerHyperparameter(
par, lower=lower, upper=upper, q=quantize, log=False
)
elif isinstance(domain, Categorical):
if isinstance(sampler, Uniform):
return ConfigSpace.CategoricalHyperparameter(
par, choices=domain.categories
)
raise ValueError(
"TuneBOHB does not support parameters of type "
"`{}` with samplers of type `{}`".format(
type(domain).__name__, type(domain.sampler).__name__
)
)
cs = ConfigSpace.ConfigurationSpace()
for path, domain in domain_vars:
par = "/".join(str(p) for p in path)
value = resolve_value(par, domain)
cs.add_hyperparameter(value)
return cs
def save(self, checkpoint_path: str):
save_object = self.__dict__
with open(checkpoint_path, "wb") as outputFile:
cloudpickle.dump(save_object, outputFile)
def restore(self, checkpoint_path: str):
with open(checkpoint_path, "rb") as inputFile:
save_object = cloudpickle.load(inputFile)
self.__dict__.update(save_object)
| TuneBOHB |
python | run-llama__llama_index | llama-index-integrations/storage/kvstore/llama-index-storage-kvstore-dynamodb/llama_index/storage/kvstore/dynamodb/base.py | {
"start": 1672,
"end": 6955
} | class ____(BaseKVStore):
"""
DynamoDB Key-Value store.
Stores key-value pairs in a DynamoDB Table.
The DynamoDB Table must have both a hash key and a range key,
and their types must be string.
You can specify a custom URL for DynamoDB by setting the `DYNAMODB_URL`
environment variable. This is useful if you're using a local instance of
DynamoDB for development or testing. If `DYNAMODB_URL` is not set, the
application will use the default AWS DynamoDB service.
Args:
table (Any): DynamoDB Table Service Resource
"""
def __init__(self, table: Any):
"""Init a DynamoDBKVStore."""
self._table = table
self._boto3_key = Key
self._key_hash, self._key_range = parse_schema(table)
@classmethod
def from_table_name(cls, table_name: str) -> DynamoDBKVStore:
"""
Load a DynamoDBKVStore from a DynamoDB table name.
Args:
table_name (str): DynamoDB table name
"""
# Get the DynamoDB URL from environment variable
dynamodb_url = os.getenv("DYNAMODB_URL")
# Create a session
session = boto3.Session()
# If the DynamoDB URL is set, use it as the endpoint URL
if dynamodb_url:
ddb = session.resource("dynamodb", endpoint_url=dynamodb_url)
else:
# Otherwise, let boto3 use its default configuration
ddb = session.resource("dynamodb")
return cls(table=ddb.Table(table_name))
def put(self, key: str, val: dict, collection: str = DEFAULT_COLLECTION) -> None:
"""
Put a key-value pair into the store.
Args:
key (str): key
val (dict): value
collection (str): collection name
"""
item = {k: convert_float_to_decimal(v) for k, v in val.items()}
item[self._key_hash] = collection
item[self._key_range] = key
self._table.put_item(Item=item)
async def aput(
self, key: str, val: dict, collection: str = DEFAULT_COLLECTION
) -> None:
"""
Put a key-value pair into the store.
Args:
key (str): key
val (dict): value
collection (str): collection name
"""
raise NotImplementedError
def get(self, key: str, collection: str = DEFAULT_COLLECTION) -> dict | None:
"""
Get a value from the store.
Args:
key (str): key
collection (str): collection name
"""
resp = self._table.get_item(
Key={self._key_hash: collection, self._key_range: key}
)
if (item := resp.get("Item")) is None:
return None
else:
return {
k: convert_decimal_to_int_or_float(v)
for k, v in item.items()
if k not in {self._key_hash, self._key_range}
}
async def aget(self, key: str, collection: str = DEFAULT_COLLECTION) -> dict | None:
"""
Get a value from the store.
Args:
key (str): key
collection (str): collection name
"""
raise NotImplementedError
def get_all(self, collection: str = DEFAULT_COLLECTION) -> Dict[str, dict]:
"""
Get all values from the store.
Args:
collection (str): collection name
"""
result = {}
last_evaluated_key = None
is_first = True
while last_evaluated_key is not None or is_first:
if is_first:
is_first = False
option = {
"KeyConditionExpression": self._boto3_key(self._key_hash).eq(collection)
}
if last_evaluated_key is not None:
option["ExclusiveStartKey"] = last_evaluated_key
resp = self._table.query(**option)
for item in resp.get("Items", []):
item.pop(self._key_hash)
key = item.pop(self._key_range)
result[key] = {
k: convert_decimal_to_int_or_float(v) for k, v in item.items()
}
last_evaluated_key = resp.get("LastEvaluatedKey")
return result
async def aget_all(self, collection: str = DEFAULT_COLLECTION) -> Dict[str, dict]:
"""
Get all values from the store.
Args:
collection (str): collection name
"""
raise NotImplementedError
def delete(self, key: str, collection: str = DEFAULT_COLLECTION) -> bool:
"""
Delete a value from the store.
Args:
key (str): key
collection (str): collection name
"""
resp = self._table.delete_item(
Key={self._key_hash: collection, self._key_range: key},
ReturnValues="ALL_OLD",
)
if (item := resp.get("Attributes")) is None:
return False
else:
return len(item) > 0
async def adelete(self, key: str, collection: str = DEFAULT_COLLECTION) -> bool:
"""
Delete a value from the store.
Args:
key (str): key
collection (str): collection name
"""
raise NotImplementedError
| DynamoDBKVStore |
python | coleifer__peewee | tests/regressions.py | {
"start": 58972,
"end": 59105
} | class ____(TestModel):
src = ForeignKeyField(State, backref='sources')
dest = ForeignKeyField(State, backref='dests')
| Transition |
python | mahmoud__boltons | boltons/listutils.py | {
"start": 2390,
"end": 11557
} | class ____(list):
"""The ``BarrelList`` is a :class:`list` subtype backed by many
dynamically-scaled sublists, to provide better scaling and random
insertion/deletion characteristics. It is a subtype of the builtin
:class:`list` and has an identical API, supporting indexing,
slicing, sorting, etc. If application requirements call for
something more performant, consider the `blist module available on
PyPI`_.
The name comes by way of Kurt Rose, who said it reminded him of
barrel shifters. Not sure how, but it's BList-like, so the name
stuck. BList is of course a reference to `B-trees`_.
Args:
iterable: An optional iterable of initial values for the list.
>>> blist = BList(range(100000))
>>> blist.pop(50000)
50000
>>> len(blist)
99999
>>> len(blist.lists) # how many underlying lists
8
>>> slice_idx = blist.lists[0][-1]
>>> blist[slice_idx:slice_idx + 2]
BarrelList([11637, 11638])
Slicing is supported and works just fine across list borders,
returning another instance of the BarrelList.
.. _blist module available on PyPI: https://pypi.python.org/pypi/blist
.. _B-trees: https://en.wikipedia.org/wiki/B-tree
"""
_size_factor = 1520
"This size factor is the result of tuning using the tune() function below."
def __init__(self, iterable=None):
self.lists = [[]]
if iterable:
self.extend(iterable)
@property
def _cur_size_limit(self):
len_self, size_factor = len(self), self._size_factor
return int(round(size_factor * math_log(len_self + 2, 2)))
def _translate_index(self, index):
if index < 0:
index += len(self)
rel_idx, lists = index, self.lists
for list_idx in range(len(lists)):
len_list = len(lists[list_idx])
if rel_idx < len_list:
break
rel_idx -= len_list
if rel_idx < 0:
return None, None
return list_idx, rel_idx
def _balance_list(self, list_idx):
if list_idx < 0:
list_idx += len(self.lists)
cur_list, len_self = self.lists[list_idx], len(self)
size_limit = self._cur_size_limit
if len(cur_list) > size_limit:
half_limit = size_limit // 2
while len(cur_list) > half_limit:
next_list_idx = list_idx + 1
self.lists.insert(next_list_idx, cur_list[-half_limit:])
del cur_list[-half_limit:]
return True
return False
def insert(self, index, item):
if len(self.lists) == 1:
self.lists[0].insert(index, item)
self._balance_list(0)
else:
list_idx, rel_idx = self._translate_index(index)
if list_idx is None:
raise IndexError()
self.lists[list_idx].insert(rel_idx, item)
self._balance_list(list_idx)
return
def append(self, item):
self.lists[-1].append(item)
def extend(self, iterable):
self.lists[-1].extend(iterable)
def pop(self, *a):
lists = self.lists
if len(lists) == 1 and not a:
return self.lists[0].pop()
index = a and a[0]
if index == () or index is None or index == -1:
ret = lists[-1].pop()
if len(lists) > 1 and not lists[-1]:
lists.pop()
else:
list_idx, rel_idx = self._translate_index(index)
if list_idx is None:
raise IndexError()
ret = lists[list_idx].pop(rel_idx)
self._balance_list(list_idx)
return ret
def iter_slice(self, start, stop, step=None):
iterable = self # TODO: optimization opportunities abound
# start_list_idx, stop_list_idx = 0, len(self.lists)
if start is None:
start = 0
if stop is None:
stop = len(self)
if step is not None and step < 0:
step = -step
start, stop = -start, -stop - 1
iterable = reversed(self)
if start < 0:
start += len(self)
# start_list_idx, start_rel_idx = self._translate_index(start)
if stop < 0:
stop += len(self)
# stop_list_idx, stop_rel_idx = self._translate_index(stop)
return islice(iterable, start, stop, step)
def del_slice(self, start, stop, step=None):
if step is not None and abs(step) > 1: # punt
new_list = chain(self.iter_slice(0, start, step),
self.iter_slice(stop, None, step))
self.lists[0][:] = new_list
self._balance_list(0)
return
if start is None:
start = 0
if stop is None:
stop = len(self)
start_list_idx, start_rel_idx = self._translate_index(start)
stop_list_idx, stop_rel_idx = self._translate_index(stop)
if start_list_idx is None:
raise IndexError()
if stop_list_idx is None:
raise IndexError()
if start_list_idx == stop_list_idx:
del self.lists[start_list_idx][start_rel_idx:stop_rel_idx]
elif start_list_idx < stop_list_idx:
del self.lists[start_list_idx + 1:stop_list_idx]
del self.lists[start_list_idx][start_rel_idx:]
del self.lists[stop_list_idx][:stop_rel_idx]
else:
assert False, ('start list index should never translate to'
' greater than stop list index')
__delslice__ = del_slice
@classmethod
def from_iterable(cls, it):
return cls(it)
def __iter__(self):
return chain.from_iterable(self.lists)
def __reversed__(self):
return chain.from_iterable(reversed(l) for l in reversed(self.lists))
def __len__(self):
return sum([len(l) for l in self.lists])
def __contains__(self, item):
for cur in self.lists:
if item in cur:
return True
return False
def __getitem__(self, index):
try:
start, stop, step = index.start, index.stop, index.step
except AttributeError:
index = operator.index(index)
else:
iter_slice = self.iter_slice(start, stop, step)
ret = self.from_iterable(iter_slice)
return ret
list_idx, rel_idx = self._translate_index(index)
if list_idx is None:
raise IndexError()
return self.lists[list_idx][rel_idx]
def __delitem__(self, index):
try:
start, stop, step = index.start, index.stop, index.step
except AttributeError:
index = operator.index(index)
else:
self.del_slice(start, stop, step)
return
list_idx, rel_idx = self._translate_index(index)
if list_idx is None:
raise IndexError()
del self.lists[list_idx][rel_idx]
def __setitem__(self, index, item):
try:
start, stop, step = index.start, index.stop, index.step
except AttributeError:
index = operator.index(index)
else:
if len(self.lists) == 1:
self.lists[0][index] = item
else:
tmp = list(self)
tmp[index] = item
self.lists[:] = [tmp]
self._balance_list(0)
return
list_idx, rel_idx = self._translate_index(index)
if list_idx is None:
raise IndexError()
self.lists[list_idx][rel_idx] = item
def __getslice__(self, start, stop):
iter_slice = self.iter_slice(start, stop, 1)
return self.from_iterable(iter_slice)
def __setslice__(self, start, stop, sequence):
if len(self.lists) == 1:
self.lists[0][start:stop] = sequence
else:
tmp = list(self)
tmp[start:stop] = sequence
self.lists[:] = [tmp]
self._balance_list(0)
return
def __repr__(self):
return f'{self.__class__.__name__}({list(self)!r})'
def sort(self):
# poor pythonist's mergesort, it's faster than sorted(self)
# when the lists' average length is greater than 512.
if len(self.lists) == 1:
self.lists[0].sort()
else:
for li in self.lists:
li.sort()
tmp_sorted = sorted(chain.from_iterable(self.lists))
del self.lists[:]
self.lists.append(tmp_sorted)
self._balance_list(0)
def reverse(self):
for cur in self.lists:
cur.reverse()
self.lists.reverse()
def count(self, item):
return sum([cur.count(item) for cur in self.lists])
def index(self, item):
len_accum = 0
for cur in self.lists:
try:
rel_idx = cur.index(item)
return len_accum + rel_idx
except ValueError:
len_accum += len(cur)
raise ValueError(f'{item!r} is not in list')
BList = BarrelList
| BarrelList |
python | pytorch__pytorch | test/distributed/test_c10d_gloo.py | {
"start": 91598,
"end": 91888
} | class ____(ProcessGroupGlooTest):
lazy_init = True
def setUp(self):
os.environ["TORCH_GLOO_LAZY_INIT"] = "1"
super().setUp()
def tearDown(self) -> None:
del os.environ["TORCH_GLOO_LAZY_INIT"]
return super().tearDown()
| ProcessGroupGlooLazyInitTest |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 400072,
"end": 412709
} | class ____(VegaLiteSchema):
r"""
FieldDefWithoutScale schema wrapper.
Definition object for a data field, its type and transformation of an encoding channel.
Parameters
----------
shorthand : str, dict, Sequence[str], :class:`RepeatRef`
shorthand for field, aggregate, and type
aggregate : dict, :class:`Aggregate`, :class:`ArgmaxDef`, :class:`ArgminDef`, :class:`NonArgAggregateOp`, Literal['average', 'count', 'distinct', 'max', 'mean', 'median', 'min', 'missing', 'product', 'q1', 'q3', 'ci0', 'ci1', 'stderr', 'stdev', 'stdevp', 'sum', 'valid', 'values', 'variance', 'variancep', 'exponential', 'exponentialb']
Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``,
``"min"``, ``"max"``, ``"count"``).
**Default value:** ``undefined`` (None)
**See also:** `aggregate <https://vega.github.io/vega-lite/docs/aggregate.html>`__
documentation.
bandPosition : float
Relative position on a band of a stacked, binned, time unit, or band scale. For
example, the marks will be positioned at the beginning of the band if set to ``0``,
and at the middle of the band if set to ``0.5``.
bin : bool, dict, Literal['binned'], :class:`BinParams`, None
A flag for binning a ``quantitative`` field, `an object defining binning parameters
<https://vega.github.io/vega-lite/docs/bin.html#bin-parameters>`__, or indicating
that the data for ``x`` or ``y`` channel are binned before they are imported into
Vega-Lite (``"binned"``).
* If ``true``, default `binning parameters
<https://vega.github.io/vega-lite/docs/bin.html#bin-parameters>`__ will be
applied.
* If ``"binned"``, this indicates that the data for the ``x`` (or ``y``) channel are
already binned. You can map the bin-start field to ``x`` (or ``y``) and the
bin-end field to ``x2`` (or ``y2``). The scale and axis will be formatted similar
to binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can
also set the axis's `tickMinStep
<https://vega.github.io/vega-lite/docs/axis.html#ticks>`__ property.
**Default value:** ``false``
**See also:** `bin <https://vega.github.io/vega-lite/docs/bin.html>`__
documentation.
field : str, dict, :class:`Field`, :class:`FieldName`, :class:`RepeatRef`
**Required.** A string defining the name of the field from which to pull a data
value or an object defining iterated values from the `repeat
<https://vega.github.io/vega-lite/docs/repeat.html>`__ operator.
**See also:** `field <https://vega.github.io/vega-lite/docs/field.html>`__
documentation.
**Notes:** 1) Dots (``.``) and brackets (``[`` and ``]``) can be used to access
nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"``). If
field names contain dots or brackets but are not nested, you can use ``\\`` to
escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"``). See more details
about escaping in the `field documentation
<https://vega.github.io/vega-lite/docs/field.html>`__. 2) ``field`` is not required
if ``aggregate`` is ``count``.
timeUnit : dict, :class:`TimeUnit`, :class:`MultiTimeUnit`, :class:`BinnedTimeUnit`, :class:`SingleTimeUnit`, :class:`TimeUnitParams`, :class:`UtcMultiTimeUnit`, :class:`UtcSingleTimeUnit`, :class:`LocalMultiTimeUnit`, :class:`LocalSingleTimeUnit`, Literal['binnedyear', 'binnedyearquarter', 'binnedyearquartermonth', 'binnedyearmonth', 'binnedyearmonthdate', 'binnedyearmonthdatehours', 'binnedyearmonthdatehoursminutes', 'binnedyearmonthdatehoursminutesseconds', 'binnedyearweek', 'binnedyearweekday', 'binnedyearweekdayhours', 'binnedyearweekdayhoursminutes', 'binnedyearweekdayhoursminutesseconds', 'binnedyeardayofyear', 'binnedutcyear', 'binnedutcyearquarter', 'binnedutcyearquartermonth', 'binnedutcyearmonth', 'binnedutcyearmonthdate', 'binnedutcyearmonthdatehours', 'binnedutcyearmonthdatehoursminutes', 'binnedutcyearmonthdatehoursminutesseconds', 'binnedutcyearweek', 'binnedutcyearweekday', 'binnedutcyearweekdayhours', 'binnedutcyearweekdayhoursminutes', 'binnedutcyearweekdayhoursminutesseconds', 'binnedutcyeardayofyear', 'utcyear', 'utcquarter', 'utcmonth', 'utcweek', 'utcday', 'utcdayofyear', 'utcdate', 'utchours', 'utcminutes', 'utcseconds', 'utcmilliseconds', 'year', 'quarter', 'month', 'week', 'day', 'dayofyear', 'date', 'hours', 'minutes', 'seconds', 'milliseconds', 'utcyearquarter', 'utcyearquartermonth', 'utcyearmonth', 'utcyearmonthdate', 'utcyearmonthdatehours', 'utcyearmonthdatehoursminutes', 'utcyearmonthdatehoursminutesseconds', 'utcyearweek', 'utcyearweekday', 'utcyearweekdayhours', 'utcyearweekdayhoursminutes', 'utcyearweekdayhoursminutesseconds', 'utcyeardayofyear', 'utcquartermonth', 'utcmonthdate', 'utcmonthdatehours', 'utcmonthdatehoursminutes', 'utcmonthdatehoursminutesseconds', 'utcweekday', 'utcweekdayhours', 'utcweekdayhoursminutes', 'utcweekdayhoursminutesseconds', 'utcdayhours', 'utcdayhoursminutes', 'utcdayhoursminutesseconds', 'utchoursminutes', 'utchoursminutesseconds', 'utcminutesseconds', 'utcsecondsmilliseconds', 'yearquarter', 'yearquartermonth', 'yearmonth', 'yearmonthdate', 'yearmonthdatehours', 'yearmonthdatehoursminutes', 'yearmonthdatehoursminutesseconds', 'yearweek', 'yearweekday', 'yearweekdayhours', 'yearweekdayhoursminutes', 'yearweekdayhoursminutesseconds', 'yeardayofyear', 'quartermonth', 'monthdate', 'monthdatehours', 'monthdatehoursminutes', 'monthdatehoursminutesseconds', 'weekday', 'weekdayhours', 'weekdayhoursminutes', 'weekdayhoursminutesseconds', 'dayhours', 'dayhoursminutes', 'dayhoursminutesseconds', 'hoursminutes', 'hoursminutesseconds', 'minutesseconds', 'secondsmilliseconds']
Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours``) for a temporal
field. or `a temporal field that gets casted as ordinal
<https://vega.github.io/vega-lite/docs/type.html#cast>`__.
**Default value:** ``undefined`` (None)
**See also:** `timeUnit <https://vega.github.io/vega-lite/docs/timeunit.html>`__
documentation.
title : str, :class:`Text`, Sequence[str], None
A title for the field. If ``null``, the title will be removed.
**Default value:** derived from the field's name and transformation function
(``aggregate``, ``bin`` and ``timeUnit``). If the field has an aggregate function,
the function is displayed as part of the title (e.g., ``"Sum of Profit"``). If the
field is binned or has a time unit applied, the applied function is shown in
parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"``).
Otherwise, the title is simply the field name.
**Notes**:
1) You can customize the default field title format by providing the `fieldTitle
<https://vega.github.io/vega-lite/docs/config.html#top-level-config>`__ property in
the `config <https://vega.github.io/vega-lite/docs/config.html>`__ or `fieldTitle
function via the compile function's options
<https://vega.github.io/vega-lite/usage/compile.html#field-title>`__.
2) If both field definition's ``title`` and axis, header, or legend ``title`` are
defined, axis/header/legend title will be used.
type : :class:`StandardType`, Literal['quantitative', 'ordinal', 'temporal', 'nominal']
The type of measurement (``"quantitative"``, ``"temporal"``, ``"ordinal"``, or
``"nominal"``) for the encoded field or constant value (``datum``). It can also be a
``"geojson"`` type for encoding `'geoshape'
<https://vega.github.io/vega-lite/docs/geoshape.html>`__.
Vega-Lite automatically infers data types in many cases as discussed below. However,
type is required for a field if: (1) the field is not nominal and the field encoding
has no specified ``aggregate`` (except ``argmin`` and ``argmax``), ``bin``, scale
type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal
scale for a field with ``bin`` or ``timeUnit``.
**Default value:**
1) For a data ``field``, ``"nominal"`` is the default data type unless the field
encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or
``timeUnit`` that satisfies the following criteria:
* ``"quantitative"`` is the default type if (1) the encoded field contains ``bin``
or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is
``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a
quantitative scale <https://vega.github.io/vega-lite/docs/scale.html#type>`__.
* ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit``
or (2) the specified scale type is a time or utc scale
* ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort
order
<https://vega.github.io/vega-lite/docs/sort.html#specifying-custom-sort-order>`__,
(2) the specified scale type is an ordinal/point/band scale, or (3) the encoding
channel is ``order``.
2) For a constant value in data domain (``datum``):
* ``"quantitative"`` if the datum is a number
* ``"nominal"`` if the datum is a string
* ``"temporal"`` if the datum is `a date time object
<https://vega.github.io/vega-lite/docs/datetime.html>`__
**Note:**
* Data ``type`` describes the semantics of the data rather than the primitive data
types (number, string, etc.). The same primitive data type can have different
types of measurement. For example, numeric data can represent quantitative,
ordinal, or nominal data.
* Data values for a temporal field can be either a date-time string (e.g.,
``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"``) or a
timestamp number (e.g., ``1552199579097``).
* When using with `bin <https://vega.github.io/vega-lite/docs/bin.html>`__, the
``type`` property can be either ``"quantitative"`` (for using a linear bin scale)
or `"ordinal" (for using an ordinal bin scale)
<https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__.
* When using with `timeUnit
<https://vega.github.io/vega-lite/docs/timeunit.html>`__, the ``type`` property
can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal"
(for using an ordinal scale)
<https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__.
* When using with `aggregate
<https://vega.github.io/vega-lite/docs/aggregate.html>`__, the ``type`` property
refers to the post-aggregation data type. For example, we can calculate count
``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct",
"field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``.
* Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError``) do not have
``type`` as they must have exactly the same type as their primary channels (e.g.,
``x``, ``y``).
**See also:** `type <https://vega.github.io/vega-lite/docs/type.html>`__
documentation.
"""
_schema = {"$ref": "#/definitions/FieldDefWithoutScale"}
def __init__(
self,
shorthand: Optional[str | SchemaBase | Sequence[str] | Map] = Undefined,
aggregate: Optional[SchemaBase | Map | NonArgAggregateOp_T] = Undefined,
bandPosition: Optional[float] = Undefined,
bin: Optional[bool | SchemaBase | Literal["binned"] | Map | None] = Undefined,
field: Optional[str | SchemaBase | Map] = Undefined,
timeUnit: Optional[
SchemaBase | Map | MultiTimeUnit_T | BinnedTimeUnit_T | SingleTimeUnit_T
] = Undefined,
title: Optional[str | SchemaBase | Sequence[str] | None] = Undefined,
type: Optional[SchemaBase | StandardType_T] = Undefined,
**kwds,
):
super().__init__(
shorthand=shorthand,
aggregate=aggregate,
bandPosition=bandPosition,
bin=bin,
field=field,
timeUnit=timeUnit,
title=title,
type=type,
**kwds,
)
| FieldDefWithoutScale |
python | pyqtgraph__pyqtgraph | pyqtgraph/widgets/DataFilterWidget.py | {
"start": 4295,
"end": 5534
} | class ____(ptree.types.SimpleParameter):
def __init__(self, name, opts):
self.fieldName = name
units = opts.get('units', '')
self.units = units
self.unitPower = opts.get('unitPower', 1)
ptree.types.SimpleParameter.__init__(self,
name=name, autoIncrementName=True, type='bool', value=True, removable=True, renamable=True,
children=[
#dict(name="Field", type='list', value=name, limits=fields),
dict(name='Min', type='float', value=0.0, suffix=units, siPrefix=True),
dict(name='Max', type='float', value=1.0, suffix=units, siPrefix=True),
])
def generateMask(self, data, mask):
vals = data[self.fieldName][mask]
mask[mask] = (vals >= self['Min']) & (vals < self['Max']) ## Use inclusive minimum and non-inclusive maximum. This makes it easier to create non-overlapping selections
return mask
def describe(self):
return "%s < %s < %s" % (fn.siFormat(self['Min'], suffix=self.units, power=self.unitPower), self.fieldName, fn.siFormat(self['Max'], suffix=self.units, power=self.unitPower))
def updateFilter(self, opts):
pass
| RangeFilterItem |
python | spack__spack | lib/spack/spack/repo.py | {
"start": 60665,
"end": 61267
} | class ____(RepoDescriptor):
def __init__(self, name: Optional[str], path: str) -> None:
super().__init__(name)
self.path = path
def __repr__(self) -> str:
return f"{self.__class__.__name__}(name={self.name!r}, path={self.path!r})"
def construct(
self, cache: spack.util.file_cache.FileCache, overrides: Optional[Dict[str, Any]] = None
) -> Dict[str, Union[Repo, Exception]]:
try:
return {self.path: Repo(self.path, cache=cache, overrides=overrides)}
except RepoError as e:
return {self.path: e}
| LocalRepoDescriptor |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-scrapegraph/tests/test_tools_scrapegraph.py | {
"start": 212,
"end": 421
} | class ____(BaseModel):
"""Test schema for scraping operations."""
title: str = Field(description="Title of the content")
description: str = Field(description="Description of the content")
| TestSchema |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_autofit09.py | {
"start": 315,
"end": 1052
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("autofit09.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
text_wrap = workbook.add_format({"text_wrap": True})
worksheet.write_string(0, 0, "Hello\nFoo", text_wrap)
worksheet.write_string(2, 2, "Foo\nBamboo\nBar", text_wrap)
worksheet.set_row(0, 33)
worksheet.set_row(2, 48)
worksheet.autofit()
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/lib/metadata_service/models/generated/ConnectorRegistryDestinationDefinition.py | {
"start": 10877,
"end": 11196
} | class ____(BaseModel):
class Config:
extra = Extra.forbid
__root__: Dict[
constr(regex=r"^\d+\.\d+\.\d+(-[0-9A-Za-z-.]+)?$"), VersionReleaseCandidate
] = Field(
...,
description="Each entry denotes a release candidate version of a connector.",
)
| ConnectorReleaseCandidates |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/main.py | {
"start": 1700,
"end": 32398
} | class ____:
def __init__(self, *, typ=None, pure=False, output=None, plug_ins=None): # input=None,
# type: (Any, Optional[Text], Any, Any, Any) -> None
"""
typ: 'rt'/None -> RoundTripLoader/RoundTripDumper, (default)
'safe' -> SafeLoader/SafeDumper,
'unsafe' -> normal/unsafe Loader/Dumper
'base' -> baseloader
pure: if True only use Python modules
input/output: needed to work as context manager
plug_ins: a list of plug-in files
"""
self.typ = ['rt'] if typ is None else (typ if isinstance(typ, list) else [typ])
self.pure = pure
# self._input = input
self._output = output
self._context_manager = None # type: Any
self.plug_ins = [] # type: List[Any]
for pu in ([] if plug_ins is None else plug_ins) + self.official_plug_ins():
file_name = pu.replace(os.sep, '.')
self.plug_ins.append(import_module(file_name))
self.Resolver = spack.vendor.ruamel.yaml.resolver.VersionedResolver # type: Any
self.allow_unicode = True
self.Reader = None # type: Any
self.Representer = None # type: Any
self.Constructor = None # type: Any
self.Scanner = None # type: Any
self.Serializer = None # type: Any
self.default_flow_style = None # type: Any
self.comment_handling = None
typ_found = 1
setup_rt = False
if 'rt' in self.typ:
setup_rt = True
elif 'safe' in self.typ:
self.Emitter = (
spack.vendor.ruamel.yaml.emitter.Emitter if pure or CEmitter is None else CEmitter
)
self.Representer = spack.vendor.ruamel.yaml.representer.SafeRepresenter
self.Parser = spack.vendor.ruamel.yaml.parser.Parser if pure or CParser is None else CParser
self.Composer = spack.vendor.ruamel.yaml.composer.Composer
self.Constructor = spack.vendor.ruamel.yaml.constructor.SafeConstructor
elif 'base' in self.typ:
self.Emitter = spack.vendor.ruamel.yaml.emitter.Emitter
self.Representer = spack.vendor.ruamel.yaml.representer.BaseRepresenter
self.Parser = spack.vendor.ruamel.yaml.parser.Parser if pure or CParser is None else CParser
self.Composer = spack.vendor.ruamel.yaml.composer.Composer
self.Constructor = spack.vendor.ruamel.yaml.constructor.BaseConstructor
elif 'unsafe' in self.typ:
self.Emitter = (
spack.vendor.ruamel.yaml.emitter.Emitter if pure or CEmitter is None else CEmitter
)
self.Representer = spack.vendor.ruamel.yaml.representer.Representer
self.Parser = spack.vendor.ruamel.yaml.parser.Parser if pure or CParser is None else CParser
self.Composer = spack.vendor.ruamel.yaml.composer.Composer
self.Constructor = spack.vendor.ruamel.yaml.constructor.Constructor
elif 'rtsc' in self.typ:
self.default_flow_style = False
# no optimized rt-dumper yet
self.Emitter = spack.vendor.ruamel.yaml.emitter.Emitter
self.Serializer = spack.vendor.ruamel.yaml.serializer.Serializer
self.Representer = spack.vendor.ruamel.yaml.representer.RoundTripRepresenter
self.Scanner = spack.vendor.ruamel.yaml.scanner.RoundTripScannerSC
# no optimized rt-parser yet
self.Parser = spack.vendor.ruamel.yaml.parser.RoundTripParserSC
self.Composer = spack.vendor.ruamel.yaml.composer.Composer
self.Constructor = spack.vendor.ruamel.yaml.constructor.RoundTripConstructor
self.comment_handling = C_PRE
else:
setup_rt = True
typ_found = 0
if setup_rt:
self.default_flow_style = False
# no optimized rt-dumper yet
self.Emitter = spack.vendor.ruamel.yaml.emitter.Emitter
self.Serializer = spack.vendor.ruamel.yaml.serializer.Serializer
self.Representer = spack.vendor.ruamel.yaml.representer.RoundTripRepresenter
self.Scanner = spack.vendor.ruamel.yaml.scanner.RoundTripScanner
# no optimized rt-parser yet
self.Parser = spack.vendor.ruamel.yaml.parser.RoundTripParser
self.Composer = spack.vendor.ruamel.yaml.composer.Composer
self.Constructor = spack.vendor.ruamel.yaml.constructor.RoundTripConstructor
del setup_rt
self.stream = None
self.canonical = None
self.old_indent = None
self.width = None
self.line_break = None
self.map_indent = None
self.sequence_indent = None
self.sequence_dash_offset = 0
self.compact_seq_seq = None
self.compact_seq_map = None
self.sort_base_mapping_type_on_output = None # default: sort
self.top_level_colon_align = None
self.prefix_colon = None
self.version = None
self.preserve_quotes = None
self.allow_duplicate_keys = False # duplicate keys in map, set
self.encoding = 'utf-8'
self.explicit_start = None
self.explicit_end = None
self.tags = None
self.default_style = None
self.top_level_block_style_scalar_no_indent_error_1_1 = False
# directives end indicator with single scalar document
self.scalar_after_indicator = None
# [a, b: 1, c: {d: 2}] vs. [a, {b: 1}, {c: {d: 2}}]
self.brace_single_entry_mapping_in_flow_sequence = False
for module in self.plug_ins:
if getattr(module, 'typ', None) in self.typ:
typ_found += 1
module.init_typ(self)
break
if typ_found == 0:
raise NotImplementedError(
'typ "{}"not recognised (need to install plug-in?)'.format(self.typ)
)
@property
def reader(self):
# type: () -> Any
try:
return self._reader # type: ignore
except AttributeError:
self._reader = self.Reader(None, loader=self)
return self._reader
@property
def scanner(self):
# type: () -> Any
try:
return self._scanner # type: ignore
except AttributeError:
self._scanner = self.Scanner(loader=self)
return self._scanner
@property
def parser(self):
# type: () -> Any
attr = '_' + sys._getframe().f_code.co_name
if not hasattr(self, attr):
if self.Parser is not CParser:
setattr(self, attr, self.Parser(loader=self))
else:
if getattr(self, '_stream', None) is None:
# wait for the stream
return None
else:
# if not hasattr(self._stream, 'read') and hasattr(self._stream, 'open'):
# # pathlib.Path() instance
# setattr(self, attr, CParser(self._stream))
# else:
setattr(self, attr, CParser(self._stream))
# self._parser = self._composer = self
# nprint('scanner', self.loader.scanner)
return getattr(self, attr)
@property
def composer(self):
# type: () -> Any
attr = '_' + sys._getframe().f_code.co_name
if not hasattr(self, attr):
setattr(self, attr, self.Composer(loader=self))
return getattr(self, attr)
@property
def constructor(self):
# type: () -> Any
attr = '_' + sys._getframe().f_code.co_name
if not hasattr(self, attr):
cnst = self.Constructor(preserve_quotes=self.preserve_quotes, loader=self)
cnst.allow_duplicate_keys = self.allow_duplicate_keys
setattr(self, attr, cnst)
return getattr(self, attr)
@property
def resolver(self):
# type: () -> Any
attr = '_' + sys._getframe().f_code.co_name
if not hasattr(self, attr):
setattr(self, attr, self.Resolver(version=self.version, loader=self))
return getattr(self, attr)
@property
def emitter(self):
# type: () -> Any
attr = '_' + sys._getframe().f_code.co_name
if not hasattr(self, attr):
if self.Emitter is not CEmitter:
_emitter = self.Emitter(
None,
canonical=self.canonical,
indent=self.old_indent,
width=self.width,
allow_unicode=self.allow_unicode,
line_break=self.line_break,
prefix_colon=self.prefix_colon,
brace_single_entry_mapping_in_flow_sequence=self.brace_single_entry_mapping_in_flow_sequence, # NOQA
dumper=self,
)
setattr(self, attr, _emitter)
if self.map_indent is not None:
_emitter.best_map_indent = self.map_indent
if self.sequence_indent is not None:
_emitter.best_sequence_indent = self.sequence_indent
if self.sequence_dash_offset is not None:
_emitter.sequence_dash_offset = self.sequence_dash_offset
# _emitter.block_seq_indent = self.sequence_dash_offset
if self.compact_seq_seq is not None:
_emitter.compact_seq_seq = self.compact_seq_seq
if self.compact_seq_map is not None:
_emitter.compact_seq_map = self.compact_seq_map
else:
if getattr(self, '_stream', None) is None:
# wait for the stream
return None
return None
return getattr(self, attr)
@property
def serializer(self):
# type: () -> Any
attr = '_' + sys._getframe().f_code.co_name
if not hasattr(self, attr):
setattr(
self,
attr,
self.Serializer(
encoding=self.encoding,
explicit_start=self.explicit_start,
explicit_end=self.explicit_end,
version=self.version,
tags=self.tags,
dumper=self,
),
)
return getattr(self, attr)
@property
def representer(self):
# type: () -> Any
attr = '_' + sys._getframe().f_code.co_name
if not hasattr(self, attr):
repres = self.Representer(
default_style=self.default_style,
default_flow_style=self.default_flow_style,
dumper=self,
)
if self.sort_base_mapping_type_on_output is not None:
repres.sort_base_mapping_type_on_output = self.sort_base_mapping_type_on_output
setattr(self, attr, repres)
return getattr(self, attr)
def scan(self, stream):
# type: (StreamTextType) -> Any
"""
Scan a YAML stream and produce scanning tokens.
"""
if not hasattr(stream, 'read') and hasattr(stream, 'open'):
# pathlib.Path() instance
with stream.open('rb') as fp:
return self.scan(fp)
_, parser = self.get_constructor_parser(stream)
try:
while self.scanner.check_token():
yield self.scanner.get_token()
finally:
parser.dispose()
try:
self._reader.reset_reader()
except AttributeError:
pass
try:
self._scanner.reset_scanner()
except AttributeError:
pass
def parse(self, stream):
# type: (StreamTextType) -> Any
"""
Parse a YAML stream and produce parsing events.
"""
if not hasattr(stream, 'read') and hasattr(stream, 'open'):
# pathlib.Path() instance
with stream.open('rb') as fp:
return self.parse(fp)
_, parser = self.get_constructor_parser(stream)
try:
while parser.check_event():
yield parser.get_event()
finally:
parser.dispose()
try:
self._reader.reset_reader()
except AttributeError:
pass
try:
self._scanner.reset_scanner()
except AttributeError:
pass
def compose(self, stream):
# type: (Union[Path, StreamTextType]) -> Any
"""
Parse the first YAML document in a stream
and produce the corresponding representation tree.
"""
if not hasattr(stream, 'read') and hasattr(stream, 'open'):
# pathlib.Path() instance
with stream.open('rb') as fp:
return self.compose(fp)
constructor, parser = self.get_constructor_parser(stream)
try:
return constructor.composer.get_single_node()
finally:
parser.dispose()
try:
self._reader.reset_reader()
except AttributeError:
pass
try:
self._scanner.reset_scanner()
except AttributeError:
pass
def compose_all(self, stream):
# type: (Union[Path, StreamTextType]) -> Any
"""
Parse all YAML documents in a stream
and produce corresponding representation trees.
"""
constructor, parser = self.get_constructor_parser(stream)
try:
while constructor.composer.check_node():
yield constructor.composer.get_node()
finally:
parser.dispose()
try:
self._reader.reset_reader()
except AttributeError:
pass
try:
self._scanner.reset_scanner()
except AttributeError:
pass
# separate output resolver?
# def load(self, stream=None):
# if self._context_manager:
# if not self._input:
# raise TypeError("Missing input stream while dumping from context manager")
# for data in self._context_manager.load():
# yield data
# return
# if stream is None:
# raise TypeError("Need a stream argument when not loading from context manager")
# return self.load_one(stream)
def load(self, stream):
# type: (Union[Path, StreamTextType]) -> Any
"""
at this point you either have the non-pure Parser (which has its own reader and
scanner) or you have the pure Parser.
If the pure Parser is set, then set the Reader and Scanner, if not already set.
If either the Scanner or Reader are set, you cannot use the non-pure Parser,
so reset it to the pure parser and set the Reader resp. Scanner if necessary
"""
if not hasattr(stream, 'read') and hasattr(stream, 'open'):
# pathlib.Path() instance
with stream.open('rb') as fp:
return self.load(fp)
constructor, parser = self.get_constructor_parser(stream)
try:
return constructor.get_single_data()
finally:
parser.dispose()
try:
self._reader.reset_reader()
except AttributeError:
pass
try:
self._scanner.reset_scanner()
except AttributeError:
pass
def load_all(self, stream): # *, skip=None):
# type: (Union[Path, StreamTextType]) -> Any
if not hasattr(stream, 'read') and hasattr(stream, 'open'):
# pathlib.Path() instance
with stream.open('r') as fp:
for d in self.load_all(fp):
yield d
return
# if skip is None:
# skip = []
# elif isinstance(skip, int):
# skip = [skip]
constructor, parser = self.get_constructor_parser(stream)
try:
while constructor.check_data():
yield constructor.get_data()
finally:
parser.dispose()
try:
self._reader.reset_reader()
except AttributeError:
pass
try:
self._scanner.reset_scanner()
except AttributeError:
pass
def get_constructor_parser(self, stream):
# type: (StreamTextType) -> Any
"""
the old cyaml needs special setup, and therefore the stream
"""
if self.Parser is not CParser:
if self.Reader is None:
self.Reader = spack.vendor.ruamel.yaml.reader.Reader
if self.Scanner is None:
self.Scanner = spack.vendor.ruamel.yaml.scanner.Scanner
self.reader.stream = stream
else:
if self.Reader is not None:
if self.Scanner is None:
self.Scanner = spack.vendor.ruamel.yaml.scanner.Scanner
self.Parser = spack.vendor.ruamel.yaml.parser.Parser
self.reader.stream = stream
elif self.Scanner is not None:
if self.Reader is None:
self.Reader = spack.vendor.ruamel.yaml.reader.Reader
self.Parser = spack.vendor.ruamel.yaml.parser.Parser
self.reader.stream = stream
else:
# combined C level reader>scanner>parser
# does some calls to the resolver, e.g. BaseResolver.descend_resolver
# if you just initialise the CParser, to much of resolver.py
# is actually used
rslvr = self.Resolver
# if rslvr is spack.vendor.ruamel.yaml.resolver.VersionedResolver:
# rslvr = spack.vendor.ruamel.yaml.resolver.Resolver
class XLoader(self.Parser, self.Constructor, rslvr): # type: ignore
def __init__(selfx, stream, version=self.version, preserve_quotes=None):
# type: (StreamTextType, Optional[VersionType], Optional[bool]) -> None # NOQA
CParser.__init__(selfx, stream)
selfx._parser = selfx._composer = selfx
self.Constructor.__init__(selfx, loader=selfx)
selfx.allow_duplicate_keys = self.allow_duplicate_keys
rslvr.__init__(selfx, version=version, loadumper=selfx)
self._stream = stream
loader = XLoader(stream)
return loader, loader
return self.constructor, self.parser
def emit(self, events, stream):
# type: (Any, Any) -> None
"""
Emit YAML parsing events into a stream.
If stream is None, return the produced string instead.
"""
_, _, emitter = self.get_serializer_representer_emitter(stream, None)
try:
for event in events:
emitter.emit(event)
finally:
try:
emitter.dispose()
except AttributeError:
raise
def serialize(self, node, stream):
# type: (Any, Optional[StreamType]) -> Any
"""
Serialize a representation tree into a YAML stream.
If stream is None, return the produced string instead.
"""
self.serialize_all([node], stream)
def serialize_all(self, nodes, stream):
# type: (Any, Optional[StreamType]) -> Any
"""
Serialize a sequence of representation trees into a YAML stream.
If stream is None, return the produced string instead.
"""
serializer, _, emitter = self.get_serializer_representer_emitter(stream, None)
try:
serializer.open()
for node in nodes:
serializer.serialize(node)
serializer.close()
finally:
try:
emitter.dispose()
except AttributeError:
raise
def dump(self, data, stream=None, *, transform=None):
# type: (Any, Union[Path, StreamType], Any, Any) -> Any
if self._context_manager:
if not self._output:
raise TypeError('Missing output stream while dumping from context manager')
if transform is not None:
raise TypeError(
'{}.dump() in the context manager cannot have transform keyword '
''.format(self.__class__.__name__)
)
self._context_manager.dump(data)
else: # old style
if stream is None:
raise TypeError('Need a stream argument when not dumping from context manager')
return self.dump_all([data], stream, transform=transform)
def dump_all(self, documents, stream, *, transform=None):
# type: (Any, Union[Path, StreamType], Any) -> Any
if self._context_manager:
raise NotImplementedError
self._output = stream
self._context_manager = YAMLContextManager(self, transform=transform)
for data in documents:
self._context_manager.dump(data)
self._context_manager.teardown_output()
self._output = None
self._context_manager = None
def Xdump_all(self, documents, stream, *, transform=None):
# type: (Any, Any, Any) -> Any
"""
Serialize a sequence of Python objects into a YAML stream.
"""
if not hasattr(stream, 'write') and hasattr(stream, 'open'):
# pathlib.Path() instance
with stream.open('w') as fp:
return self.dump_all(documents, fp, transform=transform)
# The stream should have the methods `write` and possibly `flush`.
if self.top_level_colon_align is True:
tlca = max([len(str(x)) for x in documents[0]]) # type: Any
else:
tlca = self.top_level_colon_align
if transform is not None:
fstream = stream
if self.encoding is None:
stream = StringIO()
else:
stream = BytesIO()
serializer, representer, emitter = self.get_serializer_representer_emitter(
stream, tlca
)
try:
self.serializer.open()
for data in documents:
try:
self.representer.represent(data)
except AttributeError:
# nprint(dir(dumper._representer))
raise
self.serializer.close()
finally:
try:
self.emitter.dispose()
except AttributeError:
raise
# self.dumper.dispose() # cyaml
delattr(self, '_serializer')
delattr(self, '_emitter')
if transform:
val = stream.getvalue()
if self.encoding:
val = val.decode(self.encoding)
if fstream is None:
transform(val)
else:
fstream.write(transform(val))
return None
def get_serializer_representer_emitter(self, stream, tlca):
# type: (StreamType, Any) -> Any
# we have only .Serializer to deal with (vs .Reader & .Scanner), much simpler
if self.Emitter is not CEmitter:
if self.Serializer is None:
self.Serializer = spack.vendor.ruamel.yaml.serializer.Serializer
self.emitter.stream = stream
self.emitter.top_level_colon_align = tlca
if self.scalar_after_indicator is not None:
self.emitter.scalar_after_indicator = self.scalar_after_indicator
return self.serializer, self.representer, self.emitter
if self.Serializer is not None:
# cannot set serializer with CEmitter
self.Emitter = spack.vendor.ruamel.yaml.emitter.Emitter
self.emitter.stream = stream
self.emitter.top_level_colon_align = tlca
if self.scalar_after_indicator is not None:
self.emitter.scalar_after_indicator = self.scalar_after_indicator
return self.serializer, self.representer, self.emitter
# C routines
rslvr = (
spack.vendor.ruamel.yaml.resolver.BaseResolver
if 'base' in self.typ
else spack.vendor.ruamel.yaml.resolver.Resolver
)
class XDumper(CEmitter, self.Representer, rslvr): # type: ignore
def __init__(
selfx,
stream,
default_style=None,
default_flow_style=None,
canonical=None,
indent=None,
width=None,
allow_unicode=None,
line_break=None,
encoding=None,
explicit_start=None,
explicit_end=None,
version=None,
tags=None,
block_seq_indent=None,
top_level_colon_align=None,
prefix_colon=None,
):
# type: (StreamType, Any, Any, Any, Optional[bool], Optional[int], Optional[int], Optional[bool], Any, Any, Optional[bool], Optional[bool], Any, Any, Any, Any, Any) -> None # NOQA
CEmitter.__init__(
selfx,
stream,
canonical=canonical,
indent=indent,
width=width,
encoding=encoding,
allow_unicode=allow_unicode,
line_break=line_break,
explicit_start=explicit_start,
explicit_end=explicit_end,
version=version,
tags=tags,
)
selfx._emitter = selfx._serializer = selfx._representer = selfx
self.Representer.__init__(
selfx, default_style=default_style, default_flow_style=default_flow_style
)
rslvr.__init__(selfx)
self._stream = stream
dumper = XDumper(
stream,
default_style=self.default_style,
default_flow_style=self.default_flow_style,
canonical=self.canonical,
indent=self.old_indent,
width=self.width,
allow_unicode=self.allow_unicode,
line_break=self.line_break,
explicit_start=self.explicit_start,
explicit_end=self.explicit_end,
version=self.version,
tags=self.tags,
)
self._emitter = self._serializer = dumper
return dumper, dumper, dumper
# basic types
def map(self, **kw):
# type: (Any) -> Any
if 'rt' in self.typ:
return CommentedMap(**kw)
else:
return dict(**kw)
def seq(self, *args):
# type: (Any) -> Any
if 'rt' in self.typ:
return CommentedSeq(*args)
else:
return list(*args)
# helpers
def official_plug_ins(self):
# type: () -> Any
"""search for list of subdirs that are plug-ins, if __file__ is not available, e.g.
single file installers that are not properly emulating a file-system (issue 324)
no plug-ins will be found. If any are packaged, you know which file that are
and you can explicitly provide it during instantiation:
yaml = spack.vendor.ruamel.yaml.YAML(plug_ins=['spack.vendor.ruamel.yaml/spack.vendor.jinja2/__plug_in__'])
"""
try:
bd = os.path.dirname(__file__)
except NameError:
return []
gpbd = os.path.dirname(os.path.dirname(bd))
res = [x.replace(gpbd, "")[1:-3] for x in glob.glob(bd + '/*/__plug_in__.py')]
return res
def register_class(self, cls):
# type:(Any) -> Any
"""
register a class for dumping loading
- if it has attribute yaml_tag use that to register, else use class name
- if it has methods to_yaml/from_yaml use those to dump/load else dump attributes
as mapping
"""
tag = getattr(cls, 'yaml_tag', '!' + cls.__name__)
try:
self.representer.add_representer(cls, cls.to_yaml)
except AttributeError:
def t_y(representer, data):
# type: (Any, Any) -> Any
return representer.represent_yaml_object(
tag, data, cls, flow_style=representer.default_flow_style
)
self.representer.add_representer(cls, t_y)
try:
self.constructor.add_constructor(tag, cls.from_yaml)
except AttributeError:
def f_y(constructor, node):
# type: (Any, Any) -> Any
return constructor.construct_yaml_object(node, cls)
self.constructor.add_constructor(tag, f_y)
return cls
# ### context manager
def __enter__(self):
# type: () -> Any
self._context_manager = YAMLContextManager(self)
return self
def __exit__(self, typ, value, traceback):
# type: (Any, Any, Any) -> None
if typ:
nprint('typ', typ)
self._context_manager.teardown_output()
# self._context_manager.teardown_input()
self._context_manager = None
# ### backwards compatibility
def _indent(self, mapping=None, sequence=None, offset=None):
# type: (Any, Any, Any) -> None
if mapping is not None:
self.map_indent = mapping
if sequence is not None:
self.sequence_indent = sequence
if offset is not None:
self.sequence_dash_offset = offset
@property
def indent(self):
# type: () -> Any
return self._indent
@indent.setter
def indent(self, val):
# type: (Any) -> None
self.old_indent = val
@property
def block_seq_indent(self):
# type: () -> Any
return self.sequence_dash_offset
@block_seq_indent.setter
def block_seq_indent(self, val):
# type: (Any) -> None
self.sequence_dash_offset = val
def compact(self, seq_seq=None, seq_map=None):
# type: (Any, Any) -> None
self.compact_seq_seq = seq_seq
self.compact_seq_map = seq_map
| YAML |
python | django__django | tests/admin_views/tests.py | {
"start": 200519,
"end": 204173
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(
username="super", password="secret", email="super@example.com"
)
def setUp(self):
self.client.force_login(self.superuser)
def test_inline(self):
"""
Inline models which inherit from a common parent are correctly handled.
"""
foo_user = "foo username"
bar_user = "bar username"
name_re = re.compile(b'name="(.*?)"')
# test the add case
response = self.client.get(reverse("admin:admin_views_persona_add"))
names = name_re.findall(response.content)
names.remove(b"csrfmiddlewaretoken")
# make sure we have no duplicate HTML names
self.assertEqual(len(names), len(set(names)))
# test the add case
post_data = {
"name": "Test Name",
# inline data
"accounts-TOTAL_FORMS": "1",
"accounts-INITIAL_FORMS": "0",
"accounts-MAX_NUM_FORMS": "0",
"accounts-0-username": foo_user,
"accounts-2-TOTAL_FORMS": "1",
"accounts-2-INITIAL_FORMS": "0",
"accounts-2-MAX_NUM_FORMS": "0",
"accounts-2-0-username": bar_user,
}
response = self.client.post(reverse("admin:admin_views_persona_add"), post_data)
self.assertEqual(response.status_code, 302) # redirect somewhere
self.assertEqual(Persona.objects.count(), 1)
self.assertEqual(FooAccount.objects.count(), 1)
self.assertEqual(BarAccount.objects.count(), 1)
self.assertEqual(FooAccount.objects.all()[0].username, foo_user)
self.assertEqual(BarAccount.objects.all()[0].username, bar_user)
self.assertEqual(Persona.objects.all()[0].accounts.count(), 2)
persona_id = Persona.objects.all()[0].id
foo_id = FooAccount.objects.all()[0].id
bar_id = BarAccount.objects.all()[0].id
# test the edit case
response = self.client.get(
reverse("admin:admin_views_persona_change", args=(persona_id,))
)
names = name_re.findall(response.content)
names.remove(b"csrfmiddlewaretoken")
# make sure we have no duplicate HTML names
self.assertEqual(len(names), len(set(names)))
post_data = {
"name": "Test Name",
"accounts-TOTAL_FORMS": "2",
"accounts-INITIAL_FORMS": "1",
"accounts-MAX_NUM_FORMS": "0",
"accounts-0-username": "%s-1" % foo_user,
"accounts-0-account_ptr": str(foo_id),
"accounts-0-persona": str(persona_id),
"accounts-2-TOTAL_FORMS": "2",
"accounts-2-INITIAL_FORMS": "1",
"accounts-2-MAX_NUM_FORMS": "0",
"accounts-2-0-username": "%s-1" % bar_user,
"accounts-2-0-account_ptr": str(bar_id),
"accounts-2-0-persona": str(persona_id),
}
response = self.client.post(
reverse("admin:admin_views_persona_change", args=(persona_id,)), post_data
)
self.assertEqual(response.status_code, 302)
self.assertEqual(Persona.objects.count(), 1)
self.assertEqual(FooAccount.objects.count(), 1)
self.assertEqual(BarAccount.objects.count(), 1)
self.assertEqual(FooAccount.objects.all()[0].username, "%s-1" % foo_user)
self.assertEqual(BarAccount.objects.all()[0].username, "%s-1" % bar_user)
self.assertEqual(Persona.objects.all()[0].accounts.count(), 2)
@override_settings(ROOT_URLCONF="admin_views.urls")
| AdminInheritedInlinesTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-intercom/unit_tests/integration/test_segments.py | {
"start": 2577,
"end": 2979
} | class ____(TestCase):
@HttpMocker()
def test_when_read_then_extract_records(self, http_mocker: HttpMocker) -> None:
http_mocker.get(
HttpRequest("https://api.intercom.io/segments"),
_response().with_record(_record()).with_record(_record()).build(),
)
output = read(ConfigBuilder(), StateBuilder())
assert len(output.records) == 2
| SegmentsTest |
python | ray-project__ray | release/air_tests/air_benchmarks/workloads/benchmark_util.py | {
"start": 1476,
"end": 4086
} | class ____:
def run_command(self, cmd: str):
return subprocess.check_call(cmd)
def run_fn(self, fn: Callable, *args, **kwargs):
return fn(*args, **kwargs)
def create_actors_with_options(
num_actors: int,
resources: Dict[str, Union[float, int]],
) -> List[ray.actor.ActorHandle]:
num_cpus = resources.pop("CPU", 1)
num_gpus = resources.pop("GPU", 0)
options = {"num_cpus": num_cpus, "num_gpus": num_gpus, "resources": resources}
return [CommandRunner.options(**options).remote() for _ in range(num_actors)]
def run_commands_on_actors(actors: List[ray.actor.ActorHandle], cmds: List[List[str]]):
assert len(actors) == len(cmds)
futures = []
for actor, cmd in zip(actors, cmds):
futures.append(actor.run_command.remote(cmd))
return ray.get(futures)
def run_fn_on_actors(
actors: List[ray.actor.ActorHandle], fn: Callable, *args, **kwargs
):
futures = []
for actor in actors:
futures.append(actor.run_fn.remote(fn, *args, **kwargs))
return ray.get(futures)
def get_ip_port_actors(actors: List[ray.actor.ActorHandle]) -> List[str]:
# We need this wrapper to avoid deserialization issues with benchmark_util.py
def get_ip_port():
ip = ray.util.get_node_ip_address()
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.bind(("localhost", 0))
port = s.getsockname()[1]
return ip, port
return run_fn_on_actors(actors=actors, fn=get_ip_port)
def get_gpu_ids_actors(actors: List[ray.actor.ActorHandle]) -> List[List[int]]:
# We need this wrapper to avoid deserialization issues with benchmark_util.py
def get_gpu_ids():
return ray.get_gpu_ids()
return run_fn_on_actors(actors=actors, fn=get_gpu_ids)
def map_ips_to_gpus(ips: List[str], gpus: List[List[int]]):
assert len(ips) == len(gpus)
map = defaultdict(set)
for ip, gpu in zip(ips, gpus):
map[ip].update(set(gpu))
return {ip: sorted(gpus) for ip, gpus in map.items()}
def set_cuda_visible_devices(
actors: List[ray.actor.ActorHandle],
actor_ips: List[str],
ip_to_gpus: Dict[str, set],
):
assert len(actors) == len(actor_ips)
def set_env(key: str, val: str):
os.environ[key] = val
futures = []
for actor, ip in zip(actors, actor_ips):
assert ip in ip_to_gpus
gpu_str = ",".join([str(device) for device in sorted(ip_to_gpus[ip])])
future = actor.run_fn.remote(set_env, "CUDA_VISIBLE_DEVICES", gpu_str)
futures.append(future)
ray.get(futures)
| CommandRunner |
python | mlflow__mlflow | tests/evaluate/test_evaluation.py | {
"start": 28613,
"end": 28890
} | class ____(ModelEvaluator):
@classmethod
def can_evaluate(cls, *, model_type, evaluator_config, **kwargs):
raise RuntimeError()
def evaluate(self, *, model, model_type, dataset, run_id, evaluator_config, **kwargs):
raise RuntimeError()
| FakeEvaluator1 |
python | protocolbuffers__protobuf | python/google/protobuf/internal/descriptor_pool_test.py | {
"start": 68815,
"end": 69143
} | class ____(descriptor_database.DescriptorDatabase):
def FindFileContainingExtension(self, extendee_name, extension_number):
return descriptor_pb2.FileDescriptorProto.FromString(
factory_test2_pb2.DESCRIPTOR.serialized_pb
)
def FindAllExtensionNumbers(self, extendee_name):
return [1001, 1002]
| LocalFakeDB |
python | great-expectations__great_expectations | great_expectations/data_context/types/resource_identifiers.py | {
"start": 1915,
"end": 2795
} | class ____(DataContextKey):
"""A BatchIdentifier tracks"""
def __init__(
self,
batch_identifier: Union[BatchKwargs, dict, str],
data_asset_name: Optional[str] = None,
) -> None:
super().__init__()
# if isinstance(batch_identifier, (BatchKwargs, dict)):
# self._batch_identifier = batch_identifier.batch_fingerprint
self._batch_identifier = batch_identifier
self._data_asset_name = data_asset_name
@property
def batch_identifier(self):
return self._batch_identifier
@property
def data_asset_name(self):
return self._data_asset_name
def to_tuple(self): # type: ignore[explicit-override] # FIXME
return (self.batch_identifier,)
@classmethod
@override
def from_tuple(cls, tuple_):
return cls(batch_identifier=tuple_[0])
| BatchIdentifier |
python | doocs__leetcode | solution/0200-0299/0272.Closest Binary Search Tree Value II/Solution.py | {
"start": 192,
"end": 717
} | class ____:
def closestKValues(self, root: TreeNode, target: float, k: int) -> List[int]:
def dfs(root):
if root is None:
return
dfs(root.left)
if len(q) < k:
q.append(root.val)
else:
if abs(root.val - target) >= abs(q[0] - target):
return
q.popleft()
q.append(root.val)
dfs(root.right)
q = deque()
dfs(root)
return list(q)
| Solution |
python | huggingface__transformers | src/transformers/models/autoformer/modeling_autoformer.py | {
"start": 17034,
"end": 17532
} | class ____(nn.Module):
def __init__(self, feature_size, d_model):
super().__init__()
self.value_projection = nn.Linear(in_features=feature_size, out_features=d_model, bias=False)
def forward(self, x):
return self.value_projection(x)
# Class based on
# https://github.com/thuml/Autoformer/blob/c6a0694ff484753f2d986cc0bb1f99ee850fc1a8/layers/Autoformer_EncDec.py#L39
# where AutoformerSeriesDecompositionLayer is series_decomp + moving_average
| AutoformerValueEmbedding |
python | PyCQA__pylint | pylint/checkers/logging.py | {
"start": 4753,
"end": 16207
} | class ____(checkers.BaseChecker):
"""Checks use of the logging module."""
name = "logging"
msgs = MSGS
options = (
(
"logging-modules",
{
"default": ("logging",),
"type": "csv",
"metavar": "<comma separated list>",
"help": "Logging modules to check that the string format "
"arguments are in logging function parameter format.",
},
),
(
"logging-format-style",
{
"default": "old",
"type": "choice",
"metavar": "<old (%) or new ({)>",
"choices": ["old", "new"],
"help": "The type of string formatting that logging methods do. "
"`old` means using % formatting, `new` is for `{}` formatting.",
},
),
)
def visit_module(self, _: nodes.Module) -> None:
"""Clears any state left in this checker from last module checked."""
# The code being checked can just as easily "import logging as foo",
# so it is necessary to process the imports and store in this field
# what name the logging module is actually given.
self._logging_names: set[str] = set()
logging_mods = self.linter.config.logging_modules
self._format_style = self.linter.config.logging_format_style
self._logging_modules = set(logging_mods)
self._from_imports = {}
for logging_mod in logging_mods:
parts = logging_mod.rsplit(".", 1)
if len(parts) > 1:
self._from_imports[parts[0]] = parts[1]
def visit_importfrom(self, node: nodes.ImportFrom) -> None:
"""Checks to see if a module uses a non-Python logging module."""
try:
logging_name = self._from_imports[node.modname]
for module, as_name in node.names:
if module == logging_name:
self._logging_names.add(as_name or module)
except KeyError:
pass
def visit_import(self, node: nodes.Import) -> None:
"""Checks to see if this module uses Python's built-in logging."""
for module, as_name in node.names:
if module in self._logging_modules:
self._logging_names.add(as_name or module)
def visit_call(self, node: nodes.Call) -> None:
"""Checks calls to logging methods."""
def is_logging_name() -> bool:
match node.func:
case nodes.Attribute(expr=nodes.Name(name=name)):
return name in self._logging_names
return False
def is_logger_class() -> tuple[bool, str | None]:
for inferred in infer_all(node.func):
if isinstance(inferred, astroid.BoundMethod):
parent = inferred._proxied.parent
if isinstance(parent, nodes.ClassDef) and (
parent.qname() == "logging.Logger"
or any(
ancestor.qname() == "logging.Logger"
for ancestor in parent.ancestors()
)
):
return True, inferred._proxied.name
return False, None
if is_logging_name():
name = node.func.attrname
else:
result, name = is_logger_class()
if not result:
return
self._check_log_method(node, name)
def _check_log_method(self, node: nodes.Call, name: str) -> None:
"""Checks calls to logging.log(level, format, *format_args)."""
if name == "log":
if node.starargs or node.kwargs or len(node.args) < 2:
# Either a malformed call, star args, or double-star args. Beyond
# the scope of this checker.
return
format_pos: Literal[0, 1] = 1
elif name in CHECKED_CONVENIENCE_FUNCTIONS:
if node.starargs or node.kwargs or not node.args:
# Either no args, star args, or double-star args. Beyond the
# scope of this checker.
return
format_pos = 0
else:
return
match format_arg := node.args[format_pos]:
case nodes.BinOp():
binop = format_arg
emit = binop.op == "%"
if binop.op == "+" and not self._is_node_explicit_str_concatenation(
binop
):
total_number_of_strings = sum(
1
for operand in (binop.left, binop.right)
if self._is_operand_literal_str(utils.safe_infer(operand))
)
emit = total_number_of_strings > 0
if emit:
self.add_message(
"logging-not-lazy",
node=node,
args=(self._helper_string(node),),
)
case nodes.Call():
self._check_call_func(format_arg)
case nodes.Const():
self._check_format_string(node, format_pos)
case nodes.JoinedStr():
if str_formatting_in_f_string(format_arg):
return
self.add_message(
"logging-fstring-interpolation",
node=node,
args=(self._helper_string(node),),
)
def _helper_string(self, node: nodes.Call) -> str:
"""Create a string that lists the valid types of formatting for this node."""
valid_types = ["lazy %"]
if not self.linter.is_message_enabled(
"logging-fstring-formatting", node.fromlineno
):
valid_types.append("fstring")
if not self.linter.is_message_enabled(
"logging-format-interpolation", node.fromlineno
):
valid_types.append(".format()")
if not self.linter.is_message_enabled("logging-not-lazy", node.fromlineno):
valid_types.append("%")
return " or ".join(valid_types)
@staticmethod
def _is_operand_literal_str(operand: InferenceResult | None) -> bool:
"""Return True if the operand in argument is a literal string."""
return isinstance(operand, nodes.Const) and operand.name == "str"
@staticmethod
def _is_node_explicit_str_concatenation(node: nodes.NodeNG) -> bool:
"""Return True if the node represents an explicitly concatenated string."""
if not isinstance(node, nodes.BinOp):
return False
return (
LoggingChecker._is_operand_literal_str(node.left)
or LoggingChecker._is_node_explicit_str_concatenation(node.left)
) and (
LoggingChecker._is_operand_literal_str(node.right)
or LoggingChecker._is_node_explicit_str_concatenation(node.right)
)
def _check_call_func(self, node: nodes.Call) -> None:
"""Checks that function call is not format_string.format()."""
func = utils.safe_infer(node.func)
types = ("str", "unicode")
methods = ("format",)
if (
isinstance(func, astroid.BoundMethod)
and is_method_call(func, types, methods)
and not is_complex_format_str(func.bound)
):
self.add_message(
"logging-format-interpolation",
node=node,
args=(self._helper_string(node),),
)
def _check_format_string(self, node: nodes.Call, format_arg: Literal[0, 1]) -> None:
"""Checks that format string tokens match the supplied arguments.
Args:
node: AST node to be checked.
format_arg: Index of the format string in the node arguments.
"""
num_args = _count_supplied_tokens(node.args[format_arg + 1 :])
format_string = node.args[format_arg].value
required_num_args = 0
if isinstance(format_string, bytes):
format_string = format_string.decode()
if isinstance(format_string, str):
try:
if self._format_style == "old":
keyword_args, required_num_args, _, _ = utils.parse_format_string(
format_string
)
if keyword_args:
# Keyword checking on logging strings is complicated by
# special keywords - out of scope.
return
elif self._format_style == "new":
(
keyword_arguments,
implicit_pos_args,
explicit_pos_args,
) = utils.parse_format_method_string(format_string)
keyword_args_cnt = len(
{k for k, _ in keyword_arguments if not isinstance(k, int)}
)
required_num_args = (
keyword_args_cnt + implicit_pos_args + explicit_pos_args
)
except utils.UnsupportedFormatCharacter as ex:
char = format_string[ex.index]
self.add_message(
"logging-unsupported-format",
node=node,
args=(char, ord(char), ex.index),
)
return
except utils.IncompleteFormatString:
self.add_message("logging-format-truncated", node=node)
return
if num_args > required_num_args:
self.add_message("logging-too-many-args", node=node, confidence=HIGH)
elif num_args < required_num_args:
self.add_message("logging-too-few-args", node=node)
def is_complex_format_str(node: nodes.NodeNG) -> bool:
"""Return whether the node represents a string with complex formatting specs."""
inferred = utils.safe_infer(node)
if not (isinstance(inferred, nodes.Const) and isinstance(inferred.value, str)):
return True
try:
parsed = list(string.Formatter().parse(inferred.value))
except ValueError:
# This format string is invalid
return False
return any(format_spec for (_, _, format_spec, _) in parsed)
def _count_supplied_tokens(args: list[nodes.NodeNG]) -> int:
"""Counts the number of tokens in an args list.
The Python log functions allow for special keyword arguments: func,
exc_info and extra. To handle these cases correctly, we only count
arguments that aren't keywords.
Args:
args: AST nodes that are arguments for a log format string.
Returns:
Number of AST nodes that aren't keywords.
"""
return sum(1 for arg in args if not isinstance(arg, nodes.Keyword))
def str_formatting_in_f_string(node: nodes.JoinedStr) -> bool:
"""Determine whether the node represents an f-string with string formatting.
For example: `f'Hello %s'`
"""
# Check "%" presence first for performance.
return any(
"%" in val.value and any(x in val.value for x in MOST_COMMON_FORMATTING)
for val in node.values
if isinstance(val, nodes.Const)
)
def register(linter: PyLinter) -> None:
linter.register_checker(LoggingChecker(linter))
| LoggingChecker |
python | sphinx-doc__sphinx | sphinx/locale/__init__.py | {
"start": 382,
"end": 7326
} | class ____:
"""The proxy implementation attempts to be as complete as possible, so that
the lazy objects should mostly work as expected, for example for sorting.
"""
__slots__ = '_catalogue', '_namespace', '_message'
def __init__(self, catalogue: str, namespace: str, message: str) -> None:
self._catalogue = catalogue
self._namespace = namespace
self._message = message
def __str__(self) -> str:
try:
return translators[self._namespace, self._catalogue].gettext(self._message)
except KeyError:
# NullTranslations().gettext(self._message) == self._message
return self._message
def __dir__(self) -> list[str]:
return dir(str)
def __getattr__(self, name: str) -> Any:
return getattr(self.__str__(), name)
def __getstate__(self) -> tuple[str, str, str]:
return self._catalogue, self._namespace, self._message
def __setstate__(self, tup: tuple[str, str, str]) -> None:
self._catalogue, self._namespace, self._message = tup
def __copy__(self) -> _TranslationProxy:
return _TranslationProxy(self._catalogue, self._namespace, self._message)
def __repr__(self) -> str:
try:
return f'i{self.__str__()!r}'
except Exception:
return (
self.__class__.__name__
+ f'({self._catalogue}, {self._namespace}, {self._message})'
)
def __add__(self, other: str) -> str:
return self.__str__() + other
def __radd__(self, other: str) -> str:
return other + self.__str__()
def __mod__(self, other: str) -> str:
return self.__str__() % other
def __rmod__(self, other: str) -> str:
return other % self.__str__()
def __mul__(self, other: Any) -> str:
return self.__str__() * other
def __rmul__(self, other: Any) -> str:
return other * self.__str__()
def __hash__(self) -> int:
return hash(self.__str__())
def __eq__(self, other: object) -> bool:
return self.__str__() == other
def __lt__(self, string: str) -> bool:
return self.__str__() < string
def __contains__(self, char: str) -> bool:
return char in self.__str__()
def __len__(self) -> int:
return len(self.__str__())
def __getitem__(self, index: int | slice) -> str:
return self.__str__()[index]
translators: dict[tuple[str, str], NullTranslations] = {}
def init(
locale_dirs: Iterable[str | os.PathLike[str] | None],
language: str | None,
catalog: str = 'sphinx',
namespace: str = 'general',
) -> tuple[NullTranslations, bool]:
"""Look for message catalogs in `locale_dirs` and *ensure* that there is at
least a NullTranslations catalog set in `translators`. If called multiple
times or if several ``.mo`` files are found, their contents are merged
together (thus making ``init`` reentrant).
"""
translator = translators.get((namespace, catalog))
# ignore previously failed attempts to find message catalogs
if translator.__class__ is NullTranslations:
translator = None
if language:
languages: list[str] | None = [language]
else:
languages = None
# loading
# the None entry is the system's default locale path
for dir_ in locale_dirs:
try:
trans = translation(catalog, localedir=dir_, languages=languages)
if translator is None:
translator = trans
else:
translator.add_fallback(trans)
except Exception:
# Language couldn't be found in the specified path
pass
if translator is not None:
has_translation = True
else:
translator = NullTranslations()
has_translation = False
# guarantee translators[(namespace, catalog)] exists
translators[namespace, catalog] = translator
return translator, has_translation
def init_console(
locale_dir: str | os.PathLike[str] | None = None,
catalog: str = 'sphinx',
) -> tuple[NullTranslations, bool]:
"""Initialize locale for console.
.. versionadded:: 1.8
"""
if locale_dir is None:
locale_dir = _LOCALE_DIR
if sys.platform == 'win32':
language = None
else:
try:
# encoding is ignored
language, _ = locale.getlocale(locale.LC_MESSAGES)
except AttributeError:
# Fallback to the default language in case LC_MESSAGES is not defined.
language = None
return init([locale_dir], language, catalog, 'console')
def get_translator(
catalog: str = 'sphinx', namespace: str = 'general'
) -> NullTranslations:
return translators.get((namespace, catalog), NullTranslations())
def is_translator_registered(
catalog: str = 'sphinx', namespace: str = 'general'
) -> bool:
return (namespace, catalog) in translators
def get_translation(catalog: str, namespace: str = 'general') -> Callable[[str], str]:
"""Get a translation function based on the *catalog* and *namespace*.
The extension can use this API to translate the messages on the
extension::
from pathlib import Path
from sphinx.locale import get_translation
MESSAGE_CATALOG_NAME = 'myextension' # name of *.pot, *.po and *.mo files
_ = get_translation(MESSAGE_CATALOG_NAME)
text = _('Hello Sphinx!')
def setup(app):
package_dir = Path(__file__).resolve().parent
locale_dir = package_dir / 'locales'
app.add_message_catalog(MESSAGE_CATALOG_NAME, locale_dir)
With this code, sphinx searches a message catalog from
``${package_dir}/locales/${language}/LC_MESSAGES/myextension.mo``.
The :confval:`language` is used for the searching.
.. versionadded:: 1.8
"""
def gettext(message: str) -> str:
if not is_translator_registered(catalog, namespace):
# not initialized yet
return _TranslationProxy(catalog, namespace, message) # type: ignore[return-value]
else:
translator = get_translator(catalog, namespace)
return translator.gettext(message)
return gettext
# A shortcut for sphinx-core
#: Translation function for messages on documentation (menu, labels, themes and so on).
#: This function follows :confval:`language` setting.
_ = get_translation('sphinx')
#: Translation function for console messages
#: This function follows locale setting (`LC_ALL`, `LC_MESSAGES` and so on).
__ = get_translation('sphinx', 'console')
# labels
admonitionlabels = {
'attention': _('Attention'),
'caution': _('Caution'),
'danger': _('Danger'),
'error': _('Error'),
'hint': _('Hint'),
'important': _('Important'),
'note': _('Note'),
'seealso': _('See also'),
'tip': _('Tip'),
'warning': _('Warning'),
}
| _TranslationProxy |
python | aio-libs__aiohttp | aiohttp/_websocket/models.py | {
"start": 2124,
"end": 2288
} | class ____(NamedTuple):
data: None = None
size: int = 0
extra: str | None = None
type: Literal[WSMsgType.CLOSING] = WSMsgType.CLOSING
| WSMessageClosing |
python | huggingface__transformers | src/transformers/models/qwen3/modeling_qwen3.py | {
"start": 3738,
"end": 10083
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: Qwen3Config, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.config = config
self.rope_type = self.config.rope_parameters["rope_type"]
rope_init_fn: Callable = self.compute_default_rope_parameters
if self.rope_type != "default":
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
self.register_buffer("inv_freq", inv_freq, persistent=False)
self.original_inv_freq = inv_freq
@staticmethod
def compute_default_rope_parameters(
config: Optional[Qwen3Config] = None,
device: Optional["torch.device"] = None,
seq_len: Optional[int] = None,
) -> tuple["torch.Tensor", float]:
"""
Computes the inverse frequencies according to the original RoPE implementation
Args:
config ([`~transformers.PreTrainedConfig`]):
The model configuration.
device (`torch.device`):
The device to use for initialization of the inverse frequencies.
seq_len (`int`, *optional*):
The current sequence length. Unused for this type of RoPE.
Returns:
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
"""
base = config.rope_parameters["rope_theta"]
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
attention_factor = 1.0 # Unused in this type of RoPE
# Compute the inverse frequencies
inv_freq = 1.0 / (
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
)
return inv_freq, attention_factor
@torch.no_grad()
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
def forward(self, x, position_ids):
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
position_ids_expanded = position_ids[:, None, :].float()
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
with torch.autocast(device_type=device_type, enabled=False): # Force float32
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
emb = torch.cat((freqs, freqs), dim=-1)
cos = emb.cos() * self.attention_scaling
sin = emb.sin() * self.attention_scaling
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
def rotate_half(x):
"""Rotates half the hidden dims of the input."""
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
@use_kernel_func_from_hub("rotary_pos_emb")
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
"""Applies Rotary Position Embedding to the query and key tensors.
Args:
q (`torch.Tensor`): The query tensor.
k (`torch.Tensor`): The key tensor.
cos (`torch.Tensor`): The cosine part of the rotary embedding.
sin (`torch.Tensor`): The sine part of the rotary embedding.
position_ids (`torch.Tensor`, *optional*):
Deprecated and unused.
unsqueeze_dim (`int`, *optional*, defaults to 1):
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
"""
cos = cos.unsqueeze(unsqueeze_dim)
sin = sin.unsqueeze(unsqueeze_dim)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
"""
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
"""
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
if n_rep == 1:
return hidden_states
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
def eager_attention_forward(
module: nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: Optional[torch.Tensor],
scaling: float,
dropout: float = 0.0,
**kwargs: Unpack[TransformersKwargs],
):
key_states = repeat_kv(key, module.num_key_value_groups)
value_states = repeat_kv(value, module.num_key_value_groups)
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
if attention_mask is not None:
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
attn_weights = attn_weights + causal_mask
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
attn_output = torch.matmul(attn_weights, value_states)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
| Qwen3RotaryEmbedding |
python | kamyu104__LeetCode-Solutions | Python/design-linked-list.py | {
"start": 29,
"end": 144
} | class ____(object):
def __init__(self, value):
self.val = value
self.next = self.prev = None
| Node |
python | openai__openai-python | src/openai/types/beta/threads/message.py | {
"start": 1159,
"end": 3414
} | class ____(BaseModel):
id: str
"""The identifier, which can be referenced in API endpoints."""
assistant_id: Optional[str] = None
"""
If applicable, the ID of the
[assistant](https://platform.openai.com/docs/api-reference/assistants) that
authored this message.
"""
attachments: Optional[List[Attachment]] = None
"""A list of files attached to the message, and the tools they were added to."""
completed_at: Optional[int] = None
"""The Unix timestamp (in seconds) for when the message was completed."""
content: List[MessageContent]
"""The content of the message in array of text and/or images."""
created_at: int
"""The Unix timestamp (in seconds) for when the message was created."""
incomplete_at: Optional[int] = None
"""The Unix timestamp (in seconds) for when the message was marked as incomplete."""
incomplete_details: Optional[IncompleteDetails] = None
"""On an incomplete message, details about why the message is incomplete."""
metadata: Optional[Metadata] = None
"""Set of 16 key-value pairs that can be attached to an object.
This can be useful for storing additional information about the object in a
structured format, and querying for objects via API or the dashboard.
Keys are strings with a maximum length of 64 characters. Values are strings with
a maximum length of 512 characters.
"""
object: Literal["thread.message"]
"""The object type, which is always `thread.message`."""
role: Literal["user", "assistant"]
"""The entity that produced the message. One of `user` or `assistant`."""
run_id: Optional[str] = None
"""
The ID of the [run](https://platform.openai.com/docs/api-reference/runs)
associated with the creation of this message. Value is `null` when messages are
created manually using the create message or create thread endpoints.
"""
status: Literal["in_progress", "incomplete", "completed"]
"""
The status of the message, which can be either `in_progress`, `incomplete`, or
`completed`.
"""
thread_id: str
"""
The [thread](https://platform.openai.com/docs/api-reference/threads) ID that
this message belongs to.
"""
| Message |
python | encode__starlette | starlette/responses.py | {
"start": 6565,
"end": 7160
} | class ____(Response):
def __init__(
self,
url: str | URL,
status_code: int = 307,
headers: Mapping[str, str] | None = None,
background: BackgroundTask | None = None,
) -> None:
super().__init__(content=b"", status_code=status_code, headers=headers, background=background)
self.headers["location"] = quote(str(url), safe=":/%#?=@[]!$&'()*+,;")
Content = str | bytes | memoryview
SyncContentStream = Iterable[Content]
AsyncContentStream = AsyncIterable[Content]
ContentStream = AsyncContentStream | SyncContentStream
| RedirectResponse |
python | scrapy__scrapy | tests/CrawlerProcess/twisted_reactor_custom_settings.py | {
"start": 58,
"end": 326
} | class ____(scrapy.Spider):
name = "asyncio_reactor"
custom_settings = {
"TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor",
}
process = CrawlerProcess()
process.crawl(AsyncioReactorSpider)
process.start()
| AsyncioReactorSpider |
python | pydantic__pydantic | tests/benchmarks/test_isinstance.py | {
"start": 33,
"end": 266
} | class ____(BaseModel):
my_str: str
mv2 = ModelV2(my_str='hello')
def test_isinstance_basemodel(benchmark) -> None:
@benchmark
def run():
for _ in range(10000):
assert isinstance(mv2, BaseModel)
| ModelV2 |
python | Pylons__pyramid | tests/test_view.py | {
"start": 39721,
"end": 39837
} | class ____(Exception):
status = '404 Not Found'
app_iter = ['Not Found']
headerlist = []
| ExceptionResponse |
python | vyperlang__vyper | vyper/semantics/types/primitives.py | {
"start": 13250,
"end": 13440
} | class ____(AddressT):
_id = "self"
def compare_type(self, other):
# compares true to AddressT
return isinstance(other, type(self)) or isinstance(self, type(other))
| SelfT |
python | scipy__scipy | scipy/optimize/tests/test_lsq_common.py | {
"start": 442,
"end": 3954
} | class ____:
def test_step_size_to_bounds(self):
lb = np.array([-1.0, 2.5, 10.0])
ub = np.array([1.0, 5.0, 100.0])
x = np.array([0.0, 2.5, 12.0])
s = np.array([0.1, 0.0, 0.0])
step, hits = step_size_to_bound(x, s, lb, ub)
assert_equal(step, 10)
assert_equal(hits, [1, 0, 0])
s = np.array([0.01, 0.05, -1.0])
step, hits = step_size_to_bound(x, s, lb, ub)
assert_equal(step, 2)
assert_equal(hits, [0, 0, -1])
s = np.array([10.0, -0.0001, 100.0])
step, hits = step_size_to_bound(x, s, lb, ub)
assert_equal(step, np.array(-0))
assert_equal(hits, [0, -1, 0])
s = np.array([1.0, 0.5, -2.0])
step, hits = step_size_to_bound(x, s, lb, ub)
assert_equal(step, 1.0)
assert_equal(hits, [1, 0, -1])
s = np.zeros(3)
step, hits = step_size_to_bound(x, s, lb, ub)
assert_equal(step, np.inf)
assert_equal(hits, [0, 0, 0])
def test_find_active_constraints(self):
lb = np.array([0.0, -10.0, 1.0])
ub = np.array([1.0, 0.0, 100.0])
x = np.array([0.5, -5.0, 2.0])
active = find_active_constraints(x, lb, ub)
assert_equal(active, [0, 0, 0])
x = np.array([0.0, 0.0, 10.0])
active = find_active_constraints(x, lb, ub)
assert_equal(active, [-1, 1, 0])
active = find_active_constraints(x, lb, ub, rtol=0)
assert_equal(active, [-1, 1, 0])
x = np.array([1e-9, -1e-8, 100 - 1e-9])
active = find_active_constraints(x, lb, ub)
assert_equal(active, [0, 0, 1])
active = find_active_constraints(x, lb, ub, rtol=1.5e-9)
assert_equal(active, [-1, 0, 1])
lb = np.array([1.0, -np.inf, -np.inf])
ub = np.array([np.inf, 10.0, np.inf])
x = np.ones(3)
active = find_active_constraints(x, lb, ub)
assert_equal(active, [-1, 0, 0])
# Handles out-of-bound cases.
x = np.array([0.0, 11.0, 0.0])
active = find_active_constraints(x, lb, ub)
assert_equal(active, [-1, 1, 0])
active = find_active_constraints(x, lb, ub, rtol=0)
assert_equal(active, [-1, 1, 0])
def test_make_strictly_feasible(self):
lb = np.array([-0.5, -0.8, 2.0])
ub = np.array([0.8, 1.0, 3.0])
x = np.array([-0.5, 0.0, 2 + 1e-10])
x_new = make_strictly_feasible(x, lb, ub, rstep=0)
assert_(x_new[0] > -0.5)
assert_equal(x_new[1:], x[1:])
x_new = make_strictly_feasible(x, lb, ub, rstep=1e-4)
assert_equal(x_new, [-0.5 + 1e-4, 0.0, 2 * (1 + 1e-4)])
x = np.array([-0.5, -1, 3.1])
x_new = make_strictly_feasible(x, lb, ub)
assert_(np.all((x_new >= lb) & (x_new <= ub)))
x_new = make_strictly_feasible(x, lb, ub, rstep=0)
assert_(np.all((x_new >= lb) & (x_new <= ub)))
lb = np.array([-1, 100.0])
ub = np.array([1, 100.0 + 1e-10])
x = np.array([0, 100.0])
x_new = make_strictly_feasible(x, lb, ub, rstep=1e-8)
assert_equal(x_new, [0, 100.0 + 0.5e-10])
def test_scaling_vector(self):
lb = np.array([-np.inf, -5.0, 1.0, -np.inf])
ub = np.array([1.0, np.inf, 10.0, np.inf])
x = np.array([0.5, 2.0, 5.0, 0.0])
g = np.array([1.0, 0.1, -10.0, 0.0])
v, dv = CL_scaling_vector(x, g, lb, ub)
assert_equal(v, [1.0, 7.0, 5.0, 1.0])
assert_equal(dv, [0.0, 1.0, -1.0, 0.0])
| TestBounds |
python | ansible__ansible | test/units/parsing/vault/test_vault.py | {
"start": 6692,
"end": 10731
} | class ____(unittest.TestCase):
def setUp(self):
self.vault_password = "test-vault-password"
text_secret = TextVaultSecret(self.vault_password)
self.vault_secrets = [('foo', text_secret)]
def test(self):
secret = vault.FileVaultSecret()
self.assertIsNone(secret._bytes)
self.assertIsNone(secret._text)
def test_repr_empty(self):
secret = vault.FileVaultSecret()
self.assertEqual(repr(secret), "FileVaultSecret()")
def test_repr(self):
tmp_file = tempfile.NamedTemporaryFile(delete=False)
fake_loader = DictDataLoader({tmp_file.name: 'sdfadf'})
secret = vault.FileVaultSecret(loader=fake_loader, filename=tmp_file.name)
filename = tmp_file.name
tmp_file.close()
self.assertEqual(repr(secret), "FileVaultSecret(filename='%s')" % filename)
def test_empty_bytes(self):
secret = vault.FileVaultSecret()
self.assertIsNone(secret.bytes)
def test_file(self):
password = 'some password'
tmp_file = tempfile.NamedTemporaryFile(delete=False)
tmp_file.write(to_bytes(password))
tmp_file.close()
fake_loader = DictDataLoader({tmp_file.name: 'sdfadf'})
secret = vault.FileVaultSecret(loader=fake_loader, filename=tmp_file.name)
secret.load()
os.unlink(tmp_file.name)
self.assertEqual(secret.bytes, to_bytes(password))
def test_file_empty(self):
tmp_file = tempfile.NamedTemporaryFile(delete=False)
tmp_file.write(to_bytes(''))
tmp_file.close()
fake_loader = DictDataLoader({tmp_file.name: ''})
secret = vault.FileVaultSecret(loader=fake_loader, filename=tmp_file.name)
self.assertRaisesRegex(vault.AnsibleVaultPasswordError,
'Invalid vault password was provided from file.*%s' % tmp_file.name,
secret.load)
os.unlink(tmp_file.name)
def test_file_encrypted(self):
vault_password = "test-vault-password"
text_secret = TextVaultSecret(vault_password)
vault_secrets = [('foo', text_secret)]
password = 'some password'
# 'some password' encrypted with 'test-ansible-password'
password_file_content = """$ANSIBLE_VAULT;1.1;AES256
61393863643638653437313566313632306462383837303132346434616433313438353634613762
3334363431623364386164616163326537366333353663650a663634306232363432626162353665
39623061353266373631636331643761306665343731376633623439313138396330346237653930
6432643864346136640a653364386634666461306231353765636662316335613235383565306437
3737
"""
tmp_file = tempfile.NamedTemporaryFile(delete=False)
tmp_file.write(to_bytes(password_file_content))
tmp_file.close()
fake_loader = DictDataLoader({tmp_file.name: 'sdfadf'})
fake_loader._vault.secrets = vault_secrets
secret = vault.FileVaultSecret(loader=fake_loader, filename=tmp_file.name)
secret.load()
os.unlink(tmp_file.name)
self.assertEqual(secret.bytes, to_bytes(password))
def test_file_not_a_directory(self):
filename = '/dev/null/foobar'
fake_loader = DictDataLoader({filename: 'sdfadf'})
secret = vault.FileVaultSecret(loader=fake_loader, filename=filename)
self.assertRaisesRegex(errors.AnsibleError,
'.*Could not read vault password file.*/dev/null/foobar.*Not a directory',
secret.load)
def test_file_not_found(self):
tmp_file = tempfile.NamedTemporaryFile()
filename = os.path.realpath(tmp_file.name)
tmp_file.close()
fake_loader = DictDataLoader({filename: 'sdfadf'})
secret = vault.FileVaultSecret(loader=fake_loader, filename=filename)
self.assertRaisesRegex(errors.AnsibleError,
'.*Could not read vault password file.*%s.*' % filename,
secret.load)
| TestFileVaultSecret |
python | huggingface__transformers | src/transformers/models/ibert/modeling_ibert.py | {
"start": 22436,
"end": 23029
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.quant_mode = config.quant_mode
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.activation = nn.Tanh()
def forward(self, hidden_states):
# We "pool" the model by simply taking the hidden state corresponding
# to the first token.
first_token_tensor = hidden_states[:, 0]
pooled_output = self.dense(first_token_tensor)
pooled_output = self.activation(pooled_output)
return pooled_output
@auto_docstring
| IBertPooler |
python | ansible__ansible | test/units/parsing/yaml/test_loader.py | {
"start": 6422,
"end": 8344
} | class ____(unittest.TestCase, YamlTestUtils):
def setUp(self):
self.vault_password = "hunter42"
vault_secret = TextVaultSecret(self.vault_password)
self.vault_secrets = [('vault_secret', vault_secret),
('default', vault_secret)]
self.vault = vault.VaultLib(self.vault_secrets)
@property
def vault_secret(self):
return vault.match_encrypt_secret(self.vault_secrets)[1]
def test_wrong_password(self):
plaintext = u"Ansible"
bob_password = "this is a different password"
bobs_secret = TextVaultSecret(bob_password)
bobs_secrets = [('default', bobs_secret)]
bobs_vault = vault.VaultLib(bobs_secrets)
ciphertext = bobs_vault.encrypt(plaintext, vault.match_encrypt_secret(bobs_secrets)[1])
try:
self.vault.decrypt(ciphertext)
except Exception as e:
self.assertIsInstance(e, errors.AnsibleError)
self.assertEqual(e.message, 'Decryption failed (no vault secrets were found that could decrypt).')
def _encrypt_plaintext(self, plaintext):
# Construct a yaml repr of a vault by hand
vaulted_var_bytes = self.vault.encrypt(plaintext, self.vault_secret)
# add yaml tag
vaulted_var = vaulted_var_bytes.decode()
lines = vaulted_var.splitlines()
lines2 = []
for line in lines:
lines2.append(' %s' % line)
vaulted_var = '\n'.join(lines2)
tagged_vaulted_var = u"""!vault |\n%s""" % vaulted_var
return tagged_vaulted_var
def _build_stream(self, yaml_text):
stream = StringIO(yaml_text)
stream.name = 'my.yml'
return stream
def _load_yaml(self, yaml_text, password):
stream = self._build_stream(yaml_text)
data = yaml.load(stream, Loader=AnsibleLoader)
return data
| TestAnsibleLoaderVault |
python | hyperopt__hyperopt | hyperopt/exceptions.py | {
"start": 786,
"end": 898
} | class ____(Exception):
"""All optimization steps have finished with status base.STATUS_FAIL"""
| AllTrialsFailed |
python | keras-team__keras | guides/custom_train_step_in_tensorflow.py | {
"start": 7500,
"end": 9470
} | class ____(keras.Model):
def train_step(self, data):
# Unpack the data. Its structure depends on your model and
# on what you pass to `fit()`.
if len(data) == 3:
x, y, sample_weight = data
else:
sample_weight = None
x, y = data
with tf.GradientTape() as tape:
y_pred = self(x, training=True) # Forward pass
# Compute the loss value.
# The loss function is configured in `compile()`.
loss = self.compute_loss(
y=y,
y_pred=y_pred,
sample_weight=sample_weight,
)
# Compute gradients
trainable_vars = self.trainable_variables
gradients = tape.gradient(loss, trainable_vars)
# Update weights
self.optimizer.apply(gradients, trainable_vars)
# Update the metrics.
# Metrics are configured in `compile()`.
for metric in self.metrics:
if metric.name == "loss":
metric.update_state(loss)
else:
metric.update_state(y, y_pred, sample_weight=sample_weight)
# Return a dict mapping metric names to current value.
# Note that it will include the loss (tracked in self.metrics).
return {m.name: m.result() for m in self.metrics}
# Construct and compile an instance of CustomModel
inputs = keras.Input(shape=(32,))
outputs = keras.layers.Dense(1)(inputs)
model = CustomModel(inputs, outputs)
model.compile(optimizer="adam", loss="mse", metrics=["mae"])
# You can now use sample_weight argument
x = np.random.random((1000, 32))
y = np.random.random((1000, 1))
sw = np.random.random((1000, 1))
model.fit(x, y, sample_weight=sw, epochs=3)
"""
## Providing your own evaluation step
What if you want to do the same for calls to `model.evaluate()`? Then you would
override `test_step` in exactly the same way. Here's what it looks like:
"""
| CustomModel |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.