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 | PyCQA__pylint | tests/functional/u/unused/unused_private_member.py | {
"start": 9453,
"end": 9683
} | class ____:
"""Regression test for https://github.com/pylint-dev/pylint/issues/6709"""
def __init__(self, parent):
self.__parent: Item = parent
self.__item = self.__parent.__item # [unused-private-member]
| Item |
python | huggingface__transformers | src/transformers/models/data2vec/configuration_data2vec_audio.py | {
"start": 796,
"end": 16345
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Data2VecAudioModel`]. It is used to instantiate
an Data2VecAudio 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 Data2VecAudio
[facebook/data2vec-audio-base-960h](https://huggingface.co/facebook/data2vec-audio-base-960h) 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 32):
Vocabulary size of the Data2VecAudio model. Defines the number of different tokens that can be represented
by the `inputs_ids` passed when calling [`Data2VecAudioModel`]. Vocabulary size
of the model. Defines the different tokens that can be represented by the *inputs_ids* passed to the
forward method of [`Data2VecAudioModel`].
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" (i.e., feed-forward) layer in the Transformer encoder.
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"selu"` and `"gelu_new"` are supported.
hidden_dropout (`float`, *optional*, defaults to 0.1):
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
activation_dropout (`float`, *optional*, defaults to 0.1):
The dropout ratio for activations inside the fully connected layer.
attention_dropout (`float`, *optional*, defaults to 0.1):
The dropout ratio for the attention probabilities.
final_dropout (`float`, *optional*, defaults to 0.1):
The dropout probability for the final projection layer of [`Data2VecAudioForCTC`].
layerdrop (`float`, *optional*, defaults to 0.1):
The LayerDrop probability. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556) for more
details.
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.
feat_proj_dropout (`float`, *optional*, defaults to 0.0):
The dropout probability for output of the feature encoder.
feat_extract_activation (`str, `optional`, defaults to `"gelu"`):
The non-linear activation function (function or string) in the 1D convolutional layers of the feature
extractor. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.
conv_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`):
A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
feature encoder. The length of *conv_dim* defines the number of 1D convolutional layers.
conv_stride (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`):
A tuple of integers defining the stride of each 1D convolutional layer in the feature encoder. The length
of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*.
conv_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 3, 3)`):
A tuple of integers defining the kernel size of each 1D convolutional layer in the feature encoder. The
length of *conv_kernel* defines the number of convolutional layers and has to match the length of
*conv_dim*.
conv_bias (`bool`, *optional*, defaults to `False`):
Whether the 1D convolutional layers have a bias.
num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
embeddings layer.
num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
Number of groups of 1D convolutional positional embeddings layer.
mask_time_prob (`float`, *optional*, defaults to 0.05):
Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
procedure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If
reasoning from the probability of each feature vector to be chosen as the start of the vector span to be
masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
mask_time_length (`int`, *optional*, defaults to 10):
Length of vector span along the time axis.
mask_time_min_masks (`int`, *optional*, defaults to 2),:
The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
mask_time_min_masks''
mask_feature_prob (`float`, *optional*, defaults to 0.0):
Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
masking procedure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over
the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector
span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
True`.
mask_feature_length (`int`, *optional*, defaults to 10):
Length of vector span along the feature axis.
mask_feature_min_masks (`int`, *optional*, defaults to 0),:
The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
step, irrespectively of `mask_feature_prob`. Only relevant if
''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''
ctc_loss_reduction (`str`, *optional*, defaults to `"sum"`):
Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an
instance of [`Data2VecAudioForCTC`].
ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
of [`Data2VecAudioForCTC`].
use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
instance of [`Data2VecAudioForSequenceClassification`].
classifier_proj_size (`int`, *optional*, defaults to 256):
Dimensionality of the projection before token mean-pooling for classification.
tdnn_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 1500)`):
A tuple of integers defining the number of output channels of each 1D convolutional layer in the *TDNN*
module of the *XVector* model. The length of *tdnn_dim* defines the number of *TDNN* layers.
tdnn_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 3, 3, 1, 1)`):
A tuple of integers defining the kernel size of each 1D convolutional layer in the *TDNN* module of the
*XVector* model. The length of *tdnn_kernel* has to match the length of *tdnn_dim*.
tdnn_dilation (`tuple[int]` or `list[int]`, *optional*, defaults to `(1, 2, 3, 1, 1)`):
A tuple of integers defining the dilation factor of each 1D convolutional layer in *TDNN* module of the
*XVector* model. The length of *tdnn_dilation* has to match the length of *tdnn_dim*.
xvector_output_dim (`int`, *optional*, defaults to 512):
Dimensionality of the *XVector* embedding vectors.
add_adapter (`bool`, *optional*, defaults to `False`):
Whether a convolutional network should be stacked on top of the Data2VecAudio Encoder. Can be very useful
for warm-starting Data2VecAudio for SpeechEncoderDecoder models.
adapter_kernel_size (`int`, *optional*, defaults to 3):
Kernel size of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
adapter_stride (`int`, *optional*, defaults to 2):
Stride of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
num_adapter_layers (`int`, *optional*, defaults to 3):
Number of convolutional layers that should be used in the adapter network. Only relevant if `add_adapter is
True`.
output_hidden_size (`int`, *optional*):
Dimensionality of the encoder output layer. If not defined, this defaults to *hidden-size*. Only relevant
if `add_adapter is True`.
Example:
```python
>>> from transformers import Data2VecAudioConfig, Data2VecAudioModel
>>> # Initializing a Data2VecAudio facebook/data2vec-audio-base-960h style configuration
>>> configuration = Data2VecAudioConfig()
>>> # Initializing a model (with random weights) from the facebook/data2vec-audio-base-960h style configuration
>>> model = Data2VecAudioModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "data2vec-audio"
def __init__(
self,
vocab_size=32,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
hidden_act="gelu",
hidden_dropout=0.1,
activation_dropout=0.1,
attention_dropout=0.1,
feat_proj_dropout=0.0,
final_dropout=0.1,
layerdrop=0.1,
initializer_range=0.02,
layer_norm_eps=1e-5,
feat_extract_activation="gelu",
conv_dim=(512, 512, 512, 512, 512, 512, 512),
conv_stride=(5, 2, 2, 2, 2, 2, 2),
conv_kernel=(10, 3, 3, 3, 3, 2, 2),
conv_bias=False,
num_conv_pos_embedding_groups=16,
conv_pos_kernel_size=19,
num_conv_pos_embeddings=5,
mask_time_prob=0.05,
mask_time_length=10,
mask_time_min_masks=2,
mask_feature_prob=0.0,
mask_feature_length=10,
mask_feature_min_masks=0,
ctc_loss_reduction="sum",
ctc_zero_infinity=False,
use_weighted_layer_sum=False,
classifier_proj_size=256,
tdnn_dim=(512, 512, 512, 512, 1500),
tdnn_kernel=(5, 3, 3, 1, 1),
tdnn_dilation=(1, 2, 3, 1, 1),
xvector_output_dim=512,
pad_token_id=0,
bos_token_id=1,
eos_token_id=2,
add_adapter=False,
adapter_kernel_size=3,
adapter_stride=2,
num_adapter_layers=3,
output_hidden_size=None,
**kwargs,
):
super().__init__(**kwargs, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id)
self.hidden_size = hidden_size
self.feat_extract_activation = feat_extract_activation
self.conv_dim = list(conv_dim)
self.conv_stride = list(conv_stride)
self.conv_kernel = list(conv_kernel)
self.conv_bias = conv_bias
self.num_conv_pos_embeddings = num_conv_pos_embeddings
self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups
self.conv_pos_kernel_size = conv_pos_kernel_size
self.num_feat_extract_layers = len(self.conv_dim)
self.num_hidden_layers = num_hidden_layers
self.intermediate_size = intermediate_size
self.hidden_act = hidden_act
self.num_attention_heads = num_attention_heads
self.hidden_dropout = hidden_dropout
self.attention_dropout = attention_dropout
self.activation_dropout = activation_dropout
self.feat_proj_dropout = feat_proj_dropout
self.final_dropout = final_dropout
self.layerdrop = layerdrop
self.layer_norm_eps = layer_norm_eps
self.initializer_range = initializer_range
self.vocab_size = vocab_size
self.use_weighted_layer_sum = use_weighted_layer_sum
if (
(len(self.conv_stride) != self.num_feat_extract_layers)
or (len(self.conv_kernel) != self.num_feat_extract_layers)
or (len(self.conv_dim) != self.num_feat_extract_layers)
):
raise ValueError(
"Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
" `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"
f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."
)
# fine-tuning config parameters for SpecAugment: https://huggingface.co/papers/1904.08779
self.mask_time_prob = mask_time_prob
self.mask_time_length = mask_time_length
self.mask_time_min_masks = mask_time_min_masks
self.mask_feature_prob = mask_feature_prob
self.mask_feature_length = mask_feature_length
self.mask_feature_min_masks = mask_feature_min_masks
# ctc loss
self.ctc_loss_reduction = ctc_loss_reduction
self.ctc_zero_infinity = ctc_zero_infinity
# adapter
self.add_adapter = add_adapter
self.adapter_kernel_size = adapter_kernel_size
self.adapter_stride = adapter_stride
self.num_adapter_layers = num_adapter_layers
self.output_hidden_size = output_hidden_size or hidden_size
# SequenceClassification-specific parameter. Feel free to ignore for other classes.
self.classifier_proj_size = classifier_proj_size
# XVector-specific parameters. Feel free to ignore for other classes.
self.tdnn_dim = list(tdnn_dim)
self.tdnn_kernel = list(tdnn_kernel)
self.tdnn_dilation = list(tdnn_dilation)
self.xvector_output_dim = xvector_output_dim
@property
def inputs_to_logits_ratio(self):
return math.prod(self.conv_stride)
__all__ = ["Data2VecAudioConfig"]
| Data2VecAudioConfig |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/strategies/_internal/core.py | {
"start": 15949,
"end": 39310
} | class ____:
def __init__(self, values):
self._values = values
self._iter = iter(self._values)
def __iter__(self):
return self._iter
def __next__(self):
return next(self._iter)
def __repr__(self) -> str:
return f"iter({self._values!r})"
@defines_strategy()
def iterables(
elements: SearchStrategy[Ex],
*,
min_size: int = 0,
max_size: int | None = None,
unique_by: (
None | Callable[[Ex], Hashable] | tuple[Callable[[Ex], Hashable], ...]
) = None,
unique: bool = False,
) -> SearchStrategy[Iterable[Ex]]:
"""This has the same behaviour as lists, but returns iterables instead.
Some iterables cannot be indexed (e.g. sets) and some do not have a
fixed length (e.g. generators). This strategy produces iterators,
which cannot be indexed and do not have a fixed length. This ensures
that you do not accidentally depend on sequence behaviour.
"""
return lists(
elements=elements,
min_size=min_size,
max_size=max_size,
unique_by=unique_by,
unique=unique,
).map(PrettyIter)
# this type definition is imprecise, in multiple ways:
# * mapping and optional can be of different types:
# s: dict[str | int, int] = st.fixed_dictionaries(
# {"a": st.integers()}, optional={1: st.integers()}
# )
# * the values in either mapping or optional need not all be of the same type:
# s: dict[str, int | bool] = st.fixed_dictionaries(
# {"a": st.integers(), "b": st.booleans()}
# )
# * the arguments may be of any dict-compatible type, in which case the return
# value will be of that type instead of dit
#
# Overloads may help here, but I doubt we'll be able to satisfy all these
# constraints.
#
# Here's some platonic ideal test cases for revealed_types.py, with the understanding
# that some may not be achievable:
#
# ("fixed_dictionaries({'a': booleans()})", "dict[str, bool]"),
# ("fixed_dictionaries({'a': booleans(), 'b': integers()})", "dict[str, bool | int]"),
# ("fixed_dictionaries({}, optional={'a': booleans()})", "dict[str, bool]"),
# (
# "fixed_dictionaries({'a': booleans()}, optional={1: booleans()})",
# "dict[str | int, bool]",
# ),
# (
# "fixed_dictionaries({'a': booleans()}, optional={1: integers()})",
# "dict[str | int, bool | int]",
# ),
@defines_strategy()
def fixed_dictionaries(
mapping: dict[T, SearchStrategy[Ex]],
*,
optional: dict[T, SearchStrategy[Ex]] | None = None,
) -> SearchStrategy[dict[T, Ex]]:
"""Generates a dictionary of the same type as mapping with a fixed set of
keys mapping to strategies. ``mapping`` must be a dict subclass.
Generated values have all keys present in mapping, in iteration order,
with the corresponding values drawn from mapping[key].
If ``optional`` is passed, the generated value *may or may not* contain each
key from ``optional`` and a value drawn from the corresponding strategy.
Generated values may contain optional keys in an arbitrary order.
Examples from this strategy shrink by shrinking each individual value in
the generated dictionary, and omitting optional key-value pairs.
"""
check_type(dict, mapping, "mapping")
for k, v in mapping.items():
check_strategy(v, f"mapping[{k!r}]")
if optional is not None:
check_type(dict, optional, "optional")
for k, v in optional.items():
check_strategy(v, f"optional[{k!r}]")
if type(mapping) != type(optional):
raise InvalidArgument(
f"Got arguments of different types: "
f"mapping={nicerepr(type(mapping))}, "
f"optional={nicerepr(type(optional))}"
)
if set(mapping) & set(optional):
raise InvalidArgument(
"The following keys were in both mapping and optional, "
f"which is invalid: {set(mapping) & set(optional)!r}"
)
return FixedDictStrategy(mapping, optional=optional)
_get_first_item = operator.itemgetter(0)
@cacheable
@defines_strategy()
def dictionaries(
keys: SearchStrategy[Ex],
values: SearchStrategy[T],
*,
dict_class: type = dict,
min_size: int = 0,
max_size: int | None = None,
) -> SearchStrategy[dict[Ex, T]]:
# Describing the exact dict_class to Mypy drops the key and value types,
# so we report Dict[K, V] instead of Mapping[Any, Any] for now. Sorry!
"""Generates dictionaries of type ``dict_class`` with keys drawn from the ``keys``
argument and values drawn from the ``values`` argument.
The size parameters have the same interpretation as for
:func:`~hypothesis.strategies.lists`.
Examples from this strategy shrink by trying to remove keys from the
generated dictionary, and by shrinking each generated key and value.
"""
check_valid_sizes(min_size, max_size)
if max_size == 0:
return fixed_dictionaries(dict_class())
check_strategy(keys, "keys")
check_strategy(values, "values")
return lists(
tuples(keys, values),
min_size=min_size,
max_size=max_size,
unique_by=_get_first_item,
).map(dict_class)
@cacheable
@defines_strategy(force_reusable_values=True)
def characters(
*,
codec: str | None = None,
min_codepoint: int | None = None,
max_codepoint: int | None = None,
categories: Collection[CategoryName] | None = None,
exclude_categories: Collection[CategoryName] | None = None,
exclude_characters: Collection[str] | None = None,
include_characters: Collection[str] | None = None,
# Note: these arguments are deprecated aliases for backwards compatibility
blacklist_categories: Collection[CategoryName] | None = None,
whitelist_categories: Collection[CategoryName] | None = None,
blacklist_characters: Collection[str] | None = None,
whitelist_characters: Collection[str] | None = None,
) -> SearchStrategy[str]:
r"""Generates characters, length-one :class:`python:str`\ ings,
following specified filtering rules.
- When no filtering rules are specified, any character can be produced.
- If ``min_codepoint`` or ``max_codepoint`` is specified, then only
characters having a codepoint in that range will be produced.
- If ``categories`` is specified, then only characters from those
Unicode categories will be produced. This is a further restriction,
characters must also satisfy ``min_codepoint`` and ``max_codepoint``.
- If ``exclude_categories`` is specified, then any character from those
categories will not be produced. You must not pass both ``categories``
and ``exclude_categories``; these arguments are alternative ways to
specify exactly the same thing.
- If ``include_characters`` is specified, then any additional characters
in that list will also be produced.
- If ``exclude_characters`` is specified, then any characters in
that list will be not be produced. Any overlap between
``include_characters`` and ``exclude_characters`` will raise an
exception.
- If ``codec`` is specified, only characters in the specified `codec encodings`_
will be produced.
The ``_codepoint`` arguments must be integers between zero and
:obj:`python:sys.maxunicode`. The ``_characters`` arguments must be
collections of length-one unicode strings, such as a unicode string.
The ``_categories`` arguments must be used to specify either the
one-letter Unicode major category or the two-letter Unicode
`general category`_. For example, ``('Nd', 'Lu')`` signifies "Number,
decimal digit" and "Letter, uppercase". A single letter ('major category')
can be given to match all corresponding categories, for example ``'P'``
for characters in any punctuation category.
We allow codecs from the :mod:`codecs` module and their aliases, platform
specific and user-registered codecs if they are available, and
`python-specific text encodings`_ (but not text or binary transforms).
``include_characters`` which cannot be encoded using this codec will
raise an exception. If non-encodable codepoints or categories are
explicitly allowed, the ``codec`` argument will exclude them without
raising an exception.
.. _general category: https://en.wikipedia.org/wiki/Unicode_character_property
.. _codec encodings: https://docs.python.org/3/library/codecs.html#encodings-and-unicode
.. _python-specific text encodings: https://docs.python.org/3/library/codecs.html#python-specific-encodings
Examples from this strategy shrink towards the codepoint for ``'0'``,
or the first allowable codepoint after it if ``'0'`` is excluded.
"""
check_valid_size(min_codepoint, "min_codepoint")
check_valid_size(max_codepoint, "max_codepoint")
check_valid_interval(min_codepoint, max_codepoint, "min_codepoint", "max_codepoint")
categories = cast(Categories | None, categories)
if categories is not None and exclude_categories is not None:
raise InvalidArgument(
f"Pass at most one of {categories=} and {exclude_categories=} - "
"these arguments both specify which categories are allowed, so it "
"doesn't make sense to use both in a single call."
)
# Handle deprecation of whitelist/blacklist arguments
has_old_arg = any(v is not None for k, v in locals().items() if "list" in k)
has_new_arg = any(v is not None for k, v in locals().items() if "lude" in k)
if has_old_arg and has_new_arg:
raise InvalidArgument(
"The deprecated blacklist/whitelist arguments cannot be used in "
"the same call as their replacement include/exclude arguments."
)
if blacklist_categories is not None:
exclude_categories = blacklist_categories
if whitelist_categories is not None:
categories = whitelist_categories
if blacklist_characters is not None:
exclude_characters = blacklist_characters
if whitelist_characters is not None:
include_characters = whitelist_characters
if (
min_codepoint is None
and max_codepoint is None
and categories is None
and exclude_categories is None
and include_characters is not None
and codec is None
):
raise InvalidArgument(
"Nothing is excluded by other arguments, so passing only "
f"{include_characters=} would have no effect. "
"Also pass categories=(), or use "
f"sampled_from({include_characters!r}) instead."
)
exclude_characters = exclude_characters or ""
include_characters = include_characters or ""
if not_one_char := [c for c in exclude_characters if len(c) != 1]:
raise InvalidArgument(
"Elements of exclude_characters are required to be a single character, "
f"but {not_one_char!r} passed in {exclude_characters=} was not."
)
if not_one_char := [c for c in include_characters if len(c) != 1]:
raise InvalidArgument(
"Elements of include_characters are required to be a single character, "
f"but {not_one_char!r} passed in {include_characters=} was not."
)
overlap = set(exclude_characters).intersection(include_characters)
if overlap:
raise InvalidArgument(
f"Characters {sorted(overlap)!r} are present in both "
f"{include_characters=} and {exclude_characters=}"
)
if categories is not None:
categories = as_general_categories(categories, "categories")
if exclude_categories is not None:
exclude_categories = as_general_categories(
exclude_categories, "exclude_categories"
)
if categories is not None and not categories and not include_characters:
raise InvalidArgument(
"When `categories` is an empty collection and there are "
"no characters specified in include_characters, nothing can "
"be generated by the characters() strategy."
)
both_cats = set(exclude_categories or ()).intersection(categories or ())
if both_cats:
# Note: we check that exactly one of `categories` or `exclude_categories` is
# passed above, but retain this older check for the deprecated arguments.
raise InvalidArgument(
f"Categories {sorted(both_cats)!r} are present in both "
f"{categories=} and {exclude_categories=}"
)
elif exclude_categories is not None:
categories = set(all_categories()) - set(exclude_categories)
del exclude_categories
if codec is not None:
try:
codec = codecs.lookup(codec).name
# Check this is not a str-to-str or bytes-to-bytes codec; see
# https://docs.python.org/3/library/codecs.html#binary-transforms
"".encode(codec)
except LookupError:
raise InvalidArgument(f"{codec=} is not valid on this system") from None
except Exception:
raise InvalidArgument(f"{codec=} is not a valid codec") from None
for char in include_characters:
try:
char.encode(encoding=codec, errors="strict")
except UnicodeEncodeError:
raise InvalidArgument(
f"Character {char!r} in {include_characters=} "
f"cannot be encoded with {codec=}"
) from None
# ascii and utf-8 are sufficient common that we have faster special handling
if codec == "ascii":
if (max_codepoint is None) or (max_codepoint > 127):
max_codepoint = 127
codec = None
elif codec == "utf-8":
if categories is None:
categories = all_categories()
categories = tuple(c for c in categories if c != "Cs")
return OneCharStringStrategy.from_characters_args(
categories=categories,
exclude_characters=exclude_characters,
min_codepoint=min_codepoint,
max_codepoint=max_codepoint,
include_characters=include_characters,
codec=codec,
)
# Hide the deprecated aliases from documentation and casual inspection
characters.__signature__ = (__sig := get_signature(characters)).replace( # type: ignore
parameters=[p for p in __sig.parameters.values() if "list" not in p.name]
)
@cacheable
@defines_strategy(force_reusable_values=True)
def text(
alphabet: Collection[str] | SearchStrategy[str] = characters(codec="utf-8"),
*,
min_size: int = 0,
max_size: int | None = None,
) -> SearchStrategy[str]:
"""Generates strings with characters drawn from ``alphabet``, which should
be a collection of length one strings or a strategy generating such strings.
The default alphabet strategy can generate the full unicode range but
excludes surrogate characters because they are invalid in the UTF-8
encoding. You can use :func:`~hypothesis.strategies.characters` without
arguments to find surrogate-related bugs such as :bpo:`34454`.
``min_size`` and ``max_size`` have the usual interpretations.
Note that Python measures string length by counting codepoints: U+00C5
``Å`` is a single character, while U+0041 U+030A ``Å`` is two - the ``A``,
and a combining ring above.
Examples from this strategy shrink towards shorter strings, and with the
characters in the text shrinking as per the alphabet strategy.
This strategy does not :func:`~python:unicodedata.normalize` examples,
so generated strings may be in any or none of the 'normal forms'.
"""
check_valid_sizes(min_size, max_size)
if isinstance(alphabet, SearchStrategy):
char_strategy = unwrap_strategies(alphabet)
if isinstance(char_strategy, SampledFromStrategy):
# Check this via the up-front validation logic below, and incidentally
# convert into a `characters()` strategy for standard text shrinking.
return text(char_strategy.elements, min_size=min_size, max_size=max_size)
elif not isinstance(char_strategy, OneCharStringStrategy):
char_strategy = char_strategy.map(_check_is_single_character)
else:
non_string = [c for c in alphabet if not isinstance(c, str)]
if non_string:
raise InvalidArgument(
"The following elements in alphabet are not unicode "
f"strings: {non_string!r}"
)
not_one_char = [c for c in alphabet if len(c) != 1]
if not_one_char:
raise InvalidArgument(
"The following elements in alphabet are not of length one, "
f"which leads to violation of size constraints: {not_one_char!r}"
)
if alphabet in ["ascii", "utf-8"]:
warnings.warn(
f"st.text({alphabet!r}): it seems like you are trying to use the "
f"codec {alphabet!r}. st.text({alphabet!r}) instead generates "
f"strings using the literal characters {list(alphabet)!r}. To specify "
f"the {alphabet} codec, use st.text(st.characters(codec={alphabet!r})). "
"If you intended to use character literals, you can silence this "
"warning by reordering the characters.",
HypothesisWarning,
# this stacklevel is of course incorrect, but breaking out of the
# levels of LazyStrategy and validation isn't worthwhile.
stacklevel=1,
)
char_strategy = (
characters(categories=(), include_characters=alphabet)
if alphabet
else nothing()
)
if (max_size == 0 or char_strategy.is_empty) and not min_size:
return just("")
# mypy is unhappy with ListStrategy(SearchStrategy[list[Ex]]) and then TextStrategy
# setting Ex = str. Mypy is correct to complain because we have an LSP violation
# here in the TextStrategy.do_draw override. Would need refactoring to resolve.
return TextStrategy(char_strategy, min_size=min_size, max_size=max_size) # type: ignore
@overload
def from_regex(
regex: bytes | Pattern[bytes],
*,
fullmatch: bool = False,
) -> SearchStrategy[bytes]: # pragma: no cover
...
@overload
def from_regex(
regex: str | Pattern[str],
*,
fullmatch: bool = False,
alphabet: str | SearchStrategy[str] = characters(codec="utf-8"),
) -> SearchStrategy[str]: # pragma: no cover
...
@cacheable
@defines_strategy()
def from_regex(
regex: AnyStr | Pattern[AnyStr],
*,
fullmatch: bool = False,
alphabet: str | SearchStrategy[str] | None = None,
) -> SearchStrategy[AnyStr]:
r"""Generates strings that contain a match for the given regex (i.e. ones
for which :func:`python:re.search` will return a non-None result).
``regex`` may be a pattern or :func:`compiled regex <python:re.compile>`.
Both byte-strings and unicode strings are supported, and will generate
examples of the same type.
You can use regex flags such as :obj:`python:re.IGNORECASE` or
:obj:`python:re.DOTALL` to control generation. Flags can be passed either
in compiled regex or inside the pattern with a ``(?iLmsux)`` group.
Some regular expressions are only partly supported - the underlying
strategy checks local matching and relies on filtering to resolve
context-dependent expressions. Using too many of these constructs may
cause health-check errors as too many examples are filtered out. This
mainly includes (positive or negative) lookahead and lookbehind groups.
If you want the generated string to match the whole regex you should use
boundary markers. So e.g. ``r"\A.\Z"`` will return a single character
string, while ``"."`` will return any string, and ``r"\A.$"`` will return
a single character optionally followed by a ``"\n"``.
Alternatively, passing ``fullmatch=True`` will ensure that the whole
string is a match, as if you had used the ``\A`` and ``\Z`` markers.
The ``alphabet=`` argument constrains the characters in the generated
string, as for :func:`text`, and is only supported for unicode strings.
Examples from this strategy shrink towards shorter strings and lower
character values, with exact behaviour that may depend on the pattern.
"""
check_type((str, bytes, re.Pattern), regex, "regex")
check_type(bool, fullmatch, "fullmatch")
pattern = regex.pattern if isinstance(regex, re.Pattern) else regex
if alphabet is not None:
check_type((str, SearchStrategy), alphabet, "alphabet")
if not isinstance(pattern, str):
raise InvalidArgument("alphabet= is not supported for bytestrings")
alphabet = OneCharStringStrategy.from_alphabet(alphabet)
elif isinstance(pattern, str):
alphabet = characters(codec="utf-8")
# TODO: We would like to move this to the top level, but pending some major
# refactoring it's hard to do without creating circular imports.
from hypothesis.strategies._internal.regex import regex_strategy
return regex_strategy(regex, fullmatch, alphabet=alphabet)
@cacheable
@defines_strategy(force_reusable_values=True)
def binary(
*,
min_size: int = 0,
max_size: int | None = None,
) -> SearchStrategy[bytes]:
"""Generates :class:`python:bytes`.
The generated :class:`python:bytes` will have a length of at least ``min_size``
and at most ``max_size``. If ``max_size`` is None there is no upper limit.
Examples from this strategy shrink towards smaller strings and lower byte
values.
"""
check_valid_sizes(min_size, max_size)
return BytesStrategy(min_size, max_size)
@cacheable
@defines_strategy()
def randoms(
*,
note_method_calls: bool = False,
use_true_random: bool = False,
) -> SearchStrategy[random.Random]:
"""Generates instances of ``random.Random``. The generated Random instances
are of a special HypothesisRandom subclass.
- If ``note_method_calls`` is set to ``True``, Hypothesis will print the
randomly drawn values in any falsifying test case. This can be helpful
for debugging the behaviour of randomized algorithms.
- If ``use_true_random`` is set to ``True`` then values will be drawn from
their usual distribution, otherwise they will actually be Hypothesis
generated values (and will be shrunk accordingly for any failing test
case). Setting ``use_true_random=False`` will tend to expose bugs that
would occur with very low probability when it is set to True, and this
flag should only be set to True when your code relies on the distribution
of values for correctness.
For managing global state, see the :func:`~hypothesis.strategies.random_module`
strategy and :func:`~hypothesis.register_random` function.
"""
check_type(bool, note_method_calls, "note_method_calls")
check_type(bool, use_true_random, "use_true_random")
from hypothesis.strategies._internal.random import RandomStrategy
return RandomStrategy(
use_true_random=use_true_random, note_method_calls=note_method_calls
)
| PrettyIter |
python | kamyu104__LeetCode-Solutions | Python/minimum-weighted-subgraph-with-the-required-paths.py | {
"start": 206,
"end": 1396
} | class ____(object):
def minimumWeight(self, n, edges, src1, src2, dest):
"""
:type n: int
:type edges: List[List[int]]
:type src1: int
:type src2: int
:type dest: int
:rtype: int
"""
def dijkstra(adj, start):
best = [float("inf")]*len(adj)
best[start] = 0
min_heap = [(0, start)]
while min_heap:
curr, u = heapq.heappop(min_heap)
if best[u] < curr:
continue
for v, w in adj[u]:
if best[v] <= curr+w:
continue
best[v] = curr+w
heapq.heappush(min_heap, (curr+w, v))
return best
adj1, adj2 = [[[] for _ in xrange(n)] for _ in xrange(2)]
for u, v, w in edges:
adj1[u].append((v, w))
adj2[v].append((u, w))
dist1 = dijkstra(adj1, src1)
dist2 = dijkstra(adj1, src2)
dist3 = dijkstra(adj2, dest)
result = min(dist1[i]+dist2[i]+dist3[i] for i in xrange(n))
return result if result != float("inf") else -1
| Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pydocstyle/all.py | {
"start": 61,
"end": 124
} | class ____:
class PublicNestedClass:
pass
| PublicClass |
python | davidhalter__parso | parso/python/pep8.py | {
"start": 1621,
"end": 3666
} | class ____(IndentationNode):
def __init__(self, config, leaf, parent, in_suite_introducer=False):
self.leaf = leaf
# Figure out here what the indentation is. For chained brackets
# we can basically use the previous indentation.
previous_leaf = leaf
n = parent
if n.type == IndentationTypes.IMPLICIT:
n = n.parent
while True:
if hasattr(n, 'leaf') and previous_leaf.line != n.leaf.line:
break
previous_leaf = previous_leaf.get_previous_leaf()
if not isinstance(n, BracketNode) or previous_leaf != n.leaf:
break
n = n.parent
parent_indentation = n.indentation
next_leaf = leaf.get_next_leaf()
if '\n' in next_leaf.prefix or '\r' in next_leaf.prefix:
# This implies code like:
# foobarbaz(
# a,
# b,
# )
self.bracket_indentation = parent_indentation \
+ config.closing_bracket_hanging_indentation
self.indentation = parent_indentation + config.indentation
self.type = IndentationTypes.HANGING_BRACKET
else:
# Implies code like:
# foobarbaz(
# a,
# b,
# )
expected_end_indent = leaf.end_pos[1]
if '\t' in config.indentation:
self.indentation = None
else:
self.indentation = ' ' * expected_end_indent
self.bracket_indentation = self.indentation
self.type = IndentationTypes.VERTICAL_BRACKET
if in_suite_introducer and parent.type == IndentationTypes.SUITE \
and self.indentation == parent_indentation + config.indentation:
self.indentation += config.indentation
# The closing bracket should have the same indentation.
self.bracket_indentation = self.indentation
self.parent = parent
| BracketNode |
python | ansible__ansible | lib/ansible/plugins/inventory/script.py | {
"start": 6242,
"end": 15227
} | class ____(BaseInventoryPlugin):
"""Host inventory parser for ansible using external inventory scripts."""
NAME = 'script'
def __init__(self) -> None:
super(InventoryModule, self).__init__()
self._hosts: set[str] = set()
def verify_file(self, path: str) -> bool:
return super(InventoryModule, self).verify_file(path) and os.access(path, os.X_OK)
def parse(self, inventory: InventoryData, loader: DataLoader, path: str, cache: bool = False) -> None:
super(InventoryModule, self).parse(inventory, loader, path)
self.set_options()
origin = Origin(description=f'<inventory script output from {path!r}>')
data, stderr, stderr_help_text = run_command(path, ['--list'], origin)
try:
profile_name = detect_profile_name(data)
decoder = get_decoder(profile_name)
except Exception as ex:
raise AnsibleError(
message="Unable to get JSON decoder for inventory script result.",
help_text=stderr_help_text,
# obj will be added by inventory manager
) from ex
try:
try:
processed = json.loads(data, cls=decoder)
except Exception as json_ex:
AnsibleJSONParserError.handle_exception(json_ex, origin)
except Exception as ex:
raise AnsibleError(
message="Inventory script result could not be parsed as JSON.",
help_text=stderr_help_text,
# obj will be added by inventory manager
) from ex
# if no other errors happened, and you want to force displaying stderr, do so now
if stderr and self.get_option('always_show_stderr'):
self.display.error(msg=stderr)
data_from_meta: dict | None = None
# A "_meta" subelement may contain a variable "hostvars" which contains a hash for each host
# if this "hostvars" exists at all then do not call --host for each # host.
# This is for efficiency and scripts should still return data
# if called with --host for backwards compat with 1.2 and earlier.
for (group, gdata) in processed.items():
if group == '_meta':
data_from_meta = gdata.get('hostvars')
if not isinstance(data_from_meta, dict):
raise TypeError(f"Value contains '_meta.hostvars' which is {native_type_name(data_from_meta)!r} instead of {native_type_name(dict)!r}.")
else:
self._parse_group(group, gdata, origin)
if data_from_meta is None:
display.deprecated(
msg="Inventory scripts should always provide 'meta.hostvars'. "
"Host variables will be collected by running the inventory script with the '--host' option for each host.",
version='2.23',
obj=origin,
)
for host in self._hosts:
if data_from_meta is None:
got = self.get_host_variables(path, host, origin)
else:
got = data_from_meta.get(host, {})
self._populate_host_vars([host], got)
def _parse_group(self, group: str, data: t.Any, origin: Origin) -> None:
"""Normalize and ingest host/var information for the named group."""
group = self.inventory.add_group(group)
if not isinstance(data, dict):
original_type = native_type_name(data)
data = {'hosts': data}
display.deprecated(
msg=f"Group {group!r} was converted to {native_type_name(dict)!r} from {original_type!r}.",
version='2.23',
obj=origin,
)
elif not any(k in data for k in ('hosts', 'vars', 'children')):
data = {'hosts': [group], 'vars': data}
display.deprecated(
msg=f"Treating malformed group {group!r} as the sole host of that group. Variables provided in this manner cannot be templated.",
version='2.23',
obj=origin,
)
if (data_hosts := data.get('hosts', ...)) is not ...:
if not isinstance(data_hosts, list):
raise TypeError(f"Value contains '{group}.hosts' which is {native_type_name(data_hosts)!r} instead of {native_type_name(list)!r}.")
for hostname in data_hosts:
self._hosts.add(hostname)
self.inventory.add_host(hostname, group)
if (data_vars := data.get('vars', ...)) is not ...:
if not isinstance(data_vars, dict):
raise TypeError(f"Value contains '{group}.vars' which is {native_type_name(data_vars)!r} instead of {native_type_name(dict)!r}.")
for k, v in data_vars.items():
self.inventory.set_variable(group, k, v)
if group != '_meta' and isinstance(data, dict) and 'children' in data:
for child_name in data['children']:
child_name = self.inventory.add_group(child_name)
self.inventory.add_child(group, child_name)
@staticmethod
def get_host_variables(path: str, host: str, origin: Origin) -> dict:
"""Runs <script> --host <hostname>, to determine additional host variables."""
origin = origin.replace(description=f'{origin.description} for host {host!r}')
data, stderr, stderr_help_text = run_command(path, ['--host', host], origin)
if not data.strip():
return {}
try:
try:
# Use standard legacy trust inversion here.
# Unlike the normal inventory output, everything here is considered a variable and thus supports trust (and trust inversion).
processed = json.loads(data, cls=_legacy.Decoder)
except Exception as json_ex:
AnsibleJSONParserError.handle_exception(json_ex, origin)
except Exception as ex:
raise AnsibleError(
message=f"Inventory script result for host {host!r} could not be parsed as JSON.",
help_text=stderr_help_text,
# obj will be added by inventory manager
) from ex
return processed
def detect_profile_name(value: str) -> str:
"""
Detect (optional) JSON profile name from an inventory JSON document.
Defaults to `inventory_legacy`.
"""
try:
data = json.loads(value)
except Exception as ex:
raise ValueError('Value could not be parsed as JSON.') from ex
if not isinstance(data, dict):
raise TypeError(f'Value is {native_type_name(data)!r} instead of {native_type_name(dict)!r}.')
if (meta := data.get('_meta', ...)) is ...:
return _inventory_legacy.Decoder.profile_name
if not isinstance(meta, dict):
raise TypeError(f"Value contains '_meta' which is {native_type_name(meta)!r} instead of {native_type_name(dict)!r}.")
if (profile := meta.get('profile', ...)) is ...:
return _inventory_legacy.Decoder.profile_name
if not isinstance(profile, str):
raise TypeError(f"Value contains '_meta.profile' which is {native_type_name(profile)!r} instead of {native_type_name(str)!r}.")
if not profile.startswith('inventory_'):
raise ValueError(f"Non-inventory profile {profile!r} is not allowed.")
return profile
def run_command(path: str, options: list[str], origin: Origin) -> tuple[str, str, str]:
"""Run an inventory script, normalize and validate output."""
cmd = [path] + options
try:
sp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError as ex:
raise AnsibleError(
message=f"Failed to execute inventory script command {shlex.join(cmd)!r}.",
# obj will be added by inventory manager
) from ex
stdout_bytes, stderr_bytes = sp.communicate()
stderr = stderr_bytes.decode(errors='surrogateescape')
if stderr and not stderr.endswith('\n'):
stderr += '\n'
# DTFIX-FUTURE: another use case for the "not quite help text, definitely not message" diagnostic output on errors
stderr_help_text = f'Standard error from inventory script:\n{stderr}' if stderr.strip() else None
if sp.returncode != 0:
raise AnsibleError(
message=f"Inventory script returned non-zero exit code {sp.returncode}.",
help_text=stderr_help_text,
# obj will be added by inventory manager
)
try:
data = stdout_bytes.decode()
except Exception as ex:
raise AnsibleError(
"Inventory script result contained characters that cannot be interpreted as UTF-8.",
help_text=stderr_help_text,
# obj will be added by inventory manager
) from ex
else:
data = TrustedAsTemplate().tag(origin.tag(data))
return data, stderr, stderr_help_text
| InventoryModule |
python | conda__conda | conda/gateways/repodata/jlap/interface.py | {
"start": 4006,
"end": 4391
} | class ____(RepodataState):
skip_formats: set[str]
def __init__(self, *args, skip_formats=set(), **kwargs):
super().__init__(*args, **kwargs)
self.skip_formats = set(skip_formats)
def should_check_format(self, format):
if format in self.skip_formats:
return False
return super().should_check_format(format)
| RepodataStateSkipFormat |
python | ray-project__ray | release/train_tests/benchmark/image_classification/jpeg/factory.py | {
"start": 4481,
"end": 7768
} | class ____(
ImageClassificationTorchDataLoaderFactory, S3JpegReader
):
"""Factory for creating PyTorch DataLoaders for JPEG image classification.
Features:
- S3-based JPEG file reading with round-robin worker distribution
- Device transfer and error handling for data batches
- Row limits per worker for controlled processing
- Dataset caching for efficiency
"""
def __init__(self, benchmark_config: BenchmarkConfig, data_dirs: Dict[str, str]):
super().__init__(benchmark_config)
S3JpegReader.__init__(self) # Initialize S3JpegReader to set up _s3_client
self._data_dirs = data_dirs
self._cached_datasets = None
def get_iterable_datasets(self) -> Dict[str, IterableDataset]:
"""Get train and validation datasets with worker-specific configurations.
Returns:
Dictionary containing:
- "train": Training dataset with random transforms
- "val": Validation dataset without transforms
"""
if self._cached_datasets is not None:
return self._cached_datasets
if self._data_dirs[DatasetKey.TRAIN].startswith("s3://"):
return self._get_iterable_datasets_s3()
else:
return self._get_iterable_datasets_local()
def _get_iterable_datasets_local(self) -> Dict[str, IterableDataset]:
"""Get train and validation datasets from local filesystem."""
train_dir = self._data_dirs[DatasetKey.TRAIN]
val_dir = self._data_dirs[DatasetKey.VALID]
train_dataset = torchvision.datasets.ImageFolder(
root=train_dir,
transform=get_transform(to_torch_tensor=True, random_transforms=True),
)
val_dataset = torchvision.datasets.ImageFolder(
root=val_dir,
transform=get_transform(to_torch_tensor=True, random_transforms=False),
)
return {
DatasetKey.TRAIN: train_dataset,
DatasetKey.VALID: val_dataset,
}
def _get_iterable_datasets_s3(self) -> Dict[str, IterableDataset]:
"""Get train and validation datasets from S3."""
train_dir = self._data_dirs[DatasetKey.TRAIN]
# Get row limits for workers and total processing
(
limit_training_rows_per_worker,
limit_validation_rows_per_worker,
) = self._get_worker_row_limits()
# Get file URLs for training and validation
train_file_urls = val_file_urls = self._get_file_urls(train_dir)
train_ds = S3JpegImageIterableDataset(
file_urls=train_file_urls,
random_transforms=True,
limit_rows_per_worker=limit_training_rows_per_worker,
)
# TODO: IMAGENET_JPEG_SPLIT_S3_DIRS["val"] does not have the label
# partitioning like "train" does. So we use "train" for validation.
val_ds = S3JpegImageIterableDataset(
file_urls=val_file_urls,
random_transforms=False,
limit_rows_per_worker=limit_validation_rows_per_worker,
)
self._cached_datasets = {
DatasetKey.TRAIN: train_ds,
DatasetKey.VALID: val_ds,
}
return self._cached_datasets
| ImageClassificationJpegTorchDataLoaderFactory |
python | bokeh__bokeh | src/bokeh/io/notebook.py | {
"start": 4987,
"end": 5112
} | class ____(Protocol):
def __call__(self, obj: Model, state: State, notebook_handle: CommsHandle) -> CommsHandle: ...
| ShowDoc |
python | giampaolo__psutil | tests/test_bsd.py | {
"start": 1790,
"end": 4816
} | class ____(PsutilTestCase):
"""Generic tests common to all BSD variants."""
@classmethod
def setUpClass(cls):
cls.pid = spawn_subproc().pid
@classmethod
def tearDownClass(cls):
terminate(cls.pid)
@pytest.mark.skipif(NETBSD, reason="-o lstart doesn't work on NETBSD")
def test_process_create_time(self):
output = sh(f"ps -o lstart -p {self.pid}")
start_ps = output.replace('STARTED', '').strip()
start_psutil = psutil.Process(self.pid).create_time()
start_psutil = time.strftime(
"%a %b %e %H:%M:%S %Y", time.localtime(start_psutil)
)
assert start_ps == start_psutil
def test_disks(self):
# test psutil.disk_usage() and psutil.disk_partitions()
# against "df -a"
def df(path):
out = sh(f'df -k "{path}"').strip()
lines = out.split('\n')
lines.pop(0)
line = lines.pop(0)
dev, total, used, free = line.split()[:4]
if dev == 'none':
dev = ''
total = int(total) * 1024
used = int(used) * 1024
free = int(free) * 1024
return dev, total, used, free
for part in psutil.disk_partitions(all=False):
usage = psutil.disk_usage(part.mountpoint)
dev, total, used, free = df(part.mountpoint)
assert part.device == dev
assert usage.total == total
# 10 MB tolerance
if abs(usage.free - free) > 10 * 1024 * 1024:
return pytest.fail(f"psutil={usage.free}, df={free}")
if abs(usage.used - used) > 10 * 1024 * 1024:
return pytest.fail(f"psutil={usage.used}, df={used}")
@pytest.mark.skipif(
not shutil.which("sysctl"), reason="sysctl cmd not available"
)
def test_cpu_count_logical(self):
syst = sysctl("hw.ncpu")
assert psutil.cpu_count(logical=True) == syst
@pytest.mark.skipif(
not shutil.which("sysctl"), reason="sysctl cmd not available"
)
@pytest.mark.skipif(
NETBSD, reason="skipped on NETBSD" # we check /proc/meminfo
)
def test_virtual_memory_total(self):
num = sysctl('hw.physmem')
assert num == psutil.virtual_memory().total
@pytest.mark.skipif(
not shutil.which("ifconfig"), reason="ifconfig cmd not available"
)
def test_net_if_stats(self):
for name, stats in psutil.net_if_stats().items():
try:
out = sh(f"ifconfig {name}")
except RuntimeError:
pass
else:
assert stats.isup == ('RUNNING' in out)
if "mtu" in out:
assert stats.mtu == int(re.findall(r'mtu (\d+)', out)[0])
# =====================================================================
# --- FreeBSD
# =====================================================================
@pytest.mark.skipif(not FREEBSD, reason="FREEBSD only")
| BSDTestCase |
python | walkccc__LeetCode | solutions/2948. Make Lexicographically Smallest Array by Swapping Elements/2948.py | {
"start": 0,
"end": 1003
} | class ____:
def lexicographicallySmallestArray(
self,
nums: list[int],
limit: int,
) -> list[int]:
ans = [0] * len(nums)
numAndIndexes = sorted([(num, i) for i, num in enumerate(nums)])
# [[(num, index)]], where the difference between in each pair in each
# `[(num, index)]` group <= `limit`
numAndIndexesGroups: list[list[tuple[int, int]]] = []
for numAndIndex in numAndIndexes:
if (not numAndIndexesGroups or
numAndIndex[0] - numAndIndexesGroups[-1][-1][0] > limit):
# Start a new group.
numAndIndexesGroups.append([numAndIndex])
else:
# Append to the existing group.
numAndIndexesGroups[-1].append(numAndIndex)
for numAndIndexesGroup in numAndIndexesGroups:
sortedNums = [num for num, _ in numAndIndexesGroup]
sortedIndices = sorted([index for _, index in numAndIndexesGroup])
for num, index in zip(sortedNums, sortedIndices):
ans[index] = num
return ans
| Solution |
python | networkx__networkx | networkx/linalg/tests/test_spectrum.py | {
"start": 103,
"end": 2769
} | class ____:
@classmethod
def setup_class(cls):
deg = [3, 2, 2, 1, 0]
cls.G = nx.havel_hakimi_graph(deg)
cls.P = nx.path_graph(3)
cls.WG = nx.Graph(
(u, v, {"weight": 0.5, "other": 0.3}) for (u, v) in cls.G.edges()
)
cls.WG.add_node(4)
cls.DG = nx.DiGraph()
nx.add_path(cls.DG, [0, 1, 2])
def test_laplacian_spectrum(self):
"Laplacian eigenvalues"
evals = np.array([0, 0, 1, 3, 4])
e = sorted(nx.laplacian_spectrum(self.G))
np.testing.assert_almost_equal(e, evals)
e = sorted(nx.laplacian_spectrum(self.WG, weight=None))
np.testing.assert_almost_equal(e, evals)
e = sorted(nx.laplacian_spectrum(self.WG))
np.testing.assert_almost_equal(e, 0.5 * evals)
e = sorted(nx.laplacian_spectrum(self.WG, weight="other"))
np.testing.assert_almost_equal(e, 0.3 * evals)
def test_normalized_laplacian_spectrum(self):
"Normalized Laplacian eigenvalues"
evals = np.array([0, 0, 0.7712864461218, 1.5, 1.7287135538781])
e = sorted(nx.normalized_laplacian_spectrum(self.G))
np.testing.assert_almost_equal(e, evals)
e = sorted(nx.normalized_laplacian_spectrum(self.WG, weight=None))
np.testing.assert_almost_equal(e, evals)
e = sorted(nx.normalized_laplacian_spectrum(self.WG))
np.testing.assert_almost_equal(e, evals)
e = sorted(nx.normalized_laplacian_spectrum(self.WG, weight="other"))
np.testing.assert_almost_equal(e, evals)
def test_adjacency_spectrum(self):
"Adjacency eigenvalues"
evals = np.array([-np.sqrt(2), 0, np.sqrt(2)])
e = sorted(nx.adjacency_spectrum(self.P))
np.testing.assert_almost_equal(e, evals)
def test_modularity_spectrum(self):
"Modularity eigenvalues"
evals = np.array([-1.5, 0.0, 0.0])
e = sorted(nx.modularity_spectrum(self.P))
np.testing.assert_almost_equal(e, evals)
# Directed modularity eigenvalues
evals = np.array([-0.5, 0.0, 0.0])
e = sorted(nx.modularity_spectrum(self.DG))
np.testing.assert_almost_equal(e, evals)
def test_bethe_hessian_spectrum(self):
"Bethe Hessian eigenvalues"
evals = np.array([0.5 * (9 - np.sqrt(33)), 4, 0.5 * (9 + np.sqrt(33))])
e = sorted(nx.bethe_hessian_spectrum(self.P, r=2))
np.testing.assert_almost_equal(e, evals)
# Collapses back to Laplacian:
e1 = sorted(nx.bethe_hessian_spectrum(self.P, r=1))
e2 = sorted(nx.laplacian_spectrum(self.P))
np.testing.assert_almost_equal(e1, e2)
| TestSpectrum |
python | walkccc__LeetCode | solutions/2655. Find Maximal Uncovered Ranges/2655.py | {
"start": 0,
"end": 334
} | class ____:
def findMaximalUncoveredRanges(self, n: int, ranges: list[list[int]]) -> list[list[int]]:
ans = []
start = 0
for l, r in sorted(ranges):
if start < l:
ans.append([start, l - 1])
if start <= r:
start = r + 1
if start < n:
ans.append([start, n - 1])
return ans
| Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingFalsy1.py | {
"start": 4083,
"end": 4829
} | class ____(TypedDict):
pass
def func19(v1: TD1 | None, v2: TD2 | None, v3: TD3 | None):
if v1:
reveal_type(v1, expected_text="TD1")
else:
reveal_type(v1, expected_text="None")
if v2:
reveal_type(v2, expected_text="TD2")
else:
reveal_type(v2, expected_text="TD2 | None")
if v2 is not None:
if v2:
reveal_type(v2, expected_text="TD2")
else:
reveal_type(v2, expected_text="TD2")
v2["d1"] = 1
if v2:
reveal_type(v2, expected_text="TD2")
else:
reveal_type(v2, expected_text="Never")
if v3:
reveal_type(v3, expected_text="TD3")
else:
reveal_type(v3, expected_text="TD3 | None")
| TD3 |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 361207,
"end": 366140
} | class ____(Request):
"""
Reset a task to its initial state, along with any information stored for it (statistics, frame updates etc.).
:param force: If not true, call fails if the task status is 'completed'
:type force: bool
:param clear_all: Clear script and execution sections completely
:type clear_all: bool
:param task: Task ID
:type task: str
:param status_reason: Reason for status change
:type status_reason: str
:param status_message: Extra information regarding status change
:type status_message: str
:param return_file_urls: If set to 'true' then return the urls of the files
that were uploaded by this task. Default value is 'false'
:type return_file_urls: bool
"""
_service = "tasks"
_action = "reset"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
"clear_all": {
"default": False,
"description": "Clear script and execution sections completely",
"type": ["boolean", "null"],
},
"force": {
"default": False,
"description": "If not true, call fails if the task status is 'completed'",
"type": ["boolean", "null"],
},
"return_file_urls": {
"description": "If set to 'true' then return the urls of the files that were uploaded by this task. Default value is 'false'",
"type": "boolean",
},
"status_message": {
"description": "Extra information regarding status change",
"type": "string",
},
"status_reason": {
"description": "Reason for status change",
"type": "string",
},
"task": {"description": "Task ID", "type": "string"},
},
"required": ["task"],
"type": "object",
}
def __init__(
self,
task: str,
force: Optional[bool] = False,
clear_all: Optional[bool] = False,
status_reason: Optional[str] = None,
status_message: Optional[str] = None,
return_file_urls: Optional[bool] = None,
**kwargs: Any
) -> None:
super(ResetRequest, self).__init__(**kwargs)
self.force = force
self.clear_all = clear_all
self.task = task
self.status_reason = status_reason
self.status_message = status_message
self.return_file_urls = return_file_urls
@schema_property("force")
def force(self) -> Optional[bool]:
return self._property_force
@force.setter
def force(self, value: Optional[bool]) -> None:
if value is None:
self._property_force = None
return
self.assert_isinstance(value, "force", (bool,))
self._property_force = value
@schema_property("clear_all")
def clear_all(self) -> Optional[bool]:
return self._property_clear_all
@clear_all.setter
def clear_all(self, value: Optional[bool]) -> None:
if value is None:
self._property_clear_all = None
return
self.assert_isinstance(value, "clear_all", (bool,))
self._property_clear_all = value
@schema_property("task")
def task(self) -> str:
return self._property_task
@task.setter
def task(self, value: str) -> None:
if value is None:
self._property_task = None
return
self.assert_isinstance(value, "task", six.string_types)
self._property_task = value
@schema_property("status_reason")
def status_reason(self) -> Optional[str]:
return self._property_status_reason
@status_reason.setter
def status_reason(self, value: Optional[str]) -> None:
if value is None:
self._property_status_reason = None
return
self.assert_isinstance(value, "status_reason", six.string_types)
self._property_status_reason = value
@schema_property("status_message")
def status_message(self) -> Optional[str]:
return self._property_status_message
@status_message.setter
def status_message(self, value: Optional[str]) -> None:
if value is None:
self._property_status_message = None
return
self.assert_isinstance(value, "status_message", six.string_types)
self._property_status_message = value
@schema_property("return_file_urls")
def return_file_urls(self) -> Optional[bool]:
return self._property_return_file_urls
@return_file_urls.setter
def return_file_urls(self, value: Optional[bool]) -> None:
if value is None:
self._property_return_file_urls = None
return
self.assert_isinstance(value, "return_file_urls", (bool,))
self._property_return_file_urls = value
| ResetRequest |
python | astropy__astropy | astropy/utils/data.py | {
"start": 4089,
"end": 41349
} | class ____(AstropyWarning):
"""
This warning indicates the standard cache directory is not accessible, with
the first argument providing the warning message. If args[1] is present, it
is a filename indicating the path to a temporary file that was created to
store a remote data download in the absence of the cache.
"""
def is_url(string):
"""
Test whether a string is a valid URL for :func:`download_file`.
Parameters
----------
string : str
The string to test.
Returns
-------
status : bool
String is URL or not.
"""
url = urllib.parse.urlparse(string)
# we can't just check that url.scheme is not an empty string, because
# file paths in windows would return a non-empty scheme (e.g. e:\\
# returns 'e').
return url.scheme.lower() in ["http", "https", "ftp", "sftp", "ssh", "file"]
# Backward compatibility because some downstream packages allegedly uses it.
_is_url = is_url
def _requires_fsspec(url):
"""Does the `url` require the optional ``fsspec`` dependency to open?"""
return isinstance(url, str) and url.startswith(("s3://", "gs://"))
def _is_inside(path, parent_path):
# We have to try realpath too to avoid issues with symlinks, but we leave
# abspath because some systems like debian have the absolute path (with no
# symlinks followed) match, but the real directories in different
# locations, so need to try both cases.
return os.path.abspath(path).startswith(
os.path.abspath(parent_path)
) or os.path.realpath(path).startswith(os.path.realpath(parent_path))
@contextlib.contextmanager
def get_readable_fileobj(
name_or_obj,
encoding=None,
cache=False,
show_progress=True,
remote_timeout=None,
sources=None,
http_headers=None,
*,
use_fsspec=None,
fsspec_kwargs=None,
close_files=True,
):
"""Yield a readable, seekable file-like object from a file or URL.
This supports passing filenames, URLs, and readable file-like objects,
any of which can be compressed in gzip, bzip2, lzma (xz) or lzw (Z) if the
appropriate compression libraries are provided by the Python installation.
Notes
-----
This function is a context manager, and should be used for example
as::
with get_readable_fileobj('file.dat') as f:
contents = f.read()
If a URL is provided and the cache is in use, the provided URL will be the
name used in the cache. The contents may already be stored in the cache
under this URL provided, they may be downloaded from this URL, or they may
be downloaded from one of the locations listed in ``sources``. See
`~download_file` for details.
Parameters
----------
name_or_obj : str or file-like
The filename of the file to access (if given as a string), or
the file-like object to access.
If a file-like object, it must be opened in binary mode.
encoding : str, optional
When `None` (default), returns a file-like object with a
``read`` method that returns `str` (``unicode``) objects, using
`locale.getpreferredencoding` as an encoding. This matches
the default behavior of the built-in `open` when no ``mode``
argument is provided.
When ``'binary'``, returns a file-like object where its ``read``
method returns `bytes` objects.
When another string, it is the name of an encoding, and the
file-like object's ``read`` method will return `str` (``unicode``)
objects, decoded from binary using the given encoding.
cache : bool or "update", optional
Whether to cache the contents of remote URLs. If "update",
check the remote URL for a new version but store the result
in the cache.
show_progress : bool, optional
Whether to display a progress bar if the file is downloaded
from a remote server. Default is `True`.
remote_timeout : float
Timeout for remote requests in seconds (default is the configurable
`astropy.utils.data.Conf.remote_timeout`).
sources : list of str, optional
If provided, a list of URLs to try to obtain the file from. The
result will be stored under the original URL. The original URL
will *not* be tried unless it is in this list; this is to prevent
long waits for a primary server that is known to be inaccessible
at the moment.
http_headers : dict or None
HTTP request headers to pass into ``urlopen`` if needed. (These headers
are ignored if the protocol for the ``name_or_obj``/``sources`` entry
is not a remote HTTP URL.) In the default case (None), the headers are
``User-Agent: some_value`` and ``Accept: */*``, where ``some_value``
is set by ``astropy.utils.data.conf.default_http_user_agent``.
use_fsspec : bool, optional
Use `fsspec.open` to open the file? Defaults to `False` unless
``name_or_obj`` starts with the Amazon S3 storage prefix ``s3://``
or the Google Cloud Storage prefix ``gs://``. Can also be used for paths
with other prefixes (e.g. ``http://``) but in this case you must
explicitly pass ``use_fsspec=True``.
Use of this feature requires the optional ``fsspec`` package.
A ``ModuleNotFoundError`` will be raised if the dependency is missing.
.. versionadded:: 5.2
fsspec_kwargs : dict, optional
Keyword arguments passed on to `fsspec.open`. This can be used to
configure cloud storage credentials and caching behavior.
For example, pass ``fsspec_kwargs={"anon": True}`` to enable
anonymous access to Amazon S3 open data buckets.
See ``fsspec``'s documentation for available parameters.
.. versionadded:: 5.2
close_files : bool, optional
Close the file object when exiting the context manager.
Default is `True`.
.. versionadded:: 5.2
Returns
-------
file : :term:`file-like (readable)`
"""
# close_fds is a list of file handles created by this function
# that need to be closed. We don't want to always just close the
# returned file handle, because it may simply be the file handle
# passed in. In that case it is not the responsibility of this
# function to close it: doing so could result in a "double close"
# and an "invalid file descriptor" exception.
close_fds = []
delete_fds = []
if remote_timeout is None:
# use configfile default
remote_timeout = conf.remote_timeout
# Have `use_fsspec` default to ``True`` if the user passed an Amazon S3
# or Google Cloud Storage URI.
if use_fsspec is None and _requires_fsspec(name_or_obj):
use_fsspec = True
if use_fsspec:
if not isinstance(name_or_obj, str):
raise TypeError("`name_or_obj` must be a string when `use_fsspec=True`")
if fsspec_kwargs is None:
fsspec_kwargs = {}
# name_or_obj could be an os.PathLike object
if isinstance(name_or_obj, os.PathLike):
name_or_obj = os.fspath(name_or_obj)
# Get a file object to the content
if isinstance(name_or_obj, str):
# Use fsspec to open certain cloud-hosted files (e.g., AWS S3, Google Cloud Storage)
if use_fsspec:
if not HAS_FSSPEC:
raise ModuleNotFoundError("please install `fsspec` to open this file")
import fsspec # local import because it is a niche dependency
openfileobj = fsspec.open(name_or_obj, **fsspec_kwargs)
close_fds.append(openfileobj)
fileobj = openfileobj.open()
close_fds.append(fileobj)
else:
is_url = _is_url(name_or_obj)
if is_url:
name_or_obj = download_file(
name_or_obj,
cache=cache,
show_progress=show_progress,
timeout=remote_timeout,
sources=sources,
http_headers=http_headers,
)
fileobj = io.FileIO(name_or_obj, "r")
if is_url and not cache:
delete_fds.append(fileobj)
close_fds.append(fileobj)
else:
fileobj = name_or_obj
# Check if the file object supports random access, and if not,
# then wrap it in a BytesIO buffer. It would be nicer to use a
# BufferedReader to avoid reading loading the whole file first,
# but that might not be compatible with all possible I/O classes.
if not hasattr(fileobj, "seek"):
try:
# py.path.LocalPath objects have .read() method but it uses
# text mode, which won't work. .read_binary() does, and
# surely other ducks would return binary contents when
# called like this.
# py.path.LocalPath is what comes from the legacy tmpdir fixture
# in pytest.
fileobj = io.BytesIO(fileobj.read_binary())
except AttributeError:
fileobj = io.BytesIO(fileobj.read())
# Now read enough bytes to look at signature
signature = fileobj.read(6)
fileobj.seek(0)
if signature[:3] == b"\x1f\x8b\x08": # gzip
import struct
try:
import gzip
fileobj_new = gzip.GzipFile(fileobj=fileobj, mode="rb")
fileobj_new.read(1) # need to check that the file is really gzip
except (OSError, EOFError, struct.error): # invalid gzip file
fileobj.seek(0)
fileobj_new.close()
else:
fileobj_new.seek(0)
fileobj = fileobj_new
elif signature[:3] == b"BZh": # bzip2
if not HAS_BZ2:
for fd in close_fds:
fd.close()
raise ModuleNotFoundError(
"This Python installation does not provide the bz2 module."
)
import bz2
try:
# bz2.BZ2File does not support file objects, only filenames, so we
# need to write the data to a temporary file
with NamedTemporaryFile("wb", delete=False) as tmp:
tmp.write(fileobj.read())
tmp.close()
fileobj_new = bz2.BZ2File(tmp.name, mode="rb")
fileobj_new.read(1) # need to check that the file is really bzip2
except OSError: # invalid bzip2 file
fileobj.seek(0)
fileobj_new.close()
# raise
else:
fileobj_new.seek(0)
close_fds.append(fileobj_new)
fileobj = fileobj_new
elif signature[:6] == b"\xfd7zXZ\x00": # xz
if not HAS_LZMA:
for fd in close_fds:
fd.close()
raise ModuleNotFoundError(
"This Python installation does not provide the lzma module."
)
import lzma
try:
fileobj_new = lzma.LZMAFile(fileobj, mode="rb")
fileobj_new.read(1) # need to check that the file is really xz
except lzma.LZMAError: # invalid xz file
fileobj.seek(0)
fileobj_new.close()
# should we propagate this to the caller to signal bad content?
# raise ValueError(e)
else:
fileobj_new.seek(0)
fileobj = fileobj_new
elif signature[:2] == b"\x1f\x9d": # LZW
if not HAS_UNCOMPRESSPY:
for fd in close_fds:
fd.close()
raise ModuleNotFoundError(
"The optional package uncompresspy is necessary for reading LZW"
" compressed files (.Z extension)."
)
import uncompresspy
try:
fileobj_new = uncompresspy.LZWFile(fileobj)
fileobj_new.read(1)
except ValueError:
fileobj.seek(0)
fileobj_new.close()
else:
fileobj_new.seek(0)
close_fds.append(fileobj)
fileobj = fileobj_new
# By this point, we have a file, io.FileIO, gzip.GzipFile, bz2.BZ2File,
# lzma.LZMAFile or uncompresspy.LZWFile instance opened in binary mode (that
# is, read returns bytes). Now we need to, if requested, wrap it in a
# io.TextIOWrapper so read will return unicode based on the
# encoding parameter.
needs_textio_wrapper = encoding != "binary"
if needs_textio_wrapper:
# A bz2.BZ2File can not be wrapped by a TextIOWrapper,
# so we decompress it to a temporary file and then
# return a handle to that.
if HAS_BZ2:
import bz2
if isinstance(fileobj, bz2.BZ2File):
tmp = NamedTemporaryFile("wb", delete=False)
data = fileobj.read()
tmp.write(data)
tmp.close()
delete_fds.append(tmp)
fileobj = io.FileIO(tmp.name, "r")
close_fds.append(fileobj)
fileobj = _NonClosingBufferedReader(fileobj)
fileobj = _NonClosingTextIOWrapper(fileobj, encoding=encoding)
# Ensure that file is at the start - io.FileIO will for
# example not always be at the start:
# >>> import io
# >>> f = open('test.fits', 'rb')
# >>> f.read(4)
# 'SIMP'
# >>> f.seek(0)
# >>> fileobj = io.FileIO(f.fileno())
# >>> fileobj.tell()
# 4096L
fileobj.seek(0)
try:
yield fileobj
finally:
if close_files:
for fd in close_fds:
fd.close()
for fd in delete_fds:
os.remove(fd.name)
def get_file_contents(*args, **kwargs):
"""
Retrieves the contents of a filename or file-like object.
See the `get_readable_fileobj` docstring for details on parameters.
Returns
-------
object
The content of the file (as requested by ``encoding``).
"""
with get_readable_fileobj(*args, **kwargs) as f:
return f.read()
@contextlib.contextmanager
def get_pkg_data_fileobj(data_name, package=None, encoding=None, cache=True):
"""
Retrieves a data file from the standard locations for the package and
provides the file as a file-like object that reads bytes.
Parameters
----------
data_name : str
Name/location of the desired data file. One of the following:
* The name of a data file included in the source
distribution. The path is relative to the module
calling this function. For example, if calling from
``astropy.pkname``, use ``'data/file.dat'`` to get the
file in ``astropy/pkgname/data/file.dat``. Double-dots
can be used to go up a level. In the same example, use
``'../data/file.dat'`` to get ``astropy/data/file.dat``.
* If a matching local file does not exist, the Astropy
data server will be queried for the file.
* A hash like that produced by `compute_hash` can be
requested, prefixed by 'hash/'
e.g. 'hash/34c33b3eb0d56eb9462003af249eff28'. The hash
will first be searched for locally, and if not found,
the Astropy data server will be queried.
package : str, optional
If specified, look for a file relative to the given package, rather
than the default of looking relative to the calling module's package.
encoding : str, optional
When `None` (default), returns a file-like object with a
``read`` method returns `str` (``unicode``) objects, using
`locale.getpreferredencoding` as an encoding. This matches
the default behavior of the built-in `open` when no ``mode``
argument is provided.
When ``'binary'``, returns a file-like object where its ``read``
method returns `bytes` objects.
When another string, it is the name of an encoding, and the
file-like object's ``read`` method will return `str` (``unicode``)
objects, decoded from binary using the given encoding.
cache : bool
If True, the file will be downloaded and saved locally or the
already-cached local copy will be accessed. If False, the
file-like object will directly access the resource (e.g. if a
remote URL is accessed, an object like that from
`urllib.request.urlopen` is returned).
Returns
-------
fileobj : file-like
An object with the contents of the data file available via
``read`` function. Can be used as part of a ``with`` statement,
automatically closing itself after the ``with`` block.
Raises
------
urllib.error.URLError
If a remote file cannot be found.
OSError
If problems occur writing or reading a local file.
Examples
--------
This will retrieve a data file and its contents for the `astropy.wcs`
tests::
>>> from astropy.utils.data import get_pkg_data_fileobj
>>> with get_pkg_data_fileobj('data/3d_cd.hdr',
... package='astropy.wcs.tests') as fobj:
... fcontents = fobj.read()
...
This next example would download a data file from the astropy data server
because the ``allsky/allsky_rosat.fits`` file is not present in the
source distribution. It will also save the file locally so the
next time it is accessed it won't need to be downloaded.::
>>> from astropy.utils.data import get_pkg_data_fileobj
>>> with get_pkg_data_fileobj('allsky/allsky_rosat.fits',
... encoding='binary') as fobj: # doctest: +REMOTE_DATA +IGNORE_OUTPUT
... fcontents = fobj.read()
...
Downloading http://data.astropy.org/allsky/allsky_rosat.fits [Done]
This does the same thing but does *not* cache it locally::
>>> with get_pkg_data_fileobj('allsky/allsky_rosat.fits',
... encoding='binary', cache=False) as fobj: # doctest: +REMOTE_DATA +IGNORE_OUTPUT
... fcontents = fobj.read()
...
Downloading http://data.astropy.org/allsky/allsky_rosat.fits [Done]
See Also
--------
get_pkg_data_contents : returns the contents of a file or url as a bytes object
get_pkg_data_filename : returns a local name for a file containing the data
"""
datafn = get_pkg_data_path(data_name, package=package)
if os.path.isdir(datafn):
raise OSError(
"Tried to access a data file that's actually a package data directory"
)
elif os.path.isfile(datafn): # local file
with get_readable_fileobj(datafn, encoding=encoding) as fileobj:
yield fileobj
else: # remote file
with get_readable_fileobj(
conf.dataurl + data_name,
encoding=encoding,
cache=cache,
sources=[conf.dataurl + data_name, conf.dataurl_mirror + data_name],
) as fileobj:
# We read a byte to trigger any URLErrors
fileobj.read(1)
fileobj.seek(0)
yield fileobj
def get_pkg_data_filename(
data_name, package=None, show_progress=True, remote_timeout=None
):
"""
Retrieves a data file from the standard locations for the package and
provides a local filename for the data.
This function is similar to `get_pkg_data_fileobj` but returns the
file *name* instead of a readable file-like object. This means
that this function must always cache remote files locally, unlike
`get_pkg_data_fileobj`.
Parameters
----------
data_name : str
Name/location of the desired data file. One of the following:
* The name of a data file included in the source
distribution. The path is relative to the module
calling this function. For example, if calling from
``astropy.pkname``, use ``'data/file.dat'`` to get the
file in ``astropy/pkgname/data/file.dat``. Double-dots
can be used to go up a level. In the same example, use
``'../data/file.dat'`` to get ``astropy/data/file.dat``.
* If a matching local file does not exist, the Astropy
data server will be queried for the file.
* A hash like that produced by `compute_hash` can be
requested, prefixed by 'hash/'
e.g. 'hash/34c33b3eb0d56eb9462003af249eff28'. The hash
will first be searched for locally, and if not found,
the Astropy data server will be queried.
package : str, optional
If specified, look for a file relative to the given package, rather
than the default of looking relative to the calling module's package.
show_progress : bool, optional
Whether to display a progress bar if the file is downloaded
from a remote server. Default is `True`.
remote_timeout : float
Timeout for the requests in seconds (default is the
configurable `astropy.utils.data.Conf.remote_timeout`).
Raises
------
urllib.error.URLError
If a remote file cannot be found.
OSError
If problems occur writing or reading a local file.
Returns
-------
filename : str
A file path on the local file system corresponding to the data
requested in ``data_name``.
Examples
--------
This will retrieve the contents of the data file for the `astropy.wcs`
tests::
>>> from astropy.utils.data import get_pkg_data_filename
>>> fn = get_pkg_data_filename('data/3d_cd.hdr',
... package='astropy.wcs.tests')
>>> with open(fn) as f:
... fcontents = f.read()
...
This retrieves a data file by hash either locally or from the astropy data
server::
>>> from astropy.utils.data import get_pkg_data_filename
>>> fn = get_pkg_data_filename('hash/34c33b3eb0d56eb9462003af249eff28') # doctest: +SKIP
>>> with open(fn) as f:
... fcontents = f.read()
...
See Also
--------
get_pkg_data_contents : returns the contents of a file or url as a bytes object
get_pkg_data_fileobj : returns a file-like object with the data
"""
if remote_timeout is None:
# use configfile default
remote_timeout = conf.remote_timeout
if data_name.startswith("hash/"):
# first try looking for a local version if a hash is specified
hashfn = _find_hash_fn(data_name[5:])
if hashfn is None:
return download_file(
conf.dataurl + data_name,
cache=True,
show_progress=show_progress,
timeout=remote_timeout,
sources=[conf.dataurl + data_name, conf.dataurl_mirror + data_name],
)
else:
return hashfn
else:
fs_path = os.path.normpath(data_name)
datafn = get_pkg_data_path(fs_path, package=package)
if os.path.isdir(datafn):
raise OSError(
"Tried to access a data file that's actually a package data directory"
)
elif os.path.isfile(datafn): # local file
return datafn
else: # remote file
return download_file(
conf.dataurl + data_name,
cache=True,
show_progress=show_progress,
timeout=remote_timeout,
sources=[conf.dataurl + data_name, conf.dataurl_mirror + data_name],
)
def get_pkg_data_contents(data_name, package=None, encoding=None, cache=True):
"""
Retrieves a data file from the standard locations and returns its
contents as a bytes object.
Parameters
----------
data_name : str
Name/location of the desired data file. One of the following:
* The name of a data file included in the source
distribution. The path is relative to the module
calling this function. For example, if calling from
``astropy.pkname``, use ``'data/file.dat'`` to get the
file in ``astropy/pkgname/data/file.dat``. Double-dots
can be used to go up a level. In the same example, use
``'../data/file.dat'`` to get ``astropy/data/file.dat``.
* If a matching local file does not exist, the Astropy
data server will be queried for the file.
* A hash like that produced by `compute_hash` can be
requested, prefixed by 'hash/'
e.g. 'hash/34c33b3eb0d56eb9462003af249eff28'. The hash
will first be searched for locally, and if not found,
the Astropy data server will be queried.
* A URL to some other file.
package : str, optional
If specified, look for a file relative to the given package, rather
than the default of looking relative to the calling module's package.
encoding : str, optional
When `None` (default), returns a file-like object with a
``read`` method that returns `str` (``unicode``) objects, using
`locale.getpreferredencoding` as an encoding. This matches
the default behavior of the built-in `open` when no ``mode``
argument is provided.
When ``'binary'``, returns a file-like object where its ``read``
method returns `bytes` objects.
When another string, it is the name of an encoding, and the
file-like object's ``read`` method will return `str` (``unicode``)
objects, decoded from binary using the given encoding.
cache : bool
If True, the file will be downloaded and saved locally or the
already-cached local copy will be accessed. If False, the
file-like object will directly access the resource (e.g. if a
remote URL is accessed, an object like that from
`urllib.request.urlopen` is returned).
Returns
-------
contents : bytes
The complete contents of the file as a bytes object.
Raises
------
urllib.error.URLError
If a remote file cannot be found.
OSError
If problems occur writing or reading a local file.
See Also
--------
get_pkg_data_fileobj : returns a file-like object with the data
get_pkg_data_filename : returns a local name for a file containing the data
"""
with get_pkg_data_fileobj(
data_name, package=package, encoding=encoding, cache=cache
) as fd:
contents = fd.read()
return contents
def get_pkg_data_filenames(datadir, package=None, pattern="*"):
"""
Returns the path of all of the data files in a given directory
that match a given glob pattern.
Parameters
----------
datadir : str
Name/location of the desired data files. One of the following:
* The name of a directory included in the source
distribution. The path is relative to the module
calling this function. For example, if calling from
``astropy.pkname``, use ``'data'`` to get the
files in ``astropy/pkgname/data``.
* Remote URLs are not currently supported.
package : str, optional
If specified, look for a file relative to the given package, rather
than the default of looking relative to the calling module's package.
pattern : str, optional
A UNIX-style filename glob pattern to match files. See the
`glob` module in the standard library for more information.
By default, matches all files.
Returns
-------
filenames : iterator of str
Paths on the local filesystem in *datadir* matching *pattern*.
Examples
--------
This will retrieve the contents of the data file for the `astropy.wcs`
tests::
>>> from astropy.utils.data import get_pkg_data_filenames
>>> for fn in get_pkg_data_filenames('data/maps', 'astropy.wcs.tests',
... '*.hdr'):
... with open(fn) as f:
... fcontents = f.read()
...
"""
path = get_pkg_data_path(datadir, package=package)
if os.path.isfile(path):
raise OSError(
"Tried to access a data directory that's actually a package data file"
)
elif os.path.isdir(path):
for filename in os.listdir(path):
if fnmatch.fnmatch(filename, pattern):
yield os.path.join(path, filename)
else:
raise OSError("Path not found")
def get_pkg_data_fileobjs(datadir, package=None, pattern="*", encoding=None):
"""
Returns readable file objects for all of the data files in a given
directory that match a given glob pattern.
Parameters
----------
datadir : str
Name/location of the desired data files. One of the following:
* The name of a directory included in the source
distribution. The path is relative to the module
calling this function. For example, if calling from
``astropy.pkname``, use ``'data'`` to get the
files in ``astropy/pkgname/data``
* Remote URLs are not currently supported
package : str, optional
If specified, look for a file relative to the given package, rather
than the default of looking relative to the calling module's package.
pattern : str, optional
A UNIX-style filename glob pattern to match files. See the
`glob` module in the standard library for more information.
By default, matches all files.
encoding : str, optional
When `None` (default), returns a file-like object with a
``read`` method that returns `str` (``unicode``) objects, using
`locale.getpreferredencoding` as an encoding. This matches
the default behavior of the built-in `open` when no ``mode``
argument is provided.
When ``'binary'``, returns a file-like object where its ``read``
method returns `bytes` objects.
When another string, it is the name of an encoding, and the
file-like object's ``read`` method will return `str` (``unicode``)
objects, decoded from binary using the given encoding.
Returns
-------
fileobjs : iterator of file object
File objects for each of the files on the local filesystem in
*datadir* matching *pattern*.
Examples
--------
This will retrieve the contents of the data file for the `astropy.wcs`
tests::
>>> from astropy.utils.data import get_pkg_data_filenames
>>> for fd in get_pkg_data_fileobjs('data/maps', 'astropy.wcs.tests',
... '*.hdr'):
... fcontents = fd.read()
...
"""
for fn in get_pkg_data_filenames(datadir, package=package, pattern=pattern):
with get_readable_fileobj(fn, encoding=encoding) as fd:
yield fd
def compute_hash(localfn):
"""Computes the MD5 hash for a file.
The hash for a data file is used for looking up data files in a unique
fashion. This is of particular use for tests; a test may require a
particular version of a particular file, in which case it can be accessed
via hash to get the appropriate version.
Typically, if you wish to write a test that requires a particular data
file, you will want to submit that file to the astropy data servers, and
use
e.g. ``get_pkg_data_filename('hash/34c33b3eb0d56eb9462003af249eff28')``,
but with the hash for your file in place of the hash in the example.
Parameters
----------
localfn : str
The path to the file for which the hash should be generated.
Returns
-------
hash : str
The hex digest of the cryptographic hash for the contents of the
``localfn`` file.
"""
with open(localfn, "rb") as f:
h = hashlib.md5(usedforsecurity=False)
block = f.read(conf.compute_hash_block_size)
while block:
h.update(block)
block = f.read(conf.compute_hash_block_size)
return h.hexdigest()
def get_pkg_data_path(*path, package=None):
"""Get path from source-included data directories.
Parameters
----------
*path : str
Name/location of the desired data file/directory.
May be a tuple of strings for ``os.path`` joining.
package : str or None, optional, keyword-only
If specified, look for a file relative to the given package, rather
than the calling module's package.
Returns
-------
path : str
Name/location of the desired data file/directory.
Raises
------
ImportError
Given package or module is not importable.
RuntimeError
If the local data file is outside of the package's tree.
"""
if package is None:
module = find_current_module(1, finddiff=["astropy.utils.data", "contextlib"])
if module is None:
# not called from inside an astropy package. So just pass name
# through
return os.path.join(*path)
if not hasattr(module, "__package__") or not module.__package__:
# The __package__ attribute may be missing or set to None; see
# PEP-366, also astropy issue #1256
if "." in module.__name__:
package = module.__name__.rpartition(".")[0]
else:
package = module.__name__
else:
package = module.__package__
else:
# Backward-compatibility for files that used to exist in astropy.utils.iers
if package == "astropy.utils.iers":
filename = os.path.basename(path[-1])
if filename in _IERS_DATA_REDIRECTS:
warn(
f"Accessing {filename} in this way is deprecated in v6.0, "
f"use astropy.utils.iers.{_IERS_DATA_REDIRECTS[filename][0]} "
"instead.",
AstropyDeprecationWarning,
)
return _IERS_DATA_REDIRECTS[filename][1]
# package errors if it isn't a str
# so there is no need for checks in the containing if/else
module = import_module(package)
# module path within package
module_path = os.path.dirname(module.__file__)
full_path = os.path.join(module_path, *path)
# Check that file is inside tree.
rootpkgname = package.partition(".")[0]
root_dir = os.path.dirname(import_module(rootpkgname).__file__)
if not _is_inside(full_path, root_dir):
raise RuntimeError(
f"attempted to get a local data file outside of the {rootpkgname} tree."
)
return full_path
def _find_hash_fn(hexdigest, pkgname="astropy"):
"""
Looks for a local file by hash - returns file name if found and a valid
file, otherwise returns None.
"""
for v in cache_contents(pkgname=pkgname).values():
if compute_hash(v) == hexdigest:
return v
return None
def get_free_space_in_dir(path, unit=False):
"""
Given a path to a directory, returns the amount of free space
on that filesystem.
Parameters
----------
path : str
The path to a directory.
unit : bool or `~astropy.units.Unit`
Return the amount of free space as Quantity in the given unit,
if provided. Default is `False` for backward-compatibility.
Returns
-------
free_space : int or `~astropy.units.Quantity`
The amount of free space on the partition that the directory is on.
If ``unit=False``, it is returned as plain integer (in bytes).
"""
if not os.path.isdir(path):
raise OSError(
"Can only determine free space associated with directories, not files."
)
# Actually you can on Linux but I want to avoid code that fails
# on Windows only.
free_space = shutil.disk_usage(path).free
if unit:
from astropy import units as u
# TODO: Automatically determine best prefix to use.
if unit is True:
unit = u.byte
free_space = u.Quantity(free_space, u.byte).to(unit)
return free_space
def check_free_space_in_dir(path, size):
"""
Determines if a given directory has enough space to hold a file of
a given size.
Parameters
----------
path : str
The path to a directory.
size : int or `~astropy.units.Quantity`
A proposed filesize. If not a Quantity, assume it is in bytes.
Raises
------
OSError
There is not enough room on the filesystem.
"""
space = get_free_space_in_dir(path, unit=getattr(size, "unit", False))
if space < size:
from astropy.utils.console import human_file_size
raise OSError(
f"Not enough free space in {path} "
f"to download a {human_file_size(size)} file, "
f"only {human_file_size(space)} left"
)
| CacheMissingWarning |
python | getsentry__sentry | src/sentry/monitors/validators.py | {
"start": 3133,
"end": 3355
} | class ____(serializers.Serializer):
target_identifier = serializers.IntegerField(help_text="ID of target object")
target_type = serializers.CharField(help_text="One of [Member, Team]")
| MonitorAlertRuleTargetValidator |
python | apache__airflow | providers/alibaba/src/airflow/providers/alibaba/cloud/exceptions.py | {
"start": 822,
"end": 954
} | class ____(Exception):
"""Raised when MaxCompute project or endpoint is not configured properly."""
| MaxComputeConfigurationException |
python | doocs__leetcode | solution/1700-1799/1781.Sum of Beauty of All Substrings/Solution.py | {
"start": 0,
"end": 283
} | class ____:
def beautySum(self, s: str) -> int:
ans, n = 0, len(s)
for i in range(n):
cnt = Counter()
for j in range(i, n):
cnt[s[j]] += 1
ans += max(cnt.values()) - min(cnt.values())
return ans
| Solution |
python | lxml__lxml | doc/s5/ep2008/atom.py | {
"start": 6419,
"end": 7228
} | class ____(object):
"""
Returns a single subelement based on tag. Setting the attribute
removes the element and adds a new one. Deleting it removes the
element.
"""
def __init__(self, tag):
self.tag = tag
self.__doc__ = 'Get the <atom:%s> element' % self.tag
def __get__(self, obj, type=None):
if obj is None:
return self
return obj._atom_get(self.tag)
def __set__(self, obj, value):
el = obj._atom_get(self.tag)
if el is not None:
parent = el.getparent()
index = parent.index(el)
parent[index] = value
else:
obj.append(value)
def __delete__(self):
el = obj._atom_get(self.tag)
if el is not None:
obj.remove(el)
| _element_property |
python | plotly__plotly.py | plotly/graph_objs/carpet/baxis/title/_font.py | {
"start": 233,
"end": 9887
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "carpet.baxis.title"
_path_str = "carpet.baxis.title.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
@property
def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser can only apply a font if it is
available on the system where it runs. Provide multiple font
families, separated by commas, to indicate the order in which
to apply fonts if they aren't available.
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = val
@property
def lineposition(self):
"""
Sets the kind of decoration line(s) with text, such as an
"under", "over" or "through" as well as combinations e.g.
"under+over", etc.
The 'lineposition' property is a flaglist and may be specified
as a string containing:
- Any combination of ['under', 'over', 'through'] joined with '+' characters
(e.g. 'under+over')
OR exactly one of ['none'] (e.g. 'none')
Returns
-------
Any
"""
return self["lineposition"]
@lineposition.setter
def lineposition(self, val):
self["lineposition"] = val
@property
def shadow(self):
"""
Sets the shape and color of the shadow behind text. "auto"
places minimal shadow and applies contrast text font color. See
https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow
for additional options.
The 'shadow' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["shadow"]
@shadow.setter
def shadow(self, val):
self["shadow"] = val
@property
def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
@property
def style(self):
"""
Sets whether a font should be styled with a normal or italic
face from its family.
The 'style' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'italic']
Returns
-------
Any
"""
return self["style"]
@style.setter
def style(self, val):
self["style"] = val
@property
def textcase(self):
"""
Sets capitalization of text. It can be used to make text appear
in all-uppercase or all-lowercase, or with each word
capitalized.
The 'textcase' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'word caps', 'upper', 'lower']
Returns
-------
Any
"""
return self["textcase"]
@textcase.setter
def textcase(self, val):
self["textcase"] = val
@property
def variant(self):
"""
Sets the variant of the font.
The 'variant' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'small-caps', 'all-small-caps',
'all-petite-caps', 'petite-caps', 'unicase']
Returns
-------
Any
"""
return self["variant"]
@variant.setter
def variant(self, val):
self["variant"] = val
@property
def weight(self):
"""
Sets the weight (or boldness) of the font.
The 'weight' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [1, 1000]
OR exactly one of ['normal', 'bold'] (e.g. 'bold')
Returns
-------
int
"""
return self["weight"]
@weight.setter
def weight(self, val):
self["weight"] = val
@property
def _prop_descriptions(self):
return """\
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
"""
def __init__(
self,
arg=None,
color=None,
family=None,
lineposition=None,
shadow=None,
size=None,
style=None,
textcase=None,
variant=None,
weight=None,
**kwargs,
):
"""
Construct a new Font object
Sets this axis' title font.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.carpet.baxis.title.Font`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
Returns
-------
Font
"""
super().__init__("font")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.carpet.baxis.title.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.carpet.baxis.title.Font`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("family", arg, family)
self._set_property("lineposition", arg, lineposition)
self._set_property("shadow", arg, shadow)
self._set_property("size", arg, size)
self._set_property("style", arg, style)
self._set_property("textcase", arg, textcase)
self._set_property("variant", arg, variant)
self._set_property("weight", arg, weight)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Font |
python | pytorch__pytorch | test/test_jit_llga_fuser.py | {
"start": 30857,
"end": 32754
} | class ____(JitLlgaTestCase):
@skipIfNoTorchVision
def _test_vision(self, model_name, dtype):
m = getattr(torchvision.models, model_name)().eval()
if dtype == torch.bfloat16:
m = optimization.fuse(m)
x = torch.rand(1, 3, 224, 224) / 10
_, graph = self.checkTrace(m, [x], dtype)
self.assertFused(graph, ['aten::_convolution', 'aten::batch_norm',
'aten::relu', 'aten::linear',
'aten::avg_pool2d', 'aten::max_pool2d'])
for model_name, enabled in [
['resnet50', True],
['resnext50_32x4d', True],
['resnext101_32x8d', True],
['densenet121', True],
['densenet161', True],
['densenet169', True],
['densenet201', True],
['efficientnet_b0', True],
['efficientnet_b1', True],
['efficientnet_b2', True],
['efficientnet_b3', True],
['efficientnet_b4', True],
['efficientnet_b5', True],
['efficientnet_b6', True],
['efficientnet_b7', True],
['regnet_y_400mf', True],
['googlenet', TEST_SCIPY],
['mobilenet_v2', True],
['mobilenet_v3_large', True],
['mnasnet1_0', True],
['squeezenet1_0', True],
['vgg16', True],
['alexnet', True],
['shufflenet_v2_x1_0', True],
['wide_resnet50_2', True],
]:
def _wrapper(mname, dtype):
@unittest.skipIf(not enabled, 'Disabled')
@separate_process
def test(self, dtype=dtype):
return self._test_vision(mname, dtype)
return test
for dtype in [torch.bfloat16, torch.float32]:
setattr(TestModel, 'test_vision_{}_{}'.format(model_name, str(dtype).split("torch.")[1]), _wrapper(model_name, dtype))
instantiate_device_type_tests(TestFusionPattern, globals())
instantiate_device_type_tests(TestOp, globals())
if __name__ == '__main__':
if sys.version_info < (3, 14):
run_tests()
| TestModel |
python | huggingface__transformers | src/transformers/activations.py | {
"start": 6259,
"end": 6811
} | class ____(nn.Module):
"""
See Mish: A Self-Regularized Non-Monotonic Activation Function (Misra., https://huggingface.co/papers/1908.08681). Also
visit the official repository for the paper: https://github.com/digantamisra98/Mish
"""
def __init__(self):
super().__init__()
self.act = nn.functional.mish
def _mish_python(self, input: Tensor) -> Tensor:
return input * torch.tanh(nn.functional.softplus(input))
def forward(self, input: Tensor) -> Tensor:
return self.act(input)
| MishActivation |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_internal/resolution/resolvelib/reporter.py | {
"start": 235,
"end": 2147
} | class ____(BaseReporter):
def __init__(self) -> None:
self.reject_count_by_package: DefaultDict[str, int] = defaultdict(int)
self._messages_at_reject_count = {
1: (
"pip is looking at multiple versions of {package_name} to "
"determine which version is compatible with other "
"requirements. This could take a while."
),
8: (
"pip is still looking at multiple versions of {package_name} to "
"determine which version is compatible with other "
"requirements. This could take a while."
),
13: (
"This is taking longer than usual. You might need to provide "
"the dependency resolver with stricter constraints to reduce "
"runtime. See https://pip.pypa.io/warnings/backtracking for "
"guidance. If you want to abort this run, press Ctrl + C."
),
}
def rejecting_candidate(self, criterion: Any, candidate: Candidate) -> None:
self.reject_count_by_package[candidate.name] += 1
count = self.reject_count_by_package[candidate.name]
if count not in self._messages_at_reject_count:
return
message = self._messages_at_reject_count[count]
logger.info("INFO: %s", message.format(package_name=candidate.name))
msg = "Will try a different candidate, due to conflict:"
for req_info in criterion.information:
req, parent = req_info.requirement, req_info.parent
# Inspired by Factory.get_installation_error
msg += "\n "
if parent:
msg += f"{parent.name} {parent.version} depends on "
else:
msg += "The user requested "
msg += req.format_for_error()
logger.debug(msg)
| PipReporter |
python | pypa__pip | src/pip/_vendor/urllib3/contrib/_securetransport/bindings.py | {
"start": 14456,
"end": 17632
} | class ____(object):
"""
A class object that acts as essentially a namespace for Security constants.
"""
kSSLSessionOptionBreakOnServerAuth = 0
kSSLProtocol2 = 1
kSSLProtocol3 = 2
kTLSProtocol1 = 4
kTLSProtocol11 = 7
kTLSProtocol12 = 8
# SecureTransport does not support TLS 1.3 even if there's a constant for it
kTLSProtocol13 = 10
kTLSProtocolMaxSupported = 999
kSSLClientSide = 1
kSSLStreamType = 0
kSecFormatPEMSequence = 10
kSecTrustResultInvalid = 0
kSecTrustResultProceed = 1
# This gap is present on purpose: this was kSecTrustResultConfirm, which
# is deprecated.
kSecTrustResultDeny = 3
kSecTrustResultUnspecified = 4
kSecTrustResultRecoverableTrustFailure = 5
kSecTrustResultFatalTrustFailure = 6
kSecTrustResultOtherError = 7
errSSLProtocol = -9800
errSSLWouldBlock = -9803
errSSLClosedGraceful = -9805
errSSLClosedNoNotify = -9816
errSSLClosedAbort = -9806
errSSLXCertChainInvalid = -9807
errSSLCrypto = -9809
errSSLInternal = -9810
errSSLCertExpired = -9814
errSSLCertNotYetValid = -9815
errSSLUnknownRootCert = -9812
errSSLNoRootCert = -9813
errSSLHostNameMismatch = -9843
errSSLPeerHandshakeFail = -9824
errSSLPeerUserCancelled = -9839
errSSLWeakPeerEphemeralDHKey = -9850
errSSLServerAuthCompleted = -9841
errSSLRecordOverflow = -9847
errSecVerifyFailed = -67808
errSecNoTrustSettings = -25263
errSecItemNotFound = -25300
errSecInvalidTrustSettings = -25262
# Cipher suites. We only pick the ones our default cipher string allows.
# Source: https://developer.apple.com/documentation/security/1550981-ssl_cipher_suite_values
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02C
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = 0xC030
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02B
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0xC02F
TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA9
TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA8
TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = 0x009F
TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = 0x009E
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0xC024
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = 0xC028
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = 0xC00A
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = 0xC014
TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x006B
TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x0039
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = 0xC023
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = 0xC027
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = 0xC009
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = 0xC013
TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x0067
TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x0033
TLS_RSA_WITH_AES_256_GCM_SHA384 = 0x009D
TLS_RSA_WITH_AES_128_GCM_SHA256 = 0x009C
TLS_RSA_WITH_AES_256_CBC_SHA256 = 0x003D
TLS_RSA_WITH_AES_128_CBC_SHA256 = 0x003C
TLS_RSA_WITH_AES_256_CBC_SHA = 0x0035
TLS_RSA_WITH_AES_128_CBC_SHA = 0x002F
TLS_AES_128_GCM_SHA256 = 0x1301
TLS_AES_256_GCM_SHA384 = 0x1302
TLS_AES_128_CCM_8_SHA256 = 0x1305
TLS_AES_128_CCM_SHA256 = 0x1304
| SecurityConst |
python | huggingface__transformers | tests/models/chinese_clip/test_modeling_chinese_clip.py | {
"start": 1591,
"end": 8100
} | class ____:
def __init__(
self,
parent,
batch_size=13,
seq_length=7,
is_training=True,
use_input_mask=True,
use_token_type_ids=True,
use_labels=True,
vocab_size=99,
hidden_size=32,
num_hidden_layers=2,
num_attention_heads=4,
intermediate_size=37,
hidden_act="gelu",
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
max_position_embeddings=512,
type_vocab_size=16,
type_sequence_label_size=2,
initializer_range=0.02,
num_labels=3,
num_choices=4,
scope=None,
):
self.parent = parent
self.batch_size = batch_size
self.seq_length = seq_length
self.is_training = is_training
self.use_input_mask = use_input_mask
self.use_token_type_ids = use_token_type_ids
self.use_labels = use_labels
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.intermediate_size = intermediate_size
self.hidden_act = hidden_act
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.type_sequence_label_size = type_sequence_label_size
self.initializer_range = initializer_range
self.num_labels = num_labels
self.num_choices = num_choices
self.scope = scope
def prepare_config_and_inputs(self):
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
input_mask = None
if self.use_input_mask:
input_mask = random_attention_mask([self.batch_size, self.seq_length])
token_type_ids = None
if self.use_token_type_ids:
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
sequence_labels = None
token_labels = None
choice_labels = None
if self.use_labels:
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
choice_labels = ids_tensor([self.batch_size], self.num_choices)
config = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def get_config(self):
"""
Returns a tiny configuration by default.
"""
return ChineseCLIPTextConfig(
vocab_size=self.vocab_size,
hidden_size=self.hidden_size,
num_hidden_layers=self.num_hidden_layers,
num_attention_heads=self.num_attention_heads,
intermediate_size=self.intermediate_size,
hidden_act=self.hidden_act,
hidden_dropout_prob=self.hidden_dropout_prob,
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
max_position_embeddings=self.max_position_embeddings,
type_vocab_size=self.type_vocab_size,
is_decoder=False,
initializer_range=self.initializer_range,
)
def prepare_config_and_inputs_for_decoder(self):
(
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
) = self.prepare_config_and_inputs()
config.is_decoder = True
encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
return (
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
)
def create_and_check_model(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
model = ChineseCLIPTextModel(config=config)
model.to(torch_device)
model.eval()
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
result = model(input_ids, token_type_ids=token_type_ids)
result = model(input_ids)
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
def create_and_check_model_as_decoder(
self,
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
):
config.add_cross_attention = True
model = ChineseCLIPTextModel(config)
model.to(torch_device)
model.eval()
result = model(
input_ids,
attention_mask=input_mask,
token_type_ids=token_type_ids,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
)
result = model(
input_ids,
attention_mask=input_mask,
token_type_ids=token_type_ids,
encoder_hidden_states=encoder_hidden_states,
)
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
def prepare_config_and_inputs_for_common(self):
config_and_inputs = self.prepare_config_and_inputs()
(
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
) = config_and_inputs
inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
return config, inputs_dict
| ChineseCLIPTextModelTester |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/missingSuper1.py | {
"start": 635,
"end": 720
} | class ____(ParentA, ParentB):
def __init__(self):
super().__init__()
| ChildB |
python | pytransitions__transitions | transitions/extensions/asyncio.py | {
"start": 2639,
"end": 3082
} | class ____(NestedState, AsyncState):
"""A state that allows substates. Callback execution is done asynchronously."""
async def scoped_enter(self, event_data, scope=None):
self._scope = scope or []
await self.enter(event_data)
self._scope = []
async def scoped_exit(self, event_data, scope=None):
self._scope = scope or []
await self.exit(event_data)
self._scope = []
| NestedAsyncState |
python | google__pytype | pytype/rewrite/abstract/functions_test.py | {
"start": 4883,
"end": 5375
} | class ____(test_utils.PytdTestBase,
test_utils.ContextfulTestBase):
def test_return(self):
pytd_func = self.build_pytd('def f() -> int: ...')
func = self.ctx.abstract_converter.pytd_function_to_value(pytd_func)
args = functions.MappedArgs(signature=func.signatures[0], argdict={})
ret = func.call_with_mapped_args(args).get_return_value()
self.assertIsInstance(ret, classes.FrozenInstance)
self.assertEqual(ret.cls.name, 'int')
| PytdFunctionTest |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/range_formatting/fmt_on_off.py | {
"start": 0,
"end": 573
} | class ____:
# Range that falls entirely in a suppressed range
# fmt: off<RANGE_START>
def method( self ):
print ( "str" )
<RANGE_END># fmt: on
# This should net get formatted because it isn't in a formatting range.
def not_in_formatting_range ( self): ...
# Range that starts in a suppressed range and ends in a formatting range
# fmt: off<RANGE_START>
def other( self):
print ( "str" )
# fmt: on
def formatted ( self):
pass
<RANGE_END>
def outside_formatting_range (self): pass
| MyClass |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_tasks.py | {
"start": 5366,
"end": 6124
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.tasks.CloudTasksHook")
def test_delete_queue(self, mock_hook):
mock_hook.return_value.delete_queue.return_value = None
operator = CloudTasksQueueDeleteOperator(location=LOCATION, queue_name=QUEUE_ID, task_id="id")
operator.execute(context=mock.MagicMock())
mock_hook.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=None,
)
mock_hook.return_value.delete_queue.assert_called_once_with(
location=LOCATION,
queue_name=QUEUE_ID,
project_id=None,
retry=DEFAULT,
timeout=None,
metadata=(),
)
| TestCloudTasksQueueDelete |
python | numba__numba | numba/tests/test_unicode_names.py | {
"start": 939,
"end": 1509
} | class ____(TestCase):
def test_normalize_ir_text(self):
# non-unicode input
out = cgutils.normalize_ir_text('abc')
# str returned
self.assertIsInstance(out, str)
# try encoding to latin
out.encode('latin1')
def test_normalize_ir_text_unicode(self):
# unicode input
out = cgutils.normalize_ir_text(unicode_name2)
# str returned
self.assertIsInstance(out, str)
# try encoding to latin
out.encode('latin1')
if __name__ == '__main__':
unittest.main()
| TestUnicodeUtils |
python | pypa__warehouse | tests/unit/oidc/forms/test_google.py | {
"start": 2746,
"end": 3728
} | class ____:
@pytest.mark.parametrize(
("sub", "email"),
[
(None, "some-email@example.com"),
("some-subject", "some-email@example.com"),
],
)
def test_validate(self, sub, email):
data = MultiDict(
{
"sub": sub,
"email": email,
}
)
form = google.GooglePublisherForm(MultiDict(data))
assert form.validate(), str(form.errors)
@pytest.mark.parametrize(
("sub", "email"),
[
("", ""),
(None, ""),
("some-subject", ""),
("some-subject", "invalid_email"),
],
)
def test_validate_basic_invalid_fields(self, sub, email):
data = MultiDict(
{
"sub": sub,
"email": email,
}
)
form = google.GooglePublisherForm(MultiDict(data))
assert not form.validate()
| TestGooglePublisherForm |
python | zostera__django-bootstrap4 | src/bootstrap4/renderers.py | {
"start": 4502,
"end": 7170
} | class ____(BaseRenderer):
"""Default form renderer."""
def __init__(self, form, *args, **kwargs):
if not isinstance(form, BaseForm):
raise BootstrapError('Parameter "form" should contain a valid Django Form.')
self.form = form
super().__init__(*args, **kwargs)
self.error_css_class = kwargs.get("error_css_class", None)
self.required_css_class = kwargs.get("required_css_class", None)
self.bound_css_class = kwargs.get("bound_css_class", None)
self.alert_error_type = kwargs.get("alert_error_type", "non_fields")
self.form_check_class = kwargs.get("form_check_class", "form-check")
def render_fields(self):
rendered_fields = []
for field in self.form:
rendered_fields.append(
render_field(
field,
layout=self.layout,
form_group_class=self.form_group_class,
field_class=self.field_class,
label_class=self.label_class,
form_check_class=self.form_check_class,
show_label=self.show_label,
show_help=self.show_help,
exclude=self.exclude,
set_placeholder=self.set_placeholder,
size=self.size,
horizontal_label_class=self.horizontal_label_class,
horizontal_field_class=self.horizontal_field_class,
error_css_class=self.error_css_class,
required_css_class=self.required_css_class,
bound_css_class=self.bound_css_class,
)
)
return "\n".join(rendered_fields)
def get_fields_errors(self):
form_errors = []
for field in self.form:
if not field.is_hidden and field.errors:
form_errors += field.errors
return form_errors
def render_errors(self, type="all"):
form_errors = None
if type == "all":
form_errors = self.get_fields_errors() + self.form.non_field_errors()
elif type == "fields":
form_errors = self.get_fields_errors()
elif type == "non_fields":
form_errors = self.form.non_field_errors()
if form_errors:
return render_template_file(
"bootstrap4/form_errors.html",
context={"errors": form_errors, "form": self.form, "layout": self.layout, "type": type},
)
return ""
def _render(self):
return self.render_errors(self.alert_error_type) + self.render_fields()
| FormRenderer |
python | pytorch__pytorch | torch/fx/experimental/unification/multipledispatch/dispatcher.py | {
"start": 12382,
"end": 13972
} | class ____(Dispatcher):
"""Dispatch methods based on type signature
See Also:
Dispatcher
"""
# pyrefly: ignore [bad-override]
__slots__ = ("obj", "cls")
@classmethod
def get_func_params(cls, func):
if hasattr(inspect, "signature"):
sig = inspect.signature(func)
return itl.islice(sig.parameters.values(), 1, None)
def __get__(self, instance, owner):
self.obj = instance
self.cls = owner
return self
def __call__(self, *args, **kwargs):
types = tuple(type(arg) for arg in args)
func = self.dispatch(*types)
if not func:
raise NotImplementedError(
f"Could not find signature for {self.name}: <{str_signature(types)}>"
)
return func(self.obj, *args, **kwargs)
def str_signature(sig):
"""String representation of type signature
>>> str_signature((int, float))
'int, float'
"""
return ", ".join(cls.__name__ for cls in sig)
def warning_text(name, amb):
"""The text for ambiguity warnings"""
text = f"\nAmbiguities exist in dispatched function {name}\n\n"
text += "The following signatures may result in ambiguous behavior:\n"
for pair in amb:
text += "\t" + ", ".join("[" + str_signature(s) + "]" for s in pair) + "\n"
text += "\n\nConsider making the following additions:\n\n"
text += "\n\n".join(
[
"@dispatch(" + str_signature(super_signature(s)) + f")\ndef {name}(...)"
for s in amb
]
)
return text
| MethodDispatcher |
python | pdm-project__pdm | src/pdm/resolver/uv.py | {
"start": 1019,
"end": 9597
} | class ____(Resolver):
def __post_init__(self) -> None:
super().__post_init__()
if self.locked_repository is None:
self.locked_repository = self.project.get_locked_repository()
if self.update_strategy not in {"reuse", "all"}:
self.project.core.ui.warn(
f"{self.update_strategy} update strategy is not supported by uv, using 'reuse' instead"
)
self.update_strategy = "reuse"
if FLAG_INHERIT_METADATA in self.strategies:
self.project.core.ui.warn("inherit_metadata strategy is not supported by uv resolver, it will be ignored")
self.strategies.discard(FLAG_INHERIT_METADATA)
this_spec = self.environment.spec
assert this_spec.platform is not None
if self.target.platform and (
self.target.platform.sys_platform != this_spec.platform.sys_platform
or self.target.platform.arch != this_spec.platform.arch
):
self.project.core.ui.warn(
f"Resolving against target {self.target.platform} on {this_spec.platform} is not supported by uv mode, "
"the resolution may be inaccurate."
)
def _build_lock_command(self) -> list[str | HiddenText]:
cmd: list[str | HiddenText] = [
*self.project.core.uv_cmd,
"lock",
"-p",
str(self.environment.interpreter.executable),
]
if self.project.core.ui.verbosity > 0:
cmd.append("--verbose")
if not self.project.core.state.enable_cache:
cmd.append("--no-cache")
first_index = True
for source in self.project.sources:
url = source.url_with_credentials
if source.type == "find_links":
cmd.extend(["--find-links", url])
elif first_index:
cmd.extend(["--index-url", url])
first_index = False
else:
cmd.extend(["--extra-index-url", url])
if self.project.pyproject.settings.get("resolution", {}).get("respect-source-order", False):
cmd.append("--index-strategy=unsafe-first-match")
else:
cmd.append("--index-strategy=unsafe-best-match")
if self.update_strategy != "all":
for name in self.tracked_names:
cmd.extend(["-P", name])
if self.project.pyproject.allow_prereleases:
cmd.append("--prerelease=allow")
no_binary = self.environment._setting_list("PDM_NO_BINARY", "resolution.no-binary")
only_binary = self.environment._setting_list("PDM_ONLY_BINARY", "resolution.only-binary")
if ":all:" in no_binary:
cmd.append("--no-binary")
else:
for pkg in no_binary:
cmd.extend(["--no-binary-package", pkg])
if ":all:" in only_binary:
cmd.append("--no-build")
else:
for pkg in only_binary:
cmd.extend(["--no-build-package", pkg])
if not self.project.core.state.build_isolation:
cmd.append("--no-build-isolation")
if cs := self.project.core.state.config_settings:
for k, v in cs.items():
cmd.extend(["--config-setting", f"{k}={v}"])
if FLAG_DIRECT_MINIMAL_VERSIONS in self.strategies:
cmd.append("--resolution=lowest-direct")
if dt := self.project.core.state.exclude_newer:
cmd.extend(["--exclude-newer", dt.isoformat()])
return cmd
def _parse_uv_lock(self, path: Path) -> Resolution:
from unearth import Link
from pdm.compat import tomllib
with path.open("rb") as f:
data = tomllib.load(f)
packages: list[Package] = []
hash_cache = self.project.make_hash_cache()
session = self.environment.session
def make_requirement(dep: dict[str, Any]) -> str:
req = NamedRequirement(name=dep["name"])
if version := dep.get("version"):
req.specifier = get_specifier(f"=={version}")
if marker := dep.get("marker"):
req.marker = get_marker(marker)
if extra := dep.get("extra"):
req.extras = extra
return req.as_line()
def make_hash(item: dict[str, Any], fallback_url: str | None = None) -> FileHash:
url = item.get("url") or fallback_url
if url is None:
raise KeyError("url")
link = Link(url)
hash_value = item.get("hash")
if hash_value is None:
hash_value = hash_cache.get_hash(link, session)
return {"url": url, "file": link.filename, "hash": hash_value}
for package in data["package"]:
if (
self.project.name
and package["name"] == normalize_name(self.project.name)
and (not self.keep_self or package["source"].get("virtual"))
):
continue
req: Requirement
if url := package["source"].get("url"):
req = FileRequirement.create(url=url, name=package["name"])
elif git := package["source"].get("git"):
matches = GIT_URL.match(git)
if not matches:
raise ValueError(f"Invalid git URL: {git}")
url = f"git+{matches.group('repo')}"
if ref := matches.group("ref"):
url += f"@{ref}"
req = VcsRequirement.create(url=url, name=package["name"])
req.revision = matches.group("revision")
elif editable := package["source"].get("editable"):
req = FileRequirement.create(path=editable, name=package["name"], editable=True)
elif filepath := package["source"].get("path"):
req = FileRequirement.create(path=filepath, name=package["name"])
else:
req = NamedRequirement.create(name=package["name"], specifier=f"=={package['version']}")
candidate = Candidate(req, name=package["name"], version=package["version"])
fallback_url = package["source"].get("url")
for wheel in package.get("wheels", []):
candidate.hashes.append(make_hash(wheel, fallback_url))
if sdist := package.get("sdist"):
candidate.hashes.append(make_hash(sdist, fallback_url))
entry = Package(candidate, [make_requirement(dep) for dep in package.get("dependencies", [])], "")
packages.append(entry)
if optional_dependencies := package.get("optional-dependencies"):
for group, deps in optional_dependencies.items():
extra_entry = Package(
candidate.copy_with(replace(req, extras=(group,))),
[f"{req.key}=={candidate.version}", *(make_requirement(dep) for dep in deps)],
"",
)
packages.append(extra_entry)
return Resolution(packages, self.requested_groups)
def resolve(self) -> Resolution:
from pdm.formats.uv import uv_file_builder
locked_repo = self.locked_repository or self.project.get_locked_repository()
with uv_file_builder(self.project, str(self.target.requires_python), self.requirements, locked_repo) as builder:
venv_project = self.environment.interpreter.get_venv()
if venv_project is None:
raise ProjectError("uv mode doesn't support non-virtual environments")
builder.build_pyproject_toml()
uv_lock_path = self.project.root / "uv.lock"
if self.update_strategy != "all":
builder.build_uv_lock()
try:
if isinstance(self.reporter, RichLockReporter):
self.reporter.stop()
uv_lock_command = self._build_lock_command()
self.project.core.ui.echo(f"Running uv lock command: {uv_lock_command}", verbosity=Verbosity.DETAIL)
real_command = [s.secret if isinstance(s, HiddenText) else s for s in uv_lock_command]
env = {**os.environ, "UV_PROJECT_ENVIRONMENT": str(venv_project.root)}
subprocess.run(real_command, cwd=self.project.root, check=True, env=env)
finally:
if isinstance(self.reporter, RichLockReporter):
self.reporter.start()
return self._parse_uv_lock(uv_lock_path)
| UvResolver |
python | Pylons__pyramid | tests/pkgs/legacysecurityapp/__init__.py | {
"start": 151,
"end": 1192
} | class ____:
def permits(self, context, principals, permission):
if 'bob' in principals and permission == 'foo':
return Allowed('')
else:
return Denied('')
def principals_allowed_by_permission(self, context, permission):
raise NotImplementedError() # pragma: no cover
def public(context, request):
return Response('Hello')
def private(context, request):
return Response('Secret')
def inaccessible(context, request):
raise AssertionError() # pragma: no cover
def includeme(config):
config.set_authentication_policy(RemoteUserAuthenticationPolicy())
config.set_authorization_policy(AuthorizationPolicy())
config.add_route('public', '/public')
config.add_view(public, route_name='public')
config.add_route('private', '/private')
config.add_view(private, route_name='private', permission='foo')
config.add_route('inaccessible', '/inaccessible')
config.add_view(inaccessible, route_name='inaccessible', permission='bar')
| AuthorizationPolicy |
python | ray-project__ray | python/ray/_private/thirdparty/pyamdsmi/pyamdsmi.py | {
"start": 5958,
"end": 19979
} | class ____(c_int):
RSMI_IOLINK_TYPE_UNDEFINED = 0
RSMI_IOLINK_TYPE_HYPERTRANSPORT = 1
RSMI_IOLINK_TYPE_PCIEXPRESS = 2
RSMI_IOLINK_TYPE_AMBA = 3
RSMI_IOLINK_TYPE_MIPI = 4
RSMI_IOLINK_TYPE_QPI_1_1 = 5
RSMI_IOLINK_TYPE_RESERVED1 = 6
RSMI_IOLINK_TYPE_RESERVED2 = 7
RSMI_IOLINK_TYPE_RAPID_IO = 8
RSMI_IOLINK_TYPE_INFINIBAND = 9
RSMI_IOLINK_TYPE_RESERVED3 = 10
RSMI_IOLINK_TYPE_XGMI = 11
RSMI_IOLINK_TYPE_XGOP = 12
RSMI_IOLINK_TYPE_GZ = 13
RSMI_IOLINK_TYPE_ETHERNET_RDMA = 14
RSMI_IOLINK_TYPE_RDMA_OTHER = 15
RSMI_IOLINK_TYPE_OTHER = 16
RSMI_IOLINK_TYPE_NUMIOLINKTYPES = 17
RSMI_IOLINK_TYPE_SIZE = 0xFFFFFFFF
## Library loading
rocm_lib = None
lib_load_lock = threading.Lock()
_rocm_lib_refcount = 0
## Function access, to prevent lib_load_lock deadlock
_rocml_get_function_ptr_cache = dict()
def _rocml_get_function_ptr(name):
global rocm_lib
if name in _rocml_get_function_ptr_cache:
return _rocml_get_function_ptr_cache[name]
lib_load_lock.acquire()
try:
# ensure library was loaded
if rocm_lib == None:
raise ROCMLError_Uninitialized
try:
_rocml_get_function_ptr_cache[name] = getattr(rocm_lib, name)
return _rocml_get_function_ptr_cache[name]
except AttributeError:
raise ROCMLError_FunctionNotFound
finally:
# lock is always freed
lib_load_lock.release()
def _load_rocm_library():
"""Load ROCm library if not already loaded"""
global rocm_lib
if rocm_lib == None:
lib_load_lock.acquire()
try:
if rocm_lib == None:
try:
if sys.platform[:3] == 'win':
raise ROCMLError_NotSupported('Windows platform is not supported yet')
else:
# assume linux
path_librocm = _find_lib_rocm()
cdll.LoadLibrary(path_librocm)
rocm_lib = CDLL(path_librocm)
except OSError:
raise ROCMLError_LibraryNotFound('ROCm library not found')
if rocm_lib == None:
raise ROCMLError_LibraryNotFound('ROCm library not found')
finally:
lib_load_lock.release()
def _find_lib_rocm():
"""search for librocm and returns path
if search fails, returns empty string
"""
rocm_path = os.environ.get('ROCM_PATH', '/opt/rocm')
rocm_lib_path = join(rocm_path, f'lib/{LIBROCM_NAME}')
return rocm_lib_path if isfile(rocm_lib_path) else ''
def _driver_initialized():
""" Returns true if amdgpu is found in the list of initialized modules
"""
initialized = ''
try:
initialized = str(subprocess.check_output("cat /sys/module/amdgpu/initstate |grep live", shell=True, stderr=subprocess.DEVNULL))
except subprocess.CalledProcessError:
pass
return len(initialized) > 0
def smi_initialize():
"""Initialize ROCm binding of SMI"""
_load_rocm_library()
if _driver_initialized():
ret_init = rocm_lib.rsmi_init(0)
if ret_init != 0:
logging.debug("ROCm SMI init returned value: %s", ret_init)
raise RuntimeError('ROCm SMI initialization failed')
else:
raise RuntimeError('ROCm driver initilization failed')
# update reference count
global _rocm_lib_refcount
lib_load_lock.acquire()
_rocm_lib_refcount += 1
lib_load_lock.release()
def rsmi_ret_ok(my_ret):
""" Returns true if RSMI call status is 0 (success)
@param device: DRM device identifier
@param my_ret: Return of RSMI call (rocm_smi_lib API)
@param metric: Parameter of GPU currently being analyzed
"""
if my_ret != rsmi_status_t.RSMI_STATUS_SUCCESS:
err_str = c_char_p()
rocm_lib.rsmi_status_string(my_ret, byref(err_str))
logging.debug("ROCm RSMI error: %s", err_str.value.decode())
return False
return True
def smi_shutdown():
"""leave the library loaded, but shutdown the interface"""
rsmi_ret_ok(rocm_lib.rsmi_shut_down())
# update reference count
global _rocm_lib_refcount
lib_load_lock.acquire()
_rocm_lib_refcount -= 1
lib_load_lock.release()
def smi_get_kernel_version():
"""returns ROCm kernerl driver version"""
ver_str = create_string_buffer(256)
ret = rocm_lib.rsmi_version_str_get(rsmi_sw_component_t.RSMI_SW_COMP_DRIVER, ver_str, 256)
return ver_str.value.decode() if rsmi_ret_ok(ret) else ''
def smi_get_device_id(dev):
"""returns device id of the device as 64bit integer"""
uid = c_uint64()
ret = rocm_lib.rsmi_dev_id_get(dev, byref(uid))
return uid.value if rsmi_ret_ok(ret) else -1
def smi_get_device_count():
"""returns a list of GPU devices """
num_device = c_uint32(0)
ret = rocm_lib.rsmi_num_monitor_devices(byref(num_device))
return num_device.value if rsmi_ret_ok(ret) else -1
def smi_get_device_name(dev):
"""returns the name of a GPU device"""
series = create_string_buffer(RSMI_MAX_BUFFER_LENGTH)
ret = rocm_lib.rsmi_dev_name_get(dev, series, RSMI_MAX_BUFFER_LENGTH)
return series.value.decode() if rsmi_ret_ok(ret) else ''
def smi_get_device_unique_id(dev):
"""returns unique id of the device as 64bit integer"""
uid = c_uint64()
ret = rocm_lib.rsmi_dev_unique_id_get(dev, byref(uid))
return uid.value if rsmi_ret_ok(ret) else -1
def smi_get_device_utilization(dev):
"""returns GPU device busy percent of device_id dev"""
busy_percent = c_uint32()
ret = rocm_lib.rsmi_dev_busy_percent_get(dev, byref(busy_percent))
return busy_percent.value if rsmi_ret_ok(ret) else -1
def smi_get_device_memory_used(dev, type='VRAM'):
"""returns used memory of device_id dev in bytes"""
type_idx = memory_type_l.index(type)
used = c_uint64()
ret = rocm_lib.rsmi_dev_memory_usage_get(dev, type_idx, byref(used))
return used.value if rsmi_ret_ok(ret) else -1
def smi_get_device_memory_total(dev, type='VRAM'):
"""returns total memory of device_id dev in bytes"""
type_idx = memory_type_l.index(type)
total = c_uint64()
ret = rocm_lib.rsmi_dev_memory_total_get(dev, type_idx, byref(total))
return total.value if rsmi_ret_ok(ret) else -1
def smi_get_device_memory_busy(dev):
"""returns percentage of time any device memory is being used"""
busy_percent = c_uint32()
ret = rocm_lib.rsmi_dev_memory_busy_percent_get(dev, byref(busy_percent))
return busy_percent.value if rsmi_ret_ok(ret) else -1
def smi_get_device_memory_reserved_pages(dev):
"""returns info about reserved memory pages"""
num_pages = c_uint32()
records = rsmi_retired_page_record_t()
ret = rocm_lib.rsmi_dev_memory_reserved_pages_get(dev, byref(num_pages), byref(records))
return (num_pages.value, records) if rsmi_ret_ok(ret) else -1
# PCIE functions
def smi_get_device_pcie_bandwidth(dev):
"""returns list of possible pcie bandwidths for the device in bytes/sec"""
bandwidth = rsmi_pcie_bandwidth_t()
ret = rocm_lib.rsmi_dev_pci_bandwidth_get(dev, byref(bandwidth))
return bandwidth if rsmi_ret_ok(ret) else -1
def smi_get_device_pci_id(dev):
"""returns unique PCI ID of the device in 64bit Hex with format:
BDFID = ((DOMAIN & 0xffffffff) << 32) | ((BUS & 0xff) << 8) |
((DEVICE & 0x1f) <<3 ) | (FUNCTION & 0x7)
"""
bdfid = c_uint64()
ret = rocm_lib.rsmi_dev_pci_id_get(dev, byref(bdfid))
return bdfid.value if rsmi_ret_ok(ret) else -1
def smi_get_device_topo_numa_affinity(dev):
"""returns the NUMA node associated with the device"""
numa_node = c_uint32()
ret = reocm_lib.rsmi_topo_numa_affinity_get(dev, byref(numa_node))
return numa_node.value if rsmi_ret_ok(ret) else -1
def smi_get_device_pcie_throughput(dev):
"""returns measured pcie throughput for the device in bytes/sec"""
sent = c_uint64()
recv = c_uint64()
max_pkt_sz = c_uint64()
ret = rocm_lib.rsmi_dev_pci_throughput_get(dev, byref(sent), byref(recv), byref(max_pkt_sz))
return (recv.value + sent.value) * max_pkt_sz.value if rsmi_ret_ok(ret) else -1
def smi_get_device_pci_replay_counter(dev):
"""return PCIe replay counter of the device"""
counter = c_uint64()
ret = rocm_lib.rsmi_dev_pci_replay_counter_get(dev, byref(counter))
return counter.value if rsmi_ret_ok(ret) else -1
# Compute partition functions
def smi_get_device_compute_partition(dev):
"""returns the compute partition of the device"""
partition = create_string_buffer(RSMI_MAX_BUFFER_LENGTH)
ret = rocm_lib.rsmi_dev_compute_partition_get(dev, byref(partition), RSMI_MAX_BUFFER_LENGTH)
return partition.value.decode() if rsmi_ret_ok(ret) else ''
def smi_set_device_compute_partition(dev, partition):
"""modifies the compute partition of the selected device"""
ret = rocm_lib.rsmi_dev_compute_partition_set(dev, partition)
return rsmi_ret_ok(ret)
def smi_reset_device_compute_partition(dev):
"""reverts the compute partition of the selected device to its boot state"""
ret = rocm_lib.rsmi_dev_compute_partition_reset(dev)
return rsmi_ret_ok(ret)
# Memory partition functions
def smi_get_device_memory_partition(dev):
"""returns the memory partition of the device"""
partition = create_string_buffer(RSMI_MAX_BUFFER_LENGTH)
ret = rocm_lib.rsmi_dev_memory_partition_get(dev, byref(partition), RSMI_MAX_BUFFER_LENGTH)
return partition.value.decode() if rsmi_ret_ok(ret) else ''
def smi_set_device_memory_partition(dev, partition):
"""modifies the memory partition of the selected device"""
ret = rocm_lib.rsmi_dev_memory_partition_set(dev, partition)
return rsmi_ret_ok(ret)
def smi_reset_device_memory_partition(dev):
"""reverts the memory partition of the selected device to its boot state"""
ret = rocm_lib.rsmi_dev_memory_partition_reset(dev)
return rsmi_ret_ok(ret)
# Hardware Topology functions
def smi_get_device_topo_numa_node_number(dev):
"""returns the NUMA node associated with the device"""
numa_node = c_uint32()
ret = rocm_lib.rsmi_topo_get_numa_node_number(dev, byref(numa_node))
return numa_node.value if rsmi_ret_ok(ret) else -1
def smi_get_device_topo_link_weight(dev_src, dev_dst):
"""returns the weight of the link between two devices"""
weight = c_uint64()
ret = rocm_lib.rsmi_topo_get_link_weight(dev_src, dev_dst, byref(weight))
return weight.value if rsmi_ret_ok(ret) else -1
def smi_get_device_minmax_bandwidth(dev_src, dev_dst):
"""returns the minimum and maximum io link bandwidth between two devices
API works if src and dst are connected via XGMI and are 1 hop away.
"""
assert smi_get_device_link_type(dev_src, dev_dst)[0] == 1, 'Devices must be 1 hop away'
min_bandwidth = c_uint64()
max_bandwidth = c_uint64()
ret = rocm_lib.rsmi_minmax_bandwidth_get(dev_src, dev_dst, byref(min_bandwidth), byref(max_bandwidth))
return (min_bandwidth.value, max_bandwidth.value) if rsmi_ret_ok(ret) else -1
def smi_get_device_link_type(dev_src, dev_dst):
"""returns the hops and the type of link between two devices"""
hops = c_uint64()
link_type = rsmi_io_link_type()
ret = rocm_lib.rsmi_topo_get_link_type(dev_src, dev_dst, byref(hops), byref(link_type))
return (hops.value, link_type.value) if rsmi_ret_ok(ret) else -1
def smi_is_device_p2p_accessible(dev_src, dev_dst):
"""returns true if two devices are p2p accessible"""
accessible = c_bool()
ret = rocm_lib.rsmi_is_P2P_accessible(dev_src, dev_dst, byref(accessible))
return accessible.value if rsmi_ret_ok(ret) else -1
def smi_get_device_compute_process():
"""returns list of process ids running compute on the system"""
num_procs = c_uint32()
ret = rocm_lib.rsmi_compute_process_info_get(None, byref(num_procs))
if rsmi_ret_ok(ret):
buff_sz = num_procs.value + 10
proc_info = (rsmi_process_info_t * buff_sz)()
ret2 = rocm_lib.rsmi_compute_process_info_get(byref(proc_info), byref(num_procs))
return [proc_info[i].process_id for i in range(num_procs.value)] if rsmi_ret_ok(ret2) else []
else:
return []
def smi_get_compute_process_info_by_device(device_id: int, proc_ids: list) -> list:
"""Returns list of process info running compute on the specified device by process IDs.
Args:
device_id: The device index to query
proc_ids: List of process IDs to get info for
Returns:
List of process info structures for the specified device and process IDs
"""
proc_infos = []
for proc_id in proc_ids:
proc_info = rsmi_process_info_t()
ret = rocm_lib.rsmi_compute_process_info_by_device_get(proc_id, device_id, byref(proc_info))
if rsmi_ret_ok(ret):
proc_infos.append(proc_info)
return proc_infos
def smi_get_device_average_power(dev):
"""returns average power of device_id dev"""
power = c_uint32()
ret = rocm_lib.rsmi_dev_power_ave_get(dev, 0, byref(power))
return power.value * 1e-6 if rsmi_ret_ok(ret) else -1
# XGMI fuctions
def smi_get_device_xgmi_error_status(dev):
"""returns XGMI error status for a device"""
status = rsmi_xgmi_status_t()
ret = rocm_lib.rsmi_dev_xgmi_error_status(dev, byref(status))
return status.value if rsmi_ret_ok(ret) else -1
def smi_reset_device_xgmi_error(dev):
"""resets XGMI error status for a device"""
ret = rocm_lib.rsmi_dev_xgmi_error_reset(dev)
return rsmi_ret_ok(ret)
def smi_get_device_xgmi_hive_id(dev):
"""returns XGMI hive ID for a device"""
hive_id = c_uint64()
ret = rocm_lib.rsmi_dev_xgmi_hive_id_get(dev, byref(hive_id))
return hive_id.value if rsmi_ret_ok(ret) else -1
| rsmi_io_link_type |
python | vyperlang__vyper | vyper/venom/passes/dft.py | {
"start": 426,
"end": 7689
} | class ____(IRPass):
function: IRFunction
data_offspring: dict[IRInstruction, OrderedSet[IRInstruction]]
visited_instructions: OrderedSet[IRInstruction]
# "data dependency analysis"
dda: dict[IRInstruction, OrderedSet[IRInstruction]]
# "effect dependency analysis"
eda: dict[IRInstruction, OrderedSet[IRInstruction]]
stack_order: StackOrderAnalysis
cfg: CFGAnalysis
def run_pass(self) -> None:
self.data_offspring = {}
self.visited_instructions: OrderedSet[IRInstruction] = OrderedSet()
self.dfg = self.analyses_cache.force_analysis(DFGAnalysis)
self.cfg = self.analyses_cache.request_analysis(CFGAnalysis)
self.stack_order = StackOrderAnalysis(self.analyses_cache)
worklist = deque(self.cfg.dfs_post_walk)
last_order: dict[IRBasicBlock, list[IRVariable]] = dict()
while len(worklist) > 0:
bb = worklist.popleft()
self.stack_order.analyze_bb(bb)
order = self.stack_order.get_stack(bb)
if bb in last_order and last_order[bb] == order:
break
last_order[bb] = order
self.order = list(reversed(order))
self._process_basic_block(bb)
for pred in self.cfg.cfg_in(bb):
worklist.append(pred)
self.analyses_cache.invalidate_analysis(LivenessAnalysis)
def _process_basic_block(self, bb: IRBasicBlock) -> None:
self._calculate_dependency_graphs(bb)
self.instructions = list(bb.pseudo_instructions)
non_phi_instructions = list(bb.non_phi_instructions)
self.visited_instructions = OrderedSet()
for inst in bb.instructions:
self._calculate_data_offspring(inst)
# Compute entry points in the graph of instruction dependencies
entry_instructions: OrderedSet[IRInstruction] = OrderedSet(non_phi_instructions)
for inst in non_phi_instructions:
to_remove = self.dda.get(inst, OrderedSet()) | self.eda.get(inst, OrderedSet())
entry_instructions.dropmany(to_remove)
entry_instructions_list = list(entry_instructions)
self.visited_instructions = OrderedSet()
for inst in entry_instructions_list:
self._process_instruction_r(self.instructions, inst)
bb.instructions = self.instructions
assert bb.is_terminated, f"Basic block should be terminated {bb}"
def _process_instruction_r(self, instructions: list[IRInstruction], inst: IRInstruction):
if inst in self.visited_instructions:
return
self.visited_instructions.add(inst)
if inst.is_pseudo:
return
children = list(self.dda[inst] | self.eda[inst])
def cost(x: IRInstruction) -> int | float:
# intuition:
# effect-only dependencies which have data dependencies
# effect-only dependencies which have no data dependencies
# indirect data dependencies (offspring of operands)
# direct data dependencies (order of operands)
is_effect_only = x not in self.dda[inst] and x in self.eda[inst]
if is_effect_only or inst.flippable:
has_data_offspring = len(self.data_offspring[x]) > 0
return -1 if has_data_offspring else 0
assert x in self.dda[inst] # sanity check
# locate operands that are produced by x and prefer earliest match
operand_idxs = [
i
for i, op in enumerate(inst.operands)
if self.dfg.get_producing_instruction(op) is x
]
if len(operand_idxs) > 0:
return min(operand_idxs) + len(self.order)
outputs = x.get_outputs()
operand_positions = [
inst.operands.index(out_var) for out_var in outputs if out_var in inst.operands
]
if len(operand_positions) > 0:
return min(operand_positions) + len(self.order)
order_positions = [
self.order.index(out_var) for out_var in outputs if out_var in self.order
]
if len(order_positions) > 0:
return min(order_positions)
# fall back to a stable default when no operand is associated
return len(self.order)
# heuristic: sort by size of child dependency graph
orig_children = children.copy()
children.sort(key=cost)
if inst.flippable and (orig_children != children):
inst.flip()
for dep_inst in children:
self._process_instruction_r(instructions, dep_inst)
instructions.append(inst)
def _calculate_dependency_graphs(self, bb: IRBasicBlock) -> None:
# ida: instruction dependency analysis
self.dda = defaultdict(OrderedSet)
self.eda = defaultdict(OrderedSet)
non_phis = list(bb.non_phi_instructions)
#
# Compute dependency graph
#
last_write_effects: dict[effects.Effects, IRInstruction] = {}
all_read_effects: dict[effects.Effects, list[IRInstruction]] = defaultdict(list)
for inst in non_phis:
if inst.is_bb_terminator:
for var in self.order:
dep = self.dfg.get_producing_instruction(var)
if dep is not None and dep.parent == bb:
self.dda[inst].add(dep)
for op in inst.operands:
dep = self.dfg.get_producing_instruction(op)
if dep is not None and dep.parent == bb:
self.dda[inst].add(dep)
write_effects = inst.get_write_effects()
read_effects = inst.get_read_effects()
for write_effect in write_effects:
# ALL reads must happen before this write
if write_effect in all_read_effects:
for read_inst in all_read_effects[write_effect]:
self.eda[inst].add(read_inst)
# prevent reordering write-after-write for the same effect
if (write_effect & ~effects.Effects.MSIZE) in last_write_effects:
self.eda[inst].add(last_write_effects[write_effect])
last_write_effects[write_effect] = inst
# clear previous read effects after a write
if write_effect in all_read_effects:
all_read_effects[write_effect] = []
for read_effect in read_effects:
if read_effect in last_write_effects and last_write_effects[read_effect] != inst:
self.eda[inst].add(last_write_effects[read_effect])
all_read_effects[read_effect].append(inst)
def _calculate_data_offspring(self, inst: IRInstruction):
if inst in self.data_offspring:
return self.data_offspring[inst]
self.data_offspring[inst] = self.dda[inst].copy()
deps = self.dda[inst]
for dep_inst in deps:
assert inst.parent == dep_inst.parent
res = self._calculate_data_offspring(dep_inst)
self.data_offspring[inst] |= res
return self.data_offspring[inst]
| DFTPass |
python | getsentry__sentry-python | tests/integrations/langchain/test_langchain.py | {
"start": 1411,
"end": 61377
} | class ____(ChatOpenAI):
def _stream(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> Iterator[ChatGenerationChunk]:
for x in stream_result_mock():
yield x
@property
def _llm_type(self) -> str:
return llm_type
@pytest.mark.parametrize(
"send_default_pii, include_prompts, use_unknown_llm_type",
[
(True, True, False),
(True, False, False),
(False, True, False),
(False, False, True),
],
)
def test_langchain_agent(
sentry_init, capture_events, send_default_pii, include_prompts, use_unknown_llm_type
):
global llm_type
llm_type = "acme-llm" if use_unknown_llm_type else "openai-chat"
sentry_init(
integrations=[
LangchainIntegration(
include_prompts=include_prompts,
)
],
traces_sample_rate=1.0,
send_default_pii=send_default_pii,
)
events = capture_events()
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are very powerful assistant, but don't know current events",
),
("user", "{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
]
)
global stream_result_mock
stream_result_mock = Mock(
side_effect=[
[
ChatGenerationChunk(
type="ChatGenerationChunk",
message=AIMessageChunk(
content="",
additional_kwargs={
"tool_calls": [
{
"index": 0,
"id": "call_BbeyNhCKa6kYLYzrD40NGm3b",
"function": {
"arguments": "",
"name": "get_word_length",
},
"type": "function",
}
]
},
),
),
ChatGenerationChunk(
type="ChatGenerationChunk",
message=AIMessageChunk(
content="",
additional_kwargs={
"tool_calls": [
{
"index": 0,
"id": None,
"function": {
"arguments": '{"word": "eudca"}',
"name": None,
},
"type": None,
}
]
},
),
),
ChatGenerationChunk(
type="ChatGenerationChunk",
message=AIMessageChunk(
content="5",
usage_metadata={
"input_tokens": 142,
"output_tokens": 50,
"total_tokens": 192,
"input_token_details": {"audio": 0, "cache_read": 0},
"output_token_details": {"audio": 0, "reasoning": 0},
},
),
generation_info={"finish_reason": "function_call"},
),
],
[
ChatGenerationChunk(
text="The word eudca has 5 letters.",
type="ChatGenerationChunk",
message=AIMessageChunk(
content="The word eudca has 5 letters.",
usage_metadata={
"input_tokens": 89,
"output_tokens": 28,
"total_tokens": 117,
"input_token_details": {"audio": 0, "cache_read": 0},
"output_token_details": {"audio": 0, "reasoning": 0},
},
),
),
ChatGenerationChunk(
type="ChatGenerationChunk",
generation_info={"finish_reason": "stop"},
message=AIMessageChunk(content=""),
),
],
]
)
llm = MockOpenAI(
model_name="gpt-3.5-turbo",
temperature=0,
openai_api_key="badkey",
)
agent = create_openai_tools_agent(llm, [get_word_length], prompt)
agent_executor = AgentExecutor(agent=agent, tools=[get_word_length], verbose=True)
with start_transaction():
list(agent_executor.stream({"input": "How many letters in the word eudca"}))
tx = events[0]
assert tx["type"] == "transaction"
chat_spans = list(x for x in tx["spans"] if x["op"] == "gen_ai.chat")
tool_exec_span = next(x for x in tx["spans"] if x["op"] == "gen_ai.execute_tool")
assert len(chat_spans) == 2
# We can't guarantee anything about the "shape" of the langchain execution graph
assert len(list(x for x in tx["spans"] if x["op"] == "gen_ai.chat")) > 0
# Token usage is only available in newer versions of langchain (v0.2+)
# where usage_metadata is supported on AIMessageChunk
if "gen_ai.usage.input_tokens" in chat_spans[0]["data"]:
assert chat_spans[0]["data"]["gen_ai.usage.input_tokens"] == 142
assert chat_spans[0]["data"]["gen_ai.usage.output_tokens"] == 50
assert chat_spans[0]["data"]["gen_ai.usage.total_tokens"] == 192
if "gen_ai.usage.input_tokens" in chat_spans[1]["data"]:
assert chat_spans[1]["data"]["gen_ai.usage.input_tokens"] == 89
assert chat_spans[1]["data"]["gen_ai.usage.output_tokens"] == 28
assert chat_spans[1]["data"]["gen_ai.usage.total_tokens"] == 117
if send_default_pii and include_prompts:
assert (
"You are very powerful"
in chat_spans[0]["data"][SPANDATA.GEN_AI_REQUEST_MESSAGES]
)
assert "5" in chat_spans[0]["data"][SPANDATA.GEN_AI_RESPONSE_TEXT]
assert "word" in tool_exec_span["data"][SPANDATA.GEN_AI_TOOL_INPUT]
assert 5 == int(tool_exec_span["data"][SPANDATA.GEN_AI_TOOL_OUTPUT])
assert (
"You are very powerful"
in chat_spans[1]["data"][SPANDATA.GEN_AI_REQUEST_MESSAGES]
)
assert "5" in chat_spans[1]["data"][SPANDATA.GEN_AI_RESPONSE_TEXT]
# Verify tool calls are recorded when PII is enabled
assert SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS in chat_spans[0].get("data", {}), (
"Tool calls should be recorded when send_default_pii=True and include_prompts=True"
)
tool_calls_data = chat_spans[0]["data"][SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS]
assert isinstance(tool_calls_data, (list, str)) # Could be serialized
if isinstance(tool_calls_data, str):
assert "get_word_length" in tool_calls_data
elif isinstance(tool_calls_data, list) and len(tool_calls_data) > 0:
# Check if tool calls contain expected function name
tool_call_str = str(tool_calls_data)
assert "get_word_length" in tool_call_str
else:
assert SPANDATA.GEN_AI_REQUEST_MESSAGES not in chat_spans[0].get("data", {})
assert SPANDATA.GEN_AI_RESPONSE_TEXT not in chat_spans[0].get("data", {})
assert SPANDATA.GEN_AI_REQUEST_MESSAGES not in chat_spans[1].get("data", {})
assert SPANDATA.GEN_AI_RESPONSE_TEXT not in chat_spans[1].get("data", {})
assert SPANDATA.GEN_AI_TOOL_INPUT not in tool_exec_span.get("data", {})
assert SPANDATA.GEN_AI_TOOL_OUTPUT not in tool_exec_span.get("data", {})
# Verify tool calls are NOT recorded when PII is disabled
assert SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS not in chat_spans[0].get(
"data", {}
), (
f"Tool calls should NOT be recorded when send_default_pii={send_default_pii} "
f"and include_prompts={include_prompts}"
)
assert SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS not in chat_spans[1].get(
"data", {}
), (
f"Tool calls should NOT be recorded when send_default_pii={send_default_pii} "
f"and include_prompts={include_prompts}"
)
# Verify that available tools are always recorded regardless of PII settings
for chat_span in chat_spans:
span_data = chat_span.get("data", {})
if SPANDATA.GEN_AI_REQUEST_AVAILABLE_TOOLS in span_data:
tools_data = span_data[SPANDATA.GEN_AI_REQUEST_AVAILABLE_TOOLS]
assert tools_data is not None, (
"Available tools should always be recorded regardless of PII settings"
)
def test_langchain_error(sentry_init, capture_events):
sentry_init(
integrations=[LangchainIntegration(include_prompts=True)],
traces_sample_rate=1.0,
send_default_pii=True,
)
events = capture_events()
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are very powerful assistant, but don't know current events",
),
("user", "{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
]
)
global stream_result_mock
stream_result_mock = Mock(side_effect=ValueError("API rate limit error"))
llm = MockOpenAI(
model_name="gpt-3.5-turbo",
temperature=0,
openai_api_key="badkey",
)
agent = create_openai_tools_agent(llm, [get_word_length], prompt)
agent_executor = AgentExecutor(agent=agent, tools=[get_word_length], verbose=True)
with start_transaction(), pytest.raises(ValueError):
list(agent_executor.stream({"input": "How many letters in the word eudca"}))
error = events[0]
assert error["level"] == "error"
def test_span_status_error(sentry_init, capture_events):
global llm_type
llm_type = "acme-llm"
sentry_init(
integrations=[LangchainIntegration(include_prompts=True)],
traces_sample_rate=1.0,
)
events = capture_events()
with start_transaction(name="test"):
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are very powerful assistant, but don't know current events",
),
("user", "{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
]
)
global stream_result_mock
stream_result_mock = Mock(side_effect=ValueError("API rate limit error"))
llm = MockOpenAI(
model_name="gpt-3.5-turbo",
temperature=0,
openai_api_key="badkey",
)
agent = create_openai_tools_agent(llm, [get_word_length], prompt)
agent_executor = AgentExecutor(
agent=agent, tools=[get_word_length], verbose=True
)
with pytest.raises(ValueError):
list(agent_executor.stream({"input": "How many letters in the word eudca"}))
(error, transaction) = events
assert error["level"] == "error"
assert transaction["spans"][0]["status"] == "internal_error"
assert transaction["spans"][0]["tags"]["status"] == "internal_error"
assert transaction["contexts"]["trace"]["status"] == "internal_error"
def test_span_origin(sentry_init, capture_events):
sentry_init(
integrations=[LangchainIntegration()],
traces_sample_rate=1.0,
)
events = capture_events()
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are very powerful assistant, but don't know current events",
),
("user", "{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
]
)
global stream_result_mock
stream_result_mock = Mock(
side_effect=[
[
ChatGenerationChunk(
type="ChatGenerationChunk",
message=AIMessageChunk(
content="",
additional_kwargs={
"tool_calls": [
{
"index": 0,
"id": "call_BbeyNhCKa6kYLYzrD40NGm3b",
"function": {
"arguments": "",
"name": "get_word_length",
},
"type": "function",
}
]
},
),
),
ChatGenerationChunk(
type="ChatGenerationChunk",
message=AIMessageChunk(
content="",
additional_kwargs={
"tool_calls": [
{
"index": 0,
"id": None,
"function": {
"arguments": '{"word": "eudca"}',
"name": None,
},
"type": None,
}
]
},
),
),
ChatGenerationChunk(
type="ChatGenerationChunk",
message=AIMessageChunk(
content="5",
usage_metadata={
"input_tokens": 142,
"output_tokens": 50,
"total_tokens": 192,
"input_token_details": {"audio": 0, "cache_read": 0},
"output_token_details": {"audio": 0, "reasoning": 0},
},
),
generation_info={"finish_reason": "function_call"},
),
],
[
ChatGenerationChunk(
text="The word eudca has 5 letters.",
type="ChatGenerationChunk",
message=AIMessageChunk(
content="The word eudca has 5 letters.",
usage_metadata={
"input_tokens": 89,
"output_tokens": 28,
"total_tokens": 117,
"input_token_details": {"audio": 0, "cache_read": 0},
"output_token_details": {"audio": 0, "reasoning": 0},
},
),
),
ChatGenerationChunk(
type="ChatGenerationChunk",
generation_info={"finish_reason": "stop"},
message=AIMessageChunk(content=""),
),
],
]
)
llm = MockOpenAI(
model_name="gpt-3.5-turbo",
temperature=0,
openai_api_key="badkey",
)
agent = create_openai_tools_agent(llm, [get_word_length], prompt)
agent_executor = AgentExecutor(agent=agent, tools=[get_word_length], verbose=True)
with start_transaction():
list(agent_executor.stream({"input": "How many letters in the word eudca"}))
(event,) = events
assert event["contexts"]["trace"]["origin"] == "manual"
for span in event["spans"]:
assert span["origin"] == "auto.ai.langchain"
def test_manual_callback_no_duplication(sentry_init):
"""
Test that when a user manually provides a SentryLangchainCallback,
the integration doesn't create a duplicate callback.
"""
# Track callback instances
tracked_callback_instances = set()
class CallbackTrackingModel(BaseChatModel):
"""Mock model that tracks callback instances for testing."""
def _generate(
self,
messages,
stop=None,
run_manager=None,
**kwargs,
):
# Track all SentryLangchainCallback instances
if run_manager:
for handler in run_manager.handlers:
if isinstance(handler, SentryLangchainCallback):
tracked_callback_instances.add(id(handler))
for handler in run_manager.inheritable_handlers:
if isinstance(handler, SentryLangchainCallback):
tracked_callback_instances.add(id(handler))
return ChatResult(
generations=[
ChatGenerationChunk(message=AIMessageChunk(content="Hello!"))
],
llm_output={},
)
@property
def _llm_type(self):
return "test_model"
@property
def _identifying_params(self):
return {}
sentry_init(integrations=[LangchainIntegration()])
# Create a manual SentryLangchainCallback
manual_callback = SentryLangchainCallback(
max_span_map_size=100, include_prompts=False
)
# Create RunnableConfig with the manual callback
config = RunnableConfig(callbacks=[manual_callback])
# Invoke the model with the config
llm = CallbackTrackingModel()
llm.invoke("Hello", config)
# Verify that only ONE SentryLangchainCallback instance was used
assert len(tracked_callback_instances) == 1, (
f"Expected exactly 1 SentryLangchainCallback instance, "
f"but found {len(tracked_callback_instances)}. "
f"This indicates callback duplication occurred."
)
# Verify the callback ID matches our manual callback
assert id(manual_callback) in tracked_callback_instances
def test_span_map_is_instance_variable():
"""Test that each SentryLangchainCallback instance has its own span_map."""
# Create two separate callback instances
callback1 = SentryLangchainCallback(max_span_map_size=100, include_prompts=True)
callback2 = SentryLangchainCallback(max_span_map_size=100, include_prompts=True)
# Verify they have different span_map instances
assert callback1.span_map is not callback2.span_map, (
"span_map should be an instance variable, not shared between instances"
)
def test_langchain_callback_manager(sentry_init):
sentry_init(
integrations=[LangchainIntegration()],
traces_sample_rate=1.0,
)
local_manager = BaseCallbackManager(handlers=[])
with mock.patch("sentry_sdk.integrations.langchain.manager") as mock_manager_module:
mock_configure = mock_manager_module._configure
# Explicitly re-run setup_once, so that mock_manager_module._configure gets patched
LangchainIntegration.setup_once()
callback_manager_cls = Mock()
mock_manager_module._configure(
callback_manager_cls, local_callbacks=local_manager
)
assert mock_configure.call_count == 1
call_args = mock_configure.call_args
assert call_args.args[0] is callback_manager_cls
passed_manager = call_args.args[2]
assert passed_manager is not local_manager
assert local_manager.handlers == []
[handler] = passed_manager.handlers
assert isinstance(handler, SentryLangchainCallback)
def test_langchain_callback_manager_with_sentry_callback(sentry_init):
sentry_init(
integrations=[LangchainIntegration()],
traces_sample_rate=1.0,
)
sentry_callback = SentryLangchainCallback(0, False)
local_manager = BaseCallbackManager(handlers=[sentry_callback])
with mock.patch("sentry_sdk.integrations.langchain.manager") as mock_manager_module:
mock_configure = mock_manager_module._configure
# Explicitly re-run setup_once, so that mock_manager_module._configure gets patched
LangchainIntegration.setup_once()
callback_manager_cls = Mock()
mock_manager_module._configure(
callback_manager_cls, local_callbacks=local_manager
)
assert mock_configure.call_count == 1
call_args = mock_configure.call_args
assert call_args.args[0] is callback_manager_cls
passed_manager = call_args.args[2]
assert passed_manager is local_manager
[handler] = passed_manager.handlers
assert handler is sentry_callback
def test_langchain_callback_list(sentry_init):
sentry_init(
integrations=[LangchainIntegration()],
traces_sample_rate=1.0,
)
local_callbacks = []
with mock.patch("sentry_sdk.integrations.langchain.manager") as mock_manager_module:
mock_configure = mock_manager_module._configure
# Explicitly re-run setup_once, so that mock_manager_module._configure gets patched
LangchainIntegration.setup_once()
callback_manager_cls = Mock()
mock_manager_module._configure(
callback_manager_cls, local_callbacks=local_callbacks
)
assert mock_configure.call_count == 1
call_args = mock_configure.call_args
assert call_args.args[0] is callback_manager_cls
passed_callbacks = call_args.args[2]
assert passed_callbacks is not local_callbacks
assert local_callbacks == []
[handler] = passed_callbacks
assert isinstance(handler, SentryLangchainCallback)
def test_langchain_callback_list_existing_callback(sentry_init):
sentry_init(
integrations=[LangchainIntegration()],
traces_sample_rate=1.0,
)
sentry_callback = SentryLangchainCallback(0, False)
local_callbacks = [sentry_callback]
with mock.patch("sentry_sdk.integrations.langchain.manager") as mock_manager_module:
mock_configure = mock_manager_module._configure
# Explicitly re-run setup_once, so that mock_manager_module._configure gets patched
LangchainIntegration.setup_once()
callback_manager_cls = Mock()
mock_manager_module._configure(
callback_manager_cls, local_callbacks=local_callbacks
)
assert mock_configure.call_count == 1
call_args = mock_configure.call_args
assert call_args.args[0] is callback_manager_cls
passed_callbacks = call_args.args[2]
assert passed_callbacks is local_callbacks
[handler] = passed_callbacks
assert handler is sentry_callback
def test_tools_integration_in_spans(sentry_init, capture_events):
"""Test that tools are properly set on spans in actual LangChain integration."""
global llm_type
llm_type = "openai-chat"
sentry_init(
integrations=[LangchainIntegration(include_prompts=False)],
traces_sample_rate=1.0,
)
events = capture_events()
prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a helpful assistant"),
("user", "{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
]
)
global stream_result_mock
stream_result_mock = Mock(
side_effect=[
[
ChatGenerationChunk(
type="ChatGenerationChunk",
message=AIMessageChunk(content="Simple response"),
),
]
]
)
llm = MockOpenAI(
model_name="gpt-3.5-turbo",
temperature=0,
openai_api_key="badkey",
)
agent = create_openai_tools_agent(llm, [get_word_length], prompt)
agent_executor = AgentExecutor(agent=agent, tools=[get_word_length], verbose=True)
with start_transaction():
list(agent_executor.stream({"input": "Hello"}))
# Check that events were captured and contain tools data
if events:
tx = events[0]
spans = tx.get("spans", [])
# Look for spans that should have tools data
tools_found = False
for span in spans:
span_data = span.get("data", {})
if SPANDATA.GEN_AI_REQUEST_AVAILABLE_TOOLS in span_data:
tools_found = True
tools_data = span_data[SPANDATA.GEN_AI_REQUEST_AVAILABLE_TOOLS]
# Verify tools are in the expected format
assert isinstance(tools_data, (str, list)) # Could be serialized
if isinstance(tools_data, str):
# If serialized as string, should contain tool name
assert "get_word_length" in tools_data
else:
# If still a list, verify structure
assert len(tools_data) >= 1
names = [
tool.get("name")
for tool in tools_data
if isinstance(tool, dict)
]
assert "get_word_length" in names
# Ensure we found at least one span with tools data
assert tools_found, "No spans found with tools data"
def test_langchain_integration_with_langchain_core_only(sentry_init, capture_events):
"""Test that the langchain integration works when langchain.agents.AgentExecutor
is not available or langchain is not installed, but langchain-core is.
"""
from langchain_core.outputs import LLMResult, Generation
with patch("sentry_sdk.integrations.langchain.AgentExecutor", None):
from sentry_sdk.integrations.langchain import (
LangchainIntegration,
SentryLangchainCallback,
)
sentry_init(
integrations=[LangchainIntegration(include_prompts=True)],
traces_sample_rate=1.0,
send_default_pii=True,
)
events = capture_events()
try:
LangchainIntegration.setup_once()
except Exception as e:
pytest.fail(f"setup_once() failed when AgentExecutor is None: {e}")
callback = SentryLangchainCallback(max_span_map_size=100, include_prompts=True)
run_id = "12345678-1234-1234-1234-123456789012"
serialized = {"_type": "openai-chat", "model_name": "gpt-3.5-turbo"}
prompts = ["What is the capital of France?"]
with start_transaction():
callback.on_llm_start(
serialized=serialized,
prompts=prompts,
run_id=run_id,
invocation_params={
"temperature": 0.7,
"max_tokens": 100,
"model": "gpt-3.5-turbo",
},
)
response = LLMResult(
generations=[[Generation(text="The capital of France is Paris.")]],
llm_output={
"token_usage": {
"total_tokens": 25,
"prompt_tokens": 10,
"completion_tokens": 15,
}
},
)
callback.on_llm_end(response=response, run_id=run_id)
assert len(events) > 0
tx = events[0]
assert tx["type"] == "transaction"
llm_spans = [
span for span in tx.get("spans", []) if span.get("op") == "gen_ai.pipeline"
]
assert len(llm_spans) > 0
llm_span = llm_spans[0]
assert llm_span["description"] == "Langchain LLM call"
assert llm_span["data"]["gen_ai.request.model"] == "gpt-3.5-turbo"
assert (
llm_span["data"]["gen_ai.response.text"]
== "The capital of France is Paris."
)
assert llm_span["data"]["gen_ai.usage.total_tokens"] == 25
assert llm_span["data"]["gen_ai.usage.input_tokens"] == 10
assert llm_span["data"]["gen_ai.usage.output_tokens"] == 15
def test_langchain_message_role_mapping(sentry_init, capture_events):
"""Test that message roles are properly normalized in langchain integration."""
global llm_type
llm_type = "openai-chat"
sentry_init(
integrations=[LangchainIntegration(include_prompts=True)],
traces_sample_rate=1.0,
send_default_pii=True,
)
events = capture_events()
prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a helpful assistant"),
("human", "{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
]
)
global stream_result_mock
stream_result_mock = Mock(
side_effect=[
[
ChatGenerationChunk(
type="ChatGenerationChunk",
message=AIMessageChunk(content="Test response"),
),
]
]
)
llm = MockOpenAI(
model_name="gpt-3.5-turbo",
temperature=0,
openai_api_key="badkey",
)
agent = create_openai_tools_agent(llm, [get_word_length], prompt)
agent_executor = AgentExecutor(agent=agent, tools=[get_word_length], verbose=True)
# Test input that should trigger message role normalization
test_input = "Hello, how are you?"
with start_transaction():
list(agent_executor.stream({"input": test_input}))
assert len(events) > 0
tx = events[0]
assert tx["type"] == "transaction"
# Find spans with gen_ai operation that should have message data
gen_ai_spans = [
span for span in tx.get("spans", []) if span.get("op", "").startswith("gen_ai")
]
# Check if any span has message data with normalized roles
message_data_found = False
for span in gen_ai_spans:
span_data = span.get("data", {})
if SPANDATA.GEN_AI_REQUEST_MESSAGES in span_data:
message_data_found = True
messages_data = span_data[SPANDATA.GEN_AI_REQUEST_MESSAGES]
# Parse the message data (might be JSON string)
if isinstance(messages_data, str):
try:
messages = json.loads(messages_data)
except json.JSONDecodeError:
# If not valid JSON, skip this assertion
continue
else:
messages = messages_data
# Verify that the input message is present and contains the test input
assert isinstance(messages, list)
assert len(messages) > 0
# The test input should be in one of the messages
input_found = False
for msg in messages:
if isinstance(msg, dict) and test_input in str(msg.get("content", "")):
input_found = True
break
elif isinstance(msg, str) and test_input in msg:
input_found = True
break
assert input_found, (
f"Test input '{test_input}' not found in messages: {messages}"
)
break
# The message role mapping functionality is primarily tested through the normalization
# that happens in the integration code. The fact that we can capture and process
# the messages without errors indicates the role mapping is working correctly.
assert message_data_found, "No span found with gen_ai request messages data"
def test_langchain_message_role_normalization_units():
"""Test the message role normalization functions directly."""
from sentry_sdk.ai.utils import normalize_message_role, normalize_message_roles
# Test individual role normalization
assert normalize_message_role("ai") == "assistant"
assert normalize_message_role("human") == "user"
assert normalize_message_role("tool_call") == "tool"
assert normalize_message_role("system") == "system"
assert normalize_message_role("user") == "user"
assert normalize_message_role("assistant") == "assistant"
assert normalize_message_role("tool") == "tool"
# Test unknown role (should remain unchanged)
assert normalize_message_role("unknown_role") == "unknown_role"
# Test message list normalization
test_messages = [
{"role": "human", "content": "Hello"},
{"role": "ai", "content": "Hi there!"},
{"role": "tool_call", "content": "function_call"},
{"role": "system", "content": "You are helpful"},
{"content": "Message without role"},
"string message",
]
normalized = normalize_message_roles(test_messages)
# Verify the original messages are not modified
assert test_messages[0]["role"] == "human" # Original unchanged
assert test_messages[1]["role"] == "ai" # Original unchanged
# Verify the normalized messages have correct roles
assert normalized[0]["role"] == "user" # human -> user
assert normalized[1]["role"] == "assistant" # ai -> assistant
assert normalized[2]["role"] == "tool" # tool_call -> tool
assert normalized[3]["role"] == "system" # system unchanged
assert "role" not in normalized[4] # Message without role unchanged
assert normalized[5] == "string message" # String message unchanged
def test_langchain_message_truncation(sentry_init, capture_events):
"""Test that large messages are truncated properly in Langchain integration."""
from langchain_core.outputs import LLMResult, Generation
sentry_init(
integrations=[LangchainIntegration(include_prompts=True)],
traces_sample_rate=1.0,
send_default_pii=True,
)
events = capture_events()
callback = SentryLangchainCallback(max_span_map_size=100, include_prompts=True)
run_id = "12345678-1234-1234-1234-123456789012"
serialized = {"_type": "openai-chat", "model_name": "gpt-3.5-turbo"}
large_content = (
"This is a very long message that will exceed our size limits. " * 1000
)
prompts = [
"small message 1",
large_content,
large_content,
"small message 4",
"small message 5",
]
with start_transaction():
callback.on_llm_start(
serialized=serialized,
prompts=prompts,
run_id=run_id,
invocation_params={
"temperature": 0.7,
"max_tokens": 100,
"model": "gpt-3.5-turbo",
},
)
response = LLMResult(
generations=[[Generation(text="The response")]],
llm_output={
"token_usage": {
"total_tokens": 25,
"prompt_tokens": 10,
"completion_tokens": 15,
}
},
)
callback.on_llm_end(response=response, run_id=run_id)
assert len(events) > 0
tx = events[0]
assert tx["type"] == "transaction"
llm_spans = [
span for span in tx.get("spans", []) if span.get("op") == "gen_ai.pipeline"
]
assert len(llm_spans) > 0
llm_span = llm_spans[0]
assert SPANDATA.GEN_AI_REQUEST_MESSAGES in llm_span["data"]
messages_data = llm_span["data"][SPANDATA.GEN_AI_REQUEST_MESSAGES]
assert isinstance(messages_data, str)
parsed_messages = json.loads(messages_data)
assert isinstance(parsed_messages, list)
assert len(parsed_messages) == 2
assert "small message 4" in str(parsed_messages[0])
assert "small message 5" in str(parsed_messages[1])
assert tx["_meta"]["spans"]["0"]["data"]["gen_ai.request.messages"][""]["len"] == 5
@pytest.mark.parametrize(
"send_default_pii, include_prompts",
[
(True, True),
(True, False),
(False, True),
(False, False),
],
)
def test_langchain_embeddings_sync(
sentry_init, capture_events, send_default_pii, include_prompts
):
"""Test that sync embedding methods (embed_documents, embed_query) are properly traced."""
try:
from langchain_openai import OpenAIEmbeddings
except ImportError:
pytest.skip("langchain_openai not installed")
sentry_init(
integrations=[LangchainIntegration(include_prompts=include_prompts)],
traces_sample_rate=1.0,
send_default_pii=send_default_pii,
)
events = capture_events()
# Mock the actual API call
with mock.patch.object(
OpenAIEmbeddings,
"embed_documents",
wraps=lambda self, texts: [[0.1, 0.2, 0.3] for _ in texts],
) as mock_embed_documents:
embeddings = OpenAIEmbeddings(
model="text-embedding-ada-002", openai_api_key="test-key"
)
# Force setup to re-run to ensure our mock is wrapped
LangchainIntegration.setup_once()
with start_transaction(name="test_embeddings"):
# Test embed_documents
result = embeddings.embed_documents(["Hello world", "Test document"])
assert len(result) == 2
mock_embed_documents.assert_called_once()
# Check captured events
assert len(events) >= 1
tx = events[0]
assert tx["type"] == "transaction"
# Find embeddings span
embeddings_spans = [
span for span in tx.get("spans", []) if span.get("op") == "gen_ai.embeddings"
]
assert len(embeddings_spans) == 1
embeddings_span = embeddings_spans[0]
assert embeddings_span["description"] == "embeddings text-embedding-ada-002"
assert embeddings_span["origin"] == "auto.ai.langchain"
assert embeddings_span["data"]["gen_ai.operation.name"] == "embeddings"
assert embeddings_span["data"]["gen_ai.request.model"] == "text-embedding-ada-002"
# Check if input is captured based on PII settings
if send_default_pii and include_prompts:
assert SPANDATA.GEN_AI_EMBEDDINGS_INPUT in embeddings_span["data"]
input_data = embeddings_span["data"][SPANDATA.GEN_AI_EMBEDDINGS_INPUT]
# Could be serialized as string
if isinstance(input_data, str):
assert "Hello world" in input_data
assert "Test document" in input_data
else:
assert "Hello world" in input_data
assert "Test document" in input_data
else:
assert SPANDATA.GEN_AI_EMBEDDINGS_INPUT not in embeddings_span.get("data", {})
@pytest.mark.parametrize(
"send_default_pii, include_prompts",
[
(True, True),
(False, False),
],
)
def test_langchain_embeddings_embed_query(
sentry_init, capture_events, send_default_pii, include_prompts
):
"""Test that embed_query method is properly traced."""
try:
from langchain_openai import OpenAIEmbeddings
except ImportError:
pytest.skip("langchain_openai not installed")
sentry_init(
integrations=[LangchainIntegration(include_prompts=include_prompts)],
traces_sample_rate=1.0,
send_default_pii=send_default_pii,
)
events = capture_events()
# Mock the actual API call
with mock.patch.object(
OpenAIEmbeddings,
"embed_query",
wraps=lambda self, text: [0.1, 0.2, 0.3],
) as mock_embed_query:
embeddings = OpenAIEmbeddings(
model="text-embedding-ada-002", openai_api_key="test-key"
)
# Force setup to re-run to ensure our mock is wrapped
LangchainIntegration.setup_once()
with start_transaction(name="test_embeddings_query"):
result = embeddings.embed_query("What is the capital of France?")
assert len(result) == 3
mock_embed_query.assert_called_once()
# Check captured events
assert len(events) >= 1
tx = events[0]
assert tx["type"] == "transaction"
# Find embeddings span
embeddings_spans = [
span for span in tx.get("spans", []) if span.get("op") == "gen_ai.embeddings"
]
assert len(embeddings_spans) == 1
embeddings_span = embeddings_spans[0]
assert embeddings_span["data"]["gen_ai.operation.name"] == "embeddings"
assert embeddings_span["data"]["gen_ai.request.model"] == "text-embedding-ada-002"
# Check if input is captured based on PII settings
if send_default_pii and include_prompts:
assert SPANDATA.GEN_AI_EMBEDDINGS_INPUT in embeddings_span["data"]
input_data = embeddings_span["data"][SPANDATA.GEN_AI_EMBEDDINGS_INPUT]
# Could be serialized as string
if isinstance(input_data, str):
assert "What is the capital of France?" in input_data
else:
assert "What is the capital of France?" in input_data
else:
assert SPANDATA.GEN_AI_EMBEDDINGS_INPUT not in embeddings_span.get("data", {})
@pytest.mark.parametrize(
"send_default_pii, include_prompts",
[
(True, True),
(False, False),
],
)
@pytest.mark.asyncio
async def test_langchain_embeddings_async(
sentry_init, capture_events, send_default_pii, include_prompts
):
"""Test that async embedding methods (aembed_documents, aembed_query) are properly traced."""
try:
from langchain_openai import OpenAIEmbeddings
except ImportError:
pytest.skip("langchain_openai not installed")
sentry_init(
integrations=[LangchainIntegration(include_prompts=include_prompts)],
traces_sample_rate=1.0,
send_default_pii=send_default_pii,
)
events = capture_events()
async def mock_aembed_documents(self, texts):
return [[0.1, 0.2, 0.3] for _ in texts]
# Mock the actual API call
with mock.patch.object(
OpenAIEmbeddings,
"aembed_documents",
wraps=mock_aembed_documents,
) as mock_aembed:
embeddings = OpenAIEmbeddings(
model="text-embedding-ada-002", openai_api_key="test-key"
)
# Force setup to re-run to ensure our mock is wrapped
LangchainIntegration.setup_once()
with start_transaction(name="test_async_embeddings"):
result = await embeddings.aembed_documents(
["Async hello", "Async test document"]
)
assert len(result) == 2
mock_aembed.assert_called_once()
# Check captured events
assert len(events) >= 1
tx = events[0]
assert tx["type"] == "transaction"
# Find embeddings span
embeddings_spans = [
span for span in tx.get("spans", []) if span.get("op") == "gen_ai.embeddings"
]
assert len(embeddings_spans) == 1
embeddings_span = embeddings_spans[0]
assert embeddings_span["description"] == "embeddings text-embedding-ada-002"
assert embeddings_span["origin"] == "auto.ai.langchain"
assert embeddings_span["data"]["gen_ai.operation.name"] == "embeddings"
assert embeddings_span["data"]["gen_ai.request.model"] == "text-embedding-ada-002"
# Check if input is captured based on PII settings
if send_default_pii and include_prompts:
assert SPANDATA.GEN_AI_EMBEDDINGS_INPUT in embeddings_span["data"]
input_data = embeddings_span["data"][SPANDATA.GEN_AI_EMBEDDINGS_INPUT]
# Could be serialized as string
if isinstance(input_data, str):
assert "Async hello" in input_data or "Async test document" in input_data
else:
assert "Async hello" in input_data or "Async test document" in input_data
else:
assert SPANDATA.GEN_AI_EMBEDDINGS_INPUT not in embeddings_span.get("data", {})
@pytest.mark.asyncio
async def test_langchain_embeddings_aembed_query(sentry_init, capture_events):
"""Test that aembed_query method is properly traced."""
try:
from langchain_openai import OpenAIEmbeddings
except ImportError:
pytest.skip("langchain_openai not installed")
sentry_init(
integrations=[LangchainIntegration(include_prompts=True)],
traces_sample_rate=1.0,
send_default_pii=True,
)
events = capture_events()
async def mock_aembed_query(self, text):
return [0.1, 0.2, 0.3]
# Mock the actual API call
with mock.patch.object(
OpenAIEmbeddings,
"aembed_query",
wraps=mock_aembed_query,
) as mock_aembed:
embeddings = OpenAIEmbeddings(
model="text-embedding-ada-002", openai_api_key="test-key"
)
# Force setup to re-run to ensure our mock is wrapped
LangchainIntegration.setup_once()
with start_transaction(name="test_async_embeddings_query"):
result = await embeddings.aembed_query("Async query test")
assert len(result) == 3
mock_aembed.assert_called_once()
# Check captured events
assert len(events) >= 1
tx = events[0]
assert tx["type"] == "transaction"
# Find embeddings span
embeddings_spans = [
span for span in tx.get("spans", []) if span.get("op") == "gen_ai.embeddings"
]
assert len(embeddings_spans) == 1
embeddings_span = embeddings_spans[0]
assert embeddings_span["data"]["gen_ai.operation.name"] == "embeddings"
assert embeddings_span["data"]["gen_ai.request.model"] == "text-embedding-ada-002"
# Check if input is captured
assert SPANDATA.GEN_AI_EMBEDDINGS_INPUT in embeddings_span["data"]
input_data = embeddings_span["data"][SPANDATA.GEN_AI_EMBEDDINGS_INPUT]
# Could be serialized as string
if isinstance(input_data, str):
assert "Async query test" in input_data
else:
assert "Async query test" in input_data
def test_langchain_embeddings_no_model_name(sentry_init, capture_events):
"""Test embeddings when model name is not available."""
try:
from langchain_openai import OpenAIEmbeddings
except ImportError:
pytest.skip("langchain_openai not installed")
sentry_init(
integrations=[LangchainIntegration(include_prompts=False)],
traces_sample_rate=1.0,
)
events = capture_events()
# Mock the actual API call and remove model attribute
with mock.patch.object(
OpenAIEmbeddings,
"embed_documents",
wraps=lambda self, texts: [[0.1, 0.2, 0.3] for _ in texts],
):
embeddings = OpenAIEmbeddings(openai_api_key="test-key")
# Remove model attribute to test fallback
delattr(embeddings, "model")
if hasattr(embeddings, "model_name"):
delattr(embeddings, "model_name")
# Force setup to re-run to ensure our mock is wrapped
LangchainIntegration.setup_once()
with start_transaction(name="test_embeddings_no_model"):
embeddings.embed_documents(["Test"])
# Check captured events
assert len(events) >= 1
tx = events[0]
assert tx["type"] == "transaction"
# Find embeddings span
embeddings_spans = [
span for span in tx.get("spans", []) if span.get("op") == "gen_ai.embeddings"
]
assert len(embeddings_spans) == 1
embeddings_span = embeddings_spans[0]
assert embeddings_span["description"] == "embeddings"
assert embeddings_span["data"]["gen_ai.operation.name"] == "embeddings"
# Model name should not be set if not available
assert (
"gen_ai.request.model" not in embeddings_span["data"]
or embeddings_span["data"]["gen_ai.request.model"] is None
)
def test_langchain_embeddings_integration_disabled(sentry_init, capture_events):
"""Test that embeddings are not traced when integration is disabled."""
try:
from langchain_openai import OpenAIEmbeddings
except ImportError:
pytest.skip("langchain_openai not installed")
# Initialize without LangchainIntegration
sentry_init(traces_sample_rate=1.0)
events = capture_events()
with mock.patch.object(
OpenAIEmbeddings,
"embed_documents",
return_value=[[0.1, 0.2, 0.3]],
):
embeddings = OpenAIEmbeddings(
model="text-embedding-ada-002", openai_api_key="test-key"
)
with start_transaction(name="test_embeddings_disabled"):
embeddings.embed_documents(["Test"])
# Check that no embeddings spans were created
if events:
tx = events[0]
embeddings_spans = [
span
for span in tx.get("spans", [])
if span.get("op") == "gen_ai.embeddings"
]
# Should be empty since integration is disabled
assert len(embeddings_spans) == 0
def test_langchain_embeddings_multiple_providers(sentry_init, capture_events):
"""Test that embeddings work with different providers."""
try:
from langchain_openai import OpenAIEmbeddings, AzureOpenAIEmbeddings
except ImportError:
pytest.skip("langchain_openai not installed")
sentry_init(
integrations=[LangchainIntegration(include_prompts=True)],
traces_sample_rate=1.0,
send_default_pii=True,
)
events = capture_events()
# Mock both providers
with mock.patch.object(
OpenAIEmbeddings,
"embed_documents",
wraps=lambda self, texts: [[0.1, 0.2, 0.3] for _ in texts],
), mock.patch.object(
AzureOpenAIEmbeddings,
"embed_documents",
wraps=lambda self, texts: [[0.4, 0.5, 0.6] for _ in texts],
):
openai_embeddings = OpenAIEmbeddings(
model="text-embedding-ada-002", openai_api_key="test-key"
)
azure_embeddings = AzureOpenAIEmbeddings(
model="text-embedding-ada-002",
azure_endpoint="https://test.openai.azure.com/",
openai_api_key="test-key",
)
# Force setup to re-run
LangchainIntegration.setup_once()
with start_transaction(name="test_multiple_providers"):
openai_embeddings.embed_documents(["OpenAI test"])
azure_embeddings.embed_documents(["Azure test"])
# Check captured events
assert len(events) >= 1
tx = events[0]
assert tx["type"] == "transaction"
# Find embeddings spans
embeddings_spans = [
span for span in tx.get("spans", []) if span.get("op") == "gen_ai.embeddings"
]
# Should have 2 spans, one for each provider
assert len(embeddings_spans) == 2
# Verify both spans have proper data
for span in embeddings_spans:
assert span["data"]["gen_ai.operation.name"] == "embeddings"
assert span["data"]["gen_ai.request.model"] == "text-embedding-ada-002"
assert SPANDATA.GEN_AI_EMBEDDINGS_INPUT in span["data"]
def test_langchain_embeddings_error_handling(sentry_init, capture_events):
"""Test that errors in embeddings are properly captured."""
try:
from langchain_openai import OpenAIEmbeddings
except ImportError:
pytest.skip("langchain_openai not installed")
sentry_init(
integrations=[LangchainIntegration(include_prompts=True)],
traces_sample_rate=1.0,
send_default_pii=True,
)
events = capture_events()
# Mock the API call to raise an error
with mock.patch.object(
OpenAIEmbeddings,
"embed_documents",
side_effect=ValueError("API error"),
):
embeddings = OpenAIEmbeddings(
model="text-embedding-ada-002", openai_api_key="test-key"
)
# Force setup to re-run
LangchainIntegration.setup_once()
with start_transaction(name="test_embeddings_error"):
with pytest.raises(ValueError):
embeddings.embed_documents(["Test"])
# The error should be captured
assert len(events) >= 1
# We should have both the transaction and potentially an error event
[e for e in events if e.get("level") == "error"]
# Note: errors might not be auto-captured depending on SDK settings,
# but the span should still be created
def test_langchain_embeddings_multiple_calls(sentry_init, capture_events):
"""Test that multiple embeddings calls within a transaction are all traced."""
try:
from langchain_openai import OpenAIEmbeddings
except ImportError:
pytest.skip("langchain_openai not installed")
sentry_init(
integrations=[LangchainIntegration(include_prompts=True)],
traces_sample_rate=1.0,
send_default_pii=True,
)
events = capture_events()
# Mock the actual API calls
with mock.patch.object(
OpenAIEmbeddings,
"embed_documents",
wraps=lambda self, texts: [[0.1, 0.2, 0.3] for _ in texts],
), mock.patch.object(
OpenAIEmbeddings,
"embed_query",
wraps=lambda self, text: [0.4, 0.5, 0.6],
):
embeddings = OpenAIEmbeddings(
model="text-embedding-ada-002", openai_api_key="test-key"
)
# Force setup to re-run
LangchainIntegration.setup_once()
with start_transaction(name="test_multiple_embeddings"):
# Call embed_documents
embeddings.embed_documents(["First batch", "Second batch"])
# Call embed_query
embeddings.embed_query("Single query")
# Call embed_documents again
embeddings.embed_documents(["Third batch"])
# Check captured events
assert len(events) >= 1
tx = events[0]
assert tx["type"] == "transaction"
# Find embeddings spans - should have 3 (2 embed_documents + 1 embed_query)
embeddings_spans = [
span for span in tx.get("spans", []) if span.get("op") == "gen_ai.embeddings"
]
assert len(embeddings_spans) == 3
# Verify all spans have proper data
for span in embeddings_spans:
assert span["data"]["gen_ai.operation.name"] == "embeddings"
assert span["data"]["gen_ai.request.model"] == "text-embedding-ada-002"
assert SPANDATA.GEN_AI_EMBEDDINGS_INPUT in span["data"]
# Verify the input data is different for each span
input_data_list = [
span["data"][SPANDATA.GEN_AI_EMBEDDINGS_INPUT] for span in embeddings_spans
]
# They should all be different (different inputs)
assert len(set(str(data) for data in input_data_list)) == 3
def test_langchain_embeddings_span_hierarchy(sentry_init, capture_events):
"""Test that embeddings spans are properly nested within parent spans."""
try:
from langchain_openai import OpenAIEmbeddings
except ImportError:
pytest.skip("langchain_openai not installed")
sentry_init(
integrations=[LangchainIntegration(include_prompts=True)],
traces_sample_rate=1.0,
send_default_pii=True,
)
events = capture_events()
# Mock the actual API call
with mock.patch.object(
OpenAIEmbeddings,
"embed_documents",
wraps=lambda self, texts: [[0.1, 0.2, 0.3] for _ in texts],
):
embeddings = OpenAIEmbeddings(
model="text-embedding-ada-002", openai_api_key="test-key"
)
# Force setup to re-run
LangchainIntegration.setup_once()
with start_transaction(name="test_span_hierarchy"):
with sentry_sdk.start_span(op="custom", name="custom operation"):
embeddings.embed_documents(["Test within custom span"])
# Check captured events
assert len(events) >= 1
tx = events[0]
assert tx["type"] == "transaction"
# Find all spans
embeddings_spans = [
span for span in tx.get("spans", []) if span.get("op") == "gen_ai.embeddings"
]
custom_spans = [span for span in tx.get("spans", []) if span.get("op") == "custom"]
assert len(embeddings_spans) == 1
assert len(custom_spans) == 1
# Both spans should exist
embeddings_span = embeddings_spans[0]
custom_span = custom_spans[0]
assert embeddings_span["data"]["gen_ai.operation.name"] == "embeddings"
assert custom_span["description"] == "custom operation"
def test_langchain_embeddings_with_list_and_string_inputs(sentry_init, capture_events):
"""Test that embeddings correctly handle both list and string inputs."""
try:
from langchain_openai import OpenAIEmbeddings
except ImportError:
pytest.skip("langchain_openai not installed")
sentry_init(
integrations=[LangchainIntegration(include_prompts=True)],
traces_sample_rate=1.0,
send_default_pii=True,
)
events = capture_events()
# Mock the actual API calls
with mock.patch.object(
OpenAIEmbeddings,
"embed_documents",
wraps=lambda self, texts: [[0.1, 0.2, 0.3] for _ in texts],
), mock.patch.object(
OpenAIEmbeddings,
"embed_query",
wraps=lambda self, text: [0.4, 0.5, 0.6],
):
embeddings = OpenAIEmbeddings(
model="text-embedding-ada-002", openai_api_key="test-key"
)
# Force setup to re-run
LangchainIntegration.setup_once()
with start_transaction(name="test_input_types"):
# embed_documents takes a list
embeddings.embed_documents(["List item 1", "List item 2", "List item 3"])
# embed_query takes a string
embeddings.embed_query("Single string query")
# Check captured events
assert len(events) >= 1
tx = events[0]
assert tx["type"] == "transaction"
# Find embeddings spans
embeddings_spans = [
span for span in tx.get("spans", []) if span.get("op") == "gen_ai.embeddings"
]
assert len(embeddings_spans) == 2
# Both should have input data captured as lists
for span in embeddings_spans:
assert SPANDATA.GEN_AI_EMBEDDINGS_INPUT in span["data"]
input_data = span["data"][SPANDATA.GEN_AI_EMBEDDINGS_INPUT]
# Input should be normalized to list format
if isinstance(input_data, str):
# If serialized, should contain the input text
assert "List item" in input_data or "Single string query" in input_data, (
f"Expected input text in serialized data: {input_data}"
)
@pytest.mark.parametrize(
"response_metadata_model,expected_model",
[
("gpt-3.5-turbo", "gpt-3.5-turbo"),
(None, None),
],
)
def test_langchain_response_model_extraction(
sentry_init,
capture_events,
response_metadata_model,
expected_model,
):
sentry_init(
integrations=[LangchainIntegration(include_prompts=True)],
traces_sample_rate=1.0,
send_default_pii=True,
)
events = capture_events()
callback = SentryLangchainCallback(max_span_map_size=100, include_prompts=True)
run_id = "test-response-model-uuid"
serialized = {"_type": "openai-chat", "model_name": "gpt-3.5-turbo"}
prompts = ["Test prompt"]
with start_transaction():
callback.on_llm_start(
serialized=serialized,
prompts=prompts,
run_id=run_id,
invocation_params={"model": "gpt-3.5-turbo"},
)
response_metadata = {"model_name": response_metadata_model}
message = AIMessageChunk(
content="Test response", response_metadata=response_metadata
)
generation = Mock(text="Test response", message=message)
response = Mock(generations=[[generation]])
callback.on_llm_end(response=response, run_id=run_id)
assert len(events) > 0
tx = events[0]
assert tx["type"] == "transaction"
llm_spans = [
span for span in tx.get("spans", []) if span.get("op") == "gen_ai.pipeline"
]
assert len(llm_spans) > 0
llm_span = llm_spans[0]
if expected_model is not None:
assert SPANDATA.GEN_AI_RESPONSE_MODEL in llm_span["data"]
assert llm_span["data"][SPANDATA.GEN_AI_RESPONSE_MODEL] == expected_model
else:
assert SPANDATA.GEN_AI_RESPONSE_MODEL not in llm_span.get("data", {})
| MockOpenAI |
python | openai__openai-python | src/openai/types/realtime/input_audio_buffer_timeout_triggered.py | {
"start": 209,
"end": 853
} | class ____(BaseModel):
audio_end_ms: int
"""
Millisecond offset of audio written to the input audio buffer at the time the
timeout was triggered.
"""
audio_start_ms: int
"""
Millisecond offset of audio written to the input audio buffer that was after the
playback time of the last model response.
"""
event_id: str
"""The unique ID of the server event."""
item_id: str
"""The ID of the item associated with this segment."""
type: Literal["input_audio_buffer.timeout_triggered"]
"""The event type, must be `input_audio_buffer.timeout_triggered`."""
| InputAudioBufferTimeoutTriggered |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-firebolt/destination_firebolt/writer.py | {
"start": 311,
"end": 2523
} | class ____:
"""
Base class for shared writer logic.
"""
flush_interval = 1000
def __init__(self, connection: Connection) -> None:
"""
:param connection: Firebolt SDK connection class with established connection
to the databse.
"""
self.connection = connection
self._buffer = defaultdict(list)
self._values = 0
def delete_table(self, name: str) -> None:
"""
Delete the resulting table.
Primarily used in Overwrite strategy to clean up previous data.
:param name: table name to delete.
"""
cursor = self.connection.cursor()
cursor.execute(f"DROP TABLE IF EXISTS _airbyte_raw_{name}")
def create_raw_table(self, name: str):
"""
Create the resulting _airbyte_raw table.
:param name: table name to create.
"""
query = f"""
CREATE FACT TABLE IF NOT EXISTS _airbyte_raw_{name} (
_airbyte_ab_id TEXT,
_airbyte_emitted_at TIMESTAMP,
_airbyte_data TEXT
)
PRIMARY INDEX _airbyte_ab_id
"""
cursor = self.connection.cursor()
cursor.execute(query)
def queue_write_data(self, stream_name: str, id: str, time: datetime, record: str) -> None:
"""
Queue up data in a buffer in memory before writing to the database.
When flush_interval is reached data is persisted.
:param stream_name: name of the stream for which the data corresponds.
:param id: unique identifier of this data row.
:param time: time of writing.
:param record: string representation of the json data payload.
"""
self._buffer[stream_name].append((id, time, record))
self._values += 1
if self._values == self.flush_interval:
self._flush()
def _flush(self):
"""
Stub for the intermediate data flush that's triggered during the
buffering operation.
"""
raise NotImplementedError()
def flush(self):
"""
Stub for the data flush at the end of writing operation.
"""
raise NotImplementedError()
| FireboltWriter |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/control_flow/py_func_test.py | {
"start": 2906,
"end": 16744
} | class ____(PyFuncTestBase):
"""Encapsulates tests for py_func only."""
def testRealDataTypes(self):
def sum_func(x, y):
return x + y
for dtype in [dtypes.float16, dtypes.float32, dtypes.float64,
dtypes.uint8, dtypes.int8, dtypes.uint16, dtypes.int16,
dtypes.int32, dtypes.int64]:
with self.cached_session():
x = constant_op.constant(1, dtype=dtype)
y = constant_op.constant(2, dtype=dtype)
z = self.evaluate(script_ops.py_func(sum_func, [x, y], dtype))
self.assertEqual(z, 3)
def testComplexDataTypes(self):
def sub_func(x, y):
return x - y
for dtype in [dtypes.complex64, dtypes.complex128]:
with self.cached_session():
x = constant_op.constant(1 + 1j, dtype=dtype)
y = constant_op.constant(2 - 2j, dtype=dtype)
z = self.evaluate(script_ops.py_func(sub_func, [x, y], dtype))
self.assertEqual(z, -1 + 3j)
def testBoolDataTypes(self):
def and_func(x, y):
return x and y
dtype = dtypes.bool
with self.cached_session():
x = constant_op.constant(True, dtype=dtype)
y = constant_op.constant(False, dtype=dtype)
z = self.evaluate(script_ops.py_func(and_func, [x, y], dtype))
self.assertEqual(z, False)
def testSingleType(self):
with self.cached_session():
x = constant_op.constant(1.0, dtypes.float32)
y = constant_op.constant(2.0, dtypes.float32)
z = self.evaluate(script_ops.py_func(np_func, [x, y], dtypes.float32))
self.assertEqual(z, np_func(1.0, 2.0).astype(np.float32))
def testScalar(self):
with self.cached_session():
x = constant_op.constant(1.0, dtypes.float32)
y = constant_op.constant(2.0, dtypes.float32)
z = self.evaluate(
script_ops.eager_py_func(np_func, [x, y], [dtypes.float32]))
self.assertEqual(z[0], np_func(1.0, 2.0).astype(np.float32))
@test_util.run_v1_only("b/120545219")
def testArray(self):
with self.cached_session():
x = constant_op.constant([1.0, 2.0], dtypes.float64)
y = constant_op.constant([2.0, 3.0], dtypes.float64)
z = self.evaluate(script_ops.py_func(np_func, [x, y], [dtypes.float64]))
self.assertAllEqual(z[0],
np_func([1.0, 2.0], [2.0, 3.0]).astype(np.float64))
def testComplexType(self):
with self.cached_session():
x = constant_op.constant(1 + 2j, dtypes.complex64)
y = constant_op.constant(3 + 4j, dtypes.complex64)
z = self.evaluate(script_ops.py_func(np_func, [x, y], dtypes.complex64))
self.assertAllClose(z, np_func(1 + 2j, 3 + 4j))
def testRFFT(self):
with self.cached_session():
x = constant_op.constant([1., 2., 3., 4.], dtypes.float32)
def rfft(x):
return np.fft.rfft(x).astype(np.complex64)
y = self.evaluate(script_ops.py_func(rfft, [x], dtypes.complex64))
self.assertAllClose(y, np.fft.rfft([1., 2., 3., 4.]))
def testPythonLiteral(self):
with self.cached_session():
def literal(x):
return 1.0 if float(x) == 0.0 else 0.0
x = constant_op.constant(0.0, dtypes.float64)
y = self.evaluate(script_ops.py_func(literal, [x], dtypes.float64))
self.assertAllClose(y, 1.0)
def testList(self):
with self.cached_session():
def list_func(x):
return [x, x + 1]
x = constant_op.constant(0.0, dtypes.float64)
y = self.evaluate(
script_ops.py_func(list_func, [x], [dtypes.float64] * 2))
self.assertAllClose(y, [0.0, 1.0])
def testTuple(self):
# returns a tuple
with self.cached_session():
def tuple_func(x):
return x, x + 1
x = constant_op.constant(0.0, dtypes.float64)
y = self.evaluate(
script_ops.py_func(tuple_func, [x], [dtypes.float64] * 2))
self.assertAllClose(y, [0.0, 1.0])
# returns a tuple, Tout and inp a tuple
with self.cached_session():
x = constant_op.constant(0.0, dtypes.float64)
y = self.evaluate(
script_ops.py_func(tuple_func, (x,),
(dtypes.float64, dtypes.float64)))
self.assertAllClose(y, [0.0, 1.0])
@test_util.run_v1_only("b/120545219")
def testStrings(self):
def read_fixed_length_numpy_strings():
return np.array([b" there"])
def read_and_return_strings(x, y):
return x + y
with self.cached_session():
x = constant_op.constant([b"hello", b"hi"], dtypes.string)
y = self.evaluate(
script_ops.py_func(read_fixed_length_numpy_strings, [],
dtypes.string))
z = self.evaluate(
script_ops.py_func(read_and_return_strings, [x, y], dtypes.string))
self.assertAllEqual(z, [b"hello there", b"hi there"])
@test_util.run_v1_only("b/120545219")
def testStringsAreConvertedToBytes(self):
def read_fixed_length_numpy_strings():
return np.array([" there"])
def read_and_return_strings(x, y):
return x + y
with self.cached_session():
x = constant_op.constant(["hello", "hi"], dtypes.string)
y = self.evaluate(
script_ops.py_func(read_fixed_length_numpy_strings, [],
dtypes.string))
z = self.evaluate(
script_ops.py_func(read_and_return_strings, [x, y], dtypes.string))
self.assertAllEqual(z, [b"hello there", b"hi there"])
@test_util.run_v1_only("b/120545219")
def testObjectArraysAreConvertedToBytes(self):
def read_object_array():
return np.array([b" there", u" ya"], dtype=np.object_)
def read_and_return_strings(x, y):
return x + y
with self.cached_session():
x = constant_op.constant(["hello", "hi"], dtypes.string)
y, = script_ops.py_func(read_object_array, [],
[dtypes.string])
z, = script_ops.py_func(read_and_return_strings, [x, y], [dtypes.string])
self.assertListEqual(list(self.evaluate(z)), [b"hello there", b"hi ya"])
@test_util.run_v1_only("b/120545219")
def testStringPadding(self):
correct = [b"this", b"is", b"a", b"test"]
with self.cached_session():
s, = script_ops.py_func(lambda: [correct], [], [dtypes.string])
self.assertAllEqual(s, correct)
@test_util.run_v1_only("b/120545219")
def testStringPaddingAreConvertedToBytes(self):
inp = ["this", "is", "a", "test"]
correct = [b"this", b"is", b"a", b"test"]
with self.cached_session():
s, = script_ops.py_func(lambda: [inp], [], [dtypes.string])
self.assertAllEqual(s, correct)
@test_util.run_v1_only("b/120545219")
def testNulTerminatedStrings(self):
inp = np.array(["this\0", "is\0\0", "a\0", "test\0\0"], dtype=np.str_)
correct = [b"this", b"is", b"a", b"test"]
with self.cached_session():
s, = script_ops.py_func(lambda: [inp], [], [dtypes.string])
self.assertAllEqual(s, correct)
@test_util.run_v1_only("b/120545219")
def testLarge(self):
with self.cached_session() as sess:
x = array_ops.zeros([1000000], dtype=np.float32)
y = script_ops.py_func(lambda x: x + 1, [x], [dtypes.float32])
z = script_ops.py_func(lambda x: x * 2, [x], [dtypes.float32])
for _ in range(100):
sess.run([y[0].op, z[0].op])
def testNoInput(self):
with self.cached_session():
x = self.evaluate(script_ops.py_func(lambda: 42.0, [], dtypes.float64))
self.assertAllClose(x, 42.0)
@test_util.run_v1_only("b/120545219")
def testAlias(self):
with self.cached_session():
np_array = np.array([1.0, 2.0], dtype=np.float32)
tf_array = script_ops.py_func(lambda: np_array, [], [dtypes.float32])
value = tf_array + constant_op.constant([2.0, 3.0], dtype=dtypes.float32)
value.op.run()
self.assertAllEqual(np_array, [1.0, 2.0])
@test_util.run_v1_only("b/120545219")
def testReturnUnicodeString(self):
with self.cached_session():
correct = u"你好 世界"
def unicode_string():
return correct
z, = script_ops.py_func(unicode_string, [], [dtypes.string])
self.assertEqual(self.evaluate(z), correct.encode("utf8"))
@test_util.run_v1_only("b/120545219")
def testBadNumpyReturnType(self):
with self.cached_session():
def bad():
# Structured numpy arrays aren't supported.
return np.array([], dtype=[("foo", np.float32)])
y, = script_ops.py_func(bad, [], [dtypes.float32])
with self.assertRaisesRegex(errors.InternalError,
"Unsupported numpy data type"):
self.evaluate(y)
@test_util.run_v1_only("b/120545219")
def testBadReturnType(self):
with self.cached_session():
def bad():
# Non-string python objects aren't supported.
return {"foo": dtypes.float32}
z, = script_ops.py_func(bad, [], [dtypes.int64])
with self.assertRaisesRegex(errors.InternalError,
"Unsupported object type"):
self.evaluate(z)
@test_util.run_v1_only("b/120545219")
def testReturnInput(self):
with self.cached_session():
def ident(x):
return x[0]
p = array_ops.placeholder(dtypes.float32)
# Create a numpy array aliasing a tensor and a tensor aliasing this array
z, = script_ops.py_func(ident, [p], [dtypes.float32])
z += 0.0 # Makes sure we release the tensor aliasing the numpy array x[0]
# above instead of using its memory as the return value of
# session.run
self.assertEqual(0.0, z.eval(feed_dict={p: [0.0]}))
def testStateful(self):
# Not using self.cached_session(), which disables optimization.
with session_lib.Session():
producer = iter(range(3))
x, = script_ops.py_func(lambda: next(producer), [], [dtypes.int64])
self.assertEqual(self.evaluate(x), 0)
self.assertEqual(self.evaluate(x), 1)
self.assertEqual(self.evaluate(x), 2)
@test_util.enable_tf_xla_constant_folding("b/134376434")
def testStateless(self):
# Not using self.cached_session(), which disables optimization.
with session_lib.Session():
producer = iter(range(3))
x, = script_ops.py_func(
lambda: next(producer), [], [dtypes.int64], stateful=False)
self.assertEqual(self.evaluate(x), 0)
self.assertEqual(self.evaluate(x), 0)
self.assertEqual(self.evaluate(x), 0)
@test_util.run_v1_only("b/120545219")
def testGradientFunction(self):
# Input to tf.compat.v1.py_func is necessary,
# otherwise get_gradient_function() returns None per default.
a = constant_op.constant(0)
x, = script_ops.py_func(lambda a: 0, [a], [dtypes.int64])
y, = script_ops.py_func(lambda a: 0, [a], [dtypes.int64], stateful=False)
self.assertEqual(None, ops.get_gradient_function(x.op))
self.assertEqual(None, ops.get_gradient_function(y.op))
@test_util.run_v1_only("b/120545219")
def testCOrder(self):
with self.cached_session():
val = [[1, 2], [3, 4]]
x, = script_ops.py_func(lambda: np.array(val, order="F"), [],
[dtypes.int64])
self.assertAllEqual(val, self.evaluate(x))
@test_util.run_v1_only("b/120545219")
def testParallel(self):
# Tests that tf.compat.v1.py_func's can run in parallel if they release
# the GIL.
with self.cached_session() as session:
q = queue.Queue(1)
def blocking_put():
q.put(42)
q.join() # Wait for task_done().
return 42
def blocking_get():
v = q.get(block=True) # Wait for put().
q.task_done()
return v
x, = script_ops.py_func(blocking_put, [], [dtypes.int64])
y, = script_ops.py_func(blocking_get, [], [dtypes.int64])
# This will result in a deadlock if the py_func's don't run in parallel.
session.run([x, y])
def testNoReturnValueStateful(self):
class State:
def __init__(self):
self._value = np.array([1], np.int64)
def _increment(self, diff):
self._value += diff
def increment(self, diff):
return script_ops.py_func(self._increment, [diff], [], stateful=True)
@property
def value(self):
return self._value
with self.cached_session():
s = State()
op = s.increment(constant_op.constant(2, dtypes.int64))
ret = self.evaluate(op)
self.assertIsNone(ret)
self.assertAllEqual([3], s.value)
@test_util.run_v1_only("b/120545219")
def testNoReturnValueStateless(self):
def do_nothing(unused_x):
pass
f = script_ops.py_func(
do_nothing, [constant_op.constant(3, dtypes.int64)], [], stateful=False)
with self.cached_session():
self.assertEqual(self.evaluate(f), [])
@test_util.run_v1_only("b/120545219")
def testExceptionHandling(self):
with self.cached_session():
self.verifyExceptionHandling(ValueError, errors.InvalidArgumentError)
self.verifyExceptionHandling(TypeError, errors.InvalidArgumentError)
self.verifyExceptionHandling(StopIteration, errors.OutOfRangeError)
self.verifyExceptionHandling(MemoryError, errors.ResourceExhaustedError)
self.verifyExceptionHandling(NotImplementedError,
errors.UnimplementedError)
class WeirdError(Exception):
pass
self.verifyExceptionHandling(WeirdError, errors.UnknownError)
def testFunctionReferencesAreKept(self):
g = ops.Graph()
with g.as_default():
c = constant_op.constant([1.], dtypes.float32)
@batch_ops.batch_function(1, 10, 100000)
def fn(x):
# Upon exiting this function, the py_func holds the sole reference
# to this lambda, without which it would be garbage collected.
return script_ops.py_func(lambda x: x, [x], [dtypes.float32])
result = fn(c)
gc.collect()
self.evaluate(result)
| PyFuncTest |
python | OmkarPathak__pygorithm | tests/test_data_structure.py | {
"start": 788,
"end": 1226
} | class ____(unittest.TestCase):
def test_infix_to_postfix(self):
myExp = 'a+b*(c^d-e)^(f+g*h)-i'
myExp = [i for i in myExp]
myStack = stack.Stack(len(myExp)) # create a stack
result = stack.InfixToPostfix(myExp, myStack)
resultString = result.infix_to_postfix()
expectedResult = 'a b c d ^ e - f g h * + ^ * + i -'
self.assertTrue(resultString, expectedResult)
| TestInfixToPostfix |
python | vyperlang__vyper | vyper/builtins/functions.py | {
"start": 87351,
"end": 87569
} | class ____(ABIEncode):
_id = "_abi_encode"
def _try_fold(self, node):
vyper_warn(f"`{self._id}()` is deprecated! Please use `{super()._id}()` instead.", node)
super()._try_fold(node)
| OldABIEncode |
python | huggingface__transformers | src/transformers/models/mobilevitv2/modeling_mobilevitv2.py | {
"start": 20998,
"end": 23882
} | class ____(MobileViTV2PreTrainedModel):
def __init__(self, config: MobileViTV2Config, expand_output: bool = True):
r"""
expand_output (`bool`, *optional*, defaults to `True`):
Whether to expand the output of the model. If `True`, the model will output pooled features in addition to
hidden states. If `False`, only the hidden states will be returned.
"""
super().__init__(config)
self.config = config
self.expand_output = expand_output
layer_0_dim = make_divisible(
clip(value=32 * config.width_multiplier, min_val=16, max_val=64), divisor=8, min_value=16
)
self.conv_stem = MobileViTV2ConvLayer(
config,
in_channels=config.num_channels,
out_channels=layer_0_dim,
kernel_size=3,
stride=2,
use_normalization=True,
use_activation=True,
)
self.encoder = MobileViTV2Encoder(config)
# Initialize weights and apply final processing
self.post_init()
@auto_docstring
def forward(
self,
pixel_values: Optional[torch.Tensor] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if pixel_values is None:
raise ValueError("You have to specify pixel_values")
embedding_output = self.conv_stem(pixel_values)
encoder_outputs = self.encoder(
embedding_output,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
if self.expand_output:
last_hidden_state = encoder_outputs[0]
# global average pooling: (batch_size, channels, height, width) -> (batch_size, channels)
pooled_output = torch.mean(last_hidden_state, dim=[-2, -1], keepdim=False)
else:
last_hidden_state = encoder_outputs[0]
pooled_output = None
if not return_dict:
output = (last_hidden_state, pooled_output) if pooled_output is not None else (last_hidden_state,)
return output + encoder_outputs[1:]
return BaseModelOutputWithPoolingAndNoAttention(
last_hidden_state=last_hidden_state,
pooler_output=pooled_output,
hidden_states=encoder_outputs.hidden_states,
)
@auto_docstring(
custom_intro="""
MobileViTV2 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
ImageNet.
"""
)
| MobileViTV2Model |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 17108,
"end": 17890
} | class ____(WebTestCase):
def get_handlers(self):
self.cleanup_event = Event()
return [("/", ConnectionCloseHandler, dict(test=self))]
def test_connection_close(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
s.connect(("127.0.0.1", self.get_http_port()))
self.stream = IOStream(s)
self.stream.write(b"GET / HTTP/1.0\r\n\r\n")
self.wait()
# Let the hanging coroutine clean up after itself
self.cleanup_event.set()
self.io_loop.run_sync(lambda: gen.sleep(0))
def on_handler_waiting(self):
logging.debug("handler waiting")
self.stream.close()
def on_connection_close(self):
logging.debug("connection closed")
self.stop()
| ConnectionCloseTest |
python | django-haystack__django-haystack | test_haystack/elasticsearch_tests/test_elasticsearch_backend.py | {
"start": 25527,
"end": 27915
} | class ____(TestCase):
def setUp(self):
self.sample_objs = []
for i in range(1, 4):
mock = MockModel()
mock.id = i
mock.author = "daniel%s" % i
mock.pub_date = datetime.date(2009, 2, 25) - datetime.timedelta(days=i)
self.sample_objs.append(mock)
# Stow.
# Point the backend at a URL that doesn't exist so we can watch the
# sparks fly.
self.old_es_url = settings.HAYSTACK_CONNECTIONS["elasticsearch"]["URL"]
settings.HAYSTACK_CONNECTIONS["elasticsearch"]["URL"] = (
"%s/foo/" % self.old_es_url
)
self.cap = CaptureHandler()
logging.getLogger("haystack").addHandler(self.cap)
config = apps.get_app_config("haystack")
logging.getLogger("haystack").removeHandler(config.stream)
# Setup the rest of the bits.
self.old_ui = connections["elasticsearch"].get_unified_index()
ui = UnifiedIndex()
self.smmi = ElasticsearchMockSearchIndex()
ui.build(indexes=[self.smmi])
connections["elasticsearch"]._index = ui
self.sb = connections["elasticsearch"].get_backend()
def tearDown(self):
# Restore.
settings.HAYSTACK_CONNECTIONS["elasticsearch"]["URL"] = self.old_es_url
connections["elasticsearch"]._index = self.old_ui
config = apps.get_app_config("haystack")
logging.getLogger("haystack").removeHandler(self.cap)
logging.getLogger("haystack").addHandler(config.stream)
@unittest.expectedFailure
def test_all_cases(self):
# Prior to the addition of the try/except bits, these would all fail miserably.
self.assertEqual(len(CaptureHandler.logs_seen), 0)
self.sb.update(self.smmi, self.sample_objs)
self.assertEqual(len(CaptureHandler.logs_seen), 1)
self.sb.remove(self.sample_objs[0])
self.assertEqual(len(CaptureHandler.logs_seen), 2)
self.sb.search("search")
self.assertEqual(len(CaptureHandler.logs_seen), 3)
self.sb.more_like_this(self.sample_objs[0])
self.assertEqual(len(CaptureHandler.logs_seen), 4)
self.sb.clear([MockModel])
self.assertEqual(len(CaptureHandler.logs_seen), 5)
self.sb.clear()
self.assertEqual(len(CaptureHandler.logs_seen), 6)
| FailedElasticsearchSearchBackendTestCase |
python | openai__openai-python | src/openai/resources/realtime/realtime.py | {
"start": 33608,
"end": 34704
} | class ____(BaseAsyncRealtimeConnectionResource):
async def update(self, *, session: session_update_event_param.Session, event_id: str | Omit = omit) -> None:
"""
Send this event to update the session’s configuration.
The client may send this event at any time to update any field
except for `voice` and `model`. `voice` can be updated only if there have been no other audio outputs yet.
When the server receives a `session.update`, it will respond
with a `session.updated` event showing the full, effective configuration.
Only the fields that are present in the `session.update` are updated. To clear a field like
`instructions`, pass an empty string. To clear a field like `tools`, pass an empty array.
To clear a field like `turn_detection`, pass `null`.
"""
await self._connection.send(
cast(
RealtimeClientEventParam,
strip_not_given({"type": "session.update", "session": session, "event_id": event_id}),
)
)
| AsyncRealtimeSessionResource |
python | huggingface__transformers | src/transformers/models/glm/modeling_glm.py | {
"start": 22078,
"end": 22179
} | class ____(GenericForSequenceClassification, GlmPreTrainedModel):
pass
| GlmForSequenceClassification |
python | Pylons__pyramid | src/pyramid/authorization.py | {
"start": 1058,
"end": 1233
} | class ____(_ACLDenied):
pass
ALL_PERMISSIONS = AllPermissionsList() # api
DENY_ALL = (Deny, Everyone, ALL_PERMISSIONS) # api
@implementer(IAuthorizationPolicy)
| ACLDenied |
python | explosion__spaCy | spacy/lang/lij/__init__.py | {
"start": 330,
"end": 430
} | class ____(Language):
lang = "lij"
Defaults = LigurianDefaults
__all__ = ["Ligurian"]
| Ligurian |
python | Farama-Foundation__Gymnasium | gymnasium/wrappers/vector/rendering.py | {
"start": 7216,
"end": 20614
} | class ____(
gym.vector.VectorWrapper,
gym.utils.RecordConstructorArgs,
):
"""Adds support for video recording for Vector-based environments.
The class is the same as gymnasium.wrappers.rendering.RecordVideo, but
expects multiple frames when rendering the environment (one for each
environment of the VectorEnv). Frames are concatenated into one frame such
that its aspect ratio is as close as possible to the desired one.
Examples - Run 5 environments for 200 timesteps, and save the video every 5 episodes:
>>> import os
>>> import gymnasium as gym
>>> from gymnasium.wrappers.vector import RecordVideo
>>> envs = gym.make_vec("CartPole-v1", num_envs=5, render_mode="rgb_array")
>>> envs = RecordVideo(
... envs,
... video_folder="save_videos_5envs",
... video_aspect_ratio=(1,1),
... episode_trigger=lambda t: t % 5 == 0,
... )
>>> _ = envs.reset(seed=123)
>>> _ = envs.action_space.seed(123)
>>> for i in range(200):
... actions = envs.action_space.sample()
... _ = envs.step(actions)
>>> envs.close()
>>> len(os.listdir("save_videos_5envs"))
2
"""
def __init__(
self,
env: gym.vector.VectorEnv,
video_folder: str,
video_aspect_ratio: tuple[int, int] = (1, 1),
record_first_only: bool = False,
episode_trigger: Callable[[int], bool] | None = None,
step_trigger: Callable[[int], bool] | None = None,
video_length: int = 0,
name_prefix: str = "rl-video",
fps: int | None = None,
disable_logger: bool = True,
gc_trigger: Callable[[int], bool] | None = lambda episode: True,
):
"""Wrapper records videos of environment rollouts.
Args:
env: The environment that will be wrapped
video_folder (str): The folder where the recordings will be stored
video_aspect_ratio (tuple): the desired aspect ratio of the video concatenating all environments. For example, (1, 1) means an
aspect ratio of 1:1, while (16, 9) means 16:9.
record_first_only (bool): if True, only the first environment is recorded.
episode_trigger: Function that accepts an integer and returns ``True`` iff a recording should be started at this episode
step_trigger: Function that accepts an integer and returns ``True`` iff a recording should be started at this step
video_length (int): The length of recorded episodes. If 0, entire episodes are recorded.
Otherwise, snippets of the specified length are captured
name_prefix (str): Will be prepended to the filename of the recordings
fps (int): The frame per second in the video. Provides a custom video fps for environment, if ``None`` then
the environment metadata ``render_fps`` key is used if it exists, otherwise a default value of 30 is used.
disable_logger (bool): Whether to disable moviepy logger or not, default it is disabled
gc_trigger: Function that accepts an integer and returns ``True`` iff garbage collection should be performed after this episode
Note:
For vector environments that use same-step autoreset (see https://farama.org/Vector-Autoreset-Mode for more details)
then the final frame of the episode will not be included in the video.
"""
VectorWrapper.__init__(self, env)
gym.utils.RecordConstructorArgs.__init__(
self,
video_folder=video_folder,
episode_trigger=episode_trigger,
step_trigger=step_trigger,
video_length=video_length,
name_prefix=name_prefix,
disable_logger=disable_logger,
)
if env.render_mode in {None, "human", "ansi"}:
raise ValueError(
f"Render mode is {env.render_mode}, which is incompatible with RecordVideo.",
"Initialize your environment with a render_mode that returns an image, such as rgb_array.",
)
if episode_trigger is None and step_trigger is None:
from gymnasium.utils.save_video import capped_cubic_video_schedule
episode_trigger = capped_cubic_video_schedule
autoreset_mode = env.metadata.get("autoreset_mode", None)
if autoreset_mode is not None:
self.autoreset_mode = autoreset_mode
else:
warn(
f"{env} metadata doesn't specify its autoreset mode ({env.metadata!r}), therefore, defaulting to next step."
)
self.autoreset_mode = gym.vector.AutoresetMode.NEXT_STEP
if self.autoreset_mode == gym.vector.AutoresetMode.SAME_STEP:
logger.warn(
"Vector environment's autoreset mode is same-step (https://farama.org/Vector-Autoreset-Mode). Recorded episodes will not contain the last frame of the episode."
)
self.has_autoreset = False
self.episode_trigger = episode_trigger
self.step_trigger = step_trigger
self.disable_logger = disable_logger
self.gc_trigger = gc_trigger
self.record_first_only = record_first_only
self.video_aspect_ratio = video_aspect_ratio
self.frame_cols = -1
self.frame_rows = -1
self.video_folder = os.path.abspath(video_folder)
if os.path.isdir(self.video_folder):
logger.warn(
f"Overwriting existing videos at {self.video_folder} folder "
f"(try specifying a different `video_folder` for the `RecordVideo` wrapper if this is not desired)"
)
os.makedirs(self.video_folder, exist_ok=True)
if fps is None:
fps = self.metadata.get("render_fps", 30)
self.frames_per_sec: int = fps
self.name_prefix: str = name_prefix
self._video_name: str | None = None
self.video_length: int = video_length if video_length != 0 else float("inf")
self.recording: bool = False
self.recorded_frames: list[np.ndarray] = []
self.render_history: list[np.ndarray] = []
self.step_id = -1
self.episode_id = -1
try:
import moviepy # noqa: F401
except ImportError as e:
raise error.DependencyNotInstalled(
'MoviePy is not installed, run `pip install "gymnasium[other]"`'
) from e
def _get_concat_frame_shape(self, n_frames, h, w):
"""Finds the right shape to concatenate frames from all environments into one frame."""
target_video_aspect_ratio = (
self.video_aspect_ratio[0] / self.video_aspect_ratio[1]
)
best_rows, best_cols = 1, n_frames
min_diff = np.inf
for rows in range(1, int(n_frames**0.5) + 1):
if n_frames % rows == 0:
cols = n_frames // rows
total_height = rows * h
total_width = cols * w
aspect = total_width / total_height
diff = abs(aspect - target_video_aspect_ratio)
if diff < min_diff:
min_diff = diff
best_rows, best_cols = rows, cols
self.frame_rows = best_rows
self.frame_cols = best_cols
def _concat_frames(self, frames):
"""Concatenates a list of frames into one large frame."""
frames = np.array(frames)
n_frames, h, w, c = frames.shape
grid = np.zeros(
(self.frame_rows * h, self.frame_cols * w, c), dtype=frames.dtype
)
for idx in range(n_frames):
r = idx // self.frame_cols
c_ = idx % self.frame_cols
grid[r * h : (r + 1) * h, c_ * w : (c_ + 1) * w] = frames[idx]
return grid
def _capture_frame(self):
assert self.recording, "Cannot capture a frame, recording wasn't started."
envs_frame = self.env.render()
assert isinstance(envs_frame, Sequence), type(envs_frame)
assert len(envs_frame) == self.num_envs
if self.record_first_only:
envs_frame = [envs_frame[0]]
if self.frame_cols == -1 or self.frame_rows == -1:
n_frames = len(envs_frame)
h, w, c = envs_frame[0].shape
self._get_concat_frame_shape(n_frames, h, w)
concatenated_envs_frame = self._concat_frames(envs_frame)
self.recorded_frames.append(concatenated_envs_frame)
def reset(
self, *, seed: int | None = None, options: dict[str, Any] | None = None
) -> tuple[ObsType, dict[str, Any]]:
"""Reset the environment and eventually starts a new recording."""
if options is None or "reset_mask" not in options or options["reset_mask"][0]:
self.episode_id += 1
if self.recording and self.video_length == float("inf"):
self.stop_recording()
if self.episode_trigger and self.episode_trigger(self.episode_id):
self.start_recording(f"{self.name_prefix}-episode-{self.episode_id}")
obs, info = super().reset(seed=seed, options=options)
if self.recording:
self._capture_frame()
if len(self.recorded_frames) > self.video_length:
self.stop_recording()
self.has_autoreset = False
return obs, info
def step(
self, actions: ActType
) -> tuple[ObsType, SupportsFloat, bool, bool, dict[str, Any]]:
"""Steps through the environment using action, recording observations if :attr:`self.recording`."""
obs, rewards, terminations, truncations, info = self.env.step(actions)
self.step_id += 1
if self.autoreset_mode == gym.vector.AutoresetMode.NEXT_STEP:
if self.has_autoreset:
self.episode_id += 1
if self.recording and self.video_length == float("inf"):
self.stop_recording()
if self.episode_trigger and self.episode_trigger(self.episode_id):
self.start_recording(
f"{self.name_prefix}-episode-{self.episode_id}"
)
self.has_autoreset = terminations[0] or truncations[0]
elif self.autoreset_mode == gym.vector.AutoresetMode.SAME_STEP and (
terminations[0] or truncations[0]
):
self.episode_id += 1
if self.recording and self.video_length == float("inf"):
self.stop_recording()
if self.episode_trigger and self.episode_trigger(self.episode_id):
self.start_recording(f"{self.name_prefix}-episode-{self.episode_id}")
if self.step_trigger and self.step_trigger(self.step_id):
self.start_recording(f"{self.name_prefix}-step-{self.step_id}")
if self.recording:
self._capture_frame()
if len(self.recorded_frames) > self.video_length:
self.stop_recording()
return obs, rewards, terminations, truncations, info
def render(self) -> RenderFrame | list[RenderFrame]:
"""Compute the render frames as specified by render_mode attribute during initialization of the environment."""
render_out = super().render()
if self.recording and isinstance(render_out, list):
self.recorded_frames += render_out
if len(self.render_history) > 0:
tmp_history = self.render_history
self.render_history = []
return tmp_history + render_out
else:
return render_out
def close(self):
"""Closes the wrapper then the video recorder."""
super().close()
if self.recording:
self.stop_recording()
def start_recording(self, video_name: str):
"""Start a new recording. If it is already recording, stops the current recording before starting the new one."""
if self.recording:
self.stop_recording()
self.recording = True
self._video_name = video_name
def stop_recording(self):
"""Stop current recording and saves the video."""
assert self.recording, "stop_recording was called, but no recording was started"
if len(self.recorded_frames) == 0:
logger.warn("Ignored saving a video as there were zero frames to save.")
else:
try:
from moviepy.video.io.ImageSequenceClip import ImageSequenceClip
except ImportError as e:
raise error.DependencyNotInstalled(
'MoviePy is not installed, run `pip install "gymnasium[other]"`'
) from e
clip = ImageSequenceClip(self.recorded_frames, fps=self.frames_per_sec)
moviepy_logger = None if self.disable_logger else "bar"
path = os.path.join(self.video_folder, f"{self._video_name}.mp4")
clip.write_videofile(path, logger=moviepy_logger)
self.recorded_frames = []
self.recording = False
self._video_name = None
if self.gc_trigger and self.gc_trigger(self.episode_id):
gc.collect()
def __del__(self):
"""Warn the user in case last video wasn't saved."""
if len(self.recorded_frames) > 0:
logger.warn("Unable to save last video! Did you call close()?")
| RecordVideo |
python | pytorch__pytorch | test/mobile/model_test/math_ops.py | {
"start": 10278,
"end": 11562
} | class ____(torch.nn.Module):
def forward(self):
a = torch.tensor(0)
b = torch.tensor(1)
return len(
torch.allclose(a, b),
torch.argsort(a),
torch.eq(a, b),
torch.eq(a, 1),
torch.equal(a, b),
torch.ge(a, b),
torch.ge(a, 1),
torch.greater_equal(a, b),
torch.greater_equal(a, 1),
torch.gt(a, b),
torch.gt(a, 1),
torch.greater(a, b),
torch.isclose(a, b),
torch.isfinite(a),
torch.isin(a, b),
torch.isinf(a),
torch.isposinf(a),
torch.isneginf(a),
torch.isnan(a),
torch.isreal(a),
torch.kthvalue(a, 1),
torch.le(a, b),
torch.le(a, 1),
torch.less_equal(a, b),
torch.lt(a, b),
torch.lt(a, 1),
torch.less(a, b),
torch.maximum(a, b),
torch.minimum(a, b),
torch.fmax(a, b),
torch.fmin(a, b),
torch.ne(a, b),
torch.ne(a, 1),
torch.not_equal(a, b),
torch.sort(a),
torch.topk(a, 1),
torch.msort(a),
)
| ComparisonOpsModule |
python | chroma-core__chroma | chromadb/segment/__init__.py | {
"start": 423,
"end": 840
} | class ____(Enum):
SQLITE = "urn:chroma:segment/metadata/sqlite"
HNSW_LOCAL_MEMORY = "urn:chroma:segment/vector/hnsw-local-memory"
HNSW_LOCAL_PERSISTED = "urn:chroma:segment/vector/hnsw-local-persisted"
HNSW_DISTRIBUTED = "urn:chroma:segment/vector/hnsw-distributed"
BLOCKFILE_RECORD = "urn:chroma:segment/record/blockfile"
BLOCKFILE_METADATA = "urn:chroma:segment/metadata/blockfile"
| SegmentType |
python | kubernetes-client__python | kubernetes/base/dynamic/exceptions.py | {
"start": 3127,
"end": 3197
} | class ____(DynamicApiError):
""" 404: StatusNotFound """
| NotFoundError |
python | pytorch__pytorch | torch/_functorch/make_functional.py | {
"start": 10790,
"end": 22935
} | class ____(nn.Module):
"""
This is the callable object returned by :func:`make_functional`.
"""
def __init__(
self,
stateless_model: nn.Module,
param_names: tuple[str, ...],
names_map: dict[str, list[str]],
) -> None:
super().__init__()
self.stateless_model = stateless_model
self.param_names = param_names
self.names_map = names_map
@staticmethod
def _create_from(
model: nn.Module, disable_autograd_tracking: bool = False
) -> tuple["FunctionalModule", tuple[Tensor, ...]]:
# TODO: We don't need to copy the model to create a stateless copy
model_copy = copy.deepcopy(model)
params, param_names, names_map = extract_weights(model_copy)
if disable_autograd_tracking:
for param in params:
param.requires_grad_(False)
return FunctionalModule(model_copy, param_names, names_map), params
def forward(self, params: Iterable[Tensor], *args, **kwargs) -> Any:
# Temporarily load the state back onto self.stateless_model
old_state = _swap_state(self.stateless_model, self.names_map, params)
try:
return self.stateless_model(*args, **kwargs)
finally:
# Remove the loaded state on self.stateless_model
_swap_state(self.stateless_model, self.names_map, old_state)
def make_functional(
model: nn.Module, disable_autograd_tracking: bool = False
) -> tuple[FunctionalModule, tuple[Tensor, ...]]:
"""make_functional(model, disable_autograd_tracking=False) -> func, params
Given a ``torch.nn.Module``, :func:`make_functional` extracts the state
(params) and returns a functional version of the model, ``func``. This
makes it so that it is possible use transforms over the parameters of
``model``.
``func`` can be invoked as follows:
.. code-block:: python
import torch
import torch.nn as nn
from functorch import make_functional
x = torch.randn(4, 3)
model = nn.Linear(3, 3)
func, params = make_functional(model)
func(params, x)
And here is an example of applying the grad transform over the parameters
of a model.
.. code-block:: python
import torch
import torch.nn as nn
from functorch import make_functional, grad
x = torch.randn(4, 3)
t = torch.randn(4, 3)
model = nn.Linear(3, 3)
func, params = make_functional(model)
def compute_loss(params, x, t):
y = func(params, x)
return nn.functional.mse_loss(y, t)
grad_weights = grad(compute_loss)(params, x, t)
If the model has any buffers, please use :func:`make_functional_with_buffers` instead.
Args:
model (torch.nn.Module): Input model.
disable_autograd_tracking (bool): Flag to disable gradients tracking for output parameters.
The returned params are unrelated to the set of params from the original model. If False (default),
the params will have ``requires_grad=True`` on them (aka they will be trackable with regular
PyTorch autograd), matching the requires_grad-ness of the params from the original model.
Otherwise, the returned params will have ``requires_grad=False``. Default, False.
If you plan on using regular PyTorch autograd (e.g., if you want to call ``.backward()`` or
``torch.autograd.grad()``, then set ``disable_autograd_tracking=False``.
Otherwise, if you're only planning on using functorch's gradient transforms,
then please set ``disable_autograd_tracking=True`` to avoid unnecessarily tracking
history with PyTorch autograd.
"""
buffers = list(model.buffers())
if len(buffers) > 0:
raise RuntimeError(
"make_functional(model): `model` has buffers. Please use "
"make_functional_with_buffers(model) instead."
)
return FunctionalModule._create_from(
model, disable_autograd_tracking=disable_autograd_tracking
)
def make_functional_with_buffers(
model: nn.Module, disable_autograd_tracking: bool = False
) -> tuple[FunctionalModuleWithBuffers, tuple[Tensor, ...], tuple[Tensor, ...]]:
"""make_functional_with_buffers(model, disable_autograd_tracking=False) -> func, params, buffers
Given a ``torch.nn.Module``, make_functional_with_buffers extracts the
state (params and buffers) and returns a functional version of the model
``func`` that can be invoked like a function.
``func`` can be invoked as follows:
.. code-block:: python
import torch
import torch.nn as nn
from functorch import make_functional_with_buffers
x = torch.randn(4, 3)
model = nn.Linear(3, 3)
func, params, buffers = make_functional_with_buffers(model)
func(params, buffers, x)
And here is an example of applying the grad transform over the parameters
of a model:
.. code-block:: python
import torch
import torch.nn as nn
from functorch import make_functional_with_buffers, grad
x = torch.randn(4, 3)
t = torch.randn(4, 3)
model = nn.Linear(3, 3)
func, params, buffers = make_functional_with_buffers(model)
def compute_loss(params, buffers, x, t):
y = func(params, buffers, x)
return nn.functional.mse_loss(y, t)
grad_weights = grad(compute_loss)(params, buffers, x, t)
Args:
model (torch.nn.Module): Input model.
disable_autograd_tracking (bool): Flag to disable gradients tracking for output parameters.
The returned params are unrelated to the set of params from the original model. If False (default),
the params will have ``requires_grad=True`` on them (aka they will be trackable with regular
PyTorch autograd), matching the requires_grad-ness of the params from the original model.
Otherwise, the returned params will have ``requires_grad=False``. Default, False.
If you plan on using regular PyTorch autograd (e.g., if you want to call ``.backward()`` or
``torch.autograd.grad()``, then set ``disable_autograd_tracking=False``.
Otherwise, if you're only planning on using functorch's gradient transforms,
then please set ``disable_autograd_tracking=True`` to avoid unnecessarily tracking
history with PyTorch autograd.
"""
return FunctionalModuleWithBuffers._create_from(
model, disable_autograd_tracking=disable_autograd_tracking
)
def transpose_stack(
tuple_of_tuple_of_tensors: tuple[tuple[Tensor, ...], ...],
) -> tuple[Tensor, ...]:
tuple_of_tuple_of_tensors = tuple(zip(*tuple_of_tuple_of_tensors))
results = tuple(
torch.stack(shards).detach() for shards in tuple_of_tuple_of_tensors
)
return results
def combine_state_for_ensemble(
models: Sequence[nn.Module],
) -> tuple[FunctionalModuleWithBuffers, tuple[Tensor, ...], tuple[Tensor, ...]]:
"""combine_state_for_ensemble(models) -> func, params, buffers
Prepares a list of torch.nn.Modules for ensembling with :func:`vmap`.
Given a list of ``M`` ``nn.Modules`` of the same class, stacks all of their
parameters and buffers together to make ``params`` and ``buffers``.
Each parameter and buffer in the result will have an additional dimension
of size ``M``.
:func:`combine_state_for_ensemble` also returns ``func``, a functional
version of one of the models in :attr:`models`. One cannot directly run
``func(params, buffers, *args, **kwargs)`` directly, you probably want to
use ``vmap(func, ...)(params, buffers, *args, **kwargs)``
Here's an example of how to ensemble over a very simple model:
.. code-block:: python
num_models = 5
batch_size = 64
in_features, out_features = 3, 3
models = [torch.nn.Linear(in_features, out_features) for i in range(num_models)]
data = torch.randn(batch_size, 3)
fmodel, params, buffers = combine_state_for_ensemble(models)
output = vmap(fmodel, (0, 0, None))(params, buffers, data)
assert output.shape == (num_models, batch_size, out_features)
.. warning::
All of the modules being stacked together must be the same (except for
the values of their parameters/buffers). For example, they should be in the
same mode (training vs eval).
This API is subject to change -- we're investigating better ways to
create ensembles and would love your feedback how to improve this.
"""
if len(models) == 0:
raise RuntimeError(
"combine_state_for_ensemble: Expected at least one model, got 0."
)
if not (all(m.training for m in models) or all(not m.training for m in models)):
raise RuntimeError(
"combine_state_for_ensemble: Expected all models to "
"have the same training/eval mode."
)
model0_typ = type(models[0])
if not all(type(m) is model0_typ for m in models):
raise RuntimeError(
"combine_state_for_ensemble: Expected all models to be of the same class."
)
funcs, params, buffers = zip(
*[make_functional_with_buffers(model) for model in models]
)
params = transpose_stack(params)
buffers = transpose_stack(buffers)
return funcs[0], params, buffers
def functional_init(
model_class: type[nn.Module],
ensemble_shape: Union[tuple[()], tuple[int]] = (),
device: torch.types.Device = "cpu",
):
def wrapped(*args, **kwargs):
if len(ensemble_shape) >= 2:
raise ValueError("NYI: ensemble_shape with more than 1 element")
if len(ensemble_shape) == 0:
model = model_class(*args, **kwargs).to(device)
return make_functional_deprecated_v1(model)
num_models = ensemble_shape[0] # type: ignore[misc]
if num_models <= 0:
raise ValueError(f"num_models {num_models} should be > 0")
# NB: Not very efficient, more of a POC
models = tuple(
model_class(*args, **kwargs).to(device) for _ in range(num_models)
)
_, fn, names = make_functional_deprecated_v1(model_class(*args, **kwargs))
weights = tuple(make_functional_deprecated_v1(model)[0] for model in models)
weights = tuple(zip(*weights))
weights = tuple(torch.stack(shards).detach() for shards in weights)
return weights, fn, names
return wrapped
def functional_init_with_buffers(
model_class: type[nn.Module],
ensemble_shape: Union[tuple[()], tuple[int]] = (),
device: torch.types.Device = "cpu",
):
def wrapped(*args, **kwargs):
if len(ensemble_shape) >= 2:
raise ValueError("NYI: ensemble_shape with more than 1 element")
if len(ensemble_shape) == 0:
model = model_class(*args, **kwargs).to(device)
return make_functional_deprecated_v1(model)
num_models = ensemble_shape[0] # type: ignore[misc]
if num_models <= 0:
raise ValueError(f"num_models {num_models} should be > 0")
# NB: Not very efficient, more of a POC
models = tuple(
model_class(*args, **kwargs).to(device) for _ in range(num_models)
)
(
_,
_,
fn,
weight_names,
buffer_names,
) = make_functional_with_buffers_deprecated_v1(model_class(*args, **kwargs))
weights, buffers = zip(
*tuple(
make_functional_with_buffers_deprecated_v1(model)[:2]
for model in models
)
)
weights = tuple(zip(*weights))
weights = tuple(torch.stack(shards).detach() for shards in weights)
buffers = tuple(zip(*buffers))
buffers = tuple(torch.stack(shards).detach() for shards in buffers)
return weights, buffers, fn, weight_names, buffer_names
return wrapped
| FunctionalModule |
python | getsentry__sentry | src/sentry/api/fields/empty_integer.py | {
"start": 81,
"end": 605
} | class ____(serializers.IntegerField):
"""
DRF used to translate a blank field as a null integer, but after 3.x it
doesn't accept an empty string as a value. We rely on this behaviour in some
cases, so this restores it.
"""
def to_internal_value(self, data):
if data == "":
return None
return super().to_internal_value(data)
def run_validation(self, data=empty):
if data == "":
return None
return super().run_validation(data)
| EmptyIntegerField |
python | openai__openai-python | src/openai/types/chat/chat_completion_user_message_param.py | {
"start": 345,
"end": 792
} | class ____(TypedDict, total=False):
content: Required[Union[str, Iterable[ChatCompletionContentPartParam]]]
"""The contents of the user message."""
role: Required[Literal["user"]]
"""The role of the messages author, in this case `user`."""
name: str
"""An optional name for the participant.
Provides the model information to differentiate between participants of the same
role.
"""
| ChatCompletionUserMessageParam |
python | Farama-Foundation__Gymnasium | gymnasium/envs/mujoco/mujoco_rendering.py | {
"start": 833,
"end": 5325
} | class ____:
def __init__(
self,
model: "mujoco.MjModel",
data: "mujoco.MjData",
width: int,
height: int,
max_geom: int = 1000,
visual_options: dict[int, bool] = {},
):
"""Render context superclass for offscreen and window rendering."""
self.model = model
self.data = data
self._markers = []
self._overlays = {}
self.viewport = mujoco.MjrRect(0, 0, width, height)
# This goes to specific visualizer
self.scn = mujoco.MjvScene(self.model, max_geom)
self.cam = mujoco.MjvCamera()
self.vopt = mujoco.MjvOption()
self.pert = mujoco.MjvPerturb()
for flag, value in visual_options.items():
self.vopt.flags[flag] = value
self.make_context_current()
# Keep in Mujoco Context
self.con = mujoco.MjrContext(self.model, mujoco.mjtFontScale.mjFONTSCALE_150)
self._set_mujoco_buffer()
def _set_mujoco_buffer(self):
raise NotImplementedError
def make_context_current(self):
raise NotImplementedError
def add_overlay(self, gridpos: int, text1: str, text2: str):
"""Overlays text on the scene."""
if gridpos not in self._overlays:
self._overlays[gridpos] = ["", ""]
self._overlays[gridpos][0] += text1 + "\n"
self._overlays[gridpos][1] += text2 + "\n"
def add_marker(self, **marker_params):
self._markers.append(marker_params)
def _add_marker_to_scene(self, marker: dict):
if self.scn.ngeom >= self.scn.maxgeom:
raise RuntimeError(f"Ran out of geoms. maxgeom: {self.scn.maxgeom}")
if _MUJOCO_MARKER_LEGACY_MODE: # Old API for markers requires special handling
self._legacy_add_marker_to_scene(marker)
else:
geom_type = marker.get("type", mujoco.mjtGeom.mjGEOM_SPHERE)
size = marker.get("size", np.array([0.01, 0.01, 0.01]))
pos = marker.get("pos", np.array([0.0, 0.0, 0.0]))
mat = marker.get("mat", np.eye(3).flatten())
rgba = marker.get("rgba", np.array([1.0, 1.0, 1.0, 1.0]))
mujoco.mjv_initGeom(
self.scn.geoms[self.scn.ngeom],
geom_type,
size=size,
pos=pos,
mat=mat,
rgba=rgba,
)
self.scn.ngeom += 1
def _legacy_add_marker_to_scene(self, marker: dict):
"""Add a marker to the scene compatible with older versions of MuJoCo.
MuJoCo 3.2 introduced breaking changes to the visual geometries API. To maintain
compatibility with older versions, we use the legacy API when an older version of MuJoCo is
detected.
Args:
marker: A dictionary containing the marker parameters.
"""
g = self.scn.geoms[self.scn.ngeom]
# default values.
g.dataid = -1
g.objtype = mujoco.mjtObj.mjOBJ_UNKNOWN
g.objid = -1
g.category = mujoco.mjtCatBit.mjCAT_DECOR
g.texid = -1
g.texuniform = 0
g.texrepeat[0] = 1
g.texrepeat[1] = 1
g.emission = 0
g.specular = 0.5
g.shininess = 0.5
g.reflectance = 0
g.type = mujoco.mjtGeom.mjGEOM_BOX
g.size[:] = np.ones(3) * 0.1
g.mat[:] = np.eye(3)
g.rgba[:] = np.ones(4)
for key, value in marker.items():
if isinstance(value, (int, float, mujoco._enums.mjtGeom)):
setattr(g, key, value)
elif isinstance(value, (tuple, list, np.ndarray)):
attr = getattr(g, key)
attr[:] = np.asarray(value).reshape(attr.shape)
elif isinstance(value, str):
assert key == "label", "Only label is a string in mjtGeom."
if value is None:
g.label[0] = 0
else:
g.label = value
elif hasattr(g, key):
raise ValueError(
"mjtGeom has attr {} but type {} is invalid".format(
key, type(value)
)
)
else:
raise ValueError("mjtGeom doesn't have field %s" % key)
def close(self):
"""Override close in your rendering subclass to perform any necessary cleanup
after env.close() is called.
"""
raise NotImplementedError
| BaseRender |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli/cli/list.py | {
"start": 14613,
"end": 18797
} | class ____:
has_full_value: bool
has_branch_value: bool
has_local_value: bool
def _get_dagster_plus_keys(
location_name: str, env_var_keys: set[str]
) -> Optional[Mapping[str, DagsterPlusScopesForVariable]]:
"""Retrieves the set Dagster Plus keys for the given location name, if Plus is configured, otherwise returns None."""
if not DagsterPlusCliConfig.exists():
return None
config = DagsterPlusCliConfig.get()
if not config.organization:
return None
scopes_for_key = defaultdict(lambda: DagsterPlusScopesForVariable(False, False, False))
gql_client = DagsterPlusGraphQLClient.from_config(config)
secrets_by_location = gql_client.execute(
gql.GET_SECRETS_FOR_SCOPES_QUERY_NO_VALUE,
{
"locationName": location_name,
"scopes": {
"fullDeploymentScope": True,
"allBranchDeploymentsScope": True,
"localDeploymentScope": True,
},
},
)["secretsOrError"]["secrets"]
for secret in secrets_by_location:
key = secret["secretName"]
if key in env_var_keys:
if secret["fullDeploymentScope"]:
scopes_for_key[key].has_full_value = True
if secret["allBranchDeploymentsScope"]:
scopes_for_key[key].has_branch_value = True
if secret["localDeploymentScope"]:
scopes_for_key[key].has_local_value = True
return scopes_for_key
@list_group.command(name="envs", aliases=["env"], cls=DgClickCommand)
@dg_path_options
@dg_global_options
@cli_telemetry_wrapper
def list_env_command(target_path: Path, **global_options: object) -> None:
"""List environment variables from the .env file of the current project."""
from rich.console import Console
cli_config = normalize_cli_config(global_options, click.get_current_context())
dg_context = DgContext.for_project_environment(target_path, cli_config)
env = ProjectEnvVars.from_ctx(dg_context)
used_env_vars = get_project_specified_env_vars(dg_context)
if not env.values and not used_env_vars:
click.echo("No environment variables are defined for this project.")
return
env_var_keys = env.values.keys() | used_env_vars.keys()
plus_keys = _get_dagster_plus_keys(dg_context.project_name, env_var_keys)
table = DagsterOuterTable([])
table.add_column("Env Var")
table.add_column("Value")
table.add_column("Components")
if plus_keys is not None:
table.add_column("Dev")
table.add_column("Branch")
table.add_column("Full")
for key in sorted(env_var_keys):
components = used_env_vars.get(key, [])
table.add_row(
key,
"✓" if key in env.values else "",
", ".join(str(path) for path in components),
*(
[
"✓" if plus_keys[key].has_local_value else "",
"✓" if plus_keys[key].has_branch_value else "",
"✓" if plus_keys[key].has_full_value else "",
]
if plus_keys is not None
else []
),
)
console = Console()
console.print(table)
@list_group.command(name="component-tree", aliases=["tree"], cls=DgClickCommand)
@click.option(
"--output-file",
help="Write to file instead of stdout. If not specified, will write to stdout.",
)
@dg_path_options
@dg_global_options
@cli_telemetry_wrapper
def list_component_tree_command(
target_path: Path,
output_file: Optional[str],
**other_opts: object,
) -> None:
cli_config = normalize_cli_config(other_opts, click.get_current_context())
dg_context = DgContext.for_project_environment(target_path, cli_config)
from dagster.components.core.component_tree import ComponentTree
tree = ComponentTree.for_project(dg_context.root_path)
output = tree.to_string_representation(hide_plain_defs=True)
if output_file:
click.echo("[dagster-components] Writing to file " + output_file)
Path(output_file).write_text(output)
else:
click.echo(output)
| DagsterPlusScopesForVariable |
python | kamyu104__LeetCode-Solutions | Python/longest-subsequence-with-decreasing-adjacent-difference.py | {
"start": 61,
"end": 684
} | class ____(object):
def longestSubsequence(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 2
mx = max(nums)
dp = [[0]*mx for _ in xrange(mx)]
for x in nums:
x -= 1
for nx in xrange(len(dp[x])):
d = abs(nx-x)
dp[x][d] = max(dp[x][d], dp[nx][d]+1)
for d in reversed(xrange(len(dp[x])-1)):
dp[x][d] = max(dp[x][d], dp[x][d+1])
result = max(result, dp[x][0])
return result
# Time: O(r^2 + n * r), r = max(nums)
# Space: O(r^2)
# dp
| Solution |
python | google__pytype | pytype/rewrite/convert_test.py | {
"start": 1018,
"end": 1509
} | class ____(ConverterTestBase):
def test_basic(self):
pytd_func = self.build_pytd("""
from typing import Any
def f(x: Any) -> Any: ...
""")
func = self.conv.pytd_function_to_value(pytd_func)
self.assertIsInstance(func, abstract.PytdFunction)
self.assertEqual(func.name, 'f')
self.assertEqual(func.module, '<test>')
self.assertEqual(len(func.signatures), 1)
self.assertEqual(repr(func.signatures[0]), 'def f(x: Any) -> Any')
| PytdFunctionToValueTest |
python | django-haystack__django-haystack | test_haystack/solr_tests/test_solr_backend.py | {
"start": 50983,
"end": 54254
} | class ____(TestCase):
fixtures = ["base_data.json", "bulk_data.json"]
def setUp(self):
super().setUp()
# Wipe it clean.
clear_solr_index()
self.old_ui = connections["solr"].get_unified_index()
self.ui = UnifiedIndex()
self.smmi = SolrMockModelSearchIndex()
self.sammi = SolrAnotherMockModelSearchIndex()
self.ui.build(indexes=[self.smmi, self.sammi])
connections["solr"]._index = self.ui
self.sqs = SearchQuerySet("solr")
self.smmi.update("solr")
self.sammi.update("solr")
def tearDown(self):
# Restore.
connections["solr"]._index = self.old_ui
super().tearDown()
def test_more_like_this(self):
all_mlt = self.sqs.more_like_this(MockModel.objects.get(pk=1))
self.assertEqual(
all_mlt.count(),
len([result.pk for result in all_mlt]),
msg="mlt SearchQuerySet .count() didn't match retrieved result length",
)
# Rather than hard-code assumptions about Solr's return order, we have a few very similar
# items which we'll confirm are included in the first 5 results. This is still ugly as we're
# hard-coding primary keys but it's better than breaking any time a Solr update or data
# change causes a score to shift slightly
top_results = [int(result.pk) for result in all_mlt[:5]]
for i in (14, 6, 10, 4, 5):
self.assertIn(i, top_results)
filtered_mlt = self.sqs.filter(name="daniel3").more_like_this(
MockModel.objects.get(pk=3)
)
self.assertLess(filtered_mlt.count(), all_mlt.count())
top_filtered_results = [int(result.pk) for result in filtered_mlt[:5]]
for i in (16, 17, 19, 13, 23):
self.assertIn(i, top_filtered_results)
mlt_filtered = self.sqs.more_like_this(MockModel.objects.get(pk=3)).filter(
name="daniel3"
)
self.assertLess(mlt_filtered.count(), all_mlt.count())
top_mlt_filtered_pks = [int(result.pk) for result in mlt_filtered[:5]]
for i in (17, 16, 19, 23, 13):
self.assertIn(i, top_mlt_filtered_pks)
filtered_mlt_with_models = self.sqs.models(MockModel).more_like_this(
MockModel.objects.get(pk=1)
)
self.assertLessEqual(filtered_mlt_with_models.count(), all_mlt.count())
top_filtered_with_models = [
int(result.pk) for result in filtered_mlt_with_models[:5]
]
for i in (14, 6, 4, 5, 10):
self.assertIn(i, top_filtered_with_models)
def test_more_like_this_defer(self):
mi = MockModel.objects.defer("foo").get(pk=1)
deferred = self.sqs.models(MockModel).more_like_this(mi)
top_results = [int(result.pk) for result in deferred[:5]]
for i in (14, 6, 4, 5, 10):
self.assertIn(i, top_results)
def test_more_like_this_custom_result_class(self):
"""Ensure that swapping the ``result_class`` works"""
first_result = self.sqs.result_class(MockSearchResult).more_like_this(
MockModel.objects.get(pk=1)
)[0]
self.assertIsInstance(first_result, MockSearchResult)
| LiveSolrMoreLikeThisTestCase |
python | getsentry__sentry | tests/snuba/rules/conditions/test_event_frequency.py | {
"start": 52095,
"end": 52369
} | class ____(
ErrorEventMixin,
EventUniqueUserFrequencyConditionWithConditionsTestCase,
):
pass
@freeze_time(
(timezone.now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0)
)
| ErrorIssueUniqueUserFrequencyConditionWithConditionsTestCase |
python | Pylons__pyramid | tests/pkgs/eventonly/__init__.py | {
"start": 321,
"end": 587
} | class ____:
def __init__(self, val, config):
self.val = val
def text(self):
return f'yup_with_extra_args = {self.val}'
phash = text
def __call__(self, event, *args):
return getattr(event.response, 'yup', False)
| YupWithAllArgs |
python | ray-project__ray | python/ray/serve/tests/test_runtime_env.py | {
"start": 1717,
"end": 2096
} | class ____:
def __call__(self, *args):
return open("hello").read()
handle = serve.run(Test.bind(), name="app")
assert handle.remote().result() == "world"
"""
run_string_as_driver(driver1)
driver2 = driver1 + "\nserve.delete('app')"
run_string_as_driver(driver2)
if __name__ == "__main__":
import sys
sys.exit(pytest.main(["-sv", __file__]))
| Test |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 428591,
"end": 428775
} | class ____(VegaLiteSchema):
"""Fit schema wrapper."""
_schema = {"$ref": "#/definitions/Fit"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| Fit |
python | apache__airflow | devel-common/src/tests_common/pytest_plugin.py | {
"start": 58546,
"end": 63041
} | class ____(Protocol):
"""Type stub for create_task_instance."""
def __call__(
self,
*,
logical_date: datetime | None = ...,
dagrun_state: DagRunState = ...,
state: TaskInstanceState = ...,
run_id: str = ...,
run_type: DagRunType = ...,
data_interval: DataInterval = ...,
external_executor_id: str = ...,
dag_id: str = "dag",
task_id: str = "op1",
task_display_name: str = ...,
max_active_tis_per_dag: int = 16,
max_active_tis_per_dagrun: int = ...,
pool: str = "default_pool",
executor_config: dict = ...,
trigger_rule: TriggerRule = ...,
on_success_callback: Callable = ...,
on_execute_callback: Callable = ...,
on_failure_callback: Callable = ...,
on_retry_callback: Callable = ...,
email: str = ...,
map_index: int = -1,
**kwargs,
) -> TaskInstance: ...
@pytest.fixture
def create_task_instance(dag_maker: DagMaker, create_dummy_dag: CreateDummyDAG) -> CreateTaskInstance:
"""
Create a TaskInstance, and associated DB rows (DagRun, DagModel, etc).
Uses ``create_dummy_dag`` to create the dag structure.
"""
from airflow.providers.standard.operators.empty import EmptyOperator
from tests_common.test_utils.version_compat import AIRFLOW_V_3_0_PLUS, NOTSET, ArgNotSet
def maker(
logical_date: datetime | None | ArgNotSet = NOTSET,
run_after=None,
dagrun_state=None,
state=None,
run_id=None,
run_type=None,
data_interval=None,
external_executor_id=None,
dag_id="dag",
task_id="op1",
task_display_name=None,
max_active_tis_per_dag=16,
max_active_tis_per_dagrun=None,
pool="default_pool",
executor_config=None,
trigger_rule="all_done",
on_success_callback=None,
on_execute_callback=None,
on_failure_callback=None,
on_retry_callback=None,
on_skipped_callback=None,
inlets=None,
outlets=None,
email=None,
map_index=-1,
hostname=None,
pid=None,
last_heartbeat_at=None,
**kwargs,
) -> TaskInstance:
timezone = _import_timezone()
if run_after is None:
run_after = timezone.utcnow()
if logical_date is NOTSET:
# For now: default to having a logical date if None is not explicitly passed.
logical_date = timezone.utcnow()
with dag_maker(dag_id, **kwargs):
op_kwargs = {}
op_kwargs["task_display_name"] = task_display_name
task = EmptyOperator(
task_id=task_id,
max_active_tis_per_dag=max_active_tis_per_dag,
max_active_tis_per_dagrun=max_active_tis_per_dagrun,
executor_config=executor_config or {},
on_success_callback=on_success_callback,
on_execute_callback=on_execute_callback,
on_failure_callback=on_failure_callback,
on_retry_callback=on_retry_callback,
on_skipped_callback=on_skipped_callback,
inlets=inlets,
outlets=outlets,
email=email,
pool=pool,
trigger_rule=trigger_rule,
**op_kwargs,
)
if AIRFLOW_V_3_0_PLUS:
dagrun_kwargs = {
"logical_date": logical_date,
"run_after": run_after,
"state": dagrun_state,
}
else:
dagrun_kwargs = {
"logical_date": logical_date if logical_date not in (None, NOTSET) else run_after,
"state": dagrun_state,
}
if run_id is not None:
dagrun_kwargs["run_id"] = run_id
if run_type is not None:
dagrun_kwargs["run_type"] = run_type
if data_interval is not None:
dagrun_kwargs["data_interval"] = data_interval
dagrun = dag_maker.create_dagrun(**dagrun_kwargs)
(ti,) = dagrun.task_instances
ti.task = task
ti.state = state
ti.external_executor_id = external_executor_id
ti.map_index = map_index
ti.hostname = hostname or ""
ti.pid = pid
ti.last_heartbeat_at = last_heartbeat_at
dag_maker.session.flush()
return ti
return maker
| CreateTaskInstance |
python | pytorch__pytorch | torch/ao/nn/intrinsic/modules/fused.py | {
"start": 8005,
"end": 8586
} | class ____(_FusedModule):
r"""This is a sequential container which calls the Linear and BatchNorm1d modules.
During quantization this will be replaced with the corresponding fused module."""
def __init__(self, linear, bn):
assert (
type_before_parametrizations(linear) == Linear
and type_before_parametrizations(bn) == BatchNorm1d
), (
f"Incorrect types for input modules{type_before_parametrizations(linear)}"
f"{type_before_parametrizations(bn)}"
)
super().__init__(linear, bn)
| LinearBn1d |
python | jazzband__django-oauth-toolkit | tests/test_oauth2_backends.py | {
"start": 2175,
"end": 5591
} | class ____(TestCase):
factory = RequestFactory()
@classmethod
def setUpTestData(cls):
cls.oauthlib_core = OAuthLibCore()
cls.user = UserModel.objects.create_user("john", "test@example.com", "123456")
cls.app = ApplicationModel.objects.create(
name="app",
client_id="app_id",
client_secret="app_secret",
client_type=ApplicationModel.CLIENT_CONFIDENTIAL,
authorization_grant_type=ApplicationModel.GRANT_PASSWORD,
user=cls.user,
)
def test_create_token_response_valid(self):
payload = (
"grant_type=password&username=john&password=123456&client_id=app_id&client_secret=app_secret"
)
request = self.factory.post(
"/o/token/",
payload,
content_type="application/x-www-form-urlencoded",
HTTP_AUTHORIZATION="Basic %s" % base64.b64encode(b"john:123456").decode(),
)
uri, headers, body, status = self.oauthlib_core.create_token_response(request)
self.assertEqual(status, 200)
def test_create_token_response_query_params(self):
payload = (
"grant_type=password&username=john&password=123456&client_id=app_id&client_secret=app_secret"
)
request = self.factory.post(
"/o/token/?test=foo",
payload,
content_type="application/x-www-form-urlencoded",
HTTP_AUTHORIZATION="Basic %s" % base64.b64encode(b"john:123456").decode(),
)
uri, headers, body, status = self.oauthlib_core.create_token_response(request)
self.assertEqual(status, 400)
self.assertDictEqual(
json.loads(body),
{"error": "invalid_request", "error_description": "URL query parameters are not allowed"},
)
def test_create_revocation_response_valid(self):
AccessTokenModel.objects.create(
user=self.user, token="tokstr", application=self.app, expires=now() + timedelta(days=365)
)
payload = "client_id=app_id&client_secret=app_secret&token=tokstr"
request = self.factory.post(
"/o/revoke_token/",
payload,
content_type="application/x-www-form-urlencoded",
HTTP_AUTHORIZATION="Basic %s" % base64.b64encode(b"john:123456").decode(),
)
uri, headers, body, status = self.oauthlib_core.create_revocation_response(request)
self.assertEqual(status, 200)
def test_create_revocation_response_query_params(self):
token = AccessTokenModel.objects.create(
user=self.user, token="tokstr", application=self.app, expires=now() + timedelta(days=365)
)
payload = "client_id=app_id&client_secret=app_secret&token=tokstr"
request = self.factory.post(
"/o/revoke_token/?test=foo",
payload,
content_type="application/x-www-form-urlencoded",
HTTP_AUTHORIZATION="Basic %s" % base64.b64encode(b"john:123456").decode(),
)
uri, headers, body, status = self.oauthlib_core.create_revocation_response(request)
self.assertEqual(status, 400)
self.assertDictEqual(
json.loads(body),
{"error": "invalid_request", "error_description": "URL query parameters are not allowed"},
)
token.delete()
| TestOAuthLibCoreBackendErrorHandling |
python | Pylons__pyramid | tests/test_wsgi.py | {
"start": 748,
"end": 4594
} | class ____(unittest.TestCase):
def _callFUT(self, app):
from pyramid.wsgi import wsgiapp2
return wsgiapp2(app)
def test_wsgiapp2_none(self):
self.assertRaises(ValueError, self._callFUT, None)
def test_decorator_with_subpath_and_view_name(self):
context = DummyContext()
request = DummyRequest()
request.subpath = ('subpath',)
request.environ = {
'SCRIPT_NAME': '/foo',
'PATH_INFO': '/b/view_name/subpath',
}
decorator = self._callFUT(dummyapp)
response = decorator(context, request)
self.assertEqual(response, dummyapp)
self.assertEqual(request.environ['PATH_INFO'], '/subpath')
self.assertEqual(request.environ['SCRIPT_NAME'], '/foo/b/view_name')
def test_decorator_with_subpath_no_view_name(self):
context = DummyContext()
request = DummyRequest()
request.subpath = ('subpath',)
request.environ = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/b/subpath'}
decorator = self._callFUT(dummyapp)
response = decorator(context, request)
self.assertEqual(response, dummyapp)
self.assertEqual(request.environ['PATH_INFO'], '/subpath')
self.assertEqual(request.environ['SCRIPT_NAME'], '/foo/b')
def test_decorator_no_subpath_with_view_name(self):
context = DummyContext()
request = DummyRequest()
request.subpath = ()
request.environ = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/b/view_name'}
decorator = self._callFUT(dummyapp)
response = decorator(context, request)
self.assertEqual(response, dummyapp)
self.assertEqual(request.environ['PATH_INFO'], '/')
self.assertEqual(request.environ['SCRIPT_NAME'], '/foo/b/view_name')
def test_decorator_traversed_empty_with_view_name(self):
context = DummyContext()
request = DummyRequest()
request.subpath = ()
request.environ = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/view_name'}
decorator = self._callFUT(dummyapp)
response = decorator(context, request)
self.assertEqual(response, dummyapp)
self.assertEqual(request.environ['PATH_INFO'], '/')
self.assertEqual(request.environ['SCRIPT_NAME'], '/foo/view_name')
def test_decorator_traversed_empty_no_view_name(self):
context = DummyContext()
request = DummyRequest()
request.subpath = ()
request.environ = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/'}
decorator = self._callFUT(dummyapp)
response = decorator(context, request)
self.assertEqual(response, dummyapp)
self.assertEqual(request.environ['PATH_INFO'], '/')
self.assertEqual(request.environ['SCRIPT_NAME'], '/foo')
def test_decorator_traversed_empty_no_view_name_no_script_name(self):
context = DummyContext()
request = DummyRequest()
request.subpath = ()
request.environ = {'SCRIPT_NAME': '', 'PATH_INFO': '/'}
decorator = self._callFUT(dummyapp)
response = decorator(context, request)
self.assertEqual(response, dummyapp)
self.assertEqual(request.environ['PATH_INFO'], '/')
self.assertEqual(request.environ['SCRIPT_NAME'], '')
def test_decorator_on_callable_object_instance(self):
context = DummyContext()
request = DummyRequest()
request.subpath = ()
request.environ = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/'}
app = DummyApp()
decorator = self._callFUT(app)
response = decorator(context, request)
self.assertEqual(response, app)
self.assertEqual(request.environ['PATH_INFO'], '/')
self.assertEqual(request.environ['SCRIPT_NAME'], '/foo')
def dummyapp(environ, start_response):
""" """
| WSGIApp2Tests |
python | pandas-dev__pandas | pandas/tests/frame/indexing/test_getitem.py | {
"start": 12995,
"end": 14437
} | class ____:
def test_getitem_slice_float64(self, frame_or_series):
values = np.arange(10.0, 50.0, 2)
index = Index(values)
start, end = values[[5, 15]]
data = np.random.default_rng(2).standard_normal((20, 3))
if frame_or_series is not DataFrame:
data = data[:, 0]
obj = frame_or_series(data, index=index)
result = obj[start:end]
expected = obj.iloc[5:16]
tm.assert_equal(result, expected)
result = obj.loc[start:end]
tm.assert_equal(result, expected)
def test_getitem_datetime_slice(self):
# GH#43223
df = DataFrame(
{"a": 0},
index=DatetimeIndex(
[
"11.01.2011 22:00",
"11.01.2011 23:00",
"12.01.2011 00:00",
"2011-01-13 00:00",
]
),
)
with pytest.raises(
KeyError, match="Value based partial slicing on non-monotonic"
):
df["2011-01-01":"2011-11-01"]
def test_getitem_slice_same_dim_only_one_axis(self):
# GH#54622
df = DataFrame(np.random.default_rng(2).standard_normal((10, 8)))
result = df.iloc[(slice(None, None, 2),)]
assert result.shape == (5, 8)
expected = df.iloc[slice(None, None, 2), slice(None)]
tm.assert_frame_equal(result, expected)
| TestGetitemSlice |
python | doocs__leetcode | solution/2300-2399/2342.Max Sum of a Pair With Equal Sum of Digits/Solution.py | {
"start": 0,
"end": 348
} | class ____:
def maximumSum(self, nums: List[int]) -> int:
d = defaultdict(int)
ans = -1
for v in nums:
x, y = 0, v
while y:
x += y % 10
y //= 10
if x in d:
ans = max(ans, d[x] + v)
d[x] = max(d[x], v)
return ans
| Solution |
python | conda__conda | conda/gateways/connection/session.py | {
"start": 1337,
"end": 3972
} | class ____(BaseAdapter):
def send(self, request: Request, *args, **kwargs):
raise OfflineError(
f"EnforceUnusedAdapter called with url {request.url}.\n"
"This command is using a remote connection in offline mode."
)
def close(self):
raise NotImplementedError()
def get_channel_name_from_url(url: str) -> str | None:
"""
Given a URL, determine the channel it belongs to and return its name.
"""
return Channel.from_url(url).canonical_name
@cache
def get_session(url: str):
"""
Function that determines the correct Session object to be returned
based on the URL that is passed in.
"""
channel_name = get_channel_name_from_url(url)
# If for whatever reason a channel name can't be determined, (should be unlikely)
# we just return the default session object.
if channel_name is None:
return CondaSession()
# We ensure here if there are duplicates defined, we choose the last one
channel_settings = {}
for settings in context.channel_settings:
channel = settings.get("channel", "")
if channel == channel_name:
# First we check for exact match
channel_settings = settings
continue
# If we don't have an exact match, we attempt to match a URL pattern
parsed_url = urlparse(url)
parsed_setting = urlparse(channel)
# We require that the schemes must be identical to prevent downgrade attacks.
# This includes the case of a scheme-less pattern like "*", which is not allowed.
if parsed_setting.scheme != parsed_url.scheme:
continue
url_without_schema = parsed_url.netloc + parsed_url.path
pattern = parsed_setting.netloc + parsed_setting.path
if fnmatch(url_without_schema, pattern):
channel_settings = settings
auth_handler = channel_settings.get("auth", "").strip() or None
# Return default session object
if auth_handler is None:
return CondaSession()
auth_handler_cls = context.plugin_manager.get_auth_handler(auth_handler)
if not auth_handler_cls:
return CondaSession()
return CondaSession(auth=auth_handler_cls(channel_name))
def get_session_storage_key(auth) -> str:
"""
Function that determines which storage key to use for our CondaSession object caching
"""
if auth is None:
return "default"
if isinstance(auth, tuple):
return hash(auth)
auth_type = type(auth)
return f"{auth_type.__module__}.{auth_type.__qualname__}::{auth.channel_name}"
| EnforceUnusedAdapter |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py | {
"start": 5681,
"end": 6315
} | class ____(IncrementalShopifyStream):
"""
Collects stream does not support Incremental Refresh based on datetime fields, only `since_id` is supported:
https://shopify.dev/docs/admin-api/rest/reference/products/collect
The Collect stream is the link between Products and Collections, if the Collection is created for Products,
the `collect` record is created, it's reasonable to Full Refresh all collects. As for Incremental refresh -
we would use the since_id specificaly for this stream.
"""
data_field = "collects"
cursor_field = "id"
order_field = "id"
filter_field = "since_id"
| Collects |
python | huggingface__transformers | src/transformers/generation/logits_process.py | {
"start": 86239,
"end": 90992
} | class ____(LogitsProcessor):
r"""
[`LogitsProcessor`] that exponentially increases the score of the `eos_token_id` after `start_index` has been
reached. This allows generating shorter sequences without having a hard cutoff, allowing the `eos_token` to be
predicted in a meaningful position.
Args:
exponential_decay_length_penalty (`tuple(int, float)`):
This tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty
starts and `decay_factor` represents the factor of exponential decay
eos_token_id (`Union[int, list[int], torch.Tensor]`):
The id(s) of the *end-of-sequence* token.
input_ids_seq_length (`int`):
The length of the input sequence.
Examples:
```python
>>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
>>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
>>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
>>> text = "Just wanted to let you know, I"
>>> inputs = tokenizer(text, return_tensors="pt")
>>> # Let's consider that we want short sentences, so we limit `max_length=30`. However, we observe that the answer
>>> # tends to end abruptly.
>>> set_seed(1)
>>> outputs = model.generate(**inputs, do_sample=True, temperature=0.9, max_length=30, pad_token_id=50256)
>>> print(tokenizer.batch_decode(outputs)[0])
Just wanted to let you know, I received a link to an ebook, the book How To Start A Social Network which was
published in 2010. Although
>>> # To promote the appearance of the EOS token at the right time, we add the `exponential_decay_length_penalty =
>>> # (start_index, decay_factor)`. Instead of cutting at max_tokens, the output comes to an end before and usually
>>> # with more meaning. What happens is that starting from `start_index` the EOS token score will be increased
>>> # by `decay_factor` exponentially. However, if you set a high decay factor, you may also end up with abruptly
>>> # ending sequences.
>>> set_seed(1)
>>> outputs = model.generate(
... **inputs,
... do_sample=True,
... temperature=0.9,
... max_length=30,
... pad_token_id=50256,
... exponential_decay_length_penalty=(15, 1.6),
... )
>>> print(tokenizer.batch_decode(outputs)[0])
Just wanted to let you know, I received a link to an ebook, the book How To Start A Social Network
which<|endoftext|>
>>> # With a small decay factor, you will have a higher chance of getting a meaningful sequence.
>>> set_seed(1)
>>> outputs = model.generate(
... **inputs,
... do_sample=True,
... temperature=0.9,
... max_length=30,
... pad_token_id=50256,
... exponential_decay_length_penalty=(15, 1.01),
... )
>>> print(tokenizer.batch_decode(outputs)[0])
Just wanted to let you know, I received a link to an ebook, the book How To Start A Social Network which was
published in 2010.<|endoftext|>
```
"""
def __init__(
self,
exponential_decay_length_penalty: tuple[int, float],
eos_token_id: int | list[int] | torch.Tensor,
input_ids_seq_length: int,
):
self.regulation_start = exponential_decay_length_penalty[0] + input_ids_seq_length
self.regulation_factor = exponential_decay_length_penalty[1]
if not isinstance(eos_token_id, torch.Tensor):
if isinstance(eos_token_id, int):
eos_token_id = [eos_token_id]
eos_token_id = torch.tensor(eos_token_id)
self.eos_token_id = eos_token_id
if torch.is_floating_point(eos_token_id) or (eos_token_id < 0).any():
raise ValueError(f"`eos_token_id` has to be a list of positive integers, but is {eos_token_id}")
@add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
cur_len = input_ids.shape[-1]
self.eos_token_id = self.eos_token_id.to(scores.device)
penalties = torch.zeros_like(scores)
scores_processed = scores
if cur_len > self.regulation_start:
penalty_idx = cur_len - self.regulation_start
# To support negative logits we compute the penalty of the absolute value and add to the original logit
penalty = torch.abs(scores[:, self.eos_token_id]) * (pow(self.regulation_factor, penalty_idx) - 1)
penalties[:, self.eos_token_id] = penalty
scores_processed = scores + penalties
return scores_processed
| ExponentialDecayLengthPenalty |
python | readthedocs__readthedocs.org | readthedocs/core/unresolver.py | {
"start": 3179,
"end": 4393
} | class ____:
# The domain that was used to extract the information from.
source_domain: str
source: DomainSourceType
project: Project
# Domain object for custom domains.
domain: Domain = None
external_version_slug: str = None
@property
def is_from_custom_domain(self):
return self.source == DomainSourceType.custom_domain
@property
def is_from_public_domain(self):
return self.source == DomainSourceType.public_domain
@property
def is_from_http_header(self):
return self.source == DomainSourceType.http_header
@property
def is_from_external_domain(self):
return self.source == DomainSourceType.external_domain
def _expand_regex(pattern):
"""
Expand a pattern with the patterns from pattern_opts.
This is used to avoid having a long regex.
"""
return re.compile(
pattern.format(
language=f"(?P<language>{pattern_opts['lang_slug']})",
version=f"(?P<version>{pattern_opts['version_slug']})",
filename=f"(?P<filename>{pattern_opts['filename_slug']})",
subproject=f"(?P<subproject>{pattern_opts['project_slug']})",
)
)
| UnresolvedDomain |
python | Netflix__metaflow | test/core/tests/resume_foreach_inner.py | {
"start": 67,
"end": 2300
} | class ____(MetaflowTest):
"""
Resuming from a foreach inner should work.
Check that data changes in all downstream steps after resume.
"""
RESUME = True
PRIORITY = 3
SKIP_GRAPHS = [
"simple_switch",
"nested_switch",
"branch_in_switch",
"foreach_in_switch",
"switch_in_branch",
"switch_in_foreach",
"recursive_switch",
"recursive_switch_inside_foreach",
]
@steps(0, ["start"])
def step_start(self):
self.data = "start"
self.after = False
@steps(0, ["foreach-nested-split", "foreach-split"], required=True)
def step_split(self):
if self.after:
assert_equals("resume", self.data)
else:
assert_equals("start", self.data)
@steps(0, ["foreach-inner"], required=True)
def inner(self):
self.after = True
if is_resumed():
self.data = "resume"
else:
self.data = "run"
raise ResumeFromHere()
self.stack = [
list(map(str, getattr(self, frame.var))) for frame in self._foreach_stack
]
self.var = ["".join(str(x[2]) for x in self.foreach_stack())]
@steps(0, ["join"], required=True)
def step_join(self, inputs):
from itertools import chain
self.var = list(sorted(chain.from_iterable(i.var for i in inputs)))
self.data = inputs[0].data
self.after = inputs[0].after
self.stack = inputs[0].stack
if self.after:
assert_equals("resume", self.data)
else:
assert_equals("start", self.data)
@steps(2, ["all"])
def step_all(self):
if self.after:
assert_equals("resume", self.data)
else:
assert_equals("start", self.data)
def check_results(self, flow, checker):
from itertools import product
checker.assert_artifact("start", "data", "start")
checker.assert_artifact("end", "data", "resume")
stack = next(iter(checker.artifact_dict("end", "stack").values()))["stack"]
expected = sorted("".join(p) for p in product(*stack))
checker.assert_artifact("end", "var", expected)
| ResumeForeachInnerTest |
python | huggingface__transformers | src/transformers/models/modernbert_decoder/modeling_modernbert_decoder.py | {
"start": 16949,
"end": 17509
} | class ____(nn.Module):
def __init__(self, config: ModernBertDecoderConfig):
super().__init__()
self.config = config
self.dense = nn.Linear(config.hidden_size, config.hidden_size, config.classifier_bias)
self.act = ACT2FN[config.classifier_activation]
self.norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps, bias=config.norm_bias)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
return self.norm(self.act(self.dense(hidden_states)))
@auto_docstring
| ModernBertDecoderPredictionHead |
python | great-expectations__great_expectations | great_expectations/core/data_context_key.py | {
"start": 2502,
"end": 3427
} | class ____(DataContextKey):
def __init__(
self,
resource_name: Optional[str] = None,
) -> None:
self._resource_name = resource_name
@property
def resource_name(self) -> Union[str, None]:
return self._resource_name
@override
def to_tuple(self) -> Tuple[str]:
"""
See parent `DataContextKey.to_tuple` for more information.
"""
return (self._resource_name or "",)
@override
def to_fixed_length_tuple(self) -> Tuple[str]:
"""
See parent `DataContextKey.to_fixed_length_tuple` for more information.
"""
return self.to_tuple()
@classmethod
@override
def from_fixed_length_tuple(cls, tuple_: tuple) -> DataContextVariableKey:
"""
See parent `DataContextKey.from_fixed_length_tuple` for more information.
"""
return cls.from_tuple(tuple_)
| DataContextVariableKey |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 860,
"end": 971
} | class ____(str, BaseEnum):
"""Scope of the role permission."""
MATCH = "match"
ALL = "all"
| RoleScope |
python | PrefectHQ__prefect | tests/server/models/test_block_documents.py | {
"start": 34385,
"end": 39468
} | class ____:
@pytest.fixture(autouse=True)
async def block_documents(self, session, block_schemas):
block_documents = []
block_documents.append(
await models.block_documents.create_block_document(
session=session,
block_document=schemas.actions.BlockDocumentCreate(
block_schema_id=block_schemas[0].id,
name="block-1",
block_type_id=block_schemas[0].block_type_id,
),
)
)
block_documents.append(
await models.block_documents.create_block_document(
session=session,
block_document=schemas.actions.BlockDocumentCreate(
block_schema_id=block_schemas[1].id,
name="block-2",
block_type_id=block_schemas[1].block_type_id,
data={"x": 1},
),
)
)
block_documents.append(
await models.block_documents.create_block_document(
session=session,
block_document=schemas.actions.BlockDocumentCreate(
block_schema_id=block_schemas[2].id,
name="block-3",
block_type_id=block_schemas[2].block_type_id,
data={"y": 2},
),
)
)
block_documents.append(
await models.block_documents.create_block_document(
session=session,
block_document=schemas.actions.BlockDocumentCreate(
block_schema_id=block_schemas[1].id,
name="block-4",
block_type_id=block_schemas[1].block_type_id,
),
)
)
block_documents.append(
await models.block_documents.create_block_document(
session=session,
block_document=schemas.actions.BlockDocumentCreate(
block_schema_id=block_schemas[2].id,
name="block-5",
block_type_id=block_schemas[2].block_type_id,
),
)
)
block_documents.append(
await models.block_documents.create_block_document(
session=session,
block_document=schemas.actions.BlockDocumentCreate(
block_schema_id=block_schemas[2].id,
block_type_id=block_schemas[2].block_type_id,
is_anonymous=True,
),
)
)
block_documents.append(
await models.block_documents.create_block_document(
session=session,
block_document=schemas.actions.BlockDocumentCreate(
name="nested-block-1",
block_schema_id=block_schemas[3].id,
block_type_id=block_schemas[3].block_type_id,
data={
"b": {"$ref": {"block_document_id": block_documents[1].id}},
"z": "index",
},
),
)
)
block_documents.append(
await models.block_documents.create_block_document(
session=session,
block_document=schemas.actions.BlockDocumentCreate(
name="nested-block-2",
block_schema_id=block_schemas[4].id,
block_type_id=block_schemas[4].block_type_id,
data={
"c": {"$ref": {"block_document_id": block_documents[2].id}},
"d": {"$ref": {"block_document_id": block_documents[5].id}},
},
),
)
)
await session.commit()
return sorted(block_documents, key=lambda b: b.name)
async def test_count_block_documents(self, session, block_documents):
read_blocks_count = await models.block_documents.count_block_documents(
session=session,
)
# by default, exclude anonymous block documents
assert read_blocks_count == len(
[b.id for b in block_documents if not b.is_anonymous]
)
async def test_count_block_documents_filter_capabilities(
self, session, block_documents
):
fly_and_swim_block_documents_count = (
await models.block_documents.count_block_documents(
session=session,
block_schema_filter=schemas.filters.BlockSchemaFilter(
block_capabilities=dict(all_=["fly", "swim"])
),
)
)
assert fly_and_swim_block_documents_count == 1
fly_block_documents_count = await models.block_documents.count_block_documents(
session=session,
block_schema_filter=schemas.filters.BlockSchemaFilter(
block_capabilities=dict(all_=["fly"])
),
)
fly_block_documents_count == 3
| TestCountBlockDocuments |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/triggers/eks.py | {
"start": 1309,
"end": 3551
} | class ____(AwsBaseWaiterTrigger):
"""
Trigger for EksCreateClusterOperator.
The trigger will asynchronously wait for the cluster to be created.
:param cluster_name: The name of the EKS cluster
:param waiter_delay: The amount of time in seconds to wait between attempts.
:param waiter_max_attempts: The maximum number of attempts to be made.
:param aws_conn_id: The Airflow connection used for AWS credentials.
:param region_name: Which AWS region the connection should use.
If this is None or empty then the default boto3 behaviour is used.
"""
def __init__(
self,
cluster_name: str,
waiter_delay: int,
waiter_max_attempts: int,
aws_conn_id: str | None,
region_name: str | None = None,
):
super().__init__(
serialized_fields={"cluster_name": cluster_name, "region_name": region_name},
waiter_name="cluster_active",
waiter_args={"name": cluster_name},
failure_message="Error checking Eks cluster",
status_message="Eks cluster status is",
status_queries=["cluster.status"],
return_value=None,
waiter_delay=waiter_delay,
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
region_name=region_name,
)
def hook(self) -> AwsGenericHook:
return EksHook(aws_conn_id=self.aws_conn_id, region_name=self.region_name)
async def run(self):
async with await self.hook().get_async_conn() as client:
waiter = client.get_waiter(self.waiter_name)
try:
await async_wait(
waiter,
self.waiter_delay,
self.attempts,
self.waiter_args,
self.failure_message,
self.status_message,
self.status_queries,
)
except AirflowException as exception:
self.log.error("Error creating cluster: %s", exception)
yield TriggerEvent({"status": "failed"})
else:
yield TriggerEvent({"status": "success"})
| EksCreateClusterTrigger |
python | PrefectHQ__prefect | src/prefect/events/filters.py | {
"start": 1188,
"end": 2283
} | class ____(PrefectBaseModel, extra="forbid"): # type: ignore[call-arg]
"""A base class for filtering event data."""
def get_filters(self) -> list["EventDataFilter"]:
filters: list[EventDataFilter] = []
for filter in [
getattr(self, name) for name in self.__class__.model_fields.keys()
]:
# Any embedded list of filters are flattened and thus ANDed together
subfilters: list[EventDataFilter] = (
filter if isinstance(filter, list) else [filter]
)
for subfilter in subfilters:
if not isinstance(subfilter, EventDataFilter):
continue
filters.append(subfilter)
return filters
def includes(self, event: Event) -> bool:
"""Does the given event match the criteria of this filter?"""
return all(filter.includes(event) for filter in self.get_filters())
def excludes(self, event: Event) -> bool:
"""Would the given filter exclude this event?"""
return not self.includes(event)
| EventDataFilter |
python | numpy__numpy | numpy/exceptions.py | {
"start": 1194,
"end": 1477
} | class ____(RuntimeWarning):
"""
The warning raised when casting a complex dtype to a real dtype.
As implemented, casting a complex number to a real discards its imaginary
part, but this behavior may not be what the user actually wants.
"""
pass
| ComplexWarning |
python | MongoEngine__mongoengine | tests/fixtures.py | {
"start": 697,
"end": 800
} | class ____(DynamicEmbeddedDocument):
date = DateTimeField(default=datetime.now)
| PickleDynamicEmbedded |
python | keon__algorithms | tests/test_maths.py | {
"start": 10717,
"end": 11047
} | class ____(unittest.TestCase):
"""[summary]
Test for the file hailstone.py
Arguments:
unittest {[type]} -- [description]
"""
def test_hailstone(self):
self.assertEqual([8, 4, 2, 1], hailstone.hailstone(8))
self.assertEqual([10, 5, 16, 8, 4, 2, 1], hailstone.hailstone(10))
| TestHailstone |
python | getsentry__sentry | fixtures/safe_migrations_apps/bad_flow_delete_field_double_pending_app/migrations/0001_initial.py | {
"start": 153,
"end": 645
} | class ____(CheckedMigration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="TestTable",
fields=[
(
"id",
models.AutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
),
),
("field", models.IntegerField(null=True)),
],
),
]
| Migration |
python | pandas-dev__pandas | pandas/tests/scalar/timedelta/test_arithmetic.py | {
"start": 31582,
"end": 39803
} | class ____:
def test_compare_pytimedelta_bounds(self):
# GH#49021 don't overflow on comparison with very large pytimedeltas
for unit in ["ns", "us"]:
tdmax = Timedelta.max.as_unit(unit).max
tdmin = Timedelta.min.as_unit(unit).min
assert tdmax < timedelta.max
assert tdmax <= timedelta.max
assert not tdmax > timedelta.max
assert not tdmax >= timedelta.max
assert tdmax != timedelta.max
assert not tdmax == timedelta.max
assert tdmin > timedelta.min
assert tdmin >= timedelta.min
assert not tdmin < timedelta.min
assert not tdmin <= timedelta.min
assert tdmin != timedelta.min
assert not tdmin == timedelta.min
# But the "ms" and "s"-reso bounds extend pass pytimedelta
for unit in ["ms", "s"]:
tdmax = Timedelta.max.as_unit(unit).max
tdmin = Timedelta.min.as_unit(unit).min
assert tdmax > timedelta.max
assert tdmax >= timedelta.max
assert not tdmax < timedelta.max
assert not tdmax <= timedelta.max
assert tdmax != timedelta.max
assert not tdmax == timedelta.max
assert tdmin < timedelta.min
assert tdmin <= timedelta.min
assert not tdmin > timedelta.min
assert not tdmin >= timedelta.min
assert tdmin != timedelta.min
assert not tdmin == timedelta.min
def test_compare_pytimedelta_bounds2(self):
# a pytimedelta outside the microsecond bounds
pytd = timedelta(days=999999999, seconds=86399)
# NB: np.timedelta64(td, "s"") incorrectly overflows
td64 = np.timedelta64(pytd.days, "D") + np.timedelta64(pytd.seconds, "s")
td = Timedelta(td64)
assert td.days == pytd.days
assert td.seconds == pytd.seconds
assert td == pytd
assert not td != pytd
assert not td < pytd
assert not td > pytd
assert td <= pytd
assert td >= pytd
td2 = td - Timedelta(seconds=1).as_unit("s")
assert td2 != pytd
assert not td2 == pytd
assert td2 < pytd
assert td2 <= pytd
assert not td2 > pytd
assert not td2 >= pytd
def test_compare_tick(self, tick_classes):
cls = tick_classes
off = cls(4)
td = off._as_pd_timedelta
assert isinstance(td, Timedelta)
assert td == off
assert not td != off
assert td <= off
assert td >= off
assert not td < off
assert not td > off
assert not td == 2 * off
assert td != 2 * off
assert td <= 2 * off
assert td < 2 * off
assert not td >= 2 * off
assert not td > 2 * off
def test_comparison_object_array(self):
# analogous to GH#15183
td = Timedelta("2 days")
other = Timedelta("3 hours")
arr = np.array([other, td], dtype=object)
res = arr == td
expected = np.array([False, True], dtype=bool)
assert (res == expected).all()
# 2D case
arr = np.array([[other, td], [td, other]], dtype=object)
res = arr != td
expected = np.array([[True, False], [False, True]], dtype=bool)
assert res.shape == expected.shape
assert (res == expected).all()
def test_compare_timedelta_ndarray(self):
# GH#11835
periods = [Timedelta("0 days 01:00:00"), Timedelta("0 days 01:00:00")]
arr = np.array(periods)
result = arr[0] > arr
expected = np.array([False, False])
tm.assert_numpy_array_equal(result, expected)
def test_compare_td64_ndarray(self):
# GG#33441
arr = np.arange(5).astype("timedelta64[ns]")
td = Timedelta(arr[1])
expected = np.array([False, True, False, False, False], dtype=bool)
result = td == arr
tm.assert_numpy_array_equal(result, expected)
result = arr == td
tm.assert_numpy_array_equal(result, expected)
result = td != arr
tm.assert_numpy_array_equal(result, ~expected)
result = arr != td
tm.assert_numpy_array_equal(result, ~expected)
def test_compare_custom_object(self):
"""
Make sure non supported operations on Timedelta returns NonImplemented
and yields to other operand (GH#20829).
"""
class CustomClass:
def __init__(self, cmp_result=None) -> None:
self.cmp_result = cmp_result
def generic_result(self):
if self.cmp_result is None:
return NotImplemented
else:
return self.cmp_result
def __eq__(self, other):
return self.generic_result()
def __gt__(self, other):
return self.generic_result()
t = Timedelta("1s")
assert t != "string"
assert t != 1
assert t != CustomClass()
assert t != CustomClass(cmp_result=False)
assert t < CustomClass(cmp_result=True)
assert not t < CustomClass(cmp_result=False)
assert t == CustomClass(cmp_result=True)
@pytest.mark.parametrize("val", ["string", 1])
def test_compare_unknown_type(self, val):
# GH#20829
t = Timedelta("1s")
msg = "not supported between instances of 'Timedelta' and '(int|str)'"
with pytest.raises(TypeError, match=msg):
t >= val
with pytest.raises(TypeError, match=msg):
t > val
with pytest.raises(TypeError, match=msg):
t <= val
with pytest.raises(TypeError, match=msg):
t < val
def test_ops_notimplemented():
class Other:
pass
other = Other()
td = Timedelta("1 day")
assert td.__add__(other) is NotImplemented
assert td.__sub__(other) is NotImplemented
assert td.__truediv__(other) is NotImplemented
assert td.__mul__(other) is NotImplemented
assert td.__floordiv__(other) is NotImplemented
def test_ops_error_str():
# GH#13624
td = Timedelta("1 day")
for left, right in [(td, "a"), ("a", td)]:
msg = "|".join(
[
"unsupported operand type",
r'can only concatenate str \(not "Timedelta"\) to str',
"must be str, not Timedelta",
]
)
with pytest.raises(TypeError, match=msg):
left + right
msg = "not supported between instances of"
with pytest.raises(TypeError, match=msg):
left > right
assert not left == right
assert left != right
@pytest.mark.parametrize("box", [True, False])
def test_ops_str_deprecated(box):
# GH#59653
td = Timedelta("1 day")
item = "1"
if box:
item = np.array([item], dtype=object)
msg = "Scalar operations between Timedelta and string are deprecated"
with tm.assert_produces_warning(Pandas4Warning, match=msg):
td + item
with tm.assert_produces_warning(Pandas4Warning, match=msg):
item + td
with tm.assert_produces_warning(Pandas4Warning, match=msg):
td - item
with tm.assert_produces_warning(Pandas4Warning, match=msg):
item - td
with tm.assert_produces_warning(Pandas4Warning, match=msg):
item / td
if not box:
with tm.assert_produces_warning(Pandas4Warning, match=msg):
td / item
with tm.assert_produces_warning(Pandas4Warning, match=msg):
item // td
with tm.assert_produces_warning(Pandas4Warning, match=msg):
td // item
else:
msg = "|".join(
[
"ufunc 'divide' cannot use operands",
"Invalid dtype object for __floordiv__",
r"unsupported operand type\(s\) for /: 'int' and 'str'",
]
)
with pytest.raises(TypeError, match=msg):
td / item
with pytest.raises(TypeError, match=msg):
item // td
with pytest.raises(TypeError, match=msg):
td // item
| TestTimedeltaComparison |
python | pydantic__pydantic | tests/mypy/modules/plugin_success_baseConfig.py | {
"start": 4220,
"end": 4566
} | class ____(BaseModel):
# Required
a: int
b: int = Field()
c: int = Field(...)
# Default
d: int = Field(1)
# Default factory
g: list[int] = Field(default_factory=_default_factory_list)
h: str = Field(default_factory=_default_factory_str)
i: str = Field(default_factory=lambda: 'test')
| FieldDefaultTestingModel |
python | huggingface__transformers | tests/models/wav2vec2/test_modeling_wav2vec2.py | {
"start": 50312,
"end": 77939
} | class ____(unittest.TestCase):
def tearDown(self):
super().tearDown()
# clean-up as much as possible GPU memory occupied by PyTorch
cleanup(torch_device, gc_collect=True)
def _load_datasamples(self, num_samples):
ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
# automatic decoding with librispeech
speech_samples = ds.sort("id").filter(
lambda x: x["id"] in [f"1272-141231-000{i}" for i in range(num_samples)]
)[:num_samples]["audio"]
return [x["array"] for x in speech_samples]
def _load_superb(self, task, num_samples):
ds = load_dataset("anton-l/superb_dummy", task, split="test")
return ds[:num_samples]
def test_inference_ctc_normal(self):
model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h")
model.to(torch_device)
processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h", do_lower_case=True)
input_speech = self._load_datasamples(1)
input_values = processor(input_speech, return_tensors="pt").input_values.to(torch_device)
with torch.no_grad():
logits = model(input_values).logits
predicted_ids = torch.argmax(logits, dim=-1)
predicted_trans = processor.batch_decode(predicted_ids)
EXPECTED_TRANSCRIPTIONS = ["a man said to the universe sir i exist"]
self.assertListEqual(predicted_trans, EXPECTED_TRANSCRIPTIONS)
def test_inference_ctc_normal_batched(self):
model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h")
model.to(torch_device)
processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h", do_lower_case=True)
input_speech = self._load_datasamples(2)
inputs = processor(input_speech, return_tensors="pt", padding=True)
input_values = inputs.input_values.to(torch_device)
with torch.no_grad():
logits = model(input_values).logits
predicted_ids = torch.argmax(logits, dim=-1)
predicted_trans = processor.batch_decode(predicted_ids)
EXPECTED_TRANSCRIPTIONS = [
"a man said to the universe sir i exist",
"sweat covered brion's body trickling into the tight lowing cloth that was the only garment he wore",
]
self.assertListEqual(predicted_trans, EXPECTED_TRANSCRIPTIONS)
def test_inference_ctc_robust_batched(self):
model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-large-960h-lv60-self").to(torch_device)
processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-large-960h-lv60-self", do_lower_case=True)
input_speech = self._load_datasamples(4)
inputs = processor(input_speech, return_tensors="pt", padding=True)
input_values = inputs.input_values.to(torch_device)
attention_mask = inputs.attention_mask.to(torch_device)
with torch.no_grad():
logits = model(input_values, attention_mask=attention_mask).logits
predicted_ids = torch.argmax(logits, dim=-1)
predicted_trans = processor.batch_decode(predicted_ids)
EXPECTED_TRANSCRIPTIONS = [
"a man said to the universe sir i exist",
"sweat covered brion's body trickling into the tight loin cloth that was the only garment he wore",
"the cut on his chest still dripping blood the ache of his overstrained eyes even the soaring arena around"
" him with the thousands of spectators were trivialities not worth thinking about",
"his instant panic was followed by a small sharp blow high on his chest",
]
self.assertListEqual(predicted_trans, EXPECTED_TRANSCRIPTIONS)
@unittest.skipIf(torch_device != "cpu", "cannot make deterministic on GPU")
def test_inference_integration(self):
model = Wav2Vec2ForPreTraining.from_pretrained("facebook/wav2vec2-base")
model.to(torch_device)
feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("facebook/wav2vec2-base")
input_speech = self._load_datasamples(2)
inputs_dict = feature_extractor(input_speech, return_tensors="pt", padding=True)
batch_size = inputs_dict["input_values"].shape[0]
feature_seq_length = int(model._get_feat_extract_output_lengths(inputs_dict["input_values"].shape[1]))
features_shape = (batch_size, feature_seq_length)
np.random.seed(4)
mask_time_indices = _compute_mask_indices(
features_shape,
model.config.mask_time_prob,
model.config.mask_time_length,
min_masks=2,
)
mask_time_indices = torch.from_numpy(mask_time_indices).to(torch_device)
with torch.no_grad():
outputs = model(
inputs_dict.input_values.to(torch_device),
mask_time_indices=mask_time_indices,
)
# compute cosine similarity
cosine_sim = torch.cosine_similarity(outputs.projected_states, outputs.projected_quantized_states, dim=-1)
# retrieve cosine sim of masked features
cosine_sim_masked = cosine_sim[mask_time_indices]
# cosine similarity of model is all > 0.5 as model is
# pre-trained on contrastive loss
# fmt: off
expected_cosine_sim_masked = torch.tensor([
0.8523, 0.5860, 0.6905, 0.5557, 0.7456, 0.5249, 0.6639, 0.7654, 0.7565,
0.8167, 0.8222, 0.7960, 0.8034, 0.8166, 0.8310, 0.8263, 0.8274, 0.8258,
0.8179, 0.8412, 0.8536, 0.5098, 0.4728, 0.6461, 0.4498, 0.6002, 0.5774,
0.6457, 0.7123, 0.5668, 0.6866, 0.4960, 0.6293, 0.7423, 0.7419, 0.7526,
0.7768, 0.4898, 0.5393, 0.8183
], device=torch_device)
# fmt: on
torch.testing.assert_close(cosine_sim_masked, expected_cosine_sim_masked, rtol=1e-3, atol=1e-3)
def test_inference_pretrained(self):
model = Wav2Vec2ForPreTraining.from_pretrained("facebook/wav2vec2-base")
model.to(torch_device)
feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
"facebook/wav2vec2-base", return_attention_mask=True
)
input_speech = self._load_datasamples(2)
inputs_dict = feature_extractor(input_speech, return_tensors="pt", padding=True)
batch_size = inputs_dict["input_values"].shape[0]
feature_seq_length = int(model._get_feat_extract_output_lengths(inputs_dict["input_values"].shape[1]))
features_shape = (batch_size, feature_seq_length)
torch.manual_seed(0)
mask_time_indices = _compute_mask_indices(
features_shape,
model.config.mask_time_prob,
model.config.mask_time_length,
min_masks=2,
)
mask_time_indices = torch.from_numpy(mask_time_indices).to(torch_device)
with torch.no_grad():
outputs = model(
inputs_dict.input_values.to(torch_device),
attention_mask=inputs_dict.attention_mask.to(torch_device),
mask_time_indices=mask_time_indices,
)
# compute cosine similarity
cosine_sim = torch.cosine_similarity(outputs.projected_states, outputs.projected_quantized_states, dim=-1)
# retrieve cosine sim of masked features
cosine_sim_masked = cosine_sim[mask_time_indices]
# ... now compare to randomly initialized model
config = Wav2Vec2Config.from_pretrained("facebook/wav2vec2-base")
model_rand = Wav2Vec2ForPreTraining(config).to(torch_device).eval()
with torch.no_grad():
outputs_rand = model_rand(
inputs_dict.input_values.to(torch_device),
attention_mask=inputs_dict.attention_mask.to(torch_device),
mask_time_indices=mask_time_indices,
)
# compute cosine similarity
cosine_sim_rand = torch.cosine_similarity(
outputs_rand.projected_states, outputs_rand.projected_quantized_states, dim=-1
)
# retrieve cosine sim of masked features
cosine_sim_masked_rand = cosine_sim_rand[mask_time_indices]
# a pretrained wav2vec2 model has learned to predict the quantized latent states
# => the cosine similarity between quantized states and predicted states > 0.5
# a random wav2vec2 model has not learned to predict the quantized latent states
# => the cosine similarity between quantized states and predicted states is very likely < 0.1
self.assertTrue(cosine_sim_masked.mean().item() - 5 * cosine_sim_masked_rand.mean().item() > 0)
@unittest.skipIf(torch_device != "cpu", "cannot make deterministic on GPU")
def test_loss_pretraining(self):
model = Wav2Vec2ForPreTraining.from_pretrained(
"facebook/wav2vec2-base",
attention_dropout=0.0,
feat_proj_dropout=0.0,
hidden_dropout=0.0,
layerdrop=0.0,
)
model.to(torch_device).train()
feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
"facebook/wav2vec2-base", return_attention_mask=True
)
input_speech = self._load_datasamples(2)
inputs_dict = feature_extractor(input_speech, return_tensors="pt", padding=True)
batch_size = inputs_dict["input_values"].shape[0]
feature_seq_length = int(model._get_feat_extract_output_lengths(inputs_dict["input_values"].shape[1]))
features_shape = (batch_size, feature_seq_length)
torch.manual_seed(0)
np.random.seed(0)
mask_time_indices = _compute_mask_indices(
features_shape,
model.config.mask_time_prob,
model.config.mask_time_length,
min_masks=2,
)
sampled_negative_indices = _sample_negative_indices(
mask_time_indices.shape, model.config.num_negatives, mask_time_indices
)
mask_time_indices = torch.from_numpy(mask_time_indices).to(torch_device)
sampled_negative_indices = torch.from_numpy(sampled_negative_indices).to(torch_device)
with torch.no_grad():
outputs = model(
inputs_dict.input_values.to(torch_device),
attention_mask=inputs_dict.attention_mask.to(torch_device),
mask_time_indices=mask_time_indices,
sampled_negative_indices=sampled_negative_indices,
)
# check diversity loss
num_codevectors = model.config.num_codevectors_per_group * model.config.num_codevector_groups
diversity_loss = (num_codevectors - outputs.codevector_perplexity) / num_codevectors
self.assertTrue(abs(diversity_loss.item() - 0.9538) < 1e-3)
# check overall loss (contrastive loss + diversity loss)
expected_loss = 116.7094
self.assertTrue(abs(outputs.loss.item() - expected_loss) < 1e-3)
def test_inference_keyword_spotting(self):
model = Wav2Vec2ForSequenceClassification.from_pretrained("superb/wav2vec2-base-superb-ks").to(torch_device)
processor = Wav2Vec2FeatureExtractor.from_pretrained("superb/wav2vec2-base-superb-ks")
input_data = self._load_superb("ks", 4)
inputs = processor(input_data["speech"], return_tensors="pt", padding=True)
input_values = inputs.input_values.to(torch_device)
attention_mask = inputs.attention_mask.to(torch_device)
with torch.no_grad():
outputs = model(input_values, attention_mask=attention_mask)
predicted_logits, predicted_ids = torch.max(outputs.logits, dim=-1)
expected_labels = [7, 6, 10, 9]
# s3prl logits for the same batch
expected_logits = torch.tensor([6.1186, 11.8961, 10.2931, 6.0898], device=torch_device)
self.assertListEqual(predicted_ids.tolist(), expected_labels)
torch.testing.assert_close(predicted_logits, expected_logits, rtol=1e-2, atol=1e-2)
def test_inference_intent_classification(self):
model = Wav2Vec2ForSequenceClassification.from_pretrained("superb/wav2vec2-base-superb-ic").to(torch_device)
processor = Wav2Vec2FeatureExtractor.from_pretrained("superb/wav2vec2-base-superb-ic")
input_data = self._load_superb("ic", 4)
inputs = processor(input_data["speech"], return_tensors="pt", padding=True)
input_values = inputs.input_values.to(torch_device)
attention_mask = inputs.attention_mask.to(torch_device)
with torch.no_grad():
outputs = model(input_values, attention_mask=attention_mask)
predicted_logits_action, predicted_ids_action = torch.max(outputs.logits[:, :6], dim=-1)
predicted_logits_object, predicted_ids_object = torch.max(outputs.logits[:, 6:20], dim=-1)
predicted_logits_location, predicted_ids_location = torch.max(outputs.logits[:, 20:24], dim=-1)
expected_labels_action = [0, 0, 2, 3]
expected_logits_action = torch.tensor([0.4568, 11.0848, 1.6621, 9.3841], device=torch_device)
expected_labels_object = [3, 10, 3, 4]
expected_logits_object = torch.tensor([1.5322, 10.7094, 5.2469, 22.1318], device=torch_device)
expected_labels_location = [0, 0, 0, 1]
expected_logits_location = torch.tensor([1.5335, 6.5096, 10.5704, 11.0569], device=torch_device)
self.assertListEqual(predicted_ids_action.tolist(), expected_labels_action)
self.assertListEqual(predicted_ids_object.tolist(), expected_labels_object)
self.assertListEqual(predicted_ids_location.tolist(), expected_labels_location)
torch.testing.assert_close(predicted_logits_action, expected_logits_action, rtol=1e-2, atol=1e-2)
torch.testing.assert_close(predicted_logits_object, expected_logits_object, rtol=1e-2, atol=1e-2)
torch.testing.assert_close(predicted_logits_location, expected_logits_location, rtol=1e-2, atol=1e-2)
def test_inference_speaker_identification(self):
model = Wav2Vec2ForSequenceClassification.from_pretrained("superb/wav2vec2-base-superb-sid").to(torch_device)
processor = Wav2Vec2FeatureExtractor.from_pretrained("superb/wav2vec2-base-superb-sid")
input_data = self._load_superb("si", 4)
output_logits = []
with torch.no_grad():
for example in input_data["speech"]:
input = processor(example, return_tensors="pt", padding=True)
output = model(input.input_values.to(torch_device), attention_mask=None)
output_logits.append(output.logits[0])
output_logits = torch.stack(output_logits)
predicted_logits, predicted_ids = torch.max(output_logits, dim=-1)
expected_labels = [251, 1, 1, 3]
# s3prl logits for the same batch
expected_logits = torch.tensor([37.5627, 71.6362, 64.2419, 31.7778], device=torch_device)
self.assertListEqual(predicted_ids.tolist(), expected_labels)
torch.testing.assert_close(predicted_logits, expected_logits, rtol=1e-2, atol=1e-2)
def test_inference_emotion_recognition(self):
model = Wav2Vec2ForSequenceClassification.from_pretrained("superb/wav2vec2-base-superb-er").to(torch_device)
processor = Wav2Vec2FeatureExtractor.from_pretrained("superb/wav2vec2-base-superb-er")
input_data = self._load_superb("er", 4)
inputs = processor(input_data["speech"], return_tensors="pt", padding=True)
input_values = inputs.input_values.to(torch_device)
attention_mask = inputs.attention_mask.to(torch_device)
with torch.no_grad():
outputs = model(input_values, attention_mask=attention_mask)
predicted_logits, predicted_ids = torch.max(outputs.logits, dim=-1)
expected_labels = [1, 1, 2, 2]
# s3prl logits for the same batch
expected_logits = torch.tensor([2.1722, 3.0779, 8.0287, 6.6797], device=torch_device)
self.assertListEqual(predicted_ids.tolist(), expected_labels)
torch.testing.assert_close(predicted_logits, expected_logits, rtol=1e-2, atol=1e-2)
def test_phoneme_recognition(self):
model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft").to(torch_device)
processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft")
input_speech = self._load_datasamples(4)
inputs = processor(input_speech, return_tensors="pt", padding=True)
input_values = inputs.input_values.to(torch_device)
attention_mask = inputs.attention_mask.to(torch_device)
with torch.no_grad():
logits = model(input_values, attention_mask=attention_mask).logits
predicted_ids = torch.argmax(logits, dim=-1)
predicted_trans = processor.batch_decode(predicted_ids)
EXPECTED_TRANSCRIPTIONS = [
"ɐ m æ n s ɛ d t ə ð ə j uː n ɪ v ɚ s s ɚ aɪ ɛ ɡ z ɪ s t",
"s w ɛ t k ʌ v ɚ d b ɹ iː ɔ n z b ɑː d i t ɹ ɪ k l ɪ ŋ ɪ n t ə ð ə t aɪ t l oɪ n k l ɑː θ ð æ w ʌ z ð ɪ oʊ"
" n l i ɡ ɑːɹ m ə n t h iː w ɔːɹ",
"ð ə k aɪ t ɔ n h ɪ z tʃ ɛ s t s t ɪ l d ɹ ɪ p ɪ ŋ b l ʌ d ð ɪ eɪ k ʌ v h ɪ z oʊ v ɚ s t ɹ eɪ n d aɪ z iː"
" v ə n ð ə s ɔːɹ ɹ ɪ ŋ ɐ ɹ iː n ɐ ɚ ɹ aʊ n d h ɪ m w ɪ ð ə θ aʊ z ə n d z ʌ v s p ɛ k t eɪ ɾ ɚ z w ɜː t ɹ"
" ɪ v ɪ æ l ᵻ ɾ i z n ɑː t w ɜː θ θ ɪ ŋ k ɪ ŋ ɐ b aʊ t",
"h ɪ z ɪ n s t ə n t v p æ n ɪ k w ʌ z f ɑː l oʊ d b aɪ ɐ s m ɔː l ʃ ɑːɹ p b l oʊ h aɪ ɔ n h ɪ z tʃ ɛ s t",
]
# should correspond to =>:
# [
# "a man said to the universe sir i exist",
# "sweat covered brion's body trickling into the tight loin cloth that was the only garment he wore",
# "the cut on his chest still dripping blood the ache of his overstrained eyes even the soaring arena around him with the thousands of spectators were trivialities not worth thinking about",
# "his instant panic was followed by a small sharp blow high on his chest",
# ]
self.assertListEqual(predicted_trans, EXPECTED_TRANSCRIPTIONS)
@require_pyctcdecode
@require_torchaudio
def test_wav2vec2_with_lm(self):
ds = load_dataset("fixie-ai/common_voice_17_0", "es", split="test", streaming=True)
sample = next(iter(ds))
resampled_audio = torchaudio.functional.resample(
torch.tensor(sample["audio"]["array"]), 48_000, 16_000
).numpy()
model = Wav2Vec2ForCTC.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm").to(
torch_device
)
processor = Wav2Vec2ProcessorWithLM.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm")
input_values = processor(resampled_audio, return_tensors="pt").input_values
with torch.no_grad():
logits = model(input_values.to(torch_device)).logits
transcription = processor.batch_decode(logits.cpu().numpy()).text
expected_transcription = "el resto de los equipos se mantienen en su sede"
self.assertEqual(transcription[0], expected_transcription)
@require_pyctcdecode
@require_torchaudio
def test_wav2vec2_with_lm_pool(self):
ds = load_dataset("fixie-ai/common_voice_17_0", "es", split="test", streaming=True)
sample = next(iter(ds))
resampled_audio = torchaudio.functional.resample(
torch.tensor(sample["audio"]["array"]), 48_000, 16_000
).numpy()
model = Wav2Vec2ForCTC.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm").to(
torch_device
)
processor = Wav2Vec2ProcessorWithLM.from_pretrained("patrickvonplaten/wav2vec2-large-xlsr-53-spanish-with-lm")
input_values = processor(resampled_audio, return_tensors="pt").input_values
with torch.no_grad():
logits = model(input_values.to(torch_device)).logits
# test user-managed pool
with multiprocessing.get_context("fork").Pool(2) as pool:
transcription = processor.batch_decode(logits.cpu().numpy(), pool).text
expected_transcription = "el resto de los equipos se mantienen en su sede"
self.assertEqual(transcription[0], expected_transcription)
# user-managed pool + num_processes should trigger a warning
with (
CaptureLogger(processing_wav2vec2_with_lm.logger) as cl,
multiprocessing.get_context("fork").Pool(2) as pool,
):
transcription = processor.batch_decode(logits.cpu().numpy(), pool, num_processes=2).text
self.assertIn("num_process", cl.out)
self.assertIn("it will be ignored", cl.out)
self.assertEqual(transcription[0], expected_transcription)
@require_pyctcdecode
@require_torchaudio
def test_wav2vec2_with_lm_invalid_pool(self):
run_test_in_subprocess(test_case=self, target_func=_test_wav2vec2_with_lm_invalid_pool, inputs=None)
def test_inference_diarization(self):
model = Wav2Vec2ForAudioFrameClassification.from_pretrained("anton-l/wav2vec2-base-superb-sd").to(torch_device)
processor = Wav2Vec2FeatureExtractor.from_pretrained("anton-l/wav2vec2-base-superb-sd")
input_data = self._load_superb("sd", 4)
inputs = processor(input_data["speech"], return_tensors="pt", padding=True, sampling_rate=16_000)
input_values = inputs.input_values.to(torch_device)
attention_mask = inputs.attention_mask.to(torch_device)
with torch.no_grad():
outputs = model(input_values, attention_mask=attention_mask)
# labels is a one-hot array of shape (num_frames, num_speakers)
labels = (outputs.logits > 0).long()
# s3prl logits for the same batch
expected_logits = torch.tensor(
[
[[-5.2807, -5.1272], [-5.4059, -4.7757], [-5.2764, -4.9621], [-5.0117, -4.5851]],
[[-1.7643, -0.5462], [-1.7369, -0.2649], [-1.5066, -0.6200], [-4.5703, -2.4863]],
[[-0.8656, -0.4783], [-0.8899, -0.3289], [-0.9267, -0.5781], [-0.7817, -0.4619]],
[[-4.8625, -2.5316], [-5.2339, -2.2155], [-4.9835, -2.0344], [-4.4727, -1.8421]],
],
device=torch_device,
)
self.assertEqual(labels[0, :, 0].sum(), 555)
self.assertEqual(labels[0, :, 1].sum(), 299)
torch.testing.assert_close(outputs.logits[:, :4], expected_logits, rtol=1e-2, atol=1e-2)
def test_inference_speaker_verification(self):
model = Wav2Vec2ForXVector.from_pretrained("anton-l/wav2vec2-base-superb-sv").to(torch_device)
processor = Wav2Vec2FeatureExtractor.from_pretrained("anton-l/wav2vec2-base-superb-sv")
input_data = self._load_superb("si", 4)
inputs = processor(input_data["speech"], return_tensors="pt", padding=True, sampling_rate=16_000)
labels = torch.tensor([5, 1, 1, 3], device=torch_device).T
with torch.no_grad():
input_values = inputs.input_values.to(torch_device)
attention_mask = inputs.attention_mask.to(torch_device)
outputs = model(input_values, attention_mask=attention_mask, labels=labels)
embeddings = torch.nn.functional.normalize(outputs.embeddings, dim=-1).cpu()
cosine_sim = torch.nn.CosineSimilarity(dim=-1)
# id10002 vs id10002
self.assertAlmostEqual(cosine_sim(embeddings[1], embeddings[2]).numpy(), 0.9758, 3)
# id10006 vs id10002
self.assertAlmostEqual(cosine_sim(embeddings[0], embeddings[1]).numpy(), 0.7579, 3)
# id10002 vs id10004
self.assertAlmostEqual(cosine_sim(embeddings[2], embeddings[3]).numpy(), 0.7594, 3)
self.assertAlmostEqual(outputs.loss.item(), 17.7963, 2)
@require_torchaudio
def test_inference_mms_1b_all(self):
model = Wav2Vec2ForCTC.from_pretrained("facebook/mms-1b-all").to(torch_device)
processor = Wav2Vec2Processor.from_pretrained("facebook/mms-1b-all")
LANG_MAP = {"it": "ita", "es": "spa", "fr": "fra", "en": "eng"}
def run_model(lang):
ds = load_dataset("fixie-ai/common_voice_17_0", lang, split="test", streaming=True)
sample = next(iter(ds))
wav2vec2_lang = LANG_MAP[lang]
model.load_adapter(wav2vec2_lang)
processor.tokenizer.set_target_lang(wav2vec2_lang)
resampled_audio = torchaudio.functional.resample(
torch.tensor(sample["audio"]["array"]), 48_000, 16_000
).numpy()
inputs = processor(resampled_audio, sampling_rate=16_000, return_tensors="pt")
input_values = inputs.input_values.to(torch_device)
attention_mask = inputs.attention_mask.to(torch_device)
with torch.no_grad():
outputs = model(input_values, attention_mask=attention_mask).logits
ids = torch.argmax(outputs, dim=-1)[0]
transcription = processor.decode(ids)
return transcription
TRANSCRIPTIONS = {
"it": "viaggiarono in italia dove lavorarono con hamilton",
"es": "el resto de los equipos se mantienen en su sede",
"fr": "il a obtenu son batchelor of lows",
"en": "joe keton disapproved of films and buster also had reservations about the media",
}
for lang in LANG_MAP:
assert run_model(lang) == TRANSCRIPTIONS[lang]
@require_flash_attn
@require_torch_gpu
@mark.flash_attn_test
def test_inference_ctc_fa2(self):
model_fa = Wav2Vec2ForCTC.from_pretrained(
"facebook/wav2vec2-base-960h", attn_implementation="flash_attention_2", dtype=torch.bfloat16
)
model_fa.to(torch_device)
processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h", do_lower_case=True)
input_speech = self._load_datasamples(1)
input_values = processor(input_speech, return_tensors="pt").input_values.to(torch_device)
with torch.no_grad():
logits = model_fa(input_values.to(torch.bfloat16)).logits
predicted_ids = torch.argmax(logits, dim=-1)
predicted_trans = processor.batch_decode(predicted_ids)
EXPECTED_TRANSCRIPTIONS = ["a man said to the universe sir i exist"]
self.assertListEqual(predicted_trans, EXPECTED_TRANSCRIPTIONS)
@require_flash_attn
@require_torch_gpu
@mark.flash_attn_test
def test_inference_ctc_fa2_batched(self):
model_fa = Wav2Vec2ForCTC.from_pretrained(
"facebook/wav2vec2-base-960h", attn_implementation="flash_attention_2", dtype=torch.bfloat16
)
model_fa.to(torch_device)
processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h", do_lower_case=True)
input_speech = self._load_datasamples(2)
inputs = processor(input_speech, return_tensors="pt", padding=True, return_attention_mask=True)
inputs = inputs.to(torch_device)
with torch.no_grad():
logits = model_fa(inputs.input_values.to(torch.bfloat16), attention_mask=inputs.attention_mask).logits
predicted_ids = torch.argmax(logits, dim=-1)
predicted_trans = processor.batch_decode(predicted_ids)
EXPECTED_TRANSCRIPTIONS = [
"a man said to the universe sir i exist",
"sweat covered brion's body trickling into the tight lowing cloth that was the only garment he wore",
]
self.assertListEqual(predicted_trans, EXPECTED_TRANSCRIPTIONS)
| Wav2Vec2ModelIntegrationTest |
python | getsentry__sentry | src/sentry/workflow_engine/endpoints/organization_incident_groupopenperiod_index.py | {
"start": 1035,
"end": 3070
} | class ____(OrganizationEndpoint):
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
}
owner = ApiOwner.ISSUES
permission_classes = (OrganizationDetectorPermission,)
@extend_schema(
operation_id="Fetch Incident and Group Open Period Relationship",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
],
responses={
200: IncidentGroupOpenPeriodSerializer,
400: RESPONSE_BAD_REQUEST,
401: RESPONSE_UNAUTHORIZED,
403: RESPONSE_FORBIDDEN,
404: RESPONSE_NOT_FOUND,
},
)
def get(self, request, organization):
"""
Returns an incident and group open period relationship.
Can optionally filter by incident_id, incident_identifier, group_id, or open_period_id.
"""
validator = IncidentGroupOpenPeriodValidator(data=request.query_params)
validator.is_valid(raise_exception=True)
incident_id = validator.validated_data.get("incident_id")
incident_identifier = validator.validated_data.get("incident_identifier")
group_id = validator.validated_data.get("group_id")
open_period_id = validator.validated_data.get("open_period_id")
queryset = IncidentGroupOpenPeriod.objects.filter(
group_open_period__project__organization=organization
)
if incident_id:
queryset = queryset.filter(incident_id=incident_id)
if incident_identifier:
queryset = queryset.filter(incident_identifier=incident_identifier)
if group_id:
queryset = queryset.filter(group_open_period__group_id=group_id)
if open_period_id:
queryset = queryset.filter(group_open_period_id=open_period_id)
incident_groupopenperiod = queryset.first()
if not incident_groupopenperiod:
raise ResourceDoesNotExist
return Response(serialize(incident_groupopenperiod, request.user))
| OrganizationIncidentGroupOpenPeriodIndexEndpoint |
python | django__django | tests/auth_tests/test_auth_backends.py | {
"start": 1192,
"end": 1478
} | class ____(ExceptionReporter):
def get_traceback_frames(self):
frames = super().get_traceback_frames()
return [
frame
for frame in frames
if not isinstance(dict(frame["vars"]).get("self"), Client)
]
| FilteredExceptionReporter |
python | mozilla__bleach | bleach/_vendor/html5lib/constants.py | {
"start": 83307,
"end": 83431
} | class ____(UserWarning):
"""Raised when the current tree is unable to represent the input data"""
pass
| DataLossWarning |
python | joke2k__faker | faker/providers/lorem/de_AT/__init__.py | {
"start": 49,
"end": 191
} | class ____(GermanProvider):
"""Implement lorem provider for ``de_DE`` locale.
Using the same as in ```de_DE```.
"""
pass
| Provider |
python | huggingface__transformers | src/transformers/models/pop2piano/modeling_pop2piano.py | {
"start": 18506,
"end": 19961
} | class ____(nn.Module):
def __init__(self, config, layer_idx: Optional[int] = None):
super().__init__()
self.EncDecAttention = Pop2PianoAttention(config, has_relative_attention_bias=False, layer_idx=layer_idx)
self.layer_norm = Pop2PianoLayerNorm(config.d_model, eps=config.layer_norm_epsilon)
self.dropout = nn.Dropout(config.dropout_rate)
def forward(
self,
hidden_states,
key_value_states,
attention_mask=None,
position_bias=None,
past_key_values=None,
use_cache=False,
query_length=None,
output_attentions=False,
cache_position=None,
):
normed_hidden_states = self.layer_norm(hidden_states)
attention_output = self.EncDecAttention(
normed_hidden_states,
mask=attention_mask,
key_value_states=key_value_states,
position_bias=position_bias,
past_key_values=past_key_values,
use_cache=use_cache,
query_length=query_length,
output_attentions=output_attentions,
cache_position=cache_position,
)
layer_output = hidden_states + self.dropout(attention_output[0])
outputs = (layer_output,) + attention_output[1:] # add attentions if we output them
return outputs
# Copied from transformers.models.t5.modeling_t5.T5Block with T5->Pop2Piano,t5->pop2piano
| Pop2PianoLayerCrossAttention |
python | huggingface__transformers | src/transformers/models/git/modeling_git.py | {
"start": 8468,
"end": 9142
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
GIT_SELF_ATTENTION_CLASSES = {
"eager": GitSelfAttention,
}
| GitSelfOutput |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 532475,
"end": 532976
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of ConvertPullRequestToDraft"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "pull_request")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
pull_request = sgqlc.types.Field("PullRequest", graphql_name="pullRequest")
"""The pull request that is now a draft."""
| ConvertPullRequestToDraftPayload |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.