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
|
joke2k__faker
|
faker/providers/bank/th_TH/__init__.py
|
{
"start": 42,
"end": 1059
}
|
class ____(BankProvider):
"""Implement bank provider for ``th_TH`` locale."""
bban_format = "#" * 10
country_code = "TH"
swift_bank_codes = (
"AIAC",
"ANZB",
"BKKB",
"BAAB",
"BOFA",
"AYUD",
"BKCH",
"BOTH",
"BNPA",
"UBOB",
"CITI",
"CRES",
"DEUT",
"EXTH",
"GSBA",
"BHOB",
"ICBK",
"TIBT",
"CHAS",
"KASI",
"KKPB",
"KRTH",
"LAHR",
"ICBC",
"MHCB",
"OCBC",
"DCBB",
"SICO",
"SMEB",
"SCBL",
"SMBC",
"THBK",
"HSBC",
"TMBK",
"UOVB",
)
swift_location_codes = (
"BK",
"B2",
"BB",
"BX",
"2X",
)
swift_branch_codes = (
"BKO",
"BNA",
"RYO",
"CHB",
"IBF",
"SEC",
"HDY",
"CHM",
"NAV",
"XXX",
)
|
Provider
|
python
|
falconry__falcon
|
tests/test_cookies.py
|
{
"start": 1546,
"end": 1992
}
|
class ____:
def on_get(self, req, resp):
resp.set_cookie('foo', 'bar', same_site='Lax')
resp.set_cookie('barz', 'barz', same_site='')
def on_post(self, req, resp):
resp.set_cookie('bar', 'foo', same_site='STRICT')
def on_put(self, req, resp):
resp.set_cookie('baz', 'foo', same_site='none')
def on_delete(self, req, resp):
resp.set_cookie('baz', 'foo', same_site='')
|
CookieResourceSameSite
|
python
|
readthedocs__readthedocs.org
|
readthedocs/builds/migrations/0039_migrate_config_data.py
|
{
"start": 1361,
"end": 1576
}
|
class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("builds", "0038_add_new_jsonfields"),
]
operations = [
migrations.RunPython(forwards_func),
]
|
Migration
|
python
|
scrapy__scrapy
|
docs/_ext/scrapydocs.py
|
{
"start": 434,
"end": 487
}
|
class ____(General, Element):
pass
|
SettingslistNode
|
python
|
huggingface__transformers
|
src/transformers/models/bert/configuration_bert.py
|
{
"start": 864,
"end": 5870
}
|
class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`BertModel`]. It is used to
instantiate a BERT model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a similar configuration to that of the BERT
[google-bert/bert-base-uncased](https://huggingface.co/google-bert/bert-base-uncased) architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 30522):
Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`BertModel`].
hidden_size (`int`, *optional*, defaults to 768):
Dimensionality of the encoder layers and the pooler layer.
num_hidden_layers (`int`, *optional*, defaults to 12):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 12):
Number of attention heads for each attention layer in the Transformer encoder.
intermediate_size (`int`, *optional*, defaults to 3072):
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"silu"` and `"gelu_new"` are supported.
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
The dropout ratio for the attention probabilities.
max_position_embeddings (`int`, *optional*, defaults to 512):
The maximum sequence length that this model might ever be used with. Typically set this to something large
just in case (e.g., 512 or 1024 or 2048).
type_vocab_size (`int`, *optional*, defaults to 2):
The vocabulary size of the `token_type_ids` passed when calling [`BertModel`].
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
The epsilon used by the layer normalization layers.
is_decoder (`bool`, *optional*, defaults to `False`):
Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
use_cache (`bool`, *optional*, defaults to `True`):
Whether or not the model should return the last key/values attentions (not used by all models). Only
relevant if `config.is_decoder=True`.
classifier_dropout (`float`, *optional*):
The dropout ratio for the classification head.
Examples:
```python
>>> from transformers import BertConfig, BertModel
>>> # Initializing a BERT google-bert/bert-base-uncased style configuration
>>> configuration = BertConfig()
>>> # Initializing a model (with random weights) from the google-bert/bert-base-uncased style configuration
>>> model = BertModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "bert"
def __init__(
self,
vocab_size=30522,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
hidden_act="gelu",
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
max_position_embeddings=512,
type_vocab_size=2,
initializer_range=0.02,
layer_norm_eps=1e-12,
pad_token_id=0,
use_cache=True,
classifier_dropout=None,
**kwargs,
):
super().__init__(pad_token_id=pad_token_id, **kwargs)
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.hidden_act = hidden_act
self.intermediate_size = intermediate_size
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.max_position_embeddings = max_position_embeddings
self.type_vocab_size = type_vocab_size
self.initializer_range = initializer_range
self.layer_norm_eps = layer_norm_eps
self.use_cache = use_cache
self.classifier_dropout = classifier_dropout
__all__ = ["BertConfig"]
|
BertConfig
|
python
|
dagster-io__dagster
|
python_modules/dagster-graphql/dagster_graphql/schema/solids.py
|
{
"start": 6775,
"end": 8856
}
|
class ____(graphene.ObjectType):
solid = graphene.NonNull(lambda: GrapheneSolid)
definition = graphene.NonNull(GrapheneOutputDefinition)
depended_by = non_null_list(GrapheneInput)
class Meta:
name = "Output"
def __init__(self, represented_pipeline, current_dep_structure, solid_name, output_name):
self._represented_pipeline = check.inst_param(
represented_pipeline, "represented_pipeline", RepresentedJob
)
self._current_dep_structure = check.inst_param(
current_dep_structure, "current_dep_structure", DependencyStructureIndex
)
self._solid_name = check.str_param(solid_name, "solid_name")
self._output_name = check.str_param(output_name, "output_name")
self._solid_invocation_snap = current_dep_structure.get_invocation(solid_name)
self._solid_def_snap = represented_pipeline.get_node_def_snap(
self._solid_invocation_snap.node_def_name
)
self._output_def_snap = self._solid_def_snap.get_output_snap(output_name)
super().__init__()
def resolve_solid(self, _) -> "GrapheneSolid":
return GrapheneSolid(
self._represented_pipeline, self._solid_name, self._current_dep_structure
)
def resolve_definition(self, _graphene_info: ResolveInfo) -> GrapheneOutputDefinition:
return GrapheneOutputDefinition(
self._represented_pipeline,
self._solid_def_snap.name,
self._output_name,
self._output_def_snap.is_dynamic,
)
def resolve_depended_by(self, _graphene_info: ResolveInfo) -> Sequence[GrapheneInput]:
return [
GrapheneInput(
self._represented_pipeline,
self._current_dep_structure,
input_handle_snap.node_name,
input_handle_snap.input_name,
)
for input_handle_snap in self._current_dep_structure.get_downstream_inputs(
self._solid_name, self._output_def_snap.name
)
]
|
GrapheneOutput
|
python
|
numba__numba
|
numba/core/types/npytypes.py
|
{
"start": 16813,
"end": 17961
}
|
class ____(Type):
"""
This is the type for `np.ndarray.ctypes`.
"""
def __init__(self, arytype):
# This depends on the ndim for the shape and strides attributes,
# even though they are not implemented, yet.
self.dtype = arytype.dtype
self.ndim = arytype.ndim
name = "ArrayCTypes(dtype={0}, ndim={1})".format(self.dtype, self.ndim)
super(ArrayCTypes, self).__init__(name)
@property
def key(self):
return self.dtype, self.ndim
def can_convert_to(self, typingctx, other):
"""
Convert this type to the corresponding pointer type.
This allows passing a array.ctypes object to a C function taking
a raw pointer.
Note that in pure Python, the array.ctypes object can only be
passed to a ctypes function accepting a c_void_p, not a typed
pointer.
"""
from . import CPointer, voidptr
# XXX what about readonly
if isinstance(other, CPointer) and other.dtype == self.dtype:
return Conversion.safe
elif other == voidptr:
return Conversion.safe
|
ArrayCTypes
|
python
|
PyCQA__pylint
|
tests/functional/i/invalid/invalid_name/invalid_name_module_level.py
|
{
"start": 1286,
"end": 1423
}
|
class ____:
INPUT = ">>> "
INPUT = Theme()
input = Theme() # pylint: disable=redefined-builtin
OUTPUT = Theme()
output = Theme()
|
Theme
|
python
|
getsentry__sentry
|
tests/sentry/plugins/interfaces/test_releasehook.py
|
{
"start": 256,
"end": 742
}
|
class ____(TestCase):
def test_minimal(self) -> None:
project = self.create_project()
version = "bbee5b51f84611e4b14834363b8514c2"
hook = ReleaseHook(project)
hook.finish_release(version)
release = Release.objects.get(organization_id=project.organization_id, version=version)
assert release.date_released
assert release.organization
assert ReleaseProject.objects.get(release=release, project=project)
|
FinishReleaseTest
|
python
|
numba__numba
|
numba/misc/llvm_pass_timings.py
|
{
"start": 3224,
"end": 8983
}
|
class ____:
"""A class for processing raw timing report from LLVM.
The processing is done lazily so we don't waste time processing unused
timing information.
"""
def __init__(self, raw_data):
self._raw_data = raw_data
def __bool__(self):
return bool(self._raw_data)
def get_raw_data(self):
"""Returns the raw string data.
Returns
-------
res: str
"""
return self._raw_data
def get_total_time(self):
"""Compute the total time spend in all passes.
Returns
-------
res: float
"""
return self.list_records()[-1].wall_time
def list_records(self):
"""Get the processed data for the timing report.
Returns
-------
res: List[PassTimingRecord]
"""
return self._processed
def list_top(self, n):
"""Returns the top(n) most time-consuming (by wall-time) passes.
Parameters
----------
n: int
This limits the maximum number of items to show.
This function will show the ``n`` most time-consuming passes.
Returns
-------
res: List[PassTimingRecord]
Returns the top(n) most time-consuming passes in descending order.
"""
records = self.list_records()
key = operator.attrgetter("wall_time")
return heapq.nlargest(n, records[:-1], key)
def summary(self, topn=5, indent=0):
"""Return a string summarizing the timing information.
Parameters
----------
topn: int; optional
This limits the maximum number of items to show.
This function will show the ``topn`` most time-consuming passes.
indent: int; optional
Set the indentation level. Defaults to 0 for no indentation.
Returns
-------
res: str
"""
buf = []
prefix = " " * indent
def ap(arg):
buf.append(f"{prefix}{arg}")
ap(f"Total {self.get_total_time():.4f}s")
ap("Top timings:")
for p in self.list_top(topn):
ap(f" {p.wall_time:.4f}s ({p.wall_percent:5}%) {p.pass_name}")
return "\n".join(buf)
@cached_property
def _processed(self):
"""A cached property for lazily processing the data and returning it.
See ``_process()`` for details.
"""
return self._process()
def _process(self):
"""Parses the raw string data from LLVM timing report and attempts
to improve the data by recomputing the times
(See `_adjust_timings()``).
"""
def parse(raw_data):
"""A generator that parses the raw_data line-by-line to extract
timing information for each pass.
"""
lines = raw_data.splitlines()
colheader = r"[a-zA-Z+ ]+"
# Take at least one column header.
multicolheaders = fr"(?:\s*-+{colheader}-+)+"
line_iter = iter(lines)
# find column headers
header_map = {
"User Time": "user",
"System Time": "system",
"User+System": "user_system",
"Wall Time": "wall",
"Instr": "instruction",
"Name": "pass_name",
}
for ln in line_iter:
m = re.match(multicolheaders, ln)
if m:
# Get all the column headers
raw_headers = re.findall(r"[a-zA-Z][a-zA-Z+ ]+", ln)
headers = [header_map[k.strip()] for k in raw_headers]
break
assert headers[-1] == 'pass_name'
# compute the list of available attributes from the column headers
attrs = []
n = r"\s*((?:[0-9]+\.)?[0-9]+)"
pat = ""
for k in headers[:-1]:
if k == "instruction":
pat += n
else:
attrs.append(f"{k}_time")
attrs.append(f"{k}_percent")
pat += rf"\s+(?:{n}\s*\({n}%\)|-+)"
# put default value 0.0 to all missing attributes
missing = {}
for k in PassTimingRecord._fields:
if k not in attrs and k != 'pass_name':
missing[k] = 0.0
# parse timings
pat += r"\s*(.*)"
for ln in line_iter:
m = re.match(pat, ln)
if m is not None:
raw_data = list(m.groups())
data = {k: float(v) if v is not None else 0.0
for k, v in zip(attrs, raw_data)}
data.update(missing)
pass_name = raw_data[-1]
rec = PassTimingRecord(
pass_name=pass_name, **data,
)
yield rec
if rec.pass_name == "Total":
# "Total" means the report has ended
break
# Check that we have reach the end of the report
remaining = '\n'.join(line_iter)
# FIXME: Need to handle parsing of Analysis execution timing report
if "Analysis execution timing report" in remaining:
return
if remaining:
raise ValueError(
f"unexpected text after parser finished:\n{remaining}"
)
# Parse raw data
records = list(parse(self._raw_data))
return _adjust_timings(records)
NamedTimings = namedtuple("NamedTimings", ["name", "timings"])
|
ProcessedPassTimings
|
python
|
pytorch__pytorch
|
tools/test/test_codegen_model.py
|
{
"start": 384,
"end": 5168
}
|
class ____(expecttest.TestCase):
def assertParseErrorInline(self, yaml_str: str, expect: str) -> None:
es = yaml.load(yaml_str, Loader=LineLoader)
try:
parse_native_yaml_struct(es, set())
except AssertionError as e:
# hack to strip out the context
msg, _ = str(e).split(" in ", 2)
self.assertExpectedInline("\n".join(textwrap.wrap(msg)), expect, skip=1)
return
self.fail(msg="Did not raise when expected to")
def assertUfuncErrorInline(self, yaml_str: str, expect: str) -> None:
# parse a single structured group out of the yaml to g
es = yaml.load(yaml_str, Loader=LineLoader)
parsed_yaml = parse_native_yaml_struct(es, set())
native_functions, backend_indices = (
parsed_yaml.native_functions,
parsed_yaml.backend_indices,
)
grouped_native_functions = gen.get_grouped_native_functions(native_functions)
assert len(grouped_native_functions) == 1
g = grouped_native_functions[0]
assert isinstance(g, NativeFunctionsGroup)
assert g.out.ufunc_inner_loop
# this is not ufunc codegen per se, but it does some basic sanity tests for
# ufunc generation
gen.compute_meta_function_declaration(g)
dest.compute_native_function_declaration(g, backend_indices[DispatchKey.CPU])
dest.compute_native_function_declaration(g, backend_indices[DispatchKey.CUDA])
try:
# the real kahuna
dest.compute_ufunc_cpu(g)
dest.compute_ufunc_cpu_kernel(g)
dest.compute_ufunc_cuda(g)
except AssertionError as e:
# hack to strip out the context
msg, _ = str(e).split(" in ", 2)
self.assertExpectedInline("\n".join(textwrap.wrap(msg)), expect, skip=1)
return
self.fail(msg="Did not raise when expected to")
# NB: indent is hardcoded to be two here, so format your yaml accordingly
binop_out = (
"func: binop.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)"
)
ti_binop_out = f"""{binop_out}
structured: True
structured_inherits: TensorIteratorBase"""
ti_binop = """func: binop(Tensor self, Tensor other) -> Tensor
structured_delegate: binop.out
"""
ti_unop_out = """func: unop.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
structured: True
structured_inherits: TensorIteratorBase"""
ti_unop = """func: unop(Tensor self) -> Tensor
structured_delegate: unop.out
"""
def test_nonstructured_ufunc(self) -> None:
yaml_str = f"""\
- {self.binop_out}
ufunc_inner_loop:
Generic: binop (Bool)
"""
self.assertParseErrorInline(
yaml_str,
"""\
ufunc must be structured""",
)
def test_overlapping_ufunc_and_dispatch(self) -> None:
yaml_str = f"""\
- {self.ti_binop_out}
ufunc_inner_loop:
Generic: binop (Bool)
dispatch:
CPU: binop_cpu
"""
self.assertParseErrorInline(
yaml_str,
"""\
ufunc should not have explicit dispatch entry for CPU""",
)
# See https://github.com/pytorch/pytorch/pull/65851#discussion_r810238456
@unittest.expectedFailure
def test_scalaronly_shadowed(self) -> None:
yaml_str = f"""\
- {self.ti_binop_out}
ufunc_inner_loop:
Generic: binop (Bool)
ScalarOnly: binop (Bool)
"""
self.assertParseErrorInline(
yaml_str,
"""\
""",
)
def test_conflicting_ufunc(self) -> None:
yaml_str = f"""\
- {self.ti_binop_out}
ufunc_inner_loop:
Generic: binop (Bool)
ScalarOnly: binop_scalar (Bool)
- {self.ti_binop}
"""
self.assertUfuncErrorInline(
yaml_str,
"""\
ScalarOnly and Generic must have same ufunc name""",
)
def test_invalid_cudafunctoronself_for_binary_op(self) -> None:
yaml_str = f"""\
- {self.ti_unop_out}
ufunc_inner_loop:
Generic: unop (All)
CUDAFunctorOnSelf: unop_self_cuda (All)
- {self.ti_unop}
"""
self.assertUfuncErrorInline(
yaml_str,
"""\
cannot use CUDAFunctorOnSelf on non-binary function""",
)
def test_parse_custom_class_type(self) -> None:
custom_class_name = "namespace_foo.class_bar"
custom_class_name_with_prefix = f"__torch__.torch.classes.{custom_class_name}"
custom_class_type = cast(
CustomClassType, Type.parse(custom_class_name_with_prefix)
)
self.assertTrue(isinstance(custom_class_type, CustomClassType))
self.assertEqual(custom_class_name, custom_class_type.class_name)
self.assertEqual(custom_class_name_with_prefix, str(custom_class_type))
|
TestCodegenModel
|
python
|
viewflow__viewflow
|
viewflow/workflow/migrations/0006_merge.py
|
{
"start": 108,
"end": 277
}
|
class ____(migrations.Migration):
dependencies = [
("viewflow", "0005_rename_flowcls"),
("viewflow", "0005_merge"),
]
operations = []
|
Migration
|
python
|
tensorflow__tensorflow
|
tensorflow/python/keras/layers/convolutional.py
|
{
"start": 15820,
"end": 21782
}
|
class ____(Conv):
"""1D convolution layer (e.g. temporal convolution).
This layer creates a convolution kernel that is convolved
with the layer input over a single spatial (or temporal) dimension
to produce a tensor of outputs.
If `use_bias` is True, a bias vector is created and added to the outputs.
Finally, if `activation` is not `None`,
it is applied to the outputs as well.
When using this layer as the first layer in a model,
provide an `input_shape` argument
(tuple of integers or `None`, e.g.
`(10, 128)` for sequences of 10 vectors of 128-dimensional vectors,
or `(None, 128)` for variable-length sequences of 128-dimensional vectors.
Examples:
>>> # The inputs are 128-length vectors with 10 timesteps, and the batch size
>>> # is 4.
>>> input_shape = (4, 10, 128)
>>> x = tf.random.normal(input_shape)
>>> y = tf.keras.layers.Conv1D(
... 32, 3, activation='relu',input_shape=input_shape[1:])(x)
>>> print(y.shape)
(4, 8, 32)
>>> # With extended batch shape [4, 7] (e.g. weather data where batch
>>> # dimensions correspond to spatial location and the third dimension
>>> # corresponds to time.)
>>> input_shape = (4, 7, 10, 128)
>>> x = tf.random.normal(input_shape)
>>> y = tf.keras.layers.Conv1D(
... 32, 3, activation='relu', input_shape=input_shape[2:])(x)
>>> print(y.shape)
(4, 7, 8, 32)
Args:
filters: Integer, the dimensionality of the output space
(i.e. the number of output filters in the convolution).
kernel_size: An integer or tuple/list of a single integer,
specifying the length of the 1D convolution window.
strides: An integer or tuple/list of a single integer,
specifying the stride length of the convolution.
Specifying any stride value != 1 is incompatible with specifying
any `dilation_rate` value != 1.
padding: One of `"valid"`, `"same"` or `"causal"` (case-insensitive).
`"valid"` means no padding. `"same"` results in padding with zeros evenly
to the left/right or up/down of the input such that output has the same
height/width dimension as the input.
`"causal"` results in causal (dilated) convolutions, e.g. `output[t]`
does not depend on `input[t+1:]`. Useful when modeling temporal data
where the model should not violate the temporal order.
See [WaveNet: A Generative Model for Raw Audio, section
2.1](https://arxiv.org/abs/1609.03499).
data_format: A string,
one of `channels_last` (default) or `channels_first`.
dilation_rate: an integer or tuple/list of a single integer, specifying
the dilation rate to use for dilated convolution.
Currently, specifying any `dilation_rate` value != 1 is
incompatible with specifying any `strides` value != 1.
groups: A positive integer specifying the number of groups in which the
input is split along the channel axis. Each group is convolved
separately with `filters / groups` filters. The output is the
concatenation of all the `groups` results along the channel axis.
Input channels and `filters` must both be divisible by `groups`.
activation: Activation function to use.
If you don't specify anything, no activation is applied (
see `keras.activations`).
use_bias: Boolean, whether the layer uses a bias vector.
kernel_initializer: Initializer for the `kernel` weights matrix (
see `keras.initializers`). Defaults to 'glorot_uniform'.
bias_initializer: Initializer for the bias vector (
see `keras.initializers`). Defaults to 'zeros'.
kernel_regularizer: Regularizer function applied to
the `kernel` weights matrix (see `keras.regularizers`).
bias_regularizer: Regularizer function applied to the bias vector (
see `keras.regularizers`).
activity_regularizer: Regularizer function applied to
the output of the layer (its "activation") (
see `keras.regularizers`).
kernel_constraint: Constraint function applied to the kernel matrix (
see `keras.constraints`).
bias_constraint: Constraint function applied to the bias vector (
see `keras.constraints`).
Input shape:
3+D tensor with shape: `batch_shape + (steps, input_dim)`
Output shape:
3+D tensor with shape: `batch_shape + (new_steps, filters)`
`steps` value might have changed due to padding or strides.
Returns:
A tensor of rank 3 representing
`activation(conv1d(inputs, kernel) + bias)`.
Raises:
ValueError: when both `strides > 1` and `dilation_rate > 1`.
"""
def __init__(self,
filters,
kernel_size,
strides=1,
padding='valid',
data_format='channels_last',
dilation_rate=1,
groups=1,
activation=None,
use_bias=True,
kernel_initializer='glorot_uniform',
bias_initializer='zeros',
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
**kwargs):
super(Conv1D, self).__init__(
rank=1,
filters=filters,
kernel_size=kernel_size,
strides=strides,
padding=padding,
data_format=data_format,
dilation_rate=dilation_rate,
groups=groups,
activation=activations.get(activation),
use_bias=use_bias,
kernel_initializer=initializers.get(kernel_initializer),
bias_initializer=initializers.get(bias_initializer),
kernel_regularizer=regularizers.get(kernel_regularizer),
bias_regularizer=regularizers.get(bias_regularizer),
activity_regularizer=regularizers.get(activity_regularizer),
kernel_constraint=constraints.get(kernel_constraint),
bias_constraint=constraints.get(bias_constraint),
**kwargs)
|
Conv1D
|
python
|
numba__numba
|
numba/core/types/function_type.py
|
{
"start": 3186,
"end": 4028
}
|
class ____(FunctionType):
_counter = 0
def __init__(self, nargs, dispatchers):
from numba.core.typing.templates import Signature
signature = Signature(types.undefined,
(types.undefined,) * nargs, recvr=None)
super(UndefinedFunctionType, self).__init__(signature)
self.dispatchers = dispatchers
# make the undefined function type instance unique
type(self)._counter += 1
self._key += str(type(self)._counter)
def get_precise(self):
"""
Return precise function type if possible.
"""
for dispatcher in self.dispatchers:
for cres in dispatcher.overloads.values():
sig = types.unliteral(cres.signature)
return FunctionType(sig)
return self
|
UndefinedFunctionType
|
python
|
getsentry__sentry
|
tests/sentry/db/models/manager/test_base_query_set.py
|
{
"start": 1315,
"end": 3850
}
|
class ____(TestCase):
def test_not_triggered(self) -> None:
with (
catch_signal(post_update) as handler,
override_options({"groups.enable-post-update-signal": True}),
):
self.group.message = "hi"
self.group.save()
assert not handler.called
with (
catch_signal(post_update) as handler,
override_options({"groups.enable-post-update-signal": True}),
):
self.group.update(message="hi")
assert not handler.called
with (
catch_signal(post_update) as handler,
override_options({"groups.enable-post-update-signal": False}),
):
assert Group.objects.filter(id=self.group.id).update(message="hi") == 1
assert not handler.called
with (
catch_signal(post_update) as handler,
override_options({"groups.enable-post-update-signal": True}),
):
assert (
Group.objects.filter(id=self.group.id)
.with_post_update_signal(False)
.update(message="hi")
== 1
)
assert not handler.called
# Test signal not fired when Django detects the query will return no results
with (
catch_signal(post_update) as handler,
override_options({"groups.enable-post-update-signal": True}),
):
assert (
Group.objects.filter(id__in=[]).with_post_update_signal(True).update(message="hi")
== 0
)
assert not handler.called
def test_enable(self) -> None:
qs = Group.objects.all()
assert not qs._with_post_update_signal
new_qs = qs.with_post_update_signal(True)
# Make sure we don't modify the previous queryset
assert not qs._with_post_update_signal
assert new_qs._with_post_update_signal
def test_triggered(self) -> None:
message = "hi"
with (
catch_signal(post_update) as handler,
override_options({"groups.enable-post-update-signal": True}),
):
assert Group.objects.filter(id=self.group.id).update(message=message) == 1
self.group.refresh_from_db()
assert self.group.message == message
handler.assert_called_once_with(
signal=post_update,
sender=Group,
updated_fields=["message"],
model_ids=[self.group.id],
)
|
TestSendPostUpdateSignal
|
python
|
weaviate__weaviate-python-client
|
weaviate/collections/classes/config_vectorizers.py
|
{
"start": 12011,
"end": 12567
}
|
class ____(_VectorizerConfigCreate):
vectorizer: Union[Vectorizers, _EnumLikeStr] = Field(
default=Vectorizers.TEXT2VEC_COHERE, frozen=True, exclude=True
)
baseURL: Optional[AnyHttpUrl]
model: Optional[str]
dimensions: Optional[int]
truncate: Optional[CohereTruncation]
vectorizeClassName: bool
def _to_dict(self) -> Dict[str, Any]:
ret_dict = super()._to_dict()
if self.baseURL is not None:
ret_dict["baseURL"] = self.baseURL.unicode_string()
return ret_dict
|
_Text2VecCohereConfig
|
python
|
apache__airflow
|
providers/microsoft/azure/tests/unit/microsoft/azure/fs/test_msgraph.py
|
{
"start": 1521,
"end": 5923
}
|
class ____:
@patch("airflow.providers.microsoft.azure.fs.msgraph.BaseHook.get_connection")
@patch("msgraphfs.MSGDriveFS")
def test_get_fs_with_drive_id(self, mock_msgdrivefs, mock_get_connection, mock_connection):
mock_get_connection.return_value = mock_connection
mock_fs_instance = MagicMock()
mock_msgdrivefs.return_value = mock_fs_instance
result = get_fs("msgraph_default")
mock_msgdrivefs.assert_called_once_with(
drive_id="test_drive_id",
oauth2_client_params={
"client_id": "test_client_id",
"client_secret": "test_client_secret",
"tenant_id": "test_tenant_id",
},
)
assert result == mock_fs_instance
@patch("msgraphfs.MSGDriveFS")
def test_get_fs_no_connection(self, mock_msgdrivefs):
mock_fs_instance = MagicMock()
mock_msgdrivefs.return_value = mock_fs_instance
result = get_fs(None)
mock_msgdrivefs.assert_called_once_with({})
assert result == mock_fs_instance
@patch("airflow.providers.microsoft.azure.fs.msgraph.BaseHook.get_connection")
@patch("msgraphfs.MSGDriveFS")
def test_get_fs_with_extra_oauth_params(self, mock_msgdrivefs, mock_get_connection):
connection = Connection(
conn_id="msgraph_extra",
conn_type="msgraph",
login="test_client_id",
password="test_client_secret",
host="test_tenant_id",
extra={
"drive_id": "test_drive_id",
"scope": "https://graph.microsoft.com/.default",
"token_endpoint": "https://login.microsoftonline.com/test/oauth2/v2.0/token",
"redirect_uri": "http://localhost:8080/callback",
},
)
mock_get_connection.return_value = connection
mock_fs_instance = MagicMock()
mock_msgdrivefs.return_value = mock_fs_instance
result = get_fs("msgraph_extra")
expected_oauth2_params = {
"client_id": "test_client_id",
"client_secret": "test_client_secret",
"tenant_id": "test_tenant_id",
"scope": "https://graph.microsoft.com/.default",
"token_endpoint": "https://login.microsoftonline.com/test/oauth2/v2.0/token",
"redirect_uri": "http://localhost:8080/callback",
}
mock_msgdrivefs.assert_called_once_with(
drive_id="test_drive_id", oauth2_client_params=expected_oauth2_params
)
assert result == mock_fs_instance
@patch("airflow.providers.microsoft.azure.fs.msgraph.BaseHook.get_connection")
@patch("msgraphfs.MSGDriveFS")
def test_get_fs_with_storage_options(self, mock_msgdrivefs, mock_get_connection, mock_connection_minimal):
mock_get_connection.return_value = mock_connection_minimal
mock_fs_instance = MagicMock()
mock_msgdrivefs.return_value = mock_fs_instance
storage_options = {"drive_id": "storage_drive_id", "scope": "custom.scope"}
result = get_fs("msgraph_minimal", storage_options=storage_options)
expected_oauth2_params = {
"client_id": "test_client_id",
"client_secret": "test_client_secret",
"tenant_id": "test_tenant_id",
"scope": "custom.scope",
}
mock_msgdrivefs.assert_called_once_with(
drive_id="storage_drive_id", oauth2_client_params=expected_oauth2_params
)
assert result == mock_fs_instance
@patch("airflow.providers.microsoft.azure.fs.msgraph.BaseHook.get_connection")
@patch("msgraphfs.MSGDriveFS")
def test_get_fs_incomplete_credentials(self, mock_msgdrivefs, mock_get_connection):
# Connection with missing client_secret
connection = Connection(
conn_id="msgraph_incomplete",
conn_type="msgraph",
login="test_client_id",
host="test_tenant_id",
)
mock_get_connection.return_value = connection
mock_fs_instance = MagicMock()
mock_msgdrivefs.return_value = mock_fs_instance
result = get_fs("msgraph_incomplete")
# Should return default filesystem when credentials are incomplete
mock_msgdrivefs.assert_called_once_with(drive_id=None, oauth2_client_params={})
assert result == mock_fs_instance
|
TestMSGraphFS
|
python
|
cython__cython
|
docs/examples/tutorial/memory_allocation/some_memory.py
|
{
"start": 96,
"end": 1095
}
|
class ____:
data: cython.p_double
def __cinit__(self, number: cython.size_t):
# allocate some memory (uninitialised, may contain arbitrary data)
self.data = cython.cast(cython.p_double, PyMem_Malloc(
number * cython.sizeof(cython.double)))
if not self.data:
raise MemoryError()
def resize(self, new_number: cython.size_t):
# Allocates new_number * sizeof(double) bytes,
# preserving the current content and making a best-effort to
# reuse the original data location.
mem = cython.cast(cython.p_double, PyMem_Realloc(
self.data, new_number * cython.sizeof(cython.double)))
if not mem:
raise MemoryError()
# Only overwrite the pointer if the memory was really reallocated.
# On error (mem is NULL), the originally memory has not been freed.
self.data = mem
def __dealloc__(self):
PyMem_Free(self.data) # no-op if self.data is NULL
|
SomeMemory
|
python
|
huggingface__transformers
|
src/transformers/models/cohere/modeling_cohere.py
|
{
"start": 3155,
"end": 6203
}
|
class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: CohereConfig, 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[CohereConfig] = 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)
position_ids_expanded = position_ids[:, None, :].float()
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
with torch.autocast(device_type=device_type, enabled=False): # Force float32
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
emb = torch.repeat_interleave(freqs, 2, dim=-1) # diff from Llama: we interleave() instead of cat()
cos = emb.cos() * self.attention_scaling
sin = emb.sin() * self.attention_scaling
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
CohereRotaryEmbedding
|
python
|
sqlalchemy__sqlalchemy
|
test/orm/test_relationships.py
|
{
"start": 7319,
"end": 10982
}
|
class ____(fixtures.MappedTest):
"""Test flush() when a mapper is dependent on multiple relationships"""
run_setup_mappers = "once"
run_inserts = "once"
run_deletes = None
@classmethod
def define_tables(cls, metadata):
Table(
"tbl_a",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("name", String(128)),
)
Table(
"tbl_b",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("name", String(128)),
)
Table(
"tbl_c",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column(
"tbl_a_id", Integer, ForeignKey("tbl_a.id"), nullable=False
),
Column("name", String(128)),
)
Table(
"tbl_d",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column(
"tbl_c_id", Integer, ForeignKey("tbl_c.id"), nullable=False
),
Column("tbl_b_id", Integer, ForeignKey("tbl_b.id")),
Column("name", String(128)),
)
@classmethod
def setup_classes(cls):
class A(cls.Basic):
pass
class B(cls.Basic):
pass
class C(cls.Basic):
pass
class D(cls.Basic):
pass
@classmethod
def setup_mappers(cls):
A, C, B, D, tbl_b, tbl_c, tbl_a, tbl_d = (
cls.classes.A,
cls.classes.C,
cls.classes.B,
cls.classes.D,
cls.tables.tbl_b,
cls.tables.tbl_c,
cls.tables.tbl_a,
cls.tables.tbl_d,
)
cls.mapper_registry.map_imperatively(
A,
tbl_a,
properties=dict(
c_rows=relationship(
C, cascade="all, delete-orphan", backref="a_row"
)
),
)
cls.mapper_registry.map_imperatively(B, tbl_b)
cls.mapper_registry.map_imperatively(
C,
tbl_c,
properties=dict(
d_rows=relationship(
D, cascade="all, delete-orphan", backref="c_row"
)
),
)
cls.mapper_registry.map_imperatively(
D, tbl_d, properties=dict(b_row=relationship(B))
)
@classmethod
def insert_data(cls, connection):
A, C, B, D = (
cls.classes.A,
cls.classes.C,
cls.classes.B,
cls.classes.D,
)
session = Session(connection)
a = A(name="a1")
b = B(name="b1")
c = C(name="c1", a_row=a)
d1 = D(name="d1", b_row=b, c_row=c) # noqa
d2 = D(name="d2", b_row=b, c_row=c) # noqa
d3 = D(name="d3", b_row=b, c_row=c) # noqa
session.add(a)
session.add(b)
session.flush()
def test_DeleteRootTable(self):
A = self.classes.A
session = fixture_session()
a = session.query(A).filter_by(name="a1").one()
session.delete(a)
session.flush()
def test_DeleteMiddleTable(self):
C = self.classes.C
session = fixture_session()
c = session.query(C).filter_by(name="c1").one()
session.delete(c)
session.flush()
|
DependencyTwoParentTest
|
python
|
tensorflow__tensorflow
|
tensorflow/python/compiler/tensorrt/test/shape_output_test.py
|
{
"start": 4266,
"end": 5390
}
|
class ____(trt_test.TfTrtIntegrationTestBase):
"""In TRT 7, an input tensor can be pruned if it is not used by the network.
This happens if only its shape is used, but the shape is already defined by
the optimization profile by setting min=max. (nvbugs/3153064)
After pruning, the TRT network has no input bindings.
"""
def setUp(self):
super().setUp()
self.DisableNonTrtOptimizers()
def GraphFn(self, x):
q = array_ops.shape(x)
q = q * 2 + q * q
return array_ops.identity(q, name="output_0")
def GetParams(self):
return self.BuildParamsWithMask(
self.GraphFn,
dtypes.float32, [[1, 2, 5, 3]], [[4]],
extra_inputs=[],
extra_outputs=[],
input_mask=[[False, True, True, True]],
output_mask=[[True]])
def ExpectedEnginesToBuild(self, run_params):
"""Returns the expected engines to build."""
return ["TRTEngineOp_000"]
def ShouldRunTest(self, run_params):
# Shape op is only converted in dynamic shape mode.
return (run_params.dynamic_shape and
run_params.is_v2, "test v2 dynamic shape")
|
PrunedInputTest
|
python
|
django__django
|
tests/prefetch_related/models.py
|
{
"start": 7596,
"end": 7791
}
|
class ____(models.Model):
lesson_entry = models.ForeignKey(LessonEntry, models.CASCADE)
name = models.CharField(max_length=200)
# Ticket #21410: Regression when related_name="+"
|
WordEntry
|
python
|
readthedocs__readthedocs.org
|
readthedocs/config/tests/test_config.py
|
{
"start": 6381,
"end": 67964
}
|
class ____:
def test_version(self):
build = get_build_config({})
assert build.version == "2"
def test_formats_check_valid(self):
build = get_build_config({"formats": ["htmlzip", "pdf", "epub"]})
build.validate()
assert build.formats == ["htmlzip", "pdf", "epub"]
@pytest.mark.parametrize("value", [3, "invalid", {"other": "value"}])
def test_formats_check_invalid_value(self, value):
build = get_build_config({"formats": value})
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_LIST
assert excinfo.value.format_values.get("key") == "formats"
def test_formats_check_invalid_type(self):
build = get_build_config(
{"formats": ["htmlzip", "invalid", "epub"]},
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_CHOICE
assert excinfo.value.format_values.get("key") == "formats"
def test_formats_default_value(self):
build = get_build_config({})
build.validate()
assert build.formats == []
# TODO: remove/adapt all these tests that use "defaults".
# I'm removing them from the code since we don't need them anymore.
def test_formats_overrides_default_values(self):
build = get_build_config(
{},
)
build.validate()
assert build.formats == []
def test_formats_priority_over_defaults(self):
build = get_build_config(
{"formats": []},
)
build.validate()
assert build.formats == []
build = get_build_config(
{"formats": ["pdf"]},
)
build.validate()
assert build.formats == ["pdf"]
def test_formats_allow_empty(self):
build = get_build_config({"formats": []})
build.validate()
assert build.formats == []
def test_formats_allow_all_keyword(self):
build = get_build_config({"formats": "all"})
build.validate()
assert build.formats == ["htmlzip", "pdf", "epub"]
def test_conda_check_valid(self, tmpdir):
apply_fs(tmpdir, {"environment.yml": ""})
build = get_build_config(
{"conda": {"environment": "environment.yml"}},
source_file=str(tmpdir.join("readthedocs.yml")),
)
build.validate()
assert build.conda.environment == "environment.yml"
def test_conda_key_required_for_conda_mamba(self):
build = get_build_config(
{
"build": {
"os": "ubuntu-22.04",
"tools": {
"python": "miniconda3-4.7",
},
},
}
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigError.CONDA_KEY_REQUIRED
assert excinfo.value.format_values.get("key") == "conda"
def test_conda_key_not_required_for_conda_mamba_when_build_commands(self):
build = get_build_config(
{
"build": {
"os": "ubuntu-22.04",
"tools": {
"python": "mambaforge-22.9",
},
"commands": [
"mamba env create --file environment.yml",
],
},
}
)
with does_not_raise(ConfigError):
build.validate()
@pytest.mark.parametrize("value", [3, [], "invalid"])
def test_conda_check_invalid_value(self, value):
build = get_build_config({"conda": value})
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_DICT
assert excinfo.value.format_values.get("key") == "conda"
@pytest.mark.parametrize("value", [3, [], {}])
def test_conda_check_invalid_file_value(self, value):
build = get_build_config({"conda": {"file": value}})
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.VALUE_NOT_FOUND
assert excinfo.value.format_values.get("key") == "conda.environment"
def test_conda_check_file_required(self):
build = get_build_config({"conda": {"no-file": "other"}})
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.VALUE_NOT_FOUND
assert excinfo.value.format_values.get("key") == "conda.environment"
@pytest.mark.parametrize("value", [3, [], "invalid"])
def test_build_check_invalid_type(self, value):
build = get_build_config({"build": value})
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_DICT
assert excinfo.value.format_values.get("key") == "build"
@pytest.mark.parametrize("value", [3, [], {}])
def test_build_image_check_invalid_type(self, value):
build = get_build_config({"build": {"image": value}})
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.VALUE_NOT_FOUND
assert excinfo.value.format_values.get("key") == "build.os"
@pytest.mark.parametrize("value", ["", None, "latest"])
def test_new_build_config_invalid_os(self, value):
build = get_build_config(
{
"build": {
"os": value,
"tools": {"python": "3"},
},
},
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_CHOICE
assert excinfo.value.format_values.get("key") == "build.os"
@pytest.mark.parametrize(
"value", ["", None, "python", ["python", "nodejs"], {}, {"cobol": "99"}]
)
def test_new_build_config_invalid_tools(self, value):
build = get_build_config(
{
"build": {
"os": "ubuntu-20.04",
"tools": value,
},
},
)
with raises(ConfigError) as excinfo:
build.validate()
# TODO: split this test to check specific errors now we have better messages
assert excinfo.value.message_id in (
ConfigError.NOT_BUILD_TOOLS_OR_COMMANDS,
ConfigValidationError.INVALID_DICT,
ConfigValidationError.VALUE_NOT_FOUND,
ConfigValidationError.INVALID_CHOICE,
)
assert excinfo.value.format_values.get("key") in ("build.tools", "build")
def test_new_build_config_invalid_tools_version(self):
build = get_build_config(
{
"build": {
"os": "ubuntu-20.04",
"tools": {"python": "2.6"},
},
},
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_CHOICE
assert excinfo.value.format_values.get("key") == "build.tools.python"
assert excinfo.value.format_values.get("choices") == ", ".join(
settings.RTD_DOCKER_BUILD_SETTINGS["tools"]["python"].keys()
)
def test_new_build_config(self):
build = get_build_config(
{
"build": {
"os": "ubuntu-20.04",
"tools": {"python": "3.9"},
},
},
)
build.validate()
assert isinstance(build.build, BuildWithOs)
assert build.build.os == "ubuntu-20.04"
assert build.build.tools["python"].version == "3.9"
full_version = settings.RTD_DOCKER_BUILD_SETTINGS["tools"]["python"]["3.9"]
assert build.build.tools["python"].full_version == full_version
assert build.python_interpreter == "python"
def test_new_build_config_conflict_with_build_image(self):
build = get_build_config(
{
"build": {
"image": "latest",
"os": "ubuntu-20.04",
"tools": {"python": "3.9"},
},
},
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigError.INVALID_KEY_NAME
assert excinfo.value.format_values.get("key") == "build.image"
def test_new_build_config_conflict_with_build_python_version(self):
build = get_build_config(
{
"build": {
"os": "ubuntu-20.04",
"tools": {"python": "3.8"},
},
"python": {"version": "3.8"},
},
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigError.INVALID_KEY_NAME
assert excinfo.value.format_values.get("key") == "python.version"
def test_commands_build_config_tools_and_commands_valid(self):
"""
Test that build.tools and build.commands are valid together.
"""
build = get_build_config(
{
"build": {
"os": "ubuntu-20.04",
"tools": {"python": "3.8"},
"commands": ["pip install pelican", "pelican content"],
},
},
)
build.validate()
assert isinstance(build.build, BuildWithOs)
assert build.build.commands == ["pip install pelican", "pelican content"]
def test_build_jobs_without_build_os_is_invalid(self):
"""
build.jobs can't be used without build.os
"""
build = get_build_config(
{
"build": {
"tools": {"python": "3.8"},
"jobs": {
"pre_checkout": ["echo pre_checkout"],
},
},
},
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.VALUE_NOT_FOUND
assert excinfo.value.format_values.get("key") == "build.os"
def test_commands_build_config_invalid_command(self):
build = get_build_config(
{
"build": {
"os": "ubuntu-20.04",
"tools": {"python": "3.8"},
"commands": "command as string",
},
},
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_LIST
assert excinfo.value.format_values.get("key") == "build.commands"
def test_commands_build_config_invalid_no_os(self):
build = get_build_config(
{
"build": {
"commands": ["pip install pelican", "pelican content"],
},
},
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.VALUE_NOT_FOUND
assert excinfo.value.format_values.get("key") == "build.os"
def test_commands_build_config_valid(self):
"""It's valid to build with just build.os and build.commands."""
build = get_build_config(
{
"build": {
"os": "ubuntu-22.04",
"commands": ["echo 'hello world' > _readthedocs/html/index.html"],
},
},
)
build.validate()
assert isinstance(build.build, BuildWithOs)
assert build.build.commands == [
"echo 'hello world' > _readthedocs/html/index.html"
]
@pytest.mark.parametrize("value", ["", None, "pre_invalid"])
def test_jobs_build_config_invalid_jobs(self, value):
build = get_build_config(
{
"build": {
"os": "ubuntu-20.04",
"tools": {"python": "3.8"},
"jobs": {value: ["echo 1234", "git fetch --unshallow"]},
},
},
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_CHOICE
assert excinfo.value.format_values.get("key") == "build.jobs"
@pytest.mark.parametrize("value", ["", None, "echo 123", 42])
def test_jobs_build_config_invalid_job_commands(self, value):
build = get_build_config(
{
"build": {
"os": "ubuntu-20.04",
"tools": {"python": "3.8"},
"jobs": {
"pre_install": value,
},
},
},
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_LIST
assert excinfo.value.format_values.get("key") == "build.jobs.pre_install"
def test_jobs_build_config(self):
build = get_build_config(
{
"build": {
"os": "ubuntu-20.04",
"tools": {"python": "3.8"},
"jobs": {
"pre_checkout": ["echo pre_checkout"],
"post_checkout": ["echo post_checkout"],
"pre_system_dependencies": ["echo pre_system_dependencies"],
"post_system_dependencies": ["echo post_system_dependencies"],
"pre_create_environment": ["echo pre_create_environment"],
"post_create_environment": ["echo post_create_environment"],
"pre_install": ["echo pre_install", "echo `date`"],
"post_install": ["echo post_install"],
"pre_build": [
"echo pre_build",
'sed -i -e "s|{VERSION}|${READTHEDOCS_VERSION_NAME}|g"',
],
"post_build": ["echo post_build"],
},
},
},
)
build.validate()
assert isinstance(build.build, BuildWithOs)
assert isinstance(build.build.jobs, BuildJobs)
assert build.build.jobs.pre_checkout == ["echo pre_checkout"]
assert build.build.jobs.post_checkout == ["echo post_checkout"]
assert build.build.jobs.pre_system_dependencies == [
"echo pre_system_dependencies"
]
assert build.build.jobs.post_system_dependencies == [
"echo post_system_dependencies"
]
assert build.build.jobs.pre_create_environment == [
"echo pre_create_environment"
]
assert build.build.jobs.create_environment is None
assert build.build.jobs.post_create_environment == [
"echo post_create_environment"
]
assert build.build.jobs.pre_install == ["echo pre_install", "echo `date`"]
assert build.build.jobs.install is None
assert build.build.jobs.post_install == ["echo post_install"]
assert build.build.jobs.pre_build == [
"echo pre_build",
'sed -i -e "s|{VERSION}|${READTHEDOCS_VERSION_NAME}|g"',
]
assert build.build.jobs.build == BuildJobsBuildTypes()
assert build.build.jobs.post_build == ["echo post_build"]
def test_build_jobs_partial_override(self):
build = get_build_config(
{
"formats": ["pdf", "htmlzip", "epub"],
"build": {
"os": "ubuntu-20.04",
"tools": {"python": "3"},
"jobs": {
"create_environment": ["echo make_environment"],
"install": ["echo install"],
"build": {
"html": ["echo build html"],
"pdf": ["echo build pdf"],
"epub": ["echo build epub"],
"htmlzip": ["echo build htmlzip"],
},
},
},
},
)
build.validate()
assert isinstance(build.build, BuildWithOs)
assert isinstance(build.build.jobs, BuildJobs)
assert build.build.jobs.create_environment == ["echo make_environment"]
assert build.build.jobs.install == ["echo install"]
assert build.build.jobs.build.html == ["echo build html"]
assert build.build.jobs.build.pdf == ["echo build pdf"]
assert build.build.jobs.build.epub == ["echo build epub"]
assert build.build.jobs.build.htmlzip == ["echo build htmlzip"]
def test_build_jobs_build_should_match_formats(self):
build = get_build_config(
{
"formats": ["pdf"],
"build": {
"os": "ubuntu-24.04",
"tools": {"python": "3"},
"jobs": {
"build": {
"epub": ["echo build epub"],
},
},
},
},
)
with raises(ConfigError) as excinfo:
build.validate()
assert (
excinfo.value.message_id
== ConfigError.BUILD_JOBS_BUILD_TYPE_MISSING_IN_FORMATS
)
def test_build_jobs_build_defaults(self):
build = get_build_config(
{
"build": {
"os": "ubuntu-24.04",
"tools": {"python": "3"},
"jobs": {
"build": {
"html": ["echo build html"],
},
},
},
},
)
build.validate()
assert build.build.jobs.build.html == ["echo build html"]
assert build.build.jobs.build.pdf is None
assert build.build.jobs.build.htmlzip is None
assert build.build.jobs.build.epub is None
def test_build_jobs_partial_override_empty_commands(self):
build = get_build_config(
{
"formats": ["pdf"],
"build": {
"os": "ubuntu-24.04",
"tools": {"python": "3"},
"jobs": {
"create_environment": [],
"install": [],
"build": {
"html": [],
"pdf": [],
},
},
},
},
)
build.validate()
assert isinstance(build.build, BuildWithOs)
assert isinstance(build.build.jobs, BuildJobs)
assert build.build.jobs.create_environment == []
assert build.build.jobs.install == []
assert build.build.jobs.build.html == []
assert build.build.jobs.build.pdf == []
assert build.build.jobs.build.epub == None
assert build.build.jobs.build.htmlzip == None
@pytest.mark.parametrize(
"value",
[
[],
["cmatrix"],
["Mysql", "cmatrix", "postgresql-dev"],
],
)
def test_build_apt_packages_check_valid(self, value):
build = get_build_config(
{
"build": {
"os": "ubuntu-22.04",
"tools": {"python": "3"},
"apt_packages": value,
}
}
)
build.validate()
assert build.build.apt_packages == value
@pytest.mark.parametrize(
"value",
[3, "string", {}],
)
def test_build_apt_packages_invalid_type(self, value):
build = get_build_config(
{
"build": {
"os": "ubuntu-22.04",
"tools": {"python": "3"},
"apt_packages": value,
}
}
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_LIST
assert excinfo.value.format_values.get("key") == "build.apt_packages"
@pytest.mark.parametrize(
"error_index, value",
[
(0, ["/", "cmatrix"]),
(1, ["cmatrix", "-q"]),
(1, ["cmatrix", " -q"]),
(1, ["cmatrix", "\\-q"]),
(1, ["cmatrix", "--quiet"]),
(1, ["cmatrix", " --quiet"]),
(2, ["cmatrix", "quiet", "./package.deb"]),
(2, ["cmatrix", "quiet", " ./package.deb "]),
(2, ["cmatrix", "quiet", "/home/user/package.deb"]),
(2, ["cmatrix", "quiet", " /home/user/package.deb"]),
(2, ["cmatrix", "quiet", "../package.deb"]),
(2, ["cmatrix", "quiet", " ../package.deb"]),
(1, ["one", "$two"]),
(1, ["one", "non-ascíí"]),
# We don't allow regex for now.
(1, ["mysql", "cmatrix$"]),
(0, ["^mysql-*", "cmatrix$"]),
# We don't allow specifying versions for now.
(0, ["postgresql=1.2.3"]),
# We don't allow specifying distributions for now.
(0, ["cmatrix/bionic"]),
],
)
def test_build_apt_packages_invalid_value(self, error_index, value):
build = get_build_config(
{
"build": {
"os": "ubuntu-22.04",
"tools": {"python": "3"},
"apt_packages": value,
}
}
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id in (
ConfigError.APT_INVALID_PACKAGE_NAME,
ConfigError.APT_INVALID_PACKAGE_NAME_PREFIX,
)
assert (
excinfo.value.format_values.get("key")
== f"build.apt_packages.{error_index}"
)
@pytest.mark.parametrize("value", [3, [], "invalid"])
def test_python_check_invalid_types(self, value):
build = get_build_config({"python": value})
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_DICT
assert excinfo.value.format_values.get("key") == "python"
@pytest.mark.parametrize("value", [[], {}, "3", "3.10"])
def test_python_version_check_invalid_types(self, value):
build = get_build_config({"python": {"version": value}})
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigError.INVALID_KEY_NAME
assert excinfo.value.format_values.get("key") == "python.version"
def test_python_install_default_value(self):
build = get_build_config({})
build.validate()
install = build.python.install
assert len(install) == 0
def test_python_install_check_default(self, tmpdir):
build = get_build_config(
{
"python": {
"install": [
{
"path": ".",
}
],
},
},
source_file=str(tmpdir.join("readthedocs.yml")),
)
build.validate()
install = build.python.install
assert len(install) == 1
assert isinstance(install[0], PythonInstall)
assert install[0].path == "."
assert install[0].method == PIP
assert install[0].extra_requirements == []
@pytest.mark.parametrize("value", ["invalid", "apt"])
def test_python_install_method_check_invalid(self, value, tmpdir):
build = get_build_config(
{
"python": {
"install": [
{
"path": ".",
"method": value,
}
],
},
},
source_file=str(tmpdir.join("readthedocs.yml")),
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_CHOICE
assert excinfo.value.format_values.get("key") == "python.install.0.method"
def test_python_install_requirements_check_valid(self, tmpdir):
apply_fs(tmpdir, {"requirements.txt": ""})
build = get_build_config(
{
"python": {
"install": [{"requirements": "requirements.txt"}],
},
},
source_file=str(tmpdir.join("readthedocs.yml")),
)
build.validate()
install = build.python.install
assert len(install) == 1
assert isinstance(install[0], PythonInstallRequirements)
assert install[0].requirements == "requirements.txt"
def test_python_install_requirements_does_not_allow_null(self, tmpdir):
build = get_build_config(
{
"python": {
"install": [
{
"path": ".",
"requirements": None,
}
],
},
},
source_file=str(tmpdir.join("readthedocs.yml")),
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_STRING
assert excinfo.value.format_values.get("key") == "python.install.0.requirements"
def test_python_install_requirements_error_msg(self, tmpdir):
build = get_build_config(
{
"python": {
"install": [
{
"path": ".",
"requirements": None,
}
],
},
},
source_file=str(tmpdir.join("readthedocs.yml")),
)
with raises(ConfigError) as excinfo:
build.validate()
assert str(excinfo.value) == "Build user exception"
# assert registry.get()
# == 'Invalid configuration option "python.install[0].requirements": expected string'
def test_python_install_requirements_does_not_allow_empty_string(self, tmpdir):
build = get_build_config(
{
"python": {
"install": [
{
"path": ".",
"requirements": "",
}
],
},
},
source_file=str(tmpdir.join("readthedocs.yml")),
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_PATH
assert excinfo.value.format_values.get("key") == "python.install.0.requirements"
@pytest.mark.parametrize("value", [3, [], {}])
def test_python_install_requirements_check_invalid_types(self, value, tmpdir):
build = get_build_config(
{
"python": {
"install": [
{
"path": ".",
"requirements": value,
}
],
},
},
source_file=str(tmpdir.join("readthedocs.yml")),
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_STRING
assert excinfo.value.format_values.get("key") == "python.install.0.requirements"
def test_python_install_path_is_required(self, tmpdir):
build = get_build_config(
{
"python": {
"install": [
{
"method": "pip",
}
],
},
},
source_file=str(tmpdir.join("readthedocs.yml")),
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigError.PIP_PATH_OR_REQUIREMENT_REQUIRED
assert excinfo.value.format_values.get("key") == "python.install.0"
def test_python_install_pip_check_valid(self, tmpdir):
build = get_build_config(
{
"python": {
"install": [
{
"path": ".",
"method": "pip",
}
],
},
},
source_file=str(tmpdir.join("readthedocs.yml")),
)
build.validate()
install = build.python.install
assert len(install) == 1
assert install[0].path == "."
assert install[0].method == PIP
def test_python_install_setuptools_check_valid(self, tmpdir):
build = get_build_config(
{
"python": {
"install": [
{
"path": ".",
"method": "setuptools",
}
],
},
},
source_file=str(tmpdir.join("readthedocs.yml")),
)
build.validate()
install = build.python.install
assert len(install) == 1
assert install[0].path == "."
assert install[0].method == SETUPTOOLS
def test_python_install_allow_empty_list(self):
build = get_build_config(
{"python": {"install": []}},
)
build.validate()
assert build.python.install == []
def test_python_install_default(self):
build = get_build_config({"python": {}})
build.validate()
assert build.python.install == []
@pytest.mark.parametrize("value", [2, "string", {}])
def test_python_install_check_invalid_type(self, value):
build = get_build_config(
{"python": {"install": value}},
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_LIST
assert excinfo.value.format_values.get("key") == "python.install"
def test_python_install_extra_requirements_and_pip(self, tmpdir):
build = get_build_config(
{
"python": {
"install": [
{
"path": ".",
"method": "pip",
"extra_requirements": ["docs", "tests"],
}
],
},
},
source_file=str(tmpdir.join("readthedocs.yml")),
)
build.validate()
install = build.python.install
assert len(install) == 1
assert install[0].extra_requirements == ["docs", "tests"]
def test_python_install_extra_requirements_and_setuptools(self, tmpdir):
build = get_build_config(
{
"python": {
"install": [
{
"path": ".",
"method": "setuptools",
"extra_requirements": ["docs", "tests"],
}
],
}
},
source_file=str(tmpdir.join("readthedocs.yml")),
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigError.USE_PIP_FOR_EXTRA_REQUIREMENTS
@pytest.mark.parametrize("value", [2, "invalid", {}, "", None])
def test_python_install_extra_requirements_check_type(self, value, tmpdir):
build = get_build_config(
{
"python": {
"install": [
{
"path": ".",
"method": "pip",
"extra_requirements": value,
}
],
},
},
source_file=str(tmpdir.join("readthedocs.yml")),
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_LIST
assert (
excinfo.value.format_values.get("key")
== "python.install.0.extra_requirements"
)
def test_python_install_extra_requirements_allow_empty(self, tmpdir):
build = get_build_config(
{
"python": {
"install": [
{
"path": ".",
"method": "pip",
"extra_requirements": [],
}
],
},
},
source_file=str(tmpdir.join("readthedocs.yml")),
)
build.validate()
install = build.python.install
assert len(install) == 1
assert install[0].extra_requirements == []
def test_python_install_several_respects_order(self, tmpdir):
apply_fs(
tmpdir,
{
"one": {},
"two": {},
"three.txt": "",
},
)
build = get_build_config(
{
"python": {
"install": [
{
"path": "one",
"method": "pip",
"extra_requirements": [],
},
{
"path": "two",
"method": "setuptools",
},
{
"requirements": "three.txt",
},
],
},
},
source_file=str(tmpdir.join("readthedocs.yml")),
)
build.validate()
install = build.python.install
assert len(install) == 3
assert install[0].path == "one"
assert install[0].method == PIP
assert install[0].extra_requirements == []
assert install[1].path == "two"
assert install[1].method == SETUPTOOLS
assert install[2].requirements == "three.txt"
@pytest.mark.parametrize("value", [[], True, 0, "invalid"])
def test_sphinx_validate_type(self, value):
build = get_build_config({"sphinx": value})
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_DICT
assert excinfo.value.format_values.get("key") == "sphinx"
def test_sphinx_is_default_doc_type(self):
build = get_build_config({})
build.validate()
assert build.sphinx is not None
assert build.mkdocs is None
assert build.doctype == "sphinx"
@pytest.mark.parametrize(
"value,expected",
[
("html", "sphinx"),
("htmldir", "sphinx_htmldir"),
("dirhtml", "sphinx_htmldir"),
("singlehtml", "sphinx_singlehtml"),
],
)
def test_sphinx_builder_check_valid(self, value, expected):
build = get_build_config(
{"sphinx": {"builder": value}},
)
build.validate()
assert build.sphinx.builder == expected
assert build.doctype == expected
@pytest.mark.parametrize("value", [[], True, 0, "invalid"])
def test_sphinx_builder_check_invalid(self, value):
build = get_build_config({"sphinx": {"builder": value}})
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_CHOICE
assert excinfo.value.format_values.get("key") == "sphinx.builder"
def test_sphinx_builder_default(self):
build = get_build_config({})
build.validate()
build.sphinx.builder == "sphinx"
def test_sphinx_builder_ignores_default(self):
build = get_build_config(
{},
)
build.validate()
build.sphinx.builder == "sphinx"
def test_sphinx_configuration_check_valid(self, tmpdir):
apply_fs(tmpdir, {"conf.py": ""})
build = get_build_config(
{"sphinx": {"configuration": "conf.py"}},
source_file=str(tmpdir.join("readthedocs.yml")),
)
build.validate()
assert build.sphinx.configuration == "conf.py"
def test_sphinx_cant_be_used_with_mkdocs(self, tmpdir):
apply_fs(tmpdir, {"conf.py": ""})
build = get_build_config(
{
"sphinx": {"configuration": "conf.py"},
"mkdocs": {},
},
source_file=str(tmpdir.join("readthedocs.yml")),
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigError.SPHINX_MKDOCS_CONFIG_TOGETHER
def test_sphinx_configuration_allow_null(self):
build = get_build_config(
{"sphinx": {"configuration": None}},
)
build.validate()
assert build.sphinx.configuration is None
def test_sphinx_configuration_check_default(self):
build = get_build_config({})
build.validate()
assert build.sphinx.configuration is None
@pytest.mark.parametrize("value", [[], True, 0, {}])
def test_sphinx_configuration_validate_type(self, value):
build = get_build_config(
{"sphinx": {"configuration": value}},
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_STRING
assert excinfo.value.format_values.get("key") == "sphinx.configuration"
@pytest.mark.parametrize("value", [True, False])
def test_sphinx_fail_on_warning_check_valid(self, value):
build = get_build_config({"sphinx": {"fail_on_warning": value}})
build.validate()
assert build.sphinx.fail_on_warning is value
@pytest.mark.parametrize("value", [[], "invalid", 5])
def test_sphinx_fail_on_warning_check_invalid(self, value):
build = get_build_config({"sphinx": {"fail_on_warning": value}})
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_BOOL
assert excinfo.value.format_values.get("key") == "sphinx.fail_on_warning"
def test_sphinx_fail_on_warning_check_default(self):
build = get_build_config({})
build.validate()
assert build.sphinx.fail_on_warning is False
@pytest.mark.parametrize("value", [[], True, 0, "invalid"])
def test_mkdocs_validate_type(self, value):
build = get_build_config({"mkdocs": value})
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_DICT
assert excinfo.value.format_values.get("key") == "mkdocs"
def test_mkdocs_default(self):
build = get_build_config({})
build.validate()
assert build.mkdocs is None
def test_mkdocs_configuration_check_valid(self, tmpdir):
apply_fs(tmpdir, {"mkdocs.yml": ""})
build = get_build_config(
{"mkdocs": {"configuration": "mkdocs.yml"}},
source_file=str(tmpdir.join("readthedocs.yml")),
)
build.validate()
assert build.mkdocs.configuration == "mkdocs.yml"
assert build.doctype == "mkdocs"
assert build.sphinx is None
def test_mkdocs_configuration_allow_null(self):
build = get_build_config(
{"mkdocs": {"configuration": None}},
)
build.validate()
assert build.mkdocs.configuration is None
def test_mkdocs_configuration_check_default(self):
build = get_build_config(
{"mkdocs": {}},
)
build.validate()
assert build.mkdocs.configuration is None
@pytest.mark.parametrize("value", [[], True, 0, {}])
def test_mkdocs_configuration_validate_type(self, value):
build = get_build_config(
{"mkdocs": {"configuration": value}},
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_STRING
assert excinfo.value.format_values.get("key") == "mkdocs.configuration"
@pytest.mark.parametrize("value", [True, False])
def test_mkdocs_fail_on_warning_check_valid(self, value):
build = get_build_config(
{"mkdocs": {"fail_on_warning": value}},
)
build.validate()
assert build.mkdocs.fail_on_warning is value
@pytest.mark.parametrize("value", [[], "invalid", 5])
def test_mkdocs_fail_on_warning_check_invalid(self, value):
build = get_build_config(
{"mkdocs": {"fail_on_warning": value}},
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_BOOL
assert excinfo.value.format_values.get("key") == "mkdocs.fail_on_warning"
def test_mkdocs_fail_on_warning_check_default(self):
build = get_build_config(
{"mkdocs": {}},
)
build.validate()
assert build.mkdocs.fail_on_warning is False
def test_submodule_defaults(self):
build = get_build_config({})
build.validate()
assert build.submodules.include == []
assert build.submodules.exclude == ALL
assert build.submodules.recursive is False
@pytest.mark.parametrize("value", [[], "invalid", 0])
def test_submodules_check_invalid_type(self, value):
build = get_build_config({"submodules": value})
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_DICT
assert excinfo.value.format_values.get("key") == "submodules"
def test_submodules_include_check_valid(self):
build = get_build_config(
{
"submodules": {
"include": ["one", "two"],
},
}
)
build.validate()
assert build.submodules.include == ["one", "two"]
assert build.submodules.exclude == []
assert build.submodules.recursive is False
@pytest.mark.parametrize("value", ["invalid", True, 0, {}])
def test_submodules_include_check_invalid(self, value):
build = get_build_config(
{
"submodules": {
"include": value,
},
}
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_LIST
assert excinfo.value.format_values.get("key") == "submodules.include"
def test_submodules_include_allows_all_keyword(self):
build = get_build_config(
{
"submodules": {
"include": "all",
},
}
)
build.validate()
assert build.submodules.include == ALL
assert build.submodules.exclude == []
assert build.submodules.recursive is False
def test_submodules_exclude_check_valid(self):
build = get_build_config(
{
"submodules": {
"exclude": ["one", "two"],
},
}
)
build.validate()
assert build.submodules.include == []
assert build.submodules.exclude == ["one", "two"]
assert build.submodules.recursive is False
@pytest.mark.parametrize("value", ["invalid", True, 0, {}])
def test_submodules_exclude_check_invalid(self, value):
build = get_build_config(
{
"submodules": {
"exclude": value,
},
}
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_LIST
assert excinfo.value.format_values.get("key") == "submodules.exclude"
def test_submodules_exclude_allows_all_keyword(self):
build = get_build_config(
{
"submodules": {
"exclude": "all",
},
}
)
build.validate()
assert build.submodules.include == []
assert build.submodules.exclude == ALL
assert build.submodules.recursive is False
def test_submodules_cant_exclude_and_include(self):
build = get_build_config(
{
"submodules": {
"include": ["two"],
"exclude": ["one"],
},
}
)
with raises(ConfigError) as excinfo:
build.validate()
assert (
excinfo.value.message_id == ConfigError.SUBMODULES_INCLUDE_EXCLUDE_TOGETHER
)
def test_submodules_can_exclude_include_be_empty(self):
build = get_build_config(
{
"submodules": {
"exclude": "all",
"include": [],
},
}
)
build.validate()
assert build.submodules.include == []
assert build.submodules.exclude == ALL
assert build.submodules.recursive is False
@pytest.mark.parametrize("value", [True, False])
def test_submodules_recursive_check_valid(self, value):
build = get_build_config(
{
"submodules": {
"include": ["one", "two"],
"recursive": value,
},
}
)
build.validate()
assert build.submodules.include == ["one", "two"]
assert build.submodules.exclude == []
assert build.submodules.recursive is value
@pytest.mark.parametrize("value", [[], "invalid", 5])
def test_submodules_recursive_check_invalid(self, value):
build = get_build_config(
{
"submodules": {
"include": ["one", "two"],
"recursive": value,
},
}
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_BOOL
assert excinfo.value.format_values.get("key") == "submodules.recursive"
def test_submodules_recursive_explicit_default(self):
build = get_build_config(
{
"submodules": {
"include": [],
"recursive": False,
},
}
)
build.validate()
assert build.submodules.include == []
assert build.submodules.exclude == ALL
assert build.submodules.recursive is False
build = get_build_config(
{
"submodules": {
"exclude": [],
"recursive": False,
},
}
)
build.validate()
assert build.submodules.include == []
assert build.submodules.exclude == []
assert build.submodules.recursive is False
@pytest.mark.parametrize("value", ["invalid", True, 0, []])
def test_search_invalid_type(self, value):
build = get_build_config(
{
"search": value,
}
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id == ConfigValidationError.INVALID_DICT
assert excinfo.value.format_values.get("key") == "search"
@pytest.mark.parametrize(
"value",
[
"invalid",
True,
0,
[],
{"foo/bar": 11},
{"foo/bar": -11},
{"foo/bar": 2.5},
{"foo/bar": "bar"},
{"/": 1},
{"/foo/..": 1},
{"..": 1},
{"/foo/bar/../../../": 1},
{10: "bar"},
{10: 0},
],
)
def test_search_ranking_invalid_type(self, value):
build = get_build_config(
{
"search": {"ranking": value},
}
)
with raises(ConfigError) as excinfo:
build.validate()
# TODO: these test should be split to validate the exact ``message_id``
assert excinfo.value.message_id in (
ConfigValidationError.INVALID_DICT,
ConfigValidationError.INVALID_CHOICE,
ConfigValidationError.INVALID_PATH_PATTERN,
ConfigValidationError.INVALID_STRING,
)
assert excinfo.value.format_values.get("key") == "search.ranking"
@pytest.mark.parametrize("value", list(range(-10, 10 + 1)))
def test_search_valid_ranking(self, value):
build = get_build_config(
{
"search": {
"ranking": {
"foo/bar": value,
"bar/foo": value,
},
},
}
)
build.validate()
assert build.search.ranking == {"foo/bar": value, "bar/foo": value}
@pytest.mark.parametrize(
"path, expected",
[
("/foo/bar", "foo/bar"),
("///foo//bar", "foo/bar"),
("///foo//bar/", "foo/bar"),
("/foo/bar/../", "foo"),
("/foo*", "foo*"),
("/foo/bar/*", "foo/bar/*"),
("/foo/bar?/*", "foo/bar?/*"),
("foo/[bc]ar/*/", "foo/[bc]ar/*"),
("*", "*"),
("index.html", "index.html"),
],
)
def test_search_ranking_normilize_path(self, path, expected):
build = get_build_config(
{
"search": {
"ranking": {
path: 1,
},
},
}
)
build.validate()
assert build.search.ranking == {expected: 1}
@pytest.mark.parametrize(
"value",
[
"invalid",
True,
0,
[2, 3],
{"foo/bar": 11},
],
)
def test_search_ignore_invalid_type(self, value):
build = get_build_config(
{
"search": {"ignore": value},
}
)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id in (
ConfigValidationError.INVALID_LIST,
ConfigValidationError.INVALID_STRING,
)
assert excinfo.value.format_values.get("key") == "search.ignore"
@pytest.mark.parametrize(
"path, expected",
[
("/foo/bar", "foo/bar"),
("///foo//bar", "foo/bar"),
("///foo//bar/", "foo/bar"),
("/foo/bar/../", "foo"),
("/foo*", "foo*"),
("/foo/bar/*", "foo/bar/*"),
("/foo/bar?/*", "foo/bar?/*"),
("foo/[bc]ar/*/", "foo/[bc]ar/*"),
("*", "*"),
("index.html", "index.html"),
],
)
def test_search_ignore_valid_type(self, path, expected):
build = get_build_config(
{
"search": {
"ignore": [path],
},
}
)
build.validate()
assert build.search.ignore == [expected]
@pytest.mark.parametrize(
"value,key",
[
({"typo": "something"}, "typo"),
(
{
"pyton": {
"version": "another typo",
}
},
"pyton.version",
),
(
{
"build": {
"os": "ubuntu-22.04",
"tools": {"python": "3"},
"extra": "key",
}
},
"build.extra",
),
(
{
"python": {
"install": [
{
"path": ".",
},
{
"path": ".",
"method": "pip",
"invalid": "key",
},
]
}
},
"python.install.1.invalid",
),
],
)
def test_strict_validation(self, value, key):
build = get_build_config(value)
with raises(ConfigError) as excinfo:
build.validate()
assert excinfo.value.message_id in (
ConfigError.INVALID_KEY_NAME,
ConfigValidationError.INVALID_BOOL,
)
assert excinfo.value.format_values.get("key") == key
@pytest.mark.parametrize(
"value,expected",
[
({}, []),
({"one": 1}, ["one"]),
({"one": {"two": 3}}, ["one", "two"]),
(OrderedDict([("one", 1), ("two", 2)]), ["one"]),
(OrderedDict([("one", {"two": 2}), ("three", 3)]), ["one", "two"]),
],
)
def test_get_extra_key(self, value, expected):
build = get_build_config({})
assert build._get_extra_key(value) == expected
def test_pop_config_single(self):
build = get_build_config({})
build.pop_config("version")
build.pop_config("build")
assert build._raw_config == {}
def test_pop_config_nested(self):
build = get_build_config({})
build.pop_config("version")
build.pop_config("build.os")
build.pop_config("build.tools")
assert build._raw_config == {}
def test_pop_config_nested_with_residue(self):
build = get_build_config({})
build.pop_config("version")
build.pop_config("build.tools")
assert build._raw_config == {"build": {"os": "ubuntu-22.04"}}
def test_pop_config_default_none(self):
build = get_build_config({})
assert build.pop_config("one.four") is None
def test_pop_config_default(self):
build = get_build_config({})
assert build.pop_config("one.four", 4) == 4
def test_pop_config_raise_exception(self):
build = get_build_config({})
with raises(ConfigValidationError) as excinfo:
build.pop_config("build.invalid", raise_ex=True)
assert excinfo.value.format_values.get("value") == "invalid"
assert excinfo.value.message_id == ConfigValidationError.VALUE_NOT_FOUND
def test_sphinx_without_explicit_configuration(self):
data = {
"sphinx": {},
}
get_build_config(data, validate=True)
with raises(ConfigError) as excinfo:
get_build_config(data, validate=True, deprecate_implicit_keys=True)
assert excinfo.value.message_id == ConfigError.SPHINX_CONFIG_MISSING
data["sphinx"]["configuration"] = "conf.py"
get_build_config(data, validate=True, deprecate_implicit_keys=True)
def test_mkdocs_without_explicit_configuration(self):
data = {
"mkdocs": {},
}
get_build_config(data, validate=True)
with raises(ConfigError) as excinfo:
get_build_config(data, validate=True, deprecate_implicit_keys=True)
assert excinfo.value.message_id == ConfigError.MKDOCS_CONFIG_MISSING
data["mkdocs"]["configuration"] = "mkdocs.yml"
get_build_config(data, validate=True, deprecate_implicit_keys=True)
def test_config_without_sphinx_key(self):
data = {
"build": {
"os": "ubuntu-22.04",
"tools": {
"python": "3",
},
"jobs": {},
},
}
get_build_config(data, validate=True)
with raises(ConfigError) as excinfo:
get_build_config(data, validate=True, deprecate_implicit_keys=True)
assert excinfo.value.message_id == ConfigError.SPHINX_CONFIG_MISSING
# No exception should be raised when overriding any of the the new jobs.
data_copy = data.copy()
data_copy["build"]["jobs"]["create_environment"] = ["echo 'Hello World'"]
get_build_config(data_copy, validate=True, deprecate_implicit_keys=True)
data_copy = data.copy()
data_copy["build"]["jobs"]["install"] = ["echo 'Hello World'"]
get_build_config(data_copy, validate=True, deprecate_implicit_keys=True)
data_copy = data.copy()
data_copy["build"]["jobs"]["build"] = {"html": ["echo 'Hello World'"]}
get_build_config(data_copy, validate=True, deprecate_implicit_keys=True)
def test_sphinx_and_mkdocs_arent_required_when_using_build_commands(self):
data = {
"build": {
"os": "ubuntu-22.04",
"tools": {
"python": "3",
},
"commands": ["echo 'Hello World'"],
},
}
get_build_config(data, validate=True, deprecate_implicit_keys=True)
def test_as_dict_new_build_config(self, tmpdir):
build = get_build_config(
{
"version": 2,
"formats": ["pdf"],
"build": {
"os": "ubuntu-20.04",
"tools": {
"python": "3.9",
"nodejs": "16",
},
},
"python": {
"install": [
{
"requirements": "requirements.txt",
}
],
},
},
source_file=str(tmpdir.join("readthedocs.yml")),
)
build.validate()
expected_dict = {
"version": "2",
"formats": ["pdf"],
"python": {
"install": [
{
"requirements": "requirements.txt",
}
],
},
"build": {
"os": "ubuntu-20.04",
"tools": {
"python": {
"version": "3.9",
"full_version": settings.RTD_DOCKER_BUILD_SETTINGS["tools"][
"python"
]["3.9"],
},
"nodejs": {
"version": "16",
"full_version": settings.RTD_DOCKER_BUILD_SETTINGS["tools"][
"nodejs"
]["16"],
},
},
"commands": [],
"jobs": {
"pre_checkout": [],
"post_checkout": [],
"pre_system_dependencies": [],
"post_system_dependencies": [],
"pre_create_environment": [],
"create_environment": None,
"post_create_environment": [],
"pre_install": [],
"install": None,
"post_install": [],
"pre_build": [],
"build": {
"html": None,
"pdf": None,
"epub": None,
"htmlzip": None,
},
"post_build": [],
},
"apt_packages": [],
},
"conda": None,
"sphinx": {
"builder": "sphinx",
"configuration": None,
"fail_on_warning": False,
},
"mkdocs": None,
"doctype": "sphinx",
"submodules": {
"include": [],
"exclude": ALL,
"recursive": False,
},
"search": {
"ranking": {},
"ignore": [
"search.html",
"search/index.html",
"404.html",
"404/index.html",
],
},
}
assert build.as_dict() == expected_dict
|
TestBuildConfigV2
|
python
|
doocs__leetcode
|
solution/1100-1199/1157.Online Majority Element In Subarray/Solution.py
|
{
"start": 0,
"end": 136
}
|
class ____:
__slots__ = ("l", "r", "x", "cnt")
def __init__(self):
self.l = self.r = 0
self.x = self.cnt = 0
|
Node
|
python
|
apache__airflow
|
dev/breeze/tests/test_ui_commands.py
|
{
"start": 1023,
"end": 2379
}
|
class ____:
def test_get_plural_base_with_suffix(self):
suffixes = ["_one", "_other"]
assert get_plural_base("message_one", suffixes) == "message"
assert get_plural_base("message_other", suffixes) == "message"
def test_get_plural_base_without_suffix(self):
suffixes = ["_one", "_other"]
assert get_plural_base("message", suffixes) is None
def test_get_plural_base_with_complex_suffixes(self):
suffixes = ["_zero", "_one", "_two", "_few", "_many", "_other"]
assert get_plural_base("item_zero", suffixes) == "item"
assert get_plural_base("item_many", suffixes) == "item"
def test_expand_plural_keys_english(self):
keys = {"message_one", "message_other", "simple"}
expanded = expand_plural_keys(keys, "en")
# Should include both _one and _other forms for "message"
assert "message_one" in expanded
assert "message_other" in expanded
assert "simple" in expanded
def test_expand_plural_keys_polish(self):
keys = {"message_one"}
expanded = expand_plural_keys(keys, "pl")
# Polish has 4 forms: _one, _few, _many, _other
assert "message_one" in expanded
assert "message_few" in expanded
assert "message_many" in expanded
assert "message_other" in expanded
|
TestPluralHandling
|
python
|
apache__airflow
|
airflow-core/src/airflow/models/backfill.py
|
{
"start": 3345,
"end": 5140
}
|
class ____(Base):
"""Model representing a backfill job."""
__tablename__ = "backfill"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
dag_id: Mapped[str] = mapped_column(StringID(), nullable=False)
from_date: Mapped[datetime] = mapped_column(UtcDateTime, nullable=False)
to_date: Mapped[datetime] = mapped_column(UtcDateTime, nullable=False)
dag_run_conf: Mapped[dict] = mapped_column(JSONField(json=json), nullable=False, default={})
is_paused: Mapped[bool | None] = mapped_column(Boolean, default=False, nullable=True)
"""
Controls whether new dag runs will be created for this backfill.
Does not pause existing dag runs.
"""
reprocess_behavior: Mapped[str] = mapped_column(
StringID(), nullable=False, default=ReprocessBehavior.NONE
)
max_active_runs: Mapped[int] = mapped_column(Integer, default=10, nullable=False)
created_at: Mapped[datetime] = mapped_column(UtcDateTime, default=timezone.utcnow, nullable=False)
completed_at: Mapped[datetime | None] = mapped_column(UtcDateTime, nullable=True)
updated_at: Mapped[datetime] = mapped_column(
UtcDateTime, default=timezone.utcnow, onupdate=timezone.utcnow, nullable=False
)
triggering_user_name: Mapped[str | None] = mapped_column(
String(512),
nullable=True,
) # The user that triggered the Backfill, if applicable
backfill_dag_run_associations = relationship("BackfillDagRun", back_populates="backfill")
dag_model = relationship(
"DagModel",
primaryjoin="DagModel.dag_id == Backfill.dag_id",
viewonly=True,
foreign_keys=[dag_id],
)
def __repr__(self):
return f"Backfill({self.dag_id=}, {self.from_date=}, {self.to_date=})"
|
Backfill
|
python
|
sympy__sympy
|
sympy/utilities/lambdify.py
|
{
"start": 51451,
"end": 59739
}
|
class ____(_EvaluatorPrinter):
def _print_unpacking(self, lvalues, rvalue):
"""Generate argument unpacking code.
This method is used when the input value is not iterable,
but can be indexed (see issue #14655).
"""
def flat_indexes(elems):
for n, el in enumerate(elems):
if iterable(el):
for ndeep in flat_indexes(el):
yield (n,) + ndeep
else:
yield (n,)
indexed = ', '.join('{}[{}]'.format(rvalue, ']['.join(map(str, ind)))
for ind in flat_indexes(lvalues))
return ['[{}] = [{}]'.format(', '.join(flatten(lvalues)), indexed)]
def _imp_namespace(expr, namespace=None):
""" Return namespace dict with function implementations
We need to search for functions in anything that can be thrown at
us - that is - anything that could be passed as ``expr``. Examples
include SymPy expressions, as well as tuples, lists and dicts that may
contain SymPy expressions.
Parameters
----------
expr : object
Something passed to lambdify, that will generate valid code from
``str(expr)``.
namespace : None or mapping
Namespace to fill. None results in new empty dict
Returns
-------
namespace : dict
dict with keys of implemented function names within ``expr`` and
corresponding values being the numerical implementation of
function
Examples
========
>>> from sympy.abc import x
>>> from sympy.utilities.lambdify import implemented_function, _imp_namespace
>>> from sympy import Function
>>> f = implemented_function(Function('f'), lambda x: x+1)
>>> g = implemented_function(Function('g'), lambda x: x*10)
>>> namespace = _imp_namespace(f(g(x)))
>>> sorted(namespace.keys())
['f', 'g']
"""
# Delayed import to avoid circular imports
from sympy.core.function import FunctionClass
if namespace is None:
namespace = {}
# tuples, lists, dicts are valid expressions
if is_sequence(expr):
for arg in expr:
_imp_namespace(arg, namespace)
return namespace
elif isinstance(expr, dict):
for key, val in expr.items():
# functions can be in dictionary keys
_imp_namespace(key, namespace)
_imp_namespace(val, namespace)
return namespace
# SymPy expressions may be Functions themselves
func = getattr(expr, 'func', None)
if isinstance(func, FunctionClass):
imp = getattr(func, '_imp_', None)
if imp is not None:
name = expr.func.__name__
if name in namespace and namespace[name] != imp:
raise ValueError('We found more than one '
'implementation with name '
'"%s"' % name)
namespace[name] = imp
# and / or they may take Functions as arguments
if hasattr(expr, 'args'):
for arg in expr.args:
_imp_namespace(arg, namespace)
return namespace
def implemented_function(symfunc, implementation):
""" Add numerical ``implementation`` to function ``symfunc``.
``symfunc`` can be an ``UndefinedFunction`` instance, or a name string.
In the latter case we create an ``UndefinedFunction`` instance with that
name.
Be aware that this is a quick workaround, not a general method to create
special symbolic functions. If you want to create a symbolic function to be
used by all the machinery of SymPy you should subclass the ``Function``
class.
Parameters
----------
symfunc : ``str`` or ``UndefinedFunction`` instance
If ``str``, then create new ``UndefinedFunction`` with this as
name. If ``symfunc`` is an Undefined function, create a new function
with the same name and the implemented function attached.
implementation : callable
numerical implementation to be called by ``evalf()`` or ``lambdify``
Returns
-------
afunc : sympy.FunctionClass instance
function with attached implementation
Examples
========
>>> from sympy.abc import x
>>> from sympy.utilities.lambdify import implemented_function
>>> from sympy import lambdify
>>> f = implemented_function('f', lambda x: x+1)
>>> lam_f = lambdify(x, f(x))
>>> lam_f(4)
5
"""
# Delayed import to avoid circular imports
from sympy.core.function import UndefinedFunction
# if name, create function to hold implementation
kwargs = {}
if isinstance(symfunc, UndefinedFunction):
kwargs = symfunc._kwargs
symfunc = symfunc.__name__
if isinstance(symfunc, str):
# Keyword arguments to UndefinedFunction are added as attributes to
# the created class.
symfunc = UndefinedFunction(
symfunc, _imp_=staticmethod(implementation), **kwargs)
elif not isinstance(symfunc, UndefinedFunction):
raise ValueError(filldedent('''
symfunc should be either a string or
an UndefinedFunction instance.'''))
return symfunc
def _too_large_for_docstring(expr, limit):
"""Decide whether an ``Expr`` is too large to be fully rendered in a
``lambdify`` docstring.
This is a fast alternative to ``count_ops``, which can become prohibitively
slow for large expressions, because in this instance we only care whether
``limit`` is exceeded rather than counting the exact number of nodes in the
expression.
Parameters
==========
expr : ``Expr``, (nested) ``list`` of ``Expr``, or ``Matrix``
The same objects that can be passed to the ``expr`` argument of
``lambdify``.
limit : ``int`` or ``None``
The threshold above which an expression contains too many nodes to be
usefully rendered in the docstring. If ``None`` then there is no limit.
Returns
=======
bool
``True`` if the number of nodes in the expression exceeds the limit,
``False`` otherwise.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.utilities.lambdify import _too_large_for_docstring
>>> expr = x
>>> _too_large_for_docstring(expr, None)
False
>>> _too_large_for_docstring(expr, 100)
False
>>> _too_large_for_docstring(expr, 1)
False
>>> _too_large_for_docstring(expr, 0)
True
>>> _too_large_for_docstring(expr, -1)
True
Does this split it?
>>> expr = [x, y, z]
>>> _too_large_for_docstring(expr, None)
False
>>> _too_large_for_docstring(expr, 100)
False
>>> _too_large_for_docstring(expr, 1)
True
>>> _too_large_for_docstring(expr, 0)
True
>>> _too_large_for_docstring(expr, -1)
True
>>> expr = [x, [y], z, [[x+y], [x*y*z, [x+y+z]]]]
>>> _too_large_for_docstring(expr, None)
False
>>> _too_large_for_docstring(expr, 100)
False
>>> _too_large_for_docstring(expr, 1)
True
>>> _too_large_for_docstring(expr, 0)
True
>>> _too_large_for_docstring(expr, -1)
True
>>> expr = ((x + y + z)**5).expand()
>>> _too_large_for_docstring(expr, None)
False
>>> _too_large_for_docstring(expr, 100)
True
>>> _too_large_for_docstring(expr, 1)
True
>>> _too_large_for_docstring(expr, 0)
True
>>> _too_large_for_docstring(expr, -1)
True
>>> from sympy import Matrix
>>> expr = Matrix([[(x + y + z), ((x + y + z)**2).expand(),
... ((x + y + z)**3).expand(), ((x + y + z)**4).expand()]])
>>> _too_large_for_docstring(expr, None)
False
>>> _too_large_for_docstring(expr, 1000)
False
>>> _too_large_for_docstring(expr, 100)
True
>>> _too_large_for_docstring(expr, 1)
True
>>> _too_large_for_docstring(expr, 0)
True
>>> _too_large_for_docstring(expr, -1)
True
"""
# Must be imported here to avoid a circular import error
from sympy.core.traversal import postorder_traversal
if limit is None:
return False
for i, _ in enumerate(postorder_traversal(expr), 1):
if i > limit:
return True
return False
|
_TensorflowEvaluatorPrinter
|
python
|
sqlalchemy__sqlalchemy
|
lib/sqlalchemy/sql/base.py
|
{
"start": 83570,
"end": 84559
}
|
class ____(
util.ReadOnlyContainer, ColumnCollection[_COLKEY, _COL_co]
):
__slots__ = ("_parent",)
def __init__(self, collection: ColumnCollection[_COLKEY, _COL_co]):
object.__setattr__(self, "_parent", collection)
object.__setattr__(self, "_colset", collection._colset)
object.__setattr__(self, "_index", collection._index)
object.__setattr__(self, "_collection", collection._collection)
object.__setattr__(self, "_proxy_index", collection._proxy_index)
def __getstate__(self) -> Dict[str, _COL_co]:
return {"_parent": self._parent}
def __setstate__(self, state: Dict[str, Any]) -> None:
parent = state["_parent"]
self.__init__(parent) # type: ignore
def add(self, column: Any, key: Any = ...) -> Any:
self._readonly()
def extend(self, elements: Any) -> NoReturn:
self._readonly()
def remove(self, item: Any) -> NoReturn:
self._readonly()
|
ReadOnlyColumnCollection
|
python
|
encode__django-rest-framework
|
rest_framework/fields.py
|
{
"start": 27213,
"end": 27521
}
|
class ____(CharField):
default_error_messages = {
'invalid': _('Enter a valid email address.')
}
def __init__(self, **kwargs):
super().__init__(**kwargs)
validator = EmailValidator(message=self.error_messages['invalid'])
self.validators.append(validator)
|
EmailField
|
python
|
doocs__leetcode
|
solution/0800-0899/0859.Buddy Strings/Solution.py
|
{
"start": 0,
"end": 377
}
|
class ____:
def buddyStrings(self, s: str, goal: str) -> bool:
m, n = len(s), len(goal)
if m != n:
return False
cnt1, cnt2 = Counter(s), Counter(goal)
if cnt1 != cnt2:
return False
diff = sum(s[i] != goal[i] for i in range(n))
return diff == 2 or (diff == 0 and any(v > 1 for v in cnt1.values()))
|
Solution
|
python
|
huggingface__transformers
|
src/transformers/models/udop/modeling_udop.py
|
{
"start": 43111,
"end": 43949
}
|
class ____(RelativePositionBiasBase):
def __init__(self, scaling_factor=1, max_distance=128, **kwargs):
"""
Reimplementation of T5 relative position bias. Distance between given tokens is their distance in the sequence.
Parameters are the same as in base class
"""
super().__init__(scaling_factor=scaling_factor, max_distance=max_distance, **kwargs)
def prepare_input(self, attention_mask: Optional[Tensor] = None, bbox: Optional[dict[str, Any]] = None) -> Tensor:
if self.scaling_factor != 1:
raise ValueError("No need to scale 1d features")
relative_position = self.get_relative_position(
torch.arange(attention_mask.size(1), dtype=torch.long, device=attention_mask.device)[None, :]
)
return relative_position
|
RelativePositionBias1D
|
python
|
pandas-dev__pandas
|
asv_bench/benchmarks/rolling.py
|
{
"start": 9162,
"end": 9975
}
|
class ____:
params = (
["sum", "median", "mean", "max", "min", "kurt", "sum"],
[
("rolling", {"window": 2}),
("rolling", {"window": "30s"}),
("expanding", {}),
],
)
def setup(self, method, window_kwargs):
N = 1000
window, kwargs = window_kwargs
df = pd.DataFrame(
{
"A": [str(i) for i in range(N)] * 10,
"B": list(range(N)) * 10,
}
)
if isinstance(kwargs.get("window", None), str):
df.index = pd.date_range(start="1900-01-01", freq="1min", periods=N * 10)
self.groupby_window = getattr(df.groupby("A"), window)(**kwargs)
def time_method(self, method, window_kwargs):
getattr(self.groupby_window, method)()
|
Groupby
|
python
|
apache__airflow
|
providers/standard/tests/unit/standard/operators/test_python.py
|
{
"start": 39972,
"end": 49140
}
|
class ____(BasePythonTest):
def test_template_fields(self):
assert set(PythonOperator.template_fields).issubset(PythonVirtualenvOperator.template_fields)
def test_fail(self):
def f():
raise RuntimeError
with pytest.raises(CalledProcessError):
self.run_as_task(f)
def test_fail_with_message(self):
def f():
raise RuntimeError("Custom error message")
with pytest.raises(AirflowException, match="Custom error message"):
self.run_as_task(f)
def test_string_args(self):
def f():
print(virtualenv_string_args)
if virtualenv_string_args[0] != virtualenv_string_args[2]:
raise RuntimeError
self.run_as_task(f, string_args=[1, 2, 1])
def test_with_args(self):
def f(a, b, c=False, d=False):
if a == 0 and b == 1 and c and not d:
return True
raise RuntimeError
self.run_as_task(f, op_args=[0, 1], op_kwargs={"c": True})
def test_return_none(self):
def f():
return None
ti = self.run_as_task(f, return_ti=True)
assert ti.xcom_pull() is None
def test_return_false(self):
def f():
return False
ti = self.run_as_task(f, return_ti=True)
assert ti.xcom_pull() is False
def test_lambda(self):
with pytest.raises(
ValueError, match="PythonVirtualenvOperator only supports functions for python_callable arg"
):
PythonVirtualenvOperator(python_callable=lambda x: 4, task_id=self.task_id)
def test_nonimported_as_arg(self):
def f(_):
return None
self.run_as_task(f, op_args=[datetime.now(tz=_timezone.utc)])
def test_context(self):
def f(templates_dict):
return templates_dict["ds"]
task = self.run_as_task(f, templates_dict={"ds": "{{ ds }}"})
assert task.templates_dict == {"ds": self.ds_templated}
@pytest.mark.parametrize(
"serializer",
[
pytest.param("pickle", id="pickle"),
pytest.param("dill", marks=DILL_MARKER, id="dill"),
pytest.param("cloudpickle", marks=CLOUDPICKLE_MARKER, id="cloudpickle"),
pytest.param(None, id="default"),
],
)
def test_deepcopy(self, serializer):
"""Test that operator are deep-copyable."""
def f():
return 1
op = self.opcls(task_id="task", python_callable=f, **self.default_kwargs())
copy.deepcopy(op)
def test_virtualenv_serializable_context_fields(self, create_task_instance):
"""Ensure all template context fields are listed in the operator.
This exists mainly so when a field is added to the context, we remember to
also add it to PythonVirtualenvOperator.
"""
# These are intentionally NOT serialized into the virtual environment:
# * Variables pointing to the task instance itself.
# * Variables that are accessor instances.
intentionally_excluded_context_keys = {
"task_instance",
"ti",
"var", # Accessor for Variable; var->json and var->value.
"conn", # Accessor for Connection.
"map_index_template",
}
intentionally_excluded_context_keys |= {
"inlet_events",
"outlet_events",
}
ti = create_task_instance(dag_id=self.dag_id, task_id=self.task_id, schedule=None)
context = ti.get_template_context()
declared_keys = {
*PythonVirtualenvOperator.BASE_SERIALIZABLE_CONTEXT_KEYS,
*PythonVirtualenvOperator.PENDULUM_SERIALIZABLE_CONTEXT_KEYS,
*PythonVirtualenvOperator.AIRFLOW_SERIALIZABLE_CONTEXT_KEYS,
*intentionally_excluded_context_keys,
}
if AIRFLOW_V_3_0_PLUS:
declared_keys -= {
"execution_date",
"next_ds",
"next_ds_nodash",
"prev_ds",
"prev_ds_nodash",
"tomorrow_ds",
"tomorrow_ds_nodash",
"triggering_dataset_events",
"yesterday_ds",
"yesterday_ds_nodash",
"next_execution_date",
"prev_execution_date",
"prev_execution_date_success",
"conf",
"expanded_ti_count",
}
else:
declared_keys.remove("triggering_asset_events")
assert set(context) == declared_keys
@pytest.mark.parametrize(
("kwargs", "actual_exit_code", "expected_state"),
[
({}, 0, TaskInstanceState.SUCCESS),
({}, 100, TaskInstanceState.FAILED),
({}, 101, TaskInstanceState.FAILED),
({"skip_on_exit_code": None}, 0, TaskInstanceState.SUCCESS),
({"skip_on_exit_code": None}, 100, TaskInstanceState.FAILED),
({"skip_on_exit_code": None}, 101, TaskInstanceState.FAILED),
({"skip_on_exit_code": 100}, 0, TaskInstanceState.SUCCESS),
({"skip_on_exit_code": 100}, 100, TaskInstanceState.SKIPPED),
({"skip_on_exit_code": 100}, 101, TaskInstanceState.FAILED),
({"skip_on_exit_code": 0}, 0, TaskInstanceState.SKIPPED),
({"skip_on_exit_code": [100]}, 0, TaskInstanceState.SUCCESS),
({"skip_on_exit_code": [100]}, 100, TaskInstanceState.SKIPPED),
({"skip_on_exit_code": [100]}, 101, TaskInstanceState.FAILED),
({"skip_on_exit_code": [100, 102]}, 101, TaskInstanceState.FAILED),
({"skip_on_exit_code": (100,)}, 0, TaskInstanceState.SUCCESS),
({"skip_on_exit_code": (100,)}, 100, TaskInstanceState.SKIPPED),
({"skip_on_exit_code": (100,)}, 101, TaskInstanceState.FAILED),
],
)
def test_on_skip_exit_code(self, kwargs, actual_exit_code, expected_state):
def f(exit_code):
if exit_code != 0:
raise SystemExit(exit_code)
if expected_state == TaskInstanceState.FAILED:
with pytest.raises(CalledProcessError):
self.run_as_task(f, op_kwargs={"exit_code": actual_exit_code}, **kwargs)
else:
ti = self.run_as_task(
f,
return_ti=True,
op_kwargs={"exit_code": actual_exit_code},
**kwargs,
)
assert ti.state == expected_state
@pytest.mark.parametrize(
"serializer",
[
pytest.param(
"dill",
marks=pytest.mark.skipif(
DILL_INSTALLED, reason="For this test case `dill` shouldn't be installed"
),
id="dill",
),
pytest.param(
"cloudpickle",
marks=pytest.mark.skipif(
CLOUDPICKLE_INSTALLED, reason="For this test case `cloudpickle` shouldn't be installed"
),
id="cloudpickle",
),
],
)
def test_advanced_serializer_not_installed(self, serializer, caplog):
"""Test case for check raising an error if dill/cloudpickle is not installed."""
def f(a): ...
with pytest.raises(ModuleNotFoundError):
self.run_as_task(f, op_args=[42], serializer=serializer)
assert f"Unable to import `{serializer}` module." in caplog.text
def test_environment_variables(self):
def f():
import os
return os.environ["MY_ENV_VAR"]
ti = self.run_as_task(f, env_vars={"MY_ENV_VAR": "ABCDE"}, return_ti=True)
assert ti.xcom_pull() == "ABCDE"
def test_environment_variables_with_inherit_env_true(self, monkeypatch):
monkeypatch.setenv("MY_ENV_VAR", "QWERT")
def f():
import os
return os.environ["MY_ENV_VAR"]
ti = self.run_as_task(f, inherit_env=True, return_ti=True)
assert ti.xcom_pull() == "QWERT"
def test_environment_variables_with_inherit_env_false(self, monkeypatch):
monkeypatch.setenv("MY_ENV_VAR", "TYUIO")
def f():
import os
return os.environ["MY_ENV_VAR"]
with pytest.raises(AirflowException):
self.run_as_task(f, inherit_env=False)
def test_environment_variables_overriding(self, monkeypatch):
monkeypatch.setenv("MY_ENV_VAR", "ABCDE")
def f():
import os
return os.environ["MY_ENV_VAR"]
ti = self.run_as_task(f, env_vars={"MY_ENV_VAR": "EFGHI"}, inherit_env=True, return_ti=True)
assert ti.xcom_pull() == "EFGHI"
venv_cache_path = tempfile.mkdtemp(prefix="venv_cache_path")
# when venv tests are run in parallel to other test they create new processes and this might take
# quite some time in shared docker environment and get some contention even between different containers
# therefore we have to extend timeouts for those tests
@pytest.mark.execution_timeout(120)
@pytest.mark.virtualenv_operator
|
BaseTestPythonVirtualenvOperator
|
python
|
nedbat__coveragepy
|
tests/test_api.py
|
{
"start": 41557,
"end": 44641
}
|
class ____(CoverageTest):
"""Test that the API works properly the way various third-party plugins call it.
We don't actually use the plugins, but these tests call the API the same
way they do.
"""
def pretend_to_be_nose_with_cover(self, erase: bool = False, cd: bool = False) -> None:
"""This is what the nose --with-cover plugin does."""
self.make_file(
"no_biggie.py",
"""\
a = 1
b = 2
if b == 1:
c = 4
""",
)
self.make_file("sub/hold.txt", "")
cov = coverage.Coverage()
if erase:
cov.combine()
cov.erase()
cov.load()
self.start_import_stop(cov, "no_biggie")
if cd:
os.chdir("sub")
cov.combine()
cov.save()
cov.report(["no_biggie.py"], show_missing=True)
assert self.stdout() == textwrap.dedent("""\
Name Stmts Miss Cover Missing
--------------------------------------------
no_biggie.py 4 1 75% 4
--------------------------------------------
TOTAL 4 1 75%
""")
if cd:
os.chdir("..")
def test_nose_plugin(self) -> None:
self.pretend_to_be_nose_with_cover()
def test_nose_plugin_with_erase(self) -> None:
self.pretend_to_be_nose_with_cover(erase=True)
def test_nose_plugin_with_cd(self) -> None:
# https://github.com/coveragepy/coveragepy/issues/916
self.pretend_to_be_nose_with_cover(cd=True)
def pretend_to_be_pytestcov(self, append: bool) -> None:
"""Act like pytest-cov."""
self.make_file(
"prog.py",
"""\
a = 1
b = 2
if b == 1:
c = 4
""",
)
self.make_file(
".coveragerc",
"""\
[run]
parallel = True
source = .
""",
)
cov = coverage.Coverage(source=None, branch=None, config_file=".coveragerc")
if append:
cov.load()
else:
cov.erase()
self.start_import_stop(cov, "prog")
cov.combine()
cov.save()
report = io.StringIO()
cov.report(
show_missing=None, ignore_errors=True, file=report, skip_covered=None, skip_empty=None
)
assert report.getvalue() == textwrap.dedent("""\
Name Stmts Miss Cover
-----------------------------
prog.py 4 1 75%
-----------------------------
TOTAL 4 1 75%
""")
self.assert_file_count(".coverage", 0)
self.assert_file_count(".coverage.*", 1)
def test_pytestcov_parallel(self) -> None:
self.pretend_to_be_pytestcov(append=False)
def test_pytestcov_parallel_append(self) -> None:
self.pretend_to_be_pytestcov(append=True)
|
TestRunnerPluginTest
|
python
|
google__jax
|
tests/pmap_test.py
|
{
"start": 128202,
"end": 129110
}
|
class ____(EagerPmapMixin, PythonPmapTest):
def test_custom_jvp(self):
@jax.custom_jvp
def foo(x):
return jnp.exp(x)
@foo.defjvp
def foo_jvp(xs, ts):
(x,), (t,) = xs, ts
return foo(x), t * 4.
f = lambda x, t: jax.jvp(foo, (x,), (t,))
x = jnp.arange(
jax.local_device_count() * 5, dtype=jnp.dtype('float32')).reshape((
jax.local_device_count(), 5))
self.assertAllClose(self.pmap(f)(x, x), jax.vmap(f)(x, x))
def test_custom_vjp(self):
@jax.custom_vjp
def foo(x):
return jnp.exp(x)
def foo_fwd(x):
return foo(x), x
def foo_bwd(_, g):
return (g * 5.,)
foo.defvjp(foo_fwd, foo_bwd)
f = jax.grad(foo)
x = jnp.arange(jax.local_device_count(), dtype=jnp.dtype('float32'))
self.assertAllClose(self.pmap(f)(x), jax.vmap(f)(x))
@jtu.pytest_mark_if_available('multiaccelerator')
|
PythonPmapEagerTest
|
python
|
getsentry__sentry
|
src/sentry/issues/grouptype.py
|
{
"start": 16321,
"end": 16695
}
|
class ____(GroupType):
type_id = 1015
slug = "performance_large_http_payload"
description = "Large HTTP payload"
category = GroupCategory.PERFORMANCE.value
category_v2 = GroupCategory.HTTP_CLIENT.value
noise_config = NoiseConfig()
default_priority = PriorityLevel.LOW
released = True
@dataclass(frozen=True)
|
PerformanceLargeHTTPPayloadGroupType
|
python
|
Netflix__metaflow
|
metaflow/packaging_sys/v1.py
|
{
"start": 805,
"end": 23139
}
|
class ____(MetaflowCodeContentV1Base):
METAFLOW_SUFFIXES_LIST = [".py", ".html", ".css", ".js"]
def __init__(
self,
code_dir: str = MetaflowCodeContentV1Base._code_dir,
other_dir: str = MetaflowCodeContentV1Base._other_dir,
criteria: Callable[[ModuleType], bool] = lambda x: True,
):
super().__init__(code_dir, other_dir)
self._metaflow_root = get_metaflow_root()
self._metaflow_version = get_version()
self._criteria = criteria
# We try to find the modules we need to package. We will first look at all modules
# and apply the criteria to them. Then we will use the most parent module that
# fits the criteria as the module to package
# Make a copy since sys.modules could be modified while we load other
# modules. See https://github.com/Netflix/metaflow/issues/2489
all_modules = dict(sys.modules)
modules = filter(lambda x: criteria(x[1]), all_modules.items())
# Ensure that we see the parent modules first
modules = sorted(modules, key=lambda x: x[0])
if modules:
last_prefix = modules[0][0]
new_modules = [modules[0]]
for name, mod in modules[1:]:
if name.startswith(last_prefix + "."):
# This is a submodule of the last module, we can skip it
continue
# Otherwise, we have a new top-level module
last_prefix = name
new_modules.append((name, mod))
else:
new_modules = []
self._modules = {} # type: Dict[str, _ModuleInfo]
# We do this explicitly module by module to harden it against misbehaving
# modules like the one in:
# https://github.com/Netflix/metaflow/issues/2512
# We will silently ignore modules that are not well built.
for name, mod in new_modules:
try:
minfo = _ModuleInfo(
name,
set(
Path(p).resolve().as_posix()
for p in getattr(mod, "__path__", [mod.__file__])
),
mod,
True, # This is a Metaflow module (see filter below)
)
except:
continue
self._modules[name] = minfo
# Contain metadata information regarding the distributions packaged.
# This allows Metaflow to "fake" distribution information when packaged
self._distmetainfo = {} # type: Dict[str, Dict[str, str]]
# Maps an absolute path on the filesystem to the path of the file in the
# archive.
self._files = {} # type: Dict[str, str]
self._files_from_modules = {} # type: Dict[str, str]
self._other_files = {} # type: Dict[str, str]
self._other_content = {} # type: Dict[str, bytes]
debug.package_exec(f"Used system modules found: {str(self._modules)}")
# Populate with files from the third party modules
for k, v in self._modules.items():
self._files_from_modules.update(self._module_files(k, v.root_paths))
# Figure out the files to package for Metaflow and extensions
self._cached_metaflow_files = list(self._metaflow_distribution_files())
self._cached_metaflow_files.extend(list(self._metaflow_extension_files()))
def create_mfcontent_info(self) -> Dict[str, Any]:
return {"version": 1, "module_files": list(self._files_from_modules.values())}
def get_excluded_tl_entries(self) -> List[str]:
"""
When packaging Metaflow from within an executing Metaflow flow, we need to
exclude the files that are inserted by this content from being packaged (possibly).
Use this function to return these files or top-level directories.
Returns
-------
List[str]
Files or directories to exclude
"""
return [self._code_dir, self._other_dir]
def content_names(
self, content_types: Optional[int] = None
) -> Generator[Tuple[str, str], None, None]:
"""
Detailed list of the content of this MetaflowCodeContent. This will list all files
(or non files -- for the INFO or CONFIG data for example) present in the archive.
Parameters
----------
content_types : Optional[int]
The type of content to get the names of. If None, all content is returned.
Yields
------
Generator[Tuple[str, str], None, None]
Path on the filesystem and the name in the archive
"""
yield from self._content(content_types, generate_value=False)
def contents(
self, content_types: Optional[int] = None
) -> Generator[Tuple[Union[bytes, str], str], None, None]:
"""
Very similar to content_names but returns the content of the non-files
as well as bytes. For files, identical output as content_names
Parameters
----------
content_types : Optional[int]
The type of content to get the content of. If None, all content is returned.
Yields
------
Generator[Tuple[Union[str, bytes], str], None, None]
Content of the MF content
"""
yield from self._content(content_types, generate_value=True)
def show(self) -> str:
"""
Returns a more human-readable string representation of the content of this
MetaflowCodeContent. This will not, for example, list all files but summarize what
is included at a more high level.
Returns
-------
str
A human-readable string representation of the content of this MetaflowCodeContent
"""
all_user_step_decorators = {}
for k, v in UserStepDecoratorMeta.all_decorators().items():
all_user_step_decorators.setdefault(
getattr(v, "_original_module", v.__module__), []
).append(k)
all_user_flow_decorators = {}
for k, v in FlowMutatorMeta.all_decorators().items():
all_user_flow_decorators.setdefault(
getattr(v, "_original_module", v.__module__), []
).append(k)
result = []
if self._metaflow_version:
result.append(f"\nMetaflow version: {self._metaflow_version}")
ext_info = extension_info()
if ext_info["installed"]:
result.append("\nMetaflow extensions packaged:")
for ext_name, ext_info in ext_info["installed"].items():
result.append(
f" - {ext_name} ({ext_info['extension_name']}) @ {ext_info['dist_version']}"
)
if self._modules:
mf_modules = []
other_modules = []
for name, info in self._modules.items():
if info.metaflow_module:
mf_modules.append(f" - {name} @ {', '.join(info.root_paths)}")
module_user_step_decorators = [
", ".join(v)
for k, v in all_user_step_decorators.items()
if k == info.name or k.startswith(info.name + ".")
]
module_user_flow_decorators = [
", ".join(v)
for k, v in all_user_flow_decorators.items()
if k == info.name or k.startswith(info.name + ".")
]
if module_user_step_decorators:
mf_modules.append(
f" - Provides step decorators: {', '.join(module_user_step_decorators)}"
)
if module_user_flow_decorators:
mf_modules.append(
f" - Provides flow mutators: {', '.join(module_user_flow_decorators)}"
)
else:
other_modules.append(f" - {name} @ {', '.join(info.root_paths)}")
if mf_modules:
result.append("\nMetaflow modules:")
result.extend(mf_modules)
if other_modules:
result.append("\nNon-Metaflow packaged modules:")
result.extend(other_modules)
return "\n".join(result)
def add_info(self, info: Dict[str, Any]) -> None:
"""
Add the content of the INFO file to the Metaflow content
Parameters
----------
info: Dict[str, Any]
The content of the INFO file
"""
info_file_path = os.path.join(self._other_dir, self._info_file)
if info_file_path in self._other_content:
raise MetaflowException("INFO file already present in the MF environment")
self._other_content[info_file_path] = json.dumps(info).encode("utf-8")
def add_config(self, config: Dict[str, Any]) -> None:
"""
Add the content of the CONFIG file to the Metaflow content
Parameters
----------
config: Dict[str, Any]
The content of the CONFIG file
"""
config_file_path = os.path.join(self._other_dir, self._config_file)
if config_file_path in self._other_content:
raise MetaflowException("CONFIG file already present in the MF environment")
self._other_content[config_file_path] = json.dumps(config).encode("utf-8")
def add_module(self, module: ModuleType) -> None:
"""
Add a python module to the Metaflow content
Parameters
----------
module_path: ModuleType
The module to add
"""
name = module.__name__
debug.package_exec(f"Adding module {name} to the MF content")
# If the module is a single file, we handle this here by looking at __file__
# which will point to the single file. If it is an actual module, __path__
# will contain the path(s) to the module
if hasattr(module, "__file__") and module.__file__:
root_paths = [Path(module.__file__).resolve().as_posix()]
else:
root_paths = []
seen_path_values = set()
new_paths = module.__spec__.submodule_search_locations
while new_paths:
paths = new_paths
new_paths = []
for p in paths:
if p in seen_path_values:
continue
if os.path.isdir(p):
root_paths.append(Path(p).resolve().as_posix())
elif p in sys.path_importer_cache:
# We have a path hook that we likely need to call to get the actual path
addl_spec = sys.path_importer_cache[p].find_spec(name)
if (
addl_spec is not None
and addl_spec.submodule_search_locations
):
new_paths.extend(addl_spec.submodule_search_locations)
else:
# This may not be as required since it is likely the importer cache has
# everything already but just in case, we will also go through the
# path hooks and see if we find another one
for path_hook in sys.path_hooks:
try:
finder = path_hook(p)
addl_spec = finder.find_spec(name)
if (
addl_spec is not None
and addl_spec.submodule_search_locations
):
new_paths.extend(
addl_spec.submodule_search_locations
)
break
except ImportError:
continue
seen_path_values.add(p)
self._modules[name] = _ModuleInfo(
name,
set(root_paths),
module,
False, # This is not a Metaflow module (added by the user manually)
)
self._files_from_modules.update(
self._module_files(name, self._modules[name].root_paths)
)
def add_code_file(self, file_path: str, file_name: str) -> None:
"""
Add a code file to the Metaflow content
Parameters
----------
file_path: str
The path to the code file to add (on the filesystem)
file_name: str
The path in the archive to add the code file to
"""
file_path = os.path.realpath(file_path)
debug.package_exec(
f"Adding code file {file_path} as {file_name} to the MF content"
)
if file_path in self._files and self._files[file_path] != os.path.join(
self._code_dir, file_name.lstrip("/")
):
raise MetaflowException(
"File '%s' is already present in the MF content with a different name: '%s'"
% (file_path, self._files[file_path])
)
self._files[file_path] = os.path.join(self._code_dir, file_name.lstrip("/"))
def add_other_file(self, file_path: str, file_name: str) -> None:
"""
Add a non-python file to the Metaflow content
Parameters
----------
file_path: str
The path to the file to add (on the filesystem)
file_name: str
The path in the archive to add the file to
"""
file_path = os.path.realpath(file_path)
debug.package_exec(
f"Adding other file {file_path} as {file_name} to the MF content"
)
if file_path in self._other_files and self._other_files[
file_path
] != os.path.join(self._other_dir, file_name.lstrip("/")):
raise MetaflowException(
"File %s is already present in the MF content with a different name: %s"
% (file_path, self._other_files[file_path])
)
self._other_files[file_path] = os.path.join(
self._other_dir, file_name.lstrip("/")
)
def _content(
self, content_types: Optional[int] = None, generate_value: bool = False
) -> Generator[Tuple[Union[str, bytes], str], None, None]:
from ..package import MetaflowPackage # Prevent circular dependency
if content_types is None:
content_types = ContentType.ALL_CONTENT.value
if content_types & ContentType.CODE_CONTENT.value:
yield from self._cached_metaflow_files
yield from self._files.items()
if content_types & ContentType.MODULE_CONTENT.value:
yield from self._files_from_modules.items()
if content_types & ContentType.OTHER_CONTENT.value:
yield from self._other_files.items()
if generate_value:
for k, v in self._other_content.items():
yield v, k
# Include the distribution file too
yield json.dumps(self._distmetainfo).encode("utf-8"), os.path.join(
self._other_dir, self._dist_info_file
)
yield json.dumps(self.create_mfcontent_info()).encode(
"utf-8"
), MFCONTENT_MARKER
else:
for k in self._other_content.keys():
yield "<generated %s content>" % (os.path.basename(k)), k
yield "<generated %s content>" % (
os.path.basename(self._dist_info_file)
), os.path.join(self._other_dir, self._dist_info_file)
yield "<generated %s content>" % MFCONTENT_MARKER, MFCONTENT_MARKER
def _metaflow_distribution_files(self) -> Generator[Tuple[str, str], None, None]:
debug.package_exec("Including Metaflow from '%s'" % self._metaflow_root)
for path_tuple in walk(
os.path.join(self._metaflow_root, "metaflow"),
exclude_hidden=False,
file_filter=suffix_filter(self.METAFLOW_SUFFIXES_LIST),
):
yield path_tuple[0], os.path.join(self._code_dir, path_tuple[1])
def _metaflow_extension_files(self) -> Generator[Tuple[str, str], None, None]:
# Metaflow extensions; for now, we package *all* extensions but this may change
# at a later date; it is possible to call `package_mfext_package` instead of
# `package_mfext_all` but in that case, make sure to also add a
# metaflow_extensions/__init__.py file to properly "close" the metaflow_extensions
# package and prevent other extensions from being loaded that may be
# present in the rest of the system
for path_tuple in package_mfext_all():
yield path_tuple[0], os.path.join(self._code_dir, path_tuple[1])
if debug.package:
ext_info = package_mfext_all_descriptions()
ext_info = {
k: {k1: v1 for k1, v1 in v.items() if k1 in ("root_paths",)}
for k, v in ext_info.items()
}
debug.package_exec(f"Metaflow extensions packaged: {ext_info}")
def _module_files(
self, name: str, paths: Set[str]
) -> Generator[Tuple[str, str], None, None]:
debug.package_exec(
" Looking for distributions for module %s in %s" % (name, paths)
)
paths = set(paths) # Do not modify external paths
has_init = False
distributions = modules_to_distributions().get(name)
prefix_parts = tuple(name.split("."))
seen_distributions = set()
if distributions:
for dist in distributions:
dist_name = dist.metadata["Name"] # dist.name not always present
if dist_name in seen_distributions:
continue
# For some reason, sometimes the same distribution appears twice. We
# don't need to process twice.
seen_distributions.add(dist_name)
debug.package_exec(
" Including distribution '%s' for module '%s'"
% (dist_name, name)
)
dist_root = str(dist.locate_file(name))
has_file_in_root = False
if dist_name not in self._distmetainfo:
# Possible that a distribution contributes to multiple modules
self._distmetainfo[dist_name] = {
# We can add more if needed but these are likely the most
# useful (captures, name, version, etc and files which can
# be used to find non-python files in the distribution).
"METADATA": dist.read_text("METADATA") or "",
"RECORD": dist.read_text("RECORD") or "",
}
for file in dist.files or []:
# Skip files that do not belong to this module (distribution may
# provide multiple modules)
if (
file.parts[: len(prefix_parts)] != prefix_parts
or file.suffix == ".pth"
or str(file).startswith("__editable__")
):
continue
if file.parts[len(prefix_parts)] == "__init__.py":
has_init = True
has_file_in_root = True
# At this point, we know that we are seeing actual files in the
# dist_root so we make sure it is as expected
if dist_root not in paths:
# This is an error because it means that this distribution is
# not contributing to the module.
raise RuntimeError(
"Distribution '%s' is not contributing to module '%s' as "
"expected (got '%s' when expected one of %s)"
% (dist.metadata["Name"], name, dist_root, paths)
)
yield str(
dist.locate_file(file).resolve().as_posix()
), os.path.join(self._code_dir, *prefix_parts, *file.parts[1:])
if has_file_in_root:
paths.discard(dist_root)
# Now if there are more paths left in paths, it means there is a non-distribution
# component to this package which we also include.
debug.package_exec(
" Looking for non-distribution files for module '%s' in %s"
% (name, paths)
)
for path in paths:
if not Path(path).is_dir():
# Single file for the module -- this will be something like <name>.py
yield path, os.path.join(
self._code_dir, *prefix_parts[:-1], f"{prefix_parts[-1]}.py"
)
has_init = True
else:
for root, _, files in walk_without_cycles(path):
for file in files:
if any(file.endswith(x) for x in EXT_EXCLUDE_SUFFIXES):
continue
rel_path = os.path.relpath(os.path.join(root, file), path)
if rel_path == "__init__.py":
has_init = True
yield os.path.join(root, file), os.path.join(
self._code_dir,
name,
rel_path,
)
# We now include an empty __init__.py file to close the module and prevent
# leaks from possible namespace packages
if not has_init:
yield os.path.join(
self._metaflow_root, "metaflow", "extension_support", "_empty_file.py"
), os.path.join(self._code_dir, *prefix_parts, "__init__.py")
|
MetaflowCodeContentV1
|
python
|
google__jax
|
jax/_src/pallas/triton/lowering.py
|
{
"start": 20609,
"end": 21841
}
|
class ____:
arg_types: Sequence[jax.typing.DTypeLike]
symbol: str
result_type: str
def matches(self, avals: Sequence[jax_core.ShapedArray]) -> bool:
if len(avals) != len(self.arg_types):
return False
return all(
aval.dtype == jnp.dtype(arg_type)
or (aval.weak_type and aval.dtype.kind == jnp.dtype(arg_type).kind)
for aval, arg_type in zip(avals, self.arg_types)
)
def lower(self, ctx: LoweringRuleContext, *args: Sequence[ir.Value]):
[out_aval] = ctx.avals_out
bcast_args = []
for aval, arg, arg_type in zip(ctx.avals_in, args, self.arg_types):
bcast_arg = _bcast_to(_ensure_ir_value(arg, aval), out_aval.shape)
if aval.weak_type and aval.dtype != jnp.dtype(arg_type):
bcast_arg = _cast(bcast_arg, aval.dtype, jnp.dtype(arg_type))
bcast_args.append(bcast_arg)
result_type = _dtype_to_ir_type(jnp.dtype(self.result_type))
if out_aval.shape:
result_type = ir.RankedTensorType.get(out_aval.shape, result_type)
return tt_dialect.extern_elementwise(
result_type,
bcast_args,
libname="",
libpath="",
symbol=self.symbol,
pure=True,
)
@dataclasses.dataclass(frozen=True)
|
_Extern
|
python
|
pypa__warehouse
|
tests/unit/accounts/test_views.py
|
{
"start": 3948,
"end": 6906
}
|
class ____:
def test_user_redirects_username(self, db_request):
user = UserFactory.create()
db_request.current_route_path = pretend.call_recorder(
lambda username: "/user/the-redirect/"
)
# Intentionally swap the case of the username to trigger the redirect
db_request.matchdict = {"username": user.username.swapcase()}
result = views.profile(user, db_request)
assert isinstance(result, HTTPMovedPermanently)
assert result.headers["Location"] == "/user/the-redirect/"
assert db_request.current_route_path.calls == [
pretend.call(username=user.username)
]
def test_returns_user(self, db_request):
user = UserFactory.create()
assert views.profile(user, db_request) == {
"user": user,
"live_projects": [],
"archived_projects": [],
}
def test_user_profile_queries_once_for_all_projects(
self, db_request, query_recorder
):
user = UserFactory.create()
projects = ProjectFactory.create_batch(3)
for project in projects:
# associate the user to each project as role: owner
RoleFactory.create(user=user, project=project)
# Add some releases, with time skew to ensure the ordering is correct
ReleaseFactory.create(
project=project, created=project.created + datetime.timedelta(minutes=1)
)
ReleaseFactory.create(
project=project, created=project.created + datetime.timedelta(minutes=2)
)
# Add a prerelease, shouldn't affect any results
ReleaseFactory.create(
project=project,
created=project.created + datetime.timedelta(minutes=3),
is_prerelease=True,
)
# add one more project, associated to the user, but no releases
RoleFactory.create(user=user, project=ProjectFactory.create())
with query_recorder:
response = views.profile(user, db_request)
assert response["user"] == user
assert len(response["live_projects"]) == 3
# Two queries, one for the user (via context), one for their projects
assert len(query_recorder.queries) == 2
def test_returns_archived_projects(self, db_request):
user = UserFactory.create()
projects = ProjectFactory.create_batch(3)
for project in projects:
RoleFactory.create(user=user, project=project)
ReleaseFactory.create(project=project)
archived_project = ProjectFactory.create(lifecycle_status="archived")
RoleFactory.create(user=user, project=archived_project)
ReleaseFactory.create(project=archived_project)
resp = views.profile(user, db_request)
assert len(resp["live_projects"]) == 3
assert len(resp["archived_projects"]) == 1
|
TestUserProfile
|
python
|
pytorch__pytorch
|
test/quantization/eager/test_fuse_eager.py
|
{
"start": 913,
"end": 23117
}
|
class ____(QuantizationTestCase):
def test_fuse_module_train(self):
model = ModelForFusion(default_qat_qconfig).train()
# Test step by step fusion
model = fuse_modules_qat(model, ["conv1", "bn1", "relu1"])
model = fuse_modules_qat(model, ["sub1.conv", "sub1.bn"])
self.assertEqual(
type(model.conv1),
nni.ConvBnReLU2d,
msg="Fused Conv + BN + Relu first layer",
)
self.assertEqual(
type(model.bn1),
torch.nn.Identity,
msg="Fused Conv + BN + Relu (skipped BN)",
)
self.assertEqual(
type(model.relu1),
torch.nn.Identity,
msg="Fused Conv + BN + Relu (skipped Relu)",
)
self.assertEqual(
type(model.sub1.conv), nni.ConvBn2d, msg="Fused submodule Conv + BN"
)
self.assertEqual(
type(model.sub1.bn),
torch.nn.Identity,
msg="Fused submodule Conv + BN (skipped BN)",
)
self.assertEqual(
type(model.sub2.conv), torch.nn.Conv2d, msg="Non-fused submodule Conv"
)
self.assertEqual(
type(model.sub2.relu), torch.nn.ReLU, msg="Non-fused submodule ReLU"
)
model = prepare_qat(model)
self.checkObservers(model)
def checkQAT(model):
self.assertEqual(type(model.conv1), nniqat.ConvBnReLU2d)
self.assertEqual(type(model.bn1), nn.Identity)
self.assertEqual(type(model.relu1), nn.Identity)
self.assertEqual(type(model.sub1.conv), nniqat.ConvBn2d)
self.assertEqual(type(model.sub1.bn), nn.Identity)
self.assertEqual(type(model.sub2.conv), nn.Conv2d)
self.assertEqual(type(model.sub2.relu), nn.ReLU)
checkQAT(model)
test_only_train_fn(model, self.img_data_1d_train)
model = convert(model)
def checkQuantized(model):
self.assertEqual(type(model.conv1), nniq.ConvReLU2d)
self.assertEqual(type(model.bn1), nn.Identity)
self.assertEqual(type(model.relu1), nn.Identity)
self.assertEqual(type(model.sub1.conv), nnq.Conv2d)
self.assertEqual(type(model.sub1.bn), nn.Identity)
self.assertEqual(type(model.sub2.conv), nn.Conv2d)
self.assertEqual(type(model.sub2.relu), nn.ReLU)
test_only_eval_fn(model, self.img_data_1d)
self.checkNoQconfig(model)
with self.assertRaisesRegex(
RuntimeError,
"Could not run 'aten::native_batch_norm' with arguments from the 'QuantizedCPU'",
):
checkQuantized(model)
model = ModelForFusion(default_qat_qconfig).train()
model = fuse_modules_qat(
model, [["conv1", "bn1", "relu1"], ["sub1.conv", "sub1.bn"]]
)
model = quantize_qat(model, test_only_train_fn, [self.img_data_1d_train])
with self.assertRaisesRegex(
RuntimeError,
"Could not run 'aten::native_batch_norm' with arguments from the 'QuantizedCPU'",
):
checkQuantized(model)
def test_fuse_module_eval(self):
model = ModelForFusion(default_qconfig)
model.eval()
model = fuse_modules(
model,
[
["conv3", "bn3", "relu4"],
["conv1", "bn1", "relu1"],
["conv2", "relu2"],
["bn2", "relu3"],
["sub1.conv", "sub1.bn"],
],
)
self.assertEqual(
type(model.conv1),
nni.ConvReLU2d,
msg="Fused Conv + BN + Relu first layer (BN is folded)",
)
self.assertEqual(
type(model.conv1[0]),
nn.Conv2d,
msg="Fused Conv + BN + Relu (Conv + folded BN only)",
)
self.assertEqual(
type(model.conv1[1]),
nn.ReLU,
msg="Fused Conv + BN + Relu second layer (Relu only)",
)
self.assertEqual(
type(model.bn1),
nn.Identity,
msg="Fused Conv + BN + Relu second layer (Skipped BN)",
)
self.assertEqual(
type(model.relu1),
nn.Identity,
msg="Fused Conv + BN + Relu second layer (Skipped Relu)",
)
self.assertEqual(
type(model.conv2),
nni.ConvReLU3d,
msg="Fused Conv + BN + Relu first layer (BN is folded)",
)
self.assertEqual(
type(model.bn2),
nni.BNReLU3d,
msg="Fused BN + Relu first layer (Relu is folded))",
)
self.assertEqual(
type(model.relu3),
nn.Identity,
msg="Fused BN + Relu second layer (Skipped Relu)",
)
self.assertEqual(
type(model.conv2[0]),
nn.Conv3d,
msg="Fused Conv + BN + Relu (Conv + folded BN only)",
)
self.assertEqual(
type(model.conv2[1]),
nn.ReLU,
msg="Fused Conv + BN + Relu second layer (Relu only)",
)
self.assertEqual(
type(model.relu2),
nn.Identity,
msg="Fused Conv + BN + Relu second layer (Skipped Relu)",
)
self.assertEqual(
type(model.conv3),
nni.ConvReLU1d,
msg="Fused Conv + Relu for Conv1d (folded BN)",
)
self.assertEqual(
type(model.conv3[0]), nn.Conv1d, msg="Fused Conv + Relu for Conv1d "
)
self.assertEqual(
type(model.conv3[1]), nn.ReLU, msg="Fused Conv + Relu for Conv1d"
)
self.assertEqual(
type(model.bn3),
nn.Identity,
msg="Fused Conv + BN + Relu for Conv1d (Skipped BN)",
)
self.assertEqual(
type(model.sub1.conv), nn.Conv2d, msg="Fused submodule Conv + folded BN"
)
self.assertEqual(
type(model.sub1.bn), nn.Identity, msg="Fused submodule (skipped BN)"
)
self.assertEqual(
type(model.sub2.conv), nn.Conv2d, msg="Non-fused submodule Conv"
)
self.assertEqual(
type(model.sub2.relu), torch.nn.ReLU, msg="Non-fused submodule ReLU"
)
model = prepare(model)
self.checkObservers(model)
test_only_eval_fn(model, self.img_data_1d)
model = convert(model)
def checkQuantized(model):
self.assertEqual(type(model.conv3), nniq.ConvReLU1d)
self.assertEqual(type(model.conv1), nniq.ConvReLU2d)
self.assertEqual(type(model.bn1), nn.Identity)
self.assertEqual(type(model.relu1), nn.Identity)
self.assertEqual(type(model.sub1.conv), nnq.Conv2d)
self.assertEqual(type(model.sub1.bn), nn.Identity)
self.assertEqual(type(model.sub2.conv), nn.Conv2d)
self.assertEqual(type(model.sub2.relu), nn.ReLU)
self.assertEqual(type(model.bn2), nniq.BNReLU3d)
test_only_eval_fn(model, self.img_data_1d)
self.checkNoQconfig(model)
checkQuantized(model)
model = ModelForFusion(default_qconfig).eval()
model = fuse_modules(
model,
[
["conv1", "bn1", "relu1"],
["conv2", "relu2"],
["bn2", "relu3"],
["sub1.conv", "sub1.bn"],
["conv3", "bn3", "relu4"],
],
)
model = quantize(model, test_only_eval_fn, [self.img_data_1d])
checkQuantized(model)
def test_fusion_sequential_model_train(self):
for qengine in supported_qengines:
with override_quantized_engine(qengine):
model = ModelWithSequentialFusion().train()
model.to(torch.float)
fuse_modules_qat(
model,
[
["conv1", "relu1"],
["features.0.0", "features.0.1", "features.0.2"],
["features.1.0", "features.1.1", "features.1.2"],
["features.2.0", "features.2.1", "features.2.2"],
["classifier.0", "classifier.1"],
],
inplace=True,
)
self.assertEqual(
type(model.conv1),
nni.ConvReLU2d,
msg="Fused Conv + Relu: nni.ConvReLU2d",
)
self.assertEqual(
type(model.conv1[0]), nn.Conv2d, msg="Fused Conv + Relu: Conv2d"
)
self.assertEqual(
type(model.conv1[1]), nn.ReLU, msg="Fused Conv + Relu: Relu"
)
self.assertEqual(
type(model.relu1), nn.Identity, msg="Fused Conv + Relu: Identity"
)
for i in range(3):
self.assertEqual(
type(model.features[i][0]),
nni.ConvBnReLU2d,
msg="Fused submodule Conv + folded BN",
)
self.assertEqual(
type(model.features[i][1]),
nn.Identity,
msg="Fused submodule (skipped BN)",
)
self.assertEqual(
type(model.features[i][2]),
nn.Identity,
msg="Non-fused submodule Conv",
)
self.assertEqual(type(model.classifier[0]), nni.LinearReLU)
self.assertEqual(type(model.classifier[1]), nn.Identity)
model.qconfig = torch.ao.quantization.get_default_qat_qconfig(qengine)
prepare_qat(model, inplace=True)
self.checkObservers(model)
model(self.img_data_2d[0][0])
def checkQAT(model):
self.assertEqual(type(model.conv1), nniqat.ConvReLU2d)
self.assertEqual(type(model.relu1), nn.Identity)
for i in range(3):
self.assertEqual(
type(model.features[i][0]),
nniqat.ConvBnReLU2d,
msg="Fused submodule Conv + folded BN",
)
self.assertEqual(
type(model.features[i][1]),
nn.Identity,
msg="Fused submodule (skipped BN)",
)
self.assertEqual(
type(model.features[i][2]),
nn.Identity,
msg="Non-fused submodule Conv",
)
self.assertEqual(type(model.classifier[0]), nniqat.LinearReLU)
self.assertEqual(type(model.classifier[1]), nn.Identity)
checkQAT(model)
model(self.img_data_2d[1][0])
convert(model, inplace=True)
model(self.img_data_2d[1][0])
self.checkModelWithSequentialQuantized(model)
def test_fusion_sequential_model_eval(self):
for qengine in supported_qengines:
with override_quantized_engine(qengine):
model = ModelWithSequentialFusion().eval()
model.to(torch.float)
fuse_modules(
model,
[
["conv1", "relu1"],
["features.0.0", "features.0.1", "features.0.2"],
["features.1.0", "features.1.1", "features.1.2"],
["features.2.0", "features.2.1", "features.2.2"],
["classifier.0", "classifier.1"],
],
inplace=True,
)
self.assertEqual(
type(model.conv1),
nni.ConvReLU2d,
msg="Fused Conv + Relu: nni.ConvReLU2d",
)
self.assertEqual(
type(model.conv1[0]), nn.Conv2d, msg="Fused Conv + Relu: Conv2d"
)
self.assertEqual(
type(model.conv1[1]), nn.ReLU, msg="Fused Conv + Relu: Relu"
)
self.assertEqual(
type(model.relu1), nn.Identity, msg="Fused Conv + Relu: Identity"
)
for i in range(3):
self.assertEqual(
type(model.features[i][0]),
nni.ConvReLU2d,
msg="Fused submodule Conv + folded BN",
)
self.assertEqual(
type(model.features[i][1]),
nn.Identity,
msg="Fused submodule (skipped BN)",
)
self.assertEqual(
type(model.features[i][2]),
nn.Identity,
msg="Non-fused submodule Conv",
)
self.assertEqual(type(model.classifier[0]), nni.LinearReLU)
self.assertEqual(type(model.classifier[1]), nn.Identity)
model.qconfig = torch.ao.quantization.get_default_qconfig(qengine)
prepare(model, inplace=True)
self.checkObservers(model)
model(self.img_data_2d[0][0])
convert(model, inplace=True)
model(self.img_data_2d[1][0])
self.checkModelWithSequentialQuantized(model)
def checkModelWithSequentialQuantized(self, model):
self.assertEqual(type(model.conv1), nniq.ConvReLU2d)
self.assertEqual(type(model.relu1), nn.Identity)
for i in range(3):
self.assertEqual(type(model.features[i][0]), nniq.ConvReLU2d)
self.assertEqual(type(model.features[i][1]), nn.Identity)
self.assertEqual(type(model.features[i][2]), nn.Identity)
self.assertEqual(type(model.classifier[0]), nniq.LinearReLU)
self.assertEqual(type(model.classifier[1]), nn.Identity)
def test_fusion_conv_with_bias(self):
for qengine in supported_qengines:
with override_quantized_engine(qengine):
model_orig = ModelForFusionWithBias().train()
# reference model
model_ref = copy.deepcopy(model_orig)
# output with no fusion.
out_ref = model_ref(self.img_data_2d[0][0])
# fused model
model_orig.qconfig = QConfig(
activation=torch.nn.Identity, weight=torch.nn.Identity
)
model = fuse_modules_qat(
model_orig, [["conv1", "bn1", "relu1"], ["conv2", "bn2"]]
)
prep_model = prepare_qat(model, inplace=False)
# output with fusion but no observers.
out_fused = prep_model(self.img_data_2d[0][0])
self.assertEqual(out_ref, out_fused)
def checkBN(bn_ref, bn):
self.assertEqual(bn_ref.weight, bn.weight)
self.assertEqual(bn_ref.bias, bn.bias)
self.assertEqual(bn_ref.running_mean, bn.running_mean)
self.assertEqual(bn_ref.running_var, bn.running_var)
checkBN(model_ref.bn1, prep_model.conv1.bn)
checkBN(model_ref.bn2, prep_model.conv2.bn)
model.qconfig = torch.ao.quantization.get_default_qconfig(qengine)
prepare_qat(model, inplace=True)
model(self.img_data_2d[0][0])
def checkQAT(model):
self.assertEqual(type(model.conv1), nniqat.ConvBnReLU2d)
self.assertEqual(type(model.bn1), nn.Identity)
self.assertEqual(type(model.relu1), nn.Identity)
self.assertEqual(type(model.conv2), nniqat.ConvBn2d)
self.assertEqual(type(model.bn2), nn.Identity)
checkQAT(model)
def test_fusion_linear_bn_eval(self):
model = ModelForLinearBNFusion().train()
inp1 = torch.randn(8, 20)
inp2 = torch.randn(8, 20)
# Get some interesting values into the running mean and variance.
model(inp1)
model.eval()
golden = model(inp2)
model = fuse_modules(model, [["fc", "bn"]])
self.assertEqual(type(model.bn), nn.Identity)
self.assertEqual(golden, model(inp2))
def test_fusion_convtranspose_bn_eval(self):
model = ModelForConvTransposeBNFusion().train()
inp1 = torch.randn(8, 3, 16)
inp2 = torch.randn(8, 3, 16)
# Get some interesting values into the running mean and variance.
model(inp1)
model.eval()
golden = model(inp2)
model = fuse_modules(
model, [["conv1", "bn1"], ["conv2", "bn2"], ["conv3", "bn3"]]
)
self.assertEqual(type(model.bn1), nn.Identity)
self.assertEqual(type(model.bn2), nn.Identity)
self.assertEqual(type(model.bn3), nn.Identity)
self.assertEqual(golden, model(inp2))
def test_fuse_function_customization(self):
dummy_model = SingleLayerLinearModel().train()
dummy_model.eval()
# A custom fuse funct
def custom_fuse_func(module, is_qat, add_fuser_mapping):
return [torch.nn.Identity()]
dummy_model = fuse_modules(dummy_model, [["fc1"]], fuser_func=custom_fuse_func)
self.assertEqual(type(dummy_model.fc1), nn.Identity)
def test_forward_hooks_preserved(self):
r"""Test case that checks whether forward pre hooks of the first module and
post forward hooks of the last module in modules list passed to fusion function preserved.
(e.g. before fusion: [nn.Conv2d (with pre forward hooks), nn.BatchNorm2d, nn.ReLU (with post forward hooks)]
after fusion: [nni.ConvBnReLU2d (with pre and post hooks), nn.Identity, nn.Identity])
"""
model = ModelForFusion(default_qat_qconfig).train()
counter = {
"pre_forwards": 0,
"forwards": 0,
}
fused = False
def fw_pre_hook(fused_module_class, h_module, input):
if fused:
self.assertEqual(
type(h_module),
fused_module_class,
"After fusion owner of the first module's forward pre hook is not a fused module",
)
counter["pre_forwards"] += 1
def fw_hook(fused_module_class, h_module, input, output):
if fused:
self.assertEqual(
type(h_module),
fused_module_class,
"After fusion owner of the last module's forward hook is not a fused module",
)
counter["forwards"] += 1
# Registering two pre and two post forward hooks, thus expecting counter increment by two each inference
model.conv1.register_forward_pre_hook(
lambda *args: fw_pre_hook(nni.ConvBnReLU2d, *args)
)
model.sub1.conv.register_forward_pre_hook(
lambda *args: fw_pre_hook(nni.ConvBn2d, *args)
)
model.relu1.register_forward_hook(
lambda *args: fw_hook(nni.ConvBnReLU2d, *args)
)
model.sub1.bn.register_forward_hook(lambda *args: fw_hook(nni.ConvBn2d, *args))
test_only_eval_fn(model, self.img_data_1d)
self.assertEqual(counter["pre_forwards"], 2 * len(self.img_data_1d))
self.assertEqual(counter["forwards"], 2 * len(self.img_data_1d))
model = fuse_modules_qat(model, ["conv1", "bn1", "relu1"])
model = fuse_modules_qat(model, ["sub1.conv", "sub1.bn"])
fused = True
before_fusion_pre_count = counter["pre_forwards"]
before_fusion_post_count = counter["forwards"]
test_only_eval_fn(model, self.img_data_1d)
self.assertEqual(
counter["pre_forwards"] - before_fusion_pre_count, 2 * len(self.img_data_1d)
)
self.assertEqual(
counter["forwards"] - before_fusion_post_count, 2 * len(self.img_data_1d)
)
def test_fuse_modules_with_nested_hooks(self):
r"""Test case that checks whether a nested module with sub-sub modules registered with hooks
can be safely fused. Safeguard for issues similar to https://github.com/pytorch/pytorch/issues/105063
in the future.
"""
def myhook(*x):
return ""
for qengine in supported_qengines:
with override_quantized_engine(qengine):
model = ModelWithSequentialFusion().eval()
for sub_model in model.modules():
if isinstance(sub_model, nn.Sequential):
for layer in sub_model:
if hasattr(layer, "register_forward_hook"):
layer.register_forward_hook(myhook)
fuse_modules(
model,
[["features.0.0", "features.0.1", "features.0.2"]],
inplace=True,
)
self.assertEqual(
type(model.features[0][0]),
nni.ConvReLU2d,
msg="Fused submodule Conv + folded BN",
)
self.assertEqual(
type(model.features[0][1]),
nn.Identity,
msg="Fused submodule (skipped BN)",
)
self.assertEqual(
type(model.features[0][2]),
nn.Identity,
msg="Non-fused submodule Conv",
)
if __name__ == "__main__":
raise RuntimeError(
"This test file is not meant to be run directly, use:\n\n"
"\tpython test/test_quantization.py TESTNAME\n\n"
"instead."
)
|
TestFuseEager
|
python
|
walkccc__LeetCode
|
solutions/3251. Find the Count of Monotonic Pairs II/3251.py
|
{
"start": 0,
"end": 1234
}
|
class ____:
# Same as 3250. Find the Count of Monotonic Pairs I
def countOfPairs(self, nums: list[int]) -> int:
MOD = 1_000_000_007
MAX = 1000
n = len(nums)
# dp[i][num] := the number of valid ways to fill the arrays up to index i
# with arr1[i] = num
dp = [[0] * (MAX + 1) for _ in range(n)]
for num in range(nums[0] + 1):
dp[0][num] = 1
for i in range(1, n):
ways = 0
prevNum = 0
# To satisfy arr1, prevNum <= num.
# To satisfy arr2, nums[i - 1] - prevNum >= nums[i] - num.
# => prevNum <= min(num, num - (nums[i] - nums[i - 1])).
# As we move from `num` to `num + 1`, the range of valid `prevNum` values
# becomes prevNum <= min(num + 1, num + 1 - (nums[i] - nums[i - 1])).
# Since the range of `prevNum` can only increase by at most 1, there's
# no need to iterate through all possible values of `prevNum`. We can
# simply increment `prevNum` by 1 if it meets the condition.
for num in range(nums[i] + 1):
if prevNum <= min(num, num - (nums[i] - nums[i - 1])):
ways = (ways + dp[i - 1][prevNum]) % MOD
prevNum += 1
dp[i][num] = ways
return sum(dp[n - 1]) % MOD
|
Solution
|
python
|
numpy__numpy
|
numpy/distutils/ccompiler_opt.py
|
{
"start": 634,
"end": 23216
}
|
class ____:
"""An abstract class holds all configurable attributes of `CCompilerOpt`,
these class attributes can be used to change the default behavior
of `CCompilerOpt` in order to fit other requirements.
Attributes
----------
conf_nocache : bool
Set True to disable memory and file cache.
Default is False.
conf_noopt : bool
Set True to forces the optimization to be disabled,
in this case `CCompilerOpt` tends to generate all
expected headers in order to 'not' break the build.
Default is False.
conf_cache_factors : list
Add extra factors to the primary caching factors. The caching factors
are utilized to determine if there are changes had happened that
requires to discard the cache and re-updating it. The primary factors
are the arguments of `CCompilerOpt` and `CCompiler`'s properties(type, flags, etc).
Default is list of two items, containing the time of last modification
of `ccompiler_opt` and value of attribute "conf_noopt"
conf_tmp_path : str,
The path of temporary directory. Default is auto-created
temporary directory via ``tempfile.mkdtemp()``.
conf_check_path : str
The path of testing files. Each added CPU feature must have a
**C** source file contains at least one intrinsic or instruction that
related to this feature, so it can be tested against the compiler.
Default is ``./distutils/checks``.
conf_target_groups : dict
Extra tokens that can be reached from dispatch-able sources through
the special mark ``@targets``. Default is an empty dictionary.
**Notes**:
- case-insensitive for tokens and group names
- sign '#' must stick in the begin of group name and only within ``@targets``
**Example**:
.. code-block:: console
$ "@targets #avx_group other_tokens" > group_inside.c
>>> CCompilerOpt.conf_target_groups["avx_group"] = \\
"$werror $maxopt avx2 avx512f avx512_skx"
>>> cco = CCompilerOpt(cc_instance)
>>> cco.try_dispatch(["group_inside.c"])
conf_c_prefix : str
The prefix of public C definitions. Default is ``"NPY_"``.
conf_c_prefix_ : str
The prefix of internal C definitions. Default is ``"NPY__"``.
conf_cc_flags : dict
Nested dictionaries defining several compiler flags
that linked to some major functions, the main key
represent the compiler name and sub-keys represent
flags names. Default is already covers all supported
**C** compilers.
Sub-keys explained as follows:
"native": str or None
used by argument option `native`, to detect the current
machine support via the compiler.
"werror": str or None
utilized to treat warning as errors during testing CPU features
against the compiler and also for target's policy `$werror`
via dispatch-able sources.
"maxopt": str or None
utilized for target's policy '$maxopt' and the value should
contains the maximum acceptable optimization by the compiler.
e.g. in gcc ``'-O3'``
**Notes**:
* case-sensitive for compiler names and flags
* use space to separate multiple flags
* any flag will tested against the compiler and it will skipped
if it's not applicable.
conf_min_features : dict
A dictionary defines the used CPU features for
argument option ``'min'``, the key represent the CPU architecture
name e.g. ``'x86'``. Default values provide the best effort
on wide range of users platforms.
**Note**: case-sensitive for architecture names.
conf_features : dict
Nested dictionaries used for identifying the CPU features.
the primary key is represented as a feature name or group name
that gathers several features. Default values covers all
supported features but without the major options like "flags",
these undefined options handle it by method `conf_features_partial()`.
Default value is covers almost all CPU features for *X86*, *IBM/Power64*
and *ARM 7/8*.
Sub-keys explained as follows:
"implies" : str or list, optional,
List of CPU feature names to be implied by it,
the feature name must be defined within `conf_features`.
Default is None.
"flags": str or list, optional
List of compiler flags. Default is None.
"detect": str or list, optional
List of CPU feature names that required to be detected
in runtime. By default, its the feature name or features
in "group" if its specified.
"implies_detect": bool, optional
If True, all "detect" of implied features will be combined.
Default is True. see `feature_detect()`.
"group": str or list, optional
Same as "implies" but doesn't require the feature name to be
defined within `conf_features`.
"interest": int, required
a key for sorting CPU features
"headers": str or list, optional
intrinsics C header file
"disable": str, optional
force disable feature, the string value should contains the
reason of disabling.
"autovec": bool or None, optional
True or False to declare that CPU feature can be auto-vectorized
by the compiler.
By default(None), treated as True if the feature contains at
least one applicable flag. see `feature_can_autovec()`
"extra_checks": str or list, optional
Extra test case names for the CPU feature that need to be tested
against the compiler.
Each test case must have a C file named ``extra_xxxx.c``, where
``xxxx`` is the case name in lower case, under 'conf_check_path'.
It should contain at least one intrinsic or function related to the test case.
If the compiler able to successfully compile the C file then `CCompilerOpt`
will add a C ``#define`` for it into the main dispatch header, e.g.
``#define {conf_c_prefix}_XXXX`` where ``XXXX`` is the case name in upper case.
**NOTES**:
* space can be used as separator with options that supports "str or list"
* case-sensitive for all values and feature name must be in upper-case.
* if flags aren't applicable, its will skipped rather than disable the
CPU feature
* the CPU feature will disabled if the compiler fail to compile
the test file
"""
conf_nocache = False
conf_noopt = False
conf_cache_factors = None
conf_tmp_path = None
conf_check_path = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "checks"
)
conf_target_groups = {}
conf_c_prefix = 'NPY_'
conf_c_prefix_ = 'NPY__'
conf_cc_flags = dict(
gcc = dict(
# native should always fail on arm and ppc64,
# native usually works only with x86
native = '-march=native',
opt = '-O3',
werror = '-Werror',
),
clang = dict(
native = '-march=native',
opt = "-O3",
# One of the following flags needs to be applicable for Clang to
# guarantee the sanity of the testing process, however in certain
# cases `-Werror` gets skipped during the availability test due to
# "unused arguments" warnings.
# see https://github.com/numpy/numpy/issues/19624
werror = '-Werror=switch -Werror',
),
icc = dict(
native = '-xHost',
opt = '-O3',
werror = '-Werror',
),
iccw = dict(
native = '/QxHost',
opt = '/O3',
werror = '/Werror',
),
msvc = dict(
native = None,
opt = '/O2',
werror = '/WX',
),
fcc = dict(
native = '-mcpu=a64fx',
opt = None,
werror = None,
)
)
conf_min_features = dict(
x86 = "SSE SSE2",
x64 = "SSE SSE2 SSE3",
ppc64 = '', # play it safe
ppc64le = "VSX VSX2",
s390x = '',
armhf = '', # play it safe
aarch64 = "NEON NEON_FP16 NEON_VFPV4 ASIMD"
)
conf_features = dict(
# X86
SSE = dict(
interest=1, headers="xmmintrin.h",
# enabling SSE without SSE2 is useless also
# it's non-optional for x86_64
implies="SSE2"
),
SSE2 = dict(interest=2, implies="SSE", headers="emmintrin.h"),
SSE3 = dict(interest=3, implies="SSE2", headers="pmmintrin.h"),
SSSE3 = dict(interest=4, implies="SSE3", headers="tmmintrin.h"),
SSE41 = dict(interest=5, implies="SSSE3", headers="smmintrin.h"),
POPCNT = dict(interest=6, implies="SSE41", headers="popcntintrin.h"),
SSE42 = dict(interest=7, implies="POPCNT"),
AVX = dict(
interest=8, implies="SSE42", headers="immintrin.h",
implies_detect=False
),
XOP = dict(interest=9, implies="AVX", headers="x86intrin.h"),
FMA4 = dict(interest=10, implies="AVX", headers="x86intrin.h"),
F16C = dict(interest=11, implies="AVX"),
FMA3 = dict(interest=12, implies="F16C"),
AVX2 = dict(interest=13, implies="F16C"),
AVX512F = dict(
interest=20, implies="FMA3 AVX2", implies_detect=False,
extra_checks="AVX512F_REDUCE"
),
AVX512CD = dict(interest=21, implies="AVX512F"),
AVX512_KNL = dict(
interest=40, implies="AVX512CD", group="AVX512ER AVX512PF",
detect="AVX512_KNL", implies_detect=False
),
AVX512_KNM = dict(
interest=41, implies="AVX512_KNL",
group="AVX5124FMAPS AVX5124VNNIW AVX512VPOPCNTDQ",
detect="AVX512_KNM", implies_detect=False
),
AVX512_SKX = dict(
interest=42, implies="AVX512CD", group="AVX512VL AVX512BW AVX512DQ",
detect="AVX512_SKX", implies_detect=False,
extra_checks="AVX512BW_MASK AVX512DQ_MASK"
),
AVX512_CLX = dict(
interest=43, implies="AVX512_SKX", group="AVX512VNNI",
detect="AVX512_CLX"
),
AVX512_CNL = dict(
interest=44, implies="AVX512_SKX", group="AVX512IFMA AVX512VBMI",
detect="AVX512_CNL", implies_detect=False
),
AVX512_ICL = dict(
interest=45, implies="AVX512_CLX AVX512_CNL",
group="AVX512VBMI2 AVX512BITALG AVX512VPOPCNTDQ",
detect="AVX512_ICL", implies_detect=False
),
AVX512_SPR = dict(
interest=46, implies="AVX512_ICL", group="AVX512FP16",
detect="AVX512_SPR", implies_detect=False
),
# IBM/Power
## Power7/ISA 2.06
VSX = dict(interest=1, headers="altivec.h", extra_checks="VSX_ASM"),
## Power8/ISA 2.07
VSX2 = dict(interest=2, implies="VSX", implies_detect=False),
## Power9/ISA 3.00
VSX3 = dict(interest=3, implies="VSX2", implies_detect=False,
extra_checks="VSX3_HALF_DOUBLE"),
## Power10/ISA 3.1
VSX4 = dict(interest=4, implies="VSX3", implies_detect=False,
extra_checks="VSX4_MMA"),
# IBM/Z
## VX(z13) support
VX = dict(interest=1, headers="vecintrin.h"),
## Vector-Enhancements Facility
VXE = dict(interest=2, implies="VX", implies_detect=False),
## Vector-Enhancements Facility 2
VXE2 = dict(interest=3, implies="VXE", implies_detect=False),
# ARM
NEON = dict(interest=1, headers="arm_neon.h"),
NEON_FP16 = dict(interest=2, implies="NEON"),
## FMA
NEON_VFPV4 = dict(interest=3, implies="NEON_FP16"),
## Advanced SIMD
ASIMD = dict(interest=4, implies="NEON_FP16 NEON_VFPV4", implies_detect=False),
## ARMv8.2 half-precision & vector arithm
ASIMDHP = dict(interest=5, implies="ASIMD"),
## ARMv8.2 dot product
ASIMDDP = dict(interest=6, implies="ASIMD"),
## ARMv8.2 Single & half-precision Multiply
ASIMDFHM = dict(interest=7, implies="ASIMDHP")
)
def conf_features_partial(self):
"""Return a dictionary of supported CPU features by the platform,
and accumulate the rest of undefined options in `conf_features`,
the returned dict has same rules and notes in
class attribute `conf_features`, also its override
any options that been set in 'conf_features'.
"""
if self.cc_noopt:
# optimization is disabled
return {}
on_x86 = self.cc_on_x86 or self.cc_on_x64
is_unix = self.cc_is_gcc or self.cc_is_clang or self.cc_is_fcc
if on_x86 and is_unix: return dict(
SSE = dict(flags="-msse"),
SSE2 = dict(flags="-msse2"),
SSE3 = dict(flags="-msse3"),
SSSE3 = dict(flags="-mssse3"),
SSE41 = dict(flags="-msse4.1"),
POPCNT = dict(flags="-mpopcnt"),
SSE42 = dict(flags="-msse4.2"),
AVX = dict(flags="-mavx"),
F16C = dict(flags="-mf16c"),
XOP = dict(flags="-mxop"),
FMA4 = dict(flags="-mfma4"),
FMA3 = dict(flags="-mfma"),
AVX2 = dict(flags="-mavx2"),
AVX512F = dict(flags="-mavx512f -mno-mmx"),
AVX512CD = dict(flags="-mavx512cd"),
AVX512_KNL = dict(flags="-mavx512er -mavx512pf"),
AVX512_KNM = dict(
flags="-mavx5124fmaps -mavx5124vnniw -mavx512vpopcntdq"
),
AVX512_SKX = dict(flags="-mavx512vl -mavx512bw -mavx512dq"),
AVX512_CLX = dict(flags="-mavx512vnni"),
AVX512_CNL = dict(flags="-mavx512ifma -mavx512vbmi"),
AVX512_ICL = dict(
flags="-mavx512vbmi2 -mavx512bitalg -mavx512vpopcntdq"
),
AVX512_SPR = dict(flags="-mavx512fp16"),
)
if on_x86 and self.cc_is_icc: return dict(
SSE = dict(flags="-msse"),
SSE2 = dict(flags="-msse2"),
SSE3 = dict(flags="-msse3"),
SSSE3 = dict(flags="-mssse3"),
SSE41 = dict(flags="-msse4.1"),
POPCNT = {},
SSE42 = dict(flags="-msse4.2"),
AVX = dict(flags="-mavx"),
F16C = {},
XOP = dict(disable="Intel Compiler doesn't support it"),
FMA4 = dict(disable="Intel Compiler doesn't support it"),
# Intel Compiler doesn't support AVX2 or FMA3 independently
FMA3 = dict(
implies="F16C AVX2", flags="-march=core-avx2"
),
AVX2 = dict(implies="FMA3", flags="-march=core-avx2"),
# Intel Compiler doesn't support AVX512F or AVX512CD independently
AVX512F = dict(
implies="AVX2 AVX512CD", flags="-march=common-avx512"
),
AVX512CD = dict(
implies="AVX2 AVX512F", flags="-march=common-avx512"
),
AVX512_KNL = dict(flags="-xKNL"),
AVX512_KNM = dict(flags="-xKNM"),
AVX512_SKX = dict(flags="-xSKYLAKE-AVX512"),
AVX512_CLX = dict(flags="-xCASCADELAKE"),
AVX512_CNL = dict(flags="-xCANNONLAKE"),
AVX512_ICL = dict(flags="-xICELAKE-CLIENT"),
AVX512_SPR = dict(disable="Not supported yet")
)
if on_x86 and self.cc_is_iccw: return dict(
SSE = dict(flags="/arch:SSE"),
SSE2 = dict(flags="/arch:SSE2"),
SSE3 = dict(flags="/arch:SSE3"),
SSSE3 = dict(flags="/arch:SSSE3"),
SSE41 = dict(flags="/arch:SSE4.1"),
POPCNT = {},
SSE42 = dict(flags="/arch:SSE4.2"),
AVX = dict(flags="/arch:AVX"),
F16C = {},
XOP = dict(disable="Intel Compiler doesn't support it"),
FMA4 = dict(disable="Intel Compiler doesn't support it"),
# Intel Compiler doesn't support FMA3 or AVX2 independently
FMA3 = dict(
implies="F16C AVX2", flags="/arch:CORE-AVX2"
),
AVX2 = dict(
implies="FMA3", flags="/arch:CORE-AVX2"
),
# Intel Compiler doesn't support AVX512F or AVX512CD independently
AVX512F = dict(
implies="AVX2 AVX512CD", flags="/Qx:COMMON-AVX512"
),
AVX512CD = dict(
implies="AVX2 AVX512F", flags="/Qx:COMMON-AVX512"
),
AVX512_KNL = dict(flags="/Qx:KNL"),
AVX512_KNM = dict(flags="/Qx:KNM"),
AVX512_SKX = dict(flags="/Qx:SKYLAKE-AVX512"),
AVX512_CLX = dict(flags="/Qx:CASCADELAKE"),
AVX512_CNL = dict(flags="/Qx:CANNONLAKE"),
AVX512_ICL = dict(flags="/Qx:ICELAKE-CLIENT"),
AVX512_SPR = dict(disable="Not supported yet")
)
if on_x86 and self.cc_is_msvc: return dict(
SSE = dict(flags="/arch:SSE") if self.cc_on_x86 else {},
SSE2 = dict(flags="/arch:SSE2") if self.cc_on_x86 else {},
SSE3 = {},
SSSE3 = {},
SSE41 = {},
POPCNT = dict(headers="nmmintrin.h"),
SSE42 = {},
AVX = dict(flags="/arch:AVX"),
F16C = {},
XOP = dict(headers="ammintrin.h"),
FMA4 = dict(headers="ammintrin.h"),
# MSVC doesn't support FMA3 or AVX2 independently
FMA3 = dict(
implies="F16C AVX2", flags="/arch:AVX2"
),
AVX2 = dict(
implies="F16C FMA3", flags="/arch:AVX2"
),
# MSVC doesn't support AVX512F or AVX512CD independently,
# always generate instructions belong to (VL/VW/DQ)
AVX512F = dict(
implies="AVX2 AVX512CD AVX512_SKX", flags="/arch:AVX512"
),
AVX512CD = dict(
implies="AVX512F AVX512_SKX", flags="/arch:AVX512"
),
AVX512_KNL = dict(
disable="MSVC compiler doesn't support it"
),
AVX512_KNM = dict(
disable="MSVC compiler doesn't support it"
),
AVX512_SKX = dict(flags="/arch:AVX512"),
AVX512_CLX = {},
AVX512_CNL = {},
AVX512_ICL = {},
AVX512_SPR= dict(
disable="MSVC compiler doesn't support it"
)
)
on_power = self.cc_on_ppc64le or self.cc_on_ppc64
if on_power:
partial = dict(
VSX = dict(
implies=("VSX2" if self.cc_on_ppc64le else ""),
flags="-mvsx"
),
VSX2 = dict(
flags="-mcpu=power8", implies_detect=False
),
VSX3 = dict(
flags="-mcpu=power9 -mtune=power9", implies_detect=False
),
VSX4 = dict(
flags="-mcpu=power10 -mtune=power10", implies_detect=False
)
)
if self.cc_is_clang:
partial["VSX"]["flags"] = "-maltivec -mvsx"
partial["VSX2"]["flags"] = "-mcpu=power8"
partial["VSX3"]["flags"] = "-mcpu=power9"
partial["VSX4"]["flags"] = "-mcpu=power10"
return partial
on_zarch = self.cc_on_s390x
if on_zarch:
partial = dict(
VX = dict(
flags="-march=arch11 -mzvector"
),
VXE = dict(
flags="-march=arch12", implies_detect=False
),
VXE2 = dict(
flags="-march=arch13", implies_detect=False
)
)
return partial
if self.cc_on_aarch64 and is_unix: return dict(
NEON = dict(
implies="NEON_FP16 NEON_VFPV4 ASIMD", autovec=True
),
NEON_FP16 = dict(
implies="NEON NEON_VFPV4 ASIMD", autovec=True
),
NEON_VFPV4 = dict(
implies="NEON NEON_FP16 ASIMD", autovec=True
),
ASIMD = dict(
implies="NEON NEON_FP16 NEON_VFPV4", autovec=True
),
ASIMDHP = dict(
flags="-march=armv8.2-a+fp16"
),
ASIMDDP = dict(
flags="-march=armv8.2-a+dotprod"
),
ASIMDFHM = dict(
flags="-march=armv8.2-a+fp16fml"
),
)
if self.cc_on_armhf and is_unix: return dict(
NEON = dict(
flags="-mfpu=neon"
),
NEON_FP16 = dict(
flags="-mfpu=neon-fp16 -mfp16-format=ieee"
),
NEON_VFPV4 = dict(
flags="-mfpu=neon-vfpv4",
),
ASIMD = dict(
flags="-mfpu=neon-fp-armv8 -march=armv8-a+simd",
),
ASIMDHP = dict(
flags="-march=armv8.2-a+fp16"
),
ASIMDDP = dict(
flags="-march=armv8.2-a+dotprod",
),
ASIMDFHM = dict(
flags="-march=armv8.2-a+fp16fml"
)
)
# TODO: ARM MSVC
return {}
def __init__(self):
if self.conf_tmp_path is None:
import shutil
import tempfile
tmp = tempfile.mkdtemp()
def rm_temp():
try:
shutil.rmtree(tmp)
except OSError:
pass
atexit.register(rm_temp)
self.conf_tmp_path = tmp
if self.conf_cache_factors is None:
self.conf_cache_factors = [
os.path.getmtime(__file__),
self.conf_nocache
]
|
_Config
|
python
|
ethereum__web3.py
|
ens/_normalization.py
|
{
"start": 2192,
"end": 2562
}
|
class ____:
type: str
tokens: list[Token]
def __init__(
self,
type: str = None,
tokens: list[Token] = None,
) -> None:
self.type = type
self.tokens = tokens
@property
def text(self) -> str:
if not self.tokens:
return ""
return "".join(token.text for token in self.tokens)
|
Label
|
python
|
django__django
|
tests/template_tests/filter_tests/test_rjust.py
|
{
"start": 163,
"end": 856
}
|
class ____(SimpleTestCase):
@setup(
{
"rjust01": (
'{% autoescape off %}.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.'
"{% endautoescape %}"
)
}
)
def test_rjust01(self):
output = self.engine.render_to_string(
"rjust01", {"a": "a&b", "b": mark_safe("a&b")}
)
self.assertEqual(output, ". a&b. . a&b.")
@setup({"rjust02": '.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.'})
def test_rjust02(self):
output = self.engine.render_to_string(
"rjust02", {"a": "a&b", "b": mark_safe("a&b")}
)
self.assertEqual(output, ". a&b. . a&b.")
|
RjustTests
|
python
|
modin-project__modin
|
modin/tests/config/test_envvars.py
|
{
"start": 10626,
"end": 29914
}
|
class ____:
@pytest.mark.parametrize(
"engine, storage_format, expected_backend",
[
("Python", "Pandas", "Python_Test"),
("Ray", "Pandas", "Ray"),
param(
"Unidist",
"Pandas",
"Unidist",
marks=pytest.mark.skip(reason=UNIDIST_SKIP_REASON),
),
("Dask", "Pandas", "Dask"),
("Native", "Native", "Pandas"),
],
)
def test_setting_execution_changes_backend(
self, engine, storage_format, expected_backend
):
previous_backend = cfg.Backend.get()
with switch_execution(engine, storage_format):
assert cfg.Backend.get() == expected_backend
assert cfg.Backend.get() == previous_backend
def test_subscribing_to_backend_triggers_callback(self):
backend_subscriber = Mock()
cfg.Backend.subscribe(backend_subscriber)
backend_subscriber.assert_called_once_with(cfg.Backend)
def test_setting_backend_triggers_all_callbacks(self):
# Start with a known backend (rather than the one that we start the
# test with).
with cfg.context(Backend="Pandas"):
backend_subscriber = Mock()
cfg.Backend.subscribe(backend_subscriber)
backend_subscriber.reset_mock()
storage_format_subscriber = Mock()
cfg.StorageFormat.subscribe(storage_format_subscriber)
storage_format_subscriber.reset_mock()
engine_subscriber = Mock()
cfg.Engine.subscribe(engine_subscriber)
engine_subscriber.reset_mock()
with cfg.context(Backend="Python_Test"):
backend_subscriber.assert_called_once_with(cfg.Backend)
storage_format_subscriber.assert_called_once_with(cfg.StorageFormat)
engine_subscriber.assert_called_once_with(cfg.Engine)
@pytest.mark.parametrize(
"backend, expected_engine, expected_storage_format",
[
("Python_test", "Python", "Pandas"),
("PYTHON_test", "Python", "Pandas"),
("python_TEST", "Python", "Pandas"),
("Ray", "Ray", "Pandas"),
param(
"Unidist",
"Unidist",
"Pandas",
marks=pytest.mark.skip(reason=UNIDIST_SKIP_REASON),
),
("Dask", "Dask", "Pandas"),
("Pandas", "Native", "Native"),
],
)
def test_setting_backend_changes_execution(
self, backend, expected_engine, expected_storage_format
):
previous_engine = cfg.Engine.get()
previous_storage_format = cfg.StorageFormat.get()
with cfg.context(Backend=backend):
assert cfg.Engine.get() == expected_engine
assert cfg.StorageFormat.get() == expected_storage_format
assert cfg.Engine.get() == previous_engine
assert cfg.StorageFormat.get() == previous_storage_format
def test_setting_engine_alone_changes_backend(self):
# Start with a known backend (rather than the one that we start the
# test with).
with switch_execution(storage_format="Pandas", engine="Ray"):
current_backend = cfg.Backend.get()
assert current_backend == "Ray"
with cfg.context(Engine="Python"):
assert cfg.Backend.get() == "Python_Test"
assert cfg.Backend.get() == current_backend
def test_setting_engine_triggers_callbacks(self):
# Start with a known backend (rather than the one that we start the
# test with).
with switch_execution(storage_format="Pandas", engine="Ray"):
engine_subscriber = Mock()
cfg.Engine.subscribe(engine_subscriber)
engine_subscriber.reset_mock()
backend_subscriber = Mock()
cfg.Backend.subscribe(backend_subscriber)
backend_subscriber.reset_mock()
storage_format_subscriber = Mock()
cfg.StorageFormat.subscribe(storage_format_subscriber)
storage_format_subscriber.reset_mock()
with cfg.context(Engine="Dask"):
engine_subscriber.assert_called_once_with(cfg.Engine)
backend_subscriber.assert_called_once_with(cfg.Backend)
# StorageFormat stayed the same, so we don't call its callback.
storage_format_subscriber.assert_not_called()
def test_setting_storage_format_triggers_callbacks(self):
# There's only one built-in storage format, pandas, so we add a new one
# here.
cfg.StorageFormat.add_option("Pandasduplicate")
from modin.core.execution.dispatching.factories import factories
factories.PandasduplicateOnRayFactory = factories.PandasOnRayFactory
cfg.Backend.register_backend(
"NewBackend",
cfg.Execution(
storage_format="Pandasduplicate",
engine="Ray",
),
)
with switch_execution(storage_format="Pandas", engine="Ray"):
engine_subscriber = Mock()
cfg.Engine.subscribe(engine_subscriber)
engine_subscriber.reset_mock()
backend_subscriber = Mock()
cfg.Backend.subscribe(backend_subscriber)
backend_subscriber.reset_mock()
storage_format_subscriber = Mock()
cfg.StorageFormat.subscribe(storage_format_subscriber)
storage_format_subscriber.reset_mock()
with cfg.context(StorageFormat="PANDASDUPLICATE"):
storage_format_subscriber.assert_called_once_with(cfg.StorageFormat)
backend_subscriber.assert_called_once_with(cfg.Backend)
# Engine stayed the same, so we don't call its callback.
engine_subscriber.assert_not_called()
@pytest.mark.parametrize("name", ["Python_Test", "python_Test"])
def test_register_existing_backend(self, name):
with pytest.raises(
ValueError,
match=re.escape(
"Backend 'Python_Test' is already registered with the execution "
+ "Execution(storage_format='Pandas', engine='Python')"
),
):
cfg.Backend.register_backend(
name,
cfg.Execution(
storage_format="Pandas",
engine="Python",
),
)
def test_register_existing_execution(self):
with pytest.raises(
ValueError,
match=re.escape(
"Execution(storage_format='Pandas', engine='Python') is already registered with the backend Python_Test."
),
):
cfg.Backend.register_backend(
"NewBackend2",
cfg.Execution(
storage_format="Pandas",
engine="Python",
),
)
def test_set_invalid_backend(self):
with pytest.raises(ValueError, match=re.escape("Unknown backend 'Unknown'")):
cfg.Backend.put("Unknown")
def test_switch_to_unregistered_backend_with_switch_execution(self):
cfg.StorageFormat.add_option("Pandas2")
from modin.core.execution.dispatching.factories import factories
factories.Pandas2OnRayFactory = factories.PandasOnRayFactory
with pytest.raises(
ValueError,
match=re.escape(
"Execution(storage_format='Pandas2', engine='Ray') "
+ "has no known backend. Please register a backend for it with "
+ "Backend.register_backend()"
),
), switch_execution(engine="Ray", storage_format="Pandas2"):
pass
def test_switch_to_unregistered_backend_with_switch_storage_format(self):
cfg.StorageFormat.add_option("Pandas3")
from modin.core.execution.dispatching.factories import factories
factories.Pandas2OnRayFactory = factories.PandasOnPythonFactory
with cfg.context(StorageFormat="Pandas", Engine="Python"):
with pytest.raises(
ValueError,
match=re.escape(
"Execution(storage_format='Pandas3', engine='Python') "
+ "has no known backend. Please register a backend for it with "
+ "Backend.register_backend()"
),
):
cfg.StorageFormat.put("Pandas3")
def test_switch_to_unregistered_backend_with_switch_engine(self):
cfg.Engine.add_option("Python2")
from modin.core.execution.dispatching.factories import factories
factories.PandasOnPython2Factory = factories.PandasOnPythonFactory
with cfg.context(StorageFormat="Pandas", Engine="Python"):
with pytest.raises(
ValueError,
match=re.escape(
"Execution(storage_format='Pandas', engine='Python2') "
+ "has no known backend. Please register a backend for it with "
+ "Backend.register_backend()"
),
):
cfg.Engine.put("Python2")
# The default engine and storage format, and hence the default backend,
# will depend on which engines are available in the current environment.
# For simplicity, patch the defaults.
@patch(
target="modin.config.StorageFormat._get_default",
)
@patch(
target="modin.config.Engine._get_default",
)
def test_backend_default(
self,
mocked_get_default,
mocked_get_default2,
):
mocked_get_default.return_value = "Native"
mocked_get_default2.return_value = "Native"
assert cfg.Backend._get_default() == "Pandas"
def test_add_backend_option(self):
with pytest.raises(
ValueError,
match=re.escape(
"Cannot add an option to Backend directly. Use Backend.register_backend instead."
),
):
cfg.Backend.add_option("NewBackend")
@pytest.mark.parametrize(
"order_to_get_in",
itertools.permutations(
[
cfg.Backend,
cfg.Engine,
cfg.StorageFormat,
]
),
ids=lambda permutation: "_".join(x.__name__ for x in permutation),
)
@pytest.mark.parametrize(
"storage_environment_variable, engine_environment_variable, variable_to_expected_value",
[
(
"Native",
"Native",
{
cfg.Backend: "Pandas",
cfg.Engine: "Native",
cfg.StorageFormat: "Native",
},
),
(
"NATIVE",
"NATIVE",
{
cfg.Backend: "Pandas",
cfg.Engine: "Native",
cfg.StorageFormat: "Native",
},
),
(
"Pandas",
"Dask",
{
cfg.Backend: "Dask",
cfg.Engine: "Dask",
cfg.StorageFormat: "Pandas",
},
),
],
)
def test_storage_format_and_engine_come_from_environment(
self,
monkeypatch,
clear_backend_execution_and_storage_format,
order_to_get_in,
storage_environment_variable,
engine_environment_variable,
variable_to_expected_value,
):
with mock.patch.dict(
os.environ,
{
cfg.StorageFormat.varname: storage_environment_variable,
cfg.Engine.varname: engine_environment_variable,
},
):
for variable in order_to_get_in:
expected_value = variable_to_expected_value[variable]
assert (
variable.get() == expected_value
), f"{variable.__name__} was {variable.get()} instead of {expected_value}"
@pytest.mark.parametrize(
"order_to_get_in",
itertools.permutations(
[
cfg.Backend,
cfg.Engine,
cfg.StorageFormat,
]
),
ids=lambda permutation: "_".join(x.__name__ for x in permutation),
)
@pytest.mark.parametrize(
"engine_environment_variable, variable_to_expected_value",
[
(
"Dask",
{cfg.Backend: "Dask", cfg.StorageFormat: "Pandas", cfg.Engine: "Dask"},
),
(
"DASK",
{cfg.Backend: "Dask", cfg.StorageFormat: "Pandas", cfg.Engine: "Dask"},
),
(
"python",
{
cfg.Backend: "Python_Test",
cfg.StorageFormat: "Pandas",
cfg.Engine: "Python",
},
),
(
"ray",
{cfg.Backend: "Ray", cfg.StorageFormat: "Pandas", cfg.Engine: "Ray"},
),
# note that we can't test Native here because it's not valid to use
# "Native" engine with the default storage format of "Pandas."
],
)
def test_only_engine_comes_from_environment(
self,
clear_backend_execution_and_storage_format,
order_to_get_in,
engine_environment_variable,
variable_to_expected_value,
):
with mock.patch.dict(
os.environ,
{cfg.Engine.varname: engine_environment_variable},
):
for var in order_to_get_in:
expected_value = variable_to_expected_value[var]
assert (
var.get() == expected_value
), f"{var.__name__} was {var.get()} instead of {expected_value}"
@pytest.mark.parametrize(
"order_to_get_in",
itertools.permutations(
[
cfg.Backend,
cfg.Engine,
cfg.StorageFormat,
]
),
ids=lambda permutation: "_".join(x.__name__ for x in permutation),
)
def test_only_storage_format_comes_from_environment(
self,
clear_backend_execution_and_storage_format,
order_to_get_in,
add_pandas_duplicate_on_ray_execution,
):
# To test switching StorageFormat alone, we have to add a new backend
# that works with the default "Pandas" execution.
with mock.patch.dict(
os.environ,
{
cfg.StorageFormat.varname: "Test_Pandasduplicate",
},
):
cfg.Engine.put("Ray")
for variable in order_to_get_in:
expected_value = {
cfg.Backend: "Test_Backend_1",
cfg.Engine: "Ray",
cfg.StorageFormat: "Test_Pandasduplicate",
}[variable]
assert (
variable.get() == expected_value
), f"{variable.__name__} was {variable.get()} instead of {expected_value}"
@pytest.mark.parametrize(
"order_to_get_in",
itertools.permutations(
[
cfg.Backend,
cfg.Engine,
cfg.StorageFormat,
]
),
ids=lambda permutation: "_".join(x.__name__ for x in permutation),
)
@pytest.mark.parametrize(
"backend_environment_variable, variable_to_expected_value",
[
(
"Pandas",
{
cfg.Backend: "Pandas",
cfg.Engine: "Native",
cfg.StorageFormat: "Native",
},
),
(
"Ray",
{cfg.Backend: "Ray", cfg.Engine: "Ray", cfg.StorageFormat: "Pandas"},
),
(
"Dask",
{cfg.Backend: "Dask", cfg.Engine: "Dask", cfg.StorageFormat: "Pandas"},
),
(
"python_test",
{
cfg.Backend: "Python_Test",
cfg.Engine: "Python",
cfg.StorageFormat: "Pandas",
},
),
],
)
def test_backend_comes_from_environment(
self,
monkeypatch,
clear_backend_execution_and_storage_format,
order_to_get_in,
backend_environment_variable,
variable_to_expected_value,
):
with mock.patch.dict(
os.environ,
{
cfg.Backend.varname: backend_environment_variable,
},
):
for variable in order_to_get_in:
expected_value = variable_to_expected_value[variable]
assert (
variable.get() == expected_value
), f"{variable.__name__} was {variable.get()} instead of {expected_value}"
@pytest.mark.parametrize(
"order_to_get_in",
itertools.permutations(
[cfg.Backend, cfg.Engine, cfg.StorageFormat],
),
ids=lambda permutation: "_".join(x.__name__ for x in permutation),
)
def test_environment_not_set_and_pick_up_default_engine(
self, clear_backend_execution_and_storage_format, order_to_get_in
):
for variable in order_to_get_in:
assert variable.get() == variable._get_default()
@pytest.mark.parametrize(
"execution_variable, value",
[(cfg.Engine, "Python"), (cfg.StorageFormat, "Pandas")],
)
@pytest.mark.parametrize(
"variable_to_get",
[cfg.Backend, cfg.Engine, cfg.StorageFormat],
)
def test_conflicting_execution_and_backend_in_environment(
self,
monkeypatch,
clear_backend_execution_and_storage_format,
execution_variable,
value,
variable_to_get,
):
monkeypatch.setitem(os.environ, cfg.Backend.varname, "Ray")
monkeypatch.setitem(os.environ, execution_variable.varname, value)
with pytest.raises(
ValueError,
match=re.escape("Can't specify both execution and backend in environment"),
):
variable_to_get.get()
def test_get_execution_for_unknown_backend(self):
backend_choice_string = ", ".join(
f"'{choice}'" for choice in cfg.Backend.choices
)
with pytest.raises(
ValueError,
match=re.escape(
f"Unknown backend 'Unknown'. Available backends are: {backend_choice_string}"
),
):
cfg.Backend.get_execution_for_backend("Unknown")
@pytest.mark.parametrize(
"config_name",
[
"NPartitions",
"CpuCount",
"LogMemoryInterval",
"LogFileSize",
"MinRowPartitionSize",
"MinColumnPartitionSize",
],
)
def test_wrong_values(config_name):
config: cfg.EnvironmentVariable = getattr(cfg, config_name)
new_value = -1
with pytest.raises(ValueError):
with cfg.context(**{config_name: new_value}):
_ = config.get()
|
TestBackend
|
python
|
cython__cython
|
Cython/Compiler/PyrexTypes.py
|
{
"start": 88937,
"end": 89110
}
|
class ____(CIntType):
to_py_function = "PyLong_FromSsize_t"
from_py_function = "PyLong_AsSsize_t"
def sign_and_name(self):
return "Py_ssize_t"
|
CSSizeTType
|
python
|
getsentry__sentry
|
tests/sentry/seer/assisted_query/test_issues_tools.py
|
{
"start": 22395,
"end": 30849
}
|
class ____(APITestCase, SnubaTestCase):
databases = {"default", "control"}
def setUp(self):
super().setUp()
self.min_ago = before_now(minutes=1)
def test_get_issues_stats_success(self):
"""Test that get_issues_stats returns stats for issues"""
# Store two events to create issues
event1 = self.store_event(
data={
"event_id": "a" * 32,
"message": "First error",
"timestamp": self.min_ago.isoformat(),
},
project_id=self.project.id,
)
event2 = self.store_event(
data={
"event_id": "b" * 32,
"message": "Second error",
"timestamp": self.min_ago.isoformat(),
},
project_id=self.project.id,
)
issue_ids = [str(event1.group_id), str(event2.group_id)]
result = get_issues_stats(
org_id=self.organization.id,
issue_ids=issue_ids,
project_ids=[self.project.id],
query="is:unresolved",
stats_period="24h",
)
assert result is not None
assert isinstance(result, list)
assert len(result) == 2
# Verify each stat has the expected fields
for stat in result:
assert "id" in stat
assert "count" in stat
assert "userCount" in stat
assert "firstSeen" in stat
assert "lastSeen" in stat
assert stat["id"] in issue_ids
# Verify stats field structure
# stats should be a dict with stats_period keys (e.g., "24h", "14d")
# Each value is an array of (timestamp, count) tuples
assert "stats" in stat
assert isinstance(stat["stats"], dict)
# Should have the stats_period key we passed ("24h")
assert "24h" in stat["stats"]
# The value should be an array of tuples
assert isinstance(stat["stats"]["24h"], list)
# Each element should be a tuple of (timestamp, count) where both are numbers
for data_point in stat["stats"]["24h"]:
assert isinstance(data_point, tuple)
assert len(data_point) == 2
assert isinstance(data_point[0], (int, float)) # timestamp
assert isinstance(data_point[1], (int, float)) # count
# Verify lifetime field structure
# lifetime should be a dict with count, userCount, firstSeen, lastSeen
assert "lifetime" in stat
assert isinstance(stat["lifetime"], dict)
assert "count" in stat["lifetime"]
assert "userCount" in stat["lifetime"]
assert "firstSeen" in stat["lifetime"]
assert "lastSeen" in stat["lifetime"]
# count should be a string representation of the number
assert isinstance(stat["lifetime"]["count"], str)
# userCount should be an integer
assert isinstance(stat["lifetime"]["userCount"], int)
# firstSeen and lastSeen are datetime objects or None
assert stat["lifetime"]["firstSeen"] is None or isinstance(
stat["lifetime"]["firstSeen"], datetime
)
assert stat["lifetime"]["lastSeen"] is None or isinstance(
stat["lifetime"]["lastSeen"], datetime
)
def test_get_issues_stats_with_multiple_projects(self):
"""Test that get_issues_stats works with multiple project IDs"""
project2 = self.create_project(organization=self.organization)
event1 = self.store_event(
data={
"event_id": "a" * 32,
"message": "Project 1 error",
"timestamp": self.min_ago.isoformat(),
},
project_id=self.project.id,
)
event2 = self.store_event(
data={
"event_id": "b" * 32,
"message": "Project 2 error",
"timestamp": self.min_ago.isoformat(),
},
project_id=project2.id,
)
issue_ids = [str(event1.group_id), str(event2.group_id)]
result = get_issues_stats(
org_id=self.organization.id,
issue_ids=issue_ids,
project_ids=[self.project.id, project2.id],
query="is:unresolved",
stats_period="24h",
)
assert result is not None
assert isinstance(result, list)
# Should return stats for both issues
assert len(result) >= 2
returned_issue_ids = {stat["id"] for stat in result}
assert str(event1.group_id) in returned_issue_ids
assert str(event2.group_id) in returned_issue_ids
def test_get_issues_stats_nonexistent_org(self):
"""Test that get_issues_stats returns None for nonexistent org"""
result = get_issues_stats(
org_id=999999,
issue_ids=["123"],
project_ids=[self.project.id],
query="is:unresolved",
stats_period="24h",
)
assert result is None
def test_get_issues_stats_empty_issue_ids(self):
"""Test that get_issues_stats handles empty issue IDs"""
result = get_issues_stats(
org_id=self.organization.id,
issue_ids=[],
project_ids=[self.project.id],
query="is:unresolved",
stats_period="24h",
)
assert result is not None
assert isinstance(result, list)
assert len(result) == 0
def test_get_issues_stats_stats_and_lifetime_structure(self):
"""Test that stats and lifetime fields have the correct structure"""
# Create an issue
event = self.store_event(
data={
"event_id": "a" * 32,
"message": "Test error",
"timestamp": self.min_ago.isoformat(),
},
project_id=self.project.id,
)
result = get_issues_stats(
org_id=self.organization.id,
issue_ids=[str(event.group_id)],
project_ids=[self.project.id],
query="is:unresolved",
stats_period="24h",
)
assert result is not None
assert len(result) == 1
stat = result[0]
# Verify stats structure:
# stats is a dict where keys are stats_period strings (e.g., "24h", "14d")
# and values are arrays of (timestamp, count) tuples
assert "stats" in stat
assert isinstance(stat["stats"], dict)
assert "24h" in stat["stats"]
assert isinstance(stat["stats"]["24h"], list)
# Each element should be a tuple of (timestamp, count)
for timepoint in stat["stats"]["24h"]:
assert isinstance(timepoint, tuple)
assert len(timepoint) == 2
timestamp, count = timepoint
assert isinstance(timestamp, (int, float))
assert isinstance(count, (int, float))
# Timestamp should be a reasonable Unix timestamp (seconds since epoch)
# For 24h period, should be within last day
assert timestamp > 0
# Verify lifetime structure:
# lifetime is a dict with count (string), userCount (int), firstSeen (datetime), lastSeen (datetime)
assert "lifetime" in stat
assert isinstance(stat["lifetime"], dict)
lifetime = stat["lifetime"]
# Required fields
assert "count" in lifetime
assert "userCount" in lifetime
assert "firstSeen" in lifetime
assert "lastSeen" in lifetime
# Field types
assert isinstance(lifetime["count"], str)
# Count should be a numeric string representing the total times seen
# (e.g., "1", "42", "1000")
assert lifetime["count"].isdigit()
assert isinstance(lifetime["userCount"], int)
# firstSeen and lastSeen are datetime objects or None
if lifetime["firstSeen"] is not None:
assert isinstance(lifetime["firstSeen"], datetime)
if lifetime["lastSeen"] is not None:
assert isinstance(lifetime["lastSeen"], datetime)
# Optional stats field in lifetime (currently None in implementation)
if "stats" in lifetime:
assert lifetime["stats"] is None or isinstance(lifetime["stats"], dict)
|
TestGetIssuesStats
|
python
|
getsentry__sentry
|
src/sentry/rules/conditions/existing_high_priority_issue.py
|
{
"start": 440,
"end": 1727
}
|
class ____(EventCondition):
id = "sentry.rules.conditions.high_priority_issue.ExistingHighPriorityIssueCondition"
label = "Sentry marks an existing issue as high priority"
def passes(self, event: GroupEvent, state: EventState) -> bool:
if state.is_new:
return False
return state.has_escalated and event.group.priority == PriorityLevel.HIGH
def get_activity(
self, start: datetime, end: datetime, limit: int
) -> Sequence[ConditionActivity]:
activities = (
Activity.objects.filter(
project=self.project,
datetime__gte=start,
datetime__lt=end,
data={"priority": "high", "reason": "escalating"},
type__in=[ActivityType.SET_PRIORITY.value],
user_id=None,
)
.order_by("-datetime")[:limit]
.values_list("group", "datetime", "data")
)
return [
ConditionActivity(
group_id=group_id,
type=ConditionActivityType.EXISTING_HIGH_PRIORITY_ISSUE,
timestamp=timestamp,
)
for group_id, timestamp, data in activities
if group_id is not None
]
|
ExistingHighPriorityIssueCondition
|
python
|
falconry__falcon
|
tests/test_httperror.py
|
{
"start": 36515,
"end": 40570
}
|
class ____:
@pytest.fixture
def client(self, util, asgi):
app = util.create_app(asgi)
app.add_route('/', GoneResource())
return testing.TestClient(app)
def test_unknown_accept(self, client):
res = client.simulate_get(headers={'Accept': 'foo/bar'})
assert res.content_type == 'application/json'
assert res.headers['vary'] == 'Accept'
assert res.content == b''
@pytest.mark.parametrize('has_json_handler', [True, False])
def test_defaults_to_json(self, client, has_json_handler):
if not has_json_handler:
client.app.req_options.media_handlers.pop(MEDIA_JSON)
client.app.resp_options.media_handlers.pop(MEDIA_JSON)
res = client.simulate_get()
assert res.content_type == 'application/json'
assert res.headers['vary'] == 'Accept'
assert res.content == JSON_CONTENT
@pytest.mark.parametrize(
'accept, content_type, content',
(JSON, XML, CUSTOM_JSON, CUSTOM_XML, YAML, ASYNC_ONLY, ASYNC_WITH_SYNC),
)
def test_serializes_error_to_preferred_by_sender(
self, accept, content_type, content, client, asgi
):
client.app.resp_options.xml_error_serialization = True
client.app.resp_options.media_handlers[MEDIA_YAML] = FakeYamlMediaHandler()
client.app.resp_options.media_handlers[ASYNC_WITH_SYNC[0]] = (
SyncInterfaceMediaHandler()
)
if asgi:
client.app.resp_options.media_handlers[ASYNC_ONLY[0]] = (
AsyncOnlyMediaHandler()
)
res = client.simulate_get(headers={'Accept': accept})
assert res.headers['vary'] == 'Accept'
if content_type == ASYNC_ONLY[0] and not asgi:
# media-json is the default content type
assert res.content_type == MEDIA_JSON
assert res.content == b''
else:
assert res.content_type == content_type
assert res.content == content
def test_json_async_only_error(self, util):
app = util.create_app(True)
app.add_route('/', GoneResource())
app.resp_options.media_handlers[MEDIA_JSON] = AsyncOnlyMediaHandler()
client = testing.TestClient(app)
with pytest.raises(NotImplementedError, match='requires the sync interface'):
client.simulate_get()
@pytest.mark.parametrize('accept', [MEDIA_XML, 'application/xhtml+xml'])
def test_add_xml_handler(self, client, enable_xml, accept):
enable_xml(client.app)
client.app.resp_options.media_handlers[MEDIA_XML] = FakeYamlMediaHandler()
res = client.simulate_get(headers={'Accept': accept})
assert res.content_type == MEDIA_XML
assert res.content == YAML[-1]
@pytest.mark.parametrize(
'accept, content_type',
[
(
# firefox
'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,'
'image/webp,image/png,image/svg+xml,*/*;q=0.8',
MEDIA_XML,
),
(
# safari / chrome
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,'
'image/apng,*/*;q=0.8',
MEDIA_XML,
),
('text/html, application/xhtml+xml, image/jxr, */*', MEDIA_JSON), # edge
(f'text/html,{MEDIA_YAML};q=0.8,*/*;q=0.7', MEDIA_YAML),
(f'text/html,{MEDIA_YAML};q=0.8,{MEDIA_JSON};q=0.8', MEDIA_JSON),
],
)
def test_hard_content_types(self, client, accept, content_type, enable_xml):
has_xml = enable_xml(client.app)
client.app.resp_options.default_media_type = 'my_type'
client.app.resp_options.media_handlers[MEDIA_YAML] = FakeYamlMediaHandler()
res = client.simulate_get(headers={'Accept': accept})
if has_xml or content_type != MEDIA_XML:
assert res.content_type == content_type
else:
assert res.content_type == MEDIA_JSON
|
TestDefaultSerializeError
|
python
|
walkccc__LeetCode
|
solutions/3142. Check if Grid Satisfies Conditions/3142.py
|
{
"start": 0,
"end": 360
}
|
class ____:
def satisfiesConditions(self, grid: list[list[int]]) -> bool:
m = len(grid)
n = len(grid[0])
return (all(grid[i][j] == grid[i + 1][j]
for i in range(m - 1)
for j in range(n)) and
all(grid[i][j] != grid[i][j + 1]
for i in range(m)
for j in range(n - 1)))
|
Solution
|
python
|
microsoft__pyright
|
packages/pyright-internal/src/tests/samples/paramSpec40.py
|
{
"start": 608,
"end": 862
}
|
class ____(TypedDict, total=False):
e: str
f: str
def func3(
a: int, b: int, /, *, c: str = ..., d: str = ..., **kwargs: Unpack[TD1]
) -> float: ...
call(func3, 1, 2, e="", c="")
call(func3, 1, 2, c="", d="", e="")
call(func3, 1, 2, e="")
|
TD1
|
python
|
google__flatbuffers
|
tests/MyGame/Example/NestedStruct.py
|
{
"start": 3326,
"end": 5225
}
|
class ____(object):
# NestedStructT
def __init__(
self,
a = None,
b = 0,
c = None,
d = None,
):
self.a = a # type: Optional[List[int]]
self.b = b # type: int
self.c = c # type: Optional[List[int]]
self.d = d # type: Optional[List[int]]
@classmethod
def InitFromBuf(cls, buf, pos):
nestedStruct = NestedStruct()
nestedStruct.Init(buf, pos)
return cls.InitFromObj(nestedStruct)
@classmethod
def InitFromPackedBuf(cls, buf, pos=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos)
return cls.InitFromBuf(buf, pos+n)
@classmethod
def InitFromObj(cls, nestedStruct):
x = NestedStructT()
x._UnPack(nestedStruct)
return x
# NestedStructT
def _UnPack(self, nestedStruct):
if nestedStruct is None:
return
if not nestedStruct.AIsNone():
if np is None:
self.a = []
for i in range(nestedStruct.ALength()):
self.a.append(nestedStruct.A(i))
else:
self.a = nestedStruct.AAsNumpy()
self.b = nestedStruct.B()
if not nestedStruct.CIsNone():
if np is None:
self.c = []
for i in range(nestedStruct.CLength()):
self.c.append(nestedStruct.C(i))
else:
self.c = nestedStruct.CAsNumpy()
if not nestedStruct.DIsNone():
if np is None:
self.d = []
for i in range(nestedStruct.DLength()):
self.d.append(nestedStruct.D(i))
else:
self.d = nestedStruct.DAsNumpy()
# NestedStructT
def Pack(self, builder):
return CreateNestedStruct(builder, self.a, self.b, self.c, self.d)
|
NestedStructT
|
python
|
jazzband__django-pipeline
|
pipeline/finders.py
|
{
"start": 2605,
"end": 3333
}
|
class ____(PatternFilterMixin, DjangoFileSystemFinder):
"""
Like FileSystemFinder, but doesn't return any additional ignored patterns
This allows us to concentrate/compress our components without dragging
the raw versions in too.
"""
ignore_patterns = [
"*.js",
"*.css",
"*.less",
"*.scss",
"*.styl",
"*.sh",
"*.html",
"*.md",
"*.markdown",
"*.php",
"*.txt",
"README*",
"LICENSE*",
"*examples*",
"*test*",
"*bin*",
"*samples*",
"*docs*",
"*build*",
"*demo*",
"Makefile*",
"Gemfile*",
"node_modules",
]
|
FileSystemFinder
|
python
|
ray-project__ray
|
python/ray/train/tests/test_torch_utils.py
|
{
"start": 3865,
"end": 4920
}
|
class ____:
def test_load_module(self):
assert load_torch_model(torch_module) == torch_module
def test_load_state_dict(self):
state_dict = torch_module.state_dict()
model_definition = torch.nn.Linear(1, 1)
assert model_definition.state_dict() != state_dict
assert load_torch_model(state_dict, model_definition).state_dict() == state_dict
def test_load_state_dict_fail(self):
with pytest.raises(ValueError):
# model_definition is required to load state dict.
load_torch_model(torch_module.state_dict())
def test_contains_tensor():
t = torch.tensor([0])
assert contains_tensor(t)
assert contains_tensor([1, 2, 3, t, 5, 6])
assert contains_tensor([1, 2, 3, {"dict": t}, 5, 6])
assert contains_tensor({"outer": [1, 2, 3, {"dict": t}, 5, 6]})
assert contains_tensor({t: [1, 2, 3, {"dict": 2}, 5, 6]})
assert not contains_tensor([4, 5, 6])
if __name__ == "__main__":
import sys
sys.exit(pytest.main(["-sv", __file__]))
|
TestLoadTorchModel
|
python
|
TheAlgorithms__Python
|
maths/numerical_analysis/adams_bashforth.py
|
{
"start": 262,
"end": 7099
}
|
class ____:
"""
args:
func: An ordinary differential equation (ODE) as function of x and y.
x_initials: List containing initial required values of x.
y_initials: List containing initial required values of y.
step_size: The increment value of x.
x_final: The final value of x.
Returns: Solution of y at each nodal point
>>> def f(x, y):
... return x + y
>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0.2, 1], 0.2, 1) # doctest: +ELLIPSIS
AdamsBashforth(func=..., x_initials=[0, 0.2, 0.4], y_initials=[0, 0.2, 1], step...)
>>> AdamsBashforth(f, [0, 0.2, 1], [0, 0, 0.04], 0.2, 1).step_2()
Traceback (most recent call last):
...
ValueError: The final value of x must be greater than the initial values of x.
>>> AdamsBashforth(f, [0, 0.2, 0.3], [0, 0, 0.04], 0.2, 1).step_3()
Traceback (most recent call last):
...
ValueError: x-values must be equally spaced according to step size.
>>> AdamsBashforth(f,[0,0.2,0.4,0.6,0.8],[0,0,0.04,0.128,0.307],-0.2,1).step_5()
Traceback (most recent call last):
...
ValueError: Step size must be positive.
"""
func: Callable[[float, float], float]
x_initials: list[float]
y_initials: list[float]
step_size: float
x_final: float
def __post_init__(self) -> None:
if self.x_initials[-1] >= self.x_final:
raise ValueError(
"The final value of x must be greater than the initial values of x."
)
if self.step_size <= 0:
raise ValueError("Step size must be positive.")
if not all(
round(x1 - x0, 10) == self.step_size
for x0, x1 in zip(self.x_initials, self.x_initials[1:])
):
raise ValueError("x-values must be equally spaced according to step size.")
def step_2(self) -> np.ndarray:
"""
>>> def f(x, y):
... return x
>>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_2()
array([0. , 0. , 0.06, 0.16, 0.3 , 0.48])
>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_2()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""
if len(self.x_initials) != 2 or len(self.y_initials) != 2:
raise ValueError("Insufficient initial points information.")
x_0, x_1 = self.x_initials[:2]
y_0, y_1 = self.y_initials[:2]
n = int((self.x_final - x_1) / self.step_size)
y = np.zeros(n + 2)
y[0] = y_0
y[1] = y_1
for i in range(n):
y[i + 2] = y[i + 1] + (self.step_size / 2) * (
3 * self.func(x_1, y[i + 1]) - self.func(x_0, y[i])
)
x_0 = x_1
x_1 += self.step_size
return y
def step_3(self) -> np.ndarray:
"""
>>> def f(x, y):
... return x + y
>>> y = AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_3()
>>> float(y[3])
0.15533333333333332
>>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_3()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""
if len(self.x_initials) != 3 or len(self.y_initials) != 3:
raise ValueError("Insufficient initial points information.")
x_0, x_1, x_2 = self.x_initials[:3]
y_0, y_1, y_2 = self.y_initials[:3]
n = int((self.x_final - x_2) / self.step_size)
y = np.zeros(n + 4)
y[0] = y_0
y[1] = y_1
y[2] = y_2
for i in range(n + 1):
y[i + 3] = y[i + 2] + (self.step_size / 12) * (
23 * self.func(x_2, y[i + 2])
- 16 * self.func(x_1, y[i + 1])
+ 5 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 += self.step_size
return y
def step_4(self) -> np.ndarray:
"""
>>> def f(x,y):
... return x + y
>>> y = AdamsBashforth(
... f, [0, 0.2, 0.4, 0.6], [0, 0, 0.04, 0.128], 0.2, 1).step_4()
>>> float(y[4])
0.30699999999999994
>>> float(y[5])
0.5771083333333333
>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_4()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""
if len(self.x_initials) != 4 or len(self.y_initials) != 4:
raise ValueError("Insufficient initial points information.")
x_0, x_1, x_2, x_3 = self.x_initials[:4]
y_0, y_1, y_2, y_3 = self.y_initials[:4]
n = int((self.x_final - x_3) / self.step_size)
y = np.zeros(n + 4)
y[0] = y_0
y[1] = y_1
y[2] = y_2
y[3] = y_3
for i in range(n):
y[i + 4] = y[i + 3] + (self.step_size / 24) * (
55 * self.func(x_3, y[i + 3])
- 59 * self.func(x_2, y[i + 2])
+ 37 * self.func(x_1, y[i + 1])
- 9 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 = x_3
x_3 += self.step_size
return y
def step_5(self) -> np.ndarray:
"""
>>> def f(x,y):
... return x + y
>>> y = AdamsBashforth(
... f, [0, 0.2, 0.4, 0.6, 0.8], [0, 0.02140, 0.02140, 0.22211, 0.42536],
... 0.2, 1).step_5()
>>> float(y[-1])
0.05436839444444452
>>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_5()
Traceback (most recent call last):
...
ValueError: Insufficient initial points information.
"""
if len(self.x_initials) != 5 or len(self.y_initials) != 5:
raise ValueError("Insufficient initial points information.")
x_0, x_1, x_2, x_3, x_4 = self.x_initials[:5]
y_0, y_1, y_2, y_3, y_4 = self.y_initials[:5]
n = int((self.x_final - x_4) / self.step_size)
y = np.zeros(n + 6)
y[0] = y_0
y[1] = y_1
y[2] = y_2
y[3] = y_3
y[4] = y_4
for i in range(n + 1):
y[i + 5] = y[i + 4] + (self.step_size / 720) * (
1901 * self.func(x_4, y[i + 4])
- 2774 * self.func(x_3, y[i + 3])
- 2616 * self.func(x_2, y[i + 2])
- 1274 * self.func(x_1, y[i + 1])
+ 251 * self.func(x_0, y[i])
)
x_0 = x_1
x_1 = x_2
x_2 = x_3
x_3 = x_4
x_4 += self.step_size
return y
if __name__ == "__main__":
import doctest
doctest.testmod()
|
AdamsBashforth
|
python
|
microsoft__pyright
|
packages/pyright-internal/src/tests/samples/callbackProtocol1.py
|
{
"start": 2268,
"end": 2474
}
|
class ____:
def __call__(self) -> None:
pass
def test_func7(*args: *tuple[int, *tuple[int, ...]]) -> int:
return 123
# This should generate an error.
f7: TestClass7 = test_func7
|
TestClass7
|
python
|
HypothesisWorks__hypothesis
|
hypothesis-python/tests/attrs/test_pretty.py
|
{
"start": 2243,
"end": 2436
}
|
class ____:
@attrs.define
class A:
x: int
def test_includes_namespace_classes_in_pretty():
obj = Namespace.A(x=1)
assert pretty.pretty(obj) == "Namespace.A(x=1)"
|
Namespace
|
python
|
spack__spack
|
lib/spack/spack/vendor/jinja2/runtime.py
|
{
"start": 4121,
"end": 12787
}
|
class ____:
"""The template context holds the variables of a template. It stores the
values passed to the template and also the names the template exports.
Creating instances is neither supported nor useful as it's created
automatically at various stages of the template evaluation and should not
be created by hand.
The context is immutable. Modifications on :attr:`parent` **must not**
happen and modifications on :attr:`vars` are allowed from generated
template code only. Template filters and global functions marked as
:func:`pass_context` get the active context passed as first argument
and are allowed to access the context read-only.
The template context supports read only dict operations (`get`,
`keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
`__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`
method that doesn't fail with a `KeyError` but returns an
:class:`Undefined` object for missing variables.
"""
_legacy_resolve_mode: t.ClassVar[bool] = False
def __init_subclass__(cls) -> None:
if "resolve_or_missing" in cls.__dict__:
# If the subclass overrides resolve_or_missing it opts in to
# modern mode no matter what.
cls._legacy_resolve_mode = False
elif "resolve" in cls.__dict__ or cls._legacy_resolve_mode:
# If the subclass overrides resolve, or if its base is
# already in legacy mode, warn about legacy behavior.
import warnings
warnings.warn(
"Overriding 'resolve' is deprecated and will not have"
" the expected behavior in Jinja 3.1. Override"
" 'resolve_or_missing' instead ",
DeprecationWarning,
stacklevel=2,
)
cls._legacy_resolve_mode = True
def __init__(
self,
environment: "Environment",
parent: t.Dict[str, t.Any],
name: t.Optional[str],
blocks: t.Dict[str, t.Callable[["Context"], t.Iterator[str]]],
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
):
self.parent = parent
self.vars: t.Dict[str, t.Any] = {}
self.environment: "Environment" = environment
self.eval_ctx = EvalContext(self.environment, name)
self.exported_vars: t.Set[str] = set()
self.name = name
self.globals_keys = set() if globals is None else set(globals)
# create the initial mapping of blocks. Whenever template inheritance
# takes place the runtime will update this mapping with the new blocks
# from the template.
self.blocks = {k: [v] for k, v in blocks.items()}
def super(
self, name: str, current: t.Callable[["Context"], t.Iterator[str]]
) -> t.Union["BlockReference", "Undefined"]:
"""Render a parent block."""
try:
blocks = self.blocks[name]
index = blocks.index(current) + 1
blocks[index]
except LookupError:
return self.environment.undefined(
f"there is no parent block called {name!r}.", name="super"
)
return BlockReference(name, self, blocks, index)
def get(self, key: str, default: t.Any = None) -> t.Any:
"""Look up a variable by name, or return a default if the key is
not found.
:param key: The variable name to look up.
:param default: The value to return if the key is not found.
"""
try:
return self[key]
except KeyError:
return default
def resolve(self, key: str) -> t.Union[t.Any, "Undefined"]:
"""Look up a variable by name, or return an :class:`Undefined`
object if the key is not found.
If you need to add custom behavior, override
:meth:`resolve_or_missing`, not this method. The various lookup
functions use that method, not this one.
:param key: The variable name to look up.
"""
if self._legacy_resolve_mode:
if key in self.vars:
return self.vars[key]
if key in self.parent:
return self.parent[key]
return self.environment.undefined(name=key)
rv = self.resolve_or_missing(key)
if rv is missing:
return self.environment.undefined(name=key)
return rv
def resolve_or_missing(self, key: str) -> t.Any:
"""Look up a variable by name, or return a ``missing`` sentinel
if the key is not found.
Override this method to add custom lookup behavior.
:meth:`resolve`, :meth:`get`, and :meth:`__getitem__` use this
method. Don't call this method directly.
:param key: The variable name to look up.
"""
if self._legacy_resolve_mode:
rv = self.resolve(key)
if isinstance(rv, Undefined):
return missing
return rv
if key in self.vars:
return self.vars[key]
if key in self.parent:
return self.parent[key]
return missing
def get_exported(self) -> t.Dict[str, t.Any]:
"""Get a new dict with the exported variables."""
return {k: self.vars[k] for k in self.exported_vars}
def get_all(self) -> t.Dict[str, t.Any]:
"""Return the complete context as dict including the exported
variables. For optimizations reasons this might not return an
actual copy so be careful with using it.
"""
if not self.vars:
return self.parent
if not self.parent:
return self.vars
return dict(self.parent, **self.vars)
@internalcode
def call(
__self, __obj: t.Callable, *args: t.Any, **kwargs: t.Any # noqa: B902
) -> t.Union[t.Any, "Undefined"]:
"""Call the callable with the arguments and keyword arguments
provided but inject the active context or environment as first
argument if the callable has :func:`pass_context` or
:func:`pass_environment`.
"""
if __debug__:
__traceback_hide__ = True # noqa
# Allow callable classes to take a context
if (
hasattr(__obj, "__call__") # noqa: B004
and _PassArg.from_obj(__obj.__call__) is not None # type: ignore
):
__obj = __obj.__call__ # type: ignore
pass_arg = _PassArg.from_obj(__obj)
if pass_arg is _PassArg.context:
# the active context should have access to variables set in
# loops and blocks without mutating the context itself
if kwargs.get("_loop_vars"):
__self = __self.derived(kwargs["_loop_vars"])
if kwargs.get("_block_vars"):
__self = __self.derived(kwargs["_block_vars"])
args = (__self,) + args
elif pass_arg is _PassArg.eval_context:
args = (__self.eval_ctx,) + args
elif pass_arg is _PassArg.environment:
args = (__self.environment,) + args
kwargs.pop("_block_vars", None)
kwargs.pop("_loop_vars", None)
try:
return __obj(*args, **kwargs)
except StopIteration:
return __self.environment.undefined(
"value was undefined because a callable raised a"
" StopIteration exception"
)
def derived(self, locals: t.Optional[t.Dict[str, t.Any]] = None) -> "Context":
"""Internal helper function to create a derived context. This is
used in situations where the system needs a new context in the same
template that is independent.
"""
context = new_context(
self.environment, self.name, {}, self.get_all(), True, None, locals
)
context.eval_ctx = self.eval_ctx
context.blocks.update((k, list(v)) for k, v in self.blocks.items())
return context
keys = _dict_method_all(dict.keys)
values = _dict_method_all(dict.values)
items = _dict_method_all(dict.items)
def __contains__(self, name: str) -> bool:
return name in self.vars or name in self.parent
def __getitem__(self, key: str) -> t.Any:
"""Look up a variable by name with ``[]`` syntax, or raise a
``KeyError`` if the key is not found.
"""
item = self.resolve_or_missing(key)
if item is missing:
raise KeyError(key)
return item
def __repr__(self) -> str:
return f"<{type(self).__name__} {self.get_all()!r} of {self.name!r}>"
|
Context
|
python
|
django__django
|
tests/managers_regress/models.py
|
{
"start": 1494,
"end": 1617
}
|
class ____(AbstractBase1):
data = models.CharField(max_length=25)
def __str__(self):
return self.data
|
Child1
|
python
|
PyCQA__pylint
|
tests/functional/a/arguments_differ.py
|
{
"start": 4360,
"end": 4795
}
|
class ____(ParentClass):
def meth(self, _arg, dummy):
# no error here, "dummy" and "_" are being ignored if
# spotted in a variable name (declared in dummy_parameter_regex)
pass
# https://github.com/pylint-dev/pylint/issues/4443
# Some valid overwrites with type annotations
import typing # pylint: disable=wrong-import-position
from typing import Dict # pylint: disable=wrong-import-position
|
ChildClass
|
python
|
pypa__twine
|
twine/exceptions.py
|
{
"start": 1926,
"end": 2821
}
|
class ____(TwineException):
"""An upload attempt was detected to deprecated PyPI domains.
The sites pypi.python.org and testpypi.python.org are deprecated.
"""
@classmethod
def from_args(
cls, target_url: str, default_url: str, test_url: str
) -> "UploadToDeprecatedPyPIDetected":
"""Return an UploadToDeprecatedPyPIDetected instance."""
return cls(
"You're trying to upload to the legacy PyPI site '{}'. "
"Uploading to those sites is deprecated. \n "
"The new sites are pypi.org and test.pypi.org. Try using "
"{} (or {}) to upload your packages instead. "
"These are the default URLs for Twine now. \n More at "
"https://packaging.python.org/guides/migrating-to-pypi-org/"
" .".format(target_url, default_url, test_url)
)
|
UploadToDeprecatedPyPIDetected
|
python
|
django__django
|
tests/admin_inlines/admin.py
|
{
"start": 3548,
"end": 3650
}
|
class ____(admin.ModelAdmin):
class Media:
js = ("my_awesome_admin_scripts.js",)
|
HolderAdmin
|
python
|
urllib3__urllib3
|
dummyserver/testcase.py
|
{
"start": 9532,
"end": 11289
}
|
class ____:
"""
Marks an HTTP(S)Connection's socket after a request was made.
Helps a test server understand when a client finished a request,
without implementing a complete HTTP server.
"""
MARK_FORMAT = b"$#MARK%04x*!"
@classmethod
@contextlib.contextmanager
def mark(cls, monkeypatch: pytest.MonkeyPatch) -> typing.Generator[None]:
"""
Mark connections under in that context.
"""
orig_request = HTTPConnection.request
def call_and_mark(
target: typing.Callable[..., None],
) -> typing.Callable[..., None]:
def part(
self: HTTPConnection, *args: typing.Any, **kwargs: typing.Any
) -> None:
target(self, *args, **kwargs)
self.sock.sendall(cls._get_socket_mark(self.sock, False))
return part
with monkeypatch.context() as m:
m.setattr(HTTPConnection, "request", call_and_mark(orig_request))
yield
@classmethod
def consume_request(cls, sock: socket.socket, chunks: int = 65536) -> bytearray:
"""
Consume a socket until after the HTTP request is sent.
"""
consumed = bytearray()
mark = cls._get_socket_mark(sock, True)
while True:
b = sock.recv(chunks)
if not b:
break
consumed += b
if consumed.endswith(mark):
break
return consumed
@classmethod
def _get_socket_mark(cls, sock: socket.socket, server: bool) -> bytes:
if server:
port = sock.getpeername()[1]
else:
port = sock.getsockname()[1]
return cls.MARK_FORMAT % (port,)
|
ConnectionMarker
|
python
|
euske__pdfminer
|
pdfminer/layout.py
|
{
"start": 3685,
"end": 3977
}
|
class ____(LTComponent):
def __init__(self, linewidth, pts):
LTComponent.__init__(self, get_bound(pts))
self.pts = pts
self.linewidth = linewidth
return
def get_pts(self):
return ','.join('%.3f,%.3f' % p for p in self.pts)
## LTLine
##
|
LTCurve
|
python
|
pytorch__pytorch
|
test/inductor/test_mix_order_reduction.py
|
{
"start": 443,
"end": 699
}
|
class ____(TestCase):
def setUp(self):
super().setUp()
metrics.reset()
def check_numeric(self, f, args, tol=1e-3):
ref = f(*args)
act = torch.compile(f)(*args)
self.assertTrue(same(ref, act, tol=tol))
|
TestBase
|
python
|
HypothesisWorks__hypothesis
|
hypothesis-python/tests/cover/test_lookup.py
|
{
"start": 32486,
"end": 32889
}
|
class ____(typing.Generic[_ValueType]):
value: _ValueType # the same name we have in `__init__`
__signature__ = signature(use_signature)
def __init__(self, value: int) -> None:
"""By this example we show, that ``__signature__`` is the most important source."""
assert isinstance(value, str)
def selfless_signature(value: str) -> None: ...
|
AnnotatedConstructorWithSignature
|
python
|
dagster-io__dagster
|
python_modules/dagster/dagster/_core/run_coordinator/base.py
|
{
"start": 1038,
"end": 2052
}
|
class ____(ABC, MayHaveInstanceWeakref[T_DagsterInstance]):
@abstractmethod
def submit_run(self, context: SubmitRunContext) -> DagsterRun:
"""Submit a run to the run coordinator for execution.
Args:
context (SubmitRunContext): information about the submission - every run coordinator
will need the PipelineRun, and some run coordinators may need information from the
WorkspaceRequestContext from which the run was launched.
Returns:
PipelineRun: The queued run
"""
@abstractmethod
def cancel_run(self, run_id: str) -> bool:
"""Cancels a run. The run may be queued in the coordinator, or it may have been launched.
Returns False is the process was already canceled. Returns true if the cancellation was
successful.
"""
def dispose(self) -> None:
"""Do any resource cleanup that should happen when the DagsterInstance is
cleaning itself up.
"""
|
RunCoordinator
|
python
|
tensorflow__tensorflow
|
tensorflow/python/autograph/core/converter_testing.py
|
{
"start": 3014,
"end": 4082
}
|
class ____(test.TestCase):
"""Base class for unit tests in this module. Contains relevant utilities."""
def setUp(self):
# AutoGraph tests must run in graph mode to properly test control flow.
self.graph = ops.Graph().as_default()
self.graph.__enter__()
def tearDown(self):
self.graph.__exit__(None, None, None)
@contextlib.contextmanager
def assertPrints(self, expected_result):
try:
out_capturer = io.StringIO()
sys.stdout = out_capturer
yield
self.assertEqual(out_capturer.getvalue(), expected_result)
finally:
sys.stdout = sys.__stdout__
def transform(
self, f, converter_module, include_ast=False, ag_overrides=None):
program_ctx = converter.ProgramContext(
options=converter.ConversionOptions(recursive=True),
autograph_module=api)
tr = TestingTranspiler(converter_module, ag_overrides)
transformed, _, _ = tr.transform_function(f, program_ctx)
if include_ast:
return transformed, tr.transformed_ast, tr.transform_ctx
return transformed
|
TestCase
|
python
|
pytorch__pytorch
|
torch/_inductor/dtype_propagation.py
|
{
"start": 2236,
"end": 12027
}
|
class ____:
"""
Propagate dtype from args to output
"""
# Singleton DtypePropagationOpsHandler, because we meta program over a number of op rules.
# Those are only defined after other inductor state has run.
_instance: Optional["DtypePropagationOpsHandler"] = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self) -> None:
for op, rule in torch._inductor.utils.op_dtype_propagation_rules.items():
fn = (
functools.partial(self.return_dtype, dtype=rule.override_return_dtype)
if rule.override_return_dtype
else functools.partial(
self.op_dtype_rule, type_promotion_kind=rule.type_promotion_kind
)
)
setattr(self, op, fn)
# Set pointwise operation rules
for op in torch._inductor.codegen.common.pointwise_overrides_data.values():
if not hasattr(self, op.name):
setattr(
self,
op.name,
functools.partial(
self.op_dtype_rule, type_promotion_kind=op.type_promotion_kind
),
)
# Set boolean operation rules
for op in torch._inductor.utils.boolean_ops():
if not hasattr(self, op):
setattr(
self, op, functools.partial(self.return_dtype, dtype=torch.bool)
)
unimplemented_ops = OP_NAMES - OrderedSet(dir(self))
torch._check(
len(unimplemented_ops) == 0,
lambda: f"Unimplemented dtype rule for ops: {unimplemented_ops}",
)
# metaprogrammed in __init__
@staticmethod
def op_dtype_rule(
*args: DTypeArg, type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND
) -> torch.dtype:
return promote_types(args, type_promotion_kind=type_promotion_kind)
@staticmethod
def return_dtype(*args: DTypeArg, dtype: torch.dtype) -> torch.dtype:
return dtype
# op rules
@staticmethod
def constant(value: torch.types.Number, dtype: torch.dtype) -> torch.dtype:
return upcast_compute_type(dtype)
@staticmethod
def load_seed(name: str, offset: int) -> torch.dtype:
return upcast_compute_type(V.graph.get_dtype(name))
@staticmethod
def randint64(seed: int, offset: int, low: int, high: int) -> torch.dtype:
return torch.int64
@staticmethod
def masked(
mask: DTypeArg, body: Callable[[], DTypeArg], other: DTypeArg
) -> torch.dtype:
from .loop_body import LoopBodyBlock
assert isinstance(body, LoopBodyBlock), "body must be a LoopBodyBlock"
# TODO - we avoid calling this in codegen, needs work for non codegen use cases
loads = body.graph.find_nodes(op="call_method", target="load")
if len(loads) <= 1:
return promote_types([other])
return upcast_compute_type(V.graph.get_dtype(loads[-1].args[1]))
@staticmethod
def where(a: DTypeArg, b: DTypeArg, c: DTypeArg) -> torch.dtype:
return promote_types([b, c])
@staticmethod
def index_expr(expr: sympy.Expr, dtype: torch.dtype) -> torch.dtype:
# TODO - TODO - rationalize index_expr. The dtype is not always used and we are inconsistent about int32 or int64
# in lowerings. cpp just uses the dtype
if dtype not in (torch.int32, torch.int64) or not hasattr(
V.kernel, "index_dtype"
):
return upcast_compute_type(dtype)
return V.kernel.get_index_dtype_as_torch_dtype()
@staticmethod
def to_dtype(
x: DTypeArg,
dtype: torch.dtype,
src_dtype: Optional[torch.dtype] = None,
use_compute_types=True,
) -> torch.dtype:
return upcast_compute_type(dtype) if use_compute_types else dtype
@staticmethod
def to_dtype_bitcast(
x: DTypeArg, dtype: torch.dtype, src_dtype: torch.dtype
) -> torch.dtype:
return upcast_compute_type(dtype)
@staticmethod
def gelu(x: DTypeArg) -> torch.dtype:
return promote_types([x])
@staticmethod
def mul(a: DTypeArg, b: DTypeArg) -> torch.dtype:
return promote_types([a, b])
@staticmethod
def truediv(a: DTypeArg, b: DTypeArg) -> torch.dtype:
return promote_types([a, b])
@staticmethod
def pow(a: DTypeArg, b: DTypeArg) -> torch.dtype:
return promote_types([a, b])
@staticmethod
def mod(a: DTypeArg, b: DTypeArg) -> torch.dtype:
return promote_types([a, b])
@staticmethod
def indirect_indexing(
x: DTypeArg, size: int, check: bool = True, wrap_neg: bool = True
) -> torch.dtype:
return torch.int64
@staticmethod
def randn(seed: int, offset: int) -> torch.dtype:
return torch.float
@staticmethod
def rand(seed: int, offset: int) -> torch.dtype:
return torch.float
@staticmethod
def store_reduction(name: str, index, value: DTypeArg) -> None:
return None
@staticmethod
def reduction(
dtype: torch.dtype, src_dtype: torch.dtype, reduction_type: str, value: DTypeArg
) -> torch.dtype:
return dtype
@staticmethod
def store(name: str, index, value: DTypeArg, mode: Optional[str] = None) -> None:
return None
@staticmethod
def partial_accumulate(
name: str,
reduction_type: str,
value: DTypeArg,
extra_meta: dict[str, Any],
) -> None:
return None
@staticmethod
def load(name: str, index) -> torch.dtype:
return upcast_compute_type(V.graph.get_dtype(name))
@staticmethod
def floor(x: DTypeArg) -> torch.dtype:
return promote_types(
[x], type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT
)
@staticmethod
def ceil_to_int(x: DTypeArg, dtype: torch.dtype) -> torch.dtype:
return dtype
@staticmethod
def int_truediv(x: DTypeArg, y: DTypeArg) -> torch.dtype:
return promote_types(
[x, y], type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT
)
@staticmethod
def scan(
dtypes: tuple[torch.dtype, ...],
combine_fn: Callable[[tuple[T, ...], tuple[T, ...]], tuple[T, ...]],
values: tuple[T, ...],
) -> tuple[torch.dtype, ...]:
return dtypes
@staticmethod
def fmod(x: DTypeArg, y: DTypeArg) -> torch.dtype:
return promote_types([x, y])
@staticmethod
def round_to_int(x: DTypeArg, dtype: torch.dtype) -> torch.dtype:
return dtype
@staticmethod
def identity(x: DTypeArg) -> torch.dtype:
return promote_types([x])
@staticmethod
def frexp(x: DTypeArg) -> tuple[torch.dtype, torch.dtype]:
# TODO - need to handle multiple outputs
return (promote_types([x]), torch.int32)
@staticmethod
def sort(
dtypes: tuple[torch.dtype, ...],
values: tuple[T, ...],
stable: bool,
descending: bool,
) -> tuple[torch.dtype, ...]:
return dtypes
@staticmethod
def trunc(x: DTypeArg) -> torch.dtype:
return promote_types([x])
@staticmethod
def bucketize(
values: DTypeArg,
boundaries: tuple[str, sympy.Expr, sympy.Expr, sympy.Expr],
boundary_indices: DTypeArg,
indexing_dtype: torch.dtype,
right: bool,
sorter: Optional[tuple[str, sympy.Expr]] = None,
sorter_indices: Optional[T] = None,
) -> torch.dtype:
return indexing_dtype
@staticmethod
def rshift(x: DTypeArg, y: DTypeArg) -> torch.dtype:
return promote_types([x])
@staticmethod
def round(x: DTypeArg) -> torch.dtype:
return promote_types(
[x], type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT
)
@staticmethod
def trunc_to_int(x: DTypeArg, dtype: torch.dtype) -> torch.dtype:
return dtype
@staticmethod
def floor_to_int(x: DTypeArg, dtype: torch.dtype) -> torch.dtype:
return dtype
@staticmethod
def truncdiv(x: DTypeArg, y: DTypeArg) -> torch.dtype:
return promote_types([x, y])
@staticmethod
def floordiv(x: DTypeArg, y: DTypeArg) -> torch.dtype:
return promote_types([x, y])
@staticmethod
def halide_clamp(value, size, check):
# TODO - way of registering dtype for op in backend
return torch.int32
@staticmethod
def dot(x: DTypeArg, y: DTypeArg) -> torch.dtype:
# triton tl.dot out_dtype is tl.float32 by default.
return torch.float32
@staticmethod
def inline_asm_elementwise(
*inputs, asm, constraints=None, dtype=torch.float32, is_pure=True, pack=1
):
return dtype
@staticmethod
def lshift(x: DTypeArg, y: DTypeArg) -> torch.dtype:
return promote_types([x])
@staticmethod
def check_bounds(
expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool
) -> None:
return None
def output(self, *args: DTypeArg) -> None:
raise AssertionError(
f"{type(self).__name__}: ops.output should not appear here"
)
def placeholder(self, index: int) -> torch.dtype:
raise AssertionError(
f"{type(self).__name__}: ops.placeholder should not appear here"
)
@staticmethod
def device_assert_async(cond, msg: str) -> None:
return None
if TYPE_CHECKING:
class _typecheck_DtypePropagation(DtypePropagationOpsHandler, OpsHandler[Any]):
pass # mypy will error if we got any of the signatures wrong
|
DtypePropagationOpsHandler
|
python
|
charliermarsh__ruff
|
crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_length.py
|
{
"start": 932,
"end": 1006
}
|
class ____:
def __len__(self):
raise NotImplementedError
|
Length5
|
python
|
pypa__warehouse
|
warehouse/utils/sns.py
|
{
"start": 502,
"end": 4230
}
|
class ____:
def __init__(self, *, topics, session=None):
self.topics = topics
self.http = session if session is not None else requests.session()
def verify(self, message):
if message.get("SignatureVersion") == "2":
self._validate_v2_signature(message)
else:
raise InvalidMessageError("Unknown SignatureVersion")
self._validate_timestamp(message["Timestamp"])
self._validate_topic(message["TopicArn"])
def _validate_topic(self, topic):
if topic not in self.topics:
raise InvalidMessageError("Invalid TopicArn")
def _validate_timestamp(self, timestamp_str):
now = datetime.datetime.now(datetime.UTC)
try:
timestamp = datetime.datetime.strptime(
timestamp_str, "%Y-%m-%dT%H:%M:%S.%fZ"
).replace(tzinfo=datetime.UTC)
except ValueError:
raise InvalidMessageError("Unknown Timestamp format")
age = now - timestamp
if age > datetime.timedelta(hours=1):
raise InvalidMessageError("Message has expired")
def _validate_v2_signature(self, message):
pubkey = self._get_pubkey(message["SigningCertURL"])
signature = self._get_signature(message)
data = self._get_data_to_sign(message)
try:
pubkey.verify(signature, data, PKCS1v15(), SHA256())
except _InvalidSignature:
raise InvalidMessageError("Invalid Signature") from None
def _get_pubkey(self, cert_url):
# Before we do anything, we need to verify that the URL for the
# signature matches what we expect.
cert_url_p = parse_url(cert_url)
cert_scheme = cert_url_p.scheme
cert_host = cert_url_p.netloc
if cert_scheme != "https":
raise InvalidMessageError("Invalid scheme for SigningCertURL")
if not cert_host or _signing_url_host_re.fullmatch(cert_host) is None:
raise InvalidMessageError("Invalid location for SigningCertURL")
resp = self.http.get(cert_url)
resp.raise_for_status()
cert = x509.load_pem_x509_certificate(resp.content)
return cert.public_key()
def _get_signature(self, message):
return base64.b64decode(message["Signature"])
def _get_data_to_sign(self, message):
if message["Type"] == "Notification":
parts = self._get_parts_to_sign_notification(message)
elif message["Type"] in {"SubscriptionConfirmation", "UnsubscribeConfirmation"}:
parts = self._get_parts_to_sign_subscription(message)
else:
raise InvalidMessageError("Invalid Type")
return ("\n".join(parts) + "\n").encode("utf8")
def _get_parts_to_sign_notification(self, message):
parts = ["Message", message["Message"], "MessageId", message["MessageId"]]
if "Subject" in message:
parts.extend(["Subject", message["Subject"]])
parts.extend(
[
"Timestamp",
message["Timestamp"],
"TopicArn",
message["TopicArn"],
"Type",
message["Type"],
]
)
return parts
def _get_parts_to_sign_subscription(self, message):
return [
"Message",
message["Message"],
"MessageId",
message["MessageId"],
"SubscribeURL",
message["SubscribeURL"],
"Timestamp",
message["Timestamp"],
"Token",
message["Token"],
"TopicArn",
message["TopicArn"],
"Type",
message["Type"],
]
|
MessageVerifier
|
python
|
weaviate__weaviate-python-client
|
weaviate/collections/classes/batch.py
|
{
"start": 6231,
"end": 6411
}
|
class ____:
"""This class contains the error information for a single reference in a batch operation."""
message: str
reference: BatchReference
@dataclass
|
ErrorReference
|
python
|
kubernetes-client__python
|
kubernetes/client/models/v1_glusterfs_volume_source.py
|
{
"start": 383,
"end": 5961
}
|
class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'endpoints': 'str',
'path': 'str',
'read_only': 'bool'
}
attribute_map = {
'endpoints': 'endpoints',
'path': 'path',
'read_only': 'readOnly'
}
def __init__(self, endpoints=None, path=None, read_only=None, local_vars_configuration=None): # noqa: E501
"""V1GlusterfsVolumeSource - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._endpoints = None
self._path = None
self._read_only = None
self.discriminator = None
self.endpoints = endpoints
self.path = path
if read_only is not None:
self.read_only = read_only
@property
def endpoints(self):
"""Gets the endpoints of this V1GlusterfsVolumeSource. # noqa: E501
endpoints is the endpoint name that details Glusterfs topology. # noqa: E501
:return: The endpoints of this V1GlusterfsVolumeSource. # noqa: E501
:rtype: str
"""
return self._endpoints
@endpoints.setter
def endpoints(self, endpoints):
"""Sets the endpoints of this V1GlusterfsVolumeSource.
endpoints is the endpoint name that details Glusterfs topology. # noqa: E501
:param endpoints: The endpoints of this V1GlusterfsVolumeSource. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and endpoints is None: # noqa: E501
raise ValueError("Invalid value for `endpoints`, must not be `None`") # noqa: E501
self._endpoints = endpoints
@property
def path(self):
"""Gets the path of this V1GlusterfsVolumeSource. # noqa: E501
path is the Glusterfs volume path. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod # noqa: E501
:return: The path of this V1GlusterfsVolumeSource. # noqa: E501
:rtype: str
"""
return self._path
@path.setter
def path(self, path):
"""Sets the path of this V1GlusterfsVolumeSource.
path is the Glusterfs volume path. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod # noqa: E501
:param path: The path of this V1GlusterfsVolumeSource. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and path is None: # noqa: E501
raise ValueError("Invalid value for `path`, must not be `None`") # noqa: E501
self._path = path
@property
def read_only(self):
"""Gets the read_only of this V1GlusterfsVolumeSource. # noqa: E501
readOnly here will force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod # noqa: E501
:return: The read_only of this V1GlusterfsVolumeSource. # noqa: E501
:rtype: bool
"""
return self._read_only
@read_only.setter
def read_only(self, read_only):
"""Sets the read_only of this V1GlusterfsVolumeSource.
readOnly here will force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod # noqa: E501
:param read_only: The read_only of this V1GlusterfsVolumeSource. # noqa: E501
:type: bool
"""
self._read_only = read_only
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1GlusterfsVolumeSource):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1GlusterfsVolumeSource):
return True
return self.to_dict() != other.to_dict()
|
V1GlusterfsVolumeSource
|
python
|
davidhalter__parso
|
parso/python/token.py
|
{
"start": 350,
"end": 909
}
|
class ____(Enum):
STRING = TokenType('STRING')
NUMBER = TokenType('NUMBER')
NAME = TokenType('NAME', contains_syntax=True)
ERRORTOKEN = TokenType('ERRORTOKEN')
NEWLINE = TokenType('NEWLINE')
INDENT = TokenType('INDENT')
DEDENT = TokenType('DEDENT')
ERROR_DEDENT = TokenType('ERROR_DEDENT')
FSTRING_STRING = TokenType('FSTRING_STRING')
FSTRING_START = TokenType('FSTRING_START')
FSTRING_END = TokenType('FSTRING_END')
OP = TokenType('OP', contains_syntax=True)
ENDMARKER = TokenType('ENDMARKER')
|
PythonTokenTypes
|
python
|
charliermarsh__ruff
|
crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/class_definition.py
|
{
"start": 1192,
"end": 1236
}
|
class ____:
"""Docstring"""
x = 1
|
Test
|
python
|
pandas-dev__pandas
|
pandas/tests/libs/test_hashtable.py
|
{
"start": 19316,
"end": 21277
}
|
class ____:
def test_get_set_contains_len(self, table_type, dtype):
index = float("nan")
table = table_type()
assert index not in table
table.set_item(index, 42)
assert len(table) == 1
assert index in table
assert table.get_item(index) == 42
table.set_item(index, 41)
assert len(table) == 1
assert index in table
assert table.get_item(index) == 41
def test_map_locations(self, table_type, dtype):
N = 10
table = table_type()
keys = np.full(N, np.nan, dtype=dtype)
table.map_locations(keys)
assert len(table) == 1
assert table.get_item(np.nan) == N - 1
def test_unique(self, table_type, dtype):
N = 1020
table = table_type()
keys = np.full(N, np.nan, dtype=dtype)
unique = table.unique(keys)
assert np.all(np.isnan(unique)) and len(unique) == 1
def test_unique_for_nan_objects_floats():
table = ht.PyObjectHashTable()
keys = np.array([float("nan") for i in range(50)], dtype=np.object_)
unique = table.unique(keys)
assert len(unique) == 1
def test_unique_for_nan_objects_complex():
table = ht.PyObjectHashTable()
keys = np.array([complex(float("nan"), 1.0) for i in range(50)], dtype=np.object_)
unique = table.unique(keys)
assert len(unique) == 1
def test_unique_for_nan_objects_tuple():
table = ht.PyObjectHashTable()
keys = np.array(
[1] + [(1.0, (float("nan"), 1.0)) for i in range(50)], dtype=np.object_
)
unique = table.unique(keys)
assert len(unique) == 2
@pytest.mark.parametrize(
"dtype",
[
np.object_,
np.complex128,
np.int64,
np.uint64,
np.float64,
np.complex64,
np.int32,
np.uint32,
np.float32,
np.int16,
np.uint16,
np.int8,
np.uint8,
np.intp,
],
)
|
TestHashTableWithNans
|
python
|
spyder-ide__spyder
|
spyder/plugins/help/widgets.py
|
{
"start": 6782,
"end": 8690
}
|
class ____(QWidget):
"""
Read-only editor widget with find dialog
"""
# Signals
focus_changed = Signal()
sig_custom_context_menu_requested = Signal(QPoint)
def __init__(self, parent):
QWidget.__init__(self, parent)
self.editor = None
# Read-only simple code editor
self.editor = SimpleCodeEditor(self)
self.editor.setup_editor(
language='py',
highlight_current_line=False,
linenumbers=False,
)
self.editor.sig_focus_changed.connect(self.focus_changed)
self.editor.setReadOnly(True)
self.editor.setContextMenuPolicy(Qt.CustomContextMenu)
# Find/replace widget
self.find_widget = FindReplace(self)
self.find_widget.set_editor(self.editor)
self.find_widget.hide()
layout = QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self.editor)
layout.addWidget(self.find_widget)
self.setLayout(layout)
self.editor.customContextMenuRequested.connect(
self.sig_custom_context_menu_requested)
def set_font(self, font, color_scheme=None):
"""Set font"""
self.editor.set_color_scheme(color_scheme)
self.editor.set_font(font)
def set_color_scheme(self, color_scheme):
"""Set color scheme"""
self.editor.set_color_scheme(color_scheme)
def set_text(self, text, is_code):
if is_code:
self.editor.set_language('py')
else:
self.editor.set_language(None)
self.editor.set_text(text)
self.editor.set_cursor_position('sof')
def clear(self):
self.editor.clear()
def set_wrap_mode(self, value):
self.editor.toggle_wrap_mode(value)
def copy(self):
self.editor.copy()
def select_all(self):
self.editor.selectAll()
|
PlainText
|
python
|
python__mypy
|
mypy/stats.py
|
{
"start": 1437,
"end": 15711
}
|
class ____(TraverserVisitor):
def __init__(
self,
inferred: bool,
filename: str,
modules: dict[str, MypyFile],
typemap: dict[Expression, Type] | None = None,
all_nodes: bool = False,
visit_untyped_defs: bool = True,
) -> None:
self.inferred = inferred
self.filename = filename
self.modules = modules
self.typemap = typemap
self.all_nodes = all_nodes
self.visit_untyped_defs = visit_untyped_defs
self.num_precise_exprs = 0
self.num_imprecise_exprs = 0
self.num_any_exprs = 0
self.num_simple_types = 0
self.num_generic_types = 0
self.num_tuple_types = 0
self.num_function_types = 0
self.num_typevar_types = 0
self.num_complex_types = 0
self.num_any_types = 0
self.line = -1
self.line_map: dict[int, int] = {}
self.type_of_any_counter: Counter[int] = Counter()
self.any_line_map: dict[int, list[AnyType]] = {}
# For each scope (top level/function), whether the scope was type checked
# (annotated function).
#
# TODO: Handle --check-untyped-defs
self.checked_scopes = [True]
self.output: list[str] = []
TraverserVisitor.__init__(self)
def visit_mypy_file(self, o: MypyFile) -> None:
self.cur_mod_node = o
self.cur_mod_id = o.fullname
super().visit_mypy_file(o)
def visit_import_from(self, imp: ImportFrom) -> None:
self.process_import(imp)
def visit_import_all(self, imp: ImportAll) -> None:
self.process_import(imp)
def process_import(self, imp: ImportFrom | ImportAll) -> None:
import_id, ok = correct_relative_import(
self.cur_mod_id, imp.relative, imp.id, self.cur_mod_node.is_package_init_file()
)
if ok and import_id in self.modules:
kind = TYPE_PRECISE
else:
kind = TYPE_ANY
self.record_line(imp.line, kind)
def visit_import(self, imp: Import) -> None:
if all(id in self.modules for id, _ in imp.ids):
kind = TYPE_PRECISE
else:
kind = TYPE_ANY
self.record_line(imp.line, kind)
def visit_func_def(self, o: FuncDef) -> None:
with self.enter_scope(o):
self.line = o.line
if len(o.expanded) > 1 and o.expanded != [o] * len(o.expanded):
if o in o.expanded:
print(
"{}:{}: ERROR: cycle in function expansion; skipping".format(
self.filename, o.line
)
)
return
for defn in o.expanded:
assert isinstance(defn, FuncDef)
self.visit_func_def(defn)
else:
if o.type:
assert isinstance(o.type, CallableType)
sig = o.type
arg_types = sig.arg_types
if sig.arg_names and sig.arg_names[0] == "self" and not self.inferred:
arg_types = arg_types[1:]
for arg in arg_types:
self.type(arg)
self.type(sig.ret_type)
elif self.all_nodes:
self.record_line(self.line, TYPE_ANY)
if not o.is_dynamic() or self.visit_untyped_defs:
super().visit_func_def(o)
@contextmanager
def enter_scope(self, o: FuncDef) -> Iterator[None]:
self.checked_scopes.append(o.type is not None and self.checked_scopes[-1])
yield None
self.checked_scopes.pop()
def is_checked_scope(self) -> bool:
return self.checked_scopes[-1]
def visit_class_def(self, o: ClassDef) -> None:
self.record_line(o.line, TYPE_PRECISE) # TODO: Look at base classes
# Override this method because we don't want to analyze base_type_exprs (base_type_exprs
# are base classes in a class declaration).
# While base_type_exprs are technically expressions, type analyzer does not visit them and
# they are not in the typemap.
for d in o.decorators:
d.accept(self)
o.defs.accept(self)
def visit_type_application(self, o: TypeApplication) -> None:
self.line = o.line
for t in o.types:
self.type(t)
super().visit_type_application(o)
def visit_assignment_stmt(self, o: AssignmentStmt) -> None:
self.line = o.line
if isinstance(o.rvalue, nodes.CallExpr) and isinstance(
o.rvalue.analyzed, nodes.TypeVarExpr
):
# Type variable definition -- not a real assignment.
return
if o.type:
# If there is an explicit type, don't visit the l.h.s. as an expression
# to avoid double-counting and mishandling special forms.
self.type(o.type)
o.rvalue.accept(self)
return
elif self.inferred and not self.all_nodes:
# if self.all_nodes is set, lvalues will be visited later
for lvalue in o.lvalues:
if isinstance(lvalue, nodes.TupleExpr):
items = lvalue.items
else:
items = [lvalue]
for item in items:
if isinstance(item, RefExpr) and item.is_inferred_def:
if self.typemap is not None:
self.type(self.typemap.get(item))
super().visit_assignment_stmt(o)
def visit_expression_stmt(self, o: ExpressionStmt) -> None:
if isinstance(o.expr, (StrExpr, BytesExpr)):
# Docstring
self.record_line(o.line, TYPE_EMPTY)
else:
super().visit_expression_stmt(o)
def visit_pass_stmt(self, o: PassStmt) -> None:
self.record_precise_if_checked_scope(o)
def visit_break_stmt(self, o: BreakStmt) -> None:
self.record_precise_if_checked_scope(o)
def visit_continue_stmt(self, o: ContinueStmt) -> None:
self.record_precise_if_checked_scope(o)
def visit_name_expr(self, o: NameExpr) -> None:
if o.fullname in ("builtins.None", "builtins.True", "builtins.False", "builtins.Ellipsis"):
self.record_precise_if_checked_scope(o)
else:
self.process_node(o)
super().visit_name_expr(o)
def visit_yield_from_expr(self, o: YieldFromExpr) -> None:
if o.expr:
o.expr.accept(self)
def visit_call_expr(self, o: CallExpr) -> None:
self.process_node(o)
if o.analyzed:
o.analyzed.accept(self)
else:
o.callee.accept(self)
for a in o.args:
a.accept(self)
self.record_call_target_precision(o)
def record_call_target_precision(self, o: CallExpr) -> None:
"""Record precision of formal argument types used in a call."""
if not self.typemap or o.callee not in self.typemap:
# Type not available.
return
callee_type = get_proper_type(self.typemap[o.callee])
if isinstance(callee_type, CallableType):
self.record_callable_target_precision(o, callee_type)
else:
pass # TODO: Handle overloaded functions, etc.
def record_callable_target_precision(self, o: CallExpr, callee: CallableType) -> None:
"""Record imprecision caused by callee argument types.
This only considers arguments passed in a call expression. Arguments
with default values that aren't provided in a call arguably don't
contribute to typing imprecision at the *call site* (but they
contribute at the function definition).
"""
assert self.typemap
typemap = self.typemap
actual_to_formal = map_formals_to_actuals(
o.arg_kinds,
o.arg_names,
callee.arg_kinds,
callee.arg_names,
lambda n: typemap[o.args[n]],
)
for formals in actual_to_formal:
for n in formals:
formal = get_proper_type(callee.arg_types[n])
if isinstance(formal, AnyType):
self.record_line(o.line, TYPE_ANY)
elif is_imprecise(formal):
self.record_line(o.line, TYPE_IMPRECISE)
def visit_member_expr(self, o: MemberExpr) -> None:
self.process_node(o)
super().visit_member_expr(o)
def visit_op_expr(self, o: OpExpr) -> None:
self.process_node(o)
super().visit_op_expr(o)
def visit_comparison_expr(self, o: ComparisonExpr) -> None:
self.process_node(o)
super().visit_comparison_expr(o)
def visit_index_expr(self, o: IndexExpr) -> None:
self.process_node(o)
super().visit_index_expr(o)
def visit_assignment_expr(self, o: AssignmentExpr) -> None:
self.process_node(o)
super().visit_assignment_expr(o)
def visit_unary_expr(self, o: UnaryExpr) -> None:
self.process_node(o)
super().visit_unary_expr(o)
def visit_str_expr(self, o: StrExpr) -> None:
self.record_precise_if_checked_scope(o)
def visit_bytes_expr(self, o: BytesExpr) -> None:
self.record_precise_if_checked_scope(o)
def visit_int_expr(self, o: IntExpr) -> None:
self.record_precise_if_checked_scope(o)
def visit_float_expr(self, o: FloatExpr) -> None:
self.record_precise_if_checked_scope(o)
def visit_complex_expr(self, o: ComplexExpr) -> None:
self.record_precise_if_checked_scope(o)
def visit_ellipsis(self, o: EllipsisExpr) -> None:
self.record_precise_if_checked_scope(o)
# Helpers
def process_node(self, node: Expression) -> None:
if self.all_nodes:
if self.typemap is not None:
self.line = node.line
self.type(self.typemap.get(node))
def record_precise_if_checked_scope(self, node: Node) -> None:
if isinstance(node, Expression) and self.typemap and node not in self.typemap:
kind = TYPE_UNANALYZED
elif self.is_checked_scope():
kind = TYPE_PRECISE
else:
kind = TYPE_ANY
self.record_line(node.line, kind)
def type(self, t: Type | None) -> None:
t = get_proper_type(t)
if not t:
# If an expression does not have a type, it is often due to dead code.
# Don't count these because there can be an unanalyzed value on a line with other
# analyzed expressions, which overwrite the TYPE_UNANALYZED.
self.record_line(self.line, TYPE_UNANALYZED)
return
if isinstance(t, AnyType) and is_special_form_any(t):
# TODO: What if there is an error in special form definition?
self.record_line(self.line, TYPE_PRECISE)
return
if isinstance(t, AnyType):
self.log(" !! Any type around line %d" % self.line)
self.num_any_exprs += 1
self.record_line(self.line, TYPE_ANY)
elif (not self.all_nodes and is_imprecise(t)) or (self.all_nodes and is_imprecise2(t)):
self.log(" !! Imprecise type around line %d" % self.line)
self.num_imprecise_exprs += 1
self.record_line(self.line, TYPE_IMPRECISE)
else:
self.num_precise_exprs += 1
self.record_line(self.line, TYPE_PRECISE)
for typ in get_proper_types(collect_all_inner_types(t)) + [t]:
if isinstance(typ, AnyType):
typ = get_original_any(typ)
if is_special_form_any(typ):
continue
self.type_of_any_counter[typ.type_of_any] += 1
self.num_any_types += 1
if self.line in self.any_line_map:
self.any_line_map[self.line].append(typ)
else:
self.any_line_map[self.line] = [typ]
elif isinstance(typ, Instance):
if typ.args:
if any(is_complex(arg) for arg in typ.args):
self.num_complex_types += 1
else:
self.num_generic_types += 1
else:
self.num_simple_types += 1
elif isinstance(typ, FunctionLike):
self.num_function_types += 1
elif isinstance(typ, TupleType):
if any(is_complex(item) for item in typ.items):
self.num_complex_types += 1
else:
self.num_tuple_types += 1
elif isinstance(typ, TypeVarType):
self.num_typevar_types += 1
def log(self, string: str) -> None:
self.output.append(string)
def record_line(self, line: int, precision: int) -> None:
self.line_map[line] = max(precision, self.line_map.get(line, TYPE_EMPTY))
def dump_type_stats(
tree: MypyFile,
path: str,
modules: dict[str, MypyFile],
inferred: bool = False,
typemap: dict[Expression, Type] | None = None,
) -> None:
if is_special_module(path):
return
print(path)
visitor = StatisticsVisitor(inferred, filename=tree.fullname, modules=modules, typemap=typemap)
tree.accept(visitor)
for line in visitor.output:
print(line)
print(" ** precision **")
print(" precise ", visitor.num_precise_exprs)
print(" imprecise", visitor.num_imprecise_exprs)
print(" any ", visitor.num_any_exprs)
print(" ** kinds **")
print(" simple ", visitor.num_simple_types)
print(" generic ", visitor.num_generic_types)
print(" function ", visitor.num_function_types)
print(" tuple ", visitor.num_tuple_types)
print(" TypeVar ", visitor.num_typevar_types)
print(" complex ", visitor.num_complex_types)
print(" any ", visitor.num_any_types)
def is_special_module(path: str) -> bool:
return os.path.basename(path) in ("abc.pyi", "typing.pyi", "builtins.pyi")
def is_imprecise(t: Type) -> bool:
return t.accept(HasAnyQuery())
|
StatisticsVisitor
|
python
|
conda__conda
|
conda/models/records.py
|
{
"start": 2986,
"end": 3132
}
|
class ____(DictSafeMixin, Entity):
source = StringField()
type = LinkTypeField(LinkType, required=False)
EMPTY_LINK = Link(source="")
|
Link
|
python
|
sqlalchemy__sqlalchemy
|
test/dialect/postgresql/test_types.py
|
{
"start": 187239,
"end": 187320
}
|
class ____(_NumRangeTests, _RangeTypeCompilation):
pass
|
NumRangeCompilationTest
|
python
|
jina-ai__jina
|
jina/proto/docarray_v1/pb/jina_pb2_grpc.py
|
{
"start": 21252,
"end": 22148
}
|
class ____(object):
"""*
jina gRPC service to trigger a snapshot at the Executor Runtime.
"""
@staticmethod
def snapshot_status(
request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None,
):
return grpc.experimental.unary_unary(
request,
target,
'/jina.JinaExecutorSnapshotProgress/snapshot_status',
jina__pb2.SnapshotId.SerializeToString,
jina__pb2.SnapshotStatusProto.FromString,
options,
channel_credentials,
insecure,
call_credentials,
compression,
wait_for_ready,
timeout,
metadata,
)
|
JinaExecutorSnapshotProgress
|
python
|
huggingface__transformers
|
src/transformers/models/glm4v_moe/modular_glm4v_moe.py
|
{
"start": 21030,
"end": 21177
}
|
class ____(Glm4MoeTopkRouter, nn.Module):
def __init__(self, config: Glm4vMoeTextConfig):
super().__init__(config)
|
Glm4vMoeTextTopkRouter
|
python
|
pytorch__pytorch
|
test/export/test_export_opinfo.py
|
{
"start": 4067,
"end": 8250
}
|
class ____(TestCase):
# In CI, this test runs on a CUDA machine with cuda build
# We set CUDA_VISIBLE_DEVICES="" to simulate a CPU machine with cuda build
# Running this on all ops in op_db is too slow, so we only run on a selected subset
@onlyCUDA
@skipIfRocm
@ops(selected_op_db, allowed_dtypes=(torch.float,))
def test_fake_export(self, device, dtype, op):
test_script = f"""\
import torch
import itertools
from torch.testing._internal.common_methods_invocations import op_db
from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode
from torch.utils import _pytree as pytree
ops = [op for op in op_db if op.name == "{op.name}"]
assert len(ops) > 0
for op in ops:
sample_inputs_itr = op.sample_inputs("cpu", torch.float, requires_grad=False)
mode = FakeTensorMode(allow_non_fake_inputs=True)
target_device = "cuda:0"
def to_fake_device(x):
return x.to(target_device)
# Limit to first 100 inputs so tests don't take too long
for sample_input in itertools.islice(sample_inputs_itr, 100):
args = tuple([sample_input.input] + list(sample_input.args))
kwargs = sample_input.kwargs
# hack to skip non-tensor in args, as export doesn't support it
if any(not isinstance(arg, torch.Tensor) for arg in args):
continue
if "device" in kwargs:
kwargs["device"] = target_device
with mode:
args, kwargs = pytree.tree_map_only(
torch.Tensor, to_fake_device, (args, kwargs)
)
class Module(torch.nn.Module):
def forward(self, *args):
return op.op(*args, **kwargs)
m = Module()
ep = torch.export.export(m, args)
for node in ep.graph.nodes:
if node.op == "call_function":
fake_tensor = node.meta.get("val", None)
if isinstance(fake_tensor, FakeTensor):
assert fake_tensor.device == torch.device(target_device)
"""
r = (
(
subprocess.check_output(
[sys.executable, "-c", test_script],
env={"CUDA_VISIBLE_DEVICES": ""},
)
)
.decode("ascii")
.strip()
)
self.assertEqual(r, "")
@unittest.skipIf(not torch.backends.cuda.is_built(), "requires CUDA build")
@skipIfRocm
def test_preserve_original_behavior(self):
test_script = f"""\
import torch
from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode
def cuda_calls_behavior_unchanged():
exception_count = 0
try:
cpu_x = torch.randn(2)
cuda_x = cpu_x.to("cuda")
except Exception as e:
exception_count += 1
try:
torch.randn(2, device="cuda")
except Exception as e:
exception_count += 1
try:
torch.cuda.get_device_capability()
except Exception as e:
exception_count += 1
try:
torch.cuda.set_device(1)
except Exception as e:
exception_count += 1
try:
torch.cuda.current_device()
except Exception as e:
exception_count += 1
assert torch.cuda.is_available() == False
assert torch.cuda.device_count() == 0
assert exception_count == 5
cuda_calls_behavior_unchanged()
cpu_x = torch.randn(2)
with FakeTensorMode(allow_non_fake_inputs=True) as mode:
cuda_x = mode.from_tensor(cpu_x)
cuda_x.fake_device = torch.device("cuda")
cuda_y = cuda_x + cuda_x
assert cuda_y.device.type == "cuda"
# should fail again after exiting the fake mode, with the identical error message
cuda_calls_behavior_unchanged()
"""
r = (
(
subprocess.check_output(
[sys.executable, "-c", test_script],
env={"CUDA_VISIBLE_DEVICES": ""},
)
)
.decode("ascii")
.strip()
)
self.assertEqual(r, "")
instantiate_device_type_tests(TestExportOnFakeCuda, globals(), only_for="cuda")
if __name__ == "__main__":
run_tests()
|
TestExportOnFakeCuda
|
python
|
PyCQA__pyflakes
|
pyflakes/messages.py
|
{
"start": 4532,
"end": 4865
}
|
class ____(Message):
"""
Indicates that a variable has been explicitly annotated to but not actually
used.
"""
message = 'local variable %r is annotated but never used'
def __init__(self, filename, loc, names):
Message.__init__(self, filename, loc)
self.message_args = (names,)
|
UnusedAnnotation
|
python
|
ipython__ipython
|
tests/test_hooks.py
|
{
"start": 852,
"end": 2302
}
|
class ____(object):
def __init__(self, message):
self.message = message
self.called = False
def __call__(self):
self.called = True
raise TryNext(self.message)
# -----------------------------------------------------------------------------
# Test functions
# -----------------------------------------------------------------------------
def test_command_chain_dispatcher_ff():
"""Test two failing hooks"""
fail1 = Fail("fail1")
fail2 = Fail("fail2")
dp = CommandChainDispatcher([(0, fail1), (10, fail2)])
with pytest.raises(TryNext) as e:
dp()
assert str(e.value) == "fail2"
assert fail1.called is True
assert fail2.called is True
def test_command_chain_dispatcher_fofo():
"""Test a mixture of failing and succeeding hooks."""
fail1 = Fail("fail1")
fail2 = Fail("fail2")
okay1 = Okay("okay1")
okay2 = Okay("okay2")
dp = CommandChainDispatcher(
[
(0, fail1),
# (5, okay1), # add this later
(10, fail2),
(15, okay2),
]
)
dp.add(okay1, 5)
assert dp() == "okay1"
assert fail1.called is True
assert okay1.called is True
assert fail2.called is False
assert okay2.called is False
def test_command_chain_dispatcher_eq_priority():
okay1 = Okay("okay1")
okay2 = Okay("okay2")
dp = CommandChainDispatcher([(1, okay1)])
dp.add(okay2, 1)
|
Fail
|
python
|
pytorch__pytorch
|
test/dynamo/cpython/3_13/test_generators.py
|
{
"start": 51469,
"end": 53533
}
|
class ____:
def __init__(self, n):
self.n = n
rangen = range(n)
# Assign a unique int to each column and diagonal.
# columns: n of those, range(n).
# NW-SE diagonals: 2n-1 of these, i-j unique and invariant along
# each, smallest i-j is 0-(n-1) = 1-n, so add n-1 to shift to 0-
# based.
# NE-SW diagonals: 2n-1 of these, i+j unique and invariant along
# each, smallest i+j is 0, largest is 2n-2.
# For each square, compute a bit vector of the columns and
# diagonals it covers, and for each row compute a function that
# generates the possibilities for the columns in that row.
self.rowgenerators = []
for i in rangen:
rowuses = [(1 << j) | # column ordinal
(1 << (n + i-j + n-1)) | # NW-SE ordinal
(1 << (n + 2*n-1 + i+j)) # NE-SW ordinal
for j in rangen]
def rowgen(rowuses=rowuses):
for j in rangen:
uses = rowuses[j]
if uses & self.used == 0:
self.used |= uses
yield j
self.used &= ~uses
self.rowgenerators.append(rowgen)
# Generate solutions.
def solve(self):
self.used = 0
for row2col in conjoin(self.rowgenerators):
yield row2col
def printsolution(self, row2col):
n = self.n
assert n == len(row2col)
sep = "+" + "-+" * n
print(sep)
for i in range(n):
squares = [" " for j in range(n)]
squares[row2col[i]] = "Q"
print("|" + "|".join(squares) + "|")
print(sep)
# A conjoin-based Knight's Tour solver. This is pretty sophisticated
# (e.g., when used with flat_conjoin above, and passing hard=1 to the
# constructor, a 200x200 Knight's Tour was found quickly -- note that we're
# creating 10s of thousands of generators then!), and is lengthy.
|
Queens
|
python
|
django__django
|
django/contrib/postgres/lookups.py
|
{
"start": 1125,
"end": 1230
}
|
class ____(Transform):
bilateral = True
lookup_name = "unaccent"
function = "UNACCENT"
|
Unaccent
|
python
|
sympy__sympy
|
sympy/polys/polymatrix.py
|
{
"start": 367,
"end": 9771
}
|
class ____:
"""
A mutable matrix of objects from poly module or to operate with them.
Examples
========
>>> from sympy.polys.polymatrix import PolyMatrix
>>> from sympy import Symbol, Poly
>>> x = Symbol('x')
>>> pm1 = PolyMatrix([[Poly(x**2, x), Poly(-x, x)], [Poly(x**3, x), Poly(-1 + x, x)]])
>>> v1 = PolyMatrix([[1, 0], [-1, 0]], x)
>>> pm1*v1
PolyMatrix([
[ x**2 + x, 0],
[x**3 - x + 1, 0]], ring=QQ[x])
>>> pm1.ring
ZZ[x]
>>> v1*pm1
PolyMatrix([
[ x**2, -x],
[-x**2, x]], ring=QQ[x])
>>> pm2 = PolyMatrix([[Poly(x**2, x, domain='QQ'), Poly(0, x, domain='QQ'), Poly(1, x, domain='QQ'), \
Poly(x**3, x, domain='QQ'), Poly(0, x, domain='QQ'), Poly(-x**3, x, domain='QQ')]])
>>> v2 = PolyMatrix([1, 0, 0, 0, 0, 0], x)
>>> v2.ring
QQ[x]
>>> pm2*v2
PolyMatrix([[x**2]], ring=QQ[x])
"""
def __new__(cls, *args, ring=None):
if not args:
# PolyMatrix(ring=QQ[x])
if ring is None:
raise TypeError("The ring needs to be specified for an empty PolyMatrix")
rows, cols, items, gens = 0, 0, [], ()
elif isinstance(args[0], list):
elements, gens = args[0], args[1:]
if not elements:
# PolyMatrix([])
rows, cols, items = 0, 0, []
elif isinstance(elements[0], (list, tuple)):
# PolyMatrix([[1, 2]], x)
rows, cols = len(elements), len(elements[0])
items = [e for row in elements for e in row]
else:
# PolyMatrix([1, 2], x)
rows, cols = len(elements), 1
items = elements
elif [type(a) for a in args[:3]] == [int, int, list]:
# PolyMatrix(2, 2, [1, 2, 3, 4], x)
rows, cols, items, gens = args[0], args[1], args[2], args[3:]
elif [type(a) for a in args[:3]] == [int, int, type(lambda: 0)]:
# PolyMatrix(2, 2, lambda i, j: i+j, x)
rows, cols, func, gens = args[0], args[1], args[2], args[3:]
items = [func(i, j) for i in range(rows) for j in range(cols)]
else:
raise TypeError("Invalid arguments")
# PolyMatrix([[1]], x, y) vs PolyMatrix([[1]], (x, y))
if len(gens) == 1 and isinstance(gens[0], tuple):
gens = gens[0]
# gens is now a tuple (x, y)
return cls.from_list(rows, cols, items, gens, ring)
@classmethod
def from_list(cls, rows, cols, items, gens, ring):
# items can be Expr, Poly, or a mix of Expr and Poly
items = [_sympify(item) for item in items]
if items and all(isinstance(item, Poly) for item in items):
polys = True
else:
polys = False
# Identify the ring for the polys
if ring is not None:
# Parse a domain string like 'QQ[x]'
if isinstance(ring, str):
ring = Poly(0, Dummy(), domain=ring).domain
elif polys:
p = items[0]
for p2 in items[1:]:
p, _ = p.unify(p2)
ring = p.domain[p.gens]
else:
items, info = parallel_poly_from_expr(items, gens, field=True)
ring = info['domain'][info['gens']]
polys = True
# Efficiently convert when all elements are Poly
if polys:
p_ring = Poly(0, ring.symbols, domain=ring.domain)
to_ring = ring.ring.from_list
convert_poly = lambda p: to_ring(p.unify(p_ring)[0].rep.to_list())
elements = [convert_poly(p) for p in items]
else:
convert_expr = ring.from_sympy
elements = [convert_expr(e.as_expr()) for e in items]
# Convert to domain elements and construct DomainMatrix
elements_lol = [[elements[i*cols + j] for j in range(cols)] for i in range(rows)]
dm = DomainMatrix(elements_lol, (rows, cols), ring)
return cls.from_dm(dm)
@classmethod
def from_dm(cls, dm):
obj = super().__new__(cls)
dm = dm.to_sparse()
R = dm.domain
obj._dm = dm
obj.ring = R
obj.domain = R.domain
obj.gens = R.symbols
return obj
def to_Matrix(self):
return self._dm.to_Matrix()
@classmethod
def from_Matrix(cls, other, *gens, ring=None):
return cls(*other.shape, other.flat(), *gens, ring=ring)
def set_gens(self, gens):
return self.from_Matrix(self.to_Matrix(), gens)
def __repr__(self):
if self.rows * self.cols:
return 'Poly' + repr(self.to_Matrix())[:-1] + f', ring={self.ring})'
else:
return f'PolyMatrix({self.rows}, {self.cols}, [], ring={self.ring})'
@property
def shape(self):
return self._dm.shape
@property
def rows(self):
return self.shape[0]
@property
def cols(self):
return self.shape[1]
def __len__(self):
return self.rows * self.cols
def __getitem__(self, key):
def to_poly(v):
ground = self._dm.domain.domain
gens = self._dm.domain.symbols
return Poly(v.to_dict(), gens, domain=ground)
dm = self._dm
if isinstance(key, slice):
items = dm.flat()[key]
return [to_poly(item) for item in items]
elif isinstance(key, int):
i, j = divmod(key, self.cols)
e = dm[i,j]
return to_poly(e.element)
i, j = key
if isinstance(i, int) and isinstance(j, int):
return to_poly(dm[i, j].element)
else:
return self.from_dm(dm[i, j])
def __eq__(self, other):
if not isinstance(self, type(other)):
return NotImplemented
return self._dm == other._dm
def __add__(self, other):
if isinstance(other, type(self)):
return self.from_dm(self._dm + other._dm)
return NotImplemented
def __sub__(self, other):
if isinstance(other, type(self)):
return self.from_dm(self._dm - other._dm)
return NotImplemented
def __mul__(self, other):
if isinstance(other, type(self)):
return self.from_dm(self._dm * other._dm)
elif isinstance(other, int):
other = _sympify(other)
if isinstance(other, Expr):
Kx = self.ring
try:
other_ds = DomainScalar(Kx.from_sympy(other), Kx)
except (CoercionFailed, ValueError):
other_ds = DomainScalar.from_sympy(other)
return self.from_dm(self._dm * other_ds)
return NotImplemented
def __rmul__(self, other):
if isinstance(other, int):
other = _sympify(other)
if isinstance(other, Expr):
other_ds = DomainScalar.from_sympy(other)
return self.from_dm(other_ds * self._dm)
return NotImplemented
def __truediv__(self, other):
if isinstance(other, Poly):
other = other.as_expr()
elif isinstance(other, int):
other = _sympify(other)
if not isinstance(other, Expr):
return NotImplemented
other = self.domain.from_sympy(other)
inverse = self.ring.convert_from(1/other, self.domain)
inverse = DomainScalar(inverse, self.ring)
dm = self._dm * inverse
return self.from_dm(dm)
def __neg__(self):
return self.from_dm(-self._dm)
def transpose(self):
return self.from_dm(self._dm.transpose())
def row_join(self, other):
dm = DomainMatrix.hstack(self._dm, other._dm)
return self.from_dm(dm)
def col_join(self, other):
dm = DomainMatrix.vstack(self._dm, other._dm)
return self.from_dm(dm)
def applyfunc(self, func):
M = self.to_Matrix().applyfunc(func)
return self.from_Matrix(M, self.gens)
@classmethod
def eye(cls, n, gens):
return cls.from_dm(DomainMatrix.eye(n, QQ[gens]))
@classmethod
def zeros(cls, m, n, gens):
return cls.from_dm(DomainMatrix.zeros((m, n), QQ[gens]))
def rref(self, simplify='ignore', normalize_last='ignore'):
# If this is K[x] then computes RREF in ground field K.
if not (self.domain.is_Field and all(p.is_ground for p in self)):
raise ValueError("PolyMatrix rref is only for ground field elements")
dm = self._dm
dm_ground = dm.convert_to(dm.domain.domain)
dm_rref, pivots = dm_ground.rref()
dm_rref = dm_rref.convert_to(dm.domain)
return self.from_dm(dm_rref), pivots
def nullspace(self):
# If this is K[x] then computes nullspace in ground field K.
if not (self.domain.is_Field and all(p.is_ground for p in self)):
raise ValueError("PolyMatrix nullspace is only for ground field elements")
dm = self._dm
K, Kx = self.domain, self.ring
dm_null_rows = dm.convert_to(K).nullspace(divide_last=True).convert_to(Kx)
dm_null = dm_null_rows.transpose()
dm_basis = [dm_null[:,i] for i in range(dm_null.shape[1])]
return [self.from_dm(dmvec) for dmvec in dm_basis]
def rank(self):
return self.cols - len(self.nullspace())
MutablePolyMatrix = PolyMatrix = MutablePolyDenseMatrix
|
MutablePolyDenseMatrix
|
python
|
joke2k__faker
|
faker/providers/internet/pl_PL/__init__.py
|
{
"start": 46,
"end": 510
}
|
class ____(InternetProvider):
free_email_domains = (
"onet.pl",
"interia.pl",
"gmail.com",
"o2.pl",
"yahoo.com",
"hotmail.com",
)
tlds = ("com", "com", "com", "net", "org", "pl", "pl", "pl")
replacements = (
("ą", "a"),
("ć", "c"),
("ę", "e"),
("ł", "l"),
("ń", "n"),
("ó", "o"),
("ś", "s"),
("ź", "z"),
("ż", "z"),
)
|
Provider
|
python
|
pandas-dev__pandas
|
pandas/core/arrays/sparse/accessor.py
|
{
"start": 8310,
"end": 15178
}
|
class ____(BaseAccessor, PandasDelegate):
"""
DataFrame accessor for sparse data.
It allows users to interact with a `DataFrame` that contains sparse data types
(`SparseDtype`). It provides methods and attributes to efficiently work with sparse
storage, reducing memory usage while maintaining compatibility with standard pandas
operations.
Parameters
----------
data : scipy.sparse.spmatrix
Must be convertible to csc format.
See Also
--------
DataFrame.sparse.density : Ratio of non-sparse points to total (dense) data points.
Examples
--------
>>> df = pd.DataFrame({"a": [1, 2, 0, 0], "b": [3, 0, 0, 4]}, dtype="Sparse[int]")
>>> df.sparse.density
np.float64(0.5)
"""
def _validate(self, data) -> None:
dtypes = data.dtypes
if not all(isinstance(t, SparseDtype) for t in dtypes):
raise AttributeError(self._validation_msg)
@classmethod
def from_spmatrix(cls, data, index=None, columns=None) -> DataFrame:
"""
Create a new DataFrame from a scipy sparse matrix.
Parameters
----------
data : scipy.sparse.spmatrix
Must be convertible to csc format.
index, columns : Index, optional
Row and column labels to use for the resulting DataFrame.
Defaults to a RangeIndex.
Returns
-------
DataFrame
Each column of the DataFrame is stored as a
:class:`arrays.SparseArray`.
See Also
--------
DataFrame.sparse.to_coo : Return the contents of the frame as a
sparse SciPy COO matrix.
Examples
--------
>>> import scipy.sparse
>>> mat = scipy.sparse.eye(3, dtype=int)
>>> pd.DataFrame.sparse.from_spmatrix(mat)
0 1 2
0 1 0 0
1 0 1 0
2 0 0 1
"""
from pandas._libs.sparse import IntIndex
from pandas import DataFrame
data = data.tocsc()
index, columns = cls._prep_index(data, index, columns)
n_rows, n_columns = data.shape
# We need to make sure indices are sorted, as we create
# IntIndex with no input validation (i.e. check_integrity=False ).
# Indices may already be sorted in scipy in which case this adds
# a small overhead.
data.sort_indices()
indices = data.indices
indptr = data.indptr
array_data = data.data
dtype = SparseDtype(array_data.dtype)
arrays = []
for i in range(n_columns):
sl = slice(indptr[i], indptr[i + 1])
idx = IntIndex(n_rows, indices[sl], check_integrity=False)
arr = SparseArray._simple_new(array_data[sl], idx, dtype)
arrays.append(arr)
return DataFrame._from_arrays(
arrays, columns=columns, index=index, verify_integrity=False
)
def to_dense(self) -> DataFrame:
"""
Convert a DataFrame with sparse values to dense.
Returns
-------
DataFrame
A DataFrame with the same values stored as dense arrays.
See Also
--------
DataFrame.sparse.density : Ratio of non-sparse points to total
(dense) data points.
Examples
--------
>>> df = pd.DataFrame({"A": pd.arrays.SparseArray([0, 1, 0])})
>>> df.sparse.to_dense()
A
0 0
1 1
2 0
"""
data = {k: v.array.to_dense() for k, v in self._parent.items()}
return self._parent._constructor(
data, index=self._parent.index, columns=self._parent.columns
)
def to_coo(self) -> spmatrix:
"""
Return the contents of the frame as a sparse SciPy COO matrix.
Returns
-------
scipy.sparse.spmatrix
If the caller is heterogeneous and contains booleans or objects,
the result will be of dtype=object. See Notes.
See Also
--------
DataFrame.sparse.to_dense : Convert a DataFrame with sparse values to dense.
Notes
-----
The dtype will be the lowest-common-denominator type (implicit
upcasting); that is to say if the dtypes (even of numeric types)
are mixed, the one that accommodates all will be chosen.
e.g. If the dtypes are float16 and float32, dtype will be upcast to
float32. By numpy.find_common_type convention, mixing int64 and
and uint64 will result in a float64 dtype.
Examples
--------
>>> df = pd.DataFrame({"A": pd.arrays.SparseArray([0, 1, 0, 1])})
>>> df.sparse.to_coo()
<COOrdinate sparse matrix of dtype 'int64'
with 2 stored elements and shape (4, 1)>
"""
import_optional_dependency("scipy")
from scipy.sparse import coo_matrix
dtype = find_common_type(self._parent.dtypes.to_list())
if isinstance(dtype, SparseDtype):
dtype = dtype.subtype
cols, rows, data = [], [], []
for col, (_, ser) in enumerate(self._parent.items()):
sp_arr = ser.array
row = sp_arr.sp_index.indices
cols.append(np.repeat(col, len(row)))
rows.append(row)
data.append(sp_arr.sp_values.astype(dtype, copy=False))
cols_arr = np.concatenate(cols)
rows_arr = np.concatenate(rows)
data_arr = np.concatenate(data)
return coo_matrix((data_arr, (rows_arr, cols_arr)), shape=self._parent.shape)
@property
def density(self) -> float:
"""
Ratio of non-sparse points to total (dense) data points.
See Also
--------
DataFrame.sparse.from_spmatrix : Create a new DataFrame from a
scipy sparse matrix.
Examples
--------
>>> df = pd.DataFrame({"A": pd.arrays.SparseArray([0, 1, 0, 1])})
>>> df.sparse.density
np.float64(0.5)
"""
tmp = np.mean([column.array.density for _, column in self._parent.items()])
return tmp
@staticmethod
def _prep_index(data, index, columns):
from pandas.core.indexes.api import (
default_index,
ensure_index,
)
N, K = data.shape
if index is None:
index = default_index(N)
else:
index = ensure_index(index)
if columns is None:
columns = default_index(K)
else:
columns = ensure_index(columns)
if len(columns) != K:
raise ValueError(f"Column length mismatch: {len(columns)} vs. {K}")
if len(index) != N:
raise ValueError(f"Index length mismatch: {len(index)} vs. {N}")
return index, columns
|
SparseFrameAccessor
|
python
|
chroma-core__chroma
|
chromadb/api/configuration.py
|
{
"start": 13958,
"end": 14776
}
|
class ____(CollectionConfigurationInternal):
"""Configuration parameters for creating a collection."""
def __init__(self, hnsw_configuration: Optional[HNSWConfigurationInternal]):
"""Initializes a new instance of the CollectionConfiguration class.
Args:
hnsw_configuration: The HNSW configuration to use for the collection.
"""
if hnsw_configuration is None:
hnsw_configuration = HNSWConfigurationInternal()
parameters = [
ConfigurationParameter(name="hnsw_configuration", value=hnsw_configuration)
]
super().__init__(parameters=parameters)
# Alias for user convenience - the user doesn't need to know this is an 'Interface'.
CollectionConfiguration = CollectionConfigurationInterface
|
CollectionConfigurationInterface
|
python
|
gevent__gevent
|
src/gevent/tests/test__threadpool.py
|
{
"start": 14973,
"end": 15203
}
|
class ____(object):
refs = None
def func(self, arg1, kwarg1=None):
result = Object()
self.refs.extend([weakref.ref(x) for x in (arg1, kwarg1, result)])
return result
def noop():
pass
|
SomeClass
|
python
|
pytorch__pytorch
|
torch/fx/graph.py
|
{
"start": 8742,
"end": 8966
}
|
class ____(NamedTuple):
"""
Contains extra info stored when we're using Pytrees
"""
orig_args: list[str]
in_spec: pytree.TreeSpec
out_spec: Optional[pytree.TreeSpec]
@dataclass(frozen=True)
|
_PyTreeInfo
|
python
|
tensorflow__tensorflow
|
tensorflow/python/distribute/v1/input_lib.py
|
{
"start": 7275,
"end": 9029
}
|
class ____(input_lib.DistributedIteratorBase):
"""Input Iterator for a distributed dataset."""
# We need a private initializer method for re-initializing multidevice
# iterators when used with Keras training loops. If we don't reinitialize the
# iterator we run into memory leak issues (b/123315763).
@property
def _initializer(self):
init_ops = []
for it in self._iterators:
init_ops.extend(it.initialize())
return control_flow_ops.group(init_ops)
@deprecated(None, "Use the iterator's `initializer` property instead.")
def initialize(self):
"""Initialize underlying iterators.
Returns:
A list of any initializer ops that should be run.
"""
return self._initializer
@property
def initializer(self):
"""Returns a list of ops that initialize the iterator."""
return self.initialize()
# TODO(priyag): Remove when we switch to using `MultiDeviceIterator` for TPUs.
@property
def output_classes(self):
return self._iterators[0].output_classes
# TODO(priyag): Remove when we switch to using `MultiDeviceIterator` for TPUs.
@property
def output_shapes(self):
return self._iterators[0].output_shapes
# TODO(priyag): Remove when we switch to using `MultiDeviceIterator` for TPUs.
@property
def output_types(self):
return self._iterators[0].output_types
# TODO(priyag): Remove when we switch to using `MultiDeviceIterator` for TPUs.
def get_iterator(self, worker):
for i, w in enumerate(self._input_workers.worker_devices):
if worker == w:
return self._iterators[i]
return None
@property
def element_spec(self):
"""The type specification of an element of this iterator."""
return self._element_spec
|
DistributedIteratorV1
|
python
|
airbytehq__airbyte
|
airbyte-integrations/connectors/source-github/source_github/streams.py
|
{
"start": 21489,
"end": 21812
}
|
class ____(GithubStream):
"""
API docs: https://docs.github.com/en/rest/repos/repos?apiVersion=2022-11-28#list-repository-tags
"""
primary_key = ["repository", "name"]
def path(self, stream_slice: Mapping[str, Any] = None, **kwargs) -> str:
return f"repos/{stream_slice['repository']}/tags"
|
Tags
|
python
|
walkccc__LeetCode
|
solutions/3244. Shortest Distance After Road Addition Queries II/3244.py
|
{
"start": 0,
"end": 645
}
|
class ____:
def shortestDistanceAfterQueries(
self,
n: int,
queries: list[list[int]],
) -> list[int]:
ans = []
nodeToFarthestNode = {i: i + 1 for i in range(n - 1)}
for u, v in queries:
# If `u` exists in the map and `v` is farther than the current farthest
# node for `u`, we need to update the map and remove intermediate nodes.
if u in nodeToFarthestNode and nodeToFarthestNode[u] < v:
node = nodeToFarthestNode[u]
while node < v:
node = nodeToFarthestNode.pop(node)
nodeToFarthestNode[u] = v
ans.append(len(nodeToFarthestNode))
return ans
|
Solution
|
python
|
ray-project__ray
|
rllib/models/tf/layers/relative_multi_head_attention.py
|
{
"start": 5286,
"end": 5757
}
|
class ____(tf.keras.layers.Layer if tf else object):
def __init__(self, out_dim, **kwargs):
super().__init__(**kwargs)
self.inverse_freq = 1 / (10000 ** (tf.range(0, out_dim, 2.0) / out_dim))
def call(self, seq_length):
pos_offsets = tf.cast(tf.range(seq_length - 1, -1, -1), tf.float32)
inputs = pos_offsets[:, None] * self.inverse_freq[None, :]
return tf.concat((tf.sin(inputs), tf.cos(inputs)), axis=-1)
|
PositionalEmbedding
|
python
|
spack__spack
|
lib/spack/spack/test/modules/common.py
|
{
"start": 2740,
"end": 2982
}
|
class ____:
def __init__(self, db_ids, spec_hash_to_db):
self.upstream_dbs = db_ids
self.spec_hash_to_db = spec_hash_to_db
def db_for_spec_hash(self, spec_hash):
return self.spec_hash_to_db.get(spec_hash)
|
MockDb
|
python
|
tensorflow__tensorflow
|
tensorflow/python/ops/data_flow_ops.py
|
{
"start": 4415,
"end": 25337
}
|
class ____:
"""Base class for queue implementations.
A queue is a TensorFlow data structure that stores tensors across
multiple steps, and exposes operations that enqueue and dequeue
tensors.
Each queue element is a tuple of one or more tensors, where each
tuple component has a static dtype, and may have a static shape. The
queue implementations support versions of enqueue and dequeue that
handle single elements, versions that support enqueuing and
dequeuing a batch of elements at once.
See `tf.queue.FIFOQueue` and
`tf.queue.RandomShuffleQueue` for concrete
implementations of this class, and instructions on how to create
them.
"""
def __init__(self, dtypes, shapes, names, queue_ref):
"""Constructs a queue object from a queue reference.
The two optional lists, `shapes` and `names`, must be of the same length
as `dtypes` if provided. The values at a given index `i` indicate the
shape and name to use for the corresponding queue component in `dtypes`.
Args:
dtypes: A list of types. The length of dtypes must equal the number
of tensors in each element.
shapes: Constraints on the shapes of tensors in an element:
A list of shape tuples or None. This list is the same length
as dtypes. If the shape of any tensors in the element are constrained,
all must be; shapes can be None if the shapes should not be constrained.
names: Optional list of names. If provided, the `enqueue()` and
`dequeue()` methods will use dictionaries with these names as keys.
Must be None or a list or tuple of the same length as `dtypes`.
queue_ref: The queue reference, i.e. the output of the queue op.
Raises:
ValueError: If one of the arguments is invalid.
"""
self._dtypes = dtypes
if shapes is not None:
if len(shapes) != len(dtypes):
raise ValueError("Queue shapes must have the same length as dtypes, "
f"received len(shapes)={len(shapes)}, "
f"len(dtypes)={len(dtypes)}")
self._shapes = [tensor_shape.TensorShape(s) for s in shapes]
else:
self._shapes = [tensor_shape.unknown_shape() for _ in self._dtypes]
if names is not None:
if len(names) != len(dtypes):
raise ValueError("Queue names must have the same length as dtypes,"
f"received len(names)={len(names)},"
f"len {len(dtypes)}")
self._names = names
else:
self._names = None
self._queue_ref = queue_ref
if isinstance(queue_ref, ops.EagerTensor):
if context.context().scope_name:
self._name = context.context().scope_name
else:
self._name = "Empty"
self._resource_deleter = resource_variable_ops.EagerResourceDeleter(
queue_ref, None)
else:
self._name = self._queue_ref.op.name.split("/")[-1]
@staticmethod
def from_list(index, queues):
"""Create a queue using the queue reference from `queues[index]`.
Args:
index: An integer scalar tensor that determines the input that gets
selected.
queues: A list of `QueueBase` objects.
Returns:
A `QueueBase` object.
Raises:
TypeError: When `queues` is not a list of `QueueBase` objects,
or when the data types of `queues` are not all the same.
"""
if ((not queues) or (not isinstance(queues, list)) or
(not all(isinstance(x, QueueBase) for x in queues))):
raise TypeError("A list of queues expected")
dtypes = queues[0].dtypes
if not all(dtypes == q.dtypes for q in queues[1:]):
raise TypeError("Queues do not have matching component dtypes.")
names = queues[0].names
if not all(names == q.names for q in queues[1:]):
raise TypeError("Queues do not have matching component names.")
queue_shapes = [q.shapes for q in queues]
reduced_shapes = [
functools.reduce(_shape_common, s) for s in zip(*queue_shapes)
]
queue_refs = array_ops_stack.stack([x.queue_ref for x in queues])
selected_queue = array_ops.gather(queue_refs, index)
return QueueBase(
dtypes=dtypes,
shapes=reduced_shapes,
names=names,
queue_ref=selected_queue)
@property
def queue_ref(self):
"""The underlying queue reference."""
return self._queue_ref
@property
def name(self):
"""The name of the underlying queue."""
if context.executing_eagerly():
return self._name
return self._queue_ref.op.name
@property
def dtypes(self):
"""The list of dtypes for each component of a queue element."""
return self._dtypes
@property
def shapes(self):
"""The list of shapes for each component of a queue element."""
return self._shapes
@property
def names(self):
"""The list of names for each component of a queue element."""
return self._names
def _check_enqueue_dtypes(self, vals):
"""Validate and convert `vals` to a list of `Tensor`s.
The `vals` argument can be a Tensor, a list or tuple of tensors, or a
dictionary with tensor values.
If it is a dictionary, the queue must have been constructed with a
`names` attribute and the dictionary keys must match the queue names.
If the queue was constructed with a `names` attribute, `vals` must
be a dictionary.
Args:
vals: A tensor, a list or tuple of tensors, or a dictionary..
Returns:
A list of `Tensor` objects.
Raises:
ValueError: If `vals` is invalid.
"""
if isinstance(vals, dict):
if not self._names:
raise ValueError("Queue must have names to enqueue a dictionary")
if sorted(self._names, key=str) != sorted(vals.keys(), key=str):
raise ValueError("Keys in dictionary to enqueue do not match "
f"names of Queue. Dictionary: {sorted(vals.keys())},"
f"Queue: {sorted(self._names)}")
# The order of values in `self._names` indicates the order in which the
# tensors in the dictionary `vals` must be listed.
vals = [vals[k] for k in self._names]
else:
if self._names:
raise ValueError("You must enqueue a dictionary in a Queue with names")
if not isinstance(vals, (list, tuple)):
vals = [vals]
tensors = []
for i, (val, dtype) in enumerate(zip(vals, self._dtypes)):
tensors.append(
ops.convert_to_tensor(val, dtype=dtype, name="component_%d" % i))
return tensors
def _scope_vals(self, vals):
"""Return a list of values to pass to `name_scope()`.
Args:
vals: A tensor, a list or tuple of tensors, or a dictionary.
Returns:
The values in vals as a list.
"""
if isinstance(vals, (list, tuple)):
return vals
elif isinstance(vals, dict):
return vals.values()
else:
return [vals]
def enqueue(self, vals, name=None):
"""Enqueues one element to this queue.
If the queue is full when this operation executes, it will block
until the element has been enqueued.
At runtime, this operation may raise an error if the queue is
`tf.QueueBase.close` before or during its execution. If the
queue is closed before this operation runs,
`tf.errors.CancelledError` will be raised. If this operation is
blocked, and either (i) the queue is closed by a close operation
with `cancel_pending_enqueues=True`, or (ii) the session is
`tf.Session.close`,
`tf.errors.CancelledError` will be raised.
>>> q = tf.queue.FIFOQueue(capacity=3, dtypes=tf.int32)
>>> q.enqueue(1)
>>> q.enqueue(2)
>>> q.size()
<tf.Tensor: shape=(), dtype=int32, numpy=2>
>>> q = tf.queue.FIFOQueue(2, tf.int32, shapes=tf.TensorShape(4))
>>> q.enqueue(tf.constant([1, 2, 3, 4], dtype=tf.int32))
>>> q.size()
<tf.Tensor: shape=(), dtype=int32, numpy=1>
Args:
vals: A tensor, a list or tuple of tensors, or a dictionary containing
the values to enqueue.
name: A name for the operation (optional).
Returns:
The operation that enqueues a new tuple of tensors to the queue.
"""
with ops.name_scope(name, "%s_enqueue" % self._name,
self._scope_vals(vals)) as scope:
vals = self._check_enqueue_dtypes(vals)
# NOTE(mrry): Not using a shape function because we need access to
# the `QueueBase` object.
for val, shape in zip(vals, self._shapes):
val.get_shape().assert_is_compatible_with(shape)
if self._queue_ref.dtype == _dtypes.resource:
return gen_data_flow_ops.queue_enqueue_v2(
self._queue_ref, vals, name=scope)
else:
return gen_data_flow_ops.queue_enqueue(
self._queue_ref, vals, name=scope)
def enqueue_many(self, vals, name=None):
"""Enqueues zero or more elements to this queue.
This operation slices each component tensor along the 0th dimension to
make multiple queue elements. All of the tensors in `vals` must have the
same size in the 0th dimension.
If the queue is full when this operation executes, it will block
until all of the elements have been enqueued.
At runtime, this operation may raise an error if the queue is
`tf.QueueBase.close` before or during its execution. If the
queue is closed before this operation runs,
`tf.errors.CancelledError` will be raised. If this operation is
blocked, and either (i) the queue is closed by a close operation
with `cancel_pending_enqueues=True`, or (ii) the session is
`tf.Session.close`,
`tf.errors.CancelledError` will be raised.
>>> q = tf.queue.FIFOQueue(capacity=10, dtypes=tf.int32)
>>> q.enqueue_many(tf.constant([1, 2, 3, 4, 5], dtype=tf.int32))
>>> q.size()
<tf.Tensor: shape=(), dtype=int32, numpy=5>
Args:
vals: A tensor, a list or tuple of tensors, or a dictionary
from which the queue elements are taken.
name: A name for the operation (optional).
Returns:
The operation that enqueues a batch of tuples of tensors to the queue.
"""
with ops.name_scope(name, "%s_EnqueueMany" % self._name,
self._scope_vals(vals)) as scope:
vals = self._check_enqueue_dtypes(vals)
# NOTE(mrry): Not using a shape function because we need access to
# the `QueueBase` object.
# NOTE(fchollet): the code that follow is verbose because it needs to be
# compatible with both TF v1 TensorShape behavior and TF v2 behavior.
batch_dim = tensor_shape.dimension_value(
vals[0].get_shape().with_rank_at_least(1)[0])
batch_dim = tensor_shape.Dimension(batch_dim)
for val, shape in zip(vals, self._shapes):
val_batch_dim = tensor_shape.dimension_value(
val.get_shape().with_rank_at_least(1)[0])
val_batch_dim = tensor_shape.Dimension(val_batch_dim)
batch_dim = batch_dim.merge_with(val_batch_dim)
val.get_shape()[1:].assert_is_compatible_with(shape)
return gen_data_flow_ops.queue_enqueue_many_v2(
self._queue_ref, vals, name=scope)
def _dequeue_return_value(self, tensors):
"""Return the value to return from a dequeue op.
If the queue has names, return a dictionary with the
names as keys. Otherwise return either a single tensor
or a list of tensors depending on the length of `tensors`.
Args:
tensors: List of tensors from the dequeue op.
Returns:
A single tensor, a list of tensors, or a dictionary
of tensors.
"""
if self._names:
# The returned values in `tensors` are in the same order as
# the names in `self._names`.
return {n: tensors[i] for i, n in enumerate(self._names)}
elif len(tensors) == 1:
return tensors[0]
else:
return tensors
def dequeue(self, name=None):
"""Dequeues one element from this queue.
If the queue is empty when this operation executes, it will block
until there is an element to dequeue.
At runtime, this operation may raise an error if the queue is
`tf.QueueBase.close` before or during its execution. If the
queue is closed, the queue is empty, and there are no pending
enqueue operations that can fulfill this request,
`tf.errors.OutOfRangeError` will be raised. If the session is
`tf.Session.close`,
`tf.errors.CancelledError` will be raised.
>>> q = tf.queue.FIFOQueue(capacity=2, dtypes=tf.int32)
>>> q.enqueue(1)
>>> q.enqueue(2)
>>> q.dequeue()
<tf.Tensor: shape=(), dtype=int32, numpy=1>
>>> q.dequeue()
<tf.Tensor: shape=(), dtype=int32, numpy=2>
Args:
name: A name for the operation (optional).
Returns:
The tuple of tensors that was dequeued.
"""
if name is None:
name = "%s_Dequeue" % self._name
if self._queue_ref.dtype == _dtypes.resource:
ret = gen_data_flow_ops.queue_dequeue_v2(
self._queue_ref, self._dtypes, name=name)
else:
ret = gen_data_flow_ops.queue_dequeue(
self._queue_ref, self._dtypes, name=name)
# NOTE(mrry): Not using a shape function because we need access to
# the `QueueBase` object.
if not context.executing_eagerly():
op = ret[0].op
for output, shape in zip(op.values(), self._shapes):
output.set_shape(shape)
return self._dequeue_return_value(ret)
def dequeue_many(self, n, name=None):
"""Dequeues and concatenates `n` elements from this queue.
This operation concatenates queue-element component tensors along
the 0th dimension to make a single component tensor. All of the
components in the dequeued tuple will have size `n` in the 0th dimension.
If the queue is closed and there are less than `n` elements left, then an
`OutOfRange` exception is raised.
At runtime, this operation may raise an error if the queue is
`tf.QueueBase.close` before or during its execution. If the
queue is closed, the queue contains fewer than `n` elements, and
there are no pending enqueue operations that can fulfill this
request, `tf.errors.OutOfRangeError` will be raised. If the
session is `tf.Session.close`,
`tf.errors.CancelledError` will be raised.
>>> q = tf.queue.FIFOQueue(10, tf.int32, shapes=tf.TensorShape(2))
>>> q.enqueue(tf.constant([1, 2], dtype=tf.int32, shape=(2)))
>>> q.enqueue(tf.constant([3, 4], dtype=tf.int32, shape=(2)))
>>> q.enqueue(tf.constant([5, 6], dtype=tf.int32, shape=(2)))
>>> q.enqueue(tf.constant([7, 8], dtype=tf.int32, shape=(2)))
>>> q.dequeue_many(3)
<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
array([[1, 2],
[3, 4],
[5, 6]], dtype=int32)>
Args:
n: A scalar `Tensor` containing the number of elements to dequeue.
name: A name for the operation (optional).
Returns:
The list of concatenated tensors that was dequeued.
"""
if name is None:
name = "%s_DequeueMany" % self._name
ret = gen_data_flow_ops.queue_dequeue_many_v2(
self._queue_ref, n=n, component_types=self._dtypes, name=name)
# NOTE(mrry): Not using a shape function because we need access to
# the Queue object.
if not context.executing_eagerly():
op = ret[0].op
batch_dim = tensor_shape.Dimension(
tensor_util.constant_value(op.inputs[1]))
for output, shape in zip(op.values(), self._shapes):
output.set_shape(
tensor_shape.TensorShape([batch_dim]).concatenate(shape))
return self._dequeue_return_value(ret)
def dequeue_up_to(self, n, name=None):
"""Dequeues and concatenates `n` elements from this queue.
**Note** This operation is not supported by all queues. If a queue does not
support DequeueUpTo, then a `tf.errors.UnimplementedError` is raised.
This operation concatenates queue-element component tensors along
the 0th dimension to make a single component tensor. If the queue
has not been closed, all of the components in the dequeued tuple
will have size `n` in the 0th dimension.
If the queue is closed and there are more than `0` but fewer than
`n` elements remaining, then instead of raising a
`tf.errors.OutOfRangeError` like `tf.QueueBase.dequeue_many`,
less than `n` elements are returned immediately. If the queue is
closed and there are `0` elements left in the queue, then a
`tf.errors.OutOfRangeError` is raised just like in `dequeue_many`.
Otherwise the behavior is identical to `dequeue_many`.
>>> q = tf.queue.FIFOQueue(10, tf.int32, shapes=tf.TensorShape(2))
>>> q.enqueue(tf.constant([1, 2], dtype=tf.int32, shape=(2)))
>>> q.enqueue(tf.constant([3, 4], dtype=tf.int32, shape=(2)))
>>> q.close()
>>> q.dequeue_up_to(5)
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[1, 2],
[3, 4]], dtype=int32)>
Args:
n: A scalar `Tensor` containing the number of elements to dequeue.
name: A name for the operation (optional).
Returns:
The tuple of concatenated tensors that was dequeued.
"""
if name is None:
name = "%s_DequeueUpTo" % self._name
ret = gen_data_flow_ops.queue_dequeue_up_to_v2(
self._queue_ref, n=n, component_types=self._dtypes, name=name)
# NOTE(mrry): Not using a shape function because we need access to
# the Queue object.
if not context.executing_eagerly():
op = ret[0].op
for output, shape in zip(op.values(), self._shapes):
output.set_shape(tensor_shape.TensorShape([None]).concatenate(shape))
return self._dequeue_return_value(ret)
def close(self, cancel_pending_enqueues=False, name=None):
"""Closes this queue.
This operation signals that no more elements will be enqueued in
the given queue. Subsequent `enqueue` and `enqueue_many`
operations will fail. Subsequent `dequeue` and `dequeue_many`
operations will continue to succeed if sufficient elements remain
in the queue. Subsequently, dequeue and dequeue_many operations
that would otherwise block waiting for more elements (if close
hadn't been called) will now fail immediately.
If `cancel_pending_enqueues` is `True`, all pending requests will also
be canceled.
>>> q = tf.queue.FIFOQueue(capacity=3, dtypes=tf.int32)
>>> q.is_closed()
<tf.Tensor: shape=(), dtype=bool, numpy=False>
>>> q.close()
>>> q.is_closed()
<tf.Tensor: shape=(), dtype=bool, numpy=True>
Args:
cancel_pending_enqueues: (Optional.) A boolean, defaulting to `False`
(described above).
name: A name for the operation (optional).
Returns:
The operation that closes the queue.
"""
if name is None:
name = "%s_Close" % self._name
if self._queue_ref.dtype == _dtypes.resource:
return gen_data_flow_ops.queue_close_v2(
self._queue_ref,
cancel_pending_enqueues=cancel_pending_enqueues,
name=name)
else:
return gen_data_flow_ops.queue_close(
self._queue_ref,
cancel_pending_enqueues=cancel_pending_enqueues,
name=name)
def is_closed(self, name=None):
"""Returns true if queue is closed.
This operation returns true if the queue is closed and false if the queue
is open.
>>> q = tf.queue.FIFOQueue(capacity=3, dtypes=tf.int32)
>>> q.is_closed()
<tf.Tensor: shape=(), dtype=bool, numpy=False>
Args:
name: A name for the operation (optional).
Returns:
True if the queue is closed and false if the queue is open.
"""
if name is None:
name = "%s_Is_Closed" % self._name
if self._queue_ref.dtype == _dtypes.resource:
return gen_data_flow_ops.queue_is_closed_v2(self._queue_ref, name=name)
else:
return gen_data_flow_ops.queue_is_closed_(self._queue_ref, name=name)
def size(self, name=None):
"""Compute the number of elements in this queue.
>>> q = tf.queue.FIFOQueue(capacity=10, dtypes=tf.int32)
>>> q.enqueue_many(tf.constant([1, 2, 3, 4], dtype=tf.int32))
>>> q.size()
<tf.Tensor: shape=(), dtype=int32, numpy=4>
Args:
name: A name for the operation (optional).
Returns:
A scalar tensor containing the number of elements in this queue.
"""
if name is None:
name = "%s_Size" % self._name
if self._queue_ref.dtype == _dtypes.resource:
return gen_data_flow_ops.queue_size_v2(self._queue_ref, name=name)
else:
return gen_data_flow_ops.queue_size(self._queue_ref, name=name)
def _shared_name(shared_name):
if context.executing_eagerly():
return str(ops.uid())
return shared_name
@tf_export(
"queue.RandomShuffleQueue",
v1=["queue.RandomShuffleQueue",
"io.RandomShuffleQueue", "RandomShuffleQueue"])
@deprecation.deprecated_endpoints(
["io.RandomShuffleQueue", "RandomShuffleQueue"])
|
QueueBase
|
python
|
ray-project__ray
|
python/ray/_private/gcs_pubsub.py
|
{
"start": 6593,
"end": 7433
}
|
class ____(_AioSubscriber):
def __init__(
self,
worker_id: bytes = None,
address: str = None,
channel: grpc.Channel = None,
):
super().__init__(
pubsub_pb2.RAY_NODE_RESOURCE_USAGE_CHANNEL, worker_id, address, channel
)
async def poll(self, timeout=None) -> Tuple[bytes, str]:
"""Polls for new resource usage message.
Returns:
A tuple of string reporter ID and resource usage json string.
"""
await self._poll(timeout=timeout)
return self._pop_resource_usage(self._queue)
@staticmethod
def _pop_resource_usage(queue):
if len(queue) == 0:
return None, None
msg = queue.popleft()
return msg.key_id.decode(), msg.node_resource_usage_message.json
|
GcsAioResourceUsageSubscriber
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.