language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
PyCQA__pylint
tests/functional/a/abstract/abstract_class_instantiated.py
{ "start": 808, "end": 856 }
class ____(SecondBadClass): pass
ThirdBadClass
python
getsentry__sentry
tests/sentry/integrations/slack/webhooks/commands/test_link_user.py
{ "start": 1337, "end": 2171 }
class ____(SlackCommandsTest): """Slash commands results are generated on Region Silo""" @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_link_command(self, mock_record: MagicMock) -> None: data = self.send_slack_message("link") assert "Link your Slack identity" in get_response_text(data) assert_slo_metric(mock_record, EventLifecycleOutcome.SUCCESS) @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_link_command_already_linked(self, mock_record: MagicMock) -> None: self.link_user() data = self.send_slack_message("link") assert "You are already linked as" in get_response_text(data) assert_slo_metric(mock_record, EventLifecycleOutcome.SUCCESS) @control_silo_test
SlackCommandsLinkUserTest
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/extra/ghostwriter.py
{ "start": 36416, "end": 73249 }
class ____(NamedTuple): type_name: str imports: set[str] def _parameters_to_annotation_name( parameters: Iterable[Any] | None, imports: ImportSet ) -> str | None: if parameters is None: return None annotations = tuple( annotation for annotation in map(_parameter_to_annotation, parameters) if annotation is not None ) if not annotations: return None if len(annotations) == 1: type_name, new_imports = annotations[0] imports.update(new_imports) return type_name joined = _join_generics(("typing.Union", {"typing"}), annotations) if joined is None: return None imports.update(joined.imports) return joined.type_name def _join_generics( origin_type_data: tuple[str, set[str]] | None, annotations: Iterable[_AnnotationData | None], ) -> _AnnotationData | None: if origin_type_data is None: return None # because typing.Optional is converted to a Union, it also contains None # since typing.Optional only accepts one type variable, we need to remove it if origin_type_data is not None and origin_type_data[0] == "typing.Optional": annotations = ( annotation for annotation in annotations if annotation is None or annotation.type_name != "None" ) origin_type, imports = origin_type_data joined = _join_argument_annotations(annotations) if joined is None or not joined[0]: return None arg_types, new_imports = joined imports.update(new_imports) return _AnnotationData("{}[{}]".format(origin_type, ", ".join(arg_types)), imports) def _join_argument_annotations( annotations: Iterable[_AnnotationData | None], ) -> tuple[list[str], set[str]] | None: imports: set[str] = set() arg_types: list[str] = [] for annotation in annotations: if annotation is None: return None arg_types.append(annotation.type_name) imports.update(annotation.imports) return arg_types, imports def _parameter_to_annotation(parameter: Any) -> _AnnotationData | None: # if a ForwardRef could not be resolved if isinstance(parameter, str): return None if isinstance(parameter, ForwardRef): if sys.version_info[:2] < (3, 14): forwarded_value = parameter.__forward_value__ if forwarded_value is None: return None else: # ForwardRef.__forward_value__ was removed in 3.14 in favor of # ForwardRef.evaluate(). See also PEP 649, PEP 749, and # typing.evaluate_forward_ref. # # .evaluate() with Format.VALUE (the default) throws if the name # could not be resolved. # https://docs.python.org/3.14/library/annotationlib.html#annotationlib.ForwardRef.evaluate try: forwarded_value = parameter.evaluate() except Exception: return None return _parameter_to_annotation(forwarded_value) # the arguments of Callable are in a list if isinstance(parameter, list): joined = _join_argument_annotations( _parameter_to_annotation(param) for param in parameter ) if joined is None: return None arg_type_names, new_imports = joined return _AnnotationData("[{}]".format(", ".join(arg_type_names)), new_imports) if isinstance(parameter, type): if parameter.__module__ == "builtins": return _AnnotationData( "None" if parameter.__name__ == "NoneType" else parameter.__name__, set(), ) type_name = _get_qualname(parameter, include_module=True) # the types.UnionType does not support type arguments and needs to be translated if type_name == "types.UnionType": return _AnnotationData("typing.Union", {"typing"}) else: if hasattr(parameter, "__module__") and hasattr(parameter, "__name__"): type_name = _get_qualname(parameter, include_module=True) else: type_name = str(parameter) if type_name.startswith("hypothesis.strategies."): return _AnnotationData(type_name.replace("hypothesis.strategies", "st"), set()) origin_type = get_origin(parameter) # if not generic or no generic arguments if origin_type is None or origin_type == parameter: return _AnnotationData(type_name, set(type_name.rsplit(".", maxsplit=1)[:-1])) arg_types = get_args(parameter) if {type(a) for a in arg_types} == {TypeVar}: arg_types = () # typing types get translated to classes that don't support generics origin_annotation: _AnnotationData | None if type_name.startswith("typing."): try: new_type_name = type_name[: type_name.index("[")] except ValueError: new_type_name = type_name origin_annotation = _AnnotationData(new_type_name, {"typing"}) else: origin_annotation = _parameter_to_annotation(origin_type) if arg_types: return _join_generics( origin_annotation, (_parameter_to_annotation(arg_type) for arg_type in arg_types), ) return origin_annotation def _are_annotations_used(*functions: Callable) -> bool: for function in functions: try: params = get_signature(function).parameters.values() except Exception: pass else: if any(param.annotation != inspect.Parameter.empty for param in params): return True return False def _make_test(imports: ImportSet, body: str) -> str: # Discarding "builtins." and "__main__" probably isn't particularly useful # for user code, but important for making a good impression in demos. body = body.replace("builtins.", "").replace("__main__.", "") imports |= {("hypothesis", "given"), ("hypothesis", "strategies as st")} if " reject()\n" in body: imports.add(("hypothesis", "reject")) do_not_import = {"builtins", "__main__", "hypothesis.strategies"} direct = {f"import {i}" for i in imports - do_not_import if isinstance(i, str)} from_imports = defaultdict(set) for module, name in {i for i in imports if isinstance(i, tuple)}: if not (module.startswith("hypothesis.strategies") and name in st.__all__): from_imports[module].add(name) from_ = { "from {} import {}".format(module, ", ".join(sorted(names))) for module, names in from_imports.items() if isinstance(module, str) and module not in do_not_import } header = IMPORT_SECTION.format(imports="\n".join(sorted(direct) + sorted(from_))) nothings = body.count("st.nothing()") if nothings == 1: header += "# TODO: replace st.nothing() with an appropriate strategy\n\n" elif nothings >= 1: header += "# TODO: replace st.nothing() with appropriate strategies\n\n" return black.format_str(header + body, mode=black.Mode()) def _is_probably_ufunc(obj): # See https://numpy.org/doc/stable/reference/ufuncs.html - there doesn't seem # to be an upstream function to detect this, so we just guess. has_attributes = [ "nin", "nout", "nargs", "ntypes", "types", "identity", "signature", ] return callable(obj) and all(hasattr(obj, name) for name in has_attributes) # If we have a pair of functions where one name matches the regex and the second # is the result of formatting the template with matched groups, our magic() # ghostwriter will write a roundtrip test for them. Additional patterns welcome. ROUNDTRIP_PAIRS = ( # Defined prefix, shared postfix. The easy cases. (r"write(.+)", "read{}"), (r"save(.+)", "load{}"), (r"dump(.+)", "load{}"), (r"to(.+)", "from{}"), # Known stem, maybe matching prefixes, maybe matching postfixes. (r"(.*)en(.+)", "{}de{}"), # Shared postfix, prefix only on "inverse" function (r"(.+)", "de{}"), (r"(?!safe)(.+)", "un{}"), # safe_load / unsafe_load isn't a roundtrip # a2b_postfix and b2a_postfix. Not a fan of this pattern, but it's pretty # common in code imitating an C API - see e.g. the stdlib binascii module. (r"(.+)2(.+?)(_.+)?", "{1}2{0}{2}"), # Common in e.g. the colorsys module (r"(.+)_to_(.+)", "{1}_to_{0}"), # Sockets patterns (r"(inet|if)_(.+)to(.+)", "{0}_{2}to{1}"), (r"(\w)to(\w)(.+)", "{1}to{0}{2}"), (r"send(.+)", "recv{}"), (r"send(.+)", "receive{}"), ) def _get_testable_functions(thing: object) -> dict[str, Callable]: by_name = {} if callable(thing): funcs: list[Any | None] = [thing] elif isinstance(thing, types.ModuleType): if hasattr(thing, "__all__"): funcs = [getattr(thing, name, None) for name in thing.__all__] elif hasattr(thing, "__package__"): pkg = thing.__package__ funcs = [ v for k, v in vars(thing).items() if callable(v) and not is_mock(v) and ((not pkg) or getattr(v, "__module__", pkg).startswith(pkg)) and not k.startswith("_") ] if pkg and any(getattr(f, "__module__", pkg) == pkg for f in funcs): funcs = [f for f in funcs if getattr(f, "__module__", pkg) == pkg] else: raise InvalidArgument(f"Can't test non-module non-callable {thing!r}") for f in list(funcs): if inspect.isclass(f): funcs += [ v.__get__(f) for k, v in vars(f).items() if hasattr(v, "__func__") and not is_mock(v) and not k.startswith("_") ] for f in funcs: try: if ( (not is_mock(f)) and callable(f) and _get_params(f) and not isinstance(f, enum.EnumMeta) ): if getattr(thing, "__name__", None): if inspect.isclass(thing): KNOWN_FUNCTION_LOCATIONS[f] = _get_module_helper(thing) elif isinstance(thing, types.ModuleType): KNOWN_FUNCTION_LOCATIONS[f] = thing.__name__ try: _get_params(f) by_name[_get_qualname(f, include_module=True)] = f except Exception: # usually inspect.signature on C code such as socket.inet_aton, # or Pandas 'CallableDynamicDoc' object has no attr. '__name__' pass except (TypeError, ValueError): pass return by_name def magic( *modules_or_functions: Callable | types.ModuleType, except_: Except = (), style: str = "pytest", annotate: bool | None = None, ) -> str: """Guess which ghostwriters to use, for a module or collection of functions. As for all ghostwriters, the ``except_`` argument should be an :class:`python:Exception` or tuple of exceptions, and ``style`` may be either ``"pytest"`` to write test functions or ``"unittest"`` to write test methods and :class:`~python:unittest.TestCase`. After finding the public functions attached to any modules, the ``magic`` ghostwriter looks for pairs of functions to pass to :func:`~roundtrip`, then checks for :func:`~binary_operation` and :func:`~ufunc` functions, and any others are passed to :func:`~fuzz`. For example, try :command:`hypothesis write gzip` on the command line! """ except_ = _check_except(except_) _check_style(style) if not modules_or_functions: raise InvalidArgument("Must pass at least one function or module to test.") parts = [] by_name = {} imports = set() for thing in modules_or_functions: by_name.update(found := _get_testable_functions(thing)) if (not found) and isinstance(thing, types.ModuleType): msg = f"# Found no testable functions in {thing.__name__} (from {thing.__file__!r})" mods: list = [] for k in sorted(sys.modules, key=len): if ( k.startswith(f"{thing.__name__}.") and "._" not in k.removeprefix(thing.__name__) and not k.startswith(tuple(f"{m}." for m in mods)) and _get_testable_functions(sys.modules[k]) ): mods.append(k) if mods: msg += ( f"\n# Try writing tests for submodules, e.g. by using:\n" f"# hypothesis write {' '.join(sorted(mods))}" ) parts.append(msg) if not by_name: return "\n\n".join(parts) if annotate is None: annotate = _are_annotations_used(*by_name.values()) def make_(how, *args, **kwargs): imp, body = how(*args, **kwargs, except_=except_, style=style) imports.update(imp) parts.append(body) # Look for pairs of functions that roundtrip, based on known naming patterns. for writename, readname in ROUNDTRIP_PAIRS: for name in sorted(by_name): match = re.fullmatch(writename, name.split(".")[-1]) if match: inverse_name = readname.format(*match.groups()) for other in sorted( n for n in by_name if n.split(".")[-1] == inverse_name ): make_( _make_roundtrip_body, (by_name.pop(name), by_name.pop(other)), annotate=annotate, ) break else: try: other_func = getattr( sys.modules[_get_module(by_name[name])], inverse_name, ) _get_params(other_func) # we want to skip if this fails except Exception: pass else: make_( _make_roundtrip_body, (by_name.pop(name), other_func), annotate=annotate, ) # Look for equivalent functions: same name, all required arguments of any can # be found in all signatures, and if all have return-type annotations they match. names = defaultdict(list) for _, f in sorted(by_name.items()): names[_get_qualname(f)].append(f) for group in names.values(): if len(group) >= 2 and len({frozenset(_get_params(f)) for f in group}) == 1: sentinel = object() returns = {get_type_hints(f).get("return", sentinel) for f in group} if len(returns - {sentinel}) <= 1: make_(_make_equiv_body, group, annotate=annotate) for f in group: by_name.pop(_get_qualname(f, include_module=True)) # Look for binary operators - functions with two identically-typed arguments, # and the same return type. The latter restriction might be lifted later. for name, func in sorted(by_name.items()): hints = get_type_hints(func) hints.pop("return", None) params = _get_params(func) if (len(hints) == len(params) == 2) or ( _get_module(func) == "operator" and "item" not in func.__name__ and tuple(params) in [("a", "b"), ("x", "y")] ): a, b = hints.values() or [Any, Any] arg1, arg2 = params if a == b and len(arg1) == len(arg2) <= 3: # https://en.wikipedia.org/wiki/Distributive_property#Other_examples known = { "mul": "add", "matmul": "add", "or_": "and_", "and_": "or_", }.get(func.__name__, "") distributes_over = getattr(sys.modules[_get_module(func)], known, None) make_( _make_binop_body, func, commutative=func.__name__ != "matmul", distributes_over=distributes_over, annotate=annotate, ) del by_name[name] # Look for Numpy ufuncs or gufuncs, and write array-oriented tests for them. if "numpy" in sys.modules: for name, func in sorted(by_name.items()): if _is_probably_ufunc(func): make_(_make_ufunc_body, func, annotate=annotate) del by_name[name] # For all remaining callables, just write a fuzz-test. In principle we could # guess at equivalence or idempotence; but it doesn't seem accurate enough to # be worth the trouble when it's so easy for the user to specify themselves. for _, f in sorted(by_name.items()): make_( _make_test_body, f, test_body=_write_call(f, except_=except_), ghost="fuzz", annotate=annotate, ) return _make_test(imports, "\n".join(parts)) def fuzz( func: Callable, *, except_: Except = (), style: str = "pytest", annotate: bool | None = None, ) -> str: """Write source code for a property-based test of ``func``. The resulting test checks that valid input only leads to expected exceptions. For example: .. code-block:: python from re import compile, error from hypothesis.extra import ghostwriter ghostwriter.fuzz(compile, except_=error) Gives: .. code-block:: python # This test code was written by the `hypothesis.extra.ghostwriter` module # and is provided under the Creative Commons Zero public domain dedication. import re from hypothesis import given, reject, strategies as st # TODO: replace st.nothing() with an appropriate strategy @given(pattern=st.nothing(), flags=st.just(0)) def test_fuzz_compile(pattern, flags): try: re.compile(pattern=pattern, flags=flags) except re.error: reject() Note that it includes all the required imports. Because the ``pattern`` parameter doesn't have annotations or a default argument, you'll need to specify a strategy - for example :func:`~hypothesis.strategies.text` or :func:`~hypothesis.strategies.binary`. After that, you have a test! """ if not callable(func): raise InvalidArgument(f"Got non-callable {func=}") except_ = _check_except(except_) _check_style(style) if annotate is None: annotate = _are_annotations_used(func) imports, body = _make_test_body( func, test_body=_write_call(func, except_=except_), except_=except_, ghost="fuzz", style=style, annotate=annotate, ) return _make_test(imports, body) def idempotent( func: Callable, *, except_: Except = (), style: str = "pytest", annotate: bool | None = None, ) -> str: """Write source code for a property-based test of ``func``. The resulting test checks that if you call ``func`` on it's own output, the result does not change. For example: .. code-block:: python from typing import Sequence from hypothesis.extra import ghostwriter def timsort(seq: Sequence[int]) -> Sequence[int]: return sorted(seq) ghostwriter.idempotent(timsort) Gives: .. code-block:: python # This test code was written by the `hypothesis.extra.ghostwriter` module # and is provided under the Creative Commons Zero public domain dedication. from hypothesis import given, strategies as st @given(seq=st.one_of(st.binary(), st.binary().map(bytearray), st.lists(st.integers()))) def test_idempotent_timsort(seq): result = timsort(seq=seq) repeat = timsort(seq=result) assert result == repeat, (result, repeat) """ if not callable(func): raise InvalidArgument(f"Got non-callable {func=}") except_ = _check_except(except_) _check_style(style) if annotate is None: annotate = _are_annotations_used(func) imports, body = _make_test_body( func, test_body="result = {}\nrepeat = {}".format( _write_call(func, except_=except_), _write_call(func, "result", except_=except_), ), except_=except_, assertions=_assert_eq(style, "result", "repeat"), ghost="idempotent", style=style, annotate=annotate, ) return _make_test(imports, body) def _make_roundtrip_body(funcs, except_, style, annotate): first_param = next(iter(_get_params(funcs[0]))) test_lines = [ _write_call(funcs[0], assign="value0", except_=except_), *( _write_call(f, f"value{i}", assign=f"value{i + 1}", except_=except_) for i, f in enumerate(funcs[1:]) ), ] return _make_test_body( *funcs, test_body="\n".join(test_lines), except_=except_, assertions=_assert_eq(style, first_param, f"value{len(funcs) - 1}"), ghost="roundtrip", style=style, annotate=annotate, ) def roundtrip( *funcs: Callable, except_: Except = (), style: str = "pytest", annotate: bool | None = None, ) -> str: """Write source code for a property-based test of ``funcs``. The resulting test checks that if you call the first function, pass the result to the second (and so on), the final result is equal to the first input argument. This is a *very* powerful property to test, especially when the config options are varied along with the object to round-trip. For example, try ghostwriting a test for :func:`python:json.dumps` - would you have thought of all that? .. code-block:: shell hypothesis write --roundtrip json.dumps json.loads """ if not funcs: raise InvalidArgument("Round-trip of zero functions is meaningless.") for i, f in enumerate(funcs): if not callable(f): raise InvalidArgument(f"Got non-callable funcs[{i}]={f!r}") except_ = _check_except(except_) _check_style(style) if annotate is None: annotate = _are_annotations_used(*funcs) return _make_test(*_make_roundtrip_body(funcs, except_, style, annotate)) def _get_varnames(funcs): var_names = [f"result_{f.__name__}" for f in funcs] if len(set(var_names)) < len(var_names): var_names = [f"result_{f.__name__}_{_get_module(f)}" for f in funcs] if len(set(var_names)) < len(var_names): var_names = [f"result_{i}_{f.__name__}" for i, f in enumerate(funcs)] return var_names def _make_equiv_body(funcs, except_, style, annotate): var_names = _get_varnames(funcs) test_lines = [ _write_call(f, assign=vname, except_=except_) for vname, f in zip(var_names, funcs, strict=True) ] assertions = "\n".join( _assert_eq(style, var_names[0], vname) for vname in var_names[1:] ) return _make_test_body( *funcs, test_body="\n".join(test_lines), except_=except_, assertions=assertions, ghost="equivalent", style=style, annotate=annotate, ) EQUIV_FIRST_BLOCK = """ try: {} exc_type = None target(1, label="input was valid") {}except Exception as exc: exc_type = type(exc) """.strip() EQUIV_CHECK_BLOCK = """ if exc_type: with {ctx}(exc_type): {check_raises} else: {call} {compare} """.rstrip() def _make_equiv_errors_body(funcs, except_, style, annotate): var_names = _get_varnames(funcs) first, *rest = funcs first_call = _write_call(first, assign=var_names[0], except_=except_) extra_imports, suppress = _exception_string(except_) extra_imports.add(("hypothesis", "target")) catch = f"except {suppress}:\n reject()\n" if suppress else "" test_lines = [EQUIV_FIRST_BLOCK.format(indent(first_call, prefix=" "), catch)] for vname, f in zip(var_names[1:], rest, strict=True): if style == "pytest": ctx = "pytest.raises" extra_imports.add("pytest") else: assert style == "unittest" ctx = "self.assertRaises" block = EQUIV_CHECK_BLOCK.format( ctx=ctx, check_raises=indent(_write_call(f, except_=()), " "), call=indent(_write_call(f, assign=vname, except_=()), " "), compare=indent(_assert_eq(style, var_names[0], vname), " "), ) test_lines.append(block) imports, source_code = _make_test_body( *funcs, test_body="\n".join(test_lines), except_=(), ghost="equivalent", style=style, annotate=annotate, ) return imports | extra_imports, source_code def equivalent( *funcs: Callable, allow_same_errors: bool = False, except_: Except = (), style: str = "pytest", annotate: bool | None = None, ) -> str: """Write source code for a property-based test of ``funcs``. The resulting test checks that calling each of the functions returns an equal value. This can be used as a classic 'oracle', such as testing a fast sorting algorithm against the :func:`python:sorted` builtin, or for differential testing where none of the compared functions are fully trusted but any difference indicates a bug (e.g. running a function on different numbers of threads, or simply multiple times). The functions should have reasonably similar signatures, as only the common parameters will be passed the same arguments - any other parameters will be allowed to vary. If allow_same_errors is True, then the test will pass if calling each of the functions returns an equal value, *or* if the first function raises an exception and each of the others raises an exception of the same type. This relaxed mode can be useful for code synthesis projects. """ if len(funcs) < 2: raise InvalidArgument("Need at least two functions to compare.") for i, f in enumerate(funcs): if not callable(f): raise InvalidArgument(f"Got non-callable funcs[{i}]={f!r}") check_type(bool, allow_same_errors, "allow_same_errors") except_ = _check_except(except_) _check_style(style) if annotate is None: annotate = _are_annotations_used(*funcs) if allow_same_errors and not any(issubclass(Exception, ex) for ex in except_): imports, source_code = _make_equiv_errors_body(funcs, except_, style, annotate) else: imports, source_code = _make_equiv_body(funcs, except_, style, annotate) return _make_test(imports, source_code) X = TypeVar("X") Y = TypeVar("Y") def binary_operation( func: Callable[[X, X], Y], *, associative: bool = True, commutative: bool = True, identity: X | EllipsisType | None = ..., distributes_over: Callable[[X, X], X] | None = None, except_: Except = (), style: str = "pytest", annotate: bool | None = None, ) -> str: """Write property tests for the binary operation ``func``. While :wikipedia:`binary operations <Binary_operation>` are not particularly common, they have such nice properties to test that it seems a shame not to demonstrate them with a ghostwriter. For an operator ``f``, test that: - if :wikipedia:`associative <Associative_property>`, ``f(a, f(b, c)) == f(f(a, b), c)`` - if :wikipedia:`commutative <Commutative_property>`, ``f(a, b) == f(b, a)`` - if :wikipedia:`identity <Identity_element>` is not None, ``f(a, identity) == a`` - if :wikipedia:`distributes_over <Distributive_property>` is ``+``, ``f(a, b) + f(a, c) == f(a, b+c)`` For example: .. code-block:: python ghostwriter.binary_operation( operator.mul, identity=1, distributes_over=operator.add, style="unittest", ) """ if not callable(func): raise InvalidArgument(f"Got non-callable {func=}") except_ = _check_except(except_) _check_style(style) check_type(bool, associative, "associative") check_type(bool, commutative, "commutative") if distributes_over is not None and not callable(distributes_over): raise InvalidArgument( f"{distributes_over=} must be an operation which " f"distributes over {func.__name__}" ) if not any([associative, commutative, identity, distributes_over]): raise InvalidArgument( "You must select at least one property of the binary operation to test." ) if annotate is None: annotate = _are_annotations_used(func) imports, body = _make_binop_body( func, associative=associative, commutative=commutative, identity=identity, distributes_over=distributes_over, except_=except_, style=style, annotate=annotate, ) return _make_test(imports, body) def _make_binop_body( func: Callable[[X, X], Y], *, associative: bool = True, commutative: bool = True, identity: X | EllipsisType | None = ..., distributes_over: Callable[[X, X], X] | None = None, except_: tuple[type[Exception], ...], style: str, annotate: bool, ) -> tuple[ImportSet, str]: strategies = _get_strategies(func) operands, b = (strategies.pop(p) for p in list(_get_params(func))[:2]) if repr(operands) != repr(b): operands |= b operands_name = func.__name__ + "_operands" all_imports = set() parts = [] def maker( sub_property: str, args: str, body: str, right: str | None = None, ) -> None: if right is None: assertions = "" else: body = f"{body}\n{right}" assertions = _assert_eq(style, "left", "right") imports, body = _make_test_body( func, test_body=body, ghost=sub_property + "_binary_operation", except_=except_, assertions=assertions, style=style, given_strategies={**strategies, **{n: operands_name for n in args}}, annotate=annotate, ) all_imports.update(imports) if style == "unittest": endline = "(unittest.TestCase):\n" body = body[body.index(endline) + len(endline) + 1 :] parts.append(body) if associative: maker( "associative", "abc", _write_call(func, "a", _write_call(func, "b", "c"), assign="left"), _write_call( func, _write_call(func, "a", "b"), "c", assign="right", ), ) if commutative: maker( "commutative", "ab", _write_call(func, "a", "b", assign="left"), _write_call(func, "b", "a", assign="right"), ) if identity is not None: # Guess that the identity element is the minimal example from our operands # strategy. This is correct often enough to be worthwhile, and close enough # that it's a good starting point to edit much of the rest. if identity is ...: try: identity = find(operands, lambda x: True, settings=_quietly_settings) except Exception: identity = "identity element here" # type: ignore # If the repr of this element is invalid Python, stringify it - this # can't be executed as-is, but at least makes it clear what should # happen. E.g. type(None) -> <class 'NoneType'> -> quoted. try: # We don't actually execute this code object; we're just compiling # to check that the repr is syntactically valid. HOWEVER, we're # going to output that code string into test code which will be # executed; so you still shouldn't ghostwrite for hostile code. compile(repr(identity), "<string>", "exec") except SyntaxError: identity = repr(identity) # type: ignore identity_parts = [ f"{identity = }", _assert_eq( style, "a", _write_call(func, "a", "identity"), ), _assert_eq( style, "a", _write_call(func, "identity", "a"), ), ] maker("identity", "a", "\n".join(identity_parts)) if distributes_over: do = distributes_over dist_parts = [ _write_call(func, "a", _write_call(do, "b", "c"), assign="left"), _write_call( do, _write_call(func, "a", "b"), _write_call(func, "a", "c"), assign="ldist", ), _assert_eq(style, "ldist", "left"), "\n", _write_call(func, _write_call(do, "a", "b"), "c", assign="right"), _write_call( do, _write_call(func, "a", "c"), _write_call(func, "b", "c"), assign="rdist", ), _assert_eq(style, "rdist", "right"), ] maker(do.__name__ + "_distributes_over", "abc", "\n".join(dist_parts)) operands_imports, operands_repr = _valid_syntax_repr(operands) all_imports.update(operands_imports) operands_repr = _st_strategy_names(operands_repr) classdef = "" if style == "unittest": classdef = f"class TestBinaryOperation{func.__name__}(unittest.TestCase):\n " return ( all_imports, classdef + f"{operands_name} = {operands_repr}\n" + "\n".join(parts), ) def ufunc( func: Callable, *, except_: Except = (), style: str = "pytest", annotate: bool | None = None, ) -> str: """Write a property-based test for the :doc:`array ufunc <numpy:reference/ufuncs>` ``func``. The resulting test checks that your ufunc or :doc:`gufunc <numpy:reference/c-api/generalized-ufuncs>` has the expected broadcasting and dtype casting behaviour. You will probably want to add extra assertions, but as with the other ghostwriters this gives you a great place to start. .. code-block:: shell hypothesis write numpy.matmul """ if not _is_probably_ufunc(func): raise InvalidArgument(f"{func=} does not seem to be a ufunc") except_ = _check_except(except_) _check_style(style) if annotate is None: annotate = _are_annotations_used(func) return _make_test( *_make_ufunc_body(func, except_=except_, style=style, annotate=annotate) ) def _make_ufunc_body(func, *, except_, style, annotate): import hypothesis.extra.numpy as npst if func.signature is None: shapes = npst.mutually_broadcastable_shapes(num_shapes=func.nin) else: shapes = npst.mutually_broadcastable_shapes(signature=func.signature) shapes.function.__module__ = npst.__name__ body = """ input_shapes, expected_shape = shapes input_dtypes, expected_dtype = types.split("->") array_strats = [ arrays(dtype=dtp, shape=shp, elements={{"allow_nan": True}}) for dtp, shp in zip(input_dtypes, input_shapes) ] {array_names} = data.draw(st.tuples(*array_strats)) result = {call} """.format( array_names=", ".join(ascii_lowercase[: func.nin]), call=_write_call(func, *ascii_lowercase[: func.nin], except_=except_), ) assertions = "\n{shape_assert}\n{type_assert}".format( shape_assert=_assert_eq(style, "result.shape", "expected_shape"), type_assert=_assert_eq(style, "result.dtype.char", "expected_dtype"), ) qname = _get_qualname(func, include_module=True) obj_sigs = ["O" in sig for sig in func.types] if all(obj_sigs) or not any(obj_sigs): types = f"sampled_from({qname}.types)" else: types = f"sampled_from([sig for sig in {qname}.types if 'O' not in sig])" return _make_test_body( func, test_body=dedent(body).strip(), except_=except_, assertions=assertions, ghost="ufunc" if func.signature is None else "gufunc", style=style, given_strategies={"data": st.data(), "shapes": shapes, "types": types}, imports={("hypothesis.extra.numpy", "arrays")}, annotate=annotate, )
_AnnotationData
python
allegroai__clearml
clearml/backend_api/services/v2_13/tasks.py
{ "start": 347999, "end": 355470 }
class ____(Response): """ Response of tasks.reset endpoint. :param updated: Number of tasks updated (0 or 1) :type updated: int :param fields: Updated fields names and values :type fields: dict :param deleted_indices: List of deleted ES indices that were removed as part of the reset process :type deleted_indices: Sequence[str] :param dequeued: Response from queues.remove_task :type dequeued: dict :param frames: Response from frames.rollback :type frames: dict :param events: Response from events.delete_for_task :type events: dict :param deleted_models: Number of output models deleted by the reset :type deleted_models: int :param urls: The urls of the files that were uploaded by this task. Returned if the 'return_file_urls' was set to True :type urls: TaskUrls """ _service = "tasks" _action = "reset" _version = "2.13" _schema = { "definitions": { "task_urls": { "properties": { "artifact_urls": { "items": {"type": "string"}, "type": ["array", "null"], }, "event_urls": { "items": {"type": "string"}, "type": ["array", "null"], }, "model_urls": { "items": {"type": "string"}, "type": ["array", "null"], }, }, "type": "object", } }, "properties": { "deleted_indices": { "description": "List of deleted ES indices that were removed as part of the reset process", "items": {"type": "string"}, "type": ["array", "null"], }, "deleted_models": { "description": "Number of output models deleted by the reset", "type": ["integer", "null"], }, "dequeued": { "additionalProperties": True, "description": "Response from queues.remove_task", "type": ["object", "null"], }, "events": { "additionalProperties": True, "description": "Response from events.delete_for_task", "type": ["object", "null"], }, "fields": { "additionalProperties": True, "description": "Updated fields names and values", "type": ["object", "null"], }, "frames": { "additionalProperties": True, "description": "Response from frames.rollback", "type": ["object", "null"], }, "updated": { "description": "Number of tasks updated (0 or 1)", "enum": [0, 1], "type": ["integer", "null"], }, "urls": { "description": "The urls of the files that were uploaded by this task. Returned if the 'return_file_urls' was set to True", "oneOf": [{"$ref": "#/definitions/task_urls"}, {"type": "null"}], }, }, "type": "object", } def __init__( self, updated: Optional[int] = None, fields: Optional[dict] = None, deleted_indices: Optional[List[str]] = None, dequeued: Optional[dict] = None, frames: Optional[dict] = None, events: Optional[dict] = None, deleted_models: Optional[int] = None, urls: Any = None, **kwargs: Any ) -> None: super(ResetResponse, self).__init__(**kwargs) self.updated = updated self.fields = fields self.deleted_indices = deleted_indices self.dequeued = dequeued self.frames = frames self.events = events self.deleted_models = deleted_models self.urls = urls @schema_property("updated") def updated(self) -> Optional[int]: return self._property_updated @updated.setter def updated(self, value: Optional[int]) -> None: if value is None: self._property_updated = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "updated", six.integer_types) self._property_updated = value @schema_property("fields") def fields(self) -> Optional[dict]: return self._property_fields @fields.setter def fields(self, value: Optional[dict]) -> None: if value is None: self._property_fields = None return self.assert_isinstance(value, "fields", (dict,)) self._property_fields = value @schema_property("deleted_indices") def deleted_indices(self) -> Optional[List[str]]: return self._property_deleted_indices @deleted_indices.setter def deleted_indices(self, value: Optional[List[str]]) -> None: if value is None: self._property_deleted_indices = None return self.assert_isinstance(value, "deleted_indices", (list, tuple)) self.assert_isinstance(value, "deleted_indices", six.string_types, is_array=True) self._property_deleted_indices = value @schema_property("dequeued") def dequeued(self) -> Optional[dict]: return self._property_dequeued @dequeued.setter def dequeued(self, value: Optional[dict]) -> None: if value is None: self._property_dequeued = None return self.assert_isinstance(value, "dequeued", (dict,)) self._property_dequeued = value @schema_property("frames") def frames(self) -> Optional[dict]: return self._property_frames @frames.setter def frames(self, value: Optional[dict]) -> None: if value is None: self._property_frames = None return self.assert_isinstance(value, "frames", (dict,)) self._property_frames = value @schema_property("events") def events(self) -> Optional[dict]: return self._property_events @events.setter def events(self, value: Optional[dict]) -> None: if value is None: self._property_events = None return self.assert_isinstance(value, "events", (dict,)) self._property_events = value @schema_property("deleted_models") def deleted_models(self) -> Optional[int]: return self._property_deleted_models @deleted_models.setter def deleted_models(self, value: Optional[int]) -> None: if value is None: self._property_deleted_models = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "deleted_models", six.integer_types) self._property_deleted_models = value @schema_property("urls") def urls(self) -> Any: return self._property_urls @urls.setter def urls(self, value: Any) -> None: if value is None: self._property_urls = None return if isinstance(value, dict): value = TaskUrls.from_dict(value) else: self.assert_isinstance(value, "urls", TaskUrls) self._property_urls = value
ResetResponse
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1212577, "end": 1212808 }
class ____(sgqlc.types.Type, Node): """A branch linked to an issue.""" __schema__ = github_schema __field_names__ = ("ref",) ref = sgqlc.types.Field("Ref", graphql_name="ref") """The branch's ref."""
LinkedBranch
python
scikit-image__scikit-image
src/skimage/_shared/utils.py
{ "start": 6663, "end": 16007 }
class ____: """Deprecate a parameter of a function. Parameters ---------- deprecated_name : str The name of the deprecated parameter. start_version : str The package version in which the warning was introduced. stop_version : str The package version in which the warning will be replaced by an error / the deprecation is completed. template : str, optional If given, this message template is used instead of the default one. new_name : str, optional If given, the default message will recommend the new parameter name and an error will be raised if the user uses both old and new names for the same parameter. modify_docstring : bool, optional If the wrapped function has a docstring, add the deprecated parameters to the "Other Parameters" section. stacklevel : {None, int}, optional If None, the decorator attempts to detect the appropriate stacklevel for the deprecation warning automatically. This can fail, e.g., due to decorating a closure, in which case you can set the stacklevel manually here. The outermost decorator should have stacklevel 2, the next inner one stacklevel 3, etc. Notes ----- Assign `DEPRECATED` as the new default value for the deprecated parameter. This marks the status of the parameter also in the signature and rendered HTML docs. This decorator can be stacked to deprecate more than one parameter. Examples -------- >>> from skimage._shared.utils import deprecate_parameter, DEPRECATED >>> @deprecate_parameter( ... "b", new_name="c", start_version="0.1", stop_version="0.3" ... ) ... def foo(a, b=DEPRECATED, *, c=None): ... return a, c Calling ``foo(1, b=2)`` will warn with:: FutureWarning: Parameter `b` is deprecated since version 0.1 and will be removed in 0.3 (or later). To avoid this warning, please use the parameter `c` instead. For more details, see the documentation of `foo`. """ DEPRECATED = DEPRECATED # Make signal value accessible for convenience remove_parameter_template = ( "Parameter `{deprecated_name}` is deprecated since version " "{deprecated_version} and will be removed in {changed_version} (or " "later). To avoid this warning, please do not use the parameter " "`{deprecated_name}`. For more details, see the documentation of " "`{func_name}`." ) replace_parameter_template = ( "Parameter `{deprecated_name}` is deprecated since version " "{deprecated_version} and will be removed in {changed_version} (or " "later). To avoid this warning, please use the parameter `{new_name}` " "instead. For more details, see the documentation of `{func_name}`." ) def __init__( self, deprecated_name, *, start_version, stop_version, template=None, new_name=None, modify_docstring=True, stacklevel=None, ): self.deprecated_name = deprecated_name self.new_name = new_name self.template = template self.start_version = start_version self.stop_version = stop_version self.modify_docstring = modify_docstring self.stacklevel = stacklevel def __call__(self, func): parameters = inspect.signature(func).parameters try: deprecated_idx = list(parameters.keys()).index(self.deprecated_name) except ValueError as e: raise ValueError(f"{self.deprecated_name!r} not in parameters") from e new_idx = False if self.new_name: try: new_idx = list(parameters.keys()).index(self.new_name) except ValueError as e: raise ValueError(f"{self.new_name!r} not in parameters") from e if parameters[self.deprecated_name].default is not DEPRECATED: raise RuntimeError( f"Expected `{self.deprecated_name}` to have the value {DEPRECATED!r} " f"to indicate its status in the rendered signature." ) if self.template is not None: template = self.template elif self.new_name is not None: template = self.replace_parameter_template else: template = self.remove_parameter_template warning_message = template.format( deprecated_name=self.deprecated_name, deprecated_version=self.start_version, changed_version=self.stop_version, func_name=func.__qualname__, new_name=self.new_name, ) @functools.wraps(func) def fixed_func(*args, **kwargs): deprecated_value = DEPRECATED new_value = DEPRECATED # Extract value of deprecated parameter if len(args) > deprecated_idx: deprecated_value = args[deprecated_idx] # Overwrite old with DEPRECATED if replacement exists if self.new_name is not None: args = ( args[:deprecated_idx] + (DEPRECATED,) + args[deprecated_idx + 1 :] ) if self.deprecated_name in kwargs.keys(): deprecated_value = kwargs[self.deprecated_name] # Overwrite old with DEPRECATED if replacement exists if self.new_name is not None: kwargs[self.deprecated_name] = DEPRECATED # Extract value of new parameter (if present) if new_idx is not False and len(args) > new_idx: new_value = args[new_idx] if self.new_name and self.new_name in kwargs.keys(): new_value = kwargs[self.new_name] if deprecated_value is not DEPRECATED: stacklevel = ( self.stacklevel if self.stacklevel is not None else _warning_stacklevel(func) ) warnings.warn( warning_message, category=FutureWarning, stacklevel=stacklevel ) if new_value is not DEPRECATED: raise ValueError( f"Both deprecated parameter `{self.deprecated_name}` " f"and new parameter `{self.new_name}` are used. Use " f"only the latter to avoid conflicting values." ) elif self.new_name is not None: # Assign old value to new one kwargs[self.new_name] = deprecated_value return func(*args, **kwargs) if self.modify_docstring and func.__doc__ is not None: newdoc = _docstring_add_deprecated( func, {self.deprecated_name: self.new_name}, self.start_version ) fixed_func.__doc__ = newdoc return fixed_func def _docstring_add_deprecated(func, kwarg_mapping, deprecated_version): """Add deprecated kwarg(s) to the "Other Params" section of a docstring. Parameters ---------- func : function The function whose docstring we wish to update. kwarg_mapping : dict A dict containing {old_arg: new_arg} key/value pairs, see `deprecate_parameter`. deprecated_version : str A major.minor version string specifying when old_arg was deprecated. Returns ------- new_doc : str The updated docstring. Returns the original docstring if numpydoc is not available. """ if func.__doc__ is None: return None try: from numpydoc.docscrape import FunctionDoc, Parameter except ImportError: # Return an unmodified docstring if numpydoc is not available. return func.__doc__ Doc = FunctionDoc(func) for old_arg, new_arg in kwarg_mapping.items(): desc = [] if new_arg is None: desc.append(f'`{old_arg}` is deprecated.') else: desc.append(f'Deprecated in favor of `{new_arg}`.') desc += ['', f'.. deprecated:: {deprecated_version}'] Doc['Other Parameters'].append( Parameter(name=old_arg, type='DEPRECATED', desc=desc) ) new_docstring = str(Doc) # new_docstring will have a header starting with: # # .. function:: func.__name__ # # and some additional blank lines. We strip these off below. split = new_docstring.split('\n') no_header = split[1:] while not no_header[0].strip(): no_header.pop(0) # Store the initial description before any of the Parameters fields. # Usually this is a single line, but the while loop covers any case # where it is not. descr = no_header.pop(0) while no_header[0].strip(): descr += '\n ' + no_header.pop(0) descr += '\n\n' # '\n ' rather than '\n' here to restore the original indentation. final_docstring = descr + '\n '.join(no_header) # strip any extra spaces from ends of lines final_docstring = '\n'.join([line.rstrip() for line in final_docstring.split('\n')]) return final_docstring
deprecate_parameter
python
lepture__authlib
authlib/oauth2/rfc6749/errors.py
{ "start": 4551, "end": 4987 }
class ____(OAuth2Error): """The authorization grant type is not supported by the authorization server. https://tools.ietf.org/html/rfc6749#section-5.2 """ error = "unsupported_grant_type" def __init__(self, grant_type): super().__init__() self.grant_type = grant_type def get_error_description(self): return f"grant_type={self.grant_type} is not supported"
UnsupportedGrantTypeError
python
kamyu104__LeetCode-Solutions
Python/reformat-phone-number.py
{ "start": 48, "end": 1104 }
class ____(object): def reformatNumber(self, number): """ :type number: str :rtype: str """ number = list(number) src_len = 0 for c in number: # remove non-digit characters if c.isdigit(): number[src_len] = c src_len += 1 dst_len = src_len + (src_len-1)//3 if dst_len > len(number): # resize the buffer to expected final size number.extend([0]*(dst_len-len(number))) while dst_len < len(number): number.pop() curr = dst_len-1 for l, i in enumerate(reversed(xrange(src_len)), (3-src_len%3)%3): if l and l%3 == 0: # group by 3 digits number[curr] = '-' curr -= 1 number[curr] = number[i] curr -= 1 if dst_len >= 3 and number[dst_len-2] == '-': # adjust for the 4 digits case number[dst_len-3], number[dst_len-2] = number[dst_len-2], number[dst_len-3] return "".join(number)
Solution
python
astropy__astropy
astropy/time/tests/test_quantity_interaction.py
{ "start": 11078, "end": 13326 }
class ____: def test_delta_ut1_utc(self): t = Time("2010-01-01 00:00:00", format="iso", scale="utc", precision=6) t.delta_ut1_utc = 0.3 * u.s assert t.ut1.iso == "2010-01-01 00:00:00.300000" t.delta_ut1_utc = 0.4 / 60.0 * u.minute assert t.ut1.iso == "2010-01-01 00:00:00.400000" with pytest.raises(u.UnitsError): t.delta_ut1_utc = 0.4 * u.m # Also check that a TimeDelta works. t.delta_ut1_utc = TimeDelta(0.3, format="sec") assert t.ut1.iso == "2010-01-01 00:00:00.300000" t.delta_ut1_utc = TimeDelta(0.5 / 24.0 / 3600.0, format="jd") assert t.ut1.iso == "2010-01-01 00:00:00.500000" def test_delta_tdb_tt(self): t = Time("2010-01-01 00:00:00", format="iso", scale="tt", precision=6) t.delta_tdb_tt = 20.0 * u.second assert t.tdb.iso == "2010-01-01 00:00:20.000000" t.delta_tdb_tt = 30.0 / 60.0 * u.minute assert t.tdb.iso == "2010-01-01 00:00:30.000000" with pytest.raises(u.UnitsError): t.delta_tdb_tt = 0.4 * u.m # Also check that a TimeDelta works. t.delta_tdb_tt = TimeDelta(40.0, format="sec") assert t.tdb.iso == "2010-01-01 00:00:40.000000" t.delta_tdb_tt = TimeDelta(50.0 / 24.0 / 3600.0, format="jd") assert t.tdb.iso == "2010-01-01 00:00:50.000000" @pytest.mark.parametrize( "q1, q2", ( (5e8 * u.s, None), (5e17 * u.ns, None), (4e8 * u.s, 1e17 * u.ns), (4e14 * u.us, 1e17 * u.ns), ), ) def test_quantity_conversion_rounding(q1, q2): """Check that no rounding errors are incurred by unit conversion. This occurred before as quantities in seconds were converted to days before trying to split them into two-part doubles. See gh-7622. """ t = Time("2001-01-01T00:00:00.", scale="tai") expected = Time("2016-11-05T00:53:20.", scale="tai") if q2 is None: t0 = t + q1 else: t0 = t + q1 + q2 assert abs(t0 - expected) < 20 * u.ps dt1 = TimeDelta(q1, q2) t1 = t + dt1 assert abs(t1 - expected) < 20 * u.ps dt2 = TimeDelta(q1, q2, format="sec") t2 = t + dt2 assert abs(t2 - expected) < 20 * u.ps
TestDeltaAttributes
python
pytorch__pytorch
torch/ao/nn/quantized/modules/__init__.py
{ "start": 3833, "end": 4521 }
class ____(torch.nn.Module): r"""Dequantizes an incoming tensor Examples:: >>> input = torch.tensor([[1., -1.], [1., -1.]]) >>> scale, zero_point, dtype = 1.0, 2, torch.qint8 >>> qm = Quantize(scale, zero_point, dtype) >>> # xdoctest: +SKIP >>> quantized_input = qm(input) >>> dqm = DeQuantize() >>> dequantized = dqm(quantized_input) >>> print(dequantized) tensor([[ 1., -1.], [ 1., -1.]], dtype=torch.float32) """ def forward(self, Xq): return Xq.dequantize() @staticmethod def from_float(mod, use_precomputed_fake_quant=False): return DeQuantize()
DeQuantize
python
getsentry__sentry
tests/sentry/middleware/integrations/test_integration_control.py
{ "start": 890, "end": 6418 }
class ____(TestCase): get_response = MagicMock() middleware = IntegrationControlMiddleware(get_response=get_response) integration_cls = IntegrationClassification(response_handler=get_response) plugin_cls = PluginClassification(response_handler=get_response) def setUp(self) -> None: self.factory = RequestFactory() def validate_mock_ran_with_noop(self, request, mock): # Ensure mock runs when middleware is called mock.reset_mock() response = self.middleware(request) assert mock.called # Ensure noop response assert response == self.get_response() @override_settings(SILO_MODE=SiloMode.MONOLITH) @patch.object( IntegrationControlMiddleware, "_should_operate", wraps=middleware._should_operate, ) def test_inactive_on_monolith(self, mock_should_operate) -> None: request = self.factory.post("/extensions/slack/webhook/") assert mock_should_operate(request) is False self.validate_mock_ran_with_noop(request, mock_should_operate) @override_settings(SILO_MODE=SiloMode.REGION) @patch.object( IntegrationControlMiddleware, "_should_operate", wraps=middleware._should_operate, ) def test_inactive_on_region_silo(self, mock_should_operate) -> None: request = self.factory.post("/extensions/slack/webhook/") assert mock_should_operate(request) is False self.validate_mock_ran_with_noop(request, mock_should_operate) @override_settings(SILO_MODE=SiloMode.CONTROL) @patch.object(IntegrationClassification, "should_operate", wraps=integration_cls.should_operate) @patch.object(PluginClassification, "should_operate", wraps=plugin_cls.should_operate) def test_attempts_all_classifications( self, mock_plugin_operate, mock_integration_operate ) -> None: class NewClassification(BaseClassification): pass self.middleware.register_classifications(classifications=[NewClassification]) with ( patch.object( NewClassification, "should_operate", return_value=True ) as mock_new_should_operate, patch.object(NewClassification, "get_response") as mock_new_get_response, ): self.middleware(self.factory.post("/")) assert mock_integration_operate.called assert mock_plugin_operate.called assert mock_new_should_operate.called assert mock_new_get_response.called @override_settings(SILO_MODE=SiloMode.CONTROL) @patch.object(IntegrationClassification, "should_operate", wraps=integration_cls.should_operate) @patch.object(PluginClassification, "should_operate", wraps=plugin_cls.should_operate) def test_attempts_ordered_classifications( self, mock_plugin_operate, mock_integration_operate ) -> None: self.middleware(self.factory.post("/extensions/slack/webhook/")) assert mock_integration_operate.called assert not mock_plugin_operate.called @override_settings(SILO_MODE=SiloMode.CONTROL) @patch.object(SlackRequestParser, "get_response") def test_returns_parser_get_response_integration(self, mock_parser_get_response) -> None: result = HttpResponse(status=204) mock_parser_get_response.return_value = result response = self.middleware(self.factory.post("/extensions/slack/webhook/")) assert result == response @override_settings(SILO_MODE=SiloMode.CONTROL) @patch.object(JiraServerRequestParser, "get_response") def test_returns_parser_get_response_jiraserver(self, mock_parser_get_response) -> None: result = HttpResponse(status=204) mock_parser_get_response.return_value = result response = self.middleware( self.factory.post("/extensions/jira_server/issue-updated/abc-123/") ) assert result == response # jira-server is the inflection used in URLS and should match response = self.middleware( self.factory.post("/extensions/jira-server/issue-updated/abc-123/") ) assert result == response @override_settings(SILO_MODE=SiloMode.CONTROL) @patch.object(JiraRequestParser, "get_response") def test_returns_parser_get_response_jira(self, mock_parser_get_response) -> None: result = HttpResponse(status=204) mock_parser_get_response.return_value = result response = self.middleware(self.factory.post("/extensions/jira/issue-updated/abc-123/")) assert result == response # provider pattern should capture - and forward to jira server. response = self.middleware( self.factory.post("/extensions/jira-server/issue-updated/abc-123/") ) assert result != response @override_settings(SILO_MODE=SiloMode.CONTROL) def test_handles_missing_integration(self) -> None: response = self.middleware(self.factory.post("/extensions/jira/issue-updated/")) assert response.status_code == 404 @override_settings(SILO_MODE=SiloMode.CONTROL) @patch.object(PluginRequestParser, "get_response") def test_returns_parser_get_response_plugin(self, mock_parser_get_response) -> None: result = HttpResponse(status=204) mock_parser_get_response.return_value = result response = self.middleware(self.factory.post("/plugins/bitbucket/organizations/1/webhook/")) assert result == response
IntegrationControlMiddlewareTest
python
getsentry__sentry
src/sentry/sentry_apps/api/endpoints/installation_external_requests.py
{ "start": 540, "end": 1409 }
class ____(SentryAppInstallationBaseEndpoint): owner = ApiOwner.INTEGRATIONS publish_status = { "GET": ApiPublishStatus.PRIVATE, } def get(self, request: Request, installation) -> Response: try: project = Project.objects.get( id=request.GET.get("projectId"), organization_id=installation.organization_id ) except Project.DoesNotExist: project = None kwargs = { "install": installation, "uri": request.GET.get("uri"), "query": request.GET.get("query"), "dependent_data": request.GET.get("dependentData"), } if project: kwargs.update({"project_slug": project.slug}) choices = SelectRequester(**kwargs).run() return Response(choices)
SentryAppInstallationExternalRequestsEndpoint
python
pypa__pipenv
pipenv/utils/requirementslib.py
{ "start": 11703, "end": 28060 }
class ____(KeyError, IndexError, TypeError): """An amalgamation of KeyError, IndexError, and TypeError, representing what can occur when looking up a path in a nested object.""" def __init__(self, exc, seg, path): self.exc = exc self.seg = seg self.path = path def __repr__(self): cn = self.__class__.__name__ return f"{cn}({self.exc!r}, {self.seg!r}, {self.path!r})" def __str__(self): return f"could not access {self.seg} from path {self.path}, got error: {self.exc}" def get_path(root, path, default=_UNSET): """Retrieve a value from a nested object via a tuple representing the lookup path. >>> root = {'a': {'b': {'c': [[1], [2], [3]]}}} >>> get_path(root, ('a', 'b', 'c', 2, 0)) 3 The path format is intentionally consistent with that of :func:`remap`. One of get_path's chief aims is improved error messaging. EAFP is great, but the error messages are not. For instance, ``root['a']['b']['c'][2][1]`` gives back ``IndexError: list index out of range`` What went out of range where? get_path currently raises ``PathAccessError: could not access 2 from path ('a', 'b', 'c', 2, 1), got error: IndexError('list index out of range',)``, a subclass of IndexError and KeyError. You can also pass a default that covers the entire operation, should the lookup fail at any level. Args: root: The target nesting of dictionaries, lists, or other objects supporting ``__getitem__``. path (tuple): A list of strings and integers to be successively looked up within *root*. default: The value to be returned should any ``PathAccessError`` exceptions be raised. """ if isinstance(path, str): path = path.split(".") cur = root try: for seg in path: try: cur = cur[seg] except (KeyError, IndexError) as exc: # noqa: PERF203 raise PathAccessError(exc, seg, path) except TypeError: # either string index in a list, or a parent that # doesn't support indexing try: seg = int(seg) cur = cur[seg] except (ValueError, KeyError, IndexError, TypeError): if not hasattr(cur, "__iter__"): exc = TypeError(f"{type(cur).__name__!r} object is not indexable") raise PathAccessError(exc, seg, path) except PathAccessError: if default is _UNSET: raise return default return cur def default_visit(path, key, value): return key, value _orig_default_visit = default_visit # Modified from https://github.com/mahmoud/boltons/blob/master/boltons/iterutils.py def dict_path_enter(path, key, value): if isinstance(value, str): return value, False elif isinstance(value, (tomlkit.items.Table, tomlkit.items.InlineTable)): return value.__class__( tomlkit.container.Container(), value.trivia, False ), ItemsView(value) elif isinstance(value, (Mapping, dict)): return value.__class__(), ItemsView(value) elif isinstance(value, tomlkit.items.Array): return value.__class__([], value.trivia), enumerate(value) elif isinstance(value, (Sequence, list)): return value.__class__(), enumerate(value) elif isinstance(value, (Set, set)): return value.__class__(), enumerate(value) else: return value, False def dict_path_exit(path, key, old_parent, new_parent, new_items): ret = new_parent if isinstance(new_parent, (Mapping, dict)): vals = dict(new_items) try: new_parent.update(new_items) except AttributeError: # Handle toml containers specifically try: new_parent.update(vals) # Now use default fallback if needed except AttributeError: ret = new_parent.__class__(vals) elif isinstance(new_parent, tomlkit.items.Array): vals = tomlkit.items.item([v for i, v in new_items]) try: new_parent._value.extend(vals._value) except AttributeError: ret = tomlkit.items.item(vals) elif isinstance(new_parent, (Sequence, list)): vals = [v for i, v in new_items] try: new_parent.extend(vals) except AttributeError: ret = new_parent.__class__(vals) # tuples elif isinstance(new_parent, (Set, set)): vals = [v for i, v in new_items] try: new_parent.update(vals) except AttributeError: ret = new_parent.__class__(vals) # frozensets else: raise RuntimeError(f"Unexpected iterable type: {type(new_parent)!r}") return ret def remap( root, visit=default_visit, enter=dict_path_enter, exit=dict_path_exit, **kwargs ): """The remap ("recursive map") function is used to traverse and transform nested structures. Lists, tuples, sets, and dictionaries are just a few of the data structures nested into heterogeneous tree-like structures that are so common in programming. Unfortunately, Python's built-in ways to manipulate collections are almost all flat. List comprehensions may be fast and succinct, but they do not recurse, making it tedious to apply quick changes or complex transforms to real-world data. remap goes where list comprehensions cannot. Here's an example of removing all Nones from some data: >>> from pprint import pprint >>> reviews = {'Star Trek': {'TNG': 10, 'DS9': 8.5, 'ENT': None}, ... 'Babylon 5': 6, 'Dr. Who': None} >>> pprint(remap(reviews, lambda p, k, v: v is not None)) {'Babylon 5': 6, 'Star Trek': {'DS9': 8.5, 'TNG': 10}} Notice how both Nones have been removed despite the nesting in the dictionary. Not bad for a one-liner, and that's just the beginning. See `this remap cookbook`_ for more delicious recipes. .. _this remap cookbook: http://sedimental.org/remap.html remap takes four main arguments: the object to traverse and three optional callables which determine how the remapped object will be created. Args: root: The target object to traverse. By default, remap supports iterables like :class:`list`, :class:`tuple`, :class:`dict`, and :class:`set`, but any object traversable by *enter* will work. visit (callable): This function is called on every item in *root*. It must accept three positional arguments, *path*, *key*, and *value*. *path* is simply a tuple of parents' keys. *visit* should return the new key-value pair. It may also return ``True`` as shorthand to keep the old item unmodified, or ``False`` to drop the item from the new structure. *visit* is called after *enter*, on the new parent. The *visit* function is called for every item in root, including duplicate items. For traversable values, it is called on the new parent object, after all its children have been visited. The default visit behavior simply returns the key-value pair unmodified. enter (callable): This function controls which items in *root* are traversed. It accepts the same arguments as *visit*: the path, the key, and the value of the current item. It returns a pair of the blank new parent, and an iterator over the items which should be visited. If ``False`` is returned instead of an iterator, the value will not be traversed. The *enter* function is only called once per unique value. The default enter behavior support mappings, sequences, and sets. Strings and all other iterables will not be traversed. exit (callable): This function determines how to handle items once they have been visited. It gets the same three arguments as the other functions -- *path*, *key*, *value* -- plus two more: the blank new parent object returned from *enter*, and a list of the new items, as remapped by *visit*. Like *enter*, the *exit* function is only called once per unique value. The default exit behavior is to simply add all new items to the new parent, e.g., using :meth:`list.extend` and :meth:`dict.update` to add to the new parent. Immutable objects, such as a :class:`tuple` or :class:`namedtuple`, must be recreated from scratch, but use the same type as the new parent passed back from the *enter* function. reraise_visit (bool): A pragmatic convenience for the *visit* callable. When set to ``False``, remap ignores any errors raised by the *visit* callback. Items causing exceptions are kept. See examples for more details. remap is designed to cover the majority of cases with just the *visit* callable. While passing in multiple callables is very empowering, remap is designed so very few cases should require passing more than one function. When passing *enter* and *exit*, it's common and easiest to build on the default behavior. Simply add ``from boltons.iterutils import default_enter`` (or ``default_exit``), and have your enter/exit function call the default behavior before or after your custom logic. See `this example`_. Duplicate and self-referential objects (aka reference loops) are automatically handled internally, `as shown here`_. .. _this example: http://sedimental.org/remap.html#sort_all_lists .. _as shown here: http://sedimental.org/remap.html#corner_cases """ # TODO: improve argument formatting in sphinx doc # TODO: enter() return (False, items) to continue traverse but cancel copy? if not callable(visit): raise TypeError(f"visit expected callable, not: {visit!r}") if not callable(enter): raise TypeError(f"enter expected callable, not: {enter!r}") if not callable(exit): raise TypeError(f"exit expected callable, not: {exit!r}") reraise_visit = kwargs.pop("reraise_visit", True) if kwargs: raise TypeError(f"Unexpected keyword arguments: {kwargs.keys()!r}") path, registry, stack = (), {}, [(None, root)] new_items_stack = [] while stack: key, value = stack.pop() id_value = id(value) if key is _REMAP_EXIT: key, new_parent, old_parent = value id_value = id(old_parent) path, new_items = new_items_stack.pop() value = exit(path, key, old_parent, new_parent, new_items) registry[id_value] = value if not new_items_stack: continue elif id_value in registry: value = registry[id_value] else: res = enter(path, key, value) try: new_parent, new_items = res except TypeError: # TODO: handle False? raise TypeError( f"enter should return a tuple of (new_parent, items_iterator), not: {res!r}" ) if new_items is not False: # traverse unless False is explicitly passed registry[id_value] = new_parent new_items_stack.append((path, [])) if value is not root: path += (key,) stack.append((_REMAP_EXIT, (key, new_parent, value))) if new_items: stack.extend(reversed(list(new_items))) continue if visit is _orig_default_visit: # avoid function call overhead by inlining identity operation visited_item = (key, value) else: try: visited_item = visit(path, key, value) except Exception: if reraise_visit: raise visited_item = True if visited_item is False: continue # drop elif visited_item is True: visited_item = (key, value) # TODO: typecheck? # raise TypeError('expected (key, value) from visit(),' # ' not: %r' % visited_item) try: new_items_stack[-1][1].append(visited_item) except IndexError: raise TypeError(f"Expected remappable root, not: {root!r}") return value def merge_items(target_list, sourced=False): if not sourced: target_list = [(id(t), t) for t in target_list] ret = None source_map = {} def remerge_enter(path, key, value): new_parent, new_items = dict_path_enter(path, key, value) if ret and not path and key is None: new_parent = ret try: cur_val = get_path(ret, path + (key,)) except KeyError: pass else: new_parent = cur_val return new_parent, new_items def remerge_exit(path, key, old_parent, new_parent, new_items): return dict_path_exit(path, key, old_parent, new_parent, new_items) for t_name, target in target_list: if sourced: def remerge_visit(path, key, value): source_map[path + (key,)] = t_name # noqa: B023 return True else: remerge_visit = default_visit ret = remap(target, enter=remerge_enter, visit=remerge_visit, exit=remerge_exit) if not sourced: return ret return ret, source_map def get_pip_command() -> InstallCommand: """Get pip's InstallCommand for configuration management and defaults.""" # Use pip's parser for pip.conf management and defaults. # General options (find_links, index_url, extra_index_url, trusted_host, # and pre) are deferred to pip. pip_command = InstallCommand( name="InstallCommand", summary="pipenv pip Install command." ) return pip_command def unpack_url( link: Link, location: str, download: Downloader, verbosity: int, download_dir: Optional[str] = None, hashes: Optional[Hashes] = None, ) -> Optional[File]: """Unpack link into location, downloading if required. :param hashes: A Hashes object, one of whose embedded hashes must match, or HashMismatch will be raised. If the Hashes is empty, no matches are required, and unhashable types of requirements (like VCS ones, which would ordinarily raise HashUnsupported) are allowed. """ # non-editable vcs urls if link.scheme in VCS_SCHEMES: unpack_vcs_link(link, location, verbosity=verbosity) return File(location, content_type=None) assert not link.is_existing_dir() # file urls if link.is_file: file = get_file_url(link, download_dir, hashes=hashes) # http urls else: file = get_http_url( link, download, download_dir, hashes=hashes, ) # unpack the archive to the build dir location. even when only downloading # archives, they have to be unpacked to parse dependencies, except wheels if not link.is_wheel: unpack_file(file.path, location, file.content_type) return file def get_http_url( link: Link, download: Downloader, download_dir: Optional[str] = None, hashes: Optional[Hashes] = None, ) -> File: """Download a file from an HTTP URL.""" temp_dir = TempDirectory(kind="unpack", globally_managed=False) # If a download dir is specified, is the file already downloaded there? already_downloaded_path = None if download_dir: already_downloaded_path = _check_download_dir(link, download_dir, hashes) if already_downloaded_path: from_path = already_downloaded_path content_type = None else: # let's download to a tmp dir from_path, content_type = download(link, temp_dir.path) if hashes: hashes.check_against_path(from_path) return File(from_path, content_type)
PathAccessError
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1400310, "end": 1401588 }
class ____(sgqlc.types.Type, Node): """Represents a 'removed_from_merge_queue' event on a given pull request. """ __schema__ = github_schema __field_names__ = ("actor", "before_commit", "created_at", "enqueuer", "merge_queue", "pull_request", "reason") actor = sgqlc.types.Field(Actor, graphql_name="actor") """Identifies the actor who performed the event.""" before_commit = sgqlc.types.Field(Commit, graphql_name="beforeCommit") """Identifies the before commit SHA for the 'removed_from_merge_queue' event. """ created_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="createdAt") """Identifies the date and time when the object was created.""" enqueuer = sgqlc.types.Field("User", graphql_name="enqueuer") """The user who removed this Pull Request from the merge queue""" merge_queue = sgqlc.types.Field(MergeQueue, graphql_name="mergeQueue") """The merge queue where this pull request was removed from.""" pull_request = sgqlc.types.Field(PullRequest, graphql_name="pullRequest") """PullRequest referenced by event.""" reason = sgqlc.types.Field(String, graphql_name="reason") """The reason this pull request was removed from the queue."""
RemovedFromMergeQueueEvent
python
ray-project__ray
python/ray/tests/test_task_metrics.py
{ "start": 17010, "end": 17806 }
class ____: def f(self): try: ray.get(phaser.inc.remote()) except Exception: print("RESTART") os._exit(1) f = F.remote() ray.get(f.f.remote()) time.sleep(999) """ proc = run_string_as_driver_nonblocking(driver) expected = { ("F.__init__", "FINISHED", "0"): 1.0, ("F.f", "FAILED", "0"): 1.0, ("F.f", "FAILED", "1"): 1.0, ("F.f", "FINISHED", "1"): 1.0, ("Phaser.__init__", "FINISHED", "0"): 1.0, ("Phaser.inc", "FINISHED", "0"): 1.0, } wait_for_condition( lambda: expected.items() <= tasks_by_all(info, timeseries).items(), timeout=20, retry_interval_ms=500, ) proc.kill() if __name__ == "__main__": sys.exit(pytest.main(["-sv", __file__]))
F
python
pyinstaller__pyinstaller
bootloader/waflib/Runner.py
{ "start": 1486, "end": 2023 }
class ____(Utils.threading.Thread): def __init__(self, spawner, task): Utils.threading.Thread.__init__(self) self.task = task self.spawner = spawner self.daemon = True self.start() def run(self): try: if not self.spawner.master.stop: self.spawner.master.process_task(self.task) finally: self.spawner.sem.release() self.spawner.master.out.put(self.task) self.task = None self.spawner = None
Consumer
python
graphql-python__graphene
graphene/relay/tests/test_connection_query.py
{ "start": 416, "end": 7013 }
class ____(ObjectType): letters = ConnectionField(LetterConnection) connection_letters = ConnectionField(LetterConnection) async_letters = ConnectionField(LetterConnection) node = Node.Field() def resolve_letters(self, info, **args): return list(letters.values()) async def resolve_async_letters(self, info, **args): return list(letters.values()) def resolve_connection_letters(self, info, **args): return LetterConnection( page_info=PageInfo(has_next_page=True, has_previous_page=False), edges=[ LetterConnection.Edge(node=Letter(id=0, letter="A"), cursor="a-cursor") ], ) schema = Schema(Query) letters = {letter: Letter(id=i, letter=letter) for i, letter in enumerate(letter_chars)} def edges(selected_letters): return [ { "node": {"id": base64("Letter:%s" % letter.id), "letter": letter.letter}, "cursor": base64("arrayconnection:%s" % letter.id), } for letter in [letters[i] for i in selected_letters] ] def cursor_for(ltr): letter = letters[ltr] return base64("arrayconnection:%s" % letter.id) async def execute(args=""): if args: args = "(" + args + ")" return await schema.execute_async( """ { letters%s { edges { node { id letter } cursor } pageInfo { hasPreviousPage hasNextPage startCursor endCursor } } } """ % args ) async def check(args, letters, has_previous_page=False, has_next_page=False): result = await execute(args) expected_edges = edges(letters) expected_page_info = { "hasPreviousPage": has_previous_page, "hasNextPage": has_next_page, "endCursor": expected_edges[-1]["cursor"] if expected_edges else None, "startCursor": expected_edges[0]["cursor"] if expected_edges else None, } assert not result.errors assert result.data == { "letters": {"edges": expected_edges, "pageInfo": expected_page_info} } @mark.asyncio async def test_returns_all_elements_without_filters(): await check("", "ABCDE") @mark.asyncio async def test_respects_a_smaller_first(): await check("first: 2", "AB", has_next_page=True) @mark.asyncio async def test_respects_an_overly_large_first(): await check("first: 10", "ABCDE") @mark.asyncio async def test_respects_a_smaller_last(): await check("last: 2", "DE", has_previous_page=True) @mark.asyncio async def test_respects_an_overly_large_last(): await check("last: 10", "ABCDE") @mark.asyncio async def test_respects_first_and_after(): await check(f'first: 2, after: "{cursor_for("B")}"', "CD", has_next_page=True) @mark.asyncio async def test_respects_first_and_after_with_long_first(): await check(f'first: 10, after: "{cursor_for("B")}"', "CDE") @mark.asyncio async def test_respects_last_and_before(): await check(f'last: 2, before: "{cursor_for("D")}"', "BC", has_previous_page=True) @mark.asyncio async def test_respects_last_and_before_with_long_last(): await check(f'last: 10, before: "{cursor_for("D")}"', "ABC") @mark.asyncio async def test_respects_first_and_after_and_before_too_few(): await check( f'first: 2, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "BC", has_next_page=True, ) @mark.asyncio async def test_respects_first_and_after_and_before_too_many(): await check( f'first: 4, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "BCD" ) @mark.asyncio async def test_respects_first_and_after_and_before_exactly_right(): await check( f'first: 3, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "BCD" ) @mark.asyncio async def test_respects_last_and_after_and_before_too_few(): await check( f'last: 2, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "CD", has_previous_page=True, ) @mark.asyncio async def test_respects_last_and_after_and_before_too_many(): await check( f'last: 4, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "BCD" ) @mark.asyncio async def test_respects_last_and_after_and_before_exactly_right(): await check( f'last: 3, after: "{cursor_for("A")}", before: "{cursor_for("E")}"', "BCD" ) @mark.asyncio async def test_returns_no_elements_if_first_is_0(): await check("first: 0", "", has_next_page=True) @mark.asyncio async def test_returns_all_elements_if_cursors_are_invalid(): await check('before: "invalid" after: "invalid"', "ABCDE") @mark.asyncio async def test_returns_all_elements_if_cursors_are_on_the_outside(): await check( f'before: "{base64("arrayconnection:%s" % 6)}" after: "{base64("arrayconnection:%s" % -1)}"', "ABCDE", ) @mark.asyncio async def test_returns_no_elements_if_cursors_cross(): await check( f'before: "{base64("arrayconnection:%s" % 2)}" after: "{base64("arrayconnection:%s" % 4)}"', "", ) @mark.asyncio async def test_connection_type_nodes(): result = await schema.execute_async( """ { connectionLetters { edges { node { id letter } cursor } pageInfo { hasPreviousPage hasNextPage } } } """ ) assert not result.errors assert result.data == { "connectionLetters": { "edges": [ {"node": {"id": "TGV0dGVyOjA=", "letter": "A"}, "cursor": "a-cursor"} ], "pageInfo": {"hasPreviousPage": False, "hasNextPage": True}, } } @mark.asyncio async def test_connection_async(): result = await schema.execute_async( """ { asyncLetters(first:1) { edges { node { id letter } } pageInfo { hasPreviousPage hasNextPage } } } """ ) assert not result.errors assert result.data == { "asyncLetters": { "edges": [{"node": {"id": "TGV0dGVyOjA=", "letter": "A"}}], "pageInfo": {"hasPreviousPage": False, "hasNextPage": True}, } }
Query
python
scipy__scipy
scipy/optimize/tests/test__shgo.py
{ "start": 34780, "end": 39217 }
class ____: def test_1_maxiter(self): """Test failure on insufficient iterations""" options = {'maxiter': 2} res = shgo(test4_1.f, test4_1.bounds, n=2, iters=None, options=options, sampling_method='sobol') np.testing.assert_equal(False, res.success) # np.testing.assert_equal(4, res.nfev) np.testing.assert_equal(4, res.tnev) def test_2_sampling(self): """Rejection of unknown sampling method""" assert_raises(ValueError, shgo, test1_1.f, test1_1.bounds, sampling_method='not_Sobol') def test_3_1_no_min_pool_sobol(self): """Check that the routine stops when no minimiser is found after maximum specified function evaluations""" options = {'maxfev': 10, # 'maxev': 10, 'disp': True} res = shgo(test_table.f, test_table.bounds, n=3, options=options, sampling_method='sobol') np.testing.assert_equal(False, res.success) # np.testing.assert_equal(9, res.nfev) np.testing.assert_equal(12, res.nfev) def test_3_2_no_min_pool_simplicial(self): """Check that the routine stops when no minimiser is found after maximum specified sampling evaluations""" options = {'maxev': 10, 'disp': True} res = shgo(test_table.f, test_table.bounds, n=3, options=options, sampling_method='simplicial') np.testing.assert_equal(False, res.success) def test_4_1_bound_err(self): """Specified bounds ub > lb""" bounds = [(6, 3), (3, 5)] assert_raises(ValueError, shgo, test1_1.f, bounds) def test_4_2_bound_err(self): """Specified bounds are of the form (lb, ub)""" bounds = [(3, 5, 5), (3, 5)] assert_raises(ValueError, shgo, test1_1.f, bounds) def test_5_1_1_infeasible_sobol(self): """Ensures the algorithm terminates on infeasible problems after maxev is exceeded. Use infty constraints option""" options = {'maxev': 100, 'disp': True} res = shgo(test_infeasible.f, test_infeasible.bounds, constraints=test_infeasible.cons, n=100, options=options, sampling_method='sobol') np.testing.assert_equal(False, res.success) def test_5_1_2_infeasible_sobol(self): """Ensures the algorithm terminates on infeasible problems after maxev is exceeded. Do not use infty constraints option""" options = {'maxev': 100, 'disp': True, 'infty_constraints': False} res = shgo(test_infeasible.f, test_infeasible.bounds, constraints=test_infeasible.cons, n=100, options=options, sampling_method='sobol') np.testing.assert_equal(False, res.success) def test_5_2_infeasible_simplicial(self): """Ensures the algorithm terminates on infeasible problems after maxev is exceeded.""" options = {'maxev': 1000, 'disp': False} res = shgo(test_infeasible.f, test_infeasible.bounds, constraints=test_infeasible.cons, n=100, options=options, sampling_method='simplicial') np.testing.assert_equal(False, res.success) def test_6_1_lower_known_f_min(self): """Test Global mode limiting local evaluations with f* too high""" options = { # Specify known function value 'f_min': test2_1.expected_fun + 2.0, 'f_tol': 1e-6, # Specify number of local iterations to perform+ 'minimize_every_iter': True, 'local_iter': 1, 'infty_constraints': False} args = (test2_1.f, test2_1.bounds) kwargs = {'constraints': test2_1.cons, 'n': None, 'iters': None, 'options': options, 'sampling_method': 'sobol' } warns(UserWarning, shgo, *args, **kwargs) def test(self): from scipy.optimize import rosen, shgo bounds = [(0, 2), (0, 2), (0, 2), (0, 2), (0, 2)] def fun(x): fun.nfev += 1 return rosen(x) fun.nfev = 0 result = shgo(fun, bounds) print(result.x, result.fun, fun.nfev) # 50 # Returns
TestShgoFailures
python
redis__redis-py
redis/commands/cluster.py
{ "start": 29094, "end": 30745 }
class ____( ClusterDataAccessCommands, AsyncDataAccessCommands ): """ A class for Redis Cluster Data Access Commands The class inherits from Redis's core DataAccessCommand class and do the required adjustments to work with cluster mode """ async def scan_iter( self, match: Optional[PatternT] = None, count: Optional[int] = None, _type: Optional[str] = None, **kwargs, ) -> AsyncIterator: # Do the first query with cursor=0 for all nodes cursors, data = await self.scan(match=match, count=count, _type=_type, **kwargs) for value in data: yield value cursors = {name: cursor for name, cursor in cursors.items() if cursor != 0} if cursors: # Get nodes by name nodes = {name: self.get_node(node_name=name) for name in cursors.keys()} # Iterate over each node till its cursor is 0 kwargs.pop("target_nodes", None) while cursors: for name, cursor in cursors.items(): cur, data = await self.scan( cursor=cursor, match=match, count=count, _type=_type, target_nodes=nodes[name], **kwargs, ) for value in data: yield value cursors[name] = cur[name] cursors = { name: cursor for name, cursor in cursors.items() if cursor != 0 }
AsyncClusterDataAccessCommands
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/sqltypes.py
{ "start": 81981, "end": 102093 }
class ____(Indexable, TypeEngine[Any]): """Represent a SQL JSON type. .. note:: :class:`_types.JSON` is provided as a facade for vendor-specific JSON types. Since it supports JSON SQL operations, it only works on backends that have an actual JSON type, currently: * PostgreSQL - see :class:`sqlalchemy.dialects.postgresql.JSON` and :class:`sqlalchemy.dialects.postgresql.JSONB` for backend-specific notes * MySQL - see :class:`sqlalchemy.dialects.mysql.JSON` for backend-specific notes * SQLite as of version 3.9 - see :class:`sqlalchemy.dialects.sqlite.JSON` for backend-specific notes * Microsoft SQL Server 2016 and later - see :class:`sqlalchemy.dialects.mssql.JSON` for backend-specific notes :class:`_types.JSON` is part of the Core in support of the growing popularity of native JSON datatypes. The :class:`_types.JSON` type stores arbitrary JSON format data, e.g.:: data_table = Table( "data_table", metadata, Column("id", Integer, primary_key=True), Column("data", JSON), ) with engine.connect() as conn: conn.execute( data_table.insert(), {"data": {"key1": "value1", "key2": "value2"}} ) **JSON-Specific Expression Operators** The :class:`_types.JSON` datatype provides these additional SQL operations: * Keyed index operations:: data_table.c.data["some key"] * Integer index operations:: data_table.c.data[3] * Path index operations:: data_table.c.data[("key_1", "key_2", 5, ..., "key_n")] * Data casters for specific JSON element types, subsequent to an index or path operation being invoked:: data_table.c.data["some key"].as_integer() Additional operations may be available from the dialect-specific versions of :class:`_types.JSON`, such as :class:`sqlalchemy.dialects.postgresql.JSON` and :class:`sqlalchemy.dialects.postgresql.JSONB` which both offer additional PostgreSQL-specific operations. **Casting JSON Elements to Other Types** Index operations, i.e. those invoked by calling upon the expression using the Python bracket operator as in ``some_column['some key']``, return an expression object whose type defaults to :class:`_types.JSON` by default, so that further JSON-oriented instructions may be called upon the result type. However, it is likely more common that an index operation is expected to return a specific scalar element, such as a string or integer. In order to provide access to these elements in a backend-agnostic way, a series of data casters are provided: * :meth:`.JSON.Comparator.as_string` - return the element as a string * :meth:`.JSON.Comparator.as_boolean` - return the element as a boolean * :meth:`.JSON.Comparator.as_float` - return the element as a float * :meth:`.JSON.Comparator.as_integer` - return the element as an integer These data casters are implemented by supporting dialects in order to assure that comparisons to the above types will work as expected, such as:: # integer comparison data_table.c.data["some_integer_key"].as_integer() == 5 # boolean comparison data_table.c.data["some_boolean"].as_boolean() == True .. note:: The data caster functions are new in version 1.3.11, and supersede the previous documented approaches of using CAST; for reference, this looked like:: from sqlalchemy import cast, type_coerce from sqlalchemy import String, JSON cast(data_table.c.data["some_key"], String) == type_coerce(55, JSON) The above case now works directly as:: data_table.c.data["some_key"].as_integer() == 5 For details on the previous comparison approach within the 1.3.x series, see the documentation for SQLAlchemy 1.2 or the included HTML files in the doc/ directory of the version's distribution. **Detecting Changes in JSON columns when using the ORM** The :class:`_types.JSON` type, when used with the SQLAlchemy ORM, does not detect in-place mutations to the structure. In order to detect these, the :mod:`sqlalchemy.ext.mutable` extension must be used, most typically using the :class:`.MutableDict` class. This extension will allow "in-place" changes to the datastructure to produce events which will be detected by the unit of work. See the example at :class:`.HSTORE` for a simple example involving a dictionary. Alternatively, assigning a JSON structure to an ORM element that replaces the old one will always trigger a change event. **Support for JSON null vs. SQL NULL** When working with NULL values, the :class:`_types.JSON` type recommends the use of two specific constants in order to differentiate between a column that evaluates to SQL NULL, e.g. no value, vs. the JSON-encoded string of ``"null"``. To insert or select against a value that is SQL NULL, use the constant :func:`.null`. This symbol may be passed as a parameter value specifically when using the :class:`_types.JSON` datatype, which contains special logic that interprets this symbol to mean that the column value should be SQL NULL as opposed to JSON ``"null"``:: from sqlalchemy import null conn.execute(table.insert(), {"json_value": null()}) To insert or select against a value that is JSON ``"null"``, use the constant :attr:`_types.JSON.NULL`:: conn.execute(table.insert(), {"json_value": JSON.NULL}) The :class:`_types.JSON` type supports a flag :paramref:`_types.JSON.none_as_null` which when set to True will result in the Python constant ``None`` evaluating to the value of SQL NULL, and when set to False results in the Python constant ``None`` evaluating to the value of JSON ``"null"``. The Python value ``None`` may be used in conjunction with either :attr:`_types.JSON.NULL` and :func:`.null` in order to indicate NULL values, but care must be taken as to the value of the :paramref:`_types.JSON.none_as_null` in these cases. **Customizing the JSON Serializer** The JSON serializer and deserializer used by :class:`_types.JSON` defaults to Python's ``json.dumps`` and ``json.loads`` functions; in the case of the psycopg2 dialect, psycopg2 may be using its own custom loader function. In order to affect the serializer / deserializer, they are currently configurable at the :func:`_sa.create_engine` level via the :paramref:`_sa.create_engine.json_serializer` and :paramref:`_sa.create_engine.json_deserializer` parameters. For example, to turn off ``ensure_ascii``:: engine = create_engine( "sqlite://", json_serializer=lambda obj: json.dumps(obj, ensure_ascii=False), ) .. seealso:: :class:`sqlalchemy.dialects.postgresql.JSON` :class:`sqlalchemy.dialects.postgresql.JSONB` :class:`sqlalchemy.dialects.mysql.JSON` :class:`sqlalchemy.dialects.sqlite.JSON` """ # noqa: E501 __visit_name__ = "JSON" operator_classes = OperatorClass.JSON hashable = False NULL = util.symbol("JSON_NULL") """Describe the json value of NULL. This value is used to force the JSON value of ``"null"`` to be used as the value. A value of Python ``None`` will be recognized either as SQL NULL or JSON ``"null"``, based on the setting of the :paramref:`_types.JSON.none_as_null` flag; the :attr:`_types.JSON.NULL` constant can be used to always resolve to JSON ``"null"`` regardless of this setting. This is in contrast to the :func:`_expression.null` construct, which always resolves to SQL NULL. E.g.:: from sqlalchemy import null from sqlalchemy.dialects.postgresql import JSON # will *always* insert SQL NULL obj1 = MyObject(json_value=null()) # will *always* insert JSON string "null" obj2 = MyObject(json_value=JSON.NULL) session.add_all([obj1, obj2]) session.commit() In order to set JSON NULL as a default value for a column, the most transparent method is to use :func:`_expression.text`:: Table( "my_table", metadata, Column("json_data", JSON, default=text("'null'")) ) While it is possible to use :attr:`_types.JSON.NULL` in this context, the :attr:`_types.JSON.NULL` value will be returned as the value of the column, which in the context of the ORM or other repurposing of the default value, may not be desirable. Using a SQL expression means the value will be re-fetched from the database within the context of retrieving generated defaults. """ # noqa: E501 def __init__(self, none_as_null: bool = False): """Construct a :class:`_types.JSON` type. :param none_as_null=False: if True, persist the value ``None`` as a SQL NULL value, not the JSON encoding of ``null``. Note that when this flag is False, the :func:`.null` construct can still be used to persist a NULL value, which may be passed directly as a parameter value that is specially interpreted by the :class:`_types.JSON` type as SQL NULL:: from sqlalchemy import null conn.execute(table.insert(), {"data": null()}) .. note:: :paramref:`_types.JSON.none_as_null` does **not** apply to the values passed to :paramref:`_schema.Column.default` and :paramref:`_schema.Column.server_default`; a value of ``None`` passed for these parameters means "no default present". Additionally, when used in SQL comparison expressions, the Python value ``None`` continues to refer to SQL null, and not JSON NULL. The :paramref:`_types.JSON.none_as_null` flag refers explicitly to the **persistence** of the value within an INSERT or UPDATE statement. The :attr:`_types.JSON.NULL` value should be used for SQL expressions that wish to compare to JSON null. .. seealso:: :attr:`.types.JSON.NULL` """ self.none_as_null = none_as_null class JSONElementType(TypeEngine[Any]): """Common function for index / path elements in a JSON expression.""" _integer = Integer() _string = String() def string_bind_processor( self, dialect: Dialect ) -> Optional[_BindProcessorType[str]]: return self._string._cached_bind_processor(dialect) def string_literal_processor( self, dialect: Dialect ) -> Optional[_LiteralProcessorType[str]]: return self._string._cached_literal_processor(dialect) def bind_processor(self, dialect: Dialect) -> _BindProcessorType[Any]: int_processor = self._integer._cached_bind_processor(dialect) string_processor = self.string_bind_processor(dialect) def process(value: Optional[Any]) -> Any: if int_processor and isinstance(value, int): value = int_processor(value) elif string_processor and isinstance(value, str): value = string_processor(value) return value return process def literal_processor( self, dialect: Dialect ) -> _LiteralProcessorType[Any]: int_processor = self._integer._cached_literal_processor(dialect) string_processor = self.string_literal_processor(dialect) def process(value: Optional[Any]) -> Any: if int_processor and isinstance(value, int): value = int_processor(value) elif string_processor and isinstance(value, str): value = string_processor(value) else: raise NotImplementedError() return value return process class JSONIndexType(JSONElementType): """Placeholder for the datatype of a JSON index value. This allows execution-time processing of JSON index values for special syntaxes. """ class JSONIntIndexType(JSONIndexType): """Placeholder for the datatype of a JSON index value. This allows execution-time processing of JSON index values for special syntaxes. """ class JSONStrIndexType(JSONIndexType): """Placeholder for the datatype of a JSON index value. This allows execution-time processing of JSON index values for special syntaxes. """ class JSONPathType(JSONElementType): """Placeholder type for JSON path operations. This allows execution-time processing of a path-based index value into a specific SQL syntax. """ __visit_name__ = "json_path" class Comparator(Indexable.Comparator[_T], Concatenable.Comparator[_T]): """Define comparison operations for :class:`_types.JSON`.""" __slots__ = () type: JSON def _setup_getitem(self, index): if not isinstance(index, str) and isinstance( index, collections_abc.Sequence ): index = coercions.expect( roles.BinaryElementRole, index, expr=self.expr, operator=operators.json_path_getitem_op, bindparam_type=JSON.JSONPathType, ) operator = operators.json_path_getitem_op else: index = coercions.expect( roles.BinaryElementRole, index, expr=self.expr, operator=operators.json_getitem_op, bindparam_type=( JSON.JSONIntIndexType if isinstance(index, int) else JSON.JSONStrIndexType ), ) operator = operators.json_getitem_op return operator, index, self.type def as_boolean(self): """Consider an indexed value as boolean. This is similar to using :class:`_sql.type_coerce`, and will usually not apply a ``CAST()``. e.g.:: stmt = select(mytable.c.json_column["some_data"].as_boolean()).where( mytable.c.json_column["some_data"].as_boolean() == True ) """ # noqa: E501 return self._binary_w_type(Boolean(), "as_boolean") def as_string(self): """Consider an indexed value as string. This is similar to using :class:`_sql.type_coerce`, and will usually not apply a ``CAST()``. e.g.:: stmt = select(mytable.c.json_column["some_data"].as_string()).where( mytable.c.json_column["some_data"].as_string() == "some string" ) """ # noqa: E501 return self._binary_w_type(Unicode(), "as_string") def as_integer(self): """Consider an indexed value as integer. This is similar to using :class:`_sql.type_coerce`, and will usually not apply a ``CAST()``. e.g.:: stmt = select(mytable.c.json_column["some_data"].as_integer()).where( mytable.c.json_column["some_data"].as_integer() == 5 ) """ # noqa: E501 return self._binary_w_type(Integer(), "as_integer") def as_float(self): """Consider an indexed value as float. This is similar to using :class:`_sql.type_coerce`, and will usually not apply a ``CAST()``. e.g.:: stmt = select(mytable.c.json_column["some_data"].as_float()).where( mytable.c.json_column["some_data"].as_float() == 29.75 ) """ # noqa: E501 return self._binary_w_type(Float(), "as_float") def as_numeric(self, precision, scale, asdecimal=True): """Consider an indexed value as numeric/decimal. This is similar to using :class:`_sql.type_coerce`, and will usually not apply a ``CAST()``. e.g.:: stmt = select(mytable.c.json_column["some_data"].as_numeric(10, 6)).where( mytable.c.json_column["some_data"].as_numeric(10, 6) == 29.75 ) .. versionadded:: 1.4.0b2 """ # noqa: E501 return self._binary_w_type( Numeric(precision, scale, asdecimal=asdecimal), "as_numeric" ) def as_json(self): """Consider an indexed value as JSON. This is similar to using :class:`_sql.type_coerce`, and will usually not apply a ``CAST()``. e.g.:: stmt = select(mytable.c.json_column["some_data"].as_json()) This is typically the default behavior of indexed elements in any case. Note that comparison of full JSON structures may not be supported by all backends. """ return self.expr def _binary_w_type(self, typ, method_name): if not isinstance( self.expr, elements.BinaryExpression ) or self.expr.operator not in ( operators.json_getitem_op, operators.json_path_getitem_op, ): raise exc.InvalidRequestError( "The JSON cast operator JSON.%s() only works with a JSON " "index expression e.g. col['q'].%s()" % (method_name, method_name) ) expr = self.expr._clone() expr.type = typ return expr comparator_factory = Comparator @property def should_evaluate_none(self): """Alias of :attr:`_types.JSON.none_as_null`""" return not self.none_as_null @should_evaluate_none.setter def should_evaluate_none(self, value): self.none_as_null = not value @util.memoized_property def _str_impl(self): return String() def _make_bind_processor(self, string_process, json_serializer): if string_process: def process(value): if value is self.NULL: value = None elif isinstance(value, elements.Null) or ( value is None and self.none_as_null ): return None serialized = json_serializer(value) return string_process(serialized) else: def process(value): if value is self.NULL: value = None elif isinstance(value, elements.Null) or ( value is None and self.none_as_null ): return None return json_serializer(value) return process def bind_processor(self, dialect): string_process = self._str_impl.bind_processor(dialect) json_serializer = dialect._json_serializer or json.dumps return self._make_bind_processor(string_process, json_serializer) def result_processor(self, dialect, coltype): string_process = self._str_impl.result_processor(dialect, coltype) json_deserializer = dialect._json_deserializer or json.loads def process(value): if value is None: return None if string_process: value = string_process(value) return json_deserializer(value) return process
JSON
python
PrefectHQ__prefect
tests/test_flow_engine.py
{ "start": 64503, "end": 75421 }
class ____: async def get_flow_run_for_flow(self, flow_name: str): async with get_client() as prefect_client: flow_runs = await prefect_client.read_flow_runs( flow_filter=FlowFilter(name=FlowFilterName(any_=[flow_name])) ) assert len(flow_runs) == 1 return flow_runs[0] async def test_basic(self, engine_type: Literal["sync", "async"]): if engine_type == "sync": @flow(name=f"test_basic_{uuid.uuid4()}", persist_result=True) def foo(): return 42 else: @flow(name=f"test_basic_{uuid.uuid4()}", persist_result=True) async def foo(): return 42 process = run_flow_in_subprocess(foo) process.join() assert process.exitcode == 0 flow_run = await self.get_flow_run_for_flow(foo.name) assert flow_run.state.is_completed() assert await flow_run.state.result() == 42 async def test_with_params(self, engine_type: Literal["sync", "async"]): if engine_type == "sync": @flow(name=f"test_with_params_{uuid.uuid4()}", persist_result=True) def bar(x: int, y: Optional[str] = None): return x, y else: @flow(name=f"test_with_params_{uuid.uuid4()}", persist_result=True) async def bar(x: int, y: Optional[str] = None): return x, y parameters = get_call_parameters(bar.fn, (42,), dict(y="nate")) process = run_flow_in_subprocess(bar, parameters=parameters) process.join() assert process.exitcode == 0 flow_run = await self.get_flow_run_for_flow(bar.name) assert flow_run.state.is_completed() assert await flow_run.state.result() == (42, "nate") async def test_flow_ends_in_failed(self, engine_type: Literal["sync", "async"]): if engine_type == "sync": @flow(name=f"test_flow_ends_in_failed_{uuid.uuid4()}") def foo(): raise ValueError("xyz") else: @flow(name=f"test_flow_ends_in_failed_{uuid.uuid4()}") async def foo(): raise ValueError("xyz") process = run_flow_in_subprocess(foo) process.join() assert process.exitcode == 1 flow_run = await self.get_flow_run_for_flow(foo.name) assert flow_run.state.is_failed() async def test_tracks_parent_when_run_in_flow( self, prefect_client: PrefectClient, engine_type: Literal["sync", "async"] ): if engine_type == "sync": @flow(name=f"child_flow_{uuid.uuid4()}", persist_result=True) def child_flow(): return 42 else: @flow(name=f"child_flow_{uuid.uuid4()}", persist_result=True) async def child_flow(): return 42 @flow(name=f"parent_flow_{uuid.uuid4()}", persist_result=True) def parent_flow(): process = run_flow_in_subprocess(child_flow) process.join() return process.exitcode assert run_flow(parent_flow) == 0 parent_flow_run = await self.get_flow_run_for_flow(parent_flow.name) child_flow_run = await self.get_flow_run_for_flow(child_flow.name) dummy_task_run = await prefect_client.read_task_run( child_flow_run.parent_task_run_id ) assert dummy_task_run.flow_run_id == parent_flow_run.id async def test_with_provided_context( self, prefect_client: PrefectClient, engine_type: Literal["sync", "async"] ): tags_context = TagsContext(current_tags={"foo", "bar"}) if engine_type == "sync": @flow( name=f"test_with_provided_context_{uuid.uuid4()}", persist_result=True ) def foo(): return TagsContext.get().current_tags else: @flow( name=f"test_with_provided_context_{uuid.uuid4()}", persist_result=True ) async def foo(): return TagsContext.get().current_tags context = {"tags_context": tags_context.serialize()} process = run_flow_in_subprocess(foo, context=context) process.join() assert process.exitcode == 0 flow_run = await self.get_flow_run_for_flow(foo.name) assert flow_run.state.is_completed() assert await flow_run.state.result() == {"foo", "bar"} async def test_with_provided_flow_run( self, engine_type: Literal["sync", "async"], prefect_client: PrefectClient ): if engine_type == "sync": @flow( name=f"test_with_provided_flow_run_{uuid.uuid4()}", persist_result=True ) def foo(): return 42 else: @flow( name=f"test_with_provided_flow_run_{uuid.uuid4()}", persist_result=True ) async def foo(): return 42 flow_run = await prefect_client.create_flow_run( flow=foo, ) process = run_flow_in_subprocess(foo, flow_run=flow_run) process.join() assert process.exitcode == 0 flow_run = await prefect_client.read_flow_run(flow_run.id) assert flow_run.state.is_completed() assert await flow_run.state.result() == 42 async def test_flow_is_suspended( self, engine_type: Literal["sync", "async"], prefect_client: PrefectClient ): if engine_type == "sync": @flow(name=f"test_flow_is_suspended_{uuid.uuid4()}", persist_result=True) def foo(): suspend_flow_run() return 42 else: @flow(name=f"test_flow_is_suspended_{uuid.uuid4()}", persist_result=True) async def foo(): await suspend_flow_run() return 42 flow_id = await prefect_client.create_flow(foo) deployment_id = await prefect_client.create_deployment( flow_id=flow_id, name=f"test_flow_is_suspended_{uuid.uuid4()}", ) flow_run = await prefect_client.create_flow_run_from_deployment(deployment_id) process = run_flow_in_subprocess(foo, flow_run) process.join() assert process.exitcode == 0 flow_run = await prefect_client.read_flow_run(flow_run.id) assert flow_run.state.is_paused() async def test_flow_is_aborted( self, engine_type: Literal["sync", "async"], prefect_client: PrefectClient ): if engine_type == "sync": @flow(name=f"test_flow_is_aborted_{uuid.uuid4()}", persist_result=True) def foo(): raise Abort() else: @flow(name=f"test_flow_is_aborted_{uuid.uuid4()}", persist_result=True) async def foo(): raise Abort() flow_id = await prefect_client.create_flow(foo) deployment_id = await prefect_client.create_deployment( flow_id=flow_id, name=f"test_flow_is_suspended_{uuid.uuid4()}", ) flow_run = await prefect_client.create_flow_run_from_deployment(deployment_id) process = run_flow_in_subprocess(foo, flow_run) process.join() assert process.exitcode == 0 flow_run = await prefect_client.read_flow_run(flow_run.id) # Stays in running state because the flow run is aborted manually assert flow_run.state.is_running() async def test_deployment_parameters_accessible_in_subprocess( self, engine_type: Literal["sync", "async"], prefect_client: PrefectClient ): """Test that deployment.parameters is accessible in subprocess (issue #19329).""" deployment_params = { "source_name": "ABC", "database_export_date": "2025-08-27", "bucket_name": "data-migration", } if engine_type == "sync": @flow(name=f"test_deployment_params_{uuid.uuid4()}", persist_result=True) def foo(source_name: str, database_export_date: str, bucket_name: str): from prefect.runtime import deployment return deployment.parameters else: @flow(name=f"test_deployment_params_{uuid.uuid4()}", persist_result=True) async def foo( source_name: str, database_export_date: str, bucket_name: str ): from prefect.runtime import deployment return deployment.parameters flow_id = await prefect_client.create_flow(foo) deployment_id = await prefect_client.create_deployment( flow_id=flow_id, name=f"test_deployment_params_{uuid.uuid4()}", parameters=deployment_params, ) flow_run = await prefect_client.create_flow_run_from_deployment(deployment_id) process = run_flow_in_subprocess(foo, flow_run) process.join() assert process.exitcode == 0 flow_run = await prefect_client.read_flow_run(flow_run.id) assert flow_run.state.is_completed() # deployment.parameters should match what we set result = await flow_run.state.result() assert result == deployment_params async def test_flow_raises_a_base_exception( self, engine_type: Literal["sync", "async"] ): if engine_type == "sync": @flow( name=f"test_flow_raises_a_base_exception_{uuid.uuid4()}", persist_result=True, ) def foo(): raise BaseException() else: @flow( name=f"test_flow_raises_a_base_exception_{uuid.uuid4()}", persist_result=True, ) async def foo(): raise BaseException() process = run_flow_in_subprocess(foo) process.join() assert process.exitcode == 1 flow_run = await self.get_flow_run_for_flow(foo.name) assert flow_run.state.is_crashed() async def test_flow_process_is_killed(self, engine_type: Literal["sync", "async"]): if engine_type == "sync": @flow( name=f"test_flow_process_is_killed_{uuid.uuid4()}", persist_result=True ) def foo(): signal.raise_signal(signal.SIGKILL) else: @flow( name=f"test_flow_process_is_killed_{uuid.uuid4()}", persist_result=True ) async def foo(): signal.raise_signal(signal.SIGKILL) process = run_flow_in_subprocess(foo) process.join() assert process.exitcode == -9 flow_run = await self.get_flow_run_for_flow(foo.name) # Stays in running state because the process died assert flow_run.state.is_running()
TestRunFlowInSubprocess
python
apache__airflow
providers/databricks/src/airflow/providers/databricks/utils/mixins.py
{ "start": 2383, "end": 7407 }
class ____: """ Mixin class to be used by both the DatabricksSqlStatementsOperator, and the DatabricksSqlStatementSensor. - _handle_operator_execution (renamed to _handle_execution) - _handle_deferrable_operator_execution (renamed to _handle_deferrable_execution) - execute_complete - on_kill """ def _handle_execution(self: HandleExecutionHasFields) -> None: """Execute a SQL statement in non-deferrable mode.""" # Determine the time at which the Task will timeout. The statement_state is defined here in the event # the while-loop is never entered end_time = time.time() + self.timeout while end_time > time.time(): statement_state: SQLStatementState = self._hook.get_sql_statement_state(self.statement_id) if statement_state.is_terminal: if statement_state.is_successful: self.log.info("%s completed successfully.", self.task_id) return error_message = ( f"{self.task_id} failed with terminal state: {statement_state.state} " f"and with the error code {statement_state.error_code} " f"and error message {statement_state.error_message}" ) raise AirflowException(error_message) self.log.info("%s in run state: %s", self.task_id, statement_state.state) self.log.info("Sleeping for %s seconds.", self.polling_period_seconds) time.sleep(self.polling_period_seconds) # Once the timeout is exceeded, the query is cancelled. This is an important steps; if a query takes # to log, it needs to be killed. Otherwise, it may be the case that there are "zombie" queries running # that are no longer being orchestrated self._hook.cancel_sql_statement(self.statement_id) raise AirflowException( f"{self.task_id} timed out after {self.timeout} seconds with state: {statement_state}", ) def _handle_deferrable_execution( self: HandleDeferrableExecutionHasFields, defer_method_name: str = "execute_complete" ) -> None: """Execute a SQL statement in deferrable mode.""" statement_state: SQLStatementState = self._hook.get_sql_statement_state(self.statement_id) end_time: float = time.time() + self.timeout if not statement_state.is_terminal: # If the query is still running and there is no statement_id, this is somewhat of a "zombie" # query, and should throw an exception if not self.statement_id: raise AirflowException("Failed to retrieve statement_id after submitting SQL statement.") self.defer( trigger=DatabricksSQLStatementExecutionTrigger( statement_id=self.statement_id, databricks_conn_id=self.databricks_conn_id, end_time=end_time, polling_period_seconds=self.polling_period_seconds, retry_limit=self.databricks_retry_limit, retry_delay=self.databricks_retry_delay, retry_args=self.databricks_retry_args, ), method_name=defer_method_name, ) else: if statement_state.is_successful: self.log.info("%s completed successfully.", self.task_id) else: error_message = ( f"{self.task_id} failed with terminal state: {statement_state.state} " f"and with the error code {statement_state.error_code} " f"and error message {statement_state.error_message}" ) raise AirflowException(error_message) def execute_complete(self: ExecuteCompleteHasFields, context: Context, event: dict): statement_state = SQLStatementState.from_json(event["state"]) error = event["error"] # Save as instance attribute again after coming back from defer (e.g., for later use in listeners) self.statement_id = event["statement_id"] if statement_state.is_successful: self.log.info("SQL Statement with ID %s completed successfully.", self.statement_id) return error_message = f"SQL Statement execution failed with terminal state: {statement_state} and with the error {error}" raise AirflowException(error_message) def on_kill(self: OnKillHasFields) -> None: if self.statement_id: self._hook.cancel_sql_statement(self.statement_id) self.log.info( "Task: %s with statement ID: %s was requested to be cancelled.", self.task_id, self.statement_id, ) else: self.log.error( "Error: Task: %s with invalid statement_id was requested to be cancelled.", self.task_id )
DatabricksSQLStatementsMixin
python
mahmoud__glom
glom/core.py
{ "start": 67102, "end": 67649 }
class ____: """Evaluate specs one after the other, passing the result of the previous evaluation in as the target of the next spec: >>> glom({'a': {'b': -5}}, Pipe('a', 'b', abs)) 5 Same behavior as ``Auto(tuple(steps))``, but useful for explicit usage in other modes. """ def __init__(self, *steps): self.steps = steps def glomit(self, target, scope): return _handle_tuple(target, self.steps, scope) def __repr__(self): return self.__class__.__name__ + bbrepr(self.steps)
Pipe
python
langchain-ai__langchain
libs/langchain_v1/tests/unit_tests/agents/test_system_message.py
{ "start": 2089, "end": 10806 }
class ____: """Test ModelRequest with system_message field.""" @pytest.mark.parametrize( "system_message,system_prompt,expected_msg,expected_prompt", [ # Test with SystemMessage ( SystemMessage(content="You are helpful"), None, SystemMessage(content="You are helpful"), "You are helpful", ), # Test with None (None, None, None, None), # Test with string (backward compat) (None, "You are helpful", SystemMessage(content="You are helpful"), "You are helpful"), ], ) def test_create_with_various_system_inputs( self, system_message, system_prompt, expected_msg, expected_prompt ) -> None: """Test creating ModelRequest with various system message inputs.""" model = GenericFakeChatModel(messages=iter([AIMessage(content="Hello")])) request = ModelRequest( model=model, system_message=system_message, system_prompt=system_prompt, messages=[HumanMessage("Hi")], tool_choice=None, tools=[], response_format=None, state={}, runtime=None, ) if expected_msg is None: assert request.system_message is None else: assert request.system_message.content == expected_msg.content assert request.system_prompt == expected_prompt def test_system_prompt_property_with_list_content(self) -> None: """Test system_prompt property handles list content.""" model = GenericFakeChatModel(messages=iter([AIMessage(content="Hello")])) system_msg = SystemMessage(content=["Part 1", "Part 2"]) request = ModelRequest( model=model, system_message=system_msg, messages=[], tool_choice=None, tools=[], response_format=None, state={}, runtime=None, ) assert request.system_prompt is not None assert "Part 1" in request.system_prompt @pytest.mark.parametrize( "override_with,expected_text", [ ("system_message", "New"), ("system_prompt", "New prompt"), ], ) def test_override_methods(self, override_with, expected_text) -> None: """Test override() with system_message and system_prompt parameters.""" model = GenericFakeChatModel(messages=iter([AIMessage(content="Hello")])) original_msg = SystemMessage(content="Original") original_request = ModelRequest( model=model, system_message=original_msg, messages=[], tool_choice=None, tools=[], response_format=None, state={}, runtime=None, ) if override_with == "system_message": new_request = original_request.override(system_message=SystemMessage(content="New")) else: # system_prompt new_request = original_request.override(system_prompt="New prompt") assert isinstance(new_request.system_message, SystemMessage) assert new_request.system_prompt == expected_text assert original_request.system_prompt == "Original" def test_override_system_prompt_to_none(self) -> None: """Test override() setting system_prompt to None.""" model = GenericFakeChatModel(messages=iter([AIMessage(content="Hello")])) original_request = ModelRequest( model=model, system_message=SystemMessage(content="Original"), messages=[], tool_choice=None, tools=[], response_format=None, state={}, runtime=None, ) new_request = original_request.override(system_prompt=None) assert new_request.system_message is None assert new_request.system_prompt is None @pytest.mark.parametrize( "use_constructor", [True, False], ids=["constructor", "override"], ) def test_cannot_set_both_system_prompt_and_system_message(self, use_constructor) -> None: """Test that setting both system_prompt and system_message raises error.""" model = GenericFakeChatModel(messages=iter([AIMessage(content="Hello")])) with pytest.raises(ValueError, match="Cannot specify both"): if use_constructor: ModelRequest( model=model, system_prompt="String prompt", system_message=SystemMessage(content="Message prompt"), messages=[], tool_choice=None, tools=[], response_format=None, state={}, runtime=None, ) else: request = ModelRequest( model=model, system_message=None, messages=[], tool_choice=None, tools=[], response_format=None, state={}, runtime=None, ) request.override( system_prompt="String prompt", system_message=SystemMessage(content="Message prompt"), ) @pytest.mark.parametrize( "new_value,should_be_none", [ ("New prompt", False), (None, True), ], ) def test_setattr_system_prompt_deprecated(self, new_value, should_be_none) -> None: """Test that setting system_prompt via setattr raises deprecation warning.""" model = GenericFakeChatModel(messages=iter([AIMessage(content="Hello")])) request = ModelRequest( model=model, system_message=SystemMessage(content="Original") if not should_be_none else None, messages=[], tool_choice=None, tools=[], response_format=None, state={}, runtime=None, ) with pytest.warns(DeprecationWarning, match="system_prompt is deprecated"): request.system_prompt = new_value if should_be_none: assert request.system_message is None assert request.system_prompt is None else: assert isinstance(request.system_message, SystemMessage) assert request.system_message.content_blocks[0]["text"] == new_value def test_system_message_with_complex_content(self) -> None: """Test SystemMessage with complex content (list of dicts).""" model = GenericFakeChatModel(messages=iter([AIMessage(content="Hello")])) system_msg = SystemMessage( content=[ {"type": "text", "text": "You are helpful"}, {"type": "text", "text": "Be concise", "cache_control": {"type": "ephemeral"}}, ] ) request = ModelRequest( model=model, system_message=system_msg, messages=[], tool_choice=None, tools=[], response_format=None, state={}, runtime=None, ) assert isinstance(request.system_message.content_blocks, list) assert len(request.system_message.content_blocks) == 2 assert request.system_message.content_blocks[1].get("cache_control") == { "type": "ephemeral" } def test_multiple_overrides_with_system_message(self) -> None: """Test chaining overrides with system_message.""" model = GenericFakeChatModel(messages=iter([AIMessage(content="Hello")])) original_request = ModelRequest( model=model, system_message=SystemMessage(content="Prompt 1"), messages=[], tool_choice=None, tools=[], response_format=None, state={}, runtime=None, ) final_request = ( original_request.override(system_message=SystemMessage(content="Prompt 2")) .override(tool_choice="auto") .override(system_message=SystemMessage(content="Prompt 3")) ) assert final_request.system_prompt == "Prompt 3" assert final_request.tool_choice == "auto" assert original_request.system_prompt == "Prompt 1" # ============================================================================= # create_agent Tests # =============================================================================
TestModelRequestSystemMessage
python
getsentry__sentry
src/sentry/preprod/pull_request/types.py
{ "start": 225, "end": 359 }
class ____(StrEnum): ADDED = "added" MODIFIED = "modified" REMOVED = "removed" RENAMED = "renamed"
PullRequestFileStatus
python
apache__airflow
dev/breeze/src/airflow_breeze/commands/release_management_commands.py
{ "start": 106240, "end": 171034 }
class ____(NamedTuple): """Stores details about commits""" full_hash: str short_hash: str date: str message: str message_without_backticks: str pr: int | None def get_change_from_line(line: str): split_line = line.split(" ", maxsplit=3) message = split_line[3] pr = None pr_match = PR_PATTERN.match(message) if pr_match: pr = pr_match.group(1) return Change( full_hash=split_line[0], short_hash=split_line[1], date=split_line[2], message=message, message_without_backticks=message.replace("`", "'").replace("&#39;", "'").replace("&amp;", "&"), pr=int(pr) if pr else None, ) def get_changes( verbose: bool, previous_release: str, current_release: str, is_helm_chart: bool = False, ) -> list[Change]: print(MY_DIR_PATH, SOURCE_DIR_PATH) change_strings = subprocess.check_output( get_git_log_command( verbose, from_commit=previous_release, to_commit=current_release, is_helm_chart=is_helm_chart, ), cwd=SOURCE_DIR_PATH, text=True, ) return [get_change_from_line(line) for line in change_strings.splitlines()] def render_template( template_name: str, context: dict[str, Any], autoescape: bool = True, keep_trailing_newline: bool = False, ) -> str: import jinja2 template_loader = jinja2.FileSystemLoader(searchpath=MY_DIR_PATH) template_env = jinja2.Environment( loader=template_loader, undefined=jinja2.StrictUndefined, autoescape=autoescape, keep_trailing_newline=keep_trailing_newline, ) template = template_env.get_template(f"{template_name}_TEMPLATE.md.jinja2") content: str = template.render(context) return content def print_issue_content( current_release: str, pull_requests, linked_issues, users: dict[int, set[str]], is_helm_chart: bool = False, ): link = f"https://pypi.org/project/apache-airflow/{current_release}/" link_text = f"Apache Airflow RC {current_release}" if is_helm_chart: link = f"https://dist.apache.org/repos/dist/dev/airflow/{current_release}" link_text = f"Apache Airflow Helm Chart {current_release.split('/')[-1]}" # Only include PRs that have corresponding user data to avoid KeyError in template pr_list = sorted([pr for pr in pull_requests.keys() if pr in users]) user_logins: dict[int, str] = {pr: " ".join(f"@{u}" for u in uu) for pr, uu in users.items()} all_users: set[str] = set() for user_list in users.values(): all_users.update(user_list) all_users = {user for user in all_users if user not in {"github-actions[bot]", "dependabot[bot]"}} all_user_logins = " ".join(f"@{u}" for u in all_users) content = render_template( template_name="ISSUE", context={ "link": link, "link_text": link_text, "pr_list": pr_list, "pull_requests": pull_requests, "linked_issues": linked_issues, "users": users, "user_logins": user_logins, "all_user_logins": all_user_logins, }, autoescape=False, keep_trailing_newline=True, ) print(content) @release_management_group.command( name="generate-issue-content-helm-chart", help="Generates content for issue to test the helm chart release.", ) @click.option( "--github-token", envvar="GITHUB_TOKEN", help=textwrap.dedent( """ GitHub token used to authenticate. You can set omit it if you have GITHUB_TOKEN env variable set. Can be generated with: https://github.com/settings/tokens/new?description=Read%20sssues&scopes=repo:status""" ), ) @click.option( "--previous-release", type=str, help="commit reference (for example hash or tag) of the previous release.", required=True, ) @click.option( "--current-release", type=str, help="commit reference (for example hash or tag) of the current release.", required=True, ) @click.option("--excluded-pr-list", type=str, help="Coma-separated list of PRs to exclude from the issue.") @click.option( "--limit-pr-count", type=int, default=None, help="Limit PR count processes (useful for testing small subset of PRs).", ) @option_verbose def generate_issue_content_helm_chart( github_token: str, previous_release: str, current_release: str, excluded_pr_list: str, limit_pr_count: int | None, ): generate_issue_content( github_token, previous_release, current_release, excluded_pr_list, limit_pr_count, is_helm_chart=True, ) @release_management_group.command( name="generate-issue-content-core", help="Generates content for issue to test the core release." ) @click.option( "--github-token", envvar="GITHUB_TOKEN", help=textwrap.dedent( """ GitHub token used to authenticate. You can set omit it if you have GITHUB_TOKEN env variable set. Can be generated with: https://github.com/settings/tokens/new?description=Read%20sssues&scopes=repo:status""" ), ) @click.option( "--previous-release", type=str, help="commit reference (for example hash or tag) of the previous release.", required=True, ) @click.option( "--current-release", type=str, help="commit reference (for example hash or tag) of the current release.", required=True, ) @click.option("--excluded-pr-list", type=str, help="Coma-separated list of PRs to exclude from the issue.") @click.option( "--limit-pr-count", type=int, default=None, help="Limit PR count processes (useful for testing small subset of PRs).", ) @option_verbose def generate_issue_content_core( github_token: str, previous_release: str, current_release: str, excluded_pr_list: str, limit_pr_count: int | None, ): generate_issue_content( github_token, previous_release, current_release, excluded_pr_list, limit_pr_count, is_helm_chart=False, ) @release_management_group.command( name="generate-providers-metadata", help="Generates metadata for providers." ) @click.option( "--refresh-constraints-and-airflow-releases", is_flag=True, envvar="REFRESH_CONSTRAINTS_AND_AIRFLOW_RELEASES", help="Refresh constraints and airflow_releases before generating metadata", ) @click.option( "--provider-id", type=BetterChoice(get_available_distributions(include_removed=True, include_suspended=True)), envvar="PROVIDER_ID", help="Provider_id to generate metadata for. If not specified, metadata for all packages will be generated. " "This is debug-only option. When this option is specified, the metadata produced for " "the distribution will not be written to the file, but printed via console.", ) @click.option( "--provider-version", type=str, envvar="PROVIDER_VERSION", help="Provider version to generate metadata for. Only used when --provider-id is specified. Limits running " "metadata generation to only this version of the provider.", ) @option_github_token @option_dry_run @option_verbose def generate_providers_metadata( refresh_constraints_and_airflow_releases: bool, provider_id: str | None, provider_version: str | None, github_token: str | None, ): import json if PROVIDER_METADATA_JSON_PATH.exists(): current_metadata = json.loads(PROVIDER_METADATA_JSON_PATH.read_text()) else: current_metadata = {} metadata_dict: dict[str, dict[str, dict[str, str]]] = {} all_airflow_releases, airflow_release_dates = get_all_constraint_files_and_airflow_releases( refresh_constraints_and_airflow_releases=refresh_constraints_and_airflow_releases, airflow_constraints_mode=CONSTRAINTS, github_token=github_token, ) constraints = load_constraints() if provider_id: get_console().print(f"[info]Generating metadata for provider {provider_id} only (for debugging)[/]") result = generate_providers_metadata_for_provider( provider_id, provider_version=provider_version, constraints=constraints, all_airflow_releases=all_airflow_releases, airflow_release_dates=airflow_release_dates, current_metadata=current_metadata, ) if result: metadata_dict[provider_id] = result get_console().print(metadata_dict) return partial_generate_providers_metadata = partial( generate_providers_metadata_for_provider, provider_version=None, constraints=constraints, all_airflow_releases=all_airflow_releases, airflow_release_dates=airflow_release_dates, current_metadata=current_metadata, ) package_ids = DEPENDENCIES.keys() with Pool() as pool: results = pool.map( partial_generate_providers_metadata, package_ids, ) for package_id, result in zip(package_ids, results): if result: metadata_dict[package_id] = result PROVIDER_METADATA_JSON_PATH.write_text(json.dumps(metadata_dict, indent=4) + "\n") @release_management_group.command( name="update-providers-next-version", help="Update provider versions marked with '# use next version' comment.", ) @option_verbose def update_providers_next_version(): """ Scan all provider pyproject.toml files for dependencies with "# use next version" comment and update them to use the current version from the referenced provider's pyproject.toml. """ from airflow_breeze.utils.packages import update_providers_with_next_version_comment get_console().print("\n[info]Scanning for providers with '# use next version' comments...\n") updates_made = update_providers_with_next_version_comment() if updates_made: get_console().print("\n[success]Summary of updates:[/]") for provider_id, dependencies in updates_made.items(): get_console().print(f"\n[info]Provider: {provider_id}[/]") for dep_name, dep_info in dependencies.items(): get_console().print(f" • {dep_name}: {dep_info['old_version']} → {dep_info['new_version']}") get_console().print( f"\n[success]Updated {len(updates_made)} provider(s) with " f"{sum(len(deps) for deps in updates_made.values())} dependency change(s).[/]" ) else: get_console().print( "\n[info]No updates needed. All providers with '# use next version' " "comments are already using the latest versions.[/]" ) def fetch_remote(constraints_repo: Path, remote_name: str) -> None: run_command(["git", "fetch", remote_name], cwd=constraints_repo) def checkout_constraint_tag_and_reset_branch(constraints_repo: Path, airflow_version: str) -> None: run_command( ["git", "reset", "--hard"], cwd=constraints_repo, ) # Switch to tag run_command( ["git", "checkout", f"constraints-{airflow_version}"], cwd=constraints_repo, ) # Create or reset branch to point run_command( ["git", "checkout", "-B", f"constraints-{airflow_version}-fix"], cwd=constraints_repo, ) get_console().print( f"[info]Checked out constraints tag: constraints-{airflow_version} and " f"reset branch constraints-{airflow_version}-fix to it.[/]" ) result = run_command( ["git", "show", "-s", "--format=%H"], cwd=constraints_repo, text=True, capture_output=True, ) get_console().print(f"[info]The hash commit of the tag:[/] {result.stdout}") def update_comment(content: str, comment_file: Path) -> str: comment_text = comment_file.read_text() if comment_text in content: return content comment_lines = comment_text.splitlines() content_lines = content.splitlines() updated_lines: list[str] = [] updated = False for line in content_lines: if not line.strip().startswith("#") and not updated: updated_lines.extend(comment_lines) updated = True updated_lines.append(line) return "".join(f"{line}\n" for line in updated_lines) def modify_single_file_constraints( constraints_file: Path, updated_constraints: tuple[str, ...] | None, comment_file: Path | None ) -> bool: constraint_content = constraints_file.read_text() original_content = constraint_content if comment_file: constraint_content = update_comment(constraint_content, comment_file) if updated_constraints: for constraint in updated_constraints: package, version = constraint.split("==") constraint_content = re.sub( rf"^{package}==.*$", f"{package}=={version}", constraint_content, flags=re.MULTILINE ) if constraint_content != original_content: if not get_dry_run(): constraints_file.write_text(constraint_content) get_console().print("[success]Updated.[/]") return True get_console().print("[warning]The file has not been modified.[/]") return False def modify_all_constraint_files( constraints_repo: Path, updated_constraint: tuple[str, ...] | None, comment_file: Path | None, airflow_constrains_mode: str | None, ) -> bool: get_console().print("[info]Updating constraints files:[/]") modified = False select_glob = "constraints-*.txt" if airflow_constrains_mode == "constraints": select_glob = "constraints-[0-9.]*.txt" elif airflow_constrains_mode == "constraints-source-providers": select_glob = "constraints-source-providers-[0-9.]*.txt" elif airflow_constrains_mode == "constraints-no-providers": select_glob = "constraints-no-providers-[0-9.]*.txt" else: raise RuntimeError(f"Invalid airflow-constraints-mode: {airflow_constrains_mode}") for constraints_file in constraints_repo.glob(select_glob): get_console().print(f"[info]Updating {constraints_file.name}") if modify_single_file_constraints(constraints_file, updated_constraint, comment_file): modified = True return modified def confirm_modifications(constraints_repo: Path) -> bool: run_command(["git", "diff"], cwd=constraints_repo, env={"PAGER": ""}) confirm = user_confirm("Do you want to continue?") if confirm == Answer.YES: return True if confirm == Answer.NO: return False sys.exit(1) def commit_constraints_and_tag(constraints_repo: Path, airflow_version: str, commit_message: str) -> None: run_command( ["git", "commit", "-a", "--no-verify", "-m", commit_message], cwd=constraints_repo, ) run_command( ["git", "tag", f"constraints-{airflow_version}", "--force", "-s", "-m", commit_message, "HEAD"], cwd=constraints_repo, ) def push_constraints_and_tag(constraints_repo: Path, remote_name: str, airflow_version: str) -> None: run_command( ["git", "push", remote_name, f"constraints-{airflow_version}-fix"], cwd=constraints_repo, ) run_command( ["git", "push", remote_name, f"constraints-{airflow_version}", "--force"], cwd=constraints_repo, ) @release_management_group.command( name="update-constraints", help="Update released constraints with manual changes." ) @click.option( "--constraints-repo", type=click.Path(file_okay=False, dir_okay=True, path_type=Path, exists=True), required=True, envvar="CONSTRAINTS_REPO", help="Path where airflow repository is checked out, with ``constraints-main`` branch checked out.", ) @click.option( "--remote-name", type=str, default="apache", envvar="REMOTE_NAME", help="Name of the remote to push the changes to.", ) @click.option( "--airflow-versions", type=str, required=True, envvar="AIRFLOW_VERSIONS", help="Comma separated list of Airflow versions to update constraints for.", ) @click.option( "--commit-message", type=str, required=True, envvar="COMMIT_MESSAGE", help="Commit message to use for the constraints update.", ) @click.option( "--updated-constraint", required=False, envvar="UPDATED_CONSTRAINT", multiple=True, help="Constraints to be set - in the form of `package==version`. Can be repeated", ) @click.option( "--comment-file", required=False, type=click.Path(file_okay=True, dir_okay=False, path_type=Path, exists=True), envvar="COMMENT_FILE", help="File containing comment to be added to the constraint " "file before the first package (if not added yet).", ) @option_airflow_constraints_mode_update @option_verbose @option_dry_run @option_answer def update_constraints( constraints_repo: Path, remote_name: str, airflow_versions: str, commit_message: str, airflow_constraints_mode: str | None, updated_constraint: tuple[str, ...] | None, comment_file: Path | None, ) -> None: if not updated_constraint and not comment_file: get_console().print("[error]You have to provide one of --updated-constraint or --comment-file[/]") sys.exit(1) airflow_versions_array = airflow_versions.split(",") if not airflow_versions_array: get_console().print("[error]No airflow versions specified - you provided empty string[/]") sys.exit(1) get_console().print(f"Updating constraints for {airflow_versions_array} with {updated_constraint}") if ( user_confirm(f"The {constraints_repo.name} repo will be reset. Continue?", quit_allowed=False) != Answer.YES ): sys.exit(1) fetch_remote(constraints_repo, remote_name) for airflow_version in airflow_versions_array: checkout_constraint_tag_and_reset_branch(constraints_repo, airflow_version) if modify_all_constraint_files( constraints_repo, updated_constraint, comment_file, airflow_constraints_mode ): if confirm_modifications(constraints_repo): commit_constraints_and_tag(constraints_repo, airflow_version, commit_message) push_constraints_and_tag(constraints_repo, remote_name, airflow_version) def split_version_and_suffix(file_name: str, suffix: str) -> VersionedFile: from packaging.version import Version no_suffix_file = file_name[: -len(suffix)] no_version_file, version = no_suffix_file.rsplit("-", 1) no_version_file = no_version_file.replace("_", "-") return VersionedFile( base=no_version_file + "-", version=version, suffix=suffix, type=no_version_file + "-" + suffix, comparable_version=Version(version), file_name=file_name, ) def split_date_version_and_suffix(file_name: str, suffix: str) -> VersionedFile: """Split file name with date-based version (YYYY-MM-DD format) and suffix. Example: apache_airflow_providers-2025-11-18-source.tar.gz """ from packaging.version import Version no_suffix_file = file_name[: -len(suffix)] # Date format is YYYY-MM-DD, so we need to extract last 3 parts parts = no_suffix_file.rsplit("-", 3) if len(parts) != 4: raise ValueError(f"Invalid date-versioned file name format: {file_name}") no_version_file = parts[0] date_version = f"{parts[1]}-{parts[2]}-{parts[3]}" # Validate date format try: datetime.strptime(date_version, "%Y-%m-%d") except ValueError as e: raise ValueError(f"Invalid date format in file name {file_name}: {e}") no_version_file = no_version_file.replace("_", "-") # Convert date to a comparable version format (YYYYMMDD as integer-like version) comparable_date_str = date_version.replace("-", ".") return VersionedFile( base=no_version_file + "-", version=date_version, suffix=suffix, type=no_version_file + "-" + suffix, comparable_version=Version(comparable_date_str), file_name=file_name, ) PYTHON_CLIENT_DIR_PATH = AIRFLOW_ROOT_PATH / "clients" / "python" PYTHON_CLIENT_DIST_DIR_PATH = PYTHON_CLIENT_DIR_PATH / "dist" PYTHON_CLIENT_TMP_DIR = PYTHON_CLIENT_DIR_PATH / "tmp" REPRODUCIBLE_BUILD_YAML = AIRFLOW_ROOT_PATH / "reproducible_build.yaml" VERSION_FILE = PYTHON_CLIENT_DIR_PATH / "version.txt" SOURCE_API_YAML_PATH = ( AIRFLOW_ROOT_PATH / "airflow-core/src/airflow/api_fastapi/core_api/openapi/v2-rest-api-generated.yaml" ) TARGET_API_YAML_PATH = PYTHON_CLIENT_DIR_PATH / "v2.yaml" OPENAPI_GENERATOR_CLI_VER = "7.13.0" GENERATED_CLIENT_DIRECTORIES_TO_COPY: list[Path] = [ Path("airflow_client") / "client", Path("docs"), Path("test"), ] FILES_TO_COPY_TO_CLIENT_REPO = [ ".openapi-generator-ignore", "CHANGELOG.md", "README.md", "INSTALL", "LICENSE", "NOTICE", "pyproject.toml", "test_python_client.py", "version.txt", ] def _get_python_client_version(version_suffix=None): from packaging.version import Version python_client_version = VERSION_FILE.read_text().strip() version = Version(python_client_version) if version_suffix: if version.pre: current_suffix = version.pre[0] + str(version.pre[1]) if current_suffix != version_suffix: get_console().print( f"[error]The version suffix for PyPI ({version_suffix}) does not match the " f"suffix in the version ({version})[/]" ) sys.exit(1) return version.base_version + version_suffix return python_client_version def _generate_python_client_sources(python_client_version: str) -> None: get_console().print(f"\n[info]Generating client code in {PYTHON_CLIENT_TMP_DIR}[/]") result = run_command( [ "docker", "run", "--rm", "-u", f"{os.getuid()}:{os.getgid()}", "-v", f"{TARGET_API_YAML_PATH}:/spec.yaml", "-v", f"{PYTHON_CLIENT_TMP_DIR}:/output", f"openapitools/openapi-generator-cli:v{OPENAPI_GENERATOR_CLI_VER}", "generate", "--input-spec", "/spec.yaml", "--generator-name", "python", "--git-user-id", f"{os.environ.get('GIT_USER')}", "--output", "/output", "--package-name", "airflow_client.client", "--git-repo-id", "airflow-client-python", "--additional-properties", f"packageVersion={python_client_version}", ], capture_output=True, text=True, check=False, ) if result.returncode != 0: get_console().print("[error]Failed to generate client code[/]") get_console().print(result.stdout, markup=False) get_console().print(result.stderr, markup=False, style="error") sys.exit(result.returncode) get_console().print(f"[success]Generated client code in {PYTHON_CLIENT_TMP_DIR}:[/]") get_console().print(f"\n[info]Content of {PYTHON_CLIENT_TMP_DIR}:[/]") for file in sorted(PYTHON_CLIENT_TMP_DIR.glob("*")): get_console().print(f"[info] {file.name}[/]") get_console().print() def _copy_selected_sources_from_tmp_directory_to_clients_python(): get_console().print( f"[info]Copying selected sources: {GENERATED_CLIENT_DIRECTORIES_TO_COPY} from " f"{PYTHON_CLIENT_TMP_DIR} to {PYTHON_CLIENT_DIR_PATH}[/]" ) for dir in GENERATED_CLIENT_DIRECTORIES_TO_COPY: source_dir = PYTHON_CLIENT_TMP_DIR / dir target_dir = PYTHON_CLIENT_DIR_PATH / dir get_console().print(f"[info] Copying generated sources from {source_dir} to {target_dir}[/]") shutil.rmtree(target_dir, ignore_errors=True) shutil.copytree(source_dir, target_dir) get_console().print(f"[success] Copied generated sources from {source_dir} to {target_dir}[/]") get_console().print( f"[info]Copied selected sources {GENERATED_CLIENT_DIRECTORIES_TO_COPY} from " f"{PYTHON_CLIENT_TMP_DIR} to {PYTHON_CLIENT_DIR_PATH}[/]\n" ) get_console().print(f"\n[info]Content of {PYTHON_CLIENT_DIR_PATH}:[/]") for file in sorted(PYTHON_CLIENT_DIR_PATH.glob("*")): get_console().print(f"[info] {file.name}[/]") get_console().print() def _build_client_packages_with_hatch(source_date_epoch: int, distribution_format: str): command = [ "hatch", "build", "-c", ] if distribution_format == "sdist" or distribution_format == "both": command += ["-t", "sdist"] if distribution_format == "wheel" or distribution_format == "both": command += ["-t", "wheel"] env_copy = os.environ.copy() env_copy["SOURCE_DATE_EPOCH"] = str(source_date_epoch) run_command( cmd=command, cwd=PYTHON_CLIENT_DIR_PATH, env=env_copy, check=True, ) shutil.copytree(PYTHON_CLIENT_DIST_DIR_PATH, AIRFLOW_DIST_PATH, dirs_exist_ok=True) def _build_client_packages_with_docker(source_date_epoch: int, distribution_format: str): _build_local_build_image() command = "hatch build -c " if distribution_format == "sdist" or distribution_format == "both": command += "-t sdist " if distribution_format == "wheel" or distribution_format == "both": command += "-t wheel " container_id = f"airflow-build-{random.getrandbits(64):08x}" result = run_command( cmd=[ "docker", "run", "--name", container_id, "-t", "-e", f"SOURCE_DATE_EPOCH={source_date_epoch}", "-e", "HOME=/opt/airflow/files/home", "-e", "GITHUB_ACTIONS", "-w", "/opt/airflow/clients/python", AIRFLOW_BUILD_IMAGE_TAG, "bash", "-c", command, ], check=False, ) if result.returncode != 0: get_console().print("[error]Error preparing Python client packages[/]") fix_ownership_using_docker() sys.exit(result.returncode) AIRFLOW_DIST_PATH.mkdir(parents=True, exist_ok=True) get_console().print() # Copy all files in the dist directory in container to the host dist directory (note '/.' in SRC) run_command(["docker", "cp", f"{container_id}:/opt/airflow/clients/python/dist/.", "./dist"], check=True) run_command(["docker", "rm", "--force", container_id], check=False, stdout=DEVNULL, stderr=DEVNULL) @release_management_group.command(name="prepare-python-client", help="Prepares python client packages.") @option_distribution_format @option_version_suffix @option_use_local_hatch @click.option( "--python-client-repo", envvar="PYTHON_CLIENT_REPO", type=click.Path(file_okay=False, dir_okay=True, path_type=Path, exists=True), help="Directory where the python client repo is checked out", ) @click.option( "--only-publish-build-scripts", envvar="ONLY_PUBLISH_BUILD_SCRIPTS", is_flag=True, help="Only publish updated build scripts to python client repo, not generated client code.", ) @click.option( "--security-schemes", default="Basic,GoogleOpenID,Kerberos", envvar="SECURITY_SCHEMES", show_default=True, help="Security schemes to be added to the API documentation (coma separated)", ) @option_dry_run @option_verbose def prepare_python_client( distribution_format: str, version_suffix: str, use_local_hatch: bool, python_client_repo: Path | None, only_publish_build_scripts: bool, security_schemes: str, ): shutil.rmtree(PYTHON_CLIENT_TMP_DIR, ignore_errors=True) PYTHON_CLIENT_TMP_DIR.mkdir(parents=True, exist_ok=True) shutil.copy(src=SOURCE_API_YAML_PATH, dst=TARGET_API_YAML_PATH) import yaml openapi_yaml = yaml.safe_load(TARGET_API_YAML_PATH.read_text()) # Client generator does not yet support OpenAPI 3.1 fully def fix_anyof_null_and_required(obj): """ Fixes OpenAPI 3.1 `anyOf` constructs with `type: null` to be compatible with OpenAPI 3.0 generators. Specifically: - Replaces `anyOf: [<type>, {"type": "null"}]` with the base type + `nullable: true` - Ensures such fields are treated as optional by removing them from any `required` list This is a workaround for https://github.com/OpenAPITools/openapi-generator issues with `"null"` handling. Note: `type: "null"` is valid OpenAPI 3.1, but openapi-generator treats it incorrectly in some Python generators. """ if isinstance(obj, dict): if "anyOf" in obj: types = [x.get("type") for x in obj["anyOf"] if isinstance(x, dict)] if "null" in types and len(types) == 2: non_null_type = next(t for t in obj["anyOf"] if t.get("type") != "null") return {**non_null_type, "nullable": True} # Fix `required` list by removing nullable fields if "required" in obj and "properties" in obj: new_required = [] for field in obj["required"]: prop = obj["properties"].get(field, {}) if ( isinstance(prop, dict) and "anyOf" in prop and any(t.get("type") == "null" for t in prop["anyOf"] if isinstance(t, dict)) ): continue new_required.append(field) obj["required"] = new_required return {k: fix_anyof_null_and_required(v) for k, v in obj.items()} if isinstance(obj, list): return [fix_anyof_null_and_required(i) for i in obj] return obj openapi_yaml = fix_anyof_null_and_required(openapi_yaml) # Add security schemes to documentation security: list[dict[str, Any]] = [] for scheme in security_schemes.split(","): security.append({scheme: []}) openapi_yaml["security"] = security TARGET_API_YAML_PATH.write_text(yaml.dump(openapi_yaml)) def patch_trigger_dag_run_post_body(): """ Post-process the generated `TriggerDAGRunPostBody` model to explicitly include `"logical_date": None` in the `to_dict()` output if it was not set. Why this is needed: - The Airflow API server expects the `logical_date` field to always be present in the request payload, even if its value is `null`. - By default, the OpenAPI-generated Pydantic model uses `model_dump(exclude_none=True)`, which omits any fields set to `None`, including `logical_date`. - This causes a 422 error from the server when the field is missing, despite it being marked `nullable`. Since we cannot fix this cleanly via OpenAPI spec due to OpenAPI Generator's limitations with `nullable` and `anyOf`, we insert an explicit fallback into `to_dict()` after client codegen. This patch: - Locates the `_dict = self.model_dump(...)` line in `to_dict()` - Inserts a conditional to add `"logical_date": None` if it's missing """ current_python_version = f"{sys.version_info.major}.{sys.version_info.minor}" if current_python_version != DEFAULT_PYTHON_MAJOR_MINOR_VERSION: get_console().print( f"[error]Python version mismatch: current version is {current_python_version}, " f"but default version is {DEFAULT_PYTHON_MAJOR_MINOR_VERSION} - this might cause " f"reproducibility problems with prepared package.[/]" ) get_console().print( f"[info]Please reinstall breeze with uv using Python {DEFAULT_PYTHON_MAJOR_MINOR_VERSION}:[/]" ) get_console().print( f"\nuv tool install --python {DEFAULT_PYTHON_MAJOR_MINOR_VERSION} -e ./dev/breeze --force\n" ) sys.exit(1) TRIGGER_MODEL_PATH = PYTHON_CLIENT_TMP_DIR / Path( "airflow_client/client/models/trigger_dag_run_post_body.py" ) class LogicalDateDictPatch(ast.NodeTransformer): def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef: if node.name != "to_dict": return node # Inject this: injected = ast.parse('if "logical_date" not in _dict:\n _dict["logical_date"] = None').body for idx, stmt in enumerate(node.body): if ( isinstance(stmt, ast.Assign) and isinstance(stmt.targets[0], ast.Name) and stmt.targets[0].id == "_dict" and isinstance(stmt.value, ast.Call) and isinstance(stmt.value.func, ast.Attribute) and stmt.value.func.attr == "model_dump" ): node.body.insert(idx + 1, *injected) break return node source = TRIGGER_MODEL_PATH.read_text(encoding="utf-8") tree = ast.parse(source) LogicalDateDictPatch().visit(tree) ast.fix_missing_locations(tree) TRIGGER_MODEL_PATH.write_text(ast.unparse(tree), encoding="utf-8") _generate_python_client_sources(python_client_version=_get_python_client_version()) # Call this after codegen and before packaging try: patch_trigger_dag_run_post_body() except Exception: get_console().print("[warning]Failed to patch trigger_dag_run_post_body.py - skipping this step[/]") _copy_selected_sources_from_tmp_directory_to_clients_python() reproducible_build_yaml = yaml.safe_load(REPRODUCIBLE_BUILD_YAML.read_text()) source_date_epoch = reproducible_build_yaml["source-date-epoch"] if python_client_repo: if not only_publish_build_scripts: get_console().print( f"[info]Copying generated client from {PYTHON_CLIENT_DIR_PATH} to {python_client_repo}[/]" ) for dir in GENERATED_CLIENT_DIRECTORIES_TO_COPY: source_dir = PYTHON_CLIENT_DIR_PATH / dir target_dir = python_client_repo / dir get_console().print(f"[info] Copying {source_dir} to {target_dir}[/]") shutil.rmtree(target_dir, ignore_errors=True) shutil.copytree(source_dir, target_dir) get_console().print(f"[success] Copied {source_dir} to {target_dir}[/]") get_console().print( f"[info]Copied generated client from {PYTHON_CLIENT_DIR_PATH} to {python_client_repo}[/]" ) get_console().print( f"[info]Copying build scripts from {PYTHON_CLIENT_DIR_PATH} to {python_client_repo}[/]" ) for file in FILES_TO_COPY_TO_CLIENT_REPO: source_file = PYTHON_CLIENT_DIR_PATH / file target_file = python_client_repo / file get_console().print(f"[info] Copying {source_file} to {target_file}[/]") shutil.copy(source_file, target_file) get_console().print(f"[success] Copied {source_file} to {target_file}[/]") get_console().print( f"[success]Copied build scripts from {PYTHON_CLIENT_DIR_PATH} to {python_client_repo}[/]" ) spec_dir = python_client_repo / "spec" spec_dir.mkdir(parents=True, exist_ok=True) source_spec_file = PYTHON_CLIENT_DIR_PATH / "v2.yaml" target_spec_file = spec_dir / "v2.yaml" get_console().print(f"[info] Copying {source_spec_file} to {target_spec_file}[/]") shutil.copy(source_spec_file, target_spec_file) get_console().print(f"[success] Copied {source_spec_file} to {target_spec_file}[/]") # Copy gitignore file source_gitignore_file = PYTHON_CLIENT_DIR_PATH / "python-client.gitignore" target_gitignore_file = python_client_repo / ".gitignore" get_console().print(f"[info] Copying {source_gitignore_file} to {target_gitignore_file}[/]") shutil.copy(source_gitignore_file, target_gitignore_file) get_console().print(f"[success] Copied {source_gitignore_file} to {target_gitignore_file}[/]") get_console().print( f"[success]Copied client code from {PYTHON_CLIENT_DIR_PATH} to {python_client_repo}[/]\n" ) else: get_console().print( "\n[warning]No python client repo directory provided - skipping copying the generated client[/]\n" ) get_console().print(f"\n[info]Building packages in {PYTHON_CLIENT_DIST_DIR_PATH}[/]\n") shutil.rmtree(PYTHON_CLIENT_DIST_DIR_PATH, ignore_errors=True) PYTHON_CLIENT_DIST_DIR_PATH.mkdir(parents=True, exist_ok=True) version = _get_python_client_version(version_suffix) original_version = VERSION_FILE.read_text().strip() if version_suffix: VERSION_FILE.write_text(version + "\n") try: if use_local_hatch: _build_client_packages_with_hatch( source_date_epoch=source_date_epoch, distribution_format=distribution_format ) else: _build_client_packages_with_docker( source_date_epoch=source_date_epoch, distribution_format=distribution_format ) get_console().print(f"\n[success]Built packages in {AIRFLOW_DIST_PATH}[/]\n") finally: if version_suffix: VERSION_FILE.write_text(original_version) CHART_DIR = AIRFLOW_ROOT_PATH / "chart" CHART_YAML_FILE = CHART_DIR / "Chart.yaml" VALUES_YAML_FILE = CHART_DIR / "values.yaml" @release_management_group.command(name="prepare-helm-chart-tarball", help="Prepares helm chart tarball.") @click.option( "--version", help="Version used for helm chart. This version has to be set and has to match the version in " "Chart.yaml, unless the --ignore-version-check flag is used.", envvar="VERSION", ) @click.option( "--version-suffix", help="Version suffix used to publish the package. Needs to be present as we always build " "archive using release candidate tag.", required=True, envvar="VERSION_SUFFIX", ) @click.option( "--ignore-version-check", is_flag=True, help="Ignores result of version update check. Produce tarball regardless of " "whether version is correctly set in the Chart.yaml.", ) @click.option( "--skip-tagging", is_flag=True, help="Skip tagging the chart. Useful if the tag is already created, or when you verify the chart.", ) @click.option( "--skip-tag-signing", is_flag=True, help="Skip signing the tag. Useful for CI where we just tag without signing the tag.", ) @click.option( "--override-tag", is_flag=True, help="Override tag if it already exists. Useful when you want to re-create the tag, usually when you" "test the breeze command locally.", ) @option_dry_run @option_verbose def prepare_helm_chart_tarball( version: str | None, version_suffix: str, ignore_version_check: bool, override_tag: bool, skip_tagging: bool, skip_tag_signing: bool, ) -> None: import yaml chart_yaml_file_content = CHART_YAML_FILE.read_text() chart_yaml_dict = yaml.safe_load(chart_yaml_file_content) version_in_chart = chart_yaml_dict["version"] airflow_version_in_chart = chart_yaml_dict["appVersion"] values_content = yaml.safe_load(VALUES_YAML_FILE.read_text()) airflow_version_in_values = values_content["airflowVersion"] default_airflow_tag_in_values = values_content["defaultAirflowTag"] # Check if this is an RC version and replace documentation links with staging URLs is_rc_version = version_suffix and "rc" in version_suffix.lower() if is_rc_version: get_console().print( f"[info]RC version detected ({version_suffix}). Replacing documentation links with staging URLs.[/]" ) # Replace production URLs with staging URLs for RC versions chart_yaml_file_content = chart_yaml_file_content.replace( "https://airflow.apache.org/", "https://airflow.staged.apache.org/" ) get_console().print("[success]Documentation links updated to staging environment for RC version.[/]") if ignore_version_check: if not version: version = version_in_chart else: if not version or not version_suffix: get_console().print( "[error]You need to provide --version and --version-suffix parameter unless you " "use --ignore-version-check[/]" ) sys.exit(1) get_console().print(f"[info]Airflow version in values.yaml: {airflow_version_in_values}[/]") get_console().print(f"[info]Default Airflow Tag in values.yaml: {default_airflow_tag_in_values}[/]") get_console().print(f"[info]Airflow version in Chart.yaml: {airflow_version_in_chart}[/]") if airflow_version_in_values != default_airflow_tag_in_values: get_console().print( f"[error]Airflow version ({airflow_version_in_values}) does not match the " f"defaultAirflowTag ({default_airflow_tag_in_values}) in values.yaml[/]" ) sys.exit(1) updating = False if version_in_chart != version: get_console().print( f"[warning]Version in chart.yaml ({version_in_chart}) does not match the version " f"passed as parameter ({version}). Updating[/]" ) updating = True chart_yaml_file_content = chart_yaml_file_content.replace( f"version: {version_in_chart}", f"version: {version}" ) else: get_console().print(f"[success]Version in chart.yaml is good: {version}[/]") if airflow_version_in_values != airflow_version_in_chart: get_console().print( f"[warning]Airflow version in Chart.yaml ({airflow_version_in_chart}) does not match the " f"airflow version ({airflow_version_in_values}) in values.yaml. Updating[/]" ) updating = True chart_yaml_file_content = chart_yaml_file_content.replace( f"appVersion: {airflow_version_in_chart}", f"appVersion: {airflow_version_in_values}" ) else: get_console().print( f"[success]Airflow version in chart.yaml matches the airflow version in values.yaml: " f"({airflow_version_in_values})[/]" ) if updating: CHART_YAML_FILE.write_text(chart_yaml_file_content) get_console().print("\n[warning]Versions of the chart has been updated[/]\n") if ignore_version_check: get_console().print( "[warning]Ignoring the version check. " "The tarball will be created but it should not be published[/]" ) else: get_console().print( "\n[info]Please create a PR with that change, get it merged, and try again.[/]\n" ) sys.exit(1) tag_with_suffix = f"helm-chart/{version}{version_suffix}" if not skip_tagging: get_console().print(f"[info]Tagging the chart with {tag_with_suffix}[/]") tag_command = [ "git", "tag", tag_with_suffix, "-m", f"Apache Airflow Helm Chart {version}{version_suffix}", ] if override_tag: tag_command.append("--force") if not skip_tag_signing: tag_command.append("--sign") result = run_command(tag_command, check=False) if result.returncode != 0: get_console().print(f"[error]Error tagging the chart with {tag_with_suffix}.\n") get_console().print( "[warning]If you are sure the tag is set correctly, you can add --skip-tagging" " flag to the command[/]" ) sys.exit(result.returncode) else: get_console().print(f"[warning]Skipping tagging the chart with {tag_with_suffix}[/]") get_console().print(f"[info]Creating tarball for Helm Chart {tag_with_suffix}[/]") archive_name = f"airflow-chart-{version}-source.tar.gz" OUT_PATH.mkdir(parents=True, exist_ok=True) source_archive = OUT_PATH / archive_name source_archive.unlink(missing_ok=True) result = run_command( [ "git", "-c", "tar.umask=0077", "archive", "--format=tar.gz", tag_with_suffix, f"--prefix=airflow-chart-{version}/", "-o", source_archive.as_posix(), "chart", ".rat-excludes", ], check=False, ) if result.returncode != 0: get_console().print(f"[error]Error running git archive for Helm Chart {tag_with_suffix}[/]") sys.exit(result.returncode) AIRFLOW_DIST_PATH.mkdir(parents=True, exist_ok=True) final_archive = AIRFLOW_DIST_PATH / archive_name final_archive.unlink(missing_ok=True) result = repack_deterministically( source_archive=source_archive, dest_archive=final_archive, prepend_path=None, timestamp=get_source_date_epoch(CHART_DIR), ) if result.returncode != 0: get_console().print( f"[error]Error repackaging source tarball for Helm Chart from {source_archive} tp " f"{tag_with_suffix}[/]" ) sys.exit(result.returncode) get_console().print(f"[success]Tarball created in {final_archive}") @release_management_group.command(name="prepare-helm-chart-package", help="Prepares helm chart package.") @click.option( "--sign-email", help="Email associated with the key used to sign the package.", envvar="SIGN_EMAIL", default="", ) @click.option( "--version-suffix", help="Version suffix used to determine if RC version. For RC versions, documentation links will be replaced with staging URLs.", default="", envvar="VERSION_SUFFIX", ) @option_dry_run @option_verbose def prepare_helm_chart_package(sign_email: str, version_suffix: str): import yaml from airflow_breeze.utils.kubernetes_utils import ( K8S_BIN_BASE_PATH, make_sure_helm_installed, sync_virtualenv, ) # Check if this is an RC version and temporarily replace documentation links chart_yaml_backup = None is_rc_version = version_suffix and "rc" in version_suffix.lower() if is_rc_version: get_console().print( f"[info]RC version detected ({version_suffix}). Temporarily replacing documentation links with staging URLs for packaging.[/]" ) # Backup original content chart_yaml_backup = CHART_YAML_FILE.read_text() # Replace production URLs with staging URLs for RC versions chart_yaml_content = chart_yaml_backup.replace( "https://airflow.apache.org/", "https://airflow.staged.apache.org/" ) CHART_YAML_FILE.write_text(chart_yaml_content) get_console().print( "[success]Documentation links temporarily updated to staging environment for RC version packaging.[/]" ) try: chart_yaml_dict = yaml.safe_load(CHART_YAML_FILE.read_text()) version = chart_yaml_dict["version"] result = sync_virtualenv(force_venv_setup=False) if result.returncode != 0: sys.exit(result.returncode) make_sure_helm_installed() get_console().print(f"[info]Packaging the chart for Helm Chart {version}[/]") k8s_env = os.environ.copy() k8s_env["PATH"] = str(K8S_BIN_BASE_PATH) + os.pathsep + k8s_env["PATH"] # Tar on modern unix options requires --wildcards parameter to work with globs # See https://github.com/technosophos/helm-gpg/issues/1 k8s_env["TAR_OPTIONS"] = "--wildcards" archive_name = f"airflow-{version}.tgz" OUT_PATH.mkdir(parents=True, exist_ok=True) result = run_command( cmd=["helm", "package", "chart", "--dependency-update", "--destination", OUT_PATH.as_posix()], env=k8s_env, check=False, ) if result.returncode != 0: get_console().print("[error]Error packaging the chart[/]") sys.exit(result.returncode) AIRFLOW_DIST_PATH.mkdir(parents=True, exist_ok=True) final_archive = AIRFLOW_DIST_PATH / archive_name final_archive.unlink(missing_ok=True) source_archive = OUT_PATH / archive_name result = repack_deterministically( source_archive=source_archive, dest_archive=final_archive, prepend_path=None, timestamp=get_source_date_epoch(CHART_DIR), ) if result.returncode != 0: get_console().print( f"[error]Error repackaging package for Helm Chart from {source_archive} to {final_archive}[/]" ) sys.exit(result.returncode) else: get_console().print(f"[success]Package created in {final_archive}[/]") if sign_email: get_console().print(f"[info]Signing the package with {sign_email}[/]") prov_file = final_archive.with_suffix(".tgz.prov") if prov_file.exists(): get_console().print(f"[warning]Removing existing {prov_file}[/]") prov_file.unlink() result = run_command( cmd=["helm", "gpg", "sign", "-u", sign_email, archive_name], cwd=AIRFLOW_DIST_PATH.as_posix(), env=k8s_env, check=False, ) if result.returncode != 0: get_console().print("[error]Error signing the chart[/]") sys.exit(result.returncode) result = run_command( cmd=["helm", "gpg", "verify", archive_name], cwd=AIRFLOW_DIST_PATH.as_posix(), env=k8s_env, check=False, ) if result.returncode != 0: get_console().print("[error]Error signing the chart[/]") sys.exit(result.returncode) else: get_console().print(f"[success]Chart signed - the {prov_file} file created.[/]") finally: # Restore original Chart.yaml content if it was modified for RC version if is_rc_version and chart_yaml_backup: CHART_YAML_FILE.write_text(chart_yaml_backup) get_console().print("[info]Restored original Chart.yaml content after packaging.[/]") def generate_issue_content( github_token: str, previous_release: str, current_release: str, excluded_pr_list: str, limit_pr_count: int | None, is_helm_chart: bool, ): from github import Github, Issue, PullRequest, UnknownObjectException PullRequestOrIssue = PullRequest.PullRequest | Issue.Issue verbose = get_verbose() previous = previous_release current = current_release changes = get_changes(verbose, previous, current, is_helm_chart) change_prs = [change.pr for change in changes] if excluded_pr_list: excluded_prs = [int(pr) for pr in excluded_pr_list.split(",")] else: excluded_prs = [] prs = [pr for pr in change_prs if pr is not None and pr not in excluded_prs] g = Github(github_token) repo = g.get_repo("apache/airflow") pull_requests: dict[int, PullRequestOrIssue] = {} linked_issues: dict[int, list[Issue.Issue]] = defaultdict(lambda: []) users: dict[int, set[str]] = defaultdict(lambda: set()) count_prs = limit_pr_count or len(prs) with Progress(console=get_console()) as progress: task = progress.add_task(f"Retrieving {count_prs} PRs ", total=count_prs) for pr_number in prs[:count_prs]: progress.console.print( f"Retrieving PR#{pr_number}: https://github.com/apache/airflow/pull/{pr_number}" ) pr: PullRequestOrIssue try: pr = repo.get_pull(pr_number) except UnknownObjectException: # Fallback to issue if PR not found try: pr = repo.get_issue(pr_number) # (same fields as PR) except UnknownObjectException: get_console().print(f"[red]The PR #{pr_number} could not be found[/]") continue if pr.user.login == "dependabot[bot]": get_console().print(f"[yellow]Skipping PR #{pr_number} as it was created by dependabot[/]") continue # Ignore doc-only and skipped PRs label_names = [label.name for label in pr.labels] if not is_helm_chart and ("type:doc-only" in label_names or "changelog:skip" in label_names): continue pull_requests[pr_number] = pr # retrieve and append commit authors (to handle cherry picks) if hasattr(pr, "get_commits"): try: commits = pr.get_commits() for commit in commits: author = commit.author if author: users[pr_number].add(author.login) progress.console.print(f"Added commit author {author.login} for PR#{pr_number}") except Exception as e: progress.console.print( f"[warn]Could not retrieve commits for PR#{pr_number}: {e}, skipping[/]" ) # GitHub does not have linked issues in PR - but we quite rigorously add Fixes/Closes # Relate so we can find those from the body if pr.body: body = " ".join(pr.body.splitlines()) body_without_code_blocks = remove_code_blocks(body) linked_issue_numbers = { int(issue_match.group(1)) for issue_match in ISSUE_MATCH_IN_BODY.finditer(body_without_code_blocks) } for linked_issue_number in linked_issue_numbers: progress.console.print( f"Retrieving Linked issue PR#{linked_issue_number}: " f"https://github.com/apache/airflow/issue/{linked_issue_number}" ) try: linked_issues[pr_number].append(repo.get_issue(linked_issue_number)) except UnknownObjectException: progress.console.print( f"Failed to retrieve linked issue #{linked_issue_number}: Unknown Issue" ) # do not add bot users to the list of users if not pr.user.login.endswith("[bot]"): users[pr_number].add(pr.user.login) for linked_issue in linked_issues[pr_number]: users[pr_number].add(linked_issue.user.login) progress.advance(task) print_issue_content(current, pull_requests, linked_issues, users, is_helm_chart) @release_management_group.command(name="publish-docs-to-s3", help="Publishes docs to S3.") @click.option( "--source-dir-path", help="Path to the directory with the generated documentation.", required=True, ) @click.option( "--exclude-docs", help="Comma separated list of directories to exclude from the documentation.", default="", ) @click.option( "--dry-run", is_flag=True, help="Dry run - only print what would be done.", ) @click.option( "--overwrite", is_flag=True, help="Overwrite existing files in the S3 bucket.", ) @click.option( "--destination-location", help="Name of the S3 bucket to publish the documentation to.", type=NotVerifiedBetterChoice(DESTINATION_LOCATIONS), required=True, ) @click.option( "--publish-all-docs", is_flag=True, help="Publish all the available docs in the source directory." ) @click.option( "--stable-versions", is_flag=True, help="Publish all the stable versions of the docs in the source directory.", ) @click.option( "--skip-write-to-stable-folder", is_flag=True, help="Skip writing stable versions folder.", ) @option_parallelism def publish_docs_to_s3( source_dir_path: str, destination_location: str, exclude_docs: str, dry_run: bool, overwrite: bool, parallelism: int, publish_all_docs: bool, stable_versions: bool, skip_write_to_stable_folder: bool, ): from airflow_breeze.utils.publish_docs_to_s3 import S3DocsPublish if publish_all_docs and stable_versions: get_console().print("[error]You cannot use --publish-all and --stable-versions together[/]") sys.exit(1) destination_location = destination_location.rstrip("/") source_dir_path = source_dir_path.rstrip("/") get_console().print("[info]Your publishing docs to S3[/]") get_console().print(f"[info]Your source directory path is {source_dir_path}[/]") get_console().print(f"[info]Your destination path to docs is {destination_location}[/]") get_console().print(f"[info]Your excluded docs are {exclude_docs}[/]") docs_to_s3 = S3DocsPublish( source_dir_path=source_dir_path, exclude_docs=exclude_docs, dry_run=dry_run, overwrite=overwrite, destination_location=destination_location, parallelism=parallelism, skip_write_to_stable_folder=skip_write_to_stable_folder, ) if publish_all_docs: docs_to_s3.publish_all_docs() if stable_versions: docs_to_s3.publish_stable_version_docs() from airflow_breeze.utils.publish_docs_to_s3 import version_error if version_error: get_console().print( "[error]There was an error with the version of the docs. " "Please check the version in the docs and try again.[/]" ) sys.exit(1) @release_management_group.command( name="constraints-version-check", help="Check constraints against released versions of packages." ) @option_builder @option_python @option_airflow_constraints_mode_ci @click.option( "--diff-mode", type=click.Choice(["full", "diff-all", "diff-constraints"], case_sensitive=False), default="full", show_default=True, help="Report mode: full, diff-all, diff-constraints.", ) @click.option( "--package", multiple=True, help="Only check specific package(s). Can be used multiple times.", ) @click.option( "--explain-why/--no-explain-why", default=False, help="Show explanations for outdated packages.", ) @option_github_token @option_github_repository @option_verbose @option_dry_run def version_check( python: str, airflow_constraints_mode: str, diff_mode, package: tuple[str], explain_why: bool, github_token: str, github_repository: str, builder: str, ): perform_environment_checks() fix_ownership_using_docker() cleanup_python_generated_files() build_params = BuildCiParams( github_repository=github_repository, python=python, builder=builder, ) rebuild_or_pull_ci_image_if_needed(command_params=build_params) if os.environ.get("CI", "false") == "true": # Show output outside the group in CI print("::endgroup::") selected_packages = set(package) if package else None constraints_version_check( python=python, airflow_constraints_mode=airflow_constraints_mode, diff_mode=diff_mode, selected_packages=selected_packages, explain_why=explain_why, github_token=github_token, github_repository=github_repository, ) @release_management_group.command( name="check-release-files", help="Verify that all expected packages are present in Apache Airflow svn.", ) @click.option( "--path-to-airflow-svn", "-p", required=True, type=click.Path(exists=True, file_okay=False, dir_okay=True, resolve_path=True, path_type=Path), envvar="PATH_TO_AIRFLOW_SVN", help="Path to directory where release files are checked out from SVN (e.g., ~/code/asf-dist/dev/airflow)", ) @click.option( "--version", type=str, help="Version of package to verify (e.g., 2.8.1rc2, 1.0.0rc1). " "Required for airflow, task-sdk, airflow-ctl, and python-client.", ) @click.option( "--release-date", type=str, help="Date of the release in YYYY-MM-DD format. Required for providers.", ) @click.option( "--packages-file", type=click.Path(exists=True, file_okay=True, dir_okay=False, resolve_path=True, path_type=Path), default="packages.txt", show_default=True, help="File containing list of packages to check (for providers only).", ) @click.argument( "release_type", type=BetterChoice(["airflow", "task-sdk", "airflow-ctl", "python-client", "providers"]), required=True, ) @option_verbose @option_dry_run def check_release_files( path_to_airflow_svn: Path, version: str | None, release_date: str | None, packages_file: Path, release_type: str, ): """ Verify that all expected packages are present in Apache Airflow svn. In case of providers, it will generate Dockerfile.pmc that you can use to verify that all packages are installable. In case of providers, you should update `packages.txt` file with list of packages that you expect to find (copy-paste the list from VOTE thread). """ from airflow_breeze.utils.check_release_files import ( AIRFLOW_CTL_DOCKER, AIRFLOW_DOCKER, PROVIDERS_DOCKER, PYTHON_CLIENT_DOCKER, TASK_SDK_DOCKER, check_airflow_ctl_release, check_airflow_release, check_providers, check_python_client_release, check_task_sdk_release, create_docker, get_packages, warn_of_missing_files, ) console = get_console() # Validate required parameters based on release type if release_type == "providers": if not release_date: console.print("[error]--release-date is required for providers[/]") sys.exit(1) directory = path_to_airflow_svn / "providers" / release_date else: if not version: console.print(f"[error]--version is required for {release_type}[/]") sys.exit(1) # Determine directory based on release type if release_type == "airflow": directory = path_to_airflow_svn / version elif release_type == "task-sdk": directory = path_to_airflow_svn / version elif release_type == "airflow-ctl": directory = path_to_airflow_svn / "airflow-ctl" / version elif release_type == "python-client": directory = path_to_airflow_svn / "clients" / "python" / version else: console.print(f"[error]Unknown release type: {release_type}[/]") sys.exit(1) if not directory.exists(): console.print(f"[error]Directory does not exist: {directory}[/]") sys.exit(1) files = os.listdir(directory) dockerfile_path = AIRFLOW_ROOT_PATH / "Dockerfile.pmc" # Check files based on release type missing_files = [] if release_type == "providers": packages = get_packages(packages_file) missing_files = check_providers(files, release_date, packages) pips = [f"{name}=={ver}" for name, ver in packages] create_docker( PROVIDERS_DOCKER.format("RUN uv pip install --pre --system " + " ".join(f"'{p}'" for p in pips)), dockerfile_path, ) elif release_type == "airflow": missing_files = check_airflow_release(files, version) create_docker(AIRFLOW_DOCKER.format(version), dockerfile_path) elif release_type == "task-sdk": missing_files = check_task_sdk_release(files, version) create_docker(TASK_SDK_DOCKER.format(version), dockerfile_path) elif release_type == "airflow-ctl": missing_files = check_airflow_ctl_release(files, version) create_docker(AIRFLOW_CTL_DOCKER.format(version), dockerfile_path) elif release_type == "python-client": missing_files = check_python_client_release(files, version) create_docker(PYTHON_CLIENT_DOCKER.format(version), dockerfile_path) if missing_files: warn_of_missing_files(missing_files, str(directory)) sys.exit(1) else: console.print("\n[success]All expected files are present![/]") sys.exit(0)
Change
python
conda__conda
conda/base/constants.py
{ "start": 8372, "end": 11156 }
class ____(ValueEnum): CRITICAL = "critical" WARNING = "warning" INFO = "info" # Magic files for permissions determination PACKAGE_CACHE_MAGIC_FILE: Final[PathType] = "urls.txt" PREFIX_MAGIC_FILE: Final[PathType] = join("conda-meta", "history") PREFIX_FROZEN_FILE: Final[PathType] = join("conda-meta", "frozen") PREFIX_CREATION_TIMESTAMP_FILE: Final[PathType] = join("conda-meta", "created_at") PREFIX_STATE_FILE: Final[PathType] = join("conda-meta", "state") PREFIX_PINNED_FILE: Final[PathType] = join("conda-meta", "pinned") PACKAGE_ENV_VARS_DIR: Final[PathType] = join("etc", "conda", "env_vars.d") CONDA_ENV_VARS_UNSET_VAR: Final = "***unset***" RESERVED_ENV_VARS: Final = ("PATH",) # TODO: should be frozendict(), but I don't want to import frozendict from auxlib here. NAMESPACES_MAP: Final = { # base package name, namespace "python": "python", "r": "r", "r-base": "r", "mro-base": "r", "erlang": "erlang", "java": "java", "openjdk": "java", "julia": "julia", "latex": "latex", "lua": "lua", "nodejs": "js", "perl": "perl", "php": "php", "ruby": "ruby", "m2-base": "m2", "msys2-conda-epoch": "m2w64", } NAMESPACE_PACKAGE_NAMES: Final = frozenset(NAMESPACES_MAP) NAMESPACES: Final = frozenset(NAMESPACES_MAP.values()) # Namespace arbiters of uniqueness # global: some repository established by Anaconda, Inc. and conda-forge # python: https://pypi.org/simple # r: https://cran.r-project.org/web/packages/available_packages_by_name.html # erlang: https://hex.pm/packages # java: https://repo1.maven.org/maven2/ # julia: https://pkg.julialang.org/ # latex: https://ctan.org/pkg # lua: https://luarocks.org/m/root # js: https://docs.npmjs.com/misc/registry # pascal: ??? # perl: https://www.cpan.org/modules/01modules.index.html # php: https://packagist.org/ # ruby: https://rubygems.org/gems # clojure: https://clojars.org/ # Not all python namespace packages are registered on PyPI. If a package # contains files in site-packages, it probably belongs in the python namespace. # Indicates whether or not external plugins (i.e., plugins that aren't shipped # with conda) are enabled NO_PLUGINS: Final = False # When this string is present in an environment file, it indicates that the file # describes an explicit environment spec. EXPLICIT_MARKER: Final = "@EXPLICIT" # These variables describe the various sources for config that are supported by conda. # In addition to these sources, conda also supports configuration from condarc config # files (these are referred to in the context object by their full path as a pathlib.Path). CMD_LINE_SOURCE: Final = "cmd_line" ENV_VARS_SOURCE: Final = "envvars" CONFIGURATION_SOURCES: Final = (CMD_LINE_SOURCE, ENV_VARS_SOURCE)
NoticeLevel
python
sympy__sympy
sympy/matrices/common.py
{ "start": 56426, "end": 73319 }
class ____(MatrixRequired): """Provides basic matrix shape and elementwise operations. Should not be instantiated directly.""" def _eval_adjoint(self): return self.transpose().conjugate() def _eval_applyfunc(self, f): out = self._new(self.rows, self.cols, [f(x) for x in self]) return out def _eval_as_real_imag(self): # type: ignore return (self.applyfunc(re), self.applyfunc(im)) def _eval_conjugate(self): return self.applyfunc(lambda x: x.conjugate()) def _eval_permute_cols(self, perm): # apply the permutation to a list mapping = list(perm) def entry(i, j): return self[i, mapping[j]] return self._new(self.rows, self.cols, entry) def _eval_permute_rows(self, perm): # apply the permutation to a list mapping = list(perm) def entry(i, j): return self[mapping[i], j] return self._new(self.rows, self.cols, entry) def _eval_trace(self): return sum(self[i, i] for i in range(self.rows)) def _eval_transpose(self): return self._new(self.cols, self.rows, lambda i, j: self[j, i]) def adjoint(self): """Conjugate transpose or Hermitian conjugation.""" return self._eval_adjoint() def applyfunc(self, f): """Apply a function to each element of the matrix. Examples ======== >>> from sympy import Matrix >>> m = Matrix(2, 2, lambda i, j: i*2+j) >>> m Matrix([ [0, 1], [2, 3]]) >>> m.applyfunc(lambda i: 2*i) Matrix([ [0, 2], [4, 6]]) """ if not callable(f): raise TypeError("`f` must be callable.") return self._eval_applyfunc(f) def as_real_imag(self, deep=True, **hints): """Returns a tuple containing the (real, imaginary) part of matrix.""" # XXX: Ignoring deep and hints... return self._eval_as_real_imag() def conjugate(self): """Return the by-element conjugation. Examples ======== >>> from sympy import SparseMatrix, I >>> a = SparseMatrix(((1, 2 + I), (3, 4), (I, -I))) >>> a Matrix([ [1, 2 + I], [3, 4], [I, -I]]) >>> a.C Matrix([ [ 1, 2 - I], [ 3, 4], [-I, I]]) See Also ======== transpose: Matrix transposition H: Hermite conjugation sympy.matrices.matrixbase.MatrixBase.D: Dirac conjugation """ return self._eval_conjugate() def doit(self, **hints): return self.applyfunc(lambda x: x.doit(**hints)) def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False): """Apply evalf() to each element of self.""" options = {'subs':subs, 'maxn':maxn, 'chop':chop, 'strict':strict, 'quad':quad, 'verbose':verbose} return self.applyfunc(lambda i: i.evalf(n, **options)) def expand(self, deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints): """Apply core.function.expand to each entry of the matrix. Examples ======== >>> from sympy.abc import x >>> from sympy import Matrix >>> Matrix(1, 1, [x*(x+1)]) Matrix([[x*(x + 1)]]) >>> _.expand() Matrix([[x**2 + x]]) """ return self.applyfunc(lambda x: x.expand( deep, modulus, power_base, power_exp, mul, log, multinomial, basic, **hints)) @property def H(self): """Return Hermite conjugate. Examples ======== >>> from sympy import Matrix, I >>> m = Matrix((0, 1 + I, 2, 3)) >>> m Matrix([ [ 0], [1 + I], [ 2], [ 3]]) >>> m.H Matrix([[0, 1 - I, 2, 3]]) See Also ======== conjugate: By-element conjugation sympy.matrices.matrixbase.MatrixBase.D: Dirac conjugation """ return self.T.C def permute(self, perm, orientation='rows', direction='forward'): r"""Permute the rows or columns of a matrix by the given list of swaps. Parameters ========== perm : Permutation, list, or list of lists A representation for the permutation. If it is ``Permutation``, it is used directly with some resizing with respect to the matrix size. If it is specified as list of lists, (e.g., ``[[0, 1], [0, 2]]``), then the permutation is formed from applying the product of cycles. The direction how the cyclic product is applied is described in below. If it is specified as a list, the list should represent an array form of a permutation. (e.g., ``[1, 2, 0]``) which would would form the swapping function `0 \mapsto 1, 1 \mapsto 2, 2\mapsto 0`. orientation : 'rows', 'cols' A flag to control whether to permute the rows or the columns direction : 'forward', 'backward' A flag to control whether to apply the permutations from the start of the list first, or from the back of the list first. For example, if the permutation specification is ``[[0, 1], [0, 2]]``, If the flag is set to ``'forward'``, the cycle would be formed as `0 \mapsto 2, 2 \mapsto 1, 1 \mapsto 0`. If the flag is set to ``'backward'``, the cycle would be formed as `0 \mapsto 1, 1 \mapsto 2, 2 \mapsto 0`. If the argument ``perm`` is not in a form of list of lists, this flag takes no effect. Examples ======== >>> from sympy import eye >>> M = eye(3) >>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='forward') Matrix([ [0, 0, 1], [1, 0, 0], [0, 1, 0]]) >>> from sympy import eye >>> M = eye(3) >>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='backward') Matrix([ [0, 1, 0], [0, 0, 1], [1, 0, 0]]) Notes ===== If a bijective function `\sigma : \mathbb{N}_0 \rightarrow \mathbb{N}_0` denotes the permutation. If the matrix `A` is the matrix to permute, represented as a horizontal or a vertical stack of vectors: .. math:: A = \begin{bmatrix} a_0 \\ a_1 \\ \vdots \\ a_{n-1} \end{bmatrix} = \begin{bmatrix} \alpha_0 & \alpha_1 & \cdots & \alpha_{n-1} \end{bmatrix} If the matrix `B` is the result, the permutation of matrix rows is defined as: .. math:: B := \begin{bmatrix} a_{\sigma(0)} \\ a_{\sigma(1)} \\ \vdots \\ a_{\sigma(n-1)} \end{bmatrix} And the permutation of matrix columns is defined as: .. math:: B := \begin{bmatrix} \alpha_{\sigma(0)} & \alpha_{\sigma(1)} & \cdots & \alpha_{\sigma(n-1)} \end{bmatrix} """ from sympy.combinatorics import Permutation # allow british variants and `columns` if direction == 'forwards': direction = 'forward' if direction == 'backwards': direction = 'backward' if orientation == 'columns': orientation = 'cols' if direction not in ('forward', 'backward'): raise TypeError("direction='{}' is an invalid kwarg. " "Try 'forward' or 'backward'".format(direction)) if orientation not in ('rows', 'cols'): raise TypeError("orientation='{}' is an invalid kwarg. " "Try 'rows' or 'cols'".format(orientation)) if not isinstance(perm, (Permutation, Iterable)): raise ValueError( "{} must be a list, a list of lists, " "or a SymPy permutation object.".format(perm)) # ensure all swaps are in range max_index = self.rows if orientation == 'rows' else self.cols if not all(0 <= t <= max_index for t in flatten(list(perm))): raise IndexError("`swap` indices out of range.") if perm and not isinstance(perm, Permutation) and \ isinstance(perm[0], Iterable): if direction == 'forward': perm = list(reversed(perm)) perm = Permutation(perm, size=max_index+1) else: perm = Permutation(perm, size=max_index+1) if orientation == 'rows': return self._eval_permute_rows(perm) if orientation == 'cols': return self._eval_permute_cols(perm) def permute_cols(self, swaps, direction='forward'): """Alias for ``self.permute(swaps, orientation='cols', direction=direction)`` See Also ======== permute """ return self.permute(swaps, orientation='cols', direction=direction) def permute_rows(self, swaps, direction='forward'): """Alias for ``self.permute(swaps, orientation='rows', direction=direction)`` See Also ======== permute """ return self.permute(swaps, orientation='rows', direction=direction) def refine(self, assumptions=True): """Apply refine to each element of the matrix. Examples ======== >>> from sympy import Symbol, Matrix, Abs, sqrt, Q >>> x = Symbol('x') >>> Matrix([[Abs(x)**2, sqrt(x**2)],[sqrt(x**2), Abs(x)**2]]) Matrix([ [ Abs(x)**2, sqrt(x**2)], [sqrt(x**2), Abs(x)**2]]) >>> _.refine(Q.real(x)) Matrix([ [ x**2, Abs(x)], [Abs(x), x**2]]) """ return self.applyfunc(lambda x: refine(x, assumptions)) def replace(self, F, G, map=False, simultaneous=True, exact=None): """Replaces Function F in Matrix entries with Function G. Examples ======== >>> from sympy import symbols, Function, Matrix >>> F, G = symbols('F, G', cls=Function) >>> M = Matrix(2, 2, lambda i, j: F(i+j)) ; M Matrix([ [F(0), F(1)], [F(1), F(2)]]) >>> N = M.replace(F,G) >>> N Matrix([ [G(0), G(1)], [G(1), G(2)]]) """ return self.applyfunc( lambda x: x.replace(F, G, map=map, simultaneous=simultaneous, exact=exact)) def rot90(self, k=1): """Rotates Matrix by 90 degrees Parameters ========== k : int Specifies how many times the matrix is rotated by 90 degrees (clockwise when positive, counter-clockwise when negative). Examples ======== >>> from sympy import Matrix, symbols >>> A = Matrix(2, 2, symbols('a:d')) >>> A Matrix([ [a, b], [c, d]]) Rotating the matrix clockwise one time: >>> A.rot90(1) Matrix([ [c, a], [d, b]]) Rotating the matrix anticlockwise two times: >>> A.rot90(-2) Matrix([ [d, c], [b, a]]) """ mod = k%4 if mod == 0: return self if mod == 1: return self[::-1, ::].T if mod == 2: return self[::-1, ::-1] if mod == 3: return self[::, ::-1].T def simplify(self, **kwargs): """Apply simplify to each element of the matrix. Examples ======== >>> from sympy.abc import x, y >>> from sympy import SparseMatrix, sin, cos >>> SparseMatrix(1, 1, [x*sin(y)**2 + x*cos(y)**2]) Matrix([[x*sin(y)**2 + x*cos(y)**2]]) >>> _.simplify() Matrix([[x]]) """ return self.applyfunc(lambda x: x.simplify(**kwargs)) def subs(self, *args, **kwargs): # should mirror core.basic.subs """Return a new matrix with subs applied to each entry. Examples ======== >>> from sympy.abc import x, y >>> from sympy import SparseMatrix, Matrix >>> SparseMatrix(1, 1, [x]) Matrix([[x]]) >>> _.subs(x, y) Matrix([[y]]) >>> Matrix(_).subs(y, x) Matrix([[x]]) """ if len(args) == 1 and not isinstance(args[0], (dict, set)) and iter(args[0]) and not is_sequence(args[0]): args = (list(args[0]),) return self.applyfunc(lambda x: x.subs(*args, **kwargs)) def trace(self): """ Returns the trace of a square matrix i.e. the sum of the diagonal elements. Examples ======== >>> from sympy import Matrix >>> A = Matrix(2, 2, [1, 2, 3, 4]) >>> A.trace() 5 """ if self.rows != self.cols: raise NonSquareMatrixError() return self._eval_trace() def transpose(self): """ Returns the transpose of the matrix. Examples ======== >>> from sympy import Matrix >>> A = Matrix(2, 2, [1, 2, 3, 4]) >>> A.transpose() Matrix([ [1, 3], [2, 4]]) >>> from sympy import Matrix, I >>> m=Matrix(((1, 2+I), (3, 4))) >>> m Matrix([ [1, 2 + I], [3, 4]]) >>> m.transpose() Matrix([ [ 1, 3], [2 + I, 4]]) >>> m.T == m.transpose() True See Also ======== conjugate: By-element conjugation """ return self._eval_transpose() @property def T(self): '''Matrix transposition''' return self.transpose() @property def C(self): '''By-element conjugation''' return self.conjugate() def n(self, *args, **kwargs): """Apply evalf() to each element of self.""" return self.evalf(*args, **kwargs) def xreplace(self, rule): # should mirror core.basic.xreplace """Return a new matrix with xreplace applied to each entry. Examples ======== >>> from sympy.abc import x, y >>> from sympy import SparseMatrix, Matrix >>> SparseMatrix(1, 1, [x]) Matrix([[x]]) >>> _.xreplace({x: y}) Matrix([[y]]) >>> Matrix(_).xreplace({y: x}) Matrix([[x]]) """ return self.applyfunc(lambda x: x.xreplace(rule)) def _eval_simplify(self, **kwargs): # XXX: We can't use self.simplify here as mutable subclasses will # override simplify and have it return None return MatrixOperations.simplify(self, **kwargs) def _eval_trigsimp(self, **opts): from sympy.simplify.trigsimp import trigsimp return self.applyfunc(lambda x: trigsimp(x, **opts)) def upper_triangular(self, k=0): """Return the elements on and above the kth diagonal of a matrix. If k is not specified then simply returns upper-triangular portion of a matrix Examples ======== >>> from sympy import ones >>> A = ones(4) >>> A.upper_triangular() Matrix([ [1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1], [0, 0, 0, 1]]) >>> A.upper_triangular(2) Matrix([ [0, 0, 1, 1], [0, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0]]) >>> A.upper_triangular(-1) Matrix([ [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1]]) """ def entry(i, j): return self[i, j] if i + k <= j else self.zero return self._new(self.rows, self.cols, entry) def lower_triangular(self, k=0): """Return the elements on and below the kth diagonal of a matrix. If k is not specified then simply returns lower-triangular portion of a matrix Examples ======== >>> from sympy import ones >>> A = ones(4) >>> A.lower_triangular() Matrix([ [1, 0, 0, 0], [1, 1, 0, 0], [1, 1, 1, 0], [1, 1, 1, 1]]) >>> A.lower_triangular(-2) Matrix([ [0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 0], [1, 1, 0, 0]]) >>> A.lower_triangular(1) Matrix([ [1, 1, 0, 0], [1, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1]]) """ def entry(i, j): return self[i, j] if i + k >= j else self.zero return self._new(self.rows, self.cols, entry)
MatrixOperations
python
getsentry__sentry
src/sentry/sentry_apps/api/endpoints/organization_sentry_apps.py
{ "start": 1178, "end": 2627 }
class ____(ControlSiloOrganizationEndpoint): owner = ApiOwner.ECOSYSTEM publish_status = { "GET": ApiPublishStatus.PUBLIC, } @extend_schema( operation_id="Retrieve the custom integrations created by an organization", parameters=[ GlobalParams.ORG_ID_OR_SLUG, ], responses={ 200: inline_sentry_response_serializer( "OrganizationSentryAppDetailsResponse", list[SentryAppSerializerResponse] ), }, examples=SentryAppExamples.GET_ORGANIZATIONS_SENTRY_APPS, ) def get( self, request: Request, organization_context: RpcUserOrganizationContext, organization: RpcOrganization, ) -> Response: """ Retrieve the custom integrations for an organization """ queryset = SentryApp.objects.filter(owner_id=organization.id, application__isnull=False) status = request.GET.get("status") if status is not None: queryset = queryset.filter(status=SentryAppStatus.as_int(status)) return self.paginate( request=request, queryset=queryset, order_by="-date_added", paginator_cls=OffsetPaginator, on_results=lambda x: serialize( x, request.user, access=request.access, serializer=ResponseSentryAppSerializer() ), )
OrganizationSentryAppsEndpoint
python
bokeh__bokeh
src/bokeh/document/json.py
{ "start": 1921, "end": 2002 }
class ____(TypedDict): kind: Literal["TitleChanged"] title: str
TitleChanged
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_ip_asn_country_code_in_set.py
{ "start": 938, "end": 2029 }
class ____(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.ip_asn_country_code_in_set" condition_value_keys = ("country_codes",) # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _pandas(cls, column, country_codes, **kwargs): return column.apply(lambda x: is_ip_asn_country_code_in_set(x, country_codes)) # This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine # @column_condition_partial(engine=SqlAlchemyExecutionEngine) # def _sqlalchemy(cls, column, _dialect, **kwargs): # raise NotImplementedError # This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine # @column_condition_partial(engine=SparkDFExecutionEngine) # def _spark(cls, column, **kwargs): # raise NotImplementedError # This class defines the Expectation itself
ColumnValuesToBePrivateIpV6
python
neetcode-gh__leetcode
python/0473-matchsticks-to-square.py
{ "start": 0, "end": 651 }
class ____: def makesquare(self, matchsticks: List[int]) -> bool: length = sum(matchsticks) // 4 sides = [0] * 4 if sum(matchsticks) / 4 != length: return False matchsticks.sort(reverse=True) def backtrack(i): if i == len(matchsticks): return True for j in range(4): if sides[j] + matchsticks[i] <= length: sides[j] += matchsticks[i] if backtrack(i + 1): return True sides[j] -= matchsticks[i] return False return backtrack(0)
Solution
python
gevent__gevent
src/greentest/3.14/test_urllib2.py
{ "start": 2752, "end": 11396 }
class ____(unittest.TestCase): def test_request_headers_dict(self): """ The Request.headers dictionary is not a documented interface. It should stay that way, because the complete set of headers are only accessible through the .get_header(), .has_header(), .header_items() interface. However, .headers pre-dates those methods, and so real code will be using the dictionary. The introduction in 2.4 of those methods was a mistake for the same reason: code that previously saw all (urllib2 user)-provided headers in .headers now sees only a subset. """ url = "http://example.com" self.assertEqual(Request(url, headers={"Spam-eggs": "blah"} ).headers["Spam-eggs"], "blah") self.assertEqual(Request(url, headers={"spam-EggS": "blah"} ).headers["Spam-eggs"], "blah") def test_request_headers_methods(self): """ Note the case normalization of header names here, to .capitalize()-case. This should be preserved for backwards-compatibility. (In the HTTP case, normalization to .title()-case is done by urllib2 before sending headers to http.client). Note that e.g. r.has_header("spam-EggS") is currently False, and r.get_header("spam-EggS") returns None, but that could be changed in future. Method r.remove_header should remove items both from r.headers and r.unredirected_hdrs dictionaries """ url = "http://example.com" req = Request(url, headers={"Spam-eggs": "blah"}) self.assertTrue(req.has_header("Spam-eggs")) self.assertEqual(req.header_items(), [('Spam-eggs', 'blah')]) req.add_header("Foo-Bar", "baz") self.assertEqual(sorted(req.header_items()), [('Foo-bar', 'baz'), ('Spam-eggs', 'blah')]) self.assertFalse(req.has_header("Not-there")) self.assertIsNone(req.get_header("Not-there")) self.assertEqual(req.get_header("Not-there", "default"), "default") req.remove_header("Spam-eggs") self.assertFalse(req.has_header("Spam-eggs")) req.add_unredirected_header("Unredirected-spam", "Eggs") self.assertTrue(req.has_header("Unredirected-spam")) req.remove_header("Unredirected-spam") self.assertFalse(req.has_header("Unredirected-spam")) def test_password_manager(self): mgr = urllib.request.HTTPPasswordMgr() add = mgr.add_password find_user_pass = mgr.find_user_password add("Some Realm", "http://example.com/", "joe", "password") add("Some Realm", "http://example.com/ni", "ni", "ni") add("Some Realm", "http://c.example.com:3128", "3", "c") add("Some Realm", "d.example.com", "4", "d") add("Some Realm", "e.example.com:3128", "5", "e") # For the same realm, password set the highest path is the winner. self.assertEqual(find_user_pass("Some Realm", "example.com"), ('joe', 'password')) self.assertEqual(find_user_pass("Some Realm", "http://example.com/ni"), ('joe', 'password')) self.assertEqual(find_user_pass("Some Realm", "http://example.com"), ('joe', 'password')) self.assertEqual(find_user_pass("Some Realm", "http://example.com/"), ('joe', 'password')) self.assertEqual(find_user_pass("Some Realm", "http://example.com/spam"), ('joe', 'password')) self.assertEqual(find_user_pass("Some Realm", "http://example.com/spam/spam"), ('joe', 'password')) # You can have different passwords for different paths. add("c", "http://example.com/foo", "foo", "ni") add("c", "http://example.com/bar", "bar", "nini") add("c", "http://example.com/foo/bar", "foobar", "nibar") self.assertEqual(find_user_pass("c", "http://example.com/foo"), ('foo', 'ni')) self.assertEqual(find_user_pass("c", "http://example.com/bar"), ('bar', 'nini')) self.assertEqual(find_user_pass("c", "http://example.com/foo/"), ('foo', 'ni')) self.assertEqual(find_user_pass("c", "http://example.com/foo/bar"), ('foo', 'ni')) self.assertEqual(find_user_pass("c", "http://example.com/foo/baz"), ('foo', 'ni')) self.assertEqual(find_user_pass("c", "http://example.com/foobar"), (None, None)) add("c", "http://example.com/baz/", "baz", "ninini") self.assertEqual(find_user_pass("c", "http://example.com/baz"), (None, None)) self.assertEqual(find_user_pass("c", "http://example.com/baz/"), ('baz', 'ninini')) self.assertEqual(find_user_pass("c", "http://example.com/baz/bar"), ('baz', 'ninini')) # For the same path, newer password should be considered. add("b", "http://example.com/", "first", "blah") add("b", "http://example.com/", "second", "spam") self.assertEqual(find_user_pass("b", "http://example.com/"), ('second', 'spam')) # No special relationship between a.example.com and example.com: add("a", "http://example.com", "1", "a") self.assertEqual(find_user_pass("a", "http://example.com/"), ('1', 'a')) self.assertEqual(find_user_pass("a", "http://a.example.com/"), (None, None)) # Ports: self.assertEqual(find_user_pass("Some Realm", "c.example.com"), (None, None)) self.assertEqual(find_user_pass("Some Realm", "c.example.com:3128"), ('3', 'c')) self.assertEqual( find_user_pass("Some Realm", "http://c.example.com:3128"), ('3', 'c')) self.assertEqual(find_user_pass("Some Realm", "d.example.com"), ('4', 'd')) self.assertEqual(find_user_pass("Some Realm", "e.example.com:3128"), ('5', 'e')) def test_password_manager_default_port(self): """ The point to note here is that we can't guess the default port if there's no scheme. This applies to both add_password and find_user_password. """ mgr = urllib.request.HTTPPasswordMgr() add = mgr.add_password find_user_pass = mgr.find_user_password add("f", "http://g.example.com:80", "10", "j") add("g", "http://h.example.com", "11", "k") add("h", "i.example.com:80", "12", "l") add("i", "j.example.com", "13", "m") self.assertEqual(find_user_pass("f", "g.example.com:100"), (None, None)) self.assertEqual(find_user_pass("f", "g.example.com:80"), ('10', 'j')) self.assertEqual(find_user_pass("f", "g.example.com"), (None, None)) self.assertEqual(find_user_pass("f", "http://g.example.com:100"), (None, None)) self.assertEqual(find_user_pass("f", "http://g.example.com:80"), ('10', 'j')) self.assertEqual(find_user_pass("f", "http://g.example.com"), ('10', 'j')) self.assertEqual(find_user_pass("g", "h.example.com"), ('11', 'k')) self.assertEqual(find_user_pass("g", "h.example.com:80"), ('11', 'k')) self.assertEqual(find_user_pass("g", "http://h.example.com:80"), ('11', 'k')) self.assertEqual(find_user_pass("h", "i.example.com"), (None, None)) self.assertEqual(find_user_pass("h", "i.example.com:80"), ('12', 'l')) self.assertEqual(find_user_pass("h", "http://i.example.com:80"), ('12', 'l')) self.assertEqual(find_user_pass("i", "j.example.com"), ('13', 'm')) self.assertEqual(find_user_pass("i", "j.example.com:80"), (None, None)) self.assertEqual(find_user_pass("i", "http://j.example.com"), ('13', 'm')) self.assertEqual(find_user_pass("i", "http://j.example.com:80"), (None, None))
RequestHdrsTests
python
readthedocs__readthedocs.org
readthedocs/projects/tests/test_views.py
{ "start": 800, "end": 6024 }
class ____(TestCase): def setUp(self): self.user = get(User) self.project = get(Project, users=[self.user]) self.integration = get( Integration, integration_type=Integration.GITHUB_WEBHOOK, project=self.project, ) self.url = reverse("projects_edit", args=[self.project.slug]) self.client.force_login(self.user) def test_unsuported_integration(self): self.integration.delete() resp = self.client.get(self.url) field = resp.context["form"].fields["external_builds_enabled"] self.assertTrue(field.disabled) self.assertTrue( field.help_text.startswith( "To build from pull requests you need a GitHub or GitLab" ) ) get( Integration, project=self.project, integration_type=Integration.BITBUCKET_WEBHOOK, ) resp = self.client.get(self.url) field = resp.context["form"].fields["external_builds_enabled"] self.assertTrue(field.disabled) self.assertTrue( field.help_text.startswith( "To build from pull requests you need a GitHub or GitLab" ) ) def test_github_integration(self): self.integration.provider_data = {} self.integration.save() resp = self.client.get(self.url) field = resp.context["form"].fields["external_builds_enabled"] self.assertFalse(field.disabled) self.assertTrue(field.help_text.startswith("More information in")) self.integration.provider_data = {"events": ["pull_request"]} self.integration.save() resp = self.client.get(self.url) field = resp.context["form"].fields["external_builds_enabled"] self.assertFalse(field.disabled) self.assertTrue(field.help_text.startswith("More information in")) self.integration.provider_data = {"events": []} self.integration.save() resp = self.client.get(self.url) field = resp.context["form"].fields["external_builds_enabled"] self.assertTrue(field.disabled) self.assertTrue( field.help_text.startswith( "To build from pull requests your repository's webhook needs to send pull request events." ) ) def test_github_app_integration(self): Integration.objects.all().delete() github_app_installation = get( GitHubAppInstallation, ) remote_repository = get( RemoteRepository, vcs_provider=GITHUB_APP, github_app_installation=github_app_installation, ) self.project.remote_repository = remote_repository self.project.save() resp = self.client.get(self.url) field = resp.context["form"].fields["external_builds_enabled"] assert not field.disabled assert field.help_text.startswith("More information in") def test_gitlab_integration(self): self.integration.integration_type = Integration.GITLAB_WEBHOOK self.integration.provider_data = {} self.integration.save() resp = self.client.get(self.url) field = resp.context["form"].fields["external_builds_enabled"] self.assertFalse(field.disabled) self.assertTrue(field.help_text.startswith("More information in")) self.integration.provider_data = {"merge_requests_events": True} self.integration.save() resp = self.client.get(self.url) field = resp.context["form"].fields["external_builds_enabled"] self.assertFalse(field.disabled) self.assertTrue(field.help_text.startswith("More information in")) self.integration.provider_data = {"merge_requests_events": False} self.integration.save() resp = self.client.get(self.url) field = resp.context["form"].fields["external_builds_enabled"] self.assertTrue(field.disabled) self.assertTrue( field.help_text.startswith( "To build from pull requests your repository's webhook needs to send pull request events." ) ) @override_settings(ALLOW_PRIVATE_REPOS=True) def test_privacy_level_pr_previews_match_remote_repository_if_public(self): remote_repository = get(RemoteRepository, private=False) self.project.remote_repository = remote_repository self.project.save() resp = self.client.get(self.url) field = resp.context["form"].fields["external_builds_privacy_level"] self.assertTrue(field.disabled) self.assertIn("We have detected that this project is public", field.help_text) self.assertEqual(self.project.external_builds_privacy_level, PUBLIC) remote_repository.private = True remote_repository.save() self.project.save() resp = self.client.get(self.url) field = resp.context["form"].fields["external_builds_privacy_level"] self.assertFalse(field.disabled) self.assertEqual(self.project.external_builds_privacy_level, PUBLIC) @override_settings(RTD_ALLOW_ORGANIZATIONS=True)
TestExternalBuildOption
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 41873, "end": 42217 }
class ____(str, Enum): """ Fusion algorithm allows to combine results of multiple prefetches. Available fusion algorithms: * `rrf` - Reciprocal Rank Fusion (with default parameters) * `dbsf` - Distribution-Based Score Fusion """ def __str__(self) -> str: return str(self.value) RRF = "rrf" DBSF = "dbsf"
Fusion
python
huggingface__transformers
tests/models/llava_onevision/test_modeling_llava_onevision.py
{ "start": 10530, "end": 25548 }
class ____(unittest.TestCase): def setUp(self): self.processor = AutoProcessor.from_pretrained( "llava-hf/llava-onevision-qwen2-0.5b-ov-hf", padding_side="left" ) image_file = hf_hub_download( repo_id="raushan-testing-hf/images_test", filename="llava_v1_5_radar.jpg", repo_type="dataset" ) video_file = hf_hub_download( repo_id="raushan-testing-hf/videos-test", filename="video_demo.npy", repo_type="dataset" ) self.image = Image.open(image_file) self.video = np.load(video_file) self.prompt_image = "user\n<image>\nWhat do you see in this image?<|im_end|>\n<|im_start|>assistant\n" self.prompt_video = "user\n<video>\nWhat do you see in this video?<|im_end|>\n<|im_start|>assistant\n" def tearDown(self): cleanup(torch_device, gc_collect=True) @slow @require_bitsandbytes def test_small_model_integration_test(self): model = LlavaOnevisionForConditionalGeneration.from_pretrained( "llava-hf/llava-onevision-qwen2-0.5b-ov-hf", dtype="float16", device_map=torch_device ) inputs = self.processor(images=self.image, text=self.prompt_image, return_tensors="pt").to( torch_device, torch.float16 ) self.assertTrue(inputs.input_ids.shape[1] == 6567) # should expand num-image-tokens times self.assertTrue(inputs.pixel_values.shape == torch.Size([1, 10, 3, 384, 384])) self.assertTrue(inputs.image_sizes.tolist() == [[899, 1024]]) # verify single forward pass inputs = inputs.to(torch_device) # verify generation output = model.generate(**inputs, max_new_tokens=100) EXPECTED_DECODED_TEXTS = Expectations( { ("xpu", 3): 'user\n\nWhat do you see in this image?\nassistant\nThe image is a radar chart that compares the performance of different models in a specific task, likely related to natural language processing or machine learning. The chart is divided into several axes, each representing a different model or method. The models are color-coded and labeled with their respective names. The axes are labeled with terms such as "VQA," "GQA," "MQA," "VQAv2," "MM-Vet," "LLaVA-Bench," "LLaVA-1', ("cuda", 7): 'user\n\nWhat do you see in this image?\nassistant\nThe image is a radar chart that compares the performance of different models in a specific task, likely related to natural language processing or machine learning. The chart is divided into several axes, each representing a different model or method. The models are color-coded and labeled with their respective names. The axes are labeled with terms such as "VQA," "GQA," "MQA," "VQAv2," "MM-Vet," "LLaVA-Bench," "LLaVA-1', ("cuda", 8): 'user\n\nWhat do you see in this image?\nassistant\nThe image is a radar chart that compares the performance of different models in a specific task, likely related to natural language processing or machine learning. The chart is divided into several axes, each representing a different model or method. The models are color-coded and labeled with their respective names. The axes are labeled with terms such as "VQA," "GQA," "MQA," "VIZ," "TextVQA," "SQA-IMG," and "MQE." The radar chart shows', } ) # fmt: skip EXPECTED_DECODED_TEXT = EXPECTED_DECODED_TEXTS.get_expectation() DECODED_TEXT = self.processor.decode(output[0], skip_special_tokens=True) self.assertEqual(DECODED_TEXT, EXPECTED_DECODED_TEXT) @slow @require_bitsandbytes def test_small_model_integration_test_batch(self): model = LlavaOnevisionForConditionalGeneration.from_pretrained( "llava-hf/llava-onevision-qwen2-0.5b-ov-hf", dtype="float16", device_map=torch_device ) inputs = self.processor( text=[self.prompt_image, self.prompt_video], images=self.image, videos=self.video, return_tensors="pt", padding=True, ).to(torch_device, torch.float16) output = model.generate(**inputs, max_new_tokens=20) EXPECTED_DECODED_TEXT = ['user\n\nWhat do you see in this image?\nassistant\nThe image is a radar chart that compares the performance of different models in a specific task, likely related', 'user\n\nWhat do you see in this video?\nassistant\nA child wearing a light blue sleeveless top and pink pants is seen sitting on a bed, eng'] # fmt: skip self.assertEqual( self.processor.batch_decode(output, skip_special_tokens=True), EXPECTED_DECODED_TEXT, ) @slow @require_bitsandbytes def test_small_model_integration_test_video(self): # related to (#29835) model = LlavaOnevisionForConditionalGeneration.from_pretrained( "llava-hf/llava-onevision-qwen2-0.5b-ov-hf", dtype="float16", device_map=torch_device, ) inputs = self.processor(text=self.prompt_video, videos=self.video, return_tensors="pt").to( torch_device, torch.float16 ) # verify generation output = model.generate(**inputs, max_new_tokens=40) EXPECTED_DECODED_TEXT = 'user\n\nWhat do you see in this video?\nassistant\nA child wearing a light blue sleeveless top and pink pants is seen sitting on a bed, engrossed in reading a book.' # fmt: skip self.assertEqual( self.processor.decode(output[0], skip_special_tokens=True), EXPECTED_DECODED_TEXT, ) @slow @require_bitsandbytes def test_small_model_integration_test_multi_image(self): # related to (#29835) model = LlavaOnevisionForConditionalGeneration.from_pretrained( "llava-hf/llava-onevision-qwen2-0.5b-ov-hf", dtype="float16", device_map=torch_device, ) url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg" image = Image.open(requests.get(url, stream=True).raw) prompt = ( "user\n<image><image>\nWhat is the difference between these images?<|im_end|>\n<|im_start|>assistant\n" ) inputs = self.processor(text=prompt, images=[self.image, image], return_tensors="pt").to( torch_device, torch.float16 ) # verify generation output = model.generate(**inputs, max_new_tokens=40) output_text = self.processor.decode(output[0], skip_special_tokens=True) # fmt: off EXPECTED_DECODED_TEXTS = Expectations( { ("cuda", None): "user\n\nWhat is the difference between these images?\nassistant\nThe images you've provided appear to be related to a graphical representation of a radar chart, which is a type of data visualization used to show the distribution of a particular variable across a geographic area. The", ("xpu", 3): "user\n\nWhat is the difference between these images?\nassistant\nThe images you've provided appear to be related to a graphical representation of a radar chart, which is a type of data visualization used to show the distribution of a particular variable across a geographic area. The", } ) EXPECTED_DECODED_TEXT = EXPECTED_DECODED_TEXTS.get_expectation() # fmt: on self.assertEqual(output_text, EXPECTED_DECODED_TEXT) @slow @require_bitsandbytes def test_small_model_integration_test_multi_image_nested(self): # related to (#34585) model = LlavaOnevisionForConditionalGeneration.from_pretrained( "llava-hf/llava-onevision-qwen2-0.5b-ov-hf", dtype="float16", device_map=torch_device, ) url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg" image = Image.open(requests.get(url, stream=True).raw) prompts = [ "user\nTell me about the french revolution.<|im_end|>\n<|im_start|>assistant\n", # text-only case "user\n<image><image>\nWhat is the difference between these images?<|im_end|>\n<|im_start|>assistant\n", self.prompt_image, ] images_nested = [[], [image, self.image], [self.image]] inputs = self.processor( text=prompts, images=images_nested, return_tensors="pt", padding=True, ).to(torch_device, torch.float16) # verify generation output = model.generate(**inputs, max_new_tokens=40) # fmt: off EXPECTED_DECODED_TEXTS = Expectations( { ("cuda", None): [ "user\nTell me about the french revolution.\nassistant\nThe French Revolution! A pivotal event in modern history that had a profound impact on the course of Western civilization. Here's a brief overview:\n\n**Background**\n\nIn the late 18th century,", "user\n\nWhat is the difference between these images?\nassistant\nThe first image shows a stop sign with a traditional Chinese architectural background, while the second image displays a radar chart with various algorithms and models, including BLIP-2, InstructBLIP, Q", "user\n\nWhat do you see in this image?\nassistant\nThe image is a radar chart that compares the performance of different models in a specific task, likely related to natural language processing or machine learning. The chart is divided into several axes, each representing a different" ], ("xpu", 3): [ "user\nTell me about the french revolution.\nassistant\nThe French Revolution! A pivotal event in modern history that had a profound impact on the course of Western civilization. Here's a brief overview:\n\n**Background**\n\nIn the late 18th century,", 'user\n\nWhat is the difference between these images?\nassistant\nThe image shows a traffic light with a stop sign in the foreground, while the other images show a car driving through a street intersection.', 'user\n\nWhat do you see in this image?\nassistant\nThe image is a radar chart that represents the performance of different machine learning models in terms of their ability to predict the number of users who have been infected with COVID-19. The radar chart is' ], } ) EXPECTED_DECODED_TEXT = EXPECTED_DECODED_TEXTS.get_expectation() # fmt: on DECODED_TEXT = self.processor.batch_decode(output, skip_special_tokens=True) self.assertListEqual(DECODED_TEXT, EXPECTED_DECODED_TEXT) @slow @require_bitsandbytes def test_small_model_integration_test_multi_video(self): # related to (#29835) model = LlavaOnevisionForConditionalGeneration.from_pretrained( "llava-hf/llava-onevision-qwen2-0.5b-ov-hf", dtype="float16", device_map=torch_device, ) prompt = "user\n<video><video>\nAre these videos identical?<|im_end|>\n<|im_start|>assistant\n" inputs = self.processor(text=prompt, videos=[self.video, self.video], return_tensors="pt").to( torch_device, torch.float16 ) # verify generation output = model.generate(**inputs, max_new_tokens=40) EXPECTED_DECODED_TEXT = "user\n\nAre these videos identical?\nassistant\nNo, the video is not identical; it shows slight variations in the child's actions and the background." # fmt: skip self.assertEqual( self.processor.decode(output[0], skip_special_tokens=True), EXPECTED_DECODED_TEXT, ) @slow @require_bitsandbytes def test_small_model_integration_test_batch_different_resolutions(self): model = LlavaOnevisionForConditionalGeneration.from_pretrained( "llava-hf/llava-onevision-qwen2-0.5b-ov-hf", dtype="float16", device_map=torch_device ) url = "http://images.cocodataset.org/val2017/000000039769.jpg" lowres_url = "https://4.img-dpreview.com/files/p/TS560x560~forums/56876524/03975b28741443319e9a94615e35667e" cats_image = Image.open(requests.get(url, stream=True).raw) lowres_img = Image.open(requests.get(lowres_url, stream=True).raw) inputs = self.processor( text=[self.prompt_image, self.prompt_image], images=[lowres_img, cats_image], return_tensors="pt", padding=True, ).to(torch_device, torch.float16) # verify generation output = model.generate(**inputs, max_new_tokens=50) EXPECTED_DECODED_TEXT = [ 'user\n\nWhat do you see in this image?\nassistant\nThe image shows a scene of two deer in a grassy area with trees in the background. The weather appears to be foggy, giving the scene a misty and somewhat mysterious atmosphere. The deer are standing close to each other, possibly grazing or', 'user\n\nWhat do you see in this image?\nassistant\nIn the tranquil setting of this image, two cats are enjoying a peaceful nap on a vibrant pink blanket. The cat on the left, with its gray and black striped fur, is lying on its side, its head comfortably resting on the blanket. Its', ] # fmt: skip self.assertEqual( self.processor.batch_decode(output, skip_special_tokens=True), EXPECTED_DECODED_TEXT, ) @slow @require_bitsandbytes def test_small_model_integration_test_batch_matches_single(self): model = LlavaOnevisionForConditionalGeneration.from_pretrained( "llava-hf/llava-onevision-qwen2-0.5b-ov-hf", dtype="float16", device_map=torch_device, ) url = "http://images.cocodataset.org/val2017/000000039769.jpg" lowres_url = "https://4.img-dpreview.com/files/p/TS560x560~forums/56876524/03975b28741443319e9a94615e35667e" cats_image = Image.open(requests.get(url, stream=True).raw) lowres_img = Image.open(requests.get(lowres_url, stream=True).raw) inputs_batched = self.processor( text=[self.prompt_image, self.prompt_image], images=[lowres_img, cats_image], return_tensors="pt", padding=True, ).to(torch_device, torch.float16) inputs_single = self.processor( text=self.prompt_image, images=lowres_img, return_tensors="pt", padding=True ).to(torch_device, torch.float16) # verify generation output_batched = model.generate(**inputs_batched, max_new_tokens=50) output_single = model.generate(**inputs_single, max_new_tokens=50) self.assertEqual( self.processor.decode(output_batched[0], skip_special_tokens=True), self.processor.decode(output_single[0], skip_special_tokens=True), )
LlavaOnevisionForConditionalGenerationIntegrationTest
python
scrapy__scrapy
tests/test_spidermiddleware_process_start.py
{ "start": 1955, "end": 2277 }
class ____: async def process_start(self, start): yield ITEM_A async for item_or_request in start: yield item_or_request yield ITEM_C def process_start_requests(self, start, spider): yield ITEM_A yield from start yield ITEM_C
UniversalWrapSpiderMiddleware
python
kamyu104__LeetCode-Solutions
Python/sum-of-good-numbers.py
{ "start": 37, "end": 334 }
class ____(object): def sumOfGoodNumbers(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ return sum(nums[i] for i in xrange(len(nums)) if (i-k < 0 or nums[i-k] < nums[i]) and (i+k >= len(nums) or nums[i+k] < nums[i]))
Solution
python
streamlit__streamlit
lib/streamlit/runtime/scriptrunner_utils/script_requests.py
{ "start": 1500, "end": 2411 }
class ____: """Data attached to RERUN requests. Immutable.""" query_string: str = "" widget_states: WidgetStates | None = None page_script_hash: str = "" page_name: str = "" # A single fragment_id to append to fragment_id_queue. fragment_id: str | None = None # The queue of fragment_ids waiting to be run. fragment_id_queue: list[str] = field(default_factory=list) is_fragment_scoped_rerun: bool = False # set to true when a script is rerun by the fragment auto-rerun mechanism is_auto_rerun: bool = False # Hashes of messages that are cached in the client browser: cached_message_hashes: set[str] = field(default_factory=set) # context_info is used to store information from the user browser (e.g. timezone) context_info: ContextInfo | None = None def __repr__(self) -> str: return util.repr_(self) @dataclass(frozen=True)
RerunData
python
nedbat__coveragepy
coverage/html.py
{ "start": 2707, "end": 2922 }
class ____: """Data for each index page.""" noun: str plural: str filename: str summaries: list[IndexItem] totals: Numbers skipped_covered_count: int skipped_empty_count: int
IndexPage
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-oci-data-science/tests/test_oci_data_science_client.py
{ "start": 10542, "end": 17205 }
class ____: """Unit tests for Client class.""" def setup_method(self): self.endpoint = "https://example.com/api" self.auth_mock = {"signer": Mock()} self.retries = 2 self.backoff_factor = 0.1 self.timeout = 10 self.client = Client( endpoint=self.endpoint, auth=self.auth_mock, retries=self.retries, backoff_factor=self.backoff_factor, timeout=self.timeout, ) # Mock the internal HTTPX client self.client._client = Mock() def test_request_success(self): """Ensures that _request returns JSON response on success.""" payload = {"prompt": "Hello"} response_json = {"choices": [{"text": "Hi"}]} response_mock = Mock() response_mock.json.return_value = response_json response_mock.status_code = 200 self.client._client.post.return_value = response_mock result = self.client._request(payload) assert result == response_json def test_request_http_error(self): """Ensures that _request raises ExtendedRequestException on HTTP error.""" payload = {"prompt": "Hello"} response_mock = Mock() response_mock.status_code = 500 response_mock.raise_for_status.side_effect = httpx.HTTPStatusError( "Server error", request=None, response=response_mock ) response_mock.text = "Internal Server Error" self.client._client.post.return_value = response_mock with pytest.raises(ExtendedRequestException) as exc_info: self.client._request(payload) assert "Request failed" in str(exc_info.value) assert exc_info.value.response_text == "Internal Server Error" def test_stream_success(self): """Ensures that _stream yields parsed lines on success.""" payload = {"prompt": "Hello"} response_mock = Mock() response_mock.status_code = 200 response_mock.iter_lines.return_value = [ b'data: {"key": "value1"}', b'data: {"key": "value2"}', b"[DONE]", ] # Mock the context manager stream_cm = MagicMock() stream_cm.__enter__.return_value = response_mock self.client._client.stream.return_value = stream_cm result = list(self.client._stream(payload)) assert result == [{"key": "value1"}, {"key": "value2"}] @patch("time.sleep", return_value=None) def test_stream_retry_on_exception(self, mock_sleep): """Ensures that _stream retries on exceptions and raises after retries exhausted.""" payload = {"prompt": "Hello"} # Mock the exception to be raised def side_effect(*args, **kwargs): raise httpx.RequestError("Connection error") # Mock the context manager self.client._client.stream.side_effect = side_effect with pytest.raises(ExtendedRequestException): list(self.client._stream(payload)) assert ( self.client._client.stream.call_count == self.retries + 1 ) # initial attempt + retries def test_generate_stream(self): """Ensures that generate method calls _stream when stream=True.""" payload = {"prompt": "Hello"} response_mock = Mock() response_mock.status_code = 200 response_mock.iter_lines.return_value = [b'data: {"key": "value"}', b"[DONE]"] # Mock the context manager stream_cm = MagicMock() stream_cm.__enter__.return_value = response_mock self.client._client.stream.return_value = stream_cm result = list(self.client.generate(prompt="Hello", stream=True)) assert result == [{"key": "value"}] def test_generate_request(self): """Ensures that generate method calls _request when stream=False.""" payload = {"prompt": "Hello"} response_json = {"choices": [{"text": "Hi"}]} response_mock = Mock() response_mock.json.return_value = response_json response_mock.status_code = 200 self.client._client.post.return_value = response_mock result = self.client.generate(prompt="Hello", stream=False) assert result == response_json def test_chat_stream(self): """Ensures that chat method calls _stream when stream=True.""" messages = [{"role": "user", "content": "Hello"}] response_mock = Mock() response_mock.status_code = 200 response_mock.iter_lines.return_value = [b'data: {"key": "value"}', b"[DONE]"] # Mock the context manager stream_cm = MagicMock() stream_cm.__enter__.return_value = response_mock self.client._client.stream.return_value = stream_cm result = list(self.client.chat(messages=messages, stream=True)) assert result == [{"key": "value"}] def test_chat_request(self): """Ensures that chat method calls _request when stream=False.""" messages = [{"role": "user", "content": "Hello"}] response_json = {"choices": [{"message": {"content": "Hi"}}]} response_mock = Mock() response_mock.json.return_value = response_json response_mock.status_code = 200 self.client._client.post.return_value = response_mock result = self.client.chat(messages=messages, stream=False) assert result == response_json def test_close(self): """Ensures that close method closes the client.""" self.client._client.close = Mock() self.client.close() self.client._client.close.assert_called_once() def test_is_closed(self): """Ensures that is_closed returns the client's is_closed status.""" self.client._client.is_closed = False assert not self.client.is_closed() self.client._client.is_closed = True assert self.client.is_closed() def test_context_manager(self): """Ensures that the client can be used as a context manager.""" self.client.close = Mock() with self.client as client_instance: assert client_instance == self.client self.client.close.assert_called_once() def test_del(self): """Ensures that __del__ method closes the client.""" client = Client( endpoint=self.endpoint, auth=self.auth_mock, retries=self.retries, backoff_factor=self.backoff_factor, timeout=self.timeout, ) client.close = Mock() client.__del__() # Manually invoke __del__ client.close.assert_called_once() @pytest.mark.asyncio
TestClient
python
fluentpython__example-code-2e
15-more-types/cafeteria/contravariant.py
{ "start": 58, "end": 102 }
class ____: # <1> """Any refuse."""
Refuse
python
getsentry__sentry
tests/snuba/test_metrics_layer.py
{ "start": 33070, "end": 35660 }
class ____(TestCase, BaseMetricsTestCase): def ts(self, dt: datetime) -> int: return int(dt.timestamp()) def setUp(self) -> None: super().setUp() self.generic_metrics: Mapping[str, Literal["counter", "set", "distribution", "gauge"]] = { TransactionMRI.DURATION.value: "distribution", TransactionMRI.USER.value: "set", TransactionMRI.COUNT_PER_ROOT_PROJECT.value: "counter", "g:transactions/test_gauge@none": "gauge", } self.now = datetime.now(tz=timezone.utc).replace(microsecond=0) self.hour_ago = self.now - timedelta(hours=1) self.org_id = self.project.organization_id for mri, metric_type in self.generic_metrics.items(): assert metric_type in {"counter", "distribution", "set", "gauge"} for i in range(2): value: int | dict[str, int] if metric_type == "gauge": value = { "min": i, "max": i, "sum": i, "count": i, "last": i, } else: value = i self.store_metric( self.org_id, self.project.id, mri, { "transaction": f"transaction_{i % 2}", "status_code": "500" if i % 2 == 0 else "200", "device": "BlackBerry" if i % 2 == 0 else "Nokia", }, self.ts(self.hour_ago + timedelta(minutes=1 * i)), value, ) def test_fetch_metric_mris(self) -> None: metric_mris = fetch_metric_mris(self.org_id, [self.project.id], UseCaseID.TRANSACTIONS) assert len(metric_mris) == 1 assert len(metric_mris[self.project.id]) == 4 assert metric_mris[self.project.id] == [ "c:transactions/count_per_root_project@none", "s:transactions/user@none", "g:transactions/test_gauge@none", "d:transactions/duration@millisecond", ] def test_fetch_metric_tag_keys(self) -> None: tag_keys = fetch_metric_tag_keys( self.org_id, [self.project.id], UseCaseID.TRANSACTIONS, "g:transactions/test_gauge@none" ) assert len(tag_keys) == 1 assert len(tag_keys[self.project.id]) == 3 assert tag_keys[self.project.id] == ["status_code", "device", "transaction"]
MQLMetaTest
python
keras-team__keras
keras/src/optimizers/schedules/learning_rate_schedule.py
{ "start": 28057, "end": 35828 }
class ____(LearningRateSchedule): """A `LearningRateSchedule` that uses a cosine decay schedule with restarts. See [Loshchilov & Hutter, ICLR2016](https://arxiv.org/abs/1608.03983), SGDR: Stochastic Gradient Descent with Warm Restarts. When training a model, it is often useful to lower the learning rate as the training progresses. This schedule applies a cosine decay function with restarts to an optimizer step, given a provided initial learning rate. It requires a `step` value to compute the decayed learning rate. You can just pass a backend variable that you increment at each training step. The schedule is a 1-arg callable that produces a decayed learning rate when passed the current optimizer step. This can be useful for changing the learning rate value across different invocations of optimizer functions. The learning rate multiplier first decays from 1 to `alpha` for `first_decay_steps` steps. Then, a warm restart is performed. Each new warm restart runs for `t_mul` times more steps and with `m_mul` times initial learning rate as the new learning rate. Example: ```python first_decay_steps = 1000 lr_decayed_fn = ( keras.optimizers.schedules.CosineDecayRestarts( initial_learning_rate, first_decay_steps)) ``` You can pass this schedule directly into a `keras.optimizers.Optimizer` as the learning rate. The learning rate schedule is also serializable and deserializable using `keras.optimizers.schedules.serialize` and `keras.optimizers.schedules.deserialize`. Args: initial_learning_rate: A Python float. The initial learning rate. first_decay_steps: A Python integer. Number of steps to decay over. t_mul: A Python float. Used to derive the number of iterations in the i-th period. m_mul: A Python float. Used to derive the initial learning rate of the i-th period. alpha: A Python float. Minimum learning rate value as a fraction of the `initial_learning_rate`. name: String. Optional name of the operation. Defaults to `"SGDRDecay"`. Returns: A 1-arg callable learning rate schedule that takes the current optimizer step and outputs the decayed learning rate, a scalar tensor of the same type as `initial_learning_rate`. """ def __init__( self, initial_learning_rate, first_decay_steps, t_mul=2.0, m_mul=1.0, alpha=0.0, name="SGDRDecay", ): super().__init__() self.initial_learning_rate = initial_learning_rate self.first_decay_steps = first_decay_steps self._t_mul = t_mul self._m_mul = m_mul self.alpha = alpha self.name = name if self.first_decay_steps <= 0: raise ValueError( "Argument `first_decay_steps` must be > 0. " f"Received: first_decay_steps={self.first_decay_steps}" ) def __call__(self, step): with ops.name_scope(self.name): initial_learning_rate = ops.convert_to_tensor( self.initial_learning_rate ) dtype = initial_learning_rate.dtype first_decay_steps = ops.cast(self.first_decay_steps, dtype) alpha = ops.cast(self.alpha, dtype) t_mul = ops.cast(self._t_mul, dtype) m_mul = ops.cast(self._m_mul, dtype) global_step_recomp = ops.cast(step, dtype) completed_fraction = global_step_recomp / first_decay_steps def compute_step(completed_fraction, geometric=False): """Helper for `cond` operation.""" if geometric: # ops.log is sensitive to the precision of dtype, so we need # the additional casting i_restart = ops.floor( ops.log( ops.cast( 1.0 - completed_fraction * (1.0 - t_mul), dtype ) ) / ops.log(t_mul) ) sum_r = ops.divide( 1.0 - ops.power(t_mul, i_restart), (1.0 - t_mul) ) completed_fraction = ops.divide( ops.subtract(completed_fraction, sum_r), ops.power(t_mul, i_restart), ) else: i_restart = ops.floor(completed_fraction) completed_fraction -= i_restart return i_restart, completed_fraction i_restart, completed_fraction = ops.cond( ops.equal(t_mul, 1.0), lambda: compute_step(completed_fraction, geometric=False), lambda: compute_step(completed_fraction, geometric=True), ) m_fac = ops.power(m_mul, i_restart) cosine_decayed = ( 0.5 * m_fac * ( 1.0 + ops.cos( ops.multiply( ops.array(math.pi, dtype=dtype), completed_fraction ) ) ) ) decayed = ops.add(ops.multiply((1 - alpha), cosine_decayed), alpha) return ops.multiply(initial_learning_rate, decayed) def get_config(self): return { "initial_learning_rate": self.initial_learning_rate, "first_decay_steps": self.first_decay_steps, "t_mul": self._t_mul, "m_mul": self._m_mul, "alpha": self.alpha, "name": self.name, } @keras_export("keras.optimizers.schedules.serialize") def serialize(learning_rate_schedule): """Serializes a `LearningRateSchedule` into a JSON-compatible dict. Args: learning_rate_schedule: The `LearningRateSchedule` object to serialize. Returns: A JSON-serializable dict representing the object's config. Example: >>> lr_schedule = keras.optimizers.schedules.ExponentialDecay( ... 0.1, decay_steps=100000, decay_rate=0.96, staircase=True) >>> keras.optimizers.schedules.serialize(lr_schedule) {'module': 'keras.optimizers.schedules', 'class_name': 'ExponentialDecay', 'config': {...}, 'registered_name': None} """ return serialization_lib.serialize_keras_object(learning_rate_schedule) @keras_export("keras.optimizers.schedules.deserialize") def deserialize(config, custom_objects=None): """Instantiates a `LearningRateSchedule` object from a serialized form. Args: config: The serialized form of the `LearningRateSchedule`. Dictionary of the form {'class_name': str, 'config': dict}. custom_objects: A dictionary mapping class names (or function names) of custom (non-Keras) objects to class/functions. Returns: A `LearningRateSchedule` object. Example: ```python # Configuration for PolynomialDecay config = { 'class_name': 'PolynomialDecay', 'config': {'cycle': False, 'decay_steps': 10000, 'end_learning_rate': 0.01, 'initial_learning_rate': 0.1, 'name': None, 'power': 0.5 } } lr_schedule = keras.optimizers.schedules.deserialize(config) ``` """ return serialization_lib.deserialize_keras_object( config, module_objects=globals(), custom_objects=custom_objects, printable_module_name="decay", )
CosineDecayRestarts
python
openai__openai-python
src/openai/types/realtime/realtime_response_create_mcp_tool.py
{ "start": 1891, "end": 2324 }
class ____(BaseModel): always: Optional[RequireApprovalMcpToolApprovalFilterAlways] = None """A filter object to specify which tools are allowed.""" never: Optional[RequireApprovalMcpToolApprovalFilterNever] = None """A filter object to specify which tools are allowed.""" RequireApproval: TypeAlias = Union[RequireApprovalMcpToolApprovalFilter, Literal["always", "never"], None]
RequireApprovalMcpToolApprovalFilter
python
FactoryBoy__factory_boy
factory/base.py
{ "start": 13979, "end": 21782 }
class ____(Generic[T]): """Factory base support for sequences, attributes and stubs.""" # Backwards compatibility UnknownStrategy = errors.UnknownStrategy UnsupportedStrategy = errors.UnsupportedStrategy def __new__(cls, *args, **kwargs): """Would be called if trying to instantiate the class.""" raise errors.FactoryError('You cannot instantiate BaseFactory') _meta = FactoryOptions() # ID to use for the next 'declarations.Sequence' attribute. _counter = None @classmethod def reset_sequence(cls, value=None, force=False): """Reset the sequence counter. Args: value (int or None): the new 'next' sequence value; if None, recompute the next value from _setup_next_sequence(). force (bool): whether to force-reset parent sequence counters in a factory inheritance chain. """ cls._meta.reset_sequence(value, force=force) @classmethod def _setup_next_sequence(cls): """Set up an initial sequence value for Sequence attributes. Returns: int: the first available ID to use for instances of this factory. """ return 0 @classmethod def _adjust_kwargs(cls, **kwargs): """Extension point for custom kwargs adjustment.""" return kwargs @classmethod def _generate(cls, strategy, params): """generate the object. Args: params (dict): attributes to use for generating the object strategy: the strategy to use """ if cls._meta.abstract: raise errors.FactoryError( "Cannot generate instances of abstract factory %(f)s; " "Ensure %(f)s.Meta.model is set and %(f)s.Meta.abstract " "is either not set or False." % dict(f=cls.__name__)) step = builder.StepBuilder(cls._meta, params, strategy) return step.build() @classmethod def _after_postgeneration(cls, instance, create, results=None): """Hook called after post-generation declarations have been handled. Args: instance (object): the generated object create (bool): whether the strategy was 'build' or 'create' results (dict or None): result of post-generation declarations """ pass @classmethod def _build(cls, model_class, *args, **kwargs): """Actually build an instance of the model_class. Customization point, will be called once the full set of args and kwargs has been computed. Args: model_class (type): the class for which an instance should be built args (tuple): arguments to use when building the class kwargs (dict): keyword arguments to use when building the class """ return model_class(*args, **kwargs) @classmethod def _create(cls, model_class, *args, **kwargs): """Actually create an instance of the model_class. Customization point, will be called once the full set of args and kwargs has been computed. Args: model_class (type): the class for which an instance should be created args (tuple): arguments to use when creating the class kwargs (dict): keyword arguments to use when creating the class """ return model_class(*args, **kwargs) @classmethod def build(cls, **kwargs) -> T: """Build an instance of the associated class, with overridden attrs. The instance will not be saved and persisted to any datastore. """ return cls._generate(enums.BUILD_STRATEGY, kwargs) @classmethod def build_batch(cls, size: int, **kwargs) -> List[T]: """Build a batch of instances of the given class, with overridden attrs. The instances will not be saved and persisted to any datastore. Args: size (int): the number of instances to build Returns: object list: the built instances """ return [cls.build(**kwargs) for _ in range(size)] @classmethod def create(cls, **kwargs) -> T: """Create an instance of the associated class, with overridden attrs. The instance will be saved and persisted in the appropriate datastore. """ return cls._generate(enums.CREATE_STRATEGY, kwargs) @classmethod def create_batch(cls, size: int, **kwargs) -> List[T]: """Create a batch of instances of the given class, with overridden attrs. The instances will be saved and persisted in the appropriate datastore. Args: size (int): the number of instances to create Returns: object list: the created instances """ return [cls.create(**kwargs) for _ in range(size)] @classmethod def stub(cls, **kwargs): """Retrieve a stub of the associated class, with overridden attrs. This will return an object whose attributes are those defined in this factory's declarations or in the extra kwargs. """ return cls._generate(enums.STUB_STRATEGY, kwargs) @classmethod def stub_batch(cls, size, **kwargs): """Stub a batch of instances of the given class, with overridden attrs. Args: size (int): the number of instances to stub Returns: object list: the stubbed instances """ return [cls.stub(**kwargs) for _ in range(size)] @classmethod def generate(cls, strategy, **kwargs): """Generate a new instance. The instance will be created with the given strategy (one of BUILD_STRATEGY, CREATE_STRATEGY, STUB_STRATEGY). Args: strategy (str): the strategy to use for generating the instance. Returns: object: the generated instance """ assert strategy in (enums.STUB_STRATEGY, enums.BUILD_STRATEGY, enums.CREATE_STRATEGY) action = getattr(cls, strategy) return action(**kwargs) @classmethod def generate_batch(cls, strategy, size, **kwargs): """Generate a batch of instances. The instances will be created with the given strategy (one of BUILD_STRATEGY, CREATE_STRATEGY, STUB_STRATEGY). Args: strategy (str): the strategy to use for generating the instance. size (int): the number of instances to generate Returns: object list: the generated instances """ assert strategy in (enums.STUB_STRATEGY, enums.BUILD_STRATEGY, enums.CREATE_STRATEGY) batch_action = getattr(cls, '%s_batch' % strategy) return batch_action(size, **kwargs) @classmethod def simple_generate(cls, create, **kwargs): """Generate a new instance. The instance will be either 'built' or 'created'. Args: create (bool): whether to 'build' or 'create' the instance. Returns: object: the generated instance """ strategy = enums.CREATE_STRATEGY if create else enums.BUILD_STRATEGY return cls.generate(strategy, **kwargs) @classmethod def simple_generate_batch(cls, create, size, **kwargs): """Generate a batch of instances. These instances will be either 'built' or 'created'. Args: size (int): the number of instances to generate create (bool): whether to 'build' or 'create' the instances. Returns: object list: the generated instances """ strategy = enums.CREATE_STRATEGY if create else enums.BUILD_STRATEGY return cls.generate_batch(strategy, size, **kwargs)
BaseFactory
python
dateutil__dateutil
src/dateutil/rrule.py
{ "start": 1973, "end": 2610 }
class ____(weekdaybase): """ This version of weekday does not allow n = 0. """ def __init__(self, wkday, n=None): if n == 0: raise ValueError("Can't create weekday with n==0") super(weekday, self).__init__(wkday, n) MO, TU, WE, TH, FR, SA, SU = weekdays = tuple(weekday(x) for x in range(7)) def _invalidates_cache(f): """ Decorator for rruleset methods which may invalidate the cached length. """ @wraps(f) def inner_func(self, *args, **kwargs): rv = f(self, *args, **kwargs) self._invalidate_cache() return rv return inner_func
weekday
python
wandb__wandb
wandb/vendor/pygments/formatters/img.py
{ "start": 1243, "end": 1336 }
class ____(ImportError): """When Python imaging library is not available"""
PilNotAvailable
python
ray-project__ray
python/ray/dag/tests/experimental/test_compiled_graphs.py
{ "start": 35030, "end": 35333 }
class ____: def sleep_and_echo(self, x): time.sleep(x) return x def fail_if_x_is_even(self, x): if x % 2 == 0: raise ValueError("x is even") return x def sleep_and_fail(self, x): time.sleep(x) raise ValueError("fail")
FastFailActor
python
spack__spack
lib/spack/spack/externals.py
{ "start": 6078, "end": 16987 }
class ____: """Transforms a list of external dicts into a list of specs.""" def __init__( self, external_dicts: List[ExternalDict], *, complete_node: Callable[[spack.spec.Spec], None] = complete_variants_and_architecture, allow_nonexisting: bool = True, ): """Initializes a class to manage and process external specifications in ``packages.yaml``. Args: external_dicts: list of ExternalDict objects to provide external specifications. complete_node: a callable that completes a node with missing variants, targets, etc. Defaults to `complete_architecture`. allow_nonexisting: whether to allow non-existing packages. Defaults to True. Raises: spack.repo.UnknownPackageError: if a package does not exist, and allow_nonexisting is False. """ self.external_dicts = external_dicts self.specs_by_external_id: Dict[str, ExternalSpecAndConfig] = {} self.specs_by_name: Dict[str, List[ExternalSpecAndConfig]] = {} self.nodes: List[spack.spec.Spec] = [] self.allow_nonexisting = allow_nonexisting # Fill the data structures above (can be done lazily) self.complete_node = complete_node self._parse() def _parse(self) -> None: # Parse all nodes without creating edges among them self._parse_all_nodes() # Map dependencies specified as specs to a single id self._ensure_dependencies_have_single_id() # Attach dependencies to externals self._create_edges() # Mark the specs as concrete for node in self.nodes: node._finalize_concretization() def _create_edges(self): for eid, entry in self.specs_by_external_id.items(): current_node, current_dict = entry.spec, entry.config line_info = _line_info(current_dict) spec_str = current_dict["spec"] # Compute the dependency types for this spec pkg_class, deptypes_by_package = spack.repo.PATH.get_pkg_class(current_node.name), {} for when, by_name in pkg_class.dependencies.items(): if not current_node.satisfies(when): continue for name, dep in by_name.items(): if name not in deptypes_by_package: deptypes_by_package[name] = dep.depflag deptypes_by_package[name] |= dep.depflag for dependency_dict in current_dict.get("dependencies", []): dependency_id = dependency_dict.get("id") if not dependency_id: raise ExternalDependencyError( f"A dependency for {spec_str} does not have an external id{line_info}" ) elif dependency_id not in self.specs_by_external_id: raise ExternalDependencyError( f"A dependency for {spec_str} has an external id " f"{dependency_id} that cannot be found in packages.yaml{line_info}" ) dependency_node = self.specs_by_external_id[dependency_id].spec # Compute dependency types and virtuals depflag = spack.deptypes.NONE if "deptypes" in dependency_dict: depflag = spack.deptypes.canonicalize(dependency_dict["deptypes"]) virtuals: Tuple[str, ...] = () if "virtuals" in dependency_dict: virtuals = tuple(dependency_dict["virtuals"].split(",")) # Infer dependency types and virtuals if the user didn't specify them if depflag == spack.deptypes.NONE and not virtuals: # Infer the deptype if only '%' was used in the spec inferred_virtuals = [] for name, current_flag in deptypes_by_package.items(): if not dependency_node.intersects(name): continue depflag |= current_flag if spack.repo.PATH.is_virtual(name): inferred_virtuals.append(name) virtuals = tuple(inferred_virtuals) elif depflag == spack.deptypes.NONE: depflag = spack.deptypes.DEFAULT current_node._add_dependency(dependency_node, depflag=depflag, virtuals=virtuals) def _ensure_dependencies_have_single_id(self): for eid, entry in self.specs_by_external_id.items(): current_node, current_dict = entry.spec, entry.config spec_str = current_dict["spec"] line_info = _line_info(current_dict) if current_node.dependencies() and "dependencies" in current_dict: raise ExternalSpecError( f"the spec {spec_str} cannot specify dependencies both in the root spec and" f"in the 'dependencies' field{line_info}" ) # Transform inline entries like 'mpich %gcc' to a canonical form using 'dependencies' for edge in current_node.edges_to_dependencies(): entry: DependencyDict = {"spec": str(edge.spec)} # Handle entries with more options specified if edge.depflag != 0: entry["deptypes"] = spack.deptypes.flag_to_tuple(edge.depflag) if edge.virtuals: entry["virtuals"] = ",".join(edge.virtuals) current_dict.setdefault("dependencies", []).append(entry) current_node.clear_edges() # Map a spec: to id: for dependency_dict in current_dict.get("dependencies", []): if "id" in dependency_dict: continue if "spec" not in dependency_dict: raise ExternalDependencyError( f"the spec {spec_str} needs to specify either the id or the spec " f"of its dependencies{line_info}" ) query_spec = spack.spec.Spec(dependency_dict["spec"]) candidates = [ x for x in self.specs_by_name.get(query_spec.name, []) if x.spec.satisfies(query_spec) ] if len(candidates) == 0: raise ExternalDependencyError( f"the spec '{spec_str}' depends on '{query_spec}', but there is no such " f"external spec in packages.yaml{line_info}" ) elif len(candidates) > 1: candidates_str = ( f" [candidates are {', '.join([str(x.spec) for x in candidates])}]" ) raise ExternalDependencyError( f"the spec '{spec_str}' depends on '{query_spec}', but there are multiple " f"external specs that could satisfy the request{candidates_str}{line_info}" ) dependency_dict["id"] = candidates[0].config["id"] def _parse_all_nodes(self) -> None: """Parses all the nodes from the external dicts but doesn't add any edge.""" for external_dict in self.external_dicts: line_info = _line_info(external_dict) try: node = node_from_dict(external_dict) except spack.spec.UnsatisfiableArchitectureSpecError: spec_str, target_str = external_dict["spec"], external_dict["required_target"] tty.debug( f"[{__name__}]{line_info} Skipping external spec '{spec_str}' because it " f"cannot be constrained with the required target '{target_str}'." ) continue except ExternalSpecError as e: warnings.warn(f"{e}{line_info}") continue package_exists = spack.repo.PATH.exists(node.name) # If we allow non-existing packages, just continue if not package_exists and self.allow_nonexisting: continue if not package_exists and not self.allow_nonexisting: raise ExternalSpecError(f"Package '{node.name}' does not exist{line_info}") eid = external_dict.setdefault("id", str(uuid.uuid4())) if eid in self.specs_by_external_id: other_node = self.specs_by_external_id[eid] other_line_info = _line_info(other_node.config) raise DuplicateExternalError( f"Specs {node} and {other_node.spec} cannot have the same external id {eid}" f"{line_info}{other_line_info}" ) self.complete_node(node) # Add a Python dependency to Python extensions that don't specify it pkg_class = spack.repo.PATH.get_pkg_class(node.name) if ( "dependencies" not in external_dict and not node.dependencies() and any([c.__name__ == "PythonExtension" for c in pkg_class.__mro__]) ): warnings.warn( f"Spack is trying attach a Python dependency to '{node}'. This feature is " f"deprecated, and will be removed in v1.2. Please make the dependency " f"explicit in your configuration." ) external_dict.setdefault("dependencies", []).append({"spec": "python"}) # Normalize internally so that each node has a unique id spec_and_config = ExternalSpecAndConfig(spec=node, config=external_dict) self.specs_by_external_id[eid] = spec_and_config self.specs_by_name.setdefault(node.name, []).append(spec_and_config) self.nodes.append(node) def get_specs_for_package(self, package_name: str) -> List[spack.spec.Spec]: """Returns the external specs for a given package name.""" result = self.specs_by_name.get(package_name, []) return [x.spec for x in result] def all_specs(self) -> List[spack.spec.Spec]: """Returns all the external specs.""" return self.nodes def query(self, query: Union[str, spack.spec.Spec]) -> List[spack.spec.Spec]: """Returns the external specs matching a query spec.""" result = [] for node in self.nodes: if node.satisfies(query): result.append(node) return result def external_spec(config: ExternalDict) -> spack.spec.Spec: """Returns an external spec from a dictionary representation.""" return ExternalSpecsParser([config]).all_specs()[0]
ExternalSpecsParser
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/window_test.py
{ "start": 1349, "end": 10652 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate( combinations.times( test_base.default_test_combinations(), combinations.combine( count=20, size=[10, 14, 17], shift=[7, 14], stride=[1, 2, 6], drop_remainder=[True, False]) + combinations.combine( count=[0, 1], size=10, shift=4, stride=1, drop_remainder=[True, False]))) def testWindowDataset(self, count, size, shift, stride, drop_remainder): """Tests a dataset that slides a window its input elements.""" components = (np.arange(7), np.array([[1, 2, 3]]) * np.arange(7)[:, np.newaxis], np.array(37.0) * np.arange(7)) def _map_fn(x, y, z): return math_ops.square(x), math_ops.square(y), math_ops.square(z) def _flat_map_fn(x, y, z): return dataset_ops.Dataset.zip((x.batch(batch_size=size), y.batch(batch_size=size), z.batch(batch_size=size))) dataset = dataset_ops.Dataset.from_tensor_slices(components).map( _map_fn).repeat(count).window( size=size, shift=shift, stride=stride, drop_remainder=drop_remainder).flat_map(_flat_map_fn) get_next = self.getNext(dataset) self.assertEqual([[None] + list(c.shape[1:]) for c in components], [ts.as_list() for ts in nest.flatten( dataset_ops.get_legacy_output_shapes(dataset))]) num_full_batches = max(0, (count * 7 - ((size - 1) * stride + 1)) // shift + 1) for i in range(num_full_batches): result = self.evaluate(get_next()) for component, result_component in zip(components, result): for j in range(size): self.assertAllEqual(component[(i * shift + j * stride) % 7]**2, result_component[j]) if not drop_remainder: num_partial_batches = (count * 7) // shift + ( (count * 7) % shift > 0) - num_full_batches for i in range(num_partial_batches): result = self.evaluate(get_next()) for component, result_component in zip(components, result): remaining = (count * 7) - ((num_full_batches + i) * shift) num_elements = remaining // stride + ((remaining % stride) > 0) for j in range(num_elements): self.assertAllEqual( component[((num_full_batches + i) * shift + j * stride) % 7]**2, result_component[j]) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) @combinations.generate( combinations.times( test_base.default_test_combinations(), combinations.combine(count=20, size=0, shift=3, stride=1) + combinations.combine(count=20, size=3, shift=0, stride=1) + combinations.combine(count=20, size=3, shift=3, stride=0))) def testWindowDatasetInvalid(self, count, size, shift, stride): with self.assertRaises(errors.InvalidArgumentError): ds = dataset_ops.Dataset.range(10).map(lambda x: x).repeat(count).window( size=size, shift=shift, stride=stride).flat_map(lambda x: x.batch(batch_size=size)) self.evaluate(ds._variant_tensor) @combinations.generate(test_base.default_test_combinations()) def testWindowDifferentNestedStructures(self): ds = dataset_ops.Dataset.from_tensor_slices(([1, 2], [3, 4])).window(2) self.getNext(ds) ds = dataset_ops.Dataset.from_tensor_slices({"a": [1, 2]}).window(2) self.getNext(ds) @combinations.generate(test_base.default_test_combinations()) def testWindowSparse(self): def _sparse(i): return sparse_tensor.SparseTensorValue( indices=[[0]], values=(i * [1]), dense_shape=[1]) dataset = dataset_ops.Dataset.range(10).map(_sparse).window( size=5, shift=3, drop_remainder=True).flat_map(lambda x: x.batch(batch_size=5)) num_batches = (10 - 5) // 3 + 1 expected_output = [ sparse_tensor.SparseTensorValue( indices=[[0, 0], [1, 0], [2, 0], [3, 0], [4, 0]], values=[i * 3, i * 3 + 1, i * 3 + 2, i * 3 + 3, i * 3 + 4], dense_shape=[5, 1]) for i in range(num_batches) ] self.assertDatasetProduces(dataset, expected_output=expected_output) @combinations.generate(test_base.default_test_combinations()) def testWindowSparseWithDifferentDenseShapes(self): def _sparse(i): return sparse_tensor.SparseTensorValue( indices=array_ops.expand_dims( math_ops.range(i, dtype=dtypes.int64), 1), values=array_ops.fill([math_ops.cast(i, dtypes.int32)], i), dense_shape=[i]) dataset = dataset_ops.Dataset.range(10).map(_sparse).window( size=5, shift=3, drop_remainder=True).flat_map(lambda x: x.batch(batch_size=5)) expected_output = [] num_batches = (10 - 5) // 3 + 1 for i in range(num_batches): expected_indices = [] expected_values = [] for j in range(5): for k in range(i * 3 + j): expected_indices.append([j, k]) expected_values.append(i * 3 + j) expected_output.append( sparse_tensor.SparseTensorValue( indices=expected_indices, values=expected_values, dense_shape=[5, i * 3 + 5 - 1])) self.assertDatasetProduces(dataset, expected_output=expected_output) @combinations.generate(test_base.default_test_combinations()) def testNestedWindowSparse(self): def _sparse(i): return sparse_tensor.SparseTensorValue( indices=[[0]], values=(i * [1]), dense_shape=[1]) dataset = dataset_ops.Dataset.range(10).map(_sparse).window( size=4, shift=2, drop_remainder=True).flat_map(lambda x: x.batch(batch_size=4)).window( size=3, shift=1, drop_remainder=True).flat_map(lambda x: x.batch(batch_size=3)) expected_output = [ sparse_tensor.SparseTensorValue( indices=[[0, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0], [1, 0, 0], [1, 1, 0], [1, 2, 0], [1, 3, 0], [2, 0, 0], [2, 1, 0], [2, 2, 0], [2, 3, 0]], values=[0, 1, 2, 3, 2, 3, 4, 5, 4, 5, 6, 7], dense_shape=[3, 4, 1]), sparse_tensor.SparseTensorValue( indices=[[0, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0], [1, 0, 0], [1, 1, 0], [1, 2, 0], [1, 3, 0], [2, 0, 0], [2, 1, 0], [2, 2, 0], [2, 3, 0]], values=[2, 3, 4, 5, 4, 5, 6, 7, 6, 7, 8, 9], dense_shape=[3, 4, 1]) ] self.assertDatasetProduces(dataset, expected_output=expected_output) @combinations.generate(test_base.default_test_combinations()) def testWindowShapeError(self): def generator(): yield [1.0, 2.0, 3.0] yield [4.0, 5.0, 6.0] yield [7.0, 8.0, 9.0, 10.0] dataset = dataset_ops.Dataset.from_generator( generator, dtypes.float32, output_shapes=[None]).window( size=3, shift=1).flat_map(lambda x: x.batch(batch_size=3)) self.assertDatasetProduces( dataset, expected_error=( errors.InvalidArgumentError, r"Cannot batch tensors with different shapes in component 0. " r"First element had shape \[3\] and element 2 had shape \[4\].")) @combinations.generate(test_base.default_test_combinations()) def testWindowIgnoreErrors(self): input_values = np.float32([1., np.nan, 2., np.nan, 3.]) dataset = dataset_ops.Dataset.from_tensor_slices(input_values).map( lambda x: array_ops.check_numerics(x, "message")).window( size=2, shift=2, stride=2, drop_remainder=True).flat_map(lambda x: x.batch(batch_size=2)) self.assertDatasetProduces( dataset, expected_output=[np.float32([1., 2.]), np.float32([2., 3.])]) # Eager-only because the test enumerates the dataset. @combinations.generate(test_base.eager_only_combinations()) def testNestedOutput(self): dataset = dataset_ops.Dataset.range(100) dataset = dataset_ops.Dataset.zip((dataset, dataset)).window(10) for i, nested_dataset in enumerate(dataset): x, y = nested_dataset self.assertDatasetProduces(x, range(i*10, (i+1)*10)) self.assertDatasetProduces(y, range(i*10, (i+1)*10)) @combinations.generate(test_base.default_test_combinations()) def testDropRemainderOutput(self): dataset = dataset_ops.Dataset.range(100) dataset = dataset.window(30, drop_remainder=True) dataset = dataset.flat_map(lambda x: x.batch(30)) dataset = dataset.batch(4) self.assertDatasetProduces( dataset, expected_output=[[[y + 30 * x for y in range(30)] for x in range(3)]]) @combinations.generate(test_base.default_test_combinations()) def testName(self): dataset = dataset_ops.Dataset.from_tensors(42).window( 1, name="window").flat_map(lambda x: x) self.assertDatasetProduces(dataset, [42])
WindowTest
python
pandas-dev__pandas
pandas/tests/arrays/sparse/test_indexing.py
{ "start": 342, "end": 3892 }
class ____: def test_getitem(self, arr): dense = arr.to_dense() for i, value in enumerate(arr): tm.assert_almost_equal(value, dense[i]) tm.assert_almost_equal(arr[-i], dense[-i]) def test_getitem_arraylike_mask(self, arr): arr = SparseArray([0, 1, 2]) result = arr[[True, False, True]] expected = SparseArray([0, 2]) tm.assert_sp_array_equal(result, expected) @pytest.mark.parametrize( "slc", [ np.s_[:], np.s_[1:10], np.s_[1:100], np.s_[10:1], np.s_[:-3], np.s_[-5:-4], np.s_[:-12], np.s_[-12:], np.s_[2:], np.s_[2::3], np.s_[::2], np.s_[::-1], np.s_[::-2], np.s_[1:6:2], np.s_[:-6:-2], ], ) @pytest.mark.parametrize( "as_dense", [[np.nan] * 10, [1] * 10, [np.nan] * 5 + [1] * 5, []] ) def test_getslice(self, slc, as_dense): as_dense = np.array(as_dense) arr = SparseArray(as_dense) result = arr[slc] expected = SparseArray(as_dense[slc]) tm.assert_sp_array_equal(result, expected) def test_getslice_tuple(self): dense = np.array([np.nan, 0, 3, 4, 0, 5, np.nan, np.nan, 0]) sparse = SparseArray(dense) res = sparse[(slice(4, None),)] exp = SparseArray(dense[4:]) tm.assert_sp_array_equal(res, exp) sparse = SparseArray(dense, fill_value=0) res = sparse[(slice(4, None),)] exp = SparseArray(dense[4:], fill_value=0) tm.assert_sp_array_equal(res, exp) msg = "too many indices for array" with pytest.raises(IndexError, match=msg): sparse[4:, :] with pytest.raises(IndexError, match=msg): # check numpy compat dense[4:, :] def test_boolean_slice_empty(self): arr = SparseArray([0, 1, 2]) res = arr[[False, False, False]] assert res.dtype == arr.dtype def test_getitem_bool_sparse_array(self, arr): # GH 23122 spar_bool = SparseArray([False, True] * 5, dtype=np.bool_, fill_value=True) exp = SparseArray([np.nan, 2, np.nan, 5, 6]) tm.assert_sp_array_equal(arr[spar_bool], exp) spar_bool = ~spar_bool res = arr[spar_bool] exp = SparseArray([np.nan, 1, 3, 4, np.nan]) tm.assert_sp_array_equal(res, exp) spar_bool = SparseArray( [False, True, np.nan] * 3, dtype=np.bool_, fill_value=np.nan ) res = arr[spar_bool] exp = SparseArray([np.nan, 3, 5]) tm.assert_sp_array_equal(res, exp) def test_getitem_bool_sparse_array_as_comparison(self): # GH 45110 arr = SparseArray([1, 2, 3, 4, np.nan, np.nan], fill_value=np.nan) res = arr[arr > 2] exp = SparseArray([3.0, 4.0], fill_value=np.nan) tm.assert_sp_array_equal(res, exp) def test_get_item(self, arr): zarr = SparseArray([0, 0, 1, 2, 3, 0, 4, 5, 0, 6], fill_value=0) assert np.isnan(arr[1]) assert arr[2] == 1 assert arr[7] == 5 assert zarr[0] == 0 assert zarr[2] == 1 assert zarr[7] == 5 errmsg = "must be an integer between -10 and 10" with pytest.raises(IndexError, match=errmsg): arr[11] with pytest.raises(IndexError, match=errmsg): arr[-11] assert arr[-1] == arr[len(arr) - 1]
TestGetitem
python
django__django
tests/fixtures/models.py
{ "start": 2995, "end": 3324 }
class ____(models.Model): name = models.CharField(max_length=100) authors = models.ManyToManyField(Person) class Meta: ordering = ("name",) def __str__(self): authors = " and ".join(a.name for a in self.authors.all()) return "%s by %s" % (self.name, authors) if authors else self.name
Book
python
ansible__ansible
test/units/test_context.py
{ "start": 247, "end": 747 }
class ____: pass def test_set_global_context(): options = FakeOptions() options.tags = [u'production', u'webservers'] options.check_mode = True options.start_at_task = u'Start with くらとみ' expected = frozenset((('tags', (u'production', u'webservers')), ('check_mode', True), ('start_at_task', u'Start with くらとみ'))) context._init_global_context(options) assert frozenset(context.CLIARGS.items()) == expected
FakeOptions
python
pydantic__pydantic
pydantic-core/tests/serializers/test_bytes.py
{ "start": 2495, "end": 2534 }
class ____(bytes): pass
BytesSubclass
python
pytorch__pytorch
torch/distributed/tensor/examples/convnext_example.py
{ "start": 568, "end": 1297 }
class ____(nn.Module): def __init__(self, normalized_shape, eps=1e-6, data_format=torch.contiguous_format): super().__init__() self.weight = nn.Parameter(torch.ones(normalized_shape)) self.bias = nn.Parameter(torch.zeros(normalized_shape)) self.eps = eps self.data_format = data_format if self.data_format != torch.contiguous_format: raise NotImplementedError self.normalized_shape = (normalized_shape,) def forward(self, x): u = x.mean(1, keepdim=True) s = (x - u).pow(2).mean(1, keepdim=True) x = (x - u) / torch.sqrt(s + self.eps) x = self.weight[:, None, None] * x + self.bias[:, None, None] return x
LayerNorm
python
pypa__pip
tests/lib/options_helpers.py
{ "start": 594, "end": 882 }
class ____: def setup_method(self) -> None: commands_dict["fake"] = CommandInfo( "tests.lib.options_helpers", "FakeCommand", "fake summary", ) def teardown_method(self) -> None: commands_dict.pop("fake")
AddFakeCommandMixin
python
jazzband__django-waffle
waffle/tests/test_testutils.py
{ "start": 10193, "end": 10392 }
class ____(OverrideFlagOnClassTestsMixin, TestCase): """ Run tests with Django TestCase """ @override_flag('foo', active=False)
OverrideFlagOnClassTestCase
python
pyca__cryptography
src/cryptography/hazmat/primitives/serialization/pkcs7.py
{ "start": 1308, "end": 1673 }
class ____(utils.Enum): Text = "Add text/plain MIME type" Binary = "Don't translate input data into canonical MIME format" DetachedSignature = "Don't embed data in the PKCS7 structure" NoCapabilities = "Don't embed SMIME capabilities" NoAttributes = "Don't embed authenticatedAttributes" NoCerts = "Don't embed signer certificate"
PKCS7Options
python
huggingface__transformers
src/transformers/models/zamba2/modeling_zamba2.py
{ "start": 16228, "end": 25309 }
class ____(nn.Module): """ Multi-headed attention from 'Attention Is All You Need' paper. Adapted from transformers.models.mistral.modeling_mistral.MistralAttention: The input dimension here is attention_hidden_size = 2 * hidden_size, and head_dim = attention_hidden_size // num_heads. The extra factor of 2 comes from the input being the concatenation of original_hidden_states with the output of the previous (mamba) layer (see fig. 2 in https://huggingface.co/papers/2405.16712). Additionally, replaced attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) with attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim/2) Finally, this attention layer contributes to tied transformer blocks aimed to increasing compute without increasing model size. Because this layer is tied, un-tied adapters (formally the same as LoRA but used in the base model) modules are added to the q, k, v projectors to increase expressivity with a small memory overhead (see Fig. 2 of https://huggingface.co/papers/2411.15242). """ def __init__( self, config: Zamba2Config, layer_idx: Optional[int] = None, num_fwd_mem_blocks: Optional[int] = None, block_id: Optional[int] = None, ): super().__init__() self.config = config self.layer_idx = layer_idx self.attention_hidden_size = config.attention_hidden_size self.head_dim = config.attention_head_dim self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads self.max_position_embeddings = config.max_position_embeddings self.scaling = (self.head_dim / 2) ** -0.5 self.is_causal = True self.attention_dropout = config.attention_dropout self.q_proj = nn.Linear(config.attention_hidden_size, config.num_attention_heads * self.head_dim, bias=False) self.k_proj = nn.Linear(config.attention_hidden_size, config.num_key_value_heads * self.head_dim, bias=False) self.v_proj = nn.Linear(config.attention_hidden_size, config.num_key_value_heads * self.head_dim, bias=False) self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False) self.num_fwd_mem_blocks = num_fwd_mem_blocks self.layer_block_map = config.hybrid_layer_ids self.block_id = block_id if config.use_shared_attention_adapter: self.linear_q_adapter_list = nn.ModuleList([]) self.linear_k_adapter_list = nn.ModuleList([]) self.linear_v_adapter_list = nn.ModuleList([]) for i in range(self.num_fwd_mem_blocks): if i % config.num_mem_blocks == block_id: linear_q_adapter = nn.Sequential( nn.Linear(self.attention_hidden_size, self.config.adapter_rank, bias=False), nn.Linear(self.config.adapter_rank, self.attention_hidden_size, bias=False), ) linear_k_adapter = nn.Sequential( nn.Linear(self.attention_hidden_size, self.config.adapter_rank, bias=False), nn.Linear(self.config.adapter_rank, self.attention_hidden_size, bias=False), ) linear_v_adapter = nn.Sequential( nn.Linear(self.attention_hidden_size, self.config.adapter_rank, bias=False), nn.Linear(self.config.adapter_rank, self.attention_hidden_size, bias=False), ) else: linear_q_adapter = nn.Identity() linear_k_adapter = nn.Identity() linear_v_adapter = nn.Identity() self.linear_q_adapter_list.append(linear_q_adapter) self.linear_k_adapter_list.append(linear_k_adapter) self.linear_v_adapter_list.append(linear_v_adapter) self.layer_dic = {value: index for index, value in enumerate(self.layer_block_map)} def forward( self, hidden_states: torch.Tensor, layer_idx: int, attention_mask: Optional[torch.Tensor] = None, past_key_values: Optional[Zamba2HybridDynamicCache] = None, position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, position_ids: Optional[torch.Tensor] = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]: input_shape = hidden_states.shape[:-1] hidden_shape = (*input_shape, -1, self.head_dim) query_states = self.q_proj(hidden_states) key_states = self.k_proj(hidden_states) value_states = self.v_proj(hidden_states) if self.config.use_shared_attention_adapter: adapter_layer_idx = self.layer_dic[layer_idx] query_states = query_states + self.linear_q_adapter_list[adapter_layer_idx](hidden_states) key_states = key_states + self.linear_k_adapter_list[adapter_layer_idx](hidden_states) value_states = value_states + self.linear_v_adapter_list[adapter_layer_idx](hidden_states) query_states = query_states.view(hidden_shape).transpose(1, 2) key_states = key_states.view(hidden_shape).transpose(1, 2) value_states = value_states.view(hidden_shape).transpose(1, 2) if self.config.use_mem_rope: cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) if past_key_values is not None: key_states, value_states = past_key_values.update(key_states, value_states, layer_idx) attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] attn_output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, **kwargs, ) attn_output = attn_output.reshape(*input_shape, -1).contiguous() attn_output = self.o_proj(attn_output) return attn_output, attn_weights # Helper methods for segment sum computation def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int): """ Padding x tensor with `pad_size` on the seq_len dim (dim=1) Assumes that we only have tensors of either size 4 or 3 """ pad_shape = (0, 0, 0, 0, 0, pad_size, 0, 0) if len(input_tensor.shape) == 4 else (0, 0, 0, pad_size, 0, 0) return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0) def reshape_into_chunks(input_tensor, pad_size, chunk_size): """ Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and simultaneously splitting it into chunk sequences. Assumes that we only have tensors of either size 4 or 3 """ # [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...] input_tensor = pad_tensor_by_size(input_tensor, pad_size) if len(input_tensor.shape) == 3: # [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads] return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2]) else: # [bsz, seq_len multiple of chunk_size, num_heads, head_dim or state_size] -> [bsz, -1, chunk_size, num_heads, head_dim or state_size] return input_tensor.reshape( input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3] ) def segment_sum(input_tensor): """ More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions. """ chunk_size = input_tensor.size(-1) # 1. expand input tensor to have an additional dimension and repeat along that dimension # [..., chunk_size] -> [..., chunk_size, chunk_size] input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size) # 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1) input_tensor = input_tensor.masked_fill(~mask, 0) # 3. compute actual cumsum tensor_segsum = torch.cumsum(input_tensor, dim=-2) # 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time) mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0) tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf) return tensor_segsum is_fast_path_available = all((selective_state_update, causal_conv1d_fn, causal_conv1d_update))
Zamba2Attention
python
falconry__falcon
tests/test_validators.py
{ "start": 2373, "end": 2637 }
class ____: def __init__(self, valid=True): self._media = _VALID_MEDIA if valid else {} async def get_media(self): return self._media def MockReq(asgi, valid=True): return _MockReqAsync(valid) if asgi else _MockReq(valid)
_MockReqAsync
python
django__django
tests/sitemaps_tests/urls/http.py
{ "start": 2162, "end": 2290 }
class ____(SimpleSitemap): lastmod = datetime(2013, 3, 13, 10, 0, 0, tzinfo=timezone.get_fixed_timezone(-300))
TimezoneSiteMap
python
huggingface__transformers
src/transformers/models/ernie/modeling_ernie.py
{ "start": 21450, "end": 22868 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config self.layer = nn.ModuleList([ErnieLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)]) def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, past_key_values: Optional[Cache] = None, use_cache: Optional[bool] = None, cache_position: Optional[torch.Tensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]: for i, layer_module in enumerate(self.layer): hidden_states = layer_module( hidden_states, attention_mask, encoder_hidden_states, # as a positional argument for gradient checkpointing encoder_attention_mask=encoder_attention_mask, past_key_values=past_key_values, cache_position=cache_position, **kwargs, ) return BaseModelOutputWithPastAndCrossAttentions( last_hidden_state=hidden_states, past_key_values=past_key_values if use_cache else None, ) @auto_docstring
ErnieEncoder
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 879110, "end": 879520 }
class ____(sgqlc.types.Type): """An edge in a connection.""" __schema__ = github_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field("PullRequestReviewThread", graphql_name="node") """The item at the end of the edge."""
PullRequestReviewThreadEdge
python
kubernetes-client__python
kubernetes/client/models/v1beta1_allocated_device_status.py
{ "start": 383, "end": 10542 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'conditions': 'list[V1Condition]', 'data': 'object', 'device': 'str', 'driver': 'str', 'network_data': 'V1beta1NetworkDeviceData', 'pool': 'str', 'share_id': 'str' } attribute_map = { 'conditions': 'conditions', 'data': 'data', 'device': 'device', 'driver': 'driver', 'network_data': 'networkData', 'pool': 'pool', 'share_id': 'shareID' } def __init__(self, conditions=None, data=None, device=None, driver=None, network_data=None, pool=None, share_id=None, local_vars_configuration=None): # noqa: E501 """V1beta1AllocatedDeviceStatus - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._conditions = None self._data = None self._device = None self._driver = None self._network_data = None self._pool = None self._share_id = None self.discriminator = None if conditions is not None: self.conditions = conditions if data is not None: self.data = data self.device = device self.driver = driver if network_data is not None: self.network_data = network_data self.pool = pool if share_id is not None: self.share_id = share_id @property def conditions(self): """Gets the conditions of this V1beta1AllocatedDeviceStatus. # noqa: E501 Conditions contains the latest observation of the device's state. If the device has been configured according to the class and claim config references, the `Ready` condition should be True. Must not contain more than 8 entries. # noqa: E501 :return: The conditions of this V1beta1AllocatedDeviceStatus. # noqa: E501 :rtype: list[V1Condition] """ return self._conditions @conditions.setter def conditions(self, conditions): """Sets the conditions of this V1beta1AllocatedDeviceStatus. Conditions contains the latest observation of the device's state. If the device has been configured according to the class and claim config references, the `Ready` condition should be True. Must not contain more than 8 entries. # noqa: E501 :param conditions: The conditions of this V1beta1AllocatedDeviceStatus. # noqa: E501 :type: list[V1Condition] """ self._conditions = conditions @property def data(self): """Gets the data of this V1beta1AllocatedDeviceStatus. # noqa: E501 Data contains arbitrary driver-specific data. The length of the raw data must be smaller or equal to 10 Ki. # noqa: E501 :return: The data of this V1beta1AllocatedDeviceStatus. # noqa: E501 :rtype: object """ return self._data @data.setter def data(self, data): """Sets the data of this V1beta1AllocatedDeviceStatus. Data contains arbitrary driver-specific data. The length of the raw data must be smaller or equal to 10 Ki. # noqa: E501 :param data: The data of this V1beta1AllocatedDeviceStatus. # noqa: E501 :type: object """ self._data = data @property def device(self): """Gets the device of this V1beta1AllocatedDeviceStatus. # noqa: E501 Device references one device instance via its name in the driver's resource pool. It must be a DNS label. # noqa: E501 :return: The device of this V1beta1AllocatedDeviceStatus. # noqa: E501 :rtype: str """ return self._device @device.setter def device(self, device): """Sets the device of this V1beta1AllocatedDeviceStatus. Device references one device instance via its name in the driver's resource pool. It must be a DNS label. # noqa: E501 :param device: The device of this V1beta1AllocatedDeviceStatus. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and device is None: # noqa: E501 raise ValueError("Invalid value for `device`, must not be `None`") # noqa: E501 self._device = device @property def driver(self): """Gets the driver of this V1beta1AllocatedDeviceStatus. # noqa: E501 Driver specifies the name of the DRA driver whose kubelet plugin should be invoked to process the allocation once the claim is needed on a node. Must be a DNS subdomain and should end with a DNS domain owned by the vendor of the driver. # noqa: E501 :return: The driver of this V1beta1AllocatedDeviceStatus. # noqa: E501 :rtype: str """ return self._driver @driver.setter def driver(self, driver): """Sets the driver of this V1beta1AllocatedDeviceStatus. Driver specifies the name of the DRA driver whose kubelet plugin should be invoked to process the allocation once the claim is needed on a node. Must be a DNS subdomain and should end with a DNS domain owned by the vendor of the driver. # noqa: E501 :param driver: The driver of this V1beta1AllocatedDeviceStatus. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and driver is None: # noqa: E501 raise ValueError("Invalid value for `driver`, must not be `None`") # noqa: E501 self._driver = driver @property def network_data(self): """Gets the network_data of this V1beta1AllocatedDeviceStatus. # noqa: E501 :return: The network_data of this V1beta1AllocatedDeviceStatus. # noqa: E501 :rtype: V1beta1NetworkDeviceData """ return self._network_data @network_data.setter def network_data(self, network_data): """Sets the network_data of this V1beta1AllocatedDeviceStatus. :param network_data: The network_data of this V1beta1AllocatedDeviceStatus. # noqa: E501 :type: V1beta1NetworkDeviceData """ self._network_data = network_data @property def pool(self): """Gets the pool of this V1beta1AllocatedDeviceStatus. # noqa: E501 This name together with the driver name and the device name field identify which device was allocated (`<driver name>/<pool name>/<device name>`). Must not be longer than 253 characters and may contain one or more DNS sub-domains separated by slashes. # noqa: E501 :return: The pool of this V1beta1AllocatedDeviceStatus. # noqa: E501 :rtype: str """ return self._pool @pool.setter def pool(self, pool): """Sets the pool of this V1beta1AllocatedDeviceStatus. This name together with the driver name and the device name field identify which device was allocated (`<driver name>/<pool name>/<device name>`). Must not be longer than 253 characters and may contain one or more DNS sub-domains separated by slashes. # noqa: E501 :param pool: The pool of this V1beta1AllocatedDeviceStatus. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and pool is None: # noqa: E501 raise ValueError("Invalid value for `pool`, must not be `None`") # noqa: E501 self._pool = pool @property def share_id(self): """Gets the share_id of this V1beta1AllocatedDeviceStatus. # noqa: E501 ShareID uniquely identifies an individual allocation share of the device. # noqa: E501 :return: The share_id of this V1beta1AllocatedDeviceStatus. # noqa: E501 :rtype: str """ return self._share_id @share_id.setter def share_id(self, share_id): """Sets the share_id of this V1beta1AllocatedDeviceStatus. ShareID uniquely identifies an individual allocation share of the device. # noqa: E501 :param share_id: The share_id of this V1beta1AllocatedDeviceStatus. # noqa: E501 :type: str """ self._share_id = share_id def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1beta1AllocatedDeviceStatus): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1beta1AllocatedDeviceStatus): return True return self.to_dict() != other.to_dict()
V1beta1AllocatedDeviceStatus
python
doocs__leetcode
solution/0200-0299/0205.Isomorphic Strings/Solution.py
{ "start": 0, "end": 293 }
class ____: def isIsomorphic(self, s: str, t: str) -> bool: d1 = {} d2 = {} for a, b in zip(s, t): if (a in d1 and d1[a] != b) or (b in d2 and d2[b] != a): return False d1[a] = b d2[b] = a return True
Solution
python
TheAlgorithms__Python
data_structures/linked_list/doubly_linked_list_two.py
{ "start": 1165, "end": 6906 }
class ____: head: Node | None = None # First node in list tail: Node | None = None # Last node in list def __str__(self): current = self.head nodes = [] while current is not None: nodes.append(current.data) current = current.next return " ".join(str(node) for node in nodes) def __contains__(self, value: DataType): current = self.head while current: if current.data == value: return True current = current.next return False def __iter__(self): return LinkedListIterator(self.head) def get_head_data(self): if self.head: return self.head.data return None def get_tail_data(self): if self.tail: return self.tail.data return None def set_head(self, node: Node) -> None: if self.head is None: self.head = node self.tail = node else: self.insert_before_node(self.head, node) def set_tail(self, node: Node) -> None: if self.tail is None: self.head = node self.tail = node else: self.insert_after_node(self.tail, node) def insert(self, value: DataType) -> None: node = Node(value) if self.head is None: self.set_head(node) else: self.set_tail(node) def insert_before_node(self, node: Node, node_to_insert: Node) -> None: node_to_insert.next = node node_to_insert.previous = node.previous if node.previous is None: self.head = node_to_insert else: node.previous.next = node_to_insert node.previous = node_to_insert def insert_after_node(self, node: Node, node_to_insert: Node) -> None: node_to_insert.previous = node node_to_insert.next = node.next if node.next is None: self.tail = node_to_insert else: node.next.previous = node_to_insert node.next = node_to_insert def insert_at_position(self, position: int, value: DataType) -> None: current_position = 1 new_node = Node(value) node = self.head while node: if current_position == position: self.insert_before_node(node, new_node) return current_position += 1 node = node.next self.set_tail(new_node) def get_node(self, item: DataType) -> Node: node = self.head while node: if node.data == item: return node node = node.next raise Exception("Node not found") def delete_value(self, value): if (node := self.get_node(value)) is not None: if node == self.head: self.head = self.head.next if node == self.tail: self.tail = self.tail.previous self.remove_node_pointers(node) @staticmethod def remove_node_pointers(node: Node) -> None: if node.next: node.next.previous = node.previous if node.previous: node.previous.next = node.next node.next = None node.previous = None def is_empty(self): return self.head is None def create_linked_list() -> None: """ >>> new_linked_list = LinkedList() >>> new_linked_list.get_head_data() is None True >>> new_linked_list.get_tail_data() is None True >>> new_linked_list.is_empty() True >>> new_linked_list.insert(10) >>> new_linked_list.get_head_data() 10 >>> new_linked_list.get_tail_data() 10 >>> new_linked_list.insert_at_position(position=3, value=20) >>> new_linked_list.get_head_data() 10 >>> new_linked_list.get_tail_data() 20 >>> new_linked_list.set_head(Node(1000)) >>> new_linked_list.get_head_data() 1000 >>> new_linked_list.get_tail_data() 20 >>> new_linked_list.set_tail(Node(2000)) >>> new_linked_list.get_head_data() 1000 >>> new_linked_list.get_tail_data() 2000 >>> for value in new_linked_list: ... print(value) 1000 10 20 2000 >>> new_linked_list.is_empty() False >>> for value in new_linked_list: ... print(value) 1000 10 20 2000 >>> 10 in new_linked_list True >>> new_linked_list.delete_value(value=10) >>> 10 in new_linked_list False >>> new_linked_list.delete_value(value=2000) >>> new_linked_list.get_tail_data() 20 >>> new_linked_list.delete_value(value=1000) >>> new_linked_list.get_tail_data() 20 >>> new_linked_list.get_head_data() 20 >>> for value in new_linked_list: ... print(value) 20 >>> new_linked_list.delete_value(value=20) >>> for value in new_linked_list: ... print(value) >>> for value in range(1,10): ... new_linked_list.insert(value=value) >>> for value in new_linked_list: ... print(value) 1 2 3 4 5 6 7 8 9 >>> linked_list = LinkedList() >>> linked_list.insert_at_position(position=1, value=10) >>> str(linked_list) '10' >>> linked_list.insert_at_position(position=2, value=20) >>> str(linked_list) '10 20' >>> linked_list.insert_at_position(position=1, value=30) >>> str(linked_list) '30 10 20' >>> linked_list.insert_at_position(position=3, value=40) >>> str(linked_list) '30 10 40 20' >>> linked_list.insert_at_position(position=5, value=50) >>> str(linked_list) '30 10 40 20 50' """ if __name__ == "__main__": import doctest doctest.testmod()
LinkedList
python
django__django
tests/servers/tests.py
{ "start": 6437, "end": 6546 }
class ____(LiveServerTestCase): server_thread_class = LiveServerSingleThread
SingleThreadLiveServerTestCase
python
sympy__sympy
sympy/sets/fancysets.py
{ "start": 6869, "end": 14486 }
class ____(Set): """ Image of a set under a mathematical function. The transformation must be given as a Lambda function which has as many arguments as the elements of the set upon which it operates, e.g. 1 argument when acting on the set of integers or 2 arguments when acting on a complex region. This function is not normally called directly, but is called from ``imageset``. Examples ======== >>> from sympy import Symbol, S, pi, Dummy, Lambda >>> from sympy import FiniteSet, ImageSet, Interval >>> x = Symbol('x') >>> N = S.Naturals >>> squares = ImageSet(Lambda(x, x**2), N) # {x**2 for x in N} >>> 4 in squares True >>> 5 in squares False >>> FiniteSet(0, 1, 2, 3, 4, 5, 6, 7, 9, 10).intersect(squares) {1, 4, 9} >>> square_iterable = iter(squares) >>> for i in range(4): ... next(square_iterable) 1 4 9 16 If you want to get value for `x` = 2, 1/2 etc. (Please check whether the `x` value is in ``base_set`` or not before passing it as args) >>> squares.lamda(2) 4 >>> squares.lamda(S(1)/2) 1/4 >>> n = Dummy('n') >>> solutions = ImageSet(Lambda(n, n*pi), S.Integers) # solutions of sin(x) = 0 >>> dom = Interval(-1, 1) >>> dom.intersect(solutions) {0} See Also ======== sympy.sets.sets.imageset """ def __new__(cls, flambda, *sets): if not isinstance(flambda, Lambda): raise ValueError('First argument must be a Lambda') signature = flambda.signature if len(signature) != len(sets): raise ValueError('Incompatible signature') sets = [_sympify(s) for s in sets] if not all(isinstance(s, Set) for s in sets): raise TypeError("Set arguments to ImageSet should of type Set") if not all(cls._check_sig(sg, st) for sg, st in zip(signature, sets)): raise ValueError("Signature %s does not match sets %s" % (signature, sets)) if flambda is S.IdentityFunction and len(sets) == 1: return sets[0] if not set(flambda.variables) & flambda.expr.free_symbols: is_empty = fuzzy_or(s.is_empty for s in sets) if is_empty == True: return S.EmptySet elif is_empty == False: return FiniteSet(flambda.expr) return Basic.__new__(cls, flambda, *sets) lamda = property(lambda self: self.args[0]) base_sets = property(lambda self: self.args[1:]) @property def base_set(self): # XXX: Maybe deprecate this? It is poorly defined in handling # the multivariate case... sets = self.base_sets if len(sets) == 1: return sets[0] else: return ProductSet(*sets).flatten() @property def base_pset(self): return ProductSet(*self.base_sets) @classmethod def _check_sig(cls, sig_i, set_i): if sig_i.is_symbol: return True elif isinstance(set_i, ProductSet): sets = set_i.sets if len(sig_i) != len(sets): return False # Recurse through the signature for nested tuples: return all(cls._check_sig(ts, ps) for ts, ps in zip(sig_i, sets)) else: # XXX: Need a better way of checking whether a set is a set of # Tuples or not. For example a FiniteSet can contain Tuples # but so can an ImageSet or a ConditionSet. Others like # Integers, Reals etc can not contain Tuples. We could just # list the possibilities here... Current code for e.g. # _contains probably only works for ProductSet. return True # Give the benefit of the doubt def __iter__(self): already_seen = set() for i in self.base_pset: val = self.lamda(*i) if val in already_seen: continue else: already_seen.add(val) yield val def _is_multivariate(self): return len(self.lamda.variables) > 1 def _contains(self, other): from sympy.solvers.solveset import _solveset_multi def get_symsetmap(signature, base_sets): '''Attempt to get a map of symbols to base_sets''' queue = list(zip(signature, base_sets)) symsetmap = {} for sig, base_set in queue: if sig.is_symbol: symsetmap[sig] = base_set elif base_set.is_ProductSet: sets = base_set.sets if len(sig) != len(sets): raise ValueError("Incompatible signature") # Recurse queue.extend(zip(sig, sets)) else: # If we get here then we have something like sig = (x, y) and # base_set = {(1, 2), (3, 4)}. For now we give up. return None return symsetmap def get_equations(expr, candidate): '''Find the equations relating symbols in expr and candidate.''' queue = [(expr, candidate)] for e, c in queue: if not isinstance(e, Tuple): yield Eq(e, c) elif not isinstance(c, Tuple) or len(e) != len(c): yield False return else: queue.extend(zip(e, c)) # Get the basic objects together: other = _sympify(other) expr = self.lamda.expr sig = self.lamda.signature variables = self.lamda.variables base_sets = self.base_sets # Use dummy symbols for ImageSet parameters so they don't match # anything in other rep = {v: Dummy(v.name) for v in variables} variables = [v.subs(rep) for v in variables] sig = sig.subs(rep) expr = expr.subs(rep) # Map the parts of other to those in the Lambda expr equations = [] for eq in get_equations(expr, other): # Unsatisfiable equation? if eq is False: return S.false equations.append(eq) # Map the symbols in the signature to the corresponding domains symsetmap = get_symsetmap(sig, base_sets) if symsetmap is None: # Can't factor the base sets to a ProductSet return None # Which of the variables in the Lambda signature need to be solved for? symss = (eq.free_symbols for eq in equations) variables = set(variables) & reduce(set.union, symss, set()) # Use internal multivariate solveset variables = tuple(variables) base_sets = [symsetmap[v] for v in variables] solnset = _solveset_multi(equations, variables, base_sets) if solnset is None: return None return tfn[fuzzy_not(solnset.is_empty)] @property def is_iterable(self): return all(s.is_iterable for s in self.base_sets) def doit(self, **hints): from sympy.sets.setexpr import SetExpr f = self.lamda sig = f.signature if len(sig) == 1 and sig[0].is_symbol and isinstance(f.expr, Expr): base_set = self.base_sets[0] return SetExpr(base_set)._eval_func(f).set if all(s.is_FiniteSet for s in self.base_sets): return FiniteSet(*(f(*a) for a in product(*self.base_sets))) return self def _kind(self): return SetKind(self.lamda.expr.kind)
ImageSet
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 45292, "end": 45411 }
class ____(BaseModel): responses: Dict[str, "OperationDurationStatistics"] = Field(..., description="")
GrpcTelemetry
python
matplotlib__matplotlib
lib/matplotlib/backends/backend_pdf.py
{ "start": 14449, "end": 14641 }
class ____: """Store verbatim PDF command content for later inclusion in the stream.""" def __init__(self, x): self._x = x def pdfRepr(self): return self._x
Verbatim
python
astropy__astropy
astropy/table/tests/conftest.py
{ "start": 1232, "end": 1285 }
class ____(table.TableColumns): pass
MyTableColumns
python
walkccc__LeetCode
solutions/1759. Count Number of Homogenous Substrings/1759.py
{ "start": 0, "end": 274 }
class ____: def countHomogenous(self, s: str) -> int: MOD = 1_000_000_007 ans = 0 count = 0 currentChar = '@' for c in s: count = count + 1 if c == currentChar else 1 currentChar = c ans += count ans %= MOD return ans
Solution
python
spyder-ide__spyder
spyder/plugins/run/confpage.py
{ "start": 1343, "end": 6042 }
class ____(HoverRowsTableView): def __init__(self, parent, model): super().__init__(parent) self._parent = parent self.setModel(model) self.setSelectionBehavior(QAbstractItemView.SelectRows) self.setSelectionMode(QAbstractItemView.SingleSelection) self.setSortingEnabled(True) self.setEditTriggers(QAbstractItemView.AllEditTriggers) self.selectionModel().selectionChanged.connect(self.selection) self.verticalHeader().hide() self.reset_plain() self.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch) self.horizontalHeader().setSectionResizeMode( 1, QHeaderView.Stretch ) self.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch) def selection(self, index): # Detect if a row corresponds to a set of default parameters to prevent # users from deleting it. index = self.currentIndex().row() is_default = False if index >= 0: params_id = self._parent.table_model.params_index[index] params = self._parent.table_model.executor_conf_params[params_id] is_default = True if params.get("default") else False self._parent.set_buttons_status(is_default=is_default) # Always enable edit button self._parent.edit_configuration_btn.setEnabled(True) def adjust_cells(self): """Adjust column size based on contents.""" self.resizeColumnsToContents() model: ExecutorRunParametersTableModel = self.model() fm = self.horizontalHeader().fontMetrics() names = [fm.width(model.get_parameters_name(idx)) for idx in model] if names: self.setColumnWidth( ExecutorRunParametersTableModel.NAME, max(names)) self.horizontalHeader().setStretchLastSection(True) def reset_plain(self): self.model().reset_model() self.adjust_cells() self.selectionModel().selectionChanged.connect(self.selection) def show_editor(self, new=False, clone=False): extension, context, params = None, None, None extensions, contexts, plugin_name, executor_params = ( self._parent.get_executor_configurations() ) if not new: index = self.currentIndex().row() model: ExecutorRunParametersTableModel = self.model() (extension, context, params) = model[index] self.dialog = ExecutionParametersDialog( parent=self, executor_name=plugin_name, executor_params=executor_params, param_names=self.model().get_parameter_names(), extensions=extensions, contexts=contexts, current_params=params, extension=extension, context=context, new_config=new, ) self.dialog.setup() self.dialog.finished.connect( functools.partial( self.process_run_dialog_result, new=new, clone=clone, params=params ) ) if not clone: self.dialog.open() else: self.dialog.accept() def process_run_dialog_result(self, result, new=False, clone=False, params=None): status = self.dialog.status if status == RunDialogStatus.Close: return conf = self.dialog.get_configuration() if conf is None: return else: extension, context, new_executor_params = conf if not new and clone: new_executor_params["uuid"] = str(uuid4()) new_executor_params["name"] = _('%s (copy)') % params['name'] changes = [] if params and not clone: changes.append(('deleted', params)) changes.append(('new', new_executor_params)) self.model().apply_changes(changes, extension, context) def clone_configuration(self): self.show_editor(clone=True) def focusInEvent(self, e): """Qt Override.""" super().focusInEvent(e) self.selectRow(self.currentIndex().row()) self.selection(self.currentIndex().row()) def keyPressEvent(self, event): """Qt Override.""" key = event.key() if key in [Qt.Key_Enter, Qt.Key_Return]: self.show_editor() elif key in [Qt.Key_Up, Qt.Key_Down, Qt.Key_Left, Qt.Key_Right]: super().keyPressEvent(event) else: super().keyPressEvent(event) def mouseDoubleClickEvent(self, event): """Qt Override.""" self.show_editor()
RunParametersTableView
python
apache__airflow
providers/celery/tests/unit/celery/executors/test_celery_executor.py
{ "start": 2480, "end": 4099 }
class ____: @property def state(self): raise Exception(FAKE_EXCEPTION_MSG) def task_id(self): return "task_id" @contextlib.contextmanager def _prepare_app(broker_url=None, execute=None): broker_url = broker_url or conf.get("celery", "BROKER_URL") if AIRFLOW_V_3_0_PLUS: execute_name = "execute_workload" execute = execute or celery_executor_utils.execute_workload.__wrapped__ else: execute_name = "execute_command" execute = execute or celery_executor_utils.execute_command.__wrapped__ test_config = dict(celery_executor_utils.celery_configuration) test_config.update({"broker_url": broker_url}) test_app = Celery(broker_url, config_source=test_config) test_execute = test_app.task(execute) patch_app = mock.patch.object(celery_executor_utils, "app", test_app) patch_execute = mock.patch.object(celery_executor_utils, execute_name, test_execute) backend = test_app.backend if hasattr(backend, "ResultSession"): # Pre-create the database tables now, otherwise SQLA via Celery has a # race condition where it one of the subprocesses can die with "Table # already exists" error, because SQLA checks for which tables exist, # then issues a CREATE TABLE, rather than doing CREATE TABLE IF NOT # EXISTS session = backend.ResultSession() session.close() with patch_app, patch_execute: try: yield test_app finally: # Clear event loop to tear down each celery instance set_event_loop(None)
FakeCeleryResult
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/matrix_mult_test.py
{ "start": 2067, "end": 2980 }
class ____(op_bench.TorchBenchmarkBase): def init(self, B, M, N, device, op_func): self.inputs = { "input_one": torch.rand(B, M, N, device=device), "input_two": torch.rand(B, M, N, device=device), } self.op_func = op_func def forward(self, input_one, input_two): if self.op_func.__name__ == "einsum": return torch.einsum("bij,bij->bij", input_one, input_two) else: return torch.mul(input_one, input_two) op_bench.generate_pt_tests_from_op_list( batch_mm_op_list, batch_mm_configs_short + batch_mm_configs_long, BatchMatrixMultBenchmark, ) op_bench.generate_pt_tests_from_op_list( batch_elementwise_op_list, batch_elementwise_configs_short + batch_elementwise_configs_long, BatchElementWiseBenchmark, ) if __name__ == "__main__": op_bench.benchmark_runner.main()
BatchElementWiseBenchmark
python
pypa__virtualenv
src/virtualenv/create/via_global_ref/builtin/cpython/cpython3.py
{ "start": 1580, "end": 6427 }
class ____(CPythonWindows, CPython3): """CPython 3 on Windows.""" @classmethod def setup_meta(cls, interpreter): if is_store_python(interpreter): # store python is not supported here return None return super().setup_meta(interpreter) @classmethod def sources(cls, interpreter): if cls.has_shim(interpreter): refs = cls.executables(interpreter) else: refs = chain( cls.executables(interpreter), cls.dll_and_pyd(interpreter), cls.python_zip(interpreter), ) yield from refs @classmethod def executables(cls, interpreter): sources = super().sources(interpreter) if interpreter.version_info >= (3, 13): # Create new refs with corrected launcher paths updated_sources = [] for ref in sources: if ref.src.name == "python.exe": launcher_path = ref.src.with_name("venvlauncher.exe") if launcher_path.exists(): new_ref = ExePathRefToDest( launcher_path, dest=ref.dest, targets=[ref.base, *ref.aliases], must=ref.must, when=ref.when ) updated_sources.append(new_ref) continue elif ref.src.name == "pythonw.exe": w_launcher_path = ref.src.with_name("venvwlauncher.exe") if w_launcher_path.exists(): new_ref = ExePathRefToDest( w_launcher_path, dest=ref.dest, targets=[ref.base, *ref.aliases], must=ref.must, when=ref.when, ) updated_sources.append(new_ref) continue # Keep the original ref unchanged updated_sources.append(ref) return updated_sources return sources @classmethod def has_shim(cls, interpreter): return interpreter.version_info.minor >= 7 and cls.shim(interpreter) is not None # noqa: PLR2004 @classmethod def shim(cls, interpreter): root = Path(interpreter.system_stdlib) / "venv" / "scripts" / "nt" # Before 3.13 the launcher was called python.exe, after is venvlauncher.exe # https://github.com/python/cpython/issues/112984 exe_name = "venvlauncher.exe" if interpreter.version_info >= (3, 13) else "python.exe" shim = root / exe_name if shim.exists(): return shim return None @classmethod def host_python(cls, interpreter): if cls.has_shim(interpreter): # starting with CPython 3.7 Windows ships with a venvlauncher.exe that avoids the need for dll/pyd copies # it also means the wrapper must be copied to avoid bugs such as https://bugs.python.org/issue42013 return cls.shim(interpreter) return super().host_python(interpreter) @classmethod def dll_and_pyd(cls, interpreter): folders = [Path(interpreter.system_executable).parent] # May be missing on some Python hosts. # See https://github.com/pypa/virtualenv/issues/2368 dll_folder = Path(interpreter.system_prefix) / "DLLs" if dll_folder.is_dir(): folders.append(dll_folder) for folder in folders: for file in folder.iterdir(): if file.suffix in {".pyd", ".dll"}: yield PathRefToDest(file, cls.to_bin) @classmethod def python_zip(cls, interpreter): """ "python{VERSION}.zip" contains compiled *.pyc std lib packages, where "VERSION" is `py_version_nodot` var from the `sysconfig` module. :see: https://docs.python.org/3/using/windows.html#the-embeddable-package :see: `discovery.py_info.PythonInfo` class (interpreter). :see: `python -m sysconfig` output. :note: The embeddable Python distribution for Windows includes "python{VERSION}.zip" and "python{VERSION}._pth" files. User can move/rename *zip* file and edit `sys.path` by editing *_pth* file. Here the `pattern` is used only for the default *zip* file name! """ # noqa: D205 pattern = f"*python{interpreter.version_nodot}.zip" matches = fnmatch.filter(interpreter.path, pattern) matched_paths = map(Path, matches) existing_paths = filter(method("exists"), matched_paths) path = next(existing_paths, None) if path is not None: yield PathRefToDest(path, cls.to_bin) __all__ = [ "CPython3", "CPython3Posix", "CPython3Windows", ]
CPython3Windows
python
great-expectations__great_expectations
great_expectations/exceptions/exceptions.py
{ "start": 14386, "end": 14522 }
class ____(GreatExpectationsError): """Error connecting to a database including during an integration test."""
DatabaseConnectionError
python
pyparsing__pyparsing
examples/lineno_example.py
{ "start": 966, "end": 1530 }
class ____: def __init__(self, st, locn, tok_string): self.token_string = tok_string self.locn = locn self.source_line = pp.line(locn, st) self.line_no = pp.lineno(locn, st) self.col = pp.col(locn, st) def __str__(self): return f"{self.token_string!r} (line: {self.line_no}, col: {self.col})" def create_token_object(st, locn, toks): return Token(st, locn, toks[0]) wd = pp.Word(pp.alphas).set_parse_action(create_token_object) for token_obj in wd[1, ...].parse_string(data): print(token_obj)
Token
python
airbytehq__airbyte
airbyte-integrations/connectors/source-mailchimp/unit_tests/test_config_datacenter_migration.py
{ "start": 463, "end": 3793 }
class ____: """Test cases for ExtractAndSetDataCenterConfigValue.""" def setup_method(self): """Set up test fixtures.""" self.extractor = ExtractAndSetDataCenterConfigValue() def test_transform_with_existing_data_center(self): """Test that transform exits early if data_center already exists.""" config = {"data_center": "us10", "credentials": {"auth_type": "oauth2.0"}} original_config = config.copy() self.extractor.transform(config) # Config should remain unchanged assert config == original_config def test_transform_oauth_success(self, requests_mock): """Test successful OAuth data center extraction.""" requests_mock.get("https://login.mailchimp.com/oauth2/metadata", json={"dc": "us10"}) config = {"credentials": {"auth_type": "oauth2.0", "access_token": "test_token"}} self.extractor.transform(config) assert config.get("data_center") == "us10" def test_transform_oauth_invalid_token(self, requests_mock): """Test OAuth invalid token error handling.""" requests_mock.get("https://login.mailchimp.com/oauth2/metadata", json={"error": "invalid_token"}) config = {"credentials": {"auth_type": "oauth2.0", "access_token": "invalid_token"}} with pytest.raises(AirbyteTracedException) as exc_info: self.extractor.transform(config) assert exc_info.value.failure_type == FailureType.config_error assert "invalid" in exc_info.value.message.lower() def test_transform_oauth_network_error(self, requests_mock): """Test OAuth network error handling.""" requests_mock.get("https://login.mailchimp.com/oauth2/metadata", exc=requests.exceptions.RequestException("Network error")) config = {"credentials": {"auth_type": "oauth2.0", "access_token": "test_token"}} with pytest.raises(AirbyteTracedException) as exc_info: self.extractor.transform(config) assert exc_info.value.failure_type == FailureType.config_error assert "Unable to extract data center" in exc_info.value.message def test_transform_apikey_credentials_success(self): """Test successful API key data center extraction from credentials.""" config = {"credentials": {"auth_type": "apikey", "apikey": "test_key-us20"}} self.extractor.transform(config) assert config.get("data_center") == "us20" def test_transform_apikey_top_level_success(self): """Test successful API key data center extraction from top level (backward compatibility).""" config = {"apikey": "test_key-us30"} self.extractor.transform(config) assert config.get("data_center") == "us30" def test_transform_oauth_http_error(self, requests_mock): """Test OAuth HTTP error handling.""" requests_mock.get("https://login.mailchimp.com/oauth2/metadata", status_code=500) config = {"credentials": {"auth_type": "oauth2.0", "access_token": "test_token"}} with pytest.raises(AirbyteTracedException) as exc_info: self.extractor.transform(config) assert exc_info.value.failure_type == FailureType.config_error assert "Unable to extract data center" in exc_info.value.message
TestExtractAndSetDataCenterConfigValue
python
explosion__spaCy
spacy/lang/ti/__init__.py
{ "start": 735, "end": 834 }
class ____(Language): lang = "ti" Defaults = TigrinyaDefaults __all__ = ["Tigrinya"]
Tigrinya
python
pennersr__django-allauth
tests/apps/socialaccount/test_registry.py
{ "start": 297, "end": 2012 }
class ____(TestCase): @override_settings( INSTALLED_APPS=[ "allauth.socialaccount.providers.facebook", ] ) def test_load_provider_with_default_app_config(self): registry = providers.ProviderRegistry() provider_list = registry.get_class_list() self.assertTrue(registry.loaded) self.assertEqual(1, len(provider_list)) self.assertTrue( issubclass( provider_list[0], providers.facebook.provider.FacebookProvider, ) ) app_config_list = list(apps.get_app_configs()) self.assertEqual(1, len(app_config_list)) app_config = app_config_list[0] self.assertEqual("allauth.socialaccount.providers.facebook", app_config.name) self.assertEqual("facebook", app_config.label) @override_settings( INSTALLED_APPS=[ "tests.apps.socialaccount.test_registry.CustomFacebookAppConfig", ] ) def test_load_provider_with_custom_app_config(self): registry = providers.ProviderRegistry() provider_list = registry.get_class_list() self.assertTrue(registry.loaded) self.assertEqual(1, len(provider_list)) self.assertTrue( issubclass( provider_list[0], providers.facebook.provider.FacebookProvider, ) ) app_config_list = list(apps.get_app_configs()) self.assertEqual(1, len(app_config_list)) app_config = app_config_list[0] self.assertEqual("allauth.socialaccount.providers.facebook", app_config.name) self.assertEqual("allauth_facebook", app_config.label)
ProviderRegistryTests
python
davidhalter__jedi
jedi/inference/value/iterable.py
{ "start": 6508, "end": 7682 }
class ____(LazyAttributeOverwrite, IterableMixin): api_type = 'instance' @property def name(self): return compiled.CompiledValueName(self, self.array_type) def _get_generics(self): return (self.merge_types_of_iterate().py__class__(),) @inference_state_method_cache(default=()) def _cached_generics(self): return self._get_generics() def _get_wrapped_value(self): from jedi.inference.gradual.base import GenericClass from jedi.inference.gradual.generics import TupleGenericManager klass = compiled.builtin_from_name(self.inference_state, self.array_type) c, = GenericClass( klass, TupleGenericManager(self._cached_generics()) ).execute_annotation() return c def py__bool__(self): return None # We don't know the length, because of appends. @safe_property def parent(self): return self.inference_state.builtins_module def py__getitem__(self, index_value_set, contextualized_node): if self.array_type == 'dict': return self._dict_values() return iterate_values(ValueSet([self]))
Sequence
python
getsentry__sentry
tests/sentry/utils/security/test_orgauthtoken_token.py
{ "start": 214, "end": 2524 }
class ____(TestCase): def test_generate_token(self) -> None: token = generate_token("test-org", "https://test-region.sentry.io") assert token assert token.startswith(SENTRY_ORG_AUTH_TOKEN_PREFIX) def test_parse_token(self) -> None: token = generate_token("test-org", "https://test-region.sentry.io") token_payload = parse_token(token) assert token_payload is not None assert token_payload["org"] == "test-org" assert token_payload["url"] == "http://testserver" assert token_payload["region_url"] == "https://test-region.sentry.io" def test_parse_invalid_token(self) -> None: assert parse_token("invalid-token") is None def test_parse_invalid_token_json(self) -> None: payload_str = ( '{"iat": 12345678,"url": "test-site","region_url": "test-site","org": "test-org}' ) payload_hashed = base64_encode_str(payload_str) token = SENTRY_ORG_AUTH_TOKEN_PREFIX + payload_hashed + "_secret" assert parse_token(token) is None def test_parse_invalid_token_iat(self) -> None: payload = { "url": "test-site", "region_url": "test-site", "org": "test-org", } payload_str = json.dumps(payload) payload_hashed = base64_encode_str(payload_str) token = SENTRY_ORG_AUTH_TOKEN_PREFIX + payload_hashed + "_secret" assert parse_token(token) is None def test_parse_invalid_token_missing_secret(self) -> None: payload = { "iat": 12345678, "url": "test-site", "region_url": "test-site", "org": "test-org", } payload_str = json.dumps(payload) payload_hashed = base64_encode_str(payload_str) token = SENTRY_ORG_AUTH_TOKEN_PREFIX + payload_hashed assert parse_token(token) is None def test_generate_token_unique(self) -> None: jwt1 = generate_token("test-org", "https://test-region.sentry.io") jwt2 = generate_token("test-org", "https://test-region.sentry.io") jwt3 = generate_token("test-org", "https://test-region.sentry.io") assert jwt1 assert jwt2 assert jwt3 assert jwt1 != jwt2 assert jwt2 != jwt3
OrgAuthTokenTokenTest
python
kamyu104__LeetCode-Solutions
Python/number-of-ways-to-build-house-of-cards.py
{ "start": 466, "end": 944 }
class ____(object): def houseOfCards(self, n): """ :type n: int :rtype: int """ dp = [[0]*(n+1) for _ in xrange((n+1)//3+1)] # dp[t][i]: number of ways with i cards and t triangles in the first row dp[0][0] = 1 for t in xrange(1, (n+1)//3+1): for i in xrange(3*t-1, n+1): dp[t][i] = sum(dp[j][i-(3*t-1)] for j in xrange(t)) return sum(dp[t][n] for t in xrange((n+1)//3+1))
Solution_TLE
python
huggingface__transformers
src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py
{ "start": 142619, "end": 145615 }
class ____(nn.Module): """ A modified Snake function which uses separate parameters for the magnitude of the periodic components Shape: - Input: (B, C, T) - Output: (B, C, T), same shape as the input Parameters: - alpha - trainable parameter that controls frequency - beta - trainable parameter that controls magnitude References: - This activation function is a modified version based on this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda: https://huggingface.co/papers/2006.08195 """ def __init__(self, in_features, alpha=1.0): super().__init__() self.in_features = in_features # initialize alpha self.alpha = Parameter(torch.zeros(in_features) * alpha) self.beta = Parameter(torch.zeros(in_features) * alpha) self.no_div_by_zero = 0.000000001 def forward(self, hidden_states): """ Forward pass of the function. Applies the function to the input elementwise. SnakeBeta ∶= x + 1/b * sin^2 (xa) """ alpha = self.alpha.unsqueeze(0).unsqueeze(-1) # line up with x to [B, C, T] beta = self.beta.unsqueeze(0).unsqueeze(-1) alpha = torch.exp(alpha) beta = torch.exp(beta) hidden_states = hidden_states + (1.0 / (beta + self.no_div_by_zero)) * torch.pow( torch.sin(hidden_states * alpha), 2 ) return hidden_states def kaiser_sinc_filter1d(cutoff, half_width, kernel_size): """Generates a 1D Kaiser-windowed sinc filter. Args: cutoff (float): Normalized cutoff frequency (0 to 0.5). half_width (float): Transition bandwidth. kernel_size (int): Number of filter taps. Returns: torch.Tensor: A tensor of shape (1, 1, kernel_size) representing the filter. """ is_even = kernel_size % 2 == 0 half_size = kernel_size // 2 # Compute Kaiser window parameters delta_f = 4 * half_width attenuation = 2.285 * (half_size - 1) * math.pi * delta_f + 7.95 if attenuation > 50.0: beta = 0.1102 * (attenuation - 8.7) elif attenuation >= 21.0: beta = 0.5842 * (attenuation - 21) ** 0.4 + 0.07886 * (attenuation - 21.0) else: beta = 0.0 kaiser_window = torch.kaiser_window(kernel_size, beta=beta, periodic=False, dtype=torch.float32) # Compute time indices if is_even: time_indices = torch.arange(-half_size, half_size) + 0.5 else: time_indices = torch.arange(kernel_size) - half_size # Compute sinc filter if cutoff == 0: return torch.zeros((1, 1, kernel_size), dtype=torch.float32) # Ensures correct shape sinc_filter = torch.sinc(2 * cutoff * time_indices) normalized_filter = 2 * cutoff * kaiser_window * sinc_filter # Normalize to ensure sum = 1 (avoid leakage of constant component) normalized_filter /= normalized_filter.sum() return normalized_filter.view(1, 1, kernel_size)
SnakeBeta
python
fastai__fastai
fastai/torch_core.py
{ "start": 4745, "end": 4954 }
class ____(ndarray): "An `ndarray` that can modify casting behavior" @classmethod def _before_cast(cls, x): return x if isinstance(x,ndarray) else array(x) # %% ../nbs/00_torch_core.ipynb 28
ArrayBase
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/isinstance4.py
{ "start": 610, "end": 715 }
class ____(Protocol): pass isinstance(4, MyProtocol2) issubclass(str, (str, MyProtocol2))
MyProtocol2
python
pytorch__pytorch
torch/onnx/_internal/fx/passes/type_promotion.py
{ "start": 47581, "end": 50495 }
class ____(_python_dispatch.TorchDispatchMode): """Trace ops that were dispatched. Utilize the dispatch mechanism in [`__torch_dispatch__`](https://dev-discuss.pytorch.org/t/what-and-why-is-torch-dispatch/557) to trace op overloads that were dispatched to. This is used to find the compatible op overload for a given op overload packet for different set of args and kwargs. """ def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.traced_ops = [] def __torch_dispatch__(self, func, types, args=(), kwargs=None): self.traced_ops.append(func) return func(*args, **kwargs) def find_compatible_op_overload( op: torch._ops.OpOverloadPacket, args: tuple, kwargs: dict ) -> torch._ops.OpOverload: """Find compatible OpOverload for an OpOverloadPacket using provided args and kwargs. Each "call_function" fx.Node in the fx.GraphModule has a target that represents a torch._ops.OpOverload. The OpOverload contains an OpOverloadPacket that holds all the available overloads for the operation. During the type promotion pass, there are cases where the types of the args and kwargs may change, such as promoting Python numbers to tensors. Consequently, the original OpOverload might not be compatible with the updated args and kwargs. This function is used to identify the compatible OpOverload for the given args and kwargs. Args: op: OpOverloadPacket to find compatible OpOverload for. args: The positional arguments to consider for compatibility. kwargs: The keyword arguments to consider for compatibility. Returns: torch._ops.OpOverload: The compatible OpOverload found for the given args and kwargs. Raises: RuntimeError: If no compatible op overload is found. Examples: >>> import torch >>> packet = torch.ops.aten.pow >>> args = (torch.tensor([1.0, 2.0]), 2) >>> find_compatible_op_overload(packet, args, {})._overloadname 'Tensor_Scalar' >>> args = (torch.tensor([1.0, 2.0]), torch.tensor(2.0)) >>> find_compatible_op_overload(packet, args, {})._overloadname 'Tensor_Tensor' """ # Utilize the dispatch mechanism to find the compatible op overload. op_trace_dispatch_mode = _OpTraceDispatchMode() with op_trace_dispatch_mode: op(*args, **kwargs) assert len(op_trace_dispatch_mode.traced_ops) >= 1, ( "Expected at least 1 traced op, got 0" ) new_op_overload = op_trace_dispatch_mode.traced_ops[0] assert isinstance(new_op_overload, torch._ops.OpOverload), ( f"Expected OpOverload, got {type(new_op_overload)}" ) assert new_op_overload.overloadpacket == op, ( f"Expected same OpOverload packet, got {new_op_overload.overloadpacket} != {op}" ) return new_op_overload
_OpTraceDispatchMode
python
getsentry__sentry-python
sentry_sdk/integrations/openai.py
{ "start": 1564, "end": 25131 }
class ____(Integration): identifier = "openai" origin = f"auto.ai.{identifier}" def __init__(self, include_prompts=True, tiktoken_encoding_name=None): # type: (OpenAIIntegration, bool, Optional[str]) -> None self.include_prompts = include_prompts self.tiktoken_encoding = None if tiktoken_encoding_name is not None: import tiktoken # type: ignore self.tiktoken_encoding = tiktoken.get_encoding(tiktoken_encoding_name) @staticmethod def setup_once(): # type: () -> None Completions.create = _wrap_chat_completion_create(Completions.create) AsyncCompletions.create = _wrap_async_chat_completion_create( AsyncCompletions.create ) Embeddings.create = _wrap_embeddings_create(Embeddings.create) AsyncEmbeddings.create = _wrap_async_embeddings_create(AsyncEmbeddings.create) if RESPONSES_API_ENABLED: Responses.create = _wrap_responses_create(Responses.create) AsyncResponses.create = _wrap_async_responses_create(AsyncResponses.create) def count_tokens(self, s): # type: (OpenAIIntegration, str) -> int if self.tiktoken_encoding is not None: return len(self.tiktoken_encoding.encode_ordinary(s)) return 0 def _capture_exception(exc, manual_span_cleanup=True): # type: (Any, bool) -> None # Close an eventually open span # We need to do this by hand because we are not using the start_span context manager current_span = sentry_sdk.get_current_span() set_span_errored(current_span) if manual_span_cleanup and current_span is not None: current_span.__exit__(None, None, None) event, hint = event_from_exception( exc, client_options=sentry_sdk.get_client().options, mechanism={"type": "openai", "handled": False}, ) sentry_sdk.capture_event(event, hint=hint) def _get_usage(usage, names): # type: (Any, List[str]) -> int for name in names: if hasattr(usage, name) and isinstance(getattr(usage, name), int): return getattr(usage, name) return 0 def _calculate_token_usage( messages, response, span, streaming_message_responses, count_tokens ): # type: (Optional[Iterable[ChatCompletionMessageParam]], Any, Span, Optional[List[str]], Callable[..., Any]) -> None input_tokens = 0 # type: Optional[int] input_tokens_cached = 0 # type: Optional[int] output_tokens = 0 # type: Optional[int] output_tokens_reasoning = 0 # type: Optional[int] total_tokens = 0 # type: Optional[int] if hasattr(response, "usage"): input_tokens = _get_usage(response.usage, ["input_tokens", "prompt_tokens"]) if hasattr(response.usage, "input_tokens_details"): input_tokens_cached = _get_usage( response.usage.input_tokens_details, ["cached_tokens"] ) output_tokens = _get_usage( response.usage, ["output_tokens", "completion_tokens"] ) if hasattr(response.usage, "output_tokens_details"): output_tokens_reasoning = _get_usage( response.usage.output_tokens_details, ["reasoning_tokens"] ) total_tokens = _get_usage(response.usage, ["total_tokens"]) # Manually count tokens if input_tokens == 0: for message in messages or []: if isinstance(message, dict) and "content" in message: input_tokens += count_tokens(message["content"]) elif isinstance(message, str): input_tokens += count_tokens(message) if output_tokens == 0: if streaming_message_responses is not None: for message in streaming_message_responses: output_tokens += count_tokens(message) elif hasattr(response, "choices"): for choice in response.choices: if hasattr(choice, "message"): output_tokens += count_tokens(choice.message) # Do not set token data if it is 0 input_tokens = input_tokens or None input_tokens_cached = input_tokens_cached or None output_tokens = output_tokens or None output_tokens_reasoning = output_tokens_reasoning or None total_tokens = total_tokens or None record_token_usage( span, input_tokens=input_tokens, input_tokens_cached=input_tokens_cached, output_tokens=output_tokens, output_tokens_reasoning=output_tokens_reasoning, total_tokens=total_tokens, ) def _set_input_data(span, kwargs, operation, integration): # type: (Span, dict[str, Any], str, OpenAIIntegration) -> None # Input messages (the prompt or data sent to the model) messages = kwargs.get("messages") if messages is None: messages = kwargs.get("input") if isinstance(messages, str): messages = [messages] if ( messages is not None and len(messages) > 0 and should_send_default_pii() and integration.include_prompts ): normalized_messages = normalize_message_roles(messages) scope = sentry_sdk.get_current_scope() messages_data = truncate_and_annotate_messages(normalized_messages, span, scope) if messages_data is not None: # Use appropriate field based on operation type if operation == "embeddings": set_data_normalized( span, SPANDATA.GEN_AI_EMBEDDINGS_INPUT, messages_data, unpack=False ) else: set_data_normalized( span, SPANDATA.GEN_AI_REQUEST_MESSAGES, messages_data, unpack=False ) # Input attributes: Common set_data_normalized(span, SPANDATA.GEN_AI_SYSTEM, "openai") set_data_normalized(span, SPANDATA.GEN_AI_OPERATION_NAME, operation) # Input attributes: Optional kwargs_keys_to_attributes = { "model": SPANDATA.GEN_AI_REQUEST_MODEL, "stream": SPANDATA.GEN_AI_RESPONSE_STREAMING, "max_tokens": SPANDATA.GEN_AI_REQUEST_MAX_TOKENS, "presence_penalty": SPANDATA.GEN_AI_REQUEST_PRESENCE_PENALTY, "frequency_penalty": SPANDATA.GEN_AI_REQUEST_FREQUENCY_PENALTY, "temperature": SPANDATA.GEN_AI_REQUEST_TEMPERATURE, "top_p": SPANDATA.GEN_AI_REQUEST_TOP_P, } for key, attribute in kwargs_keys_to_attributes.items(): value = kwargs.get(key) if value is not None and _is_given(value): set_data_normalized(span, attribute, value) # Input attributes: Tools tools = kwargs.get("tools") if tools is not None and _is_given(tools) and len(tools) > 0: set_data_normalized( span, SPANDATA.GEN_AI_REQUEST_AVAILABLE_TOOLS, safe_serialize(tools) ) def _set_output_data(span, response, kwargs, integration, finish_span=True): # type: (Span, Any, dict[str, Any], OpenAIIntegration, bool) -> None if hasattr(response, "model"): set_data_normalized(span, SPANDATA.GEN_AI_RESPONSE_MODEL, response.model) # Input messages (the prompt or data sent to the model) # used for the token usage calculation messages = kwargs.get("messages") if messages is None: messages = kwargs.get("input") if messages is not None and isinstance(messages, str): messages = [messages] if hasattr(response, "choices"): if should_send_default_pii() and integration.include_prompts: response_text = [ choice.message.model_dump() for choice in response.choices if choice.message is not None ] if len(response_text) > 0: set_data_normalized(span, SPANDATA.GEN_AI_RESPONSE_TEXT, response_text) _calculate_token_usage(messages, response, span, None, integration.count_tokens) if finish_span: span.__exit__(None, None, None) elif hasattr(response, "output"): if should_send_default_pii() and integration.include_prompts: output_messages = { "response": [], "tool": [], } # type: (dict[str, list[Any]]) for output in response.output: if output.type == "function_call": output_messages["tool"].append(output.dict()) elif output.type == "message": for output_message in output.content: try: output_messages["response"].append(output_message.text) except AttributeError: # Unknown output message type, just return the json output_messages["response"].append(output_message.dict()) if len(output_messages["tool"]) > 0: set_data_normalized( span, SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS, output_messages["tool"], unpack=False, ) if len(output_messages["response"]) > 0: set_data_normalized( span, SPANDATA.GEN_AI_RESPONSE_TEXT, output_messages["response"] ) _calculate_token_usage(messages, response, span, None, integration.count_tokens) if finish_span: span.__exit__(None, None, None) elif hasattr(response, "_iterator"): data_buf: list[list[str]] = [] # one for each choice old_iterator = response._iterator def new_iterator(): # type: () -> Iterator[ChatCompletionChunk] count_tokens_manually = True for x in old_iterator: with capture_internal_exceptions(): # OpenAI chat completion API if hasattr(x, "choices"): choice_index = 0 for choice in x.choices: if hasattr(choice, "delta") and hasattr( choice.delta, "content" ): content = choice.delta.content if len(data_buf) <= choice_index: data_buf.append([]) data_buf[choice_index].append(content or "") choice_index += 1 # OpenAI responses API elif hasattr(x, "delta"): if len(data_buf) == 0: data_buf.append([]) data_buf[0].append(x.delta or "") # OpenAI responses API end of streaming response if RESPONSES_API_ENABLED and isinstance(x, ResponseCompletedEvent): _calculate_token_usage( messages, x.response, span, None, integration.count_tokens, ) count_tokens_manually = False yield x with capture_internal_exceptions(): if len(data_buf) > 0: all_responses = ["".join(chunk) for chunk in data_buf] if should_send_default_pii() and integration.include_prompts: set_data_normalized( span, SPANDATA.GEN_AI_RESPONSE_TEXT, all_responses ) if count_tokens_manually: _calculate_token_usage( messages, response, span, all_responses, integration.count_tokens, ) if finish_span: span.__exit__(None, None, None) async def new_iterator_async(): # type: () -> AsyncIterator[ChatCompletionChunk] count_tokens_manually = True async for x in old_iterator: with capture_internal_exceptions(): # OpenAI chat completion API if hasattr(x, "choices"): choice_index = 0 for choice in x.choices: if hasattr(choice, "delta") and hasattr( choice.delta, "content" ): content = choice.delta.content if len(data_buf) <= choice_index: data_buf.append([]) data_buf[choice_index].append(content or "") choice_index += 1 # OpenAI responses API elif hasattr(x, "delta"): if len(data_buf) == 0: data_buf.append([]) data_buf[0].append(x.delta or "") # OpenAI responses API end of streaming response if RESPONSES_API_ENABLED and isinstance(x, ResponseCompletedEvent): _calculate_token_usage( messages, x.response, span, None, integration.count_tokens, ) count_tokens_manually = False yield x with capture_internal_exceptions(): if len(data_buf) > 0: all_responses = ["".join(chunk) for chunk in data_buf] if should_send_default_pii() and integration.include_prompts: set_data_normalized( span, SPANDATA.GEN_AI_RESPONSE_TEXT, all_responses ) if count_tokens_manually: _calculate_token_usage( messages, response, span, all_responses, integration.count_tokens, ) if finish_span: span.__exit__(None, None, None) if str(type(response._iterator)) == "<class 'async_generator'>": response._iterator = new_iterator_async() else: response._iterator = new_iterator() else: _calculate_token_usage(messages, response, span, None, integration.count_tokens) if finish_span: span.__exit__(None, None, None) def _new_chat_completion_common(f, *args, **kwargs): # type: (Any, Any, Any) -> Any integration = sentry_sdk.get_client().get_integration(OpenAIIntegration) if integration is None: return f(*args, **kwargs) if "messages" not in kwargs: # invalid call (in all versions of openai), let it return error return f(*args, **kwargs) try: iter(kwargs["messages"]) except TypeError: # invalid call (in all versions), messages must be iterable return f(*args, **kwargs) model = kwargs.get("model") operation = "chat" span = sentry_sdk.start_span( op=consts.OP.GEN_AI_CHAT, name=f"{operation} {model}", origin=OpenAIIntegration.origin, ) span.__enter__() _set_input_data(span, kwargs, operation, integration) response = yield f, args, kwargs _set_output_data(span, response, kwargs, integration, finish_span=True) return response def _wrap_chat_completion_create(f): # type: (Callable[..., Any]) -> Callable[..., Any] def _execute_sync(f, *args, **kwargs): # type: (Any, Any, Any) -> Any gen = _new_chat_completion_common(f, *args, **kwargs) try: f, args, kwargs = next(gen) except StopIteration as e: return e.value try: try: result = f(*args, **kwargs) except Exception as e: _capture_exception(e) raise e from None return gen.send(result) except StopIteration as e: return e.value @wraps(f) def _sentry_patched_create_sync(*args, **kwargs): # type: (Any, Any) -> Any integration = sentry_sdk.get_client().get_integration(OpenAIIntegration) if integration is None or "messages" not in kwargs: # no "messages" means invalid call (in all versions of openai), let it return error return f(*args, **kwargs) return _execute_sync(f, *args, **kwargs) return _sentry_patched_create_sync def _wrap_async_chat_completion_create(f): # type: (Callable[..., Any]) -> Callable[..., Any] async def _execute_async(f, *args, **kwargs): # type: (Any, Any, Any) -> Any gen = _new_chat_completion_common(f, *args, **kwargs) try: f, args, kwargs = next(gen) except StopIteration as e: return await e.value try: try: result = await f(*args, **kwargs) except Exception as e: _capture_exception(e) raise e from None return gen.send(result) except StopIteration as e: return e.value @wraps(f) async def _sentry_patched_create_async(*args, **kwargs): # type: (Any, Any) -> Any integration = sentry_sdk.get_client().get_integration(OpenAIIntegration) if integration is None or "messages" not in kwargs: # no "messages" means invalid call (in all versions of openai), let it return error return await f(*args, **kwargs) return await _execute_async(f, *args, **kwargs) return _sentry_patched_create_async def _new_embeddings_create_common(f, *args, **kwargs): # type: (Any, Any, Any) -> Any integration = sentry_sdk.get_client().get_integration(OpenAIIntegration) if integration is None: return f(*args, **kwargs) model = kwargs.get("model") operation = "embeddings" with sentry_sdk.start_span( op=consts.OP.GEN_AI_EMBEDDINGS, name=f"{operation} {model}", origin=OpenAIIntegration.origin, ) as span: _set_input_data(span, kwargs, operation, integration) response = yield f, args, kwargs _set_output_data(span, response, kwargs, integration, finish_span=False) return response def _wrap_embeddings_create(f): # type: (Any) -> Any def _execute_sync(f, *args, **kwargs): # type: (Any, Any, Any) -> Any gen = _new_embeddings_create_common(f, *args, **kwargs) try: f, args, kwargs = next(gen) except StopIteration as e: return e.value try: try: result = f(*args, **kwargs) except Exception as e: _capture_exception(e, manual_span_cleanup=False) raise e from None return gen.send(result) except StopIteration as e: return e.value @wraps(f) def _sentry_patched_create_sync(*args, **kwargs): # type: (Any, Any) -> Any integration = sentry_sdk.get_client().get_integration(OpenAIIntegration) if integration is None: return f(*args, **kwargs) return _execute_sync(f, *args, **kwargs) return _sentry_patched_create_sync def _wrap_async_embeddings_create(f): # type: (Any) -> Any async def _execute_async(f, *args, **kwargs): # type: (Any, Any, Any) -> Any gen = _new_embeddings_create_common(f, *args, **kwargs) try: f, args, kwargs = next(gen) except StopIteration as e: return await e.value try: try: result = await f(*args, **kwargs) except Exception as e: _capture_exception(e, manual_span_cleanup=False) raise e from None return gen.send(result) except StopIteration as e: return e.value @wraps(f) async def _sentry_patched_create_async(*args, **kwargs): # type: (Any, Any) -> Any integration = sentry_sdk.get_client().get_integration(OpenAIIntegration) if integration is None: return await f(*args, **kwargs) return await _execute_async(f, *args, **kwargs) return _sentry_patched_create_async def _new_responses_create_common(f, *args, **kwargs): # type: (Any, Any, Any) -> Any integration = sentry_sdk.get_client().get_integration(OpenAIIntegration) if integration is None: return f(*args, **kwargs) model = kwargs.get("model") operation = "responses" span = sentry_sdk.start_span( op=consts.OP.GEN_AI_RESPONSES, name=f"{operation} {model}", origin=OpenAIIntegration.origin, ) span.__enter__() _set_input_data(span, kwargs, operation, integration) response = yield f, args, kwargs _set_output_data(span, response, kwargs, integration, finish_span=True) return response def _wrap_responses_create(f): # type: (Any) -> Any def _execute_sync(f, *args, **kwargs): # type: (Any, Any, Any) -> Any gen = _new_responses_create_common(f, *args, **kwargs) try: f, args, kwargs = next(gen) except StopIteration as e: return e.value try: try: result = f(*args, **kwargs) except Exception as e: _capture_exception(e) raise e from None return gen.send(result) except StopIteration as e: return e.value @wraps(f) def _sentry_patched_create_sync(*args, **kwargs): # type: (Any, Any) -> Any integration = sentry_sdk.get_client().get_integration(OpenAIIntegration) if integration is None: return f(*args, **kwargs) return _execute_sync(f, *args, **kwargs) return _sentry_patched_create_sync def _wrap_async_responses_create(f): # type: (Any) -> Any async def _execute_async(f, *args, **kwargs): # type: (Any, Any, Any) -> Any gen = _new_responses_create_common(f, *args, **kwargs) try: f, args, kwargs = next(gen) except StopIteration as e: return await e.value try: try: result = await f(*args, **kwargs) except Exception as e: _capture_exception(e) raise e from None return gen.send(result) except StopIteration as e: return e.value @wraps(f) async def _sentry_patched_responses_async(*args, **kwargs): # type: (Any, Any) -> Any integration = sentry_sdk.get_client().get_integration(OpenAIIntegration) if integration is None: return await f(*args, **kwargs) return await _execute_async(f, *args, **kwargs) return _sentry_patched_responses_async def _is_given(obj): # type: (Any) -> bool """ Check for givenness safely across different openai versions. """ if NotGiven is not None and isinstance(obj, NotGiven): return False if Omit is not None and isinstance(obj, Omit): return False return True
OpenAIIntegration
python
xlwings__xlwings
xlwings/constants.py
{ "start": 116435, "end": 116613 }
class ____: xlSparkScaleCustom = 3 # from enum XlSparkScale xlSparkScaleGroup = 1 # from enum XlSparkScale xlSparkScaleSingle = 2 # from enum XlSparkScale
SparkScale
python
google__pytype
pytype/tools/xref/indexer.py
{ "start": 28600, "end": 39155 }
class ____: """Runs the indexer visitor and collects its results.""" def __init__(self, *, ast, src, loader, pytd_module, module_name): self.ast = ast self.source = src self.loader = loader self.pytd_module = pytd_module self.resolved_modules = loader.get_resolved_modules() self.imports = xref_utils.process_imports_map(loader.options.imports_map) self.module_name = module_name self.traces = src.traces self.defs = None self.locs = None self.refs = None self.envs = None self.modules = None self.aliases = None self.typemap = None self.classmap = None self.calls = None self.links = [] self.function_params = None self.function_map = None self.childof = [] # Optionally preserve the pytype vm so we can access the types later self.vm = None def index(self, code_ast): """Index an AST corresponding to self.source.""" v = IndexVisitor(self.ast, self.source, self.module_name) v.visit(code_ast) self.defs = v.defs self.locs = v.locs self.refs = v.refs self.envs = v.envs self.modules = v.modules self.aliases = v.aliases self.typemap = v.typemap self.classmap = v.classmap self.calls = v.calls self.function_params = v.function_params self.childof = v.childof def get_def_offsets(self, defloc): """Get the byte offsets for a definition.""" assert self.defs is not None defn = self.defs[defloc.def_id] typ = defn.typ if typ == "Attribute": start, end = self._get_attr_bounds(defn.name, defloc.location) else: start = self.source.get_offset(defloc.location) if typ in DEF_OFFSETS: start += DEF_OFFSETS[typ] end = start + len(defn.name) return (start, end) def get_doc_offsets(self, doc): """Get the byte offsets for a docstring.""" start = self.source.get_offset(doc.location) end = start + doc.length return (start, end) def finalize(self): """Postprocess the information gathered by the tree visitor.""" self.links = self._lookup_refs() def _get_attr_bounds(self, name, location): """Calculate the anchor bounds for an attr access.""" return self.get_anchor_bounds( *self.source.get_attr_location(name, location)) def get_anchor_bounds(self, location, length): """Generate byte offsets from a location and length.""" start = self.source.get_offset(location) end = start + length return (start, end) def get_ref_bounds(self, ref): if ref.typ == "Attribute": return self._get_attr_bounds(ref.name, ref.location) else: return self.get_anchor_bounds(ref.location, len(ref.name)) def _lookup_remote_symbol(self, defn, attr_name): """Try to look up a definition in an imported module.""" assert self.modules is not None if defn.id in self.modules: return Remote(self.modules[defn.id], name=attr_name, resolved=True) if not (defn.typ == "Import" or defn.typ == "ImportFrom"): return None try: [imported] = _unwrap(defn.data) except (TypeError, ValueError): resolved = False else: resolved = not isinstance(imported, abstract.Unsolvable) if not resolved: return Remote(defn.name, name=attr_name, resolved=False) assert not isinstance(imported, abstract.Module) assert defn.target remote = Remote(imported.module, name=defn.target, resolved=True) return remote.attr(attr_name) def _lookup_class_attr(self, name, attrib): """Look up a class attribute in the environment.""" assert self.envs is not None env = self.envs["module"] if name not in env.env: return None d = env.env[name] class_env = self.envs[d.id] _, defn = class_env.lookup(attrib) return defn def _get_attribute_class(self, obj): """Look up the class of an attribute target.""" if isinstance(obj, abstract.Module): return Module(obj.name) elif isinstance(obj, abstract.InterpreterClass): assert self.classmap is not None return self.classmap.get(obj) elif isinstance(obj, abstract.PyTDClass): if obj.module: return Remote(obj.module, obj.name, resolved=True) else: # Corner case: a namedtuple in the MRO of a class will generate a # PyTDClass even though it's in the current module. # TODO(mdemello): We need special handling for namedtuples to generate # and populate a class. return None else: return None def _get_mro(self, obj): if isinstance(obj, abstract.InterpreterClass): return obj.mro elif isinstance(obj, abstract.Instance): return obj.cls.mro else: return [] def _is_pytype_module(self, obj): return isinstance(obj, abstract.Module) def _lookup_attribute_by_type(self, r, attr_name): """Look up an attribute using pytype annotations.""" links = [] # For unclear reasons, we sometimes do not get two elements in r.data # See b/233390756 for an example. This handles the error gracefully, since # rhs is not used in most of this function. if not r.data: return [] elif len(r.data) == 1: lhs, rhs = r.data[0], None else: lhs, rhs = r.data for l in lhs: if self._is_pytype_module(l): lookup = [l] else: lookup = self._get_mro(l) for pytype_cls in lookup: cls = self._get_attribute_class(pytype_cls) if cls: if isinstance(cls, Definition): assert self.envs is not None env = self.envs[cls.id] _, attr_value = env.lookup(attr_name) if not attr_value and isinstance(l, abstract.Instance): try: attr_value = env.getattr(attr_name) except AttrError: # We will walk up the MRO if we can't find anything. continue if attr_value: links.append((r, attr_value)) break elif isinstance(cls, Module): # Probably extra-cautious about rhs not being a single binding, but # better to check than crash here. if len(rhs) == 1 and self._is_pytype_module(rhs[0]): # e.g. import x.y; a = x.y links.append((r, cls.submodule(attr_name))) else: links.append((r, cls.attr(attr_name))) break elif isinstance(cls, Remote): links.append((r, cls.attr(attr_name))) break return links def _lookup_refs(self): """Look up references to generate links.""" links = [] assert self.refs is not None for r in self.refs: if r.typ == "Attribute": attr_name = r.name.rsplit(".", 1)[-1] defs = self._lookup_attribute_by_type(r, attr_name) if defs: links.extend(defs) continue else: assert self.envs is not None env = self.envs[r.scope] env, defn = env.lookup(r.target) if defn: # See if this is a definition from an imported module first. remote = self._lookup_remote_symbol(defn, attr_name) if remote: links.append((r, remote)) else: # See if we can figure out the class of a bound attribute from the # typemap. typ = self.typemap.get(defn.id) if typ: for x in PytypeValue.from_data(typ): if x is None: continue # Not-yet-special-cased type, e.g. namedtuple. elif isinstance(x, Remote): links.append((r, x.attr(attr_name))) elif x.typ == "Class": d = self._lookup_class_attr(x.name, attr_name) if d: links.append((r, d)) else: # Fall back to <module>.<name> links.append((r, x)) else: links.append((r, x)) else: links.append((r, defn)) elif r.typ == "Import" or r.typ == "ImportFrom": [imported] = _unwrap(r.data) if isinstance(imported, abstract.Module): name = IMPORT_FILE_MARKER if r.name in self.resolved_modules: module = r.name else: module = imported.full_name else: assert imported.module name = r.name module = imported.module links.append((r, Remote(module, name=name, resolved=True))) else: try: assert self.envs is not None env, defn = self.envs[r.scope].lookup(r.name) except KeyError: env, defn = None, None if defn: links.append((r, defn)) else: data = PytypeValue.from_data(_unwrap(r.data)) if data: for x in data: links.append((r, x)) return links def get_pytd_def(self, data, name): assert self.vm, "Indexer vm has not been preserved." node = self.vm.ctx.root_node return self.vm.ctx.pytd_convert.value_to_pytd_def(node, data, name) def get_pytd(self, datum): if not datum: return pytd.AnythingType() t = pytd_utils.JoinTypes(v.to_pytd_type() for v in datum).Visit( visitors.RemoveUnknownClasses()) return self.loader.resolve_pytd(t, self.pytd_module) def make_serializable(self): """Delete all data that cannot be pickled.""" for r in self.refs: r.target = None r.data = None assert self.defs is not None for d in self.defs.values(): d.data = None for call in self.calls: call.return_type = None assert self.aliases is not None for a in self.aliases.values(): a.data = None for r, d in self.links: r.data = None d.data = None # This is all internal data used when building up the final index; if any of # it proves to be needed we can look at just stripping out the non-picklable # bits, or converting it to a final form in finalize() self.ast = None self.pytd_module = None self.source = None self.loader = None self.resolved_modules = None self.imports = None self.traces = None self.modules = None self.typemap = None self.classmap = None self.envs = None self.function_params = None self.calls = None
Indexer
python
spack__spack
lib/spack/spack/util/ctest_log_parser.py
{ "start": 7855, "end": 9498 }
class ____: """Class representing interesting events (e.g., errors) in a build log.""" def __init__( self, text, line_no, source_file=None, source_line_no=None, pre_context=None, post_context=None, ): self.text = text self.line_no = line_no self.source_file = (source_file,) self.source_line_no = (source_line_no,) self.pre_context = pre_context if pre_context is not None else [] self.post_context = post_context if post_context is not None else [] self.repeat_count = 0 @property def start(self): """First line in the log with text for the event or its context.""" return self.line_no - len(self.pre_context) @property def end(self): """Last line in the log with text for event or its context.""" return self.line_no + len(self.post_context) + 1 def __getitem__(self, line_no): """Index event text and context by actual line number in file.""" if line_no == self.line_no: return self.text elif line_no < self.line_no: return self.pre_context[line_no - self.line_no] elif line_no > self.line_no: return self.post_context[line_no - self.line_no - 1] def __str__(self): """Returns event lines and context.""" out = io.StringIO() for i in range(self.start, self.end): if i == self.line_no: out.write(" >> %-6d%s" % (i, self[i])) else: out.write(" %-6d%s" % (i, self[i])) return out.getvalue()
LogEvent
python
getsentry__sentry
src/sentry/workflow_engine/endpoints/organization_workflow_stats.py
{ "start": 1075, "end": 2163 }
class ____(OrganizationWorkflowEndpoint): publish_status = { "GET": ApiPublishStatus.EXPERIMENTAL, } owner = ApiOwner.ISSUES @extend_schema( operation_id="Retrieve Firing Stats for a Workflow for a Given Time Range.", parameters=[ GlobalParams.ORG_ID_OR_SLUG, WorkflowParams.WORKFLOW_ID, ], responses={ 200: TimeSeriesValueSerializer, 401: RESPONSE_UNAUTHORIZED, 403: RESPONSE_FORBIDDEN, 404: RESPONSE_NOT_FOUND, }, ) def get(self, request: Request, organization: Organization, workflow: Workflow) -> Response: """ Note that results are returned in hourly buckets. """ try: start, end = get_date_range_from_params(request.GET) except InvalidParams: raise ParseError(detail="Invalid date range") results = fetch_workflow_hourly_stats(workflow, start, end) return Response(serialize(results, request.user, TimeSeriesValueSerializer()))
OrganizationWorkflowStatsEndpoint
python
getsentry__sentry
tests/sentry/web/frontend/test_oauth_authorize.py
{ "start": 10174, "end": 14280 }
class ____(TestCase): @cached_property def path(self) -> str: return "/oauth/authorize/" def setUp(self) -> None: super().setUp() self.application = ApiApplication.objects.create( owner=self.user, redirect_uris="https://example.com" ) def test_missing_response_type(self) -> None: self.login_as(self.user) resp = self.client.get( f"{self.path}?redirect_uri=https://example.com&client_id={self.application.client_id}" ) assert resp.status_code == 400 self.assertTemplateUsed("sentry/oauth-error.html") assert resp.context["error"] == "Missing or invalid <em>client_id</em> parameter." def test_invalid_response_type(self) -> None: self.login_as(self.user) resp = self.client.get( f"{self.path}?response_type=foobar&redirect_uri=https://example.com&client_id={self.application.client_id}" ) assert resp.status_code == 400 self.assertTemplateUsed("sentry/oauth-error.html") assert resp.context["error"] == "Missing or invalid <em>client_id</em> parameter." def test_missing_client_id(self) -> None: self.login_as(self.user) resp = self.client.get(f"{self.path}?response_type=token&redirect_uri=https://example.com") assert resp.status_code == 400 self.assertTemplateUsed("sentry/oauth-error.html") assert resp.context["error"] == "Missing or invalid <em>client_id</em> parameter." def test_invalid_scope(self) -> None: self.login_as(self.user) resp = self.client.get( f"{self.path}?response_type=token&client_id={self.application.client_id}&scope=foo" ) assert resp.status_code == 302 assert resp["Location"] == "https://example.com#error=invalid_scope" assert "access_token" not in resp["Location"] assert not ApiToken.objects.filter(user=self.user).exists() def test_minimal_params_approve_flow(self) -> None: self.login_as(self.user) resp = self.client.get( f"{self.path}?response_type=token&client_id={self.application.client_id}" ) assert resp.status_code == 200 self.assertTemplateUsed("sentry/oauth-authorize.html") assert resp.context["application"] == self.application resp = self.client.post(self.path, {"op": "approve"}) assert not ApiGrant.objects.filter(user=self.user).exists() token = ApiToken.objects.get(user=self.user) assert token.application == self.application assert not token.get_scopes() assert not token.refresh_token assert resp.status_code == 302 location, fragment = resp["Location"].split("#", 1) assert location == "https://example.com" fragment_d = parse_qs(fragment) assert fragment_d["access_token"] == [token.token] assert fragment_d["token_type"] == ["Bearer"] assert "refresh_token" not in fragment_d # expires_in should be a positive integer number of seconds until expiry assert fragment_d["expires_in"] assert int(fragment_d["expires_in"][0]) > 0 assert fragment_d["token_type"] == ["Bearer"] def test_minimal_params_code_deny_flow(self) -> None: self.login_as(self.user) resp = self.client.get( f"{self.path}?response_type=token&client_id={self.application.client_id}" ) assert resp.status_code == 200 self.assertTemplateUsed("sentry/oauth-authorize.html") assert resp.context["application"] == self.application resp = self.client.post(self.path, {"op": "deny"}) assert resp.status_code == 302 location, fragment = resp["Location"].split("#", 1) assert location == "https://example.com" fragment_d = parse_qs(fragment) assert fragment_d == {"error": ["access_denied"]} assert "access_token" not in resp["Location"] assert not ApiToken.objects.filter(user=self.user).exists() @control_silo_test
OAuthAuthorizeTokenTest
python
giampaolo__psutil
tests/test_system.py
{ "start": 27129, "end": 33693 }
class ____(PsutilTestCase): @pytest.mark.skipif(not HAS_NET_IO_COUNTERS, reason="not supported") def test_net_io_counters(self): def check_ntuple(nt): assert nt[0] == nt.bytes_sent assert nt[1] == nt.bytes_recv assert nt[2] == nt.packets_sent assert nt[3] == nt.packets_recv assert nt[4] == nt.errin assert nt[5] == nt.errout assert nt[6] == nt.dropin assert nt[7] == nt.dropout assert nt.bytes_sent >= 0, nt assert nt.bytes_recv >= 0, nt assert nt.packets_sent >= 0, nt assert nt.packets_recv >= 0, nt assert nt.errin >= 0, nt assert nt.errout >= 0, nt assert nt.dropin >= 0, nt assert nt.dropout >= 0, nt ret = psutil.net_io_counters(pernic=False) check_ntuple(ret) ret = psutil.net_io_counters(pernic=True) assert ret != [] for key in ret: assert key assert isinstance(key, str) check_ntuple(ret[key]) @pytest.mark.skipif(not HAS_NET_IO_COUNTERS, reason="not supported") def test_net_io_counters_no_nics(self): # Emulate a case where no NICs are installed, see: # https://github.com/giampaolo/psutil/issues/1062 with mock.patch( 'psutil._psplatform.net_io_counters', return_value={} ) as m: assert psutil.net_io_counters(pernic=False) is None assert psutil.net_io_counters(pernic=True) == {} assert m.called def test_net_if_addrs(self): nics = psutil.net_if_addrs() assert nics, nics nic_stats = psutil.net_if_stats() # Not reliable on all platforms (net_if_addrs() reports more # interfaces). # assert sorted(nics.keys()) == sorted( # psutil.net_io_counters(pernic=True).keys() # ) families = {socket.AF_INET, socket.AF_INET6, psutil.AF_LINK} for nic, addrs in nics.items(): assert isinstance(nic, str) assert len(set(addrs)) == len(addrs) for addr in addrs: assert isinstance(addr.family, int) assert isinstance(addr.address, str) assert isinstance(addr.netmask, (str, type(None))) assert isinstance(addr.broadcast, (str, type(None))) assert addr.family in families assert isinstance(addr.family, enum.IntEnum) if nic_stats[nic].isup: # Do not test binding to addresses of interfaces # that are down if addr.family == socket.AF_INET: with socket.socket(addr.family) as s: s.bind((addr.address, 0)) elif addr.family == socket.AF_INET6: info = socket.getaddrinfo( addr.address, 0, socket.AF_INET6, socket.SOCK_STREAM, 0, socket.AI_PASSIVE, )[0] af, socktype, proto, _canonname, sa = info with socket.socket(af, socktype, proto) as s: s.bind(sa) for ip in ( addr.address, addr.netmask, addr.broadcast, addr.ptp, ): if ip is not None: # TODO: skip AF_INET6 for now because I get: # AddressValueError: Only hex digits permitted in # u'c6f3%lxcbr0' in u'fe80::c8e0:fff:fe54:c6f3%lxcbr0' if addr.family != socket.AF_INET6: check_net_address(ip, addr.family) # broadcast and ptp addresses are mutually exclusive if addr.broadcast: assert addr.ptp is None elif addr.ptp: assert addr.broadcast is None # check broadcast address if ( addr.broadcast and addr.netmask and addr.family in {socket.AF_INET, socket.AF_INET6} ): assert addr.broadcast == broadcast_addr(addr) if BSD or MACOS or SUNOS: if hasattr(socket, "AF_LINK"): assert psutil.AF_LINK == socket.AF_LINK elif LINUX: assert psutil.AF_LINK == socket.AF_PACKET elif WINDOWS: assert psutil.AF_LINK == -1 def test_net_if_addrs_mac_null_bytes(self): # Simulate that the underlying C function returns an incomplete # MAC address. psutil is supposed to fill it with null bytes. # https://github.com/giampaolo/psutil/issues/786 if POSIX: ret = [('em1', psutil.AF_LINK, '06:3d:29', None, None, None)] else: ret = [('em1', -1, '06-3d-29', None, None, None)] with mock.patch( 'psutil._psplatform.net_if_addrs', return_value=ret ) as m: addr = psutil.net_if_addrs()['em1'][0] assert m.called if POSIX: assert addr.address == '06:3d:29:00:00:00' else: assert addr.address == '06-3d-29-00-00-00' def test_net_if_stats(self): nics = psutil.net_if_stats() assert nics, nics all_duplexes = ( psutil.NIC_DUPLEX_FULL, psutil.NIC_DUPLEX_HALF, psutil.NIC_DUPLEX_UNKNOWN, ) for name, stats in nics.items(): assert isinstance(name, str) isup, duplex, speed, mtu, flags = stats assert isinstance(isup, bool) assert duplex in all_duplexes assert duplex in all_duplexes assert speed >= 0 assert mtu >= 0 assert isinstance(flags, str) @pytest.mark.skipif( not (LINUX or BSD or MACOS), reason="LINUX or BSD or MACOS specific" ) def test_net_if_stats_enodev(self): # See: https://github.com/giampaolo/psutil/issues/1279 with mock.patch( 'psutil._psplatform.cext.net_if_mtu', side_effect=OSError(errno.ENODEV, ""), ) as m: ret = psutil.net_if_stats() assert ret == {} assert m.called
TestNetAPIs
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/state.py
{ "start": 2904, "end": 34275 }
class ____(interfaces.InspectionAttrInfo, Generic[_O]): """Tracks state information at the instance level. The :class:`.InstanceState` is a key object used by the SQLAlchemy ORM in order to track the state of an object; it is created the moment an object is instantiated, typically as a result of :term:`instrumentation` which SQLAlchemy applies to the ``__init__()`` method of the class. :class:`.InstanceState` is also a semi-public object, available for runtime inspection as to the state of a mapped instance, including information such as its current status within a particular :class:`.Session` and details about data on individual attributes. The public API in order to acquire a :class:`.InstanceState` object is to use the :func:`_sa.inspect` system:: >>> from sqlalchemy import inspect >>> insp = inspect(some_mapped_object) >>> insp.attrs.nickname.history History(added=['new nickname'], unchanged=(), deleted=['nickname']) .. seealso:: :ref:`orm_mapper_inspection_instancestate` """ __slots__ = ( "__dict__", "__weakref__", "class_", "manager", "obj", "committed_state", "expired_attributes", ) manager: ClassManager[_O] session_id: Optional[int] = None key: Optional[_IdentityKeyType[_O]] = None runid: Optional[int] = None load_options: Tuple[ORMOption, ...] = () load_path: PathRegistry = PathRegistry.root insert_order: Optional[int] = None _strong_obj: Optional[object] = None obj: weakref.ref[_O] committed_state: Dict[str, Any] modified: bool = False """When ``True`` the object was modified.""" expired: bool = False """When ``True`` the object is :term:`expired`. .. seealso:: :ref:`session_expire` """ _deleted: bool = False _load_pending: bool = False _orphaned_outside_of_session: bool = False is_instance: bool = True identity_token: object = None _last_known_values: Optional[Dict[str, Any]] = None _instance_dict: _InstanceDictProto """A weak reference, or in the default case a plain callable, that returns a reference to the current :class:`.IdentityMap`, if any. """ if not TYPE_CHECKING: def _instance_dict(self): """default 'weak reference' for _instance_dict""" return None expired_attributes: Set[str] """The set of keys which are 'expired' to be loaded by the manager's deferred scalar loader, assuming no pending changes. See also the ``unmodified`` collection which is intersected against this set when a refresh operation occurs. """ callables: Dict[str, Callable[[InstanceState[_O], PassiveFlag], Any]] """A namespace where a per-state loader callable can be associated. In SQLAlchemy 1.0, this is only used for lazy loaders / deferred loaders that were set up via query option. Previously, callables was used also to indicate expired attributes by storing a link to the InstanceState itself in this dictionary. This role is now handled by the expired_attributes set. """ if not TYPE_CHECKING: callables = util.EMPTY_DICT def __init__(self, obj: _O, manager: ClassManager[_O]): self.class_ = obj.__class__ self.manager = manager self.obj = weakref.ref(obj, self._cleanup) self.committed_state = {} self.expired_attributes = set() @util.memoized_property def attrs(self) -> util.ReadOnlyProperties[AttributeState]: """Return a namespace representing each attribute on the mapped object, including its current value and history. The returned object is an instance of :class:`.AttributeState`. This object allows inspection of the current data within an attribute as well as attribute history since the last flush. """ return util.ReadOnlyProperties( {key: AttributeState(self, key) for key in self.manager} ) @property def transient(self) -> bool: """Return ``True`` if the object is :term:`transient`. .. seealso:: :ref:`session_object_states` """ return self.key is None and not self._attached @property def pending(self) -> bool: """Return ``True`` if the object is :term:`pending`. .. seealso:: :ref:`session_object_states` """ return self.key is None and self._attached @property def deleted(self) -> bool: """Return ``True`` if the object is :term:`deleted`. An object that is in the deleted state is guaranteed to not be within the :attr:`.Session.identity_map` of its parent :class:`.Session`; however if the session's transaction is rolled back, the object will be restored to the persistent state and the identity map. .. note:: The :attr:`.InstanceState.deleted` attribute refers to a specific state of the object that occurs between the "persistent" and "detached" states; once the object is :term:`detached`, the :attr:`.InstanceState.deleted` attribute **no longer returns True**; in order to detect that a state was deleted, regardless of whether or not the object is associated with a :class:`.Session`, use the :attr:`.InstanceState.was_deleted` accessor. .. seealso:: :ref:`session_object_states` """ return self.key is not None and self._attached and self._deleted @property def was_deleted(self) -> bool: """Return True if this object is or was previously in the "deleted" state and has not been reverted to persistent. This flag returns True once the object was deleted in flush. When the object is expunged from the session either explicitly or via transaction commit and enters the "detached" state, this flag will continue to report True. .. seealso:: :attr:`.InstanceState.deleted` - refers to the "deleted" state :func:`.orm.util.was_deleted` - standalone function :ref:`session_object_states` """ return self._deleted @property def persistent(self) -> bool: """Return ``True`` if the object is :term:`persistent`. An object that is in the persistent state is guaranteed to be within the :attr:`.Session.identity_map` of its parent :class:`.Session`. .. seealso:: :ref:`session_object_states` """ return self.key is not None and self._attached and not self._deleted @property def detached(self) -> bool: """Return ``True`` if the object is :term:`detached`. .. seealso:: :ref:`session_object_states` """ return self.key is not None and not self._attached @util.non_memoized_property @util.preload_module("sqlalchemy.orm.session") def _attached(self) -> bool: return ( self.session_id is not None and self.session_id in util.preloaded.orm_session._sessions ) def _track_last_known_value(self, key: str) -> None: """Track the last known value of a particular key after expiration operations. """ lkv = self._last_known_values if lkv is None: self._last_known_values = lkv = {} if key not in lkv: lkv[key] = NO_VALUE @property def session(self) -> Optional[Session]: """Return the owning :class:`.Session` for this instance, or ``None`` if none available. Note that the result here can in some cases be *different* from that of ``obj in session``; an object that's been deleted will report as not ``in session``, however if the transaction is still in progress, this attribute will still refer to that session. Only when the transaction is completed does the object become fully detached under normal circumstances. .. seealso:: :attr:`_orm.InstanceState.async_session` """ if self.session_id: try: return _sessions[self.session_id] except KeyError: pass return None @property def async_session(self) -> Optional[AsyncSession]: """Return the owning :class:`_asyncio.AsyncSession` for this instance, or ``None`` if none available. This attribute is only non-None when the :mod:`sqlalchemy.ext.asyncio` API is in use for this ORM object. The returned :class:`_asyncio.AsyncSession` object will be a proxy for the :class:`_orm.Session` object that would be returned from the :attr:`_orm.InstanceState.session` attribute for this :class:`_orm.InstanceState`. .. versionadded:: 1.4.18 .. seealso:: :ref:`asyncio_toplevel` """ if _async_provider is None: return None sess = self.session if sess is not None: return _async_provider(sess) else: return None @property def object(self) -> Optional[_O]: """Return the mapped object represented by this :class:`.InstanceState`. Returns None if the object has been garbage collected """ return self.obj() @property def identity(self) -> Optional[Tuple[Any, ...]]: """Return the mapped identity of the mapped object. This is the primary key identity as persisted by the ORM which can always be passed directly to :meth:`_query.Query.get`. Returns ``None`` if the object has no primary key identity. .. note:: An object which is :term:`transient` or :term:`pending` does **not** have a mapped identity until it is flushed, even if its attributes include primary key values. """ if self.key is None: return None else: return self.key[1] @property def identity_key(self) -> Optional[_IdentityKeyType[_O]]: """Return the identity key for the mapped object. This is the key used to locate the object within the :attr:`.Session.identity_map` mapping. It contains the identity as returned by :attr:`.identity` within it. """ return self.key @util.memoized_property def parents(self) -> Dict[int, Union[Literal[False], InstanceState[Any]]]: return {} @util.memoized_property def _pending_mutations(self) -> Dict[str, PendingCollection]: return {} @util.memoized_property def _empty_collections(self) -> Dict[str, _AdaptedCollectionProtocol]: return {} @util.memoized_property def mapper(self) -> Mapper[_O]: """Return the :class:`_orm.Mapper` used for this mapped object.""" return self.manager.mapper @property def has_identity(self) -> bool: """Return ``True`` if this object has an identity key. This should always have the same value as the expression ``state.persistent`` or ``state.detached``. """ return bool(self.key) @classmethod def _detach_states( self, states: Iterable[InstanceState[_O]], session: Session, to_transient: bool = False, ) -> None: persistent_to_detached = ( session.dispatch.persistent_to_detached or None ) deleted_to_detached = session.dispatch.deleted_to_detached or None pending_to_transient = session.dispatch.pending_to_transient or None persistent_to_transient = ( session.dispatch.persistent_to_transient or None ) for state in states: deleted = state._deleted pending = state.key is None persistent = not pending and not deleted state.session_id = None if to_transient and state.key: del state.key if persistent: if to_transient: if persistent_to_transient is not None: persistent_to_transient(session, state) elif persistent_to_detached is not None: persistent_to_detached(session, state) elif deleted and deleted_to_detached is not None: deleted_to_detached(session, state) elif pending and pending_to_transient is not None: pending_to_transient(session, state) state._strong_obj = None def _detach(self, session: Optional[Session] = None) -> None: if session: InstanceState._detach_states([self], session) else: self.session_id = self._strong_obj = None def _dispose(self) -> None: # used by the test suite, apparently self._detach() def _force_dereference(self) -> None: """Force this InstanceState to act as though its weakref has been GC'ed. this is used for test code that has to test reactions to objects being GC'ed. We can't reliably force GCs to happen under all CI circumstances. """ # if _strong_obj is set, then our object would not be getting # GC'ed (at least within the scope of what we use this for in tests). # so make sure this is not set assert self._strong_obj is None obj = self.obj() if obj is None: # object was GC'ed and we're done! woop return del obj self._cleanup(self.obj) self.obj = lambda: None # type: ignore def _cleanup(self, ref: weakref.ref[_O]) -> None: """Weakref callback cleanup. This callable cleans out the state when it is being garbage collected. this _cleanup **assumes** that there are no strong refs to us! Will not work otherwise! """ # Python builtins become undefined during interpreter shutdown. # Guard against exceptions during this phase, as the method cannot # proceed in any case if builtins have been undefined. if dict is None: return instance_dict = self._instance_dict() if instance_dict is not None: instance_dict._fast_discard(self) del self._instance_dict # we can't possibly be in instance_dict._modified # b.c. this is weakref cleanup only, that set # is strong referencing! # assert self not in instance_dict._modified self.session_id = self._strong_obj = None @property def dict(self) -> _InstanceDict: """Return the instance dict used by the object. Under normal circumstances, this is always synonymous with the ``__dict__`` attribute of the mapped object, unless an alternative instrumentation system has been configured. In the case that the actual object has been garbage collected, this accessor returns a blank dictionary. """ o = self.obj() if o is not None: return base.instance_dict(o) else: return {} def _initialize_instance(*mixed: Any, **kwargs: Any) -> None: self, instance, args = mixed[0], mixed[1], mixed[2:] # noqa manager = self.manager manager.dispatch.init(self, args, kwargs) try: manager.original_init(*mixed[1:], **kwargs) except: with util.safe_reraise(): manager.dispatch.init_failure(self, args, kwargs) def get_history(self, key: str, passive: PassiveFlag) -> History: return self.manager[key].impl.get_history(self, self.dict, passive) def get_impl(self, key: str) -> _AttributeImpl: return self.manager[key].impl def _get_pending_mutation(self, key: str) -> PendingCollection: if key not in self._pending_mutations: self._pending_mutations[key] = PendingCollection() return self._pending_mutations[key] def __getstate__(self) -> Dict[str, Any]: state_dict: Dict[str, Any] = { "instance": self.obj(), "class_": self.class_, "committed_state": self.committed_state, "expired_attributes": self.expired_attributes, } state_dict.update( (k, self.__dict__[k]) for k in ( "_pending_mutations", "modified", "expired", "callables", "key", "parents", "load_options", "class_", "expired_attributes", "info", ) if k in self.__dict__ ) if self.load_path: state_dict["load_path"] = self.load_path.serialize() state_dict["manager"] = self.manager._serialize(self, state_dict) return state_dict def __setstate__(self, state_dict: Dict[str, Any]) -> None: inst = state_dict["instance"] if inst is not None: self.obj = weakref.ref(inst, self._cleanup) self.class_ = inst.__class__ else: self.obj = lambda: None # type: ignore self.class_ = state_dict["class_"] self.committed_state = state_dict.get("committed_state", {}) self._pending_mutations = state_dict.get("_pending_mutations", {}) self.parents = state_dict.get("parents", {}) self.modified = state_dict.get("modified", False) self.expired = state_dict.get("expired", False) if "info" in state_dict: self.info.update(state_dict["info"]) if "callables" in state_dict: self.callables = state_dict["callables"] self.expired_attributes = state_dict["expired_attributes"] else: if "expired_attributes" in state_dict: self.expired_attributes = state_dict["expired_attributes"] else: self.expired_attributes = set() self.__dict__.update( [ (k, state_dict[k]) for k in ("key", "load_options") if k in state_dict ] ) if self.key: self.identity_token = self.key[2] if "load_path" in state_dict: self.load_path = PathRegistry.deserialize(state_dict["load_path"]) state_dict["manager"](self, inst, state_dict) def _reset(self, dict_: _InstanceDict, key: str) -> None: """Remove the given attribute and any callables associated with it.""" old = dict_.pop(key, None) manager_impl = self.manager[key].impl if old is not None and is_collection_impl(manager_impl): manager_impl._invalidate_collection(old) self.expired_attributes.discard(key) if self.callables: self.callables.pop(key, None) def _copy_callables(self, from_: InstanceState[Any]) -> None: if "callables" in from_.__dict__: self.callables = dict(from_.callables) @classmethod def _instance_level_callable_processor( cls, manager: ClassManager[_O], fn: _LoaderCallable, key: Any ) -> _InstallLoaderCallableProto[_O]: impl = manager[key].impl if is_collection_impl(impl): fixed_impl = impl def _set_callable( state: InstanceState[_O], dict_: _InstanceDict, row: Row[Unpack[TupleAny]], ) -> None: if "callables" not in state.__dict__: state.callables = {} old = dict_.pop(key, None) if old is not None: fixed_impl._invalidate_collection(old) state.callables[key] = fn else: def _set_callable( state: InstanceState[_O], dict_: _InstanceDict, row: Row[Unpack[TupleAny]], ) -> None: if "callables" not in state.__dict__: state.callables = {} state.callables[key] = fn return _set_callable def _expire( self, dict_: _InstanceDict, modified_set: Set[InstanceState[Any]] ) -> None: self.expired = True if self.modified: modified_set.discard(self) self.committed_state.clear() self.modified = False self._strong_obj = None if "_pending_mutations" in self.__dict__: del self.__dict__["_pending_mutations"] if "parents" in self.__dict__: del self.__dict__["parents"] self.expired_attributes.update( [impl.key for impl in self.manager._loader_impls] ) if self.callables: # the per state loader callables we can remove here are # LoadDeferredColumns, which undefers a column at the instance # level that is mapped with deferred, and LoadLazyAttribute, # which lazy loads a relationship at the instance level that # is mapped with "noload" or perhaps "immediateload". # Before 1.4, only column-based # attributes could be considered to be "expired", so here they # were the only ones "unexpired", which means to make them deferred # again. For the moment, as of 1.4 we also apply the same # treatment relationships now, that is, an instance level lazy # loader is reset in the same way as a column loader. for k in self.expired_attributes.intersection(self.callables): del self.callables[k] for k in self.manager._collection_impl_keys.intersection(dict_): collection = dict_.pop(k) collection._sa_adapter.invalidated = True if self._last_known_values: self._last_known_values.update( {k: dict_[k] for k in self._last_known_values if k in dict_} ) for key in self.manager._all_key_set.intersection(dict_): del dict_[key] self.manager.dispatch.expire(self, None) def _expire_attributes( self, dict_: _InstanceDict, attribute_names: Iterable[str], no_loader: bool = False, ) -> None: pending = self.__dict__.get("_pending_mutations", None) callables = self.callables for key in attribute_names: impl = self.manager[key].impl if impl.accepts_scalar_loader: if no_loader and (impl.callable_ or key in callables): continue self.expired_attributes.add(key) if callables and key in callables: del callables[key] old = dict_.pop(key, NO_VALUE) if is_collection_impl(impl) and old is not NO_VALUE: impl._invalidate_collection(old) lkv = self._last_known_values if lkv is not None and key in lkv and old is not NO_VALUE: lkv[key] = old self.committed_state.pop(key, None) if pending: pending.pop(key, None) self.manager.dispatch.expire(self, attribute_names) def _load_expired( self, state: InstanceState[_O], passive: PassiveFlag ) -> LoaderCallableStatus: """__call__ allows the InstanceState to act as a deferred callable for loading expired attributes, which is also serializable (picklable). """ if not passive & SQL_OK: return PASSIVE_NO_RESULT toload = self.expired_attributes.intersection(self.unmodified) toload = toload.difference( attr for attr in toload if not self.manager[attr].impl.load_on_unexpire ) self.manager.expired_attribute_loader(self, toload, passive) # if the loader failed, or this # instance state didn't have an identity, # the attributes still might be in the callables # dict. ensure they are removed. self.expired_attributes.clear() return ATTR_WAS_SET @property def unmodified(self) -> Set[str]: """Return the set of keys which have no uncommitted changes""" return set(self.manager).difference(self.committed_state) def unmodified_intersection(self, keys: Iterable[str]) -> Set[str]: """Return self.unmodified.intersection(keys).""" return ( set(keys) .intersection(self.manager) .difference(self.committed_state) ) @property def unloaded(self) -> Set[str]: """Return the set of keys which do not have a loaded value. This includes expired attributes and any other attribute that was never populated or modified. """ return ( set(self.manager) .difference(self.committed_state) .difference(self.dict) ) @property @util.deprecated( "2.0", "The :attr:`.InstanceState.unloaded_expirable` attribute is " "deprecated. Please use :attr:`.InstanceState.unloaded`.", ) def unloaded_expirable(self) -> Set[str]: """Synonymous with :attr:`.InstanceState.unloaded`. This attribute was added as an implementation-specific detail at some point and should be considered to be private. """ return self.unloaded @property def _unloaded_non_object(self) -> Set[str]: return self.unloaded.intersection( attr for attr in self.manager if self.manager[attr].impl.accepts_scalar_loader ) def _modified_event( self, dict_: _InstanceDict, attr: Optional[_AttributeImpl], previous: Any, collection: bool = False, is_userland: bool = False, ) -> None: if attr: if not attr.send_modified_events: return if is_userland and attr.key not in dict_: raise sa_exc.InvalidRequestError( "Can't flag attribute '%s' modified; it's not present in " "the object state" % attr.key ) if attr.key not in self.committed_state or is_userland: if collection: if TYPE_CHECKING: assert is_collection_impl(attr) if previous is NEVER_SET: if attr.key in dict_: previous = dict_[attr.key] if previous not in (None, NO_VALUE, NEVER_SET): previous = attr.copy(previous) self.committed_state[attr.key] = previous lkv = self._last_known_values if lkv is not None and attr.key in lkv: lkv[attr.key] = NO_VALUE # assert self._strong_obj is None or self.modified if (self.session_id and self._strong_obj is None) or not self.modified: self.modified = True instance_dict = self._instance_dict() if instance_dict: has_modified = bool(instance_dict._modified) instance_dict._modified.add(self) else: has_modified = False # only create _strong_obj link if attached # to a session inst = self.obj() if self.session_id: self._strong_obj = inst # if identity map already had modified objects, # assume autobegin already occurred, else check # for autobegin if not has_modified: # inline of autobegin, to ensure session transaction # snapshot is established try: session = _sessions[self.session_id] except KeyError: pass else: if session._transaction is None: session._autobegin_t() if inst is None and attr: raise orm_exc.ObjectDereferencedError( "Can't emit change event for attribute '%s' - " "parent object of type %s has been garbage " "collected." % (self.manager[attr.key], base.state_class_str(self)) ) def _commit(self, dict_: _InstanceDict, keys: Iterable[str]) -> None: """Commit attributes. This is used by a partial-attribute load operation to mark committed those attributes which were refreshed from the database. Attributes marked as "expired" can potentially remain "expired" after this step if a value was not populated in state.dict. """ for key in keys: self.committed_state.pop(key, None) self.expired = False self.expired_attributes.difference_update( set(keys).intersection(dict_) ) # the per-keys commit removes object-level callables, # while that of commit_all does not. it's not clear # if this behavior has a clear rationale, however tests do # ensure this is what it does. if self.callables: for key in ( set(self.callables).intersection(keys).intersection(dict_) ): del self.callables[key] def _commit_all( self, dict_: _InstanceDict, instance_dict: Optional[IdentityMap] = None, ) -> None: """commit all attributes unconditionally. This is used after a flush() or a full load/refresh to remove all pending state from the instance. - all attributes are marked as "committed" - the "strong dirty reference" is removed - the "modified" flag is set to False - any "expired" markers for scalar attributes loaded are removed. - lazy load callables for objects / collections *stay* Attributes marked as "expired" can potentially remain "expired" after this step if a value was not populated in state.dict. """ self._commit_all_states([(self, dict_)], instance_dict) @classmethod def _commit_all_states( self, iter_: Iterable[Tuple[InstanceState[Any], _InstanceDict]], instance_dict: Optional[IdentityMap] = None, ) -> None: """Mass / highly inlined version of commit_all().""" for state, dict_ in iter_: state_dict = state.__dict__ state.committed_state.clear() if "_pending_mutations" in state_dict: del state_dict["_pending_mutations"] state.expired_attributes.difference_update(dict_) if instance_dict and state.modified: instance_dict._modified.discard(state) state.modified = state.expired = False state._strong_obj = None
InstanceState
python
apache__airflow
airflow-ctl/src/airflowctl/api/operations.py
{ "start": 20911, "end": 21922 }
class ____(BaseOperations): """Dag run operations.""" def get(self, dag_id: str, dag_run_id: str) -> DAGRunResponse | ServerResponseError: """Get a dag run.""" try: self.response = self.client.get(f"/dags/{dag_id}/dagRuns/{dag_run_id}") return DAGRunResponse.model_validate_json(self.response.content) except ServerResponseError as e: raise e def list( self, dag_id: str, start_date: datetime.datetime, end_date: datetime.datetime, state: str, limit: int, ) -> DAGRunCollectionResponse | ServerResponseError: """List all dag runs.""" params = { "start_date": start_date, "end_date": end_date, "state": state, "limit": limit, "dag_id": dag_id, } return super().execute_list( path=f"/dags/{dag_id}/dagRuns", data_model=DAGRunCollectionResponse, params=params )
DagRunOperations
python
pytorch__pytorch
functorch/dim/__init__.py
{ "start": 12193, "end": 12735 }
class ____(Exception): pass from . import op_properties def _safe_print(*args: Any, **kwargs: Any) -> None: """Safe print that avoids recursive torch function dispatches.""" import sys # Convert any torch objects to basic representations safe_args = [] for arg in args: if hasattr(arg, "__class__") and "torch" in str(type(arg)): safe_args.append(f"<{type(arg).__name__}>") else: safe_args.append(str(arg)) print(*safe_args, **kwargs, file=sys.stderr)
DimensionBindError
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/plan/plan.py
{ "start": 3047, "end": 25131 }
class ____: """This is the state that is built up during the execution plan build process.""" def __init__( self, job_def: JobDefinition, resolved_run_config: ResolvedRunConfig, step_keys_to_execute: Optional[Sequence[str]], known_state: KnownExecutionState, instance_ref: Optional[InstanceRef], tags: Mapping[str, str], repository_load_data: Optional[RepositoryLoadData], ): self.job_def = check.inst_param(job_def, "job", JobDefinition) self.resolved_run_config = check.inst_param( resolved_run_config, "resolved_run_config", ResolvedRunConfig ) self.step_keys_to_execute = check.opt_nullable_sequence_param( step_keys_to_execute, "step_keys_to_execute", str ) self.known_state = check.inst_param(known_state, "known_state", KnownExecutionState) self._instance_ref = instance_ref self._tags = check.mapping_param(tags, "tags", key_type=str, value_type=str) self.repository_load_data = check.opt_inst_param( repository_load_data, "repository_load_data", RepositoryLoadData ) self._steps: dict[str, IExecutionStep] = {} self.step_output_map: dict[ NodeOutput, Union[StepOutputHandle, UnresolvedStepOutputHandle] ] = {} self._seen_handles: set[StepHandleUnion] = set() def add_step(self, step: IExecutionStep) -> None: # Keep track of the step keys we've seen so far to ensure we don't add duplicates if step.handle in self._seen_handles: keys = list(self._steps.keys()) check.failed(f"Duplicated key {step.key}. Full list seen so far: {keys}.") self._seen_handles.add(step.handle) self._steps[str(step.node_handle)] = step def get_step_by_node_handle(self, handle: NodeHandle) -> IExecutionStep: check.inst_param(handle, "handle", NodeHandle) return self._steps[str(handle)] def build(self) -> "ExecutionPlan": """Builds the execution plan.""" _check_persistent_storage_requirement( self.job_def, self.resolved_run_config, ) root_inputs: list[ Union[StepInput, UnresolvedMappedStepInput, UnresolvedCollectStepInput] ] = [] # Recursively build the execution plan starting at the root pipeline for input_def in self.job_def.graph.input_defs: input_name = input_def.name input_source = self.get_root_graph_input_source( job_def=self.job_def, input_name=input_name, input_def=input_def, ) # If an input with dagster_type "Nothing" doesn't have a value # we don't create a StepInput if input_source is None: continue root_inputs.append( StepInput( name=input_name, dagster_type_key=input_def.dagster_type.key, source=input_source, ) ) self._build_from_sorted_nodes( self.job_def.nodes_in_topological_order, self.job_def.dependency_structure, parent_step_inputs=root_inputs, ) step_dict = {step.handle: step for step in self._steps.values()} step_dict_by_key = {step.key: step for step in self._steps.values()} step_handles_to_execute = [step.handle for step in self._steps.values()] executable_map, resolvable_map = _compute_step_maps( step_dict, step_dict_by_key, step_handles_to_execute, self.known_state, ) executor_name = self.resolved_run_config.execution.execution_engine_name plan = ExecutionPlan( step_dict, executable_map, resolvable_map, step_handles_to_execute, self.known_state, _compute_artifacts_persisted( step_dict, step_dict_by_key, step_handles_to_execute, self.job_def, self.resolved_run_config, executable_map, ), executor_name=executor_name, repository_load_data=self.repository_load_data, ) if ( self.step_keys_to_execute is not None # no need to subset if plan already matches request and self.step_keys_to_execute != plan.step_keys_to_execute ): plan = plan.build_subset_plan( self.step_keys_to_execute, self.job_def, self.resolved_run_config ) return plan def _build_from_sorted_nodes( self, nodes: Sequence[Node], dependency_structure: DependencyStructure, parent_handle: Optional[NodeHandle] = None, parent_step_inputs: Optional[Sequence[StepInputUnion]] = None, ) -> None: asset_layer = self.job_def.asset_layer step_output_map: dict[NodeOutput, Union[StepOutputHandle, UnresolvedStepOutputHandle]] = {} for node in nodes: handle = NodeHandle(node.name, parent_handle) ### 1. INPUTS # Create and add execution plan steps for node inputs has_unresolved_input = False has_pending_input = False step_inputs: list[StepInputUnion] = [] for input_name, input_def in node.definition.input_dict.items(): step_input_source = get_step_input_source( self.job_def, node, input_name, input_def, dependency_structure, handle, self.resolved_run_config.ops.get(str(handle)), step_output_map, parent_step_inputs, ) # If an input with dagster_type "Nothing" doesn't have a value # we don't create a StepInput if step_input_source is None: continue if isinstance( step_input_source, (FromPendingDynamicStepOutput, FromUnresolvedStepOutput), ): has_unresolved_input = True step_inputs.append( UnresolvedMappedStepInput( name=input_name, dagster_type_key=input_def.dagster_type.key, source=step_input_source, ) ) elif isinstance(step_input_source, FromDynamicCollect): has_pending_input = True step_inputs.append( UnresolvedCollectStepInput( name=input_name, dagster_type_key=input_def.dagster_type.key, source=step_input_source, ) ) else: check.inst_param( step_input_source, "step_input_source", StepInputSource, ) step_inputs.append( StepInput( name=input_name, dagster_type_key=input_def.dagster_type.key, source=step_input_source, ) ) ### 2a. COMPUTE FUNCTION # Create and add execution plan step for the op compute function if isinstance(node.definition, OpDefinition): step_outputs = create_step_outputs( node, handle, self.resolved_run_config, asset_layer ) if has_pending_input and has_unresolved_input: check.failed("Can not have pending and unresolved step inputs") elif has_unresolved_input: new_step = UnresolvedMappedExecutionStep( handle=UnresolvedStepHandle(node_handle=handle), job_name=self.job_def.name, step_inputs=cast( "list[Union[StepInput, UnresolvedMappedStepInput]]", step_inputs ), step_outputs=step_outputs, tags=node.tags, pool=node.definition.pool, ) elif has_pending_input: new_step = UnresolvedCollectExecutionStep( handle=StepHandle(node_handle=handle), job_name=self.job_def.name, step_inputs=cast( "list[Union[StepInput, UnresolvedCollectStepInput]]", step_inputs ), step_outputs=step_outputs, tags=node.tags, pool=node.definition.pool, ) else: new_step = ExecutionStep( handle=StepHandle(node_handle=handle), job_name=self.job_def.name, step_inputs=cast("list[StepInput]", step_inputs), step_outputs=step_outputs, tags=node.tags, pool=node.definition.pool, ) self.add_step(new_step) ### 2b. RECURSE # Recurse over the nodes contained in an instance of GraphDefinition elif isinstance(node.definition, GraphDefinition): self._build_from_sorted_nodes( node.definition.nodes_in_topological_order, node.definition.dependency_structure, parent_handle=handle, parent_step_inputs=step_inputs, ) else: check.invariant( False, f"Unexpected node type {type(node.definition)} encountered during execution" " planning", ) ### 3. OUTPUTS # Create output handles for node outputs for name, output_def in node.definition.output_dict.items(): node_output = node.get_output(name) # Punch through layers of composition scope to map to the output of the # actual compute step resolved_output_def, resolved_handle = node.definition.resolve_output_to_origin( output_def.name, handle ) step = self.get_step_by_node_handle(check.not_none(resolved_handle)) if isinstance(step, (ExecutionStep, UnresolvedCollectExecutionStep)): step_output_handle: Union[StepOutputHandle, UnresolvedStepOutputHandle] = ( StepOutputHandle(step.key, resolved_output_def.name) ) elif isinstance(step, UnresolvedMappedExecutionStep): step_output_handle = UnresolvedStepOutputHandle( step.handle, resolved_output_def.name, step.resolved_by_step_key, step.resolved_by_output_name, ) else: check.failed(f"Unexpected step type {step}") step_output_map[node_output] = step_output_handle def get_root_graph_input_source( self, input_name: str, input_def: InputDefinition, job_def: JobDefinition, ) -> Optional[Union[FromConfig, FromDirectInputValue]]: input_values = job_def.input_values if input_values and input_name in input_values: return FromDirectInputValue(input_name=input_name) input_config = self.resolved_run_config.inputs if input_config and input_name in input_config: return FromConfig(input_name=input_name, node_handle=None) if input_def.dagster_type.is_nothing: return None if job_def.graph.input_has_default(input_name): return None # Otherwise we throw an error. raise DagsterInvariantViolationError( f"In top-level graph of {self.job_def.describe_target()}, input {input_name} " "must get a value from the inputs section of its configuration." ) def get_step_input_source( job_def: JobDefinition, node: Node, input_name: str, input_def: InputDefinition, dependency_structure: DependencyStructure, handle: NodeHandle, node_config: Any, step_output_map: dict[NodeOutput, Union[StepOutputHandle, UnresolvedStepOutputHandle]], parent_step_inputs: Optional[Sequence[StepInputUnion]], ) -> Optional[StepInputSourceUnion]: input_handle = node.get_input(input_name) input_def = node.definition.input_def_named(input_name) asset_layer = job_def.asset_layer if ( # input is unconnected inside the current dependency structure not dependency_structure.has_deps(input_handle) and # make sure input is unconnected in the outer dependency structure too not node.container_maps_input(input_handle.input_name) ): # can only load from source asset if assets defs are available if asset_layer.get_asset_key_for_node_input(handle, input_handle.input_name): return FromLoadableAsset() elif input_def.input_manager_key: return FromInputManager(node_handle=handle, input_name=input_name) if dependency_structure.has_direct_dep(input_handle): node_output_handle = dependency_structure.get_direct_dep(input_handle) step_output_handle = step_output_map[node_output_handle] if isinstance(step_output_handle, UnresolvedStepOutputHandle): return FromUnresolvedStepOutput( unresolved_step_output_handle=step_output_handle, ) if node_output_handle.output_def.is_dynamic: return FromPendingDynamicStepOutput( step_output_handle=step_output_handle, ) return FromStepOutput( step_output_handle=step_output_handle, fan_in=False, ) if dependency_structure.has_fan_in_deps(input_handle): dep_def = dependency_structure.get_dependency_definition(input_handle) if isinstance(dep_def, MultiDependencyDefinition): return _step_input_source_from_multi_dep_def( dependency_structure=dependency_structure, input_handle=input_handle, step_output_map=step_output_map, parent_step_inputs=parent_step_inputs, node=node, input_name=input_name, ) elif isinstance(dep_def, BlockingAssetChecksDependencyDefinition): return _step_input_source_from_blocking_asset_checks_dep_def( dep_def=dep_def, node_handle=handle, dependency_structure=dependency_structure, input_handle=input_handle, step_output_map=step_output_map, parent_step_inputs=parent_step_inputs, input_name=input_name, asset_layer=asset_layer, ) else: check.failed( "Expected fan-in deps to correspond to a MultiDependencyDefinition or" f" BlockingAssetChecksDependencyDefinition, but was {type(dep_def)}" ) if dependency_structure.has_dynamic_fan_in_dep(input_handle): node_output_handle = dependency_structure.get_dynamic_fan_in_dep(input_handle) step_output_handle = step_output_map[node_output_handle] if isinstance(step_output_handle, UnresolvedStepOutputHandle): return FromDynamicCollect( source=FromUnresolvedStepOutput( unresolved_step_output_handle=step_output_handle, ), ) elif node_output_handle.output_def.is_dynamic: return FromDynamicCollect( source=FromPendingDynamicStepOutput( step_output_handle=step_output_handle, ), ) if node_config and input_name in node_config.inputs: return FromConfig(node_handle=handle, input_name=input_name) if node.container_maps_input(input_name): if parent_step_inputs is None: check.failed("unexpected error in composition descent during plan building") parent_name = node.container_mapped_input(input_name).graph_input_name parent_inputs = {step_input.name: step_input for step_input in parent_step_inputs} if parent_name in parent_inputs: parent_input = parent_inputs[parent_name] return parent_input.source # else fall through to Nothing case or raise if node.definition.input_has_default(input_name): return FromDefaultValue(node_handle=handle, input_name=input_name) # At this point we have an input that is not hooked up to # the output of another op or provided via run config. # We will allow this for "Nothing" type inputs and continue. if input_def.dagster_type.is_nothing: return None # Otherwise we throw an error. raise DagsterInvariantViolationError( f"In {job_def.describe_target()} {node.describe_node()}, input {input_name} " "must get a value either (a) from a dependency or (b) from the " "inputs section of its configuration." ) def _step_input_source_from_multi_dep_def( dependency_structure: DependencyStructure, input_handle: NodeInput, step_output_map: dict[NodeOutput, Union[StepOutputHandle, UnresolvedStepOutputHandle]], parent_step_inputs: Optional[Sequence[StepInputUnion]], node: Node, input_name: str, ) -> FromMultipleSources: sources: list[StepInputSource] = [] deps = dependency_structure.get_fan_in_deps(input_handle) for idx, handle_or_placeholder in enumerate(deps): if isinstance(handle_or_placeholder, NodeOutput): step_output_handle = step_output_map[handle_or_placeholder] if ( isinstance(step_output_handle, UnresolvedStepOutputHandle) or handle_or_placeholder.output_def.is_dynamic ): check.failed( "Unexpected dynamic output dependency in regular fan in, " "should have been caught at definition time." ) sources.append( FromStepOutput( step_output_handle=step_output_handle, fan_in=True, ) ) else: check.invariant( handle_or_placeholder is MappedInputPlaceholder, f"Expected NodeOutput or MappedInputPlaceholder, got {handle_or_placeholder}", ) if parent_step_inputs is None: check.failed("unexpected error in composition descent during plan building") parent_name = node.container_mapped_fan_in_input(input_name, idx).graph_input_name parent_inputs = {step_input.name: step_input for step_input in parent_step_inputs} parent_input = parent_inputs[parent_name] source = parent_input.source if not isinstance(source, StepInputSource): check.failed(f"Unexpected parent mapped input source type {source}") sources.append(source) return FromMultipleSources(sources=sources) def _step_input_source_from_blocking_asset_checks_dep_def( dep_def: BlockingAssetChecksDependencyDefinition, dependency_structure: DependencyStructure, input_handle: NodeInput, step_output_map: dict[NodeOutput, Union[StepOutputHandle, UnresolvedStepOutputHandle]], parent_step_inputs: Optional[Sequence[StepInputUnion]], node_handle: NodeHandle, input_name: str, asset_layer: AssetLayer, ) -> FromMultipleSourcesLoadSingleSource: sources: list[StepInputSource] = [] source_to_load_from: Optional[StepInputSource] = None deps = dependency_structure.get_fan_in_deps(input_handle) for idx, node_output in enumerate(deps): if isinstance(node_output, NodeOutput): step_output_handle = step_output_map[node_output] if ( isinstance(step_output_handle, UnresolvedStepOutputHandle) or node_output.output_def.is_dynamic ): check.failed( "Unexpected dynamic output dependency in regular fan in, " "should have been caught at definition time." ) source = FromStepOutput(step_output_handle=step_output_handle, fan_in=True) sources.append(source) if ( dep_def.other_dependency is not None and dep_def.other_dependency.node == node_output.node_name and dep_def.other_dependency.output == node_output.output_name ): source_to_load_from = source else: check.invariant(f"Expected NodeOutput, got {node_output}") if source_to_load_from is None: asset_key_for_input = asset_layer.get_asset_key_for_node_input( node_handle, input_handle.input_name ) if asset_key_for_input: source_to_load_from = FromLoadableAsset(node_handle=node_handle, input_name=input_name) sources.append(source_to_load_from) else: check.failed("Unexpected: no sources to load from and no asset key to load from") return FromMultipleSourcesLoadSingleSource( sources=sources, source_to_load_from=source_to_load_from )
_PlanBuilder