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 | django__django | tests/admin_inlines/admin.py | {
"start": 6499,
"end": 6567
} | class ____(admin.ModelAdmin):
inlines = [ChapterInline]
| NovelAdmin |
python | tensorflow__tensorflow | tensorflow/python/keras/distribute/distribute_coordinator_utils.py | {
"start": 1612,
"end": 1982
} | class ____(object):
PS = "ps"
WORKER = "worker"
CHIEF = "chief"
EVALUATOR = "evaluator"
CLIENT = "client"
def _get_num_workers(cluster_spec):
"""Gets number of workers including chief."""
if not cluster_spec:
return 0
return len(cluster_spec.as_dict().get(_TaskType.WORKER, [])) + len(
cluster_spec.as_dict().get(_TaskType.CHIEF, []))
| _TaskType |
python | great-expectations__great_expectations | tests/datasource/fluent/test_spark_filesystem_datasource.py | {
"start": 41399,
"end": 45367
} | class ____:
@pytest.mark.spark
@pytest.mark.xfail(strict=True, reason="Will fix or refactor as part of V1-306")
def test_parameter_keys_with_partitioner_file_asset_batch_parameters(
self, file_asset, daily_partitioner
):
assert file_asset.get_batch_parameters_keys(partitioner=daily_partitioner) == (
"year",
"month",
"path",
"passenger_count",
)
@pytest.mark.spark
@pytest.mark.xfail(strict=True, reason="Will fix or refactor as part of V1-306")
def test_get_batch_with_partitioner_file_asset_one_batch_size(
self,
file_asset,
daily_partitioner,
expected_num_records_file_asset_no_partitioner_2020_10_passenger_count_2: int,
):
post_partitioner_batch_request = file_asset.build_batch_request(
options={"year": "2020", "month": "11", "passenger_count": 2},
partitioner=daily_partitioner,
)
post_partitioner_batch_list = file_asset.get_batch(post_partitioner_batch_request)
# Make sure we only have passenger_count == 2 in our batch data
post_partitioner_batch_data = post_partitioner_batch_list.data
assert (
post_partitioner_batch_data.dataframe.filter(F.col("passenger_count") == 2).count()
== expected_num_records_file_asset_no_partitioner_2020_10_passenger_count_2
)
assert (
post_partitioner_batch_data.dataframe.filter(F.col("passenger_count") != 2).count() == 0
)
@pytest.mark.spark
@pytest.mark.xfail(strict=True, reason="Will fix or refactor as part of V1-306")
def test_add_file_csv_asset_with_partitioner_conflicting_identifier_batch_parameters(
self, file_asset_with_no_partitioner: CSVAsset
):
regex = re.compile(
r"first_ten_trips_in_each_file/yellow_tripdata_sample_(?P<year>\d{4})-(?P<month>\d{2})\.csv"
)
asset_with_conflicting_partitioner = file_asset_with_no_partitioner
partitioner = FileNamePartitionerYearly(regex=regex)
assert asset_with_conflicting_partitioner.get_batch_parameters_keys(
partitioner=partitioner
) == (
"year",
"month",
"path",
)
@pytest.mark.spark
def test_add_file_csv_asset_with_partitioner_conflicting_identifier_gets_a_batch(
self, file_asset_with_no_partitioner: CSVAsset
):
regex = re.compile(
r"first_ten_trips_in_each_file/yellow_tripdata_sample_(?P<year>\d{4})-(?P<month>\d{2})\.csv"
)
asset = file_asset_with_no_partitioner
partitioner = FileNamePartitionerMonthly(regex=regex)
post_partitioner_batch_request = asset.build_batch_request(
options={"year": "2020", "month": "11"}, partitioner=partitioner
)
asset.get_batch(post_partitioner_batch_request)
# no errors!
@pytest.mark.spark
def test_add_file_csv_asset_with_partitioner_conflicting_identifier_gets_correct_data(
self,
file_asset_with_no_partitioner: CSVAsset,
expected_num_records_file_asset_no_partitioner_2020_10: int,
):
regex = re.compile(
r"first_ten_trips_in_each_file/yellow_tripdata_sample_(?P<year>\d{4})-(?P<month>\d{2})\.csv"
)
asset = file_asset_with_no_partitioner
partitioner = FileNamePartitionerMonthly(regex=regex)
post_partitioner_batch_request = asset.build_batch_request(
options={"year": "2020", "month": "11"}, partitioner=partitioner
)
post_partitioner_batch = asset.get_batch(post_partitioner_batch_request)
post_partitioner_batch_data = post_partitioner_batch.data
assert (
post_partitioner_batch_data.dataframe.count() # type: ignore[attr-defined] # FIXME CoP
== expected_num_records_file_asset_no_partitioner_2020_10
)
| TestPartitionerFileAsset |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/auto_ml.py | {
"start": 24631,
"end": 26661
} | class ____(GoogleCloudBaseOperator):
"""
Delete an AutoML training job.
Can be used with AutoMLForecastingTrainingJob, AutoMLImageTrainingJob,
AutoMLTabularTrainingJob, AutoMLTextTrainingJob, or AutoMLVideoTrainingJob.
"""
template_fields = ("training_pipeline_id", "region", "project_id", "impersonation_chain")
def __init__(
self,
*,
training_pipeline_id: str,
region: str,
project_id: str,
retry: Retry | _MethodDefault = DEFAULT,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.training_pipeline_id = training_pipeline_id
self.region = region
self.project_id = project_id
self.retry = retry
self.timeout = timeout
self.metadata = metadata
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
def execute(self, context: Context):
hook = AutoMLHook(
gcp_conn_id=self.gcp_conn_id,
impersonation_chain=self.impersonation_chain,
)
try:
self.log.info("Deleting Auto ML training pipeline: %s", self.training_pipeline_id)
training_pipeline_operation = hook.delete_training_pipeline(
training_pipeline=self.training_pipeline_id,
region=self.region,
project_id=self.project_id,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
hook.wait_for_operation(timeout=self.timeout, operation=training_pipeline_operation)
self.log.info("Training pipeline was deleted.")
except NotFound:
self.log.info("The Training Pipeline ID %s does not exist.", self.training_pipeline_id)
| DeleteAutoMLTrainingJobOperator |
python | jupyterlab__jupyterlab | jupyterlab/labapp.py | {
"start": 10215,
"end": 10391
} | class ____(WorkspaceListApp):
version = version
@default("workspaces_dir")
def _default_workspaces_dir(self):
return get_workspaces_dir()
| LabWorkspaceListApp |
python | ipython__ipython | IPython/core/magics/pylab.py | {
"start": 1391,
"end": 6624
} | class ____(Magics):
"""Magics related to matplotlib's pylab support"""
@skip_doctest
@line_magic
@magic_arguments.magic_arguments()
@magic_arguments.argument('-l', '--list', action='store_true',
help='Show available matplotlib backends')
@magic_gui_arg
def matplotlib(self, line=''):
"""Set up matplotlib to work interactively.
This function lets you activate matplotlib interactive support
at any point during an IPython session. It does not import anything
into the interactive namespace.
If you are using the inline matplotlib backend in the IPython Notebook
you can set which figure formats are enabled using the following::
In [1]: from matplotlib_inline.backend_inline import set_matplotlib_formats
In [2]: set_matplotlib_formats('pdf', 'svg')
The default for inline figures sets `bbox_inches` to 'tight'. This can
cause discrepancies between the displayed image and the identical
image created using `savefig`. This behavior can be disabled using the
`%config` magic::
In [3]: %config InlineBackend.print_figure_kwargs = {'bbox_inches':None}
In addition, see the docstrings of
`matplotlib_inline.backend_inline.set_matplotlib_formats` and
`matplotlib_inline.backend_inline.set_matplotlib_close` for more information on
changing additional behaviors of the inline backend.
Examples
--------
To enable the inline backend for usage with the IPython Notebook::
In [1]: %matplotlib inline
In this case, where the matplotlib default is TkAgg::
In [2]: %matplotlib
Using matplotlib backend: TkAgg
But you can explicitly request a different GUI backend::
In [3]: %matplotlib qt
You can list the available backends using the -l/--list option::
In [4]: %matplotlib --list
Available matplotlib backends: ['osx', 'qt4', 'qt5', 'gtk3', 'gtk4', 'notebook', 'wx', 'qt', 'nbagg',
'gtk', 'tk', 'inline']
"""
args = magic_arguments.parse_argstring(self.matplotlib, line)
if args.list:
from IPython.core.pylabtools import _list_matplotlib_backends_and_gui_loops
print(
"Available matplotlib backends: %s"
% _list_matplotlib_backends_and_gui_loops()
)
else:
gui, backend = self.shell.enable_matplotlib(args.gui)
self._show_matplotlib_backend(args.gui, backend)
@skip_doctest
@line_magic
@magic_arguments.magic_arguments()
@magic_arguments.argument(
'--no-import-all', action='store_true', default=None,
help="""Prevent IPython from performing ``import *`` into the interactive namespace.
You can govern the default behavior of this flag with the
InteractiveShellApp.pylab_import_all configurable.
"""
)
@magic_gui_arg
def pylab(self, line=''):
"""Load numpy and matplotlib to work interactively.
This function lets you activate pylab (matplotlib, numpy and
interactive support) at any point during an IPython session.
%pylab makes the following imports::
import numpy
import matplotlib
from matplotlib import pylab, mlab, pyplot
np = numpy
plt = pyplot
from IPython.display import display
from IPython.core.pylabtools import figsize, getfigs
from pylab import *
from numpy import *
If you pass `--no-import-all`, the last two `*` imports will be excluded.
See the %matplotlib magic for more details about activating matplotlib
without affecting the interactive namespace.
"""
args = magic_arguments.parse_argstring(self.pylab, line)
if args.no_import_all is None:
# get default from Application
if Application.initialized():
app = Application.instance()
try:
import_all = app.pylab_import_all
except AttributeError:
import_all = True
else:
# nothing specified, no app - default True
import_all = True
else:
# invert no-import flag
import_all = not args.no_import_all
gui, backend, clobbered = self.shell.enable_pylab(args.gui, import_all=import_all)
self._show_matplotlib_backend(args.gui, backend)
print(
"%pylab is deprecated, use %matplotlib inline and import the required libraries."
)
print("Populating the interactive namespace from numpy and matplotlib")
if clobbered:
warn("pylab import has clobbered these variables: %s" % clobbered +
"\n`%matplotlib` prevents importing * from pylab and numpy"
)
def _show_matplotlib_backend(self, gui, backend):
"""show matplotlib message backend message"""
if not gui or gui == 'auto':
print("Using matplotlib backend: %s" % backend)
| PylabMagics |
python | pytorch__pytorch | test/quantization/pt2e/test_quantize_pt2e_qat.py | {
"start": 39835,
"end": 40580
} | class ____(PT2EQATTestCase):
@skip_if_no_torchvision
@skipIfNoQNNPACK
def test_qat_resnet18(self):
import torchvision
with override_quantized_engine("qnnpack"):
example_inputs = (torch.randn(1, 3, 224, 224),)
m = torchvision.models.resnet18()
self._verify_symmetric_xnnpack_qat_numerics(m, example_inputs)
@skip_if_no_torchvision
@skipIfNoQNNPACK
def test_qat_mobilenet_v2(self):
import torchvision
with override_quantized_engine("qnnpack"):
example_inputs = (torch.randn(1, 3, 224, 224),)
m = torchvision.models.mobilenet_v2()
self._verify_symmetric_xnnpack_qat_numerics(m, example_inputs)
| TestQuantizePT2EQATModels |
python | openai__openai-python | src/openai/types/eval_create_params.py | {
"start": 3488,
"end": 3733
} | class ____(TypedDict, total=False):
content: Required[str]
"""The content of the message."""
role: Required[str]
"""The role of the message (e.g. "system", "assistant", "user")."""
| TestingCriterionLabelModelInputSimpleInputMessage |
python | MongoEngine__mongoengine | mongoengine/fields.py | {
"start": 78629,
"end": 79042
} | class ____(GeoJsonBaseField):
"""A GeoJSON field storing a line of longitude and latitude coordinates.
The data is represented as:
.. code-block:: js
{'type' : 'LineString' ,
'coordinates' : [[x1, y1], [x2, y2] ... [xn, yn]]}
You can either pass a dict with the full information or a list of points.
Requires mongodb >= 2.4
"""
_type = "LineString"
| LineStringField |
python | TheAlgorithms__Python | data_structures/linked_list/merge_two_lists.py | {
"start": 358,
"end": 2210
} | class ____:
def __init__(self, ints: Iterable[int]) -> None:
self.head: Node | None = None
for i in sorted(ints, reverse=True):
self.head = Node(i, self.head)
def __iter__(self) -> Iterator[int]:
"""
>>> tuple(SortedLinkedList(test_data_odd)) == tuple(sorted(test_data_odd))
True
>>> tuple(SortedLinkedList(test_data_even)) == tuple(sorted(test_data_even))
True
"""
node = self.head
while node:
yield node.data
node = node.next_node
def __len__(self) -> int:
"""
>>> for i in range(3):
... len(SortedLinkedList(range(i))) == i
True
True
True
>>> len(SortedLinkedList(test_data_odd))
8
"""
return sum(1 for _ in self)
def __str__(self) -> str:
"""
>>> str(SortedLinkedList([]))
''
>>> str(SortedLinkedList(test_data_odd))
'-11 -> -1 -> 0 -> 1 -> 3 -> 5 -> 7 -> 9'
>>> str(SortedLinkedList(test_data_even))
'-2 -> 0 -> 2 -> 3 -> 4 -> 6 -> 8 -> 10'
"""
return " -> ".join([str(node) for node in self])
def merge_lists(
sll_one: SortedLinkedList, sll_two: SortedLinkedList
) -> SortedLinkedList:
"""
>>> SSL = SortedLinkedList
>>> merged = merge_lists(SSL(test_data_odd), SSL(test_data_even))
>>> len(merged)
16
>>> str(merged)
'-11 -> -2 -> -1 -> 0 -> 0 -> 1 -> 2 -> 3 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10'
>>> list(merged) == list(sorted(test_data_odd + test_data_even))
True
"""
return SortedLinkedList(list(sll_one) + list(sll_two))
if __name__ == "__main__":
import doctest
doctest.testmod()
SSL = SortedLinkedList
print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
| SortedLinkedList |
python | django__django | tests/mail/tests.py | {
"start": 125427,
"end": 128572
} | class ____(SimpleTestCase):
"""
Check django.core.mail does not directly import Python legacy email APIs,
with a few specific exceptions.
"""
# From "Legacy API:" in https://docs.python.org/3/library/email.html.
legacy_email_apis = {
"email.message.Message",
"email.mime",
"email.header",
"email.charset",
"email.encoders",
"email.utils",
"email.iterators",
}
allowed_exceptions = {
# Compatibility in EmailMessage.attachments special cases:
"email.message.Message",
# No replacement in modern email API:
"email.utils.make_msgid",
}
def test_no_legacy_apis_imported(self):
django_core_mail_path = Path(mail.__file__).parent
django_path = django_core_mail_path.parent.parent.parent
for abs_path in django_core_mail_path.glob("**/*.py"):
allowed_exceptions = self.allowed_exceptions.copy()
# RemovedInDjango70Warning.
# The following will be removed after the deprecation period.
if abs_path.name == "message.py":
allowed_exceptions.update(
{
"email.charset",
"email.header.Header",
"email.mime.base.MIMEBase",
"email.mime.message.MIMEMessage",
"email.mime.multipart.MIMEMultipart",
"email.mime.text.MIMEText",
"email.utils.formataddr",
"email.utils.getaddresses",
}
)
path = abs_path.relative_to(django_path)
with self.subTest(path=str(path)):
collector = self.ImportCollector(abs_path.read_text())
used_apis = collector.get_matching_imports(self.legacy_email_apis)
used_apis -= allowed_exceptions
self.assertEqual(
"\n".join(sorted(used_apis)),
"",
f"Python legacy email APIs used in {path}",
)
class ImportCollector(ast.NodeVisitor):
"""
Collect all imports from an AST as a set of fully-qualified dotted
names.
"""
def __init__(self, source=None):
self.imports = set()
if source:
tree = ast.parse(source)
self.visit(tree)
def get_matching_imports(self, base_names):
"""
Return the set of collected imports that start with any
of the fully-qualified dotted names in iterable base_names.
"""
matcher = re.compile(
r"\b(" + r"|".join(re.escape(name) for name in base_names) + r")\b"
)
return set(name for name in self.imports if matcher.match(name))
def visit_Import(self, node):
self.imports.update(alias.name for alias in node.names)
def visit_ImportFrom(self, node):
self.imports.update(f"{node.module}.{alias.name}" for alias in node.names)
| LegacyAPINotUsedTests |
python | tensorflow__tensorflow | tensorflow/python/keras/legacy_tf_layers/convolutional.py | {
"start": 60108,
"end": 68708
} | class ____(keras_layers.Conv3DTranspose, base.Layer):
"""Transposed 3D convolution layer (sometimes called 3D Deconvolution).
Args:
filters: Integer, the dimensionality of the output space (i.e. the number
of filters in the convolution).
kernel_size: An integer or tuple/list of 3 integers, specifying the
depth, height and width of the 3D convolution window.
Can be a single integer to specify the same value for all spatial
dimensions.
strides: An integer or tuple/list of 3 integers, specifying the strides
of the convolution along the depth, height and width.
Can be a single integer to specify the same value for all spatial
dimensions.
padding: One of `"valid"` or `"same"` (case-insensitive).
`"valid"` means no padding. `"same"` results in padding evenly to
the left/right or up/down of the input such that output has the same
height/width dimension as the input.
data_format: A string, one of `channels_last` (default) or `channels_first`.
The ordering of the dimensions in the inputs.
`channels_last` corresponds to inputs with shape
`(batch, depth, height, width, channels)` while `channels_first`
corresponds to inputs with shape
`(batch, channels, depth, height, width)`.
activation: Activation function. Set it to `None` to maintain a
linear activation.
use_bias: Boolean, whether the layer uses a bias.
kernel_initializer: An initializer for the convolution kernel.
bias_initializer: An initializer for the bias vector. If `None`, the default
initializer will be used.
kernel_regularizer: Optional regularizer for the convolution kernel.
bias_regularizer: Optional regularizer for the bias vector.
activity_regularizer: Optional regularizer function for the output.
kernel_constraint: Optional projection function to be applied to the
kernel after being updated by an `Optimizer` (e.g. used to implement
norm constraints or value constraints for layer weights). The function
must take as input the unprojected variable and must return the
projected variable (which must have the same shape). Constraints are
not safe to use when doing asynchronous distributed training.
bias_constraint: Optional projection function to be applied to the
bias after being updated by an `Optimizer`.
trainable: Boolean, if `True` also add variables to the graph collection
`GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).
name: A string, the name of the layer.
"""
def __init__(self,
filters,
kernel_size,
strides=(1, 1, 1),
padding='valid',
data_format='channels_last',
activation=None,
use_bias=True,
kernel_initializer=None,
bias_initializer=init_ops.zeros_initializer(),
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
trainable=True,
name=None,
**kwargs):
super(Conv3DTranspose, self).__init__(
filters=filters,
kernel_size=kernel_size,
strides=strides,
padding=padding,
data_format=data_format,
activation=activation,
use_bias=use_bias,
kernel_initializer=kernel_initializer,
bias_initializer=bias_initializer,
kernel_regularizer=kernel_regularizer,
bias_regularizer=bias_regularizer,
activity_regularizer=activity_regularizer,
kernel_constraint=kernel_constraint,
bias_constraint=bias_constraint,
trainable=trainable,
name=name,
**kwargs)
def conv3d_transpose(inputs,
filters,
kernel_size,
strides=(1, 1, 1),
padding='valid',
data_format='channels_last',
activation=None,
use_bias=True,
kernel_initializer=None,
bias_initializer=init_ops.zeros_initializer(),
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
trainable=True,
name=None,
reuse=None):
"""Functional interface for transposed 3D convolution layer.
Args:
inputs: Input tensor.
filters: Integer, the dimensionality of the output space (i.e. the number
of filters in the convolution).
kernel_size: A tuple or list of 3 positive integers specifying the spatial
dimensions of the filters. Can be a single integer to specify the same
value for all spatial dimensions.
strides: A tuple or list of 3 positive integers specifying the strides
of the convolution. Can be a single integer to specify the same value for
all spatial dimensions.
padding: one of `"valid"` or `"same"` (case-insensitive).
`"valid"` means no padding. `"same"` results in padding evenly to
the left/right or up/down of the input such that output has the same
height/width dimension as the input.
data_format: A string, one of `channels_last` (default) or `channels_first`.
The ordering of the dimensions in the inputs.
`channels_last` corresponds to inputs with shape
`(batch, depth, height, width, channels)` while `channels_first`
corresponds to inputs with shape
`(batch, channels, depth, height, width)`.
activation: Activation function. Set it to None to maintain a
linear activation.
use_bias: Boolean, whether the layer uses a bias.
kernel_initializer: An initializer for the convolution kernel.
bias_initializer: An initializer for the bias vector. If None, the default
initializer will be used.
kernel_regularizer: Optional regularizer for the convolution kernel.
bias_regularizer: Optional regularizer for the bias vector.
activity_regularizer: Optional regularizer function for the output.
kernel_constraint: Optional projection function to be applied to the
kernel after being updated by an `Optimizer` (e.g. used to implement
norm constraints or value constraints for layer weights). The function
must take as input the unprojected variable and must return the
projected variable (which must have the same shape). Constraints are
not safe to use when doing asynchronous distributed training.
bias_constraint: Optional projection function to be applied to the
bias after being updated by an `Optimizer`.
trainable: Boolean, if `True` also add variables to the graph collection
`GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).
name: A string, the name of the layer.
reuse: Boolean, whether to reuse the weights of a previous layer
by the same name.
Returns:
Output tensor.
Raises:
ValueError: if eager execution is enabled.
"""
warnings.warn('`tf.layers.conv3d_transpose` is deprecated and '
'will be removed in a future version. '
'Please Use `tf.keras.layers.Conv3DTranspose` instead.')
layer = Conv3DTranspose(
filters=filters,
kernel_size=kernel_size,
strides=strides,
padding=padding,
data_format=data_format,
activation=activation,
use_bias=use_bias,
kernel_initializer=kernel_initializer,
bias_initializer=bias_initializer,
kernel_regularizer=kernel_regularizer,
bias_regularizer=bias_regularizer,
activity_regularizer=activity_regularizer,
kernel_constraint=kernel_constraint,
bias_constraint=bias_constraint,
trainable=trainable,
name=name,
_reuse=reuse,
_scope=name)
return layer.apply(inputs)
# Aliases
Convolution1D = Conv1D
Convolution2D = Conv2D
Convolution3D = Conv3D
SeparableConvolution2D = SeparableConv2D
Convolution2DTranspose = Deconvolution2D = Deconv2D = Conv2DTranspose
Convolution3DTranspose = Deconvolution3D = Deconv3D = Conv3DTranspose
convolution1d = conv1d
convolution2d = conv2d
convolution3d = conv3d
separable_convolution2d = separable_conv2d
convolution2d_transpose = deconvolution2d = deconv2d = conv2d_transpose
convolution3d_transpose = deconvolution3d = deconv3d = conv3d_transpose
| Conv3DTranspose |
python | spulec__freezegun | tests/test_datetimes.py | {
"start": 19462,
"end": 20275
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
assert datetime.date(2013, 4, 9) == datetime.date.today()
def setUp(self) -> None:
self.assertEqual(datetime.date(2013, 4, 9), datetime.date.today())
def tearDown(self) -> None:
self.assertEqual(datetime.date(2013, 4, 9), datetime.date.today())
@classmethod
def tearDownClass(cls) -> None:
assert datetime.date(2013, 4, 9) == datetime.date.today()
def test_class_decorator_works_on_unittest(self) -> None:
self.assertEqual(datetime.date(2013, 4, 9), datetime.date.today())
def test_class_name_preserved_by_decorator(self) -> None:
self.assertEqual(self.__class__.__name__, "TestUnitTestClassDecorator")
@freeze_time('2013-04-09')
| TestUnitTestClassDecorator |
python | numpy__numpy | numpy/f2py/symbolic.py | {
"start": 44280,
"end": 44820
} | class ____:
# Internal class to represent a pair of expressions
def __init__(self, left, right):
self.left = left
self.right = right
def substitute(self, symbols_map):
left, right = self.left, self.right
if isinstance(left, Expr):
left = left.substitute(symbols_map)
if isinstance(right, Expr):
right = right.substitute(symbols_map)
return _Pair(left, right)
def __repr__(self):
return f'{type(self).__name__}({self.left}, {self.right})'
| _Pair |
python | readthedocs__readthedocs.org | readthedocs/search/parsers.py | {
"start": 241,
"end": 17047
} | class ____:
# Limit that matches the ``index.mapping.nested_objects.limit`` ES setting.
max_inner_documents = 10000
# Limit the size of the contents to be indexed,
# to avoid filling the index with too much data.
# The limit may be exceeded if the content is too large,
# or if the content is malformed.
# A raw approximation of bytes based on the number of characters (~1.5 MB).
max_content_length = int(1.5 * 1024 * 1024)
# Block level elements have an implicit line break before and after them.
# List taken from: https://www.w3schools.com/htmL/html_blocks.asp.
block_level_elements = [
"address",
"article",
"aside",
"blockquote",
"canvas",
"dd",
"div",
"dl",
"dt",
"fieldset",
"figcaption",
"figure",
"footer",
"form",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"header",
"hr",
"li",
"main",
"nav",
"noscript",
"ol",
"p",
"pre",
"section",
"table",
"tfoot",
"ul",
"video",
]
def __init__(self, version):
self.version = version
self.project = self.version.project
self.storage = build_media_storage
def _get_page_content(self, page):
"""Gets the page content from storage."""
content = None
try:
storage_path = self.project.get_storage_path(
type_="html",
version_slug=self.version.slug,
include_file=False,
version_type=self.version.type,
)
file_path = self.storage.join(storage_path, page)
with self.storage.open(file_path, mode="r") as f:
content = f.read()
except Exception:
log.warning(
"Failed to get page content.",
page=page,
)
return content
def _get_page_title(self, body, html):
"""
Gets the title from the html page.
The title is the first section in the document,
falling back to the ``title`` tag.
"""
first_header = body.css_first("h1")
if first_header:
title, _ = self._parse_section_title(first_header)
return title
title = html.css_first("title")
if title:
return self._parse_content(title.text())
return None
def _get_main_node(self, html):
"""
Gets the main node from where to start indexing content.
The main node is tested in the following order:
- Try with a tag with the ``main`` role.
This role is used by several static sites and themes.
- Try the ``main`` tag.
- Try the first ``h1`` node and return its parent
Usually all sections are neighbors,
so they are children of the same parent node.
- Return the body element itself if all checks above fail.
"""
body = html.body
main_node = body.css_first("[role=main]")
if main_node:
return main_node
main_node = body.css_first("main")
if main_node:
return main_node
# TODO: this could be done in smarter way,
# checking for common parents between all h nodes.
first_header = body.css_first("h1")
if first_header:
return self._get_header_container(first_header).parent
return body
def _get_header_container(self, h_tag):
"""
Get the *real* container of a header tag or title.
If the parent of the ``h`` tag is a ``header`` tag,
then we return the ``header`` tag,
since the header tag acts as a container for the title of the section.
Otherwise, we return the tag itself.
"""
if h_tag.parent.tag == "header":
return h_tag.parent
return h_tag
def _parse_content(self, content):
"""Converts all new line characters and multiple spaces to a single space."""
content = content.strip().split()
content = (text.strip() for text in content)
content = " ".join(text for text in content if text)
if len(content) > self.max_content_length:
log.info(
"Content too long, truncating.",
project_slug=self.project.slug,
version_slug=self.version.slug,
content_length=len(content),
limit=self.max_content_length,
)
content = content[: self.max_content_length]
return content
def _parse_sections(self, title, body):
"""
Parses each section into a structured dict.
Sub-sections are nested, so they are children of the outer section,
and sections with the same level are neighbors.
We index the content under a section till before the next one.
We can have pages that have content before the first title or that don't have a title,
we index that content first under the title of the original page.
"""
document_title = title
indexed_nodes = []
for dd, dt, section in self._parse_dls(body):
indexed_nodes.append(dd)
indexed_nodes.append(dt)
yield section
# Remove all seen and indexed data outside of traversal.
# We want to avoid modifying the DOM tree while traversing it.
for node in indexed_nodes:
node.decompose()
# Index content for pages that don't start with a title.
# We check for sections till 3 levels to avoid indexing all the content
# in this step.
try:
content, _ = self._parse_section_content(
body.child,
depth=3,
)
if content:
yield {
"id": "",
"title": document_title,
"content": content,
}
except Exception as e:
log.info("Unable to index section", section=str(e))
# Index content from h1 to h6 headers.
for section in [body.css(f"h{h}") for h in range(1, 7)]:
for tag in section:
try:
title, _id = self._parse_section_title(tag)
next_tag = self._get_header_container(tag).next
content, _ = self._parse_section_content(next_tag, depth=2)
yield {
"id": _id,
"title": title,
"content": content,
}
except Exception:
log.info("Unable to index section.", exc_info=True)
def _parse_dls(self, body):
# All terms in <dl>s are treated as sections.
# We traverse by <dl> - traversing by <dt> has shown in experiments to render a
# different traversal order, which could make the tests more unstable.
dls = body.css("dl")
for dl in dls:
# Hack: Since we cannot use '> dt' nor ':host' in selectolax/Modest,
# we use an iterator to select immediate descendants.
dts = (node for node in dl.iter() if node.tag == "dt" and node.id)
# https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dt
# multiple <dt> elements in a row indicate several terms that are
# all defined by the immediate next <dd> element.
for dt in dts:
title, _id = self._parse_dt(dt)
# Select the first adjacent <dd> using a "gamble" that seems to work.
# In this example, we cannot use the current <dt>'s ID because they contain invalid
# CSS selector syntax and there's no apparent way to fix that.
# https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_combinator
dd = dt.css_first("dt ~ dd")
# We only index a dt with an id attribute and an accompanying dd
if not dd or not _id:
continue
# Create a copy of the node to avoid manipulating the
# data structure that we're iterating over
dd_copy = HTMLParser(dd.html).body.child
# Remove all nested domains from dd_copy.
# They are already parsed separately.
for node in dd_copy.css("dl"):
# Traverse all <dt>s with an ID (the ones we index!)
for _dt in node.css('dt[id]:not([id=""])'):
# Fetch adjacent <dd>s and remove them
_dd_dt = _dt.css_first("dt ~ dd")
if _dd_dt:
_dd_dt.decompose()
# Remove the <dt> too
_dt.decompose()
# The content of the <dt> section is the content of the accompanying <dd>
content = self._parse_content(dd_copy.text())
yield (
dd,
dt,
{
"id": _id,
"title": title,
"content": content,
},
)
def _parse_dt(self, tag):
"""
Parses a definition term <dt>.
If the <dt> does not have an id attribute, it cannot be referenced.
This should be understood by the caller.
"""
section_id = tag.attributes.get("id", "")
return self._parse_content(tag.text()), section_id
def _get_sections(self, title, body):
"""Get the first `self.max_inner_documents` sections."""
iterator = self._parse_sections(title=title, body=body)
sections = list(itertools.islice(iterator, 0, self.max_inner_documents))
try:
next(iterator)
except StopIteration:
pass
else:
log.warning(
"Limit of inner sections exceeded.",
project_slug=self.project.slug,
version_slug=self.version.slug,
limit=self.max_inner_documents,
)
return sections
def _clean_body(self, body):
"""
Removes nodes with irrelevant content before parsing its sections.
This method is documented here:
https://dev.readthedocs.io/page/search-integration.html#irrelevant-content
.. warning::
This will mutate the original `body`.
"""
nodes_to_be_removed = itertools.chain(
# Navigation nodes
body.css("nav"),
body.css("[role=navigation]"),
body.css("[role=search]"),
# Permalinks, this is a Sphinx convention.
body.css(".headerlink"),
# Line numbers from code blocks, they are very noisy in contents.
# This convention is popular in Sphinx.
body.css(".linenos"),
body.css(".lineno"),
# Sphinx doesn't wrap the result from the `toctree` directive
# in a nav tag. so we need to manually remove that content.
body.css(".toctree-wrapper"),
)
for node in nodes_to_be_removed:
node.decompose()
return body
def _is_section(self, tag):
"""
Check if `tag` is a section (linkeable header).
The tag is a section if it's a ``h`` or a ``header`` tag.
"""
is_h_tag = re.match(r"h\d$", tag.tag)
return is_h_tag or tag.tag == "header"
def _parse_section_title(self, tag):
"""
Parses a section title tag and gets its id.
The id (used to link to the section) is tested in the following order:
- Get the id from the node itself.
- Get the id from the parent node.
"""
section_id = tag.attributes.get("id", "")
if not section_id:
parent = tag.parent
section_id = parent.attributes.get("id", "")
return self._parse_content(tag.text()), section_id
def _parse_section_content(self, tag, *, depth=0):
"""
Gets the content from tag till before a new section.
if depth > 0, recursively check for sections in all tag's children.
Returns a tuple with: the parsed content,
and a boolean indicating if a section was found.
"""
contents = []
section_found = False
next_tag = tag
while next_tag:
if section_found or self._is_section(next_tag):
section_found = True
break
if self._is_code_section(next_tag):
content = self._parse_code_section(next_tag)
elif depth <= 0 or not next_tag.child:
# Calling .text() with deep `True` over a text node will return empty.
deep = next_tag.tag != "-text"
content = next_tag.text(deep=deep)
else:
content, section_found = self._parse_section_content(
tag=next_tag.child, depth=depth - 1
)
if content:
is_block_level_element = next_tag.tag in self.block_level_elements
if is_block_level_element:
# Add a line break before and after a block level element.
contents.append(f"\n{content}\n")
else:
contents.append(content)
next_tag = next_tag.next
return self._parse_content("".join(contents)), section_found
def _is_code_section(self, tag):
"""
Check if `tag` is a code section.
Sphinx and Mkdocs codeblocks usually have a class named
``highlight`` or ``highlight-{language}``.
"""
if not tag.css_first("pre"):
return False
for c in tag.attributes.get("class", "").split():
if c.startswith("highlight"):
return True
return False
def _parse_code_section(self, tag):
"""
Parse a code section to fetch relevant content only.
- Removes line numbers.
Sphinx and Mkdocs may use a table when the code block includes line numbers.
This table has a td tag with a ``lineos`` class.
Other implementations put the line number within the code,
inside span tags with the ``lineno`` class.
"""
nodes_to_be_removed = itertools.chain(tag.css(".linenos"), tag.css(".lineno"))
for node in nodes_to_be_removed:
node.decompose()
contents = []
for node in tag.css("pre"):
# XXX: Don't call to `_parse_content`
# if we decide to show code results more nicely,
# so the indentation isn't lost.
content = node.text().strip("\n")
contents.append(self._parse_content(content))
return " ".join(contents)
def parse(self, page):
"""
Get the parsed JSON for search indexing.
Returns a dictionary with the following structure.
{
'path': 'file path',
'title': 'Title',
'sections': [
{
'id': 'section-anchor',
'title': 'Section title',
'content': 'Section content',
},
],
}
"""
try:
content = self._get_page_content(page)
if content:
return self._process_content(page, content)
except Exception:
log.info("Failed to index page.", path=page, exc_info=True)
return {
"path": page,
"title": "",
"sections": [],
"main_content_hash": None,
}
def _process_content(self, page, content):
"""Parses the content into a structured dict."""
html = HTMLParser(content)
body = self._get_main_node(html)
title = ""
sections = []
main_content_hash = None
if body:
main_content_hash = hashlib.md5(body.html.encode()).hexdigest()
body = self._clean_body(body)
title = self._get_page_title(body, html) or page
sections = self._get_sections(title=title, body=body)
else:
log.info(
"Page doesn't look like it has valid content, skipping.",
page=page,
)
return {
"path": page,
"title": title,
"sections": sections,
"main_content_hash": main_content_hash,
}
| GenericParser |
python | langchain-ai__langchain | libs/langchain/tests/unit_tests/output_parsers/test_enum_parser.py | {
"start": 167,
"end": 858
} | class ____(Enum):
RED = "red"
GREEN = "green"
BLUE = "blue"
def test_enum_output_parser_parse() -> None:
parser = EnumOutputParser(enum=Colors)
# Test valid inputs
result = parser.parse("red")
assert result == Colors.RED
result = parser.parse("green")
assert result == Colors.GREEN
result = parser.parse("blue")
assert result == Colors.BLUE
# Test invalid input
with pytest.raises(OutputParserException):
parser.parse("INVALID")
def test_enum_output_parser_output_type() -> None:
"""Test the output type of the enum output parser is the expected enum."""
assert EnumOutputParser(enum=Colors).OutputType is Colors
| Colors |
python | django__django | django/db/models/fields/reverse_related.py | {
"start": 8013,
"end": 9862
} | class ____(ForeignObjectRel):
"""
Used by the ForeignKey field to store information about the relation.
``_meta.get_fields()`` returns this class to provide access to the field
flags for the reverse relation.
Note: Because we somewhat abuse the Rel objects by using them as reverse
fields we get the funny situation where
``ManyToOneRel.many_to_one == False`` and
``ManyToOneRel.one_to_many == True``. This is unfortunate but the actual
ManyToOneRel class is a private API and there is work underway to turn
reverse relations into actual fields.
"""
def __init__(
self,
field,
to,
field_name,
related_name=None,
related_query_name=None,
limit_choices_to=None,
parent_link=False,
on_delete=None,
):
super().__init__(
field,
to,
related_name=related_name,
related_query_name=related_query_name,
limit_choices_to=limit_choices_to,
parent_link=parent_link,
on_delete=on_delete,
)
self.field_name = field_name
def __getstate__(self):
state = super().__getstate__()
state.pop("related_model", None)
return state
@property
def identity(self):
return (*super().identity, self.field_name)
def get_related_field(self):
"""
Return the Field in the 'to' object to which this relationship is tied.
"""
field = self.model._meta.get_field(self.field_name)
if not field.concrete:
raise exceptions.FieldDoesNotExist(
"No related field named '%s'" % self.field_name
)
return field
def set_field_name(self):
self.field_name = self.field_name or self.model._meta.pk.name
| ManyToOneRel |
python | fsspec__filesystem_spec | fsspec/tests/test_utils.py | {
"start": 13472,
"end": 13539
} | class ____:
def __fspath__(self):
return "foo"
| _HasFspath |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/ragged_segment_op_test.py | {
"start": 1496,
"end": 9505
} | class ____(test_util.TensorFlowTestCase,
parameterized.TestCase):
def expected_value(self, data, segment_ids, num_segments, combiner):
"""Find the expected value for a call to ragged_segment_<aggregate>.
Args:
data: The input RaggedTensor, expressed as a nested python list.
segment_ids: The segment ids, as a python list of ints.
num_segments: The number of segments, as a python int.
combiner: The Python function used to combine values.
Returns:
The expected value, as a nested Python list.
"""
self.assertLen(data, len(segment_ids))
# Build an empty (num_segments x ncols) "grouped" matrix
ncols = max(len(row) for row in data)
grouped = [[[] for _ in range(ncols)] for row in range(num_segments)]
# Append values from data[row] to grouped[segment_ids[row]]
for row in range(len(data)):
for col in range(len(data[row])):
grouped[segment_ids[row]][col].append(data[row][col])
# Combine the values.
return [[combiner(values)
for values in grouped_row
if values]
for grouped_row in grouped]
@parameterized.parameters(
(ragged_math_ops.segment_sum, sum, [0, 0, 1, 1, 2, 2]),
(ragged_math_ops.segment_sum, sum, [0, 0, 0, 1, 1, 1]),
(ragged_math_ops.segment_sum, sum, [5, 4, 3, 2, 1, 0]),
(ragged_math_ops.segment_sum, sum, [0, 0, 0, 10, 10, 10]),
(ragged_math_ops.segment_prod, prod, [0, 0, 1, 1, 2, 2]),
(ragged_math_ops.segment_prod, prod, [0, 0, 0, 1, 1, 1]),
(ragged_math_ops.segment_prod, prod, [5, 4, 3, 2, 1, 0]),
(ragged_math_ops.segment_prod, prod, [0, 0, 0, 10, 10, 10]),
(ragged_math_ops.segment_min, min, [0, 0, 1, 1, 2, 2]),
(ragged_math_ops.segment_min, min, [0, 0, 0, 1, 1, 1]),
(ragged_math_ops.segment_min, min, [5, 4, 3, 2, 1, 0]),
(ragged_math_ops.segment_min, min, [0, 0, 0, 10, 10, 10]),
(ragged_math_ops.segment_max, max, [0, 0, 1, 1, 2, 2]),
(ragged_math_ops.segment_max, max, [0, 0, 0, 1, 1, 1]),
(ragged_math_ops.segment_max, max, [5, 4, 3, 2, 1, 0]),
(ragged_math_ops.segment_max, max, [0, 0, 0, 10, 10, 10]),
(ragged_math_ops.segment_mean, mean, [0, 0, 1, 1, 2, 2]),
(ragged_math_ops.segment_mean, mean, [0, 0, 0, 1, 1, 1]),
(ragged_math_ops.segment_mean, mean, [5, 4, 3, 2, 1, 0]),
(ragged_math_ops.segment_mean, mean, [0, 0, 0, 10, 10, 10]),
)
def testRaggedSegment_Int(self, segment_op, combiner, segment_ids):
rt_as_list = [[0, 1, 2, 3], [4], [], [5, 6], [7], [8, 9]]
rt = ragged_factory_ops.constant(rt_as_list)
num_segments = max(segment_ids) + 1
expected = self.expected_value(rt_as_list, segment_ids, num_segments,
combiner)
segmented = segment_op(rt, segment_ids, num_segments)
self.assertAllEqual(segmented, expected)
@parameterized.parameters(
(ragged_math_ops.segment_sum, sum, [0, 0, 1, 1, 2, 2]),
(ragged_math_ops.segment_sum, sum, [0, 0, 0, 1, 1, 1]),
(ragged_math_ops.segment_sum, sum, [5, 4, 3, 2, 1, 0]),
(ragged_math_ops.segment_sum, sum, [0, 0, 0, 10, 10, 10]),
(ragged_math_ops.segment_prod, prod, [0, 0, 1, 1, 2, 2]),
(ragged_math_ops.segment_prod, prod, [0, 0, 0, 1, 1, 1]),
(ragged_math_ops.segment_prod, prod, [5, 4, 3, 2, 1, 0]),
(ragged_math_ops.segment_prod, prod, [0, 0, 0, 10, 10, 10]),
(ragged_math_ops.segment_min, min, [0, 0, 1, 1, 2, 2]),
(ragged_math_ops.segment_min, min, [0, 0, 0, 1, 1, 1]),
(ragged_math_ops.segment_min, min, [5, 4, 3, 2, 1, 0]),
(ragged_math_ops.segment_min, min, [0, 0, 0, 10, 10, 10]),
(ragged_math_ops.segment_max, max, [0, 0, 1, 1, 2, 2]),
(ragged_math_ops.segment_max, max, [0, 0, 0, 1, 1, 1]),
(ragged_math_ops.segment_max, max, [5, 4, 3, 2, 1, 0]),
(ragged_math_ops.segment_max, max, [0, 0, 0, 10, 10, 10]),
(ragged_math_ops.segment_mean, mean, [0, 0, 1, 1, 2, 2]),
(ragged_math_ops.segment_mean, mean, [0, 0, 0, 1, 1, 1]),
(ragged_math_ops.segment_mean, mean, [5, 4, 3, 2, 1, 0]),
(ragged_math_ops.segment_mean, mean, [0, 0, 0, 10, 10, 10]),
(ragged_math_ops.segment_sqrt_n, sqrt_n, [0, 0, 1, 1, 2, 2]),
(ragged_math_ops.segment_sqrt_n, sqrt_n, [0, 0, 0, 1, 1, 1]),
(ragged_math_ops.segment_sqrt_n, sqrt_n, [5, 4, 3, 2, 1, 0]),
(ragged_math_ops.segment_sqrt_n, sqrt_n, [0, 0, 0, 10, 10, 10]),
)
def testRaggedSegment_Float(self, segment_op, combiner, segment_ids):
rt_as_list = [[0., 1., 2., 3.], [4.], [], [5., 6.], [7.], [8., 9.]]
rt = ragged_factory_ops.constant(rt_as_list)
num_segments = max(segment_ids) + 1
expected = self.expected_value(rt_as_list, segment_ids, num_segments,
combiner)
segmented = segment_op(rt, segment_ids, num_segments)
self.assertAllClose(segmented, expected)
def testRaggedRankTwo(self):
rt = ragged_factory_ops.constant([
[[111, 112, 113, 114], [121],], # row 0
[], # row 1
[[], [321, 322], [331]], # row 2
[[411, 412]] # row 3
]) # pyformat: disable
segment_ids1 = [0, 2, 2, 2]
segmented1 = ragged_math_ops.segment_sum(rt, segment_ids1, 3)
expected1 = [[[111, 112, 113, 114], [121]], # row 0
[], # row 1
[[411, 412], [321, 322], [331]] # row 2
] # pyformat: disable
self.assertAllEqual(segmented1, expected1)
segment_ids2 = [1, 2, 1, 1]
segmented2 = ragged_math_ops.segment_sum(rt, segment_ids2, 3)
expected2 = [[],
[[111+411, 112+412, 113, 114], [121+321, 322], [331]],
[]] # pyformat: disable
self.assertAllEqual(segmented2, expected2)
def testRaggedSegmentIds(self):
rt = ragged_factory_ops.constant([
[[111, 112, 113, 114], [121],], # row 0
[], # row 1
[[], [321, 322], [331]], # row 2
[[411, 412]] # row 3
]) # pyformat: disable
segment_ids = ragged_factory_ops.constant([[1, 2], [], [1, 1, 2], [2]])
segmented = ragged_math_ops.segment_sum(rt, segment_ids, 3)
expected = [[],
[111+321, 112+322, 113, 114],
[121+331+411, 412]] # pyformat: disable
self.assertAllEqual(segmented, expected)
def testShapeMismatchError1(self):
dt = constant_op.constant([1, 2, 3, 4, 5, 6])
segment_ids = ragged_factory_ops.constant([[1, 2], []])
self.assertRaisesRegex(
ValueError, 'segment_ids.shape must be a prefix of data.shape, '
'but segment_ids is ragged and data is not.',
ragged_math_ops.segment_sum, dt, segment_ids, 3)
def testShapeMismatchError2(self):
rt = ragged_factory_ops.constant([
[[111, 112, 113, 114], [121]], # row 0
[], # row 1
[[], [321, 322], [331]], # row 2
[[411, 412]] # row 3
]) # pyformat: disable
segment_ids = ragged_factory_ops.constant([[1, 2], [1], [1, 1, 2], [2]])
# Error is raised at graph-building time if we can detect it then.
self.assertRaisesRegex(
errors.InvalidArgumentError,
'segment_ids.shape must be a prefix of data.shape.*',
ragged_math_ops.segment_sum, rt, segment_ids, 3)
# Otherwise, error is raised when we run the graph.
segment_ids2 = ragged_tensor.RaggedTensor.from_row_splits(
array_ops.placeholder_with_default(segment_ids.values, None),
array_ops.placeholder_with_default(segment_ids.row_splits, None))
with self.assertRaisesRegex(
errors.InvalidArgumentError,
'segment_ids.shape must be a prefix of data.shape.*'):
self.evaluate(ragged_math_ops.segment_sum(rt, segment_ids2, 3))
if __name__ == '__main__':
googletest.main()
| RaggedSegmentOpsTest |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dag_run.py | {
"start": 57998,
"end": 61130
} | class ____:
@pytest.mark.usefixtures("configure_git_connection_for_dag_bundle")
def test_clear_dag_run(self, test_client, session):
response = test_client.post(
f"/dags/{DAG1_ID}/dagRuns/{DAG1_RUN1_ID}/clear",
json={"dry_run": False},
)
assert response.status_code == 200
body = response.json()
assert body["dag_id"] == DAG1_ID
assert body["dag_run_id"] == DAG1_RUN1_ID
assert body["state"] == "queued"
_check_last_log(
session,
dag_id=DAG1_ID,
event="clear_dag_run",
logical_date=None,
)
def test_should_respond_401(self, unauthenticated_test_client):
response = unauthenticated_test_client.post(
f"/dags/{DAG1_ID}/dagRuns/{DAG1_RUN1_ID}/clear",
json={"dry_run": False},
)
assert response.status_code == 401
def test_should_respond_403(self, unauthorized_test_client):
response = unauthorized_test_client.post(
f"/dags/{DAG1_ID}/dagRuns/{DAG1_RUN1_ID}/clear",
json={"dry_run": False},
)
assert response.status_code == 403
@pytest.mark.parametrize(
("body", "dag_run_id", "expected_state"),
[
[{"dry_run": True}, DAG1_RUN1_ID, ["success", "success"]],
[{}, DAG1_RUN1_ID, ["success", "success"]],
[{}, DAG1_RUN2_ID, ["success", "failed"]],
[{"only_failed": True}, DAG1_RUN2_ID, ["failed"]],
],
)
@pytest.mark.usefixtures("configure_git_connection_for_dag_bundle")
def test_clear_dag_run_dry_run(self, test_client, session, body, dag_run_id, expected_state):
response = test_client.post(f"/dags/{DAG1_ID}/dagRuns/{dag_run_id}/clear", json=body)
assert response.status_code == 200
body = response.json()
assert body["total_entries"] == len(expected_state)
for index, each in enumerate(sorted(body["task_instances"], key=lambda x: x["task_id"])):
assert each["state"] == expected_state[index]
dag_run = session.scalar(select(DagRun).filter_by(dag_id=DAG1_ID, run_id=DAG1_RUN1_ID))
assert dag_run.state == DAG1_RUN1_STATE
logs = (
session.query(Log)
.filter(Log.dag_id == DAG1_ID, Log.run_id == dag_run_id, Log.event == "clear_dag_run")
.count()
)
assert logs == 0
def test_clear_dag_run_not_found(self, test_client):
response = test_client.post(f"/dags/{DAG1_ID}/dagRuns/invalid/clear", json={"dry_run": False})
assert response.status_code == 404
body = response.json()
assert body["detail"] == "The DagRun with dag_id: `test_dag1` and run_id: `invalid` was not found"
def test_clear_dag_run_unprocessable_entity(self, test_client):
response = test_client.post(f"/dags/{DAG1_ID}/dagRuns/{DAG1_RUN1_ID}/clear")
assert response.status_code == 422
body = response.json()
assert body["detail"][0]["msg"] == "Field required"
assert body["detail"][0]["loc"][0] == "body"
| TestClearDagRun |
python | jazzband__tablib | tests/test_tablib_dbfpy_packages_utils.py | {
"start": 2251,
"end": 3562
} | class ____(unittest.TestCase):
"""dbfpy.utils.getDateTime test cases."""
def test_getDateTime_none(self):
# Arrange
value = None
# Act
output = utils.getDateTime(value)
# Assert
self.assertIsInstance(output, dt.datetime)
def test_getDateTime_datetime_datetime(self):
# Arrange
value = dt.datetime(2019, 10, 19, 12, 00, 00)
# Act
output = utils.getDateTime(value)
# Assert
self.assertIsInstance(output, dt.date)
self.assertEqual(output, value)
def test_getDateTime_datetime_date(self):
# Arrange
value = dt.date(2019, 10, 19)
# Act
output = utils.getDateTime(value)
# Assert
self.assertIsInstance(output, dt.date)
self.assertEqual(output, dt.datetime(2019, 10, 19, 00, 00))
def test_getDateTime_datetime_timestamp(self):
# Arrange
value = 1571515306
# Act
output = utils.getDateTime(value)
# Assert
self.assertIsInstance(output, dt.datetime)
def test_getDateTime_datetime_string(self):
# Arrange
value = "20191019"
# Act / Assert
with self.assertRaises(NotImplementedError):
utils.getDateTime(value)
| UtilsGetDateTimeTestCase |
python | realpython__materials | python-wav-files/waveio/reader.py | {
"start": 981,
"end": 1495
} | class ____:
def __init__(self, values, frames_range):
self.values = values
self.frames_range = frames_range
def __iter__(self):
return iter(self.values)
def __getattr__(self, name):
return getattr(self.values, name)
def reshape(self, *args, **kwargs):
reshaped = self.values.reshape(*args, **kwargs)
return ArraySlice(reshaped, self.frames_range)
@property
def T(self):
return ArraySlice(self.values.T, self.frames_range)
| ArraySlice |
python | google__jax | jax/_src/export/shape_poly.py | {
"start": 1758,
"end": 2468
} | class ____(core.InconclusiveDimensionOperation):
"""Raised when we cannot conclusively compute with symbolic dimensions."""
_help_msg = """
This error arises for comparison operations with shapes that
are non-constant, and the result of the operation cannot be represented as
a boolean value for all values of the symbolic dimensions involved.
Please see https://docs.jax.dev/en/latest/export/shape_poly.html#comparison-of-symbolic-dimensions-is-partially-supported
for more details.
"""
def __init__(self, message: str):
error_msg = f"{message}{InconclusiveDimensionOperation._help_msg}"
# https://github.com/python/mypy/issues/5887
super().__init__(error_msg)
| InconclusiveDimensionOperation |
python | getsentry__sentry | tests/sentry/api/serializers/test_pull_request.py | {
"start": 423,
"end": 4557
} | class ____(TestCase):
def test_simple(self) -> None:
user = self.create_user()
project = self.create_project()
release = Release.objects.create(
organization_id=project.organization_id, version=uuid4().hex
)
release.add_project(project)
repository = Repository.objects.create(
organization_id=project.organization_id, name="test/test"
)
commit_author = CommitAuthor.objects.create(
name="stebe", email="stebe@sentry.io", organization_id=project.organization_id
)
pull_request = PullRequest.objects.create(
organization_id=project.organization_id,
repository_id=repository.id,
key="9",
author=commit_author,
message="waddap",
title="cool pr",
)
result = serialize(pull_request, user)
assert result["message"] == "waddap"
assert result["title"] == "cool pr"
assert result["repository"]["name"] == "test/test"
assert result["author"] == {"name": "stebe", "email": "stebe@sentry.io"}
def test_no_author(self) -> None:
user = self.create_user()
project = self.create_project()
release = Release.objects.create(
organization_id=project.organization_id, version=uuid4().hex
)
release.add_project(project)
repository = Repository.objects.create(
organization_id=project.organization_id, name="test/test"
)
pull_request = PullRequest.objects.create(
organization_id=project.organization_id,
repository_id=repository.id,
key="abc",
message="waddap",
)
result = serialize(pull_request, user)
assert result["author"] == {}
def test_integration_repository(self) -> None:
# Add binding in case they aren't set.
bindings.add(
"integration-repository.provider", GitHubRepositoryProvider, id="integrations:github"
)
user = self.create_user()
project = self.create_project()
release = Release.objects.create(
organization_id=project.organization_id, version=uuid4().hex
)
release.add_project(project)
repository = Repository.objects.create(
organization_id=project.organization_id,
name="test/test",
provider="integrations:github",
url="https://github.com/test/test",
)
commit_author = CommitAuthor.objects.create(
name="stebe", email="stebe@sentry.io", organization_id=project.organization_id
)
pull_request = PullRequest.objects.create(
organization_id=project.organization_id,
repository_id=repository.id,
key="9",
author=commit_author,
message="waddap",
title="cool pr",
)
result = serialize(pull_request, user)
assert result["externalUrl"] == "https://github.com/test/test/pull/9"
assert result["message"] == "waddap"
assert result["title"] == "cool pr"
assert result["repository"]["name"] == "test/test"
assert result["author"] == {"name": "stebe", "email": "stebe@sentry.io"}
def test_deleted_repository(self) -> None:
commit_author = CommitAuthor.objects.create(
name="stebe", email="stebe@sentry.io", organization_id=self.project.organization_id
)
pull_request = PullRequest.objects.create(
organization_id=self.project.organization_id,
repository_id=12345,
key="9",
author=commit_author,
message="waddap",
title="cool pr",
)
result = serialize(pull_request, self.user)
assert result["message"] == pull_request.message
assert result["title"] == pull_request.title
assert result["repository"] == {}
assert result["author"] == {"name": commit_author.name, "email": commit_author.email}
assert result["externalUrl"] == ""
| PullRequestSerializerTest |
python | pallets__jinja | src/jinja2/nodes.py | {
"start": 28707,
"end": 28979
} | class ____(BinExpr):
"""Short circuited OR."""
operator = "or"
def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:
eval_ctx = get_eval_context(self, eval_ctx)
return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
| Or |
python | scipy__scipy | scipy/linalg/tests/test_fblas.py | {
"start": 18253,
"end": 18382
} | class ____(BaseGerComplex):
blas_func = fblas.zgeru
dtype = complex128
def transform(self,x):
return x
| TestZgeru |
python | getsentry__sentry | src/sentry/integrations/jira_server/integration.py | {
"start": 5416,
"end": 7182
} | class ____(forms.Form):
url = forms.CharField(
label=_("Jira URL"),
help_text=_("The base URL for your Jira Server instance, including the host and protocol."),
widget=forms.TextInput(attrs={"placeholder": "https://jira.example.com"}),
validators=[URLValidator()],
)
verify_ssl = forms.BooleanField(
label=_("Verify SSL"),
help_text=_(
"By default, we verify SSL certificates " "when making requests to your Jira instance."
),
widget=forms.CheckboxInput(),
required=False,
initial=True,
)
consumer_key = forms.CharField(
label=_("Jira Consumer Key"),
widget=forms.TextInput(attrs={"placeholder": "sentry-consumer-key"}),
)
private_key = forms.CharField(
label=_("Jira Consumer Private Key"),
widget=forms.Textarea(
attrs={
"placeholder": "-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----"
}
),
)
def clean_url(self):
"""Strip off trailing / as they cause invalid URLs downstream"""
return self.cleaned_data["url"].rstrip("/")
def clean_private_key(self):
data = self.cleaned_data["private_key"]
try:
load_pem_private_key(data.encode("utf-8"), None, default_backend())
except Exception:
raise forms.ValidationError(
"Private key must be a valid SSH private key encoded in a PEM format."
)
return data
def clean_consumer_key(self):
data = self.cleaned_data["consumer_key"]
if len(data) > 200:
raise forms.ValidationError("Consumer key is limited to 200 characters.")
return data
| InstallationForm |
python | jina-ai__jina | jina/types/mixin.py | {
"start": 167,
"end": 3814
} | class ____:
"""The base mixin class of all Jina types.
.. note::
- All Jina types should inherit from this class.
- All subclass should have ``self._pb_body``
- All subclass should implement ``__init__`` with the possibility of initializing from ``None``, e.g.:
.. highlight:: python
.. code-block:: python
class MyJinaType(ProtoTypeMixin):
def __init__(self, proto: Optional[jina_pb2.SomePbMsg] = None):
self._pb_body = proto or jina_pb2.SomePbMsg()
"""
def to_json(self) -> str:
"""Return the object in JSON string
:return: JSON string of the object
"""
from google.protobuf.json_format import MessageToJson
return MessageToJson(
self.proto, preserving_proto_field_name=True, sort_keys=True
)
def to_dict(self, **kwargs) -> Dict:
"""Return the object in Python dictionary.
.. note::
Array like object such as :class:`numpy.ndarray` (i.e. anything described as :class:`jina_pb2.NdArrayProto`)
will be converted to Python list.
:param kwargs: Extra kwargs to be passed to MessageToDict, like use_integers_for_enums
:return: dict representation of the object
"""
from google.protobuf.json_format import MessageToDict
return MessageToDict(self.proto, preserving_proto_field_name=True, **kwargs)
@property
def proto(self) -> 'jina_pb2._reflection.GeneratedProtocolMessageType':
"""Return the underlying Protobuf object
:return: Protobuf representation of the object
"""
return self._pb_body
def to_bytes(self) -> bytes:
"""Return the serialized the message to a string.
For more Pythonic code, please use ``bytes(...)``.
:return: binary string representation of the object
"""
return self.proto.SerializePartialToString()
def __getstate__(self):
return self._pb_body.__getstate__()
def __setstate__(self, state):
self.__init__()
self._pb_body.__setstate__(state)
@property
def nbytes(self) -> int:
"""Return total bytes consumed by protobuf.
:return: number of bytes
"""
return len(bytes(self))
def __getattr__(self, name: str):
return getattr(self._pb_body, name)
def __repr__(self):
content = str(tuple(field[0].name for field in self.proto.ListFields()))
content += f' at {id(self)}'
return f'<{typename(self)} {content.strip()}>'
def MergeFrom(self: T, other: T) -> None:
"""Merge the content of target
:param other: the document to merge from
"""
self._pb_body.MergeFrom(other._pb_body)
def CopyFrom(self: T, other: T) -> None:
"""Copy the content of target
:param other: the document to copy from
"""
self._pb_body.CopyFrom(other._pb_body)
def clear(self) -> None:
"""Remove all values from all fields of this Document."""
self._pb_body.Clear()
def pop(self, *fields) -> None:
"""Remove the values from the given fields of this Document.
:param fields: field names
"""
for k in fields:
self._pb_body.ClearField(k)
def __eq__(self, other):
if other is None:
return False
return self.proto == other.proto
def __bytes__(self):
return self.to_bytes()
dict = deprecate_by(to_dict)
json = deprecate_by(to_json)
binary_str = deprecate_by(to_bytes)
| ProtoTypeMixin |
python | pandas-dev__pandas | asv_bench/benchmarks/multiindex_object.py | {
"start": 1257,
"end": 2000
} | class ____:
def setup(self):
self.mi_large = MultiIndex.from_product(
[np.arange(1000), np.arange(20), list(string.ascii_letters)],
names=["one", "two", "three"],
)
self.mi_med = MultiIndex.from_product(
[np.arange(1000), np.arange(10), list("A")], names=["one", "two", "three"]
)
self.mi_small = MultiIndex.from_product(
[np.arange(100), list("A"), list("A")], names=["one", "two", "three"]
)
def time_large_get_locs(self):
self.mi_large.get_locs([999, 19, "Z"])
def time_med_get_locs(self):
self.mi_med.get_locs([999, 9, "A"])
def time_small_get_locs(self):
self.mi_small.get_locs([99, "A", "A"])
| GetLocs |
python | getsentry__sentry | tests/sentry/utils/test_event_frames.py | {
"start": 3225,
"end": 10337
} | class ____(unittest.TestCase):
def test_platform_java(self) -> None:
frames = [
{
"module": "jdk.internal.reflect.NativeMethodAccessorImpl",
"filename": "NativeMethodAccessorImpl.java",
"abs_path": "NativeMethodAccessorImpl.java",
},
{
"module": "io.sentry.example.Application",
"filename": "Application.java",
"abs_path": "Application.java",
},
{
"module": "io.sentry.example.Application",
"filename": "Application.java",
"abs_path": "Application.java",
},
]
ret = munged_filename_and_frames("java", frames, "munged_filename")
assert ret is not None
key, munged_frames = ret
assert len(munged_frames) == 3
assert munged_frames[0][key] == "jdk/internal/reflect/NativeMethodAccessorImpl.java"
assert munged_frames[1][key] == "io/sentry/example/Application.java"
assert munged_frames[2][key] == "io/sentry/example/Application.java"
for z in zip(frames, munged_frames):
assert z[0].items() <= z[1].items()
def test_platform_java_no_filename(self) -> None:
no_filename = {
"module": "io.sentry.example.Application",
}
no_munged = munged_filename_and_frames("java", [no_filename])
assert not no_munged
def test_platform_java_no_module(self) -> None:
no_module = {
"filename": "Application.java",
}
no_munged = munged_filename_and_frames("java", [no_module])
assert not no_munged
def test_platform_java_do_not_follow_java_package_naming_convention_does_not_raise_exception(
self,
) -> None:
frame = {
"abs_path": "gsp_arcus_drops_proofReadingmodecInspectionProofRead_gsp.groovy",
"module": "gsp_arcus_drops_proofReadingmodecInspectionProofRead_gsp$_run_closure2",
}
munged = munged_filename_and_frames("java", [frame])
assert munged is None
def test_platform_android_kotlin(self) -> None:
exception_frames = [
{
"function": "main",
"module": "com.android.internal.os.ZygoteInit",
"filename": "ZygoteInit.java",
"abs_path": "ZygoteInit.java",
"lineno": 1003,
"in_app": False,
},
{
"function": "run",
"module": "com.android.internal.os.RuntimeInit$MethodAndArgsCaller",
"filename": "RuntimeInit.java",
"abs_path": "RuntimeInit.java",
"lineno": 548,
"in_app": False,
},
{
"function": "invoke",
"module": "java.lang.reflect.Method",
"filename": "Method.java",
"abs_path": "Method.java",
"in_app": False,
},
{
"function": "main",
"module": "android.app.ActivityThread",
"filename": "ActivityThread.java",
"abs_path": "ActivityThread.java",
"lineno": 7842,
"in_app": False,
},
{
"function": "loop",
"module": "android.os.Looper",
"filename": "Looper.java",
"abs_path": "Looper.java",
"lineno": 288,
"in_app": False,
},
{
"function": "loopOnce",
"module": "android.os.Looper",
"filename": "Looper.java",
"abs_path": "Looper.java",
"lineno": 201,
"in_app": False,
},
{
"function": "dispatchMessage",
"module": "android.os.Handler",
"filename": "Handler.java",
"abs_path": "Handler.java",
"lineno": 99,
"in_app": False,
},
{
"function": "handleCallback",
"module": "android.os.Handler",
"filename": "Handler.java",
"abs_path": "Handler.java",
"lineno": 938,
"in_app": False,
},
{
"function": "run",
"module": "android.view.View$PerformClick",
"filename": "View.java",
"abs_path": "View.java",
"lineno": 28810,
"in_app": False,
},
{
"function": "access$3700",
"module": "android.view.View",
"filename": "View.java",
"abs_path": "View.java",
"lineno": 835,
"in_app": False,
},
{
"function": "performClickInternal",
"module": "android.view.View",
"filename": "View.java",
"abs_path": "View.java",
"lineno": 7432,
"in_app": False,
},
{
"function": "performClick",
"module": "com.google.android.material.button.MaterialButton",
"filename": "MaterialButton.java",
"abs_path": "MaterialButton.java",
"lineno": 1119,
"in_app": False,
},
{
"function": "performClick",
"module": "android.view.View",
"filename": "View.java",
"abs_path": "View.java",
"lineno": 7455,
"in_app": False,
},
{
"function": "onClick",
"module": "com.jetbrains.kmm.androidApp.MainActivity$$ExternalSyntheticLambda0",
"lineno": 2,
"in_app": True,
},
{
"function": "$r8$lambda$hGNRcN3pFcj8CSoYZBi9fT_AXd0",
"module": "com.jetbrains.kmm.androidApp.MainActivity",
"lineno": 0,
"in_app": True,
},
{
"function": "onCreate$lambda-1",
"module": "com.jetbrains.kmm.androidApp.MainActivity",
"filename": "MainActivity.kt",
"abs_path": "MainActivity.kt",
"lineno": 55,
"in_app": True,
},
]
ret = munged_filename_and_frames("java", exception_frames, "munged_filename")
assert ret is not None
key, munged_frames = ret
assert len(munged_frames) == 16
for z in zip(exception_frames, munged_frames):
assert z[0].items() <= z[1].items()
has_munged = list(filter(lambda f: f.get("filename") and f.get("module"), munged_frames))
assert len(has_munged) == 14
assert all(x["munged_filename"].endswith(x["filename"]) for x in has_munged)
| JavaFilenameMungingTestCase |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 216999,
"end": 222242
} | class ____(MemoryViewIndexNode):
is_memview_slice = True
# No-op slicing operation, this node will be replaced
is_ellipsis_noop = False
is_memview_scalar_assignment = False
is_memview_index = False
is_memview_broadcast = False
def analyse_ellipsis_noop(self, env, getting):
"""Slicing operations needing no evaluation, i.e. m[...] or m[:, :]"""
### FIXME: replace directly
self.is_ellipsis_noop = all(
index.is_slice and index.start.is_none and index.stop.is_none and index.step.is_none
for index in self.indices)
if self.is_ellipsis_noop:
self.type = self.base.type
def analyse_operation(self, env, getting, axes):
from . import MemoryView
if not getting:
self.is_memview_broadcast = True
self.none_error_message = "Cannot assign to None memoryview slice"
else:
self.none_error_message = "Cannot slice None memoryview slice"
self.analyse_ellipsis_noop(env, getting)
if self.is_ellipsis_noop:
return self
self.index = None
self.is_temp = True
self.use_managed_ref = True
if not MemoryView.validate_axes(self.pos, axes):
self.type = error_type
return self
self.type = PyrexTypes.MemoryViewSliceType(self.base.type.dtype, axes)
if not (self.base.is_simple() or self.base.result_in_temp()):
self.base = self.base.coerce_to_temp(env)
return self
def analyse_assignment(self, rhs):
if not rhs.type.is_memoryviewslice and (
self.type.dtype.assignable_from(rhs.type) or
rhs.type.is_pyobject):
# scalar assignment
return MemoryCopyScalar(self.pos, self)
else:
return MemoryCopySlice(self.pos, self)
def merged_indices(self, indices):
"""Return a new list of indices/slices with 'indices' merged into the current ones
according to slicing rules.
Is used to implement "view[i][j]" => "view[i, j]".
Return None if the indices cannot (easily) be merged at compile time.
"""
if not indices:
return None
# NOTE: Need to evaluate "self.original_indices" here as they might differ from "self.indices".
new_indices = self.original_indices[:]
indices = indices[:]
for i, s in enumerate(self.original_indices):
if s.is_slice:
if s.start.is_none and s.stop.is_none and s.step.is_none:
# Full slice found, replace by index.
new_indices[i] = indices[0]
indices.pop(0)
if not indices:
return new_indices
else:
# Found something non-trivial, e.g. a partial slice.
return None
elif not s.type.is_int:
# Not a slice, not an integer index => could be anything...
return None
if indices:
if len(new_indices) + len(indices) > self.base.type.ndim:
return None
new_indices += indices
return new_indices
def is_simple(self):
if self.is_ellipsis_noop:
# TODO: fix SimpleCallNode.is_simple()
return self.base.is_simple() or self.base.result_in_temp()
return self.result_in_temp()
def calculate_result_code(self):
"""This is called in case this is a no-op slicing node"""
return self.base.result()
def generate_result_code(self, code):
if self.is_ellipsis_noop:
return ### FIXME: remove
buffer_entry = self.buffer_entry()
have_gil = not self.in_nogil_context
# TODO Mark: this is insane, do it better
have_slices = False
it = iter(self.indices)
for index in self.original_indices:
if index.is_slice:
have_slices = True
if not index.start.is_none:
index.start = next(it)
if not index.stop.is_none:
index.stop = next(it)
if not index.step.is_none:
index.step = next(it)
else:
next(it)
assert not list(it)
buffer_entry.generate_buffer_slice_code(
code, self.original_indices, self.result(), self.type,
have_gil=have_gil, have_slices=have_slices,
directives=code.globalstate.directives)
def generate_assignment_code(self, rhs, code, overloaded_assignment=False):
if self.is_ellipsis_noop:
self.generate_subexpr_evaluation_code(code)
else:
self.generate_evaluation_code(code)
if self.is_memview_scalar_assignment:
self.generate_memoryviewslice_assign_scalar_code(rhs, code)
else:
self.generate_memoryviewslice_setslice_code(rhs, code)
if self.is_ellipsis_noop:
self.generate_subexpr_disposal_code(code)
else:
self.generate_disposal_code(code)
rhs.generate_disposal_code(code)
rhs.free_temps(code)
| MemoryViewSliceNode |
python | mwaskom__seaborn | tests/test_categorical.py | {
"start": 86988,
"end": 100033
} | class ____(SharedAggTests):
func = staticmethod(pointplot)
def get_last_color(self, ax):
color = ax.lines[-1].get_color()
return to_rgba(color)
@pytest.mark.parametrize("orient", ["x", "y"])
def test_single_var(self, orient):
vals = pd.Series([1, 3, 10])
ax = pointplot(**{orient: vals})
line = ax.lines[0]
assert getattr(line, f"get_{orient}data")() == approx(vals.mean())
@pytest.mark.parametrize("orient", ["x", "y", "h", "v"])
def test_wide_df(self, wide_df, orient):
ax = pointplot(wide_df, orient=orient)
orient = {"h": "y", "v": "x"}.get(orient, orient)
depend = {"x": "y", "y": "x"}[orient]
line = ax.lines[0]
assert_array_equal(
getattr(line, f"get_{orient}data")(),
np.arange(len(wide_df.columns)),
)
assert_array_almost_equal(
getattr(line, f"get_{depend}data")(),
wide_df.mean(axis=0),
)
@pytest.mark.parametrize("orient", ["x", "y", "h", "v"])
def test_vector_orient(self, orient):
keys, vals = ["a", "b", "c"], [1, 2, 3]
data = dict(zip(keys, vals))
orient = {"h": "y", "v": "x"}.get(orient, orient)
depend = {"x": "y", "y": "x"}[orient]
ax = pointplot(data, orient=orient)
line = ax.lines[0]
assert_array_equal(
getattr(line, f"get_{orient}data")(),
np.arange(len(keys)),
)
assert_array_equal(getattr(line, f"get_{depend}data")(), vals)
def test_xy_vertical(self):
x, y = ["a", "b", "c"], [1, 3, 2.5]
ax = pointplot(x=x, y=y)
for i, xy in enumerate(ax.lines[0].get_xydata()):
assert tuple(xy) == (i, y[i])
def test_xy_horizontal(self):
x, y = [1, 3, 2.5], ["a", "b", "c"]
ax = pointplot(x=x, y=y)
for i, xy in enumerate(ax.lines[0].get_xydata()):
assert tuple(xy) == (x[i], i)
def test_xy_with_na_grouper(self):
x, y = ["a", None, "b"], [1, 2, 3]
ax = pointplot(x=x, y=y)
_draw_figure(ax.figure) # For matplotlib<3.5
assert ax.get_xticks() == [0, 1]
assert [t.get_text() for t in ax.get_xticklabels()] == ["a", "b"]
assert_array_equal(ax.lines[0].get_xdata(), [0, 1])
assert_array_equal(ax.lines[0].get_ydata(), [1, 3])
def test_xy_with_na_value(self):
x, y = ["a", "b", "c"], [1, np.nan, 3]
ax = pointplot(x=x, y=y)
_draw_figure(ax.figure) # For matplotlib<3.5
assert ax.get_xticks() == [0, 1, 2]
assert [t.get_text() for t in ax.get_xticklabels()] == x
assert_array_equal(ax.lines[0].get_xdata(), [0, 1, 2])
assert_array_equal(ax.lines[0].get_ydata(), y)
def test_hue(self):
x, y = ["a", "a", "b", "b"], [1, 2, 3, 4]
hue = ["x", "y", "x", "y"]
ax = pointplot(x=x, y=y, hue=hue, errorbar=None)
for i, line in enumerate(ax.lines[:2]):
assert_array_equal(line.get_ydata(), y[i::2])
assert same_color(line.get_color(), f"C{i}")
def test_wide_data_is_joined(self, wide_df):
ax = pointplot(wide_df, errorbar=None)
assert len(ax.lines) == 1
def test_xy_native_scale(self):
x, y = [2, 4, 8], [1, 2, 3]
ax = pointplot(x=x, y=y, native_scale=True)
line = ax.lines[0]
assert_array_equal(line.get_xdata(), x)
assert_array_equal(line.get_ydata(), y)
# Use lambda around np.mean to avoid uninformative pandas deprecation warning
@pytest.mark.parametrize("estimator", ["mean", lambda x: np.mean(x)])
def test_estimate(self, long_df, estimator):
agg_var, val_var = "a", "y"
agg_df = long_df.groupby(agg_var)[val_var].agg(estimator)
ax = pointplot(long_df, x=agg_var, y=val_var, errorbar=None)
order = categorical_order(long_df[agg_var])
for i, xy in enumerate(ax.lines[0].get_xydata()):
assert tuple(xy) == approx((i, agg_df[order[i]]))
def test_weighted_estimate(self, long_df):
ax = pointplot(long_df, y="y", weights="x")
val = ax.lines[0].get_ydata().item()
expected = np.average(long_df["y"], weights=long_df["x"])
assert val == expected
def test_estimate_log_transform(self, long_df):
ax = mpl.figure.Figure().subplots()
ax.set_xscale("log")
pointplot(x=long_df["z"], ax=ax)
val, = ax.lines[0].get_xdata()
assert val == 10 ** np.log10(long_df["z"]).mean()
def test_errorbars(self, long_df):
agg_var, val_var = "a", "y"
agg_df = long_df.groupby(agg_var)[val_var].agg(["mean", "std"])
ax = pointplot(long_df, x=agg_var, y=val_var, errorbar="sd")
order = categorical_order(long_df[agg_var])
for i, line in enumerate(ax.lines[1:]):
row = agg_df.loc[order[i]]
lo, hi = line.get_ydata()
assert lo == approx(row["mean"] - row["std"])
assert hi == approx(row["mean"] + row["std"])
def test_marker_linestyle(self):
x, y = ["a", "b", "c"], [1, 2, 3]
ax = pointplot(x=x, y=y, marker="s", linestyle="--")
line = ax.lines[0]
assert line.get_marker() == "s"
assert line.get_linestyle() == "--"
def test_markers_linestyles_single(self):
x, y = ["a", "b", "c"], [1, 2, 3]
ax = pointplot(x=x, y=y, markers="s", linestyles="--")
line = ax.lines[0]
assert line.get_marker() == "s"
assert line.get_linestyle() == "--"
def test_markers_linestyles_mapped(self):
x, y = ["a", "a", "b", "b"], [1, 2, 3, 4]
hue = ["x", "y", "x", "y"]
markers = ["d", "s"]
linestyles = ["--", ":"]
ax = pointplot(
x=x, y=y, hue=hue,
markers=markers, linestyles=linestyles,
errorbar=None,
)
for i, line in enumerate(ax.lines[:2]):
assert line.get_marker() == markers[i]
assert line.get_linestyle() == linestyles[i]
def test_dodge_boolean(self):
x, y = ["a", "b", "a", "b"], [1, 2, 3, 4]
hue = ["x", "x", "y", "y"]
ax = pointplot(x=x, y=y, hue=hue, dodge=True, errorbar=None)
for i, xy in enumerate(ax.lines[0].get_xydata()):
assert tuple(xy) == (i - .025, y[i])
for i, xy in enumerate(ax.lines[1].get_xydata()):
assert tuple(xy) == (i + .025, y[2 + i])
def test_dodge_float(self):
x, y = ["a", "b", "a", "b"], [1, 2, 3, 4]
hue = ["x", "x", "y", "y"]
ax = pointplot(x=x, y=y, hue=hue, dodge=.2, errorbar=None)
for i, xy in enumerate(ax.lines[0].get_xydata()):
assert tuple(xy) == (i - .1, y[i])
for i, xy in enumerate(ax.lines[1].get_xydata()):
assert tuple(xy) == (i + .1, y[2 + i])
def test_dodge_log_scale(self):
x, y = [10, 1000, 10, 1000], [1, 2, 3, 4]
hue = ["x", "x", "y", "y"]
ax = mpl.figure.Figure().subplots()
ax.set_xscale("log")
pointplot(x=x, y=y, hue=hue, dodge=.2, native_scale=True, errorbar=None, ax=ax)
for i, xy in enumerate(ax.lines[0].get_xydata()):
assert tuple(xy) == approx((10 ** (np.log10(x[i]) - .2), y[i]))
for i, xy in enumerate(ax.lines[1].get_xydata()):
assert tuple(xy) == approx((10 ** (np.log10(x[2 + i]) + .2), y[2 + i]))
def test_err_kws(self):
x, y = ["a", "a", "b", "b"], [1, 2, 3, 4]
err_kws = dict(color=(.2, .5, .3), linewidth=10)
ax = pointplot(x=x, y=y, errorbar=("pi", 100), err_kws=err_kws)
for line in ax.lines[1:]:
assert same_color(line.get_color(), err_kws["color"])
assert line.get_linewidth() == err_kws["linewidth"]
def test_err_kws_inherited(self):
x, y = ["a", "a", "b", "b"], [1, 2, 3, 4]
kws = dict(color=(.2, .5, .3), linewidth=10)
ax = pointplot(x=x, y=y, errorbar=("pi", 100), **kws)
for line in ax.lines[1:]:
assert same_color(line.get_color(), kws["color"])
assert line.get_linewidth() == kws["linewidth"]
@pytest.mark.skipif(
_version_predates(mpl, "3.6"),
reason="Legend handle missing marker property"
)
def test_legend_contents(self):
x, y = ["a", "a", "b", "b"], [1, 2, 3, 4]
hue = ["x", "y", "x", "y"]
ax = pointplot(x=x, y=y, hue=hue)
_draw_figure(ax.figure)
legend = ax.get_legend()
assert [t.get_text() for t in legend.texts] == ["x", "y"]
for i, handle in enumerate(get_legend_handles(legend)):
assert handle.get_marker() == "o"
assert handle.get_linestyle() == "-"
assert same_color(handle.get_color(), f"C{i}")
@pytest.mark.skipif(
_version_predates(mpl, "3.6"),
reason="Legend handle missing marker property"
)
def test_legend_set_props(self):
x, y = ["a", "a", "b", "b"], [1, 2, 3, 4]
hue = ["x", "y", "x", "y"]
kws = dict(marker="s", linewidth=1)
ax = pointplot(x=x, y=y, hue=hue, **kws)
legend = ax.get_legend()
for i, handle in enumerate(get_legend_handles(legend)):
assert handle.get_marker() == kws["marker"]
assert handle.get_linewidth() == kws["linewidth"]
@pytest.mark.skipif(
_version_predates(mpl, "3.6"),
reason="Legend handle missing marker property"
)
def test_legend_synced_props(self):
x, y = ["a", "a", "b", "b"], [1, 2, 3, 4]
hue = ["x", "y", "x", "y"]
kws = dict(markers=["s", "d"], linestyles=["--", ":"])
ax = pointplot(x=x, y=y, hue=hue, **kws)
legend = ax.get_legend()
for i, handle in enumerate(get_legend_handles(legend)):
assert handle.get_marker() == kws["markers"][i]
assert handle.get_linestyle() == kws["linestyles"][i]
@pytest.mark.parametrize(
"kwargs",
[
dict(data="wide"),
dict(data="wide", orient="h"),
dict(data="flat"),
dict(data="long", x="a", y="y"),
dict(data=None, x="a", y="y"),
dict(data="long", x="a", y="y", hue="a"),
dict(data=None, x="a", y="y", hue="a"),
dict(data="long", x="a", y="y", hue="b"),
dict(data=None, x="s", y="y", hue="a"),
dict(data="long", x="a", y="y", hue="s"),
dict(data="long", x="a", y="y", units="c"),
dict(data="null", x="a", y="y", hue="a"),
dict(data="long", x="s", y="y", hue="a", native_scale=True),
dict(data="long", x="d", y="y", hue="a", native_scale=True),
dict(data="long", x="a", y="y", errorbar=("pi", 50)),
dict(data="long", x="a", y="y", errorbar=None),
dict(data="null", x="a", y="y", hue="a", dodge=True),
dict(data="null", x="a", y="y", hue="a", dodge=.2),
dict(data="long", x="a", y="y", capsize=.3, err_kws=dict(c="k")),
dict(data="long", x="a", y="y", color="blue", marker="s"),
dict(data="long", x="a", y="y", hue="a", markers=["s", "d", "p"]),
]
)
def test_vs_catplot(self, long_df, wide_df, null_df, flat_series, kwargs):
kwargs = kwargs.copy()
kwargs["seed"] = 0
kwargs["n_boot"] = 10
if kwargs["data"] == "long":
kwargs["data"] = long_df
elif kwargs["data"] == "wide":
kwargs["data"] = wide_df
elif kwargs["data"] == "flat":
kwargs["data"] = flat_series
elif kwargs["data"] == "null":
kwargs["data"] = null_df
elif kwargs["data"] is None:
for var in ["x", "y", "hue"]:
if var in kwargs:
kwargs[var] = long_df[kwargs[var]]
ax = pointplot(**kwargs)
g = catplot(**kwargs, kind="point")
assert_plots_equal(ax, g.ax)
def test_legend_disabled(self, long_df):
ax = pointplot(long_df, x="x", y="y", hue="b", legend=False)
assert ax.get_legend() is None
def test_join_deprecation(self):
with pytest.warns(UserWarning, match="The `join` parameter"):
ax = pointplot(x=["a", "b", "c"], y=[1, 2, 3], join=False)
assert ax.lines[0].get_linestyle().lower() == "none"
def test_scale_deprecation(self):
x, y = ["a", "b", "c"], [1, 2, 3]
ax = pointplot(x=x, y=y, errorbar=None)
with pytest.warns(UserWarning, match="The `scale` parameter"):
pointplot(x=x, y=y, errorbar=None, scale=2)
l1, l2 = ax.lines
assert l2.get_linewidth() == 2 * l1.get_linewidth()
assert l2.get_markersize() > l1.get_markersize()
def test_layered_plot_clipping(self):
x, y = ['a'], [4]
pointplot(x=x, y=y)
x, y = ['b'], [5]
ax = pointplot(x=x, y=y)
y_range = ax.viewLim.intervaly
assert y_range[0] < 4 and y_range[1] > 5
| TestPointPlot |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_deployments.py | {
"start": 128827,
"end": 131175
} | class ____:
async def test_404_on_bad_id(self, client):
response = await client.get(f"deployments/{uuid4()}/work_queue_check")
assert response.status_code == status.HTTP_404_NOT_FOUND
async def test_well_formed_response(
self,
session,
client,
flow,
):
await models.work_queues.create_work_queue(
session=session,
work_queue=schemas.actions.WorkQueueCreate(
name="First",
filter=schemas.core.QueueFilter(tags=["a"]),
),
)
await models.work_queues.create_work_queue(
session=session,
work_queue=schemas.actions.WorkQueueCreate(
name="Second",
filter=schemas.core.QueueFilter(tags=["b"]),
),
)
deployment = await models.deployments.create_deployment(
session=session,
deployment=schemas.core.Deployment(
name="My Deployment",
flow_id=flow.id,
tags=["a", "b", "c"],
),
)
await session.commit()
response = await client.get(f"deployments/{deployment.id}/work_queue_check")
assert response.status_code == status.HTTP_200_OK
connection_url = PREFECT_API_DATABASE_CONNECTION_URL.value()
dialect = get_dialect(connection_url)
if dialect.name == "postgresql":
assert len(response.json()) == 2
q1, q2 = response.json()
assert {q1["name"], q2["name"]} == {"First", "Second"}
assert set(q1["filter"]["tags"] + q2["filter"]["tags"]) == {"a", "b"}
assert (
q1["filter"]["deployment_ids"] == q2["filter"]["deployment_ids"] is None
)
else:
# sqlite picks up the default queue because it has no filter
assert len(response.json()) == 3
q1, q2, q3 = response.json()
assert {q1["name"], q2["name"], q3["name"]} == {
"First",
"Second",
"default",
}
assert set(q2["filter"]["tags"] + q3["filter"]["tags"]) == {"a", "b"}
assert (
q2["filter"]["deployment_ids"] == q3["filter"]["deployment_ids"] is None
)
| TestGetDeploymentWorkQueueCheck |
python | airbytehq__airbyte | airbyte-ci/connectors/connectors_qa/src/connectors_qa/checks/assets.py | {
"start": 1951,
"end": 4288
} | class ____(AssetsCheck):
name = "Connectors must have an icon"
description = "Each connector must have an icon available in at the root of the connector code directory. It must be an SVG file named `icon.svg` and must be a square."
requires_metadata = False
def _check_is_valid_svg(self, icon_path: Path) -> Tuple[bool, str | None]:
try:
# Ensure the file has an .svg extension
if not icon_path.suffix.lower() == ".svg":
return False, "Icon file is not a SVG file"
# Parse the file as XML
tree = ET.parse(icon_path)
root = tree.getroot()
# Check if the root tag is an 'svg' element
if root.tag == "{http://www.w3.org/2000/svg}svg":
return True, None
else:
return False, "Icon file is not a valid SVG file"
except (ET.ParseError, FileNotFoundError):
# If parsing fails or file not found, it's not a valid SVG
return False, "Icon file is not a valid SVG file"
def _run(self, connector: Connector) -> CheckResult:
if not connector.icon_path or not connector.icon_path.exists():
return self.create_check_result(
connector=connector,
passed=False,
message="Icon file is missing. Please create an icon file at the root of the connector code directory",
)
is_valid_svg, error_message = self._check_is_valid_svg(connector.icon_path)
if not is_valid_svg:
assert error_message is not None
return self.create_check_result(
connector=connector,
passed=False,
message=error_message,
)
if connector.icon_path.read_text().strip().lower() == DEFAULT_AIRBYTE_ICON.strip().lower():
return self.create_check_result(
connector=connector,
passed=False,
message="Icon file is the default Airbyte icon. Please replace it with a custom square icon",
)
# TODO check that the icon is a square
return self.create_check_result(connector=connector, passed=True, message="Icon file is a valid SVG file")
ENABLED_CHECKS = [CheckConnectorIconIsAvailable()]
| CheckConnectorIconIsAvailable |
python | apache__airflow | providers/apache/kafka/tests/unit/apache/kafka/triggers/test_await_message.py | {
"start": 1490,
"end": 1687
} | class ____:
def __init__(*args, **kwargs) -> None:
pass
def poll(*args, **kwargs):
return MockedMessage()
def commit(*args, **kwargs):
return True
| MockedConsumer |
python | getsentry__sentry | tests/sentry/releases/endpoints/test_organization_release_files.py | {
"start": 7605,
"end": 14621
} | class ____(APITestCase):
def test_simple(self) -> None:
project = self.create_project(name="foo")
release = Release.objects.create(organization_id=project.organization_id, version="1")
release.add_project(project)
assert release.count_artifacts() == 0
url = reverse(
"sentry-api-0-organization-release-files",
kwargs={
"organization_id_or_slug": project.organization.slug,
"version": release.version,
},
)
self.login_as(user=self.user)
response = self.client.post(
url,
{
"name": "http://example.com/application.js",
"header": "X-SourceMap: http://example.com",
"file": SimpleUploadedFile(
"application.js", b"function() { }", content_type="application/javascript"
),
},
format="multipart",
)
assert release.count_artifacts() == 1
assert response.status_code == 201, response.content
releasefile = ReleaseFile.objects.get(release_id=release.id)
assert releasefile.name == "http://example.com/application.js"
assert releasefile.ident == ReleaseFile.get_ident("http://example.com/application.js")
assert releasefile.file.headers == {
"Content-Type": "application/javascript",
"X-SourceMap": "http://example.com",
}
def test_no_file(self) -> None:
project = self.create_project(name="foo")
release = Release.objects.create(organization_id=project.organization_id, version="1")
release.add_project(project)
url = reverse(
"sentry-api-0-organization-release-files",
kwargs={
"organization_id_or_slug": project.organization.slug,
"version": release.version,
},
)
self.login_as(user=self.user)
response = self.client.post(
url, {"header": "X-SourceMap: http://example.com"}, format="multipart"
)
assert response.status_code == 400, response.content
def test_missing_name(self) -> None:
project = self.create_project(name="foo")
release = Release.objects.create(organization_id=project.organization_id, version="1")
release.add_project(project)
url = reverse(
"sentry-api-0-organization-release-files",
kwargs={
"organization_id_or_slug": project.organization.slug,
"version": release.version,
},
)
self.login_as(user=self.user)
response = self.client.post(
url,
{
"header": "X-SourceMap: http://example.com",
# We can't use SimpleUploadedFile here, because it validates file names
# and doesn't allow for empty strings.
"file": ContentFile(
content=b"function() { }",
name="",
),
},
format="multipart",
)
assert response.status_code == 400, response.content
def test_invalid_name(self) -> None:
project = self.create_project(name="foo")
release = Release.objects.create(organization_id=project.organization_id, version="1")
release.add_project(project)
url = reverse(
"sentry-api-0-organization-release-files",
kwargs={
"organization_id_or_slug": project.organization.slug,
"version": release.version,
},
)
self.login_as(user=self.user)
response = self.client.post(
url,
{
"name": "http://exa\tmple.com/applic\nati\ron.js\n",
"header": "X-SourceMap: http://example.com/test.map.js",
"file": SimpleUploadedFile(
"application.js", b"function() { }", content_type="application/javascript"
),
},
format="multipart",
)
assert response.status_code == 400, response.content
def test_bad_headers(self) -> None:
project = self.create_project(name="foo")
release = Release.objects.create(organization_id=project.organization_id, version="1")
release.add_project(project)
url = reverse(
"sentry-api-0-organization-release-files",
kwargs={
"organization_id_or_slug": project.organization.slug,
"version": release.version,
},
)
self.login_as(user=self.user)
response = self.client.post(
url,
{
"name": "http://example.com/application.js",
"header": "lol",
"file": SimpleUploadedFile(
"application.js", b"function() { }", content_type="application/javascript"
),
},
format="multipart",
)
assert response.status_code == 400, response.content
response = self.client.post(
url,
{
"name": "http://example.com/application.js",
"header": "X-SourceMap: http://example.com/\r\n\ntest.map.js\n",
"file": SimpleUploadedFile(
"application.js", b"function() { }", content_type="application/javascript"
),
},
format="multipart",
)
assert response.status_code == 400, response.content
def test_duplicate_file(self) -> None:
project = self.create_project(name="foo")
release = Release.objects.create(organization_id=project.organization_id, version="1")
release.add_project(project)
url = reverse(
"sentry-api-0-organization-release-files",
kwargs={
"organization_id_or_slug": project.organization.slug,
"version": release.version,
},
)
self.login_as(user=self.user)
data = {
"name": "http://example.com/application.js",
"header": "X-SourceMap: http://example.com",
"file": SimpleUploadedFile(
"application.js", b"function() { }", content_type="application/javascript"
),
}
response = self.client.post(url, data, format="multipart")
assert response.status_code == 201, response.content
releasefile = ReleaseFile.objects.get(release_id=release.id)
assert releasefile.name == "http://example.com/application.js"
assert releasefile.file.headers == {
"Content-Type": "application/javascript",
"X-SourceMap": "http://example.com",
}
# Now upload it again!
response = self.client.post(url, data, format="multipart")
assert response.status_code == 409, response.content
| ReleaseFileCreateTest |
python | encode__django-rest-framework | tests/test_validation.py | {
"start": 5672,
"end": 7696
} | class ____(TestCase):
CHOICES = [
(0, 'Small'),
(1, 'Medium'),
(2, 'Large'),
]
SINGLE_CHOICES = [0, 1, 2]
CHOICES_NESTED = [
('Category', (
(1, 'First'),
(2, 'Second'),
(3, 'Third'),
)),
(4, 'Fourth'),
]
MIXED_CHOICES = [
('Category', (
(1, 'First'),
(2, 'Second'),
)),
3,
(4, 'Fourth'),
]
def test_choices(self):
"""
Make sure a value for choices works as expected.
"""
f = serializers.ChoiceField(choices=self.CHOICES)
value = self.CHOICES[0][0]
try:
f.to_internal_value(value)
except serializers.ValidationError:
self.fail("Value %s does not validate" % str(value))
def test_single_choices(self):
"""
Make sure a single value for choices works as expected.
"""
f = serializers.ChoiceField(choices=self.SINGLE_CHOICES)
value = self.SINGLE_CHOICES[0]
try:
f.to_internal_value(value)
except serializers.ValidationError:
self.fail("Value %s does not validate" % str(value))
def test_nested_choices(self):
"""
Make sure a nested value for choices works as expected.
"""
f = serializers.ChoiceField(choices=self.CHOICES_NESTED)
value = self.CHOICES_NESTED[0][1][0][0]
try:
f.to_internal_value(value)
except serializers.ValidationError:
self.fail("Value %s does not validate" % str(value))
def test_mixed_choices(self):
"""
Make sure mixed values for choices works as expected.
"""
f = serializers.ChoiceField(choices=self.MIXED_CHOICES)
value = self.MIXED_CHOICES[1]
try:
f.to_internal_value(value)
except serializers.ValidationError:
self.fail("Value %s does not validate" % str(value))
| TestChoiceFieldChoicesValidate |
python | pypa__pip | src/pip/_vendor/pkg_resources/__init__.py | {
"start": 44745,
"end": 45226
} | class ____(RuntimeError):
"""An error occurred extracting a resource
The following attributes are available from instances of this exception:
manager
The resource manager that raised this exception
cache_path
The base directory for resource extraction
original_error
The exception instance that caused extraction to fail
"""
manager: ResourceManager
cache_path: str
original_error: BaseException | None
| ExtractionError |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-aws-datalake/destination_aws_datalake/config_reader.py | {
"start": 428,
"end": 655
} | class ____(enum.Enum):
PARQUET = "Parquet"
JSONL = "JSONL"
@staticmethod
def from_string(s: str):
if s == "Parquet":
return OutputFormat.PARQUET
return OutputFormat.JSONL
| OutputFormat |
python | cython__cython | docs/examples/userguide/early_binding_for_speed/rectangle.py | {
"start": 15,
"end": 516
} | class ____:
x0: cython.int
y0: cython.int
x1: cython.int
y1: cython.int
def __init__(self, x0: cython.int, y0: cython.int, x1: cython.int, y1: cython.int):
self.x0 = x0
self.y0 = y0
self.x1 = x1
self.y1 = y1
def area(self):
area = (self.x1 - self.x0) * (self.y1 - self.y0)
if area < 0:
area = -area
return area
def rectArea(x0, y0, x1, y1):
rect = Rectangle(x0, y0, x1, y1)
return rect.area()
| Rectangle |
python | celery__celery | t/unit/events/test_events.py | {
"start": 205,
"end": 775
} | class ____:
raise_on_publish = False
def __init__(self, *args, **kwargs):
self.sent = []
def publish(self, msg, *args, **kwargs):
if self.raise_on_publish:
raise KeyError()
self.sent.append(msg)
def close(self):
pass
def has_event(self, kind):
for event in self.sent:
if event['type'] == kind:
return event
return False
def test_Event():
event = Event('world war II')
assert event['type'] == 'world war II'
assert event['timestamp']
| MockProducer |
python | doocs__leetcode | solution/0600-0699/0628.Maximum Product of Three Numbers/Solution2.py | {
"start": 0,
"end": 240
} | class ____:
def maximumProduct(self, nums: List[int]) -> int:
top3 = nlargest(3, nums)
bottom2 = nlargest(2, nums, key=lambda x: -x)
return max(top3[0] * top3[1] * top3[2], top3[0] * bottom2[0] * bottom2[1])
| Solution |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/links/sagemaker_unified_studio.py | {
"start": 914,
"end": 1202
} | class ____(BaseAwsLink):
"""Helper class for constructing Amazon SageMaker Unified Studio Links."""
name = "Amazon SageMaker Unified Studio"
key = "sagemaker_unified_studio"
format_str = BASE_AWS_CONSOLE_LINK + "/datazone/home?region={region_name}"
| SageMakerUnifiedStudioLink |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/sqlite/base.py | {
"start": 43859,
"end": 46337
} | class ____(_DateTimeMixin, sqltypes.Date):
r"""Represent a Python date object in SQLite using a string.
The default string storage format is::
"%(year)04d-%(month)02d-%(day)02d"
e.g.:
.. sourcecode:: text
2011-03-15
The incoming storage format is by default parsed using the
Python ``date.fromisoformat()`` function.
.. versionchanged:: 2.0 ``date.fromisoformat()`` is used for default
date string parsing.
The storage format can be customized to some degree using the
``storage_format`` and ``regexp`` parameters, such as::
import re
from sqlalchemy.dialects.sqlite import DATE
d = DATE(
storage_format="%(month)02d/%(day)02d/%(year)04d",
regexp=re.compile("(?P<month>\d+)/(?P<day>\d+)/(?P<year>\d+)"),
)
:param storage_format: format string which will be applied to the
dict with keys year, month, and day.
:param regexp: regular expression which will be applied to
incoming result rows, replacing the use of ``date.fromisoformat()`` to
parse incoming strings. If the regexp contains named groups, the resulting
match dict is applied to the Python date() constructor as keyword
arguments. Otherwise, if positional groups are used, the date()
constructor is called with positional arguments via
``*map(int, match_obj.groups(0))``.
"""
_storage_format = "%(year)04d-%(month)02d-%(day)02d"
def bind_processor(
self, dialect: Dialect
) -> Optional[_BindProcessorType[Any]]:
datetime_date = datetime.date
format_ = self._storage_format
def process(value):
if value is None:
return None
elif isinstance(value, datetime_date):
return format_ % {
"year": value.year,
"month": value.month,
"day": value.day,
}
else:
raise TypeError(
"SQLite Date type only accepts Python "
"date objects as input."
)
return process
def result_processor(
self, dialect: Dialect, coltype: object
) -> Optional[_ResultProcessorType[Any]]:
if self._reg:
return processors.str_to_datetime_processor_factory(
self._reg, datetime.date
)
else:
return processors.str_to_date
| DATE |
python | milvus-io__pymilvus | tests/test_decorators.py | {
"start": 5329,
"end": 5518
} | class ____(grpc.RpcError):
def code(self):
return grpc.StatusCode.DEADLINE_EXCEEDED
def details(self):
return "details of deadline exceeded"
| MockDeadlineExceededError |
python | pypa__pipenv | pipenv/patched/pip/_internal/metadata/importlib/_dists.py | {
"start": 1179,
"end": 3465
} | class ____(importlib.metadata.Distribution):
"""An ``importlib.metadata.Distribution`` read from a wheel.
Although ``importlib.metadata.PathDistribution`` accepts ``zipfile.Path``,
its implementation is too "lazy" for pip's needs (we can't keep the ZipFile
handle open for the entire lifetime of the distribution object).
This implementation eagerly reads the entire metadata directory into the
memory instead, and operates from that.
"""
def __init__(
self,
files: Mapping[pathlib.PurePosixPath, bytes],
info_location: pathlib.PurePosixPath,
) -> None:
self._files = files
self.info_location = info_location
@classmethod
def from_zipfile(
cls,
zf: zipfile.ZipFile,
name: str,
location: str,
) -> "WheelDistribution":
info_dir, _ = parse_wheel(zf, name)
paths = (
(name, pathlib.PurePosixPath(name.split("/", 1)[-1]))
for name in zf.namelist()
if name.startswith(f"{info_dir}/")
)
files = {
relpath: read_wheel_metadata_file(zf, fullpath)
for fullpath, relpath in paths
}
info_location = pathlib.PurePosixPath(location, info_dir)
return cls(files, info_location)
def iterdir(self, path: InfoPath) -> Iterator[pathlib.PurePosixPath]:
# Only allow iterating through the metadata directory.
if pathlib.PurePosixPath(str(path)) in self._files:
return iter(self._files)
raise FileNotFoundError(path)
def read_text(self, filename: str) -> Optional[str]:
try:
data = self._files[pathlib.PurePosixPath(filename)]
except KeyError:
return None
try:
text = data.decode("utf-8")
except UnicodeDecodeError as e:
wheel = self.info_location.parent
error = f"Error decoding metadata for {wheel}: {e} in {filename} file"
raise UnsupportedWheel(error)
return text
def locate_file(self, path: Union[str, "PathLike[str]"]) -> pathlib.Path:
# This method doesn't make sense for our in-memory wheel, but the API
# requires us to define it.
raise NotImplementedError
| WheelDistribution |
python | kubernetes-client__python | kubernetes/client/models/v1_topology_selector_label_requirement.py | {
"start": 383,
"end": 4840
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'key': 'str',
'values': 'list[str]'
}
attribute_map = {
'key': 'key',
'values': 'values'
}
def __init__(self, key=None, values=None, local_vars_configuration=None): # noqa: E501
"""V1TopologySelectorLabelRequirement - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._key = None
self._values = None
self.discriminator = None
self.key = key
self.values = values
@property
def key(self):
"""Gets the key of this V1TopologySelectorLabelRequirement. # noqa: E501
The label key that the selector applies to. # noqa: E501
:return: The key of this V1TopologySelectorLabelRequirement. # noqa: E501
:rtype: str
"""
return self._key
@key.setter
def key(self, key):
"""Sets the key of this V1TopologySelectorLabelRequirement.
The label key that the selector applies to. # noqa: E501
:param key: The key of this V1TopologySelectorLabelRequirement. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and key is None: # noqa: E501
raise ValueError("Invalid value for `key`, must not be `None`") # noqa: E501
self._key = key
@property
def values(self):
"""Gets the values of this V1TopologySelectorLabelRequirement. # noqa: E501
An array of string values. One value must match the label to be selected. Each entry in Values is ORed. # noqa: E501
:return: The values of this V1TopologySelectorLabelRequirement. # noqa: E501
:rtype: list[str]
"""
return self._values
@values.setter
def values(self, values):
"""Sets the values of this V1TopologySelectorLabelRequirement.
An array of string values. One value must match the label to be selected. Each entry in Values is ORed. # noqa: E501
:param values: The values of this V1TopologySelectorLabelRequirement. # noqa: E501
:type: list[str]
"""
if self.local_vars_configuration.client_side_validation and values is None: # noqa: E501
raise ValueError("Invalid value for `values`, must not be `None`") # noqa: E501
self._values = values
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1TopologySelectorLabelRequirement):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1TopologySelectorLabelRequirement):
return True
return self.to_dict() != other.to_dict()
| V1TopologySelectorLabelRequirement |
python | python-pillow__Pillow | src/PIL/ImageCms.py | {
"start": 3932,
"end": 6969
} | class ____(IntFlag):
"""Flags and documentation are taken from ``lcms2.h``."""
NONE = 0
NOCACHE = 0x0040
"""Inhibit 1-pixel cache"""
NOOPTIMIZE = 0x0100
"""Inhibit optimizations"""
NULLTRANSFORM = 0x0200
"""Don't transform anyway"""
GAMUTCHECK = 0x1000
"""Out of Gamut alarm"""
SOFTPROOFING = 0x4000
"""Do softproofing"""
BLACKPOINTCOMPENSATION = 0x2000
NOWHITEONWHITEFIXUP = 0x0004
"""Don't fix scum dot"""
HIGHRESPRECALC = 0x0400
"""Use more memory to give better accuracy"""
LOWRESPRECALC = 0x0800
"""Use less memory to minimize resources"""
# this should be 8BITS_DEVICELINK, but that is not a valid name in Python:
USE_8BITS_DEVICELINK = 0x0008
"""Create 8 bits devicelinks"""
GUESSDEVICECLASS = 0x0020
"""Guess device class (for ``transform2devicelink``)"""
KEEP_SEQUENCE = 0x0080
"""Keep profile sequence for devicelink creation"""
FORCE_CLUT = 0x0002
"""Force CLUT optimization"""
CLUT_POST_LINEARIZATION = 0x0001
"""create postlinearization tables if possible"""
CLUT_PRE_LINEARIZATION = 0x0010
"""create prelinearization tables if possible"""
NONEGATIVES = 0x8000
"""Prevent negative numbers in floating point transforms"""
COPY_ALPHA = 0x04000000
"""Alpha channels are copied on ``cmsDoTransform()``"""
NODEFAULTRESOURCEDEF = 0x01000000
_GRIDPOINTS_1 = 1 << 16
_GRIDPOINTS_2 = 2 << 16
_GRIDPOINTS_4 = 4 << 16
_GRIDPOINTS_8 = 8 << 16
_GRIDPOINTS_16 = 16 << 16
_GRIDPOINTS_32 = 32 << 16
_GRIDPOINTS_64 = 64 << 16
_GRIDPOINTS_128 = 128 << 16
@staticmethod
def GRIDPOINTS(n: int) -> Flags:
"""
Fine-tune control over number of gridpoints
:param n: :py:class:`int` in range ``0 <= n <= 255``
"""
return Flags.NONE | ((n & 0xFF) << 16)
_MAX_FLAG = reduce(operator.or_, Flags)
_FLAGS = {
"MATRIXINPUT": 1,
"MATRIXOUTPUT": 2,
"MATRIXONLY": (1 | 2),
"NOWHITEONWHITEFIXUP": 4, # Don't hot fix scum dot
# Don't create prelinearization tables on precalculated transforms
# (internal use):
"NOPRELINEARIZATION": 16,
"GUESSDEVICECLASS": 32, # Guess device class (for transform2devicelink)
"NOTCACHE": 64, # Inhibit 1-pixel cache
"NOTPRECALC": 256,
"NULLTRANSFORM": 512, # Don't transform anyway
"HIGHRESPRECALC": 1024, # Use more memory to give better accuracy
"LOWRESPRECALC": 2048, # Use less memory to minimize resources
"WHITEBLACKCOMPENSATION": 8192,
"BLACKPOINTCOMPENSATION": 8192,
"GAMUTCHECK": 4096, # Out of Gamut alarm
"SOFTPROOFING": 16384, # Do softproofing
"PRESERVEBLACK": 32768, # Black preservation
"NODEFAULTRESOURCEDEF": 16777216, # CRD special
"GRIDPOINTS": lambda n: (n & 0xFF) << 16, # Gridpoints
}
# --------------------------------------------------------------------.
# Experimental PIL-level API
# --------------------------------------------------------------------.
##
# Profile.
| Flags |
python | apache__airflow | providers/apache/spark/src/airflow/providers/apache/spark/operators/spark_jdbc.py | {
"start": 1103,
"end": 8913
} | class ____(SparkSubmitOperator):
"""
Extend the SparkSubmitOperator to perform data transfers to/from JDBC-based databases with Apache Spark.
As with the SparkSubmitOperator, it assumes that the "spark-submit" binary is available on the PATH.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:SparkJDBCOperator`
:param spark_app_name: Name of the job (default airflow-spark-jdbc)
:param spark_conn_id: The :ref:`spark connection id <howto/connection:spark-submit>`
as configured in Airflow administration
:param spark_conf: Any additional Spark configuration properties
:param spark_py_files: Additional python files used (.zip, .egg, or .py)
:param spark_files: Additional files to upload to the container running the job
:param spark_jars: Additional jars to upload and add to the driver and
executor classpath
:param cmd_type: Which way the data should flow. 2 possible values:
spark_to_jdbc: data written by spark from metastore to jdbc
jdbc_to_spark: data written by spark from jdbc to metastore
:param jdbc_table: The name of the JDBC table
:param jdbc_conn_id: Connection id used for connection to JDBC database
:param jdbc_driver: Name of the JDBC driver to use for the JDBC connection. This
driver (usually a jar) should be passed in the 'jars' parameter
:param metastore_table: The name of the metastore table,
:param jdbc_truncate: (spark_to_jdbc only) Whether Spark should truncate or
drop and recreate the JDBC table. This only takes effect if
'save_mode' is set to Overwrite. Also, if the schema is
different, Spark cannot truncate, and will drop and recreate
:param save_mode: The Spark save-mode to use (e.g. overwrite, append, etc.)
:param save_format: (jdbc_to_spark-only) The Spark save-format to use (e.g. parquet)
:param batch_size: (spark_to_jdbc only) The size of the batch to insert per round
trip to the JDBC database. Defaults to 1000
:param fetch_size: (jdbc_to_spark only) The size of the batch to fetch per round trip
from the JDBC database. Default depends on the JDBC driver
:param num_partitions: The maximum number of partitions that can be used by Spark
simultaneously, both for spark_to_jdbc and jdbc_to_spark
operations. This will also cap the number of JDBC connections
that can be opened
:param partition_column: (jdbc_to_spark-only) A numeric column to be used to
partition the metastore table by. If specified, you must
also specify:
num_partitions, lower_bound, upper_bound
:param lower_bound: (jdbc_to_spark-only) Lower bound of the range of the numeric
partition column to fetch. If specified, you must also specify:
num_partitions, partition_column, upper_bound
:param upper_bound: (jdbc_to_spark-only) Upper bound of the range of the numeric
partition column to fetch. If specified, you must also specify:
num_partitions, partition_column, lower_bound
:param create_table_column_types: (spark_to_jdbc-only) The database column data types
to use instead of the defaults, when creating the
table. Data type information should be specified in
the same format as CREATE TABLE columns syntax
(e.g: "name CHAR(64), comments VARCHAR(1024)").
The specified types should be valid spark sql data
types.
:param kwargs: kwargs passed to SparkSubmitOperator.
"""
def __init__(
self,
*,
spark_app_name: str = "airflow-spark-jdbc",
spark_conn_id: str = "spark-default",
spark_conf: dict[str, Any] | None = None,
spark_py_files: str | None = None,
spark_files: str | None = None,
spark_jars: str | None = None,
cmd_type: str = "spark_to_jdbc",
jdbc_table: str | None = None,
jdbc_conn_id: str = "jdbc-default",
jdbc_driver: str | None = None,
metastore_table: str | None = None,
jdbc_truncate: bool = False,
save_mode: str | None = None,
save_format: str | None = None,
batch_size: int | None = None,
fetch_size: int | None = None,
num_partitions: int | None = None,
partition_column: str | None = None,
lower_bound: str | None = None,
upper_bound: str | None = None,
create_table_column_types: str | None = None,
**kwargs: Any,
) -> None:
super().__init__(**kwargs)
self._spark_app_name = spark_app_name
self._spark_conn_id = spark_conn_id
self._spark_conf = spark_conf
self._spark_py_files = spark_py_files
self._spark_files = spark_files
self._spark_jars = spark_jars
self._cmd_type = cmd_type
self._jdbc_table = jdbc_table
self._jdbc_conn_id = jdbc_conn_id
self._jdbc_driver = jdbc_driver
self._metastore_table = metastore_table
self._jdbc_truncate = jdbc_truncate
self._save_mode = save_mode
self._save_format = save_format
self._batch_size = batch_size
self._fetch_size = fetch_size
self._num_partitions = num_partitions
self._partition_column = partition_column
self._lower_bound = lower_bound
self._upper_bound = upper_bound
self._create_table_column_types = create_table_column_types
self._hook: SparkJDBCHook | None = None
def execute(self, context: Context) -> None:
"""Call the SparkSubmitHook to run the provided spark job."""
if self._hook is None:
self._hook = self._get_hook()
self._hook.submit_jdbc_job()
def on_kill(self) -> None:
if self._hook is None:
self._hook = self._get_hook()
self._hook.on_kill()
def _get_hook(self) -> SparkJDBCHook:
return SparkJDBCHook(
spark_app_name=self._spark_app_name,
spark_conn_id=self._spark_conn_id,
spark_conf=self._spark_conf,
spark_py_files=self._spark_py_files,
spark_files=self._spark_files,
spark_jars=self._spark_jars,
num_executors=self._num_executors,
executor_cores=self._executor_cores,
executor_memory=self._executor_memory,
driver_memory=self._driver_memory,
verbose=self._verbose,
keytab=self.keytab,
principal=self.principal,
cmd_type=self._cmd_type,
jdbc_table=self._jdbc_table,
jdbc_conn_id=self._jdbc_conn_id,
jdbc_driver=self._jdbc_driver,
metastore_table=self._metastore_table,
jdbc_truncate=self._jdbc_truncate,
save_mode=self._save_mode,
save_format=self._save_format,
batch_size=self._batch_size,
fetch_size=self._fetch_size,
num_partitions=self._num_partitions,
partition_column=self._partition_column,
lower_bound=self._lower_bound,
upper_bound=self._upper_bound,
create_table_column_types=self._create_table_column_types,
use_krb5ccache=self._use_krb5ccache,
)
| SparkJDBCOperator |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 176075,
"end": 187817
} | class ____(VegaLiteSchema):
"""
BaseTitleNoValueRefs schema wrapper.
Parameters
----------
align : :class:`Align`, Literal['left', 'center', 'right']
Horizontal text alignment for title text. One of ``"left"``, ``"center"``, or
``"right"``.
anchor : dict, :class:`ExprRef`, :class:`TitleAnchor`, Literal[None, 'start', 'middle', 'end']
The anchor position for placing the title and subtitle text. One of ``"start"``,
``"middle"``, or ``"end"``. For example, with an orientation of top these anchor
positions map to a left-, center-, or right-aligned title.
angle : dict, float, :class:`ExprRef`
Angle in degrees of title and subtitle text.
aria : bool, dict, :class:`ExprRef`
A boolean flag indicating if `ARIA attributes
<https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA>`__ should be
included (SVG output only). If ``false``, the "aria-hidden" attribute will be set on
the output SVG group, removing the title from the ARIA accessibility tree.
**Default value:** ``true``
baseline : :class:`Baseline`, :class:`TextBaseline`, Literal['alphabetic', 'line-bottom', 'line-top', 'top', 'middle', 'bottom']
Vertical text baseline for title and subtitle text. One of ``"alphabetic"``
(default), ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, or
``"line-bottom"``. The ``"line-top"`` and ``"line-bottom"`` values operate similarly
to ``"top"`` and ``"bottom"``, but are calculated relative to the *lineHeight*
rather than *fontSize* alone.
color : str, dict, :class:`Color`, :class:`ExprRef`, :class:`HexColor`, :class:`ColorName`, Literal['black', 'silver', 'gray', 'white', 'maroon', 'red', 'purple', 'fuchsia', 'green', 'lime', 'olive', 'yellow', 'navy', 'blue', 'teal', 'aqua', 'orange', 'aliceblue', 'antiquewhite', 'aquamarine', 'azure', 'beige', 'bisque', 'blanchedalmond', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'limegreen', 'linen', 'magenta', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'oldlace', 'olivedrab', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'whitesmoke', 'yellowgreen', 'rebeccapurple'], None
Text color for title text.
dx : dict, float, :class:`ExprRef`
Delta offset for title and subtitle text x-coordinate.
dy : dict, float, :class:`ExprRef`
Delta offset for title and subtitle text y-coordinate.
font : str, dict, :class:`ExprRef`
Font name for title text.
fontSize : dict, float, :class:`ExprRef`
Font size in pixels for title text.
fontStyle : str, dict, :class:`ExprRef`, :class:`FontStyle`
Font style for title text.
fontWeight : dict, :class:`ExprRef`, :class:`FontWeight`, Literal['normal', 'bold', 'lighter', 'bolder', 100, 200, 300, 400, 500, 600, 700, 800, 900]
Font weight for title text. This can be either a string (e.g ``"bold"``,
``"normal"``) or a number (``100``, ``200``, ``300``, ..., ``900`` where
``"normal"`` = ``400`` and ``"bold"`` = ``700``).
frame : str, dict, :class:`ExprRef`, :class:`TitleFrame`, Literal['bounds', 'group']
The reference frame for the anchor position, one of ``"bounds"`` (to anchor relative
to the full bounding box) or ``"group"`` (to anchor relative to the group width or
height).
limit : dict, float, :class:`ExprRef`
The maximum allowed length in pixels of title and subtitle text.
lineHeight : dict, float, :class:`ExprRef`
Line height in pixels for multi-line title text or title text with ``"line-top"`` or
``"line-bottom"`` baseline.
offset : dict, float, :class:`ExprRef`
The orthogonal offset in pixels by which to displace the title group from its
position along the edge of the chart.
orient : dict, :class:`ExprRef`, :class:`TitleOrient`, Literal['none', 'left', 'right', 'top', 'bottom']
Default title orientation (``"top"``, ``"bottom"``, ``"left"``, or ``"right"``)
subtitleColor : str, dict, :class:`Color`, :class:`ExprRef`, :class:`HexColor`, :class:`ColorName`, Literal['black', 'silver', 'gray', 'white', 'maroon', 'red', 'purple', 'fuchsia', 'green', 'lime', 'olive', 'yellow', 'navy', 'blue', 'teal', 'aqua', 'orange', 'aliceblue', 'antiquewhite', 'aquamarine', 'azure', 'beige', 'bisque', 'blanchedalmond', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'limegreen', 'linen', 'magenta', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'oldlace', 'olivedrab', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'whitesmoke', 'yellowgreen', 'rebeccapurple'], None
Text color for subtitle text.
subtitleFont : str, dict, :class:`ExprRef`
Font name for subtitle text.
subtitleFontSize : dict, float, :class:`ExprRef`
Font size in pixels for subtitle text.
subtitleFontStyle : str, dict, :class:`ExprRef`, :class:`FontStyle`
Font style for subtitle text.
subtitleFontWeight : dict, :class:`ExprRef`, :class:`FontWeight`, Literal['normal', 'bold', 'lighter', 'bolder', 100, 200, 300, 400, 500, 600, 700, 800, 900]
Font weight for subtitle text. This can be either a string (e.g ``"bold"``,
``"normal"``) or a number (``100``, ``200``, ``300``, ..., ``900`` where
``"normal"`` = ``400`` and ``"bold"`` = ``700``).
subtitleLineHeight : dict, float, :class:`ExprRef`
Line height in pixels for multi-line subtitle text.
subtitlePadding : dict, float, :class:`ExprRef`
The padding in pixels between title and subtitle text.
zindex : dict, float, :class:`ExprRef`
The integer z-index indicating the layering of the title group relative to other
axis, mark, and legend groups.
**Default value:** ``0``.
"""
_schema = {"$ref": "#/definitions/BaseTitleNoValueRefs"}
def __init__(
self,
align: Optional[SchemaBase | Align_T] = Undefined,
anchor: Optional[Parameter | SchemaBase | Map | TitleAnchor_T] = Undefined,
angle: Optional[float | Parameter | SchemaBase | Map] = Undefined,
aria: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
baseline: Optional[SchemaBase | TextBaseline_T] = Undefined,
color: Optional[
str | Parameter | SchemaBase | Map | ColorName_T | None
] = Undefined,
dx: Optional[float | Parameter | SchemaBase | Map] = Undefined,
dy: Optional[float | Parameter | SchemaBase | Map] = Undefined,
font: Optional[str | Parameter | SchemaBase | Map] = Undefined,
fontSize: Optional[float | Parameter | SchemaBase | Map] = Undefined,
fontStyle: Optional[str | Parameter | SchemaBase | Map] = Undefined,
fontWeight: Optional[Parameter | SchemaBase | Map | FontWeight_T] = Undefined,
frame: Optional[str | Parameter | SchemaBase | Map | TitleFrame_T] = Undefined,
limit: Optional[float | Parameter | SchemaBase | Map] = Undefined,
lineHeight: Optional[float | Parameter | SchemaBase | Map] = Undefined,
offset: Optional[float | Parameter | SchemaBase | Map] = Undefined,
orient: Optional[Parameter | SchemaBase | Map | TitleOrient_T] = Undefined,
subtitleColor: Optional[
str | Parameter | SchemaBase | Map | ColorName_T | None
] = Undefined,
subtitleFont: Optional[str | Parameter | SchemaBase | Map] = Undefined,
subtitleFontSize: Optional[float | Parameter | SchemaBase | Map] = Undefined,
subtitleFontStyle: Optional[str | Parameter | SchemaBase | Map] = Undefined,
subtitleFontWeight: Optional[
Parameter | SchemaBase | Map | FontWeight_T
] = Undefined,
subtitleLineHeight: Optional[float | Parameter | SchemaBase | Map] = Undefined,
subtitlePadding: Optional[float | Parameter | SchemaBase | Map] = Undefined,
zindex: Optional[float | Parameter | SchemaBase | Map] = Undefined,
**kwds,
):
super().__init__(
align=align,
anchor=anchor,
angle=angle,
aria=aria,
baseline=baseline,
color=color,
dx=dx,
dy=dy,
font=font,
fontSize=fontSize,
fontStyle=fontStyle,
fontWeight=fontWeight,
frame=frame,
limit=limit,
lineHeight=lineHeight,
offset=offset,
orient=orient,
subtitleColor=subtitleColor,
subtitleFont=subtitleFont,
subtitleFontSize=subtitleFontSize,
subtitleFontStyle=subtitleFontStyle,
subtitleFontWeight=subtitleFontWeight,
subtitleLineHeight=subtitleLineHeight,
subtitlePadding=subtitlePadding,
zindex=zindex,
**kwds,
)
| BaseTitleNoValueRefs |
python | pytest-dev__pytest | testing/test_tmpdir.py | {
"start": 2334,
"end": 11136
} | class ____:
def test_getbasetemp_custom_removes_old(self, pytester: Pytester) -> None:
mytemp = pytester.path.joinpath("xyz")
p = pytester.makepyfile(
"""
def test_1(tmp_path):
pass
"""
)
pytester.runpytest(p, f"--basetemp={mytemp}")
assert mytemp.exists()
mytemp.joinpath("hello").touch()
pytester.runpytest(p, f"--basetemp={mytemp}")
assert mytemp.exists()
assert not mytemp.joinpath("hello").exists()
def test_policy_failed_removes_only_passed_dir(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
def test_1(tmp_path):
assert 0 == 0
def test_2(tmp_path):
assert 0 == 1
"""
)
pytester.makepyprojecttoml(
"""
[tool.pytest.ini_options]
tmp_path_retention_policy = "failed"
"""
)
pytester.inline_run(p)
root = pytester._test_tmproot
for child in root.iterdir():
base_dir = list(
filter(lambda x: x.is_dir() and not x.is_symlink(), child.iterdir())
)
assert len(base_dir) == 1
test_dir = list(
filter(
lambda x: x.is_dir() and not x.is_symlink(), base_dir[0].iterdir()
)
)
# Check only the failed one remains
assert len(test_dir) == 1
assert test_dir[0].name == "test_20"
def test_policy_failed_removes_basedir_when_all_passed(
self, pytester: Pytester
) -> None:
p = pytester.makepyfile(
"""
def test_1(tmp_path):
assert 0 == 0
"""
)
pytester.makepyprojecttoml(
"""
[tool.pytest.ini_options]
tmp_path_retention_policy = "failed"
"""
)
pytester.inline_run(p)
root = pytester._test_tmproot
for child in root.iterdir():
# This symlink will be deleted by cleanup_numbered_dir **after**
# the test finishes because it's triggered by atexit.
# So it has to be ignored here.
base_dir = filter(lambda x: not x.is_symlink(), child.iterdir())
# Check the base dir itself is gone
assert len(list(base_dir)) == 0
# issue #10502
def test_policy_failed_removes_dir_when_skipped_from_fixture(
self, pytester: Pytester
) -> None:
p = pytester.makepyfile(
"""
import pytest
@pytest.fixture
def fixt(tmp_path):
pytest.skip()
def test_fixt(fixt):
pass
"""
)
pytester.makepyprojecttoml(
"""
[tool.pytest.ini_options]
tmp_path_retention_policy = "failed"
"""
)
pytester.inline_run(p)
# Check if the whole directory is removed
root = pytester._test_tmproot
for child in root.iterdir():
base_dir = list(
filter(lambda x: x.is_dir() and not x.is_symlink(), child.iterdir())
)
assert len(base_dir) == 0
# issue #10502
def test_policy_all_keeps_dir_when_skipped_from_fixture(
self, pytester: Pytester
) -> None:
p = pytester.makepyfile(
"""
import pytest
@pytest.fixture
def fixt(tmp_path):
pytest.skip()
def test_fixt(fixt):
pass
"""
)
pytester.makepyprojecttoml(
"""
[tool.pytest.ini_options]
tmp_path_retention_policy = "all"
"""
)
pytester.inline_run(p)
# Check if the whole directory is kept
root = pytester._test_tmproot
for child in root.iterdir():
base_dir = list(
filter(lambda x: x.is_dir() and not x.is_symlink(), child.iterdir())
)
assert len(base_dir) == 1
test_dir = list(
filter(
lambda x: x.is_dir() and not x.is_symlink(), base_dir[0].iterdir()
)
)
assert len(test_dir) == 1
testdata = [
("mypath", True),
("/mypath1", False),
("./mypath1", True),
("../mypath3", False),
("../../mypath4", False),
("mypath5/..", False),
("mypath6/../mypath6", True),
("mypath7/../mypath7/..", False),
]
@pytest.mark.parametrize("basename, is_ok", testdata)
def test_mktemp(pytester: Pytester, basename: str, is_ok: bool) -> None:
mytemp = pytester.mkdir("mytemp")
p = pytester.makepyfile(
f"""
def test_abs_path(tmp_path_factory):
tmp_path_factory.mktemp('{basename}', numbered=False)
"""
)
result = pytester.runpytest(p, f"--basetemp={mytemp}")
if is_ok:
assert result.ret == 0
assert mytemp.joinpath(basename).exists()
else:
assert result.ret == 1
result.stdout.fnmatch_lines("*ValueError*")
def test_tmp_path_always_is_realpath(pytester: Pytester, monkeypatch) -> None:
# the reason why tmp_path should be a realpath is that
# when you cd to it and do "os.getcwd()" you will anyway
# get the realpath. Using the symlinked path can thus
# easily result in path-inequality
# XXX if that proves to be a problem, consider using
# os.environ["PWD"]
realtemp = pytester.mkdir("myrealtemp")
linktemp = pytester.path.joinpath("symlinktemp")
attempt_symlink_to(linktemp, str(realtemp))
monkeypatch.setenv("PYTEST_DEBUG_TEMPROOT", str(linktemp))
pytester.makepyfile(
"""
def test_1(tmp_path):
assert tmp_path.resolve() == tmp_path
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
def test_tmp_path_too_long_on_parametrization(pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrize("arg", ["1"*1000])
def test_some(arg, tmp_path):
tmp_path.joinpath("hello").touch()
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
def test_tmp_path_factory(pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope='session')
def session_dir(tmp_path_factory):
return tmp_path_factory.mktemp('data', numbered=False)
def test_some(session_dir):
assert session_dir.is_dir()
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
def test_tmp_path_fallback_tox_env(pytester: Pytester, monkeypatch) -> None:
"""Test that tmp_path works even if environment variables required by getpass
module are missing (#1010).
"""
monkeypatch.delenv("USER", raising=False)
monkeypatch.delenv("USERNAME", raising=False)
pytester.makepyfile(
"""
def test_some(tmp_path):
assert tmp_path.is_dir()
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
@pytest.fixture
def break_getuser(monkeypatch):
monkeypatch.setattr("os.getuid", lambda: -1)
# taken from python 2.7/3.4
for envvar in ("LOGNAME", "USER", "LNAME", "USERNAME"):
monkeypatch.delenv(envvar, raising=False)
@pytest.mark.usefixtures("break_getuser")
@pytest.mark.skipif(sys.platform.startswith("win"), reason="no os.getuid on windows")
def test_tmp_path_fallback_uid_not_found(pytester: Pytester) -> None:
"""Test that tmp_path works even if the current process's user id does not
correspond to a valid user.
"""
pytester.makepyfile(
"""
def test_some(tmp_path):
assert tmp_path.is_dir()
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
@pytest.mark.usefixtures("break_getuser")
@pytest.mark.skipif(sys.platform.startswith("win"), reason="no os.getuid on windows")
def test_get_user_uid_not_found():
"""Test that get_user() function works even if the current process's
user id does not correspond to a valid user (e.g. running pytest in a
Docker container with 'docker run -u'.
"""
assert get_user() is None
@pytest.mark.skipif(not sys.platform.startswith("win"), reason="win only")
def test_get_user(monkeypatch):
"""Test that get_user() function works even if environment variables
required by getpass module are missing from the environment on Windows
(#1010).
"""
monkeypatch.delenv("USER", raising=False)
monkeypatch.delenv("USERNAME", raising=False)
assert get_user() is None
| TestConfigTmpPath |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/roles.py | {
"start": 3300,
"end": 3407
} | class ____(AllowsLambdaRole, ByOfRole):
__slots__ = ()
_role_name = "ORDER BY expression"
| OrderByRole |
python | openai__openai-python | src/openai/resources/fine_tuning/fine_tuning.py | {
"start": 4216,
"end": 4794
} | class ____:
def __init__(self, fine_tuning: FineTuning) -> None:
self._fine_tuning = fine_tuning
@cached_property
def jobs(self) -> JobsWithStreamingResponse:
return JobsWithStreamingResponse(self._fine_tuning.jobs)
@cached_property
def checkpoints(self) -> CheckpointsWithStreamingResponse:
return CheckpointsWithStreamingResponse(self._fine_tuning.checkpoints)
@cached_property
def alpha(self) -> AlphaWithStreamingResponse:
return AlphaWithStreamingResponse(self._fine_tuning.alpha)
| FineTuningWithStreamingResponse |
python | pytorch__pytorch | torch/_inductor/codegen/wrapper.py | {
"start": 27688,
"end": 28327
} | class ____(MemoryPlanningLine):
node: BufferLike
reused_as: BufferLike
layout: ir.Layout
def plan(self, state: MemoryPlanningState) -> MemoryPlanningLine:
return self
def codegen(self, code: IndentedBuffer) -> None:
assert isinstance(self.layout, ir.NonOwningLayout)
assert isinstance(self.layout.view, ir.ReinterpretView)
self.wrapper.codegen_deferred_allocation(
self.reused_as.get_name(), self.layout.view
)
def codegen_fx(self, converter: FxConverter) -> FxConversionFunc:
return converter._generate_reinterpret
@dataclasses.dataclass
| ReinterpretLine |
python | getsentry__sentry | src/sentry/relocation/models/relocationtransfer.py | {
"start": 625,
"end": 1405
} | class ____(DefaultFieldsModel):
"""
Base class for control + region relocation transfer models
Relocation transfers are used to record a retriable
state of a regional transfer for relocation data.
These models replace outbox based transfers.
"""
__relocation_scope__ = RelocationScope.Excluded
relocation_uuid = UUIDField()
org_slug = models.CharField(null=False)
requesting_region = models.CharField(null=False)
exporting_region = models.CharField(null=False)
state = models.CharField(
choices=RelocationTransferState, default=RelocationTransferState.Request
)
scheduled_for = models.DateTimeField(null=True, default=timezone.now)
class Meta:
abstract = True
@control_silo_model
| BaseRelocationTransfer |
python | pypa__setuptools | pkg_resources/__init__.py | {
"start": 8567,
"end": 9479
} | class ____(ResolutionError):
"""
An already-installed version conflicts with the requested version.
Should be initialized with the installed Distribution and the requested
Requirement.
"""
_template = "{self.dist} is installed but {self.req} is required"
@property
def dist(self) -> Distribution:
return self.args[0]
@property
def req(self) -> Requirement:
return self.args[1]
def report(self):
return self._template.format(**locals())
def with_context(
self, required_by: set[Distribution | str]
) -> Self | ContextualVersionConflict:
"""
If required_by is non-empty, return a version of self that is a
ContextualVersionConflict.
"""
if not required_by:
return self
args = self.args + (required_by,)
return ContextualVersionConflict(*args)
| VersionConflict |
python | conda__conda | conda/exceptions.py | {
"start": 20856,
"end": 22791
} | class ____(CondaError):
def __init__(
self,
message: str,
url: str,
status_code: int | str,
reason: str,
elapsed_time: timedelta | str,
response: requests.Response | None = None,
caused_by: Any = None,
):
# if response includes a valid json body we prefer the reason/message defined there
try:
body = response.json()
except (AttributeError, JSONDecodeError):
body = {}
else:
reason = body.get("reason") or reason
message = body.get("message") or message
# if RFC 9457 'detail' is present, it is preferred over 'message'
# See https://datatracker.ietf.org/doc/html/rfc9457
message = body.get("detail") or message
# standardize arguments
url = maybe_unquote(url)
status_code = status_code or "000"
reason = reason or "CONNECTION FAILED"
elapsed_time = elapsed_time or "-"
if isinstance(elapsed_time, timedelta):
elapsed_time = str(elapsed_time).split(":", 1)[-1]
# extract CF-RAY
try:
cf_ray = response.headers["CF-RAY"]
except (AttributeError, KeyError):
cf_ray = ""
else:
cf_ray = f"CF-RAY: {cf_ray}\n"
super().__init__(
dals(
f"""
HTTP {status_code} {reason} for url <{url}>
Elapsed: {elapsed_time}
{cf_ray}
"""
)
# since message may include newlines don't include in f-string/dals above
+ message,
url=url,
status_code=status_code,
reason=reason,
elapsed_time=elapsed_time,
response_details=stringify(response, content_max_len=1024) or "",
json=body,
caused_by=caused_by,
)
| CondaHTTPError |
python | django-compressor__django-compressor | compressor/tests/test_offline.py | {
"start": 16261,
"end": 16424
} | class ____(OfflineTestCaseMixin, TestCase):
templates_dir = "test_static_templatetag"
expected_hash = "be0b1eade28b"
| OfflineCompressStaticTemplateTagTestCase |
python | huggingface__transformers | tests/models/pvt_v2/test_modeling_pvt_v2.py | {
"start": 4960,
"end": 9779
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (PvtV2Model, PvtV2ForImageClassification) if is_torch_available() else ()
pipeline_model_mapping = (
{"feature-extraction": PvtV2Model, "image-classification": PvtV2ForImageClassification}
if is_torch_available()
else {}
)
test_resize_embeddings = False
has_attentions = False
test_torch_exportable = True
def setUp(self):
self.model_tester = PvtV2ModelTester(self)
self.config_tester = PvtV2ConfigTester(self, config_class=PvtV2Config)
def test_config(self):
self.config_tester.run_common_tests()
def test_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*config_and_inputs)
def test_batching_equivalence(self, atol=5e-4, rtol=5e-4):
super().test_batching_equivalence(atol=atol, rtol=rtol)
@unittest.skip(reason="Pvt-V2 does not use inputs_embeds")
def test_inputs_embeds(self):
pass
@unittest.skip(reason="Pvt-V2 does not have get_input_embeddings method and get_output_embeddings methods")
def test_model_get_set_embeddings(self):
pass
@unittest.skip(reason="This architecture does not work with using reentrant.")
def test_training_gradient_checkpointing(self):
# Scenario - 1 default behaviour
self.check_training_gradient_checkpointing()
@unittest.skip(reason="This architecture does not work with using reentrant.")
def test_training_gradient_checkpointing_use_reentrant(self):
# Scenario - 2 with `use_reentrant=True` - this is the default value that is used in pytorch's
# torch.utils.checkpoint.checkpoint
self.check_training_gradient_checkpointing(gradient_checkpointing_kwargs={"use_reentrant": True})
def test_hidden_states_output(self):
def check_hidden_states_output(inputs_dict, config, model_class):
model = model_class(config)
model.to(torch_device)
model.eval()
with torch.no_grad():
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
hidden_states = outputs.hidden_states
expected_num_layers = len(self.model_tester.depths)
self.assertEqual(len(hidden_states), expected_num_layers)
# verify the first hidden states (first block)
self.assertListEqual(
list(hidden_states[0].shape[-3:]),
[
self.model_tester.hidden_sizes[self.model_tester.out_indices[0]],
self.model_tester.image_size // 2 ** (2 + self.model_tester.out_indices[0]),
self.model_tester.image_size // 2 ** (2 + self.model_tester.out_indices[0]),
],
)
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
inputs_dict["output_hidden_states"] = True
check_hidden_states_output(inputs_dict, config, model_class)
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
config.output_hidden_states = True
check_hidden_states_output(inputs_dict, config, model_class)
def test_training(self):
if not self.model_tester.is_training:
self.skipTest(reason="model_tester.is_training is set to False")
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
config.return_dict = True
for model_class in self.all_model_classes:
if model_class.__name__ in MODEL_MAPPING_NAMES.values():
continue
model = model_class(config)
model.to(torch_device)
model.train()
inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
loss = model(**inputs).loss
loss.backward()
def test_forward_signature(self):
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
model = model_class(config)
signature = inspect.signature(model.forward)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
arg_names = [*signature.parameters.keys()]
expected_arg_names = ["pixel_values"]
self.assertListEqual(arg_names[:1], expected_arg_names)
@slow
def test_model_from_pretrained(self):
model_name = "OpenGVLab/pvt_v2_b0"
model = PvtV2Model.from_pretrained(model_name)
self.assertIsNotNone(model)
@require_torch
| PvtV2ModelTest |
python | dask__distributed | distributed/client.py | {
"start": 213998,
"end": 216475
} | class ____:
"""
Collect task stream within a context block
This provides diagnostic information about every task that was run during
the time when this block was active.
This must be used as a context manager.
Parameters
----------
plot: boolean, str
If true then also return a Bokeh figure
If plot == 'save' then save the figure to a file
filename: str (optional)
The filename to save to if you set ``plot='save'``
Examples
--------
>>> with get_task_stream() as ts:
... x.compute()
>>> ts.data
[...]
Get back a Bokeh figure and optionally save to a file
>>> with get_task_stream(plot='save', filename='task-stream.html') as ts:
... x.compute()
>>> ts.figure
<Bokeh Figure>
To share this file with others you may wish to upload and serve it online.
A common way to do this is to upload the file as a gist, and then serve it
on https://raw.githack.com ::
$ python -m pip install gist
$ gist task-stream.html
https://gist.github.com/8a5b3c74b10b413f612bb5e250856ceb
You can then navigate to that site, click the "Raw" button to the right of
the ``task-stream.html`` file, and then provide that URL to
https://raw.githack.com . This process should provide a sharable link that
others can use to see your task stream plot.
See Also
--------
Client.get_task_stream: Function version of this context manager
"""
def __init__(self, client=None, plot=False, filename="task-stream.html"):
self.data = []
self._plot = plot
self._filename = filename
self.figure = None
self.client = client or default_client()
self.client.get_task_stream(start=0, stop=0) # ensure plugin
def __enter__(self):
self.start = time()
return self
def __exit__(self, exc_type, exc_value, traceback):
L = self.client.get_task_stream(
start=self.start, plot=self._plot, filename=self._filename
)
if self._plot:
L, self.figure = L
self.data.extend(L)
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_value, traceback):
L = await self.client.get_task_stream(
start=self.start, plot=self._plot, filename=self._filename
)
if self._plot:
L, self.figure = L
self.data.extend(L)
| get_task_stream |
python | numba__numba | numba/cuda/tests/cudapy/test_matmul.py | {
"start": 324,
"end": 2084
} | class ____(CUDATestCase):
def test_func(self):
@cuda.jit(void(float32[:, ::1], float32[:, ::1], float32[:, ::1]))
def cu_square_matrix_mul(A, B, C):
sA = cuda.shared.array(shape=SM_SIZE, dtype=float32)
sB = cuda.shared.array(shape=(tpb, tpb), dtype=float32)
tx = cuda.threadIdx.x
ty = cuda.threadIdx.y
bx = cuda.blockIdx.x
by = cuda.blockIdx.y
bw = cuda.blockDim.x
bh = cuda.blockDim.y
x = tx + bx * bw
y = ty + by * bh
acc = float32(0) # forces all the math to be f32
for i in range(bpg):
if x < n and y < n:
sA[ty, tx] = A[y, tx + i * tpb]
sB[ty, tx] = B[ty + i * tpb, x]
cuda.syncthreads()
if x < n and y < n:
for j in range(tpb):
acc += sA[ty, j] * sB[j, tx]
cuda.syncthreads()
if x < n and y < n:
C[y, x] = acc
np.random.seed(42)
A = np.array(np.random.random((n, n)), dtype=np.float32)
B = np.array(np.random.random((n, n)), dtype=np.float32)
C = np.empty_like(A)
stream = cuda.stream()
with stream.auto_synchronize():
dA = cuda.to_device(A, stream)
dB = cuda.to_device(B, stream)
dC = cuda.to_device(C, stream)
cu_square_matrix_mul[(bpg, bpg), (tpb, tpb), stream](dA, dB, dC)
dC.copy_to_host(C, stream)
# Host compute
Cans = np.dot(A, B)
# Check result
np.testing.assert_allclose(C, Cans, rtol=1e-5)
if __name__ == '__main__':
unittest.main()
| TestCudaMatMul |
python | python-markdown__markdown | markdown/extensions/footnotes.py | {
"start": 9175,
"end": 12868
} | class ____(BlockProcessor):
""" Find footnote definitions and store for later use. """
RE = re.compile(r'^[ ]{0,3}\[\^([^\]]*)\]:[ ]*(.*)$', re.MULTILINE)
def __init__(self, footnotes: FootnoteExtension):
super().__init__(footnotes.parser)
self.footnotes = footnotes
def test(self, parent: etree.Element, block: str) -> bool:
return True
def run(self, parent: etree.Element, blocks: list[str]) -> bool:
""" Find, set, and remove footnote definitions. """
block = blocks.pop(0)
m = self.RE.search(block)
if m:
id = m.group(1)
fn_blocks = [m.group(2)]
# Handle rest of block
therest = block[m.end():].lstrip('\n')
m2 = self.RE.search(therest)
if m2:
# Another footnote exists in the rest of this block.
# Any content before match is continuation of this footnote, which may be lazily indented.
before = therest[:m2.start()].rstrip('\n')
fn_blocks[0] = '\n'.join([fn_blocks[0], self.detab(before)]).lstrip('\n')
# Add back to blocks everything from beginning of match forward for next iteration.
blocks.insert(0, therest[m2.start():])
else:
# All remaining lines of block are continuation of this footnote, which may be lazily indented.
fn_blocks[0] = '\n'.join([fn_blocks[0], self.detab(therest)]).strip('\n')
# Check for child elements in remaining blocks.
fn_blocks.extend(self.detectTabbed(blocks))
footnote = "\n\n".join(fn_blocks)
self.footnotes.setFootnote(id, footnote.rstrip())
if block[:m.start()].strip():
# Add any content before match back to blocks as separate block
blocks.insert(0, block[:m.start()].rstrip('\n'))
return True
# No match. Restore block.
blocks.insert(0, block)
return False
def detectTabbed(self, blocks: list[str]) -> list[str]:
""" Find indented text and remove indent before further processing.
Returns:
A list of blocks with indentation removed.
"""
fn_blocks = []
while blocks:
if blocks[0].startswith(' '*4):
block = blocks.pop(0)
# Check for new footnotes within this block and split at new footnote.
m = self.RE.search(block)
if m:
# Another footnote exists in this block.
# Any content before match is continuation of this footnote, which may be lazily indented.
before = block[:m.start()].rstrip('\n')
fn_blocks.append(self.detab(before))
# Add back to blocks everything from beginning of match forward for next iteration.
blocks.insert(0, block[m.start():])
# End of this footnote.
break
else:
# Entire block is part of this footnote.
fn_blocks.append(self.detab(block))
else:
# End of this footnote.
break
return fn_blocks
def detab(self, block: str) -> str:
""" Remove one level of indent from a block.
Preserve lazily indented blocks by only removing indent from indented lines.
"""
lines = block.split('\n')
for i, line in enumerate(lines):
if line.startswith(' '*4):
lines[i] = line[4:]
return '\n'.join(lines)
| FootnoteBlockProcessor |
python | run-llama__llama_index | llama-index-integrations/retrievers/llama-index-retrievers-galaxia/llama_index/retrievers/galaxia/base.py | {
"start": 284,
"end": 2880
} | class ____:
def __init__(
self,
api_url: str,
api_key: str,
knowledge_base_id: str,
n_retries: int,
wait_time: int,
):
self.api_url = api_url
self.api_key = api_key
self.knowledge_base_id = knowledge_base_id
self.n_retries = n_retries
self.wait_time = wait_time
self.headers = {"X-Api-Key": api_key, "Content-Type": "application/json"}
def initialize(
self,
conn: http.client.HTTPSConnection,
question: str,
) -> dict:
payload_0 = '{\n "algorithmVersion":"%s",\n' % self.knowledge_base_id
payload_1 = ' "text":"%s" \n}' % question.replace('"', '\\"')
payload = payload_0 + payload_1
conn.request("POST", "/analyze/initialize", payload, self.headers)
res = conn.getresponse()
data = res.read()
return json.loads(data.decode("utf-8"))
def check_status(
self,
conn: http.client.HTTPSConnection,
init_res: dict,
) -> dict:
payload = '{\n "operationId": "%s"\n}' % init_res["operationId"]
conn.request("POST", "/analyze/status", payload, self.headers)
res = conn.getresponse()
data = res.read()
return json.loads(data.decode("utf-8"))
def get_result(self, conn: http.client.HTTPSConnection, init_res: dict) -> dict:
payload = '{\n "operationId": "%s"\n}' % init_res["operationId"]
conn.request("POST", "/analyze/result", payload, self.headers)
res = conn.getresponse()
data = res.read()
return json.loads(data.decode("utf-8"))
def retrieve(
self,
query: str,
) -> Union[dict, None]:
conn = http.client.HTTPSConnection(self.api_url)
flag_init = False
for i in range(self.n_retries):
init_res = self.initialize(conn, query)
if "operationId" in init_res:
flag_init = True
break
time.sleep(self.wait_time * i)
if not flag_init:
# failed to init
return None
flag_proc = False
for i in range(1, self.n_retries + 1):
time.sleep(self.wait_time * i)
status = self.check_status(conn, init_res)
if status["status"] == "processed":
flag_proc = True
break
if flag_proc:
res = self.get_result(conn, init_res)
return res["result"]["resultItems"]
else:
# failed to process
return None
| GalaxiaClient |
python | doocs__leetcode | solution/2400-2499/2412.Minimum Money Required Before Transactions/Solution.py | {
"start": 0,
"end": 323
} | class ____:
def minimumMoney(self, transactions: List[List[int]]) -> int:
s = sum(max(0, a - b) for a, b in transactions)
ans = 0
for a, b in transactions:
if a > b:
ans = max(ans, s + b)
else:
ans = max(ans, s + a)
return ans
| Solution |
python | anthropics__anthropic-sdk-python | src/anthropic/resources/beta/files.py | {
"start": 26117,
"end": 26779
} | class ____:
def __init__(self, files: AsyncFiles) -> None:
self._files = files
self.list = async_to_streamed_response_wrapper(
files.list,
)
self.delete = async_to_streamed_response_wrapper(
files.delete,
)
self.download = async_to_custom_streamed_response_wrapper(
files.download,
AsyncStreamedBinaryAPIResponse,
)
self.retrieve_metadata = async_to_streamed_response_wrapper(
files.retrieve_metadata,
)
self.upload = async_to_streamed_response_wrapper(
files.upload,
)
| AsyncFilesWithStreamingResponse |
python | redis__redis-py | redis/client.py | {
"start": 29864,
"end": 50767
} | class ____:
"""
PubSub provides publish, subscribe and listen support to Redis channels.
After subscribing to one or more channels, the listen() method will block
until a message arrives on one of the subscribed channels. That message
will be returned and it's safe to start listening again.
"""
PUBLISH_MESSAGE_TYPES = ("message", "pmessage", "smessage")
UNSUBSCRIBE_MESSAGE_TYPES = ("unsubscribe", "punsubscribe", "sunsubscribe")
HEALTH_CHECK_MESSAGE = "redis-py-health-check"
def __init__(
self,
connection_pool,
shard_hint=None,
ignore_subscribe_messages: bool = False,
encoder: Optional["Encoder"] = None,
push_handler_func: Union[None, Callable[[str], None]] = None,
event_dispatcher: Optional["EventDispatcher"] = None,
):
self.connection_pool = connection_pool
self.shard_hint = shard_hint
self.ignore_subscribe_messages = ignore_subscribe_messages
self.connection = None
self.subscribed_event = threading.Event()
# we need to know the encoding options for this connection in order
# to lookup channel and pattern names for callback handlers.
self.encoder = encoder
self.push_handler_func = push_handler_func
if event_dispatcher is None:
self._event_dispatcher = EventDispatcher()
else:
self._event_dispatcher = event_dispatcher
self._lock = threading.RLock()
if self.encoder is None:
self.encoder = self.connection_pool.get_encoder()
self.health_check_response_b = self.encoder.encode(self.HEALTH_CHECK_MESSAGE)
if self.encoder.decode_responses:
self.health_check_response = ["pong", self.HEALTH_CHECK_MESSAGE]
else:
self.health_check_response = [b"pong", self.health_check_response_b]
if self.push_handler_func is None:
_set_info_logger()
self.reset()
def __enter__(self) -> "PubSub":
return self
def __exit__(self, exc_type, exc_value, traceback) -> None:
self.reset()
def __del__(self) -> None:
try:
# if this object went out of scope prior to shutting down
# subscriptions, close the connection manually before
# returning it to the connection pool
self.reset()
except Exception:
pass
def reset(self) -> None:
if self.connection:
self.connection.disconnect()
self.connection.deregister_connect_callback(self.on_connect)
self.connection_pool.release(self.connection)
self.connection = None
self.health_check_response_counter = 0
self.channels = {}
self.pending_unsubscribe_channels = set()
self.shard_channels = {}
self.pending_unsubscribe_shard_channels = set()
self.patterns = {}
self.pending_unsubscribe_patterns = set()
self.subscribed_event.clear()
def close(self) -> None:
self.reset()
def on_connect(self, connection) -> None:
"Re-subscribe to any channels and patterns previously subscribed to"
# NOTE: for python3, we can't pass bytestrings as keyword arguments
# so we need to decode channel/pattern names back to unicode strings
# before passing them to [p]subscribe.
self.pending_unsubscribe_channels.clear()
self.pending_unsubscribe_patterns.clear()
self.pending_unsubscribe_shard_channels.clear()
if self.channels:
channels = {
self.encoder.decode(k, force=True): v for k, v in self.channels.items()
}
self.subscribe(**channels)
if self.patterns:
patterns = {
self.encoder.decode(k, force=True): v for k, v in self.patterns.items()
}
self.psubscribe(**patterns)
if self.shard_channels:
shard_channels = {
self.encoder.decode(k, force=True): v
for k, v in self.shard_channels.items()
}
self.ssubscribe(**shard_channels)
@property
def subscribed(self) -> bool:
"""Indicates if there are subscriptions to any channels or patterns"""
return self.subscribed_event.is_set()
def execute_command(self, *args):
"""Execute a publish/subscribe command"""
# NOTE: don't parse the response in this function -- it could pull a
# legitimate message off the stack if the connection is already
# subscribed to one or more channels
if self.connection is None:
self.connection = self.connection_pool.get_connection()
# register a callback that re-subscribes to any channels we
# were listening to when we were disconnected
self.connection.register_connect_callback(self.on_connect)
if self.push_handler_func is not None:
self.connection._parser.set_pubsub_push_handler(self.push_handler_func)
self._event_dispatcher.dispatch(
AfterPubSubConnectionInstantiationEvent(
self.connection, self.connection_pool, ClientType.SYNC, self._lock
)
)
connection = self.connection
kwargs = {"check_health": not self.subscribed}
if not self.subscribed:
self.clean_health_check_responses()
with self._lock:
self._execute(connection, connection.send_command, *args, **kwargs)
def clean_health_check_responses(self) -> None:
"""
If any health check responses are present, clean them
"""
ttl = 10
conn = self.connection
while conn and self.health_check_response_counter > 0 and ttl > 0:
if self._execute(conn, conn.can_read, timeout=conn.socket_timeout):
response = self._execute(conn, conn.read_response)
if self.is_health_check_response(response):
self.health_check_response_counter -= 1
else:
raise PubSubError(
"A non health check response was cleaned by "
"execute_command: {}".format(response)
)
ttl -= 1
def _reconnect(self, conn) -> None:
"""
The supported exceptions are already checked in the
retry object so we don't need to do it here.
In this error handler we are trying to reconnect to the server.
"""
conn.disconnect()
conn.connect()
def _execute(self, conn, command, *args, **kwargs):
"""
Connect manually upon disconnection. If the Redis server is down,
this will fail and raise a ConnectionError as desired.
After reconnection, the ``on_connect`` callback should have been
called by the # connection to resubscribe us to any channels and
patterns we were previously listening to
"""
if conn.should_reconnect():
self._reconnect(conn)
response = conn.retry.call_with_retry(
lambda: command(*args, **kwargs),
lambda _: self._reconnect(conn),
)
return response
def parse_response(self, block=True, timeout=0):
"""Parse the response from a publish/subscribe command"""
conn = self.connection
if conn is None:
raise RuntimeError(
"pubsub connection not set: "
"did you forget to call subscribe() or psubscribe()?"
)
self.check_health()
def try_read():
if not block:
if not conn.can_read(timeout=timeout):
return None
else:
conn.connect()
return conn.read_response(disconnect_on_error=False, push_request=True)
response = self._execute(conn, try_read)
if self.is_health_check_response(response):
# ignore the health check message as user might not expect it
self.health_check_response_counter -= 1
return None
return response
def is_health_check_response(self, response) -> bool:
"""
Check if the response is a health check response.
If there are no subscriptions redis responds to PING command with a
bulk response, instead of a multi-bulk with "pong" and the response.
"""
return response in [
self.health_check_response, # If there was a subscription
self.health_check_response_b, # If there wasn't
]
def check_health(self) -> None:
conn = self.connection
if conn is None:
raise RuntimeError(
"pubsub connection not set: "
"did you forget to call subscribe() or psubscribe()?"
)
if conn.health_check_interval and time.monotonic() > conn.next_health_check:
conn.send_command("PING", self.HEALTH_CHECK_MESSAGE, check_health=False)
self.health_check_response_counter += 1
def _normalize_keys(self, data) -> Dict:
"""
normalize channel/pattern names to be either bytes or strings
based on whether responses are automatically decoded. this saves us
from coercing the value for each message coming in.
"""
encode = self.encoder.encode
decode = self.encoder.decode
return {decode(encode(k)): v for k, v in data.items()}
def psubscribe(self, *args, **kwargs):
"""
Subscribe to channel patterns. Patterns supplied as keyword arguments
expect a pattern name as the key and a callable as the value. A
pattern's callable will be invoked automatically when a message is
received on that pattern rather than producing a message via
``listen()``.
"""
if args:
args = list_or_args(args[0], args[1:])
new_patterns = dict.fromkeys(args)
new_patterns.update(kwargs)
ret_val = self.execute_command("PSUBSCRIBE", *new_patterns.keys())
# update the patterns dict AFTER we send the command. we don't want to
# subscribe twice to these patterns, once for the command and again
# for the reconnection.
new_patterns = self._normalize_keys(new_patterns)
self.patterns.update(new_patterns)
if not self.subscribed:
# Set the subscribed_event flag to True
self.subscribed_event.set()
# Clear the health check counter
self.health_check_response_counter = 0
self.pending_unsubscribe_patterns.difference_update(new_patterns)
return ret_val
def punsubscribe(self, *args):
"""
Unsubscribe from the supplied patterns. If empty, unsubscribe from
all patterns.
"""
if args:
args = list_or_args(args[0], args[1:])
patterns = self._normalize_keys(dict.fromkeys(args))
else:
patterns = self.patterns
self.pending_unsubscribe_patterns.update(patterns)
return self.execute_command("PUNSUBSCRIBE", *args)
def subscribe(self, *args, **kwargs):
"""
Subscribe to channels. Channels supplied as keyword arguments expect
a channel name as the key and a callable as the value. A channel's
callable will be invoked automatically when a message is received on
that channel rather than producing a message via ``listen()`` or
``get_message()``.
"""
if args:
args = list_or_args(args[0], args[1:])
new_channels = dict.fromkeys(args)
new_channels.update(kwargs)
ret_val = self.execute_command("SUBSCRIBE", *new_channels.keys())
# update the channels dict AFTER we send the command. we don't want to
# subscribe twice to these channels, once for the command and again
# for the reconnection.
new_channels = self._normalize_keys(new_channels)
self.channels.update(new_channels)
if not self.subscribed:
# Set the subscribed_event flag to True
self.subscribed_event.set()
# Clear the health check counter
self.health_check_response_counter = 0
self.pending_unsubscribe_channels.difference_update(new_channels)
return ret_val
def unsubscribe(self, *args):
"""
Unsubscribe from the supplied channels. If empty, unsubscribe from
all channels
"""
if args:
args = list_or_args(args[0], args[1:])
channels = self._normalize_keys(dict.fromkeys(args))
else:
channels = self.channels
self.pending_unsubscribe_channels.update(channels)
return self.execute_command("UNSUBSCRIBE", *args)
def ssubscribe(self, *args, target_node=None, **kwargs):
"""
Subscribes the client to the specified shard channels.
Channels supplied as keyword arguments expect a channel name as the key
and a callable as the value. A channel's callable will be invoked automatically
when a message is received on that channel rather than producing a message via
``listen()`` or ``get_sharded_message()``.
"""
if args:
args = list_or_args(args[0], args[1:])
new_s_channels = dict.fromkeys(args)
new_s_channels.update(kwargs)
ret_val = self.execute_command("SSUBSCRIBE", *new_s_channels.keys())
# update the s_channels dict AFTER we send the command. we don't want to
# subscribe twice to these channels, once for the command and again
# for the reconnection.
new_s_channels = self._normalize_keys(new_s_channels)
self.shard_channels.update(new_s_channels)
if not self.subscribed:
# Set the subscribed_event flag to True
self.subscribed_event.set()
# Clear the health check counter
self.health_check_response_counter = 0
self.pending_unsubscribe_shard_channels.difference_update(new_s_channels)
return ret_val
def sunsubscribe(self, *args, target_node=None):
"""
Unsubscribe from the supplied shard_channels. If empty, unsubscribe from
all shard_channels
"""
if args:
args = list_or_args(args[0], args[1:])
s_channels = self._normalize_keys(dict.fromkeys(args))
else:
s_channels = self.shard_channels
self.pending_unsubscribe_shard_channels.update(s_channels)
return self.execute_command("SUNSUBSCRIBE", *args)
def listen(self):
"Listen for messages on channels this client has been subscribed to"
while self.subscribed:
response = self.handle_message(self.parse_response(block=True))
if response is not None:
yield response
def get_message(
self, ignore_subscribe_messages: bool = False, timeout: float = 0.0
):
"""
Get the next message if one is available, otherwise None.
If timeout is specified, the system will wait for `timeout` seconds
before returning. Timeout should be specified as a floating point
number, or None, to wait indefinitely.
"""
if not self.subscribed:
# Wait for subscription
start_time = time.monotonic()
if self.subscribed_event.wait(timeout) is True:
# The connection was subscribed during the timeout time frame.
# The timeout should be adjusted based on the time spent
# waiting for the subscription
time_spent = time.monotonic() - start_time
timeout = max(0.0, timeout - time_spent)
else:
# The connection isn't subscribed to any channels or patterns,
# so no messages are available
return None
response = self.parse_response(block=(timeout is None), timeout=timeout)
if response:
return self.handle_message(response, ignore_subscribe_messages)
return None
get_sharded_message = get_message
def ping(self, message: Union[str, None] = None) -> bool:
"""
Ping the Redis server to test connectivity.
Sends a PING command to the Redis server and returns True if the server
responds with "PONG".
"""
args = ["PING", message] if message is not None else ["PING"]
return self.execute_command(*args)
def handle_message(self, response, ignore_subscribe_messages=False):
"""
Parses a pub/sub message. If the channel or pattern was subscribed to
with a message handler, the handler is invoked instead of a parsed
message being returned.
"""
if response is None:
return None
if isinstance(response, bytes):
response = [b"pong", response] if response != b"PONG" else [b"pong", b""]
message_type = str_if_bytes(response[0])
if message_type == "pmessage":
message = {
"type": message_type,
"pattern": response[1],
"channel": response[2],
"data": response[3],
}
elif message_type == "pong":
message = {
"type": message_type,
"pattern": None,
"channel": None,
"data": response[1],
}
else:
message = {
"type": message_type,
"pattern": None,
"channel": response[1],
"data": response[2],
}
# if this is an unsubscribe message, remove it from memory
if message_type in self.UNSUBSCRIBE_MESSAGE_TYPES:
if message_type == "punsubscribe":
pattern = response[1]
if pattern in self.pending_unsubscribe_patterns:
self.pending_unsubscribe_patterns.remove(pattern)
self.patterns.pop(pattern, None)
elif message_type == "sunsubscribe":
s_channel = response[1]
if s_channel in self.pending_unsubscribe_shard_channels:
self.pending_unsubscribe_shard_channels.remove(s_channel)
self.shard_channels.pop(s_channel, None)
else:
channel = response[1]
if channel in self.pending_unsubscribe_channels:
self.pending_unsubscribe_channels.remove(channel)
self.channels.pop(channel, None)
if not self.channels and not self.patterns and not self.shard_channels:
# There are no subscriptions anymore, set subscribed_event flag
# to false
self.subscribed_event.clear()
if message_type in self.PUBLISH_MESSAGE_TYPES:
# if there's a message handler, invoke it
if message_type == "pmessage":
handler = self.patterns.get(message["pattern"], None)
elif message_type == "smessage":
handler = self.shard_channels.get(message["channel"], None)
else:
handler = self.channels.get(message["channel"], None)
if handler:
handler(message)
return None
elif message_type != "pong":
# this is a subscribe/unsubscribe message. ignore if we don't
# want them
if ignore_subscribe_messages or self.ignore_subscribe_messages:
return None
return message
def run_in_thread(
self,
sleep_time: float = 0.0,
daemon: bool = False,
exception_handler: Optional[Callable] = None,
pubsub=None,
sharded_pubsub: bool = False,
) -> "PubSubWorkerThread":
for channel, handler in self.channels.items():
if handler is None:
raise PubSubError(f"Channel: '{channel}' has no handler registered")
for pattern, handler in self.patterns.items():
if handler is None:
raise PubSubError(f"Pattern: '{pattern}' has no handler registered")
for s_channel, handler in self.shard_channels.items():
if handler is None:
raise PubSubError(
f"Shard Channel: '{s_channel}' has no handler registered"
)
pubsub = self if pubsub is None else pubsub
thread = PubSubWorkerThread(
pubsub,
sleep_time,
daemon=daemon,
exception_handler=exception_handler,
sharded_pubsub=sharded_pubsub,
)
thread.start()
return thread
| PubSub |
python | scrapy__scrapy | scrapy/dupefilters.py | {
"start": 1318,
"end": 4161
} | class ____(BaseDupeFilter):
"""Duplicate request filtering class (:setting:`DUPEFILTER_CLASS`) that
filters out requests with the canonical
(:func:`w3lib.url.canonicalize_url`) :attr:`~scrapy.http.Request.url`,
:attr:`~scrapy.http.Request.method` and :attr:`~scrapy.http.Request.body`.
"""
def __init__(
self,
path: str | None = None,
debug: bool = False,
*,
fingerprinter: RequestFingerprinterProtocol | None = None,
) -> None:
self.file = None
self.fingerprinter: RequestFingerprinterProtocol = (
fingerprinter or RequestFingerprinter()
)
self.fingerprints: set[str] = set()
self.logdupes = True
self.debug = debug
self.logger = logging.getLogger(__name__)
if path:
# line-by-line writing, see: https://github.com/scrapy/scrapy/issues/6019
self.file = Path(path, "requests.seen").open(
"a+", buffering=1, encoding="utf-8"
)
self.file.reconfigure(write_through=True)
self.file.seek(0)
self.fingerprints.update(x.rstrip() for x in self.file)
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
assert crawler.request_fingerprinter
debug = crawler.settings.getbool("DUPEFILTER_DEBUG")
return cls(
job_dir(crawler.settings),
debug,
fingerprinter=crawler.request_fingerprinter,
)
def request_seen(self, request: Request) -> bool:
fp = self.request_fingerprint(request)
if fp in self.fingerprints:
return True
self.fingerprints.add(fp)
if self.file:
self.file.write(fp + "\n")
return False
def request_fingerprint(self, request: Request) -> str:
"""Returns a string that uniquely identifies the specified request."""
return self.fingerprinter.fingerprint(request).hex()
def close(self, reason: str) -> None:
if self.file:
self.file.close()
def log(self, request: Request, spider: Spider) -> None:
if self.debug:
msg = "Filtered duplicate request: %(request)s (referer: %(referer)s)"
args = {"request": request, "referer": referer_str(request)}
self.logger.debug(msg, args, extra={"spider": spider})
elif self.logdupes:
msg = (
"Filtered duplicate request: %(request)s"
" - no more duplicates will be shown"
" (see DUPEFILTER_DEBUG to show all duplicates)"
)
self.logger.debug(msg, {"request": request}, extra={"spider": spider})
self.logdupes = False
assert spider.crawler.stats
spider.crawler.stats.inc_value("dupefilter/filtered")
| RFPDupeFilter |
python | realpython__materials | flask-connexion-rest-part-2/rp_flask_api/models.py | {
"start": 354,
"end": 574
} | class ____(ma.SQLAlchemyAutoSchema):
class Meta:
model = Person
load_instance = True
sqla_session = db.session
person_schema = PersonSchema()
people_schema = PersonSchema(many=True)
| PersonSchema |
python | wandb__wandb | wandb/sdk/launch/agent/config.py | {
"start": 734,
"end": 856
} | class ____(str, Enum):
"""Enum of valid registry types."""
ecr = "ecr"
acr = "acr"
gcr = "gcr"
| RegistryType |
python | huggingface__transformers | tests/models/swiftformer/test_modeling_swiftformer.py | {
"start": 1391,
"end": 4370
} | class ____:
def __init__(
self,
parent,
batch_size=13,
num_channels=3,
is_training=True,
use_labels=True,
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
image_size=224,
num_labels=3,
layer_depths=[1, 1, 1, 1],
embed_dims=[16, 16, 32, 32],
):
self.parent = parent
self.batch_size = batch_size
self.num_channels = num_channels
self.is_training = is_training
self.use_labels = use_labels
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.num_labels = num_labels
self.image_size = image_size
self.layer_depths = layer_depths
self.embed_dims = embed_dims
def prepare_config_and_inputs(self):
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
labels = None
if self.use_labels:
labels = ids_tensor([self.batch_size], self.num_labels)
config = self.get_config()
return config, pixel_values, labels
def get_config(self):
return SwiftFormerConfig(
depths=self.layer_depths,
embed_dims=self.embed_dims,
mlp_ratio=4,
downsamples=[True, True, True, True],
hidden_act="gelu",
num_labels=self.num_labels,
down_patch_size=3,
down_stride=2,
down_pad=1,
drop_rate=0.0,
drop_path_rate=0.0,
use_layer_scale=True,
layer_scale_init_value=1e-5,
)
def create_and_check_model(self, config, pixel_values, labels):
model = SwiftFormerModel(config=config)
model.to(torch_device)
model.eval()
result = model(pixel_values)
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.embed_dims[-1], 7, 7))
def create_and_check_for_image_classification(self, config, pixel_values, labels):
config.num_labels = self.num_labels
model = SwiftFormerForImageClassification(config)
model.to(torch_device)
model.eval()
result = model(pixel_values, labels=labels)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
model = SwiftFormerForImageClassification(config)
model.to(torch_device)
model.eval()
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
result = model(pixel_values)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
def prepare_config_and_inputs_for_common(self):
(config, pixel_values, labels) = self.prepare_config_and_inputs()
inputs_dict = {"pixel_values": pixel_values}
return config, inputs_dict
@require_torch
| SwiftFormerModelTester |
python | scipy__scipy | benchmarks/benchmarks/optimize.py | {
"start": 15428,
"end": 16991
} | class ____(Benchmark):
"""Class for benchmarking nonlinear least squares solvers."""
problems = extract_lsq_problems()
params = [
list(problems.keys()),
["average time", "nfev", "success"]
]
param_names = [
"problem", "result type"
]
def track_all(self, problem_name, result_type):
problem = self.problems[problem_name]
if problem.lb is not None or problem.ub is not None:
raise NotImplementedError
ftol = 1e-5
if result_type == 'average time':
n_runs = 10
t0 = time.time()
for _ in range(n_runs):
leastsq(problem.fun, problem.x0, Dfun=problem.jac, ftol=ftol,
full_output=True)
return (time.time() - t0) / n_runs
x, cov_x, info, message, ier = leastsq(
problem.fun, problem.x0, Dfun=problem.jac,
ftol=ftol, full_output=True
)
if result_type == 'nfev':
return info['nfev']
elif result_type == 'success':
return int(problem.check_answer(x, ftol))
else:
raise NotImplementedError
# `export SCIPY_XSLOW=1` to enable BenchGlobal.track_all
# `export SCIPY_GLOBAL_BENCH=AMGM,Adjiman,...` to run specific tests
# `export SCIPY_GLOBAL_BENCH_NUMTRIALS=10` to specify n_iterations, default 100
#
# then run `spin bench -s optimize.BenchGlobal`
# Note that it can take several hours to run; intermediate output
# can be found under benchmarks/global-bench-results.json
| BenchLeastSquares |
python | lepture__authlib | authlib/common/errors.py | {
"start": 743,
"end": 1615
} | class ____(AuthlibBaseError):
#: HTTP status code
status_code = 400
def __init__(self, error=None, description=None, uri=None, status_code=None):
super().__init__(error, description, uri)
if status_code is not None:
self.status_code = status_code
def get_error_description(self):
return self.description
def get_body(self):
error = [("error", self.error)]
if self.description:
error.append(("error_description", self.description))
if self.uri:
error.append(("error_uri", self.uri))
return error
def get_headers(self):
return default_json_headers[:]
def __call__(self, uri=None):
self.uri = uri
body = dict(self.get_body())
headers = self.get_headers()
return self.status_code, body, headers
| AuthlibHTTPError |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/conv_ops_test.py | {
"start": 136135,
"end": 145807
} | class ____(test.TestCase):
def _CreateNumpyTensor(self, shape):
total_size = np.prod(shape)
return np.arange(1, total_size + 1, dtype=np.float32).reshape(shape)
def _CreateConv2D(self,
input_values,
filters,
strides=[1, 1],
padding="SAME"):
return nn_ops.convolution(
input_values, filters, strides=strides, padding=padding)
# Tests tensor forwarding of a fused Conv2D+BiasAdd+Add op when the input to
# Add has refcount 1.
@test_util.run_in_graph_and_eager_modes(use_gpu=False)
def testAddWithRefCountOne(self):
expected_output = [
113377, 125570, 77305, 86738, 19433, 22226, 60681, 70722, 36291, 43718,
7143, 9206, 9785, 12098, 4783, 6366, 779, 1134
]
tensor_in_sizes = [1, 3, 3, 2]
filter_in_sizes = [2, 2, 2, 2]
bias_in_sizes = [2]
x = self._CreateNumpyTensor(tensor_in_sizes)
filter_in = self._CreateNumpyTensor(filter_in_sizes)
bias_in = self._CreateNumpyTensor(bias_in_sizes)
# To get different weights for filter
offset = 1
conv1 = self._CreateConv2D(x, filter_in)
conv2 = self._CreateConv2D(conv1, filter_in + offset)
conv = self._CreateConv2D(conv1, filter_in - offset)
bias_add = nn_ops.bias_add(conv, bias_in)
add = math_ops.add_n([bias_add, conv2])
self.assertAllEqual(
np.rint(expected_output),
self.evaluate(add).reshape(-1))
# Tests tensor forwarding of a fused Conv2D+BiasAdd+Add op when the input to
# Add has a total refcount of 2, and Add is its last consumer.
@test_util.run_in_graph_and_eager_modes(use_gpu=False)
def testAddWithRefCountTwoAndRunAddLast(self):
expected_output = [
1.907175e+06, 2.253505e+06, 7.809210e+05, 9.537180e+05, 1.184170e+05,
1.523070e+05, 5.367010e+05, 6.803700e+05, 1.867090e+05, 2.529460e+05,
2.362300e+04, 3.522600e+04, 5.121700e+04, 7.168300e+04, 1.494300e+04,
2.347400e+04, 1.558000e+03, 2.903000e+03
]
tensor_in_sizes = [1, 3, 3, 2]
filter_in_sizes = [2, 2, 2, 2]
bias_in_sizes = [2]
x = self._CreateNumpyTensor(tensor_in_sizes)
filter_in = self._CreateNumpyTensor(filter_in_sizes)
bias_in = self._CreateNumpyTensor(bias_in_sizes)
# To get different weights for filter
offset = 1
conv1 = self._CreateConv2D(x, filter_in)
conv2 = self._CreateConv2D(conv1, filter_in + offset)
conv = self._CreateConv2D(conv2, filter_in - offset)
bias_add = nn_ops.bias_add(conv, bias_in)
add = math_ops.add_n([bias_add, conv1])
self.assertAllEqual(
np.rint(expected_output),
self.evaluate(add).reshape(-1))
# Tests tensor forwarding of a fused Conv2D+BiasAdd+Add op when the input to
# Add has refcount 2 and Add (in the fused Conv2D op) is its first consumer.
@test_util.run_in_graph_and_eager_modes(use_gpu=False)
def testAddWithRefCountTwoAndRunAddFirst(self):
expected_output = [
176161, 194450, 120673, 134822, 30545, 34734, 96041, 111102, 58149,
69289, 11745, 14839, 15833, 19302, 7965, 10339, 1345, 1877
]
tensor_in_sizes = [1, 3, 3, 2]
filter_in_sizes = [2, 2, 2, 2]
bias_in_sizes = [2]
x = self._CreateNumpyTensor(tensor_in_sizes)
filter_in = self._CreateNumpyTensor(filter_in_sizes)
bias_in = self._CreateNumpyTensor(bias_in_sizes)
# To get different weights for filter
offset = 1
conv1 = self._CreateConv2D(x, filter_in)
conv2 = self._CreateConv2D(conv1, filter_in + offset)
conv = self._CreateConv2D(conv1, filter_in - offset)
bias_add = nn_ops.bias_add(conv, bias_in)
add = math_ops.add_n([bias_add, conv2])
relu = nn_ops.relu(add)
output = math_ops.add_n([relu, conv2])
self.assertAllEqual(
np.rint(expected_output),
self.evaluate(output).reshape(-1))
# Tests tensor forwarding of a fused Conv2D+BiasAdd+Add op when the input to
# Add has refcount 2, and there is no dependency between its two consumers.
@test_util.run_in_graph_and_eager_modes(use_gpu=False)
def testAddWithRefCountTwoAndNoDependence(self):
expected_output = [
176161, 194450, 120673, 134822, 30545, 34734, 96041, 111102, 58149,
69289, 11745, 14839, 15833, 19302, 7965, 10339, 1345, 1877
]
tensor_in_sizes = [1, 3, 3, 2]
filter_in_sizes = [2, 2, 2, 2]
bias_in_sizes = [2]
x = self._CreateNumpyTensor(tensor_in_sizes)
filter_in = self._CreateNumpyTensor(filter_in_sizes)
bias_in = self._CreateNumpyTensor(bias_in_sizes)
# To get different weights for filter
offset = 1
conv1 = self._CreateConv2D(x, filter_in)
conv2 = self._CreateConv2D(conv1, filter_in + offset)
conv = self._CreateConv2D(conv1, filter_in - offset)
bias_add = nn_ops.bias_add(conv, bias_in)
add = math_ops.add_n([bias_add, conv2])
relu1 = nn_ops.relu(add)
relu2 = nn_ops.relu(conv2)
output = math_ops.add_n([relu1, relu2])
self.assertAllEqual(
np.rint(expected_output),
self.evaluate(output).reshape(-1))
# Tests tensor forwarding of a fused Conv2D+BiasAdd+Add op when the input to
# Add is the same as the input to the fused Conv2D op and needs a tensor
# buffer.
@test_util.run_in_graph_and_eager_modes(use_gpu=False)
def testAddWithSameSrcAndAddTensorBuffer(self):
expected_output = [
57157, 63298, 39249, 44026, 9971, 11402, 31193, 36306, 19126, 22948,
3970, 5060, 5135, 6350, 2666, 3524, 461, 674
]
tensor_in_sizes = [1, 3, 3, 2]
filter_in_sizes = [2, 2, 2, 2]
bias_in_sizes = [2]
x = self._CreateNumpyTensor(tensor_in_sizes)
filter_in = self._CreateNumpyTensor(filter_in_sizes)
bias_in = self._CreateNumpyTensor(bias_in_sizes)
conv1 = self._CreateConv2D(x, filter_in)
conv = self._CreateConv2D(conv1, filter_in)
bias_add = nn_ops.bias_add(conv, bias_in)
add = math_ops.add_n([bias_add, conv1])
self.assertAllEqual(
np.rint(expected_output),
self.evaluate(add).reshape(-1))
# Fused resize and pad conv.
@test_util.run_in_graph_and_eager_modes()
def testResizeAndPadLargeResize(self):
with self.assertRaisesRegex((ValueError, errors_impl.InvalidArgumentError),
"Encountered overflow"):
mode = "REFLECT"
strides = [1, 1, 1, 1]
padding = "SAME"
resize_align_corners = False
tensor = constant_op.constant(
147, shape=[3, 3, 1, 4], dtype=dtypes.float32)
size = constant_op.constant([1879048192, 1879048192], dtype=dtypes.int32)
paddings = constant_op.constant([[0, 0], [0, 0], [0, 0], [0, 0]],
dtype=dtypes.int32)
kernel = constant_op.constant(
123, shape=[1, 3, 4, 1], dtype=dtypes.float32)
self.evaluate(
gen_nn_ops.fused_resize_and_pad_conv2d(
input=tensor,
size=size,
paddings=paddings,
filter=kernel,
mode=mode,
strides=strides,
padding=padding,
resize_align_corners=resize_align_corners))
if __name__ == "__main__":
for index, (input_size_, filter_size_, output_size_, stride_,
padding_) in enumerate(GetShrunkInceptionShapes()):
setattr(Conv2DTest, "testInceptionFwd_" + str(index),
test_util.run_in_graph_and_eager_modes(
GetInceptionFwdTest(input_size_, filter_size_, stride_,
padding_)))
setattr(
Conv2DTest, "testInceptionFwdDilatedConv_" + str(index),
test_util.run_in_graph_and_eager_modes(GetInceptionFwdDilatedConvTest(
input_size_, filter_size_, stride_, padding_)))
setattr(Conv2DTest, "testInceptionBackInput_" + str(index),
test_util.run_in_graph_and_eager_modes(
GetInceptionBackInputTest(input_size_, filter_size_,
output_size_, stride_, padding_)))
setattr(Conv2DTest, "testInceptionBackFilter_" + str(index),
test_util.run_in_graph_and_eager_modes(
GetInceptionBackFilterTest(input_size_, filter_size_,
output_size_, [stride_, stride_],
padding_)))
# TODO(b/35359731)
# Fwd, BckInput, and BackFilter to test that for certain input parameter
# set, winograd nonfused algorithm will be excluded from conv autotune. If
# in such case, winograd nonfused algorithm is added as one option of the
# conv autotune, and cuDNN version is smaller than 7, the following tests
# will fail.
ishape = [1, 400, 400, 1]
fshape = [1, 1, 1, 256]
oshape = [1, 400, 400, 256]
setattr(Conv2DTest, "testInceptionFwd_No_Winograd_Nonfused",
test_util.run_in_graph_and_eager_modes(
GetInceptionFwdTest(ishape, fshape, 1, "SAME", gpu_only=True)))
setattr(Conv2DTest, "testInceptionFwdDilatedConv_No_Winograd_Nonfused",
test_util.run_in_graph_and_eager_modes(
GetInceptionFwdDilatedConvTest(ishape, fshape, 1, "SAME")))
setattr(Conv2DTest, "testInceptionBackInput_No_Winograd_Nonfused",
test_util.run_in_graph_and_eager_modes(
GetInceptionBackInputTest(ishape, fshape, oshape, 1, "SAME",
gpu_only=True)))
setattr(Conv2DTest, "testInceptionBackFilter_No_Winograd_Nonfused",
test_util.run_in_graph_and_eager_modes(
GetInceptionBackFilterTest(ishape, fshape, oshape, [1, 1], "SAME",
gpu_only=True)))
test.main()
| FusedConv2DTest |
python | huggingface__transformers | src/transformers/models/idefics2/image_processing_idefics2.py | {
"start": 5266,
"end": 26717
} | class ____(BaseImageProcessor):
r"""
Constructs a Idefics image processor.
Args:
do_convert_rgb (`bool`, *optional*, defaults to `True`):
Whether to convert the image to RGB. This is useful if the input image is of a different format e.g. RGBA.
Only has an effect if the input image is in the PIL format.
do_resize (`bool`, *optional*, defaults to `True`):
Whether to resize the image. The longest edge of the image is resized to be <= `size["longest_edge"]`, with the
shortest edge resized to keep the input aspect ratio, with a minimum size of `size["shortest_edge"]`.
size (`Dict`, *optional*):
Controls the size of the output image. This is a dictionary containing the keys "shortest_edge" and "longest_edge".
resample (`Resampling`, *optional*, defaults to `Resampling.BILINEAR`):
Resampling filter to use when resizing the image.
do_rescale (`bool`, *optional*, defaults to `True`):
Whether to rescale the image. If set to `True`, the image is rescaled to have pixel values between 0 and 1.
rescale_factor (`float`, *optional*, defaults to `1/255`):
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
do_normalize (`bool`, *optional*, defaults to `True`):
Whether to normalize the image. If set to `True`, the image is normalized to have a mean of `image_mean` and
a standard deviation of `image_std`.
image_mean (`float` or `list[float]`, *optional*, defaults to `IDEFICS_STANDARD_MEAN`):
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be
overridden by the `image_mean` parameter in the `preprocess` method.
image_std (`float` or `list[float]`, *optional*, defaults to `IDEFICS_STANDARD_STD`):
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
Can be overridden by the `image_std` parameter in the `preprocess` method.
do_pad (`bool`, *optional*, defaults to `True`):
Whether or not to pad the images to the largest height and width in the batch and number of images per
sample in the batch, such that the returned tensor is of shape (batch_size, max_num_images, num_channels, max_height, max_width).
do_image_splitting (`bool`, *optional*, defaults to `False`):
Whether to split the image into a sequence 4 equal sub-images concatenated with the original image. That
strategy was first introduced in https://huggingface.co/papers/2311.06607.
"""
model_input_names = ["pixel_values", "pixel_attention_mask"]
valid_kwargs = Idefics2ImageProcessorKwargs
def __init__(
self,
do_convert_rgb: bool = True,
do_resize: bool = True,
size: Optional[dict[str, int]] = None,
resample: PILImageResampling = PILImageResampling.BILINEAR,
do_rescale: bool = True,
rescale_factor: float = 1 / 255,
do_normalize: bool = True,
image_mean: Optional[Union[float, list[float]]] = None,
image_std: Optional[Union[float, list[float]]] = None,
do_pad: bool = True,
do_image_splitting: bool = False,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.do_convert_rgb = do_convert_rgb
self.do_resize = do_resize
self.size = size if size is not None else {"shortest_edge": 378, "longest_edge": 980}
self.resample = resample
self.do_rescale = do_rescale
self.rescale_factor = rescale_factor
self.do_normalize = do_normalize
self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
self.do_pad = do_pad
self.do_image_splitting = do_image_splitting
def resize(
self,
image: np.ndarray,
size: dict[str, int],
resample: PILImageResampling = PILImageResampling.BILINEAR,
data_format: Optional[Union[str, ChannelDimension]] = None,
input_data_format: Optional[Union[str, ChannelDimension]] = None,
**kwargs,
) -> np.ndarray:
"""
Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge
resized to keep the input aspect ratio.
Args:
image (`np.ndarray`):
Image to resize.
size (`dict[str, int]`):
Size of the output image.
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
Resampling filter to use when resiizing the image.
data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format of the image. If not provided, it will be the same as the input image.
input_data_format (`ChannelDimension` or `str`, *optional*):
The channel dimension format of the input image. If not provided, it will be inferred.
"""
if "shortest_edge" in size and "longest_edge" in size:
size = get_resize_output_image_size(image, size, input_data_format)
elif "height" in size and "width" in size:
size = (size["height"], size["width"])
else:
raise ValueError(
"size must be a dictionary with keys 'shortest_edge' and 'longest_edge' or 'height' and 'width'."
)
return resize(
image, size, resample=resample, data_format=data_format, input_data_format=input_data_format, **kwargs
)
# Copied from transformers.models.vilt.image_processing_vilt.ViltImageProcessor._pad_image
def _pad_image(
self,
image: np.ndarray,
output_size: tuple[int, int],
constant_values: Union[float, Iterable[float]] = 0,
data_format: Optional[ChannelDimension] = None,
input_data_format: Optional[Union[str, ChannelDimension]] = None,
) -> np.ndarray:
"""
Pad an image with zeros to the given size.
"""
input_height, input_width = get_image_size(image, channel_dim=input_data_format)
output_height, output_width = output_size
pad_bottom = output_height - input_height
pad_right = output_width - input_width
padding = ((0, pad_bottom), (0, pad_right))
padded_image = pad(
image,
padding,
mode=PaddingMode.CONSTANT,
constant_values=constant_values,
data_format=data_format,
input_data_format=input_data_format,
)
return padded_image
def pad(
self,
images: list[np.ndarray],
constant_values: Union[float, Iterable[float]] = 0,
return_pixel_mask: bool = True,
return_tensors: Optional[Union[str, TensorType]] = None,
data_format: Optional[ChannelDimension] = None,
input_data_format: Optional[Union[str, ChannelDimension]] = None,
) -> BatchFeature:
"""
For a list of images, for each images, pads a batch of images to the bottom and right of the image with zeros to the size of largest height and width.
For each sample in the batch, pads the sample with empty images to the max_number of images per sample in the batch. Optionally returns a pixel mask.
Args:
images (`np.ndarray`):
List of list of images to pad. Pads to the largest height and width in the batch.
constant_values (`float` or `Iterable[float]`, *optional*):
The value to use for the padding if `mode` is `"constant"`.
return_pixel_mask (`bool`, *optional*, defaults to `True`):
Whether to return a pixel mask.
return_tensors (`str` or `TensorType`, *optional*):
The type of tensors to return. Can be one of:
- Unset: Return a list of `np.ndarray`.
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format of the image. If not provided, it will be the same as the input image.
input_data_format (`ChannelDimension` or `str`, *optional*):
The channel dimension format of the input image. If not provided, it will be inferred.
"""
pad_size = get_max_height_width(images, input_data_format=input_data_format)
batch_size = len(images)
max_num_images = max(len(images_) for images_ in images)
input_data_format = (
infer_channel_dimension_format(images[0][0]) if input_data_format is None else input_data_format
)
data_format = input_data_format if data_format is None else data_format
def empty_image(size, input_data_format):
if input_data_format == ChannelDimension.FIRST:
return np.zeros((3, *size), dtype=np.uint8)
elif input_data_format == ChannelDimension.LAST:
return np.zeros((*size, 3), dtype=np.uint8)
raise ValueError("Invalid channel dimension format.")
padded_images_list = [
[empty_image(pad_size, data_format) for _ in range(max_num_images)] for _ in range(batch_size)
]
padded_masks = [[np.zeros(pad_size) for _ in range(max_num_images)] for _ in range(batch_size)]
for batch_idx in range(batch_size):
for sample_idx, image in enumerate(images[batch_idx]):
padded_images_list[batch_idx][sample_idx] = self._pad_image(
image,
pad_size,
constant_values=constant_values,
data_format=data_format,
input_data_format=input_data_format,
)
padded_masks[batch_idx][sample_idx] = make_pixel_mask(
image, output_size=pad_size, input_data_format=input_data_format
)
padded_masks = padded_masks if return_pixel_mask else None
return padded_images_list, padded_masks
def _crop(
self,
im: np.ndarray,
w1: int,
h1: int,
w2: int,
h2: int,
input_data_format: Optional[Union[str, ChannelDimension]] = None,
) -> np.ndarray:
if input_data_format == ChannelDimension.FIRST:
return im[:, h1:h2, w1:w2]
elif input_data_format == ChannelDimension.LAST:
return im[h1:h2, w1:w2, :]
def split_image(
self,
image: np.ndarray,
input_data_format: Optional[Union[str, ChannelDimension]] = None,
):
"""
Split an image into 4 equal sub-images, and the concatenate that sequence with the original image.
That means that a single image becomes a sequence of 5 images.
This is a "trick" to spend more compute on each image with no changes in the vision encoder.
Args:
image (`np.ndarray`):
Images to split.
input_data_format (`ChannelDimension` or `str`, *optional*):
The channel dimension format of the input image. If not provided, it will be inferred.
"""
height, width = get_image_size(image, input_data_format)
mid_width = width // 2
mid_height = height // 2
return [
self._crop(image, 0, 0, mid_width, mid_height, input_data_format),
self._crop(image, mid_width, 0, width, mid_height, input_data_format),
self._crop(image, 0, mid_height, mid_width, height, input_data_format),
self._crop(image, mid_width, mid_height, width, height, input_data_format),
image,
]
def preprocess(
self,
images: ImageInput,
do_convert_rgb: Optional[bool] = None,
do_resize: Optional[bool] = None,
size: Optional[dict[str, int]] = None,
resample: Optional[PILImageResampling] = None,
do_rescale: Optional[bool] = None,
rescale_factor: Optional[float] = None,
do_normalize: Optional[bool] = None,
image_mean: Optional[Union[float, list[float]]] = None,
image_std: Optional[Union[float, list[float]]] = None,
do_pad: Optional[bool] = None,
do_image_splitting: Optional[bool] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
input_data_format: Optional[ChannelDimension] = None,
data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
):
"""
Preprocess a batch of images.
Args:
images (`ImageInput`):
A list of images to preprocess.
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
Whether to convert the image to RGB.
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
Whether to resize the image.
size (`dict[str, int]`, *optional*, defaults to `self.size`):
Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
the longest edge resized to keep the input aspect ratio.
resample (`int`, *optional*, defaults to `self.resample`):
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
has an effect if `do_resize` is set to `True`.
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
Whether to rescale the image.
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
Whether to normalize the image.
image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
`True`.
do_pad (`bool`, *optional*, defaults to `self.do_pad`):
Whether or not to pad the images to the largest height and width in the batch.
do_image_splitting (`bool`, *optional*, defaults to `self.do_image_splitting`):
Whether to split the image into a sequence 4 equal sub-images concatenated with the original image. That
strategy was first introduced in https://huggingface.co/papers/2311.06607.
return_tensors (`str` or `TensorType`, *optional*):
The type of tensors to return. Can be one of:
- Unset: Return a list of `np.ndarray`.
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
The channel dimension format for the output image. Can be one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
- Unset: Use the channel dimension format of the input image.
input_data_format (`ChannelDimension` or `str`, *optional*):
The channel dimension format for the input image. If unset, the channel dimension format is inferred
from the input image. Can be one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
"""
do_resize = do_resize if do_resize is not None else self.do_resize
size = size if size is not None else self.size
resample = resample if resample is not None else self.resample
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
image_mean = image_mean if image_mean is not None else self.image_mean
image_std = image_std if image_std is not None else self.image_std
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
do_pad = do_pad if do_pad is not None else self.do_pad
do_image_splitting = do_image_splitting if do_image_splitting is not None else self.do_image_splitting
images = self.fetch_images(images)
images_list = make_nested_list_of_images(images)
if not valid_images(images_list[0]):
raise ValueError("Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, or torch.Tensor")
validate_preprocess_arguments(
do_rescale=do_rescale,
rescale_factor=rescale_factor,
do_normalize=do_normalize,
image_mean=image_mean,
image_std=image_std,
do_resize=do_resize,
size=size,
resample=resample,
)
if do_convert_rgb:
images_list = [[convert_to_rgb(image) for image in images] for images in images_list]
# All transformations expect numpy arrays.
images_list = [[to_numpy_array(image) for image in images] for images in images_list]
# Search for the first image in the image list.
# NOTE: we can't slice the first image with images_list[0][0] if the first batch contains no images. See #36682
first_image_in_list = [images for images in images_list if images][0][0]
if do_rescale and is_scaled_image(first_image_in_list):
logger.warning_once(
"It looks like you are trying to rescale already rescaled images. If the input"
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
)
if input_data_format is None:
# We assume that all images have the same channel dimension format.
input_data_format = infer_channel_dimension_format(first_image_in_list)
if do_image_splitting:
new_images_list = []
for images in images_list:
new_images = []
for image in images:
new_images.extend(self.split_image(image, input_data_format))
new_images_list.append(new_images)
images_list = new_images_list
if do_resize:
images_list = [
[
self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
for image in images
]
for images in images_list
]
if do_rescale:
images_list = [
[
self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
for image in images
]
for images in images_list
]
if do_normalize:
images_list = [
[
self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
for image in images
]
for images in images_list
]
pixel_attention_mask = None
if do_pad:
images_list, pixel_attention_mask = self.pad(
images_list, return_pixel_mask=True, return_tensors=return_tensors, input_data_format=input_data_format
)
if data_format is not None:
images_list = [
[
to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
for image in images
]
for images in images_list
]
data = {"pixel_values": np.array(images_list) if do_pad else images_list} # Faster tensor conversion
if pixel_attention_mask is not None:
data["pixel_attention_mask"] = np.array(pixel_attention_mask) if do_pad else pixel_attention_mask
return BatchFeature(data=data, tensor_type=return_tensors)
__all__ = ["Idefics2ImageProcessor"]
| Idefics2ImageProcessor |
python | doocs__leetcode | solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.py | {
"start": 0,
"end": 300
} | class ____:
def numMovesStones(self, a: int, b: int, c: int) -> List[int]:
x, z = min(a, b, c), max(a, b, c)
y = a + b + c - x - z
mi = mx = 0
if z - x > 2:
mi = 1 if y - x < 3 or z - y < 3 else 2
mx = z - x - 2
return [mi, mx]
| Solution |
python | kamyu104__LeetCode-Solutions | Python/single-number-iii.py | {
"start": 369,
"end": 712
} | class ____(object):
# @param {integer[]} nums
# @return {integer[]}
def singleNumber(self, nums):
x_xor_y = 0
for i in nums:
x_xor_y ^= i
bit = x_xor_y & ~(x_xor_y - 1)
x = 0
for i in nums:
if i & bit:
x ^= i
return [x, x ^ x_xor_y]
| Solution2 |
python | pexpect__pexpect | pexpect/spawnbase.py | {
"start": 276,
"end": 478
} | class ____(object):
"""Pass bytes through unchanged."""
@staticmethod
def encode(b, final=False):
return b
@staticmethod
def decode(b, final=False):
return b
| _NullCoder |
python | pypa__warehouse | tests/unit/packaging/test_models.py | {
"start": 1544,
"end": 1715
} | class ____:
def test_repr(self, db_request):
role_invitation = DBRoleInvitationFactory()
assert isinstance(repr(role_invitation), str)
| TestRoleInvitation |
python | jazzband__django-waffle | waffle/tests/test_admin.py | {
"start": 1105,
"end": 4517
} | class ____(TestCase):
def setUp(self):
super().setUp()
self.site = AdminSite()
self.flag_admin = FlagAdmin(Flag, self.site)
def test_informative_widget(self):
request = mock.Mock()
request.has_perm = lambda self, perm: True
form = self.flag_admin.get_form(request)()
user_widget = form.fields["users"].widget
self.assertIsInstance(user_widget, InformativeManyToManyRawIdWidget)
user1 = get_user_model().objects.create(username="test1")
user2 = get_user_model().objects.create(username="test2")
self.assertIn("(test1, test2)",
user_widget.render("users", [user1.pk, user2.pk]))
def test_enable_for_all(self):
f1 = Flag.objects.create(name="flag1", everyone=False)
request = FakeRequest()
enable_for_all(None, request, Flag.objects.all())
f1.refresh_from_db()
self.assertTrue(f1.everyone)
log_entry = LogEntry.objects.get(user=request.user)
self.assertEqual(log_entry.action_flag, CHANGE)
self.assertEqual(log_entry.object_repr, "flag1 on")
def test_disable_for_all(self):
f1 = Flag.objects.create(name="flag1", everyone=True)
request = FakeRequest()
disable_for_all(None, request, Flag.objects.all())
f1.refresh_from_db()
self.assertFalse(f1.everyone)
log_entry = LogEntry.objects.get(user=request.user)
self.assertEqual(log_entry.action_flag, CHANGE)
self.assertEqual(log_entry.object_repr, "flag1 off")
def test_delete_individually(self):
Flag.objects.create(name="flag1", everyone=True)
request = FakeRequest()
delete_individually(None, request, Flag.objects.all())
self.assertIsNone(Flag.objects.first())
log_entry = LogEntry.objects.get(user=request.user)
self.assertEqual(log_entry.action_flag, DELETION)
@skip_if_admin_permissions_not_available
def test_flag_no_actions_without_permissions(self):
request = FakeRequest()
actions = self.flag_admin.get_actions(request)
self.assertEqual(actions.keys(), set())
@skip_if_admin_permissions_not_available
def test_flag_action_change(self):
request = FakeRequest()
request.user.user_permissions.add(Permission.objects.get(codename="change_flag"))
actions = self.flag_admin.get_actions(request)
self.assertEqual(actions.keys(), {"enable_for_all", "disable_for_all"})
@skip_if_admin_permissions_not_available
def test_flag_action_delete(self):
request = FakeRequest()
request.user.user_permissions.add(Permission.objects.get(codename="delete_flag"))
actions = self.flag_admin.get_actions(request)
self.assertEqual(actions.keys(), {"delete_individually"})
def test_model_can_be_registered_by_default(self):
config = get_setting("ENABLE_ADMIN_PAGES")
_register_model_to_admin_site(admin_site=self.site, config_setting=config, model=Flag)
self.assertTrue(self.site.is_registered(Flag))
@override_settings(WAFFLE_ENABLE_ADMIN_PAGES=False)
def test_admin_page_can_be_disabled(self):
config = get_setting("ENABLE_ADMIN_PAGES")
_register_model_to_admin_site(admin_site=self.site, config_setting=config, model=Flag)
self.assertFalse(self.site.is_registered(Flag))
| FlagAdminTests |
python | pydantic__pydantic | tests/test_type_adapter.py | {
"start": 969,
"end": 26010
} | class ____(NamedTuple):
x: int
@pytest.mark.parametrize(
'tp, val, expected',
[
(PydanticModel, PydanticModel(x=1), PydanticModel(x=1)),
(PydanticModel, {'x': 1}, PydanticModel(x=1)),
(SomeTypedDict, {'x': 1}, {'x': 1}),
(SomeNamedTuple, SomeNamedTuple(x=1), SomeNamedTuple(x=1)),
(list[str], ['1', '2'], ['1', '2']),
(tuple[str], ('1',), ('1',)),
(tuple[str, int], ('1', 1), ('1', 1)),
(tuple[str, ...], ('1',), ('1',)),
(dict[str, int], {'foo': 123}, {'foo': 123}),
(Union[int, str], 1, 1),
(Union[int, str], '2', '2'),
(GenericPydanticModel[int], {'x': [[1]]}, GenericPydanticModel[int](x=[[1]])),
(GenericPydanticModel[int], {'x': [['1']]}, GenericPydanticModel[int](x=[[1]])),
(NestedList[int], [[1]], [[1]]),
(NestedList[int], [['1']], [[1]]),
],
)
def test_types(tp: Any, val: Any, expected: Any):
v = TypeAdapter(tp).validate_python
assert expected == v(val)
IntList = list[int]
OuterDict = dict[str, 'IntList']
@pytest.mark.parametrize('defer_build', [False, True])
@pytest.mark.parametrize('method', ['validate', 'serialize', 'json_schema', 'json_schemas'])
def test_global_namespace_variables(defer_build: bool, method: str, generate_schema_calls):
config = ConfigDict(defer_build=True) if defer_build else None
ta = TypeAdapter(OuterDict, config=config)
assert generate_schema_calls.count == (0 if defer_build else 1), 'Should be built deferred'
if method == 'validate':
assert ta.validate_python({'foo': [1, '2']}) == {'foo': [1, 2]}
elif method == 'serialize':
assert ta.dump_python({'foo': [1, 2]}) == {'foo': [1, 2]}
elif method == 'json_schema':
assert ta.json_schema()['type'] == 'object'
else:
assert method == 'json_schemas'
schemas, _ = TypeAdapter.json_schemas([(OuterDict, 'validation', ta)])
assert schemas[(OuterDict, 'validation')]['type'] == 'object'
@pytest.mark.parametrize('defer_build', [False, True])
@pytest.mark.parametrize('method', ['validate', 'serialize', 'json_schema', 'json_schemas'])
def test_model_global_namespace_variables(defer_build: bool, method: str, generate_schema_calls):
class MyModel(BaseModel):
model_config = ConfigDict(defer_build=defer_build)
x: OuterDict
ta = TypeAdapter(MyModel)
assert generate_schema_calls.count == (0 if defer_build else 1), 'Should be built deferred'
if method == 'validate':
assert ta.validate_python({'x': {'foo': [1, '2']}}) == MyModel(x={'foo': [1, 2]})
elif method == 'serialize':
assert ta.dump_python(MyModel(x={'foo': [1, 2]})) == {'x': {'foo': [1, 2]}}
elif method == 'json_schema':
assert ta.json_schema()['title'] == 'MyModel'
else:
assert method == 'json_schemas'
_, json_schema = TypeAdapter.json_schemas([(MyModel, 'validation', TypeAdapter(MyModel))])
assert 'MyModel' in json_schema['$defs']
@pytest.mark.parametrize('defer_build', [False, True])
@pytest.mark.parametrize('method', ['validate', 'serialize', 'json_schema', 'json_schemas'])
def test_local_namespace_variables(defer_build: bool, method: str, generate_schema_calls):
IntList = list[int] # noqa: F841
OuterDict = dict[str, 'IntList']
config = ConfigDict(defer_build=True) if defer_build else None
ta = TypeAdapter(OuterDict, config=config)
assert generate_schema_calls.count == (0 if defer_build else 1), 'Should be built deferred'
if method == 'validate':
assert ta.validate_python({'foo': [1, '2']}) == {'foo': [1, 2]}
elif method == 'serialize':
assert ta.dump_python({'foo': [1, 2]}) == {'foo': [1, 2]}
elif method == 'json_schema':
assert ta.json_schema()['type'] == 'object'
else:
assert method == 'json_schemas'
schemas, _ = TypeAdapter.json_schemas([(OuterDict, 'validation', ta)])
assert schemas[(OuterDict, 'validation')]['type'] == 'object'
@pytest.mark.parametrize('defer_build', [False, True])
@pytest.mark.parametrize('method', ['validate', 'serialize', 'json_schema', 'json_schemas'])
def test_model_local_namespace_variables(defer_build: bool, method: str, generate_schema_calls):
IntList = list[int] # noqa: F841
class MyModel(BaseModel):
model_config = ConfigDict(defer_build=defer_build)
x: dict[str, 'IntList']
ta = TypeAdapter(MyModel)
assert generate_schema_calls.count == (0 if defer_build else 1), 'Should be built deferred'
if method == 'validate':
assert ta.validate_python({'x': {'foo': [1, '2']}}) == MyModel(x={'foo': [1, 2]})
elif method == 'serialize':
assert ta.dump_python(MyModel(x={'foo': [1, 2]})) == {'x': {'foo': [1, 2]}}
elif method == 'json_schema':
assert ta.json_schema()['title'] == 'MyModel'
else:
assert method == 'json_schemas'
_, json_schema = TypeAdapter.json_schemas([(MyModel, 'validation', ta)])
assert 'MyModel' in json_schema['$defs']
@pytest.mark.parametrize('defer_build', [False, True])
@pytest.mark.parametrize('method', ['validate', 'serialize', 'json_schema', 'json_schemas'])
def test_top_level_fwd_ref(defer_build: bool, method: str, generate_schema_calls):
config = ConfigDict(defer_build=True) if defer_build else None
FwdRef = ForwardRef('OuterDict', module=__name__)
ta = TypeAdapter(FwdRef, config=config)
assert generate_schema_calls.count == (0 if defer_build else 1), 'Should be built deferred'
if method == 'validate':
assert ta.validate_python({'foo': [1, '2']}) == {'foo': [1, 2]}
elif method == 'serialize':
assert ta.dump_python({'foo': [1, 2]}) == {'foo': [1, 2]}
elif method == 'json_schema':
assert ta.json_schema()['type'] == 'object'
else:
assert method == 'json_schemas'
schemas, _ = TypeAdapter.json_schemas([(FwdRef, 'validation', ta)])
assert schemas[(FwdRef, 'validation')]['type'] == 'object'
MyUnion: TypeAlias = 'Union[str, int]'
def test_type_alias():
MyList = list[MyUnion]
v = TypeAdapter(MyList).validate_python
res = v([1, '2'])
assert res == [1, '2']
def test_validate_python_strict() -> None:
class Model(TypedDict):
x: int
class ModelStrict(Model):
__pydantic_config__ = ConfigDict(strict=True) # type: ignore
lax_validator = TypeAdapter(Model)
strict_validator = TypeAdapter(ModelStrict)
assert lax_validator.validate_python({'x': '1'}, strict=None) == Model(x=1)
assert lax_validator.validate_python({'x': '1'}, strict=False) == Model(x=1)
with pytest.raises(ValidationError) as exc_info:
lax_validator.validate_python({'x': '1'}, strict=True)
assert exc_info.value.errors(include_url=False) == [
{'type': 'int_type', 'loc': ('x',), 'msg': 'Input should be a valid integer', 'input': '1'}
]
with pytest.raises(ValidationError) as exc_info:
strict_validator.validate_python({'x': '1'})
assert exc_info.value.errors(include_url=False) == [
{'type': 'int_type', 'loc': ('x',), 'msg': 'Input should be a valid integer', 'input': '1'}
]
assert strict_validator.validate_python({'x': '1'}, strict=False) == Model(x=1)
with pytest.raises(ValidationError) as exc_info:
strict_validator.validate_python({'x': '1'}, strict=True)
assert exc_info.value.errors(include_url=False) == [
{'type': 'int_type', 'loc': ('x',), 'msg': 'Input should be a valid integer', 'input': '1'}
]
@pytest.mark.xfail(reason='Need to fix this in https://github.com/pydantic/pydantic/pull/5944')
def test_validate_json_strict() -> None:
class Model(TypedDict):
x: int
class ModelStrict(Model):
__pydantic_config__ = ConfigDict(strict=True) # type: ignore
lax_validator = TypeAdapter(Model, config=ConfigDict(strict=False))
strict_validator = TypeAdapter(ModelStrict)
assert lax_validator.validate_json(json.dumps({'x': '1'}), strict=None) == Model(x=1)
assert lax_validator.validate_json(json.dumps({'x': '1'}), strict=False) == Model(x=1)
with pytest.raises(ValidationError) as exc_info:
lax_validator.validate_json(json.dumps({'x': '1'}), strict=True)
assert exc_info.value.errors(include_url=False) == [
{'type': 'int_type', 'loc': ('x',), 'msg': 'Input should be a valid integer', 'input': '1'}
]
with pytest.raises(ValidationError) as exc_info:
strict_validator.validate_json(json.dumps({'x': '1'}), strict=None)
assert exc_info.value.errors(include_url=False) == [
{'type': 'int_type', 'loc': ('x',), 'msg': 'Input should be a valid integer', 'input': '1'}
]
assert strict_validator.validate_json(json.dumps({'x': '1'}), strict=False) == Model(x=1)
with pytest.raises(ValidationError) as exc_info:
strict_validator.validate_json(json.dumps({'x': '1'}), strict=True)
assert exc_info.value.errors(include_url=False) == [
{'type': 'int_type', 'loc': ('x',), 'msg': 'Input should be a valid integer', 'input': '1'}
]
def test_validate_python_extra() -> None:
class Model(TypedDict):
x: int
class ModelForbid(Model):
__pydantic_config__ = ConfigDict(extra='forbid') # type: ignore
ignore_validator = TypeAdapter(Model)
forbid_validator = TypeAdapter(ModelForbid)
assert ignore_validator.validate_python({'x': '1', 'y': '2'}) == Model(x=1)
with pytest.raises(ValidationError) as exc_info:
ignore_validator.validate_python({'x': '1', 'y': '2'}, extra='forbid')
assert exc_info.value.errors(include_url=False) == [
{'type': 'extra_forbidden', 'loc': ('y',), 'msg': 'Extra inputs are not permitted', 'input': '2'}
]
with pytest.raises(ValidationError) as exc_info:
forbid_validator.validate_python({'x': '1', 'y': '2'})
assert exc_info.value.errors(include_url=False) == [
{'type': 'extra_forbidden', 'loc': ('y',), 'msg': 'Extra inputs are not permitted', 'input': '2'}
]
assert forbid_validator.validate_python({'x': '1', 'y': '2'}, extra='ignore') == Model(x=1)
def test_validate_json_extra() -> None:
class Model(TypedDict):
x: int
class ModelForbid(Model):
__pydantic_config__ = ConfigDict(extra='forbid') # type: ignore
ignore_validator = TypeAdapter(Model)
forbid_validator = TypeAdapter(ModelForbid)
assert ignore_validator.validate_json(json.dumps({'x': '1', 'y': '2'})) == Model(x=1)
with pytest.raises(ValidationError) as exc_info:
ignore_validator.validate_json(json.dumps({'x': '1', 'y': '2'}), extra='forbid')
assert exc_info.value.errors(include_url=False) == [
{'type': 'extra_forbidden', 'loc': ('y',), 'msg': 'Extra inputs are not permitted', 'input': '2'}
]
with pytest.raises(ValidationError) as exc_info:
forbid_validator.validate_json(json.dumps({'x': '1', 'y': '2'}))
assert exc_info.value.errors(include_url=False) == [
{'type': 'extra_forbidden', 'loc': ('y',), 'msg': 'Extra inputs are not permitted', 'input': '2'}
]
assert forbid_validator.validate_json(json.dumps({'x': '1', 'y': '2'}), extra='ignore') == Model(x=1)
def test_validate_strings_extra() -> None:
class Model(TypedDict):
x: bool
class ModelForbid(Model):
__pydantic_config__ = ConfigDict(extra='forbid') # type: ignore
ignore_validator = TypeAdapter(Model)
forbid_validator = TypeAdapter(ModelForbid)
assert ignore_validator.validate_strings({'x': 'true', 'y': 'true'}) == Model(x=True)
with pytest.raises(ValidationError) as exc_info:
ignore_validator.validate_strings({'x': 'true', 'y': 'true'}, extra='forbid')
assert exc_info.value.errors(include_url=False) == [
{'type': 'extra_forbidden', 'loc': ('y',), 'msg': 'Extra inputs are not permitted', 'input': 'true'}
]
with pytest.raises(ValidationError) as exc_info:
forbid_validator.validate_strings({'x': 'true', 'y': 'true'})
assert exc_info.value.errors(include_url=False) == [
{'type': 'extra_forbidden', 'loc': ('y',), 'msg': 'Extra inputs are not permitted', 'input': 'true'}
]
assert forbid_validator.validate_strings({'x': 'true', 'y': 'true'}, extra='ignore') == Model(x=True)
def test_validate_python_context() -> None:
contexts: list[Any] = [None, None, {'foo': 'bar'}]
class Model(BaseModel):
x: int
@field_validator('x')
def val_x(cls, v: int, info: ValidationInfo) -> int:
assert info.context == contexts.pop(0)
return v
validator = TypeAdapter(Model)
validator.validate_python({'x': 1})
validator.validate_python({'x': 1}, context=None)
validator.validate_python({'x': 1}, context={'foo': 'bar'})
assert contexts == []
def test_validate_json_context() -> None:
contexts: list[Any] = [None, None, {'foo': 'bar'}]
class Model(BaseModel):
x: int
@field_validator('x')
def val_x(cls, v: int, info: ValidationInfo) -> int:
assert info.context == contexts.pop(0)
return v
validator = TypeAdapter(Model)
validator.validate_json(json.dumps({'x': 1}))
validator.validate_json(json.dumps({'x': 1}), context=None)
validator.validate_json(json.dumps({'x': 1}), context={'foo': 'bar'})
assert contexts == []
def test_validate_python_from_attributes() -> None:
class Model(BaseModel):
x: int
class ModelFromAttributesTrue(Model):
model_config = ConfigDict(from_attributes=True)
class ModelFromAttributesFalse(Model):
model_config = ConfigDict(from_attributes=False)
@dataclass
class UnrelatedClass:
x: int = 1
input = UnrelatedClass(1)
ta = TypeAdapter(Model)
for from_attributes in (False, None):
with pytest.raises(ValidationError) as exc_info:
ta.validate_python(UnrelatedClass(), from_attributes=from_attributes)
assert exc_info.value.errors(include_url=False) == [
{
'type': 'model_type',
'loc': (),
'msg': 'Input should be a valid dictionary or instance of Model',
'input': input,
'ctx': {'class_name': 'Model'},
}
]
res = ta.validate_python(UnrelatedClass(), from_attributes=True)
assert res == Model(x=1)
ta = TypeAdapter(ModelFromAttributesTrue)
with pytest.raises(ValidationError) as exc_info:
ta.validate_python(UnrelatedClass(), from_attributes=False)
assert exc_info.value.errors(include_url=False) == [
{
'type': 'model_type',
'loc': (),
'msg': 'Input should be a valid dictionary or instance of ModelFromAttributesTrue',
'input': input,
'ctx': {'class_name': 'ModelFromAttributesTrue'},
}
]
for from_attributes in (True, None):
res = ta.validate_python(UnrelatedClass(), from_attributes=from_attributes)
assert res == ModelFromAttributesTrue(x=1)
ta = TypeAdapter(ModelFromAttributesFalse)
for from_attributes in (False, None):
with pytest.raises(ValidationError) as exc_info:
ta.validate_python(UnrelatedClass(), from_attributes=from_attributes)
assert exc_info.value.errors(include_url=False) == [
{
'type': 'model_type',
'loc': (),
'msg': 'Input should be a valid dictionary or instance of ModelFromAttributesFalse',
'input': input,
'ctx': {'class_name': 'ModelFromAttributesFalse'},
}
]
res = ta.validate_python(UnrelatedClass(), from_attributes=True)
assert res == ModelFromAttributesFalse(x=1)
@pytest.mark.parametrize(
'field_type,input_value,expected,raises_match,strict',
[
(bool, 'true', True, None, False),
(bool, 'true', True, None, True),
(bool, 'false', False, None, False),
(bool, 'e', ValidationError, 'type=bool_parsing', False),
(int, '1', 1, None, False),
(int, '1', 1, None, True),
(int, 'xxx', ValidationError, 'type=int_parsing', True),
(float, '1.1', 1.1, None, False),
(float, '1.10', 1.1, None, False),
(float, '1.1', 1.1, None, True),
(float, '1.10', 1.1, None, True),
(date, '2017-01-01', date(2017, 1, 1), None, False),
(date, '2017-01-01', date(2017, 1, 1), None, True),
(date, '2017-01-01T12:13:14.567', ValidationError, 'type=date_from_datetime_inexact', False),
(date, '2017-01-01T12:13:14.567', ValidationError, 'type=date_parsing', True),
(date, '2017-01-01T00:00:00', date(2017, 1, 1), None, False),
(date, '2017-01-01T00:00:00', ValidationError, 'type=date_parsing', True),
(datetime, '2017-01-01T12:13:14.567', datetime(2017, 1, 1, 12, 13, 14, 567_000), None, False),
(datetime, '2017-01-01T12:13:14.567', datetime(2017, 1, 1, 12, 13, 14, 567_000), None, True),
],
ids=repr,
)
@pytest.mark.parametrize('defer_build', [False, True])
def test_validate_strings(
field_type, input_value, expected, raises_match, strict, defer_build: bool, generate_schema_calls
):
config = ConfigDict(defer_build=True) if defer_build else None
ta = TypeAdapter(field_type, config=config)
assert generate_schema_calls.count == (0 if defer_build else 1), 'Should be built deferred'
if raises_match is not None:
with pytest.raises(expected, match=raises_match):
ta.validate_strings(input_value, strict=strict)
else:
assert ta.validate_strings(input_value, strict=strict) == expected
assert generate_schema_calls.count == 1, 'Should not build duplicates'
@pytest.mark.parametrize('strict', [True, False])
def test_validate_strings_dict(strict):
assert TypeAdapter(dict[int, date]).validate_strings({'1': '2017-01-01', '2': '2017-01-02'}, strict=strict) == {
1: date(2017, 1, 1),
2: date(2017, 1, 2),
}
def test_annotated_type_disallows_config() -> None:
class Model(BaseModel):
x: int
with pytest.raises(PydanticUserError, match='Cannot use `config`'):
TypeAdapter(Annotated[Model, ...], config=ConfigDict(strict=False))
def test_ta_config_with_annotated_type() -> None:
class TestValidator(BaseModel):
x: str
model_config = ConfigDict(str_to_lower=True)
assert TestValidator(x='ABC').x == 'abc'
assert TypeAdapter(TestValidator).validate_python({'x': 'ABC'}).x == 'abc'
assert TypeAdapter(Annotated[TestValidator, ...]).validate_python({'x': 'ABC'}).x == 'abc'
class TestSerializer(BaseModel):
some_bytes: bytes
model_config = ConfigDict(ser_json_bytes='base64')
result = TestSerializer(some_bytes=b'\xaa')
assert result.model_dump(mode='json') == {'some_bytes': 'qg=='}
assert TypeAdapter(TestSerializer).dump_python(result, mode='json') == {'some_bytes': 'qg=='}
# cases where SchemaSerializer is constructed within TypeAdapter's __init__
assert TypeAdapter(Annotated[TestSerializer, ...]).dump_python(result, mode='json') == {'some_bytes': 'qg=='}
assert TypeAdapter(Annotated[list[TestSerializer], ...]).dump_python([result], mode='json') == [
{'some_bytes': 'qg=='}
]
def test_eval_type_backport():
v = TypeAdapter('list[int | str]').validate_python
assert v([1, '2']) == [1, '2']
with pytest.raises(ValidationError) as exc_info:
v([{'not a str or int'}])
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'int_type',
'loc': (0, 'int'),
'msg': 'Input should be a valid integer',
'input': {'not a str or int'},
},
{
'type': 'string_type',
'loc': (0, 'str'),
'msg': 'Input should be a valid string',
'input': {'not a str or int'},
},
]
with pytest.raises(ValidationError) as exc_info:
v('not a list')
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{'type': 'list_type', 'loc': (), 'msg': 'Input should be a valid list', 'input': 'not a list'}
]
def defer_build_test_models(config: ConfigDict) -> list[Any]:
class Model(BaseModel):
model_config = config
x: int
class SubModel(Model):
y: Optional[int] = None
@pydantic_dataclass(config=config)
class DataClassModel:
x: int
@pydantic_dataclass
class SubDataClassModel(DataClassModel):
y: Optional[int] = None
class TypedDictModel(TypedDict):
__pydantic_config__ = config # type: ignore
x: int
models = [
Model,
SubModel,
create_model('DynamicModel', __base__=Model),
create_model('DynamicSubModel', __base__=SubModel),
DataClassModel,
SubDataClassModel,
TypedDictModel,
dict[str, int],
]
return [
*models,
# FastAPI heavily uses Annotated so test that as well
*[Annotated[model, Field(title='abc')] for model in models],
]
CONFIGS = [
ConfigDict(defer_build=False),
ConfigDict(defer_build=True),
]
MODELS_CONFIGS: list[tuple[Any, ConfigDict]] = [
(model, config) for config in CONFIGS for model in defer_build_test_models(config)
]
@pytest.mark.parametrize('model, config', MODELS_CONFIGS)
@pytest.mark.parametrize('method', ['schema', 'validate', 'dump'])
def test_core_schema_respects_defer_build(model: Any, config: ConfigDict, method: str, generate_schema_calls) -> None:
type_ = annotated_type(model) or model
dumped = dict(x=1) if 'dict[' in str(type_) else type_(x=1)
generate_schema_calls.reset()
type_adapter = TypeAdapter(model) if _type_has_config(model) else TypeAdapter(model, config=config)
if config.get('defer_build'):
assert generate_schema_calls.count == 0, 'Should be built deferred'
assert isinstance(type_adapter.core_schema, _mock_val_ser.MockCoreSchema), 'Should be initialized deferred'
assert isinstance(type_adapter.validator, _mock_val_ser.MockValSer), 'Should be initialized deferred'
assert isinstance(type_adapter.serializer, _mock_val_ser.MockValSer), 'Should be initialized deferred'
else:
built_inside_type_adapter = 'dict' in str(model).lower() or 'Annotated' in str(model)
assert generate_schema_calls.count == (1 if built_inside_type_adapter else 0), f'Should be built ({model})'
assert not isinstance(type_adapter.core_schema, _mock_val_ser.MockCoreSchema), (
'Should be initialized before usage'
)
assert not isinstance(type_adapter.validator, _mock_val_ser.MockValSer), 'Should be initialized before usage'
assert not isinstance(type_adapter.validator, _mock_val_ser.MockValSer), 'Should be initialized before usage'
if method == 'schema':
json_schema = type_adapter.json_schema() # Use it
assert "'type': 'integer'" in str(json_schema) # Sanity check
# Do not check generate_schema_calls count here as the json_schema generation uses generate schema internally
# assert generate_schema_calls.count < 2, 'Should not build duplicates'
elif method == 'validate':
validated = type_adapter.validate_python({'x': 1}) # Use it
assert (validated['x'] if isinstance(validated, dict) else validated.x) == 1 # Sanity check
assert generate_schema_calls.count < 2, 'Should not build duplicates'
else:
assert method == 'dump'
raw = type_adapter.dump_json(dumped) # Use it
assert json.loads(raw.decode())['x'] == 1 # Sanity check
assert generate_schema_calls.count < 2, 'Should not build duplicates'
assert not isinstance(type_adapter.core_schema, _mock_val_ser.MockCoreSchema), (
'Should be initialized after the usage'
)
assert not isinstance(type_adapter.validator, _mock_val_ser.MockValSer), 'Should be initialized after the usage'
assert not isinstance(type_adapter.validator, _mock_val_ser.MockValSer), 'Should be initialized after the usage'
def test_defer_build_raise_errors() -> None:
ta = TypeAdapter('MyInt', config=ConfigDict(defer_build=True)) # pyright: ignore[reportUndefinedVariable]
assert isinstance(ta.core_schema, _mock_val_ser.MockCoreSchema)
with pytest.raises(PydanticUndefinedAnnotation):
# `True` is the `raise_errors` default for the `rebuild` method, but we include here for clarity
ta.rebuild(raise_errors=True)
ta.rebuild(raise_errors=False)
assert isinstance(ta.core_schema, _mock_val_ser.MockCoreSchema)
MyInt = int # noqa: F841
ta.rebuild(raise_errors=True)
assert not isinstance(ta.core_schema, _mock_val_ser.MockCoreSchema)
@dataclass
| SomeNamedTuple |
python | getsentry__sentry | src/sentry/web/frontend/debug/debug_incident_trigger_email.py | {
"start": 1035,
"end": 3284
} | class ____(MailPreviewView):
@mock.patch(
"sentry.incidents.models.incident.IncidentTrigger.objects.get",
return_value=MockedIncidentTrigger(),
)
@mock.patch(
"sentry.users.models.user_option.UserOption.objects.get_value", return_value="US/Pacific"
)
def get_context(self, request, incident_trigger_mock, user_option_mock):
organization = Organization(slug="myorg")
project = Project(slug="myproject", organization=organization)
user = User()
query = SnubaQuery(
time_window=60, query="transaction:/some/transaction", aggregate="count()"
)
alert_rule = AlertRule(id=1, organization=organization, name="My Alert", snuba_query=query)
incident = Incident(
id=2,
identifier=123,
organization=organization,
title="Something broke",
alert_rule=alert_rule,
status=IncidentStatus.CRITICAL.value,
)
trigger = AlertRuleTrigger(alert_rule=alert_rule)
alert_rule_serialized_response = serialize(alert_rule, None, AlertRuleSerializer())
incident_serialized_response = serialize(incident, None, DetailedIncidentSerializer())
return generate_incident_trigger_email_context(
project=project,
organization=organization,
alert_rule_serialized_response=alert_rule_serialized_response,
incident_serialized_response=incident_serialized_response,
metric_issue_context=MetricIssueContext.from_legacy_models(
incident=incident,
new_status=IncidentStatus(incident.status),
),
alert_context=AlertContext.from_alert_rule_incident(alert_rule),
open_period_context=OpenPeriodContext.from_incident(incident),
trigger_status=TriggerStatus.ACTIVE,
trigger_threshold=trigger.alert_threshold,
user=user,
notification_uuid=str(uuid4()),
)
@property
def html_template(self) -> str:
return "sentry/emails/incidents/trigger.html"
@property
def text_template(self) -> str:
return "sentry/emails/incidents/trigger.txt"
| DebugIncidentTriggerEmailView |
python | scikit-image__scikit-image | benchmarks/benchmark_segmentation.py | {
"start": 458,
"end": 2454
} | class ____:
"""Benchmark for segmentation routines in scikit-image."""
def setup(self):
self.image = np.random.random((200, 200, 100))
self.image[:100, :100, :] += 1
self.image[150:, 150:, :] += 0.5
self.msk = np.zeros((200, 200, 100))
self.msk[10:-10, 10:-10, 10:-10] = 1
self.msk_slice = self.msk[..., 50]
if Version(skimage.__version__) >= Version('0.17.0'):
self.slic_kwargs = dict(start_label=1)
else:
self.slic_kwargs = {}
def time_slic_basic(self):
segmentation.slic(
self.image,
enforce_connectivity=False,
**_channel_kwarg(False),
**self.slic_kwargs,
)
def time_slic_basic_multichannel(self):
segmentation.slic(
self.image,
enforce_connectivity=False,
**_channel_kwarg(True),
**self.slic_kwargs,
)
def peakmem_setup(self):
"""peakmem includes the memory used by setup.
Peakmem benchmarks measure the maximum amount of RAM used by a
function. However, this maximum also includes the memory used
by ``setup`` (as of asv 0.2.1; see [1]_)
Measuring an empty peakmem function might allow us to disambiguate
between the memory used by setup and the memory used by slic (see
``peakmem_slic_basic``, below).
References
----------
.. [1]: https://asv.readthedocs.io/en/stable/writing_benchmarks.html#peak-memory
"""
pass
def peakmem_slic_basic(self):
segmentation.slic(
self.image,
enforce_connectivity=False,
**_channel_kwarg(False),
**self.slic_kwargs,
)
def peakmem_slic_basic_multichannel(self):
segmentation.slic(
self.image,
enforce_connectivity=False,
**_channel_kwarg(True),
**self.slic_kwargs,
)
| SlicSegmentation |
python | django__django | tests/modeladmin/test_checks.py | {
"start": 7953,
"end": 8832
} | class ____(CheckTestCase):
def test_duplicate_fields_in_fields(self):
class TestModelAdmin(ModelAdmin):
fields = ["name", "name"]
self.assertIsInvalid(
TestModelAdmin,
ValidationTestModel,
"The value of 'fields' contains duplicate field(s).",
"admin.E006",
"Remove duplicates of 'name'.",
)
def test_inline(self):
class ValidationTestInline(TabularInline):
model = ValidationTestInlineModel
fields = 10
class TestModelAdmin(ModelAdmin):
inlines = [ValidationTestInline]
self.assertIsInvalid(
TestModelAdmin,
ValidationTestModel,
"The value of 'fields' must be a list or tuple.",
"admin.E004",
invalid_obj=ValidationTestInline,
)
| FieldsCheckTests |
python | PyCQA__pylint | tests/functional/u/unused/unused_argument.py | {
"start": 2494,
"end": 2783
} | class ____:
"""dummy class"""
def __init__(self, arg): # [unused-argument]
"""Constructor with an extra parameter. Should raise a warning"""
self.spam = 1
# Regression test for https://github.com/pylint-dev/pylint/issues/5771
# involving keyword-only arguments
| BBBB |
python | Textualize__textual | docs/examples/widgets/text_area_custom_language.py | {
"start": 415,
"end": 885
} | class ____(App):
def compose(self) -> ComposeResult:
text_area = TextArea.code_editor(text=java_code)
text_area.cursor_blink = False
# Register the Java language and highlight query
text_area.register_language("java", java_language, java_highlight_query)
# Switch to Java
text_area.language = "java"
yield text_area
app = TextAreaCustomLanguage()
if __name__ == "__main__":
app.run()
| TextAreaCustomLanguage |
python | great-expectations__great_expectations | great_expectations/expectations/core/expect_column_values_to_match_json_schema.py | {
"start": 1147,
"end": 8151
} | class ____(ColumnMapExpectation):
"""Expect the column entries to be JSON objects matching a given JSON schema.
ExpectColumnValuesToMatchJsonSchema is a \
Column Map Expectation.
Args:
column (str): \
The column name.
json_schema (dict): \
The JSON schema to match
Keyword Args:
mostly (None or a float between 0 and 1): \
Successful if at least mostly fraction of values match the expectation. \
For more detail, see [mostly](https://docs.greatexpectations.io/docs/reference/expectations/standard_arguments/#mostly).
Other Parameters:
result_format (str or None): \
Which output mode to use: BOOLEAN_ONLY, BASIC, COMPLETE, or SUMMARY. \
For more detail, see [result_format](https://docs.greatexpectations.io/docs/reference/expectations/result_format).
catch_exceptions (boolean or None): \
If True, then catch exceptions and include them as part of the result object. \
For more detail, see [catch_exceptions](https://docs.greatexpectations.io/docs/reference/expectations/standard_arguments/#catch_exceptions).
meta (dict or None): \
A JSON-serializable dictionary (nesting allowed) that will be included in the output without \
modification. For more detail, see [meta](https://docs.greatexpectations.io/docs/reference/expectations/standard_arguments/#meta).
severity (str or None): \
{FAILURE_SEVERITY_DESCRIPTION} \
For more detail, see [failure severity](https://docs.greatexpectations.io/docs/cloud/expectations/expectations_overview/#failure-severity).
Returns:
An [ExpectationSuiteValidationResult](https://docs.greatexpectations.io/docs/terms/validation_result)
Exact fields vary depending on the values passed to result_format, catch_exceptions, and meta.
See Also:
[ExpectColumnValuesToBeJsonParseable](https://greatexpectations.io/expectations/expect_column_values_to_be_json_parseable)
[The JSON-schema docs](https://json-schema.org)
""" # noqa: E501 # FIXME CoP
json_schema: Union[dict, SuiteParameterDict]
# This dictionary contains metadata for display in the public gallery
library_metadata = {
"maturity": "production",
"tags": ["core expectation", "column map expectation"],
"contributors": ["@great_expectations"],
"requirements": [],
"has_full_test_suite": True,
"manually_reviewed_code": True,
}
map_metric = "column_values.match_json_schema"
success_keys = (
"json_schema",
"mostly",
)
args_keys = (
"column",
"json_schema",
)
@classmethod
def _prescriptive_template(
cls,
renderer_configuration: RendererConfiguration,
) -> RendererConfiguration:
add_param_args: AddParamArgs = (
("column", RendererValueType.STRING),
("mostly", RendererValueType.NUMBER),
("json_schema", RendererValueType.OBJECT),
)
for name, param_type in add_param_args:
renderer_configuration.add_param(name=name, param_type=param_type)
params = renderer_configuration.params
if not params.json_schema:
template_str = "values must match a JSON Schema but none was specified."
else:
formatted_json = f"<pre>{json.dumps(params.json_schema.value, indent=4)}</pre>"
renderer_configuration.add_param(
name="formatted_json",
param_type=RendererValueType.STRING,
value=formatted_json,
)
if params.mostly and params.mostly.value < 1.0:
renderer_configuration = cls._add_mostly_pct_param(
renderer_configuration=renderer_configuration
)
template_str = "values must match the following JSON Schema, at least $mostly_pct % of the time: $formatted_json" # noqa: E501 # FIXME CoP
else:
template_str = "values must match the following JSON Schema: $formatted_json"
if renderer_configuration.include_column_name:
template_str = f"$column {template_str}"
renderer_configuration.template_str = template_str
return renderer_configuration
@classmethod
@renderer(renderer_type=LegacyRendererType.PRESCRIPTIVE)
@render_suite_parameter_string
def _prescriptive_renderer(
cls,
configuration: Optional[ExpectationConfiguration] = None,
result: Optional[ExpectationValidationResult] = None,
runtime_configuration: Optional[dict] = None,
**kwargs,
):
runtime_configuration = runtime_configuration or {}
include_column_name = runtime_configuration.get("include_column_name") is not False
_ = runtime_configuration.get("styling")
params = substitute_none_for_missing(
configuration.kwargs,
["column", "mostly", "json_schema", "row_condition", "condition_parser"],
)
if not params.get("json_schema"):
template_str = "values must match a JSON Schema but none was specified."
else:
params["formatted_json"] = (
f"<pre>{json.dumps(params.get('json_schema'), indent=4)}</pre>"
)
if params["mostly"] is not None:
if isinstance(params["mostly"], (int, float)) and params["mostly"] < 1.0:
params["mostly_pct"] = num_to_str(params["mostly"] * 100, no_scientific=True)
# params["mostly_pct"] = "{:.14f}".format(params["mostly"]*100).rstrip("0").rstrip(".") # noqa: E501 # FIXME CoP
template_str = "values must match the following JSON Schema, at least $mostly_pct % of the time: $formatted_json" # noqa: E501 # FIXME CoP
else:
template_str = "values must match the following JSON Schema: $formatted_json"
if include_column_name:
template_str = f"$column {template_str}"
styling = runtime_configuration.get("styling") if runtime_configuration else None
if params["row_condition"] is not None:
conditional_template_str = parse_row_condition_string(params["row_condition"])
template_str, styling = _style_row_condition(
conditional_template_str,
template_str,
params,
styling,
)
return [
RenderedStringTemplateContent(
**{
"content_block_type": "string_template",
"string_template": {
"template": template_str,
"params": params,
"styling": {"params": {"formatted_json": {"classes": []}}},
},
}
)
]
| ExpectColumnValuesToMatchJsonSchema |
python | PrefectHQ__prefect | tests/test_futures.py | {
"start": 21914,
"end": 25030
} | class ____:
def test_wait(self):
mock_futures = [MockFuture(data=i) for i in range(5)]
futures = PrefectFutureList(mock_futures)
# should not raise a TimeoutError
futures.wait()
for future in futures:
assert future.state.is_completed()
@pytest.mark.timeout(method="thread") # alarm-based pytest-timeout will interfere
def test_wait_with_timeout(self):
mock_futures: List[PrefectFuture] = [MockFuture(data=i) for i in range(5)]
hanging_future = Future()
mock_futures.append(PrefectConcurrentFuture(uuid.uuid4(), hanging_future))
futures = PrefectFutureList(mock_futures)
# should not raise a TimeoutError or hang
futures.wait(timeout=0.01)
def test_results(self):
mock_futures = [MockFuture(data=i) for i in range(5)]
futures = PrefectFutureList(mock_futures)
result = futures.result()
for i, result in enumerate(result):
assert result == i
def test_results_with_failure(self):
mock_futures: List[PrefectFuture] = [MockFuture(data=i) for i in range(5)]
failing_future = Future()
failing_future.set_exception(ValueError("oops"))
mock_futures.append(PrefectConcurrentFuture(uuid.uuid4(), failing_future))
futures = PrefectFutureList(mock_futures)
with pytest.raises(ValueError, match="oops"):
futures.result()
def test_results_with_raise_on_failure_false(self):
mock_futures: List[PrefectFuture] = [MockFuture(data=i) for i in range(5)]
final_state = Failed(data=ValueError("oops"))
wrapped_future = Future()
wrapped_future.set_result(final_state)
mock_futures.append(PrefectConcurrentFuture(uuid.uuid4(), wrapped_future))
futures = PrefectFutureList(mock_futures)
result = futures.result(raise_on_failure=False)
for i, result in enumerate(result):
if i == 5:
assert isinstance(result, ValueError)
else:
assert result == i
@pytest.mark.timeout(method="thread") # alarm-based pytest-timeout will interfere
def test_results_with_timeout(self):
mock_futures: List[PrefectFuture] = [MockFuture(data=i) for i in range(5)]
failing_future = Future()
failing_future.set_exception(TimeoutError("oops"))
mock_futures.append(PrefectConcurrentFuture(uuid.uuid4(), failing_future))
futures = PrefectFutureList(mock_futures)
with pytest.raises(TimeoutError):
futures.result(timeout=0.01)
def test_result_does_not_obscure_other_timeouts(self):
mock_futures: List[PrefectFuture] = [MockFuture(data=i) for i in range(5)]
final_state = Failed(data=TimeoutError("oops"))
wrapped_future = Future()
wrapped_future.set_result(final_state)
mock_futures.append(PrefectConcurrentFuture(uuid.uuid4(), wrapped_future))
futures = PrefectFutureList(mock_futures)
with pytest.raises(TimeoutError, match="oops"):
futures.result()
| TestPrefectFutureList |
python | apache__airflow | providers/sftp/src/airflow/providers/sftp/exceptions.py | {
"start": 871,
"end": 1011
} | class ____(AirflowException):
"""Thrown when a connection has not been opened and has been tried to be used."""
| ConnectionNotOpenedException |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-mixpanel/source_mixpanel/components.py | {
"start": 3840,
"end": 4565
} | class ____(MixpanelHttpRequester):
def get_request_params(
self,
*,
stream_state: Optional[StreamState] = None,
stream_slice: Optional[StreamSlice] = None,
next_page_token: Optional[Mapping[str, Any]] = None,
) -> MutableMapping[str, Any]:
params = super().get_request_params(stream_state=stream_state, stream_slice=stream_slice, next_page_token=next_page_token)
if "start_time" in stream_slice:
params["where"] = f'properties["$last_seen"] >= "{stream_slice["start_time"]}"'
elif "start_date" in self.config:
params["where"] = f'properties["$last_seen"] >= "{self.config["start_date"]}"'
return params
| EngagesHttpRequester |
python | getsentry__sentry-python | sentry_sdk/integrations/opentelemetry/span_processor.py | {
"start": 1919,
"end": 13143
} | class ____(SpanProcessor):
"""
Converts OTel spans into Sentry spans so they can be sent to the Sentry backend.
"""
# The mapping from otel span ids to sentry spans
otel_span_map = {} # type: dict[str, Union[Transaction, SentrySpan]]
# The currently open spans. Elements will be discarded after SPAN_MAX_TIME_OPEN_MINUTES
open_spans = {} # type: dict[int, set[str]]
def __new__(cls):
# type: () -> SentrySpanProcessor
if not hasattr(cls, "instance"):
cls.instance = super().__new__(cls)
return cls.instance
def __init__(self):
# type: () -> None
@add_global_event_processor
def global_event_processor(event, hint):
# type: (Event, Hint) -> Event
return link_trace_context_to_error_event(event, self.otel_span_map)
def _prune_old_spans(self):
# type: (SentrySpanProcessor) -> None
"""
Prune spans that have been open for too long.
"""
current_time_minutes = int(time() / 60)
for span_start_minutes in list(
self.open_spans.keys()
): # making a list because we change the dict
# prune empty open spans buckets
if self.open_spans[span_start_minutes] == set():
self.open_spans.pop(span_start_minutes)
# prune old buckets
elif current_time_minutes - span_start_minutes > SPAN_MAX_TIME_OPEN_MINUTES:
for span_id in self.open_spans.pop(span_start_minutes):
self.otel_span_map.pop(span_id, None)
def on_start(self, otel_span, parent_context=None):
# type: (OTelSpan, Optional[context_api.Context]) -> None
client = get_client()
if not client.parsed_dsn:
return
if client.options["instrumenter"] != INSTRUMENTER.OTEL:
return
if not otel_span.get_span_context().is_valid:
return
if self._is_sentry_span(otel_span):
return
trace_data = self._get_trace_data(otel_span, parent_context)
parent_span_id = trace_data["parent_span_id"]
sentry_parent_span = (
self.otel_span_map.get(parent_span_id) if parent_span_id else None
)
start_timestamp = None
if otel_span.start_time is not None:
start_timestamp = datetime.fromtimestamp(
otel_span.start_time / 1e9, timezone.utc
) # OTel spans have nanosecond precision
sentry_span = None
if sentry_parent_span:
sentry_span = sentry_parent_span.start_child(
span_id=trace_data["span_id"],
name=otel_span.name,
start_timestamp=start_timestamp,
instrumenter=INSTRUMENTER.OTEL,
origin=SPAN_ORIGIN,
)
else:
sentry_span = start_transaction(
name=otel_span.name,
span_id=trace_data["span_id"],
parent_span_id=parent_span_id,
trace_id=trace_data["trace_id"],
baggage=trace_data["baggage"],
start_timestamp=start_timestamp,
instrumenter=INSTRUMENTER.OTEL,
origin=SPAN_ORIGIN,
)
self.otel_span_map[trace_data["span_id"]] = sentry_span
if otel_span.start_time is not None:
span_start_in_minutes = int(
otel_span.start_time / 1e9 / 60
) # OTel spans have nanosecond precision
self.open_spans.setdefault(span_start_in_minutes, set()).add(
trace_data["span_id"]
)
self._prune_old_spans()
def on_end(self, otel_span):
# type: (OTelSpan) -> None
client = get_client()
if client.options["instrumenter"] != INSTRUMENTER.OTEL:
return
span_context = otel_span.get_span_context()
if not span_context.is_valid:
return
span_id = format_span_id(span_context.span_id)
sentry_span = self.otel_span_map.pop(span_id, None)
if not sentry_span:
return
sentry_span.op = otel_span.name
self._update_span_with_otel_status(sentry_span, otel_span)
if isinstance(sentry_span, Transaction):
sentry_span.name = otel_span.name
sentry_span.set_context(
OPEN_TELEMETRY_CONTEXT, self._get_otel_context(otel_span)
)
self._update_transaction_with_otel_data(sentry_span, otel_span)
else:
self._update_span_with_otel_data(sentry_span, otel_span)
end_timestamp = None
if otel_span.end_time is not None:
end_timestamp = datetime.fromtimestamp(
otel_span.end_time / 1e9, timezone.utc
) # OTel spans have nanosecond precision
sentry_span.finish(end_timestamp=end_timestamp)
if otel_span.start_time is not None:
span_start_in_minutes = int(
otel_span.start_time / 1e9 / 60
) # OTel spans have nanosecond precision
self.open_spans.setdefault(span_start_in_minutes, set()).discard(span_id)
self._prune_old_spans()
def _is_sentry_span(self, otel_span):
# type: (OTelSpan) -> bool
"""
Break infinite loop:
HTTP requests to Sentry are caught by OTel and send again to Sentry.
"""
otel_span_url = None
if otel_span.attributes is not None:
otel_span_url = otel_span.attributes.get(SpanAttributes.HTTP_URL)
otel_span_url = cast("Optional[str]", otel_span_url)
parsed_dsn = get_client().parsed_dsn
dsn_url = parsed_dsn.netloc if parsed_dsn else None
if otel_span_url and dsn_url and dsn_url in otel_span_url:
return True
return False
def _get_otel_context(self, otel_span):
# type: (OTelSpan) -> dict[str, Any]
"""
Returns the OTel context for Sentry.
See: https://develop.sentry.dev/sdk/performance/opentelemetry/#step-5-add-opentelemetry-context
"""
ctx = {}
if otel_span.attributes:
ctx["attributes"] = dict(otel_span.attributes)
if otel_span.resource.attributes:
ctx["resource"] = dict(otel_span.resource.attributes)
return ctx
def _get_trace_data(self, otel_span, parent_context):
# type: (OTelSpan, Optional[context_api.Context]) -> dict[str, Any]
"""
Extracts tracing information from one OTel span and its parent OTel context.
"""
trace_data = {} # type: dict[str, Any]
span_context = otel_span.get_span_context()
span_id = format_span_id(span_context.span_id)
trace_data["span_id"] = span_id
trace_id = format_trace_id(span_context.trace_id)
trace_data["trace_id"] = trace_id
parent_span_id = (
format_span_id(otel_span.parent.span_id) if otel_span.parent else None
)
trace_data["parent_span_id"] = parent_span_id
sentry_trace_data = get_value(SENTRY_TRACE_KEY, parent_context)
sentry_trace_data = cast("dict[str, Union[str, bool, None]]", sentry_trace_data)
trace_data["parent_sampled"] = (
sentry_trace_data["parent_sampled"] if sentry_trace_data else None
)
baggage = get_value(SENTRY_BAGGAGE_KEY, parent_context)
trace_data["baggage"] = baggage
return trace_data
def _update_span_with_otel_status(self, sentry_span, otel_span):
# type: (SentrySpan, OTelSpan) -> None
"""
Set the Sentry span status from the OTel span
"""
if otel_span.status.is_unset:
return
if otel_span.status.is_ok:
sentry_span.set_status(SPANSTATUS.OK)
return
sentry_span.set_status(SPANSTATUS.INTERNAL_ERROR)
def _update_span_with_otel_data(self, sentry_span, otel_span):
# type: (SentrySpan, OTelSpan) -> None
"""
Convert OTel span data and update the Sentry span with it.
This should eventually happen on the server when ingesting the spans.
"""
sentry_span.set_data("otel.kind", otel_span.kind)
op = otel_span.name
description = otel_span.name
if otel_span.attributes is not None:
for key, val in otel_span.attributes.items():
sentry_span.set_data(key, val)
http_method = otel_span.attributes.get(SpanAttributes.HTTP_METHOD)
http_method = cast("Optional[str]", http_method)
db_query = otel_span.attributes.get(SpanAttributes.DB_SYSTEM)
if http_method:
op = "http"
if otel_span.kind == SpanKind.SERVER:
op += ".server"
elif otel_span.kind == SpanKind.CLIENT:
op += ".client"
description = http_method
peer_name = otel_span.attributes.get(SpanAttributes.NET_PEER_NAME, None)
if peer_name:
description += " {}".format(peer_name)
target = otel_span.attributes.get(SpanAttributes.HTTP_TARGET, None)
if target:
description += " {}".format(target)
if not peer_name and not target:
url = otel_span.attributes.get(SpanAttributes.HTTP_URL, None)
url = cast("Optional[str]", url)
if url:
parsed_url = urlparse(url)
url = "{}://{}{}".format(
parsed_url.scheme, parsed_url.netloc, parsed_url.path
)
description += " {}".format(url)
status_code = otel_span.attributes.get(
SpanAttributes.HTTP_STATUS_CODE, None
)
status_code = cast("Optional[int]", status_code)
if status_code:
sentry_span.set_http_status(status_code)
elif db_query:
op = "db"
statement = otel_span.attributes.get(SpanAttributes.DB_STATEMENT, None)
statement = cast("Optional[str]", statement)
if statement:
description = statement
sentry_span.op = op
sentry_span.description = description
def _update_transaction_with_otel_data(self, sentry_span, otel_span):
# type: (SentrySpan, OTelSpan) -> None
if otel_span.attributes is None:
return
http_method = otel_span.attributes.get(SpanAttributes.HTTP_METHOD)
if http_method:
status_code = otel_span.attributes.get(SpanAttributes.HTTP_STATUS_CODE)
status_code = cast("Optional[int]", status_code)
if status_code:
sentry_span.set_http_status(status_code)
op = "http"
if otel_span.kind == SpanKind.SERVER:
op += ".server"
elif otel_span.kind == SpanKind.CLIENT:
op += ".client"
sentry_span.op = op
| SentrySpanProcessor |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pytest_style/PT023.py | {
"start": 525,
"end": 735
} | class ____:
class TestNestedClass:
@pytest.mark.foo
def test_something():
pass
# With parentheses
@pytest.mark.foo()
def test_something():
pass
@pytest.mark.foo()
| TestClass |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 26984,
"end": 28682
} | class ____(Expr):
_parameters = [
"frame",
"func",
"before",
"after",
"meta",
"enforce_metadata",
"transform_divisions",
"clear_divisions",
"align_dataframes",
"token",
"kwargs",
]
_defaults = {
"meta": None,
"enfore_metadata": True,
"transform_divisions": True,
"kwargs": None,
"clear_divisions": False,
"align_dataframes": False,
"token": None,
}
@functools.cached_property
def _meta(self):
meta = self.operand("meta")
args = [self.frame._meta] + [
arg._meta if isinstance(arg, Expr) else arg
for arg in self.operands[len(self._parameters) :]
]
return _get_meta_map_partitions(
args,
[self.dependencies()[0]],
self.func,
self.kwargs,
meta,
self.kwargs.pop("parent_meta", None),
)
def _divisions(self):
args = [self.frame] + self.operands[len(self._parameters) :]
return calc_divisions_for_align(*args, allow_shuffle=False)
def _lower(self):
args = [self.frame] + self.operands[len(self._parameters) :]
args = maybe_align_partitions(*args, divisions=self._divisions())
return MapOverlap(
args[0],
self.func,
self.before,
self.after,
self._meta,
self.enforce_metadata,
self.transform_divisions,
self.clear_divisions,
self.align_dataframes,
self.token,
self.kwargs,
*args[1:],
)
| MapOverlapAlign |
python | langchain-ai__langchain | libs/langchain/tests/mock_servers/robot/server.py | {
"start": 679,
"end": 1128
} | class ____(str, Enum):
location = "location"
walking = "walking"
speed = "speed"
direction = "direction"
style = "style"
cautiousness = "cautiousness"
jumping = "jumping"
destruct = "destruct"
_ROBOT_STATE = {
"location": _ROBOT_LOCATION,
"walking": False,
"speed": 0,
"direction": "north",
"style": "normal",
"cautiousness": "medium",
"jumping": False,
"destruct": False,
}
| StateItems |
python | numba__numba | numba/cuda/cudadrv/driver.py | {
"start": 72250,
"end": 72991
} | class ____(object):
def __init__(self, memptr, view=None):
self._mem = memptr
if view is None:
self._view = self._mem
else:
assert not view.is_managed
self._view = view
mem = self._mem
def deref():
try:
mem.refct -= 1
assert mem.refct >= 0
if mem.refct == 0:
mem.free()
except ReferenceError:
# ignore reference error here
pass
self._mem.refct += 1
weakref.finalize(self, deref)
def __getattr__(self, fname):
"""Proxy MemoryPointer methods
"""
return getattr(self._view, fname)
| OwnedPointer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-linkedin-ads/unit_tests/test_source.py | {
"start": 8670,
"end": 15498
} | class ____:
@pytest.fixture
def accounts_stream(self) -> Stream:
return find_stream("accounts", TEST_CONFIG)
@pytest.fixture
def accounts_stream_url(self, accounts_stream) -> str:
return f"{accounts_stream._stream_partition_generator._partition_factory._retriever.requester.url_base}/{accounts_stream._stream_partition_generator._partition_factory._retriever.requester.path}"
@pytest.mark.parametrize(
"response_json, expected",
(
({"elements": []}, None),
(
{"elements": [{"data": []}] * 500, "metadata": {"nextPageToken": "next_page_token"}, "paging": {"start": 0, "total": 600}},
{"next_page_token": "next_page_token"},
),
),
)
def test_next_page_token(self, requests_mock, accounts_stream, accounts_stream_url, response_json, expected):
"""
Test `_next_page_token` in `SimpleRetriever`.
After reviewing `SimpleRetriever._next_page_token()`, I realized that `last_page_size`,
`last_record`, and `last_page_token_value` are internal state variables that must be
manually set or passed. Initially, I tried setting them manually within the state,
but the tests still failed with:
`TypeError: SimpleRetriever._next_page_token() missing 3 required positional arguments:
'last_page_size', 'last_record', and 'last_page_token_value'`.
To resolve this, I manually set and passed these variables as arguments to
`_next_page_token`, which got the tests to pass, as shown here.
"""
requests_mock.get(accounts_stream_url, json=response_json)
test_response = requests.get(accounts_stream_url)
last_page_size = len(response_json.get("elements", []))
last_record = response_json.get("elements", [])[-1] if response_json.get("elements") else None
last_page_token_value = None
result = accounts_stream._stream_partition_generator._partition_factory._retriever._next_page_token(
test_response, last_page_size, last_record, last_page_token_value
)
assert expected == result
def test_ad_campaign_analytics_stream(self, requests_mock):
# Test the built-in ad_campaign_analytics stream with mocked responses
config = {**TEST_CONFIG}
catalog = ConfiguredAirbyteCatalog(
streams=[
ConfiguredAirbyteStream(
stream=AirbyteStream(
name="ad_campaign_analytics",
json_schema={
"type": "object",
"properties": {
"id": {"type": ["null", "string"]},
"clicks": {"type": ["null", "number"]},
"impressions": {"type": ["null", "number"]},
"sponsoredCampaign": {"type": ["null", "number"]},
},
},
supported_sync_modes=[SyncMode.full_refresh],
),
sync_mode=SyncMode.full_refresh,
destination_sync_mode=DestinationSyncMode.overwrite,
)
]
)
expected_records = [
Record(
stream_name="ad_campaign_analytics",
data={
"clicks": 100.0,
"impressions": 19090.0,
"pivotValues": ["urn:li:sponsoredCampaign:123"],
"costInUsd": 209.449,
"start_date": "2023-01-02",
"end_date": "2023-01-02",
"string_of_pivot_values": "urn:li:sponsoredCampaign:123",
"sponsoredCampaign": "1111",
"pivot": "CAMPAIGN",
},
associated_slice=StreamSlice(
cursor_slice={"end_time": "2021-01-31", "start_time": "2021-01-01"},
partition={"campaign_id": 1111, "parent_slice": {"account_id": 1, "parent_slice": {}}},
extra_fields={"query_properties": ["dateRange", "pivotValues", "clicks", "impressions"]},
),
),
Record(
stream_name="ad_campaign_analytics",
data={
"clicks": 408.0,
"impressions": 20210.0,
"pivotValues": ["urn:li:sponsoredCampaign:123"],
"costInUsd": 509.98,
"start_date": "2023-01-03",
"end_date": "2023-01-03",
"string_of_pivot_values": "urn:li:sponsoredCampaign:123",
"sponsoredCampaign": "1111",
"pivot": "CAMPAIGN",
},
associated_slice=StreamSlice(
cursor_slice={"end_time": "2021-01-31", "start_time": "2021-01-01"},
partition={"campaign_id": 1111, "parent_slice": {"account_id": 1, "parent_slice": {}}},
extra_fields={"query_properties": ["dateRange", "pivotValues", "clicks", "impressions"]},
),
),
]
streams = get_source(config=config, catalog=catalog).streams(config=config)
ad_campaign_analytics_streams = [stream for stream in streams if stream.name == "ad_campaign_analytics"]
assert len(ad_campaign_analytics_streams) == 1
ad_campaign_analytics_stream = ad_campaign_analytics_streams[0]
requests_mock.get("https://api.linkedin.com/rest/adAccounts", json={"elements": [{"id": 1}]})
requests_mock.get(
"https://api.linkedin.com/rest/adAccounts/1/adCampaigns?q=search&search=(status:(values:List(ACTIVE,PAUSED,ARCHIVED,"
"COMPLETED,CANCELED,DRAFT,PENDING_DELETION,REMOVED)))",
json={"elements": [{"id": 1111, "lastModified": "2021-01-15"}]},
)
requests_mock.get(
"https://api.linkedin.com/rest/adAnalytics?q=analytics&campaigns=List(urn%3Ali%3AsponsoredCampaign%3A1111)&dateRange=(start:(year:2021,month:1,day:1),end:(year:2021,month:1,day:31))&fields=dateRange,pivotValues,clicks,impressions",
[
{"json": load_json_file("responses/ad_campaign_analytics/response_1.json")},
{"json": load_json_file("responses/ad_campaign_analytics/response_2.json")},
{"json": load_json_file("responses/ad_campaign_analytics/response_3.json")},
],
)
partitions = iter(ad_campaign_analytics_stream.generate_partitions())
partition_1 = next(partitions)
records = list(partition_1.read())
assert len(records) == 2
assert records == expected_records
| TestLinkedinAdsStream |
python | huggingface__transformers | src/transformers/models/audioflamingo3/modeling_audioflamingo3.py | {
"start": 16386,
"end": 17435
} | class ____(nn.Module):
"""
Audio adaptor (small MLP) that projects AudioFlamingo3Encoder features
to the LLM embedding space so they can replace `<sound>` tokens.
"""
def __init__(self, config: AudioFlamingo3Config):
super().__init__()
self.linear_1 = nn.Linear(
config.audio_config.hidden_size, config.text_config.hidden_size, bias=config.projector_bias
)
self.act = ACT2FN[config.projector_hidden_act]
self.linear_2 = nn.Linear(
config.text_config.hidden_size, config.text_config.hidden_size, bias=config.projector_bias
)
def forward(self, audio_features):
hidden_states = self.linear_1(audio_features)
hidden_states = self.act(hidden_states)
hidden_states = self.linear_2(hidden_states)
return hidden_states
@auto_docstring(
custom_intro="""
The AudioFlamingo3 model which consists of a fine-tuned Whisper encoder, a multi-modal projector and a Qwen2 language model.
"""
)
| AudioFlamingo3MultiModalProjector |
python | sqlalchemy__sqlalchemy | test/sql/test_operators.py | {
"start": 27528,
"end": 28118
} | class ____(_CustomComparatorTests, fixtures.TestBase):
def _add_override_factory(self):
class MyInteger(TypeDecorator):
impl = Integer
cache_ok = True
class comparator_factory(TypeDecorator.Comparator):
def __init__(self, expr):
super().__init__(expr)
def __add__(self, other):
return self.expr.op("goofy")(other)
def __and__(self, other):
return self.expr.op("goofy_and")(other)
return MyInteger
| TypeDecoratorComparatorTest |
python | ray-project__ray | python/ray/serve/_private/replica_result.py | {
"start": 1814,
"end": 8817
} | class ____(ReplicaResult):
def __init__(
self,
obj_ref_or_gen: Union[ray.ObjectRef, ray.ObjectRefGenerator],
metadata: RequestMetadata,
*,
with_rejection: bool = False,
):
self._obj_ref: Optional[ray.ObjectRef] = None
self._obj_ref_gen: Optional[ray.ObjectRefGenerator] = None
self._is_streaming: bool = metadata.is_streaming
self._request_id: str = metadata.request_id
self._object_ref_or_gen_sync_lock = threading.Lock()
self._lazy_object_ref_or_gen_asyncio_lock = None
self._with_rejection = with_rejection
self._rejection_response = None
if isinstance(obj_ref_or_gen, ray.ObjectRefGenerator):
self._obj_ref_gen = obj_ref_or_gen
else:
self._obj_ref = obj_ref_or_gen
if self._is_streaming:
assert (
self._obj_ref_gen is not None
), "An ObjectRefGenerator must be passed for streaming requests."
request_context = ray.serve.context._get_serve_request_context()
if request_context.cancel_on_parent_request_cancel:
# Keep track of in-flight requests.
self._response_id = generate_request_id()
ray.serve.context._add_in_flight_request(
request_context._internal_request_id, self._response_id, self
)
self.add_done_callback(
lambda _: ray.serve.context._remove_in_flight_request(
request_context._internal_request_id, self._response_id
)
)
@property
def _object_ref_or_gen_asyncio_lock(self) -> asyncio.Lock:
"""Lazy `asyncio.Lock` object."""
if self._lazy_object_ref_or_gen_asyncio_lock is None:
self._lazy_object_ref_or_gen_asyncio_lock = asyncio.Lock()
return self._lazy_object_ref_or_gen_asyncio_lock
def _process_response(f: Union[Callable, Coroutine]):
@wraps(f)
def wrapper(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except ray.exceptions.TaskCancelledError:
raise RequestCancelledError(self._request_id)
@wraps(f)
async def async_wrapper(self, *args, **kwargs):
try:
return await f(self, *args, **kwargs)
except ray.exceptions.TaskCancelledError:
raise asyncio.CancelledError()
if inspect.iscoroutinefunction(f):
return async_wrapper
else:
return wrapper
@_process_response
async def get_rejection_response(self) -> Optional[ReplicaQueueLengthInfo]:
"""Get the queue length info from the replica to handle rejection."""
assert (
self._with_rejection and self._obj_ref_gen is not None
), "get_rejection_response() can only be called when request rejection is enabled."
try:
if self._rejection_response is None:
response = await (await self._obj_ref_gen.__anext__())
self._rejection_response = pickle.loads(response)
return self._rejection_response
except asyncio.CancelledError as e:
# HTTP client disconnected or request was explicitly canceled.
logger.info(
"Cancelling request that has already been assigned to a replica."
)
self.cancel()
raise e from None
except TaskCancelledError:
raise asyncio.CancelledError()
@_process_response
def get(self, timeout_s: Optional[float]):
assert (
not self._is_streaming
), "get() can only be called on a unary ActorReplicaResult."
start_time_s = time.time()
object_ref = self.to_object_ref(timeout_s=timeout_s)
remaining_timeout_s = calculate_remaining_timeout(
timeout_s=timeout_s,
start_time_s=start_time_s,
curr_time_s=time.time(),
)
return ray.get(object_ref, timeout=remaining_timeout_s)
@_process_response
async def get_async(self):
assert (
not self._is_streaming
), "get_async() can only be called on a unary ActorReplicaResult."
return await (await self.to_object_ref_async())
@_process_response
def __next__(self):
assert (
self._is_streaming
), "next() can only be called on a streaming ActorReplicaResult."
next_obj_ref = self._obj_ref_gen.__next__()
return ray.get(next_obj_ref)
@_process_response
async def __anext__(self):
assert (
self._is_streaming
), "__anext__() can only be called on a streaming ActorReplicaResult."
next_obj_ref = await self._obj_ref_gen.__anext__()
return await next_obj_ref
def add_done_callback(self, callback: Callable):
if self._obj_ref_gen is not None:
self._obj_ref_gen.completed()._on_completed(callback)
else:
self._obj_ref._on_completed(callback)
def cancel(self):
if self._obj_ref_gen is not None:
ray.cancel(self._obj_ref_gen)
else:
ray.cancel(self._obj_ref)
def to_object_ref(self, *, timeout_s: Optional[float] = None) -> ray.ObjectRef:
assert (
not self._is_streaming
), "to_object_ref can only be called on a unary ReplicaActorResult."
# NOTE(edoakes): this section needs to be guarded with a lock and the resulting
# object ref cached in order to avoid calling `__next__()` to
# resolve to the underlying object ref more than once.
# See: https://github.com/ray-project/ray/issues/43879.
with self._object_ref_or_gen_sync_lock:
if self._obj_ref is None:
obj_ref = self._obj_ref_gen._next_sync(timeout_s=timeout_s)
if obj_ref.is_nil():
raise TimeoutError("Timed out resolving to ObjectRef.")
self._obj_ref = obj_ref
return self._obj_ref
async def to_object_ref_async(self) -> ray.ObjectRef:
assert (
not self._is_streaming
), "to_object_ref_async can only be called on a unary ReplicaActorResult."
# NOTE(edoakes): this section needs to be guarded with a lock and the resulting
# object ref cached in order to avoid calling `__anext__()` to
# resolve to the underlying object ref more than once.
# See: https://github.com/ray-project/ray/issues/43879.
async with self._object_ref_or_gen_asyncio_lock:
if self._obj_ref is None:
self._obj_ref = await self._obj_ref_gen.__anext__()
return self._obj_ref
def to_object_ref_gen(self) -> ray.ObjectRefGenerator:
assert (
self._is_streaming
), "to_object_ref_gen can only be called on a streaming ReplicaActorResult."
return self._obj_ref_gen
| ActorReplicaResult |
python | getsentry__sentry | tests/sentry/workflow_engine/processors/contexts/test_workflow_event_context.py | {
"start": 1132,
"end": 2793
} | class ____(WorkflowEventContextTestCase):
def test_set_and_get(self) -> None:
detector = self.create_detector()
organization = self.organization
environment = self.create_environment()
ctx_data = WorkflowEventContextData(
detector=detector,
organization=organization,
environment=environment,
)
WorkflowEventContext.set(ctx_data)
ctx = WorkflowEventContext.get()
assert ctx.detector == detector
assert ctx.organization == organization
assert ctx.environment == environment
def test_partial_set(self) -> None:
ctx_data = WorkflowEventContextData(
organization=self.organization,
)
self.ctx_token = WorkflowEventContext.set(ctx_data)
ctx = WorkflowEventContext.get()
assert ctx.detector is None
assert ctx.environment is None
assert ctx.organization == self.organization
def test_resetting_context(self) -> None:
detector = self.create_detector()
organization = self.organization
environment = self.create_environment()
self.ctx_token = WorkflowEventContext.set(
WorkflowEventContextData(
detector=detector,
organization=organization,
environment=environment,
)
)
# Reset context
WorkflowEventContext.reset(self.ctx_token)
self.ctx_token = None
ctx = WorkflowEventContext.get()
assert ctx.detector is None
assert ctx.organization is None
assert ctx.environment is None
| TestWorkflowEventContext |
python | kamyu104__LeetCode-Solutions | Python/minimum-time-to-kill-all-monsters.py | {
"start": 52,
"end": 690
} | class ____(object):
def minimumTime(self, power):
"""
:type power: List[int]
:rtype: int
"""
def ceil_divide(a, b):
return (a+b-1)//b
INF = float("inf")
dp = {0:0}
for gain in xrange(1, len(power)+1):
new_dp = collections.defaultdict(lambda:INF)
for mask in dp.iterkeys():
for i in xrange(len(power)):
if mask&(1<<i) == 0:
new_dp[mask|(1<<i)] = min(new_dp[mask|(1<<i)], dp[mask]+ceil_divide(power[i], gain))
dp = new_dp
return dp[(1<<len(power))-1]
| Solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.