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 | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1242997,
"end": 1243651
} | class ____(sgqlc.types.Type, Node):
"""Represents a 'moved_columns_in_project' event on a given issue or
pull request.
"""
__schema__ = github_schema
__field_names__ = ("actor", "created_at", "database_id")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
"""Identifies the actor who performed the event."""
created_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="createdAt")
"""Identifies the date and time when the object was created."""
database_id = sgqlc.types.Field(Int, graphql_name="databaseId")
"""Identifies the primary key from the database."""
| MovedColumnsInProjectEvent |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/multi_sink_ports.py | {
"start": 582,
"end": 1102
} | class ____(QueryBase):
_params = None
def send(self):
return splitwrapper(self)
def params(self, data):
self._params = data
return self
def log_call(params, response):
sinkA(params)
sinkA(response)
def wrapper2(x: Query):
params = x._params
response = None
try:
response = x.send()
except Exception as ex:
raise ex
log_call(params, response)
def issue2():
taint = source()
query = Query().params(taint)
wrapper2(query)
| Query |
python | pytorch__pytorch | test/quantization/pt2e/test_numeric_debugger.py | {
"start": 1065,
"end": 14877
} | class ____(TestCase):
def _assert_each_node_has_debug_handle(self, model) -> None:
def _assert_node_has_debug_handle(node):
self.assertTrue(
CUSTOM_KEY in node.meta
and NUMERIC_DEBUG_HANDLE_KEY in node.meta[CUSTOM_KEY],
f"Node {node} doesn't have debug handle",
)
bfs_trace_with_node_process(model, _assert_node_has_debug_handle)
def _extract_debug_handles(self, model) -> dict[str, int]:
debug_handle_map: dict[str, int] = {}
def _extract_debug_handles_from_node(node):
nonlocal debug_handle_map
if (
CUSTOM_KEY in node.meta
and NUMERIC_DEBUG_HANDLE_KEY in node.meta[CUSTOM_KEY]
):
debug_handle_map[str(node)] = node.meta[CUSTOM_KEY][
NUMERIC_DEBUG_HANDLE_KEY
]
bfs_trace_with_node_process(model, _extract_debug_handles_from_node)
return debug_handle_map
def _extract_debug_handles_with_prev_decomp_op(self, model) -> dict[str, int]:
prev_decomp_op_to_debug_handle_map: dict[str, int] = {}
def _extract_debug_handles_with_prev_decomp_op_from_node(node):
nonlocal prev_decomp_op_to_debug_handle_map
if (
CUSTOM_KEY in node.meta
and NUMERIC_DEBUG_HANDLE_KEY in node.meta[CUSTOM_KEY]
):
prev_decomp_op = str(node.meta.get("nn_module_stack"))
debug_handle = node.meta[CUSTOM_KEY][NUMERIC_DEBUG_HANDLE_KEY]
if prev_decomp_op not in prev_decomp_op_to_debug_handle_map:
prev_decomp_op_to_debug_handle_map[prev_decomp_op] = debug_handle
else:
assert (
prev_decomp_op_to_debug_handle_map[prev_decomp_op]
== debug_handle
), f"Node {node} has different debug handle {debug_handle}"
f"than previous node sharing the same decomp op {prev_decomp_op}"
bfs_trace_with_node_process(
model, _extract_debug_handles_with_prev_decomp_op_from_node
)
return prev_decomp_op_to_debug_handle_map
def test_simple(self):
m = TestHelperModules.Conv2dThenConv1d()
example_inputs = m.example_inputs()
ep = export(m, example_inputs, strict=True)
generate_numeric_debug_handle(ep)
self._assert_each_node_has_debug_handle(ep)
debug_handle_map = self._extract_debug_handles(ep)
self.assertEqual(len(set(debug_handle_map.values())), len(debug_handle_map))
def test_control_flow(self):
m = TestHelperModules.ControlFlow()
example_inputs = m.example_inputs()
ep = export(m, example_inputs, strict=True)
generate_numeric_debug_handle(ep)
self._assert_each_node_has_debug_handle(ep)
debug_handle_map = self._extract_debug_handles(ep)
self.assertEqual(len(set(debug_handle_map.values())), len(debug_handle_map))
def test_quantize_pt2e_preserve_handle(self):
m = TestHelperModules.Conv2dThenConv1d()
example_inputs = m.example_inputs()
ep = export(m, example_inputs, strict=True)
generate_numeric_debug_handle(ep)
m = ep.module()
quantizer = XNNPACKQuantizer().set_global(
get_symmetric_quantization_config(is_per_channel=False)
)
m = prepare_pt2e(m, quantizer)
debug_handle_map = self._extract_debug_handles(m)
res_counter = Counter(debug_handle_map.values())
repeated_debug_handle_ids = [1, 2, 3]
# 3 ids were repeated because we copy over the id from node to its output observer
# torch.ops.aten.conv2d.default, torch.ops.aten.squeeze.dim and torch.ops.aten.conv1d.default
for dh_id in repeated_debug_handle_ids:
self.assertEqual(res_counter[dh_id], 2)
m(*example_inputs)
m = convert_pt2e(m)
self._assert_each_node_has_debug_handle(ep)
debug_handle_map = self._extract_debug_handles(m)
res_counter = Counter(debug_handle_map.values())
# same set of ids where repeated, because we copy over the id from observer/fake_quant to
# dequantize node
repeated_debug_handle_ids = [1, 2, 3]
for dh_id in repeated_debug_handle_ids:
self.assertEqual(res_counter[dh_id], 2)
def test_copy_preserve_handle(self):
m = TestHelperModules.Conv2dThenConv1d()
example_inputs = m.example_inputs()
ep = torch.export.export(m, example_inputs, strict=True)
generate_numeric_debug_handle(ep)
self._assert_each_node_has_debug_handle(ep)
debug_handle_map_ref = self._extract_debug_handles(ep)
ep_copy = copy.copy(ep)
debug_handle_map = self._extract_debug_handles(ep_copy)
self._assert_each_node_has_debug_handle(ep)
self.assertEqual(debug_handle_map, debug_handle_map_ref)
def test_deepcopy_preserve_handle(self):
m = TestHelperModules.Conv2dThenConv1d()
example_inputs = m.example_inputs()
ep = torch.export.export(m, example_inputs, strict=True)
generate_numeric_debug_handle(ep)
debug_handle_map_ref = self._extract_debug_handles(ep)
ep_copy = copy.deepcopy(ep)
debug_handle_map = self._extract_debug_handles(ep_copy)
self._assert_each_node_has_debug_handle(ep)
self.assertEqual(debug_handle_map, debug_handle_map_ref)
@skipIfCrossRef # mlazos: retracing FX graph with torch function mode doesn't propagate metadata, because the stack
# trace of the mode torch function impl doesn't match the traced graph stored lineno.
def test_re_export_preserve_handle(self):
m = TestHelperModules.Conv2dThenConv1d()
example_inputs = m.example_inputs()
ep = export(m, example_inputs, strict=True)
generate_numeric_debug_handle(ep)
m = ep.module()
self._assert_each_node_has_debug_handle(ep)
debug_handle_map_ref = self._extract_debug_handles(ep)
ep_reexport = export(m, example_inputs, strict=True)
self._assert_each_node_has_debug_handle(ep_reexport)
debug_handle_map = self._extract_debug_handles(ep_reexport)
self.assertEqual(debug_handle_map, debug_handle_map_ref)
def test_run_decompositions_same_handle_id(self):
m = TestHelperModules.Conv2dThenConv1d()
example_inputs = m.example_inputs()
ep = export(m, example_inputs, strict=True)
generate_numeric_debug_handle(ep)
self._assert_each_node_has_debug_handle(ep)
debug_handle_map_ref = self._extract_debug_handles(ep)
ep_copy = copy.copy(ep)
ep_copy = ep_copy.run_decompositions()
self._assert_each_node_has_debug_handle(ep_copy)
debug_handle_map = self._extract_debug_handles(ep_copy)
# checking the map still has the same ids, the node may change
self.assertEqual(
set(debug_handle_map.values()), set(debug_handle_map_ref.values())
)
def test_run_decompositions_map_handle_to_new_nodes(self):
test_models = [
TestHelperModules.TwoLinearModule(),
TestHelperModules.Conv2dThenConv1d(),
]
for m in test_models:
example_inputs = m.example_inputs()
ep = export(m, example_inputs, strict=True)
generate_numeric_debug_handle(ep)
self._assert_each_node_has_debug_handle(ep)
pre_decomp_to_debug_handle_map_ref = (
self._extract_debug_handles_with_prev_decomp_op(ep)
)
ep_copy = copy.copy(ep)
ep_copy = ep_copy.run_decompositions()
self._assert_each_node_has_debug_handle(ep_copy)
pre_decomp_to_debug_handle_map = (
self._extract_debug_handles_with_prev_decomp_op(ep_copy)
)
# checking the map still has the same ids, the node may change
self.assertEqual(
pre_decomp_to_debug_handle_map, pre_decomp_to_debug_handle_map_ref
)
def test_prepare_for_propagation_comparison(self):
m = TestHelperModules.Conv2dThenConv1d()
example_inputs = m.example_inputs()
ep = export(m, example_inputs, strict=True)
generate_numeric_debug_handle(ep)
m = ep.module()
m_logger = prepare_for_propagation_comparison(m)
ref = m(*example_inputs)
res = m_logger(*example_inputs)
from torch.ao.quantization.pt2e._numeric_debugger import OutputLogger
loggers = [m for m in m_logger.modules() if isinstance(m, OutputLogger)]
self.assertEqual(len(loggers), 3)
self.assertTrue("conv2d" in [logger.node_name for logger in loggers])
self.assertEqual(res, ref)
def test_extract_results_from_loggers(self):
m = TestHelperModules.Conv2dThenConv1d()
example_inputs = m.example_inputs()
ep = export(m, example_inputs, strict=True)
generate_numeric_debug_handle(ep)
m = ep.module()
m_ref_logger = prepare_for_propagation_comparison(m)
quantizer = XNNPACKQuantizer().set_global(
get_symmetric_quantization_config(is_per_channel=False)
)
m = prepare_pt2e(m, quantizer)
m(*example_inputs)
m = convert_pt2e(m)
m_quant_logger = prepare_for_propagation_comparison(m)
m_ref_logger(*example_inputs)
m_quant_logger(*example_inputs)
ref_results = extract_results_from_loggers(m_ref_logger)
quant_results = extract_results_from_loggers(m_quant_logger)
comparison_results = compare_results(ref_results, quant_results)
for node_summary in comparison_results.values():
if len(node_summary.results) > 0:
self.assertGreaterEqual(node_summary.results[0].sqnr, 35)
def test_extract_results_from_loggers_list_output(self):
m = TestHelperModules.Conv2dWithSplit()
example_inputs = m.example_inputs()
ep = export(m, example_inputs, strict=True)
generate_numeric_debug_handle(ep)
m = ep.module()
m_ref_logger = prepare_for_propagation_comparison(m)
quantizer = XNNPACKQuantizer().set_global(
get_symmetric_quantization_config(is_per_channel=False)
)
m = prepare_pt2e(m, quantizer)
m(*example_inputs)
m = convert_pt2e(m)
m_quant_logger = prepare_for_propagation_comparison(m)
m_ref_logger(*example_inputs)
m_quant_logger(*example_inputs)
ref_results = extract_results_from_loggers(m_ref_logger)
quant_results = extract_results_from_loggers(m_quant_logger)
comparison_results = compare_results(ref_results, quant_results)
for node_summary in comparison_results.values():
if len(node_summary.results) > 0:
sqnr = node_summary.results[0].sqnr
if isinstance(sqnr, list):
for sqnr_i in sqnr:
self.assertGreaterEqual(sqnr_i, 35)
else:
self.assertGreaterEqual(sqnr, 35)
def test_added_node_gets_unique_id(self) -> None:
m = TestHelperModules.Conv2dThenConv1d()
example_inputs = m.example_inputs()
ep = export(m, example_inputs, strict=True)
generate_numeric_debug_handle(ep)
ref_handles = self._extract_debug_handles(ep)
ref_counter = Counter(ref_handles.values())
for k, v in ref_counter.items():
self.assertEqual(
v,
1,
msg=f"For handle {k}, there were {v} nodes with that handle, but expected only 1",
)
# Now that we have unique ids, add a new node into the graph and re-generate
# to make sure that the new node gets a unique id.
last_node = next(iter(reversed(ep.graph.nodes)))
with ep.graph.inserting_before(last_node):
arg = last_node.args[0]
self.assertIsInstance(arg, (list, tuple))
arg = arg[0]
# Add a function that only requires a single tensor input.
n = ep.graph.call_function(torch.ops.aten.relu.default, args=(arg,))
arg.replace_all_uses_with(n, lambda x: x != n)
ep.graph_module.recompile()
# Regenerate handles, make sure only the new relu node has a new id, and
# it doesn't clash with any of the existing ids.
generate_numeric_debug_handle(ep)
self._assert_each_node_has_debug_handle(ep)
handles_after_modification = self._extract_debug_handles(ep)
handles_counter = Counter(handles_after_modification.values())
for name, handle in ref_handles.items():
self.assertIn(name, handles_after_modification)
# Check that handle was unchanged.
self.assertEqual(handles_after_modification[name], handle)
# Check that total count was unchanged.
ref_count = ref_counter[handle]
after_count = handles_counter[handle]
self.assertEqual(
after_count,
ref_count,
msg=f"For handle {handle}, there were {after_count} nodes with that handle, but expected only {ref_count}",
)
# Check for relu specifically. Avoid hardcoding the handle id since it
# may change with future node ordering changes.
self.assertNotEqual(handles_after_modification["relu_default"], 0)
self.assertEqual(handles_counter[handles_after_modification["relu_default"]], 1)
if __name__ == "__main__":
raise_on_run_directly("test/test_quantization.py")
| TestNumericDebugger |
python | Netflix__metaflow | metaflow/client/filecache.py | {
"start": 15475,
"end": 15978
} | class ____(BlobCache):
def __init__(self, filecache, cache_id):
self._filecache = filecache
self._cache_id = cache_id
def _path(self, key):
key_dir = key[:2]
return os.path.join(
self._filecache.cache_dir, self._cache_id, key_dir, "%s.blob" % key
)
def load_key(self, key):
return self._filecache.read_file(self._path(key))
def store_key(self, key, blob):
self._filecache.create_file(self._path(key), blob)
| FileBlobCache |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/streams/streams.py | {
"start": 12932,
"end": 13024
} | class ____(AdsInsights):
action_breakdowns = ["action_reaction"]
| AdsInsightsActionReaction |
python | tensorflow__tensorflow | tensorflow/python/framework/extension_type.py | {
"start": 40574,
"end": 43615
} | class ____(ExtensionType):
"""Fallback used to decode `tf.ExtensionType` when the original type is unavailable.
When a SavedModel is serialized, the signatures of any functions in the
SavedModel can include `tf.ExtensionType` subclasses. These subclasses are
usually
registered, so they can be restored when the SavedModel is loaded. However,
if a SavedModel is loaded without first registering the ExtensionType types in
its
signature, then the SavedModel will fall back to using the
`AnonymousExtensionType`
type instead.
If necessary, `AnonymousExtensionType` objects can be converted to a concrete
`tf.ExtensionType` subclass (and vice versa) using `reinterpret`.
"""
# Let the metaclass know that it should *not* transform this class (since
# this class is part of the ExtensionType framework, and not a user class).
_tf_extension_type_do_not_transform_this_class = True
def __init__(self, **fields):
for name in fields:
if extension_type_field.ExtensionTypeField.is_reserved_name(name) or (
name.startswith('__') and name.endswith('__')
):
raise ValueError(
f'Reserved field name {name} was encountered '
'when trying to instantiate an AnonymousExtensionType.'
)
fields = [(k, _convert_anonymous_fields(v)) for (k, v) in fields.items()]
self.__dict__.update(fields)
self._tf_extension_type_convert_fields()
super().__init__()
@classmethod
def _tf_extension_type_fields(cls):
return [
extension_type_field.ExtensionTypeField(name, None)
for name in cls.__dict__
if not extension_type_field.ExtensionTypeField.is_reserved_name(name)
]
def __setattr__(self, name, value):
raise AttributeError(
f'Cannot set attribute `{name}`. '
'AnonymousExtensionType instances are immutable.'
)
def __delattr__(self, name):
raise AttributeError(
f'Cannot delete attribute `{name}`. '
'AnonymousExtensionType instances are immutable.'
)
def _tf_extension_type_convert_fields(self):
fields = [
(k, _convert_anonymous_fields(v))
for (k, v) in self.__dict__.items()
if not extension_type_field.ExtensionTypeField.is_reserved_name(k)
]
self.__dict__.update(fields)
def __repr__(self):
fields = [
f'{k}={v!r}'
for (k, v) in self.__dict__.items()
if not extension_type_field.ExtensionTypeField.is_reserved_name(k)
]
return f'AnonymousExtensionType({", ".join(fields)})'
_tf_extension_type_cached_type_spec = None
@property
def _type_spec(self): # CompositeTensor API.
# Note: the TypeSpec contains all static (non-tensor) data from `self`.
if self._tf_extension_type_cached_type_spec is None:
spec = AnonymousExtensionTypeSpec.from_value(self)
self.__dict__['_tf_extension_type_cached_type_spec'] = spec
return self._tf_extension_type_cached_type_spec
@type_spec_registry.register('tf.AnonymousExtensionType.Spec')
| AnonymousExtensionType |
python | docker__docker-py | docker/transport/unixconn.py | {
"start": 222,
"end": 716
} | class ____(urllib3.connection.HTTPConnection):
def __init__(self, base_url, unix_socket, timeout=60):
super().__init__(
'localhost', timeout=timeout
)
self.base_url = base_url
self.unix_socket = unix_socket
self.timeout = timeout
def connect(self):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.settimeout(self.timeout)
sock.connect(self.unix_socket)
self.sock = sock
| UnixHTTPConnection |
python | tiangolo__fastapi | docs_src/dataclasses/tutorial001.py | {
"start": 101,
"end": 312
} | class ____:
name: str
price: float
description: Union[str, None] = None
tax: Union[float, None] = None
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
return item
| Item |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_annotations/mypy_init_return.py | {
"start": 633,
"end": 686
} | class ____:
def __init__(self, *arg):
...
| Foo |
python | facebook__pyre-check | client/json_rpc.py | {
"start": 6678,
"end": 7929
} | class ____(JSONRPC):
id: Union[int, str, None]
@staticmethod
def from_json(response_json: JSON) -> "Response":
"""
Parse a given JSON into a JSON-RPC response.
Raises `InvalidRequestError` if the JSON body is malformed.
"""
if "result" in response_json:
return SuccessResponse.from_json(response_json)
elif "error" in response_json:
return ErrorResponse.from_json(response_json)
else:
raise InvalidRequestError(
"Either `result` or `error` must be presented in JSON-RPC "
+ f"responses. Got {response_json}."
)
@staticmethod
def from_string(response_string: str) -> "Response":
"""
Parse a given string into a JSON-RPC response.
Raises `ParseError` if the parsing fails. Raises `InvalidRequestError`
if the JSON body is malformed.
"""
try:
response_json = json.loads(response_string)
return Response.from_json(response_json)
except JSONDecodeError as error:
message = f"Cannot parse string into JSON: {error}"
raise ParseError(message) from error
@dataclasses.dataclass(frozen=True)
| Response |
python | doocs__leetcode | solution/2700-2799/2772.Apply Operations to Make All Array Elements Equal to Zero/Solution.py | {
"start": 0,
"end": 392
} | class ____:
def checkArray(self, nums: List[int], k: int) -> bool:
n = len(nums)
d = [0] * (n + 1)
s = 0
for i, x in enumerate(nums):
s += d[i]
x += s
if x == 0:
continue
if x < 0 or i + k > n:
return False
s -= x
d[i + k] += x
return True
| Solution |
python | apache__airflow | airflow-core/tests/unit/core/test_stats.py | {
"start": 1479,
"end": 1690
} | class ____:
"""
This custom Statsd class is invalid because it does not subclass
statsd.StatsClient.
"""
def __init__(self, host=None, port=None, prefix=None):
pass
| InvalidCustomStatsd |
python | django__django | django/utils/functional.py | {
"start": 7671,
"end": 12281
} | class ____:
"""
A wrapper for another class that can be used to delay instantiation of the
wrapped class.
By subclassing, you have the opportunity to intercept and alter the
instantiation. If you don't need to do that, use SimpleLazyObject.
"""
# Avoid infinite recursion when tracing __init__ (#19456).
_wrapped = None
def __init__(self):
# Note: if a subclass overrides __init__(), it will likely need to
# override __copy__() and __deepcopy__() as well.
self._wrapped = empty
def __getattribute__(self, name):
if name == "_wrapped":
# Avoid recursion when getting wrapped object.
return super().__getattribute__(name)
value = super().__getattribute__(name)
# If attribute is a proxy method, raise an AttributeError to call
# __getattr__() and use the wrapped object method.
if not getattr(value, "_mask_wrapped", True):
raise AttributeError
return value
__getattr__ = new_method_proxy(getattr)
def __setattr__(self, name, value):
if name == "_wrapped":
# Assign to __dict__ to avoid infinite __setattr__ loops.
self.__dict__["_wrapped"] = value
else:
if self._wrapped is empty:
self._setup()
setattr(self._wrapped, name, value)
def __delattr__(self, name):
if name == "_wrapped":
raise TypeError("can't delete _wrapped.")
if self._wrapped is empty:
self._setup()
delattr(self._wrapped, name)
def _setup(self):
"""
Must be implemented by subclasses to initialize the wrapped object.
"""
raise NotImplementedError(
"subclasses of LazyObject must provide a _setup() method"
)
# Because we have messed with __class__ below, we confuse pickle as to what
# class we are pickling. We're going to have to initialize the wrapped
# object to successfully pickle it, so we might as well just pickle the
# wrapped object since they're supposed to act the same way.
#
# Unfortunately, if we try to simply act like the wrapped object, the ruse
# will break down when pickle gets our id(). Thus we end up with pickle
# thinking, in effect, that we are a distinct object from the wrapped
# object, but with the same __dict__. This can cause problems (see #25389).
#
# So instead, we define our own __reduce__ method and custom unpickler. We
# pickle the wrapped object as the unpickler's argument, so that pickle
# will pickle it normally, and then the unpickler simply returns its
# argument.
def __reduce__(self):
if self._wrapped is empty:
self._setup()
return (unpickle_lazyobject, (self._wrapped,))
def __copy__(self):
if self._wrapped is empty:
# If uninitialized, copy the wrapper. Use type(self), not
# self.__class__, because the latter is proxied.
return type(self)()
else:
# If initialized, return a copy of the wrapped object.
return copy.copy(self._wrapped)
def __deepcopy__(self, memo):
if self._wrapped is empty:
# We have to use type(self), not self.__class__, because the
# latter is proxied.
result = type(self)()
memo[id(self)] = result
return result
return copy.deepcopy(self._wrapped, memo)
__bytes__ = new_method_proxy(bytes)
__str__ = new_method_proxy(str)
__bool__ = new_method_proxy(bool)
# Introspection support
__dir__ = new_method_proxy(dir)
# Need to pretend to be the wrapped class, for the sake of objects that
# care about this (especially in equality tests)
__class__ = property(new_method_proxy(operator.attrgetter("__class__")))
__eq__ = new_method_proxy(operator.eq)
__lt__ = new_method_proxy(operator.lt)
__gt__ = new_method_proxy(operator.gt)
__ne__ = new_method_proxy(operator.ne)
__hash__ = new_method_proxy(hash)
# List/Tuple/Dictionary methods support
__getitem__ = new_method_proxy(operator.getitem)
__setitem__ = new_method_proxy(operator.setitem)
__delitem__ = new_method_proxy(operator.delitem)
__iter__ = new_method_proxy(iter)
__len__ = new_method_proxy(len)
__contains__ = new_method_proxy(operator.contains)
def unpickle_lazyobject(wrapped):
"""
Used to unpickle lazy objects. Just return its argument, which will be the
wrapped object.
"""
return wrapped
| LazyObject |
python | kennethreitz__tablib | src/tablib/packages/dbfpy/fields.py | {
"start": 9182,
"end": 9621
} | class ____(DbfFieldDef):
"""Definition of the currency field."""
typeCode = "Y"
length = 8
defaultValue = 0.0
def decodeValue(self, value):
"""Return float number decoded from ``value``."""
return struct.unpack("<q", value)[0] / 10000.
def encodeValue(self, value):
"""Return string containing encoded ``value``."""
return struct.pack("<q", round(value * 10000))
| DbfCurrencyFieldDef |
python | etianen__django-reversion | tests/test_app/tests/test_admin.py | {
"start": 2322,
"end": 4606
} | class ____(LoginMixin, AdminMixin, TestBase):
def setUp(self):
super().setUp()
with reversion.create_revision():
self.obj = TestModelParent.objects.create()
with reversion.create_revision():
self.obj.name = "v2"
self.obj.parent_name = "parent v2"
self.obj.save()
def testRevisionView(self):
response = self.client.get(resolve_url(
"admin:test_app_testmodelparent_revision",
self.obj.pk,
Version.objects.get_for_object(self.obj)[1].pk,
))
self.assertContains(response, 'value="v1"')
self.assertContains(response, 'value="parent v1"')
# Test that the changes were rolled back.
self.obj.refresh_from_db()
self.assertEqual(self.obj.name, "v2")
self.assertEqual(self.obj.parent_name, "parent v2")
self.assertIn("revert", response.context)
self.assertTrue(response.context["revert"])
def testRevisionViewOldRevision(self):
response = self.client.get(resolve_url(
"admin:test_app_testmodelparent_revision",
self.obj.pk,
Version.objects.get_for_object(self.obj)[0].pk,
))
self.assertContains(response, 'value="v2"')
self.assertContains(response, 'value="parent v2"')
def testRevisionViewRevertError(self):
Version.objects.get_for_object(self.obj).update(format="boom")
response = self.client.get(resolve_url(
"admin:test_app_testmodelparent_revision",
self.obj.pk,
Version.objects.get_for_object(self.obj)[1].pk,
))
self.assertEqual(
response["Location"].replace("http://testserver", ""),
resolve_url("admin:test_app_testmodelparent_changelist"),
)
def testRevisionViewRevert(self):
self.client.post(resolve_url(
"admin:test_app_testmodelparent_revision",
self.obj.pk,
Version.objects.get_for_object(self.obj)[1].pk,
), {
"name": "v1",
"parent_name": "parent v1",
})
self.obj.refresh_from_db()
self.assertEqual(self.obj.name, "v1")
self.assertEqual(self.obj.parent_name, "parent v1")
| AdminRevisionViewTest |
python | bokeh__bokeh | src/bokeh/protocol/messages/pull_doc_reply.py | {
"start": 1635,
"end": 3167
} | class ____(Message[PullDoc]):
''' Define the ``PULL-DOC-REPLY`` message for replying to Document pull
requests from clients
The ``content`` fragment of for this message is has the form:
.. code-block:: python
{
'doc' : <Document JSON>
}
'''
msgtype = 'PULL-DOC-REPLY'
@classmethod
def create(cls, request_id: ID, document: Document, **metadata: Any) -> pull_doc_reply:
''' Create an ``PULL-DOC-REPLY`` message
Args:
request_id (str) :
The message ID for the message that issues the pull request
document (Document) :
The Document to reply with
Any additional keyword arguments will be put into the message
``metadata`` fragment as-is.
'''
header = cls.create_header(request_id=request_id)
content = PullDoc(doc=document.to_json())
msg = cls(header, metadata, content)
return msg
def push_to_document(self, doc: Document) -> None:
if 'doc' not in self.content:
raise ProtocolError("No doc in PULL-DOC-REPLY")
doc.replace_with_json(self.content['doc'])
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
| pull_doc_reply |
python | django__django | django/contrib/postgres/functions.py | {
"start": 154,
"end": 252
} | class ____(Func):
template = "CURRENT_TIMESTAMP"
output_field = DateTimeField()
| TransactionNow |
python | huggingface__transformers | src/transformers/models/deepseek_vl_hybrid/modeling_deepseek_vl_hybrid.py | {
"start": 7243,
"end": 8187
} | class ____(nn.Module):
def __init__(self, config, output_size: int = 24):
super().__init__()
self.config = config
self.output_size = output_size
self.conv1 = nn.Conv2d(
config.output_channels, config.output_channels * 2, kernel_size=3, stride=2, padding=1, bias=False
)
self.conv2 = nn.Conv2d(
config.output_channels * 2, config.output_channels * 4, kernel_size=3, stride=2, padding=1, bias=False
)
def forward(self, features: torch.Tensor) -> torch.Tensor:
# interpolate Sam encodings to match Siglip encodings
features = torch.nn.functional.interpolate(
features,
size=(4 * self.output_size, 4 * self.output_size),
mode="bilinear",
align_corners=False,
)
features = self.conv1(features)
features = self.conv2(features)
return features
| DeepseekVLSamVisionProj |
python | doocs__leetcode | solution/2200-2299/2242.Maximum Score of a Node Sequence/Solution.py | {
"start": 0,
"end": 572
} | class ____:
def maximumScore(self, scores: List[int], edges: List[List[int]]) -> int:
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
for k in g.keys():
g[k] = nlargest(3, g[k], key=lambda x: scores[x])
ans = -1
for a, b in edges:
for c in g[a]:
for d in g[b]:
if b != c != d != a:
t = scores[a] + scores[b] + scores[c] + scores[d]
ans = max(ans, t)
return ans
| Solution |
python | pytorch__pytorch | test/distributed/test_dist2.py | {
"start": 8654,
"end": 9428
} | class ____(Dist2MultiProcessTestCase):
@property
def device(self) -> torch.device:
return torch.device("cuda", self.rank)
@requires_nccl()
@skip_if_lt_x_gpu(2)
def new_group(self) -> torch.distributed.ProcessGroup:
os.environ["RANK"] = str(self.rank)
os.environ["WORLD_SIZE"] = str(self.world_size)
os.environ["MASTER_ADDR"] = "127.0.0.1"
os.environ["MASTER_PORT"] = "29501"
return dist2.new_group(
backend="nccl",
timeout=timedelta(seconds=60),
device=self.device,
)
if __name__ == "__main__":
assert not torch.cuda._initialized, (
"test_distributed must not have initialized CUDA context on main process"
)
run_tests()
| ProcessGroupNCCLTest |
python | allegroai__clearml | clearml/backend_api/services/v2_23/projects.py | {
"start": 79019,
"end": 79895
} | class ____(Request):
"""
:param project: Project id
:type project: str
"""
_service = "projects"
_action = "get_by_id"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {"project": {"description": "Project id", "type": "string"}},
"required": ["project"],
"type": "object",
}
def __init__(self, project: str, **kwargs: Any) -> None:
super(GetByIdRequest, self).__init__(**kwargs)
self.project = project
@schema_property("project")
def project(self) -> str:
return self._property_project
@project.setter
def project(self, value: str) -> None:
if value is None:
self._property_project = None
return
self.assert_isinstance(value, "project", six.string_types)
self._property_project = value
| GetByIdRequest |
python | PyCQA__pydocstyle | src/tests/test_cases/sections.py | {
"start": 6703,
"end": 10152
} | class ____: # noqa: D203
"""Test class."""
def test_method(self, test, another_test, _): # noqa: D213, D407
"""Test a valid args section.
Args:
test: A parameter.
another_test: Another parameter.
"""
def test_detailed_description(self, test, another_test, _): # noqa: D213, D407
"""Test a valid args section.
Args:
test: A parameter.
another_test: Another parameter.
Detailed description.
"""
@expect("D417: Missing argument descriptions in the docstring "
"(argument(s) test, y, z are missing descriptions in "
"'test_missing_args' docstring)", arg_count=5)
def test_missing_args(self, test, x, y, z=3, _private_arg=3): # noqa: D213, D407
"""Test a valid args section.
Args:
x: Another parameter.
"""
@classmethod
@expect("D417: Missing argument descriptions in the docstring "
"(argument(s) test, y, z are missing descriptions in "
"'test_missing_args_class_method' docstring)", arg_count=5)
def test_missing_args_class_method(cls, test, x, y, _, z=3): # noqa: D213, D407
"""Test a valid args section.
Args:
x: Another parameter. The parameter below is missing description.
y:
"""
@staticmethod
@expect("D417: Missing argument descriptions in the docstring "
"(argument(s) a, y, z are missing descriptions in "
"'test_missing_args_static_method' docstring)", arg_count=4)
def test_missing_args_static_method(a, x, y, _test, z=3): # noqa: D213, D407
"""Test a valid args section.
Args:
x: Another parameter.
"""
@staticmethod
@expect("D417: Missing argument descriptions in the docstring "
"(argument(s) a, b are missing descriptions in "
"'test_missing_docstring' docstring)", arg_count=2)
def test_missing_docstring(a, b): # noqa: D213, D407
"""Test a valid args section.
Args:
a:
"""
@staticmethod
def test_hanging_indent(skip, verbose): # noqa: D213, D407
"""Do stuff.
Args:
skip (:attr:`.Skip`):
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Etiam at tellus a tellus faucibus maximus. Curabitur tellus
mauris, semper id vehicula ac, feugiat ut tortor.
verbose (bool):
If True, print out as much infromation as possible.
If False, print out concise "one-liner" information.
"""
@expect(_D213)
@expect("D417: Missing argument descriptions in the docstring "
"(argument(s) y are missing descriptions in "
"'test_missing_numpy_args' docstring)")
def test_missing_numpy_args(_private_arg=0, x=1, y=2): # noqa: D406, D407
"""Toggle the gizmo.
Parameters
----------
x : int
The greatest integer in the history \
of the entire world.
"""
@expect(_D213)
@expect("D417: Missing argument descriptions in the docstring "
"(argument(s) y are missing descriptions in "
"'test_missing_sphynx_args' docstring)")
def test_missing_sphynx_args(_private_arg=0, x=1, y=2): # noqa: D406, D407
"""Toggle the gizmo.
:param x: The greatest integer in the history \
of the entire world.
"""
| TestGoogle |
python | doocs__leetcode | solution/3000-3099/3029.Minimum Time to Revert Word to Initial State I/Solution2.py | {
"start": 480,
"end": 797
} | class ____:
def minimumTimeToInitialState(self, word: str, k: int) -> int:
hashing = Hashing(word, 13331, 998244353)
n = len(word)
for i in range(k, n, k):
if hashing.query(1, n - i) == hashing.query(i + 1, n):
return i // k
return (n + k - 1) // k
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-my-hours/components.py | {
"start": 554,
"end": 3325
} | class ____(NoAuth):
config: Config
email: Union[InterpolatedString, str]
password: Union[InterpolatedString, str]
_access_token = None
_refreshToken = None
def __post_init__(self, parameters: Mapping[str, Any]):
self._email = InterpolatedString.create(self.email, parameters=parameters).eval(self.config)
self._password = InterpolatedString.create(self.password, parameters=parameters).eval(self.config)
def __call__(self, request: requests.PreparedRequest) -> requests.PreparedRequest:
"""Attach the page access token to params to authenticate on the HTTP request"""
if self._access_token is None or self._refreshToken is None:
self._access_token, self._refreshToken = self.generate_access_token()
headers = {self.auth_header: f"Bearer {self._access_token}", "Accept": "application/json", "api-version": "1.0"}
request.headers.update(headers)
return request
@property
def auth_header(self) -> str:
return "Authorization"
@property
def token(self) -> str:
return self._access_token
def _get_refresh_access_token_response(self):
url = f"https://api2.myhours.com/api/tokens/refresh"
headers = {"Content-Type": "application/json", "api-version": "1.0", self.auth_header: f"Bearer {self._access_token}"}
data = {
"refreshToken": self._refreshToken,
"grantType": "refresh_token",
}
try:
response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
modified_response = {
"access_token": response.json().get("accessToken"),
"refresh_token": response.json().get("refreshToken"),
"expires_in": response.json().get("expiresIn"),
}
return modified_response
except Exception as e:
raise Exception(f"Error while refreshing access token: {e}") from e
def generate_access_token(self) -> tuple[str, str]:
try:
headers = {"Content-Type": "application/json", "api-version": "1.0"}
data = {
"email": self._email,
"password": self._password,
"grantType": "password",
"clientId": "api",
}
url = "https://api2.myhours.com/api/tokens/login"
rest = requests.post(url, headers=headers, json=data)
if rest.status_code != HTTPStatus.OK:
raise HTTPError(rest.text)
return (rest.json().get("accessToken"), rest.json().get("refreshToken"))
except Exception as e:
raise Exception(f"Error while generating access token: {e}") from e
| CustomAuthenticator |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/solids.py | {
"start": 14083,
"end": 14588
} | class ____(graphene.Interface):
name = graphene.NonNull(graphene.String)
description = graphene.String()
metadata = non_null_list(GrapheneMetadataItemDefinition)
input_definitions = non_null_list(GrapheneInputDefinition)
output_definitions = non_null_list(GrapheneOutputDefinition)
assetNodes = non_null_list("dagster_graphql.schema.asset_graph.GrapheneAssetNode")
pools = non_null_list(graphene.String)
class Meta:
name = "ISolidDefinition"
| GrapheneISolidDefinition |
python | bokeh__bokeh | src/bokeh/util/tornado.py | {
"start": 2262,
"end": 4419
} | class ____:
''' Like ioloop.PeriodicCallback except the 'func' can be async and return
a Future.
Will wait for func to finish each time before we call it again. (Plain
ioloop.PeriodicCallback can "pile up" invocations if they are taking too
long.)
'''
_loop: IOLoop
_period: int
_started: bool
_stopped: bool
def __init__(self, func: Callback, period: int, io_loop: IOLoop) -> None:
# specify type here until this is released: https://github.com/python/mypy/pull/10548
self._func: Callback = func
self._loop = io_loop
self._period = period
self._started = False
self._stopped = False
# this is like gen.sleep but uses our IOLoop instead of the current IOLoop
def sleep(self) -> gen.Future[None]:
f: gen.Future[None] = gen.Future()
self._loop.call_later(self._period / 1000.0, lambda: f.set_result(None))
return f
def start(self) -> None:
if self._started:
raise RuntimeError("called start() twice on _AsyncPeriodic")
self._started = True
def invoke() -> InvokeResult:
# important to start the sleep before starting callback so any initial
# time spent in callback "counts against" the period.
sleep_future = self.sleep()
result = self._func()
if result is None:
return sleep_future
callback_future = gen.convert_yielded(result)
return gen.multi([sleep_future, callback_future])
def on_done(future: gen.Future[None]) -> None:
if not self._stopped:
# mypy can't infer type of invoker for some reason
self._loop.add_future(invoke(), on_done) # type: ignore
ex = future.exception()
if ex is not None:
log.error("Error thrown from periodic callback:")
lines = format_exception(ex.__class__, ex, ex.__traceback__)
log.error("".join(lines))
self._loop.add_future(self.sleep(), on_done)
def stop(self) -> None:
self._stopped = True
| _AsyncPeriodic |
python | getsentry__sentry | src/sentry/utils/arroyo.py | {
"start": 6999,
"end": 7896
} | class ____(ProcessingStrategy[TStrategyPayload]):
"""
A strategy for setting and re-setting the join timeout for individual
sub-sections of the processing chain. This way one can granularly disable
join() for steps that are idempotent anyway, making rebalancing faster and simpler.
"""
def __init__(
self, timeout: float | None, next_step: ProcessingStrategy[TStrategyPayload]
) -> None:
self.timeout = timeout
self.next_step = next_step
def submit(self, message: Message[TStrategyPayload]) -> None:
self.next_step.submit(message)
def poll(self) -> None:
self.next_step.poll()
def join(self, timeout: float | None = None) -> None:
self.next_step.join(self.timeout)
def close(self) -> None:
self.next_step.close()
def terminate(self) -> None:
self.next_step.terminate()
| SetJoinTimeout |
python | google__jax | tests/pallas/tpu_pallas_test.py | {
"start": 92128,
"end": 92767
} | class ____(PallasBaseTest):
def test_mlir_location(self):
# Make sure that MLIR locations are correctly propagated to primitives.
args = (jax.ShapeDtypeStruct((8, 128), jnp.float32),)
f = example_kernel.double
as_tpu_kernel = mosaic.as_tpu_kernel
def capture_as_tpu_kernel(module, *args, **kwargs):
asm = module.operation.get_asm(enable_debug_info=True)
self.assertIn('example_kernel.py":25', asm)
return as_tpu_kernel(module, *args, **kwargs)
mosaic.as_tpu_kernel = capture_as_tpu_kernel
try:
jax.jit(f).lower(*args)
finally:
mosaic.as_tpu_kernel = as_tpu_kernel
| PallasUXTest |
python | pytorch__pytorch | torch/testing/_comparison.py | {
"start": 15922,
"end": 16719
} | class ____(Pair):
"""Pair for any type of inputs that will be compared with the `==` operator.
.. note::
Since this will instantiate for any kind of inputs, it should only be used as fallback after all other pairs
couldn't handle the inputs.
"""
def compare(self) -> None:
try:
equal = self.actual == self.expected
except Exception as error:
# We are not using `self._raise_error_meta` here since we need the exception chaining
raise ErrorMeta(
ValueError,
f"{self.actual} == {self.expected} failed with:\n{error}.",
id=self.id,
) from error
if not equal:
self._fail(AssertionError, f"{self.actual} != {self.expected}")
| ObjectPair |
python | pytorch__pytorch | test/inductor/test_ordered_set.py | {
"start": 31289,
"end": 31852
} | class ____(TestBasicOps, TestCase):
def setUp(self):
super().setUp()
self.case = "unit OrderedSet (tuple)"
self.values = [(0, "zero")]
self.OrderedSet = OrderedSet(self.values)
self.dup = OrderedSet(self.values)
self.length = 1
self.repr = "{(0, 'zero')}"
def test_in(self):
self.assertIn((0, "zero"), self.OrderedSet)
def test_not_in(self):
self.assertNotIn(9, self.OrderedSet)
# ------------------------------------------------------------------------------
| TestBasicOpsTuple |
python | pallets__jinja | src/jinja2/bccache.py | {
"start": 11058,
"end": 13986
} | class ____(BytecodeCache):
"""This class implements a bytecode cache that uses a memcache cache for
storing the information. It does not enforce a specific memcache library
(tummy's memcache or cmemcache) but will accept any class that provides
the minimal interface required.
Libraries compatible with this class:
- `cachelib <https://github.com/pallets/cachelib>`_
- `python-memcached <https://pypi.org/project/python-memcached/>`_
(Unfortunately the django cache interface is not compatible because it
does not support storing binary data, only text. You can however pass
the underlying cache client to the bytecode cache which is available
as `django.core.cache.cache._client`.)
The minimal interface for the client passed to the constructor is this:
.. class:: MinimalClientInterface
.. method:: set(key, value[, timeout])
Stores the bytecode in the cache. `value` is a string and
`timeout` the timeout of the key. If timeout is not provided
a default timeout or no timeout should be assumed, if it's
provided it's an integer with the number of seconds the cache
item should exist.
.. method:: get(key)
Returns the value for the cache key. If the item does not
exist in the cache the return value must be `None`.
The other arguments to the constructor are the prefix for all keys that
is added before the actual cache key and the timeout for the bytecode in
the cache system. We recommend a high (or no) timeout.
This bytecode cache does not support clearing of used items in the cache.
The clear method is a no-operation function.
.. versionadded:: 2.7
Added support for ignoring memcache errors through the
`ignore_memcache_errors` parameter.
"""
def __init__(
self,
client: "_MemcachedClient",
prefix: str = "jinja2/bytecode/",
timeout: int | None = None,
ignore_memcache_errors: bool = True,
):
self.client = client
self.prefix = prefix
self.timeout = timeout
self.ignore_memcache_errors = ignore_memcache_errors
def load_bytecode(self, bucket: Bucket) -> None:
try:
code = self.client.get(self.prefix + bucket.key)
except Exception:
if not self.ignore_memcache_errors:
raise
else:
bucket.bytecode_from_string(code)
def dump_bytecode(self, bucket: Bucket) -> None:
key = self.prefix + bucket.key
value = bucket.bytecode_to_string()
try:
if self.timeout is not None:
self.client.set(key, value, self.timeout)
else:
self.client.set(key, value)
except Exception:
if not self.ignore_memcache_errors:
raise
| MemcachedBytecodeCache |
python | walkccc__LeetCode | solutions/2772. Apply Operations to Make All Array Elements Equal to Zero/2772.py | {
"start": 0,
"end": 498
} | class ____:
def checkArray(self, nums: list[int], k: int) -> bool:
if k == 1:
return True
needDecrease = 0
# Store nums[i - k + 1..i] with decreasing nums[i - k + 1].
dq = collections.deque()
for i, num in enumerate(nums):
if i >= k:
needDecrease -= dq.popleft()
if nums[i] < needDecrease:
return False
decreasedNum = nums[i] - needDecrease
dq.append(decreasedNum)
needDecrease += decreasedNum
return dq[-1] == 0
| Solution |
python | numba__numba | numba/core/typing/npydecl.py | {
"start": 24548,
"end": 25027
} | class ____(AbstractTemplate):
def generic(self, args, kws):
assert not kws
if len(args) != 1:
return
arrays, = args
if isinstance(arrays, types.BaseTuple):
if not arrays:
return
arrays = list(arrays)
else:
arrays = [arrays]
nditerty = types.NumpyNdIterType(arrays)
return signature(nditerty, *args)
@infer_global(pndindex)
@infer_global(np.ndindex)
| NdIter |
python | getsentry__sentry | src/flagpole/conditions.py | {
"start": 1311,
"end": 4359
} | class ____:
property: str
"""The evaluation context property to match against."""
value: Any
"""The value to compare against the condition's evaluation context property."""
operator: str = dataclasses.field(default="")
"""
The name of the operator to use when comparing the evaluation context property to the condition's value.
Values must be a valid ConditionOperatorKind.
"""
def match(self, context: EvaluationContext, segment_name: str) -> bool:
return self._operator_match(
condition_property=context.get(self.property), segment_name=segment_name
)
@abstractmethod
def _operator_match(self, condition_property: Any, segment_name: str) -> bool:
raise NotImplementedError("Each Condition needs to implement this method")
def _evaluate_in(self, condition_property: Any, segment_name: str) -> bool:
if not isinstance(self.value, list):
raise ConditionTypeMismatchException(
f"'In' condition value must be a list, but was provided a '{get_type_name(self.value)}'"
+ f" of segment {segment_name}"
)
if isinstance(condition_property, (list, dict)):
raise ConditionTypeMismatchException(
"'In' condition property value must be str | int | float | bool | None, but was provided a"
+ f"'{get_type_name(self.value)}' of segment {segment_name}"
)
if isinstance(condition_property, str):
condition_property = condition_property.lower()
return condition_property in create_case_insensitive_set_from_list(self.value)
def _evaluate_contains(self, condition_property: Any, segment_name: str) -> bool:
if not isinstance(condition_property, list):
raise ConditionTypeMismatchException(
f"'Contains' can only be checked against a list, but was given a {get_type_name(condition_property)}"
+ f" context property '{condition_property}' of segment '{segment_name}'"
)
value = self.value
if isinstance(value, str):
value = value.lower()
return value in create_case_insensitive_set_from_list(condition_property)
def _evaluate_equals(self, condition_property: Any, segment_name: str) -> bool:
if condition_property is None:
return False
if not isinstance(condition_property, type(self.value)):
value_type = get_type_name(self.value)
property_value = get_type_name(condition_property)
raise ConditionTypeMismatchException(
"'Equals' operator cannot be applied to values of mismatching types"
+ f"({value_type} and {property_value}) for segment {segment_name}"
)
if isinstance(condition_property, str):
return condition_property.lower() == self.value.lower()
return condition_property == self.value
InOperatorValueTypes = list[int] | list[float] | list[str]
| ConditionBase |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_query.py | {
"start": 60115,
"end": 65741
} | class ____(fixtures.TablesTest):
"""round trip tests related to using JSON and JSONB in UPDATE statements
with PG-specific features
"""
__only_on__ = "postgresql"
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"t",
metadata,
Column("id", Integer, primary_key=True),
Column("uuid", Uuid),
Column("j", JSON),
Column("jb", JSONB),
)
@classmethod
def insert_data(cls, connection):
connection.execute(
cls.tables["t"].insert(),
[
{"id": 1, "uuid": "d24587a1-06d9-41df-b1c3-3f423b97a755"},
{"id": 2, "uuid": "4b07e1c8-d60c-4ea8-9d01-d7cd01362224"},
],
)
def test_update_values(self, connection):
t = self.tables["t"]
value = values(
Column("id", Integer),
Column("uuid", Uuid),
Column("j", JSON),
Column("jb", JSONB),
name="update_data",
).data(
[
(
1,
"8b6ec1ec-b979-4d0b-b2ce-9acc6e4c2943",
{"foo": 1},
{"foo_jb": 1},
),
(
2,
"a2123bcb-7ea3-420a-8284-1db4b2759d79",
{"bar": 2},
{"bar_jb": 2},
),
]
)
connection.execute(
t.update()
.values(uuid=value.c.uuid, j=value.c.j, jb=value.c.jb)
.where(t.c.id == value.c.id)
)
updated_data = connection.execute(t.select().order_by(t.c.id))
eq_(
[(str(row.uuid), row.j, row.jb) for row in updated_data],
[
(
"8b6ec1ec-b979-4d0b-b2ce-9acc6e4c2943",
{"foo": 1},
{"foo_jb": 1},
),
(
"a2123bcb-7ea3-420a-8284-1db4b2759d79",
{"bar": 2},
{"bar_jb": 2},
),
],
)
@testing.only_on("postgresql>=14")
def test_jsonb_element_update_basic(self, connection):
"""Test updating individual JSONB elements with subscript syntax
test #10927
"""
t = self.tables["t"]
# Insert test data with complex JSONB
connection.execute(
t.insert(),
[
{
"id": 10,
"jb": {
"user": {"name": "Alice", "age": 30},
"active": True,
},
},
{
"id": 11,
"jb": {
"user": {"name": "Bob", "age": 25},
"active": False,
},
},
],
)
# Update specific elements using JSONB subscript syntax
# This tests the new JSONB subscripting feature from issue #10927
connection.execute(
t.update()
.values({t.c.jb["user"]["name"]: "Alice Updated"})
.where(t.c.id == 10)
)
connection.execute(
t.update().values({t.c.jb["active"]: True}).where(t.c.id == 11)
)
results = connection.execute(
t.select().where(t.c.id.in_([10, 11])).order_by(t.c.id)
)
eq_(
[row.jb for row in results],
[
{"user": {"name": "Alice Updated", "age": 30}, "active": True},
{"user": {"name": "Bob", "age": 25}, "active": True},
],
)
@testing.only_on("postgresql>=14")
def test_jsonb_element_update_multiple_keys(self, connection):
"""Test updating multiple JSONB elements in a single statement
test #10927
"""
t = self.tables["t"]
connection.execute(
t.insert(),
{
"id": 20,
"jb": {
"config": {"theme": "dark", "lang": "en"},
"version": 1,
},
},
)
# Update multiple elements at once
connection.execute(
t.update()
.values({t.c.jb["config"]["theme"]: "light", t.c.jb["version"]: 2})
.where(t.c.id == 20)
)
# Verify the updates
row = connection.execute(t.select().where(t.c.id == 20)).one()
eq_(
row.jb,
{"config": {"theme": "light", "lang": "en"}, "version": 2},
)
@testing.only_on("postgresql>=14")
def test_jsonb_element_update_array_element(self, connection):
"""Test updating JSONB array elements
test #10927
"""
t = self.tables["t"]
# Insert test data with arrays
connection.execute(
t.insert(),
{
"id": 30,
"jb": {
"tags": ["python", "sql", "postgres"],
"priority": "high",
},
},
)
# Update array element
connection.execute(
t.update()
.values({t.c.jb["tags"][1]: "postgresql"})
.where(t.c.id == 30)
)
# Verify the update
row = connection.execute(t.select().where(t.c.id == 30)).fetchone()
eq_(
row.jb,
{"tags": ["python", "postgresql", "postgres"], "priority": "high"},
)
| JSONUpdateTest |
python | getsentry__sentry | src/sentry/models/grouphistory.py | {
"start": 5773,
"end": 6509
} | class ____(BaseManager["GroupHistory"]):
def filter_to_team(self, team: Team) -> QuerySet[GroupHistory]:
from sentry.models.groupassignee import GroupAssignee
from sentry.models.project import Project
project_list = Project.objects.get_for_team_ids(team_ids=[team.id])
user_ids = list(team.member_set.values_list("user_id", flat=True))
assigned_groups = (
GroupAssignee.objects.filter(team=team)
.union(GroupAssignee.objects.filter(user_id__in=user_ids))
.values_list("group_id", flat=True)
)
return self.filter(
project__in=project_list,
group_id__in=assigned_groups,
)
@region_silo_model
| GroupHistoryManager |
python | Textualize__textual | tests/input/test_input_clear.py | {
"start": 79,
"end": 456
} | class ____(App):
def compose(self) -> ComposeResult:
yield Input("Hello, World!")
async def test_input_clear():
async with InputApp().run_test() as pilot:
input_widget = pilot.app.query_one(Input)
assert input_widget.value == "Hello, World!"
input_widget.clear()
await pilot.pause()
assert input_widget.value == ""
| InputApp |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-faiss/llama_index/readers/faiss/base.py | {
"start": 176,
"end": 2515
} | class ____(BaseReader):
"""
Faiss reader.
Retrieves documents through an existing in-memory Faiss index.
These documents can then be used in a downstream LlamaIndex data structure.
If you wish use Faiss itself as an index to to organize documents,
insert documents, and perform queries on them, please use VectorStoreIndex
with FaissVectorStore.
Args:
faiss_index (faiss.Index): A Faiss Index object (required)
"""
def __init__(self, index: Any):
"""Initialize with parameters."""
import_err_msg = """
`faiss` package not found. For instructions on
how to install `faiss` please visit
https://github.com/facebookresearch/faiss/wiki/Installing-Faiss
"""
try:
import faiss # noqa
except ImportError:
raise ImportError(import_err_msg)
self._index = index
def load_data(
self,
query: np.ndarray,
id_to_text_map: Dict[str, str],
k: int = 4,
separate_documents: bool = True,
) -> List[Document]:
"""
Load data from Faiss.
Args:
query (np.ndarray): A 2D numpy array of query vectors.
id_to_text_map (Dict[str, str]): A map from ID's to text.
k (int): Number of nearest neighbors to retrieve. Defaults to 4.
separate_documents (Optional[bool]): Whether to return separate
documents. Defaults to True.
Returns:
List[Document]: A list of documents.
"""
dists, indices = self._index.search(query, k)
documents = []
for qidx in range(indices.shape[0]):
for didx in range(indices.shape[1]):
doc_id = indices[qidx, didx]
if doc_id not in id_to_text_map:
raise ValueError(
f"Document ID {doc_id} not found in id_to_text_map."
)
text = id_to_text_map[doc_id]
documents.append(Document(text=text))
if not separate_documents:
# join all documents into one
text_list = [doc.get_content() for doc in documents]
text = "\n\n".join(text_list)
documents = [Document(text=text)]
return documents
| FaissReader |
python | django__django | django/contrib/gis/db/backends/mysql/features.py | {
"start": 219,
"end": 876
} | class ____(BaseSpatialFeatures, MySQLDatabaseFeatures):
empty_intersection_returns_none = False
has_spatialrefsys_table = False
supports_add_srs_entry = False
supports_distance_geodetic = False
supports_length_geodetic = False
supports_area_geodetic = False
supports_transform = False
supports_null_geometries = False
supports_num_points_poly = False
unsupported_geojson_options = {"crs"}
@cached_property
def supports_geometry_field_unique_index(self):
# Not supported in MySQL since
# https://dev.mysql.com/worklog/task/?id=11808
return self.connection.mysql_is_mariadb
| DatabaseFeatures |
python | scipy__scipy | benchmarks/benchmarks/stats_sampling.py | {
"start": 1158,
"end": 1886
} | class ____:
def __init__(self, shift=0.):
self.shift = shift
self.mode = shift
def pdf(self, x):
x -= self.shift
y = 1. / (abs(x) + 1.)
return y * y
def dpdf(self, x):
x -= self.shift
y = 1. / (abs(x) + 1.)
y = 2. * y * y * y
return y if (x < 0.) else -y
def cdf(self, x):
x -= self.shift
if x <= 0.:
return 0.5 / (1. - x)
return 1. - 0.5 / (1. + x)
def __repr__(self):
return f'sqrtlinshft({self.shift})'
# Sin 2 distribution
# / 0.05 + 0.45*(1 +sin(2 Pi x)) if |x| <= 1
# f(x) = <
# \ 0 otherwise
# Taken from UNU.RAN test suite (from file t_pinv.c)
| contdist3 |
python | GoogleCloudPlatform__python-docs-samples | pubsub/streaming-analytics/PubSubToGCS.py | {
"start": 2068,
"end": 2477
} | class ____(DoFn):
def process(self, element, publish_time=DoFn.TimestampParam):
"""Processes each windowed element by extracting the message body and its
publish time into a tuple.
"""
yield (
element.decode("utf-8"),
datetime.utcfromtimestamp(float(publish_time)).strftime(
"%Y-%m-%d %H:%M:%S.%f"
),
)
| AddTimestamp |
python | encode__django-rest-framework | rest_framework/generics.py | {
"start": 9428,
"end": 10163
} | class ____(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
GenericAPIView):
"""
Concrete view for retrieving, updating or deleting a model instance.
"""
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def patch(self, request, *args, **kwargs):
return self.partial_update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
| RetrieveUpdateDestroyAPIView |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 288508,
"end": 292116
} | class ____(rv_continuous):
r"""A loguniform or reciprocal continuous random variable.
%(before_notes)s
Notes
-----
The probability density function for this class is:
.. math::
f(x, a, b) = \frac{1}{x \log(b/a)}
for :math:`a \le x \le b`, :math:`b > a > 0`. This class takes
:math:`a` and :math:`b` as shape parameters.
%(after_notes)s
%(example)s
This doesn't show the equal probability of ``0.01``, ``0.1`` and
``1``. This is best when the x-axis is log-scaled:
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots(1, 1)
>>> ax.hist(np.log10(r))
>>> ax.set_ylabel("Frequency")
>>> ax.set_xlabel("Value of random variable")
>>> ax.xaxis.set_major_locator(plt.FixedLocator([-2, -1, 0]))
>>> ticks = ["$10^{{ {} }}$".format(i) for i in [-2, -1, 0]]
>>> ax.set_xticklabels(ticks) # doctest: +SKIP
>>> plt.show()
This random variable will be log-uniform regardless of the base chosen for
``a`` and ``b``. Let's specify with base ``2`` instead:
>>> rvs = %(name)s(2**-2, 2**0).rvs(size=1000)
Values of ``1/4``, ``1/2`` and ``1`` are equally likely with this random
variable. Here's the histogram:
>>> fig, ax = plt.subplots(1, 1)
>>> ax.hist(np.log2(rvs))
>>> ax.set_ylabel("Frequency")
>>> ax.set_xlabel("Value of random variable")
>>> ax.xaxis.set_major_locator(plt.FixedLocator([-2, -1, 0]))
>>> ticks = ["$2^{{ {} }}$".format(i) for i in [-2, -1, 0]]
>>> ax.set_xticklabels(ticks) # doctest: +SKIP
>>> plt.show()
"""
def _argcheck(self, a, b):
return (a > 0) & (b > a)
def _shape_info(self):
ia = _ShapeInfo("a", False, (0, np.inf), (False, False))
ib = _ShapeInfo("b", False, (0, np.inf), (False, False))
return [ia, ib]
def _fitstart(self, data):
if isinstance(data, CensoredData):
data = data._uncensor()
# Reasonable, since support is [a, b]
return super()._fitstart(data, args=(np.min(data), np.max(data)))
def _get_support(self, a, b):
return a, b
def _pdf(self, x, a, b):
# reciprocal.pdf(x, a, b) = 1 / (x*(log(b) - log(a)))
return np.exp(self._logpdf(x, a, b))
def _logpdf(self, x, a, b):
return -np.log(x) - np.log(np.log(b) - np.log(a))
def _cdf(self, x, a, b):
return (np.log(x)-np.log(a)) / (np.log(b) - np.log(a))
def _ppf(self, q, a, b):
return np.exp(np.log(a) + q*(np.log(b) - np.log(a)))
def _munp(self, n, a, b):
if n == 0:
return 1.0
t1 = 1 / (np.log(b) - np.log(a)) / n
t2 = np.real(np.exp(_log_diff(n * np.log(b), n*np.log(a))))
return t1 * t2
def _entropy(self, a, b):
return 0.5*(np.log(a) + np.log(b)) + np.log(np.log(b) - np.log(a))
fit_note = """\
`loguniform`/`reciprocal` is over-parameterized. `fit` automatically
fixes `scale` to 1 unless `fscale` is provided by the user.\n\n"""
@extend_notes_in_docstring(rv_continuous, notes=fit_note)
def fit(self, data, *args, **kwds):
fscale = kwds.pop('fscale', 1)
return super().fit(data, *args, fscale=fscale, **kwds)
# Details related to the decision of not defining
# the survival function for this distribution can be
# found in the PR: https://github.com/scipy/scipy/pull/18614
loguniform = reciprocal_gen(name="loguniform")
reciprocal = reciprocal_gen(name="reciprocal")
loguniform._support = ('a', 'b')
reciprocal._support = ('a', 'b')
| reciprocal_gen |
python | kamyu104__LeetCode-Solutions | Python/longest-square-streak-in-an-array.py | {
"start": 46,
"end": 648
} | class ____(object):
def longestSquareStreak(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sorted_nums = sorted(set(nums))
squares = {x for x in sorted_nums if x%2 < 2} # squared_num % 4 in [0, 1]
result = 0
for x in sorted_nums:
square, cnt = x**2, 1
while square in squares:
squares.remove(square)
cnt += 1
square *= square
result = max(result, cnt)
return result if result != 1 else -1
# Time: O(nlogn)
# Space: O(n)
# dp
| Solution |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_qt.py | {
"start": 44466,
"end": 44788
} | class ____(backend_tools.ConfigureSubplotsBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._subplot_dialog = None
def trigger(self, *args):
NavigationToolbar2QT.configure_subplots(self)
@backend_tools._register_tool_class(FigureCanvasQT)
| ConfigureSubplotsQt |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 531979,
"end": 532475
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of ConvertProjectCardNoteToIssue"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "project_card")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
project_card = sgqlc.types.Field("ProjectCard", graphql_name="projectCard")
"""The updated ProjectCard."""
| ConvertProjectCardNoteToIssuePayload |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_version_querysets.py | {
"start": 8146,
"end": 11868
} | class ____(TestVersionQuerySetWithManagerBase):
"""
Queries using External Manager should only include External Versions.
It will only include pull/merge request Version in the queries.
"""
def test_all(self):
query = Version.external.all()
versions = {
self.external_version_public,
self.external_version_private,
self.another_external_version_public,
self.another_external_version_private,
self.shared_external_version_public,
self.shared_external_version_private,
}
self.assertEqual(query.count(), len(versions))
self.assertEqual(set(query), versions)
def test_public_with_private_external_versions(self):
self.project.external_builds_privacy_level = PRIVATE
self.project.save()
self.another_project.external_builds_privacy_level = PRIVATE
self.another_project.save()
self.shared_project.external_builds_privacy_level = PRIVATE
self.shared_project.save()
query = Version.external.public()
versions = set()
self.assertEqual(query.count(), len(versions))
self.assertEqual(set(query), versions)
def test_public_with_some_private_external_versions(self):
self.another_project.external_builds_privacy_level = PRIVATE
self.another_project.save()
self.shared_project.external_builds_privacy_level = PRIVATE
self.shared_project.save()
query = Version.external.public()
versions = {
self.external_version_public,
self.external_version_private,
}
self.assertEqual(query.count(), len(versions))
self.assertEqual(set(query), versions)
def test_public_with_public_external_versions(self):
query = Version.external.public()
versions = {
self.external_version_public,
self.external_version_private,
self.shared_external_version_public,
self.shared_external_version_private,
self.another_external_version_public,
self.another_external_version_private,
}
self.assertEqual(query.count(), len(versions))
self.assertEqual(set(query), versions)
def test_public_user(self):
self.project.external_builds_privacy_level = PRIVATE
self.project.save()
self.another_project.external_builds_privacy_level = PRIVATE
self.another_project.save()
query = Version.external.public(user=self.user)
versions = {
self.external_version_public,
self.external_version_private,
self.shared_external_version_public,
self.shared_external_version_private,
}
self.assertEqual(query.count(), len(versions))
self.assertEqual(set(query), versions)
def test_public_project(self):
query = self.project.versions(manager=EXTERNAL).public(user=self.user)
versions = {
self.external_version_public,
self.external_version_private,
}
self.assertEqual(query.count(), len(versions))
self.assertEqual(set(query), versions)
def test_api(self):
self.project.external_builds_privacy_level = PRIVATE
self.project.save()
self.another_project.external_builds_privacy_level = PRIVATE
self.another_project.save()
query = Version.external.api()
versions = {
self.shared_external_version_public,
self.shared_external_version_private,
}
self.assertEqual(query.count(), len(versions))
self.assertEqual(set(query), versions)
| VersionQuerySetWithExternalManagerTest |
python | vyperlang__vyper | vyper/ast/nodes.py | {
"start": 44325,
"end": 45329
} | class ____(Stmt):
"""
An `implements` declaration.
Attributes
----------
children : List of (Name | Attribute)s
Name nodes for the interfaces to be implemented
"""
__slots__ = ("children",)
_only_empty_fields = ("value",)
def __init__(self, *args, **kwargs):
tmp = kwargs.pop("annotation")
if isinstance(tmp, python_ast.Tuple):
kwargs["children"] = tmp.elts
else:
kwargs["children"] = [tmp]
super().__init__(*args, **kwargs)
def validate(self):
for child in self.children:
if not isinstance(child, (Name, Attribute)):
raise StructureException("invalid implements", child)
def as_tuple(node: VyperNode):
"""
Convenience function for some AST nodes which allow either a Tuple
or single elements. Returns a python tuple of AST nodes.
"""
if isinstance(node, Tuple):
return node.elements
else:
return (node,)
| ImplementsDecl |
python | mlflow__mlflow | mlflow/entities/trace_data.py | {
"start": 244,
"end": 3531
} | class ____:
"""A container object that holds the spans data of a trace.
Args:
spans: List of spans that are part of the trace.
"""
spans: list[Span] = field(default_factory=list)
# NB: Custom constructor to allow passing additional kwargs for backward compatibility for
# DBX agent evaluator. Once they migrates to trace V3 schema, we can remove this.
def __init__(self, spans: list[Span] | None = None, **kwargs):
self.spans = spans or []
@classmethod
def from_dict(cls, d):
if not isinstance(d, dict):
raise TypeError(f"TraceData.from_dict() expects a dictionary. Got: {type(d).__name__}")
return cls(spans=[Span.from_dict(span) for span in d.get("spans", [])])
def to_dict(self) -> dict[str, Any]:
return {"spans": [span.to_dict() for span in self.spans]}
# TODO: remove this property in 3.7.0
@property
@deprecated(since="3.6.0", alternative="trace.search_spans(name=...)")
def intermediate_outputs(self) -> dict[str, Any] | None:
"""
.. deprecated:: 3.6.0
Use `trace.search_spans(name=...)` to search for spans and get the outputs.
Returns intermediate outputs produced by the model or agent while handling the request.
There are mainly two flows to return intermediate outputs:
1. When a trace is generate by the `mlflow.log_trace` API,
return `intermediate_outputs` attribute of the span.
2. When a trace is created normally with a tree of spans,
aggregate the outputs of non-root spans.
"""
root_span = self._get_root_span()
if root_span and root_span.get_attribute(SpanAttributeKey.INTERMEDIATE_OUTPUTS):
return root_span.get_attribute(SpanAttributeKey.INTERMEDIATE_OUTPUTS)
if len(self.spans) > 1:
result = {}
# spans may have duplicate names, so deduplicate the names by appending an index number.
span_name_counter = Counter(span.name for span in self.spans)
span_name_counter = {name: 1 for name, count in span_name_counter.items() if count > 1}
for span in self.spans:
span_name = span.name
if count := span_name_counter.get(span_name):
span_name_counter[span_name] += 1
span_name = f"{span_name}_{count}"
if span.parent_id and span.outputs is not None:
result[span_name] = span.outputs
return result
def _get_root_span(self) -> Span | None:
for span in self.spans:
if span.parent_id is None:
return span
# `request` and `response` are preserved for backward compatibility with v2
@property
def request(self) -> str | None:
if span := self._get_root_span():
# Accessing the OTel span directly get serialized value directly.
return span._span.attributes.get(SpanAttributeKey.INPUTS)
return None
@property
def response(self) -> str | None:
if span := self._get_root_span():
# Accessing the OTel span directly get serialized value directly.
return span._span.attributes.get(SpanAttributeKey.OUTPUTS)
return None
| TraceData |
python | PyCQA__pylint | doc/data/messages/s/subclassed-final-class/good.py | {
"start": 34,
"end": 288
} | class ____:
"""General Platypus data."""
average_length = 46
average_body_temperature = 32
def print_average_length_platypus():
output = f"The average length of a platypus is: {PlatypusData.average_length}cm"
print(output)
| PlatypusData |
python | huggingface__transformers | src/transformers/models/gemma3/modular_gemma3.py | {
"start": 32957,
"end": 37117
} | class ____(nn.Module):
def __init__(self, config: Gemma3Config):
super().__init__()
self.mm_input_projection_weight = nn.Parameter(
torch.zeros(config.vision_config.hidden_size, config.text_config.hidden_size)
)
self.mm_soft_emb_norm = Gemma3RMSNorm(
config.vision_config.hidden_size, eps=config.vision_config.layer_norm_eps
)
self.patches_per_image = int(config.vision_config.image_size // config.vision_config.patch_size)
self.tokens_per_side = int(config.mm_tokens_per_image**0.5)
self.kernel_size = self.patches_per_image // self.tokens_per_side
self.avg_pool = nn.AvgPool2d(kernel_size=self.kernel_size, stride=self.kernel_size)
def forward(self, vision_outputs: torch.Tensor):
batch_size, _, seq_length = vision_outputs.shape
reshaped_vision_outputs = vision_outputs.transpose(1, 2)
reshaped_vision_outputs = reshaped_vision_outputs.reshape(
batch_size, seq_length, self.patches_per_image, self.patches_per_image
)
reshaped_vision_outputs = reshaped_vision_outputs.contiguous()
pooled_vision_outputs = self.avg_pool(reshaped_vision_outputs)
pooled_vision_outputs = pooled_vision_outputs.flatten(2)
pooled_vision_outputs = pooled_vision_outputs.transpose(1, 2)
normed_vision_outputs = self.mm_soft_emb_norm(pooled_vision_outputs)
projected_vision_outputs = torch.matmul(normed_vision_outputs, self.mm_input_projection_weight)
return projected_vision_outputs.type_as(vision_outputs)
def create_causal_mask_mapping(
config: PreTrainedConfig,
input_embeds: torch.Tensor,
attention_mask: Optional[torch.Tensor],
cache_position: torch.Tensor,
past_key_values: Optional[Cache],
position_ids: Optional[torch.Tensor],
token_type_ids: Optional[torch.Tensor] = None,
pixel_values: Optional[torch.FloatTensor] = None,
is_training: bool = False,
**kwargs,
) -> dict:
"""
Overwrites the base `create_masks_for_generate` with `token_type_ids` masking to create the causal mask mapping
for all kinds of forward passes. Gemma3 uses a bidirectional mask for images.
Uses `pixel_values` as an optional input to disambiguate edge cases.
"""
if is_training and token_type_ids is None:
raise ValueError("`token_type_ids` is required as a model input when training")
mask_kwargs = {
"config": config.get_text_config(),
"input_embeds": input_embeds,
"attention_mask": attention_mask,
"cache_position": cache_position,
"past_key_values": past_key_values,
"position_ids": position_ids,
}
# NOTE: this `may_have_image_input` logic is not flawless, it fails when we're using a cache eagerly initialized
# (e.g. compiled prefill) AND `pixel_values` are not provided (i.e. the image data is provided through other
# means). Determining prefill in that case requires checking data values, which is not compile-compatible.
may_have_image_input = past_key_values is None or not past_key_values.is_initialized or pixel_values is not None
if token_type_ids is not None and may_have_image_input:
# We need to pass an additional mask function to account for token type ids, and it needs to be an `or` (to
# undo the causal masking)
# First find where a new image block starts: 1 if image and previous not image
# The images cannot attend to future images, but can attend to all prev images and to itself bidirectionally
is_image = (token_type_ids == 1).to(cache_position.device)
is_previous_image = nn.functional.pad(is_image, (1, 0), value=0)[:, :-1]
new_image_start = is_image & ~is_previous_image
image_group_ids = torch.cumsum(new_image_start.int(), dim=1) - 1
image_group_ids = torch.where(is_image, image_group_ids, -1)
mask_kwargs["or_mask_function"] = token_type_ids_mask_function(
token_type_ids.to(cache_position.device), image_group_ids
)
return create_masks_for_generate(**mask_kwargs)
| Gemma3MultiModalProjector |
python | tensorflow__tensorflow | tensorflow/compiler/tests/proximal_adagrad_test.py | {
"start": 1102,
"end": 6738
} | class ____(xla_test.XLATestCase):
def testResourceProximalAdagradwithoutRegularization(self):
with self.session(), self.test_scope():
var0 = resource_variable_ops.ResourceVariable([0.0, 0.0])
var1 = resource_variable_ops.ResourceVariable([0.0, 0.0])
grads0 = constant_op.constant([0.1, 0.2])
grads1 = constant_op.constant([0.01, 0.02])
opt = proximal_adagrad.ProximalAdagradOptimizer(
3.0,
initial_accumulator_value=0.1,
l1_regularization_strength=0.0,
l2_regularization_strength=0.0)
update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
self.evaluate(variables.global_variables_initializer())
self.assertAllClose([0.0, 0.0], self.evaluate(var0))
self.assertAllClose([0.0, 0.0], self.evaluate(var1))
# Run 3 steps Proximal Adagrad.
for _ in range(3):
update.run()
self.assertAllClose(
np.array([-2.60260963, -4.29698515]), self.evaluate(var0))
self.assertAllClose(
np.array([-0.28432083, -0.56694895]), self.evaluate(var1))
opt_vars = opt.variables()
self.assertStartsWith(opt_vars[0].name, var0._shared_name)
self.assertStartsWith(opt_vars[1].name, var1._shared_name)
self.assertEqual(2, len(opt_vars))
def testProximalAdagradwithoutRegularization2(self):
with self.session(), self.test_scope():
var0 = resource_variable_ops.ResourceVariable([1.0, 2.0])
var1 = resource_variable_ops.ResourceVariable([4.0, 3.0])
grads0 = constant_op.constant([0.1, 0.2])
grads1 = constant_op.constant([0.01, 0.02])
opt = proximal_adagrad.ProximalAdagradOptimizer(
3.0,
initial_accumulator_value=0.1,
l1_regularization_strength=0.0,
l2_regularization_strength=0.0)
update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
self.evaluate(variables.global_variables_initializer())
self.assertAllClose([1.0, 2.0], self.evaluate(var0))
self.assertAllClose([4.0, 3.0], self.evaluate(var1))
# Run 3 steps Proximal Adagrad.
for _ in range(3):
update.run()
self.assertAllClose(np.array([-1.60261, -2.296985]), self.evaluate(var0))
self.assertAllClose(np.array([3.715679, 2.433051]), self.evaluate(var1))
def testProximalAdagradWithL1(self):
with self.session(), self.test_scope():
var0 = resource_variable_ops.ResourceVariable([1.0, 2.0])
var1 = resource_variable_ops.ResourceVariable([4.0, 3.0])
grads0 = constant_op.constant([0.1, 0.2])
grads1 = constant_op.constant([0.01, 0.02])
opt = proximal_adagrad.ProximalAdagradOptimizer(
3.0,
initial_accumulator_value=0.1,
l1_regularization_strength=0.001,
l2_regularization_strength=0.0)
update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
self.evaluate(variables.global_variables_initializer())
self.assertAllClose([1.0, 2.0], self.evaluate(var0))
self.assertAllClose([4.0, 3.0], self.evaluate(var1))
# Run 10 steps Proximal Adagrad
for _ in range(10):
update.run()
self.assertAllClose(np.array([-6.663634, -9.190331]), self.evaluate(var0))
self.assertAllClose(np.array([2.959304, 1.029232]), self.evaluate(var1))
def testProximalAdagradWithL1_L2(self):
with self.session(), self.test_scope():
var0 = resource_variable_ops.ResourceVariable([1.0, 2.0])
var1 = resource_variable_ops.ResourceVariable([4.0, 3.0])
grads0 = constant_op.constant([0.1, 0.2])
grads1 = constant_op.constant([0.01, 0.02])
opt = proximal_adagrad.ProximalAdagradOptimizer(
3.0,
initial_accumulator_value=0.1,
l1_regularization_strength=0.001,
l2_regularization_strength=2.0)
update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
self.evaluate(variables.global_variables_initializer())
self.assertAllClose([1.0, 2.0], self.evaluate(var0))
self.assertAllClose([4.0, 3.0], self.evaluate(var1))
# Run 10 steps Proximal Adagrad.
for _ in range(10):
update.run()
self.assertAllClose(np.array([-0.0495, -0.0995]), self.evaluate(var0))
self.assertAllClose(np.array([-0.0045, -0.0095]), self.evaluate(var1))
def applyOptimizer(self, opt, steps=5):
var0 = resource_variable_ops.ResourceVariable([1.0, 2.0])
var1 = resource_variable_ops.ResourceVariable([3.0, 4.0])
grads0 = constant_op.constant([0.1, 0.2])
grads1 = constant_op.constant([0.01, 0.02])
update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
self.evaluate(variables.global_variables_initializer())
self.assertAllClose([1.0, 2.0], self.evaluate(var0))
self.assertAllClose([3.0, 4.0], self.evaluate(var1))
# Run ProximalAdagrad for a few steps
for _ in range(steps):
update.run()
return self.evaluate(var0), self.evaluate(var1)
def testEquivAdagradwithoutRegularization(self):
with self.session(), self.test_scope():
val0, val1 = self.applyOptimizer(
proximal_adagrad.ProximalAdagradOptimizer(
3.0,
initial_accumulator_value=0.1,
l1_regularization_strength=0.0,
l2_regularization_strength=0.0))
with self.session(), self.test_scope():
val2, val3 = self.applyOptimizer(
adagrad.AdagradOptimizer(
3.0, initial_accumulator_value=0.1))
self.assertAllClose(val0, val2)
self.assertAllClose(val1, val3)
if __name__ == "__main__":
test.main()
| ProximalAdagradOptimizerTest |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/contrib/completers/system.py | {
"start": 311,
"end": 2057
} | class ____(GrammarCompleter):
"""
Completer for system commands.
"""
def __init__(self) -> None:
# Compile grammar.
g = compile(
r"""
# First we have an executable.
(?P<executable>[^\s]+)
# Ignore literals in between.
(
\s+
("[^"]*" | '[^']*' | [^'"]+ )
)*
\s+
# Filename as parameters.
(
(?P<filename>[^\s]+) |
"(?P<double_quoted_filename>[^\s]+)" |
'(?P<single_quoted_filename>[^\s]+)'
)
""",
escape_funcs={
"double_quoted_filename": (lambda string: string.replace('"', '\\"')),
"single_quoted_filename": (lambda string: string.replace("'", "\\'")),
},
unescape_funcs={
"double_quoted_filename": (
lambda string: string.replace('\\"', '"')
), # XXX: not entirely correct.
"single_quoted_filename": (lambda string: string.replace("\\'", "'")),
},
)
# Create GrammarCompleter
super().__init__(
g,
{
"executable": ExecutableCompleter(),
"filename": PathCompleter(only_directories=False, expanduser=True),
"double_quoted_filename": PathCompleter(
only_directories=False, expanduser=True
),
"single_quoted_filename": PathCompleter(
only_directories=False, expanduser=True
),
},
)
| SystemCompleter |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride2.py | {
"start": 2261,
"end": 2410
} | class ____:
def method1(self, x: Self) -> Self: ...
def method2(self, x: Self) -> Self: ...
def method3(self, x: Self) -> Self: ...
| Base3 |
python | openai__openai-python | src/openai/types/batch_create_params.py | {
"start": 2053,
"end": 2519
} | class ____(TypedDict, total=False):
anchor: Required[Literal["created_at"]]
"""Anchor timestamp after which the expiration policy applies.
Supported anchors: `created_at`. Note that the anchor is the file creation time,
not the time the batch is created.
"""
seconds: Required[int]
"""The number of seconds after the anchor time that the file will expire.
Must be between 3600 (1 hour) and 2592000 (30 days).
"""
| OutputExpiresAfter |
python | google__jax | jax/_src/pallas/core.py | {
"start": 7455,
"end": 8297
} | class ____(enum.Enum):
"""Logical, device-agnostic memory spaces.
Each memory space will be translated to a device-specific memory
type during lowering.
"""
ANY = "any" # Unrestricted memory space (usually HBM)
ERROR = "error" # Memory space for checkify errors.
INDEX = "index" # Memory space for scalar prefetch arguments.
KEY = "key" # Memory space for PRNG keys.
HOST = "host" # Host memory space.
def from_type(self, type: jax_core.AbstractValue) -> MemoryRef:
return MemoryRef(type, memory_space=self)
def __call__(self, shape: tuple[int, ...], dtype: jnp.dtype):
# A convenience function for constructing MemoryRef types of ShapedArrays.
return self.from_type(jax_core.ShapedArray(shape, dtype))
def __str__(self) -> str:
return self.value
@dataclasses.dataclass(frozen=True)
| MemorySpace |
python | django__django | tests/introspection/tests.py | {
"start": 495,
"end": 18258
} | class ____(TransactionTestCase):
available_apps = ["introspection"]
def test_table_names(self):
tl = connection.introspection.table_names()
self.assertEqual(tl, sorted(tl))
self.assertIn(
Reporter._meta.db_table,
tl,
"'%s' isn't in table_list()." % Reporter._meta.db_table,
)
self.assertIn(
Article._meta.db_table,
tl,
"'%s' isn't in table_list()." % Article._meta.db_table,
)
def test_django_table_names(self):
with connection.cursor() as cursor:
cursor.execute("CREATE TABLE django_ixn_test_table (id INTEGER);")
tl = connection.introspection.django_table_names()
cursor.execute("DROP TABLE django_ixn_test_table;")
self.assertNotIn(
"django_ixn_test_table",
tl,
"django_table_names() returned a non-Django table",
)
def test_django_table_names_retval_type(self):
# Table name is a list #15216
tl = connection.introspection.django_table_names(only_existing=True)
self.assertIs(type(tl), list)
tl = connection.introspection.django_table_names(only_existing=False)
self.assertIs(type(tl), list)
def test_table_names_with_views(self):
with connection.cursor() as cursor:
try:
cursor.execute(
"CREATE VIEW introspection_article_view AS SELECT headline "
"from introspection_article;"
)
except DatabaseError as e:
if "insufficient privileges" in str(e):
self.fail("The test user has no CREATE VIEW privileges")
else:
raise
try:
self.assertIn(
"introspection_article_view",
connection.introspection.table_names(include_views=True),
)
self.assertNotIn(
"introspection_article_view", connection.introspection.table_names()
)
finally:
with connection.cursor() as cursor:
cursor.execute("DROP VIEW introspection_article_view")
def test_unmanaged_through_model(self):
tables = connection.introspection.django_table_names()
self.assertNotIn(ArticleReporter._meta.db_table, tables)
def test_installed_models(self):
tables = [Article._meta.db_table, Reporter._meta.db_table]
models = connection.introspection.installed_models(tables)
self.assertEqual(models, {Article, Reporter})
def test_sequence_list(self):
sequences = connection.introspection.sequence_list()
reporter_seqs = [
seq for seq in sequences if seq["table"] == Reporter._meta.db_table
]
self.assertEqual(
len(reporter_seqs), 1, "Reporter sequence not found in sequence_list()"
)
self.assertEqual(reporter_seqs[0]["column"], "id")
def test_get_table_description_names(self):
with connection.cursor() as cursor:
desc = connection.introspection.get_table_description(
cursor, Reporter._meta.db_table
)
self.assertEqual(
[r[0] for r in desc], [f.column for f in Reporter._meta.fields]
)
def test_get_table_description_types(self):
with connection.cursor() as cursor:
desc = connection.introspection.get_table_description(
cursor, Reporter._meta.db_table
)
self.assertEqual(
[connection.introspection.get_field_type(r[1], r) for r in desc],
[
connection.features.introspected_field_types[field]
for field in (
"BigAutoField",
"CharField",
"CharField",
"CharField",
"BigIntegerField",
"BinaryField",
"SmallIntegerField",
"DurationField",
)
],
)
def test_get_table_description_col_lengths(self):
with connection.cursor() as cursor:
desc = connection.introspection.get_table_description(
cursor, Reporter._meta.db_table
)
self.assertEqual(
[
r[2]
for r in desc
if connection.introspection.get_field_type(r[1], r) == "CharField"
],
[30, 30, 254],
)
def test_get_table_description_nullable(self):
with connection.cursor() as cursor:
desc = connection.introspection.get_table_description(
cursor, Reporter._meta.db_table
)
nullable_by_backend = connection.features.interprets_empty_strings_as_nulls
self.assertEqual(
[r[6] for r in desc],
[
False,
nullable_by_backend,
nullable_by_backend,
nullable_by_backend,
True,
True,
False,
False,
],
)
def test_bigautofield(self):
with connection.cursor() as cursor:
desc = connection.introspection.get_table_description(
cursor, City._meta.db_table
)
self.assertIn(
connection.features.introspected_field_types["BigAutoField"],
[connection.introspection.get_field_type(r[1], r) for r in desc],
)
def test_smallautofield(self):
with connection.cursor() as cursor:
desc = connection.introspection.get_table_description(
cursor, Country._meta.db_table
)
self.assertIn(
connection.features.introspected_field_types["SmallAutoField"],
[connection.introspection.get_field_type(r[1], r) for r in desc],
)
@skipUnlessDBFeature("supports_comments")
def test_db_comments(self):
with connection.cursor() as cursor:
desc = connection.introspection.get_table_description(
cursor, DbCommentModel._meta.db_table
)
table_list = connection.introspection.get_table_list(cursor)
self.assertEqual(
["'Name' column comment"],
[field.comment for field in desc if field.name == "name"],
)
self.assertEqual(
["Custom table comment"],
[
table.comment
for table in table_list
if table.name == "introspection_dbcommentmodel"
],
)
# Regression test for #9991 - 'real' types in postgres
@skipUnlessDBFeature("has_real_datatype")
def test_postgresql_real_type(self):
with connection.cursor() as cursor:
cursor.execute("CREATE TABLE django_ixn_real_test_table (number REAL);")
desc = connection.introspection.get_table_description(
cursor, "django_ixn_real_test_table"
)
cursor.execute("DROP TABLE django_ixn_real_test_table;")
self.assertEqual(
connection.introspection.get_field_type(desc[0][1], desc[0]), "FloatField"
)
@skipUnlessDBFeature("can_introspect_foreign_keys")
def test_get_relations(self):
with connection.cursor() as cursor:
relations = connection.introspection.get_relations(
cursor, Article._meta.db_table
)
if connection.vendor == "mysql" and connection.mysql_is_mariadb:
no_db_on_delete = None
else:
no_db_on_delete = DO_NOTHING
# {field_name: (field_name_other_table, other_table, db_on_delete)}
expected_relations = {
"reporter_id": ("id", Reporter._meta.db_table, no_db_on_delete),
"response_to_id": ("id", Article._meta.db_table, no_db_on_delete),
}
self.assertEqual(relations, expected_relations)
# Removing a field shouldn't disturb get_relations (#17785)
body = Article._meta.get_field("body")
with connection.schema_editor() as editor:
editor.remove_field(Article, body)
with connection.cursor() as cursor:
relations = connection.introspection.get_relations(
cursor, Article._meta.db_table
)
with connection.schema_editor() as editor:
editor.add_field(Article, body)
self.assertEqual(relations, expected_relations)
@skipUnlessDBFeature("can_introspect_foreign_keys", "supports_on_delete_db_cascade")
def test_get_relations_db_on_delete_cascade(self):
with connection.cursor() as cursor:
relations = connection.introspection.get_relations(
cursor, DbOnDeleteCascadeModel._meta.db_table
)
if connection.vendor == "mysql" and connection.mysql_is_mariadb:
no_db_on_delete = None
else:
no_db_on_delete = DO_NOTHING
# {field_name: (field_name_other_table, other_table, db_on_delete)}
expected_relations = {
"fk_db_cascade_id": ("id", City._meta.db_table, DB_CASCADE),
"fk_do_nothing_id": ("id", Country._meta.db_table, no_db_on_delete),
}
self.assertEqual(relations, expected_relations)
@skipUnlessDBFeature("can_introspect_foreign_keys", "supports_on_delete_db_null")
def test_get_relations_db_on_delete_null(self):
with connection.cursor() as cursor:
relations = connection.introspection.get_relations(
cursor, DbOnDeleteSetNullModel._meta.db_table
)
# {field_name: (field_name_other_table, other_table, db_on_delete)}
expected_relations = {
"fk_set_null_id": ("id", Reporter._meta.db_table, DB_SET_NULL),
}
self.assertEqual(relations, expected_relations)
@skipUnlessDBFeature("can_introspect_foreign_keys", "supports_on_delete_db_default")
def test_get_relations_db_on_delete_default(self):
with connection.cursor() as cursor:
relations = connection.introspection.get_relations(
cursor, DbOnDeleteSetDefaultModel._meta.db_table
)
# {field_name: (field_name_other_table, other_table, db_on_delete)}
expected_relations = {
"fk_db_set_default_id": ("id", Country._meta.db_table, DB_SET_DEFAULT),
}
self.assertEqual(relations, expected_relations)
def test_get_primary_key_column(self):
with connection.cursor() as cursor:
primary_key_column = connection.introspection.get_primary_key_column(
cursor, Article._meta.db_table
)
pk_fk_column = connection.introspection.get_primary_key_column(
cursor, District._meta.db_table
)
self.assertEqual(primary_key_column, "id")
self.assertEqual(pk_fk_column, "city_id")
def test_get_constraints_index_types(self):
with connection.cursor() as cursor:
constraints = connection.introspection.get_constraints(
cursor, Article._meta.db_table
)
index = {}
index2 = {}
for val in constraints.values():
if val["columns"] == ["headline", "pub_date"]:
index = val
if val["columns"] == [
"headline",
"response_to_id",
"pub_date",
"reporter_id",
]:
index2 = val
self.assertEqual(index["type"], Index.suffix)
self.assertEqual(index2["type"], Index.suffix)
@skipUnlessDBFeature("supports_index_column_ordering")
def test_get_constraints_indexes_orders(self):
"""
Indexes have the 'orders' key with a list of 'ASC'/'DESC' values.
"""
with connection.cursor() as cursor:
constraints = connection.introspection.get_constraints(
cursor, Article._meta.db_table
)
indexes_verified = 0
expected_columns = [
["headline", "pub_date"],
["headline", "response_to_id", "pub_date", "reporter_id"],
]
if connection.features.indexes_foreign_keys:
expected_columns += [
["reporter_id"],
["response_to_id"],
]
for val in constraints.values():
if val["index"] and not (val["primary_key"] or val["unique"]):
self.assertIn(val["columns"], expected_columns)
self.assertEqual(val["orders"], ["ASC"] * len(val["columns"]))
indexes_verified += 1
self.assertEqual(indexes_verified, len(expected_columns))
@skipUnlessDBFeature("supports_index_column_ordering", "supports_partial_indexes")
def test_get_constraints_unique_indexes_orders(self):
with connection.cursor() as cursor:
constraints = connection.introspection.get_constraints(
cursor,
UniqueConstraintConditionModel._meta.db_table,
)
self.assertIn("cond_name_without_color_uniq", constraints)
constraint = constraints["cond_name_without_color_uniq"]
self.assertIs(constraint["unique"], True)
self.assertEqual(constraint["columns"], ["name"])
self.assertEqual(constraint["orders"], ["ASC"])
def test_get_constraints(self):
def assertDetails(
details,
cols,
primary_key=False,
unique=False,
index=False,
check=False,
foreign_key=None,
):
# Different backends have different values for same constraints:
# PRIMARY KEY UNIQUE CONSTRAINT UNIQUE INDEX
# MySQL pk=1 uniq=1 idx=1 pk=0 uniq=1 idx=1 pk=0 uniq=1 idx=1
# Postgres pk=1 uniq=1 idx=0 pk=0 uniq=1 idx=0 pk=0 uniq=1 idx=1
# SQLite pk=1 uniq=0 idx=0 pk=0 uniq=1 idx=0 pk=0 uniq=1 idx=1
if details["primary_key"]:
details["unique"] = True
if details["unique"]:
details["index"] = False
self.assertEqual(details["columns"], cols)
self.assertEqual(details["primary_key"], primary_key)
self.assertEqual(details["unique"], unique)
self.assertEqual(details["index"], index)
self.assertEqual(details["check"], check)
self.assertEqual(details["foreign_key"], foreign_key)
# Test custom constraints
custom_constraints = {
"article_email_pub_date_uniq",
"email_pub_date_idx",
}
with connection.cursor() as cursor:
constraints = connection.introspection.get_constraints(
cursor, Comment._meta.db_table
)
if (
connection.features.supports_column_check_constraints
and connection.features.can_introspect_check_constraints
):
constraints.update(
connection.introspection.get_constraints(
cursor, CheckConstraintModel._meta.db_table
)
)
custom_constraints.add("up_votes_gte_0_check")
assertDetails(
constraints["up_votes_gte_0_check"], ["up_votes"], check=True
)
assertDetails(
constraints["article_email_pub_date_uniq"],
["article_id", "email", "pub_date"],
unique=True,
)
assertDetails(
constraints["email_pub_date_idx"], ["email", "pub_date"], index=True
)
# Test field constraints
field_constraints = set()
for name, details in constraints.items():
if name in custom_constraints:
continue
elif details["columns"] == ["up_votes"] and details["check"]:
assertDetails(details, ["up_votes"], check=True)
field_constraints.add(name)
elif details["columns"] == ["voting_number"] and details["check"]:
assertDetails(details, ["voting_number"], check=True)
field_constraints.add(name)
elif details["columns"] == ["ref"] and details["unique"]:
assertDetails(details, ["ref"], unique=True)
field_constraints.add(name)
elif details["columns"] == ["voting_number"] and details["unique"]:
assertDetails(details, ["voting_number"], unique=True)
field_constraints.add(name)
elif details["columns"] == ["article_id"] and details["index"]:
assertDetails(details, ["article_id"], index=True)
field_constraints.add(name)
elif details["columns"] == ["id"] and details["primary_key"]:
assertDetails(details, ["id"], primary_key=True, unique=True)
field_constraints.add(name)
elif details["columns"] == ["article_id"] and details["foreign_key"]:
assertDetails(
details, ["article_id"], foreign_key=("introspection_article", "id")
)
field_constraints.add(name)
elif details["check"]:
# Some databases (e.g. Oracle) include additional check
# constraints.
field_constraints.add(name)
# All constraints are accounted for.
self.assertEqual(
constraints.keys() ^ (custom_constraints | field_constraints), set()
)
| IntrospectionTests |
python | kamyu104__LeetCode-Solutions | Python/special-permutations.py | {
"start": 71,
"end": 875
} | class ____(object):
def specialPerm(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
MOD = 10**9+7
def backtracking(i, mask):
if mask == (1<<len(nums))-1:
return 1
if lookup[i+1][mask] == -1:
total = 0
for j in xrange(len(nums)):
if mask&(1<<j):
continue
if not (i == -1 or nums[i]%nums[j] == 0 or nums[j]%nums[i] == 0):
continue
total = (total+backtracking(j, mask|(1<<j)))%MOD
lookup[i+1][mask] = total
return lookup[i+1][mask]
lookup = [[-1]*(1<<len(nums)) for _ in xrange(len(nums)+1)]
return backtracking(-1, 0)
| Solution |
python | walkccc__LeetCode | solutions/2931. Maximum Spending After Buying Items/2931.py | {
"start": 0,
"end": 194
} | class ____:
def maxSpending(self, values: list[list[int]]) -> int:
items = sorted(item for shop in values for item in shop)
return sum(item * d for d, item in enumerate(items, 1))
| Solution |
python | getsentry__sentry | src/sentry/seer/explorer/client_models.py | {
"start": 564,
"end": 781
} | class ____(BaseModel):
"""A block in the Explorer agent's conversation/memory."""
id: str
message: Message
timestamp: str
loading: bool = False
class Config:
extra = "allow"
| MemoryBlock |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/pg8000.py | {
"start": 5564,
"end": 5653
} | class ____(ENUM):
def get_dbapi_type(self, dbapi):
return dbapi.UNKNOWN
| _PGEnum |
python | python-excel__xlwt | xlwt/BIFFRecords.py | {
"start": 61632,
"end": 61918
} | class ____(BiffRecord):
"""
This record represents a cell that contains a boolean or error value.
"""
_REC_ID = 0x0205
def __init__(self, row, col, xf_index, number, is_error):
self._rec_data = pack('<3HBB', row, col, xf_index, number, is_error)
| BoolErrRecord |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/_typing.py | {
"start": 2673,
"end": 2870
} | class ____(Protocol, Generic[_T_co]):
"""indicates a class that has a __clause_element__() method"""
def __clause_element__(self) -> roles.ExpressionElementRole[_T_co]: ...
| _HasClauseElement |
python | automl__auto-sklearn | autosklearn/util/single_thread_client.py | {
"start": 90,
"end": 690
} | class ____(dask.distributed.Future):
"""
A class that mimics a distributed Future, the outcome of
performing submit on a distributed client.
"""
def __init__(self, result: typing.Any) -> None:
self._result = result # type: typing.Any
def result(self, timeout: typing.Optional[int] = None) -> typing.Any:
return self._result
def cancel(self) -> None:
pass
def done(self) -> bool:
return True
def __repr__(self) -> str:
return "DummyFuture: {}".format(self._result)
def __del__(self) -> None:
pass
| DummyFuture |
python | automl__auto-sklearn | autosklearn/metalearning/metafeatures/metafeatures.py | {
"start": 32690,
"end": 35232
} | class ____(MetaFeature):
def _calculate(self, X, y, logger, feat_type):
import sklearn.tree
if type(y) in ("binary", "multiclass"):
kf = sklearn.model_selection.StratifiedKFold(n_splits=5)
else:
kf = sklearn.model_selection.KFold(n_splits=5)
accuracy = 0.0
for train, test in kf.split(X, y):
random_state = sklearn.utils.check_random_state(42)
node = sklearn.tree.DecisionTreeClassifier(
criterion="entropy",
max_depth=1,
random_state=random_state,
min_samples_split=2,
min_samples_leaf=1,
max_features=1,
)
node.fit(
X.iloc[train] if hasattr(X, "iloc") else X[train],
y.iloc[train] if hasattr(y, "iloc") else y[train],
)
predictions = node.predict(
X.iloc[test] if hasattr(X, "iloc") else X[test],
)
accuracy += sklearn.metrics.accuracy_score(
predictions,
y.iloc[test] if hasattr(y, "iloc") else y[test],
)
return accuracy / 5
def _calculate_sparse(self, X, y, logger, feat_type):
return np.NaN
"""
This is wrong...
@metafeatures.define("landmark_worst_node_learner")
def landmark_worst_node_learner(X, y):
# TODO: this takes more than 10 minutes on some datasets (eg mfeat-pixels)
# which has 240*6 = 1440 discrete attributes...
# TODO: calculate information gain instead of using the worst test result
import sklearn.tree
performances = []
for attribute_idx in range(X.shape[1]):
kf = sklearn.model_selection.StratifiedKFold(y, n_folds=5)
accuracy = 0.
for train, test in kf:
node = sklearn.tree.DecisionTreeClassifier(criterion="entropy",
max_features=None, max_depth=1, min_samples_split=1,
min_samples_leaf=1)
node.fit(X[train][:,attribute_idx].reshape((-1, 1)), y[train],
check_input=False)
predictions = node.predict(X[test][:,attribute_idx].reshape((-1, 1)))
accuracy += sklearn.metrics.accuracy_score(predictions, y[test])
performances.append(1 - (accuracy / 10))
return max(performances)
"""
# Replace the Elite 1NN with a normal 1NN, this slightly changes the
# intuition behind this landmark, but Elite 1NN is used nowhere else...
@metafeatures.define("Landmark1NN")
| LandmarkRandomNodeLearner |
python | kamyu104__LeetCode-Solutions | Python/minimum-operations-to-make-a-uni-value-grid.py | {
"start": 63,
"end": 1566
} | class ____(object):
def minOperations(self, grid, x):
"""
:type grid: List[List[int]]
:type x: 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
nums = [v for row in grid for v in row]
if len(set(v%x for v in nums)) > 1:
return -1
nth_element(nums, len(nums)//2)
median = nums[len(nums)//2]
return sum(abs(v-median)//x for v in nums)
| Solution |
python | getsentry__sentry | src/sentry/integrations/cursor/models.py | {
"start": 576,
"end": 843
} | class ____(BaseModel):
prompt: CursorAgentLaunchRequestPrompt
source: CursorAgentSource
model: str | None = None
target: CursorAgentLaunchRequestTarget | None = None
webhook: CursorAgentLaunchRequestWebhook | None = None
| CursorAgentLaunchRequestBody |
python | sympy__sympy | sympy/printing/lambdarepr.py | {
"start": 2114,
"end": 7451
} | class ____(LambdaPrinter):
# key, value pairs correspond to SymPy name and numexpr name
# functions not appearing in this dict will raise a TypeError
printmethod = "_numexprcode"
_numexpr_functions = {
'sin' : 'sin',
'cos' : 'cos',
'tan' : 'tan',
'asin': 'arcsin',
'acos': 'arccos',
'atan': 'arctan',
'atan2' : 'arctan2',
'sinh' : 'sinh',
'cosh' : 'cosh',
'tanh' : 'tanh',
'asinh': 'arcsinh',
'acosh': 'arccosh',
'atanh': 'arctanh',
'ln' : 'log',
'log': 'log',
'exp': 'exp',
'sqrt' : 'sqrt',
'Abs' : 'abs',
'conjugate' : 'conj',
'im' : 'imag',
're' : 'real',
'where' : 'where',
'complex' : 'complex',
'contains' : 'contains',
}
module = 'numexpr'
def _print_ImaginaryUnit(self, expr):
return '1j'
def _print_seq(self, seq, delimiter=', '):
# simplified _print_seq taken from pretty.py
s = [self._print(item) for item in seq]
if s:
return delimiter.join(s)
else:
return ""
def _print_Function(self, e):
func_name = e.func.__name__
nstr = self._numexpr_functions.get(func_name, None)
if nstr is None:
# check for implemented_function
if hasattr(e, '_imp_'):
return "(%s)" % self._print(e._imp_(*e.args))
else:
raise TypeError("numexpr does not support function '%s'" %
func_name)
return "%s(%s)" % (nstr, self._print_seq(e.args))
def _print_Piecewise(self, expr):
"Piecewise function printer"
exprs = [self._print(arg.expr) for arg in expr.args]
conds = [self._print(arg.cond) for arg in expr.args]
# If [default_value, True] is a (expr, cond) sequence in a Piecewise object
# it will behave the same as passing the 'default' kwarg to select()
# *as long as* it is the last element in expr.args.
# If this is not the case, it may be triggered prematurely.
ans = []
parenthesis_count = 0
is_last_cond_True = False
for cond, expr in zip(conds, exprs):
if cond == 'True':
ans.append(expr)
is_last_cond_True = True
break
else:
ans.append('where(%s, %s, ' % (cond, expr))
parenthesis_count += 1
if not is_last_cond_True:
# See https://github.com/pydata/numexpr/issues/298
#
# simplest way to put a nan but raises
# 'RuntimeWarning: invalid value encountered in log'
#
# There are other ways to do this such as
#
# >>> import numexpr as ne
# >>> nan = float('nan')
# >>> ne.evaluate('where(x < 0, -1, nan)', {'x': [-1, 2, 3], 'nan':nan})
# array([-1., nan, nan])
#
# That needs to be handled in the lambdified function though rather
# than here in the printer.
ans.append('log(-1)')
return ''.join(ans) + ')' * parenthesis_count
def _print_ITE(self, expr):
from sympy.functions.elementary.piecewise import Piecewise
return self._print(expr.rewrite(Piecewise))
def blacklisted(self, expr):
raise TypeError("numexpr cannot be used with %s" %
expr.__class__.__name__)
# blacklist all Matrix printing
_print_SparseRepMatrix = \
_print_MutableSparseMatrix = \
_print_ImmutableSparseMatrix = \
_print_Matrix = \
_print_DenseMatrix = \
_print_MutableDenseMatrix = \
_print_ImmutableMatrix = \
_print_ImmutableDenseMatrix = \
blacklisted
# blacklist some Python expressions
_print_list = \
_print_tuple = \
_print_Tuple = \
_print_dict = \
_print_Dict = \
blacklisted
def _print_NumExprEvaluate(self, expr):
evaluate = self._module_format(self.module +".evaluate")
return "%s('%s', truediv=True)" % (evaluate, self._print(expr.expr))
def doprint(self, expr):
from sympy.codegen.ast import CodegenAST
from sympy.codegen.pynodes import NumExprEvaluate
if not isinstance(expr, CodegenAST):
expr = NumExprEvaluate(expr)
return super().doprint(expr)
def _print_Return(self, expr):
from sympy.codegen.pynodes import NumExprEvaluate
r, = expr.args
if not isinstance(r, NumExprEvaluate):
expr = expr.func(NumExprEvaluate(r))
return super()._print_Return(expr)
def _print_Assignment(self, expr):
from sympy.codegen.pynodes import NumExprEvaluate
lhs, rhs, *args = expr.args
if not isinstance(rhs, NumExprEvaluate):
expr = expr.func(lhs, NumExprEvaluate(rhs), *args)
return super()._print_Assignment(expr)
def _print_CodeBlock(self, expr):
from sympy.codegen.ast import CodegenAST
from sympy.codegen.pynodes import NumExprEvaluate
args = [ arg if isinstance(arg, CodegenAST) else NumExprEvaluate(arg) for arg in expr.args ]
return super()._print_CodeBlock(self, expr.func(*args))
| NumExprPrinter |
python | google__jax | jaxlib/triton/dialect.py | {
"start": 1069,
"end": 1482
} | class ____(ReduceOp): # type: ignore
def __init__(
self,
operands: Sequence[ir.Value],
axis: int,
*,
loc: ir.Location | None = None,
ip: ir.InsertionPoint | None = None,
):
return_types = _infer_reduce_op_return_types(operands, axis)
super().__init__(return_types, operands, axis, loc=loc, ip=ip)
# TODO(slebedev): Consider overriding instead.
del reduce
| ReduceOp |
python | davidhalter__jedi | test/completion/classes.py | {
"start": 9472,
"end": 9832
} | class ____():
default = 3
def x(self, arg=default):
#? str()
default
return arg
def y(self):
return default
#? int()
DefaultArg().x()
#? str()
DefaultArg().y()
#? int()
DefaultArg.x()
#? str()
DefaultArg.y()
# -----------------
# Error Recovery
# -----------------
from import_tree.pkg.base import MyBase
| DefaultArg |
python | python-excel__xlwt | xlwt/antlr.py | {
"start": 74307,
"end": 75903
} | class ____(BaseAST):
def __init__(self,token=None):
super(CommonAST,self).__init__()
self.ttype = INVALID_TYPE
self.text = "<no text>"
self.line = 0
self.column= 0
self.initialize(token)
#assert self.text
### Get the token text for this node
def getText(self):
return self.text
### Get the token type for this node
def getType(self):
return self.ttype
### Get the line for this node
def getLine(self):
return self.line
### Get the column for this node
def getColumn(self):
return self.column
def initialize(self,*args):
if not args:
return
arg0 = args[0]
if isinstance(arg0,int):
arg1 = args[1]
self.setType(arg0)
self.setText(arg1)
return
if isinstance(arg0,AST) or isinstance(arg0,Token):
self.setText(arg0.getText())
self.setType(arg0.getType())
self.line = arg0.getLine()
self.column = arg0.getColumn()
return
### Set the token text for this node
def setText(self,text_):
assert is_string_type(text_)
self.text = text_
### Set the token type for this node
def setType(self,ttype_):
assert isinstance(ttype_,int)
self.ttype = ttype_
###xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx###
### CommonASTWithHiddenTokens ###
###xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx###
| CommonAST |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 174451,
"end": 175573
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"id",
"title",
"body",
"assignee_ids",
"milestone_id",
"label_ids",
"state",
"project_ids",
"client_mutation_id",
)
id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="id")
title = sgqlc.types.Field(String, graphql_name="title")
body = sgqlc.types.Field(String, graphql_name="body")
assignee_ids = sgqlc.types.Field(
sgqlc.types.list_of(sgqlc.types.non_null(ID)), graphql_name="assigneeIds"
)
milestone_id = sgqlc.types.Field(ID, graphql_name="milestoneId")
label_ids = sgqlc.types.Field(
sgqlc.types.list_of(sgqlc.types.non_null(ID)), graphql_name="labelIds"
)
state = sgqlc.types.Field(IssueState, graphql_name="state")
project_ids = sgqlc.types.Field(
sgqlc.types.list_of(sgqlc.types.non_null(ID)), graphql_name="projectIds"
)
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
| UpdateIssueInput |
python | cython__cython | docs/examples/tutorial/pure/pep_526.py | {
"start": 499,
"end": 612
} | class ____:
a: cython.int
b: cython.int
def __init__(self, b=0):
self.a = 3
self.b = b
| A |
python | kamyu104__LeetCode-Solutions | Python/detect-pattern-of-length-m-repeated-k-or-more-times.py | {
"start": 29,
"end": 449
} | class ____(object):
def containsPattern(self, arr, m, k):
"""
:type arr: List[int]
:type m: int
:type k: int
:rtype: bool
"""
cnt = 0
for i in xrange(len(arr)-m):
if arr[i] != arr[i+m]:
cnt = 0
continue
cnt += 1
if cnt == (k-1)*m:
return True
return False
| Solution |
python | allegroai__clearml | clearml/utilities/pigar/modules.py | {
"start": 375,
"end": 539
} | class ____(dict):
"""Modules object will be used to store modules information."""
def __init__(self) -> None:
super(Modules, self).__init__()
| Modules |
python | great-expectations__great_expectations | contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/expectations/expect_column_values_confidence_for_data_label_to_be_greater_than_or_equal_to_threshold.py | {
"start": 2571,
"end": 7949
} | class ____(
ColumnMapExpectation
):
"""Expect the column values to have a DataProfiler confidence threshold greater than or equal to the specified threshold for the data label.
This function builds upon the custom column map expectations of Great Expectations. This function asks the question a yes/no question of each row in the user-specified column; namely, does the confidence threshold provided by the DataProfiler model exceed the user-specified threshold.
Args:
column (str): The column name that you want to check.
data_label(str): The data label for which you want to check confidences against the threshold value
threshold (float): The value, usually as a decimal (e.g. .32), you want to use to flag low confidence predictions
df.expect_column_values_confidence_for_data_label_to_be_greater_than_or_equal_to_threshold(
column,
data_label=<>,
threshold=float(0<=1)
)
"""
examples = [
{
"data": {
"OPEID6": ["1002", "1052", "25034", "McRoomyRoom"],
"INSTNM": [
"Alabama A & M University",
"University of Alabama at Birmingham",
"Amridge University",
"McRoomyRoom",
],
"ZIP": ["35762", "35294-0110", "36117-3553", "McRoomyRoom"],
"ACCREDAGENCY": [
"Southern Association of Colleges and Schools Commission on Colleges",
"Southern Association of Colleges and Schools Commission on Colleges",
"Southern Association of Colleges and Schools Commission on Colleges",
"McRoomyRoom",
],
"INSTURL": [
"www.aamu.edu/",
"https://www.uab.edu",
"www.amridgeuniversity.edu",
"McRoomyRoom",
],
"NPCURL": [
"www.aamu.edu/admissions-aid/tuition-fees/net-price-calculator.html",
"https://uab.studentaidcalculator.com/survey.aspx",
"www2.amridgeuniversity.edu:9091/",
"McRoomyRoom",
],
"LATITUDE": ["34.783368", "33.505697", "32.362609", "McRoomyRoom"],
"LONGITUDE": ["-86.568502", "-86.799345", "-86.17401", "McRoomyRoom"],
"RELAFFIL": ["NULL", "NULL", "74", "McRoomyRoom"],
"DEATH_YR2_RT": [
"PrivacySuppressed",
"PrivacySuppressed",
"PrivacySuppressed",
"McRoomyRoom",
],
"SEARCH_STRING": [
"Alabama A & M University AAMU",
"University of Alabama at Birmingham ",
"Amridge University Southern Christian University Regions University",
"McRoomyRoom",
],
},
"tests": [
{
"title": "positive_test_with_column_one",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "ZIP", "data_label": "ADDRESS", "threshold": 0.00},
"out": {
"success": True,
},
},
{
"title": "failing_test_with_column_one",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "ZIP", "data_label": "ADDRESS", "threshold": 1.00},
"out": {
"success": False,
},
},
],
}
]
# This is the id string of the Metric used by this Expectation.
# For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above.
map_metric = (
"column_values.prediction_confidence_for_data_label_greater_than_or_equal_to_threshold"
)
# This is a list of parameter names that can affect whether the Expectation evaluates to True or False
success_keys = (
"threshold",
"data_label",
"mostly",
)
# This dictionary contains default values for any parameters that should have default values
default_kwarg_values = {
"threshold": None,
"data_label": None,
"result_format": "BASIC",
"catch_exceptions": False,
}
# This object contains metadata for display in the public Gallery
library_metadata = {
"requirements": ["dataprofiler", "tensorflow", "scikit-learn", "numpy"],
"maturity": "experimental", # "concept_only", "experimental", "beta", or "production"
"tags": ["dataprofiler"], # Tags for this Expectation in the Gallery
"contributors": [ # Github handles for all contributors to this Expectation.
"@taylorfturner", # Don't forget to add your github handle here!
],
}
if __name__ == "__main__":
diagnostics_report = ExpectColumnValuesConfidenceForDataLabelToBeGreaterThanOrEqualToThreshold().run_diagnostics()
print(diagnostics_report.generate_checklist())
| ExpectColumnValuesConfidenceForDataLabelToBeGreaterThanOrEqualToThreshold |
python | apache__airflow | helm-tests/tests/helm_tests/webserver/test_webserver.py | {
"start": 48853,
"end": 50458
} | class ____:
"""Tests webserver service account."""
def test_should_add_component_specific_labels(self):
docs = render_chart(
values={
"airflowVersion": "2.10.5",
"webserver": {
"serviceAccount": {"create": True},
"labels": {"test_label": "test_label_value"},
},
},
show_only=["templates/webserver/webserver-serviceaccount.yaml"],
)
assert "test_label" in jmespath.search("metadata.labels", docs[0])
assert jmespath.search("metadata.labels", docs[0])["test_label"] == "test_label_value"
def test_default_automount_service_account_token(self):
docs = render_chart(
values={
"airflowVersion": "2.10.5",
"webserver": {
"serviceAccount": {"create": True},
},
},
show_only=["templates/webserver/webserver-serviceaccount.yaml"],
)
assert jmespath.search("automountServiceAccountToken", docs[0]) is True
def test_overridden_automount_service_account_token(self):
docs = render_chart(
values={
"airflowVersion": "2.10.5",
"webserver": {
"serviceAccount": {"create": True, "automountServiceAccountToken": False},
},
},
show_only=["templates/webserver/webserver-serviceaccount.yaml"],
)
assert jmespath.search("automountServiceAccountToken", docs[0]) is False
| TestWebserverServiceAccount |
python | sphinx-doc__sphinx | sphinx/builders/_epub_base.py | {
"start": 2391,
"end": 2804
} | class ____(NamedTuple):
navpoint: str
playorder: int
text: str
refuri: str
children: list[NavPoint]
def sphinx_smarty_pants(t: str, language: str = 'en') -> str:
t = t.replace('"', '"')
t = smartquotes.educateDashesOldSchool(t)
t = smartquotes.educateQuotes(t, language)
t = t.replace('"', '"')
return t
ssp = sphinx_smarty_pants
# The epub publisher
| NavPoint |
python | ray-project__ray | python/ray/serve/_private/proxy_request_response.py | {
"start": 5441,
"end": 5750
} | class ____:
code: Union[str, grpc.StatusCode] # Must be convertible to a string.
is_error: bool = False
message: str = ""
# Yields protocol-specific messages followed by a final `ResponseStatus`.
ResponseGenerator = AsyncIterator[Union[Any, ResponseStatus]]
@dataclass(frozen=True)
| ResponseStatus |
python | pydantic__pydantic | tests/mypy/modules/plugin_strict_fields.py | {
"start": 556,
"end": 723
} | class ____(ModelStrictMode):
b: int = Field(strict=False)
c: int = Field(strict=True)
# expected error: a, c
ModelOverride2(a='1', b='2', c='3')
| ModelOverride2 |
python | tox-dev__tox | src/tox/execute/pep517_backend.py | {
"start": 4063,
"end": 5260
} | class ____(ExecuteInstance):
"""A backend invocation."""
def __init__(
self,
request: ExecuteRequest,
options: ExecuteOptions,
out: SyncWrite,
err: SyncWrite,
instance_status: tuple[LocalSubProcessExecuteInstance, ExecuteStatus],
) -> None:
super().__init__(request, options, out, err)
self._instance, self._status = instance_status
self._lock = Lock()
@property
def cmd(self) -> Sequence[str]:
return self._instance.cmd
def __enter__(self) -> ExecuteStatus:
self._lock.acquire()
self._swap_out_err()
return self._status
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
self._swap_out_err()
self._lock.release()
def _swap_out_err(self) -> None:
out, err = self._out, self._err
# update status to see the newly collected content
self._out, self._err = self._instance.set_out_err(out, err)
# update the thread out/err
self._status.set_out_err(out, err)
| LocalSubProcessPep517ExecuteInstance |
python | great-expectations__great_expectations | tests/core/test__docs_decorators.py | {
"start": 19383,
"end": 19902
} | class ____:
"""Docstring summary.
Longer description.
Args:
some_arg: some_arg description.
other_arg: other_arg description.
"""
def __init__(self, some_arg, other_arg) -> None:
self.some_arg = some_arg
self.other_arg = other_arg
@deprecated_argument(argument_name="some_arg", version="1.2.3", message="This is deprecated!!")
@new_argument(argument_name="other_arg", version="1.2.3", message="Added in version 1.2.3")
| _ClassFullDocstringDeprecatedAndNewAtClassLevel |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/auto_shard_dataset_test.py | {
"start": 24437,
"end": 28230
} | class ____(tf_record_test_base.TFRecordTestBase,
parameterized.TestCase):
def _setUpFiles(self, num_files, num_records_per_file):
self._num_files = num_files
self._num_records = num_records_per_file
self._filenames = self._createFiles()
@combinations.generate(test_base.default_test_combinations())
def testFileShardingWithLegacyRebatch(self):
# Tests that RebatchDatasetV1 is a passthrough op.
self._setUpFiles(num_files=5, num_records_per_file=10)
dataset = dataset_ops.Dataset.list_files(self._filenames, shuffle=False)
dataset = dataset.apply(
testing.assert_next(["Shard", "FlatMap", "Batch", "Rebatch"]))
dataset = dataset.flat_map(core_readers.TFRecordDataset)
dataset = dataset.batch(5)
dataset = distribute._LegacyRebatchDataset(dataset, num_replicas=5)
dataset = distribute._AutoShardDataset(dataset, 5, 3)
expected = [[self._record(3, i)] for i in range(10)]
self.assertDatasetProduces(dataset, expected)
@combinations.generate(test_base.default_test_combinations())
def testFileShardingWithRebatch(self):
# Tests that RebatchDatasetV2 is a passthrough op.
self._setUpFiles(num_files=3, num_records_per_file=5)
dataset = dataset_ops.Dataset.list_files(self._filenames, shuffle=False)
dataset = dataset.apply(
testing.assert_next(["Shard", "FlatMap", "Batch", "Rebatch"]))
dataset = dataset.flat_map(core_readers.TFRecordDataset)
dataset = dataset.batch(5)
dataset = dataset.rebatch(batch_size=[2, 1, 2])
dataset = distribute._AutoShardDataset(dataset, 3, 1)
expected = [[self._record(1, 0), self._record(1, 1)], [self._record(1, 2)],
[self._record(1, 3), self._record(1, 4)]]
self.assertDatasetProduces(dataset, expected)
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.times(
combinations.combine(sharding_policy=[
options_lib.AutoShardPolicy.DATA,
options_lib.AutoShardPolicy.AUTO
]), combinations.combine(with_prefetch=[True, False]))))
def testUseLegacyRebatchWithDataSharding(self, sharding_policy,
with_prefetch):
# This test simulates a distributed environment with 3 workers, each with
# 1 replica.
dataset = dataset_ops.Dataset.range(8)
dataset = dataset.batch(4)
options = options_lib.Options()
options.experimental_distribute.auto_shard_policy = sharding_policy
dataset = dataset.with_options(options)
# We expect the auto-shard rewrite to rewrite RebatchDatasetV2 to
# RebatchDataset(V1) for correctness reasons. This will modify the output
# of the dataset.
worker_a_dataset = dataset.rebatch(batch_size=[2, 1, 1])
if with_prefetch:
worker_a_dataset = worker_a_dataset.prefetch(1)
worker_a_dataset = distribute._AutoShardDataset(
worker_a_dataset, 3, 0, num_replicas=3)
expected = [[0, 1], [4, 5]]
self.assertDatasetProduces(worker_a_dataset, expected)
worker_b_dataset = dataset.rebatch(batch_size=[1, 1, 2])
if with_prefetch:
worker_b_dataset = worker_b_dataset.prefetch(1)
worker_b_dataset = distribute._AutoShardDataset(
worker_b_dataset, 3, 1, num_replicas=3)
expected = [[2, 3], [6, 7]]
self.assertDatasetProduces(worker_b_dataset, expected)
worker_c_dataset = dataset.rebatch(batch_size=[1, 2, 1])
if with_prefetch:
worker_c_dataset = worker_c_dataset.prefetch(1)
worker_c_dataset = distribute._AutoShardDataset(
worker_c_dataset, 3, 2, num_replicas=3)
expected = [[], []]
self.assertDatasetProduces(worker_c_dataset, expected)
| AutoShardWithRebatchDatasetTest |
python | Lightning-AI__lightning | tests/tests_pytorch/checkpointing/test_model_checkpoint.py | {
"start": 40860,
"end": 41062
} | class ____(Callback):
def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx):
if batch_idx == 1:
raise RuntimeError("Trouble!")
| TroubledCallbackOnTrainBatchEnd |
python | celery__celery | t/smoke/tests/failover/test_broker_failover.py | {
"start": 1077,
"end": 2451
} | class ____:
def test_killing_first_broker(self, celery_setup: CeleryTestSetup):
assert len(celery_setup.broker_cluster) > 1
celery_setup.broker.kill()
expected = "test_broker_failover"
res = identity.s(expected).apply_async(queue=celery_setup.worker.worker_queue)
assert res.get(timeout=RESULT_TIMEOUT) == expected
def test_reconnect_to_main(self, celery_setup: CeleryTestSetup):
assert len(celery_setup.broker_cluster) > 1
celery_setup.broker_cluster[0].kill()
expected = "test_broker_failover"
res = identity.s(expected).apply_async(queue=celery_setup.worker.worker_queue)
assert res.get(timeout=RESULT_TIMEOUT) == expected
celery_setup.broker_cluster[1].kill()
celery_setup.broker_cluster[0].restart()
res = identity.s(expected).apply_async(queue=celery_setup.worker.worker_queue)
assert res.get(timeout=RESULT_TIMEOUT) == expected
def test_broker_failover_ui(self, celery_setup: CeleryTestSetup):
assert len(celery_setup.broker_cluster) > 1
celery_setup.broker_cluster[0].kill()
celery_setup.worker.assert_log_exists("Will retry using next failover.")
celery_setup.worker.assert_log_exists(
f"Connected to amqp://guest:**@{celery_setup.broker_cluster[1].hostname()}:5672//"
)
| test_broker_failover |
python | encode__starlette | starlette/datastructures.py | {
"start": 6505,
"end": 6988
} | class ____:
"""
Holds a string value that should not be revealed in tracebacks etc.
You should cast the value to `str` at the point it is required.
"""
def __init__(self, value: str):
self._value = value
def __repr__(self) -> str:
class_name = self.__class__.__name__
return f"{class_name}('**********')"
def __str__(self) -> str:
return self._value
def __bool__(self) -> bool:
return bool(self._value)
| Secret |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/triggers/bigquery.py | {
"start": 16012,
"end": 23271
} | class ____(BigQueryInsertJobTrigger):
"""
BigQueryIntervalCheckTrigger run on the trigger worker, inherits from BigQueryInsertJobTrigger class.
:param conn_id: Reference to google cloud connection id
:param first_job_id: The ID of the job 1 performed
:param second_job_id: The ID of the job 2 performed
:param project_id: Google Cloud Project where the job is running
:param dataset_id: The dataset ID of the requested table. (templated)
:param table: table name
:param metrics_thresholds: dictionary of ratios indexed by metrics
:param location: The dataset location.
:param date_filter_column: column name. (templated)
:param days_back: number of days between ds and the ds we want to check against. (templated)
:param ratio_formula: ration formula. (templated)
:param ignore_zero: boolean value to consider zero or not. (templated)
:param table_id: The table ID of the requested table. (templated)
:param poll_interval: polling period in seconds to check for the status. (templated)
: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. (templated)
"""
def __init__(
self,
conn_id: str,
first_job_id: str,
second_job_id: str,
project_id: str,
table: str,
metrics_thresholds: dict[str, int],
location: str | None = None,
date_filter_column: str | None = "ds",
days_back: SupportsAbs[int] = -7,
ratio_formula: str = "max_over_min",
ignore_zero: bool = True,
dataset_id: str | None = None,
table_id: str | None = None,
poll_interval: float = 4.0,
impersonation_chain: str | Sequence[str] | None = None,
):
super().__init__(
conn_id=conn_id,
job_id=first_job_id,
project_id=project_id,
location=location,
dataset_id=dataset_id,
table_id=table_id,
poll_interval=poll_interval,
impersonation_chain=impersonation_chain,
)
self.conn_id = conn_id
self.first_job_id = first_job_id
self.second_job_id = second_job_id
self.project_id = project_id
self.table = table
self.metrics_thresholds = metrics_thresholds
self.date_filter_column = date_filter_column
self.days_back = days_back
self.ratio_formula = ratio_formula
self.ignore_zero = ignore_zero
def serialize(self) -> tuple[str, dict[str, Any]]:
"""Serialize BigQueryCheckTrigger arguments and classpath."""
return (
"airflow.providers.google.cloud.triggers.bigquery.BigQueryIntervalCheckTrigger",
{
"conn_id": self.conn_id,
"first_job_id": self.first_job_id,
"second_job_id": self.second_job_id,
"project_id": self.project_id,
"table": self.table,
"metrics_thresholds": self.metrics_thresholds,
"location": self.location,
"date_filter_column": self.date_filter_column,
"days_back": self.days_back,
"ratio_formula": self.ratio_formula,
"ignore_zero": self.ignore_zero,
"impersonation_chain": self.impersonation_chain,
},
)
async def run(self) -> AsyncIterator[TriggerEvent]:
"""Get current job execution status and yields a TriggerEvent."""
hook = self._get_async_hook()
try:
while True:
first_job_response_from_hook = await hook.get_job_status(
job_id=self.first_job_id, project_id=self.project_id
)
second_job_response_from_hook = await hook.get_job_status(
job_id=self.second_job_id, project_id=self.project_id
)
if (
first_job_response_from_hook["status"] == "success"
and second_job_response_from_hook["status"] == "success"
):
first_query_results = await hook.get_job_output(
job_id=self.first_job_id, project_id=self.project_id
)
second_query_results = await hook.get_job_output(
job_id=self.second_job_id, project_id=self.project_id
)
first_records = hook.get_records(first_query_results)
second_records = hook.get_records(second_query_results)
# If empty list, then no records are available
if not first_records:
first_job_row: str | None = None
else:
# Extract only first record from the query results
first_job_row = first_records.pop(0)
# If empty list, then no records are available
if not second_records:
second_job_row: str | None = None
else:
# Extract only first record from the query results
second_job_row = second_records.pop(0)
hook.interval_check(
first_job_row,
second_job_row,
self.metrics_thresholds,
self.ignore_zero,
self.ratio_formula,
)
yield TriggerEvent(
{
"status": "success",
"message": "Job completed",
"first_row_data": first_job_row,
"second_row_data": second_job_row,
}
)
return
elif (
first_job_response_from_hook["status"] == "pending"
or second_job_response_from_hook["status"] == "pending"
):
self.log.info("Query is still running...")
self.log.info("Sleeping for %s seconds.", self.poll_interval)
await asyncio.sleep(self.poll_interval)
else:
yield TriggerEvent(
{"status": "error", "message": second_job_response_from_hook["message"], "data": None}
)
return
except Exception as e:
self.log.exception("Exception occurred while checking for query completion")
yield TriggerEvent({"status": "error", "message": str(e)})
| BigQueryIntervalCheckTrigger |
python | django__django | tests/staticfiles_tests/storage.py | {
"start": 204,
"end": 594
} | class ____(storage.Storage):
"""
A storage class that implements get_modified_time() but raises
NotImplementedError for path().
"""
def _save(self, name, content):
return "dummy"
def delete(self, name):
pass
def exists(self, name):
pass
def get_modified_time(self, name):
return datetime(1970, 1, 1, tzinfo=UTC)
| DummyStorage |
python | getsentry__sentry | src/bitfield/types.py | {
"start": 2657,
"end": 6742
} | class ____:
"""
Represents an array of bits, each as a ``Bit`` object.
"""
def __init__(self, value, keys, labels=None):
# TODO: change to bitarray?
if value:
self._value = int(value)
else:
self._value = 0
self._keys = keys
self._labels = labels is not None and labels or keys
def __eq__(self, other):
if not isinstance(other, BitHandler):
return False
return self._value == other._value
def __lt__(self, other):
return int(self._value) < other
def __le__(self, other):
return int(self._value) <= other
def __gt__(self, other):
return int(self._value) > other
def __ge__(self, other):
return int(self._value) >= other
def __cmp__(self, other):
return cmp(self._value, other)
def __repr__(self) -> str:
return "<{}: {}>".format(
self.__class__.__name__,
", ".join(f"{k}={self.get_bit(n).is_set}" for n, k in enumerate(self._keys)),
)
def __str__(self) -> str:
return str(self._value)
def __int__(self):
return self._value
def __bool__(self):
return bool(self._value)
def __and__(self, value):
return BitHandler(self._value & int(value), self._keys)
def __or__(self, value):
return BitHandler(self._value | int(value), self._keys)
def __add__(self, value):
return BitHandler(self._value + int(value), self._keys)
def __sub__(self, value):
return BitHandler(self._value - int(value), self._keys)
def __lshift__(self, value):
return BitHandler(self._value << int(value), self._keys)
def __rshift__(self, value):
return BitHandler(self._value >> int(value), self._keys)
def __xor__(self, value):
return BitHandler(self._value ^ int(value), self._keys)
def __contains__(self, key):
bit_number = self._keys.index(key)
return bool(self.get_bit(bit_number))
def __getattr__(self, key):
if key.startswith("_"):
return object.__getattribute__(self, key)
if key not in self._keys:
raise AttributeError("%s is not a valid flag" % key)
return self.get_bit(self._keys.index(key))
__getitem__ = __getattr__
def __setattr__(self, key, value) -> None:
if key.startswith("_"):
return object.__setattr__(self, key, value)
if key not in self._keys:
raise AttributeError("%s is not a valid flag" % key)
self.set_bit(self._keys.index(key), value)
__setitem__ = __setattr__
def __iter__(self):
return self.iteritems()
def __sentry__(self):
return repr(self)
def _get_mask(self):
return self._value
mask = property(_get_mask)
def evaluate(self, evaluator, qn, connection):
return self.mask, []
def get_bit(self, bit_number):
mask = 2 ** int(bit_number)
return Bit(bit_number, self._value & mask != 0)
def set_bit(self, bit_number, true_or_false):
mask = 2 ** int(bit_number)
if true_or_false:
self._value |= mask
else:
self._value &= ~mask
return Bit(bit_number, self._value & mask != 0)
def keys(self):
return self._keys
def iterkeys(self):
return iter(self._keys)
def items(self):
return list(self.iteritems())
def iteritems(self):
for k in self._keys:
yield (k, getattr(self, k).is_set)
def get_label(self, flag):
if isinstance(flag, str):
flag = self._keys.index(flag)
if isinstance(flag, Bit):
flag = flag.number
return self._labels[flag]
# We need to register adapters in Django 1.8 in order to prevent
# "ProgrammingError: can't adapt type"
import psycopg2.extensions
psycopg2.extensions.register_adapter(Bit, lambda x: psycopg2.extensions.AsIs(int(x)))
psycopg2.extensions.register_adapter(BitHandler, lambda x: psycopg2.extensions.AsIs(int(x)))
| BitHandler |
python | buildout__buildout | src/zc/buildout/easy_install.py | {
"start": 65817,
"end": 66505
} | class ____(zc.buildout.UserError):
def __init__(self, err, ws):
ws = list(ws)
ws.sort()
self.err, self.ws = err, ws
def __str__(self):
result = ["There is a version conflict."]
if len(self.err.args) == 2:
existing_dist, req = self.err.args
result.append("We already have: %s" % existing_dist)
for dist in self.ws:
if req in dist.requires():
result.append("but %s requires %r." % (dist, str(req)))
else:
# The error argument is already a nice error string.
result.append(self.err.args[0])
return '\n'.join(result)
| VersionConflict |
python | huggingface__transformers | src/transformers/models/xlm/modeling_xlm.py | {
"start": 4789,
"end": 6084
} | class ____(nn.Module):
"""
Compute SQuAD start logits from sequence hidden states.
Args:
config ([`XLMConfig`]):
The config used by the model, will be used to grab the `hidden_size` of the model.
"""
def __init__(self, config: XLMConfig):
super().__init__()
self.dense = nn.Linear(config.hidden_size, 1)
def forward(
self, hidden_states: torch.FloatTensor, p_mask: Optional[torch.FloatTensor] = None
) -> torch.FloatTensor:
"""
Args:
hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
The final hidden states of the model.
p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*):
Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
should be masked.
Returns:
`torch.FloatTensor`: The start logits for SQuAD.
"""
x = self.dense(hidden_states).squeeze(-1)
if p_mask is not None:
if p_mask.dtype == torch.float16:
x = x * (1 - p_mask) - 65500 * p_mask
else:
x = x * (1 - p_mask) - 1e30 * p_mask
return x
| XLMPoolerStartLogits |
python | huggingface__transformers | tests/models/parakeet/test_modeling_parakeet.py | {
"start": 8880,
"end": 11406
} | class ____(ModelTesterMixin, unittest.TestCase):
all_model_classes = (ParakeetForCTC,) if is_torch_available() else ()
pipeline_model_mapping = (
{
"feature-extraction": ParakeetEncoder,
"automatic-speech-recognition": ParakeetForCTC,
}
if is_torch_available()
else {}
)
test_attention_outputs = False
test_resize_embeddings = False
test_torch_exportable = True
_is_composite = True
def setUp(self):
self.model_tester = ParakeetForCTCModelTester(self)
self.config_tester = ConfigTester(self, config_class=ParakeetCTCConfig)
def test_config(self):
self.config_tester.run_common_tests()
def test_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*config_and_inputs)
@unittest.skip(reason="ParakeetEncoder does not use inputs_embeds")
def test_model_get_set_embeddings(self):
pass
# Original function assumes vision+text model, so overwrite since Parakeet is audio+text
# Below is modified from `tests/models/granite_speech/test_modeling_granite_speech.py`
def test_sdpa_can_dispatch_composite_models(self):
if not self.has_attentions:
self.skipTest(reason="Model architecture does not support attentions")
if not self._is_composite:
self.skipTest(f"{self.all_model_classes[0].__name__} does not support SDPA")
for model_class in self.all_model_classes:
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
model = model_class(config)
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(tmpdirname)
model_sdpa = model_class.from_pretrained(tmpdirname)
model_sdpa = model_sdpa.eval().to(torch_device)
model_eager = model_class.from_pretrained(tmpdirname, attn_implementation="eager")
model_eager = model_eager.eval().to(torch_device)
self.assertTrue(model_eager.config._attn_implementation == "eager")
for name, submodule in model_eager.named_modules():
class_name = submodule.__class__.__name__
if "SdpaAttention" in class_name or "SdpaSelfAttention" in class_name:
raise ValueError("The eager model should not have SDPA attention layers")
@require_torch
| ParakeetForCTCModelTest |
python | Pylons__pyramid | tests/test_config/test_views.py | {
"start": 148329,
"end": 148521
} | class ____:
__view_defaults__ = {'containment': 'tests.test_config.IDummy'}
def __init__(self, request):
pass
def __call__(self):
return 'OK'
| DummyViewDefaultsClass |
python | huggingface__transformers | src/transformers/models/deepseek_vl/modeling_deepseek_vl.py | {
"start": 3492,
"end": 5007
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss (for next-token prediction).
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
`past_key_values` input) to speed up sequential decoding.
image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
sequence_length, hidden_size)`.
image_hidden_states of the model produced by the vision encoder, and optionally by the perceiver
"""
loss: Optional[torch.FloatTensor] = None
logits: Optional[torch.FloatTensor] = None
past_key_values: Optional[Cache] = None
hidden_states: Optional[tuple[torch.FloatTensor]] = None
attentions: Optional[tuple[torch.FloatTensor]] = None
image_hidden_states: Optional[tuple[torch.FloatTensor]] = None
| DeepseekVLCausalLMOutputWithPast |
python | huggingface__transformers | src/transformers/models/mm_grounding_dino/configuration_mm_grounding_dino.py | {
"start": 1405,
"end": 14486
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`MMGroundingDinoModel`]. It is used to instantiate a
MM Grounding DINO 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 MM Grounding DINO tiny architecture
[openmmlab-community/mm_grounding_dino_tiny_o365v1_goldg_v3det](https://huggingface.co/openmmlab-community/mm_grounding_dino_tiny_o365v1_goldg_v3det).
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
backbone_config (`PreTrainedConfig` or `dict`, *optional*, defaults to `ResNetConfig()`):
The configuration of the backbone model.
backbone (`str`, *optional*):
Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this
will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone`
is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights.
use_pretrained_backbone (`bool`, *optional*, defaults to `False`):
Whether to use pretrained weights for the backbone.
use_timm_backbone (`bool`, *optional*, defaults to `False`):
Whether to load `backbone` from the timm library. If `False`, the backbone is loaded from the transformers
library.
backbone_kwargs (`dict`, *optional*):
Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set.
text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `BertConfig`):
The config object or dictionary of the text backbone.
num_queries (`int`, *optional*, defaults to 900):
Number of object queries, i.e. detection slots. This is the maximal number of objects
[`MMGroundingDinoModel`] can detect in a single image.
encoder_layers (`int`, *optional*, defaults to 6):
Number of encoder layers.
encoder_ffn_dim (`int`, *optional*, defaults to 2048):
Dimension of the "intermediate" (often named feed-forward) layer in decoder.
encoder_attention_heads (`int`, *optional*, defaults to 8):
Number of attention heads for each attention layer in the Transformer encoder.
decoder_layers (`int`, *optional*, defaults to 6):
Number of decoder layers.
decoder_ffn_dim (`int`, *optional*, defaults to 2048):
Dimension of the "intermediate" (often named feed-forward) layer in decoder.
decoder_attention_heads (`int`, *optional*, defaults to 8):
Number of attention heads for each attention layer in the Transformer decoder.
is_encoder_decoder (`bool`, *optional*, defaults to `True`):
Whether the model is used as an encoder/decoder or not.
activation_function (`str` or `function`, *optional*, defaults to `"relu"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"silu"` and `"gelu_new"` are supported.
d_model (`int`, *optional*, defaults to 256):
Dimension of the layers.
dropout (`float`, *optional*, defaults to 0.1):
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
activation_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for activations inside the fully connected layer.
auxiliary_loss (`bool`, *optional*, defaults to `False`):
Whether auxiliary decoding losses (loss at each decoder layer) are to be used.
position_embedding_type (`str`, *optional*, defaults to `"sine"`):
Type of position embeddings to be used on top of the image features. One of `"sine"` or `"learned"`.
num_feature_levels (`int`, *optional*, defaults to 4):
The number of input feature levels.
encoder_n_points (`int`, *optional*, defaults to 4):
The number of sampled keys in each feature level for each attention head in the encoder.
decoder_n_points (`int`, *optional*, defaults to 4):
The number of sampled keys in each feature level for each attention head in the decoder.
two_stage (`bool`, *optional*, defaults to `True`):
Whether to apply a two-stage deformable DETR, where the region proposals are also generated by a variant of
Grounding DINO, which are further fed into the decoder for iterative bounding box refinement.
class_cost (`float`, *optional*, defaults to 1.0):
Relative weight of the classification error in the Hungarian matching cost.
bbox_cost (`float`, *optional*, defaults to 5.0):
Relative weight of the L1 error of the bounding box coordinates in the Hungarian matching cost.
giou_cost (`float`, *optional*, defaults to 2.0):
Relative weight of the generalized IoU loss of the bounding box in the Hungarian matching cost.
bbox_loss_coefficient (`float`, *optional*, defaults to 5.0):
Relative weight of the L1 bounding box loss in the object detection loss.
giou_loss_coefficient (`float`, *optional*, defaults to 2.0):
Relative weight of the generalized IoU loss in the object detection loss.
focal_alpha (`float`, *optional*, defaults to 0.25):
Alpha parameter in the focal loss.
disable_custom_kernels (`bool`, *optional*, defaults to `False`):
Disable the use of custom CUDA and CPU kernels. This option is necessary for the ONNX export, as custom
kernels are not supported by PyTorch ONNX export.
max_text_len (`int`, *optional*, defaults to 256):
The maximum length of the text input.
text_enhancer_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for the text enhancer.
fusion_droppath (`float`, *optional*, defaults to 0.1):
The droppath ratio for the fusion module.
fusion_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for the fusion module.
embedding_init_target (`bool`, *optional*, defaults to `True`):
Whether to initialize the target with Embedding weights.
query_dim (`int`, *optional*, defaults to 4):
The dimension of the query vector.
positional_embedding_temperature (`float`, *optional*, defaults to 20):
The temperature for Sine Positional Embedding that is used together with vision backbone.
init_std (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
The epsilon used by the layer normalization layers.
Examples:
```python
>>> from transformers import MMGroundingDinoConfig, MMGroundingDinoModel
>>> # Initializing a MM Grounding DINO configuration
>>> configuration = MMGroundingDinoConfig()
>>> # Initializing a model (with random weights) from the configuration
>>> model = MMGroundingDinoModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "mm-grounding-dino"
sub_configs = {"backbone_config": AutoConfig, "text_config": AutoConfig}
attribute_map = {
"hidden_size": "d_model",
"num_attention_heads": "encoder_attention_heads",
}
def __init__(
self,
backbone_config=None,
backbone=None,
use_pretrained_backbone=False,
use_timm_backbone=False,
backbone_kwargs=None,
text_config=None,
num_queries=900,
encoder_layers=6,
encoder_ffn_dim=2048,
encoder_attention_heads=8,
decoder_layers=6,
decoder_ffn_dim=2048,
decoder_attention_heads=8,
is_encoder_decoder=True,
activation_function="relu",
d_model=256,
dropout=0.1,
attention_dropout=0.0,
activation_dropout=0.0,
auxiliary_loss=False,
position_embedding_type="sine",
num_feature_levels=4,
encoder_n_points=4,
decoder_n_points=4,
two_stage=True,
class_cost=1.0,
bbox_cost=5.0,
giou_cost=2.0,
bbox_loss_coefficient=5.0,
giou_loss_coefficient=2.0,
focal_alpha=0.25,
disable_custom_kernels=False,
# other parameters
max_text_len=256,
text_enhancer_dropout=0.0,
fusion_droppath=0.1,
fusion_dropout=0.0,
embedding_init_target=True,
query_dim=4,
positional_embedding_temperature=20,
init_std=0.02,
layer_norm_eps=1e-5,
**kwargs,
):
if backbone_config is None and backbone is None:
logger.info("`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.")
backbone_config = CONFIG_MAPPING["swin"](
window_size=7,
image_size=224,
embed_dim=96,
depths=[2, 2, 6, 2],
num_heads=[3, 6, 12, 24],
out_indices=[2, 3, 4],
)
elif isinstance(backbone_config, dict):
backbone_model_type = backbone_config.pop("model_type")
config_class = CONFIG_MAPPING[backbone_model_type]
backbone_config = config_class.from_dict(backbone_config)
verify_backbone_config_arguments(
use_timm_backbone=use_timm_backbone,
use_pretrained_backbone=use_pretrained_backbone,
backbone=backbone,
backbone_config=backbone_config,
backbone_kwargs=backbone_kwargs,
)
if text_config is None:
text_config = {}
logger.info("text_config is None. Initializing the text config with default values (`BertConfig`).")
self.backbone_config = backbone_config
self.backbone = backbone
self.use_pretrained_backbone = use_pretrained_backbone
self.use_timm_backbone = use_timm_backbone
self.backbone_kwargs = backbone_kwargs
self.num_queries = num_queries
self.d_model = d_model
self.encoder_ffn_dim = encoder_ffn_dim
self.encoder_layers = encoder_layers
self.encoder_attention_heads = encoder_attention_heads
self.decoder_ffn_dim = decoder_ffn_dim
self.decoder_layers = decoder_layers
self.decoder_attention_heads = decoder_attention_heads
self.dropout = dropout
self.attention_dropout = attention_dropout
self.activation_dropout = activation_dropout
self.activation_function = activation_function
self.auxiliary_loss = auxiliary_loss
self.position_embedding_type = position_embedding_type
# deformable attributes
self.num_feature_levels = num_feature_levels
self.encoder_n_points = encoder_n_points
self.decoder_n_points = decoder_n_points
self.two_stage = two_stage
# Hungarian matcher
self.class_cost = class_cost
self.bbox_cost = bbox_cost
self.giou_cost = giou_cost
# Loss coefficients
self.bbox_loss_coefficient = bbox_loss_coefficient
self.giou_loss_coefficient = giou_loss_coefficient
self.focal_alpha = focal_alpha
self.disable_custom_kernels = disable_custom_kernels
# Text backbone
if isinstance(text_config, dict):
text_config["model_type"] = text_config.get("model_type", "bert")
text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
elif text_config is None:
text_config = CONFIG_MAPPING["bert"]()
self.text_config = text_config
self.max_text_len = max_text_len
# Text Enhancer
self.text_enhancer_dropout = text_enhancer_dropout
# Fusion
self.fusion_droppath = fusion_droppath
self.fusion_dropout = fusion_dropout
# Others
self.embedding_init_target = embedding_init_target
self.query_dim = query_dim
self.positional_embedding_temperature = positional_embedding_temperature
self.init_std = init_std
self.layer_norm_eps = layer_norm_eps
super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)
self.tie_encoder_decoder = True
__all__ = ["MMGroundingDinoConfig"]
| MMGroundingDinoConfig |
python | ray-project__ray | rllib/models/tests/test_catalog.py | {
"start": 2169,
"end": 2329
} | class ____(MultiActionDistribution):
@override(MultiActionDistribution)
def entropy(self):
raise NotImplementedError
| CustomMultiActionDistribution |
python | ethereum__web3.py | web3/_utils/module_testing/net_module.py | {
"start": 676,
"end": 1296
} | class ____:
@pytest.mark.asyncio
async def test_net_version(self, async_w3: "AsyncWeb3[Any]") -> None:
version = await async_w3.net.version
assert is_string(version)
assert version.isdigit()
@pytest.mark.asyncio
async def test_net_listening(self, async_w3: "AsyncWeb3[Any]") -> None:
listening = await async_w3.net.listening
assert is_boolean(listening)
@pytest.mark.asyncio
async def test_net_peer_count(self, async_w3: "AsyncWeb3[Any]") -> None:
peer_count = await async_w3.net.peer_count
assert is_integer(peer_count)
| AsyncNetModuleTest |
python | bokeh__bokeh | src/bokeh/protocol/messages/push_doc.py | {
"start": 1596,
"end": 2786
} | class ____(Message[PushDoc]):
''' Define the ``PUSH-DOC`` message for pushing Documents from clients to a
Bokeh server.
The ``content`` fragment of for this message is has the form:
.. code-block:: python
{
'doc' : <Document JSON>
}
'''
msgtype = 'PUSH-DOC'
@classmethod
def create(cls, document: Document, **metadata: Any) -> push_doc:
'''
'''
header = cls.create_header()
content = PushDoc(doc=document.to_json())
msg = cls(header, metadata, content)
return msg
def push_to_document(self, doc: Document) -> None:
'''
Raises:
ProtocolError
'''
if 'doc' not in self.content:
raise ProtocolError("No doc in PUSH-DOC")
doc.replace_with_json(self.content['doc'])
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
| push_doc |
python | pytorch__pytorch | torch/_dynamo/source.py | {
"start": 21672,
"end": 23068
} | class ____(ChainedSource):
idx_key: Union[int, str]
is_kw: bool = False
field: str = dataclasses.field(init=False, repr=False, compare=False)
_name: str = dataclasses.field(init=False, repr=False, compare=False)
def __post_init__(self) -> None:
assert self.base, (
"Base must be a valid source in order to properly track and guard this Defaults to its origin."
)
if self.is_kw:
assert isinstance(self.idx_key, str)
object.__setattr__(self, "field", "__kwdefaults__")
object.__setattr__(
self, "_name", f"{self.base.name()}.{self.field}['{self.idx_key}']"
)
else:
assert isinstance(self.idx_key, int)
object.__setattr__(self, "field", "__defaults__")
object.__setattr__(
self, "_name", f"{self.base.name()}.{self.field}[{self.idx_key}]"
)
def reconstruct(self, codegen: "PyCodegen") -> None:
codegen(self.base)
codegen.extend_output(codegen.create_load_attrs(self.field))
codegen.append_output(codegen.create_load_const(self.idx_key))
codegen.append_output(create_binary_subscr())
def guard_source(self) -> GuardSource:
return self.base.guard_source()
def name(self) -> str:
return self._name
@dataclasses.dataclass(frozen=True)
| DefaultsSource |
python | huggingface__transformers | src/transformers/models/seggpt/modeling_seggpt.py | {
"start": 9416,
"end": 16183
} | class ____(nn.Module):
"""Multi-head Attention block with relative position embeddings."""
def __init__(self, config):
super().__init__()
image_size, patch_size = config.image_size, config.patch_size
image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
input_size = (image_size[0] // config.patch_size, image_size[1] // config.patch_size)
head_dim = config.hidden_size // config.num_attention_heads
self.num_attention_heads = config.num_attention_heads
self.scale = head_dim**-0.5
self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=config.qkv_bias)
self.proj = nn.Linear(config.hidden_size, config.hidden_size)
self.use_relative_position_embeddings = config.use_relative_position_embeddings
if self.use_relative_position_embeddings:
if input_size is None:
raise ValueError("Input size must be provided if using relative positional encoding.")
# initialize relative positional embeddings
self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))
self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))
def get_rel_pos(self, q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:
"""
Get relative positional embeddings according to the relative positions of
query and key sizes.
Args:
q_size (int):
size of the query.
k_size (int):
size of key k.
rel_pos (`torch.Tensor`):
relative position embeddings (L, channel).
Returns:
Extracted positional embeddings according to relative positions.
"""
max_rel_dist = int(2 * max(q_size, k_size) - 1)
# Interpolate rel pos.
rel_pos_resized = F.interpolate(
rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1),
size=max_rel_dist,
mode="linear",
)
rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)
# Scale the coords with short length if shapes for q and k are different.
q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0)
k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0)
relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
return rel_pos_resized[relative_coords.long()]
def add_decomposed_rel_pos(
self,
attn: torch.Tensor,
query: torch.Tensor,
rel_pos_h: torch.Tensor,
rel_pos_w: torch.Tensor,
q_size: tuple[int, int],
k_size: tuple[int, int],
) -> torch.Tensor:
"""
Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.
https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py
Args:
attn (`torch.Tensor`):
attention map.
query (`torch.Tensor`):
query q in the attention layer with shape (batch_size, query_height * query_width, channel).
rel_pos_h (`torch.Tensor`):
relative position embeddings (Lh, channel) for height axis.
rel_pos_w (`torch.Tensor`):
relative position embeddings (Lw, channel) for width axis.
q_size (tuple):
spatial sequence size of query q with (query_height, query_width).
k_size (tuple):
spatial sequence size of key k with (key_height, key_width).
Returns:
attn (`torch.Tensor`):
attention map with added relative positional embeddings.
"""
query_height, query_width = q_size
key_height, key_width = k_size
relative_position_height = self.get_rel_pos(query_height, key_height, rel_pos_h)
relative_position_width = self.get_rel_pos(query_width, key_width, rel_pos_w)
batch_size, _, dim = query.shape
reshaped_query = query.reshape(batch_size, query_height, query_width, dim)
rel_h = torch.einsum("bhwc,hkc->bhwk", reshaped_query, relative_position_height)
rel_w = torch.einsum("bhwc,wkc->bhwk", reshaped_query, relative_position_width)
attn = attn.reshape(batch_size, query_height, query_width, key_height, key_width)
attn = attn + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]
attn = attn.reshape(batch_size, query_height * query_width, key_height * key_width)
return attn
def forward(self, hidden_states: torch.Tensor, output_attentions=False) -> torch.Tensor:
batch_size, height, width, _ = hidden_states.shape
# qkv with shape (3, batch_size, nHead, height * width, channel)
qkv = (
self.qkv(hidden_states)
.reshape(batch_size, height * width, 3, self.num_attention_heads, -1)
.permute(2, 0, 3, 1, 4)
)
# q, k, v with shape (batch_size * nHead, height * width, channel)
query, key, value = qkv.reshape(3, batch_size * self.num_attention_heads, height * width, -1).unbind(0)
attn_weights = (query * self.scale) @ key.transpose(-2, -1)
if self.use_relative_position_embeddings:
attn_weights = self.add_decomposed_rel_pos(
attn_weights, query, self.rel_pos_h, self.rel_pos_w, (height, width), (height, width)
)
attn_weights = torch.nn.functional.softmax(attn_weights, dtype=torch.float32, dim=-1).to(query.dtype)
if output_attentions:
# this operation is a bit awkward, but it's required to
# make sure that attn_weights keeps its gradient.
# In order to do so, attn_weights have to reshaped
# twice and have to be reused in the following
attn_weights_reshaped = attn_weights.view(batch_size, self.num_attention_heads, height * width, -1)
attn_weights = attn_weights_reshaped.view(batch_size * self.num_attention_heads, height * width, -1)
else:
attn_weights_reshaped = None
attn_output = (attn_weights @ value).reshape(batch_size, self.num_attention_heads, height, width, -1)
attn_output = attn_output.permute(0, 2, 3, 1, 4).reshape(batch_size, height, width, -1)
attn_output = self.proj(attn_output)
return (attn_output, attn_weights_reshaped)
# Copied from transformers.models.sam.modeling_sam.SamMLPBlock with SamMLPBlock->SegGptMlp
| SegGptAttention |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.