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 | readthedocs__readthedocs.org | readthedocs/projects/forms.py | {
"start": 6728,
"end": 11238
} | class ____(PrevalidatedForm):
"""
Mixin that provides a method to setup the external builds option.
TODO: Remove this once we migrate to the new dashboard,
and we don't need to support the old project settings form.
"""
def has_supported_integration(self, integrations):
supported_types = {Integration.GITHUB_WEBHOOK, Integration.GITLAB_WEBHOOK}
for integration in integrations:
if integration.integration_type in supported_types:
return True
return False
def can_build_external_versions(self, integrations):
"""
Check if external versions can be enabled for this project.
A project can build external versions if:
- They are using GitHub or GitLab.
- The repository's webhook is setup to send pull request events.
If the integration's provider data isn't set,
it could mean that the user created the integration manually,
and doesn't have an account connected.
So we don't know for sure if the webhook is sending pull request events.
"""
for integration in integrations:
provider_data = integration.provider_data
if integration.integration_type == Integration.GITHUB_WEBHOOK and (
not provider_data or "pull_request" in provider_data.get("events", [])
):
return True
if integration.integration_type == Integration.GITLAB_WEBHOOK and (
not provider_data or provider_data.get("merge_requests_events")
):
return True
return False
def setup_external_builds_option(self):
"""Disable the external builds option if the project doesn't meet the requirements."""
if (
settings.ALLOW_PRIVATE_REPOS
and self.instance.remote_repository
and not self.instance.remote_repository.private
):
self.fields["external_builds_privacy_level"].disabled = True
# TODO use a proper error/warning instead of help text for error states
help_text = _(
"We have detected that this project is public, pull request previews are set to public."
)
self.fields["external_builds_privacy_level"].help_text = help_text
def clean_prevalidation(self):
"""Disable the external builds option if the project doesn't meet the requirements."""
# If the project is attached to a GitHub app integration,
# it will always be able to build external versions.
if self.instance.is_github_app_project:
return
integrations = list(self.instance.integrations.all())
has_supported_integration = self.has_supported_integration(integrations)
can_build_external_versions = self.can_build_external_versions(integrations)
# External builds are supported for this project,
# don't disable the option.
if has_supported_integration and can_build_external_versions:
return
msg = None
url = reverse("projects_integrations", args=[self.instance.slug])
if not has_supported_integration:
msg = _(
"To build from pull requests you need a "
f'GitHub or GitLab <a href="{url}">integration</a>.'
)
if has_supported_integration and not can_build_external_versions:
# If there is only one integration, link directly to it.
if len(integrations) == 1:
url = reverse(
"projects_integrations_detail",
args=[self.instance.slug, integrations[0].pk],
)
msg = _(
"To build from pull requests your repository's webhook "
"needs to send pull request events. "
f'Try to <a href="{url}">resync your integration</a>.'
)
if msg:
# TODO use a proper error/warning instead of help text for error states
field = self.fields["external_builds_enabled"]
field.disabled = True
field.help_text = f"{msg} {field.help_text}"
# Don't raise an error on the Update form,
# to keep backwards compat
if not self.fields.get("name"):
raise RichValidationError(
msg,
header=_("Pull request builds not supported"),
)
| ProjectPRBuildsMixin |
python | readthedocs__readthedocs.org | readthedocs/builds/querysets.py | {
"start": 5041,
"end": 5131
} | class ____(SettingsOverrideObject):
_default_class = VersionQuerySetBase
| VersionQuerySet |
python | pytorch__pytorch | test/test_dynamic_shapes.py | {
"start": 2928,
"end": 6596
} | class ____(torch.Tensor):
@staticmethod
def __new__(
cls,
sym_shape,
sym_strides,
dtype,
layout,
requires_grad,
device,
storage_offset=0,
):
# TODO: this is wrong in general
sym_stride = create_contiguous(sym_shape)
r = torch.Tensor._make_wrapper_subclass(
cls,
sym_shape,
sym_stride,
storage_offset,
dtype=dtype,
layout=layout,
requires_grad=requires_grad,
device=device,
)
return r
__torch_function__ = _disabled_torch_function_impl
def new_empty(self, shape):
return FakeSymbolicTensor(
shape, None, self.dtype, self.layout, self.requires_grad, self.device
)
@classmethod
def __torch_dispatch__(cls, func_overload, types, args=(), kwargs=None):
if func_overload in meta_funcs:
return meta_funcs[func_overload](*args, **kwargs)
if func_overload == torch.ops.aten.new_empty.default:
self = args[0]
shape = args[1]
return FakeSymbolicTensor(
shape,
self.stride(),
self.dtype,
self.layout,
self.requires_grad,
self.device,
)
raise RuntimeError(f"operator {func_overload} not supported")
def create_symbolic_tensor(name, arg, shape_env, source=None, dynamic_dims=None):
from torch._dynamo.source import ConstantSource
if source is None:
source = ConstantSource(name)
constraint_dims = [None] * arg.dim()
if dynamic_dims is None:
dynamic_dims = [DimDynamic.DUCK] * arg.dim()
(
sym_shapes,
sym_strides,
sym_storage_offset,
) = shape_env.create_symbolic_sizes_strides_storage_offset(
arg,
source=source,
symbolic_context=StatelessSymbolicContext(
dynamic_sizes=dynamic_dims, constraint_sizes=constraint_dims
),
)
return FakeSymbolicTensor(
sym_shapes,
sym_strides,
arg.dtype,
arg.layout,
arg.requires_grad,
arg.device,
sym_storage_offset,
)
def create_fake_tensor_with_dynamic_size(x, shape_env, dynamic_sizes, dynamic_strides):
from torch._subclasses.fake_tensor import FakeTensorMode
with FakeTensorMode(shape_env=shape_env) as fake_mode:
return fake_mode.from_tensor(
x,
symbolic_context=StatelessSymbolicContext(
dynamic_sizes=dynamic_sizes,
dynamic_strides=dynamic_strides,
),
)
def create_symtype(cls, pytype, shape_env, val, duck=True, **kwargs):
from torch._dynamo.source import ConstantSource
symbol = shape_env.create_symbol(
val,
source=ConstantSource(f"__testing_only{len(shape_env.var_to_val)}"),
dynamic_dim=DimDynamic.DUCK if duck else DimDynamic.DYNAMIC,
constraint_dim=None,
**kwargs,
)
return cls(SymNode(symbol, shape_env, pytype, hint=val))
# TODO: default duck to False
def create_symint(shape_env, i: int, duck=True, **kwargs) -> SymInt:
return create_symtype(SymInt, int, shape_env, i, duck=duck, **kwargs)
def create_symbool(shape_env, b: bool) -> SymBool:
return create_symtype(SymBool, bool, shape_env, b)
def create_symfloat(shape_env, f: float) -> SymFloat:
return create_symtype(SymFloat, float, shape_env, f)
@skipIfTorchDynamo(
"Creating ShapeEnv fails for confusing reasons (also we never expect dynamo to see code like this)"
)
| FakeSymbolicTensor |
python | cherrypy__cherrypy | cherrypy/test/benchmark.py | {
"start": 1424,
"end": 3161
} | class ____:
"""Test web app."""
@cherrypy.expose
def index(self):
"""Produce HTTP response body of test app index URI."""
return """<html>
<head>
<title>CherryPy Benchmark</title>
</head>
<body>
<ul>
<li><a href="hello">Hello, world! (14 byte dynamic)</a></li>
<li><a href="static/index.html">Static file (14 bytes static)</a></li>
<li><form action="sizer">Response of length:
<input type='text' name='size' value='10' /></form>
</li>
</ul>
</body>
</html>"""
@cherrypy.expose
def hello(self):
"""Render a "Hello world!" message on ``/hello`` URI."""
return 'Hello, world\r\n'
@cherrypy.expose
def sizer(self, size):
"""Send a cached sized response."""
resp = size_cache.get(size, None)
if resp is None:
size_cache[size] = resp = 'X' * int(size)
return resp
def init():
"""Configure the test server."""
cherrypy.config.update(
{
'log.error.file': '',
'environment': 'production',
'server.socket_host': '127.0.0.1',
'server.socket_port': 54583,
'server.max_request_header_size': 0,
'server.max_request_body_size': 0,
},
)
# Cheat mode on ;)
del cherrypy.config['tools.log_tracebacks.on']
del cherrypy.config['tools.log_headers.on']
del cherrypy.config['tools.trailing_slash.on']
appconf = {
'/static': {
'tools.staticdir.on': True,
'tools.staticdir.dir': 'static',
'tools.staticdir.root': curdir,
},
}
globals().update(
app=cherrypy.tree.mount(Root(), SCRIPT_NAME, appconf),
)
| Root |
python | getsentry__sentry | src/sentry/migrations/0936_prompts_activity_index.py | {
"start": 155,
"end": 1558
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# of a table.
# Here are some things that make sense to mark as post deployment:
# - Large data migrations. Typically we want these to be run manually so that they can be
# monitored and not block the deploy for a long period of time while they run.
# - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to
# run this outside deployments so that we don't block them. Note that while adding an index
# is a schema change, it's completely safe to run the operation after the code has deployed.
# Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment
is_post_deployment = False
dependencies = [
("sentry", "0935_drop_old_openperiod_exclusion_constraint"),
]
operations = [
migrations.AddIndex(
model_name="promptsactivity",
index=models.Index(
fields=["feature", "organization_id", "project_id"],
name="sentry_prom_feature_56978d_idx",
),
),
]
| Migration |
python | pytorch__pytorch | test/test_pytree.py | {
"start": 29920,
"end": 54884
} | class ____(TestCase):
def test_deprecated_register_pytree_node(self):
class DummyType:
def __init__(self, x, y):
self.x = x
self.y = y
with self.assertWarnsRegex(
FutureWarning, "torch.utils._pytree._register_pytree_node"
):
python_pytree._register_pytree_node(
DummyType,
lambda dummy: ([dummy.x, dummy.y], None),
lambda xs, _: DummyType(*xs),
)
with self.assertWarnsRegex(UserWarning, "already registered"):
python_pytree._register_pytree_node(
DummyType,
lambda dummy: ([dummy.x, dummy.y], None),
lambda xs, _: DummyType(*xs),
)
def test_import_pytree_doesnt_import_optree(self):
# importing torch.utils._pytree shouldn't import optree.
# only importing torch.utils._cxx_pytree should.
script = """
import sys
import torch
import torch.utils._pytree
assert "torch.utils._pytree" in sys.modules
if "torch.utils._cxx_pytree" in sys.modules:
raise RuntimeError("importing torch.utils._pytree should not import torch.utils._cxx_pytree")
if "optree" in sys.modules:
raise RuntimeError("importing torch.utils._pytree should not import optree")
"""
try:
subprocess.check_output(
[sys.executable, "-c", script],
stderr=subprocess.STDOUT,
# On Windows, opening the subprocess with the default CWD makes `import torch`
# fail, so just set CWD to this script's directory
cwd=os.path.dirname(os.path.realpath(__file__)),
)
except subprocess.CalledProcessError as e:
self.fail(
msg=(
"Subprocess exception while attempting to run test: "
+ e.output.decode("utf-8")
)
)
def test_treespec_equality(self):
self.assertEqual(
python_pytree.treespec_leaf(),
python_pytree.treespec_leaf(),
)
self.assertEqual(
python_pytree.TreeSpec(list, None, []),
python_pytree.TreeSpec(list, None, []),
)
self.assertEqual(
python_pytree.TreeSpec(list, None, [python_pytree.treespec_leaf()]),
python_pytree.TreeSpec(list, None, [python_pytree.treespec_leaf()]),
)
self.assertFalse(
python_pytree.TreeSpec(tuple, None, [])
== python_pytree.TreeSpec(list, None, []),
)
self.assertTrue(
python_pytree.TreeSpec(tuple, None, [])
!= python_pytree.TreeSpec(list, None, []),
)
def test_treespec_repr(self):
# Check that it looks sane
tree = (0, [0, 0, [0]])
spec = python_pytree.tree_structure(tree)
self.assertEqual(
repr(spec),
(
"TreeSpec(tuple, None, [*,\n"
" TreeSpec(list, None, [*,\n"
" *,\n"
" TreeSpec(list, None, [*])])])"
),
)
@parametrize(
"spec",
[
# python_pytree.tree_structure([])
python_pytree.TreeSpec(list, None, []),
# python_pytree.tree_structure(())
python_pytree.TreeSpec(tuple, None, []),
# python_pytree.tree_structure({})
python_pytree.TreeSpec(dict, [], []),
# python_pytree.tree_structure([0])
python_pytree.TreeSpec(list, None, [python_pytree.treespec_leaf()]),
# python_pytree.tree_structure([0, 1])
python_pytree.TreeSpec(
list,
None,
[python_pytree.treespec_leaf(), python_pytree.treespec_leaf()],
),
# python_pytree.tree_structure((0, 1, 2))
python_pytree.TreeSpec(
tuple,
None,
[
python_pytree.treespec_leaf(),
python_pytree.treespec_leaf(),
python_pytree.treespec_leaf(),
],
),
# python_pytree.tree_structure({"a": 0, "b": 1, "c": 2})
python_pytree.TreeSpec(
dict,
["a", "b", "c"],
[
python_pytree.treespec_leaf(),
python_pytree.treespec_leaf(),
python_pytree.treespec_leaf(),
],
),
# python_pytree.tree_structure(OrderedDict([("a", (0, 1)), ("b", 2), ("c", {"a": 3, "b": 4, "c": 5})])
python_pytree.TreeSpec(
OrderedDict,
["a", "b", "c"],
[
python_pytree.TreeSpec(
tuple,
None,
[python_pytree.treespec_leaf(), python_pytree.treespec_leaf()],
),
python_pytree.treespec_leaf(),
python_pytree.TreeSpec(
dict,
["a", "b", "c"],
[
python_pytree.treespec_leaf(),
python_pytree.treespec_leaf(),
python_pytree.treespec_leaf(),
],
),
],
),
# python_pytree.tree_structure([(0, 1, [2, 3])])
python_pytree.TreeSpec(
list,
None,
[
python_pytree.TreeSpec(
tuple,
None,
[
python_pytree.treespec_leaf(),
python_pytree.treespec_leaf(),
python_pytree.TreeSpec(
list,
None,
[
python_pytree.treespec_leaf(),
python_pytree.treespec_leaf(),
],
),
],
),
],
),
# python_pytree.tree_structure(defaultdict(list, {"a": [0, 1], "b": [1, 2], "c": {}}))
python_pytree.TreeSpec(
defaultdict,
[list, ["a", "b", "c"]],
[
python_pytree.TreeSpec(
list,
None,
[python_pytree.treespec_leaf(), python_pytree.treespec_leaf()],
),
python_pytree.TreeSpec(
list,
None,
[python_pytree.treespec_leaf(), python_pytree.treespec_leaf()],
),
python_pytree.TreeSpec(dict, [], []),
],
),
],
)
def test_pytree_serialize(self, spec):
# Ensure that the spec is valid
self.assertEqual(
spec,
python_pytree.tree_structure(
python_pytree.tree_unflatten([0] * spec.num_leaves, spec)
),
)
serialized_spec = python_pytree.treespec_dumps(spec)
self.assertIsInstance(serialized_spec, str)
self.assertEqual(spec, python_pytree.treespec_loads(serialized_spec))
def test_pytree_serialize_defaultdict_enum(self):
spec = python_pytree.TreeSpec(
defaultdict,
[list, [TestEnum.A]],
[
python_pytree.TreeSpec(
list,
None,
[
python_pytree.treespec_leaf(),
],
),
],
)
serialized_spec = python_pytree.treespec_dumps(spec)
self.assertIsInstance(serialized_spec, str)
def test_pytree_serialize_enum(self):
spec = python_pytree.TreeSpec(dict, TestEnum.A, [python_pytree.treespec_leaf()])
serialized_spec = python_pytree.treespec_dumps(spec)
self.assertIsInstance(serialized_spec, str)
def test_pytree_serialize_namedtuple(self):
Point1 = namedtuple("Point1", ["x", "y"])
python_pytree._register_namedtuple(
Point1,
serialized_type_name="test_pytree.test_pytree_serialize_namedtuple.Point1",
)
spec = python_pytree.tree_structure(Point1(1, 2))
self.assertIs(spec.type, namedtuple)
roundtrip_spec = python_pytree.treespec_loads(
python_pytree.treespec_dumps(spec)
)
self.assertEqual(spec, roundtrip_spec)
class Point2(NamedTuple):
x: int
y: int
python_pytree._register_namedtuple(
Point2,
serialized_type_name="test_pytree.test_pytree_serialize_namedtuple.Point2",
)
spec = python_pytree.tree_structure(Point2(1, 2))
self.assertIs(spec.type, namedtuple)
roundtrip_spec = python_pytree.treespec_loads(
python_pytree.treespec_dumps(spec)
)
self.assertEqual(spec, roundtrip_spec)
class Point3(Point2):
pass
python_pytree._register_namedtuple(
Point3,
serialized_type_name="test_pytree.test_pytree_serialize_namedtuple.Point3",
)
spec = python_pytree.tree_structure(Point3(1, 2))
self.assertIs(spec.type, namedtuple)
roundtrip_spec = python_pytree.treespec_loads(
python_pytree.treespec_dumps(spec)
)
self.assertEqual(spec, roundtrip_spec)
def test_pytree_serialize_namedtuple_bad(self):
DummyType = namedtuple("DummyType", ["x", "y"])
spec = python_pytree.tree_structure(DummyType(1, 2))
with self.assertRaisesRegex(
NotImplementedError, "Please register using `_register_namedtuple`"
):
python_pytree.treespec_dumps(spec)
def test_pytree_custom_type_serialize_bad(self):
class DummyType:
def __init__(self, x, y):
self.x = x
self.y = y
python_pytree.register_pytree_node(
DummyType,
lambda dummy: ([dummy.x, dummy.y], None),
lambda xs, _: DummyType(*xs),
)
spec = python_pytree.tree_structure(DummyType(1, 2))
with self.assertRaisesRegex(
NotImplementedError, "No registered serialization name"
):
python_pytree.treespec_dumps(spec)
def test_pytree_custom_type_serialize(self):
class DummyType:
def __init__(self, x, y):
self.x = x
self.y = y
python_pytree.register_pytree_node(
DummyType,
lambda dummy: ([dummy.x, dummy.y], None),
lambda xs, _: DummyType(*xs),
serialized_type_name="test_pytree_custom_type_serialize.DummyType",
to_dumpable_context=lambda context: "moo",
from_dumpable_context=lambda dumpable_context: None,
)
spec = python_pytree.tree_structure(DummyType(1, 2))
serialized_spec = python_pytree.treespec_dumps(spec, 1)
self.assertIn("moo", serialized_spec)
roundtrip_spec = python_pytree.treespec_loads(serialized_spec)
self.assertEqual(roundtrip_spec, spec)
def test_pytree_serialize_register_bad(self):
class DummyType:
def __init__(self, x, y):
self.x = x
self.y = y
with self.assertRaisesRegex(
ValueError, "Both to_dumpable_context and from_dumpable_context"
):
python_pytree.register_pytree_node(
DummyType,
lambda dummy: ([dummy.x, dummy.y], None),
lambda xs, _: DummyType(*xs),
serialized_type_name="test_pytree_serialize_register_bad.DummyType",
to_dumpable_context=lambda context: "moo",
)
def test_pytree_context_serialize_bad(self):
class DummyType:
def __init__(self, x, y):
self.x = x
self.y = y
python_pytree.register_pytree_node(
DummyType,
lambda dummy: ([dummy.x, dummy.y], None),
lambda xs, _: DummyType(*xs),
serialized_type_name="test_pytree_serialize_serialize_bad.DummyType",
to_dumpable_context=lambda context: DummyType,
from_dumpable_context=lambda dumpable_context: None,
)
spec = python_pytree.tree_structure(DummyType(1, 2))
with self.assertRaisesRegex(
TypeError, "Object of type type is not JSON serializable"
):
python_pytree.treespec_dumps(spec)
def test_pytree_serialize_bad_protocol(self):
import json
Point = namedtuple("Point", ["x", "y"])
spec = python_pytree.tree_structure(Point(1, 2))
python_pytree._register_namedtuple(
Point,
serialized_type_name="test_pytree.test_pytree_serialize_bad_protocol.Point",
)
with self.assertRaisesRegex(ValueError, "Unknown protocol"):
python_pytree.treespec_dumps(spec, -1)
serialized_spec = python_pytree.treespec_dumps(spec)
_, data = json.loads(serialized_spec)
bad_protocol_serialized_spec = json.dumps((-1, data))
with self.assertRaisesRegex(ValueError, "Unknown protocol"):
python_pytree.treespec_loads(bad_protocol_serialized_spec)
def test_saved_serialized(self):
# python_pytree.tree_structure(OrderedDict([(1, (0, 1)), (2, 2), (3, {4: 3, 5: 4, 6: 5})]))
complicated_spec = python_pytree.TreeSpec(
OrderedDict,
[1, 2, 3],
[
python_pytree.TreeSpec(
tuple,
None,
[python_pytree.treespec_leaf(), python_pytree.treespec_leaf()],
),
python_pytree.treespec_leaf(),
python_pytree.TreeSpec(
dict,
[4, 5, 6],
[
python_pytree.treespec_leaf(),
python_pytree.treespec_leaf(),
python_pytree.treespec_leaf(),
],
),
],
)
# Ensure that the spec is valid
self.assertEqual(
complicated_spec,
python_pytree.tree_structure(
python_pytree.tree_unflatten(
[0] * complicated_spec.num_leaves, complicated_spec
)
),
)
serialized_spec = python_pytree.treespec_dumps(complicated_spec)
saved_spec = (
'[1, {"type": "collections.OrderedDict", "context": "[1, 2, 3]", '
'"children_spec": [{"type": "builtins.tuple", "context": "null", '
'"children_spec": [{"type": null, "context": null, '
'"children_spec": []}, {"type": null, "context": null, '
'"children_spec": []}]}, {"type": null, "context": null, '
'"children_spec": []}, {"type": "builtins.dict", "context": '
'"[4, 5, 6]", "children_spec": [{"type": null, "context": null, '
'"children_spec": []}, {"type": null, "context": null, "children_spec": '
'[]}, {"type": null, "context": null, "children_spec": []}]}]}]'
)
self.assertEqual(serialized_spec, saved_spec)
self.assertEqual(complicated_spec, python_pytree.treespec_loads(saved_spec))
def test_tree_map_with_path(self):
tree = [{i: i for i in range(10)}]
all_zeros = python_pytree.tree_map_with_path(
lambda kp, val: val - kp[1].key + kp[0].idx, tree
)
self.assertEqual(all_zeros, [dict.fromkeys(range(10), 0)])
def test_dataclass(self):
@dataclass
class Data:
a: torch.Tensor
b: str = "moo"
c: Optional[str] = None
d: str = field(init=False, default="")
python_pytree.register_dataclass(Data)
old_data = Data(torch.tensor(3), "b", "c")
old_data.d = "d"
new_data = python_pytree.tree_map(lambda x: x, old_data)
self.assertEqual(new_data.a, torch.tensor(3))
self.assertEqual(new_data.b, "b")
self.assertEqual(new_data.c, "c")
self.assertEqual(new_data.d, "")
python_pytree._deregister_pytree_node(Data)
with self.assertRaisesRegex(ValueError, "Missing fields"):
python_pytree.register_dataclass(Data, field_names=["a", "b"])
with self.assertRaisesRegex(ValueError, "Unexpected fields"):
python_pytree.register_dataclass(Data, field_names=["a", "b", "e"])
with self.assertRaisesRegex(ValueError, "Unexpected fields"):
python_pytree.register_dataclass(Data, field_names=["a", "b", "c", "d"])
python_pytree.register_dataclass(
Data, field_names=["a"], drop_field_names=["b", "c"]
)
old_data = Data(torch.tensor(3), "b", "c")
new_data = python_pytree.tree_map(lambda x: x, old_data)
self.assertEqual(new_data.a, torch.tensor(3))
self.assertEqual(new_data.b, "moo")
self.assertEqual(new_data.c, None)
python_pytree._deregister_pytree_node(Data)
def test_register_dataclass_class(self):
class CustomClass:
def __init__(self, x, y):
self.x = x
self.y = y
with self.assertRaisesRegex(ValueError, "field_names must be specified"):
python_pytree.register_dataclass(CustomClass)
python_pytree.register_dataclass(CustomClass, field_names=["x", "y"])
c = CustomClass(torch.tensor(0), torch.tensor(1))
mapped = python_pytree.tree_map(lambda x: x + 1, c)
self.assertEqual(mapped.x, torch.tensor(1))
self.assertEqual(mapped.y, torch.tensor(2))
def test_constant(self):
# Either use `frozen=True` or `unsafe_hash=True` so we have a
# non-default `__hash__`.
@dataclass(unsafe_hash=True)
class Config:
norm: str
python_pytree.register_constant(Config)
config = Config("l1")
elements, spec = python_pytree.tree_flatten(config)
self.assertEqual(elements, [])
self.assertEqual(spec.context.value, config)
def test_constant_default_eq_error(self):
class Config:
def __init__(self, norm: str):
self.norm = norm
try:
python_pytree.register_constant(Config)
self.assertFalse(True) # must raise error before this
except TypeError as e:
msg = "register_constant(cls) expects `cls` to have a non-default `__eq__` implementation."
self.assertIn(msg, str(e))
def test_constant_default_hash_error(self):
class Config:
def __init__(self, norm: str):
self.norm = norm
def __eq__(self, other):
return self.norm == other.norm
try:
python_pytree.register_constant(Config)
self.assertFalse(True) # must raise error before this
except TypeError as e:
msg = "register_constant(cls) expects `cls` to have a non-default `__hash__` implementation."
self.assertIn(msg, str(e))
def test_tree_map_with_path_multiple_trees(self):
@dataclass
class ACustomPytree:
x: Any
y: Any
z: Any
tree1 = [ACustomPytree(x=12, y={"cin": [1, 4, 10], "bar": 18}, z="leaf"), 5]
tree2 = [ACustomPytree(x=2, y={"cin": [2, 2, 2], "bar": 2}, z="leaf"), 2]
python_pytree.register_pytree_node(
ACustomPytree,
flatten_fn=lambda f: ([f.x, f.y], f.z),
unflatten_fn=lambda xy, z: ACustomPytree(xy[0], xy[1], z),
flatten_with_keys_fn=lambda f: ((("x", f.x), ("y", f.y)), f.z),
)
from_two_trees = python_pytree.tree_map_with_path(
lambda kp, a, b: a + b, tree1, tree2
)
from_one_tree = python_pytree.tree_map(lambda a: a + 2, tree1)
self.assertEqual(from_two_trees, from_one_tree)
def test_tree_flatten_with_path_is_leaf(self):
leaf_dict = {"foo": [(3)]}
tree = (["hello", [1, 2], leaf_dict],)
key_leaves, _ = python_pytree.tree_flatten_with_path(
tree, is_leaf=lambda x: isinstance(x, dict)
)
self.assertTrue(key_leaves[-1][1] is leaf_dict)
def test_tree_flatten_with_path_roundtrip(self):
class ANamedTuple(NamedTuple):
x: torch.Tensor
y: int
z: str
@dataclass
class ACustomPytree:
x: Any
y: Any
z: Any
python_pytree.register_pytree_node(
ACustomPytree,
flatten_fn=lambda f: ([f.x, f.y], f.z),
unflatten_fn=lambda xy, z: ACustomPytree(xy[0], xy[1], z),
flatten_with_keys_fn=lambda f: ((("x", f.x), ("y", f.y)), f.z),
)
SOME_PYTREES = [
(None,),
["hello", [1, 2], {"foo": [(3)]}],
[ANamedTuple(x=torch.rand(2, 3), y=1, z="foo")],
[ACustomPytree(x=12, y={"cin": [1, 4, 10], "bar": 18}, z="leaf"), 5],
]
for tree in SOME_PYTREES:
key_leaves, spec = python_pytree.tree_flatten_with_path(tree)
actual = python_pytree.tree_unflatten(
[leaf for _, leaf in key_leaves], spec
)
self.assertEqual(actual, tree)
def test_tree_leaves_with_path(self):
class ANamedTuple(NamedTuple):
x: torch.Tensor
y: int
z: str
@dataclass
class ACustomPytree:
x: Any
y: Any
z: Any
python_pytree.register_pytree_node(
ACustomPytree,
flatten_fn=lambda f: ([f.x, f.y], f.z),
unflatten_fn=lambda xy, z: ACustomPytree(xy[0], xy[1], z),
flatten_with_keys_fn=lambda f: ((("x", f.x), ("y", f.y)), f.z),
)
SOME_PYTREES = [
(None,),
["hello", [1, 2], {"foo": [(3)]}],
[ANamedTuple(x=torch.rand(2, 3), y=1, z="foo")],
[ACustomPytree(x=12, y={"cin": [1, 4, 10], "bar": 18}, z="leaf"), 5],
]
for tree in SOME_PYTREES:
flat_out, _ = python_pytree.tree_flatten_with_path(tree)
leaves_out = python_pytree.tree_leaves_with_path(tree)
self.assertEqual(flat_out, leaves_out)
def test_key_str(self):
class ANamedTuple(NamedTuple):
x: str
y: int
tree = (["hello", [1, 2], {"foo": [(3)], "bar": [ANamedTuple(x="baz", y=10)]}],)
flat, _ = python_pytree.tree_flatten_with_path(tree)
paths = [f"{python_pytree.keystr(kp)}: {val}" for kp, val in flat]
self.assertEqual(
paths,
[
"[0][0]: hello",
"[0][1][0]: 1",
"[0][1][1]: 2",
"[0][2]['foo'][0]: 3",
"[0][2]['bar'][0].x: baz",
"[0][2]['bar'][0].y: 10",
],
)
def test_flatten_flatten_with_key_consistency(self):
"""Check that flatten and flatten_with_key produces consistent leaves/context."""
reg = python_pytree.SUPPORTED_NODES
EXAMPLE_TREE = {
list: [1, 2, 3],
tuple: (1, 2, 3),
dict: {"foo": 1, "bar": 2},
namedtuple: namedtuple("ANamedTuple", ["x", "y"])(1, 2),
OrderedDict: OrderedDict([("foo", 1), ("bar", 2)]),
defaultdict: defaultdict(int, {"foo": 1, "bar": 2}),
deque: deque([1, 2, 3]),
torch.Size: torch.Size([1, 2, 3]),
immutable_dict: immutable_dict({"foo": 1, "bar": 2}),
immutable_list: immutable_list([1, 2, 3]),
}
for typ in reg:
example = EXAMPLE_TREE.get(typ)
if example is None:
continue
flat_with_path, spec1 = python_pytree.tree_flatten_with_path(example)
flat, spec2 = python_pytree.tree_flatten(example)
self.assertEqual(flat, [x[1] for x in flat_with_path])
self.assertEqual(spec1, spec2)
def test_key_access(self):
class ANamedTuple(NamedTuple):
x: str
y: int
tree = (["hello", [1, 2], {"foo": [(3)], "bar": [ANamedTuple(x="baz", y=10)]}],)
flat, _ = python_pytree.tree_flatten_with_path(tree)
for kp, val in flat:
self.assertEqual(python_pytree.key_get(tree, kp), val)
| TestPythonPytree |
python | huggingface__transformers | src/transformers/models/patchtst/modeling_patchtst.py | {
"start": 14051,
"end": 16540
} | class ____(nn.Module):
"""
Class to perform random or forecast masking.
Parameters:
config (`PatchTSTConfig`): model config
Returns:
x_mask (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`)
Masked patched input
mask (`torch.Tensor` of shape `(batch_size, num_channels, num_patches)`)
Bool tensor indicating True on masked points
"""
def __init__(self, config: PatchTSTConfig):
super().__init__()
self.random_mask_ratio = config.random_mask_ratio
self.channel_consistent_masking = config.channel_consistent_masking
self.mask_type = config.mask_type
self.num_forecast_mask_patches = config.num_forecast_mask_patches
self.unmasked_channel_indices = config.unmasked_channel_indices
self.mask_value = config.mask_value
if self.unmasked_channel_indices is not None:
self.unmasked_channel_indices = sorted(self.unmasked_channel_indices)
def forward(self, patch_input: torch.Tensor):
"""
Parameters:
patch_input (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`, *required*):
Patch input
Return:
masked_input (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`)
Masked patched input
mask (`torch.Tensor` of shape `(batch_size, num_channels, num_patches)`)
Bool tensor indicating True on masked points
"""
if self.mask_type == "random":
masked_input, mask = random_masking(
inputs=patch_input,
mask_ratio=self.random_mask_ratio,
unmasked_channel_indices=self.unmasked_channel_indices,
channel_consistent_masking=self.channel_consistent_masking,
mask_value=self.mask_value,
)
elif self.mask_type == "forecast":
masked_input, mask = forecast_masking(
inputs=patch_input,
num_forecast_mask_patches=self.num_forecast_mask_patches,
unmasked_channel_indices=self.unmasked_channel_indices,
mask_value=self.mask_value,
)
else:
raise ValueError(f"Invalid mask type {self.mask_type}.")
# mask: [bs x num_input_channels x num_patch]
mask = mask.bool()
return masked_input, mask
| PatchTSTMasking |
python | doocs__leetcode | solution/2500-2599/2571.Minimum Operations to Reduce an Integer to 0/Solution.py | {
"start": 0,
"end": 360
} | class ____:
def minOperations(self, n: int) -> int:
ans = cnt = 0
while n:
if n & 1:
cnt += 1
elif cnt:
ans += 1
cnt = 0 if cnt == 1 else 1
n >>= 1
if cnt == 1:
ans += 1
elif cnt > 1:
ans += 2
return ans
| Solution |
python | huggingface__transformers | tests/models/gemma3/test_modeling_gemma3.py | {
"start": 1921,
"end": 2180
} | class ____(CausalLMModelTester):
if is_torch_available():
base_model_class = Gemma3TextModel
causal_lm_class = Gemma3ForCausalLM
sequence_classification_class = Gemma3TextForSequenceClassification
@require_torch
| Gemma3TextModelTester |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 2309,
"end": 2491
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("ALL", "DIRECT", "OUTSIDE")
| CollaboratorAffiliation |
python | huggingface__transformers | tests/models/splinter/test_tokenization_splinter.py | {
"start": 754,
"end": 2747
} | class ____(TokenizerTesterMixin, unittest.TestCase):
tokenizer_class = SplinterTokenizer
from_pretrained_id = "tau/splinter-base"
test_tokenizer_from_extractor = (
False # Splinter already only provides a vocab.txt file, so we don't need to extract vocab to retest this
)
integration_expected_tokens = ['This', 'is', 'a', 'test', '[UNK]', 'I', 'was', 'born', 'in', '92', '##00', '##0', ',', 'and', 'this', 'is', 'f', '##als', '##é', '.', '生', '[UNK]', '[UNK]', '真', '[UNK]', '[UNK]', 'Hi', 'Hello', 'Hi', 'Hello', 'Hello', '<', 's', '>', 'hi', '<', 's', '>', 'there', 'The', 'following', 'string', 'should', 'be', 'properly', 'encoded', ':', 'Hello', '.', 'But', 'i', '##rd', 'and', '[UNK]', 'i', '##rd', '[UNK]', 'Hey', 'how', 'are', 'you', 'doing'] # fmt: skip
integration_expected_token_ids = [1188, 1110, 170, 2774, 100, 146, 1108, 1255, 1107, 5556, 7629, 1568, 117, 1105, 1142, 1110, 175, 7264, 2744, 119, 1056, 100, 100, 1061, 100, 100, 8790, 8667, 8790, 8667, 8667, 133, 188, 135, 20844, 133, 188, 135, 1175, 1109, 1378, 5101, 1431, 1129, 7513, 12544, 131, 8667, 119, 1252, 178, 2956, 1105, 100, 178, 2956, 100, 4403, 1293, 1132, 1128, 1833] # fmt: skip
expected_tokens_from_ids = ['This', 'is', 'a', 'test', '[UNK]', 'I', 'was', 'born', 'in', '92', '##00', '##0', ',', 'and', 'this', 'is', 'f', '##als', '##é', '.', '生', '[UNK]', '[UNK]', '真', '[UNK]', '[UNK]', 'Hi', 'Hello', 'Hi', 'Hello', 'Hello', '<', 's', '>', 'hi', '<', 's', '>', 'there', 'The', 'following', 'string', 'should', 'be', 'properly', 'encoded', ':', 'Hello', '.', 'But', 'i', '##rd', 'and', '[UNK]', 'i', '##rd', '[UNK]', 'Hey', 'how', 'are', 'you', 'doing'] # fmt: skip
integration_expected_decoded_text = "This is a test [UNK] I was born in 92000, and this is falsé. 生 [UNK] [UNK] 真 [UNK] [UNK] Hi Hello Hi Hello Hello < s > hi < s > there The following string should be properly encoded : Hello. But ird and [UNK] ird [UNK] Hey how are you doing"
| SplinterTokenizationTest |
python | sanic-org__sanic | sanic/mixins/middleware.py | {
"start": 336,
"end": 8389
} | class ____(metaclass=SanicMeta):
router: Router
def __init__(self, *args, **kwargs) -> None:
self._future_middleware: list[FutureMiddleware] = []
def _apply_middleware(self, middleware: FutureMiddleware):
raise NotImplementedError # noqa
@overload
def middleware(
self,
middleware_or_request: MiddlewareType,
attach_to: str = "request",
apply: bool = True,
*,
priority: int = 0,
) -> MiddlewareType: ...
@overload
def middleware(
self,
middleware_or_request: str,
attach_to: str = "request",
apply: bool = True,
*,
priority: int = 0,
) -> Callable[[MiddlewareType], MiddlewareType]: ...
def middleware(
self,
middleware_or_request: Union[MiddlewareType, str],
attach_to: str = "request",
apply: bool = True,
*,
priority: int = 0,
) -> Union[MiddlewareType, Callable[[MiddlewareType], MiddlewareType]]:
"""Decorator for registering middleware.
Decorate and register middleware to be called before a request is
handled or after a response is created. Can either be called as
*@app.middleware* or *@app.middleware('request')*. Although, it is
recommended to use *@app.on_request* or *@app.on_response* instead
for clarity and convenience.
See [Middleware](/guide/basics/middleware) for more information.
Args:
middleware_or_request (Union[Callable, str]): Middleware function
or the keyword 'request' or 'response'.
attach_to (str, optional): When to apply the middleware;
either 'request' (before the request is handled) or 'response'
(after the response is created). Defaults to `'request'`.
apply (bool, optional): Whether the middleware should be applied.
Defaults to `True`.
priority (int, optional): The priority level of the middleware.
Lower numbers are executed first. Defaults to `0`.
Returns:
Union[Callable, Callable[[Callable], Callable]]: The decorated
middleware function or a partial function depending on how
the method was called.
Example:
```python
@app.middleware('request')
async def custom_middleware(request):
...
```
"""
def register_middleware(middleware, attach_to="request"):
nonlocal apply
location = (
MiddlewareLocation.REQUEST
if attach_to == "request"
else MiddlewareLocation.RESPONSE
)
middleware = Middleware(middleware, location, priority=priority)
future_middleware = FutureMiddleware(middleware, attach_to)
self._future_middleware.append(future_middleware)
if apply:
self._apply_middleware(future_middleware)
return middleware
# Detect which way this was called, @middleware or @middleware('AT')
if callable(middleware_or_request):
return register_middleware(
middleware_or_request, attach_to=attach_to
)
else:
return partial(
register_middleware, attach_to=middleware_or_request
)
def on_request(self, middleware=None, *, priority=0) -> MiddlewareType:
"""Register a middleware to be called before a request is handled.
This is the same as *@app.middleware('request')*.
Args:
middleware (Callable, optional): A callable that takes in a
request. Defaults to `None`.
Returns:
Callable: The decorated middleware function or a partial function
depending on how the method was called.
Examples:
```python
@app.on_request
async def custom_middleware(request):
request.ctx.custom = 'value'
```
"""
if callable(middleware):
return self.middleware(middleware, "request", priority=priority)
else:
return partial( # type: ignore
self.middleware, attach_to="request", priority=priority
)
def on_response(self, middleware=None, *, priority=0):
"""Register a middleware to be called after a response is created.
This is the same as *@app.middleware('response')*.
Args:
middleware (Callable, optional): A callable that takes in a
request and response. Defaults to `None`.
Returns:
Callable: The decorated middleware function or a partial function
depending on how the method was called.
Examples:
```python
@app.on_response
async def custom_middleware(request, response):
response.headers['X-Server'] = 'Sanic'
```
"""
if callable(middleware):
return self.middleware(middleware, "response", priority=priority)
else:
return partial(
self.middleware, attach_to="response", priority=priority
)
def finalize_middleware(self) -> None:
"""Finalize the middleware configuration for the Sanic application.
This method completes the middleware setup for the application.
Middleware in Sanic is used to process requests globally before they
reach individual routes or after routes have been processed.
Finalization consists of identifying defined routes and optimizing
Sanic's performance to meet the application's specific needs. If
you are manually adding routes, after Sanic has started, you will
typically want to use the `amend` context manager rather than
calling this method directly.
.. note::
This method is usually called internally during the server setup
process and does not typically need to be invoked manually.
Example:
```python
app.finalize_middleware()
```
"""
for route in self.router.routes:
request_middleware = Middleware.convert(
self.request_middleware, # type: ignore
self.named_request_middleware.get(route.name, deque()), # type: ignore # noqa: E501
location=MiddlewareLocation.REQUEST,
)
response_middleware = Middleware.convert(
self.response_middleware, # type: ignore
self.named_response_middleware.get(route.name, deque()), # type: ignore # noqa: E501
location=MiddlewareLocation.RESPONSE,
)
route.extra.request_middleware = deque(
sorted(
request_middleware,
key=attrgetter("order"),
reverse=True,
)
)
route.extra.response_middleware = deque(
sorted(
response_middleware,
key=attrgetter("order"),
reverse=True,
)[::-1]
)
request_middleware = Middleware.convert(
self.request_middleware, # type: ignore
location=MiddlewareLocation.REQUEST,
)
response_middleware = Middleware.convert(
self.response_middleware, # type: ignore
location=MiddlewareLocation.RESPONSE,
)
self.request_middleware = deque(
sorted(
request_middleware,
key=attrgetter("order"),
reverse=True,
)
)
self.response_middleware = deque(
sorted(
response_middleware,
key=attrgetter("order"),
reverse=True,
)[::-1]
)
| MiddlewareMixin |
python | bokeh__bokeh | src/bokeh/models/annotations/legends.py | {
"start": 18855,
"end": 25308
} | class ____(Annotation):
""" Represents a scale bar annotation.
"""
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@error(NON_MATCHING_SCALE_BAR_UNIT)
def _check_non_matching_scale_bar_unit(self):
if not self.dimensional.is_known(self.unit):
return str(self)
range = Either(Instance(Range), Auto, default="auto", help="""
The range for which to display the scale.
This can be either a range reference or ``"auto"``, in which case the
scale bar will pick the default x or y range of the frame, depending
on the orientation of the scale bar.
""")
unit = String(default="m", help="""
The unit of the ``range`` property.
""")
dimensional = Instance(Dimensional, default=InstanceDefault(MetricLength), help="""
Defines the units of measurement.
""")
orientation = Enum(Orientation, help="""
Whether the scale bar should be oriented horizontally or vertically.
""")
location = Position(default="top_right", help="""
Position of the scale bar within the parent container (usually cartesian frame).
""")
x_units = PositionUnits(default="data", help="""
The interpretation of x coordinate values provided in ``position`` property.
""")
y_units = PositionUnits(default="data", help="""
The interpretation of y coordinate values provided in ``position`` property.
""")
anchor = AutoAnchor(default="auto", help="""
The origin for scale bar positioning.
If ``"auto"`` in any or both dimensions, then the anchor in these dimensions
will be determined based on the position, so that the scale bar looks good.
""")
length_sizing = Enum("adaptive", "exact", help="""
Defines how the length of the bar is interpreted.
This can either be:
* ``"adaptive"`` - the computed length is fit into a set of ticks provided
be the dimensional model. If no ticks are provided, then the behavior
is the same as if ``"exact"`` sizing was used
* ``"exact"`` - the computed length is used as-is
""")
bar_length = NonNegative(Either(Float, Int))(default=0.2, help="""
The length of the bar.
This is either a fraction of the frame, a number of pixels or
distance in the data space, depending on the configuration of
``bar_length_units``.
""")
bar_length_units = Enum("screen", "data", "percent", default="screen", help="""
Defines how to interpret ``bar_length``.
Supported values are:
* ``"screen"`` - the length is provided in pixels or as a percentage of
the parent container (e.g. the frame) if the value provided is in
``[0, 1]`` range
* ``"data"`` - the length is provided in data space units
* ``"percent"`` - the length is a percentage of the parent container (e.g. the frame)
.. note::
``"data"`` units assume a linear scale or a linear like scale (e.g.
categorical scale) is used. Otherwise the length of the bar would
be position dependent.
""")
bar_line = Include(ScalarLineProps, prefix="bar", help="""
The {prop} values for the bar line style.
""")
margin = Int(default=10, help="""
Amount of margin (in pixels) around the outside of the scale bar.
""")
padding = Int(default=10, help="""
Amount of padding (in pixels) between the contents of the scale bar
and its border.
""")
label = String(default="@{value} @{unit}", help="""
The label template.
This can use special variables:
* ``@{value}`` The current value. Optionally can provide a number
formatter with e.g. ``@{value}{%.2f}``.
* ``@{unit}`` The unit of measurement.
""")
label_text = Include(ScalarTextProps, prefix="label", help="""
The {prop} values for the label text style.
""")
label_align = Enum(Align, default="center", help="""
Specifies where to align scale bar's label along the bar.
This property effective when placing the label above or below
a horizontal scale bar, or left or right of a vertical one.
""")
label_location = Enum(Location, default="below", help="""
Specifies on which side of the scale bar the label will be located.
""")
label_standoff = Int(default=5, help="""
The distance (in pixels) to separate the label from the scale bar.
""")
title = String(default="", help="""
The title text to render.
""")
title_text = Include(ScalarTextProps, prefix="title", help="""
The {prop} values for the title text style.
""")
title_align = Enum(Align, default="center", help="""
Specifies where to align scale bar's title along the bar.
This property effective when placing the title above or below
a horizontal scale bar, or left or right of a vertical one.
""")
title_location = Enum(Location, default="above", help="""
Specifies on which side of the legend the title will be located.
""")
title_standoff = Int(default=5, help="""
The distance (in pixels) to separate the title from the scale bar.
""")
ticker = Instance(Ticker, default=InstanceDefault(FixedTicker, ticks=[]), help="""
A ticker to use for computing locations of axis components.
Note that if using the default fixed ticker with no predefined ticks,
then the appearance of the scale bar will be just a solid bar with
no additional markings.
""")
border_line = Include(ScalarLineProps, prefix="border", help="""
The {prop} for the scale bar border line style.
""")
background_fill = Include(ScalarFillProps, prefix="background", help="""
The {prop} for the scale bar background fill style.
""")
background_hatch = Include(ScalarHatchProps, prefix="background", help="""
The {prop} for the scale bar background hatch style.
""")
bar_line_width = Override(default=2)
border_line_color = Override(default="#e5e5e5")
border_line_alpha = Override(default=0.5)
border_line_width = Override(default=1)
background_fill_color = Override(default="#ffffff")
background_fill_alpha = Override(default=0.95)
label_text_font_size = Override(default="13px")
label_text_baseline = Override(default="middle")
title_text_font_size = Override(default="13px")
title_text_font_style = Override(default="italic")
@abstract
| ScaleBar |
python | pypa__warehouse | tests/unit/test_request.py | {
"start": 1012,
"end": 3075
} | class ____:
def test_hashes_domains_with_nonce(self):
"""Test that domains are hashed using the nonce."""
req = pretend.stub(
nonce="test-nonce-123",
registry=pretend.stub(
settings={"warehouse.allowed_domains": ["pypi.org", "test.pypi.org"]}
),
)
hashed = request._create_hashed_domains(req)
# Should return comma-separated list
assert "," in hashed
hashes = hashed.split(",")
assert len(hashes) == 2
# Each hash should be 64 chars (sha256 hex)
for h in hashes:
assert len(h) == 64
assert all(c in "0123456789abcdef" for c in h)
# Hashes should be different for different domains
assert hashes[0] != hashes[1]
def test_different_nonce_produces_different_hashes(self):
"""Test that different nonces produce different hashes for same domain."""
req1 = pretend.stub(
nonce="nonce-1",
registry=pretend.stub(settings={"warehouse.allowed_domains": ["pypi.org"]}),
)
req2 = pretend.stub(
nonce="nonce-2",
registry=pretend.stub(settings={"warehouse.allowed_domains": ["pypi.org"]}),
)
hashed1 = request._create_hashed_domains(req1)
hashed2 = request._create_hashed_domains(req2)
assert hashed1 != hashed2
def test_empty_domains_returns_empty_string(self):
"""Test that empty domain list returns empty string."""
req = pretend.stub(
nonce="test-nonce",
registry=pretend.stub(settings={"warehouse.allowed_domains": []}),
)
hashed = request._create_hashed_domains(req)
assert hashed == ""
def test_no_domains_setting_returns_empty_string(self):
"""Test that missing domains setting returns empty string."""
req = pretend.stub(nonce="test-nonce", registry=pretend.stub(settings={}))
hashed = request._create_hashed_domains(req)
assert hashed == ""
| TestCreateHashedDomains |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 592524,
"end": 593284
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for User."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("EnterpriseOutsideCollaboratorEdge"), graphql_name="edges")
"""A list of edges."""
nodes = sgqlc.types.Field(sgqlc.types.list_of("User"), graphql_name="nodes")
"""A list of nodes."""
page_info = sgqlc.types.Field(sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo")
"""Information to aid in pagination."""
total_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="totalCount")
"""Identifies the total count of items in the connection."""
| EnterpriseOutsideCollaboratorConnection |
python | keras-team__keras | keras/src/utils/file_utils_test.py | {
"start": 2143,
"end": 4342
} | class ____(test_case.TestCase):
def setUp(self):
self._cleanup(os.path.join("test_path", "to", "base_dir"))
self._cleanup(os.path.join(".", "base_dir"))
def _cleanup(self, base_dir):
if os.path.exists(base_dir):
shutil.rmtree(base_dir)
def test_is_link_in_dir_with_absolute_paths(self):
base_dir = os.path.join("test_path", "to", "base_dir")
link_path = os.path.join(base_dir, "symlink")
target_path = os.path.join(base_dir, "file.txt")
# Create the base_dir directory if it does not exist.
os.makedirs(base_dir, exist_ok=True)
# Create the file.txt file.
with open(target_path, "w") as f:
f.write("Hello, world!")
os.symlink(target_path, link_path)
# Creating a stat_result-like object with a name attribute
info = os.lstat(link_path)
info = type(
"stat_with_name",
(object,),
{
"name": os.path.basename(link_path),
"linkname": os.readlink(link_path),
},
)
self.assertTrue(file_utils.is_link_in_dir(info, base_dir))
def test_is_link_in_dir_with_relative_paths(self):
base_dir = os.path.join(".", "base_dir")
link_path = os.path.join(base_dir, "symlink")
target_path = os.path.join(base_dir, "file.txt")
# Create the base_dir directory if it does not exist.
os.makedirs(base_dir, exist_ok=True)
# Create the file.txt file.
with open(target_path, "w") as f:
f.write("Hello, world!")
os.symlink(target_path, link_path)
# Creating a stat_result-like object with a name attribute
info = os.lstat(link_path)
info = type(
"stat_with_name",
(object,),
{
"name": os.path.basename(link_path),
"linkname": os.readlink(link_path),
},
)
self.assertTrue(file_utils.is_link_in_dir(info, base_dir))
def tearDown(self):
self._cleanup(os.path.join("test_path", "to", "base_dir"))
self._cleanup(os.path.join(".", "base_dir"))
| IsLinkInDirTest |
python | getsentry__sentry | tests/sentry/api/serializers/test_debugfile.py | {
"start": 91,
"end": 2526
} | class ____(TestCase):
def test_simple(self) -> None:
file = self.create_file(
name="baz.dSYM",
size=42,
headers={"Content-Type": "application/x-mach-binary"},
checksum="dc1e3f3e411979d336c3057cce64294f3420f93a",
)
dif = self.create_dif_file(
debug_id="dfb8e43a-f242-3d73-a453-aeb6a777ef75",
code_id="DFB8E43AF2423D73A453AEB6A777EF75",
object_name="baz.dSYM",
cpu_name="x86_64",
file=file,
data={"features": ["debug"]},
)
result = serialize(dif)
result.pop("id")
result.pop("dateCreated")
assert result == {
"uuid": "dfb8e43a-f242-3d73-a453-aeb6a777ef75",
"debugId": "dfb8e43a-f242-3d73-a453-aeb6a777ef75",
"codeId": "DFB8E43AF2423D73A453AEB6A777EF75",
"cpuName": "x86_64",
"objectName": "baz.dSYM",
"symbolType": "macho",
"size": 42,
"sha1": "dc1e3f3e411979d336c3057cce64294f3420f93a",
"headers": {"Content-Type": "application/x-mach-binary"},
"data": {"features": ["debug"]},
}
def test_long_debug_id(self) -> None:
file = self.create_file(
name="baz.dSYM",
size=42,
headers={"Content-Type": "application/x-mach-binary"},
checksum="dc1e3f3e411979d336c3057cce64294f3420f93a",
)
dif = self.create_dif_file(
debug_id="dfb8e43a-f242-3d73-a453-aeb6a777ef75-feedface",
code_id="DFB8E43AF2423D73A453AEB6A777EF75feedface",
object_name="baz.dSYM",
cpu_name="x86_64",
file=file,
data={"features": ["debug"]},
)
result = serialize(dif)
result.pop("id")
result.pop("dateCreated")
assert result == {
"uuid": "dfb8e43a-f242-3d73-a453-aeb6a777ef75",
"debugId": "dfb8e43a-f242-3d73-a453-aeb6a777ef75-feedface",
"codeId": "DFB8E43AF2423D73A453AEB6A777EF75feedface",
"cpuName": "x86_64",
"objectName": "baz.dSYM",
"symbolType": "macho",
"size": 42,
"sha1": "dc1e3f3e411979d336c3057cce64294f3420f93a",
"headers": {"Content-Type": "application/x-mach-binary"},
"data": {"features": ["debug"]},
}
| DebugFileSerializerTest |
python | python__mypy | mypy/test/teststubgen.py | {
"start": 33029,
"end": 33072
} | class ____(TestBaseClass):
pass
| TestClass |
python | crytic__slither | slither/printers/functions/dominator.py | {
"start": 104,
"end": 1208
} | class ____(AbstractPrinter):
ARGUMENT = "dominator"
HELP = "Export the dominator tree of each functions"
WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#dominator"
def output(self, filename: str) -> Output:
"""
_filename is not used
Args:
_filename(string)
"""
info = ""
all_files = []
for contract in self.contracts:
for function in contract.functions + contract.modifiers:
if filename:
new_filename = f"{filename}-{contract.name}-{function.full_name}.dot"
else:
new_filename = f"dominator-{contract.name}-{function.full_name}.dot"
info += f"Export {new_filename}\n"
content = function.dominator_tree_to_dot(new_filename)
all_files.append((new_filename, content))
self.info(info)
res = self.generate_output(info)
for filename_result, content in all_files:
res.add_file(filename_result, content)
return res
| Dominator |
python | GoogleCloudPlatform__python-docs-samples | compute/client_library/snippets/instances/ip_address/get_vm_address.py | {
"start": 1572,
"end": 2891
} | class ____(Enum):
INTERNAL = "internal"
EXTERNAL = "external"
IP_V6 = "ipv6"
def get_instance_ip_address(
instance: compute_v1.Instance, ip_type: IPType
) -> List[str]:
"""
Retrieves the specified type of IP address (ipv6, internal or external) of a specified Compute Engine instance.
Args:
instance (compute_v1.Instance): instance to get
ip_type (IPType): The type of IP address to retrieve (ipv6, internal or external).
Returns:
List[str]: Requested type IP addresses of the instance.
"""
ips = []
if not instance.network_interfaces:
return ips
for interface in instance.network_interfaces:
if ip_type == IPType.EXTERNAL:
for config in interface.access_configs:
if config.type_ == "ONE_TO_ONE_NAT":
ips.append(config.nat_i_p)
elif ip_type == IPType.IP_V6:
for ipv6_config in getattr(interface, "ipv6_access_configs", []):
if ipv6_config.type_ == "DIRECT_IPV6":
ips.append(ipv6_config.external_ipv6)
elif ip_type == IPType.INTERNAL:
# Internal IP is directly available in the network interface
ips.append(interface.network_i_p)
return ips
# [END compute_ip_address_get_vm_address]
| IPType |
python | allegroai__clearml | clearml/backend_api/services/v2_9/workers.py | {
"start": 66576,
"end": 70599
} | class ____(Response):
"""
Response of workers.get_stats endpoint.
:param workers: List of the requested workers with their statistics
:type workers: Sequence[WorkerStats]
"""
_service = "workers"
_action = "get_stats"
_version = "2.9"
_schema = {
"definitions": {
"aggregation_stats": {
"properties": {
"aggregation": {
"oneOf": [
{"$ref": "#/definitions/aggregation_type"},
{"type": "null"},
]
},
"values": {
"description": "List of values corresponding to the dates in metric statistics",
"items": {"type": "number"},
"type": ["array", "null"],
},
},
"type": "object",
},
"aggregation_type": {
"description": "Metric aggregation type",
"enum": ["avg", "min", "max"],
"type": "string",
},
"metric_stats": {
"properties": {
"dates": {
"description": "List of timestamps (in seconds from epoch) in the acceding order. The timestamps are separated by the requested interval. Timestamps where no workers activity was recorded are omitted.",
"items": {"type": "integer"},
"type": ["array", "null"],
},
"metric": {
"description": "Name of the metric (cpu_usage, memory_used etc.)",
"type": ["string", "null"],
},
"stats": {
"description": "Statistics data by type",
"items": {"$ref": "#/definitions/aggregation_stats"},
"type": ["array", "null"],
},
"variant": {
"description": "Name of the metric component. Set only if 'split_by_variant' was set in the request",
"type": ["string", "null"],
},
},
"type": "object",
},
"worker_stats": {
"properties": {
"metrics": {
"description": "List of the metrics statistics for the worker",
"items": {"$ref": "#/definitions/metric_stats"},
"type": ["array", "null"],
},
"worker": {
"description": "ID of the worker",
"type": ["string", "null"],
},
},
"type": "object",
},
},
"properties": {
"workers": {
"description": "List of the requested workers with their statistics",
"items": {"$ref": "#/definitions/worker_stats"},
"type": ["array", "null"],
}
},
"type": "object",
}
def __init__(self, workers: Optional[List[Any]] = None, **kwargs: Any) -> None:
super(GetStatsResponse, self).__init__(**kwargs)
self.workers = workers
@schema_property("workers")
def workers(self) -> Optional[List[Any]]:
return self._property_workers
@workers.setter
def workers(self, value: Optional[List[Any]]) -> None:
if value is None:
self._property_workers = None
return
self.assert_isinstance(value, "workers", (list, tuple))
if any((isinstance(v, dict) for v in value)):
value = [WorkerStats.from_dict(v) if isinstance(v, dict) else v for v in value]
else:
self.assert_isinstance(value, "workers", WorkerStats, is_array=True)
self._property_workers = value
| GetStatsResponse |
python | tornadoweb__tornado | tornado/test/queues_test.py | {
"start": 757,
"end": 2525
} | class ____(AsyncTestCase):
def test_repr_and_str(self):
q = queues.Queue(maxsize=1) # type: queues.Queue[None]
self.assertIn(hex(id(q)), repr(q))
self.assertNotIn(hex(id(q)), str(q))
q.get()
for q_str in repr(q), str(q):
self.assertTrue(q_str.startswith("<Queue"))
self.assertIn("maxsize=1", q_str)
self.assertIn("getters[1]", q_str)
self.assertNotIn("putters", q_str)
self.assertNotIn("tasks", q_str)
q.put(None)
q.put(None)
# Now the queue is full, this putter blocks.
q.put(None)
for q_str in repr(q), str(q):
self.assertNotIn("getters", q_str)
self.assertIn("putters[1]", q_str)
self.assertIn("tasks=2", q_str)
def test_order(self):
q = queues.Queue() # type: queues.Queue[int]
for i in [1, 3, 2]:
q.put_nowait(i)
items = [q.get_nowait() for _ in range(3)]
self.assertEqual([1, 3, 2], items)
@gen_test
def test_maxsize(self):
self.assertRaises(TypeError, queues.Queue, maxsize=None)
self.assertRaises(ValueError, queues.Queue, maxsize=-1)
q = queues.Queue(maxsize=2) # type: queues.Queue[int]
self.assertTrue(q.empty())
self.assertFalse(q.full())
self.assertEqual(2, q.maxsize)
self.assertTrue(q.put(0).done())
self.assertTrue(q.put(1).done())
self.assertFalse(q.empty())
self.assertTrue(q.full())
put2 = q.put(2)
self.assertFalse(put2.done())
self.assertEqual(0, (yield q.get())) # Make room.
self.assertTrue(put2.done())
self.assertFalse(q.empty())
self.assertTrue(q.full())
| QueueBasicTest |
python | encode__django-rest-framework | tests/schemas/test_coreapi.py | {
"start": 30834,
"end": 30991
} | class ____(serializers.ModelSerializer):
class Meta:
model = ManyToManySource
fields = ('id', 'name', 'targets')
| ManyToManySourceSerializer |
python | ray-project__ray | rllib/algorithms/sac/sac_catalog.py | {
"start": 898,
"end": 12377
} | class ____(Catalog):
"""The catalog class used to build models for SAC.
SACCatalog provides the following models:
- Encoder: The encoder used to encode the observations for the actor
network (`pi`). For this we use the default encoder from the Catalog.
- Q-Function Encoder: The encoder used to encode the observations and
actions for the soft Q-function network.
- Target Q-Function Encoder: The encoder used to encode the observations
and actions for the target soft Q-function network.
- Pi Head: The head used to compute the policy logits. This network outputs
the mean and log-std for the action distribution (a Squashed Gaussian).
- Q-Function Head: The head used to compute the soft Q-values.
- Target Q-Function Head: The head used to compute the target soft Q-values.
Any custom Encoder to be used for the policy network can be built by overriding
the build_encoder() method. Alternatively the `encoder_config` can be overridden
by using the `model_config_dict`.
Any custom Q-Function Encoder can be built by overriding the build_qf_encoder().
Important: The Q-Function Encoder must encode both the state and the action. The
same holds true for the target Q-Function Encoder.
Any custom head can be built by overriding the build_pi_head() and build_qf_head().
Any module built for exploration or inference is built with the flag
`ìnference_only=True` and does not contain any Q-function. This flag can be set
in the `model_config_dict` with the key `ray.rllib.core.rl_module.INFERENCE_ONLY`.
"""
def __init__(
self,
observation_space: gym.Space,
action_space: gym.Space,
model_config_dict: dict,
view_requirements: dict = None,
):
"""Initializes the SACCatalog.
Args:
observation_space: The observation space of the Encoder.
action_space: The action space for the Pi Head.
model_config_dict: The model config to use.
"""
assert view_requirements is None, (
"Instead, use the new ConnectorV2 API to pick whatever information "
"you need from the running episodes"
)
super().__init__(
observation_space=observation_space,
action_space=action_space,
model_config_dict=model_config_dict,
)
if not isinstance(self.action_space, (gym.spaces.Box, gym.spaces.Discrete)):
self._raise_unsupported_action_space_error()
# Define the heads.
self.pi_and_qf_head_hiddens = self._model_config_dict["head_fcnet_hiddens"]
self.pi_and_qf_head_activation = self._model_config_dict[
"head_fcnet_activation"
]
# We don't have the exact (framework specific) action dist class yet and thus
# cannot determine the exact number of output nodes (action space) required.
# -> Build pi config only in the `self.build_pi_head` method.
self.pi_head_config = None
# SAC-Discrete: The Q-function outputs q-values for each action
# SAC-Continuous: The Q-function outputs a single value (the Q-value for the
# action taken).
required_qf_output_dim = (
self.action_space.n
if isinstance(self.action_space, gym.spaces.Discrete)
else 1
)
# TODO (simon): Implement in a later step a q network with
# different `head_fcnet_hiddens` than pi.
# TODO (simon): These latent_dims could be different for the
# q function, value function, and pi head.
# Here we consider the simple case of identical encoders.
self.qf_head_config = MLPHeadConfig(
input_dims=self.latent_dims,
hidden_layer_dims=self.pi_and_qf_head_hiddens,
hidden_layer_activation=self.pi_and_qf_head_activation,
output_layer_activation="linear",
output_layer_dim=required_qf_output_dim,
)
@OverrideToImplementCustomLogic
def build_qf_encoder(self, framework: str) -> Encoder:
"""Builds the Q-function encoder.
In contrast to PPO, SAC needs a different encoder for Pi and
Q-function as the Q-function in the continuous case has to
encode actions, too. Therefore the Q-function uses its own
encoder config.
Note, the Pi network uses the base encoder from the `Catalog`.
Args:
framework: The framework to use. Either `torch` or `tf2`.
Returns:
The encoder for the Q-network.
"""
# Compute the required dimension for the action space.
if isinstance(self.action_space, gym.spaces.Box):
required_action_dim = self.action_space.shape[0]
elif isinstance(self.action_space, gym.spaces.Discrete):
# for discrete action spaces, we don't need to encode the action
# because the Q-function will output a value for each action
required_action_dim = 0
else:
self._raise_unsupported_action_space_error()
# Encoder input for the Q-network contains state and action. We
# need to infer the shape for the input from the state and action
# spaces
if not (
isinstance(self.observation_space, gym.spaces.Box)
and len(self.observation_space.shape) == 1
):
raise ValueError("The observation space is not supported by RLlib's SAC.")
input_space = gym.spaces.Box(
-np.inf,
np.inf,
(self.observation_space.shape[0] + required_action_dim,),
dtype=np.float32,
)
self.qf_encoder_hiddens = self._model_config_dict["fcnet_hiddens"][:-1]
self.qf_encoder_activation = self._model_config_dict["fcnet_activation"]
self.qf_encoder_config = MLPEncoderConfig(
input_dims=input_space.shape,
hidden_layer_dims=self.qf_encoder_hiddens,
hidden_layer_activation=self.qf_encoder_activation,
output_layer_dim=self.latent_dims[0],
output_layer_activation=self.qf_encoder_activation,
)
return self.qf_encoder_config.build(framework=framework)
@OverrideToImplementCustomLogic
def build_pi_head(self, framework: str) -> Model:
"""Builds the policy head.
The default behavior is to build the head from the pi_head_config.
This can be overridden to build a custom policy head as a means of configuring
the behavior of the DefaultSACRLModule implementation.
Args:
framework: The framework to use. Either "torch" or "tf2".
Returns:
The policy head.
"""
# Get action_distribution_cls to find out about the output dimension for pi_head
action_distribution_cls = self.get_action_dist_cls(framework=framework)
BUILD_MAP: dict[
type[gym.spaces.Space], Callable[[str, Distribution], Model]
] = {
gym.spaces.Discrete: self._build_pi_head_discrete,
gym.spaces.Box: self._build_pi_head_continuous,
}
try:
# Try to get the build function for the action space type.
return BUILD_MAP[type(self.action_space)](
framework, action_distribution_cls
)
except KeyError:
# If the action space type is not supported, raise an error.
self._raise_unsupported_action_space_error()
def _build_pi_head_continuous(
self, framework: str, action_distribution_cls: Distribution
) -> Model:
"""Builds the policy head for continuous action spaces."""
# Get action_distribution_cls to find out about the output dimension for pi_head
# TODO (simon): CHeck, if this holds also for Squashed Gaussian.
if self._model_config_dict["free_log_std"]:
_check_if_diag_gaussian(
action_distribution_cls=action_distribution_cls, framework=framework
)
is_diag_gaussian = True
else:
is_diag_gaussian = _check_if_diag_gaussian(
action_distribution_cls=action_distribution_cls,
framework=framework,
no_error=True,
)
required_output_dim = action_distribution_cls.required_input_dim(
space=self.action_space, model_config=self._model_config_dict
)
# Now that we have the action dist class and number of outputs, we can define
# our pi-config and build the pi head.
pi_head_config_class = (
FreeLogStdMLPHeadConfig
if self._model_config_dict["free_log_std"]
else MLPHeadConfig
)
self.pi_head_config = pi_head_config_class(
input_dims=self.latent_dims,
hidden_layer_dims=self.pi_and_qf_head_hiddens,
hidden_layer_activation=self.pi_and_qf_head_activation,
output_layer_dim=required_output_dim,
output_layer_activation="linear",
clip_log_std=is_diag_gaussian,
log_std_clip_param=self._model_config_dict.get("log_std_clip_param", 20),
)
return self.pi_head_config.build(framework=framework)
def _build_pi_head_discrete(
self, framework: str, action_distribution_cls: Distribution
) -> Model:
"""Builds the policy head for discrete action spaces. The module outputs logits for Categorical
distribution.
"""
required_output_dim = action_distribution_cls.required_input_dim(
space=self.action_space, model_config=self._model_config_dict
)
self.pi_head_config = MLPHeadConfig(
input_dims=self.latent_dims,
hidden_layer_dims=self.pi_and_qf_head_hiddens,
hidden_layer_activation=self.pi_and_qf_head_activation,
output_layer_dim=required_output_dim,
output_layer_activation="linear",
)
return self.pi_head_config.build(framework=framework)
@OverrideToImplementCustomLogic
def build_qf_head(self, framework: str) -> Model:
"""Build the Q function head."""
return self.qf_head_config.build(framework=framework)
@override(Catalog)
def get_action_dist_cls(self, framework: str) -> Distribution:
"""Returns the action distribution class to use for the given framework. TorchSquashedGaussian
for continuous action spaces and TorchCategorical for discrete action spaces."""
# TODO (KIY): Catalog.get_action_dist_cls should return a type[Distribution] instead of a Distribution instance.
assert framework == "torch"
if isinstance(self.action_space, gym.spaces.Box):
# For continuous action spaces, we use a Squashed Gaussian.
return TorchSquashedGaussian
elif isinstance(self.action_space, gym.spaces.Discrete):
# For discrete action spaces, we use a Categorical distribution.
return TorchCategorical
else:
self._raise_unsupported_action_space_error()
def _raise_unsupported_action_space_error(self):
"""Raises an error if the action space is not supported."""
raise ValueError(
f"SAC only supports Box and Discrete action spaces. "
f"Got: {type(self.action_space)}"
)
| SACCatalog |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py | {
"start": 3720,
"end": 3809
} | class ____(IncrementalShopifyGraphQlBulkStream):
bulk_query: Product = Product
| Products |
python | readthedocs__readthedocs.org | readthedocs/projects/admin.py | {
"start": 1719,
"end": 1985
} | class ____(BaseInlineFormSet):
"""Limit the number of versions displayed in the inline."""
LIMIT = 200
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.queryset = self.queryset[: self.LIMIT]
| VersionInlineFormSet |
python | dagster-io__dagster | python_modules/libraries/dagster-azure/dagster_azure_tests/pipes_tests/mock_blob_storage.py | {
"start": 64,
"end": 1099
} | class ____:
"""We use this mock class to test AzureBlobStorage ContextInjector and MessageWriter.
Because both the Dagster orchestrator and the external process need to have the same view of the storage data,
it is backed in a temporary directory on the local machine.
"""
def __init__(self, temp_dir: str, storage_account: str):
self._temp_dir = temp_dir
self._storage_account = storage_account
def get_container_client(self, container: str):
return MockBlobContainerClient(self._temp_dir, self._storage_account, container)
def get_blob_client(self, container: str, blob: str):
return self.get_container_client(container).get_blob_client(blob)
def cleanup(self):
"""Deletes all data created by the MockBlobServiceClient."""
shutil.rmtree(Path(self._temp_dir).joinpath(self._storage_account), ignore_errors=True)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
return False
| MockBlobServiceClient |
python | matplotlib__matplotlib | lib/matplotlib/_type1font.py | {
"start": 2489,
"end": 2754
} | class ____(_Token):
kind = 'delimiter'
def is_delim(self):
return True
def opposite(self):
return {'[': ']', ']': '[',
'{': '}', '}': '{',
'<<': '>>', '>>': '<<'
}[self.raw]
| _DelimiterToken |
python | Textualize__textual | docs/examples/guide/layout/grid_layout2.py | {
"start": 80,
"end": 566
} | class ____(App):
CSS_PATH = "grid_layout2.tcss"
def compose(self) -> ComposeResult:
yield Static("One", classes="box")
yield Static("Two", classes="box")
yield Static("Three", classes="box")
yield Static("Four", classes="box")
yield Static("Five", classes="box")
yield Static("Six", classes="box")
yield Static("Seven", classes="box")
if __name__ == "__main__":
app = GridLayoutExample()
app.run()
| GridLayoutExample |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/configuration_qwen2_5_omni.py | {
"start": 9427,
"end": 17581
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Qwen2_5OmniThinkerForConditionalGeneration`]. It is used to instantiate an
Qwen2.5-Omni-Thinker model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuration to that of the Qwen2.5-Omni-Thinker.
e.g. [Qwen/Qwen2.5-Omni-7B](https://huggingface.co/Qwen/Qwen2.5-Omni-7B)
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 152064):
Vocabulary size of the QwenOmni model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`Qwen2VLModel`]
hidden_size (`int`, *optional*, defaults to 3584):
Dimension of the hidden representations.
intermediate_size (`int`, *optional*, defaults to 18944):
Dimension of the MLP representations.
num_hidden_layers (`int`, *optional*, defaults to 28):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 28):
Number of attention heads for each attention layer in the Transformer encoder.
num_key_value_heads (`int`, *optional*, defaults to 4):
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
by meanpooling all the original heads within that group. For more details, check out [this
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
The non-linear activation function (function or string) in the decoder.
max_position_embeddings (`int`, *optional*, defaults to 32768):
The maximum sequence length that this model might ever be used with.
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
The epsilon used by the rms normalization layers.
use_cache (`bool`, *optional*, defaults to `True`):
Whether or not the model should return the last key/values attentions (not used by all models). Only
relevant if `config.is_decoder=True`.
use_sliding_window (`bool`, *optional*, defaults to `False`):
Whether to use sliding window attention.
sliding_window (`int`, *optional*, defaults to 32768):
Sliding window attention (SWA) window size. If not specified, will default to `4096`.
max_window_layers (`int`, *optional*, defaults to 28):
The number of layers using full attention. The first `max_window_layers` layers will use full attention, while any
additional layer afterwards will use SWA (Sliding Window Attention).
layer_types (`list`, *optional*):
Attention pattern for each layer.
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
rope_parameters (`RopeParameters`, *optional*):
Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain
a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE
with longer `max_position_embeddings`.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
Example:
```python
>>> from transformers import Qwen2_5OmniThinkerForConditionalGeneration, Qwen2_5OmniThinkerConfig, Qwen2_5OmniAudioEncoderConfig, Qwen2_5OmniVisionEncoderConfig
>>> # Initializing a Qwen2_5OmniAudioEncoder config
>>> audio_config = Qwen2_5OmniAudioEncoderConfig()
>>> # Initializing a Qwen2_5OmniVisionEncoder config
>>> vision_config = Qwen2_5OmniVisionEncoderConfig()
>>> # Initializing a Qwen2.5OmniThinker configuration
>>> configuration = Qwen2_5OmniThinkerConfig(audio_config, vision_config)
>>> # Initializing a model from the Qwen-Omni style configuration
>>> model = Qwen2_5OmniThinkerForConditionalGeneration(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "qwen2_5_omni_text"
keys_to_ignore_at_inference = ["past_key_values"]
default_theta = 1000000.0
# Default tensor parallel plan for base model `Qwen25OmniText`
base_model_tp_plan = {
"layers.*.self_attn.q_proj": "colwise",
"layers.*.self_attn.k_proj": "colwise",
"layers.*.self_attn.v_proj": "colwise",
"layers.*.self_attn.o_proj": "rowwise",
"layers.*.mlp.gate_proj": "colwise",
"layers.*.mlp.up_proj": "colwise",
"layers.*.mlp.down_proj": "rowwise",
}
base_model_pp_plan = {
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
"norm": (["hidden_states"], ["hidden_states"]),
}
def __init__(
self,
vocab_size: Optional[int] = 152064,
hidden_size: Optional[int] = 3584,
intermediate_size: Optional[int] = 18944,
num_hidden_layers: Optional[int] = 28,
num_attention_heads: Optional[int] = 28,
num_key_value_heads: Optional[int] = 4,
hidden_act: Optional[str] = "silu",
max_position_embeddings: Optional[int] = 32768,
initializer_range: Optional[float] = 0.02,
rms_norm_eps: Optional[int] = 1e-6,
use_cache: Optional[bool] = True,
tie_word_embeddings: Optional[bool] = False,
rope_parameters: Optional[RopeParameters | dict[str, RopeParameters]] = None,
use_sliding_window: Optional[bool] = False,
sliding_window: Optional[int] = 32768,
max_window_layers: Optional[int] = 28,
layer_types: Optional[list[str]] = None,
attention_dropout: Optional[float] = 0.0,
**kwargs,
):
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.use_sliding_window = use_sliding_window
self.sliding_window = sliding_window if self.use_sliding_window else None
self.max_window_layers = max_window_layers
# for backward compatibility
if num_key_value_heads is None:
num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
self.attention_dropout = attention_dropout
self.layer_types = layer_types
if self.layer_types is None:
self.layer_types = [
"sliding_attention"
if self.sliding_window is not None and i >= self.max_window_layers
else "full_attention"
for i in range(self.num_hidden_layers)
]
layer_type_validation(self.layer_types, self.num_hidden_layers)
self.rope_parameters = rope_parameters
super().__init__(
tie_word_embeddings=tie_word_embeddings,
ignore_keys_at_rope_validation={"mrope"},
**kwargs,
)
| Qwen2_5OmniTextConfig |
python | numpy__numpy | benchmarks/benchmarks/bench_shape_base.py | {
"start": 4791,
"end": 5211
} | class ____(Benchmark):
"""Benchmarks for np.atleast_1d"""
def setup(self):
self.x = np.array([1, 2, 3])
self.zero_d = np.float64(1.)
def time_atleast_1d(self):
np.atleast_1d(self.x, self.x, self.x)
def time_atleast_1d_reshape(self):
np.atleast_1d(self.zero_d, self.zero_d, self.zero_d)
def time_atleast_1d_single_argument(self):
np.atleast_1d(self.x)
| AtLeast1D |
python | pandas-dev__pandas | asv_bench/benchmarks/groupby.py | {
"start": 25850,
"end": 26322
} | class ____:
# GH 20660
def setup(self):
N = 10**4
self.df = DataFrame(
np.random.randint(1000, 100000, (N, 100)),
index=np.random.randint(200, size=(N,)),
).astype("timedelta64[ns]")
self.df_int = self.df.copy().astype("int64")
def time_groupby_sum_timedelta(self):
self.df.groupby(lambda x: x).sum()
def time_groupby_sum_int(self):
self.df_int.groupby(lambda x: x).sum()
| SumTimeDelta |
python | scrapy__scrapy | tests/mockserver/http_resources.py | {
"start": 6216,
"end": 6478
} | class ____(Redirect):
def render(self, request: server.Request) -> bytes:
content = Redirect.render(self, request)
return content.replace(
b'http-equiv="refresh"', b'http-no-equiv="do-not-refresh-me"'
)
| NoMetaRefreshRedirect |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 191034,
"end": 192285
} | class ____(GeneratedAirbyteSource):
class OAuth20:
@public
def __init__(
self,
access_token: str,
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
):
self.auth_type = "oauth2.0"
self.client_id = check.opt_str_param(client_id, "client_id")
self.client_secret = check.opt_str_param(client_secret, "client_secret")
self.access_token = check.str_param(access_token, "access_token")
class APIKey:
@public
def __init__(self, apikey: str):
self.auth_type = "apikey"
self.apikey = check.str_param(apikey, "apikey")
@public
def __init__(
self, name: str, credentials: Union["MailchimpSource.OAuth20", "MailchimpSource.APIKey"]
):
"""Airbyte Source for Mailchimp.
Documentation can be found at https://docs.airbyte.com/integrations/sources/mailchimp
Args:
name (str): The name of the destination.
"""
self.credentials = check.inst_param(
credentials, "credentials", (MailchimpSource.OAuth20, MailchimpSource.APIKey)
)
super().__init__("Mailchimp", name)
| MailchimpSource |
python | anthropics__anthropic-sdk-python | src/anthropic/lib/tools/_beta_runner.py | {
"start": 1537,
"end": 1730
} | class ____(TypedDict, total=False):
extra_headers: Headers | None
extra_query: Query | None
extra_body: Body | None
timeout: float | httpx.Timeout | None | NotGiven
| RequestOptions |
python | kamyu104__LeetCode-Solutions | Python/find-kth-largest-xor-coordinate-value.py | {
"start": 64,
"end": 1782
} | class ____(object):
def kthLargestValue(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
def nth_element(nums, n, compare=lambda a, b: a < b):
def tri_partition(nums, left, right, target, compare):
mid = left
while mid <= right:
if nums[mid] == target:
mid += 1
elif compare(nums[mid], target):
nums[left], nums[mid] = nums[mid], nums[left]
left += 1
mid += 1
else:
nums[mid], nums[right] = nums[right], nums[mid]
right -= 1
return left, right
left, right = 0, len(nums)-1
while left <= right:
pivot_idx = random.randint(left, right)
pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare)
if pivot_left <= n <= pivot_right:
return
elif pivot_left > n:
right = pivot_left-1
else: # pivot_right < n.
left = pivot_right+1
vals = []
for r in xrange(len(matrix)):
curr = 0
for c in xrange(len(matrix[0])):
curr = curr^matrix[r][c]
if r == 0:
matrix[r][c] = curr
else:
matrix[r][c] = curr^matrix[r-1][c]
vals.append(matrix[r][c])
nth_element(vals, k-1, compare=lambda a, b: a > b)
return vals[k-1]
| Solution |
python | takluyver__flit | flit/upload.py | {
"start": 770,
"end": 10472
} | class ____:
url: str
username: Optional[str] = None
password: Optional[str] = None
@property
def is_pypi(self):
# Main PyPI (pypi.org) or TestPyPI (test.pypi.org)
# This is used to guess the URL for the project's HTML page
return self.url.rstrip('/').endswith('/legacy')
def get_repositories(file="~/.pypirc"):
"""Get the known repositories from a pypirc file.
This returns a dict keyed by name, of dicts with keys 'url', 'username',
'password'. Username and password may be None.
"""
cp = configparser.ConfigParser(interpolation=None)
if isinstance(file, str):
file = os.path.expanduser(file)
if not os.path.isfile(file):
return {'pypi': RepoDetails(url=PYPI)}
cp.read(file)
else:
cp.read_file(file)
names = cp.get('distutils', 'index-servers', fallback='pypi').split()
repos = {}
for name in names:
repos[name] = RepoDetails(
url=cp.get(name, 'repository', fallback=PYPI),
username=cp.get(name, 'username', fallback=None),
password=cp.get(name, 'password', fallback=None),
)
return repos
def get_repository(pypirc_path="~/.pypirc", name=None, project_name=None):
"""Get the url, username and password for one repository.
Returns a dict with keys 'url', 'username', 'password'.
There is a hierarchy of possible sources of information:
Index URL:
1. Command line arg --repository (looked up in .pypirc)
2. $FLIT_INDEX_URL
3. Repository called 'pypi' from .pypirc
4. Default PyPI (hardcoded)
Username:
1. $FLIT_USERNAME
2. Repository with specified name (default 'pypi') in .pypirc
3. Terminal prompt (write to .pypirc if it doesn't exist yet)
Password:
1. $FLIT_PASSWORD
2. Repository with specified name (default 'pypi') in .pypirc
3. keyring - pypi_token:project:<project_name>
4. keyring - pypi_token:user:<username>
5. keyring - username
6. Terminal prompt (store to keyring if available)
"""
log.debug("Loading repositories config from %r", pypirc_path)
repos_cfg = get_repositories(pypirc_path)
if name is not None:
repo = repos_cfg[name]
if 'FLIT_INDEX_URL' in os.environ:
raise OSError(
"Use either FLIT_INDEX_URL or --repository, not both"
)
elif 'FLIT_INDEX_URL' in os.environ:
repo = RepoDetails(url=os.environ['FLIT_INDEX_URL'])
elif 'pypi' in repos_cfg:
repo = repos_cfg['pypi']
else:
repo = RepoDetails(url=PYPI)
if repo.url.startswith(SWITCH_TO_HTTPS):
# Use https for PyPI, even if an http URL was given
repo.url = 'https' + repo.url[4:]
elif repo.url.startswith('http://'):
log.warning("Unencrypted connection - credentials may be visible on "
"the network.")
log.info("Using repository at %s", repo.url)
if 'FLIT_USERNAME' in os.environ:
repo.username = os.environ['FLIT_USERNAME']
if not repo.username and sys.stdin.isatty():
while not repo.username:
repo.username = input("Username: ")
if repo.url == PYPI:
write_pypirc(repo, pypirc_path)
elif not repo.username:
raise Exception("Could not find username for upload.")
if 'FLIT_PASSWORD' in os.environ:
repo.password = os.environ['FLIT_PASSWORD']
if not repo.password:
token = find_token(repo, project_name)
if token is not None:
repo.username = '__token__'
repo.password = token
else:
repo.password = get_password(repo)
return repo
def write_pypirc(repo, file="~/.pypirc"):
"""Write .pypirc if it doesn't already exist
"""
file = os.path.expanduser(file)
if os.path.isfile(file):
return
with open(file, 'w', encoding='utf-8') as f:
f.write("[pypi]\n"
f"username = {repo.username}\n")
def get_password(repo: RepoDetails):
try:
import keyring, keyring.errors
except ImportError: # pragma: no cover
log.warning("Install keyring to store tokens/passwords securely")
keyring = None
else:
try:
stored_pw = keyring.get_password(repo.url, repo.username)
if stored_pw is not None:
return stored_pw
except keyring.errors.KeyringError as e:
log.warning("Could not get password from keyring (%s)", e)
if sys.stdin.isatty():
pw = None
while not pw:
print('Server :', repo.url)
print('Username:', repo.username)
pw = getpass.getpass('Password: ')
else:
raise Exception("Could not find password for upload.")
if keyring is not None:
try:
keyring.set_password(repo.url, repo.username, pw)
log.info("Stored password with keyring")
except keyring.errors.KeyringError as e:
log.warning("Could not store password in keyring (%s)", e)
return pw
def find_token(repo: RepoDetails, project_name: str):
# https://packaging.python.org/en/latest/specifications/name-normalization/
project_name = re.sub(r"[-_.]+", "-", project_name).lower()
candidate_keys = [f"pypi_token:project:{project_name}"]
if repo.username is not None:
candidate_keys.append(f"pypi_token:user:{repo.username}")
try:
import keyring, keyring.errors
except ImportError: # pragma: no cover
pass
else:
try:
for key in candidate_keys:
token = keyring.get_password(repo.url, key)
if token is not None:
return token
except keyring.errors.KeyringError as e:
log.warning("Could not get token from keyring (%s)", e)
def build_post_data(action, metadata:Metadata):
"""Prepare the metadata needed for requests to PyPI.
"""
d = {
":action": action,
"name": metadata.name,
"version": metadata.version,
# additional meta-data
"metadata_version": '2.3',
"summary": metadata.summary,
"home_page": metadata.home_page,
"author": metadata.author,
"author_email": metadata.author_email,
"maintainer": metadata.maintainer,
"maintainer_email": metadata.maintainer_email,
"license": metadata.license,
"description": metadata.description,
"keywords": metadata.keywords,
"platform": metadata.platform,
"classifiers": metadata.classifiers,
"download_url": metadata.download_url,
"supported_platform": metadata.supported_platform,
# Metadata 1.1 (PEP 314)
"provides": metadata.provides,
"requires": metadata.requires,
"obsoletes": metadata.obsoletes,
# Metadata 1.2 (PEP 345)
"project_urls": metadata.project_urls,
"provides_dist": metadata.provides_dist,
"obsoletes_dist": metadata.obsoletes_dist,
"requires_dist": metadata.requires_dist,
"requires_external": metadata.requires_external,
"requires_python": metadata.requires_python,
# Metadata 2.1 (PEP 566)
"description_content_type": metadata.description_content_type,
"provides_extra": metadata.provides_extra,
}
return {k:v for k,v in d.items() if v}
def upload_file(file:Path, metadata:Metadata, repo: RepoDetails):
"""Upload a file to an index server, given the index server details.
"""
data = build_post_data('file_upload', metadata)
data['protocol_version'] = '1'
if file.suffix == '.whl':
data['filetype'] = 'bdist_wheel'
py2_support = not (metadata.requires_python or '')\
.startswith(('3', '>3', '>=3'))
data['pyversion'] = ('py2.' if py2_support else '') + 'py3'
else:
data['filetype'] = 'sdist'
with file.open('rb') as f:
content = f.read()
files = {'content': (file.name, content)}
data['md5_digest'] = hashlib.md5(content).hexdigest()
data['sha256_digest'] = hashlib.sha256(content).hexdigest()
log.info('Uploading %s...', file)
resp = requests.post(
repo.url, data=data, files=files, auth=(repo.username, repo.password),
)
resp.raise_for_status()
def do_upload(file:Path, metadata:Metadata, repo: RepoDetails):
"""Upload a file to an index server.
"""
upload_file(file, metadata, repo)
if repo.is_pypi:
domain = urlparse(repo.url).netloc
if domain.startswith('upload.'):
domain = domain[7:]
log.info("Package is at https://%s/project/%s/", domain, metadata.name)
else:
log.info("Package is at %s/%s", repo.url, metadata.name)
def main(ini_path, repo_name, pypirc_path=None, formats=None, use_vcs=True):
"""Build and upload wheel and sdist."""
if pypirc_path is None:
pypirc_path = PYPIRC_DEFAULT
elif not os.path.isfile(pypirc_path):
raise FileNotFoundError("The specified pypirc config file does not exist.")
ini_info = read_flit_config(ini_path)
srcdir = ini_path.parent
module = Module(ini_info.module, srcdir)
metadata = make_metadata(module, ini_info)
repo = get_repository(pypirc_path, repo_name, project_name=metadata.name)
from . import build
built = build.main(
ini_path, formats=formats, use_vcs=use_vcs
)
if built.wheel is not None:
do_upload(built.wheel.file, built.wheel.builder.metadata, repo)
if built.sdist is not None:
do_upload(built.sdist.file, built.sdist.builder.metadata, repo)
| RepoDetails |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/metaclass1.py | {
"start": 315,
"end": 357
} | class ____(metaclass=CustomMeta): ...
| Custom |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/translate.py | {
"start": 3411,
"end": 3754
} | class ____(BaseGoogleLink):
"""
Helper class for constructing Translation Legacy Model Train link.
Legacy Models are created and managed by AutoML API.
"""
name = "Translation Legacy Model Train"
key = "translation_legacy_model_train"
format_str = TRANSLATION_LEGACY_MODEL_TRAIN_LINK
| TranslationLegacyModelTrainLink |
python | numba__numba | numba/core/compiler.py | {
"start": 16174,
"end": 16555
} | class ____(CompilerBase):
"""The default compiler
"""
def define_pipelines(self):
if self.state.flags.force_pyobject:
# either object mode
return [DefaultPassBuilder.define_objectmode_pipeline(self.state),]
else:
# or nopython mode
return [DefaultPassBuilder.define_nopython_pipeline(self.state),]
| Compiler |
python | encode__django-rest-framework | tests/test_validators.py | {
"start": 24149,
"end": 24325
} | class ____(serializers.ModelSerializer):
class Meta:
model = UniqueConstraintNullableModel
fields = ('title', 'age', 'tag')
| UniqueConstraintNullableSerializer |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 21526,
"end": 21733
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("DEBIAN", "DOCKER", "MAVEN", "NPM", "NUGET", "PYPI", "RUBYGEMS")
| PackageType |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/multiple_sources.py | {
"start": 2597,
"end": 2684
} | class ____:
def multi_sink(self, user_controlled, permissive_context):
pass
| A |
python | astropy__astropy | astropy/samp/hub_proxy.py | {
"start": 259,
"end": 6041
} | class ____:
"""
Proxy class to simplify the client interaction with a SAMP hub (via the
standard profile).
"""
def __init__(self):
self.proxy = None
self._connected = False
@property
def is_connected(self):
"""
Whether the hub proxy is currently connected to a hub.
"""
return self._connected
def connect(self, hub=None, hub_params=None, pool_size=20):
"""
Connect to the current SAMP Hub.
Parameters
----------
hub : `~astropy.samp.SAMPHubServer`, optional
The hub to connect to.
hub_params : dict, optional
Optional dictionary containing the lock-file content of the Hub
with which to connect. This dictionary has the form
``{<token-name>: <token-string>, ...}``.
pool_size : int, optional
The number of socket connections opened to communicate with the
Hub.
"""
self._connected = False
self.lockfile = {}
if hub is not None and hub_params is not None:
raise ValueError("Cannot specify both hub and hub_params")
if hub_params is None:
if hub is not None:
if not hub.is_running:
raise SAMPHubError("Hub is not running")
else:
hub_params = hub.params
else:
hub_params = get_main_running_hub()
try:
url = hub_params["samp.hub.xmlrpc.url"].replace("\\", "")
self.proxy = ServerProxyPool(
pool_size, xmlrpc.ServerProxy, url, allow_none=1
)
self.ping()
self.lockfile = copy.deepcopy(hub_params)
self._connected = True
except xmlrpc.ProtocolError as p:
# 401 Unauthorized
if p.errcode == 401:
raise SAMPHubError(
"Unauthorized access. Basic Authentication required or failed."
)
else:
raise SAMPHubError(f"Protocol Error {p.errcode}: {p.errmsg}")
def disconnect(self):
"""
Disconnect from the current SAMP Hub.
"""
if self.proxy is not None:
self.proxy.shutdown()
self.proxy = None
self._connected = False
self.lockfile = {}
@property
def _samp_hub(self):
"""
Property to abstract away the path to the hub, which allows this class
to be used for other profiles.
"""
return self.proxy.samp.hub
def ping(self):
"""
Proxy to ``ping`` SAMP Hub method (Standard Profile only).
"""
return self._samp_hub.ping()
def set_xmlrpc_callback(self, private_key, xmlrpc_addr):
"""
Proxy to ``setXmlrpcCallback`` SAMP Hub method (Standard Profile only).
"""
return self._samp_hub.setXmlrpcCallback(private_key, xmlrpc_addr)
def register(self, secret):
"""
Proxy to ``register`` SAMP Hub method.
"""
return self._samp_hub.register(secret)
def unregister(self, private_key):
"""
Proxy to ``unregister`` SAMP Hub method.
"""
return self._samp_hub.unregister(private_key)
def declare_metadata(self, private_key, metadata):
"""
Proxy to ``declareMetadata`` SAMP Hub method.
"""
return self._samp_hub.declareMetadata(private_key, metadata)
def get_metadata(self, private_key, client_id):
"""
Proxy to ``getMetadata`` SAMP Hub method.
"""
return self._samp_hub.getMetadata(private_key, client_id)
def declare_subscriptions(self, private_key, subscriptions):
"""
Proxy to ``declareSubscriptions`` SAMP Hub method.
"""
return self._samp_hub.declareSubscriptions(private_key, subscriptions)
def get_subscriptions(self, private_key, client_id):
"""
Proxy to ``getSubscriptions`` SAMP Hub method.
"""
return self._samp_hub.getSubscriptions(private_key, client_id)
def get_registered_clients(self, private_key):
"""
Proxy to ``getRegisteredClients`` SAMP Hub method.
"""
return self._samp_hub.getRegisteredClients(private_key)
def get_subscribed_clients(self, private_key, mtype):
"""
Proxy to ``getSubscribedClients`` SAMP Hub method.
"""
return self._samp_hub.getSubscribedClients(private_key, mtype)
def notify(self, private_key, recipient_id, message):
"""
Proxy to ``notify`` SAMP Hub method.
"""
return self._samp_hub.notify(private_key, recipient_id, message)
def notify_all(self, private_key, message):
"""
Proxy to ``notifyAll`` SAMP Hub method.
"""
return self._samp_hub.notifyAll(private_key, message)
def call(self, private_key, recipient_id, msg_tag, message):
"""
Proxy to ``call`` SAMP Hub method.
"""
return self._samp_hub.call(private_key, recipient_id, msg_tag, message)
def call_all(self, private_key, msg_tag, message):
"""
Proxy to ``callAll`` SAMP Hub method.
"""
return self._samp_hub.callAll(private_key, msg_tag, message)
def call_and_wait(self, private_key, recipient_id, message, timeout):
"""
Proxy to ``callAndWait`` SAMP Hub method.
"""
return self._samp_hub.callAndWait(private_key, recipient_id, message, timeout)
def reply(self, private_key, msg_id, response):
"""
Proxy to ``reply`` SAMP Hub method.
"""
return self._samp_hub.reply(private_key, msg_id, response)
| SAMPHubProxy |
python | django-haystack__django-haystack | haystack/inputs.py | {
"start": 1979,
"end": 3422
} | class ____(BaseInput):
"""
A convenience class that handles common user queries.
In addition to cleaning all tokens, it handles double quote bits as
exact matches & terms with '-' in front as NOT queries.
"""
input_type_name = "auto_query"
post_process = False
exact_match_re = re.compile(r'"(?P<phrase>.*?)"')
def prepare(self, query_obj):
query_string = super().prepare(query_obj)
exacts = self.exact_match_re.findall(query_string)
tokens = []
query_bits = []
for rough_token in self.exact_match_re.split(query_string):
if not rough_token:
continue
elif rough_token not in exacts:
# We have something that's not an exact match but may have more
# than on word in it.
tokens.extend(rough_token.split(" "))
else:
tokens.append(rough_token)
for token in tokens:
if not token:
continue
if token in exacts:
query_bits.append(Exact(token, clean=True).prepare(query_obj))
elif token.startswith("-") and len(token) > 1:
# This might break Xapian. Check on this.
query_bits.append(Not(token[1:]).prepare(query_obj))
else:
query_bits.append(Clean(token).prepare(query_obj))
return " ".join(query_bits)
| AutoQuery |
python | wandb__wandb | wandb/sdk/lib/service/service_token.py | {
"start": 2150,
"end": 3673
} | class ____(ServiceToken):
"""Connects to the service using a Unix domain socket."""
def __init__(self, *, parent_pid: int, path: str) -> None:
self._parent_pid = parent_pid
self._path = path
@override
def connect(
self,
*,
asyncer: asyncio_manager.AsyncioManager,
) -> ServiceClient:
if not ipc_support.SUPPORTS_UNIX:
raise WandbServiceConnectionError("AF_UNIX socket not supported")
try:
# TODO: This may block indefinitely if the service is unhealthy.
reader, writer = asyncer.run(
lambda: asyncio.open_unix_connection(self._path),
)
except Exception as e:
raise WandbServiceConnectionError(
f"Failed to connect to service on socket {self._path}",
) from e
return ServiceClient(asyncer, reader, writer)
@override
def _as_env_string(self):
return "-".join(
(
_CURRENT_VERSION,
str(self._parent_pid),
"unix",
str(self._path),
)
)
@staticmethod
def from_env_string(token: str) -> UnixServiceToken | None:
"""Returns a Unix service token parsed from the env var."""
match = _UNIX_TOKEN_RE.fullmatch(token)
if not match:
return None
parent_pid, path = match.groups()
return UnixServiceToken(parent_pid=int(parent_pid), path=path)
@final
| UnixServiceToken |
python | sanic-org__sanic | sanic/http/constants.py | {
"start": 669,
"end": 890
} | class ____(IntEnum):
"""Enum for representing HTTP versions"""
VERSION_1 = 1
VERSION_3 = 3
def display(self) -> str:
value = 1.1 if self.value == 1 else self.value
return f"HTTP/{value}"
| HTTP |
python | huggingface__transformers | src/transformers/models/layoutlmv3/processing_layoutlmv3.py | {
"start": 883,
"end": 7189
} | class ____(ProcessorMixin):
r"""
Constructs a LayoutLMv3 processor which combines a LayoutLMv3 image processor and a LayoutLMv3 tokenizer into a
single processor.
[`LayoutLMv3Processor`] offers all the functionalities you need to prepare data for the model.
It first uses [`LayoutLMv3ImageProcessor`] to resize and normalize document images, and optionally applies OCR to
get words and normalized bounding boxes. These are then provided to [`LayoutLMv3Tokenizer`] or
[`LayoutLMv3TokenizerFast`], which turns the words and bounding boxes into token-level `input_ids`,
`attention_mask`, `token_type_ids`, `bbox`. Optionally, one can provide integer `word_labels`, which are turned
into token-level `labels` for token classification tasks (such as FUNSD, CORD).
Args:
image_processor (`LayoutLMv3ImageProcessor`, *optional*):
An instance of [`LayoutLMv3ImageProcessor`]. The image processor is a required input.
tokenizer (`LayoutLMv3Tokenizer` or `LayoutLMv3TokenizerFast`, *optional*):
An instance of [`LayoutLMv3Tokenizer`] or [`LayoutLMv3TokenizerFast`]. The tokenizer is a required input.
"""
def __init__(self, image_processor=None, tokenizer=None, **kwargs):
super().__init__(image_processor, tokenizer)
def __call__(
self,
images,
text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
text_pair: Optional[Union[PreTokenizedInput, list[PreTokenizedInput]]] = None,
boxes: Optional[Union[list[list[int]], list[list[list[int]]]]] = None,
word_labels: Optional[Union[list[int], list[list[int]]]] = None,
add_special_tokens: bool = True,
padding: Union[bool, str, PaddingStrategy] = False,
truncation: Union[bool, str, TruncationStrategy] = None,
max_length: Optional[int] = None,
stride: int = 0,
pad_to_multiple_of: Optional[int] = None,
return_token_type_ids: Optional[bool] = None,
return_attention_mask: Optional[bool] = None,
return_overflowing_tokens: bool = False,
return_special_tokens_mask: bool = False,
return_offsets_mapping: bool = False,
return_length: bool = False,
verbose: bool = True,
return_tensors: Optional[Union[str, TensorType]] = None,
**kwargs,
) -> BatchEncoding:
"""
This method first forwards the `images` argument to [`~LayoutLMv3ImageProcessor.__call__`]. In case
[`LayoutLMv3ImageProcessor`] was initialized with `apply_ocr` set to `True`, it passes the obtained words and
bounding boxes along with the additional arguments to [`~LayoutLMv3Tokenizer.__call__`] and returns the output,
together with resized and normalized `pixel_values`. In case [`LayoutLMv3ImageProcessor`] was initialized with
`apply_ocr` set to `False`, it passes the words (`text`/``text_pair`) and `boxes` specified by the user along
with the additional arguments to [`~LayoutLMv3Tokenizer.__call__`] and returns the output, together with
resized and normalized `pixel_values`.
Please refer to the docstring of the above two methods for more information.
"""
# verify input
if self.image_processor.apply_ocr and (boxes is not None):
raise ValueError(
"You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True."
)
if self.image_processor.apply_ocr and (word_labels is not None):
raise ValueError(
"You cannot provide word labels if you initialized the image processor with apply_ocr set to True."
)
# first, apply the image processor
features = self.image_processor(images=images, return_tensors=return_tensors)
# second, apply the tokenizer
if text is not None and self.image_processor.apply_ocr and text_pair is None:
if isinstance(text, str):
text = [text] # add batch dimension (as the image processor always adds a batch dimension)
text_pair = features["words"]
encoded_inputs = self.tokenizer(
text=text if text is not None else features["words"],
text_pair=text_pair if text_pair is not None else None,
boxes=boxes if boxes is not None else features["boxes"],
word_labels=word_labels,
add_special_tokens=add_special_tokens,
padding=padding,
truncation=truncation,
max_length=max_length,
stride=stride,
pad_to_multiple_of=pad_to_multiple_of,
return_token_type_ids=return_token_type_ids,
return_attention_mask=return_attention_mask,
return_overflowing_tokens=return_overflowing_tokens,
return_special_tokens_mask=return_special_tokens_mask,
return_offsets_mapping=return_offsets_mapping,
return_length=return_length,
verbose=verbose,
return_tensors=return_tensors,
**kwargs,
)
# add pixel values
images = features.pop("pixel_values")
if return_overflowing_tokens is True:
images = self.get_overflowing_images(images, encoded_inputs["overflow_to_sample_mapping"])
encoded_inputs["pixel_values"] = images
return encoded_inputs
def get_overflowing_images(self, images, overflow_to_sample_mapping):
# in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
images_with_overflow = []
for sample_idx in overflow_to_sample_mapping:
images_with_overflow.append(images[sample_idx])
if len(images_with_overflow) != len(overflow_to_sample_mapping):
raise ValueError(
"Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"
f" {len(images_with_overflow)} and {len(overflow_to_sample_mapping)}"
)
return images_with_overflow
@property
def model_input_names(self):
return ["input_ids", "bbox", "attention_mask", "pixel_values"]
__all__ = ["LayoutLMv3Processor"]
| LayoutLMv3Processor |
python | apache__airflow | providers/cncf/kubernetes/tests/unit/cncf/kubernetes/operators/test_job.py | {
"start": 36307,
"end": 40609
} | class ____:
@pytest.fixture(autouse=True)
def setup_tests(self):
self._default_client_patch = patch(f"{HOOK_CLASS}._get_default_client")
self._default_client_mock = self._default_client_patch.start()
yield
patch.stopall()
@patch(f"{HOOK_CLASS}.get_job_status")
@patch(f"{HOOK_CLASS}.wait_until_job_complete")
@patch("kubernetes.config.load_kube_config")
@patch("kubernetes.client.api.BatchV1Api.delete_namespaced_job")
def test_execute(
self,
mock_delete_namespaced_job,
mock_load_kube_config,
mock_wait_until_job_complete,
mock_get_job_status,
):
op = KubernetesDeleteJobOperator(
kubernetes_conn_id="kubernetes_default",
task_id="test_delete_job",
name=JOB_NAME,
namespace=JOB_NAMESPACE,
)
op.execute(None)
assert not mock_wait_until_job_complete.called
mock_get_job_status.assert_called_once_with(job_name=JOB_NAME, namespace=JOB_NAMESPACE)
mock_delete_namespaced_job.assert_called_once_with(name=JOB_NAME, namespace=JOB_NAMESPACE)
@patch(f"{HOOK_CLASS}.get_job_status")
@patch(f"{HOOK_CLASS}.wait_until_job_complete")
@patch("kubernetes.config.load_kube_config")
@patch("kubernetes.client.api.BatchV1Api.delete_namespaced_job")
def test_execute_wait_for_completion_true(
self,
mock_delete_namespaced_job,
mock_load_kube_config,
mock_wait_until_job_complete,
mock_get_job_status,
):
op = KubernetesDeleteJobOperator(
kubernetes_conn_id="kubernetes_default",
task_id="test_delete_job",
name=JOB_NAME,
namespace=JOB_NAMESPACE,
wait_for_completion=True,
poll_interval=JOB_POLL_INTERVAL,
)
op.execute({})
mock_wait_until_job_complete.assert_called_once_with(
job_name=JOB_NAME, namespace=JOB_NAMESPACE, job_poll_interval=JOB_POLL_INTERVAL
)
assert not mock_get_job_status.called
mock_delete_namespaced_job.assert_called_once_with(name=JOB_NAME, namespace=JOB_NAMESPACE)
@pytest.mark.parametrize(
("on_status", "success", "fail", "deleted"),
[
(None, True, True, True),
(None, True, False, True),
(None, False, True, True),
(None, False, False, True),
("Complete", True, True, True),
("Complete", True, False, True),
("Complete", False, True, False),
("Complete", False, False, False),
("Failed", True, True, True),
("Failed", True, False, False),
("Failed", False, True, True),
("Failed", False, False, False),
],
)
@patch(f"{HOOK_CLASS}.is_job_failed")
@patch(f"{HOOK_CLASS}.is_job_successful")
@patch("kubernetes.config.load_kube_config")
@patch("kubernetes.client.api.BatchV1Api.delete_namespaced_job")
def test_execute_delete_on_status(
self,
mock_delete_namespaced_job,
mock_load_kube_config,
mock_is_job_successful,
mock_is_job_failed,
on_status,
success,
fail,
deleted,
):
mock_is_job_successful.return_value = success
mock_is_job_failed.return_value = fail
op = KubernetesDeleteJobOperator(
kubernetes_conn_id="kubernetes_default",
task_id="test_delete_job",
name=JOB_NAME,
namespace=JOB_NAMESPACE,
delete_on_status=on_status,
)
op.execute({})
assert mock_delete_namespaced_job.called == deleted
def test_execute_delete_on_status_exception(self):
invalid_delete_on_status = "".join(
random.choices(string.ascii_letters + string.digits, k=random.randint(1, 16))
)
op = KubernetesDeleteJobOperator(
kubernetes_conn_id="kubernetes_default",
task_id="test_delete_job",
name=JOB_NAME,
namespace=JOB_NAMESPACE,
delete_on_status=invalid_delete_on_status,
)
with pytest.raises(AirflowException):
op.execute({})
@pytest.mark.execution_timeout(300)
| TestKubernetesDeleteJobOperator |
python | tiangolo__fastapi | scripts/notify_translations.py | {
"start": 3238,
"end": 3542
} | class ____(BaseSettings):
model_config = {"env_ignore_empty": True}
github_repository: str
github_token: SecretStr
github_event_path: Path
github_event_name: Union[str, None] = None
httpx_timeout: int = 30
debug: Union[bool, None] = False
number: int | None = None
| Settings |
python | pydantic__pydantic | tests/test_json.py | {
"start": 1404,
"end": 1463
} | class ____(Enum):
foo = 'bar'
snap = 'crackle'
| MyEnum |
python | scipy__scipy | scipy/stats/tests/test_morestats.py | {
"start": 26159,
"end": 32993
} | class ____:
def test_small(self, xp):
x = xp.asarray([1, 2, 3, 3, 4])
y = xp.asarray([3, 2, 6, 1, 6, 1, 4, 1])
W, pval = stats.ansari(x, y)
xp_assert_close(W, xp.asarray(23.5))
xp_assert_close(pval, xp.asarray(0.13499256881897437))
def test_approx(self, xp):
ramsay = xp.asarray([111, 107, 100, 99, 102, 106, 109, 108, 104, 99,
101, 96, 97, 102, 107, 113, 116, 113, 110, 98])
parekh = xp.asarray([107, 108, 106, 98, 105, 103, 110, 105, 104,
100, 96, 108, 103, 104, 114, 114, 113, 108,
106, 99])
W, pval = stats.ansari(ramsay, parekh)
xp_assert_close(W, xp.asarray(185.5))
xp_assert_close(pval, xp.asarray(0.18145819972867083))
def test_exact(self, xp):
x, y = xp.asarray([1, 2, 3, 4]), xp.asarray([15, 5, 20, 8, 10, 12])
W, pval = stats.ansari(x, y)
xp_assert_close(W, xp.asarray(10.0))
xp_assert_close(pval, xp.asarray(0.533333333333333333))
@pytest.mark.skip_xp_backends('jax.numpy', reason='no _axis_nan_policy decorator')
@pytest.mark.parametrize('args', [([], [1.]), ([1.], [])])
def test_bad_arg(self, args, xp):
args = [xp.asarray(arg) for arg in args]
with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
res = stats.ansari(*args)
xp_assert_equal(res.statistic, xp.asarray(xp.nan))
xp_assert_equal(res.pvalue, xp.asarray(xp.nan))
def test_bad_alternative(self, xp):
# invalid value for alternative must raise a ValueError
x1 = xp.asarray([1, 2, 3, 4])
x2 = xp.asarray([5, 6, 7, 8])
match = "'alternative' must be 'two-sided'"
with assert_raises(ValueError, match=match):
stats.ansari(x1, x2, alternative='foo')
def test_alternative_exact(self, xp):
x1 = xp.asarray([-5, 1, 5, 10, 15, 20, 25.]) # high scale, loc=10
x2 = xp.asarray([7.5, 8.5, 9.5, 10.5, 11.5, 12.5]) # low scale, loc=10
# ratio of scales is greater than 1. So, the
# p-value must be high when `alternative='less'`
# and low when `alternative='greater'`.
statistic, pval = stats.ansari(x1, x2)
pval_l = stats.ansari(x1, x2, alternative='less').pvalue
pval_g = stats.ansari(x1, x2, alternative='greater').pvalue
assert pval_l > 0.95
assert pval_g < 0.05 # level of significance.
# also check if the p-values sum up to 1 plus the probability
# mass under the calculated statistic.
prob = _abw_state.a.pmf(float(statistic), x1.shape[0], x2.shape[0])
prob = xp.asarray(float(prob))
xp_assert_close(pval_g + pval_l, 1 + prob, atol=1e-12)
# also check if one of the one-sided p-value equals half the
# two-sided p-value and the other one-sided p-value is its
# compliment.
xp_assert_close(pval_g, pval/2, atol=1e-12)
xp_assert_close(pval_l, 1+prob-pval/2, atol=1e-12)
# sanity check. The result should flip if
# we exchange x and y.
pval_l_reverse = stats.ansari(x2, x1, alternative='less').pvalue
pval_g_reverse = stats.ansari(x2, x1, alternative='greater').pvalue
assert pval_l_reverse < 0.05
assert pval_g_reverse > 0.95
@pytest.mark.parametrize(
'x, y, alternative, expected',
# the tests are designed in such a way that the
# if else statement in ansari test for exact
# mode is covered.
[([1, 2, 3, 4], [5, 6, 7, 8], 'less', 0.6285714285714),
([1, 2, 3, 4], [5, 6, 7, 8], 'greater', 0.6285714285714),
([1, 2, 3], [4, 5, 6, 7, 8], 'less', 0.8928571428571),
([1, 2, 3], [4, 5, 6, 7, 8], 'greater', 0.2857142857143),
([1, 2, 3, 4, 5], [6, 7, 8], 'less', 0.2857142857143),
([1, 2, 3, 4, 5], [6, 7, 8], 'greater', 0.8928571428571)]
)
def test_alternative_exact_with_R(self, x, y, alternative, expected, xp):
# testing with R on arbitrary data
# Sample R code used for the third test case above:
# ```R
# > options(digits=16)
# > x <- c(1,2,3)
# > y <- c(4,5,6,7,8)
# > ansari.test(x, y, alternative='less', exact=TRUE)
#
# Ansari-Bradley test
#
# data: x and y
# AB = 6, p-value = 0.8928571428571
# alternative hypothesis: true ratio of scales is less than 1
#
# ```
x, y = xp.asarray(x), xp.asarray(y)
pval = stats.ansari(x, y, alternative=alternative).pvalue
xp_assert_close(pval, xp.asarray(expected), atol=1e-12)
def test_alternative_approx(self, xp):
# intuitive tests for approximation
x1 = xp.asarray(stats.norm.rvs(0, 5, size=100, random_state=123))
x2 = xp.asarray(stats.norm.rvs(0, 2, size=100, random_state=123))
# for m > 55 or n > 55, the test should automatically
# switch to approximation.
pval_l = stats.ansari(x1, x2, alternative='less').pvalue
pval_g = stats.ansari(x1, x2, alternative='greater').pvalue
xp_assert_close(pval_l, xp.asarray(1.0, dtype=xp.float64), atol=1e-12)
xp_assert_close(pval_g, xp.asarray(0.0, dtype=xp.float64), atol=1e-12)
# also check if one of the one-sided p-value equals half the
# two-sided p-value and the other one-sided p-value is its
# compliment.
x1 = xp.asarray(stats.norm.rvs(0, 2, size=60, random_state=123))
x2 = xp.asarray(stats.norm.rvs(0, 1.5, size=60, random_state=123))
pval = stats.ansari(x1, x2).pvalue
pval_l = stats.ansari(x1, x2, alternative='less').pvalue
pval_g = stats.ansari(x1, x2, alternative='greater').pvalue
xp_assert_close(pval_g, pval/2, atol=1e-12)
xp_assert_close(pval_l, 1-pval/2, atol=1e-12)
@pytest.mark.parametrize('dtype', [None, 'float32', 'float64'])
@pytest.mark.parametrize('n', [10, 100]) # affects code path
@pytest.mark.parametrize('ties', [False, True]) # affects code path
def test_dtypes(self, dtype, n, ties, xp):
if is_numpy(xp) and xp.__version__ < "2.0" and dtype == 'float32':
pytest.skip("Scalar dtypes only respected after NEP 50.")
dtype = xp_default_dtype(xp) if dtype is None else getattr(xp, dtype)
rng = np.random.default_rng(78587342806484)
x, y = rng.integers(6, size=(2, n)) if ties else rng.random(size=(2, n))
ref = stats.ansari(x, y)
res = stats.ansari(xp.asarray(x, dtype=dtype), xp.asarray(y, dtype=dtype))
xp_assert_close(res.statistic, xp.asarray(ref.statistic, dtype=dtype))
xp_assert_close(res.pvalue, xp.asarray(ref.pvalue, dtype=dtype))
@make_xp_test_case(stats.bartlett)
| TestAnsari |
python | kamyu104__LeetCode-Solutions | Python/determine-if-two-strings-are-close.py | {
"start": 50,
"end": 539
} | class ____(object):
def closeStrings(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: bool
"""
if len(word1) != len(word2):
return False
cnt1, cnt2 = collections.Counter(word1), collections.Counter(word2) # Reuse of keys
return set(cnt1.iterkeys()) == set(cnt2.iterkeys()) and \
collections.Counter(cnt1.itervalues()) == collections.Counter(cnt2.itervalues())
| Solution |
python | huggingface__transformers | examples/pytorch/test_pytorch_examples.py | {
"start": 2591,
"end": 23121
} | class ____(TestCasePlus):
def test_run_glue(self):
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
run_glue.py
--model_name_or_path distilbert/distilbert-base-uncased
--output_dir {tmp_dir}
--train_file ./tests/fixtures/tests_samples/MRPC/train.csv
--validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv
--do_train
--do_eval
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--learning_rate=1e-4
--max_steps=10
--warmup_steps=2
--seed=42
--max_seq_length=128
""".split()
if is_torch_fp16_available_on_device(torch_device):
testargs.append("--fp16")
with patch.object(sys, "argv", testargs):
run_glue.main()
result = get_results(tmp_dir)
self.assertGreaterEqual(result["eval_accuracy"], 0.75)
def test_run_clm(self):
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
run_clm.py
--model_name_or_path distilbert/distilgpt2
--train_file ./tests/fixtures/sample_text.txt
--validation_file ./tests/fixtures/sample_text.txt
--do_train
--do_eval
--block_size 128
--per_device_train_batch_size 5
--per_device_eval_batch_size 5
--num_train_epochs 2
--output_dir {tmp_dir}
""".split()
if backend_device_count(torch_device) > 1:
# Skipping because there are not enough batches to train the model + would need a drop_last to work.
return
if torch_device == "cpu":
testargs.append("--use_cpu")
with patch.object(sys, "argv", testargs):
run_clm.main()
result = get_results(tmp_dir)
self.assertLess(result["perplexity"], 100)
def test_run_clm_config_overrides(self):
# test that config_overrides works, despite the misleading dumps of default un-updated
# config via tokenizer
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
run_clm.py
--model_type gpt2
--tokenizer_name openai-community/gpt2
--train_file ./tests/fixtures/sample_text.txt
--output_dir {tmp_dir}
--config_overrides n_embd=10,n_head=2
""".split()
if torch_device == "cpu":
testargs.append("--use_cpu")
logger = run_clm.logger
with patch.object(sys, "argv", testargs):
with CaptureLogger(logger) as cl:
run_clm.main()
self.assertIn('"n_embd": 10', cl.out)
self.assertIn('"n_head": 2', cl.out)
def test_run_mlm(self):
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
run_mlm.py
--model_name_or_path distilbert/distilroberta-base
--train_file ./tests/fixtures/sample_text.txt
--validation_file ./tests/fixtures/sample_text.txt
--output_dir {tmp_dir}
--do_train
--do_eval
--prediction_loss_only
--num_train_epochs=1
""".split()
if torch_device == "cpu":
testargs.append("--use_cpu")
with patch.object(sys, "argv", testargs):
run_mlm.main()
result = get_results(tmp_dir)
self.assertLess(result["perplexity"], 42)
def test_run_ner(self):
# with so little data distributed training needs more epochs to get the score on par with 0/1 gpu
epochs = 7 if backend_device_count(torch_device) > 1 else 2
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
run_ner.py
--model_name_or_path google-bert/bert-base-uncased
--train_file tests/fixtures/tests_samples/conll/sample.json
--validation_file tests/fixtures/tests_samples/conll/sample.json
--output_dir {tmp_dir}
--do_train
--do_eval
--warmup_steps=2
--learning_rate=2e-4
--per_device_train_batch_size=2
--per_device_eval_batch_size=2
--num_train_epochs={epochs}
--seed 7
""".split()
if torch_device == "cpu":
testargs.append("--use_cpu")
with patch.object(sys, "argv", testargs):
run_ner.main()
result = get_results(tmp_dir)
self.assertGreaterEqual(result["eval_accuracy"], 0.75)
self.assertLess(result["eval_loss"], 0.5)
def test_run_squad(self):
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
run_qa.py
--model_name_or_path google-bert/bert-base-uncased
--version_2_with_negative
--train_file tests/fixtures/tests_samples/SQUAD/sample.json
--validation_file tests/fixtures/tests_samples/SQUAD/sample.json
--output_dir {tmp_dir}
--max_steps=10
--warmup_steps=2
--do_train
--do_eval
--learning_rate=2e-4
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
""".split()
with patch.object(sys, "argv", testargs):
run_squad.main()
result = get_results(tmp_dir)
self.assertGreaterEqual(result["eval_f1"], 30)
self.assertGreaterEqual(result["eval_exact"], 30)
def test_run_squad_seq2seq(self):
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
run_seq2seq_qa.py
--model_name_or_path google-t5/t5-small
--context_column context
--question_column question
--answer_column answers
--version_2_with_negative
--train_file tests/fixtures/tests_samples/SQUAD/sample.json
--validation_file tests/fixtures/tests_samples/SQUAD/sample.json
--output_dir {tmp_dir}
--max_steps=10
--warmup_steps=2
--do_train
--do_eval
--learning_rate=2e-4
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--predict_with_generate
""".split()
with patch.object(sys, "argv", testargs):
run_squad_seq2seq.main()
result = get_results(tmp_dir)
self.assertGreaterEqual(result["eval_f1"], 30)
self.assertGreaterEqual(result["eval_exact"], 30)
def test_run_swag(self):
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
run_swag.py
--model_name_or_path google-bert/bert-base-uncased
--train_file tests/fixtures/tests_samples/swag/sample.json
--validation_file tests/fixtures/tests_samples/swag/sample.json
--output_dir {tmp_dir}
--max_steps=20
--warmup_steps=2
--do_train
--do_eval
--learning_rate=2e-4
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
""".split()
with patch.object(sys, "argv", testargs):
run_swag.main()
result = get_results(tmp_dir)
self.assertGreaterEqual(result["eval_accuracy"], 0.8)
def test_generation(self):
testargs = ["run_generation.py", "--prompt=Hello", "--length=10", "--seed=42"]
if is_torch_fp16_available_on_device(torch_device):
testargs.append("--fp16")
model_type, model_name = (
"--model_type=gpt2",
"--model_name_or_path=sshleifer/tiny-gpt2",
)
with patch.object(sys, "argv", testargs + [model_type, model_name]):
result = run_generation.main()
self.assertGreaterEqual(len(result[0]), 10)
@slow
def test_run_summarization(self):
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
run_summarization.py
--model_name_or_path google-t5/t5-small
--train_file tests/fixtures/tests_samples/xsum/sample.json
--validation_file tests/fixtures/tests_samples/xsum/sample.json
--output_dir {tmp_dir}
--max_steps=50
--warmup_steps=8
--do_train
--do_eval
--learning_rate=2e-4
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--predict_with_generate
""".split()
with patch.object(sys, "argv", testargs):
run_summarization.main()
result = get_results(tmp_dir)
self.assertGreaterEqual(result["eval_rouge1"], 10)
self.assertGreaterEqual(result["eval_rouge2"], 2)
self.assertGreaterEqual(result["eval_rougeL"], 7)
self.assertGreaterEqual(result["eval_rougeLsum"], 7)
@slow
def test_run_translation(self):
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
run_translation.py
--model_name_or_path sshleifer/student_marian_en_ro_6_1
--source_lang en
--target_lang ro
--train_file tests/fixtures/tests_samples/wmt16/sample.json
--validation_file tests/fixtures/tests_samples/wmt16/sample.json
--output_dir {tmp_dir}
--max_steps=50
--warmup_steps=8
--do_train
--do_eval
--learning_rate=3e-3
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--predict_with_generate
--source_lang en_XX
--target_lang ro_RO
--max_source_length 512
""".split()
with patch.object(sys, "argv", testargs):
run_translation.main()
result = get_results(tmp_dir)
self.assertGreaterEqual(result["eval_bleu"], 30)
@slow
def test_run_image_classification(self):
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
run_image_classification.py
--output_dir {tmp_dir}
--model_name_or_path google/vit-base-patch16-224-in21k
--dataset_name hf-internal-testing/cats_vs_dogs_sample
--do_train
--do_eval
--learning_rate 1e-4
--per_device_train_batch_size 2
--per_device_eval_batch_size 1
--remove_unused_columns False
--dataloader_num_workers 16
--metric_for_best_model accuracy
--max_steps 10
--train_val_split 0.1
--seed 42
--label_column_name labels
""".split()
if is_torch_fp16_available_on_device(torch_device):
testargs.append("--fp16")
with patch.object(sys, "argv", testargs):
run_image_classification.main()
result = get_results(tmp_dir)
self.assertGreaterEqual(result["eval_accuracy"], 0.8)
@slow
def test_run_speech_recognition_ctc(self):
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
run_speech_recognition_ctc.py
--output_dir {tmp_dir}
--model_name_or_path hf-internal-testing/tiny-random-wav2vec2
--dataset_name hf-internal-testing/librispeech_asr_dummy
--dataset_config_name clean
--train_split_name validation
--eval_split_name validation
--do_train
--do_eval
--learning_rate 1e-4
--per_device_train_batch_size 2
--per_device_eval_batch_size 1
--remove_unused_columns False
--preprocessing_num_workers 16
--max_steps 10
--seed 42
""".split()
if is_torch_fp16_available_on_device(torch_device):
testargs.append("--fp16")
with patch.object(sys, "argv", testargs):
run_speech_recognition_ctc.main()
result = get_results(tmp_dir)
self.assertLess(result["eval_loss"], result["train_loss"])
def test_run_speech_recognition_ctc_adapter(self):
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
run_speech_recognition_ctc_adapter.py
--output_dir {tmp_dir}
--model_name_or_path hf-internal-testing/tiny-random-wav2vec2
--dataset_name hf-internal-testing/librispeech_asr_dummy
--dataset_config_name clean
--train_split_name validation
--eval_split_name validation
--do_train
--do_eval
--learning_rate 1e-4
--per_device_train_batch_size 2
--per_device_eval_batch_size 1
--remove_unused_columns False
--preprocessing_num_workers 16
--max_steps 10
--target_language tur
--seed 42
""".split()
if is_torch_fp16_available_on_device(torch_device):
testargs.append("--fp16")
with patch.object(sys, "argv", testargs):
run_speech_recognition_ctc_adapter.main()
result = get_results(tmp_dir)
self.assertTrue(os.path.isfile(os.path.join(tmp_dir, "./adapter.tur.safetensors")))
self.assertLess(result["eval_loss"], result["train_loss"])
def test_run_speech_recognition_seq2seq(self):
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
run_speech_recognition_seq2seq.py
--output_dir {tmp_dir}
--model_name_or_path hf-internal-testing/tiny-random-speech-encoder-decoder
--dataset_name hf-internal-testing/librispeech_asr_dummy
--dataset_config_name clean
--train_split_name validation
--eval_split_name validation
--do_train
--do_eval
--learning_rate 1e-4
--per_device_train_batch_size 2
--per_device_eval_batch_size 4
--remove_unused_columns False
--preprocessing_num_workers 16
--max_steps 10
--seed 42
""".split()
if is_torch_fp16_available_on_device(torch_device):
testargs.append("--fp16")
with patch.object(sys, "argv", testargs):
run_speech_recognition_seq2seq.main()
result = get_results(tmp_dir)
self.assertLess(result["eval_loss"], result["train_loss"])
def test_run_audio_classification(self):
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
run_audio_classification.py
--output_dir {tmp_dir}
--model_name_or_path hf-internal-testing/tiny-random-wav2vec2
--dataset_name anton-l/superb_demo
--dataset_config_name ks
--train_split_name test
--eval_split_name test
--audio_column_name audio
--label_column_name label
--do_train
--do_eval
--learning_rate 1e-4
--per_device_train_batch_size 2
--per_device_eval_batch_size 1
--remove_unused_columns False
--num_train_epochs 10
--max_steps 50
--seed 42
""".split()
if is_torch_fp16_available_on_device(torch_device):
testargs.append("--fp16")
with patch.object(sys, "argv", testargs):
run_audio_classification.main()
result = get_results(tmp_dir)
self.assertLess(result["eval_loss"], result["train_loss"])
def test_run_wav2vec2_pretraining(self):
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
run_wav2vec2_pretraining_no_trainer.py
--output_dir {tmp_dir}
--model_name_or_path hf-internal-testing/tiny-random-wav2vec2
--dataset_name hf-internal-testing/librispeech_asr_dummy
--dataset_config_names clean
--dataset_split_names validation
--learning_rate 1e-4
--per_device_train_batch_size 4
--per_device_eval_batch_size 4
--preprocessing_num_workers 16
--max_train_steps 2
--validation_split_percentage 5
--seed 42
""".split()
with patch.object(sys, "argv", testargs):
run_wav2vec2_pretraining_no_trainer.main()
model = Wav2Vec2ForPreTraining.from_pretrained(tmp_dir)
self.assertIsNotNone(model)
def test_run_vit_mae_pretraining(self):
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
run_mae.py
--output_dir {tmp_dir}
--dataset_name hf-internal-testing/cats_vs_dogs_sample
--do_train
--do_eval
--learning_rate 1e-4
--per_device_train_batch_size 2
--per_device_eval_batch_size 1
--remove_unused_columns False
--dataloader_num_workers 16
--metric_for_best_model accuracy
--max_steps 10
--train_val_split 0.1
--seed 42
""".split()
if is_torch_fp16_available_on_device(torch_device):
testargs.append("--fp16")
with patch.object(sys, "argv", testargs):
run_mae.main()
model = ViTMAEForPreTraining.from_pretrained(tmp_dir)
self.assertIsNotNone(model)
@slow
def test_run_semantic_segmentation(self):
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
run_semantic_segmentation.py
--output_dir {tmp_dir}
--dataset_name huggingface/semantic-segmentation-test-sample
--do_train
--do_eval
--remove_unused_columns False
--max_steps 10
--learning_rate=2e-4
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--seed 32
""".split()
if is_torch_fp16_available_on_device(torch_device):
testargs.append("--fp16")
with patch.object(sys, "argv", testargs):
run_semantic_segmentation.main()
result = get_results(tmp_dir)
self.assertGreaterEqual(result["eval_overall_accuracy"], 0.1)
@slow
@patch.dict(os.environ, {"WANDB_DISABLED": "true"})
def test_run_object_detection(self):
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
run_object_detection.py
--model_name_or_path qubvel-hf/detr-resnet-50-finetuned-10k-cppe5
--output_dir {tmp_dir}
--dataset_name qubvel-hf/cppe-5-sample
--do_train
--do_eval
--remove_unused_columns False
--eval_do_concat_batches False
--max_steps 10
--learning_rate=1e-6
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
--seed 32
""".split()
if is_torch_fp16_available_on_device(torch_device):
testargs.append("--fp16")
with patch.object(sys, "argv", testargs):
run_object_detection.main()
result = get_results(tmp_dir)
self.assertGreaterEqual(result["test_map"], 0.1)
@slow
@patch.dict(os.environ, {"WANDB_DISABLED": "true"})
def test_run_instance_segmentation(self):
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
run_instance_segmentation.py
--model_name_or_path qubvel-hf/finetune-instance-segmentation-ade20k-mini-mask2former
--output_dir {tmp_dir}
--dataset_name qubvel-hf/ade20k-nano
--do_reduce_labels
--image_height 256
--image_width 256
--do_train
--num_train_epochs 1
--learning_rate 1e-5
--lr_scheduler_type constant
--per_device_train_batch_size 2
--per_device_eval_batch_size 1
--do_eval
--eval_strategy epoch
--seed 32
""".split()
if is_torch_fp16_available_on_device(torch_device):
testargs.append("--fp16")
with patch.object(sys, "argv", testargs):
run_instance_segmentation.main()
result = get_results(tmp_dir)
self.assertGreaterEqual(result["test_map"], 0.1)
| ExamplesTests |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 261183,
"end": 261483
} | class ____(_PrintableStructure):
_fields_ = [
('version', c_uint),
('state', c_uint),
]
def __init__(self):
super(c_nvmlPowerSmoothingState_v1_t, self).__init__(version=nvmlPowerSmoothingState_v1)
nvmlPowerSmoothingProfile_v1=0x1000018
| c_nvmlPowerSmoothingState_v1_t |
python | PrefectHQ__prefect | src/prefect/cache_policies.py | {
"start": 8500,
"end": 9015
} | class ____(CachePolicy):
"""
Policy that always returns `None` for the computed cache key.
This policy prevents persistence and avoids caching entirely.
"""
def compute_key(
self,
task_ctx: TaskRunContext,
inputs: dict[str, Any],
flow_parameters: dict[str, Any],
**kwargs: Any,
) -> Optional[str]:
return None
def __add__(self, other: "CachePolicy") -> "CachePolicy":
# adding _None is a no-op
return other
@dataclass
| _None |
python | Textualize__textual | docs/examples/guide/reactivity/set_reactive01.py | {
"start": 1070,
"end": 1555
} | class ____(App):
CSS = """
Screen {
align: center middle;
}
"""
greeting_no: var[int] = var(0)
BINDINGS = [("space", "greeting")]
def compose(self) -> ComposeResult:
yield Greeter(who="Textual")
def action_greeting(self) -> None:
self.greeting_no = (self.greeting_no + 1) % len(GREETINGS)
self.query_one(Greeter).greeting = GREETINGS[self.greeting_no]
if __name__ == "__main__":
app = NameApp()
app.run()
| NameApp |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP049_1.py | {
"start": 1438,
"end": 1665
} | class ____[T]:
def f[_T](self): # No fix, collides with `T` from outer scope
v1 = cast(_T, ...)
v2 = cast('_T', ...)
# Unfixable as the new name collides with a variable visible from one of the inner scopes
| C |
python | getsentry__sentry | src/sentry/auth/services/access/impl.py | {
"start": 863,
"end": 2849
} | class ____(AccessService):
def get_permissions_for_user(self, user_id: int) -> frozenset[str]:
user = user_service.get_user(user_id)
if user is None:
return frozenset()
return user.roles | user.permissions
def get_auth_provider(self, organization_id: int) -> RpcAuthProvider | None:
try:
return serialize_auth_provider(
AuthProvider.objects.get(organization_id=organization_id)
)
except AuthProvider.DoesNotExist:
return None
def get_auth_identity_for_user(
self, auth_provider_id: int, user_id: int
) -> RpcAuthIdentity | None:
try:
return serialize_auth_identity(
AuthIdentity.objects.get(auth_provider_id=auth_provider_id, user_id=user_id)
)
except AuthIdentity.DoesNotExist:
return None
def can_override_sso_as_owner(
self, auth_provider: RpcAuthProvider, member: RpcOrganizationMemberSummary
) -> bool:
"""If an owner is trying to gain access, allow bypassing SSO if there are no
other owners with SSO enabled.
"""
# get member role
try:
member_role = OrganizationMemberMapping.objects.get(
organizationmember_id=member.id, organization_id=member.organization_id
).role
except OrganizationMemberMapping.DoesNotExist:
return False
if member_role != roles.get_top_dog().id:
return False
user_ids = (
OrganizationMemberMapping.objects.filter(
role=roles.get_top_dog().id,
organization_id=member.organization_id,
user__is_active=True,
)
.exclude(id=member.id)
.values_list("user_id")
)
return not AuthIdentity.objects.filter(
auth_provider_id=auth_provider.id, user__in=user_ids
).exists()
| ControlAccessService |
python | streamlit__streamlit | lib/streamlit/elements/widgets/text_widgets.py | {
"start": 2212,
"end": 2457
} | class ____:
value: str | None
def deserialize(self, ui_value: str | None) -> str | None:
return ui_value if ui_value is not None else self.value
def serialize(self, v: str | None) -> str | None:
return v
| TextAreaSerde |
python | huggingface__transformers | src/transformers/models/blt/configuration_blt.py | {
"start": 10654,
"end": 19793
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`BltModel`]. It is used to instantiate a
Blt model according to the specified arguments, defining the model architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 260):
Vocabulary size of the Blt model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`BltModel`].
max_position_embeddings (`int`, *optional*, defaults to 4096):
The maximum sequence length that this model might ever be used with.
patch_in_forward (`bool`, *optional*, defaults to `True`):
Whether to perform patching during the forward pass.
patch_size (`int`, *optional*, defaults to 4):
Size of the patches used in the patching mechanism.
patching_mode (`str`, *optional*, defaults to `"entropy"`):
The mode used for patching, such as entropy-based patching.
patching_threshold (`float`, *optional*, defaults to 1.34):
Threshold value used for determining when to apply patches.
patching_batch_size (`int`, *optional*, defaults to 1):
Batch size used during the patching process.
max_patch_length (`int`, *optional*):
Maximum length of patches that can be generated.
cross_attn_k (`int`, *optional*, defaults to 2):
Number of cross-attention heads used in the model.
encoder_hash_byte_group_size (`list`, *optional*):
List of byte group sizes used in the encoder hash function.
encoder_hash_byte_group_vocab (`int`, *optional*, defaults to 500002):
Vocabulary size for the encoder hash byte groups.
encoder_hash_byte_group_nb_functions (`int`, *optional*, defaults to 1):
Number of hash functions used in the encoder byte grouping.
patcher_config (`BltPatcherConfig`, *optional*):
Configuration for the patcher component of the model.
encoder_config (`BltLocalEncoderConfig`, *optional*):
Configuration for the local encoder component of the model.
decoder_config (`BltLocalDecoderConfig`, *optional*):
Configuration for the local decoder component of the model.
global_config (`BltGlobalTransformerConfig`, *optional*):
Configuration for the global transformer component of the model.
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
Whether to tie weight embeddings.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
rope_parameters (`RopeParameters`, *optional*):
Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain
a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE
with longer `max_position_embeddings`.
```python
>>> from transformers import BltModel, BltConfig
>>> # Initializing a Blt configuration
>>> configuration = BltConfig()
>>> # Initializing a model from the configuration
>>> model = BltModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```
Checkpoint: [facebook/blt](https://huggingface.co/facebook/blt)
"""
model_type = "blt"
keys_to_ignore_at_inference = ["past_key_values"]
default_theta = 500000.0
sub_configs = {
"patcher_config": BltPatcherConfig,
"encoder_config": BltLocalEncoderConfig,
"decoder_config": BltLocalDecoderConfig,
"global_config": BltGlobalTransformerConfig,
}
def __init__(
self,
vocab_size: Optional[int] = 260,
max_position_embeddings: Optional[int] = 4096,
patch_in_forward: Optional[bool] = True,
patch_size: Optional[int] = 4,
patching_mode: Optional[str] = "entropy",
patching_threshold: Optional[float] = 1.335442066192627,
patching_batch_size: Optional[int] = 1,
max_patch_length: Optional[int] = None,
cross_attn_k: Optional[int] = 2,
encoder_hash_byte_group_size: Optional[int] = None,
encoder_hash_byte_group_vocab: Optional[int] = 500002,
encoder_hash_byte_group_nb_functions: Optional[int] = 1,
patcher_config: Optional[dict] = None,
encoder_config: Optional[dict] = None,
decoder_config: Optional[dict] = None,
global_config: Optional[dict] = None,
tie_word_embeddings: Optional[bool] = False,
initializer_range: Optional[float] = 0.02,
rope_parameters: Optional[RopeParameters | dict[str, RopeParameters]] = None,
**kwargs,
):
# Basic model configuration
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.initializer_range = initializer_range
# Patching configuration
self.patch_in_forward = patch_in_forward
self.patch_size = patch_size
self.patching_mode = patching_mode
self.patching_threshold = patching_threshold
self.patching_batch_size = patching_batch_size
self.max_patch_length = max_patch_length
self.patching_device = kwargs.get("patching_device", "cuda")
self.realtime_patching = kwargs.get("realtime_patching", True)
self.patching_threshold_add = kwargs.get("patching_threshold_add")
self.monotonicity = kwargs.get("monotonicity", False)
# Cross attention configurations
self.cross_attn_k = cross_attn_k
# Encoder configurations
self.encoder_hash_byte_group_size = encoder_hash_byte_group_size or [3, 4, 5, 6, 7, 8]
self.encoder_hash_byte_group_vocab = encoder_hash_byte_group_vocab
self.encoder_hash_byte_group_nb_functions = encoder_hash_byte_group_nb_functions
# Initialize component configurations
if patcher_config is None:
self.patcher_config = BltPatcherConfig(initializer_range=initializer_range)
logger.info("patcher_config is None, using default Blt patcher config")
elif isinstance(patcher_config, dict):
patcher_config.setdefault("initializer_range", initializer_range)
self.patcher_config = BltPatcherConfig(**patcher_config)
elif isinstance(patcher_config, BltPatcherConfig):
self.patcher_config = patcher_config
if encoder_config is None:
self.encoder_config = BltLocalEncoderConfig(initializer_range=initializer_range)
logger.info("encoder_config is None, using default Blt encoder config")
elif isinstance(encoder_config, dict):
encoder_config.setdefault("initializer_range", initializer_range)
self.encoder_config = BltLocalEncoderConfig(**encoder_config)
elif isinstance(encoder_config, BltLocalEncoderConfig):
self.encoder_config = encoder_config
if decoder_config is None:
self.decoder_config = BltLocalDecoderConfig(initializer_range=initializer_range)
logger.info("decoder_config is None, using default Blt decoder config")
elif isinstance(decoder_config, dict):
decoder_config.setdefault("initializer_range", initializer_range)
self.decoder_config = BltLocalDecoderConfig(**decoder_config)
elif isinstance(decoder_config, BltLocalDecoderConfig):
self.decoder_config = decoder_config
if global_config is None:
self.global_config = BltGlobalTransformerConfig(initializer_range=initializer_range)
logger.info("global_config is None, using default Blt global config")
elif isinstance(global_config, dict):
global_config.setdefault("initializer_range", initializer_range)
self.global_config = BltGlobalTransformerConfig(**global_config)
elif isinstance(global_config, BltGlobalTransformerConfig):
self.global_config = global_config
# Determine if token embedding projection is needed based on dimension mismatch (7b)
encoder_cross_output_size = self.encoder_config.hidden_size * self.cross_attn_k
self.global_config.encoder_cross_output_size = (
encoder_cross_output_size if encoder_cross_output_size != self.global_config.hidden_size else None
)
self.rope_parameters = rope_parameters
# Remove tie_word_embeddings from kwargs to avoid duplicate parameter error
kwargs.pop("tie_word_embeddings", None)
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
__all__ = [
"BltConfig",
"BltPatcherConfig",
"BltLocalEncoderConfig",
"BltLocalDecoderConfig",
"BltGlobalTransformerConfig",
]
| BltConfig |
python | spyder-ide__spyder | spyder/plugins/editor/widgets/editorstack/helpers.py | {
"start": 7319,
"end": 9474
} | class ____(MutableSequence):
"""Handles editor stack history.
Works as a list of numbers corresponding to tab indexes.
Internally elements are saved using objects id's.
"""
def __init__(self, editor):
"""Initialize the StackHistory."""
self.history = list()
self.id_list = list()
self.editor = editor
def _update_id_list(self):
"""Update list of corresponding ids and tabs."""
self.id_list = [id(self.editor.tabs.widget(_i))
for _i in range(self.editor.tabs.count())]
def refresh(self):
"""Remove editors that are not longer open."""
self._update_id_list()
for _id in self.history[:]:
if _id not in self.id_list:
self.history.remove(_id)
def __len__(self):
"""Return the length of the history."""
return len(self.history)
def __getitem__(self, i):
"""Retrieve the ith element of the history."""
self._update_id_list()
try:
return self.id_list.index(self.history[i])
except ValueError:
self.refresh()
raise IndexError
def __delitem__(self, i):
"""Delete the ith element of the history."""
del self.history[i]
def __setitem__(self, i, v):
"""Set the ith element of the history."""
_id = id(self.editor.tabs.widget(v))
self.history[i] = _id
def __str__(self):
"""Return the str."""
return str(list(self))
def insert(self, i, tab_index):
"""Insert the widget (at tab index) in the position i (index)."""
_id = id(self.editor.tabs.widget(tab_index))
self.history.insert(i, _id)
def remove(self, tab_index):
"""Remove the widget at the corresponding tab_index."""
_id = id(self.editor.tabs.widget(tab_index))
if _id in self.history:
self.history.remove(_id)
def remove_and_append(self, index):
"""Remove previous entrances of a tab, and add it as the latest."""
while index in self:
self.remove(index)
self.append(index)
| StackHistory |
python | aio-libs__aiohttp | aiohttp/helpers.py | {
"start": 28006,
"end": 28092
} | class ____(BaseKey[_T]):
"""Keys for static typing support in Request."""
| RequestKey |
python | pytorch__pytorch | torch/_guards.py | {
"start": 16441,
"end": 16614
} | class ____(Generic[T]):
@abstractmethod
def copy_graphstate(self) -> T: ...
@abstractmethod
def restore_graphstate(self, state: T) -> None: ...
| Checkpointable |
python | redis__redis-py | tests/test_cache.py | {
"start": 48440,
"end": 49161
} | class ____:
MAX_SIZE = 100
EVICTION_POLICY = EvictionPolicy.LRU
def test_get_max_size(self, cache_conf: CacheConfig):
assert self.MAX_SIZE == cache_conf.get_max_size()
def test_get_eviction_policy(self, cache_conf: CacheConfig):
assert self.EVICTION_POLICY == cache_conf.get_eviction_policy()
def test_is_exceeds_max_size(self, cache_conf: CacheConfig):
assert not cache_conf.is_exceeds_max_size(self.MAX_SIZE)
assert cache_conf.is_exceeds_max_size(self.MAX_SIZE + 1)
def test_is_allowed_to_cache(self, cache_conf: CacheConfig):
assert cache_conf.is_allowed_to_cache("GET")
assert not cache_conf.is_allowed_to_cache("SET")
| TestUnitCacheConfiguration |
python | kubernetes-client__python | kubernetes/client/models/v1_pod_scheduling_gate.py | {
"start": 383,
"end": 3684
} | 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 = {
'name': 'str'
}
attribute_map = {
'name': 'name'
}
def __init__(self, name=None, local_vars_configuration=None): # noqa: E501
"""V1PodSchedulingGate - 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._name = None
self.discriminator = None
self.name = name
@property
def name(self):
"""Gets the name of this V1PodSchedulingGate. # noqa: E501
Name of the scheduling gate. Each scheduling gate must have a unique name field. # noqa: E501
:return: The name of this V1PodSchedulingGate. # noqa: E501
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this V1PodSchedulingGate.
Name of the scheduling gate. Each scheduling gate must have a unique name field. # noqa: E501
:param name: The name of this V1PodSchedulingGate. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and name is None: # noqa: E501
raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501
self._name = name
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, V1PodSchedulingGate):
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, V1PodSchedulingGate):
return True
return self.to_dict() != other.to_dict()
| V1PodSchedulingGate |
python | realpython__materials | solid-principles-python/shapes_ocp.py | {
"start": 1337,
"end": 1507
} | class ____(Shape):
def __init__(self, side):
super().__init__("square")
self.side = side
def calculate_area(self):
return self.side**2
| Square |
python | fastapi__sqlmodel | docs_src/tutorial/fastapi/multiple_models/tutorial002_py310.py | {
"start": 370,
"end": 1230
} | class ____(HeroBase):
id: int
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
connect_args = {"check_same_thread": False}
engine = create_engine(sqlite_url, echo=True, connect_args=connect_args)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
app = FastAPI()
@app.on_event("startup")
def on_startup():
create_db_and_tables()
@app.post("/heroes/", response_model=HeroPublic)
def create_hero(hero: HeroCreate):
with Session(engine) as session:
db_hero = Hero.model_validate(hero)
session.add(db_hero)
session.commit()
session.refresh(db_hero)
return db_hero
@app.get("/heroes/", response_model=list[HeroPublic])
def read_heroes():
with Session(engine) as session:
heroes = session.exec(select(Hero)).all()
return heroes
| HeroPublic |
python | astropy__astropy | astropy/modeling/fitting.py | {
"start": 5729,
"end": 5842
} | class ____(ModelsError):
"""Raised when a non-linear model is passed to a linear fitter."""
| ModelLinearityError |
python | getsentry__sentry | tests/sentry/uptime/autodetect/test_detector.py | {
"start": 361,
"end": 1604
} | class ____(UptimeTestCase):
def assert_organization_key(self, organization: Organization, exists: bool) -> None:
key = get_organization_bucket_key(organization)
cluster = get_cluster()
assert exists == cluster.sismember(key, str(organization.id))
def test(self) -> None:
autodetect_base_url_for_project(self.project, "https://sentry.io")
self.assert_organization_key(self.organization, True)
@override_options({"uptime.automatic-hostname-detection": False})
def test_no_option(self) -> None:
autodetect_base_url_for_project(self.project, "https://sentry.io")
self.assert_organization_key(self.organization, False)
def test_disabled_for_project(self) -> None:
self.project.update_option("sentry:uptime_autodetection", False)
autodetect_base_url_for_project(self.project, "https://sentry.io")
self.assert_organization_key(self.organization, False)
def test_disabled_for_organization(self) -> None:
self.organization.update_option("sentry:uptime_autodetection", False)
autodetect_base_url_for_project(self.project, "https://sentry.io")
self.assert_organization_key(self.organization, False)
| DetectBaseUrlForProjectTest |
python | getsentry__sentry | tests/sentry/stacktraces/test_in_app_normalization.py | {
"start": 7721,
"end": 16170
} | class ____(TestCase):
def assert_correct_in_app_value(self, function, is_in_app: bool):
data: dict[str, Any] = {
"platform": "cocoa",
"debug_meta": {"images": []}, # omitted
"exception": {
"values": [
{
"stacktrace": {
"frames": [
{
"function": function,
"package": "/var/containers/Bundle/Application/B33C37A8-F933-4B6B-9FFA-152282BFDF13/SentryTest.app/SentryTest",
"instruction_addr": 4295098388,
},
# We need two frames otherwise all frames are inApp
{
"function": "[KSCrash ]",
"package": "/usr/lib/system/libdyld.dylib",
"instruction_addr": 4295098388,
},
]
},
"type": "NSRangeException",
}
]
},
"contexts": {"os": {"version": "9.3.2", "type": "os", "name": "iOS"}},
}
config = load_grouping_config(get_default_grouping_config_dict())
normalize_stacktraces_for_grouping(data, grouping_config=config)
frames = data["exception"]["values"][0]["stacktrace"]["frames"]
assert frames[0]["in_app"] is is_in_app, (
"For function: " + function + " expected:" + str(is_in_app)
)
def test_ios_function_name_in_app_detection(self) -> None:
self.assert_correct_in_app_value(
function="sentrycrash__hook_dispatch_async", is_in_app=False
)
self.assert_correct_in_app_value(
function="sentrycrash__hook_dispatch_after_f", is_in_app=False
)
self.assert_correct_in_app_value(
function="sentrycrash__async_backtrace_capture", is_in_app=False
)
self.assert_correct_in_app_value(
function="__sentrycrash__hook_dispatch_async_block_invoke", is_in_app=False
)
self.assert_correct_in_app_value(function="kscm_f", is_in_app=False)
self.assert_correct_in_app_value(function="kscm_", is_in_app=False)
self.assert_correct_in_app_value(function=" kscm_", is_in_app=False)
self.assert_correct_in_app_value(function="kscm", is_in_app=True)
self.assert_correct_in_app_value(function="sentrycrashcm_f", is_in_app=False)
self.assert_correct_in_app_value(function="sentrycrashcm_", is_in_app=False)
self.assert_correct_in_app_value(function=" sentrycrashcm_", is_in_app=False)
self.assert_correct_in_app_value(function="sentrycrashcm", is_in_app=True)
self.assert_correct_in_app_value(function="kscrash_f", is_in_app=False)
self.assert_correct_in_app_value(function="kscrash_", is_in_app=False)
self.assert_correct_in_app_value(function=" kscrash_", is_in_app=False)
self.assert_correct_in_app_value(function="kscrash", is_in_app=True)
self.assert_correct_in_app_value(function="sentrycrash_f", is_in_app=False)
self.assert_correct_in_app_value(function="sentrycrash_", is_in_app=False)
self.assert_correct_in_app_value(function=" sentrycrash_", is_in_app=False)
self.assert_correct_in_app_value(function="sentrycrash", is_in_app=True)
self.assert_correct_in_app_value(function="+[KSCrash ]", is_in_app=False)
self.assert_correct_in_app_value(function="-[KSCrash]", is_in_app=False)
self.assert_correct_in_app_value(function="-[KSCrashy]", is_in_app=False)
self.assert_correct_in_app_value(function="-[MyKSCrashy ", is_in_app=True)
self.assert_correct_in_app_value(function="+[RNSentry ]", is_in_app=False)
self.assert_correct_in_app_value(function="-[RNSentry]", is_in_app=False)
self.assert_correct_in_app_value(function="-[RNSentry]", is_in_app=False)
self.assert_correct_in_app_value(function="-[MRNSentry ]", is_in_app=True)
self.assert_correct_in_app_value(function="+[Sentry ]", is_in_app=False)
self.assert_correct_in_app_value(function="-[Sentry]", is_in_app=False)
self.assert_correct_in_app_value(function="-[Sentry]", is_in_app=False)
self.assert_correct_in_app_value(function="-[MSentry capture]", is_in_app=True)
self.assert_correct_in_app_value(function="-[SentryHub captureMessage]", is_in_app=False)
self.assert_correct_in_app_value(function="-[SentryClient captureMessage]", is_in_app=False)
self.assert_correct_in_app_value(function="+[SentrySDK captureMessage]", is_in_app=False)
self.assert_correct_in_app_value(
function="-[SentryStacktraceBuilder buildStacktraceForCurrentThread]", is_in_app=False
)
self.assert_correct_in_app_value(
function="-[SentryThreadInspector getCurrentThreads]", is_in_app=False
)
self.assert_correct_in_app_value(
function="-[SentryClient captureMessage:withScope:]", is_in_app=False
)
self.assert_correct_in_app_value(
function="-[SentryFrameInAppLogic isInApp:]", is_in_app=False
)
self.assert_correct_in_app_value(
function="-[SentryFrameRemover removeNonSdkFrames:]", is_in_app=False
)
self.assert_correct_in_app_value(
function="-[SentryDebugMetaBuilder buildDebugMeta:withScope:]", is_in_app=False
)
self.assert_correct_in_app_value(
function="-[SentryCrashAdapter crashedLastLaunch]", is_in_app=False
)
self.assert_correct_in_app_value(
function="-[SentryCrashAdapter isRateLimitActive:]", is_in_app=False
)
self.assert_correct_in_app_value(
function="-[SentryTransport sendEvent:attachments:]", is_in_app=False
)
self.assert_correct_in_app_value(
function="-[SentryHttpTransport sendEvent:attachments:]", is_in_app=False
)
def test_swizzling_in_app_detection(self) -> None:
self.assert_correct_in_app_value(
function="__42-[SentryCoreDataSwizzling swizzleCoreData]_block_invoke_2.24",
is_in_app=False,
)
self.assert_correct_in_app_value(
function="__49-[SentrySwizzleWrapper swizzleSendAction:forKey:]_block_invoke_2",
is_in_app=False,
)
self.assert_correct_in_app_value(
function="__49+[SentrySwizzleWrapper swizzleSendAction:forKey:]_block_invoke_2",
is_in_app=False,
)
def test_ios_package_in_app_detection(self) -> None:
data: dict[str, Any] = {
"platform": "native",
"stacktrace": {
"frames": [
{
"package": "/var/containers/Bundle/Application/B33C37A8-F933-4B6B-9FFA-152282BFDF13/SentryTest.app/SentryTest",
"instruction_addr": "0x1000",
},
{
"package": "/var/containers/Bundle/Application/B33C37A8-F933-4B6B-9FFA-152282BFDF13/SentryTest.app/Frameworks/foo.dylib",
"instruction_addr": "0x2000",
},
{
"package": "/var/containers/Bundle/Application/B33C37A8-F933-4B6B-9FFA-152282BFDF13/SentryTest.app/Frameworks/libswiftCore.dylib",
"instruction_addr": "0x3000",
},
{"package": "/usr/lib/whatever.dylib", "instruction_addr": "0x4000"},
]
},
}
config = load_grouping_config(get_default_grouping_config_dict())
normalize_stacktraces_for_grouping(data, grouping_config=config)
# App object should be in_app
assert data["stacktrace"]["frames"][0]["in_app"] is True
# Framework should be in app (but optional)
assert data["stacktrace"]["frames"][1]["in_app"] is True
# libswift should not be system
assert data["stacktrace"]["frames"][2]["in_app"] is False
# Unknown object should default to not in_app
assert data["stacktrace"]["frames"][3]["in_app"] is False
| iOSInAppDetectionTest |
python | numpy__numpy | numpy/distutils/numpy_distribution.py | {
"start": 164,
"end": 634
} | class ____(Distribution):
def __init__(self, attrs = None):
# A list of (sconscripts, pre_hook, post_hook, src, parent_names)
self.scons_data = []
# A list of installable libraries
self.installed_libraries = []
# A dict of pkg_config files to generate/install
self.installed_pkg_config = {}
Distribution.__init__(self, attrs)
def has_scons_scripts(self):
return bool(self.scons_data)
| NumpyDistribution |
python | getsentry__sentry | src/sentry/api/endpoints/organization_events_span_ops.py | {
"start": 621,
"end": 697
} | class ____(TypedDict):
op: str
count: int
@region_silo_endpoint
| SpanOp |
python | streamlit__streamlit | lib/tests/streamlit/components_test.py | {
"start": 25874,
"end": 27021
} | class ____(DeltaGeneratorTestCase):
def test_iframe(self):
"""Test components.iframe"""
components.iframe("http://not.a.url", width=200, scrolling=True)
el = self.get_delta_from_queue().new_element
assert el.iframe.src == "http://not.a.url"
assert el.iframe.srcdoc == ""
assert el.iframe.scrolling
assert el.width_config.pixel_width == 200
assert el.iframe.width == 0.0 # deprecated field should remain at default
assert el.iframe.has_width is False # deprecated field should remain at default
def test_html(self):
"""Test components.html"""
html = r"<html><body>An HTML string!</body></html>"
components.html(html, width=200, scrolling=True)
el = self.get_delta_from_queue().new_element
assert el.iframe.src == ""
assert el.iframe.srcdoc == html
assert el.iframe.scrolling
assert el.width_config.pixel_width == 200
assert el.iframe.width == 0.0 # deprecated field should remain at default
assert el.iframe.has_width is False # deprecated field should remain at default
| IFrameTest |
python | numpy__numpy | numpy/linalg/tests/test_linalg.py | {
"start": 44940,
"end": 45293
} | class ____:
dt = None
dec = None
@staticmethod
def check_dtype(x, res):
if issubclass(x.dtype.type, np.inexact):
assert_equal(res.dtype, x.real.dtype)
else:
# For integer input, don't have to test float precision of output.
assert_(issubclass(res.dtype.type, np.floating))
| _TestNormBase |
python | tensorflow__tensorflow | tensorflow/python/ops/summary_ops_v2.py | {
"start": 14203,
"end": 15697
} | class ____(
_ResourceSummaryWriter,
resource.TrackableResource,
metaclass=_MultiMetaclass):
"""A `_ResourceSummaryWriter` subclass that implements `TrackableResource`."""
def __init__(self, create_fn, init_op_fn, mesh=None):
# Resolve multiple inheritance via explicit calls to __init__() on parents.
resource.TrackableResource.__init__(self, device="/CPU:0")
self._create_fn = create_fn
self._init_op_fn = init_op_fn
# Pass .resource_handle into _ResourceSummaryWriter parent class rather than
# create_fn, to ensure it accesses the resource handle only through the
# cached property so that everything is using a single resource handle.
_ResourceSummaryWriter.__init__(
self,
create_fn=lambda: self.resource_handle,
init_op_fn=init_op_fn,
mesh=mesh,
)
# Override for TrackableResource implementation.
def _create_resource(self):
return self._create_fn()
# Override for TrackableResource implementation.
def _initialize(self):
return self._init_op_fn(self.resource_handle)
# Override for TrackableResource implementation.
def _destroy_resource(self):
gen_resource_variable_ops.destroy_resource_op(
self.resource_handle, ignore_lookup_error=True)
def _set_up_resource_deleter(self):
# Override to suppress ResourceSummaryWriter implementation; we don't need
# the deleter since TrackableResource.__del__() handles it for us.
pass
| _TrackableResourceSummaryWriter |
python | pandas-dev__pandas | pandas/tests/arithmetic/test_period.py | {
"start": 20836,
"end": 50233
} | class ____:
# ---------------------------------------------------------------
# __add__/__sub__ with PeriodIndex
# PeriodIndex + other is defined for integers and timedelta-like others
# PeriodIndex - other is defined for integers, timedelta-like others,
# and PeriodIndex (with matching freq)
def test_parr_add_iadd_parr_raises(self, box_with_array):
rng = period_range("1/1/2000", freq="D", periods=5)
other = period_range("1/6/2000", freq="D", periods=5)
# TODO: parametrize over boxes for other?
rng = tm.box_expected(rng, box_with_array)
# An earlier implementation of PeriodIndex addition performed
# a set operation (union). This has since been changed to
# raise a TypeError. See GH#14164 and GH#13077 for historical
# reference.
msg = r"unsupported operand type\(s\) for \+: .* and .*"
with pytest.raises(TypeError, match=msg):
rng + other
with pytest.raises(TypeError, match=msg):
rng += other
def test_pi_sub_isub_pi(self):
# GH#20049
# For historical reference see GH#14164, GH#13077.
# PeriodIndex subtraction originally performed set difference,
# then changed to raise TypeError before being implemented in GH#20049
rng = period_range("1/1/2000", freq="D", periods=5)
other = period_range("1/6/2000", freq="D", periods=5)
off = rng.freq
expected = pd.Index([-5 * off] * 5)
result = rng - other
tm.assert_index_equal(result, expected)
rng -= other
tm.assert_index_equal(rng, expected)
def test_pi_sub_pi_with_nat(self):
rng = period_range("1/1/2000", freq="D", periods=5)
other = rng[1:].insert(0, pd.NaT)
assert other[1:].equals(rng[1:])
result = rng - other
off = rng.freq
expected = pd.Index([pd.NaT, 0 * off, 0 * off, 0 * off, 0 * off])
tm.assert_index_equal(result, expected)
def test_parr_sub_pi_mismatched_freq(self, box_with_array, box_with_array2):
rng = period_range("1/1/2000", freq="D", periods=5)
other = period_range("1/6/2000", freq="h", periods=5)
rng = tm.box_expected(rng, box_with_array)
other = tm.box_expected(other, box_with_array2)
msg = r"Input has different freq=[hD] from PeriodArray\(freq=[Dh]\)"
with pytest.raises(IncompatibleFrequency, match=msg):
rng - other
@pytest.mark.parametrize("n", [1, 2, 3, 4])
def test_sub_n_gt_1_ticks(self, tick_classes, n):
# GH 23878
p1_d = "19910905"
p2_d = "19920406"
p1 = PeriodIndex([p1_d], freq=tick_classes(n))
p2 = PeriodIndex([p2_d], freq=tick_classes(n))
expected = PeriodIndex([p2_d], freq=p2.freq.base) - PeriodIndex(
[p1_d], freq=p1.freq.base
)
tm.assert_index_equal((p2 - p1), expected)
@pytest.mark.parametrize("n", [1, 2, 3, 4])
@pytest.mark.parametrize(
"offset, kwd_name",
[
(pd.offsets.YearEnd, "month"),
(pd.offsets.QuarterEnd, "startingMonth"),
(pd.offsets.MonthEnd, None),
(pd.offsets.Week, "weekday"),
],
)
def test_sub_n_gt_1_offsets(self, offset, kwd_name, n):
# GH 23878
kwds = {kwd_name: 3} if kwd_name is not None else {}
p1_d = "19910905"
p2_d = "19920406"
freq = offset(n, normalize=False, **kwds)
p1 = PeriodIndex([p1_d], freq=freq)
p2 = PeriodIndex([p2_d], freq=freq)
result = p2 - p1
expected = PeriodIndex([p2_d], freq=freq.base) - PeriodIndex(
[p1_d], freq=freq.base
)
tm.assert_index_equal(result, expected)
# -------------------------------------------------------------
# Invalid Operations
@pytest.mark.parametrize(
"other",
[
# datetime scalars
Timestamp("2016-01-01"),
Timestamp("2016-01-01").to_pydatetime(),
Timestamp("2016-01-01").to_datetime64(),
# datetime-like arrays
pd.date_range("2016-01-01", periods=3, freq="h"),
pd.date_range("2016-01-01", periods=3, tz="Europe/Brussels"),
pd.date_range("2016-01-01", periods=3, freq="s")._data,
pd.date_range("2016-01-01", periods=3, tz="Asia/Tokyo")._data,
# Miscellaneous invalid types
3.14,
np.array([2.0, 3.0, 4.0]),
],
)
def test_parr_add_sub_invalid(self, other, box_with_array):
# GH#23215
rng = period_range("1/1/2000", freq="D", periods=3)
rng = tm.box_expected(rng, box_with_array)
msg = "|".join(
[
r"(:?cannot add PeriodArray and .*)",
r"(:?cannot subtract .* from (:?a\s)?.*)",
r"(:?unsupported operand type\(s\) for \+: .* and .*)",
r"unsupported operand type\(s\) for [+-]: .* and .*",
]
)
assert_invalid_addsub_type(rng, other, msg)
with pytest.raises(TypeError, match=msg):
rng + other
with pytest.raises(TypeError, match=msg):
other + rng
with pytest.raises(TypeError, match=msg):
rng - other
with pytest.raises(TypeError, match=msg):
other - rng
# -----------------------------------------------------------------
# __add__/__sub__ with ndarray[datetime64] and ndarray[timedelta64]
def test_pi_add_sub_td64_array_non_tick_raises(self):
rng = period_range("1/1/2000", freq="Q", periods=3)
tdi = TimedeltaIndex(["-1 Day", "-1 Day", "-1 Day"])
tdarr = tdi.values
msg = r"Cannot add or subtract timedelta64\[ns\] dtype from period\[Q-DEC\]"
with pytest.raises(TypeError, match=msg):
rng + tdarr
with pytest.raises(TypeError, match=msg):
tdarr + rng
with pytest.raises(TypeError, match=msg):
rng - tdarr
msg = r"cannot subtract PeriodArray from TimedeltaArray"
with pytest.raises(TypeError, match=msg):
tdarr - rng
def test_pi_add_sub_td64_array_tick(self):
# PeriodIndex + Timedelta-like is allowed only with
# tick-like frequencies
rng = period_range("1/1/2000", freq="90D", periods=3)
tdi = TimedeltaIndex(["-1 Day", "-1 Day", "-1 Day"])
tdarr = tdi.values
expected = period_range("12/31/1999", freq="90D", periods=3)
result = rng + tdi
tm.assert_index_equal(result, expected)
result = rng + tdarr
tm.assert_index_equal(result, expected)
result = tdi + rng
tm.assert_index_equal(result, expected)
result = tdarr + rng
tm.assert_index_equal(result, expected)
expected = period_range("1/2/2000", freq="90D", periods=3)
result = rng - tdi
tm.assert_index_equal(result, expected)
result = rng - tdarr
tm.assert_index_equal(result, expected)
msg = r"cannot subtract .* from .*"
with pytest.raises(TypeError, match=msg):
tdarr - rng
with pytest.raises(TypeError, match=msg):
tdi - rng
@pytest.mark.parametrize("pi_freq", ["D", "W", "Q", "h"])
@pytest.mark.parametrize("tdi_freq", [None, "h"])
def test_parr_sub_td64array(self, box_with_array, tdi_freq, pi_freq):
box = box_with_array
xbox = box if box not in [pd.array, tm.to_array] else pd.Index
tdi = TimedeltaIndex(["1 hours", "2 hours"], freq=tdi_freq)
dti = Timestamp("2018-03-07 17:16:40") + tdi
pi = dti.to_period(pi_freq)
# TODO: parametrize over box for pi?
td64obj = tm.box_expected(tdi, box)
if pi_freq == "h":
result = pi - td64obj
expected = (pi.to_timestamp("s") - tdi).to_period(pi_freq)
expected = tm.box_expected(expected, xbox)
tm.assert_equal(result, expected)
# Subtract from scalar
result = pi[0] - td64obj
expected = (pi[0].to_timestamp("s") - tdi).to_period(pi_freq)
expected = tm.box_expected(expected, box)
tm.assert_equal(result, expected)
elif pi_freq == "D":
# Tick, but non-compatible
msg = (
"Cannot add/subtract timedelta-like from PeriodArray that is "
"not an integer multiple of the PeriodArray's freq."
)
with pytest.raises(IncompatibleFrequency, match=msg):
pi - td64obj
with pytest.raises(IncompatibleFrequency, match=msg):
pi[0] - td64obj
else:
# With non-Tick freq, we could not add timedelta64 array regardless
# of what its resolution is
msg = "Cannot add or subtract timedelta64"
with pytest.raises(TypeError, match=msg):
pi - td64obj
with pytest.raises(TypeError, match=msg):
pi[0] - td64obj
# -----------------------------------------------------------------
# operations with array/Index of DateOffset objects
@pytest.mark.parametrize("box", [np.array, pd.Index])
def test_pi_add_offset_array(self, performance_warning, box):
# GH#18849
pi = PeriodIndex([Period("2015Q1"), Period("2016Q2")])
offs = box(
[
pd.offsets.QuarterEnd(n=1, startingMonth=12),
pd.offsets.QuarterEnd(n=-2, startingMonth=12),
]
)
expected = PeriodIndex([Period("2015Q2"), Period("2015Q4")]).astype(object)
with tm.assert_produces_warning(performance_warning):
res = pi + offs
tm.assert_index_equal(res, expected)
with tm.assert_produces_warning(performance_warning):
res2 = offs + pi
tm.assert_index_equal(res2, expected)
unanchored = np.array([pd.offsets.Hour(n=1), pd.offsets.Minute(n=-2)])
# addition/subtraction ops with incompatible offsets should issue
# a PerformanceWarning and _then_ raise a TypeError.
msg = r"Input cannot be converted to Period\(freq=Q-DEC\)"
with pytest.raises(IncompatibleFrequency, match=msg):
with tm.assert_produces_warning(performance_warning):
pi + unanchored
with pytest.raises(IncompatibleFrequency, match=msg):
with tm.assert_produces_warning(performance_warning):
unanchored + pi
@pytest.mark.parametrize("box", [np.array, pd.Index])
def test_pi_sub_offset_array(self, performance_warning, box):
# GH#18824
pi = PeriodIndex([Period("2015Q1"), Period("2016Q2")])
other = box(
[
pd.offsets.QuarterEnd(n=1, startingMonth=12),
pd.offsets.QuarterEnd(n=-2, startingMonth=12),
]
)
expected = PeriodIndex([pi[n] - other[n] for n in range(len(pi))])
expected = expected.astype(object)
with tm.assert_produces_warning(performance_warning):
res = pi - other
tm.assert_index_equal(res, expected)
anchored = box([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)])
# addition/subtraction ops with anchored offsets should issue
# a PerformanceWarning and _then_ raise a TypeError.
msg = r"Input has different freq=-1M from Period\(freq=Q-DEC\)"
with pytest.raises(IncompatibleFrequency, match=msg):
with tm.assert_produces_warning(performance_warning):
pi - anchored
with pytest.raises(IncompatibleFrequency, match=msg):
with tm.assert_produces_warning(performance_warning):
anchored - pi
def test_pi_add_iadd_int(self, one):
# Variants of `one` for #19012
rng = period_range("2000-01-01 09:00", freq="h", periods=10)
result = rng + one
expected = period_range("2000-01-01 10:00", freq="h", periods=10)
tm.assert_index_equal(result, expected)
rng += one
tm.assert_index_equal(rng, expected)
def test_pi_sub_isub_int(self, one):
"""
PeriodIndex.__sub__ and __isub__ with several representations of
the integer 1, e.g. int, np.int64, np.uint8, ...
"""
rng = period_range("2000-01-01 09:00", freq="h", periods=10)
result = rng - one
expected = period_range("2000-01-01 08:00", freq="h", periods=10)
tm.assert_index_equal(result, expected)
rng -= one
tm.assert_index_equal(rng, expected)
@pytest.mark.parametrize("five", [5, np.array(5, dtype=np.int64)])
def test_pi_sub_intlike(self, five):
rng = period_range("2007-01", periods=50)
result = rng - five
exp = rng + (-five)
tm.assert_index_equal(result, exp)
def test_pi_add_sub_int_array_freqn_gt1(self):
# GH#47209 test adding array of ints when freq.n > 1 matches
# scalar behavior
pi = period_range("2016-01-01", periods=10, freq="2D")
arr = np.arange(10)
result = pi + arr
expected = pd.Index([x + y for x, y in zip(pi, arr)])
tm.assert_index_equal(result, expected)
result = pi - arr
expected = pd.Index([x - y for x, y in zip(pi, arr)])
tm.assert_index_equal(result, expected)
def test_pi_sub_isub_offset(self):
# offset
# DateOffset
rng = period_range("2014", "2024", freq="Y")
result = rng - pd.offsets.YearEnd(5)
expected = period_range("2009", "2019", freq="Y")
tm.assert_index_equal(result, expected)
rng -= pd.offsets.YearEnd(5)
tm.assert_index_equal(rng, expected)
rng = period_range("2014-01", "2016-12", freq="M")
result = rng - pd.offsets.MonthEnd(5)
expected = period_range("2013-08", "2016-07", freq="M")
tm.assert_index_equal(result, expected)
rng -= pd.offsets.MonthEnd(5)
tm.assert_index_equal(rng, expected)
@pytest.mark.parametrize("transpose", [True, False])
def test_pi_add_offset_n_gt1(self, box_with_array, transpose):
# GH#23215
# add offset to PeriodIndex with freq.n > 1
per = Period("2016-01", freq="2M")
pi = PeriodIndex([per])
expected = PeriodIndex(["2016-03"], freq="2M")
pi = tm.box_expected(pi, box_with_array, transpose=transpose)
expected = tm.box_expected(expected, box_with_array, transpose=transpose)
result = pi + per.freq
tm.assert_equal(result, expected)
result = per.freq + pi
tm.assert_equal(result, expected)
def test_pi_add_offset_n_gt1_not_divisible(self, box_with_array):
# GH#23215
# PeriodIndex with freq.n > 1 add offset with offset.n % freq.n != 0
pi = PeriodIndex(["2016-01"], freq="2M")
expected = PeriodIndex(["2016-04"], freq="2M")
pi = tm.box_expected(pi, box_with_array)
expected = tm.box_expected(expected, box_with_array)
result = pi + to_offset("3ME")
tm.assert_equal(result, expected)
result = to_offset("3ME") + pi
tm.assert_equal(result, expected)
# ---------------------------------------------------------------
# __add__/__sub__ with integer arrays
@pytest.mark.parametrize("int_holder", [np.array, pd.Index])
@pytest.mark.parametrize("op", [operator.add, ops.radd])
def test_pi_add_intarray(self, int_holder, op):
# GH#19959
pi = PeriodIndex([Period("2015Q1"), Period("NaT")])
other = int_holder([4, -1])
result = op(pi, other)
expected = PeriodIndex([Period("2016Q1"), Period("NaT")])
tm.assert_index_equal(result, expected)
@pytest.mark.parametrize("int_holder", [np.array, pd.Index])
def test_pi_sub_intarray(self, int_holder):
# GH#19959
pi = PeriodIndex([Period("2015Q1"), Period("NaT")])
other = int_holder([4, -1])
result = pi - other
expected = PeriodIndex([Period("2014Q1"), Period("NaT")])
tm.assert_index_equal(result, expected)
msg = r"bad operand type for unary -: 'PeriodArray'"
with pytest.raises(TypeError, match=msg):
other - pi
# ---------------------------------------------------------------
# Timedelta-like (timedelta, timedelta64, Timedelta, Tick)
# TODO: Some of these are misnomers because of non-Tick DateOffsets
def test_parr_add_timedeltalike_minute_gt1(self, three_days, box_with_array):
# GH#23031 adding a time-delta-like offset to a PeriodArray that has
# minute frequency with n != 1. A more general case is tested below
# in test_pi_add_timedeltalike_tick_gt1, but here we write out the
# expected result more explicitly.
other = three_days
rng = period_range("2014-05-01", periods=3, freq="2D")
rng = tm.box_expected(rng, box_with_array)
expected = PeriodIndex(["2014-05-04", "2014-05-06", "2014-05-08"], freq="2D")
expected = tm.box_expected(expected, box_with_array)
result = rng + other
tm.assert_equal(result, expected)
result = other + rng
tm.assert_equal(result, expected)
# subtraction
expected = PeriodIndex(["2014-04-28", "2014-04-30", "2014-05-02"], freq="2D")
expected = tm.box_expected(expected, box_with_array)
result = rng - other
tm.assert_equal(result, expected)
msg = "|".join(
[
r"bad operand type for unary -: 'PeriodArray'",
r"cannot subtract PeriodArray from timedelta64\[[hD]\]",
]
)
with pytest.raises(TypeError, match=msg):
other - rng
@pytest.mark.parametrize("freqstr", ["5ns", "5us", "5ms", "5s", "5min", "5h", "5D"])
def test_parr_add_timedeltalike_tick_gt1(self, three_days, freqstr, box_with_array):
# GH#23031 adding a time-delta-like offset to a PeriodArray that has
# tick-like frequency with n != 1
other = three_days
rng = period_range("2014-05-01", periods=6, freq=freqstr)
first = rng[0]
rng = tm.box_expected(rng, box_with_array)
expected = period_range(first + other, periods=6, freq=freqstr)
expected = tm.box_expected(expected, box_with_array)
result = rng + other
tm.assert_equal(result, expected)
result = other + rng
tm.assert_equal(result, expected)
# subtraction
expected = period_range(first - other, periods=6, freq=freqstr)
expected = tm.box_expected(expected, box_with_array)
result = rng - other
tm.assert_equal(result, expected)
msg = "|".join(
[
r"bad operand type for unary -: 'PeriodArray'",
r"cannot subtract PeriodArray from timedelta64\[[hD]\]",
]
)
with pytest.raises(TypeError, match=msg):
other - rng
def test_pi_add_iadd_timedeltalike_daily(self, three_days):
# Tick
other = three_days
rng = period_range("2014-05-01", "2014-05-15", freq="D")
expected = period_range("2014-05-04", "2014-05-18", freq="D")
result = rng + other
tm.assert_index_equal(result, expected)
rng += other
tm.assert_index_equal(rng, expected)
def test_pi_sub_isub_timedeltalike_daily(self, three_days):
# Tick-like 3 Days
other = three_days
rng = period_range("2014-05-01", "2014-05-15", freq="D")
expected = period_range("2014-04-28", "2014-05-12", freq="D")
result = rng - other
tm.assert_index_equal(result, expected)
rng -= other
tm.assert_index_equal(rng, expected)
def test_parr_add_sub_timedeltalike_freq_mismatch_daily(
self, not_daily, box_with_array
):
other = not_daily
rng = period_range("2014-05-01", "2014-05-15", freq="D")
rng = tm.box_expected(rng, box_with_array)
msg = "|".join(
[
# non-timedelta-like DateOffset
"Input has different freq(=.+)? from Period.*?\\(freq=D\\)",
# timedelta/td64/Timedelta but not a multiple of 24H
"Cannot add/subtract timedelta-like from PeriodArray that is "
"not an integer multiple of the PeriodArray's freq.",
]
)
with pytest.raises(IncompatibleFrequency, match=msg):
rng + other
with pytest.raises(IncompatibleFrequency, match=msg):
rng += other
with pytest.raises(IncompatibleFrequency, match=msg):
rng - other
with pytest.raises(IncompatibleFrequency, match=msg):
rng -= other
def test_pi_add_iadd_timedeltalike_hourly(self, two_hours):
other = two_hours
rng = period_range("2014-01-01 10:00", "2014-01-05 10:00", freq="h")
expected = period_range("2014-01-01 12:00", "2014-01-05 12:00", freq="h")
result = rng + other
tm.assert_index_equal(result, expected)
rng += other
tm.assert_index_equal(rng, expected)
def test_parr_add_timedeltalike_mismatched_freq_hourly(
self, not_hourly, box_with_array
):
other = not_hourly
rng = period_range("2014-01-01 10:00", "2014-01-05 10:00", freq="h")
rng = tm.box_expected(rng, box_with_array)
msg = "|".join(
[
# non-timedelta-like DateOffset
"Input has different freq(=.+)? from Period.*?\\(freq=h\\)",
# timedelta/td64/Timedelta but not a multiple of 24H
"Cannot add/subtract timedelta-like from PeriodArray that is "
"not an integer multiple of the PeriodArray's freq.",
]
)
with pytest.raises(IncompatibleFrequency, match=msg):
rng + other
with pytest.raises(IncompatibleFrequency, match=msg):
rng += other
def test_pi_sub_isub_timedeltalike_hourly(self, two_hours):
other = two_hours
rng = period_range("2014-01-01 10:00", "2014-01-05 10:00", freq="h")
expected = period_range("2014-01-01 08:00", "2014-01-05 08:00", freq="h")
result = rng - other
tm.assert_index_equal(result, expected)
rng -= other
tm.assert_index_equal(rng, expected)
def test_add_iadd_timedeltalike_annual(self):
# offset
# DateOffset
rng = period_range("2014", "2024", freq="Y")
result = rng + pd.offsets.YearEnd(5)
expected = period_range("2019", "2029", freq="Y")
tm.assert_index_equal(result, expected)
rng += pd.offsets.YearEnd(5)
tm.assert_index_equal(rng, expected)
def test_pi_add_sub_timedeltalike_freq_mismatch_annual(self, mismatched_freq):
other = mismatched_freq
rng = period_range("2014", "2024", freq="Y")
msg = "Input has different freq(=.+)? from Period.*?\\(freq=Y-DEC\\)"
with pytest.raises(IncompatibleFrequency, match=msg):
rng + other
with pytest.raises(IncompatibleFrequency, match=msg):
rng += other
with pytest.raises(IncompatibleFrequency, match=msg):
rng - other
with pytest.raises(IncompatibleFrequency, match=msg):
rng -= other
def test_pi_add_iadd_timedeltalike_M(self):
rng = period_range("2014-01", "2016-12", freq="M")
expected = period_range("2014-06", "2017-05", freq="M")
result = rng + pd.offsets.MonthEnd(5)
tm.assert_index_equal(result, expected)
rng += pd.offsets.MonthEnd(5)
tm.assert_index_equal(rng, expected)
def test_pi_add_sub_timedeltalike_freq_mismatch_monthly(self, mismatched_freq):
other = mismatched_freq
rng = period_range("2014-01", "2016-12", freq="M")
msg = "Input has different freq(=.+)? from Period.*?\\(freq=M\\)"
with pytest.raises(IncompatibleFrequency, match=msg):
rng + other
with pytest.raises(IncompatibleFrequency, match=msg):
rng += other
with pytest.raises(IncompatibleFrequency, match=msg):
rng - other
with pytest.raises(IncompatibleFrequency, match=msg):
rng -= other
@pytest.mark.parametrize("transpose", [True, False])
def test_parr_add_sub_td64_nat(self, box_with_array, transpose):
# GH#23320 special handling for timedelta64("NaT")
pi = period_range("1994-04-01", periods=9, freq="19D")
other = np.timedelta64("NaT")
expected = PeriodIndex(["NaT"] * 9, freq="19D")
obj = tm.box_expected(pi, box_with_array, transpose=transpose)
expected = tm.box_expected(expected, box_with_array, transpose=transpose)
result = obj + other
tm.assert_equal(result, expected)
result = other + obj
tm.assert_equal(result, expected)
result = obj - other
tm.assert_equal(result, expected)
msg = r"cannot subtract .* from .*"
with pytest.raises(TypeError, match=msg):
other - obj
@pytest.mark.parametrize(
"other",
[
np.array(["NaT"] * 9, dtype="m8[ns]"),
TimedeltaArray._from_sequence(["NaT"] * 9, dtype="m8[ns]"),
],
)
def test_parr_add_sub_tdt64_nat_array(self, box_with_array, other):
pi = period_range("1994-04-01", periods=9, freq="19D")
expected = PeriodIndex(["NaT"] * 9, freq="19D")
obj = tm.box_expected(pi, box_with_array)
expected = tm.box_expected(expected, box_with_array)
result = obj + other
tm.assert_equal(result, expected)
result = other + obj
tm.assert_equal(result, expected)
result = obj - other
tm.assert_equal(result, expected)
msg = r"cannot subtract .* from .*"
with pytest.raises(TypeError, match=msg):
other - obj
# some but not *all* NaT
other = other.copy()
other[0] = np.timedelta64(0, "ns")
expected = PeriodIndex([pi[0]] + ["NaT"] * 8, freq="19D")
expected = tm.box_expected(expected, box_with_array)
result = obj + other
tm.assert_equal(result, expected)
result = other + obj
tm.assert_equal(result, expected)
result = obj - other
tm.assert_equal(result, expected)
with pytest.raises(TypeError, match=msg):
other - obj
# ---------------------------------------------------------------
# Unsorted
def test_parr_add_sub_index(self):
# Check that PeriodArray defers to Index on arithmetic ops
pi = period_range("2000-12-31", periods=3)
parr = pi.array
result = parr - pi
expected = pi - pi
tm.assert_index_equal(result, expected)
def test_parr_add_sub_object_array(self, performance_warning):
pi = period_range("2000-12-31", periods=3, freq="D")
parr = pi.array
other = np.array([Timedelta(days=1), pd.offsets.Day(2), 3])
with tm.assert_produces_warning(performance_warning):
result = parr + other
expected = PeriodIndex(
["2001-01-01", "2001-01-03", "2001-01-05"], freq="D"
)._data.astype(object)
tm.assert_equal(result, expected)
with tm.assert_produces_warning(performance_warning):
result = parr - other
expected = PeriodIndex(["2000-12-30"] * 3, freq="D")._data.astype(object)
tm.assert_equal(result, expected)
def test_period_add_timestamp_raises(self, box_with_array):
# GH#17983
ts = Timestamp("2017")
per = Period("2017", freq="M")
arr = pd.Index([per], dtype="Period[M]")
arr = tm.box_expected(arr, box_with_array)
msg = "cannot add PeriodArray and Timestamp"
with pytest.raises(TypeError, match=msg):
arr + ts
with pytest.raises(TypeError, match=msg):
ts + arr
if box_with_array is pd.DataFrame:
# TODO: before implementing resolution-inference we got the same
# message with DataFrame and non-DataFrame. Why did that change?
msg = "cannot add PeriodArray and Timestamp"
else:
msg = "cannot add PeriodArray and DatetimeArray"
with pytest.raises(TypeError, match=msg):
arr + Series([ts])
with pytest.raises(TypeError, match=msg):
Series([ts]) + arr
with pytest.raises(TypeError, match=msg):
arr + pd.Index([ts])
with pytest.raises(TypeError, match=msg):
pd.Index([ts]) + arr
if box_with_array is pd.DataFrame:
msg = "cannot add PeriodArray and DatetimeArray"
else:
msg = r"unsupported operand type\(s\) for \+: 'Period' and 'DatetimeArray"
with pytest.raises(TypeError, match=msg):
arr + pd.DataFrame([ts])
if box_with_array is pd.DataFrame:
msg = "cannot add PeriodArray and DatetimeArray"
else:
msg = r"unsupported operand type\(s\) for \+: 'DatetimeArray' and 'Period'"
with pytest.raises(TypeError, match=msg):
pd.DataFrame([ts]) + arr
| TestPeriodIndexArithmetic |
python | apache__airflow | shared/secrets_masker/src/airflow_shared/secrets_masker/secrets_masker.py | {
"start": 22123,
"end": 23878
} | class ____(TextIO):
"""
IO class that redacts values going into stdout.
Expected usage::
with contextlib.redirect_stdout(RedactedIO()):
... # Writes to stdout will be redacted.
"""
def __init__(self):
self.target = sys.stdout
def __enter__(self) -> TextIO:
return self.target.__enter__()
def __exit__(self, t, v, b) -> None:
return self.target.__exit__(t, v, b)
def __iter__(self) -> Iterator[str]:
return iter(self.target)
def __next__(self) -> str:
return next(self.target)
def close(self) -> None:
return self.target.close()
def fileno(self) -> int:
return self.target.fileno()
def flush(self) -> None:
return self.target.flush()
def isatty(self) -> bool:
return self.target.isatty()
def read(self, n: int = -1) -> str:
return self.target.read(n)
def readable(self) -> bool:
return self.target.readable()
def readline(self, n: int = -1) -> str:
return self.target.readline(n)
def readlines(self, n: int = -1) -> list[str]:
return self.target.readlines(n)
def seek(self, offset: int, whence: int = 0) -> int:
return self.target.seek(offset, whence)
def seekable(self) -> bool:
return self.target.seekable()
def tell(self) -> int:
return self.target.tell()
def truncate(self, s: int | None = None) -> int:
return self.target.truncate(s)
def writable(self) -> bool:
return self.target.writable()
def write(self, s: str) -> int:
s = str(redact(s))
return self.target.write(s)
def writelines(self, lines) -> None:
self.target.writelines(lines)
| RedactedIO |
python | gevent__gevent | src/greentest/3.10/test_httplib.py | {
"start": 52325,
"end": 53275
} | class ____:
"""
a simple readline class that uses an arbitrary read function and buffering
"""
def __init__(self, readfunc):
self.readfunc = readfunc
self.remainder = b""
def readline(self, limit):
data = []
datalen = 0
read = self.remainder
try:
while True:
idx = read.find(b'\n')
if idx != -1:
break
if datalen + len(read) >= limit:
idx = limit - datalen - 1
# read more data
data.append(read)
read = self.readfunc()
if not read:
idx = 0 #eof condition
break
idx += 1
data.append(read[:idx])
self.remainder = read[idx:]
return b"".join(data)
except:
self.remainder = b"".join(data)
raise
| Readliner |
python | jazzband__django-oauth-toolkit | tests/test_mixins.py | {
"start": 3428,
"end": 3937
} | class ____(BaseTest):
def test_missing_required_scopes(self):
class TestView(ScopedResourceMixin, View):
pass
test_view = TestView()
self.assertRaises(ImproperlyConfigured, test_view.get_scopes)
def test_correct_required_scopes(self):
class TestView(ScopedResourceMixin, View):
required_scopes = ["scope1", "scope2"]
test_view = TestView()
self.assertEqual(test_view.get_scopes(), ["scope1", "scope2"])
| TestScopedResourceMixin |
python | lepture__authlib | authlib/jose/rfc7518/jws_algs.py | {
"start": 780,
"end": 1065
} | class ____(JWSAlgorithm):
name = "none"
description = "No digital signature or MAC performed"
def prepare_key(self, raw_data):
return None
def sign(self, msg, key):
return b""
def verify(self, msg, sig, key):
return sig == b""
| NoneAlgorithm |
python | Farama-Foundation__Gymnasium | gymnasium/wrappers/vector/vectorize_observation.py | {
"start": 14634,
"end": 15550
} | class ____(VectorizeTransformObservation):
"""Reshapes array based observations to shapes.
Example:
>>> import gymnasium as gym
>>> envs = gym.make_vec("CarRacing-v3", num_envs=3, vectorization_mode="sync")
>>> obs, info = envs.reset(seed=123)
>>> obs.shape
(3, 96, 96, 3)
>>> envs = ReshapeObservation(envs, shape=(9216, 3))
>>> obs, info = envs.reset(seed=123)
>>> obs.shape
(3, 9216, 3)
>>> envs.close()
"""
def __init__(self, env: VectorEnv, shape: int | tuple[int, ...]):
"""Constructor for env with Box observation space that has a shape product equal to the new shape product.
Args:
env: The vector environment to wrap
shape: The reshaped observation space
"""
super().__init__(env, transform_observation.ReshapeObservation, shape=shape)
| ReshapeObservation |
python | sympy__sympy | sympy/stats/frv.py | {
"start": 11036,
"end": 15927
} | class ____(SinglePSpace, FinitePSpace):
"""
A single finite probability space
Represents the probabilities of a set of random events that can be
attributed to a single variable/symbol.
This class is implemented by many of the standard FiniteRV types such as
Die, Bernoulli, Coin, etc....
"""
@property
def domain(self):
return SingleFiniteDomain(self.symbol, self.distribution.set)
@property
def _is_symbolic(self):
"""
Helper property to check if the distribution
of the random variable is having symbolic
dimension.
"""
return self.distribution.is_symbolic
@property
def distribution(self):
return self.args[1]
def pmf(self, expr):
return self.distribution.pmf(expr)
@property # type: ignore
@cacheit
def _density(self):
return {FiniteSet((self.symbol, val)): prob
for val, prob in self.distribution.dict.items()}
@cacheit
def compute_characteristic_function(self, expr):
if self._is_symbolic:
d = self.compute_density(expr)
t = Dummy('t', real=True)
ki = Dummy('ki')
return Lambda(t, Sum(d(ki)*exp(I*ki*t), (ki, self.args[1].low, self.args[1].high)))
expr = rv_subs(expr, self.values)
return FinitePSpace(self.domain, self.distribution).compute_characteristic_function(expr)
@cacheit
def compute_moment_generating_function(self, expr):
if self._is_symbolic:
d = self.compute_density(expr)
t = Dummy('t', real=True)
ki = Dummy('ki')
return Lambda(t, Sum(d(ki)*exp(ki*t), (ki, self.args[1].low, self.args[1].high)))
expr = rv_subs(expr, self.values)
return FinitePSpace(self.domain, self.distribution).compute_moment_generating_function(expr)
def compute_quantile(self, expr):
if self._is_symbolic:
raise NotImplementedError("Computing quantile for random variables "
"with symbolic dimension because the bounds of searching the required "
"value is undetermined.")
expr = rv_subs(expr, self.values)
return FinitePSpace(self.domain, self.distribution).compute_quantile(expr)
def compute_density(self, expr):
if self._is_symbolic:
rv = list(random_symbols(expr))[0]
k = Dummy('k', integer=True)
cond = True if not isinstance(expr, (Relational, Logic)) \
else expr.subs(rv, k)
return Lambda(k,
Piecewise((self.pmf(k), And(k >= self.args[1].low,
k <= self.args[1].high, cond)), (S.Zero, True)))
expr = rv_subs(expr, self.values)
return FinitePSpace(self.domain, self.distribution).compute_density(expr)
def compute_cdf(self, expr):
if self._is_symbolic:
d = self.compute_density(expr)
k = Dummy('k')
ki = Dummy('ki')
return Lambda(k, Sum(d(ki), (ki, self.args[1].low, k)))
expr = rv_subs(expr, self.values)
return FinitePSpace(self.domain, self.distribution).compute_cdf(expr)
def compute_expectation(self, expr, rvs=None, **kwargs):
if self._is_symbolic:
rv = random_symbols(expr)[0]
k = Dummy('k', integer=True)
expr = expr.subs(rv, k)
cond = True if not isinstance(expr, (Relational, Logic)) \
else expr
func = self.pmf(k) * k if cond != True else self.pmf(k) * expr
return Sum(Piecewise((func, cond), (S.Zero, True)),
(k, self.distribution.low, self.distribution.high)).doit()
expr = _sympify(expr)
expr = rv_subs(expr, rvs)
return FinitePSpace(self.domain, self.distribution).compute_expectation(expr, rvs, **kwargs)
def probability(self, condition):
if self._is_symbolic:
#TODO: Implement the mechanism for handling queries for symbolic sized distributions.
raise NotImplementedError("Currently, probability queries are not "
"supported for random variables with symbolic sized distributions.")
condition = rv_subs(condition)
return FinitePSpace(self.domain, self.distribution).probability(condition)
def conditional_space(self, condition):
"""
This method is used for transferring the
computation to probability method because
conditional space of random variables with
symbolic dimensions is currently not possible.
"""
if self._is_symbolic:
self
domain = self.where(condition)
prob = self.probability(condition)
density = {key: val / prob
for key, val in self._density.items() if domain._test(key)}
return FinitePSpace(domain, density)
| SingleFinitePSpace |
python | django__django | tests/i18n/test_extraction.py | {
"start": 42112,
"end": 42812
} | class ____(ExtractorTests):
POT_FILE = "locale/django.pot"
def test_keep_pot_disabled_by_default(self):
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
self.assertFalse(os.path.exists(self.POT_FILE))
def test_keep_pot_explicitly_disabled(self):
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, keep_pot=False
)
self.assertFalse(os.path.exists(self.POT_FILE))
def test_keep_pot_enabled(self):
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, keep_pot=True
)
self.assertTrue(os.path.exists(self.POT_FILE))
| KeepPotFileExtractorTests |
python | mlflow__mlflow | mlflow/genai/judges/base.py | {
"start": 1638,
"end": 4332
} | class ____(Scorer):
"""
Base class for LLM-as-a-judge scorers that can be aligned with human feedback.
Judges are specialized scorers that use LLMs to evaluate outputs based on
configurable criteria and the results of human-provided feedback alignment.
"""
@property
def kind(self) -> ScorerKind:
return ScorerKind.BUILTIN
@property
@abstractmethod
def instructions(self) -> str:
"""
Plain text instructions of what this judge evaluates.
"""
@abstractmethod
def get_input_fields(self) -> list[JudgeField]:
"""
Get the input fields for this judge.
Returns:
List of JudgeField objects defining the input fields.
"""
@classmethod
def get_output_fields(cls) -> list[JudgeField]:
"""
Get the standard output fields used by all judges.
This is the source of truth for judge output field definitions.
Returns:
List of JudgeField objects defining the standard output fields.
"""
return [
JudgeField(name="result", description=_RESULT_FIELD_DESCRIPTION, value_type=str),
JudgeField(
name="rationale",
description=_RATIONALE_FIELD_DESCRIPTION,
value_type=str,
),
]
@experimental(version="3.4.0")
@record_usage_event(AlignJudgeEvent)
def align(self, traces: list[Trace], optimizer: AlignmentOptimizer | None = None) -> Judge:
"""
Align this judge with human preferences using the provided optimizer and traces.
Args:
traces: Training traces for alignment
optimizer: The alignment optimizer to use. If None, uses the default SIMBA optimizer.
Returns:
A new Judge instance that is better aligned with the input traces.
Raises:
NotImplementedError: If called on a session-level scorer. Alignment is currently
only supported for single-turn scorers.
Note on Logging:
By default, alignment optimization shows minimal progress information.
To see detailed optimization output, set the optimizer's logger to DEBUG::
import logging
# For SIMBA optimizer (default)
logging.getLogger("mlflow.genai.judges.optimizers.simba").setLevel(logging.DEBUG)
"""
if self.is_session_level_scorer:
raise NotImplementedError("Alignment is not supported for session-level scorers.")
if optimizer is None:
optimizer = get_default_optimizer()
return optimizer.align(self, traces)
| Judge |
python | google__pytype | pytype/overlays/typed_dict.py | {
"start": 9556,
"end": 13715
} | class ____(abstract.Dict):
"""Representation of TypedDict instances.
Internally, a TypedDict is a dict with a restricted set of string keys
allowed, each with a fixed type. We implement it as a subclass of Dict, with
some type checks wrapped around key accesses. If a check fails, we simply add
an error to the logs and then continue processing the method as though it were
a regular dict.
"""
def __init__(self, props, ctx):
super().__init__(ctx)
self.props = props
self.set_native_slot("__delitem__", self.delitem_slot)
self.set_native_slot("get", self.get_slot)
@property
def fields(self):
return self.props.fields
@property
def class_name(self):
return self.props.name
def __repr__(self):
return f"<TypedDict {self.class_name}>"
def _check_str_key(self, name):
if name not in self.fields:
raise error_types.TypedDictKeyMissing(self, name)
return name
def _check_str_key_value(self, node, name, value_var):
self._check_str_key(name)
typ = self.fields[name]
bad = self.ctx.matcher(node).compute_one_match(value_var, typ).bad_matches
for match in bad:
self.ctx.errorlog.annotation_type_mismatch(
self.ctx.vm.frames,
match.expected.typ,
match.actual_binding,
name,
match.error_details,
typed_dict=self,
)
return name, value_var
def _check_key(self, name_var):
"""Check that key is in the typed dict."""
try:
name = abstract_utils.get_atomic_python_constant(name_var, str)
except abstract_utils.ConversionError as e:
raise error_types.TypedDictKeyMissing(self, None) from e
return self._check_str_key(name)
def _check_value(self, node, name_var, value_var):
"""Check that value has the right type."""
# We have already called check_key so name is in fields
name = abstract_utils.get_atomic_python_constant(name_var, str)
self._check_str_key_value(node, name, value_var)
return value_var
def getitem_slot(self, node, name_var):
# A typed dict getitem should have a concrete string arg. If we have a var
# with multiple bindings just fall back to Any.
self._check_key(name_var)
return super().getitem_slot(node, name_var)
def setitem_slot(self, node, name_var, value_var):
self._check_key(name_var)
self._check_value(node, name_var, value_var)
return super().setitem_slot(node, name_var, value_var)
def set_str_item(self, node, name, value_var):
self._check_str_key_value(node, name, value_var)
return super().set_str_item(node, name, value_var)
def delitem_slot(self, node, name_var):
self._check_key(name_var)
return self.call_pytd(node, "__delitem__", name_var)
def pop_slot(self, node, key_var, default_var=None):
self._check_key(key_var)
return super().pop_slot(node, key_var, default_var)
def get_slot(self, node, key_var, default_var=None):
try:
str_key = self._check_key(key_var)
except error_types.TypedDictKeyMissing:
return node, default_var or self.ctx.convert.none.to_variable(node)
if str_key in self.pyval:
return node, self.pyval[str_key]
else:
# If total=False the key might not be in self.pyval.
# TODO(mdemello): Should we return `self.props[key].typ | default | None`
# here, or just `default | None`?
return node, default_var or self.ctx.convert.none.to_variable(node)
def merge_instance_type_parameter(self, node, name, value):
_, _, short_name = name.rpartition(".")
if short_name == abstract_utils.K:
expected_length = 1
else:
assert short_name == abstract_utils.V, name
expected_length = len(self.fields)
if len(self.get_instance_type_parameter(name).data) >= expected_length:
# Since a TypedDict's key and value types are pre-defined, we never mutate
# them once fully set.
return
super().merge_instance_type_parameter(node, name, value)
def _is_typeddict(val: abstract.BaseValue):
if isinstance(val, abstract.Union):
return all(_is_typeddict(v) for v in val.options)
return isinstance(val, TypedDictClass)
| TypedDict |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/transfers/http_to_gcs.py | {
"start": 1321,
"end": 8552
} | class ____(BaseOperator):
"""
Calls an endpoint on an HTTP system to execute an action and store the result in GCS.
:param http_conn_id: The :ref:`http connection<howto/connection:http>` to run
the operator against
:param endpoint: The relative part of the full url. (templated)
:param method: The HTTP method to use, default = "POST"
:param data: The data to pass. POST-data in POST/PUT and params
in the URL for a GET request. (templated)
:param headers: The HTTP headers to be added to the GET request
:param response_check: A check against the 'requests' response object.
The callable takes the response object as the first positional argument
and optionally any number of keyword arguments available in the context dictionary.
It should return True for 'pass' and False otherwise.
:param response_filter: A function allowing you to manipulate the response
text. e.g response_filter=lambda response: json.loads(response.text).
The callable takes the response object as the first positional argument
and optionally any number of keyword arguments available in the context dictionary.
:param extra_options: Extra options for the 'requests' library, see the
'requests' documentation (options to modify timeout, ssl, etc.)
:param log_response: Log the response (default: False)
:param auth_type: The auth type for the service
:param tcp_keep_alive: Enable TCP Keep Alive for the connection.
:param tcp_keep_alive_idle: The TCP Keep Alive Idle parameter (corresponds to ``socket.TCP_KEEPIDLE``).
:param tcp_keep_alive_count: The TCP Keep Alive count parameter (corresponds to ``socket.TCP_KEEPCNT``)
:param tcp_keep_alive_interval: The TCP Keep Alive interval parameter (corresponds to
``socket.TCP_KEEPINTVL``)
:param gcp_conn_id: The connection ID to use when fetching connection info.
:param impersonation_chain: Optional service account to impersonate using short-term credentials,
or chained list of accounts required to get the access_token of the last account in the list,
which will be impersonated in the request. If set as a string,
the account must grant the originating account the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity,
with first account from the list granting this role to the originating account.
:param bucket_name: The bucket to upload to.
:param object_name: The object name to set when uploading the file.
:param mime_type: The file mime type set when uploading the file.
:param gzip: Option to compress local file or file data for upload
:param encoding: bytes encoding for file data if provided as string
:param chunk_size: Blob chunk size.
:param timeout: Request timeout in seconds.
:param num_max_attempts: Number of attempts to try to upload the file.
:param metadata: The metadata to be uploaded with the file.
:param cache_contro: Cache-Control metadata field.
:param user_project: The identifier of the Google Cloud project to bill for the request. Required for Requester Pays buckets.
"""
template_fields: Sequence[str] = (
"http_conn_id",
"endpoint",
"data",
"headers",
"gcp_conn_id",
"bucket_name",
"object_name",
)
template_fields_renderers = {"headers": "json", "data": "py"}
template_ext: Sequence[str] = ()
ui_color = "#f4a460"
def __init__(
self,
*,
endpoint: str | None = None,
method: str = "GET",
data: Any = None,
headers: dict[str, str] | None = None,
extra_options: dict[str, Any] | None = None,
http_conn_id: str = "http_default",
log_response: bool = False,
auth_type: type[AuthBase] | None = None,
tcp_keep_alive: bool = True,
tcp_keep_alive_idle: int = 120,
tcp_keep_alive_count: int = 20,
tcp_keep_alive_interval: int = 30,
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
bucket_name: str,
object_name: str,
mime_type: str | None = None,
gzip: bool = False,
encoding: str | None = None,
chunk_size: int | None = None,
timeout: int | None = None,
num_max_attempts: int = 3,
metadata: dict | None = None,
cache_control: str | None = None,
user_project: str | None = None,
**kwargs,
):
super().__init__(**kwargs)
self.http_conn_id = http_conn_id
self.method = method
self.endpoint = endpoint
self.headers = headers or {}
self.data = data or {}
self.extra_options = extra_options or {}
self.log_response = log_response
self.auth_type = auth_type
self.tcp_keep_alive = tcp_keep_alive
self.tcp_keep_alive_idle = tcp_keep_alive_idle
self.tcp_keep_alive_count = tcp_keep_alive_count
self.tcp_keep_alive_interval = tcp_keep_alive_interval
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
self.bucket_name = bucket_name
self.object_name = object_name
self.mime_type = mime_type
self.gzip = gzip
self.encoding = encoding
self.chunk_size = chunk_size
self.timeout = timeout
self.num_max_attempts = num_max_attempts
self.metadata = metadata
self.cache_control = cache_control
self.user_project = user_project
@cached_property
def http_hook(self) -> HttpHook:
"""Create and return an HttpHook."""
return HttpHook(
self.method,
http_conn_id=self.http_conn_id,
auth_type=self.auth_type,
tcp_keep_alive=self.tcp_keep_alive,
tcp_keep_alive_idle=self.tcp_keep_alive_idle,
tcp_keep_alive_count=self.tcp_keep_alive_count,
tcp_keep_alive_interval=self.tcp_keep_alive_interval,
)
@cached_property
def gcs_hook(self) -> GCSHook:
"""Create and return an GCSHook."""
return GCSHook(gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain)
def execute(self, context: Context):
self.log.info("Calling HTTP method")
response = self.http_hook.run(
endpoint=self.endpoint, data=self.data, headers=self.headers, extra_options=self.extra_options
)
self.log.info("Uploading to GCS")
self.gcs_hook.upload(
data=response.content,
bucket_name=self.bucket_name,
object_name=self.object_name,
mime_type=self.mime_type,
gzip=self.gzip,
encoding=self.encoding or response.encoding,
chunk_size=self.chunk_size,
timeout=self.timeout,
num_max_attempts=self.num_max_attempts,
metadata=self.metadata,
cache_control=self.cache_control,
user_project=self.user_project,
)
| HttpToGCSOperator |
python | pandas-dev__pandas | scripts/check_for_inconsistent_pandas_namespace.py | {
"start": 1079,
"end": 1175
} | class ____(NamedTuple):
lineno: int
col_offset: int
namespace: str
| OffsetWithNamespace |
python | pytorch__pytorch | torch/utils/throughput_benchmark.py | {
"start": 792,
"end": 1878
} | class ____:
def __init__(self, c_stats, benchmark_config) -> None:
self._c_stats = c_stats
self.benchmark_config = benchmark_config
@property
def latency_avg_ms(self):
return self._c_stats.latency_avg_ms
@property
def num_iters(self):
return self._c_stats.num_iters
@property
def iters_per_second(self):
"""Return total number of iterations per second across all calling threads."""
return self.num_iters / self.total_time_seconds
@property
def total_time_seconds(self):
return self.num_iters * (
self.latency_avg_ms / 1000.0) / self.benchmark_config.num_calling_threads
def __str__(self) -> str:
return '\n'.join([
"Average latency per example: " + format_time(time_ms=self.latency_avg_ms),
f"Total number of iterations: {self.num_iters}",
f"Total number of iterations per second (across all threads): {self.iters_per_second:.2f}",
"Total time: " + format_time(time_s=self.total_time_seconds)
])
| ExecutionStats |
python | scrapy__scrapy | tests/test_pipeline_files.py | {
"start": 11869,
"end": 12205
} | class ____:
name = attr.ib(default="")
# default fields
file_urls: list[str] = attr.ib(default=list)
files: list[dict[str, str]] = attr.ib(default=list)
# overridden fields
custom_file_urls: list[str] = attr.ib(default=list)
custom_files: list[dict[str, str]] = attr.ib(default=list)
| FilesPipelineTestAttrsItem |
python | openai__openai-python | src/openai/types/beta/assistant_stream_event.py | {
"start": 3534,
"end": 3750
} | class ____(BaseModel):
data: Run
"""
Represents an execution run on a
[thread](https://platform.openai.com/docs/api-reference/threads).
"""
event: Literal["thread.run.expired"]
| ThreadRunExpired |
python | pytorch__pytorch | test/test_serialization.py | {
"start": 39405,
"end": 40010
} | class ____:
def __init__(self, use_zip):
self.use_zip = use_zip
self.torch_save = torch.save
def __enter__(self, *args, **kwargs):
def wrapper(*args, **kwargs):
if '_use_new_zipfile_serialization' in kwargs:
raise RuntimeError("Cannot set method manually")
kwargs['_use_new_zipfile_serialization'] = self.use_zip
return self.torch_save(*args, **kwargs)
torch.save = wrapper
def __exit__(self, *args, **kwargs):
torch.save = self.torch_save
Point = namedtuple('Point', ['x', 'y'])
| serialization_method |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 78414,
"end": 83312
} | class ____(ASTBase):
def __init__(
self,
storage: str,
threadLocal: bool,
inline: bool,
virtual: bool,
explicitSpec: ASTExplicitSpec | None,
consteval: bool,
constexpr: bool,
constinit: bool,
volatile: bool,
const: bool,
friend: bool,
attrs: ASTAttributeList,
) -> None:
self.storage = storage
self.threadLocal = threadLocal
self.inline = inline
self.virtual = virtual
self.explicitSpec = explicitSpec
self.consteval = consteval
self.constexpr = constexpr
self.constinit = constinit
self.volatile = volatile
self.const = const
self.friend = friend
self.attrs = attrs
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTDeclSpecsSimple):
return NotImplemented
return (
self.storage == other.storage
and self.threadLocal == other.threadLocal
and self.inline == other.inline
and self.virtual == other.virtual
and self.explicitSpec == other.explicitSpec
and self.consteval == other.consteval
and self.constexpr == other.constexpr
and self.constinit == other.constinit
and self.volatile == other.volatile
and self.const == other.const
and self.friend == other.friend
and self.attrs == other.attrs
)
def __hash__(self) -> int:
return hash((
self.storage,
self.threadLocal,
self.inline,
self.virtual,
self.explicitSpec,
self.consteval,
self.constexpr,
self.constinit,
self.volatile,
self.const,
self.friend,
self.attrs,
))
def mergeWith(self, other: ASTDeclSpecsSimple) -> ASTDeclSpecsSimple:
if not other:
return self
return ASTDeclSpecsSimple(
self.storage or other.storage,
self.threadLocal or other.threadLocal,
self.inline or other.inline,
self.virtual or other.virtual,
self.explicitSpec or other.explicitSpec,
self.consteval or other.consteval,
self.constexpr or other.constexpr,
self.constinit or other.constinit,
self.volatile or other.volatile,
self.const or other.const,
self.friend or other.friend,
self.attrs + other.attrs,
)
def _stringify(self, transform: StringifyTransform) -> str:
res: list[str] = []
if len(self.attrs) != 0:
res.append(transform(self.attrs))
if self.storage:
res.append(self.storage)
if self.threadLocal:
res.append('thread_local')
if self.inline:
res.append('inline')
if self.friend:
res.append('friend')
if self.virtual:
res.append('virtual')
if self.explicitSpec:
res.append(transform(self.explicitSpec))
if self.consteval:
res.append('consteval')
if self.constexpr:
res.append('constexpr')
if self.constinit:
res.append('constinit')
if self.volatile:
res.append('volatile')
if self.const:
res.append('const')
return ' '.join(res)
def describe_signature(
self, signode: TextElement, env: BuildEnvironment, symbol: Symbol
) -> None:
self.attrs.describe_signature(signode)
add_space = len(self.attrs) != 0
def _add(signode: TextElement, text: str) -> bool:
if add_space:
signode += addnodes.desc_sig_space()
signode += addnodes.desc_sig_keyword(text, text)
return True
if self.storage:
add_space = _add(signode, self.storage)
if self.threadLocal:
add_space = _add(signode, 'thread_local')
if self.inline:
add_space = _add(signode, 'inline')
if self.friend:
add_space = _add(signode, 'friend')
if self.virtual:
add_space = _add(signode, 'virtual')
if self.explicitSpec:
if add_space:
signode += addnodes.desc_sig_space()
self.explicitSpec.describe_signature(signode, env, symbol)
add_space = True
if self.consteval:
add_space = _add(signode, 'consteval')
if self.constexpr:
add_space = _add(signode, 'constexpr')
if self.constinit:
add_space = _add(signode, 'constinit')
if self.volatile:
add_space = _add(signode, 'volatile')
if self.const:
add_space = _add(signode, 'const')
| ASTDeclSpecsSimple |
python | google__jax | jax/_src/util.py | {
"start": 16285,
"end": 16481
} | class ____:
__slots__ = ["val"]
def __init__(self, val):
self.val = val
def __hash__(self):
return hash(self.val)
def __eq__(self, other):
return self.val == other.val
| Hashable |
python | celery__celery | celery/local.py | {
"start": 12986,
"end": 16039
} | class ____(ModuleType):
_compat_modules = ()
_all_by_module = {}
_direct = {}
_object_origins = {}
def __getattr__(self, name):
if name in self._object_origins:
module = __import__(self._object_origins[name], None, None,
[name])
for item in self._all_by_module[module.__name__]:
setattr(self, item, getattr(module, item))
return getattr(module, name)
elif name in self._direct: # pragma: no cover
module = __import__(self._direct[name], None, None, [name])
setattr(self, name, module)
return module
return ModuleType.__getattribute__(self, name)
def __dir__(self):
return [
attr for attr in set(self.__all__) | DEFAULT_ATTRS
if attr not in DEPRECATED_ATTRS
]
def __reduce__(self):
return import_module, (self.__name__,)
def create_module(name, attrs, cls_attrs=None, pkg=None,
base=LazyModule, prepare_attr=None):
fqdn = '.'.join([pkg.__name__, name]) if pkg else name
cls_attrs = {} if cls_attrs is None else cls_attrs
pkg, _, modname = name.rpartition('.')
cls_attrs['__module__'] = pkg
attrs = {
attr_name: (prepare_attr(attr) if prepare_attr else attr)
for attr_name, attr in attrs.items()
}
module = sys.modules[fqdn] = type(
modname, (base,), cls_attrs)(name)
module.__dict__.update(attrs)
return module
def recreate_module(name, compat_modules=None, by_module=None, direct=None,
base=LazyModule, **attrs):
compat_modules = compat_modules or COMPAT_MODULES.get(name, ())
by_module = by_module or {}
direct = direct or {}
old_module = sys.modules[name]
origins = get_origins(by_module)
_all = tuple(set(reduce(
operator.add,
[tuple(v) for v in [compat_modules, origins, direct, attrs]],
)))
cattrs = {
'_compat_modules': compat_modules,
'_all_by_module': by_module, '_direct': direct,
'_object_origins': origins,
'__all__': _all,
}
new_module = create_module(name, attrs, cls_attrs=cattrs, base=base)
new_module.__dict__.update({
mod: get_compat_module(new_module, mod) for mod in compat_modules
})
new_module.__spec__ = old_module.__spec__
return old_module, new_module
def get_compat_module(pkg, name):
def prepare(attr):
if isinstance(attr, str):
return Proxy(getappattr, (attr,))
return attr
attrs = COMPAT_MODULES[pkg.__name__][name]
if isinstance(attrs, str):
fqdn = '.'.join([pkg.__name__, name])
module = sys.modules[fqdn] = import_module(attrs)
return module
attrs['__all__'] = list(attrs)
return create_module(name, dict(attrs), pkg=pkg, prepare_attr=prepare)
def get_origins(defs):
origins = {}
for module, attrs in defs.items():
origins.update({attr: module for attr in attrs})
return origins
| LazyModule |
python | ray-project__ray | python/ray/tune/schedulers/resource_changing_scheduler.py | {
"start": 18011,
"end": 22728
} | class ____(DistributeResources):
"""This class creates a "TopJob" resource allocation function.
The function will assign all of the free resources to the best
performing trial (as defined by ``metric`` and ``mode``). The
previous best trials will not have their resources deallocated,
unless in the case outlined below.
If for some reason a trial ends up with
more resources than there are free ones, it will adjust downwards.
It will also ensure that trial as at least as many resources as
it started with (``base_trial_resource``).
The function returns a new ``PlacementGroupFactory`` with updated
resource requirements, or None. If the returned
``PlacementGroupFactory`` is equal by value to the one the
trial has currently, the scheduler will skip the update process
internally (same with None).
Args:
add_bundles: If True, create new bundles from free resources.
Otherwise, spread them among base_trial_resource bundles.
increase_by: A dict with key-value
pairs representing an atomic unit of resources (name-amount)
the trial will be increased by. If not set, the trial will
increase by 1 CPU/GPU.
increase_by_times: If set to >=1 and ``increase_by`` is set,
the trial will increase by maximum of
``increase_by_times * increase_by`` resources. If set to <1,
no upper limit is set. Ignored if ``increase_by`` is not set.
reserve_resources: A dict of
resource_name-amount pairs representing the resources
that will not be allocated to resized trials.
is that the attribute should increase monotonically.
metric: The training result objective value attribute. Stopping
procedures will use this attribute. If None, will use the metric
of the scheduler.
mode: One of {min, max}. Determines whether objective is
minimizing or maximizing the metric attribute. If None, will use the metric
of the scheduler.
"""
def __init__(
self,
add_bundles: bool = False,
increase_by: Optional[Dict[str, float]] = None,
increase_by_times: int = -1,
reserve_resources: Optional[Dict[str, float]] = None,
metric: Optional[str] = None,
mode: Optional[str] = None,
):
super().__init__(add_bundles, increase_by, increase_by_times, reserve_resources)
self.metric = metric
self.mode = mode
@property
def _metric_op(self) -> float:
if self.mode not in ("min", "max"):
raise ValueError("The mode parameter can only be either min or max.")
if self.mode == "max":
return 1.0
return -1.0
def _get_new_added_bundles(
self,
trial: Trial,
all_trials: List[Trial],
base_bundles: List[Dict[str, float]],
increase_by: Dict[str, float],
total_available_cpus: float,
total_available_gpus: float,
used_cpus: float,
used_gpus: float,
) -> List[Dict[str, float]]:
if self.metric is None:
raise ValueError(
"The metric parameter cannot be None. The parameter can be set in "
"either `DistributeResourcesToTopJob`, the base scheduler or in "
"`tune.TuneConfig()` (highest to lowest priority)."
)
free_cpus = total_available_cpus - used_cpus
free_gpus = total_available_gpus - used_gpus
sorted_trials = sorted(
all_trials,
key=lambda t: -self._metric_op * t.last_result.get(self.metric, np.inf),
)
added_bundles = self._get_added_bundles(
trial.placement_group_factory.bundles, base_bundles
)
best_trial = next(
(
t
for t in sorted_trials
if self._are_bundles_below_limit(
t.placement_group_factory.bundles, base_bundles
)
),
sorted_trials[0],
)
if (
trial.trial_id != best_trial.trial_id
# Only reduce resources here
and self._get_multiplier(increase_by, free_cpus, free_gpus) >= 0
):
return added_bundles
return self._modify_bundles_with_free_resources(
added_bundles,
increase_by,
free_cpus,
free_gpus,
)
_DistributeResourcesDefault = DistributeResources(add_bundles=False)
_DistributeResourcesDistributedDefault = DistributeResources(add_bundles=True)
@PublicAPI(stability="beta")
| DistributeResourcesToTopJob |
python | huggingface__transformers | tests/models/phi4_multimodal/test_feature_extraction_phi4_multimodal.py | {
"start": 1416,
"end": 3447
} | class ____:
def __init__(
self,
parent,
batch_size=7,
min_seq_length=400,
max_seq_length=2000,
feature_size=80,
hop_length=160,
win_length=400,
padding_value=0.0,
sampling_rate=16_000,
return_attention_mask=False,
do_normalize=True,
):
self.parent = parent
self.batch_size = batch_size
self.min_seq_length = min_seq_length
self.max_seq_length = max_seq_length
self.seq_length_diff = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
self.padding_value = padding_value
self.sampling_rate = sampling_rate
self.return_attention_mask = return_attention_mask
self.do_normalize = do_normalize
self.feature_size = feature_size
self.win_length = win_length
self.hop_length = hop_length
def prepare_feat_extract_dict(self):
return {
"feature_size": self.feature_size,
"hop_length": self.hop_length,
"win_length": self.win_length,
"padding_value": self.padding_value,
"sampling_rate": self.sampling_rate,
"return_attention_mask": self.return_attention_mask,
"do_normalize": self.do_normalize,
}
def prepare_inputs_for_common(self, equal_length=False, numpify=False):
def _flatten(list_of_lists):
return list(itertools.chain(*list_of_lists))
if equal_length:
speech_inputs = [floats_list((self.max_seq_length, self.feature_size)) for _ in range(self.batch_size)]
else:
# make sure that inputs increase in size
speech_inputs = [
floats_list((x, self.feature_size))
for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff)
]
if numpify:
speech_inputs = [np.asarray(x) for x in speech_inputs]
return speech_inputs
| Phi4MultimodalFeatureExtractionTester |
python | dask__distributed | distributed/comm/ws.py | {
"start": 2746,
"end": 5529
} | class ____(Comm):
def __init__(
self,
handler: WSHandler,
deserialize: bool = True,
allow_offload: bool = True,
):
self.handler = handler
self.allow_offload = allow_offload
super().__init__(deserialize=deserialize)
async def read(self, deserializers=None):
try:
n_frames = await self.handler.q.get()
except RuntimeError: # Event loop is closed
raise CommClosedError()
if n_frames is CommClosedError:
raise CommClosedError()
else:
n_frames = struct.unpack("Q", n_frames)[0]
frames = [(await self.handler.q.get()) for _ in range(n_frames)]
return await from_frames(
frames,
deserialize=self.deserialize,
deserializers=deserializers,
allow_offload=self.allow_offload,
)
async def write(self, msg, serializers=None, on_error=None):
frames = await to_frames(
msg,
allow_offload=self.allow_offload,
serializers=serializers,
on_error=on_error,
context={
"sender": self.local_info,
"recipient": self.remote_info,
**self.handshake_options,
},
frame_split_size=BIG_BYTES_SHARD_SIZE,
)
n = struct.pack("Q", len(frames))
nbytes_frames = 0
try:
await self.handler.write_message(n, binary=True)
for frame in frames:
if type(frame) is not bytes:
frame = bytes(frame)
await self.handler.write_message(frame, binary=True)
nbytes_frames += len(frame)
except WebSocketClosedError as e:
raise CommClosedError(str(e))
return nbytes_frames
def abort(self):
self.handler.close()
@property
def local_address(self) -> str:
return self.handler.request.host
@property
def peer_address(self) -> str:
ip = self.handler.request.remote_ip
assert isinstance(ip, str)
return ip + ":0"
@property
def same_host(self) -> bool:
"""Override Comm.same_host, adding support for HTTP-only subdomains, which won't
have a port and that may not be known to the DNS service
"""
try:
return super().same_host
except (ValueError, socket.gaierror):
return False
def closed(self):
return (
self.handler.closed
or not self.handler.ws_connection
or self.handler.request.connection.stream
and self.handler.request.connection.stream.closed
)
async def close(self):
self.handler.close()
| WSHandlerComm |
python | pyca__cryptography | tests/hazmat/primitives/test_dh.py | {
"start": 4655,
"end": 19726
} | class ____:
def test_small_key_generate_dh(self, backend):
with pytest.raises(ValueError):
dh.generate_parameters(2, 511, backend)
def test_unsupported_generator_generate_dh(self, backend):
with pytest.raises(ValueError):
dh.generate_parameters(7, 512, backend)
def test_large_key_generate_dh(self, backend):
with pytest.raises(ValueError):
dh.generate_parameters(2, 1 << 30)
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
os.path.join("asymmetric", "DH", "rfc3526.txt"), load_nist_vectors
),
)
def test_dh_parameters_allows_rfc3526_groups(self, backend, vector):
p = int.from_bytes(binascii.unhexlify(vector["p"]), "big")
if backend._fips_enabled and p < backend._fips_dh_min_modulus:
pytest.skip("modulus too small for FIPS mode")
params = dh.DHParameterNumbers(p, int(vector["g"]))
param = params.parameters(backend)
key = param.generate_private_key()
# In OpenSSL 3.0.0 OpenSSL maps to known groups. This results in
# a scenario where loading a known group with p and g returns a
# re-serialized form that has q as well (the Sophie Germain prime of
# that group). This makes a naive comparison of the parameter numbers
# objects fail, so we have to be a bit smarter
serialized_params = (
key.private_numbers().public_numbers.parameter_numbers
)
if serialized_params.q is None:
# This is the path OpenSSL < 3.0 takes
assert serialized_params == params
else:
assert serialized_params.p == params.p
assert serialized_params.g == params.g
# p = 2q + 1 since it is a Sophie Germain prime, so we can compute
# what we expect OpenSSL to have done here.
assert serialized_params.q == (params.p - 1) // 2
@pytest.mark.skip_fips(reason="modulus too small for FIPS")
@pytest.mark.parametrize("with_q", [False, True])
def test_convert_to_numbers(self, backend, with_q):
if with_q:
vector = load_vectors_from_file(
os.path.join("asymmetric", "DH", "RFC5114.txt"),
load_nist_vectors,
)[0]
p = int(vector["p"], 16)
g = int(vector["g"], 16)
q: typing.Optional[int] = int(vector["q"], 16)
else:
parameters = dh.generate_parameters(2, 512).generate_private_key()
private = parameters.private_numbers()
p = private.public_numbers.parameter_numbers.p
g = private.public_numbers.parameter_numbers.g
q = None
params = dh.DHParameterNumbers(p, g, q)
public = dh.DHPublicNumbers(1, params)
private = dh.DHPrivateNumbers(2, public)
deserialized_params = params.parameters(backend)
deserialized_public = public.public_key(backend)
deserialized_private = private.private_key(backend)
assert isinstance(deserialized_params, dh.DHParameters)
assert isinstance(deserialized_public, dh.DHPublicKey)
assert isinstance(deserialized_private, dh.DHPrivateKey)
@pytest.mark.skip_fips(reason="FIPS requires specific parameters")
def test_numbers_unsupported_parameters(self, backend):
# p is set to P_1536 + 1 because when calling private_key we want it to
# fail the DH_check call OpenSSL does, but we specifically want it to
# fail such that we don't get a DH_NOT_SUITABLE_GENERATOR. We can cause
# this by making sure p is not prime.
params = dh.DHParameterNumbers(P_1536 + 1, 2)
public = dh.DHPublicNumbers(1, params)
private = dh.DHPrivateNumbers(2, public)
with pytest.raises(ValueError):
private.private_key(backend)
@pytest.mark.skip_fips(reason="FIPS requires key size >= 2048")
@pytest.mark.parametrize("with_q", [False, True])
def test_generate_dh(self, backend, with_q):
if with_q:
vector = load_vectors_from_file(
os.path.join("asymmetric", "DH", "RFC5114.txt"),
load_nist_vectors,
)[0]
p = int(vector["p"], 16)
g = int(vector["g"], 16)
q = int(vector["q"], 16)
parameters = dh.DHParameterNumbers(p, g, q).parameters(backend)
key_size = 1024
else:
generator = 2
key_size = 512
parameters = dh.generate_parameters(generator, key_size, backend)
assert isinstance(parameters, dh.DHParameters)
key = parameters.generate_private_key()
assert isinstance(key, dh.DHPrivateKey)
assert key.key_size == key_size
public = key.public_key()
assert isinstance(public, dh.DHPublicKey)
assert public.key_size == key_size
assert isinstance(parameters, dh.DHParameters)
parameter_numbers = parameters.parameter_numbers()
assert isinstance(parameter_numbers, dh.DHParameterNumbers)
assert parameter_numbers.p.bit_length() == key_size
assert isinstance(public, dh.DHPublicKey)
assert isinstance(public.public_numbers(), dh.DHPublicNumbers)
assert isinstance(public.parameters(), dh.DHParameters)
assert isinstance(key, dh.DHPrivateKey)
assert isinstance(key.private_numbers(), dh.DHPrivateNumbers)
assert isinstance(key.parameters(), dh.DHParameters)
def test_exchange_wrong_type(self, backend):
parameters = FFDH3072_P.parameters(backend)
key1 = parameters.generate_private_key()
with pytest.raises(TypeError):
key1.exchange(b"invalidtype") # type: ignore[arg-type]
def test_exchange(self, backend):
parameters = FFDH3072_P.parameters(backend)
assert isinstance(parameters, dh.DHParameters)
key1 = parameters.generate_private_key()
key2 = parameters.generate_private_key()
symkey1 = key1.exchange(key2.public_key())
assert symkey1
assert len(symkey1) == 3072 // 8
symkey2 = key2.exchange(key1.public_key())
assert symkey1 == symkey2
def test_exchange_algorithm(self, backend):
parameters = FFDH3072_P.parameters(backend)
key1 = parameters.generate_private_key()
key2 = parameters.generate_private_key()
shared_key_bytes = key2.exchange(key1.public_key())
symkey = int.from_bytes(shared_key_bytes, "big")
symkey_manual = pow(
key1.public_key().public_numbers().y,
key2.private_numbers().x,
parameters.parameter_numbers().p,
)
assert symkey == symkey_manual
@pytest.mark.skip_fips(reason="key_size too small for FIPS")
def test_symmetric_key_padding(self, backend):
"""
This test has specific parameters that produce a symmetric key
In length 63 bytes instead 64. We make sure here that we add
padding to the key.
"""
p = int(
"11859949538425015739337467917303613431031019140213666"
"129025407300654026585086345323066284800963463204246390"
"256567934582260424238844463330887962689642467123"
)
g = 2
y = int(
"32155788395534640648739966373159697798396966919821525"
"72238852825117261342483718574508213761865276905503199"
"969908098203345481366464874759377454476688391248"
)
x = int(
"409364065449673443397833358558926598469347813468816037"
"268451847116982490733450463194921405069999008617231539"
"7147035896687401350877308899732826446337707128"
)
parameters = dh.DHParameterNumbers(p, g)
public = dh.DHPublicNumbers(y, parameters)
private = dh.DHPrivateNumbers(x, public)
key = private.private_key(backend)
symkey = key.exchange(public.public_key(backend))
assert len(symkey) == 512 // 8
assert symkey[:1] == b"\x00"
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
os.path.join("asymmetric", "DH", "bad_exchange.txt"),
load_nist_vectors,
),
)
def test_bad_exchange(self, backend, vector):
if (
backend._fips_enabled
and int(vector["p1"]) < backend._fips_dh_min_modulus
):
pytest.skip("modulus too small for FIPS mode")
parameters1 = dh.DHParameterNumbers(
int(vector["p1"]), int(vector["g"])
)
public1 = dh.DHPublicNumbers(int(vector["y1"]), parameters1)
private1 = dh.DHPrivateNumbers(int(vector["x1"]), public1)
key1 = private1.private_key(backend)
pub_key1 = key1.public_key()
parameters2 = dh.DHParameterNumbers(
int(vector["p2"]), int(vector["g"])
)
public2 = dh.DHPublicNumbers(int(vector["y2"]), parameters2)
private2 = dh.DHPrivateNumbers(int(vector["x2"]), public2)
key2 = private2.private_key(backend)
pub_key2 = key2.public_key()
with pytest.raises(ValueError):
key1.exchange(pub_key2)
with pytest.raises(ValueError):
key2.exchange(pub_key1)
def test_load_256bit_key_from_pkcs8(self, backend):
data = load_vectors_from_file(
os.path.join("asymmetric", "DH", "dh_key_256.pem"),
lambda pemfile: pemfile.read(),
mode="rb",
)
with pytest.raises(ValueError):
serialization.load_pem_private_key(data, None, backend)
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
os.path.join("asymmetric", "DH", "vec.txt"), load_nist_vectors
),
)
def test_dh_vectors(self, backend, vector):
if (
backend._fips_enabled
and int(vector["p"]) < backend._fips_dh_min_modulus
):
pytest.skip("modulus too small for FIPS mode")
if int(vector["p"]).bit_length() < 512:
pytest.skip("DH keys less than 512 bits are unsupported")
parameters = dh.DHParameterNumbers(int(vector["p"]), int(vector["g"]))
public = dh.DHPublicNumbers(int(vector["y"]), parameters)
private = dh.DHPrivateNumbers(int(vector["x"]), public)
key = private.private_key(backend)
symkey = key.exchange(public.public_key(backend))
assert int.from_bytes(symkey, "big") == int(vector["k"], 16)
@pytest.mark.skip_fips(reason="non-FIPS parameters")
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
os.path.join("asymmetric", "DH", "RFC5114.txt"), load_nist_vectors
),
)
def test_dh_vectors_with_q(self, backend, vector):
parameters = dh.DHParameterNumbers(
int(vector["p"], 16), int(vector["g"], 16), int(vector["q"], 16)
)
public1 = dh.DHPublicNumbers(int(vector["ystatcavs"], 16), parameters)
private1 = dh.DHPrivateNumbers(int(vector["xstatcavs"], 16), public1)
public2 = dh.DHPublicNumbers(int(vector["ystatiut"], 16), parameters)
private2 = dh.DHPrivateNumbers(int(vector["xstatiut"], 16), public2)
key1 = private1.private_key(backend)
key2 = private2.private_key(backend)
symkey1 = key1.exchange(public2.public_key(backend))
symkey2 = key2.exchange(public1.public_key(backend))
assert int.from_bytes(symkey1, "big") == int(vector["z"], 16)
assert int.from_bytes(symkey2, "big") == int(vector["z"], 16)
def test_exchange_old_key(self, backend):
k = load_vectors_from_file(
os.path.join("asymmetric", "DH", "dhpub_cryptography_old.pem"),
lambda f: serialization.load_pem_public_key(f.read()),
mode="rb",
)
assert isinstance(k, dh.DHPublicKey)
# Ensure this doesn't raise.
k.parameters().generate_private_key().exchange(k)
def test_public_key_equality(self, backend):
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "DH", "dhpub.pem"),
lambda pemfile: pemfile.read(),
mode="rb",
)
key_bytes_2 = load_vectors_from_file(
os.path.join("asymmetric", "DH", "dhpub_rfc5114_2.pem"),
lambda pemfile: pemfile.read(),
mode="rb",
)
key1 = serialization.load_pem_public_key(key_bytes)
key2 = serialization.load_pem_public_key(key_bytes)
key3 = serialization.load_pem_public_key(key_bytes_2)
assert key1 == key2
assert key1 != key3
assert key1 != object()
with pytest.raises(TypeError):
key1 < key2 # type: ignore[operator]
def test_public_key_copy(self):
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "DH", "dhpub.pem"),
lambda pemfile: pemfile.read(),
mode="rb",
)
key1 = serialization.load_pem_public_key(key_bytes)
key2 = copy.copy(key1)
assert key1 == key2
def test_public_key_deepcopy(self):
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "DH", "dhpub.pem"),
lambda pemfile: pemfile.read(),
mode="rb",
)
key_bytes_2 = load_vectors_from_file(
os.path.join("asymmetric", "DH", "dhpub_rfc5114_2.pem"),
lambda pemfile: pemfile.read(),
mode="rb",
)
key1 = serialization.load_pem_public_key(key_bytes)
key2 = copy.deepcopy(key1)
assert key1 == key2
key1 = serialization.load_pem_public_key(key_bytes_2)
assert key1 != key2
@pytest.mark.skip_fips(reason="non-FIPS parameters")
def test_private_key_copy(self, backend):
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "DH", "dhkey.pem"),
lambda pemfile: pemfile.read(),
mode="rb",
)
key1 = serialization.load_pem_private_key(key_bytes, None, backend)
key2 = copy.copy(key1)
assert key1 == key2
@pytest.mark.skip_fips(reason="non-FIPS parameters")
def test_private_key_deepcopy(self, backend):
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "DH", "dhkey.pem"),
lambda pemfile: pemfile.read(),
mode="rb",
)
key_bytes_2 = load_vectors_from_file(
os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.pem"),
lambda pemfile: pemfile.read(),
mode="rb",
)
key1 = serialization.load_pem_private_key(key_bytes, None, backend)
key2 = copy.deepcopy(key1)
assert key1 == key2
key1 = serialization.load_pem_private_key(key_bytes_2, None, backend)
assert key1 != key2
@pytest.mark.supported(
only_if=lambda backend: backend.dh_supported(),
skip_message="DH not supported",
)
| TestDH |
python | pyqtgraph__pyqtgraph | pyqtgraph/flowchart/Node.py | {
"start": 17627,
"end": 18675
} | class ____(QtWidgets.QGraphicsTextItem):
def __init__(self, text, parent, on_update):
super().__init__(text, parent)
self.on_update = on_update
def focusOutEvent(self, ev):
super().focusOutEvent(ev)
if self.on_update is not None:
self.on_update()
def keyPressEvent(self, ev):
if ev.key() == QtCore.Qt.Key.Key_Enter or ev.key() == QtCore.Qt.Key.Key_Return:
if self.on_update is not None:
self.on_update()
return
super().keyPressEvent(ev)
def mousePressEvent(self, ev):
if ev.button() == QtCore.Qt.MouseButton.LeftButton:
self.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.TextEditorInteraction)
self.setFocus(QtCore.Qt.FocusReason.MouseFocusReason) # focus text label
elif ev.button() == QtCore.Qt.MouseButton.RightButton:
self.setTextInteractionFlags(QtCore.Qt.TextInteractionFlag.NoTextInteraction)
#class NodeGraphicsItem(QtWidgets.QGraphicsItem):
| TextItem |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.