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
conda__conda
tests/plugins/test_env_specs.py
{ "start": 1727, "end": 6960 }
class ____: @plugins.hookimpl def conda_environment_specifiers(self): yield CondaEnvironmentSpecifier( name="rand-spec-no-autodetect", environment_spec=RandomSpecNoAutoDetect, ) @pytest.fixture() def dummy_random_spec_plugin(plugin_manager): random_spec_plugin = RandomSpecPlugin() plugin_manager.register(random_spec_plugin) return plugin_manager @pytest.fixture() def dummy_random_spec_plugin2(plugin_manager): random_spec_plugin = RandomSpecPlugin2() plugin_manager.register(random_spec_plugin) return plugin_manager @pytest.fixture() def dummy_random_spec_plugin_no_autodetect(plugin_manager): random_spec_plugin = RandomSpecPluginNoAutodetect() plugin_manager.register(random_spec_plugin) return plugin_manager @pytest.fixture() def naughty_spec_plugin(plugin_manager): plg = NaughtySpecPlugin() plugin_manager.register(plg) return plugin_manager def test_dummy_random_spec_is_registered(dummy_random_spec_plugin): """ Ensures that our dummy random spec has been registered and can recognize .random files """ filename = "test.random" env_spec_backend = dummy_random_spec_plugin.get_environment_specifier(filename) assert env_spec_backend.name == "rand-spec" assert env_spec_backend.environment_spec(filename).env is not None env_spec_backend = dummy_random_spec_plugin.get_environment_specifier_by_name( source=filename, name="rand-spec" ) assert env_spec_backend.name == "rand-spec" assert env_spec_backend.environment_spec(filename).env is not None env_spec_backend = dummy_random_spec_plugin.detect_environment_specifier( source=filename ) assert env_spec_backend.name == "rand-spec" assert env_spec_backend.environment_spec(filename).env is not None def test_raises_an_error_if_file_is_unhandleable(dummy_random_spec_plugin): """ Ensures that our dummy random spec does not recognize non-".random" files """ with pytest.raises(EnvironmentSpecPluginNotDetected): dummy_random_spec_plugin.detect_environment_specifier("test.random-not") def test_raises_an_error_if_plugin_name_does_not_exist(dummy_random_spec_plugin): """ Ensures that an error is raised if the user requests a plugin that doesn't exist """ with pytest.raises(CondaValueError): dummy_random_spec_plugin.get_environment_specifier_by_name( name="uhoh", source="test.random" ) def test_raises_an_error_if_named_plugin_can_not_be_handled( dummy_random_spec_plugin, ): """ Ensures that an error is raised if the user requests a plugin exists, but can't be handled """ with pytest.raises( PluginError, match=r"Requested plugin 'rand-spec' is unable to handle environment spec", ): dummy_random_spec_plugin.get_environment_specifier_by_name( name="rand-spec", source="test.random-not-so-much" ) def test_raise_error_for_multiple_registered_installers( dummy_random_spec_plugin, dummy_random_spec_plugin2, ): """ Ensures that we raise an error when more than one env installer is found for the same section. """ filename = "test.random" with pytest.raises(PluginError): dummy_random_spec_plugin.get_environment_specifier(filename) def test_raises_an_error_if_no_plugins_found(dummy_random_spec_plugin_no_autodetect): """ Ensures that our a plugin with autodetect disabled does not get detected """ with pytest.raises(EnvironmentSpecPluginNotDetected): dummy_random_spec_plugin_no_autodetect.get_environment_specifier("test.random") def test_explicitly_select_a_non_autodetect_plugin( dummy_random_spec_plugin, dummy_random_spec_plugin_no_autodetect ): """ Ensures that our a plugin with autodetect disabled can be explicitly selected """ env_spec = dummy_random_spec_plugin.get_environment_specifier( "test.random", name="rand-spec-no-autodetect" ) assert env_spec.name == "rand-spec-no-autodetect" assert env_spec.environment_spec.detection_supported is False def test_naught_plugin_does_not_cause_unhandled_errors( plugin_manager, dummy_random_spec_plugin, dummy_random_spec_plugin_no_autodetect, naughty_spec_plugin, ): """ Ensures that explicitly selecting a plugin that has errors is handled appropriately """ filename = "test.random" with pytest.raises( PluginError, match=rf"An error occured when handling '{filename}' with plugin 'naughty'.", ): plugin_manager.get_environment_specifier_by_name(filename, "naughty") def test_naught_plugin_does_not_cause_unhandled_errors_during_detection( plugin_manager, dummy_random_spec_plugin, dummy_random_spec_plugin_no_autodetect, naughty_spec_plugin, ): """ Ensure that plugins that cause errors does not break plugin detection """ filename = "test.random" env_spec_backend = plugin_manager.detect_environment_specifier(filename) assert env_spec_backend.name == "rand-spec" assert env_spec_backend.environment_spec(filename).env is not None
RandomSpecPluginNoAutodetect
python
kamyu104__LeetCode-Solutions
Python/destination-city.py
{ "start": 48, "end": 259 }
class ____(object): def destCity(self, paths): """ :type paths: List[List[str]] :rtype: str """ A, B = map(set, itertools.izip(*paths)) return (B-A).pop()
Solution
python
run-llama__llama_index
llama-index-core/llama_index/core/instrumentation/events/llm.py
{ "start": 5121, "end": 5758 }
class ____(BaseEvent): """ LLMChatEndEvent. Args: messages (List[ChatMessage]): List of chat messages. response (Optional[ChatResponse]): Last chat response. """ messages: List[ChatMessage] response: Optional[ChatResponse] @classmethod def class_name(cls) -> str: """Class name.""" return "LLMChatEndEvent" def model_dump(self, **kwargs: Any) -> Dict[str, Any]: if self.response is not None and isinstance(self.response.raw, BaseModel): self.response.raw = self.response.raw.model_dump() return super().model_dump(**kwargs)
LLMChatEndEvent
python
mozilla__bleach
bleach/html5lib_shim.py
{ "start": 20924, "end": 23619 }
class ____(HTMLSerializer): """HTMLSerializer that undoes & -> &amp; in attributes and sets escape_rcdata to True """ # per the HTMLSerializer.__init__ docstring: # # Whether to escape characters that need to be # escaped within normal elements within rcdata elements such as # style. # escape_rcdata = True def escape_base_amp(self, stoken): """Escapes just bare & in HTML attribute values""" # First, undo escaping of &. We need to do this because html5lib's # HTMLSerializer expected the tokenizer to consume all the character # entities and convert them to their respective characters, but the # BleachHTMLTokenizer doesn't do that. For example, this fixes # &amp;entity; back to &entity; . stoken = stoken.replace("&amp;", "&") # However, we do want all bare & that are not marking character # entities to be changed to &amp;, so let's do that carefully here. for part in next_possible_entity(stoken): if not part: continue if part.startswith("&"): entity = match_entity(part) # Only leave entities in that are not ambiguous. If they're # ambiguous, then we escape the ampersand. if entity is not None and convert_entity(entity) is not None: yield f"&{entity};" # Length of the entity plus 2--one for & at the beginning # and one for ; at the end part = part[len(entity) + 2 :] if part: yield part continue yield part.replace("&", "&amp;") def serialize(self, treewalker, encoding=None): """Wrap HTMLSerializer.serialize and conver & to &amp; in attribute values Note that this converts & to &amp; in attribute values where the & isn't already part of an unambiguous character entity. """ in_tag = False after_equals = False for stoken in super().serialize(treewalker, encoding): if in_tag: if stoken == ">": in_tag = False elif after_equals: if stoken != '"': yield from self.escape_base_amp(stoken) after_equals = False continue elif stoken == "=": after_equals = True yield stoken else: if stoken.startswith("<"): in_tag = True yield stoken
BleachHTMLSerializer
python
django__django
django/db/models/fields/tuple_lookups.py
{ "start": 1193, "end": 4987 }
class ____: allows_composite_expressions = True def get_prep_lookup(self): if self.rhs_is_direct_value(): self.check_rhs_is_tuple_or_list() self.check_rhs_length_equals_lhs_length() else: self.check_rhs_is_supported_expression() super().get_prep_lookup() return self.rhs def check_rhs_is_tuple_or_list(self): if not isinstance(self.rhs, (tuple, list)): lhs_str = self.get_lhs_str() raise ValueError( f"{self.lookup_name!r} lookup of {lhs_str} must be a tuple or a list" ) def check_rhs_length_equals_lhs_length(self): len_lhs = len(self.lhs) if len_lhs != len(self.rhs): lhs_str = self.get_lhs_str() raise ValueError( f"{self.lookup_name!r} lookup of {lhs_str} must have {len_lhs} elements" ) def check_rhs_is_supported_expression(self): if not isinstance(self.rhs, (ResolvedOuterRef, Query)): lhs_str = self.get_lhs_str() rhs_cls = self.rhs.__class__.__name__ raise ValueError( f"{self.lookup_name!r} subquery lookup of {lhs_str} " f"only supports OuterRef and QuerySet objects (received {rhs_cls!r})" ) def get_lhs_str(self): if isinstance(self.lhs, ColPairs): return repr(self.lhs.field.name) else: names = ", ".join(repr(f.name) for f in self.lhs) return f"({names})" def get_prep_lhs(self): if isinstance(self.lhs, (tuple, list)): return Tuple(*self.lhs) return super().get_prep_lhs() def process_lhs(self, compiler, connection, lhs=None): sql, params = super().process_lhs(compiler, connection, lhs) if not isinstance(self.lhs, Tuple): sql = f"({sql})" return sql, params def process_rhs(self, compiler, connection): if self.rhs_is_direct_value(): args = [ ( val if hasattr(val, "as_sql") else Value(val, output_field=col.output_field) ) for col, val in zip(self.lhs, self.rhs) ] return compiler.compile(Tuple(*args)) else: sql, params = compiler.compile(self.rhs) if isinstance(self.rhs, ColPairs): return "(%s)" % sql, params elif isinstance(self.rhs, Query): return super().process_rhs(compiler, connection) else: raise ValueError( "Composite field lookups only work with composite expressions." ) def get_fallback_sql(self, compiler, connection): raise NotImplementedError( f"{self.__class__.__name__}.get_fallback_sql() must be implemented " f"for backends that don't have the supports_tuple_lookups feature enabled." ) def as_sql(self, compiler, connection): if ( not connection.features.supports_tuple_comparison_against_subquery and isinstance(self.rhs, Query) and self.rhs.subquery and isinstance( self, (GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual) ) ): lookup = self.lookup_name msg = ( f'"{lookup}" cannot be used to target composite fields ' "through subqueries on this backend" ) raise NotSupportedError(msg) if not connection.features.supports_tuple_lookups: return self.get_fallback_sql(compiler, connection) return super().as_sql(compiler, connection)
TupleLookupMixin
python
encode__starlette
starlette/background.py
{ "start": 239, "end": 689 }
class ____: def __init__(self, func: Callable[P, Any], *args: P.args, **kwargs: P.kwargs) -> None: self.func = func self.args = args self.kwargs = kwargs self.is_async = is_async_callable(func) async def __call__(self) -> None: if self.is_async: await self.func(*self.args, **self.kwargs) else: await run_in_threadpool(self.func, *self.args, **self.kwargs)
BackgroundTask
python
doocs__leetcode
solution/3100-3199/3191.Minimum Operations to Make Binary Array Elements Equal to One I/Solution.py
{ "start": 0, "end": 324 }
class ____: def minOperations(self, nums: List[int]) -> int: ans = 0 for i, x in enumerate(nums): if x == 0: if i + 2 >= len(nums): return -1 nums[i + 1] ^= 1 nums[i + 2] ^= 1 ans += 1 return ans
Solution
python
pytorch__pytorch
test/quantization/eager/test_numeric_suite_eager.py
{ "start": 1495, "end": 1805 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.mod1 = SubModule() self.conv = torch.nn.Conv2d(3, 5, 3, bias=False).to(dtype=torch.float) def forward(self, x): x = self.mod1(x) x = self.conv(x) return x
ModelWithSubModules
python
apache__airflow
providers/apache/hive/tests/unit/apache/hive/sensors/test_hive_partition.py
{ "start": 1308, "end": 1660 }
class ____(TestHiveEnvironment): def test_hive_partition_sensor(self, mock_hive_metastore_hook): op = HivePartitionSensor( task_id="hive_partition_check", table="airflow.static_babynames_partitioned", dag=self.dag ) op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
TestHivePartitionSensor
python
sympy__sympy
sympy/core/sympify.py
{ "start": 1267, "end": 20546 }
class ____: """ Mix in this trait to a class to disallow sympification of its instances. Examples ======== >>> from sympy import sympify >>> from sympy.core.sympify import CantSympify >>> class Something(dict): ... pass ... >>> sympify(Something()) {} >>> class Something(dict, CantSympify): ... pass ... >>> sympify(Something()) Traceback (most recent call last): ... SympifyError: SympifyError: {} """ __slots__ = () def _is_numpy_instance(a): """ Checks if an object is an instance of a type from the numpy module. """ # This check avoids unnecessarily importing NumPy. We check the whole # __mro__ in case any base type is a numpy type. return any(type_.__module__ == 'numpy' for type_ in type(a).__mro__) def _convert_numpy_types(a, **sympify_args): """ Converts a numpy datatype input to an appropriate SymPy type. """ import numpy as np if not isinstance(a, np.floating): if np.iscomplex(a): return _sympy_converter[complex](a.item()) else: return sympify(a.item(), **sympify_args) else: from .numbers import Float prec = np.finfo(a).nmant + 1 # E.g. double precision means prec=53 but nmant=52 # Leading bit of mantissa is always 1, so is not stored if np.isposinf(a): return Float('inf') elif np.isneginf(a): return Float('-inf') else: p, q = a.as_integer_ratio() a = mlib.from_rational(p, q, prec) return Float(a, precision=prec) @overload def sympify(a: int, *, strict: bool = False) -> Integer: ... # type: ignore @overload def sympify(a: float, *, strict: bool = False) -> Float: ... @overload def sympify(a: Expr | complex, *, strict: bool = False) -> Expr: ... @overload def sympify(a: Tbasic, *, strict: bool = False) -> Tbasic: ... @overload def sympify(a: Any, *, strict: bool = False) -> Basic: ... def sympify(a, locals=None, convert_xor=True, strict=False, rational=False, evaluate=None): """ Converts an arbitrary expression to a type that can be used inside SymPy. Explanation =========== It will convert Python ints into instances of :class:`~.Integer`, floats into instances of :class:`~.Float`, etc. It is also able to coerce symbolic expressions which inherit from :class:`~.Basic`. This can be useful in cooperation with SAGE. .. warning:: Note that this function uses ``eval``, and thus shouldn't be used on unsanitized input. If the argument is already a type that SymPy understands, it will do nothing but return that value. This can be used at the beginning of a function to ensure you are working with the correct type. Examples ======== >>> from sympy import sympify >>> sympify(2).is_integer True >>> sympify(2).is_real True >>> sympify(2.0).is_real True >>> sympify("2.0").is_real True >>> sympify("2e-45").is_real True If the expression could not be converted, a SympifyError is raised. >>> sympify("x***2") Traceback (most recent call last): ... SympifyError: SympifyError: "could not parse 'x***2'" When attempting to parse non-Python syntax using ``sympify``, it raises a ``SympifyError``: >>> sympify("2x+1") Traceback (most recent call last): ... SympifyError: Sympify of expression 'could not parse '2x+1'' failed To parse non-Python syntax, use ``parse_expr`` from ``sympy.parsing.sympy_parser``. >>> from sympy.parsing.sympy_parser import parse_expr >>> parse_expr("2x+1", transformations="all") 2*x + 1 For more details about ``transformations``: see :func:`~sympy.parsing.sympy_parser.parse_expr` Locals ------ The sympification happens with access to everything that is loaded by ``from sympy import *``; anything used in a string that is not defined by that import will be converted to a symbol. In the following, the ``bitcount`` function is treated as a symbol and the ``O`` is interpreted as the :class:`~.Order` object (used with series) and it raises an error when used improperly: >>> s = 'bitcount(42)' >>> sympify(s) bitcount(42) >>> sympify("O(x)") O(x) >>> sympify("O + 1") Traceback (most recent call last): ... TypeError: unbound method... In order to have ``bitcount`` be recognized it can be defined in a namespace dictionary and passed as locals: >>> ns = {} >>> exec('bitcount = lambda n: int(n).bit_length()', ns) >>> sympify(s, locals=ns) 6 In order to have the ``O`` interpreted as a Symbol, identify it as such in the namespace dictionary. This can be done in a variety of ways; all three of the following are possibilities: >>> from sympy import Symbol >>> ns["O"] = Symbol("O") # method 1 >>> exec('from sympy.abc import O', ns) # method 2 >>> ns.update(dict(O=Symbol("O"))) # method 3 >>> sympify("O + 1", locals=ns) O + 1 If you want *all* single-letter and Greek-letter variables to be symbols then you can use the clashing-symbols dictionaries that have been defined there as private variables: ``_clash1`` (single-letter variables), ``_clash2`` (the multi-letter Greek names) or ``_clash`` (both single and multi-letter names that are defined in ``abc``). >>> from sympy.abc import _clash1 >>> set(_clash1) # if this fails, see issue #23903 {'E', 'I', 'N', 'O', 'Q', 'S'} >>> sympify('I & Q', _clash1) I & Q Strict ------ If the option ``strict`` is set to ``True``, only the types for which an explicit conversion has been defined are converted. In the other cases, a SympifyError is raised. >>> print(sympify(None)) None >>> sympify(None, strict=True) Traceback (most recent call last): ... SympifyError: SympifyError: None .. deprecated:: 1.6 ``sympify(obj)`` automatically falls back to ``str(obj)`` when all other conversion methods fail, but this is deprecated. ``strict=True`` will disable this deprecated behavior. See :ref:`deprecated-sympify-string-fallback`. Evaluation ---------- If the option ``evaluate`` is set to ``False``, then arithmetic and operators will be converted into their SymPy equivalents and the ``evaluate=False`` option will be added. Nested ``Add`` or ``Mul`` will be denested first. This is done via an AST transformation that replaces operators with their SymPy equivalents, so if an operand redefines any of those operations, the redefined operators will not be used. If argument a is not a string, the mathematical expression is evaluated before being passed to sympify, so adding ``evaluate=False`` will still return the evaluated result of expression. >>> sympify('2**2 / 3 + 5') 19/3 >>> sympify('2**2 / 3 + 5', evaluate=False) 2**2/3 + 5 >>> sympify('4/2+7', evaluate=True) 9 >>> sympify('4/2+7', evaluate=False) 4/2 + 7 >>> sympify(4/2+7, evaluate=False) 9.00000000000000 Extending --------- To extend ``sympify`` to convert custom objects (not derived from ``Basic``), just define a ``_sympy_`` method to your class. You can do that even to classes that you do not own by subclassing or adding the method at runtime. >>> from sympy import Matrix >>> class MyList1(object): ... def __iter__(self): ... yield 1 ... yield 2 ... return ... def __getitem__(self, i): return list(self)[i] ... def _sympy_(self): return Matrix(self) >>> sympify(MyList1()) Matrix([ [1], [2]]) If you do not have control over the class definition you could also use the ``converter`` global dictionary. The key is the class and the value is a function that takes a single argument and returns the desired SymPy object, e.g. ``converter[MyList] = lambda x: Matrix(x)``. >>> class MyList2(object): # XXX Do not do this if you control the class! ... def __iter__(self): # Use _sympy_! ... yield 1 ... yield 2 ... return ... def __getitem__(self, i): return list(self)[i] >>> from sympy.core.sympify import converter >>> converter[MyList2] = lambda x: Matrix(x) >>> sympify(MyList2()) Matrix([ [1], [2]]) Notes ===== The keywords ``rational`` and ``convert_xor`` are only used when the input is a string. convert_xor ----------- >>> sympify('x^y',convert_xor=True) x**y >>> sympify('x^y',convert_xor=False) x ^ y rational -------- >>> sympify('0.1',rational=False) 0.1 >>> sympify('0.1',rational=True) 1/10 Sometimes autosimplification during sympification results in expressions that are very different in structure than what was entered. Until such autosimplification is no longer done, the ``kernS`` function might be of some use. In the example below you can see how an expression reduces to $-1$ by autosimplification, but does not do so when ``kernS`` is used. >>> from sympy.core.sympify import kernS >>> from sympy.abc import x >>> -2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1 -1 >>> s = '-2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1' >>> sympify(s) -1 >>> kernS(s) -2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1 Parameters ========== a : - any object defined in SymPy - standard numeric Python types: ``int``, ``long``, ``float``, ``Decimal`` - strings (like ``"0.09"``, ``"2e-19"`` or ``'sin(x)'``) - booleans, including ``None`` (will leave ``None`` unchanged) - dicts, lists, sets or tuples containing any of the above convert_xor : bool, optional If true, treats ``^`` as exponentiation. If False, treats ``^`` as XOR itself. Used only when input is a string. locals : any object defined in SymPy, optional In order to have strings be recognized it can be imported into a namespace dictionary and passed as locals. strict : bool, optional If the option strict is set to ``True``, only the types for which an explicit conversion has been defined are converted. In the other cases, a SympifyError is raised. rational : bool, optional If ``True``, converts floats into :class:`~.Rational`. If ``False``, it lets floats remain as it is. Used only when input is a string. evaluate : bool, optional If False, then arithmetic and operators will be converted into their SymPy equivalents. If True the expression will be evaluated and the result will be returned. """ # XXX: If a is a Basic subclass rather than instance (e.g. sin rather than # sin(x)) then a.__sympy__ will be the property. Only on the instance will # a.__sympy__ give the *value* of the property (True). Since sympify(sin) # was used for a long time we allow it to pass. However if strict=True as # is the case in internal calls to _sympify then we only allow # is_sympy=True. # # https://github.com/sympy/sympy/issues/20124 is_sympy = getattr(a, '__sympy__', None) if is_sympy is True: return a elif is_sympy is not None: if not strict: return a else: raise SympifyError(a) if isinstance(a, CantSympify): raise SympifyError(a) cls = getattr(a, "__class__", None) #Check if there exists a converter for any of the types in the mro for superclass in getmro(cls): #First check for user defined converters conv = _external_converter.get(superclass) if conv is None: #if none exists, check for SymPy defined converters conv = _sympy_converter.get(superclass) if conv is not None: return conv(a) if cls is type(None): if strict: raise SympifyError(a) else: return a if evaluate is None: evaluate = global_parameters.evaluate # Support for basic numpy datatypes if _is_numpy_instance(a): import numpy as np if np.isscalar(a): return _convert_numpy_types(a, locals=locals, convert_xor=convert_xor, strict=strict, rational=rational, evaluate=evaluate) _sympy_ = getattr(a, "_sympy_", None) if _sympy_ is not None: return a._sympy_() if not strict: # Put numpy array conversion _before_ float/int, see # <https://github.com/sympy/sympy/issues/13924>. flat = getattr(a, "flat", None) if flat is not None: shape = getattr(a, "shape", None) if shape is not None: from sympy.tensor.array import Array return Array(a.flat, a.shape) # works with e.g. NumPy arrays if not isinstance(a, str): if _is_numpy_instance(a): import numpy as np assert not isinstance(a, np.number) if isinstance(a, np.ndarray): # Scalar arrays (those with zero dimensions) have sympify # called on the scalar element. if a.ndim == 0: try: return sympify(a.item(), locals=locals, convert_xor=convert_xor, strict=strict, rational=rational, evaluate=evaluate) except SympifyError: pass elif hasattr(a, '__float__'): # float and int can coerce size-one numpy arrays to their lone # element. See issue https://github.com/numpy/numpy/issues/10404. return sympify(float(a)) elif hasattr(a, '__int__'): return sympify(int(a)) if strict: raise SympifyError(a) if iterable(a): try: return type(a)([sympify(x, locals=locals, convert_xor=convert_xor, rational=rational, evaluate=evaluate) for x in a]) except TypeError: # Not all iterables are rebuildable with their type. pass if not isinstance(a, str): raise SympifyError('cannot sympify object of type %r' % type(a)) from sympy.parsing.sympy_parser import (parse_expr, TokenError, standard_transformations) from sympy.parsing.sympy_parser import convert_xor as t_convert_xor from sympy.parsing.sympy_parser import rationalize as t_rationalize transformations = standard_transformations if rational: transformations += (t_rationalize,) if convert_xor: transformations += (t_convert_xor,) try: a = a.replace('\n', '') expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate) except (TokenError, SyntaxError) as exc: raise SympifyError('could not parse %r' % a, exc) return expr def _sympify(a): """ Short version of :func:`~.sympify` for internal usage for ``__add__`` and ``__eq__`` methods where it is ok to allow some things (like Python integers and floats) in the expression. This excludes things (like strings) that are unwise to allow into such an expression. >>> from sympy import Integer >>> Integer(1) == 1 True >>> Integer(1) == '1' False >>> from sympy.abc import x >>> x + 1 x + 1 >>> x + '1' Traceback (most recent call last): ... TypeError: unsupported operand type(s) for +: 'Symbol' and 'str' see: sympify """ return sympify(a, strict=True) def kernS(s): """Use a hack to try keep autosimplification from distributing a a number into an Add; this modification does not prevent the 2-arg Mul from becoming an Add, however. Examples ======== >>> from sympy.core.sympify import kernS >>> from sympy.abc import x, y The 2-arg Mul distributes a number (or minus sign) across the terms of an expression, but kernS will prevent that: >>> 2*(x + y), -(x + 1) (2*x + 2*y, -x - 1) >>> kernS('2*(x + y)') 2*(x + y) >>> kernS('-(x + 1)') -(x + 1) If use of the hack fails, the un-hacked string will be passed to sympify... and you get what you get. XXX This hack should not be necessary once issue 4596 has been resolved. """ hit = False quoted = '"' in s or "'" in s if '(' in s and not quoted: if s.count('(') != s.count(")"): raise SympifyError('unmatched left parenthesis') # strip all space from s s = ''.join(s.split()) olds = s # now use space to represent a symbol that # will # step 1. turn potential 2-arg Muls into 3-arg versions # 1a. *( -> * *( s = s.replace('*(', '* *(') # 1b. close up exponentials s = s.replace('** *', '**') # 2. handle the implied multiplication of a negated # parenthesized expression in two steps # 2a: -(...) --> -( *(...) target = '-( *(' s = s.replace('-(', target) # 2b: double the matching closing parenthesis # -( *(...) --> -( *(...)) i = nest = 0 assert target.endswith('(') # assumption below while True: j = s.find(target, i) if j == -1: break j += len(target) - 1 for j in range(j, len(s)): if s[j] == "(": nest += 1 elif s[j] == ")": nest -= 1 if nest == 0: break s = s[:j] + ")" + s[j:] i = j + 2 # the first char after 2nd ) if ' ' in s: # get a unique kern kern = '_' while kern in s: kern += choice(string.ascii_letters + string.digits) s = s.replace(' ', kern) hit = kern in s else: hit = False for i in range(2): try: expr = sympify(s) break except TypeError: # the kern might cause unknown errors... if hit: s = olds # maybe it didn't like the kern; use un-kerned s hit = False continue expr = sympify(s) # let original error raise if not hit: return expr from .symbol import Symbol rep = {Symbol(kern): 1} def _clear(expr): if isinstance(expr, (list, tuple, set)): return type(expr)([_clear(e) for e in expr]) if hasattr(expr, 'subs'): return expr.subs(rep, hack2=True) return expr expr = _clear(expr) # hope that kern is not there anymore return expr # Avoid circular import from .basic import Basic
CantSympify
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/classes11.py
{ "start": 462, "end": 511 }
class ____(Sequence[int], Mapping[str, int]): ...
C
python
django__django
tests/logging_tests/tests.py
{ "start": 8834, "end": 18054 }
class ____(SimpleTestCase): logger = logging.getLogger("django") request_factory = RequestFactory() def get_admin_email_handler(self, logger): # AdminEmailHandler does not get filtered out # even with DEBUG=True. return [ h for h in logger.handlers if h.__class__.__name__ == "AdminEmailHandler" ][0] def test_fail_silently(self): admin_email_handler = self.get_admin_email_handler(self.logger) self.assertTrue(admin_email_handler.connection().fail_silently) @override_settings( ADMINS=["admin@example.com"], EMAIL_SUBJECT_PREFIX="-SuperAwesomeSubject-", ) def test_accepts_args(self): """ User-supplied arguments and the EMAIL_SUBJECT_PREFIX setting are used to compose the email subject (#16736). """ message = "Custom message that says '%s' and '%s'" token1 = "ping" token2 = "pong" admin_email_handler = self.get_admin_email_handler(self.logger) # Backup then override original filters orig_filters = admin_email_handler.filters try: admin_email_handler.filters = [] self.logger.error(message, token1, token2) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to, ["admin@example.com"]) self.assertEqual( mail.outbox[0].subject, "-SuperAwesomeSubject-ERROR: " "Custom message that says 'ping' and 'pong'", ) finally: # Restore original filters admin_email_handler.filters = orig_filters @override_settings( ADMINS=["admin@example.com"], EMAIL_SUBJECT_PREFIX="-SuperAwesomeSubject-", INTERNAL_IPS=["127.0.0.1"], ) def test_accepts_args_and_request(self): """ The subject is also handled if being passed a request object. """ message = "Custom message that says '%s' and '%s'" token1 = "ping" token2 = "pong" admin_email_handler = self.get_admin_email_handler(self.logger) # Backup then override original filters orig_filters = admin_email_handler.filters try: admin_email_handler.filters = [] request = self.request_factory.get("/") self.logger.error( message, token1, token2, extra={ "status_code": 403, "request": request, }, ) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to, ["admin@example.com"]) self.assertEqual( mail.outbox[0].subject, "-SuperAwesomeSubject-ERROR (internal IP): " "Custom message that says 'ping' and 'pong'", ) finally: # Restore original filters admin_email_handler.filters = orig_filters @override_settings( ADMINS=["admin@example.com"], EMAIL_SUBJECT_PREFIX="", DEBUG=False, ) def test_subject_accepts_newlines(self): """ Newlines in email reports' subjects are escaped to prevent AdminErrorHandler from failing (#17281). """ message = "Message \r\n with newlines" expected_subject = "ERROR: Message \\r\\n with newlines" self.assertEqual(len(mail.outbox), 0) self.logger.error(message) self.assertEqual(len(mail.outbox), 1) self.assertNotIn("\n", mail.outbox[0].subject) self.assertNotIn("\r", mail.outbox[0].subject) self.assertEqual(mail.outbox[0].subject, expected_subject) @override_settings( ADMINS=["admin@example.com"], DEBUG=False, ) def test_uses_custom_email_backend(self): """ Refs #19325 """ message = "All work and no play makes Jack a dull boy" admin_email_handler = self.get_admin_email_handler(self.logger) mail_admins_called = {"called": False} def my_mail_admins(*args, **kwargs): connection = kwargs["connection"] self.assertIsInstance(connection, MyEmailBackend) mail_admins_called["called"] = True # Monkeypatches orig_mail_admins = mail.mail_admins orig_email_backend = admin_email_handler.email_backend mail.mail_admins = my_mail_admins admin_email_handler.email_backend = "logging_tests.logconfig.MyEmailBackend" try: self.logger.error(message) self.assertTrue(mail_admins_called["called"]) finally: # Revert Monkeypatches mail.mail_admins = orig_mail_admins admin_email_handler.email_backend = orig_email_backend @override_settings( ADMINS=["admin@example.com"], ) def test_emit_non_ascii(self): """ #23593 - AdminEmailHandler should allow Unicode characters in the request. """ handler = self.get_admin_email_handler(self.logger) record = self.logger.makeRecord( "name", logging.ERROR, "function", "lno", "message", None, None ) url_path = "/º" record.request = self.request_factory.get(url_path) handler.emit(record) self.assertEqual(len(mail.outbox), 1) msg = mail.outbox[0] self.assertEqual(msg.to, ["admin@example.com"]) self.assertEqual(msg.subject, "[Django] ERROR (EXTERNAL IP): message") self.assertIn("Report at %s" % url_path, msg.body) @override_settings( MANAGERS=["manager@example.com"], DEBUG=False, ) def test_customize_send_mail_method(self): class ManagerEmailHandler(AdminEmailHandler): def send_mail(self, subject, message, *args, **kwargs): mail.mail_managers( subject, message, *args, connection=self.connection(), **kwargs ) handler = ManagerEmailHandler() record = self.logger.makeRecord( "name", logging.ERROR, "function", "lno", "message", None, None ) self.assertEqual(len(mail.outbox), 0) handler.emit(record) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to, ["manager@example.com"]) @override_settings(ALLOWED_HOSTS="example.com") def test_disallowed_host_doesnt_crash(self): admin_email_handler = self.get_admin_email_handler(self.logger) old_include_html = admin_email_handler.include_html # Text email admin_email_handler.include_html = False try: self.client.get("/", headers={"host": "evil.com"}) finally: admin_email_handler.include_html = old_include_html # HTML email admin_email_handler.include_html = True try: self.client.get("/", headers={"host": "evil.com"}) finally: admin_email_handler.include_html = old_include_html def test_default_exception_reporter_class(self): admin_email_handler = self.get_admin_email_handler(self.logger) self.assertEqual(admin_email_handler.reporter_class, ExceptionReporter) @override_settings(ADMINS=["admin@example.com"]) def test_custom_exception_reporter_is_used(self): record = self.logger.makeRecord( "name", logging.ERROR, "function", "lno", "message", None, None ) record.request = self.request_factory.get("/") handler = AdminEmailHandler( reporter_class="logging_tests.logconfig.CustomExceptionReporter" ) handler.emit(record) self.assertEqual(len(mail.outbox), 1) msg = mail.outbox[0] self.assertEqual(msg.body, "message\n\ncustom traceback text") @override_settings(ADMINS=["admin@example.com"]) def test_emit_no_form_tag(self): """HTML email doesn't contain forms.""" handler = AdminEmailHandler(include_html=True) record = self.logger.makeRecord( "name", logging.ERROR, "function", "lno", "message", None, None, ) handler.emit(record) self.assertEqual(len(mail.outbox), 1) msg = mail.outbox[0] self.assertEqual(msg.subject, "[Django] ERROR: message") self.assertEqual(len(msg.alternatives), 1) body_html = str(msg.alternatives[0].content) self.assertIn('<div id="traceback">', body_html) self.assertNotIn("<form", body_html) @override_settings(ADMINS=[]) def test_emit_no_admins(self): handler = AdminEmailHandler() record = self.logger.makeRecord( "name", logging.ERROR, "function", "lno", "message", None, None, ) with mock.patch.object( handler, "format_subject", side_effect=AssertionError("Should not be called"), ): handler.emit(record) self.assertEqual(len(mail.outbox), 0)
AdminEmailHandlerTest
python
numba__numba
numba/tests/test_flow_control.py
{ "start": 9023, "end": 33714 }
class ____(TestCase): """ Test the numba.controlflow.CFGraph class. """ def from_adj_list(self, d, entry_point=0): """ Build a CFGraph class from a dict of adjacency lists. """ g = CFGraph() # Need to add all nodes before adding edges for node in d: g.add_node(node) for node, dests in d.items(): for dest in dests: g.add_edge(node, dest) return g def loopless1(self): """ A simple CFG corresponding to the following code structure: c = (... if ... else ...) + ... return b + c """ g = self.from_adj_list({0: [18, 12], 12: [21], 18: [21], 21: []}) g.set_entry_point(0) g.process() return g def loopless1_dead_nodes(self): """ Same as loopless1(), but with added dead blocks (some of them in a loop). """ g = self.from_adj_list( {0: [18, 12], 12: [21], 18: [21], 21: [], 91: [12, 0], 92: [91, 93], 93: [92], 94: [], }) g.set_entry_point(0) g.process() return g def loopless2(self): """ A loopless CFG corresponding to the following code structure: c = (... if ... else ...) + ... if c: return ... else: return ... Note there are two exit points, and the entry point has been changed to a non-zero value. """ g = self.from_adj_list( {99: [18, 12], 12: [21], 18: [21], 21: [42, 34], 34: [], 42: []}) g.set_entry_point(99) g.process() return g def multiple_loops(self): """ A CFG with multiple nested loops: for y in b: for x in a: # This loop has two back edges if b: continue else: continue for z in c: if z: return ... """ g = self.from_adj_list({0: [7], 7: [10, 60], 10: [13], 13: [20], 20: [56, 23], 23: [32, 44], 32: [20], 44: [20], 56: [57], 57: [7], 60: [61], 61: [68], 68: [87, 71], 71: [80, 68], 80: [], 87: [88], 88: []} ) g.set_entry_point(0) g.process() return g def multiple_exits(self): """ A CFG with three loop exits, one of which is also a function exit point, and another function exit point: for x in a: if a: return b elif b: break return c """ g = self.from_adj_list( {0: [7], 7: [10, 36], 10: [19, 23], 19: [], 23: [29, 7], 29: [37], 36: [37], 37: [] }) g.set_entry_point(0) g.process() return g def infinite_loop1(self): """ A CFG with a infinite loop and an alternate exit point: if c: return while True: if a: ... else: ... """ g = self.from_adj_list( {0: [10, 6], 6: [], 10: [13], 13: [26, 19], 19: [13], 26: [13]}) g.set_entry_point(0) g.process() return g def infinite_loop2(self): """ A CFG with no exit point at all: while True: if a: ... else: ... """ g = self.from_adj_list({0: [3], 3: [16, 9], 9: [3], 16: [3]}) g.set_entry_point(0) g.process() return g def test_simple_properties(self): g = self.loopless1() self.assertEqual(sorted(g.successors(0)), [(12, None), (18, None)]) self.assertEqual(sorted(g.successors(21)), []) self.assertEqual(sorted(g.predecessors(0)), []) self.assertEqual(sorted(g.predecessors(21)), [(12, None), (18, None)]) def test_exit_points(self): g = self.loopless1() self.assertEqual(sorted(g.exit_points()), [21]) g = self.loopless1_dead_nodes() self.assertEqual(sorted(g.exit_points()), [21]) g = self.loopless2() self.assertEqual(sorted(g.exit_points()), [34, 42]) g = self.multiple_loops() self.assertEqual(sorted(g.exit_points()), [80, 88]) g = self.infinite_loop1() self.assertEqual(sorted(g.exit_points()), [6]) g = self.infinite_loop2() self.assertEqual(sorted(g.exit_points()), []) g = self.multiple_exits() self.assertEqual(sorted(g.exit_points()), [19, 37]) def test_dead_nodes(self): g = self.loopless1() self.assertEqual(len(g.dead_nodes()), 0) self.assertEqual(sorted(g.nodes()), [0, 12, 18, 21]) g = self.loopless2() self.assertEqual(len(g.dead_nodes()), 0) self.assertEqual(sorted(g.nodes()), [12, 18, 21, 34, 42, 99]) g = self.multiple_loops() self.assertEqual(len(g.dead_nodes()), 0) g = self.infinite_loop1() self.assertEqual(len(g.dead_nodes()), 0) g = self.multiple_exits() self.assertEqual(len(g.dead_nodes()), 0) # Only this example has dead nodes g = self.loopless1_dead_nodes() self.assertEqual(sorted(g.dead_nodes()), [91, 92, 93, 94]) self.assertEqual(sorted(g.nodes()), [0, 12, 18, 21]) def test_descendents(self): g = self.loopless2() d = g.descendents(34) self.assertEqual(sorted(d), []) d = g.descendents(42) self.assertEqual(sorted(d), []) d = g.descendents(21) self.assertEqual(sorted(d), [34, 42]) d = g.descendents(99) self.assertEqual(sorted(d), [12, 18, 21, 34, 42]) g = self.infinite_loop1() d = g.descendents(26) self.assertEqual(sorted(d), []) d = g.descendents(19) self.assertEqual(sorted(d), []) d = g.descendents(13) self.assertEqual(sorted(d), [19, 26]) d = g.descendents(10) self.assertEqual(sorted(d), [13, 19, 26]) d = g.descendents(6) self.assertEqual(sorted(d), []) d = g.descendents(0) self.assertEqual(sorted(d), [6, 10, 13, 19, 26]) def test_topo_order(self): g = self.loopless1() self.assertIn(g.topo_order(), ([0, 12, 18, 21], [0, 18, 12, 21])) g = self.loopless2() self.assertIn(g.topo_order(), ([99, 18, 12, 21, 34, 42], [99, 12, 18, 21, 34, 42])) g = self.infinite_loop2() self.assertIn(g.topo_order(), ([0, 3, 9, 16], [0, 3, 16, 9])) g = self.infinite_loop1() self.assertIn(g.topo_order(), ([0, 6, 10, 13, 19, 26], [0, 6, 10, 13, 26, 19], [0, 10, 13, 19, 26, 6], [0, 10, 13, 26, 19, 6])) def test_topo_sort(self): def check_topo_sort(nodes, expected): self.assertIn(list(g.topo_sort(nodes)), expected) self.assertIn(list(g.topo_sort(nodes[::-1])), expected) self.assertIn(list(g.topo_sort(nodes, reverse=True))[::-1], expected) self.assertIn(list(g.topo_sort(nodes[::-1], reverse=True))[::-1], expected) self.random.shuffle(nodes) self.assertIn(list(g.topo_sort(nodes)), expected) self.assertIn(list(g.topo_sort(nodes, reverse=True))[::-1], expected) g = self.loopless2() check_topo_sort([21, 99, 12, 34], ([99, 12, 21, 34],)) # NOTE: topo_sort() is not stable check_topo_sort([18, 12, 42, 99], ([99, 12, 18, 42], [99, 18, 12, 42])) g = self.multiple_exits() check_topo_sort([19, 10, 7, 36], ([7, 10, 19, 36], [7, 10, 36, 19], [7, 36, 10, 19])) def check_dominators(self, got, expected): self.assertEqual(sorted(got), sorted(expected)) for node in sorted(got): self.assertEqual(sorted(got[node]), sorted(expected[node]), "mismatch for %r" % (node,)) def test_dominators_loopless(self): def eq_(d, l): self.assertEqual(sorted(doms[d]), l) for g in [self.loopless1(), self.loopless1_dead_nodes()]: doms = g.dominators() eq_(0, [0]) eq_(12, [0, 12]) eq_(18, [0, 18]) eq_(21, [0, 21]) g = self.loopless2() doms = g.dominators() eq_(99, [99]) eq_(12, [12, 99]) eq_(18, [18, 99]) eq_(21, [21, 99]) eq_(34, [21, 34, 99]) eq_(42, [21, 42, 99]) def test_dominators_loops(self): g = self.multiple_exits() doms = g.dominators() self.check_dominators(doms, {0: [0], 7: [0, 7], 10: [0, 7, 10], 19: [0, 7, 10, 19], 23: [0, 7, 10, 23], 29: [0, 7, 10, 23, 29], 36: [0, 7, 36], 37: [0, 7, 37], }) g = self.multiple_loops() doms = g.dominators() self.check_dominators(doms, {0: [0], 7: [0, 7], 10: [0, 10, 7], 13: [0, 10, 13, 7], 20: [0, 10, 20, 13, 7], 23: [0, 20, 23, 7, 10, 13], 32: [32, 0, 20, 23, 7, 10, 13], 44: [0, 20, 23, 7, 10, 44, 13], 56: [0, 20, 7, 56, 10, 13], 57: [0, 20, 7, 56, 57, 10, 13], 60: [0, 60, 7], 61: [0, 60, 61, 7], 68: [0, 68, 60, 61, 7], 71: [0, 68, 71, 7, 60, 61], 80: [80, 0, 68, 71, 7, 60, 61], 87: [0, 68, 87, 7, 60, 61], 88: [0, 68, 87, 88, 7, 60, 61] }) g = self.infinite_loop1() doms = g.dominators() self.check_dominators(doms, {0: [0], 6: [0, 6], 10: [0, 10], 13: [0, 10, 13], 19: [0, 10, 19, 13], 26: [0, 10, 13, 26], }) def test_post_dominators_loopless(self): def eq_(d, l): self.assertEqual(sorted(doms[d]), l) for g in [self.loopless1(), self.loopless1_dead_nodes()]: doms = g.post_dominators() eq_(0, [0, 21]) eq_(12, [12, 21]) eq_(18, [18, 21]) eq_(21, [21]) g = self.loopless2() doms = g.post_dominators() eq_(34, [34]) eq_(42, [42]) eq_(21, [21]) eq_(18, [18, 21]) eq_(12, [12, 21]) eq_(99, [21, 99]) def test_post_dominators_loops(self): g = self.multiple_exits() doms = g.post_dominators() self.check_dominators(doms, {0: [0, 7], 7: [7], 10: [10], 19: [19], 23: [23], 29: [29, 37], 36: [36, 37], 37: [37], }) g = self.multiple_loops() doms = g.post_dominators() self.check_dominators(doms, {0: [0, 60, 68, 61, 7], 7: [60, 68, 61, 7], 10: [68, 7, 10, 13, 20, 56, 57, 60, 61], 13: [68, 7, 13, 20, 56, 57, 60, 61], 20: [20, 68, 7, 56, 57, 60, 61], 23: [68, 7, 20, 23, 56, 57, 60, 61], 32: [32, 68, 7, 20, 56, 57, 60, 61], 44: [68, 7, 44, 20, 56, 57, 60, 61], 56: [68, 7, 56, 57, 60, 61], 57: [57, 60, 68, 61, 7], 60: [60, 68, 61], 61: [68, 61], 68: [68], 71: [71], 80: [80], 87: [88, 87], 88: [88] }) def test_post_dominators_infinite_loops(self): # Post-dominators with infinite loops need special care # (the ordinary algorithm won't work). g = self.infinite_loop1() doms = g.post_dominators() self.check_dominators(doms, {0: [0], 6: [6], 10: [10, 13], 13: [13], 19: [19], 26: [26], }) g = self.infinite_loop2() doms = g.post_dominators() self.check_dominators(doms, {0: [0, 3], 3: [3], 9: [9], 16: [16], }) def test_dominator_tree(self): def check(graph, expected): domtree = graph.dominator_tree() self.assertEqual(domtree, expected) check(self.loopless1(), {0: {12, 18, 21}, 12: set(), 18: set(), 21: set()}) check(self.loopless2(), {12: set(), 18: set(), 21: {34, 42}, 34: set(), 42: set(), 99: {18, 12, 21}}) check(self.loopless1_dead_nodes(), {0: {12, 18, 21}, 12: set(), 18: set(), 21: set()}) check(self.multiple_loops(), {0: {7}, 7: {10, 60}, 60: {61}, 61: {68}, 68: {71, 87}, 87: {88}, 88: set(), 71: {80}, 80: set(), 10: {13}, 13: {20}, 20: {56, 23}, 23: {32, 44}, 44: set(), 32: set(), 56: {57}, 57: set()}) check(self.multiple_exits(), {0: {7}, 7: {10, 36, 37}, 36: set(), 10: {19, 23}, 23: {29}, 29: set(), 37: set(), 19: set()}) check(self.infinite_loop1(), {0: {10, 6}, 6: set(), 10: {13}, 13: {26, 19}, 19: set(), 26: set()}) check(self.infinite_loop2(), {0: {3}, 3: {16, 9}, 9: set(), 16: set()}) def test_immediate_dominators(self): def check(graph, expected): idoms = graph.immediate_dominators() self.assertEqual(idoms, expected) check(self.loopless1(), {0: 0, 12: 0, 18: 0, 21: 0}) check(self.loopless2(), {18: 99, 12: 99, 21: 99, 42: 21, 34: 21, 99: 99}) check(self.loopless1_dead_nodes(), {0: 0, 12: 0, 18: 0, 21: 0}) check(self.multiple_loops(), {0: 0, 7: 0, 10: 7, 13: 10, 20: 13, 23: 20, 32: 23, 44: 23, 56: 20, 57: 56, 60: 7, 61: 60, 68: 61, 71: 68, 80: 71, 87: 68, 88: 87}) check(self.multiple_exits(), {0:0, 7: 0, 10: 7, 19: 10, 23: 10, 29: 23, 36: 7, 37: 7}) check(self.infinite_loop1(), {0: 0, 6: 0, 10: 0, 13: 10, 19: 13, 26: 13}) check(self.infinite_loop2(), {0: 0, 3: 0, 9: 3, 16: 3}) def test_dominance_frontier(self): def check(graph, expected): df = graph.dominance_frontier() self.assertEqual(df, expected) check(self.loopless1(), {0: set(), 12: {21}, 18: {21}, 21: set()}) check(self.loopless2(), {18: {21}, 12: {21}, 21: set(), 42: set(), 34: set(), 99: set()}) check(self.loopless1_dead_nodes(), {0: set(), 12: {21}, 18: {21}, 21: set()}) check(self.multiple_loops(), {0: set(), 7: {7}, 10: {7}, 13: {7}, 20: {20, 7}, 23: {20}, 32: {20}, 44: {20}, 56: {7}, 57: {7}, 60: set(), 61: set(), 68: {68}, 71: {68}, 80: set(), 87: set(), 88: set()}) check(self.multiple_exits(), {0: set(), 7: {7}, 10: {37, 7}, 19: set(), 23: {37, 7}, 29: {37}, 36: {37}, 37: set()}) check(self.infinite_loop1(), {0: set(), 6: set(), 10: set(), 13: {13}, 19: {13}, 26: {13}}) check(self.infinite_loop2(), {0: set(), 3: {3}, 9: {3}, 16: {3}}) def test_backbone_loopless(self): for g in [self.loopless1(), self.loopless1_dead_nodes()]: self.assertEqual(sorted(g.backbone()), [0, 21]) g = self.loopless2() self.assertEqual(sorted(g.backbone()), [21, 99]) def test_backbone_loops(self): g = self.multiple_loops() self.assertEqual(sorted(g.backbone()), [0, 7, 60, 61, 68]) g = self.infinite_loop1() self.assertEqual(sorted(g.backbone()), [0]) g = self.infinite_loop2() self.assertEqual(sorted(g.backbone()), [0, 3]) def test_loops(self): for g in [self.loopless1(), self.loopless1_dead_nodes(), self.loopless2()]: self.assertEqual(len(g.loops()), 0) g = self.multiple_loops() # Loop headers self.assertEqual(sorted(g.loops()), [7, 20, 68]) outer1 = g.loops()[7] inner1 = g.loops()[20] outer2 = g.loops()[68] self.assertEqual(outer1.header, 7) self.assertEqual(sorted(outer1.entries), [0]) self.assertEqual(sorted(outer1.exits), [60]) self.assertEqual(sorted(outer1.body), [7, 10, 13, 20, 23, 32, 44, 56, 57]) self.assertEqual(inner1.header, 20) self.assertEqual(sorted(inner1.entries), [13]) self.assertEqual(sorted(inner1.exits), [56]) self.assertEqual(sorted(inner1.body), [20, 23, 32, 44]) self.assertEqual(outer2.header, 68) self.assertEqual(sorted(outer2.entries), [61]) self.assertEqual(sorted(outer2.exits), [80, 87]) self.assertEqual(sorted(outer2.body), [68, 71]) for node in [0, 60, 61, 80, 87, 88]: self.assertEqual(g.in_loops(node), []) for node in [7, 10, 13, 56, 57]: self.assertEqual(g.in_loops(node), [outer1]) for node in [20, 23, 32, 44]: self.assertEqual(g.in_loops(node), [inner1, outer1]) for node in [68, 71]: self.assertEqual(g.in_loops(node), [outer2]) g = self.infinite_loop1() # Loop headers self.assertEqual(sorted(g.loops()), [13]) loop = g.loops()[13] self.assertEqual(loop.header, 13) self.assertEqual(sorted(loop.entries), [10]) self.assertEqual(sorted(loop.exits), []) self.assertEqual(sorted(loop.body), [13, 19, 26]) for node in [0, 6, 10]: self.assertEqual(g.in_loops(node), []) for node in [13, 19, 26]: self.assertEqual(g.in_loops(node), [loop]) g = self.infinite_loop2() # Loop headers self.assertEqual(sorted(g.loops()), [3]) loop = g.loops()[3] self.assertEqual(loop.header, 3) self.assertEqual(sorted(loop.entries), [0]) self.assertEqual(sorted(loop.exits), []) self.assertEqual(sorted(loop.body), [3, 9, 16]) for node in [0]: self.assertEqual(g.in_loops(node), []) for node in [3, 9, 16]: self.assertEqual(g.in_loops(node), [loop]) g = self.multiple_exits() # Loop headers self.assertEqual(sorted(g.loops()), [7]) loop = g.loops()[7] self.assertEqual(loop.header, 7) self.assertEqual(sorted(loop.entries), [0]) self.assertEqual(sorted(loop.exits), [19, 29, 36]) self.assertEqual(sorted(loop.body), [7, 10, 23]) for node in [0, 19, 29, 36]: self.assertEqual(g.in_loops(node), []) for node in [7, 10, 23]: self.assertEqual(g.in_loops(node), [loop]) def test_loop_dfs_pathological(self): # The follow adjlist is an export from the reproducer in #6186 g = self.from_adj_list({ 0: {38, 14}, 14: {38, 22}, 22: {38, 30}, 30: {42, 38}, 38: {42}, 42: {64, 50}, 50: {64, 58}, 58: {128}, 64: {72, 86}, 72: {80, 86}, 80: {128}, 86: {108, 94}, 94: {108, 102}, 102: {128}, 108: {128, 116}, 116: {128, 124}, 124: {128}, 128: {178, 174}, 174: {178}, 178: {210, 206}, 206: {210}, 210: {248, 252}, 248: {252}, 252: {282, 286}, 282: {286}, 286: {296, 326}, 296: {330}, 326: {330}, 330: {370, 340}, 340: {374}, 370: {374}, 374: {380, 382}, 380: {382}, 382: {818, 390}, 390: {456, 458}, 456: {458}, 458: {538, 566}, 538: {548, 566}, 548: set(), 566: {586, 572}, 572: {586}, 586: {708, 596}, 596: {608}, 608: {610}, 610: {704, 620}, 620: {666, 630}, 630: {636, 646}, 636: {666, 646}, 646: {666}, 666: {610}, 704: {706}, 706: {818}, 708: {720}, 720: {722}, 722: {816, 732}, 732: {778, 742}, 742: {748, 758}, 748: {778, 758}, 758: {778}, 778: {722}, 816: {818}, 818: set(), }) g.set_entry_point(0) g.process() stats = {} # Compute backedges and store the iteration count for testing back_edges = g._find_back_edges(stats=stats) self.assertEqual(back_edges, {(666, 610), (778, 722)}) self.assertEqual(stats['iteration_count'], 155) def test_equals(self): def get_new(): g = self.from_adj_list({0: [18, 12], 12: [21], 18: [21], 21: []}) g.set_entry_point(0) g.process() return g x = get_new() y = get_new() # identical self.assertEqual(x, y) # identical but defined in a different order g = self.from_adj_list({0: [12, 18], 18: [21], 21: [], 12: [21]}) g.set_entry_point(0) g.process() self.assertEqual(x, g) # different entry point z = get_new() z.set_entry_point(18) z.process() self.assertNotEqual(x, z) # extra node/edge, same entry point z = self.from_adj_list({0: [18, 12], 12: [21], 18: [21], 21: [22], 22: []}) z.set_entry_point(0) z.process() self.assertNotEqual(x, z) # same nodes, different edges a = self.from_adj_list({0: [18, 12], 12: [0], 18: []}) a.set_entry_point(0) a.process() z = self.from_adj_list({0: [18, 12], 12: [18], 18: []}) z.set_entry_point(0) z.process() self.assertNotEqual(a, z)
TestCFGraph
python
apache__airflow
scripts/ci/prek/new_session_in_provide_session.py
{ "start": 1562, "end": 5187 }
class ____(enum.Enum): none = "none" new_session = "new_session" def _is_new_session_or_none(value: ast.expr) -> _SessionDefault | None: """Whether an expression is NEW_SESSION. Old code written before the introduction of NEW_SESSION (and even some new if the contributor wasn't made aware of the addition) generally uses None as the default value, so we add that to the check as well. """ if isinstance(value, ast.Constant) and value.value is None: return _SessionDefault.none if isinstance(value, ast.Name) and value.id == "NEW_SESSION": return _SessionDefault.new_session # It's possible to do FOO = NEW_SESSION and reference FOO to work around # this check, but let's rely on reviewers to catch this kind of shenanigans. return None _ALLOWED_DECORATOR_NAMES = ("overload", "provide_session", "abstractmethod") def _is_decorated_correctly(nodes: list[ast.expr]) -> bool: """Whether expected decorators are provided. Three decorators would allow NEW_SESSION usages: * ``@provide_session``: The canonical case. * ``@overload``: A typing overload and not something to actually execute. * ``@abstractmethod``: This will be overridden in a subclass anyway. """ # This only accepts those decorators literally. Should be enough? return any(isinstance(node, ast.Name) and node.id in _ALLOWED_DECORATOR_NAMES for node in nodes) def _annotation_has_none(value: ast.expr | None) -> bool: if value is None: return False if isinstance(value, ast.Constant) and value.value is None: return True if isinstance(value, ast.BinOp) and isinstance(value.op, ast.BitOr): # Type union. return _annotation_has_none(value.left) or _annotation_has_none(value.right) return False def _iter_incorrect_new_session_usages(path: pathlib.Path) -> typing.Iterator[ast.FunctionDef]: """Check NEW_SESSION usages outside functions decorated with provide_session.""" for node in ast.walk(ast.parse(path.read_text("utf-8"), str(path))): if not isinstance(node, ast.FunctionDef): continue session = _get_session_arg_and_default(node.args) if session is None or session.default is None: continue # No session argument or the argument has no default, we're good. if _is_decorated_correctly(node.decorator_list): continue # Has @provide_session so the default is expected. default_kind = _is_new_session_or_none(session.default) if default_kind is None: continue # Default value is not NEW_SESSION or None. if default_kind == _SessionDefault.none and _annotation_has_none(session.argument.annotation): continue # None is OK if the argument is explicitly typed as None. yield node def main(argv: list[str]) -> int: paths = (pathlib.Path(filename) for filename in argv[1:]) errors = [(path, error) for path in paths for error in _iter_incorrect_new_session_usages(path)] if errors: print("Incorrect @provide_session and NEW_SESSION usages:", end="\n\n") for path, error in errors: print(f"{path}:{error.lineno}") print(f"\tdef {error.name}(...", end="\n\n") print("Only function decorated with @provide_session should use 'session: Session = NEW_SESSION'.") print( "See: https://github.com/apache/airflow/blob/main/" "contributing-docs/05_pull_requests.rst#database-session-handling" ) return len(errors) if __name__ == "__main__": sys.exit(main(sys.argv))
_SessionDefault
python
google__pytype
pytype/utils_test.py
{ "start": 2784, "end": 3089 }
class ____(unittest.TestCase): """Test decorators.""" def test_annotating_decorator(self): foo = utils.AnnotatingDecorator() @foo(3) def f(): # pylint: disable=unused-variable pass self.assertEqual(foo.lookup["f"], 3) if __name__ == "__main__": unittest.main()
DecoratorsTest
python
kamyu104__LeetCode-Solutions
Python/find-the-largest-area-of-square-inside-two-rectangles.py
{ "start": 51, "end": 761 }
class ____(object): def largestSquareArea(self, bottomLeft, topRight): """ :type bottomLeft: List[List[int]] :type topRight: List[List[int]] :rtype: int """ result = 0 for i in xrange(len(bottomLeft)): for j in xrange(i+1, len(bottomLeft)): max_x = max(bottomLeft[i][0], bottomLeft[j][0]) min_x = min(topRight[i][0], topRight[j][0]) max_y = max(bottomLeft[i][1], bottomLeft[j][1]) min_y = min(topRight[i][1], topRight[j][1]) result = max(result, min(min_x-max_x, min_y-max_y)) return result**2 # Time: O(n^2) # Space: O(1) # brute force, math
Solution
python
pallets__jinja
src/jinja2/nodes.py
{ "start": 27766, "end": 27859 }
class ____(BinExpr): """Multiplies the left with the right node.""" operator = "*"
Mul
python
tensorflow__tensorflow
tensorflow/python/distribute/values_v2_test.py
{ "start": 13759, "end": 16770 }
class ____(test.TestCase, parameterized.TestCase): def create_variable(self, strategy, initial_value, enable_packed_handle, **kwargs): variables = [] for device in strategy.extended.parameter_devices: with ops.device(device): variables.append(variables_lib.Variable(initial_value, **kwargs)) return values_v2.DistributedVariable( variables, enable_packed_handle=enable_packed_handle) def assertReplica(self, distributed_var, values): for var, value in zip(distributed_var._variables, values): self.assertAllEqual(var, value) def testRead(self, strategy, enable_packed_handle, tf_function): v = self.create_variable(strategy, 0., enable_packed_handle) with ops.device(strategy.extended.parameter_devices[0]): v.assign(1.) with ops.device(strategy.extended.parameter_devices[1]): v.assign(2.) @tf_function def read_device0(): with ops.device(strategy.extended.parameter_devices[0]): return v.read_value(), v.value() @tf_function def read_device1(): with ops.device(strategy.extended.parameter_devices[1]): return v.read_value(), v.value() @tf_function def read_other_device(): with ops.device("CPU:0"): return v.read_value(), v.value() self.assertAllEqual(read_device0(), [1., 1.]) self.assertAllEqual(read_device1(), [2., 2.]) self.assertAllEqual(read_other_device(), [1., 1.]) def testAssign(self, strategy, enable_packed_handle, tf_function): v = self.create_variable(strategy, 0., enable_packed_handle) @tf_function def update_device0(): with ops.device(strategy.extended.parameter_devices[0]): v.assign(1.) @tf_function def update_device1(): with ops.device(strategy.extended.parameter_devices[1]): v.assign(2.) update_device0() update_device1() self.assertReplica(v, [1., 2.]) with ops.device("CPU:0"): # Update the primary replica. v.assign(3.) self.assertReplica(v, [3., 2.]) def testStrategyRun(self, strategy, enable_packed_handle, tf_function): if (test_util.is_tpu_strategy(strategy) and tf_function is combinations.no_tf_function): self.skipTest("tpu doesn't support eager") v = self.create_variable(strategy, 0., enable_packed_handle) @tf_function def update(per_replica): v.assign(per_replica) @tf_function def read(): return v.read_value() strategy.run( update, args=(test_util.create_per_replica(strategy, [1., 2.]),)) self.assertReplica(v, [1., 2.]) self.assertAllEqual( test_util.gather(strategy, strategy.run(read)), [1., 2.]) def _make_index_slices(values, indices, dense_shape=None): if dense_shape: dense_shape = array_ops.identity(dense_shape) return indexed_slices.IndexedSlices( array_ops.identity(values), array_ops.identity(indices), dense_shape) if __name__ == "__main__": test_util.main()
DistributedVariableTest
python
pennersr__django-allauth
allauth/mfa/base/forms.py
{ "start": 1140, "end": 1273 }
class ____(BaseAuthenticateForm): def save(self): post_authentication(context.request, self.authenticator)
AuthenticateForm
python
getsentry__sentry
src/sentry/utils/codecs.py
{ "start": 991, "end": 1402 }
class ____(Codec[TDecoded, TEncoded]): def __init__(self, outer: Codec[TDecoded, T], inner: Codec[T, TEncoded]) -> None: self.outer = outer self.inner = inner def encode(self, value: TDecoded) -> TEncoded: return self.inner.encode(self.outer.encode(value)) def decode(self, value: TEncoded) -> TDecoded: return self.outer.decode(self.inner.decode(value))
ChainedCodec
python
ray-project__ray
rllib/algorithms/cql/torch/cql_torch_learner.py
{ "start": 776, "end": 11774 }
class ____(SACTorchLearner): @override(SACTorchLearner) def compute_loss_for_module( self, *, module_id: ModuleID, config: CQLConfig, batch: Dict, fwd_out: Dict[str, TensorType], ) -> TensorType: # TODO (simon, sven): Add upstream information pieces into this timesteps # call arg to Learner.update_...(). self.metrics.log_value( (ALL_MODULES, TRAINING_ITERATION), 1, reduce="sum", ) # Get the train action distribution for the current policy and current state. # This is needed for the policy (actor) loss and the `alpha`` loss. action_dist_class = self.module[module_id].get_train_action_dist_cls() action_dist_curr = action_dist_class.from_logits( fwd_out[Columns.ACTION_DIST_INPUTS] ) # Optimize also the hyperparameter `alpha` by using the current policy # evaluated at the current state (from offline data). Note, in contrast # to the original SAC loss, here the `alpha` and actor losses are # calculated first. # TODO (simon): Check, why log(alpha) is used, prob. just better # to optimize and monotonic function. Original equation uses alpha. alpha_loss = -torch.mean( self.curr_log_alpha[module_id] * (fwd_out["logp_resampled"].detach() + self.target_entropy[module_id]) ) # Get the current alpha. alpha = torch.exp(self.curr_log_alpha[module_id]) # Start training with behavior cloning and turn to the classic Soft-Actor Critic # after `bc_iters` of training iterations. if ( self.metrics.peek((ALL_MODULES, TRAINING_ITERATION), default=0) >= config.bc_iters ): actor_loss = torch.mean( alpha.detach() * fwd_out["logp_resampled"] - fwd_out["q_curr"] ) else: # Use log-probabilities of the current action distribution to clone # the behavior policy (selected actions in data) in the first `bc_iters` # training iterations. bc_logps_curr = action_dist_curr.logp(batch[Columns.ACTIONS]) actor_loss = torch.mean( alpha.detach() * fwd_out["logp_resampled"] - bc_logps_curr ) # The critic loss is composed of the standard SAC Critic L2 loss and the # CQL entropy loss. # Get the Q-values for the actually selected actions in the offline data. # In the critic loss we use these as predictions. q_selected = fwd_out[QF_PREDS] if config.twin_q: q_twin_selected = fwd_out[QF_TWIN_PREDS] if not config.deterministic_backup: q_next = ( fwd_out["q_target_next"] - alpha.detach() * fwd_out["logp_next_resampled"] ) else: q_next = fwd_out["q_target_next"] # Now mask all Q-values with terminating next states in the targets. q_next_masked = (1.0 - batch[Columns.TERMINATEDS].float()) * q_next # Compute the right hand side of the Bellman equation. Detach this node # from the computation graph as we do not want to backpropagate through # the target network when optimizing the Q loss. # TODO (simon, sven): Kumar et al. (2020) use here also a reward scaler. q_selected_target = ( # TODO (simon): Add an `n_step` option to the `AddNextObsToBatch` connector. batch[Columns.REWARDS] # TODO (simon): Implement n_step. + (config.gamma) * q_next_masked ).detach() # Calculate the TD error. td_error = torch.abs(q_selected - q_selected_target) # Calculate a TD-error for twin-Q values, if needed. if config.twin_q: td_error += torch.abs(q_twin_selected - q_selected_target) # Rescale the TD error td_error *= 0.5 # MSBE loss for the critic(s) (i.e. Q, see eqs. (7-8) Haarnoja et al. (2018)). # Note, this needs a sample from the current policy given the next state. # Note further, we could also use here the Huber loss instead of the MSE. # TODO (simon): Add the huber loss as an alternative (SAC uses it). sac_critic_loss = torch.nn.MSELoss(reduction="mean")( q_selected, q_selected_target, ) if config.twin_q: sac_critic_twin_loss = torch.nn.MSELoss(reduction="mean")( q_twin_selected, q_selected_target, ) # Now calculate the CQL loss (we use the entropy version of the CQL algorithm). # Note, the entropy version performs best in shown experiments. # Compute the log-probabilities for the random actions (note, we generate random # actions (from the mu distribution as named in Kumar et al. (2020))). # Note, all actions, action log-probabilities and Q-values are already computed # by the module's `_forward_train` method. # TODO (simon): This is the density for a discrete uniform, however, actions # come from a continuous one. So actually this density should use (1/(high-low)) # instead of (1/2). random_density = torch.log( torch.pow( 0.5, torch.tensor( fwd_out["actions_curr_repeat"].shape[-1], device=fwd_out["actions_curr_repeat"].device, ), ) ) # Merge all Q-values and subtract the log-probabilities (note, we use the # entropy version of CQL). q_repeat = torch.cat( [ fwd_out["q_rand_repeat"] - random_density, fwd_out["q_next_repeat"] - fwd_out["logps_next_repeat"].detach(), fwd_out["q_curr_repeat"] - fwd_out["logps_curr_repeat"].detach(), ], dim=1, ) cql_loss = ( torch.logsumexp(q_repeat / config.temperature, dim=1).mean() * config.min_q_weight * config.temperature ) cql_loss -= q_selected.mean() * config.min_q_weight # Add the CQL loss term to the SAC loss term. critic_loss = sac_critic_loss + cql_loss # If a twin Q-value function is implemented calculated its CQL loss. if config.twin_q: q_twin_repeat = torch.cat( [ fwd_out["q_twin_rand_repeat"] - random_density, fwd_out["q_twin_next_repeat"] - fwd_out["logps_next_repeat"].detach(), fwd_out["q_twin_curr_repeat"] - fwd_out["logps_curr_repeat"].detach(), ], dim=1, ) cql_twin_loss = ( torch.logsumexp(q_twin_repeat / config.temperature, dim=1).mean() * config.min_q_weight * config.temperature ) cql_twin_loss -= q_twin_selected.mean() * config.min_q_weight # Add the CQL loss term to the SAC loss term. critic_twin_loss = sac_critic_twin_loss + cql_twin_loss # TODO (simon): Check, if we need to implement here also a Lagrangian # loss. total_loss = actor_loss + critic_loss + alpha_loss # Add the twin critic loss to the total loss, if needed. if config.twin_q: # Reweigh the critic loss terms in the total loss. total_loss += 0.5 * critic_twin_loss - 0.5 * critic_loss # Log important loss stats (reduce=mean (default), but with window=1 # in order to keep them history free). self.metrics.log_dict( { POLICY_LOSS_KEY: actor_loss, QF_LOSS_KEY: critic_loss, # TODO (simon): Add these keys to SAC Learner. "cql_loss": cql_loss, "alpha_loss": alpha_loss, "alpha_value": alpha[0], "log_alpha_value": torch.log(alpha)[0], "target_entropy": self.target_entropy[module_id], LOGPS_KEY: torch.mean( fwd_out["logp_resampled"] ), # torch.mean(logps_curr), QF_MEAN_KEY: torch.mean(fwd_out["q_curr_repeat"]), QF_MAX_KEY: torch.max(fwd_out["q_curr_repeat"]), QF_MIN_KEY: torch.min(fwd_out["q_curr_repeat"]), TD_ERROR_MEAN_KEY: torch.mean(td_error), }, key=module_id, window=1, # <- single items (should not be mean/ema-reduced over time). ) self._temp_losses[(module_id, POLICY_LOSS_KEY)] = actor_loss self._temp_losses[(module_id, QF_LOSS_KEY)] = critic_loss self._temp_losses[(module_id, "alpha_loss")] = alpha_loss # TODO (simon): Add loss keys for langrangian, if needed. # TODO (simon): Add only here then the Langrange parameter optimization. if config.twin_q: self.metrics.log_value( key=(module_id, QF_TWIN_LOSS_KEY), value=critic_twin_loss, window=1, # <- single items (should not be mean/ema-reduced over time). ) self._temp_losses[(module_id, QF_TWIN_LOSS_KEY)] = critic_twin_loss # Return the total loss. return total_loss @override(SACTorchLearner) def compute_gradients( self, loss_per_module: Dict[ModuleID, TensorType], **kwargs ) -> ParamDict: grads = {} for module_id in set(loss_per_module.keys()) - {ALL_MODULES}: # Loop through optimizers registered for this module. for optim_name, optim in self.get_optimizers_for_module(module_id): # Zero the gradients. Note, we need to reset the gradients b/c # each component for a module operates on the same graph. optim.zero_grad(set_to_none=True) # Compute the gradients for the component and module. loss_tensor = self._temp_losses.pop((module_id, optim_name + "_loss")) loss_tensor.backward( retain_graph=False if optim_name in ["policy", "alpha"] else True ) # Store the gradients for the component and module. # TODO (simon): Check another time the graph for overlapping # gradients. grads.update( { pid: grads[pid] + p.grad.clone() if pid in grads else p.grad.clone() for pid, p in self.filter_param_dict_for_optimizer( self._params, optim ).items() } ) assert not self._temp_losses return grads
CQLTorchLearner
python
pytorch__pytorch
torch/_dynamo/source.py
{ "start": 9596, "end": 9694 }
class ____(WeakRefCallSource): pass @dataclasses.dataclass(frozen=True)
CallFunctionNoArgsSource
python
getsentry__sentry
tests/sentry/integrations/middleware/hybrid_cloud/test_base.py
{ "start": 1358, "end": 9784 }
class ____(TestCase): response_handler = MagicMock() region_config = [ Region("us", 1, "https://us.testserver", RegionCategory.MULTI_TENANT), Region("eu", 2, "https://eu.testserver", RegionCategory.MULTI_TENANT), ] factory = RequestFactory() def setUp(self) -> None: self.request = self.factory.get("/extensions/slack/webhook/") self.parser = ExampleRequestParser(self.request, self.response_handler) @override_settings(SILO_MODE=SiloMode.MONOLITH) def test_fails_in_monolith_mode(self) -> None: with raises(SiloLimit.AvailabilityError): self.parser.get_response_from_control_silo() with raises(SiloLimit.AvailabilityError): self.parser.get_responses_from_region_silos(regions=self.region_config) @override_settings(SILO_MODE=SiloMode.REGION) def test_fails_in_region_mode(self) -> None: with raises(SiloLimit.AvailabilityError): self.parser.get_response_from_control_silo() with raises(SiloLimit.AvailabilityError): self.parser.get_responses_from_region_silos(regions=self.region_config) @override_settings(SILO_MODE=SiloMode.CONTROL) def test_get_response_from_control_silo(self) -> None: self.response_handler.reset_mock() response = self.parser.get_response_from_control_silo() assert self.response_handler.called assert response == self.response_handler(self.request) @override_settings(SILO_MODE=SiloMode.CONTROL) @patch.object(BaseRequestParser, "get_response_from_region_silo") def test_get_responses_from_region_silos(self, mock__get_response: MagicMock) -> None: mock__get_response.side_effect = lambda region: region.name response_map = self.parser.get_responses_from_region_silos(regions=self.region_config) assert mock__get_response.call_count == len(self.region_config) for region in self.region_config: assert response_map[region.name].response == region.name @override_settings(SILO_MODE=SiloMode.CONTROL) @patch.object(BaseRequestParser, "get_response_from_region_silo") def test_get_responses_from_region_silos_with_partial_failure( self, mock__get_response: MagicMock ) -> None: mock__get_response.side_effect = lambda region: error_regions(region, ["eu"]) response_map = self.parser.get_responses_from_region_silos(regions=self.region_config) assert mock__get_response.call_count == len(self.region_config) assert response_map["us"].response == "us" assert type(response_map["eu"].error) is SiloLimit.AvailabilityError @override_settings(SILO_MODE=SiloMode.CONTROL) @patch.object(BaseRequestParser, "get_response_from_region_silo") def test_get_responses_from_region_silos_with_complete_failure( self, mock__get_response: MagicMock ) -> None: mock__get_response.side_effect = lambda region: error_regions(region, ["us", "eu"]) self.response_handler.reset_mock() response_map = self.parser.get_responses_from_region_silos(regions=self.region_config) assert mock__get_response.call_count == len(self.region_config) for region in self.region_config: assert type(response_map[region.name].error) is SiloLimit.AvailabilityError @override_settings(SILO_MODE=SiloMode.CONTROL) def test_get_response_from_webhookpayload_creation(self) -> None: with pytest.raises(AttributeError): BaseRequestParser(self.request, self.response_handler).get_response_from_webhookpayload( regions=self.region_config ) class MockParser(BaseRequestParser): webhook_identifier = WebhookProviderIdentifier.SLACK provider = "slack" parser = MockParser(self.request, self.response_handler) response = parser.get_response_from_webhookpayload(regions=self.region_config) assert response.status_code == status.HTTP_202_ACCEPTED payloads = WebhookPayload.objects.all() assert len(payloads) == 2 for payload in payloads: assert payload.region_name in ["us", "eu"] assert payload.mailbox_name == "slack:0" assert payload.request_path assert payload.request_method assert payload.destination_type == DestinationType.SENTRY_REGION @override_settings(SILO_MODE=SiloMode.CONTROL) @override_options({"codecov.forward-webhooks.rollout": 1.0}) def test_forward_to_codecov(self) -> None: class MockParser(BaseRequestParser): webhook_identifier = WebhookProviderIdentifier.GITHUB provider = "github" parser = MockParser(self.request, self.response_handler) parser.forward_to_codecov(external_id="1") payloads = WebhookPayload.objects.all() assert len(payloads) == 1 for payload in payloads: assert payload.region_name is None assert payload.mailbox_name == "github:codecov:1" assert payload.request_path assert payload.request_method assert payload.destination_type == DestinationType.CODECOV @override_settings(SILO_MODE=SiloMode.CONTROL) def test_get_organizations_from_integration_success(self) -> None: integration = self.create_integration( organization=self.organization, provider="test_provider", external_id="test_external_id", ) # Create additional org integration to test multiple orgs other_org = self.create_organization() OrganizationIntegration.objects.create( organization_id=other_org.id, integration_id=integration.id, status=ObjectStatus.ACTIVE, ) parser = ExampleRequestParser(self.request, self.response_handler) organizations = parser.get_organizations_from_integration(integration) assert len(organizations) == 2 org_ids = {org.id for org in organizations} assert self.organization.id in org_ids assert other_org.id in org_ids @override_settings(SILO_MODE=SiloMode.CONTROL) @patch("sentry.integrations.middleware.hybrid_cloud.parser.logger.info") def test_get_organizations_from_integration_inactive_org(self, mock_log: MagicMock) -> None: integration = self.create_integration( organization=self.organization, provider="test_provider", external_id="test_external_id", ) other_org = self.create_organization() OrganizationIntegration.objects.create( organization_id=other_org.id, integration_id=integration.id, status=ObjectStatus.DISABLED, ) parser = ExampleRequestParser(self.request, self.response_handler) organizations = parser.get_organizations_from_integration(integration) assert len(organizations) == 1 assert organizations[0].id == self.organization.id @override_settings(SILO_MODE=SiloMode.CONTROL) @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_get_organizations_from_integration_missing_integration( self, mock_record: MagicMock ) -> None: parser = ExampleRequestParser(self.request, self.response_handler) with pytest.raises(Integration.DoesNotExist): parser.get_organizations_from_integration() assert mock_record.call_count == 2 assert_failure_metric(mock_record, Integration.DoesNotExist()) @override_settings(SILO_MODE=SiloMode.CONTROL) @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_get_organizations_from_integration_missing_org_integration( self, mock_record: MagicMock ) -> None: integration = self.create_integration( organization=self.organization, provider="test_provider", external_id="test_external_id", oi_params={"status": ObjectStatus.DISABLED}, ) parser = ExampleRequestParser(self.request, self.response_handler) organizations = parser.get_organizations_from_integration(integration) assert len(organizations) == 0 assert mock_record.call_count == 2 assert_halt_metric(mock_record, MiddlewareHaltReason.ORG_INTEGRATION_DOES_NOT_EXIST)
BaseRequestParserTest
python
huggingface__transformers
src/transformers/models/gpt_bigcode/modeling_gpt_bigcode.py
{ "start": 14451, "end": 15778 }
class ____(PreTrainedModel): config: GPTBigCodeConfig base_model_prefix = "transformer" supports_gradient_checkpointing = True _no_split_modules = ["GPTBigCodeBlock"] _skip_keys_device_placement = "past_key_values" _supports_flash_attn = True _supports_sdpa = True def __init__(self, *inputs, **kwargs): super().__init__(*inputs, **kwargs) @torch.no_grad() def _init_weights(self, module): """Initialize the weights.""" super()._init_weights(module) if isinstance(module, (GPTBigCodeMLP, GPTBigCodeAttention)): # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme: # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers. # > -- GPT-2 :: https://openai.com/blog/better-language-models/ # # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py init.normal_( module.c_proj.weight, mean=0.0, std=self.config.initializer_range / math.sqrt(2 * self.config.n_layer) ) @auto_docstring
GPTBigCodePreTrainedModel
python
run-llama__llama_index
llama-index-core/llama_index/core/program/llm_program.py
{ "start": 374, "end": 4641 }
class ____(BasePydanticProgram[Model]): """ LLM Text Completion Program. Uses generic LLM text completion + an output parser to generate a structured output. """ def __init__( self, output_parser: BaseOutputParser, output_cls: Type[Model], prompt: BasePromptTemplate, llm: LLM, verbose: bool = False, ) -> None: self._output_parser = output_parser self._output_cls = output_cls self._llm = llm self._prompt = prompt self._verbose = verbose self._prompt.output_parser = output_parser @classmethod def from_defaults( cls, output_parser: Optional[BaseOutputParser] = None, output_cls: Optional[Type[Model]] = None, prompt_template_str: Optional[str] = None, prompt: Optional[BasePromptTemplate] = None, llm: Optional[LLM] = None, verbose: bool = False, **kwargs: Any, ) -> "LLMTextCompletionProgram[Model]": llm = llm or Settings.llm if prompt is None and prompt_template_str is None: raise ValueError("Must provide either prompt or prompt_template_str.") if prompt is not None and prompt_template_str is not None: raise ValueError("Must provide either prompt or prompt_template_str.") if prompt_template_str is not None: prompt = PromptTemplate(prompt_template_str) # decide default output class if not set if output_cls is None: if not isinstance(output_parser, PydanticOutputParser): raise ValueError("Output parser must be PydanticOutputParser.") output_cls = output_parser.output_cls else: if output_parser is None: output_parser = PydanticOutputParser(output_cls=output_cls) return cls( output_parser, output_cls, prompt=cast(PromptTemplate, prompt), llm=llm, verbose=verbose, ) @property def output_cls(self) -> Type[Model]: return self._output_cls @property def prompt(self) -> BasePromptTemplate: return self._prompt @prompt.setter def prompt(self, prompt: BasePromptTemplate) -> None: self._prompt = prompt def __call__( self, llm_kwargs: Optional[Dict[str, Any]] = None, *args: Any, **kwargs: Any, ) -> Model: llm_kwargs = llm_kwargs or {} if self._llm.metadata.is_chat_model: messages = self._prompt.format_messages(llm=self._llm, **kwargs) messages = self._llm._extend_messages(messages) chat_response = self._llm.chat(messages, **llm_kwargs) raw_output = chat_response.message.content or "" else: formatted_prompt = self._prompt.format(llm=self._llm, **kwargs) response = self._llm.complete(formatted_prompt, **llm_kwargs) raw_output = response.text output = self._output_parser.parse(raw_output) if not isinstance(output, self._output_cls): raise ValueError( f"Output parser returned {type(output)} but expected {self._output_cls}" ) return output async def acall( self, llm_kwargs: Optional[Dict[str, Any]] = None, *args: Any, **kwargs: Any, ) -> Model: llm_kwargs = llm_kwargs or {} if self._llm.metadata.is_chat_model: messages = self._prompt.format_messages(llm=self._llm, **kwargs) messages = self._llm._extend_messages(messages) chat_response = await self._llm.achat(messages, **llm_kwargs) raw_output = chat_response.message.content or "" else: formatted_prompt = self._prompt.format(llm=self._llm, **kwargs) response = await self._llm.acomplete(formatted_prompt, **llm_kwargs) raw_output = response.text output = self._output_parser.parse(raw_output) if not isinstance(output, self._output_cls): raise ValueError( f"Output parser returned {type(output)} but expected {self._output_cls}" ) return output
LLMTextCompletionProgram
python
getsentry__sentry
tests/sentry/models/test_featureadoption.py
{ "start": 730, "end": 1173 }
class ____(TestFeatureAdoptionRedisCache): def setUp(self) -> None: # TODO: Once we have properly redis-cluster setup in tests and CI use that For now that's # the simplest way to test non redis-blaster compatibility. self.cache = FeatureAdoptionRedisBackend() self.cache.is_redis_cluster, self.cache.cluster = True, redis_clusters.get("default") self.org_id = 1234
TestFeatureAdoptionRedisClusterCache
python
matplotlib__matplotlib
galleries/examples/user_interfaces/embedding_in_wx2_sgskip.py
{ "start": 1495, "end": 1774 }
class ____(WIT.InspectableApp): def OnInit(self): """Create the main window and insert the custom frame.""" self.Init() frame = CanvasFrame() frame.Show(True) return True if __name__ == "__main__": app = App() app.MainLoop()
App
python
django__django
django/http/request.py
{ "start": 17360, "end": 18941 }
class ____(CaseInsensitiveMapping): HTTP_PREFIX = "HTTP_" # PEP 333 gives two headers which aren't prepended with HTTP_. UNPREFIXED_HEADERS = {"CONTENT_TYPE", "CONTENT_LENGTH"} def __init__(self, environ): headers = {} for header, value in environ.items(): name = self.parse_header_name(header) if name: headers[name] = value super().__init__(headers) def __getitem__(self, key): """Allow header lookup using underscores in place of hyphens.""" return super().__getitem__(key.replace("_", "-")) @classmethod def parse_header_name(cls, header): if header.startswith(cls.HTTP_PREFIX): header = header.removeprefix(cls.HTTP_PREFIX) elif header not in cls.UNPREFIXED_HEADERS: return None return header.replace("_", "-").title() @classmethod def to_wsgi_name(cls, header): header = header.replace("-", "_").upper() if header in cls.UNPREFIXED_HEADERS: return header return f"{cls.HTTP_PREFIX}{header}" @classmethod def to_asgi_name(cls, header): return header.replace("-", "_").upper() @classmethod def to_wsgi_names(cls, headers): return { cls.to_wsgi_name(header_name): value for header_name, value in headers.items() } @classmethod def to_asgi_names(cls, headers): return { cls.to_asgi_name(header_name): value for header_name, value in headers.items() }
HttpHeaders
python
spack__spack
lib/spack/spack/spec.py
{ "start": 221392, "end": 221749 }
class ____(spack.error.UnsatisfiableSpecError): """Raised when a spec architecture conflicts with package constraints.""" def __init__(self, provided, required): super().__init__(provided, required, "architecture") # TODO: get rid of this and be more specific about particular incompatible # dep constraints
UnsatisfiableArchitectureSpecError
python
walkccc__LeetCode
solutions/2813. Maximum Elegance of a K-Length Subsequence/2813.py
{ "start": 0, "end": 1112 }
class ____: def findMaximumElegance(self, items: list[list[int]], k: int) -> int: ans = 0 totalProfit = 0 seenCategories = set() decreasingDuplicateProfits = [] items.sort(reverse=True) for i in range(k): profit, category = items[i] totalProfit += profit if category in seenCategories: decreasingDuplicateProfits.append(profit) else: seenCategories.add(category) ans = totalProfit + len(seenCategories)**2 for i in range(k, len(items)): profit, category = items[i] if category not in seenCategories and decreasingDuplicateProfits: # If this is a new category we haven't seen before, it's worth # considering taking it and replacing the one with the least profit # since it will increase the distinct_categories and potentially result # in a larger total_profit + distinct_categories^2. totalProfit -= decreasingDuplicateProfits.pop() totalProfit += profit seenCategories.add(category) ans = max(ans, totalProfit + len(seenCategories)**2) return ans
Solution
python
getsentry__sentry
tests/sentry/api/endpoints/test_organization_sampling_project_span_counts.py
{ "start": 7054, "end": 8371 }
class ____(MetricsEnhancedPerformanceTestCase): def setUp(self) -> None: super().setUp() self.login_as(user=self.user) self.org = self.create_organization(owner=self.user) self.project_1 = self.create_project(organization=self.org, name="project_1") self.project_2 = self.create_project(organization=self.org, name="project_2") self.project_3 = self.create_project(organization=self.org, name="project_3") self.project_4 = self.create_project(organization=self.org, name="project_4") self.url = reverse( "sentry-api-0-organization-sampling-root-counts", kwargs={"organization_id_or_slug": self.org.slug}, ) @django_db_all def test_get_span_counts_with_ingested_data_30d(self) -> None: with self.feature("organizations:dynamic-sampling-custom"): response = self.client.get( self.url, data={"statsPeriod": "30d"}, ) assert response.status_code == 200 data = response.data # type: ignore[attr-defined] assert data["data"] == [] assert data["meta"] == [] assert data["end"] is None assert data["start"] is None assert data["intervals"] == []
OrganizationSamplingProjectSpanCountsNoMetricsTest
python
HypothesisWorks__hypothesis
hypothesis-python/tests/nocover/test_duplication.py
{ "start": 620, "end": 2053 }
class ____(SearchStrategy): def __init__(self, n): super().__init__() self.n = n def do_draw(self, data): return data.draw_bytes(self.n, self.n) @xfail_on_crosshair(Why.symbolic_outside_context) @pytest.mark.parametrize("n", range(1, 5)) def test_does_not_duplicate_blocks(n): counts = Counter() @given(Blocks(n)) @settings(database=None) def test(b): counts[b] += 1 test() assert set(counts.values()) == {1} @xfail_on_crosshair(Why.other, strict=False) # CrosshairInternal for n>0 @pytest.mark.parametrize("n", range(1, 5)) def test_mostly_does_not_duplicate_blocks_even_when_failing(n): counts = Counter() @settings(database=None) @given(Blocks(n)) def test(b): counts[b] += 1 if len(counts) > 3: raise ValueError try: test() except ValueError: pass # There are two circumstances in which a duplicate is allowed: We replay # the failing test once to check for flakiness, and then we replay the # fully minimized failing test at the end to display the error. The # complication comes from the fact that these may or may not be the same # test case, so we can see either two test cases each run twice or one # test case which has been run three times. assert set(counts.values()) in ({1, 2}, {1, 3}) assert len([k for k, v in counts.items() if v > 1]) <= 2
Blocks
python
redis__redis-py
tests/test_search.py
{ "start": 65444, "end": 70942 }
class ____(SearchTestsBase): @pytest.mark.redismod @pytest.mark.onlynoncluster # NOTE(imalinovskyi): This test contains hardcoded scores valid only for RediSearch 2.8+ @skip_ifmodversion_lt("2.8.0", "search") @skip_if_server_version_gte("7.9.0") def test_scorer(self, client): client.ft().create_index((TextField("description"),)) client.hset( "doc1", mapping={"description": "The quick brown fox jumps over the lazy dog"}, ) client.hset( "doc2", mapping={ "description": "Quick alice was beginning to get very tired of sitting by her quick sister on the bank, and of having nothing to do." # noqa }, ) # default scorer is TFIDF if is_resp2_connection(client): res = client.ft().search(Query("quick").with_scores()) assert 1.0 == res.docs[0].score res = client.ft().search(Query("quick").scorer("TFIDF").with_scores()) assert 1.0 == res.docs[0].score res = client.ft().search( Query("quick").scorer("TFIDF.DOCNORM").with_scores() ) assert 0.14285714285714285 == res.docs[0].score res = client.ft().search(Query("quick").scorer("BM25").with_scores()) assert 0.22471909420069797 == res.docs[0].score res = client.ft().search(Query("quick").scorer("DISMAX").with_scores()) assert 2.0 == res.docs[0].score res = client.ft().search(Query("quick").scorer("DOCSCORE").with_scores()) assert 1.0 == res.docs[0].score res = client.ft().search(Query("quick").scorer("HAMMING").with_scores()) assert 0.0 == res.docs[0].score else: res = client.ft().search(Query("quick").with_scores()) assert 1.0 == res["results"][0]["score"] res = client.ft().search(Query("quick").scorer("TFIDF").with_scores()) assert 1.0 == res["results"][0]["score"] res = client.ft().search( Query("quick").scorer("TFIDF.DOCNORM").with_scores() ) assert 0.14285714285714285 == res["results"][0]["score"] res = client.ft().search(Query("quick").scorer("BM25").with_scores()) assert 0.22471909420069797 == res["results"][0]["score"] res = client.ft().search(Query("quick").scorer("DISMAX").with_scores()) assert 2.0 == res["results"][0]["score"] res = client.ft().search(Query("quick").scorer("DOCSCORE").with_scores()) assert 1.0 == res["results"][0]["score"] res = client.ft().search(Query("quick").scorer("HAMMING").with_scores()) assert 0.0 == res["results"][0]["score"] @pytest.mark.redismod @pytest.mark.onlynoncluster @skip_if_server_version_lt("7.9.0") def test_scorer_with_new_default_scorer(self, client): client.ft().create_index((TextField("description"),)) client.hset( "doc1", mapping={"description": "The quick brown fox jumps over the lazy dog"}, ) client.hset( "doc2", mapping={ "description": "Quick alice was beginning to get very tired of sitting by her quick sister on the bank, and of having nothing to do." # noqa }, ) # default scorer is BM25STD if is_resp2_connection(client): res = client.ft().search(Query("quick").with_scores()) assert 0.23 == pytest.approx(res.docs[0].score, 0.05) res = client.ft().search(Query("quick").scorer("TFIDF").with_scores()) assert 1.0 == res.docs[0].score res = client.ft().search( Query("quick").scorer("TFIDF.DOCNORM").with_scores() ) assert 0.14285714285714285 == res.docs[0].score res = client.ft().search(Query("quick").scorer("BM25").with_scores()) assert 0.22471909420069797 == res.docs[0].score res = client.ft().search(Query("quick").scorer("DISMAX").with_scores()) assert 2.0 == res.docs[0].score res = client.ft().search(Query("quick").scorer("DOCSCORE").with_scores()) assert 1.0 == res.docs[0].score res = client.ft().search(Query("quick").scorer("HAMMING").with_scores()) assert 0.0 == res.docs[0].score else: res = client.ft().search(Query("quick").with_scores()) assert 0.23 == pytest.approx(res["results"][0]["score"], 0.05) res = client.ft().search(Query("quick").scorer("TFIDF").with_scores()) assert 1.0 == res["results"][0]["score"] res = client.ft().search( Query("quick").scorer("TFIDF.DOCNORM").with_scores() ) assert 0.14285714285714285 == res["results"][0]["score"] res = client.ft().search(Query("quick").scorer("BM25").with_scores()) assert 0.22471909420069797 == res["results"][0]["score"] res = client.ft().search(Query("quick").scorer("DISMAX").with_scores()) assert 2.0 == res["results"][0]["score"] res = client.ft().search(Query("quick").scorer("DOCSCORE").with_scores()) assert 1.0 == res["results"][0]["score"] res = client.ft().search(Query("quick").scorer("HAMMING").with_scores()) assert 0.0 == res["results"][0]["score"]
TestScorers
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_vision.py
{ "start": 15105, "end": 16270 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.vision.CloudVisionHook") def test_minimal_green_path_for_one_image(self, mock_hook): op = CloudVisionImageAnnotateOperator(request=ANNOTATE_REQUEST_TEST, task_id="id") op.execute(context=None) mock_hook.assert_called_once_with( gcp_conn_id=GCP_CONN_ID, impersonation_chain=None, ) mock_hook.return_value.annotate_image.assert_called_once_with( request=ANNOTATE_REQUEST_TEST, retry=DEFAULT, timeout=None ) @mock.patch("airflow.providers.google.cloud.operators.vision.CloudVisionHook") def test_minimal_green_path_for_batch(self, mock_hook): op = CloudVisionImageAnnotateOperator(request=ANNOTATE_REQUEST_BATCH_TEST, task_id="id") op.execute(context=None) mock_hook.assert_called_once_with( gcp_conn_id=GCP_CONN_ID, impersonation_chain=None, ) mock_hook.return_value.batch_annotate_images.assert_called_once_with( requests=ANNOTATE_REQUEST_BATCH_TEST, retry=DEFAULT, timeout=None )
TestCloudVisionAnnotateImageOperator
python
doocs__leetcode
solution/0400-0499/0469.Convex Polygon/Solution.py
{ "start": 0, "end": 540 }
class ____: def isConvex(self, points: List[List[int]]) -> bool: n = len(points) pre = cur = 0 for i in range(n): x1 = points[(i + 1) % n][0] - points[i][0] y1 = points[(i + 1) % n][1] - points[i][1] x2 = points[(i + 2) % n][0] - points[i][0] y2 = points[(i + 2) % n][1] - points[i][1] cur = x1 * y2 - x2 * y1 if cur != 0: if cur * pre < 0: return False pre = cur return True
Solution
python
dagster-io__dagster
python_modules/libraries/dagster-k8s/dagster_k8s/pipes.py
{ "start": 13704, "end": 33341 }
class ____(PipesClient, TreatAsResourceParam): """A pipes client for launching kubernetes pods. By default context is injected via environment variables and messages are parsed out of the pod logs, with other logs forwarded to stdout of the orchestration process. The first container within the containers list of the pod spec is expected (or set) to be the container prepared for pipes protocol communication. Args: env (Optional[Mapping[str, str]]): An optional dict of environment variables to pass to the subprocess. context_injector (Optional[PipesContextInjector]): A context injector to use to inject context into the k8s container process. Defaults to :py:class:`PipesEnvContextInjector`. message_reader (Optional[PipesMessageReader]): A message reader to use to read messages from the k8s container process. Defaults to :py:class:`PipesK8sPodLogsMessageReader`. load_incluster_config (Optional[bool]): Whether this client is expected to be running from inside a kubernetes cluster and should load config using ``kubernetes.config.load_incluster_config``. Otherwise ``kubernetes.config.load_kube_config`` is used with the kubeconfig_file argument. Default: None kubeconfig_file (Optional[str]): The value to pass as the config_file argument to ``kubernetes.config.load_kube_config``. Default: None. kube_context (Optional[str]): The value to pass as the context argument to ``kubernetes.config.load_kube_config``. Default: None. poll_interval (Optional[float]): How many seconds to wait between requests when polling the kubernetes API Default: 10. """ def __init__( self, env: Optional[Mapping[str, str]] = None, context_injector: Optional[PipesContextInjector] = None, message_reader: Optional[PipesMessageReader] = None, load_incluster_config: Optional[bool] = None, kubeconfig_file: Optional[str] = None, kube_context: Optional[str] = None, poll_interval: Optional[float] = DEFAULT_WAIT_BETWEEN_ATTEMPTS, ): self.env = check.opt_mapping_param(env, "env", key_type=str, value_type=str) self.context_injector = ( check.opt_inst_param( context_injector, "context_injector", PipesContextInjector, ) or PipesEnvContextInjector() ) self.message_reader = ( check.opt_inst_param(message_reader, "message_reader", PipesMessageReader) or PipesK8sPodLogsMessageReader() ) if load_incluster_config: check.invariant( kube_context is None and kubeconfig_file is None, "kubeconfig_file and kube_context should not be set when load_incluster_config is" " True ", ) self.load_incluster_config = check.opt_bool_param( load_incluster_config, "load_incluster_config" ) self.kubeconfig_file = check.opt_str_param(kubeconfig_file, "kubeconfig_file") self.kube_context = check.opt_str_param(kube_context, "kube_context") self.poll_interval = check.float_param(poll_interval, "poll_interval") @classmethod def _is_dagster_maintained(cls) -> bool: return True def _load_k8s_config(self): # when nothing is specified if ( self.load_incluster_config is None and self.kubeconfig_file is None and self.kube_context is None ): # check for env var that is always set by kubernetes and if present use in cluster if os.getenv("KUBERNETES_SERVICE_HOST"): kubernetes.config.load_incluster_config() # otherwise do default load else: kubernetes.config.load_kube_config() elif self.load_incluster_config: kubernetes.config.load_incluster_config() else: kubernetes.config.load_kube_config( config_file=self.kubeconfig_file, context=self.kube_context, ) @public def run( # pyright: ignore[reportIncompatibleMethodOverride] self, *, context: Union[OpExecutionContext, AssetExecutionContext], extras: Optional[PipesExtras] = None, image: Optional[str] = None, command: Optional[Union[str, Sequence[str]]] = None, namespace: Optional[str] = None, env: Optional[Mapping[str, str]] = None, base_pod_meta: Optional[Mapping[str, Any]] = None, base_pod_spec: Optional[Mapping[str, Any]] = None, ignore_containers: Optional[set] = None, enable_multi_container_logs: bool = False, pod_wait_timeout: float = DEFAULT_WAIT_TIMEOUT, ) -> PipesClientCompletedInvocation: """Publish a kubernetes pod and wait for it to complete, enriched with the pipes protocol. Args: context (Union[OpExecutionContext, AssetExecutionContext]): The execution context. image (Optional[str]): The image to set the first container in the pod spec to use. command (Optional[Union[str, Sequence[str]]]): The command to set the first container in the pod spec to use. namespace (Optional[str]): Which kubernetes namespace to use, defaults to the current namespace if running inside a kubernetes cluster or falling back to "default". env (Optional[Mapping[str,str]]): A mapping of environment variable names to values to set on the first container in the pod spec, on top of those configured on resource. base_pod_meta (Optional[Mapping[str, Any]]): Raw k8s config for the k8s pod's metadata (https://kubernetes.io/docs/reference/kubernetes-api/common-definitions/object-meta/#ObjectMeta) Keys can either snake_case or camelCase. The name value will be overridden. base_pod_spec (Optional[Mapping[str, Any]]): Raw k8s config for the k8s pod's pod spec (https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/pod-v1/#PodSpec). Keys can either snake_case or camelCase. The dagster context will be readable from any container within the pod, but only the first container in the `pod.spec.containers` will be able to communicate back to Dagster. extras (Optional[PipesExtras]): Extra values to pass along as part of the ext protocol. context_injector (Optional[PipesContextInjector]): Override the default ext protocol context injection. message_reader (Optional[PipesMessageReader]): Override the default ext protocol message reader. ignore_containers (Optional[Set]): Ignore certain containers from waiting for termination. Defaults to None. enable_multi_container_logs (bool): Whether or not to enable multi-container log consumption. pod_wait_timeout (float): How long to wait for the pod to terminate before raising an exception. Defaults to 24h. Set to 0 to disable. Returns: PipesClientCompletedInvocation: Wrapper containing results reported by the external process. """ self._load_k8s_config() client = DagsterKubernetesClient.production_client() with open_pipes_session( context=context, extras=extras, context_injector=self.context_injector, message_reader=self.message_reader, ) as pipes_session: namespace = namespace or detect_current_namespace(self.kubeconfig_file) or "default" pod_name = get_pod_name(context.run_id, context.op.name) pod_body = build_pod_body( pod_name=pod_name, image=image, command=command, env_vars={ **pipes_session.get_bootstrap_env_vars(), **(self.env or {}), **(env or {}), }, base_pod_meta=base_pod_meta, base_pod_spec=base_pod_spec, ) client.core_api.create_namespaced_pod(namespace, pod_body) try: # Consume pod logs if possible with self.consume_pod_logs( context=context, client=client, namespace=namespace, pod_name=pod_name, enable_multi_container_logs=enable_multi_container_logs, ): # wait until the pod is fully terminated (or raise an exception if it failed) client.wait_for_pod( pod_name, namespace, wait_for_state=WaitForPodState.Terminated, ignore_containers=ignore_containers, wait_time_between_attempts=self.poll_interval, wait_timeout=pod_wait_timeout, ) finally: client.core_api.delete_namespaced_pod(pod_name, namespace) return PipesClientCompletedInvocation(pipes_session) @contextmanager def consume_pod_logs( self, context: Union[OpExecutionContext, AssetExecutionContext], client: DagsterKubernetesClient, namespace: str, pod_name: str, enable_multi_container_logs: bool = False, ) -> Iterator: """Consume pod logs in the background if possible simple context manager to setup pod log consumption. This will be a no-op if the message_reader is of the wrong type. Args: context (Union[OpExecutionContext, AssetExecutionContext]): The execution context. client (kubernetes.client): _description_ namespace (str): The namespace the pod lives in pod_name (str): The name of the Pipes Pod enable_multi_container_logs (bool): Whether or not to enable multi-container log consumption """ if isinstance(self.message_reader, PipesK8sPodLogsMessageReader): # We need to wait for the pod to start up so that the log streaming is successful afterwards. client.wait_for_pod( pod_name, namespace, wait_for_state=WaitForPodState.Ready, wait_time_between_attempts=self.poll_interval, # After init container gains a status in the first while loop, there is still a check for # the ready state in the second while loop, which respects the below timeout only. # Very rarely, the pod will be Evicted there and we have to wait the default, unless set. wait_timeout=WAIT_TIMEOUT_FOR_READY, ) if enable_multi_container_logs: with self.message_reader.async_consume_pod_logs( context=context, core_api=client.core_api, namespace=namespace, pod_name=pod_name, ): yield return else: self.message_reader.consume_pod_logs( context=context, core_api=client.core_api, namespace=namespace, pod_name=pod_name, ) yield def build_pod_body( pod_name: str, image: Optional[str], command: Optional[Union[str, Sequence[str]]], env_vars: Mapping[str, str], base_pod_meta: Optional[Mapping[str, Any]], base_pod_spec: Optional[Mapping[str, Any]], ): meta = { **(k8s_snake_case_dict(kubernetes.client.V1ObjectMeta, base_pod_meta or {})), "name": pod_name, } if "labels" in meta: meta["labels"] = {**get_common_labels(), **meta["labels"]} else: meta["labels"] = get_common_labels() spec = {**k8s_snake_case_dict(kubernetes.client.V1PodSpec, base_pod_spec or {})} if "containers" not in spec: spec["containers"] = [{}] if "restart_policy" not in spec: spec["restart_policy"] = "Never" elif spec["restart_policy"] == "Always": raise DagsterInvariantViolationError( "A restart policy of Always is not allowed, computations are expected to complete." ) containers = spec["containers"] init_containers = spec.get("init_containers") or [] if "image" not in spec["containers"][0] and not image: raise DagsterInvariantViolationError( "Must specify image property or provide base_pod_spec with one set." ) # We set the container name for the first container in the list if it is not set. # There will be a validation error below for other containers. if "name" not in containers[0]: containers[0]["name"] = DEFAULT_CONTAINER_NAME if not init_containers and len(containers) == 1: if image: containers[0]["image"] = image if command: containers[0]["command"] = command else: if image: raise DagsterInvariantViolationError( "Should specify 'image' via 'base_pod_spec' when specifying multiple containers" ) if command: raise DagsterInvariantViolationError( "Should specify 'command' via 'base_pod_spec' when specifying multiple containers" ) for container_type, containers_ in { "containers": containers, "init_containers": init_containers, }.items(): for i, container in enumerate(containers_): for key in ["name", "image"]: if key not in container: raise DagsterInvariantViolationError( f"Must provide base_pod_spec with {container_type}[{i}].{key} property set." ) if "env" not in containers[0]: containers[0]["env"] = [] # Extend the env variables for the first container containers[0]["env"].extend({"name": k, "value": v} for k, v in env_vars.items()) if DAGSTER_PIPES_CONTEXT_ENV_VAR in env_vars: # Add the dagster context to the remaining containers for container in containers[1:] + init_containers: if "env" not in container: container["env"] = [] container["env"].append( { "name": DAGSTER_PIPES_CONTEXT_ENV_VAR, "value": env_vars[DAGSTER_PIPES_CONTEXT_ENV_VAR], } ) for env_var in container["env"]: # If the user configures DAGSTER_PIPES_MESSAGES env var, don't replace it as # they may want to configure writing messages to a file and store it somewhere # or pass it within a container through a shared volume. if env_var["name"] == DAGSTER_PIPES_MESSAGES_ENV_VAR: break else: # Default to writing messages to /dev/null within the pipes session so that # they don't need to do anything special if the want to read the pipes context # by using `with open_dagster_pipes()`. container["env"].append( { "name": DAGSTER_PIPES_MESSAGES_ENV_VAR, "value": _DEV_NULL_MESSAGE_WRITER, } ) return k8s_model_from_dict( kubernetes.client.V1Pod, { "metadata": meta, "spec": spec, }, ) def _process_log_stream(stream: Iterator[bytes]) -> Iterator[LogItem]: """This expects the logs to be of the format b'<timestamp> <msg>' and only the '<msg>' is forwarded to Dagster. If the <timestamp> is not there then the lines will be joined together. There is a limitation that the first item in the stream needs to always contain a timestamp as the first element. The timestamp is expected to be in '2024-03-22T02:17:29.885548Z' format and if the subsecond part will be truncated to microseconds. If we fail parsing the timestamp, then the priority will be set to zero in order to not drop any log items. Args: stream (Iterator[bytes]): A stream of log chunks Yields: Iterator[LogItem]: A log containing the timestamp and msg """ timestamp = "" log = "" for log_chunk in stream: for line in log_chunk.decode("utf-8").split("\n"): maybe_timestamp, _, tail = line.partition(" ") if not timestamp: # The first item in the stream will always have a timestamp. timestamp = maybe_timestamp log = tail elif maybe_timestamp == timestamp: # We have multiple messages with the same timestamp in this chunk, add them separated # with a new line log += f"\n{tail}" elif not ( len(maybe_timestamp) == len(timestamp) and _is_kube_timestamp(maybe_timestamp) ): # The line is continuation of a long line that got truncated and thus doesn't # have a timestamp in the beginning of the line. # Since all timestamps in the RFC format returned by Kubernetes have the same # length (when represented as strings) we know that the value won't be a timestamp # if the string lengths differ, however if they do not differ, we need to parse the # timestamp. log += line else: # New log line has been observed, send in the next cycle yield LogItem(timestamp=timestamp, log=log) timestamp = maybe_timestamp log = tail # Send the last message that we were building if log or timestamp: yield LogItem(timestamp=timestamp, log=log) def _is_kube_timestamp(maybe_timestamp: str) -> bool: # This extra stripping logic is necessary, as Python's strptime fn doesn't # handle valid ISO 8601 timestamps with nanoseconds which we receive in k8s # e.g. 2024-03-22T02:17:29.185548486Z # This is likely fine. We're just trying to confirm whether or not it's a # valid timestamp, not trying to parse it with full correctness. if maybe_timestamp.endswith("Z"): maybe_timestamp = maybe_timestamp[:-1] # Strip the "Z" if "." in maybe_timestamp: # Split at the decimal point to isolate the fractional seconds date_part, frac_part = maybe_timestamp.split(".") maybe_timestamp = f"{date_part}.{frac_part[:6]}Z" else: maybe_timestamp = f"{maybe_timestamp}Z" # Add the "Z" back if no fractional part try: datetime.strptime(maybe_timestamp, "%Y-%m-%dT%H:%M:%S.%fZ") return True except ValueError: return False else: try: datetime.strptime(maybe_timestamp, "%Y-%m-%dT%H:%M:%S%z") return True except ValueError: return False
PipesK8sClient
python
protocolbuffers__protobuf
python/google/protobuf/message.py
{ "start": 815, "end": 14917 }
class ____(object): """Abstract base class for protocol messages. Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below. """ # TODO: Link to an HTML document here. # TODO: Document that instances of this class will also # have an Extensions attribute with __getitem__ and __setitem__. # Again, not sure how to best convey this. # TODO: Document these fields and methods. __slots__ = [] #: The :class:`google.protobuf.Descriptor` # for this message type. DESCRIPTOR = None def __deepcopy__(self, memo=None): clone = type(self)() clone.MergeFrom(self) return clone def __dir__(self): """Provides the list of all accessible Message attributes.""" message_attributes = set(super().__dir__()) # TODO: Remove this once the UPB implementation is improved. # The UPB proto implementation currently doesn't provide proto fields as # attributes and they have to added. if self.DESCRIPTOR is not None: for field in self.DESCRIPTOR.fields: message_attributes.add(field.name) # The Fast C++ proto implementation provides inaccessible attributes that # have to be removed. for attribute in _INCONSISTENT_MESSAGE_ATTRIBUTES: if attribute not in message_attributes: continue try: getattr(self, attribute) except AttributeError: message_attributes.remove(attribute) return sorted(message_attributes) def __eq__(self, other_msg): """Recursively compares two messages by value and structure.""" raise NotImplementedError def __ne__(self, other_msg): # Can't just say self != other_msg, since that would infinitely recurse. :) return not self == other_msg def __hash__(self): raise TypeError('unhashable object') def __str__(self): """Outputs a human-readable representation of the message.""" raise NotImplementedError def __unicode__(self): """Outputs a human-readable representation of the message.""" raise NotImplementedError def __contains__(self, field_name_or_key): """Checks if a certain field is set for the message. Has presence fields return true if the field is set, false if the field is not set. Fields without presence do raise `ValueError` (this includes repeated fields, map fields, and implicit presence fields). If field_name is not defined in the message descriptor, `ValueError` will be raised. Note: WKT Struct checks if the key is contained in fields. ListValue checks if the item is contained in the list. Args: field_name_or_key: For Struct, the key (str) of the fields map. For ListValue, any type that may be contained in the list. For other messages, name of the field (str) to check for presence. Returns: bool: For Struct, whether the item is contained in fields. For ListValue, whether the item is contained in the list. For other message, whether a value has been set for the named field. Raises: ValueError: For normal messages, if the `field_name_or_key` is not a member of this message or `field_name_or_key` is not a string. """ raise NotImplementedError def MergeFrom(self, other_msg): """Merges the contents of the specified message into current message. This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged. Args: other_msg (Message): A message to merge into the current message. """ raise NotImplementedError def CopyFrom(self, other_msg): """Copies the content of the specified message into the current message. The method clears the current message and then merges the specified message using MergeFrom. Args: other_msg (Message): A message to copy into the current one. """ if self is other_msg: return self.Clear() self.MergeFrom(other_msg) def Clear(self): """Clears all data that was set in the message.""" raise NotImplementedError def SetInParent(self): """Mark this as present in the parent. This normally happens automatically when you assign a field of a sub-message, but sometimes you want to make the sub-message present while keeping it empty. If you find yourself using this, you may want to reconsider your design. """ raise NotImplementedError def IsInitialized(self): """Checks if the message is initialized. Returns: bool: The method returns True if the message is initialized (i.e. all of its required fields are set). """ raise NotImplementedError # TODO: MergeFromString() should probably return None and be # implemented in terms of a helper that returns the # of bytes read. Our # deserialization routines would use the helper when recursively # deserializing, but the end user would almost always just want the no-return # MergeFromString(). def MergeFromString(self, serialized): """Merges serialized protocol buffer data into this message. When we find a field in `serialized` that is already present in this message: - If it's a "repeated" field, we append to the end of our list. - Else, if it's a scalar, we overwrite our field. - Else, (it's a nonrepeated composite), we recursively merge into the existing composite. Args: serialized (bytes): Any object that allows us to call ``memoryview(serialized)`` to access a string of bytes using the buffer interface. Returns: int: The number of bytes read from `serialized`. For non-group messages, this will always be `len(serialized)`, but for messages which are actually groups, this will generally be less than `len(serialized)`, since we must stop when we reach an ``END_GROUP`` tag. Note that if we *do* stop because of an ``END_GROUP`` tag, the number of bytes returned does not include the bytes for the ``END_GROUP`` tag information. Raises: DecodeError: if the input cannot be parsed. """ # TODO: Document handling of unknown fields. # TODO: When we switch to a helper, this will return None. raise NotImplementedError def ParseFromString(self, serialized): """Parse serialized protocol buffer data in binary form into this message. Like :func:`MergeFromString()`, except we clear the object first. Raises: message.DecodeError if the input cannot be parsed. """ self.Clear() return self.MergeFromString(serialized) def SerializeToString(self, **kwargs): """Serializes the protocol message to a binary string. Keyword Args: deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys. Returns: A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized). Raises: EncodeError: if the message isn't initialized (see :func:`IsInitialized`). """ raise NotImplementedError def SerializePartialToString(self, **kwargs): """Serializes the protocol message to a binary string. This method is similar to SerializeToString but doesn't check if the message is initialized. Keyword Args: deterministic (bool): If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys. Returns: bytes: A serialized representation of the partial message. """ raise NotImplementedError # TODO: Decide whether we like these better # than auto-generated has_foo() and clear_foo() methods # on the instances themselves. This way is less consistent # with C++, but it makes reflection-type access easier and # reduces the number of magically autogenerated things. # # TODO: Be sure to document (and test) exactly # which field names are accepted here. Are we case-sensitive? # What do we do with fields that share names with Python keywords # like 'lambda' and 'yield'? # # nnorwitz says: # """ # Typically (in python), an underscore is appended to names that are # keywords. So they would become lambda_ or yield_. # """ def ListFields(self): """Returns a list of (FieldDescriptor, value) tuples for present fields. A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number. Returns: list[tuple(FieldDescriptor, value)]: field descriptors and values for all fields in the message which are not empty. The values vary by field type. """ raise NotImplementedError def HasField(self, field_name): """Checks if a certain field is set for the message. For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, :exc:`ValueError` will be raised. Args: field_name (str): The name of the field to check for presence. Returns: bool: Whether a value has been set for the named field. Raises: ValueError: if the `field_name` is not a member of this message. """ raise NotImplementedError def ClearField(self, field_name): """Clears the contents of a given field. Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, :exc:`ValueError` is raised. Args: field_name (str): The name of the field to check for presence. Raises: ValueError: if the `field_name` is not a member of this message. """ raise NotImplementedError def WhichOneof(self, oneof_group): """Returns the name of the field that is set inside a oneof group. If no field is set, returns None. Args: oneof_group (str): the name of the oneof group to check. Returns: str or None: The name of the group that is set, or None. Raises: ValueError: no group with the given name exists """ raise NotImplementedError def HasExtension(self, field_descriptor): """Checks if a certain extension is present for this message. Extensions are retrieved using the :attr:`Extensions` mapping (if present). Args: field_descriptor: The field descriptor for the extension to check. Returns: bool: Whether the extension is present for this message. Raises: KeyError: if the extension is repeated. Similar to repeated fields, there is no separate notion of presence: a "not present" repeated extension is an empty list. """ raise NotImplementedError def ClearExtension(self, field_descriptor): """Clears the contents of a given extension. Args: field_descriptor: The field descriptor for the extension to clear. """ raise NotImplementedError def UnknownFields(self): """Returns the UnknownFieldSet. Returns: UnknownFieldSet: The unknown fields stored in this message. """ raise NotImplementedError def DiscardUnknownFields(self): """Clears all fields in the :class:`UnknownFieldSet`. This operation is recursive for nested message. """ raise NotImplementedError def ByteSize(self): """Returns the serialized size of this message. Recursively calls ByteSize() on all contained messages. Returns: int: The number of bytes required to serialize this message. """ raise NotImplementedError @classmethod def FromString(cls, s): raise NotImplementedError def _SetListener(self, message_listener): """Internal method used by the protocol message implementation. Clients should not call this directly. Sets a listener that this message will call on certain state transitions. The purpose of this method is to register back-edges from children to parents at runtime, for the purpose of setting "has" bits and byte-size-dirty bits in the parent and ancestor objects whenever a child or descendant object is modified. If the client wants to disconnect this Message from the object tree, she explicitly sets callback to None. If message_listener is None, unregisters any existing listener. Otherwise, message_listener must implement the MessageListener interface in internal/message_listener.py, and we discard any listener registered via a previous _SetListener() call. """ raise NotImplementedError def __getstate__(self): """Support the pickle protocol.""" return dict(serialized=self.SerializePartialToString()) def __setstate__(self, state): """Support the pickle protocol.""" self.__init__() serialized = state['serialized'] # On Python 3, using encoding='latin1' is required for unpickling # protos pickled by Python 2. if not isinstance(serialized, bytes): serialized = serialized.encode('latin1') self.ParseFromString(serialized) def __reduce__(self): message_descriptor = self.DESCRIPTOR if message_descriptor.containing_type is None: return type(self), (), self.__getstate__() # the message type must be nested. # Python does not pickle nested classes; use the symbol_database on the # receiving end. container = message_descriptor return (_InternalConstructMessage, (container.full_name,), self.__getstate__()) def _InternalConstructMessage(full_name): """Constructs a nested message.""" from google.protobuf import symbol_database # pylint:disable=g-import-not-at-top return symbol_database.Default().GetSymbol(full_name)()
Message
python
python-visualization__folium
tests/test_folium.py
{ "start": 1542, "end": 18092 }
class ____: """Test class for the Folium library.""" def setup_method(self): """Setup Folium Map.""" attr = "http://openstreetmap.org" self.m = folium.Map( location=[45.5236, -122.6750], width=900, height=400, max_zoom=20, zoom_start=4, max_bounds=True, font_size="1.5rem", attr=attr, ) self.fit_bounds_template = Template( """ {% if autobounds %} var autobounds = L.featureGroup({{ features }}).getBounds() {% if not bounds %} {% set bounds = "autobounds" %} {% endif %} {% endif %} {% if bounds %} {{this._parent.get_name()}}.fitBounds({{ bounds }}, {{ fit_bounds_options }} ); {% endif %} """ ) def test_init(self): """Test map initialization.""" assert self.m.get_name().startswith("map_") assert self.m.get_root() == self.m._parent assert self.m.location == [45.5236, -122.6750] assert self.m.options["zoom"] == 4 assert self.m.options["max_bounds"] == [[-90, -180], [90, 180]] assert self.m.position == "relative" assert self.m.height == (400, "px") assert self.m.width == (900, "px") assert self.m.left == (0, "%") assert self.m.top == (0, "%") assert self.m.global_switches.no_touch is False assert self.m.global_switches.disable_3d is False assert self.m.font_size == "1.5rem" assert self.m.to_dict() == { "name": "Map", "id": self.m._id, "children": { "openstreetmap": { "name": "TileLayer", "id": self.m._children["openstreetmap"]._id, "children": {}, } }, } @pytest.mark.parametrize( "tiles,provider", [ ("OpenStreetMap", xyz.OpenStreetMap.Mapnik), ("CartoDB positron", xyz.CartoDB.Positron), ("CartoDB dark_matter", xyz.CartoDB.DarkMatter), ], ) def test_builtin_tile(self, tiles, provider): """Test custom maptiles.""" m = folium.Map(location=[45.5236, -122.6750], tiles=tiles) tiles = "".join(tiles.lower().strip().split()) url = provider.build_url(fill_subdomain=False, scale_factor="{r}") attr = provider.html_attribution assert m._children[tiles.replace("_", "")].tiles == url assert htmlsafe_json_dumps(attr) in m._parent.render() bounds = m.get_bounds() assert bounds == [[None, None], [None, None]], bounds def test_custom_tile(self): """Test custom tile URLs.""" url = "http://{s}.custom_tiles.org/{z}/{x}/{y}.png" attr = "Attribution for custom tiles" with pytest.raises(ValueError): folium.Map(location=[45.5236, -122.6750], tiles=url) m = folium.Map(location=[45.52, -122.67], tiles=url, attr=attr) assert m._children[url].tiles == url assert attr in m._parent.render() bounds = m.get_bounds() assert bounds == [[None, None], [None, None]], bounds def test_tilelayer_object(self): url = "http://{s}.custom_tiles.org/{z}/{x}/{y}.png" attr = "Attribution for custom tiles" m = folium.Map(location=[45.52, -122.67], tiles=TileLayer(url, attr=attr)) assert next(iter(m._children.values())).tiles == url assert attr in m._parent.render() def test_feature_group(self): """Test FeatureGroup.""" m = folium.Map() feature_group = folium.FeatureGroup() feature_group.add_child(folium.Marker([45, -30], popup=folium.Popup("-30"))) feature_group.add_child(folium.Marker([45, 30], popup=folium.Popup("30"))) m.add_child(feature_group) m.add_child(folium.LayerControl()) m._repr_html_() bounds = m.get_bounds() assert bounds == [[45, -30], [45, 30]], bounds def test_topo_json_smooth_factor(self): """Test topojson smooth factor method.""" self.m = folium.Map([43, -100], zoom_start=4) # Adding TopoJSON as additional layer. with open(os.path.join(rootpath, "or_counties_topo.json")) as f: choropleth = Choropleth( f, topojson="objects.or_counties_geo", smooth_factor=0.5 ).add_to(self.m) out = self.m._parent.render() # Verify TopoJson topo_json = choropleth.geojson topojson_str = topo_json._template.module.script(topo_json) assert "".join(topojson_str.split())[:-1] in "".join(out.split()) def test_choropleth_features(self): """Test to make sure that Choropleth function doesn't allow values outside of the domain defined by bins. It also tests that all parameters work as expected regarding nan and missing values. """ with open(os.path.join(rootpath, "us-counties.json")) as f: geo_data = json.load(f) data = {"1001": -1} fill_color = "BuPu" key_on = "id" with pytest.raises(ValueError): Choropleth( geo_data=geo_data, data=data, key_on=key_on, fill_color=fill_color, bins=[0, 1, 2, 3], ).add_to(self.m) self.m._parent.render() Choropleth( geo_data=geo_data, data={"1001": 1, "1003": float("nan")}, key_on=key_on, fill_color=fill_color, fill_opacity=0.543212345, nan_fill_color="a_random_color", nan_fill_opacity=0.123454321, ).add_to(self.m) out = self.m._parent.render() out_str = "".join(out.split()) assert '"fillColor":"a_random_color","fillOpacity":0.123454321' in out_str assert '"fillOpacity":0.543212345' in out_str def test_choropleth_key_on(self): """Test to make sure that Choropleth function doesn't raises a ValueError when the 'key_on' field is set to a column that might have 0 as a value. """ with open(os.path.join(rootpath, "geo_grid.json")) as f: geo_data = json.load(f) data = pd.DataFrame( { "idx": {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5}, "value": { "0": 78.0, "1": 39.0, "2": 0.0, "3": 81.0, "4": 42.0, "5": 68.0, }, } ) fill_color = "BuPu" columns = ["idx", "value"] key_on = "feature.properties.idx" Choropleth( geo_data=geo_data, data=data, key_on=key_on, fill_color=fill_color, columns=columns, ) def test_choropleth_geopandas_numeric(self): """Test to make sure that Choropleth function does complete the lookup between a GeoJSON generated from a GeoDataFrame and data from the GeoDataFrame itself. key_on field is dtype = str, while column 0 is dtype = int All geometries have matching values (no nan_fill_color allowed) """ with open(os.path.join(rootpath, "geo_grid.json")) as f: geo_data = json.load(f) geo_data_frame = gpd.GeoDataFrame.from_features(geo_data["features"]) geo_data_frame = geo_data_frame.set_crs("epsg: 4326") fill_color = "BuPu" key_on = "feature.id" Choropleth( geo_data=geo_data_frame.geometry, data=geo_data_frame.value, key_on=key_on, fill_color=fill_color, fill_opacity=0.543212345, nan_fill_color="a_random_color", nan_fill_opacity=0.123454321, ).add_to(self.m) out = self.m._parent.render() out_str = "".join(out.split()) assert '"fillColor":"a_random_color","fillOpacity":0.123454321' not in out_str assert '"fillOpacity":0.543212345' in out_str def test_choropleth_geopandas_mixed(self): """Test to make sure that Choropleth function does complete the lookup between a GeoJSON generated from a GeoDataFrame and data from a DataFrame. key_on field is dtype = str, while column 0 is dtype = object (mixed int and str) All geometries have matching values (no nan_fill_color allowed) """ with open(os.path.join(rootpath, "geo_grid.json")) as f: geo_data = json.load(f) geo_data_frame = gpd.GeoDataFrame.from_features(geo_data["features"]) geo_data_frame = geo_data_frame.set_crs("epsg: 4326") data = pd.DataFrame( { "idx": {"0": 0, "1": "1", "2": 2, "3": 3, "4": 4, "5": 5}, "value": { "0": 78.0, "1": 39.0, "2": 0.0, "3": 81.0, "4": 42.0, "5": 68.0, }, } ) fill_color = "BuPu" columns = ["idx", "value"] key_on = "feature.id" Choropleth( geo_data=geo_data_frame.geometry, data=data, key_on=key_on, columns=columns, fill_color=fill_color, fill_opacity=0.543212345, nan_fill_color="a_random_color", nan_fill_opacity=0.123454321, ).add_to(self.m) out = self.m._parent.render() out_str = "".join(out.split()) assert '"fillColor":"a_random_color","fillOpacity":0.123454321' not in out_str assert '"fillOpacity":0.543212345' in out_str def test_choropleth_geopandas_str(self): """Test to make sure that Choropleth function does complete the lookup between a GeoJSON generated from a GeoDataFrame and data from a DataFrame. key_on field and column 0 from data are both strings. All geometries have matching values (no nan_fill_color allowed) """ with open(os.path.join(rootpath, "geo_grid.json")) as f: geo_data = json.load(f) geo_data_frame = gpd.GeoDataFrame.from_features(geo_data["features"]) geo_data_frame = geo_data_frame.set_crs("epsg: 4326") data = pd.DataFrame( { "idx": {"0": "0", "1": "1", "2": "2", "3": "3", "4": "4", "5": "5"}, "value": { "0": 78.0, "1": 39.0, "2": 0.0, "3": 81.0, "4": 42.0, "5": 68.0, }, } ) fill_color = "BuPu" columns = ["idx", "value"] key_on = "feature.id" Choropleth( geo_data=geo_data_frame.geometry, data=data, key_on=key_on, columns=columns, fill_color=fill_color, fill_opacity=0.543212345, nan_fill_color="a_random_color", nan_fill_opacity=0.123454321, ).add_to(self.m) out = self.m._parent.render() out_str = "".join(out.split()) assert '"fillColor":"a_random_color","fillOpacity":0.123454321' not in out_str assert '"fillOpacity":0.543212345' in out_str def test_tile_attr_unicode(self): """Test tile attribution unicode""" m = folium.Map(location=[45.5236, -122.6750], tiles="test", attr="юникод") m._parent.render() def test_fit_bounds(self): """Test fit_bounds.""" bounds = ((52.193636, -2.221575), (52.636878, -1.139759)) self.m.fit_bounds(bounds) fitbounds = [ val for key, val in self.m._children.items() if isinstance(val, folium.FitBounds) ][0] out = self.m._parent.render() fit_bounds_rendered = self.fit_bounds_template.render( { "bounds": json.dumps(bounds), "this": fitbounds, "fit_bounds_options": {}, } ) assert "".join(fit_bounds_rendered.split()) in "".join(out.split()) def test_fit_bounds_2(self): bounds = ((52.193636, -2.221575), (52.636878, -1.139759)) self.m.fit_bounds(bounds, max_zoom=15, padding=(3, 3)) fitbounds = [ val for key, val in self.m._children.items() if isinstance(val, folium.FitBounds) ][0] out = self.m._parent.render() fit_bounds_rendered = self.fit_bounds_template.render( { "bounds": json.dumps(bounds), "fit_bounds_options": json.dumps( { "maxZoom": 15, "padding": (3, 3), }, sort_keys=True, ), "this": fitbounds, } ) assert "".join(fit_bounds_rendered.split()) in "".join(out.split()) bounds = self.m.get_bounds() assert bounds == [[None, None], [None, None]], bounds def test_custom_icon(self): """Test CustomIcon.""" icon_image = "http://leafletjs.com/docs/images/leaf-green.png" shadow_image = "http://leafletjs.com/docs/images/leaf-shadow.png" self.m = folium.Map([45, -100], zoom_start=4) i = folium.features.CustomIcon( icon_image, icon_size=(38, 95), icon_anchor=(22, 94), shadow_image=shadow_image, shadow_size=(50, 64), shadow_anchor=(4, 62), popup_anchor=(-3, -76), ) mk = folium.Marker([45, -100], icon=i, popup=folium.Popup("Hello")) self.m.add_child(mk) self.m._parent.render() bounds = self.m.get_bounds() assert bounds == [[45, -100], [45, -100]], bounds def test_global_switches(self): m = folium.Map(prefer_canvas=True) out = m._parent.render() out_str = "".join(out.split()) assert '"preferCanvas":true' in out_str assert not m.global_switches.no_touch assert not m.global_switches.disable_3d m = folium.Map(no_touch=True) out = m._parent.render() out_str = "".join(out.split()) assert '"preferCanvas":false' in out_str assert m.global_switches.no_touch assert not m.global_switches.disable_3d m = folium.Map(disable_3d=True) out = m._parent.render() out_str = "".join(out.split()) assert '"preferCanvas":false' in out_str assert not m.global_switches.no_touch assert m.global_switches.disable_3d m = folium.Map(prefer_canvas=True, no_touch=True, disable_3d=True) out = m._parent.render() out_str = "".join(out.split()) assert '"preferCanvas":true' in out_str assert m.global_switches.no_touch assert m.global_switches.disable_3d def test_json_request(self): """Test requests for remote GeoJSON files.""" self.m = folium.Map(zoom_start=4) # Adding remote GeoJSON as additional layer. GeoJson(remote_url, smooth_factor=0.5).add_to(self.m) self.m._parent.render() bounds = self.m.get_bounds() np.testing.assert_allclose( bounds, [[18.948267, -178.123152], [71.351633, 173.304726]] ) def test_control_typecheck(self): m = folium.Map( location=[39.949610, -75.150282], zoom_start=5, zoom_control=False ) tiles = TileLayer( tiles="OpenStreetMap", show=False, control=False, ) tiles.add_to(m) with pytest.raises(TypeError) as excinfo: minimap = folium.Control("MiniMap", tiles, position="downunder") minimap.add_js_link( "minimap_js", "https://cdnjs.cloudflare.com/ajax/libs/leaflet-minimap/3.6.1/Control.MiniMap.min.js", ) minimap.add_css_link( "minimap_css", "https://cdnjs.cloudflare.com/ajax/libs/leaflet-minimap/3.6.1/Control.MiniMap.css", ) minimap.add_to(m) assert "position must be one of ('bottomright', 'bottomleft'" in str( excinfo.value )
TestFolium
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-openai/llama_index/llms/openai/responses.py
{ "start": 3907, "end": 38012 }
class ____(FunctionCallingLLM): """ OpenAI Responses LLM. Args: model: name of the OpenAI model to use. temperature: a float from 0 to 1 controlling randomness in generation; higher will lead to more creative, less deterministic responses. max_output_tokens: the maximum number of tokens to generate. reasoning_options: Optional dictionary to configure reasoning for O1 models. Corresponds to the 'reasoning' parameter in the OpenAI API. Example: {"effort": "low", "summary": "concise"} include: Additional output data to include in the model response. instructions: Instructions for the model to follow. track_previous_responses: Whether to track previous responses. If true, the LLM class will statefully track previous responses. store: Whether to store previous responses in OpenAI's storage. built_in_tools: The built-in tools to use for the model to augment responses. truncation: Whether to auto-truncate the input if it exceeds the model's context window. user: An optional identifier to help track the user's requests for abuse. strict: Whether to enforce strict validation of the structured output. additional_kwargs: Add additional parameters to OpenAI request body. max_retries: How many times to retry the API call if it fails. timeout: How long to wait, in seconds, for an API call before failing. api_key: Your OpenAI api key api_base: The base URL of the API to call api_version: the version of the API to call default_headers: override the default headers for API requests. http_client: pass in your own httpx.Client instance. async_http_client: pass in your own httpx.AsyncClient instance. Examples: `pip install llama-index-llms-openai` ```python from llama_index.llms.openai import OpenAIResponses llm = OpenAIResponses(model="gpt-4o-mini", api_key="sk-...") response = llm.complete("Hi, write a short story") print(response.text) ``` """ model: str = Field( default=DEFAULT_OPENAI_MODEL, description="The OpenAI model to use." ) temperature: float = Field( default=DEFAULT_TEMPERATURE, description="The temperature to use during generation.", ge=0.0, le=2.0, ) top_p: float = Field( default=1.0, description="The top-p value to use during generation.", ge=0.0, le=1.0, ) max_output_tokens: Optional[int] = Field( description="The maximum number of tokens to generate.", gt=0, ) reasoning_options: Optional[Dict[str, Any]] = Field( default=None, description="Optional dictionary to configure reasoning for O1 models. Example: {'effort': 'low', 'summary': 'concise'}", ) include: Optional[List[str]] = Field( default=None, description="Additional output data to include in the model response.", ) instructions: Optional[str] = Field( default=None, description="Instructions for the model to follow.", ) track_previous_responses: bool = Field( default=False, description="Whether to track previous responses. If true, the LLM class will statefully track previous responses.", ) store: bool = Field( default=False, description="Whether to store previous responses in OpenAI's storage.", ) built_in_tools: Optional[List[dict]] = Field( default=None, description="The built-in tools to use for the model to augment responses.", ) truncation: str = Field( default="disabled", description="Whether to auto-truncate the input if it exceeds the model's context window.", ) user: Optional[str] = Field( default=None, description="An optional identifier to help track the user's requests for abuse.", ) call_metadata: Optional[Dict[str, Any]] = Field( default=None, description="Metadata to include in the API call.", ) additional_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Additional kwargs for the OpenAI API at inference time.", ) max_retries: int = Field( default=3, description="The maximum number of API retries.", ge=0, ) timeout: float = Field( default=60.0, description="The timeout, in seconds, for API requests.", ge=0, ) strict: bool = Field( default=False, description="Whether to enforce strict validation of the structured output.", ) default_headers: Optional[Dict[str, str]] = Field( default=None, description="The default headers for API requests." ) api_key: Optional[str] = Field(default=None, description="The OpenAI API key.") api_base: str = Field(description="The base URL for OpenAI API.") api_version: str = Field(description="The API version for OpenAI API.") context_window: Optional[int] = Field( default=None, description="The context window override for the model.", ) _client: SyncOpenAI = PrivateAttr() _aclient: AsyncOpenAI = PrivateAttr() _http_client: Optional[httpx.Client] = PrivateAttr() _async_http_client: Optional[httpx.AsyncClient] = PrivateAttr() _previous_response_id: Optional[str] = PrivateAttr() def __init__( self, model: str = DEFAULT_OPENAI_MODEL, temperature: float = DEFAULT_TEMPERATURE, max_output_tokens: Optional[int] = None, reasoning_options: Optional[Dict[str, Any]] = None, include: Optional[List[str]] = None, instructions: Optional[str] = None, track_previous_responses: bool = False, store: bool = False, built_in_tools: Optional[List[dict]] = None, truncation: str = "disabled", user: Optional[str] = None, previous_response_id: Optional[str] = None, call_metadata: Optional[Dict[str, Any]] = None, strict: bool = False, additional_kwargs: Optional[Dict[str, Any]] = None, max_retries: int = 3, timeout: float = 60.0, api_key: Optional[str] = None, api_base: Optional[str] = None, api_version: Optional[str] = None, default_headers: Optional[Dict[str, str]] = None, http_client: Optional[httpx.Client] = None, async_http_client: Optional[httpx.AsyncClient] = None, openai_client: Optional[SyncOpenAI] = None, async_openai_client: Optional[AsyncOpenAI] = None, context_window: Optional[int] = None, **kwargs: Any, ) -> None: additional_kwargs = additional_kwargs or {} api_key, api_base, api_version = resolve_openai_credentials( api_key=api_key, api_base=api_base, api_version=api_version, ) # TODO: Temp forced to 1.0 for o1 if model in O1_MODELS: temperature = 1.0 super().__init__( model=model, temperature=temperature, max_output_tokens=max_output_tokens, reasoning_options=reasoning_options, include=include, instructions=instructions, track_previous_responses=track_previous_responses, store=store, built_in_tools=built_in_tools, truncation=truncation, user=user, additional_kwargs=additional_kwargs, max_retries=max_retries, api_key=api_key, api_version=api_version, api_base=api_base, timeout=timeout, default_headers=default_headers, call_metadata=call_metadata, strict=strict, context_window=context_window, **kwargs, ) self._previous_response_id = previous_response_id # store is set to true if track_previous_responses is true if self.track_previous_responses: self.store = True self._http_client = http_client self._async_http_client = async_http_client self._client = openai_client or SyncOpenAI(**self._get_credential_kwargs()) self._aclient = async_openai_client or AsyncOpenAI( **self._get_credential_kwargs(is_async=True) ) @classmethod def class_name(cls) -> str: return "openai_responses_llm" @property def metadata(self) -> LLMMetadata: return LLMMetadata( context_window=self.context_window or openai_modelname_to_contextsize(self._get_model_name()), num_output=self.max_output_tokens or -1, is_chat_model=True, is_function_calling_model=is_function_calling_model( model=self._get_model_name() ), model_name=self.model, ) @property def _tokenizer(self) -> Optional[Tokenizer]: """ Get a tokenizer for this model, or None if a tokenizing method is unknown. OpenAI can do this using the tiktoken package, subclasses may not have this convenience. """ return tiktoken.encoding_for_model(self._get_model_name()) def _get_model_name(self) -> str: model_name = self.model if "ft-" in model_name: # legacy fine-tuning model_name = model_name.split(":")[0] elif model_name.startswith("ft:"): model_name = model_name.split(":")[1] return model_name def _is_azure_client(self) -> bool: return isinstance(self._client, AzureOpenAI) def _get_credential_kwargs(self, is_async: bool = False) -> Dict[str, Any]: return { "api_key": self.api_key, "base_url": self.api_base, "max_retries": self.max_retries, "timeout": self.timeout, "default_headers": self.default_headers, "http_client": self._async_http_client if is_async else self._http_client, } def _get_model_kwargs(self, **kwargs: Any) -> Dict[str, Any]: initial_tools = self.built_in_tools or [] model_kwargs = { "model": self.model, "include": self.include, "instructions": self.instructions, "max_output_tokens": self.max_output_tokens, "metadata": self.call_metadata, "previous_response_id": self._previous_response_id, "store": self.store, "temperature": self.temperature, "tools": [*initial_tools, *kwargs.pop("tools", [])], "top_p": self.top_p, "truncation": self.truncation, "user": self.user, } if self.model in O1_MODELS and self.reasoning_options is not None: model_kwargs["reasoning"] = self.reasoning_options # priority is class args > additional_kwargs > runtime args model_kwargs.update(self.additional_kwargs) kwargs = kwargs or {} model_kwargs.update(kwargs) return model_kwargs @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: return self._chat(messages, **kwargs) @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: return self._stream_chat(messages, **kwargs) @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: complete_fn = chat_to_completion_decorator(self._chat) return complete_fn(prompt, **kwargs) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: stream_complete_fn = stream_chat_to_completion_decorator(self._stream_chat) return stream_complete_fn(prompt, **kwargs) @staticmethod def _parse_response_output(output: List[ResponseOutputItem]) -> ChatResponse: message = ChatMessage(role=MessageRole.ASSISTANT, blocks=[]) additional_kwargs = {"built_in_tool_calls": []} blocks: List[ContentBlock] = [] for item in output: if isinstance(item, ResponseOutputMessage): for part in item.content: if hasattr(part, "text"): blocks.append(TextBlock(text=part.text)) if hasattr(part, "annotations"): additional_kwargs["annotations"] = part.annotations if hasattr(part, "refusal"): additional_kwargs["refusal"] = part.refusal message.blocks.extend(blocks) elif isinstance(item, ImageGenerationCall): # return an ImageBlock if there is image generation if item.status != "failed": additional_kwargs["built_in_tool_calls"].append(item) if item.result is not None: image_bytes = base64.b64decode(item.result) blocks.append(ImageBlock(image=image_bytes)) elif isinstance(item, ResponseCodeInterpreterToolCall): additional_kwargs["built_in_tool_calls"].append(item) elif isinstance(item, McpCall): additional_kwargs["built_in_tool_calls"].append(item) elif isinstance(item, ResponseFileSearchToolCall): additional_kwargs["built_in_tool_calls"].append(item) elif isinstance(item, ResponseFunctionToolCall): message.blocks.append( ToolCallBlock( tool_name=item.name, tool_call_id=item.call_id, tool_kwargs=item.arguments, ) ) elif isinstance(item, ResponseFunctionWebSearch): additional_kwargs["built_in_tool_calls"].append(item) elif isinstance(item, ResponseComputerToolCall): additional_kwargs["built_in_tool_calls"].append(item) elif isinstance(item, ResponseReasoningItem): content: Optional[str] = None if item.content: content = "\n".join([i.text for i in item.content]) if item.summary: if content: content += "\n" + "\n".join([i.text for i in item.summary]) else: content = "\n".join([i.text for i in item.summary]) message.blocks.append( ThinkingBlock( content=content, additional_information=item.model_dump( exclude={"content", "summary"} ), ) ) return ChatResponse(message=message, additional_kwargs=additional_kwargs) @llm_retry_decorator def _chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: kwargs_dict = self._get_model_kwargs(**kwargs) message_dicts = to_openai_message_dicts( messages, model=self.model, is_responses_api=True, ) response: Response = self._client.responses.create( input=message_dicts, stream=False, **kwargs_dict, ) if self.track_previous_responses: self._previous_response_id = response.id chat_response = OpenAIResponses._parse_response_output(response.output) chat_response.raw = response chat_response.additional_kwargs["usage"] = response.usage if hasattr(response.usage.output_tokens_details, "reasoning_tokens"): for block in chat_response.message.blocks: if isinstance(block, ThinkingBlock): block.num_tokens = ( response.usage.output_tokens_details.reasoning_tokens ) return chat_response @staticmethod def process_response_event( event: ResponseStreamEvent, built_in_tool_calls: List[Any], additional_kwargs: Dict[str, Any], current_tool_call: Optional[ResponseFunctionToolCall], track_previous_responses: bool, previous_response_id: Optional[str] = None, ) -> Tuple[ List[ContentBlock], List[Any], Dict[str, Any], Optional[ResponseFunctionToolCall], Optional[str], str, ]: """ Process a ResponseStreamEvent and update the state accordingly. Args: event: The response stream event to process content: Current accumulated content string tool_calls: List of completed tool calls built_in_tool_calls: List of built-in tool calls additional_kwargs: Additional keyword arguments to include in ChatResponse current_tool_call: The currently in-progress tool call, if any track_previous_responses: Whether to track previous response IDs previous_response_id: Previous response ID if tracking Returns: A tuple containing the updated state: (content, tool_calls, built_in_tool_calls, additional_kwargs, current_tool_call, updated_previous_response_id, delta) """ delta = "" updated_previous_response_id = previous_response_id # we use blocks instead of content, since now we also support images! :) blocks: List[ContentBlock] = [] if isinstance(event, ResponseCreatedEvent) or isinstance( event, ResponseInProgressEvent ): # Initial events, track the response id if track_previous_responses: updated_previous_response_id = event.response.id elif isinstance(event, ResponseOutputItemAddedEvent): # New output item (message, tool call, etc.) if isinstance(event.item, ResponseFunctionToolCall): current_tool_call = event.item elif isinstance(event, ResponseTextDeltaEvent): # Text content is being added delta = event.delta blocks.append(TextBlock(text=delta)) elif isinstance(event, ResponseImageGenCallPartialImageEvent): # Partial image if event.partial_image_b64: blocks.append( ImageBlock( image=base64.b64decode(event.partial_image_b64), detail=f"id_{event.partial_image_index}", ) ) elif isinstance(event, ResponseFunctionCallArgumentsDeltaEvent): # Function call arguments are being streamed if current_tool_call is not None: current_tool_call.arguments += event.delta elif isinstance(event, ResponseFunctionCallArgumentsDoneEvent): # Function call arguments are complete if current_tool_call is not None: current_tool_call.arguments = event.arguments current_tool_call.status = "completed" blocks.append( ToolCallBlock( tool_name=current_tool_call.name, tool_kwargs=current_tool_call.arguments, tool_call_id=current_tool_call.call_id, ) ) # clear the current tool call current_tool_call = None elif isinstance(event, ResponseOutputTextAnnotationAddedEvent): # Annotations for the text annotations = additional_kwargs.get("annotations", []) annotations.append(event.annotation) additional_kwargs["annotations"] = annotations elif isinstance(event, ResponseFileSearchCallCompletedEvent): # File search tool call completed built_in_tool_calls.append(event) elif isinstance(event, ResponseWebSearchCallCompletedEvent): # Web search tool call completed built_in_tool_calls.append(event) elif isinstance(event, ResponseOutputItemDoneEvent): # Reasoning information if isinstance(event.item, ResponseReasoningItem): content: Optional[str] = None if event.item.content: content = "\n".join([i.text for i in event.item.content]) if event.item.summary: if content: content += "\n" + "\n".join( [i.text for i in event.item.summary] ) else: content = "\n".join([i.text for i in event.item.summary]) blocks.append( ThinkingBlock( content=content, additional_information=event.item.model_dump( exclude={"content", "summary"} ), ) ) elif isinstance(event, ResponseCompletedEvent): # Response is complete if hasattr(event, "response") and hasattr(event.response, "usage"): additional_kwargs["usage"] = event.response.usage resp = OpenAIResponses._parse_response_output(event.response.output) blocks = resp.message.blocks return ( blocks, built_in_tool_calls, additional_kwargs, current_tool_call, updated_previous_response_id, delta, ) @llm_retry_decorator def _stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: message_dicts = to_openai_message_dicts( messages, model=self.model, is_responses_api=True, ) def gen() -> ChatResponseGen: built_in_tool_calls = [] additional_kwargs = {"built_in_tool_calls": []} current_tool_call: Optional[ResponseFunctionToolCall] = None local_previous_response_id = self._previous_response_id for event in self._client.responses.create( input=message_dicts, stream=True, **self._get_model_kwargs(**kwargs), ): # Process the event and update state ( blocks, built_in_tool_calls, additional_kwargs, current_tool_call, local_previous_response_id, delta, ) = OpenAIResponses.process_response_event( event=event, built_in_tool_calls=built_in_tool_calls, additional_kwargs=additional_kwargs, current_tool_call=current_tool_call, track_previous_responses=self.track_previous_responses, previous_response_id=local_previous_response_id, ) if ( self.track_previous_responses and local_previous_response_id != self._previous_response_id ): self._previous_response_id = local_previous_response_id if built_in_tool_calls: additional_kwargs["built_in_tool_calls"] = built_in_tool_calls # For any event, yield a ChatResponse with the current state yield ChatResponse( message=ChatMessage( role=MessageRole.ASSISTANT, blocks=blocks, ), delta=delta, raw=event, additional_kwargs=additional_kwargs, ) return gen() # ===== Async Endpoints ===== @llm_chat_callback() async def achat( self, messages: Sequence[ChatMessage], **kwargs: Any, ) -> ChatResponse: return await self._achat(messages, **kwargs) @llm_chat_callback() async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any, ) -> ChatResponseAsyncGen: return await self._astream_chat(messages, **kwargs) @llm_completion_callback() async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: acomplete_fn = achat_to_completion_decorator(self._achat) return await acomplete_fn(prompt, **kwargs) @llm_completion_callback() async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: astream_complete_fn = astream_chat_to_completion_decorator(self._astream_chat) return await astream_complete_fn(prompt, **kwargs) @llm_retry_decorator async def _achat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponse: message_dicts = to_openai_message_dicts( messages, model=self.model, is_responses_api=True, ) response: Response = await self._aclient.responses.create( input=message_dicts, stream=False, **self._get_model_kwargs(**kwargs), ) if self.track_previous_responses: self._previous_response_id = response.id chat_response = OpenAIResponses._parse_response_output(response.output) chat_response.raw = response chat_response.additional_kwargs["usage"] = response.usage return chat_response @llm_retry_decorator async def _astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: message_dicts = to_openai_message_dicts( messages, model=self.model, is_responses_api=True, ) async def gen() -> ChatResponseAsyncGen: built_in_tool_calls = [] additional_kwargs = {"built_in_tool_calls": []} current_tool_call: Optional[ResponseFunctionToolCall] = None local_previous_response_id = self._previous_response_id response_stream = await self._aclient.responses.create( input=message_dicts, stream=True, **self._get_model_kwargs(**kwargs), ) async for event in response_stream: # Process the event and update state ( blocks, built_in_tool_calls, additional_kwargs, current_tool_call, local_previous_response_id, delta, ) = OpenAIResponses.process_response_event( event=event, built_in_tool_calls=built_in_tool_calls, additional_kwargs=additional_kwargs, current_tool_call=current_tool_call, track_previous_responses=self.track_previous_responses, previous_response_id=local_previous_response_id, ) if ( self.track_previous_responses and local_previous_response_id != self._previous_response_id ): self._previous_response_id = local_previous_response_id if built_in_tool_calls: additional_kwargs["built_in_tool_calls"] = built_in_tool_calls # For any event, yield a ChatResponse with the current state yield ChatResponse( message=ChatMessage( role=MessageRole.ASSISTANT, blocks=blocks, ), delta=delta, raw=event, additional_kwargs=additional_kwargs, ) return gen() def _prepare_chat_with_tools( self, tools: Sequence["BaseTool"], user_msg: Optional[Union[str, ChatMessage]] = None, chat_history: Optional[List[ChatMessage]] = None, allow_parallel_tool_calls: bool = True, tool_required: bool = False, tool_choice: Optional[Union[str, dict]] = None, verbose: bool = False, strict: Optional[bool] = None, **kwargs: Any, ) -> Dict[str, Any]: """Predict and call the tool.""" # openai responses api has a slightly different tool spec format tool_specs = [ { "type": "function", **tool.metadata.to_openai_tool(skip_length_check=True)["function"], } for tool in tools ] if strict is not None: strict = strict else: strict = self.strict if strict: for tool_spec in tool_specs: tool_spec["strict"] = True tool_spec["parameters"]["additionalProperties"] = False if isinstance(user_msg, str): user_msg = ChatMessage(role=MessageRole.USER, content=user_msg) messages = chat_history or [] if user_msg: messages.append(user_msg) return { "messages": messages, "tools": tool_specs or None, "tool_choice": resolve_tool_choice(tool_choice, tool_required) if tool_specs else None, "parallel_tool_calls": allow_parallel_tool_calls, **kwargs, } def get_tool_calls_from_response( self, response: "ChatResponse", error_on_no_tool_call: bool = True, **kwargs: Any, ) -> List[ToolSelection]: """Predict and call the tool.""" tool_calls: List[ToolCallBlock] = [ block for block in response.message.blocks if isinstance(block, ToolCallBlock) ] if len(tool_calls) < 1: if error_on_no_tool_call: raise ValueError( f"Expected at least one tool call, but got {len(tool_calls)} tool calls." ) else: return [] tool_selections = [] for tool_call in tool_calls: # this should handle both complete and partial jsons try: argument_dict = parse_partial_json(cast(str, tool_call.tool_kwargs)) except Exception: argument_dict = {} tool_selections.append( ToolSelection( tool_id=tool_call.tool_call_id or "", tool_name=tool_call.tool_name, tool_kwargs=argument_dict, ) ) return tool_selections @dispatcher.span def structured_predict( self, output_cls: Type[Model], prompt: PromptTemplate, llm_kwargs: Optional[Dict[str, Any]] = None, **prompt_args: Any, ) -> Model: """Structured predict.""" llm_kwargs = llm_kwargs or {} llm_kwargs["tool_choice"] = ( "required" if "tool_choice" not in llm_kwargs else llm_kwargs["tool_choice"] ) # by default structured prediction uses function calling to extract structured outputs # here we force tool_choice to be required return super().structured_predict( output_cls, prompt, llm_kwargs=llm_kwargs, **prompt_args ) @dispatcher.span async def astructured_predict( self, output_cls: Type[Model], prompt: PromptTemplate, llm_kwargs: Optional[Dict[str, Any]] = None, **prompt_args: Any, ) -> Model: """Structured predict.""" llm_kwargs = llm_kwargs or {} llm_kwargs["tool_choice"] = ( "required" if "tool_choice" not in llm_kwargs else llm_kwargs["tool_choice"] ) # by default structured prediction uses function calling to extract structured outputs # here we force tool_choice to be required return await super().astructured_predict( output_cls, prompt, llm_kwargs=llm_kwargs, **prompt_args ) @dispatcher.span def stream_structured_predict( self, output_cls: Type[Model], prompt: PromptTemplate, llm_kwargs: Optional[Dict[str, Any]] = None, **prompt_args: Any, ) -> Generator[Union[Model, FlexibleModel], None, None]: """Stream structured predict.""" llm_kwargs = llm_kwargs or {} llm_kwargs["tool_choice"] = ( "required" if "tool_choice" not in llm_kwargs else llm_kwargs["tool_choice"] ) # by default structured prediction uses function calling to extract structured outputs # here we force tool_choice to be required return super().stream_structured_predict( output_cls, prompt, llm_kwargs=llm_kwargs, **prompt_args ) @dispatcher.span async def astream_structured_predict( self, output_cls: Type[Model], prompt: PromptTemplate, llm_kwargs: Optional[Dict[str, Any]] = None, **prompt_args: Any, ) -> AsyncGenerator[Union[Model, FlexibleModel], None]: """Stream structured predict.""" llm_kwargs = llm_kwargs or {} llm_kwargs["tool_choice"] = ( "required" if "tool_choice" not in llm_kwargs else llm_kwargs["tool_choice"] ) # by default structured prediction uses function calling to extract structured outputs # here we force tool_choice to be required return await super().astream_structured_predict( output_cls, prompt, llm_kwargs=llm_kwargs, **prompt_args )
OpenAIResponses
python
tensorflow__tensorflow
tensorflow/python/distribute/coordinator/values.py
{ "start": 11564, "end": 12037 }
class ____(dataset_ops.DatasetSource): """Creates a dataset given a graph def.""" def __init__(self, graph_def, element_spec): self._elem_spec = element_spec variant_tensor = ged_ops.dataset_from_graph(graph_def) super(_RemoteDataset, self).__init__(variant_tensor) @property def element_spec(self): return self._elem_spec def deserialize_dataset_from_graph(graph_def, element_spec): return _RemoteDataset(graph_def, element_spec)
_RemoteDataset
python
pypa__packaging
src/packaging/pylock.py
{ "start": 863, "end": 7258 }
class ____(Protocol): # pragma: no cover @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: ... _FromMappingProtocolT = TypeVar("_FromMappingProtocolT", bound=_FromMappingProtocol) _PYLOCK_FILE_NAME_RE = re.compile(r"^pylock\.([^.]+)\.toml$") def is_valid_pylock_path(path: Path) -> bool: """Check if the given path is a valid pylock file path.""" return path.name == "pylock.toml" or bool(_PYLOCK_FILE_NAME_RE.match(path.name)) def _toml_key(key: str) -> str: return key.replace("_", "-") def _toml_value(key: str, value: Any) -> Any: # noqa: ANN401 if isinstance(value, (Version, Marker, SpecifierSet)): return str(value) if isinstance(value, Sequence) and key == "environments": return [str(v) for v in value] return value def _toml_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]: return { _toml_key(key): _toml_value(key, value) for key, value in data if value is not None } def _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None: """Get a value from the dictionary and verify it's the expected type.""" if (value := d.get(key)) is None: return None if not isinstance(value, expected_type): raise PylockValidationError( f"Unexpected type {type(value).__name__} " f"(expected {expected_type.__name__})", context=key, ) return value def _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T: """Get a required value from the dictionary and verify it's the expected type.""" if (value := _get(d, expected_type, key)) is None: raise _PylockRequiredKeyError(key) return value def _get_sequence( d: Mapping[str, Any], expected_item_type: type[_T], key: str ) -> Sequence[_T] | None: """Get a list value from the dictionary and verify it's the expected items type.""" if (value := _get(d, Sequence, key)) is None: # type: ignore[type-abstract] return None if isinstance(value, (str, bytes)): # special case: str and bytes are Sequences, but we want to reject it raise PylockValidationError( f"Unexpected type {type(value).__name__} (expected Sequence)", context=key, ) for i, item in enumerate(value): if not isinstance(item, expected_item_type): raise PylockValidationError( f"Unexpected type {type(item).__name__} " f"(expected {expected_item_type.__name__})", context=f"{key}[{i}]", ) return value def _get_as( d: Mapping[str, Any], expected_type: type[_T], target_type: Callable[[_T], _T2], key: str, ) -> _T2 | None: """Get a value from the dictionary, verify it's the expected type, and convert to the target type. This assumes the target_type constructor accepts the value. """ if (value := _get(d, expected_type, key)) is None: return None try: return target_type(value) except Exception as e: raise PylockValidationError(e, context=key) from e def _get_required_as( d: Mapping[str, Any], expected_type: type[_T], target_type: Callable[[_T], _T2], key: str, ) -> _T2: """Get a required value from the dict, verify it's the expected type, and convert to the target type.""" if (value := _get_as(d, expected_type, target_type, key)) is None: raise _PylockRequiredKeyError(key) return value def _get_sequence_as( d: Mapping[str, Any], expected_item_type: type[_T], target_item_type: Callable[[_T], _T2], key: str, ) -> list[_T2] | None: """Get list value from dictionary and verify expected items type.""" if (value := _get_sequence(d, expected_item_type, key)) is None: return None result = [] try: for item in value: typed_item = target_item_type(item) result.append(typed_item) except Exception as e: raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e return result def _get_object( d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str ) -> _FromMappingProtocolT | None: """Get a dictionary value from the dictionary and convert it to a dataclass.""" if (value := _get(d, Mapping, key)) is None: # type: ignore[type-abstract] return None try: return target_type._from_dict(value) except Exception as e: raise PylockValidationError(e, context=key) from e def _get_sequence_of_objects( d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str ) -> list[_FromMappingProtocolT] | None: """Get a list value from the dictionary and convert its items to a dataclass.""" if (value := _get_sequence(d, Mapping, key)) is None: # type: ignore[type-abstract] return None result: list[_FromMappingProtocolT] = [] try: for item in value: typed_item = target_item_type._from_dict(item) result.append(typed_item) except Exception as e: raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e return result def _get_required_sequence_of_objects( d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str ) -> Sequence[_FromMappingProtocolT]: """Get a required list value from the dictionary and convert its items to a dataclass.""" if (result := _get_sequence_of_objects(d, target_item_type, key)) is None: raise _PylockRequiredKeyError(key) return result def _validate_normalized_name(name: str) -> NormalizedName: """Validate that a string is a NormalizedName.""" if not is_normalized_name(name): raise PylockValidationError(f"Name {name!r} is not normalized") return NormalizedName(name) def _validate_path_url(path: str | None, url: str | None) -> None: if not path and not url: raise PylockValidationError("path or url must be provided") def _validate_hashes(hashes: Mapping[str, Any]) -> Mapping[str, Any]: if not hashes: raise PylockValidationError("At least one hash must be provided") if not all(isinstance(hash_val, str) for hash_val in hashes.values()): raise PylockValidationError("Hash values must be strings") return hashes
_FromMappingProtocol
python
sphinx-doc__sphinx
sphinx/util/osutil.py
{ "start": 6312, "end": 8298 }
class ____: """File-like object that buffers output and only writes if content changed. Use this class like when writing to a file to avoid touching the original file if the content hasn't changed. This is useful in scenarios where file mtime is used to invalidate caches or trigger new behavior. When writing to this file handle, all writes are buffered until the object is closed. Objects can be used as context managers. """ def __init__(self, path: str | Path) -> None: self._path = path self._io: StringIO | None = None def write(self, data: str) -> None: if not self._io: self._io = StringIO() self._io.write(data) def close(self) -> None: """Stop accepting writes and write file, if needed.""" if not self._io: msg = 'FileAvoidWrite does not support empty files.' raise Exception(msg) buf = self.getvalue() self._io.close() try: with open(self._path, encoding='utf-8') as old_f: old_content = old_f.read() if old_content == buf: return except OSError: pass with open(self._path, 'w', encoding='utf-8') as f: f.write(buf) def __enter__(self) -> Self: return self def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> bool: self.close() return True def __getattr__(self, name: str) -> Any: # Proxy to _io instance. if not self._io: msg = 'Must write to FileAvoidWrite before other methods can be used' raise Exception(msg) return getattr(self._io, name) def rmtree(path: str | os.PathLike[str], /) -> None: path = Path(path) if path.is_dir(): shutil.rmtree(path) else: os.remove(path)
FileAvoidWrite
python
pytorch__pytorch
torch/_numpy/_dtypes.py
{ "start": 1381, "end": 1476 }
class ____(signedinteger): name = "int8" typecode = "b" torch_dtype = torch.int8
int8
python
PyCQA__pylint
tests/functional/d/dataclass/dataclass_typecheck.py
{ "start": 528, "end": 1831 }
class ____: # Attribute inference does not support Optional, so Uninferable is yielded # This should not trigger any type errors from pylint attr0: Optional[Dummy] attr1: int attr2: str attr3: Callable[[int], int] attr4: List[int] attr5: Dict[str, str] OBJ = MyClass(None, 1, 'hi', lambda x: x, [], {}) LIST = [0, 1, 2] print(LIST[OBJ.attr0]) print(LIST[OBJ.attr1]) print(LIST[OBJ.attr2]) # [invalid-sequence-index] print(LIST[OBJ.attr0::]) print(LIST[OBJ.attr1::]) print(LIST[OBJ.attr2::]) # [invalid-slice-index] OBJ.attr0(100) OBJ.attr1(100) # [not-callable] OBJ.attr3(100) print(-OBJ.attr0) print(-OBJ.attr1) print(-OBJ.attr2) # [invalid-unary-operand-type] print(1 + OBJ.attr0) print(1 + OBJ.attr1) print(1 + OBJ.attr2) # Should be an error here once unsupported-binary-operation is enabled print(1 in OBJ.attr0) print(1 in OBJ.attr1) # [unsupported-membership-test] print(1 in OBJ.attr4) print('hi' in OBJ.attr5) print(OBJ.attr0[1]) print(OBJ.attr1[1]) # [unsubscriptable-object] print(OBJ.attr4[1]) print(OBJ.attr5['hi']) OBJ.attr0[1] = 1 OBJ.attr1[1] = 1 # [unsupported-assignment-operation] OBJ.attr4[1] = 1 OBJ.attr5['hi'] = 'bye' del OBJ.attr0[1] del OBJ.attr1[1] # [unsupported-delete-operation] del OBJ.attr4[1] del OBJ.attr5['hi']
MyClass
python
encode__django-rest-framework
tests/schemas/test_coreapi.py
{ "start": 17752, "end": 17846 }
class ____(ExampleViewSet): permission_classes = [DenyAllUsingHttp404]
Http404ExampleViewSet
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/model_query.py
{ "start": 689, "end": 749 }
class ____(Base): def bar(self, y): return 0
Child
python
gevent__gevent
src/gevent/tests/test__greenlet.py
{ "start": 30283, "end": 30654 }
class ____(greentest.TestCase): def test_start(self): g = gevent.spawn(gevent.sleep, timing.SMALL_TICK) self.assert_greenlet_spawned(g) g.start() self.assert_greenlet_started(g) g.join() self.assert_greenlet_finished(g) # cannot start again g.start() self.assert_greenlet_finished(g)
TestStart
python
plotly__plotly.py
plotly/graph_objs/funnel/_hoverlabel.py
{ "start": 233, "end": 11234 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "funnel" _path_str = "funnel.hoverlabel" _valid_props = { "align", "alignsrc", "bgcolor", "bgcolorsrc", "bordercolor", "bordercolorsrc", "font", "namelength", "namelengthsrc", "showarrow", } @property def align(self): """ Sets the horizontal alignment of the text content within hover label box. Has an effect only if the hover label text spans more two or more lines The 'align' property is an enumeration that may be specified as: - One of the following enumeration values: ['left', 'right', 'auto'] - A tuple, list, or one-dimensional numpy array of the above Returns ------- Any|numpy.ndarray """ return self["align"] @align.setter def align(self, val): self["align"] = val @property def alignsrc(self): """ Sets the source reference on Chart Studio Cloud for `align`. The 'alignsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["alignsrc"] @alignsrc.setter def alignsrc(self, val): self["alignsrc"] = val @property def bgcolor(self): """ Sets the background color of the hover labels for this trace The 'bgcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list - A list or array of any of the above Returns ------- str|numpy.ndarray """ return self["bgcolor"] @bgcolor.setter def bgcolor(self, val): self["bgcolor"] = val @property def bgcolorsrc(self): """ Sets the source reference on Chart Studio Cloud for `bgcolor`. The 'bgcolorsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["bgcolorsrc"] @bgcolorsrc.setter def bgcolorsrc(self, val): self["bgcolorsrc"] = val @property def bordercolor(self): """ Sets the border color of the hover labels for this trace. The 'bordercolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list - A list or array of any of the above Returns ------- str|numpy.ndarray """ return self["bordercolor"] @bordercolor.setter def bordercolor(self, val): self["bordercolor"] = val @property def bordercolorsrc(self): """ Sets the source reference on Chart Studio Cloud for `bordercolor`. The 'bordercolorsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["bordercolorsrc"] @bordercolorsrc.setter def bordercolorsrc(self, val): self["bordercolorsrc"] = val @property def font(self): """ Sets the font used in hover labels. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.funnel.hoverlabel.Font` - A dict of string/value properties that will be passed to the Font constructor Returns ------- plotly.graph_objs.funnel.hoverlabel.Font """ return self["font"] @font.setter def font(self, val): self["font"] = val @property def namelength(self): """ Sets the default length (in number of characters) of the trace name in the hover labels for all traces. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis. The 'namelength' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [-1, 9223372036854775807] - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|numpy.ndarray """ return self["namelength"] @namelength.setter def namelength(self, val): self["namelength"] = val @property def namelengthsrc(self): """ Sets the source reference on Chart Studio Cloud for `namelength`. The 'namelengthsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["namelengthsrc"] @namelengthsrc.setter def namelengthsrc(self, val): self["namelengthsrc"] = val @property def showarrow(self): """ Sets whether or not to show the hover label arrow/triangle pointing to the data point. The 'showarrow' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["showarrow"] @showarrow.setter def showarrow(self, val): self["showarrow"] = val @property def _prop_descriptions(self): return """\ align Sets the horizontal alignment of the text content within hover label box. Has an effect only if the hover label text spans more two or more lines alignsrc Sets the source reference on Chart Studio Cloud for `align`. bgcolor Sets the background color of the hover labels for this trace bgcolorsrc Sets the source reference on Chart Studio Cloud for `bgcolor`. bordercolor Sets the border color of the hover labels for this trace. bordercolorsrc Sets the source reference on Chart Studio Cloud for `bordercolor`. font Sets the font used in hover labels. namelength Sets the default length (in number of characters) of the trace name in the hover labels for all traces. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis. namelengthsrc Sets the source reference on Chart Studio Cloud for `namelength`. showarrow Sets whether or not to show the hover label arrow/triangle pointing to the data point. """ def __init__( self, arg=None, align=None, alignsrc=None, bgcolor=None, bgcolorsrc=None, bordercolor=None, bordercolorsrc=None, font=None, namelength=None, namelengthsrc=None, showarrow=None, **kwargs, ): """ Construct a new Hoverlabel object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.funnel.Hoverlabel` align Sets the horizontal alignment of the text content within hover label box. Has an effect only if the hover label text spans more two or more lines alignsrc Sets the source reference on Chart Studio Cloud for `align`. bgcolor Sets the background color of the hover labels for this trace bgcolorsrc Sets the source reference on Chart Studio Cloud for `bgcolor`. bordercolor Sets the border color of the hover labels for this trace. bordercolorsrc Sets the source reference on Chart Studio Cloud for `bordercolor`. font Sets the font used in hover labels. namelength Sets the default length (in number of characters) of the trace name in the hover labels for all traces. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis. namelengthsrc Sets the source reference on Chart Studio Cloud for `namelength`. showarrow Sets whether or not to show the hover label arrow/triangle pointing to the data point. Returns ------- Hoverlabel """ super().__init__("hoverlabel") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.funnel.Hoverlabel constructor must be a dict or an instance of :class:`plotly.graph_objs.funnel.Hoverlabel`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("align", arg, align) self._set_property("alignsrc", arg, alignsrc) self._set_property("bgcolor", arg, bgcolor) self._set_property("bgcolorsrc", arg, bgcolorsrc) self._set_property("bordercolor", arg, bordercolor) self._set_property("bordercolorsrc", arg, bordercolorsrc) self._set_property("font", arg, font) self._set_property("namelength", arg, namelength) self._set_property("namelengthsrc", arg, namelengthsrc) self._set_property("showarrow", arg, showarrow) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Hoverlabel
python
PyCQA__pylint
tests/functional/u/unsupported/unsupported_version_for_final.py
{ "start": 984, "end": 1108 }
class ____: @mytyping.final # [using-final-decorator-in-unsupported-version] def my_method(self): pass
MyClass4
python
has2k1__plotnine
plotnine/guides/guide.py
{ "start": 940, "end": 4898 }
class ____(ABC, metaclass=Register): """ Base class for all guides Notes ----- At the moment not all parameters have been fully implemented. """ title: Optional[str] = None """ Title of the guide. Default is the name of the aesthetic or the name specified using [](`~plotnine.components.labels.lab`) """ theme: Theme = field(default_factory=Theme) """A theme to style the guide. If `None`, the plots theme is used.""" position: Optional[LegendPosition] = None """Where to place the guide relative to the panels.""" direction: Optional[Orientation] = None """ Direction of the guide. The default is depends on [](`~plotnine.themes.themeable.legend_position`). """ reverse: bool = False """Whether to reverse the order of the legend keys.""" order: int = 0 """Order of this guide among multiple guides.""" # Non-Parameter Attributes available_aes: set[str] = field(init=False, default_factory=set) def __post_init__(self): self.hash: str self.key: pd.DataFrame self.plot_layers: Layers self.plot_mapping: aes self._elements_cls = GuideElements self.elements = cast("GuideElements", None) self.guides_elements: GuidesElements def legend_aesthetics(self, layer: layer): """ Return the aesthetics that contribute to the legend Parameters ---------- layer : Layer Layer whose legend is to be drawn Returns ------- matched : list List of the names of the aethetics that contribute to the legend. """ l = layer legend_ae = set(self.key.columns) - {"label"} all_ae = ( l.mapping.keys() | (self.plot_mapping if l.inherit_aes else set()) | l.stat.DEFAULT_AES.keys() ) geom_ae = l.geom.REQUIRED_AES | l.geom.DEFAULT_AES.keys() matched = all_ae & geom_ae & legend_ae matched = list(matched - set(l.geom.aes_params)) return matched def setup(self, guides: guides): """ Setup guide for drawing process """ # guide theme has priority and its targets are tracked # independently. self.theme = guides.plot.theme + self.theme self.theme.setup(guides.plot) self.plot_layers = guides.plot.layers self.plot_mapping = guides.plot.mapping self.elements = self._elements_cls(self.theme, self) self.guides_elements = guides.elements @property def _resolved_position_justification( self, ) -> tuple[Side, float] | tuple[tuple[float, float], tuple[float, float]]: """ Return the final position & justification to draw the guide """ pos = self.elements.position just_view = asdict(self.guides_elements.justification) if isinstance(pos, str): just = cast("float", just_view[pos]) return (pos, just) else: # If no justification is given for an inside legend, # we use the position of the legend if (just := just_view["inside"]) is None: just = pos just = cast("tuple[float, float]", just) return (pos, just) def train( self, scale: scale, aesthetic: Optional[str] = None ) -> Self | None: """ Create the key for the guide Returns guide if training is successful """ def draw(self) -> PackerBase: """ Draw guide """ raise NotImplementedError def create_geoms(self) -> Optional[Self]: """ Create layers of geoms for the guide Returns ------- : self if geom layers were create or None of no geom layers were created. """ raise NotImplementedError @dataclass
guide
python
huggingface__transformers
tests/models/aimv2/test_modeling_aimv2.py
{ "start": 7726, "end": 10883 }
class ____: def __init__( self, parent, batch_size=12, seq_length=7, is_training=False, use_input_mask=True, use_labels=True, vocab_size=99, hidden_size=32, projection_dim=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, dropout=0.1, attention_dropout=0.1, max_position_embeddings=25, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.use_input_mask = use_input_mask self.use_labels = use_labels self.vocab_size = vocab_size self.hidden_size = hidden_size self.projection_dim = projection_dim self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.dropout = dropout self.attention_dropout = attention_dropout self.max_position_embeddings = max_position_embeddings def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) input_mask = None if self.use_input_mask: input_mask = random_attention_mask([self.batch_size, self.seq_length]) if input_mask is not None: batch_size, seq_length = input_mask.shape rnd_start_indices = np.random.randint(1, seq_length - 1, size=(batch_size,)) for batch_idx, start_index in enumerate(rnd_start_indices): input_mask[batch_idx, :start_index] = 1 input_mask[batch_idx, start_index:] = 0 config = self.get_config() return config, input_ids, input_mask def get_config(self): return Aimv2TextConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, projection_dim=self.projection_dim, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, dropout=self.dropout, attention_dropout=self.attention_dropout, max_position_embeddings=self.max_position_embeddings, ) def create_and_check_model(self, config, input_ids, input_mask): model = Aimv2TextModel(config=config) model.to(torch_device) model.eval() with torch.no_grad(): result = model(input_ids, attention_mask=input_mask) result = model(input_ids) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, input_ids, input_mask = config_and_inputs inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch
Aimv2TextModelTester
python
tensorflow__tensorflow
tensorflow/python/distribute/distribute_coordinator_test.py
{ "start": 14302, "end": 21455 }
class ____(DistributeCoordinatorTestBase): def testInGraphStandaloneMode(self): """Test it runs in-graph replication in standalone client mode.""" distribute_coordinator.run_distribute_coordinator( self._in_graph_worker_fn, MockStrategy(between_graph=False), cluster_spec=self._cluster_spec) self.assertEqual(self._result_correct, 1) def testBetweenGraph(self): """Test it runs between-graph replication in standalone client mode.""" distribute_coordinator.run_distribute_coordinator( self._between_graph_worker_fn, MockStrategy(between_graph=True), cluster_spec=self._cluster_spec) # Each finished worker will increment self._result_correct. self.assertEqual(self._result_correct, NUM_WORKERS) @test_util.run_v1_only("MonitoredSession removed from v2") def testBetweenGraphWithMonitoredSession(self): """Test monitored session in standalone client mode.""" distribute_coordinator.run_distribute_coordinator( self._between_graph_with_monitored_session, MockStrategy(between_graph=True), cluster_spec=self._cluster_spec) # Each finished worker will increment self._result_correct. self.assertEqual(self._result_correct, NUM_WORKERS) def testBetweenGraphContext(self): # Dumps the task contexts to the self._worker_context dict. distribute_coordinator.run_distribute_coordinator( self._dump_worker_context, MockStrategy(between_graph=True), cluster_spec=self._cluster_spec) # There is only one type of task and there three such tasks. self.assertEqual(len(self._worker_context), 1) self.assertTrue(WORKER in self._worker_context) self.assertEqual(len(self._worker_context[WORKER]), NUM_WORKERS) # Check whether each task has the right master_target, num_workers, is_chief # and distributed_mode. self.assertEqual( self._worker_context[WORKER][0], (_bytes_to_str(self._workers[0].target), NUM_WORKERS, True, True)) self.assertEqual( self._worker_context[WORKER][1], (_bytes_to_str(self._workers[1].target), NUM_WORKERS, False, True)) self.assertEqual( self._worker_context[WORKER][2], (_bytes_to_str(self._workers[2].target), NUM_WORKERS, False, True)) def testBetweenGraphStrategyProperties(self): # Dumps properties of the strategy objects. distribute_coordinator.run_distribute_coordinator( self._dump_strategy_property, MockStrategy(between_graph=True, should_init=True), cluster_spec=self._cluster_spec) # There is only one type of task and there three such tasks. self.assertEqual(len(self._strategy_property), 1) self.assertTrue(WORKER in self._strategy_property) self.assertEqual(len(self._strategy_property[WORKER]), NUM_WORKERS) # Check whether each task has the right properties of should_init, # should_checkpoint and should_save_summary. self.assertEqual(self._strategy_property[WORKER][0], (True, True, True)) self.assertEqual(self._strategy_property[WORKER][1], (True, False, False)) self.assertEqual(self._strategy_property[WORKER][2], (True, False, False)) def testInGraphContext(self): # Dumps the task contexts to the self._worker_context dict. distribute_coordinator.run_distribute_coordinator( self._dump_worker_context, MockStrategy(between_graph=False), cluster_spec=self._cluster_spec) # There is only a "None" task in the dumped task context. self.assertEqual(len(self._worker_context), 1) self.assertTrue("None" in self._worker_context) self.assertEqual(len(self._worker_context["None"]), 1) # Check whether each task has the right master_target, num_workers, is_chief # and distributed_mode. self.assertEqual( self._worker_context["None"][0], (_bytes_to_str(self._workers[0].target), NUM_WORKERS, True, True)) def testLocalContext(self): # Dumps the task contexts to the self._worker_context dict. distribute_coordinator.run_distribute_coordinator( self._dump_worker_context, MockStrategy(between_graph=False), cluster_spec=None) # There is only a "None" task. self.assertEqual(len(self._worker_context), 1) self.assertTrue("None" in self._worker_context) self.assertEqual(len(self._worker_context["None"]), 1) # Check whether each task has the right master_target, num_workers, is_chief # and distributed_mode. self.assertEqual(self._worker_context["None"][0], ("", 0, True, False)) def testBetweenGraphContextWithChief(self): # Adds a chief node, so there are NUM_WORKERS + 1 workers in total. cluster_spec = copy.deepcopy(self._cluster_spec) cluster_spec[CHIEF] = ["fake_chief"] # Dumps the task contexts to the self._worker_context dict. distribute_coordinator.run_distribute_coordinator( self._dump_worker_context, MockStrategy(between_graph=True), cluster_spec=cluster_spec, rpc_layer="grpc") # There are one CHIEF and three workers. self.assertEqual(len(self._worker_context), 2) self.assertTrue(CHIEF in self._worker_context) self.assertTrue(WORKER in self._worker_context) self.assertEqual(len(self._worker_context[CHIEF]), 1) self.assertEqual(len(self._worker_context[WORKER]), NUM_WORKERS) # Check whether each task has the right master_target, num_workers, is_chief # and distributed_mode. self.assertEqual(self._worker_context[CHIEF][0], ("grpc://fake_chief", 4, True, True)) self.assertEqual( self._worker_context[WORKER][0], (_bytes_to_str(self._workers[0].target), NUM_WORKERS + 1, False, True)) self.assertEqual( self._worker_context[WORKER][1], (_bytes_to_str(self._workers[1].target), NUM_WORKERS + 1, False, True)) self.assertEqual( self._worker_context[WORKER][2], (_bytes_to_str(self._workers[2].target), NUM_WORKERS + 1, False, True)) def testInGraphContextWithEval(self): # Adds a EVALUATOR job. cluster_spec = copy.deepcopy(self._cluster_spec) cluster_spec[EVALUATOR] = ["fake_evaluator"] # Dumps the task contexts to the self._worker_context dict. distribute_coordinator.run_distribute_coordinator( self._dump_worker_context, MockStrategy(between_graph=False), cluster_spec=cluster_spec, rpc_layer=None) # There are one "None" task and one EVALUATOR task. self.assertEqual(len(self._worker_context), 2) self.assertTrue("None" in self._worker_context) self.assertTrue(EVALUATOR in self._worker_context) self.assertEqual(len(self._worker_context["None"]), 1) self.assertEqual(len(self._worker_context[EVALUATOR]), 1) # Check whether each task has the right master_target, num_workers, is_chief # and distributed_mode. self.assertEqual(self._worker_context["None"][0], (_strip_protocol( _bytes_to_str(self._workers[0].target)), 3, True, True)) self.assertEqual(self._worker_context[EVALUATOR][0], ("", 3, True, False))
DistributeCoordinatorTestStandaloneMode
python
pytorch__pytorch
torch/_guards.py
{ "start": 29544, "end": 39397 }
class ____: """ Provides the currently installed TracingContext, or None. Note that it is a staticmethod, and invocations outside of `with tracing()` (see below), are valid but will return None. """ @staticmethod def try_get() -> TracingContext | None: return getattr(_TLS, "tracing_context", None) @staticmethod def get() -> TracingContext: if ctx := TracingContext.try_get(): return ctx raise RuntimeError( "TracingContext.get() must be called within an ongoing trace." ) def __init__(self, fake_mode: Optional[FakeTensorMode]) -> None: self.guards_context = GuardsContext() self.module_context = ModuleContext() self.global_context = GlobalContext() self.previously_inlined_functions: dict[Any, Any] = dict() self.previously_cleaned_instructions: dict[Any, Any] = dict() self.fake_mode: Optional[FakeTensorMode] = fake_mode self.frame_summary_stack: list[traceback.FrameSummary] = [] # This is morally part of frame_summary_stack, but it is kept separate # for clarity. As we process a frame, this variable gets updated # to keep track of what line we are in the function. We make a # function call, this gets cleared and the frame location is pushed # to frame_summary_stack (prepping this variable for the inner frame's # progress) self.loc_in_frame: Optional[tuple[str, int, str]] = None # this is only set after aot_autograd self.fw_metadata: Optional[ViewAndMutationMeta] = None # this is only set when the DDPOptimizer is used self.ddp_optimizer_ctx: Optional[DDPOptimizerContext] = None # this is only set after aot_autograd self.aot_graph_name: Optional[list[str]] = None self.params_flat: Optional[list[Any]] = None self.params_flat_unwrap_subclasses: Optional[list[Any]] = None self.params_unwrapped_to_flat_index: Optional[list[Any]] = None # this is for extended return calling convention from backend # compiler to aot_autograd # Per output, what the compiler specified stride of the output is, # or None if no stride is known. This is always the HINT, it # is never a SymInt (it would be better if it was a SymInt, but # I can't conveniently get this from Inductor atm. Also, be # careful not to accidentally induce guards on the SymInt if # you ever do change this in aot_autograd.py; you should check # on permutations preferentially.) self.output_strides: list[tuple[int, ...] | None] | None = None # When this is True, whenever we encounter an int in Dynamo tracing, # we will (1) force unspec it and (2) force it as a size-like unbacked # integer. This is currently used when processing certain lists of # ints that are known to be size-like and may have 0/1 entries that we # must not specialize on. self.force_unspec_int_unbacked_size_like = False # See note [Tensor Fakification and Symbol Caching] self.tensor_to_context = WeakTensorKeyDictionary() # If this true, Aot Autograd will return output Fake Tensors with appropriate # meta on the first invocation # see note: [Returning Fake Tensors on First AOT Autograd Call] self.fakify_first_call = False self.hop_dispatch_set_cache = HopDispatchSetCache() # list of code objects for inlined functions self.traced_code: list[CodeType] = [] def clear(self) -> None: # Look at the note in output_graph.py in function `save_global_state` # for the context on clearing global context. self.global_context.global_state = {} self.previously_inlined_functions.clear() self.previously_cleaned_instructions.clear() @staticmethod @contextmanager def patch(**kwargs: Any) -> Generator[None, None, None]: prior = {} ctx = TracingContext.get() for key in kwargs: # KeyError on invalid entry prior[key] = getattr(ctx, key) for key, val in kwargs.items(): setattr(ctx, key, val) try: yield finally: for key, val in prior.items(): setattr(ctx, key, val) @staticmethod def extract_stack() -> traceback.StackSummary: self = TracingContext.try_get() if self is None: return traceback.StackSummary() stack = self.frame_summary_stack if self.loc_in_frame is not None: stack = stack + [self._populate_loc_in_frame_summary()] return traceback.StackSummary.from_list(stack) def _populate_loc_in_frame_summary(self) -> traceback.FrameSummary: assert self.loc_in_frame is not None filename, lineno, frame_name = self.loc_in_frame return traceback.FrameSummary(filename, lineno, frame_name, lookup_line=False) # Call this when you want to call into some code that isn't necessarily # associated with the current frame state @staticmethod @contextlib.contextmanager def clear_frame() -> Generator[None, None, None]: tc = TracingContext.get() with ( unittest.mock.patch.object(tc, "frame_summary_stack", []), unittest.mock.patch.object(tc, "loc_in_frame", None), ): try: yield except Exception as e: # Prevent real_stack from getting attached # # The invariant is that if an Exception as real_stack, we've # appropriately attached a user stack and we no longer need to # attach anything. Because we cannot conveniently interpose # when an exception is thrown, we instead interpose everywhere # we set what the user stack is set (using the context # manager). However, our compiler stack does "tail calls" # (when it calls into user compiler), at which point the # parent exception frames would incorrectly attach an # incorrect frame. # # However, if, somehow, someone raised an exception with this # scope that had a stack (for example, because they are # restoring the user stack state appropriately as they process # node by node), we should respect it. Thus, we cannot # unconditionally set None. if not hasattr(e, "real_stack"): e.real_stack = None # type: ignore[attr-defined] raise @staticmethod @contextlib.contextmanager def current_frame( frame_summary: Optional[traceback.FrameSummary], ) -> Generator[None, None, None]: # frame_summary can be None to solely take advantage of real_stack # attachment to thrown exceptions tc = TracingContext.get() if frame_summary is not None: tc.frame_summary_stack.append(frame_summary) old = tc.loc_in_frame tc.loc_in_frame = None try: yield except Exception as e: if not hasattr(e, "real_stack"): e.real_stack = tc.extract_stack() # type: ignore[attr-defined] raise finally: if frame_summary is not None: tc.frame_summary_stack.pop() tc.loc_in_frame = old @staticmethod @contextlib.contextmanager def report_output_strides() -> Generator[ Optional[list[Optional[tuple[int, ...]]]], None, None ]: tc = TracingContext.try_get() if tc is None: yield None return old_output_strides = tc.output_strides tc.output_strides = [] try: yield tc.output_strides finally: tc.output_strides = old_output_strides @staticmethod def set_current_loc(filename: str, lineno: int, frame_name: str) -> None: # Save the current location in the frame. Lazily generate the # framesummary. TracingContext.get().loc_in_frame = (filename, lineno, frame_name) @staticmethod def get_traced_code() -> Optional[list[CodeType]]: tc = TracingContext.try_get() if tc is None: return None return tc.traced_code @contextmanager def compile_context( context: Optional[CompileContext], ) -> Generator[Optional[CompileContext], None, None]: old_context = getattr(_TLS, "compile_context", None) _TLS.compile_context = context try: yield context finally: _TLS.compile_context = old_context @contextmanager def tracing( context: Optional[TracingContext], ) -> Generator[Optional[TracingContext], None, None]: """ This function installs the passed in tracing context as a dynamic scoped global variable. Calls to TracingContext.get() while not under a `with tracing()` context will return None. """ old_context = getattr(_TLS, "tracing_context", None) _TLS.tracing_context = context try: yield context except Exception as e: if not hasattr(e, "real_stack") and context is not None: e.real_stack = context.extract_stack() # type: ignore[attr-defined] raise finally: if ( context is not None and context.fake_mode is not None and context.fake_mode.shape_env is not None ): context.fake_mode.shape_env.cleanup() _TLS.tracing_context = old_context # Subclasses can be found in torch/_dynamo/source.py # TODO(voz): Consider a toplevel torch/_source.py @dataclasses.dataclass(frozen=True)
TracingContext
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 636396, "end": 637656 }
class ____(Geometry): """ LineString schema wrapper. LineString geometry object. https://tools.ietf.org/html/rfc7946#section-3.1.4 Parameters ---------- coordinates : Sequence[Sequence[float], :class:`Position`] type : Literal['LineString'] Specifies the type of GeoJSON object. bbox : :class:`BBox`, Sequence[float] Bounding box of the coordinate range of the object's Geometries, Features, or Feature Collections. The value of the bbox member is an array of length 2*n where n is the number of dimensions represented in the contained geometries, with all axes of the most southwesterly point followed by all axes of the more northeasterly point. The axes order of a bbox follows the axes order of geometries. https://tools.ietf.org/html/rfc7946#section-5 """ _schema = {"$ref": "#/definitions/LineString"} def __init__( self, coordinates: Optional[Sequence[SchemaBase | Sequence[float]]] = Undefined, type: Optional[Literal["LineString"]] = Undefined, bbox: Optional[SchemaBase | Sequence[float]] = Undefined, **kwds, ): super().__init__(coordinates=coordinates, type=type, bbox=bbox, **kwds)
LineString
python
pytorch__pytorch
test/test_datapipe.py
{ "start": 22537, "end": 22615 }
class ____(nn.Module): def forward(self, x): return x + 1
Add1Module
python
tensorflow__tensorflow
tensorflow/python/trackable/resource.py
{ "start": 2427, "end": 3049 }
class ____(type): """Metaclass for CapturableResource.""" def __call__(cls, *args, **kwargs): def default_resource_creator(next_creator, *a, **kw): assert next_creator is None obj = cls.__new__(cls, *a, **kw) obj.__init__(*a, **kw) return obj previous_getter = lambda *a, **kw: default_resource_creator(None, *a, **kw) resource_creator_stack = ops.get_default_graph()._resource_creator_stack for getter in resource_creator_stack[cls._resource_type()]: previous_getter = _make_getter(getter, previous_getter) return previous_getter(*args, **kwargs)
_ResourceMetaclass
python
huggingface__transformers
src/transformers/models/rembert/configuration_rembert.py
{ "start": 804, "end": 6551 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`RemBertModel`]. It is used to instantiate an RemBERT model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the RemBERT [google/rembert](https://huggingface.co/google/rembert) architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: vocab_size (`int`, *optional*, defaults to 250300): Vocabulary size of the RemBERT model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`RemBertModel`]. Vocabulary size of the model. Defines the different tokens that can be represented by the *inputs_ids* passed to the forward method of [`RemBertModel`]. hidden_size (`int`, *optional*, defaults to 1152): Dimensionality of the encoder layers and the pooler layer. num_hidden_layers (`int`, *optional*, defaults to 32): Number of hidden layers in the Transformer encoder. num_attention_heads (`int`, *optional*, defaults to 18): Number of attention heads for each attention layer in the Transformer encoder. input_embedding_size (`int`, *optional*, defaults to 256): Dimensionality of the input embeddings. output_embedding_size (`int`, *optional*, defaults to 1664): Dimensionality of the output embeddings. intermediate_size (`int`, *optional*, defaults to 4608): Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`): The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported. hidden_dropout_prob (`float`, *optional*, defaults to 0): The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. attention_probs_dropout_prob (`float`, *optional*, defaults to 0): The dropout ratio for the attention probabilities. classifier_dropout_prob (`float`, *optional*, defaults to 0.1): The dropout ratio for the classifier layer when fine-tuning. max_position_embeddings (`int`, *optional*, defaults to 512): The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). type_vocab_size (`int`, *optional*, defaults to 2): The vocabulary size of the `token_type_ids` passed when calling [`RemBertModel`]. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. layer_norm_eps (`float`, *optional*, defaults to 1e-12): The epsilon used by the layer normalization layers. is_decoder (`bool`, *optional*, defaults to `False`): Whether the model is used as a decoder or not. If `False`, the model is used as an encoder. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. Example: ```python >>> from transformers import RemBertModel, RemBertConfig >>> # Initializing a RemBERT rembert style configuration >>> configuration = RemBertConfig() >>> # Initializing a model from the rembert style configuration >>> model = RemBertModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "rembert" def __init__( self, vocab_size=250300, hidden_size=1152, num_hidden_layers=32, num_attention_heads=18, input_embedding_size=256, output_embedding_size=1664, intermediate_size=4608, hidden_act="gelu", hidden_dropout_prob=0.0, attention_probs_dropout_prob=0.0, classifier_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=2, initializer_range=0.02, layer_norm_eps=1e-12, use_cache=True, pad_token_id=0, bos_token_id=312, eos_token_id=313, **kwargs, ): super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs) self.vocab_size = vocab_size self.input_embedding_size = input_embedding_size self.output_embedding_size = output_embedding_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.classifier_dropout_prob = classifier_dropout_prob self.initializer_range = initializer_range self.type_vocab_size = type_vocab_size self.layer_norm_eps = layer_norm_eps self.use_cache = use_cache self.tie_word_embeddings = False __all__ = ["RemBertConfig"]
RemBertConfig
python
getsentry__sentry
tests/sentry/lang/native/test_symbolicator.py
{ "start": 4142, "end": 9623 }
class ____: def test_custom_untouched(self) -> None: debug_id = "451a38b5-0679-79d2-0738-22a5ceb24c4b" candidates = [ { "source": "custom", "location": "http://example.net/prefix/path", "download": {"status": "ok"}, }, ] response = {"modules": [{"debug_id": debug_id, "candidates": copy.copy(candidates)}]} redact_internal_sources(response) assert response["modules"][0]["candidates"] == candidates def test_location_debug_id(self) -> None: debug_id = "451a38b5-0679-79d2-0738-22a5ceb24c4b" candidates = [ { "source": "sentry:microsoft", "location": "http://microsoft.com/prefix/path0", "download": {"status": "ok"}, }, ] response = {"modules": [{"debug_id": debug_id, "candidates": copy.copy(candidates)}]} redact_internal_sources(response) expected = [{"source": "sentry:microsoft", "download": {"status": "ok"}}] assert response["modules"][0]["candidates"] == expected def test_notfound_deduplicated(self) -> None: debug_id = "451a38b5-0679-79d2-0738-22a5ceb24c4b" candidates = [ { "source": "sentry:microsoft", "location": "http://microsoft.com/prefix/path0", "download": {"status": "notfound"}, }, { "source": "sentry:microsoft", "location": "http://microsoft.com/prefix/path1", "download": {"status": "notfound"}, }, ] response = {"modules": [{"debug_id": debug_id, "candidates": copy.copy(candidates)}]} redact_internal_sources(response) expected = [{"source": "sentry:microsoft", "download": {"status": "notfound"}}] assert response["modules"][0]["candidates"] == expected def test_notfound_omitted(self) -> None: debug_id = "451a38b5-0679-79d2-0738-22a5ceb24c4b" candidates = [ { "source": "sentry:microsoft", "location": "http://microsoft.com/prefix/path0", "download": {"status": "notfound"}, }, { "source": "sentry:microsoft", "location": "http://microsoft.com/prefix/path1", "download": {"status": "ok"}, }, ] response = {"modules": [{"debug_id": debug_id, "candidates": copy.copy(candidates)}]} redact_internal_sources(response) expected = [{"source": "sentry:microsoft", "download": {"status": "ok"}}] assert response["modules"][0]["candidates"] == expected def test_multiple_notfound_filtered(self) -> None: debug_id = "451a38b5-0679-79d2-0738-22a5ceb24c4b" candidates = [ { "source": "sentry:microsoft", "location": "http://microsoft.com/prefix/path0", "download": {"status": "notfound"}, }, { "source": "sentry:microsoft", "location": "http://microsoft.com/prefix/path1", "download": {"status": "ok"}, }, { "source": "sentry:apple", "location": "http://microsoft.com/prefix/path0", "download": {"status": "notfound"}, }, { "source": "sentry:apple", "location": "http://microsoft.com/prefix/path1", "download": {"status": "ok"}, }, ] response = {"modules": [{"debug_id": debug_id, "candidates": copy.copy(candidates)}]} redact_internal_sources(response) expected = [ {"source": "sentry:microsoft", "download": {"status": "ok"}}, {"source": "sentry:apple", "download": {"status": "ok"}}, ] assert response["modules"][0]["candidates"] == expected def test_sentry_project(self) -> None: debug_id = "451a38b5-0679-79d2-0738-22a5ceb24c4b" candidates = [ { "source": "sentry:project", "location": "sentry://project_debug_file/123", "download": {"status": "ok"}, }, ] response = {"modules": [{"debug_id": debug_id, "candidates": copy.copy(candidates)}]} redact_internal_sources(response) expected = [ { "source": "sentry:project", "location": "sentry://project_debug_file/123", "download": {"status": "ok"}, }, ] assert response["modules"][0]["candidates"] == expected def test_sentry_project_notfound_no_location(self) -> None: # For sentry:project status=notfound the location needs to be removed debug_id = "451a38b5-0679-79d2-0738-22a5ceb24c4b" candidates = [ { "source": "sentry:project", "location": "Not the locacation you are looking for", "download": {"status": "notfound"}, }, ] response = {"modules": [{"debug_id": debug_id, "candidates": copy.copy(candidates)}]} redact_internal_sources(response) expected = [{"source": "sentry:project", "download": {"status": "notfound"}}] assert response["modules"][0]["candidates"] == expected
TestInternalSourcesRedaction
python
tensorflow__tensorflow
tensorflow/dtensor/python/d_variable.py
{ "start": 5549, "end": 10576 }
class ____(resource_variable_ops.ResourceVariable): """A replacement for tf.Variable which follows initial value placement. The class also handles restore/save operations in DTensor. Note that, DVariable may fall back to normal tf.Variable at this moment if `initial_value` is not a DTensor. """ def __init__(self, initial_value, *args, dtype=None, **kwargs): """Overrides tf.Variable to fix VarHandleOp placements.""" # Variables by default use the current device scope for placement. This # wrapper has them follow the initial value's placement instead (which will # be the DTensor device if the initial value has a layout). # Pop layout from kwargs since keras make_variable may pass a 'layout' # keyword argument. We need to pop it because we are passing kwargs to # super class constructor. layout = kwargs.pop('layout', None) shape = kwargs.get('shape', None) if callable(initial_value): unwrapped = initial_value if issubclass(type(initial_value), functools.partial): unwrapped = initial_value.func # If wrapped is a CheckpointInitialValueCallable, this means that # we are creating a Variable during a checkpoint restore. # Thus the restore will happen now through this callable # and we will create the DVariable with the restored dtensor. if issubclass(type(unwrapped), trackable.CheckpointInitialValueCallable): if not shape or not layout: raise ValueError('Expected shape and layout to be not None.') # CheckpointInitialValueCallable will call an eager tf.RestoreV2, # which does not have any shape information or layout information # attached. Thus we will do two things to have them correctly specified: # # The default layout scope allows us to correctly specify the output # layout of the tf.RestoreV2 that will be called # # Passing shard_info with the correct shape allows the tf.RestoreV2 # ShapeInference to extract the shape. initial_value = api.call_with_layout( initial_value, layout, shard_info=trackable.ShardInfo( shape=shape, offset=[0] * len(shape))) else: initial_value = initial_value() # When the initial value came from a Checkpoint restoration, fetch tensor. if isinstance(initial_value, trackable.CheckpointInitialValue): initial_value = initial_value.wrapped_value initial_value = ops.convert_to_tensor(initial_value, dtype=dtype) variable_device = initial_value.device self._save_as_bf16 = False # TODO(b/159035705): The following code enables variable creation inside # a tf.function. However, it requires a global dtensor device. # if not variable_device and not tf.executing_eagerly(): # try: # initial_value.op.get_attr("_layout") # except ValueError: # pass # else: # # The initial value is a DTensor, but because the DTensor device is # # only active during eager execution at the moment we need to # # translate that into a placement for the eager VarHandleOp. # variable_device = _dtensor_device().name with ops.device(variable_device): # If initial tensor assigned to DVariable is DTensor, record the layout of # the resource so that this can be queried. if context.executing_eagerly(): if api.is_dtensor(initial_value): value_layout = api.fetch_layout(initial_value) if layout is not None and layout != value_layout: raise errors_impl.InvalidArgumentError( None, None, 'Conflicting layout are provided for initial ' f'value layout ({value_layout}) and variable ({layout}).', ) layout = value_layout elif layout is not None: initial_value = api.relayout(initial_value, layout) else: raise errors_impl.InvalidArgumentError( None, None, 'Neither layout nor DTensor initial value are provided.', ) self.layout = layout with api.default_mesh(layout.mesh): super(DVariable, self).__init__( initial_value, *args, dtype=dtype, **kwargs ) else: # FIXME(175928457): Record value layout in graph mode. if layout is not None: initial_value = api.relayout(initial_value, layout) super(DVariable, self).__init__( initial_value, *args, dtype=dtype, **kwargs) @property def save_as_bf16(self): return self._save_as_bf16 @save_as_bf16.setter def save_as_bf16(self, save_as_bf16): """Enables saving float32 as bfloat16.""" self._save_as_bf16 = save_as_bf16 and self.dtype == dtypes.float32 def _gather_saveables_for_checkpoint(self): return { trackable.VARIABLE_VALUE_KEY: functools.partial(_DVariableSaveable, self) }
DVariable
python
PyCQA__pylint
tests/functional/a/alternative/alternative_union_syntax_py37.py
{ "start": 1622, "end": 1922 }
class ____(typing.NamedTuple): my_var: int | str # Check typing.TypedDict CustomTypedDict = TypedDict("CustomTypedDict", my_var=int | str) # [unsupported-binary-operation] CustomTypedDict2 = TypedDict("CustomTypedDict2", {"my_var": int | str}) # [unsupported-binary-operation]
CustomNamedTuple3
python
fluentpython__example-code-2e
23-descriptor/method_is_descriptor.py
{ "start": 918, "end": 1104 }
class ____(collections.UserString): def __repr__(self): return 'Text({!r})'.format(self.data) def reverse(self): return self[::-1] # end::FUNC_DESCRIPTOR_EX[]
Text
python
scrapy__scrapy
tests/test_middleware.py
{ "start": 674, "end": 846 }
class ____: def open_spider(self, spider): pass def close_spider(self, spider): pass def __init__(self): raise NotConfigured("foo")
MOff
python
django__django
tests/queries/models.py
{ "start": 2199, "end": 2627 }
class ____(models.Model): name = models.CharField(max_length=10) created = models.DateTimeField() modified = models.DateTimeField(blank=True, null=True) tags = models.ManyToManyField(Tag, blank=True) creator = models.ForeignKey(Author, models.CASCADE) note = models.ForeignKey(Note, models.CASCADE) class Meta: ordering = ["-note", "name"] def __str__(self): return self.name
Item
python
mlflow__mlflow
mlflow/store/artifact/azure_blob_artifact_repo.py
{ "start": 862, "end": 12451 }
class ____(ArtifactRepository, MultipartUploadMixin): """ Stores artifacts on Azure Blob Storage. This repository is used with URIs of the form ``wasbs://<container-name>@<ystorage-account-name>.blob.core.windows.net/<path>``, following the same URI scheme as Hadoop on Azure blob storage. It requires either that: - Azure storage connection string is in the env var ``AZURE_STORAGE_CONNECTION_STRING`` - Azure storage access key is in the env var ``AZURE_STORAGE_ACCESS_KEY`` - DefaultAzureCredential is configured """ def __init__( self, artifact_uri: str, client=None, tracking_uri: str | None = None, registry_uri: str | None = None, ) -> None: super().__init__(artifact_uri, tracking_uri, registry_uri) _DEFAULT_TIMEOUT = 600 # 10 minutes self.write_timeout = MLFLOW_ARTIFACT_UPLOAD_DOWNLOAD_TIMEOUT.get() or _DEFAULT_TIMEOUT # Allow override for testing if client: self.client = client return from azure.storage.blob import BlobServiceClient (_, account, _, api_uri_suffix) = AzureBlobArtifactRepository.parse_wasbs_uri(artifact_uri) if "AZURE_STORAGE_CONNECTION_STRING" in os.environ: self.client = BlobServiceClient.from_connection_string( conn_str=os.environ.get("AZURE_STORAGE_CONNECTION_STRING"), connection_verify=get_default_host_creds(artifact_uri).verify, ) elif "AZURE_STORAGE_ACCESS_KEY" in os.environ: account_url = f"https://{account}.{api_uri_suffix}" self.client = BlobServiceClient( account_url=account_url, credential=os.environ.get("AZURE_STORAGE_ACCESS_KEY"), connection_verify=get_default_host_creds(artifact_uri).verify, ) else: try: from azure.identity import DefaultAzureCredential except ImportError as exc: raise ImportError( "Using DefaultAzureCredential requires the azure-identity package. " "Please install it via: pip install azure-identity" ) from exc account_url = f"https://{account}.{api_uri_suffix}" self.client = BlobServiceClient( account_url=account_url, credential=DefaultAzureCredential(), connection_verify=get_default_host_creds(artifact_uri).verify, ) @staticmethod def parse_wasbs_uri(uri): """Parse a wasbs:// URI, returning (container, storage_account, path, api_uri_suffix).""" parsed = urllib.parse.urlparse(uri) if parsed.scheme != "wasbs": raise Exception(f"Not a WASBS URI: {uri}") match = re.match( r"([^@]+)@([^.]+)\.(blob\.core\.(windows\.net|chinacloudapi\.cn))", parsed.netloc ) if match is None: raise Exception( "WASBS URI must be of the form " "<container>@<account>.blob.core.windows.net" " or <container>@<account>.blob.core.chinacloudapi.cn" ) container = match.group(1) storage_account = match.group(2) api_uri_suffix = match.group(3) path = parsed.path path = path.removeprefix("/") return container, storage_account, path, api_uri_suffix def log_artifact(self, local_file, artifact_path=None): (container, _, dest_path, _) = self.parse_wasbs_uri(self.artifact_uri) container_client = self.client.get_container_client(container) if artifact_path: dest_path = posixpath.join(dest_path, artifact_path) dest_path = posixpath.join(dest_path, os.path.basename(local_file)) with open(local_file, "rb") as file: container_client.upload_blob( dest_path, file, overwrite=True, timeout=self.write_timeout ) def log_artifacts(self, local_dir, artifact_path=None): (container, _, dest_path, _) = self.parse_wasbs_uri(self.artifact_uri) container_client = self.client.get_container_client(container) if artifact_path: dest_path = posixpath.join(dest_path, artifact_path) local_dir = os.path.abspath(local_dir) for root, _, filenames in os.walk(local_dir): upload_path = dest_path if root != local_dir: rel_path = os.path.relpath(root, local_dir) upload_path = posixpath.join(dest_path, rel_path) for f in filenames: remote_file_path = posixpath.join(upload_path, f) local_file_path = os.path.join(root, f) with open(local_file_path, "rb") as file: container_client.upload_blob( remote_file_path, file, overwrite=True, timeout=self.write_timeout ) def list_artifacts(self, path=None): # Newer versions of `azure-storage-blob` (>= 12.4.0) provide a public # `azure.storage.blob.BlobPrefix` object to signify that a blob is a directory, # while older versions only expose this API internally as # `azure.storage.blob._models.BlobPrefix` try: from azure.storage.blob import BlobPrefix except ImportError: from azure.storage.blob._models import BlobPrefix def is_dir(result): return isinstance(result, BlobPrefix) (container, _, artifact_path, _) = self.parse_wasbs_uri(self.artifact_uri) container_client = self.client.get_container_client(container) dest_path = artifact_path if path: dest_path = posixpath.join(dest_path, path) infos = [] prefix = dest_path if dest_path.endswith("/") else dest_path + "/" results = container_client.walk_blobs(name_starts_with=prefix) for result in results: if ( dest_path == result.name ): # result isn't actually a child of the path we're interested in, so skip it continue if not result.name.startswith(artifact_path): raise MlflowException( "The name of the listed Azure blob does not begin with the specified" f" artifact path. Artifact path: {artifact_path}. Blob name: {result.name}" ) if is_dir(result): subdir = posixpath.relpath(path=result.name, start=artifact_path) subdir = subdir.removesuffix("/") infos.append(FileInfo(subdir, is_dir=True, file_size=None)) else: # Just a plain old blob file_name = posixpath.relpath(path=result.name, start=artifact_path) infos.append(FileInfo(file_name, is_dir=False, file_size=result.size)) # The list_artifacts API expects us to return an empty list if the # the path references a single file. rel_path = dest_path[len(artifact_path) + 1 :] if (len(infos) == 1) and not infos[0].is_dir and (infos[0].path == rel_path): return [] return sorted(infos, key=lambda f: f.path) def _download_file(self, remote_file_path, local_path): (container, _, remote_root_path, _) = self.parse_wasbs_uri(self.artifact_uri) container_client = self.client.get_container_client(container) remote_full_path = posixpath.join(remote_root_path, remote_file_path) blob = container_client.download_blob(remote_full_path) with open(local_path, "wb") as file: blob.readinto(file) def delete_artifacts(self, artifact_path=None): from azure.core.exceptions import ResourceNotFoundError (container, _, dest_path, _) = self.parse_wasbs_uri(self.artifact_uri) container_client = self.client.get_container_client(container) if artifact_path: dest_path = posixpath.join(dest_path, artifact_path) try: blobs = container_client.list_blobs(name_starts_with=dest_path) blob_list = list(blobs) if not blob_list: raise MlflowException(f"No such file or directory: '{dest_path}'") for blob in blob_list: container_client.delete_blob(blob.name) except ResourceNotFoundError: raise MlflowException(f"No such file or directory: '{dest_path}'") def create_multipart_upload(self, local_file, num_parts=1, artifact_path=None): from azure.storage.blob import BlobSasPermissions, generate_blob_sas (container, _, dest_path, _) = self.parse_wasbs_uri(self.artifact_uri) if artifact_path: dest_path = posixpath.join(dest_path, artifact_path) dest_path = posixpath.join(dest_path, os.path.basename(local_file)) # Put Block: https://learn.microsoft.com/en-us/rest/api/storageservices/put-block?tabs=microsoft-entra-id # SDK: https://learn.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.blobclient?view=azure-python#azure-storage-blob-blobclient-stage-block blob_url = posixpath.join(self.client.url, container, dest_path) sas_token = generate_blob_sas( account_name=self.client.account_name, container_name=container, blob_name=dest_path, account_key=self.client.credential.account_key, permission=BlobSasPermissions(read=True, write=True), expiry=datetime.datetime.now(timezone.utc) + datetime.timedelta(hours=1), ) credentials = [] for i in range(1, num_parts + 1): block_id = f"mlflow_block_{i}" # see https://github.com/Azure/azure-sdk-for-python/blob/18a66ef98c6f2153491489d3d7d2fe4a5849e4ac/sdk/storage/azure-storage-blob/azure/storage/blob/_blob_client.py#L2468 safe_block_id = urllib.parse.quote(encode_base64(block_id), safe="") url = f"{blob_url}?comp=block&blockid={safe_block_id}&{sas_token}" credentials.append( MultipartUploadCredential( url=url, part_number=i, headers={}, ) ) return CreateMultipartUploadResponse( credentials=credentials, upload_id=None, ) def complete_multipart_upload(self, local_file, upload_id, parts=None, artifact_path=None): (container, _, dest_path, _) = self.parse_wasbs_uri(self.artifact_uri) if artifact_path: dest_path = posixpath.join(dest_path, artifact_path) dest_path = posixpath.join(dest_path, os.path.basename(local_file)) block_ids = [] for part in parts: qs = urllib.parse.urlparse(part.url).query block_id = urllib.parse.parse_qs(qs)["blockid"][0] block_id = decode_base64(urllib.parse.unquote(block_id)) block_ids.append(block_id) blob_client = self.client.get_blob_client(container, dest_path) blob_client.commit_block_list(block_ids) def abort_multipart_upload(self, local_file, upload_id, artifact_path=None): # There is no way to delete uncommitted blocks in Azure Blob Storage. # Instead, they are garbage collected within 7 days. # See https://docs.microsoft.com/en-us/rest/api/storageservices/put-block-list#remarks # The blob may already exist so we cannot delete it either. pass
AzureBlobArtifactRepository
python
plotly__plotly.py
plotly/graph_objs/scatterternary/selected/_textfont.py
{ "start": 233, "end": 2456 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scatterternary.selected" _path_str = "scatterternary.selected.textfont" _valid_props = {"color"} @property def color(self): """ Sets the text font color of selected points. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["color"] @color.setter def color(self, val): self["color"] = val @property def _prop_descriptions(self): return """\ color Sets the text font color of selected points. """ def __init__(self, arg=None, color=None, **kwargs): """ Construct a new Textfont object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scatterternary .selected.Textfont` color Sets the text font color of selected points. Returns ------- Textfont """ super().__init__("textfont") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.scatterternary.selected.Textfont constructor must be a dict or an instance of :class:`plotly.graph_objs.scatterternary.selected.Textfont`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("color", arg, color) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Textfont
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/linalg/linear_operator_block_diag_test.py
{ "start": 2466, "end": 16223 }
class ____( linear_operator_test_util.SquareLinearOperatorDerivedClassTest): """Most tests done in the base class LinearOperatorDerivedClassTest.""" def tearDown(self): config.enable_tensor_float_32_execution(self.tf32_keep_) def setUp(self): self.tf32_keep_ = config.tensor_float_32_execution_enabled() config.enable_tensor_float_32_execution(False) # Increase from 1e-6 to 1e-4 self._atol[dtypes.float32] = 1e-4 self._atol[dtypes.complex64] = 1e-4 self._rtol[dtypes.float32] = 1e-4 self._rtol[dtypes.complex64] = 1e-4 @staticmethod def optional_tests(): """List of optional test names to run.""" return [ "operator_matmul_with_same_type", "operator_solve_with_same_type", ] @staticmethod def operator_shapes_infos(): shape_info = linear_operator_test_util.OperatorShapesInfo return [ shape_info((0, 0)), shape_info((1, 1)), shape_info((1, 3, 3)), shape_info((5, 5), blocks=[(2, 2), (3, 3)]), shape_info((3, 7, 7), blocks=[(1, 2, 2), (3, 2, 2), (1, 3, 3)]), shape_info((2, 1, 5, 5), blocks=[(2, 1, 2, 2), (1, 3, 3)]), ] @staticmethod def use_blockwise_arg(): return True def operator_and_matrix( self, shape_info, dtype, use_placeholder, ensure_self_adjoint_and_pd=False): shape = list(shape_info.shape) expected_blocks = ( shape_info.__dict__["blocks"] if "blocks" in shape_info.__dict__ else [shape]) matrices = [ linear_operator_test_util.random_positive_definite_matrix( block_shape, dtype, force_well_conditioned=True) for block_shape in expected_blocks ] lin_op_matrices = matrices if use_placeholder: lin_op_matrices = [ array_ops.placeholder_with_default( matrix, shape=None) for matrix in matrices] operator = block_diag.LinearOperatorBlockDiag( [linalg.LinearOperatorFullMatrix( l, is_square=True, is_self_adjoint=True if ensure_self_adjoint_and_pd else None, is_positive_definite=True if ensure_self_adjoint_and_pd else None) for l in lin_op_matrices]) # Should be auto-set. self.assertTrue(operator.is_square) # Broadcast the shapes. expected_shape = list(shape_info.shape) matrices = linear_operator_util.broadcast_matrix_batch_dims(matrices) block_diag_dense = _block_diag_dense(expected_shape, matrices) if not use_placeholder: block_diag_dense.set_shape( expected_shape[:-2] + [expected_shape[-1], expected_shape[-1]]) return operator, block_diag_dense def test_is_x_flags(self): # Matrix with two positive eigenvalues, 1, and 1. # The matrix values do not effect auto-setting of the flags. matrix = [[1., 0.], [1., 1.]] operator = block_diag.LinearOperatorBlockDiag( [linalg.LinearOperatorFullMatrix(matrix)], is_positive_definite=True, is_non_singular=True, is_self_adjoint=False) self.assertTrue(operator.is_positive_definite) self.assertTrue(operator.is_non_singular) self.assertFalse(operator.is_self_adjoint) def test_is_x_parameters(self): matrix = [[1., 0.], [1., 1.]] sub_operator = linalg.LinearOperatorFullMatrix(matrix) operator = block_diag.LinearOperatorBlockDiag( [sub_operator], is_positive_definite=True, is_non_singular=True, is_self_adjoint=False) self.assertEqual( operator.parameters, { "name": None, "is_square": True, "is_positive_definite": True, "is_self_adjoint": False, "is_non_singular": True, "operators": [sub_operator], }) self.assertEqual( sub_operator.parameters, { "is_non_singular": None, "is_positive_definite": None, "is_self_adjoint": None, "is_square": None, "matrix": matrix, "name": "LinearOperatorFullMatrix", }) def test_block_diag_adjoint_type(self): matrix = [[1., 0.], [0., 1.]] operator = block_diag.LinearOperatorBlockDiag( [ linalg.LinearOperatorFullMatrix( matrix, is_non_singular=True, ), linalg.LinearOperatorFullMatrix( matrix, is_non_singular=True, ), ], is_non_singular=True, ) adjoint = operator.adjoint() self.assertIsInstance( adjoint, block_diag.LinearOperatorBlockDiag) self.assertEqual(2, len(adjoint.operators)) def test_block_diag_cholesky_type(self): matrix = [[1., 0.], [0., 1.]] operator = block_diag.LinearOperatorBlockDiag( [ linalg.LinearOperatorFullMatrix( matrix, is_positive_definite=True, is_self_adjoint=True, ), linalg.LinearOperatorFullMatrix( matrix, is_positive_definite=True, is_self_adjoint=True, ), ], is_positive_definite=True, is_self_adjoint=True, ) cholesky_factor = operator.cholesky() self.assertIsInstance( cholesky_factor, block_diag.LinearOperatorBlockDiag) self.assertEqual(2, len(cholesky_factor.operators)) self.assertIsInstance( cholesky_factor.operators[0], lower_triangular.LinearOperatorLowerTriangular) self.assertIsInstance( cholesky_factor.operators[1], lower_triangular.LinearOperatorLowerTriangular ) def test_block_diag_inverse_type(self): matrix = [[1., 0.], [0., 1.]] operator = block_diag.LinearOperatorBlockDiag( [ linalg.LinearOperatorFullMatrix( matrix, is_non_singular=True, ), linalg.LinearOperatorFullMatrix( matrix, is_non_singular=True, ), ], is_non_singular=True, ) inverse = operator.inverse() self.assertIsInstance( inverse, block_diag.LinearOperatorBlockDiag) self.assertEqual(2, len(inverse.operators)) def test_block_diag_matmul_type(self): matrices1 = [] matrices2 = [] for i in range(1, 5): matrices1.append(linalg.LinearOperatorFullMatrix( linear_operator_test_util.random_normal( [2, i], dtype=dtypes.float32))) matrices2.append(linalg.LinearOperatorFullMatrix( linear_operator_test_util.random_normal( [i, 3], dtype=dtypes.float32))) operator1 = block_diag.LinearOperatorBlockDiag(matrices1, is_square=False) operator2 = block_diag.LinearOperatorBlockDiag(matrices2, is_square=False) expected_matrix = math_ops.matmul( operator1.to_dense(), operator2.to_dense()) actual_operator = operator1.matmul(operator2) self.assertIsInstance( actual_operator, block_diag.LinearOperatorBlockDiag) actual_, expected_ = self.evaluate([ actual_operator.to_dense(), expected_matrix]) self.assertAllClose(actual_, expected_) def test_block_diag_matmul_raises(self): matrices1 = [] for i in range(1, 5): matrices1.append(linalg.LinearOperatorFullMatrix( linear_operator_test_util.random_normal( [2, i], dtype=dtypes.float32))) operator1 = block_diag.LinearOperatorBlockDiag(matrices1, is_square=False) operator2 = linalg.LinearOperatorFullMatrix( linear_operator_test_util.random_normal( [15, 3], dtype=dtypes.float32)) with self.assertRaisesRegex(ValueError, "Operators are incompatible"): operator1.matmul(operator2) def test_block_diag_solve_type(self): matrices1 = [] matrices2 = [] for i in range(1, 5): matrices1.append(linalg.LinearOperatorFullMatrix( linear_operator_test_util.random_tril_matrix( [i, i], dtype=dtypes.float32, force_well_conditioned=True))) matrices2.append(linalg.LinearOperatorFullMatrix( linear_operator_test_util.random_normal( [i, 3], dtype=dtypes.float32))) operator1 = block_diag.LinearOperatorBlockDiag(matrices1) operator2 = block_diag.LinearOperatorBlockDiag(matrices2, is_square=False) expected_matrix = linalg.solve( operator1.to_dense(), operator2.to_dense()) actual_operator = operator1.solve(operator2) self.assertIsInstance( actual_operator, block_diag.LinearOperatorBlockDiag) actual_, expected_ = self.evaluate([ actual_operator.to_dense(), expected_matrix]) self.assertAllClose(actual_, expected_) def test_block_diag_solve_raises(self): matrices1 = [] for i in range(1, 5): matrices1.append(linalg.LinearOperatorFullMatrix( linear_operator_test_util.random_normal( [i, i], dtype=dtypes.float32))) operator1 = block_diag.LinearOperatorBlockDiag(matrices1) operator2 = linalg.LinearOperatorFullMatrix( linear_operator_test_util.random_normal( [15, 3], dtype=dtypes.float32)) with self.assertRaisesRegex(ValueError, "Operators are incompatible"): operator1.solve(operator2) def test_tape_safe(self): matrices = [] for _ in range(4): matrices.append(variables_module.Variable( linear_operator_test_util.random_positive_definite_matrix( [2, 2], dtype=dtypes.float32, force_well_conditioned=True))) operator = block_diag.LinearOperatorBlockDiag( [linalg.LinearOperatorFullMatrix( matrix, is_self_adjoint=True, is_positive_definite=True) for matrix in matrices], is_self_adjoint=True, is_positive_definite=True, ) self.check_tape_safe(operator) def test_convert_variables_to_tensors(self): matrices = [] for _ in range(3): matrices.append(variables_module.Variable( linear_operator_test_util.random_positive_definite_matrix( [3, 3], dtype=dtypes.float32, force_well_conditioned=True))) operator = block_diag.LinearOperatorBlockDiag( [linalg.LinearOperatorFullMatrix( matrix, is_self_adjoint=True, is_positive_definite=True) for matrix in matrices], is_self_adjoint=True, is_positive_definite=True, ) with self.cached_session() as sess: sess.run([x.initializer for x in operator.variables]) self.check_convert_variables_to_tensors(operator) def test_composite_gradients(self): with backprop.GradientTape() as tape: op1 = linalg.LinearOperatorFullMatrix([[1., 0.], [0., 1.]]) op2 = linalg.LinearOperatorDiag([1., 2., 3.]) tape.watch([op1, op2]) operator = block_diag.LinearOperatorBlockDiag([op1, op2]) x = self.make_x(op1, adjoint=False) y = op1.matmul(x) connected_grad, disconnected_grad, composite_grad = tape.gradient( y, [op1, op2, operator] ) disconnected_component_grad = composite_grad.operators[1].to_dense() self.assertAllClose(connected_grad.to_dense(), composite_grad.operators[0].to_dense()) self.assertAllClose(disconnected_component_grad, array_ops.zeros_like(disconnected_component_grad)) self.assertIsNone(disconnected_grad) def test_is_non_singular_auto_set(self): # Matrix with two positive eigenvalues, 11 and 8. # The matrix values do not effect auto-setting of the flags. matrix = [[11., 0.], [1., 8.]] operator_1 = linalg.LinearOperatorFullMatrix(matrix, is_non_singular=True) operator_2 = linalg.LinearOperatorFullMatrix(matrix, is_non_singular=True) operator = block_diag.LinearOperatorBlockDiag( [operator_1, operator_2], is_positive_definite=False, # No reason it HAS to be False... is_non_singular=None) self.assertFalse(operator.is_positive_definite) self.assertTrue(operator.is_non_singular) with self.assertRaisesRegex(ValueError, "always non-singular"): block_diag.LinearOperatorBlockDiag( [operator_1, operator_2], is_non_singular=False) def test_name(self): matrix = [[11., 0.], [1., 8.]] operator_1 = linalg.LinearOperatorFullMatrix(matrix, name="left") operator_2 = linalg.LinearOperatorFullMatrix(matrix, name="right") operator = block_diag.LinearOperatorBlockDiag([operator_1, operator_2]) self.assertEqual("left_ds_right", operator.name) def test_different_dtypes_raises(self): operators = [ linalg.LinearOperatorFullMatrix(rng.rand(2, 3, 3)), linalg.LinearOperatorFullMatrix(rng.rand(2, 3, 3).astype(np.float32)) ] with self.assertRaisesRegex(TypeError, "same dtype"): block_diag.LinearOperatorBlockDiag(operators) def test_empty_operators_raises(self): with self.assertRaisesRegex(ValueError, "non-empty"): block_diag.LinearOperatorBlockDiag([]) def test_incompatible_input_blocks_raises(self): matrix_1 = array_ops.placeholder_with_default(rng.rand(4, 4), shape=None) matrix_2 = array_ops.placeholder_with_default(rng.rand(3, 3), shape=None) operators = [ linalg.LinearOperatorFullMatrix(matrix_1, is_square=True), linalg.LinearOperatorFullMatrix(matrix_2, is_square=True) ] operator = block_diag.LinearOperatorBlockDiag(operators) x = np.random.rand(2, 4, 5).tolist() msg = ("dimension does not match" if context.executing_eagerly() else "input structure is ambiguous") with self.assertRaisesRegex(ValueError, msg): operator.matmul(x) @test_util.run_all_in_graph_and_eager_modes
SquareLinearOperatorBlockDiagTest
python
getsentry__sentry
src/sentry/issues/grouptype.py
{ "start": 2229, "end": 4969 }
class ____: _registry: dict[int, type[GroupType]] = field(default_factory=dict) _slug_lookup: dict[str, type[GroupType]] = field(default_factory=dict) _category_lookup: dict[int, set[int]] = field(default_factory=lambda: defaultdict(set)) def add(self, group_type: type[GroupType]) -> None: if self._registry.get(group_type.type_id): raise ValueError( f"A group type with the type_id {group_type.type_id} has already been registered." ) self._registry[group_type.type_id] = group_type self._slug_lookup[group_type.slug] = group_type self._category_lookup[group_type.category].add(group_type.type_id) self._category_lookup[group_type.category_v2].add(group_type.type_id) def all(self) -> list[type[GroupType]]: return list(self._registry.values()) def get_visible( self, organization: Organization, actor: Any | None = None ) -> list[type[GroupType]]: with sentry_sdk.start_span(op="GroupTypeRegistry.get_visible") as span: released = [gt for gt in self.all() if gt.released] feature_to_grouptype = { gt.build_visible_feature_name(): gt for gt in self.all() if not gt.released } batch_features = features.batch_has( list(feature_to_grouptype.keys()), actor=actor, organization=organization ) enabled = [] if batch_features: feature_results = batch_features.get(f"organization:{organization.id}", {}) enabled = [ feature_to_grouptype[feature] for feature, active in feature_results.items() if active ] span.set_tag("organization_id", organization.id) span.set_tag("has_batch_features", batch_features is not None) span.set_tag("released", released) span.set_tag("enabled", enabled) span.set_data("feature_to_grouptype", feature_to_grouptype) return released + enabled def get_all_group_type_ids(self) -> set[int]: return {type.type_id for type in self._registry.values()} def get_by_category(self, category: int) -> set[int]: return self._category_lookup[category] def get_by_slug(self, slug: str) -> type[GroupType] | None: if slug not in self._slug_lookup: return None return self._slug_lookup[slug] def get_by_type_id(self, id_: int) -> type[GroupType]: if id_ not in self._registry: raise InvalidGroupTypeError(id_) return self._registry[id_] registry = GroupTypeRegistry() @dataclass(frozen=True)
GroupTypeRegistry
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/traversals.py
{ "start": 7577, "end": 11875 }
class ____(HasTraversalDispatch): """Generate a _copy_internals internal traversal dispatch for classes with a _traverse_internals collection.""" def visit_clauseelement( self, attrname, parent, element, clone=_clone, **kw ): return clone(element, **kw) def visit_clauseelement_list( self, attrname, parent, element, clone=_clone, **kw ): return [clone(clause, **kw) for clause in element] def visit_clauseelement_tuple( self, attrname, parent, element, clone=_clone, **kw ): return tuple([clone(clause, **kw) for clause in element]) def visit_executable_options( self, attrname, parent, element, clone=_clone, **kw ): return tuple([clone(clause, **kw) for clause in element]) def visit_clauseelement_unordered_set( self, attrname, parent, element, clone=_clone, **kw ): return {clone(clause, **kw) for clause in element} def visit_clauseelement_tuples( self, attrname, parent, element, clone=_clone, **kw ): return [ tuple(clone(tup_elem, **kw) for tup_elem in elem) for elem in element ] def visit_string_clauseelement_dict( self, attrname, parent, element, clone=_clone, **kw ): return {key: clone(value, **kw) for key, value in element.items()} def visit_setup_join_tuple( self, attrname, parent, element, clone=_clone, **kw ): return tuple( ( clone(target, **kw) if target is not None else None, clone(onclause, **kw) if onclause is not None else None, clone(from_, **kw) if from_ is not None else None, flags, ) for (target, onclause, from_, flags) in element ) def visit_memoized_select_entities(self, attrname, parent, element, **kw): return self.visit_clauseelement_tuple(attrname, parent, element, **kw) def visit_dml_ordered_values( self, attrname, parent, element, clone=_clone, **kw ): # sequence of 2-tuples return [ ( ( clone(key, **kw) if hasattr(key, "__clause_element__") else key ), clone(value, **kw), ) for key, value in element ] def visit_dml_values(self, attrname, parent, element, clone=_clone, **kw): return { ( clone(key, **kw) if hasattr(key, "__clause_element__") else key ): clone(value, **kw) for key, value in element.items() } def visit_dml_multi_values( self, attrname, parent, element, clone=_clone, **kw ): # sequence of sequences, each sequence contains a list/dict/tuple def copy(elem): if isinstance(elem, (list, tuple)): return [ ( clone(value, **kw) if hasattr(value, "__clause_element__") else value ) for value in elem ] elif isinstance(elem, dict): return { ( clone(key, **kw) if hasattr(key, "__clause_element__") else key ): ( clone(value, **kw) if hasattr(value, "__clause_element__") else value ) for key, value in elem.items() } else: # TODO: use abc classes assert False return [ [copy(sub_element) for sub_element in sequence] for sequence in element ] def visit_propagate_attrs( self, attrname, parent, element, clone=_clone, **kw ): return element _copy_internals = _CopyInternalsTraversal() def _flatten_clauseelement(element): while hasattr(element, "__clause_element__") and not getattr( element, "is_clause_element", False ): element = element.__clause_element__() return element
_CopyInternalsTraversal
python
kubernetes-client__python
kubernetes/base/leaderelection/leaderelection_test.py
{ "start": 855, "end": 7969 }
class ____(unittest.TestCase): def test_simple_leader_election(self): election_history = [] leadership_history = [] def on_create(): election_history.append("create record") leadership_history.append("get leadership") def on_update(): election_history.append("update record") def on_change(): election_history.append("change record") mock_lock = MockResourceLock("mock", "mock_namespace", "mock", thread_lock, on_create, on_update, on_change, None) def on_started_leading(): leadership_history.append("start leading") def on_stopped_leading(): leadership_history.append("stop leading") # Create config 4.5 4 3 config = electionconfig.Config(lock=mock_lock, lease_duration=2.5, renew_deadline=2, retry_period=1.5, onstarted_leading=on_started_leading, onstopped_leading=on_stopped_leading) # Enter leader election leaderelection.LeaderElection(config).run() self.assert_history(election_history, ["create record", "update record", "update record", "update record"]) self.assert_history(leadership_history, ["get leadership", "start leading", "stop leading"]) def test_leader_election(self): election_history = [] leadership_history = [] def on_create_A(): election_history.append("A creates record") leadership_history.append("A gets leadership") def on_update_A(): election_history.append("A updates record") def on_change_A(): election_history.append("A gets leadership") mock_lock_A = MockResourceLock("mock", "mock_namespace", "MockA", thread_lock, on_create_A, on_update_A, on_change_A, None) mock_lock_A.renew_count_max = 3 def on_started_leading_A(): leadership_history.append("A starts leading") def on_stopped_leading_A(): leadership_history.append("A stops leading") config_A = electionconfig.Config(lock=mock_lock_A, lease_duration=2.5, renew_deadline=2, retry_period=1.5, onstarted_leading=on_started_leading_A, onstopped_leading=on_stopped_leading_A) def on_create_B(): election_history.append("B creates record") leadership_history.append("B gets leadership") def on_update_B(): election_history.append("B updates record") def on_change_B(): leadership_history.append("B gets leadership") mock_lock_B = MockResourceLock("mock", "mock_namespace", "MockB", thread_lock, on_create_B, on_update_B, on_change_B, None) mock_lock_B.renew_count_max = 4 def on_started_leading_B(): leadership_history.append("B starts leading") def on_stopped_leading_B(): leadership_history.append("B stops leading") config_B = electionconfig.Config(lock=mock_lock_B, lease_duration=2.5, renew_deadline=2, retry_period=1.5, onstarted_leading=on_started_leading_B, onstopped_leading=on_stopped_leading_B) mock_lock_B.leader_record = mock_lock_A.leader_record threading.daemon = True # Enter leader election for A threading.Thread(target=leaderelection.LeaderElection(config_A).run()).start() # Enter leader election for B threading.Thread(target=leaderelection.LeaderElection(config_B).run()).start() time.sleep(5) self.assert_history(election_history, ["A creates record", "A updates record", "A updates record", "B updates record", "B updates record", "B updates record", "B updates record"]) self.assert_history(leadership_history, ["A gets leadership", "A starts leading", "A stops leading", "B gets leadership", "B starts leading", "B stops leading"]) """Expected behavior: to check if the leader stops leading if it fails to update the lock within the renew_deadline and stops leading after finally timing out. The difference between each try comes out to be approximately the sleep time. Example: create record: 0s on try update: 1.5s on update: zzz s on try update: 3s on update: zzz s on try update: 4.5s on try update: 6s Timeout - Leader Exits""" def test_Leader_election_with_renew_deadline(self): election_history = [] leadership_history = [] def on_create(): election_history.append("create record") leadership_history.append("get leadership") def on_update(): election_history.append("update record") def on_change(): election_history.append("change record") def on_try_update(): election_history.append("try update record") mock_lock = MockResourceLock("mock", "mock_namespace", "mock", thread_lock, on_create, on_update, on_change, on_try_update) mock_lock.renew_count_max = 3 def on_started_leading(): leadership_history.append("start leading") def on_stopped_leading(): leadership_history.append("stop leading") # Create config config = electionconfig.Config(lock=mock_lock, lease_duration=2.5, renew_deadline=2, retry_period=1.5, onstarted_leading=on_started_leading, onstopped_leading=on_stopped_leading) # Enter leader election leaderelection.LeaderElection(config).run() self.assert_history(election_history, ["create record", "try update record", "update record", "try update record", "update record", "try update record", "try update record"]) self.assert_history(leadership_history, ["get leadership", "start leading", "stop leading"]) def assert_history(self, history, expected): self.assertIsNotNone(expected) self.assertIsNotNone(history) self.assertEqual(len(expected), len(history)) for idx in range(len(history)): self.assertEqual(history[idx], expected[idx], msg="Not equal at index {}, expected {}, got {}".format(idx, expected[idx], history[idx]))
LeaderElectionTest
python
sympy__sympy
release/github_release.py
{ "start": 4804, "end": 9684 }
class ____(object): """ This class contains URLs and templates which used in requests to GitHub API """ def __init__(self, user="sympy", repo="sympy", api_url="https://api.github.com", authorize_url="https://api.github.com/authorizations", uploads_url='https://uploads.github.com', main_url='https://github.com'): """Generates all URLs and templates""" self.user = user self.repo = repo self.api_url = api_url self.authorize_url = authorize_url self.uploads_url = uploads_url self.main_url = main_url self.pull_list_url = api_url + "/repos" + "/" + user + "/" + repo + "/pulls" self.issue_list_url = api_url + "/repos/" + user + "/" + repo + "/issues" self.releases_url = api_url + "/repos/" + user + "/" + repo + "/releases" self.single_issue_template = self.issue_list_url + "/%d" self.single_pull_template = self.pull_list_url + "/%d" self.user_info_template = api_url + "/users/%s" self.user_repos_template = api_url + "/users/%s/repos" self.issue_comment_template = (api_url + "/repos" + "/" + user + "/" + repo + "/issues/%d" + "/comments") self.release_uploads_url = (uploads_url + "/repos/" + user + "/" + repo + "/releases/%d" + "/assets") self.release_download_url = (main_url + "/" + user + "/" + repo + "/releases/download/%s/%s") def load_token_file(path="~/.sympy/release-token"): print("> Using token file %s" % path) path = os.path.expanduser(path) path = os.path.abspath(path) if os.path.isfile(path): try: with open(path) as f: token = f.readline() except IOError: print("> Unable to read token file") return else: print("> Token file does not exist") return return token.strip() def GitHub_authenticate(urls, username, token=None): _login_message = """\ Enter your GitHub username & password or press ^C to quit. The password will be kept as a Python variable as long as this script is running and https to authenticate with GitHub, otherwise not saved anywhere else:\ """ if username: print("> Authenticating as %s" % username) else: print(_login_message) username = input("Username: ") authenticated = False if token: print("> Authenticating using token") try: GitHub_check_authentication(urls, username, None, token) except AuthenticationFailed: print("> Authentication failed") else: print("> OK") password = None authenticated = True while not authenticated: password = getpass("Password: ") try: print("> Checking username and password ...") GitHub_check_authentication(urls, username, password, None) except AuthenticationFailed: print("> Authentication failed") else: print("> OK.") authenticated = True if password: generate = input("> Generate API token? [Y/n] ") if generate.lower() in ["y", "ye", "yes", ""]: name = input("> Name of token on GitHub? [SymPy Release] ") if name == "": name = "SymPy Release" token = generate_token(urls, username, password, name=name) print("Your token is", token) print("Use this token from now on as GitHub_release:token=" + token + ",username=" + username) print(red("DO NOT share this token with anyone")) save = input("Do you want to save this token to a file [yes]? ") if save.lower().strip() in ['y', 'yes', 'ye', '']: save_token_file(token) return username, password, token def run(*cmdline, cwd=None): """ Run command in subprocess and get lines of output """ return check_output(cmdline, encoding='utf-8', cwd=cwd).splitlines() def check_tag_exists(version): """ Check if the tag for this release has been uploaded yet. """ tag = 'sympy-' + version all_tag_lines = run('git', 'ls-remote', '--tags', 'origin') return any(tag in tag_line for tag_line in all_tag_lines) def generate_token(urls, username, password, OTP=None, name="SymPy Release"): enc_data = json.dumps( { "scopes": ["public_repo"], "note": name } ) url = urls.authorize_url rep = query_GitHub(url, username=username, password=password, data=enc_data).json() return rep["token"] def GitHub_check_authentication(urls, username, password, token): """ Checks that username & password is valid. """ query_GitHub(urls.api_url, username, password, token)
URLs
python
ray-project__ray
python/ray/util/state/common.py
{ "start": 3743, "end": 6856 }
class ____: # Maximum number of entries to return limit: int = DEFAULT_LIMIT # The timeout for the API call. timeout: int = DEFAULT_RPC_TIMEOUT # If True, more detailed output will be printed. # The API could query more sources than detail == False # to get more data in detail. detail: bool = False # Filters. Each tuple pair (key, predicate, value) means key predicate value. # If there's more than 1 filter, it means AND. # E.g., [(key, "=", val), (key2, "!=" val2)] means (key=val) AND (key2!=val2) filters: Optional[List[Tuple[str, PredicateType, SupportedFilterType]]] = field( default_factory=list ) # [only tasks] If driver tasks should be excluded. exclude_driver: bool = True # When the request is processed on the server side, # we should apply multiplier so that server side can finish # processing a request within timeout. Otherwise, # timeout will always lead Http timeout. server_timeout_multiplier: float = 0.8 def __post_init__(self): # To return the data to users, when there's a partial failure # we need to have a timeout that's smaller than the users' timeout. # 80% is configured arbitrarily. self.timeout = max(1, int(self.timeout * self.server_timeout_multiplier)) assert self.timeout != 0, "0 second timeout is not supported." if self.filters is None: self.filters = [] for filter in self.filters: _, filter_predicate, _ = filter if filter_predicate != "=" and filter_predicate != "!=": raise ValueError( f"Unsupported filter predicate {filter_predicate} is given. " "Available predicates: =, !=." ) def has_conflicting_filters(self) -> bool: # Check the filters in the ListApiOptions conflicts. Specifically for: # - multiple '=' filters with the same key but different values. # TODO(myan): More conflicts situation can be added for further optimization. # For exmaple, 2 filters with same key and same value but one with '=' predicate # and ther other with '!=' predicate equal_filters = {} for filter in self.filters: filter_key, filter_predicate, filter_value = filter if filter_predicate == "=": if ( filter_key in equal_filters and equal_filters[filter_key] != filter_value ): warnings.warn( "There are multiple '=' filters with the same " f"key '{filter_key}' but different values" f"'{equal_filters[filter_key]}' & '{filter_value}'. " "Empty result set will be returned", UserWarning, ) return True elif filter_key not in equal_filters: equal_filters[filter_key] = filter_value return False @dataclass(init=not IS_PYDANTIC_2)
ListApiOptions
python
numpy__numpy
numpy/_core/tests/test_umath.py
{ "start": 110528, "end": 112671 }
class ____: def test_exceptions(self): a = np.ones(1, dtype=np.bool) assert_raises(TypeError, np.negative, a) assert_raises(TypeError, np.positive, a) assert_raises(TypeError, np.subtract, a, a) def test_truth_table_logical(self): # 2, 3 and 4 serves as true values input1 = [0, 0, 3, 2] input2 = [0, 4, 0, 2] typecodes = (np.typecodes['AllFloat'] + np.typecodes['AllInteger'] + '?') # boolean for dtype in map(np.dtype, typecodes): arg1 = np.asarray(input1, dtype=dtype) arg2 = np.asarray(input2, dtype=dtype) # OR out = [False, True, True, True] for func in (np.logical_or, np.maximum): assert_equal(func(arg1, arg2).astype(bool), out) # AND out = [False, False, False, True] for func in (np.logical_and, np.minimum): assert_equal(func(arg1, arg2).astype(bool), out) # XOR out = [False, True, True, False] for func in (np.logical_xor, np.not_equal): assert_equal(func(arg1, arg2).astype(bool), out) def test_truth_table_bitwise(self): arg1 = [False, False, True, True] arg2 = [False, True, False, True] out = [False, True, True, True] assert_equal(np.bitwise_or(arg1, arg2), out) out = [False, False, False, True] assert_equal(np.bitwise_and(arg1, arg2), out) out = [False, True, True, False] assert_equal(np.bitwise_xor(arg1, arg2), out) def test_reduce(self): none = np.array([0, 0, 0, 0], bool) some = np.array([1, 0, 1, 1], bool) every = np.array([1, 1, 1, 1], bool) empty = np.array([], bool) arrs = [none, some, every, empty] for arr in arrs: assert_equal(np.logical_and.reduce(arr), all(arr)) for arr in arrs: assert_equal(np.logical_or.reduce(arr), any(arr)) for arr in arrs: assert_equal(np.logical_xor.reduce(arr), arr.sum() % 2 == 1)
TestBool
python
falconry__falcon
e2e-tests/server/chat.py
{ "start": 101, "end": 1437 }
class ____: ALL = re.compile(r'^/all\s+(.+)$') MSG = re.compile(r'^/msg\s+(\w+)\s+(.+)$') def __init__(self, hub: Hub): self._hub = hub async def on_websocket(self, req: Request, ws: WebSocket, name: str) -> None: await ws.accept() try: await self._hub.broadcast(f'{name} CONNECTED') self._hub.add_user(name, ws) await ws.send_text(f'Hello, {name}!') while True: message = await ws.receive_text() if message == '/quit': await ws.send_text(f'Bye, {name}!') await ws.close(4001, 'quit command') break command = self.ALL.match(message) if command: text = command.group(1) await self._hub.broadcast(f'[{name}] {text}') continue command = self.MSG.match(message) if command: recipient, text = command.groups() await self._hub.message(recipient, f'[{name}] {text}') continue await ws.send_text('Supported commands: /all /msg /quit') finally: self._hub.remove_user(name) await self._hub.broadcast(f'{name} DISCONNECTED')
Chat
python
chroma-core__chroma
chromadb/errors.py
{ "start": 1126, "end": 1252 }
class ____(ChromaError): @classmethod @overrides def name(cls) -> str: return "DuplicateID"
DuplicateIDError
python
pytorch__pytorch
test/quantization/pt2e/test_quantize_pt2e_qat.py
{ "start": 40580, "end": 44799 }
class ____(QuantizationTestCase): class TwoLinear(torch.nn.Module): def __init__(self) -> None: super().__init__() self.linear1 = torch.nn.Linear(16, 8, bias=False) self.linear2 = torch.nn.Linear(8, 8) def forward(self, x): return self.linear2(self.linear1(x)) class QATPTQTestModule(torch.nn.Module): def __init__(self) -> None: super().__init__() self.conv = torch.nn.Conv2d(3, 16, 3) self.linears = TestQuantizeMixQATAndPTQ.TwoLinear() self.my_linear = torch.nn.Linear(8, 8) def forward(self, x): conv_out = self.conv(x) permute_out = torch.permute(conv_out, (0, 2, 3, 1)) linear_out = self.linears(permute_out) my_linear_out = self.my_linear(linear_out) # Hardtanh doesn't get quantized via xnnpack quantizer in this test # because it relies on the propagation rules # Need to fix this return torch.nn.functional.hardtanh(my_linear_out) def _prepare_qat_linears(self, model): for name, child in model.named_children(): if isinstance(child, (torch.nn.Linear, TestQuantizeMixQATAndPTQ.TwoLinear)): if isinstance(child, torch.nn.Linear): in_channels = child.weight.size(1) else: in_channels = child.linear1.weight.size(1) example_input = (torch.rand((1, in_channels)),) traced_child = export(child, example_input, strict=True).module() quantizer = XNNPACKQuantizer() quantization_config = get_symmetric_quantization_config( is_per_channel=True, is_qat=True ) quantizer.set_global(quantization_config) traced_child_prepared = prepare_qat_pt2e(traced_child, quantizer) setattr(model, name, traced_child_prepared) else: self._prepare_qat_linears(child) def _convert_qat_linears(self, model): for name, child in model.named_children(): if isinstance(child, torch.fx.GraphModule): torch.ao.quantization.move_exported_model_to_eval(child) converted_child = convert_pt2e(child) setattr(model, name, converted_child) else: self._convert_qat_linears(child) def test_mixing_qat_ptq(self): example_inputs = (torch.randn(2, 3, 4, 4),) model = TestQuantizeMixQATAndPTQ.QATPTQTestModule() self._prepare_qat_linears(model) model(*example_inputs) # must be fixed model.eval() self._convert_qat_linears(model) model(*example_inputs) model_pt2e = export(model, example_inputs, strict=True).module() quantizer = XNNPACKQuantizer() quantizer.set_module_type(torch.nn.Linear, None) quantization_config = get_symmetric_quantization_config() quantizer.set_global(quantization_config) model_pt2e = prepare_pt2e(model_pt2e, quantizer) after_prepare_result_pt2e = model_pt2e(*example_inputs) # noqa: F841 model_pt2e = convert_pt2e(model_pt2e) quant_result_pt2e = model_pt2e(*example_inputs) # noqa: F841 exported_model = torch.export.export(model_pt2e, example_inputs, strict=True) node_occurrence = { # conv2d: 1 for act, 1 for weight, 1 for output # 3 x linear: 1 for act, 1 for output ns.call_function( torch.ops.quantized_decomposed.quantize_per_tensor.default ): 8, ns.call_function( torch.ops.quantized_decomposed.dequantize_per_tensor.default ): 9, ns.call_function( torch.ops.quantized_decomposed.dequantize_per_channel.default ): 3, # There needs to be one for hardtanh } self.checkGraphModuleNodes( exported_model.graph_module, expected_node_occurrence=node_occurrence ) if __name__ == "__main__": raise_on_run_directly("test/test_quantization.py")
TestQuantizeMixQATAndPTQ
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_pattern05.py
{ "start": 315, "end": 3552 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_pattern05.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "column"}) chart.axis_ids = [110902272, 110756608] data = [ [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) worksheet.write_column("D1", data[3]) worksheet.write_column("E1", data[4]) worksheet.write_column("F1", data[5]) worksheet.write_column("G1", data[6]) worksheet.write_column("H1", data[7]) chart.add_series( { "values": "=Sheet1!$A$1:$A$3", "pattern": { "pattern": "percent_25", "fg_color": "#C00000", "bg_color": "#FFFFFF", }, } ) chart.add_series( { "values": "=Sheet1!$B$1:$B$3", "pattern": { "pattern": "percent_75", "fg_color": "#FF0000", }, } ) chart.add_series( { "values": "=Sheet1!$C$1:$C$3", "pattern": { "pattern": "dark_upward_diagonal", "fg_color": "#FFC000", }, } ) chart.add_series( { "values": "=Sheet1!$D$1:$D$3", "pattern": { "pattern": "narrow_horizontal", "fg_color": "#FFFF00", }, } ) chart.add_series( { "values": "=Sheet1!$E$1:$E$3", "pattern": { "pattern": "dashed_vertical", "fg_color": "#92D050", }, } ) chart.add_series( { "values": "=Sheet1!$F$1:$F$3", "pattern": { "pattern": "horizontal_brick", "fg_color": "#00B050", }, } ) chart.add_series( { "values": "=Sheet1!$G$1:$G$3", "pattern": { "pattern": "shingle", "fg_color": "#00B0F0", }, } ) chart.add_series( { "values": "=Sheet1!$H$1:$H$3", "pattern": { "pattern": "large_check", "fg_color": "#0070C0", }, } ) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
django-extensions__django-extensions
tests/management/commands/test_create_jobs.py
{ "start": 523, "end": 1109 }
class ____(CreateJobsTestsMixin, TestCase): @patch("sys.stderr", new_callable=StringIO) @patch( "django_extensions.management.commands.create_jobs._make_writeable", side_effect=OSError, ) def test_should_print_error_notice_on_OSError(self, m__make_writeable, m_stderr): call_command("create_jobs", "testapp_with_no_models_file") self.assertRegex( m_stderr.getvalue(), r"Notice: Couldn't set permission bits on \S+ You're probably using an uncommon filesystem setup. No problem.", )
CreateJobsExceptionsTests
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1303175, "end": 1303371 }
class ____(VegaLiteSchema): """TextDef schema wrapper.""" _schema = {"$ref": "#/definitions/TextDef"} def __init__(self, *args, **kwds): super().__init__(*args, **kwds)
TextDef
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-milvus/destination_milvus/config.py
{ "start": 1569, "end": 2754 }
class ____(BaseModel): host: str = Field( ..., title="Public Endpoint", order=1, description="The public endpoint of the Milvus instance. ", examples=["https://my-instance.zone.zillizcloud.com", "tcp://host.docker.internal:19530", "tcp://my-local-milvus:19530"], ) db: Optional[str] = Field(title="Database Name", description="The database to connect to", default="") collection: str = Field(..., title="Collection Name", description="The collection to load data into", order=3) auth: Union[TokenAuth, UsernamePasswordAuth, NoAuth] = Field( ..., title="Authentication", description="Authentication method", discriminator="mode", type="object", order=2 ) vector_field: str = Field(title="Vector Field", description="The field in the entity that contains the vector", default="vector") text_field: str = Field(title="Text Field", description="The field in the entity that contains the embedded text", default="text") class Config: title = "Indexing" schema_extra = { "group": "indexing", "description": "Indexing configuration", }
MilvusIndexingConfigModel
python
huggingface__transformers
src/transformers/models/chinese_clip/configuration_chinese_clip.py
{ "start": 813, "end": 6041 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`ChineseCLIPModel`]. It is used to instantiate a Chinese CLIP model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the Chinese CLIP [OFA-Sys/chinese-clip-vit-base-patch16](https: //huggingface.co/OFA-Sys/chinese-clip-vit-base-patch16) architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: vocab_size (`int`, *optional*, defaults to 30522): Vocabulary size of the CHINESE_CLIP model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`ChineseCLIPModel`]. hidden_size (`int`, *optional*, defaults to 768): Dimensionality of the encoder layers and the pooler layer. num_hidden_layers (`int`, *optional*, defaults to 12): Number of hidden layers in the Transformer encoder. num_attention_heads (`int`, *optional*, defaults to 12): Number of attention heads for each attention layer in the Transformer encoder. intermediate_size (`int`, *optional*, defaults to 3072): Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder. hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`): The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"silu"` and `"gelu_new"` are supported. hidden_dropout_prob (`float`, *optional*, defaults to 0.1): The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1): The dropout ratio for the attention probabilities. max_position_embeddings (`int`, *optional*, defaults to 512): The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). type_vocab_size (`int`, *optional*, defaults to 2): The vocabulary size of the `token_type_ids` passed when calling [`ChineseCLIPModel`]. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. initializer_factor (`float`, *optional*, defaults to 1.0): A factor for initializing all weight matrices (should be kept to 1, used internally for initialization testing). layer_norm_eps (`float`, *optional*, defaults to 1e-12): The epsilon used by the layer normalization layers. pad_token_id (`int`, *optional*, defaults to 0): Padding token id. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. Example: ```python >>> from transformers import ChineseCLIPTextConfig, ChineseCLIPTextModel >>> # Initializing a ChineseCLIPTextConfig with OFA-Sys/chinese-clip-vit-base-patch16 style configuration >>> configuration = ChineseCLIPTextConfig() >>> # Initializing a ChineseCLIPTextModel (with random weights) from the OFA-Sys/chinese-clip-vit-base-patch16 style configuration >>> model = ChineseCLIPTextModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "chinese_clip_text_model" base_config_key = "text_config" def __init__( self, vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=2, initializer_range=0.02, initializer_factor=1.0, layer_norm_eps=1e-12, pad_token_id=0, use_cache=True, **kwargs, ): super().__init__(pad_token_id=pad_token_id, **kwargs) self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.hidden_act = hidden_act self.intermediate_size = intermediate_size self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.initializer_range = initializer_range self.initializer_factor = initializer_factor self.layer_norm_eps = layer_norm_eps self.use_cache = use_cache
ChineseCLIPTextConfig
python
ansible__ansible
lib/ansible/module_utils/_internal/_datatag/__init__.py
{ "start": 31727, "end": 32600 }
class ____(datetime.date, AnsibleTaggedObject): __slots__ = _ANSIBLE_TAGGED_OBJECT_SLOTS @classmethod def _instance_factory(cls, value: datetime.date, tags_mapping: _AnsibleTagsMapping) -> _AnsibleTaggedDate: instance = cls( year=value.year, month=value.month, day=value.day, ) instance._ansible_tags_mapping = tags_mapping return instance def _native_copy(self) -> datetime.date: return datetime.date( year=self.year, month=self.month, day=self.day, ) def __new__(cls, year, *args, **kwargs): return super()._new(year, *args, **kwargs) def __reduce__(self) -> tuple: return super()._reduce(super().__reduce__()) def __repr__(self) -> str: return self._native_copy().__repr__()
_AnsibleTaggedDate
python
pandas-dev__pandas
pandas/tests/series/indexing/test_setitem.py
{ "start": 32677, "end": 33691 }
class ____(SetitemCastingEquivalents): # GH#39619 dont cast dt64 to int when doing this setitem @pytest.fixture(params=["M8[ns]", "m8[ns]"]) def dtype(self, request): return request.param @pytest.fixture def scalar(self, dtype): val = np.datetime64("2021-01-18 13:25:00", "ns") if dtype == "m8[ns]": val = val - val return val @pytest.fixture def expected(self, scalar): expected = Series([scalar, scalar, 3], dtype=object) assert isinstance(expected[0], type(scalar)) return expected @pytest.fixture def obj(self): return Series([1, 2, 3]) @pytest.fixture def key(self): return slice(None, -1) @pytest.fixture(params=[None, list, np.array]) def val(self, scalar, request): box = request.param if box is None: return scalar return box([scalar, scalar]) @pytest.fixture def raises(self): return True
TestSetitemDT64IntoInt
python
run-llama__llama_index
llama-index-packs/llama-index-packs-resume-screener/llama_index/packs/resume_screener/base.py
{ "start": 832, "end": 1084 }
class ____(BaseModel): """The decision made based on a single criteria.""" decision: bool = Field(description="The decision made based on the criteria") reasoning: str = Field(description="The reasoning behind the decision")
CriteriaDecision
python
apache__airflow
airflow-core/src/airflow/timetables/base.py
{ "start": 1299, "end": 2306 }
class ____(BaseAsset): """ Sentinel type that represents "no assets". This is only implemented to make typing easier in timetables, and not expected to be used anywhere else. :meta private: """ def __bool__(self) -> bool: return False def __or__(self, other: BaseAsset) -> BaseAsset: return NotImplemented def __and__(self, other: BaseAsset) -> BaseAsset: return NotImplemented def as_expression(self) -> Any: return None def evaluate(self, statuses: dict[AssetUniqueKey, bool], *, session: Session | None = None) -> bool: return False def iter_assets(self) -> Iterator[tuple[AssetUniqueKey, Asset]]: return iter(()) def iter_asset_aliases(self) -> Iterator[tuple[str, AssetAlias]]: return iter(()) def iter_asset_refs(self) -> Iterator[AssetRef]: return iter(()) def iter_dag_dependencies(self, source, target) -> Iterator[DagDependency]: return iter(())
_NullAsset
python
getsentry__sentry
tests/sentry/sentry_apps/tasks/test_sentry_apps.py
{ "start": 4242, "end": 21838 }
class ____(TestCase, OccurrenceTestMixin): def setUp(self) -> None: self.sentry_app = self.create_sentry_app(organization=self.organization) self.rule = Rule.objects.create(project=self.project, label="Issa Rule") self.install = self.create_sentry_app_installation( organization=self.organization, slug=self.sentry_app.slug ) @patch("sentry.utils.sentry_apps.webhooks.safe_urlopen") @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_no_sentry_app_for_send_alert_event_v2( self, mock_record: MagicMock, safe_urlopen: MagicMock ) -> None: event = self.store_event(data={}, project_id=self.project.id) assert event.group is not None group_event = GroupEvent.from_event(event, event.group) send_alert_webhook_v2( instance_id=group_event.event_id, group_id=group_event.group_id, occurrence_id=None, rule_label=self.rule.label, sentry_app_id=9999, ) assert not safe_urlopen.called assert_failure_metric( mock_record=mock_record, error_msg=SentryAppSentryError( message=SentryAppWebhookFailureReason.MISSING_SENTRY_APP ), ) # PREPARE_WEBHOOK (failure) assert_count_of_metric( mock_record=mock_record, outcome=EventLifecycleOutcome.STARTED, outcome_count=1 ) assert_count_of_metric( mock_record=mock_record, outcome=EventLifecycleOutcome.FAILURE, outcome_count=1 ) @patch("sentry.utils.sentry_apps.webhooks.safe_urlopen", return_value=MockResponseInstance) @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_missing_event(self, mock_record: MagicMock, safe_urlopen: MagicMock) -> None: project = self.create_project() issue = self.create_group(project=project) send_alert_webhook_v2( instance_id=123, group_id=issue.id, occurrence_id=None, rule_label=self.rule.label, sentry_app_id=self.sentry_app.id, ) assert not safe_urlopen.called assert_failure_metric( mock_record, SentryAppSentryError(message=SentryAppWebhookFailureReason.MISSING_EVENT) ) # PREPARE_WEBHOOK (failure) assert_count_of_metric( mock_record=mock_record, outcome=EventLifecycleOutcome.STARTED, outcome_count=1 ) assert_count_of_metric( mock_record=mock_record, outcome=EventLifecycleOutcome.FAILURE, outcome_count=1 ) @patch("sentry.utils.sentry_apps.webhooks.safe_urlopen") def test_no_sentry_app_in_future(self, safe_urlopen: MagicMock) -> None: event = self.store_event(data={}, project_id=self.project.id) assert event.group is not None group_event = GroupEvent.from_event(event, event.group) rule_future = RuleFuture(rule=self.rule, kwargs={}) with self.tasks(): notify_sentry_app(group_event, [rule_future]) assert not safe_urlopen.called @patch("sentry.utils.sentry_apps.webhooks.safe_urlopen") @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_no_installation(self, mock_record: MagicMock, safe_urlopen: MagicMock) -> None: sentry_app = self.create_sentry_app(organization=self.organization) event = self.store_event(data={}, project_id=self.project.id) assert event.group is not None group_event = GroupEvent.from_event(event, event.group) rule_future = RuleFuture(rule=self.rule, kwargs={"sentry_app": sentry_app}) with self.tasks(): notify_sentry_app(group_event, [rule_future]) assert not safe_urlopen.called assert_halt_metric( mock_record=mock_record, error_msg=SentryAppWebhookHaltReason.MISSING_INSTALLATION ) # APP_CREATE (success) -> PREPARE_WEBHOOK (failure) assert_count_of_metric( mock_record=mock_record, outcome=EventLifecycleOutcome.STARTED, outcome_count=2 ) assert_count_of_metric( mock_record=mock_record, outcome=EventLifecycleOutcome.SUCCESS, outcome_count=1 ) assert_count_of_metric( mock_record=mock_record, outcome=EventLifecycleOutcome.HALTED, outcome_count=1 ) @patch("sentry.utils.sentry_apps.webhooks.safe_urlopen", return_value=MockResponseInstance) @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_send_alert_event(self, mock_record: MagicMock, safe_urlopen: MagicMock) -> None: event = self.store_event(data={}, project_id=self.project.id) assert event.group is not None group = event.group group_event = GroupEvent.from_event(event, group) rule_future = RuleFuture(rule=self.rule, kwargs={"sentry_app": self.sentry_app}) with self.tasks(): notify_sentry_app(group_event, [rule_future]) ((args, kwargs),) = safe_urlopen.call_args_list data = json.loads(kwargs["data"]) assert data == { "action": "triggered", "installation": {"uuid": self.install.uuid}, "data": { "event": ANY, # tested below "triggered_rule": self.rule.label, }, "actor": {"type": "application", "id": "sentry", "name": "Sentry"}, } assert data["data"]["event"]["project"] == self.project.id assert data["data"]["event"]["event_id"] == group_event.event_id assert data["data"]["event"]["url"] == absolute_uri( reverse( "sentry-api-0-project-event-details", args=[self.organization.slug, self.project.slug, group_event.event_id], ) ) assert data["data"]["event"]["web_url"] == absolute_uri( reverse( "sentry-organization-event-detail", args=[self.organization.slug, group.id, group_event.event_id], ) ) assert data["data"]["event"]["issue_url"] == absolute_uri( f"/api/0/organizations/{self.organization.slug}/issues/{group.id}/" ) assert data["data"]["event"]["issue_id"] == str(group.id) assert kwargs["headers"].keys() >= { "Content-Type", "Request-ID", "Sentry-Hook-Resource", "Sentry-Hook-Timestamp", "Sentry-Hook-Signature", } buffer = SentryAppWebhookRequestsBuffer(self.sentry_app) requests = buffer.get_requests() assert len(requests) == 1 assert requests[0]["response_code"] == 200 assert requests[0]["event_type"] == "event_alert.triggered" # SLO validation assert_success_metric(mock_record=mock_record) # PREPARE_WEBHOOK (success) -> SEND_WEBHOOK (success) assert_count_of_metric( mock_record=mock_record, outcome=EventLifecycleOutcome.STARTED, outcome_count=2 ) assert_count_of_metric( mock_record=mock_record, outcome=EventLifecycleOutcome.SUCCESS, outcome_count=2 ) @patch("sentry.utils.sentry_apps.webhooks.safe_urlopen", return_value=MockResponseInstance) @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_send_alert_event_with_additional_payload( self, mock_record: MagicMock, safe_urlopen: MagicMock ) -> None: event = self.store_event(data={}, project_id=self.project.id) assert event.group is not None group_event = GroupEvent.from_event(event, event.group) settings = [ {"name": "alert_prefix", "value": "[Not Good]"}, {"name": "channel", "value": "#ignored-errors"}, {"name": "best_emoji", "value": ":fire:"}, {"name": "teamId", "value": 1}, {"name": "assigneeId", "value": 3}, ] rule_future = RuleFuture( rule=self.rule, kwargs={"sentry_app": self.sentry_app, "schema_defined_settings": settings}, ) with self.tasks(): notify_sentry_app(group_event, [rule_future]) ((args, kwargs),) = safe_urlopen.call_args_list payload = json.loads(kwargs["data"]) assert payload["action"] == "triggered" assert payload["data"]["triggered_rule"] == self.rule.label assert payload["data"]["issue_alert"] == { "id": self.rule.id, "title": self.rule.label, "sentry_app_id": self.sentry_app.id, "settings": settings, } buffer = SentryAppWebhookRequestsBuffer(self.sentry_app) requests = buffer.get_requests() assert len(requests) == 1 assert requests[0]["response_code"] == 200 assert requests[0]["event_type"] == "event_alert.triggered" # SLO validation assert_success_metric(mock_record=mock_record) # PREPARE_WEBHOOK (success) -> SEND_WEBHOOK (success) assert_count_of_metric( mock_record=mock_record, outcome=EventLifecycleOutcome.STARTED, outcome_count=2 ) assert_count_of_metric( mock_record=mock_record, outcome=EventLifecycleOutcome.SUCCESS, outcome_count=2 ) @patch("sentry.utils.sentry_apps.webhooks.safe_urlopen", return_value=MockResponseInstance) @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") @with_feature("organizations:workflow-engine-trigger-actions") def test_send_alert_event_with_additional_payload_legacy_rule_id( self, mock_record, safe_urlopen ): rule = self.create_project_rule( action_data=[ { "sentryAppInstallationUuid": self.install.uuid, "legacy_rule_id": "123", } ] ) event = self.store_event(data={}, project_id=self.project.id) assert event.group is not None group_event = GroupEvent.from_event(event, event.group) settings = [ {"name": "alert_prefix", "value": "[Not Good]"}, {"name": "channel", "value": "#ignored-errors"}, {"name": "best_emoji", "value": ":fire:"}, {"name": "teamId", "value": 1}, {"name": "assigneeId", "value": 3}, ] rule_future = RuleFuture( rule=rule, kwargs={"sentry_app": self.sentry_app, "schema_defined_settings": settings}, ) with self.tasks(): notify_sentry_app(group_event, [rule_future]) ((args, kwargs),) = safe_urlopen.call_args_list payload = json.loads(kwargs["data"]) assert payload["action"] == "triggered" assert payload["data"]["triggered_rule"] == rule.label assert payload["data"]["issue_alert"] == { # Use the legacy rule id "id": "123", "title": rule.label, "sentry_app_id": self.sentry_app.id, "settings": settings, } buffer = SentryAppWebhookRequestsBuffer(self.sentry_app) requests = buffer.get_requests() assert len(requests) == 1 assert requests[0]["response_code"] == 200 assert requests[0]["event_type"] == "event_alert.triggered" # SLO validation assert_success_metric(mock_record=mock_record) # PREPARE_WEBHOOK (success) -> SEND_WEBHOOK (success) assert_count_of_metric( mock_record=mock_record, outcome=EventLifecycleOutcome.STARTED, outcome_count=2 ) assert_count_of_metric( mock_record=mock_record, outcome=EventLifecycleOutcome.SUCCESS, outcome_count=2 ) @patch("sentry.utils.sentry_apps.webhooks.safe_urlopen", return_value=MockResponseInstance) @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_send_alert_event_with_groupevent( self, mock_record: MagicMock, safe_urlopen: MagicMock ) -> None: event = self.store_event(data={}, project_id=self.project.id) occurrence_data = self.build_occurrence_data( event_id=event.event_id, project_id=self.project.id ) occurrence, group_info = save_issue_occurrence(occurrence_data=occurrence_data, event=event) assert group_info is not None group_event = event.for_group(group_info.group) group_event.occurrence = occurrence rule_future = RuleFuture(rule=self.rule, kwargs={"sentry_app": self.sentry_app}) with self.tasks(): notify_sentry_app(group_event, [rule_future]) ((args, kwargs),) = safe_urlopen.call_args_list data = json.loads(kwargs["data"]) assert data == { "action": "triggered", "installation": {"uuid": self.install.uuid}, "data": { "event": ANY, # tested below "triggered_rule": self.rule.label, }, "actor": {"type": "application", "id": "sentry", "name": "Sentry"}, } assert data["data"]["event"]["project"] == self.project.id assert data["data"]["event"]["event_id"] == group_event.event_id assert data["data"]["event"]["url"] == absolute_uri( reverse( "sentry-api-0-project-event-details", args=[self.organization.slug, self.project.slug, group_event.event_id], ) ) assert data["data"]["event"]["web_url"] == absolute_uri( reverse( "sentry-organization-event-detail", args=[self.organization.slug, group_event.group.id, group_event.event_id], ) ) assert data["data"]["event"]["issue_url"] == absolute_uri( f"/api/0/organizations/{self.organization.slug}/issues/{group_event.group.id}/" ) assert data["data"]["event"]["issue_id"] == str(group_event.group.id) assert data["data"]["event"]["occurrence"] == convert_dict_key_case( occurrence.to_dict(), snake_to_camel_case ) assert kwargs["headers"].keys() >= { "Content-Type", "Request-ID", "Sentry-Hook-Resource", "Sentry-Hook-Timestamp", "Sentry-Hook-Signature", } buffer = SentryAppWebhookRequestsBuffer(self.sentry_app) requests = buffer.get_requests() assert len(requests) == 1 assert requests[0]["response_code"] == 200 assert requests[0]["event_type"] == "event_alert.triggered" # SLO validation assert_success_metric(mock_record=mock_record) # PREPARE_WEBHOOK (success) -> SEND_WEBHOOK (success) assert_count_of_metric( mock_record=mock_record, outcome=EventLifecycleOutcome.STARTED, outcome_count=2 ) assert_count_of_metric( mock_record=mock_record, outcome=EventLifecycleOutcome.SUCCESS, outcome_count=2 ) @patch("sentry.utils.sentry_apps.webhooks.safe_urlopen", return_value=MockResponse404) @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_send_alert_event_with_3p_failure( self, mock_record: MagicMock, safe_urlopen: MagicMock ) -> None: event = self.store_event(data={}, project_id=self.project.id) assert event.group is not None group_event = GroupEvent.from_event(event, event.group) settings = [ {"name": "alert_prefix", "value": "[Not Good]"}, {"name": "channel", "value": "#ignored-errors"}, {"name": "best_emoji", "value": ":fire:"}, {"name": "teamId", "value": 1}, {"name": "assigneeId", "value": 3}, ] rule_future = RuleFuture( rule=self.rule, kwargs={"sentry_app": self.sentry_app, "schema_defined_settings": settings}, ) with self.tasks(): notify_sentry_app(group_event, [rule_future]) ((args, kwargs),) = safe_urlopen.call_args_list payload = json.loads(kwargs["data"]) assert payload["action"] == "triggered" assert payload["data"]["triggered_rule"] == self.rule.label assert payload["data"]["issue_alert"] == { "id": self.rule.id, "title": self.rule.label, "sentry_app_id": self.sentry_app.id, "settings": settings, } buffer = SentryAppWebhookRequestsBuffer(self.sentry_app) requests = buffer.get_requests() assert len(requests) == 1 assert requests[0]["event_type"] == "event_alert.triggered" # SLO validation assert_success_metric(mock_record=mock_record) assert_halt_metric( mock_record=mock_record, error_msg=f"send_and_save_webhook_request.{SentryAppWebhookHaltReason.GOT_CLIENT_ERROR}_{404}", ) # PREPARE_WEBHOOK (success) -> SEND_WEBHOOK (halt) assert_count_of_metric( mock_record=mock_record, outcome=EventLifecycleOutcome.STARTED, outcome_count=2 ) assert_count_of_metric( mock_record=mock_record, outcome=EventLifecycleOutcome.SUCCESS, outcome_count=1 ) assert_count_of_metric( mock_record=mock_record, outcome=EventLifecycleOutcome.HALTED, outcome_count=1 ) @patch("sentry.utils.sentry_apps.webhooks.safe_urlopen", return_value=MockResponseInstance)
TestSendAlertEvent
python
getsentry__sentry
tests/sentry/integrations/utils/test_lifecycle_metrics.py
{ "start": 354, "end": 20359 }
class ____(TestCase): class TestLifecycleMetric(IntegrationEventLifecycleMetric): def get_integration_domain(self) -> IntegrationDomain: return IntegrationDomain.MESSAGING def get_integration_name(self) -> str: return "my_integration" def get_interaction_type(self) -> str: return "my_interaction" def test_key_and_tag_assignment(self) -> None: metric_obj = self.TestLifecycleMetric() key = metric_obj.get_metric_key(EventLifecycleOutcome.STARTED) assert key == "integrations.slo.started" assert metric_obj.get_metric_tags() == { "integration_domain": "messaging", "integration_name": "my_integration", "interaction_type": "my_interaction", } @staticmethod def _check_metrics_call_args(mock_metrics, expected_termination: str): assert mock_metrics.incr.call_args_list == [ mock.call( "integrations.slo.started", tags={ "integration_domain": "messaging", "integration_name": "my_integration", "interaction_type": "my_interaction", }, sample_rate=1.0, ), mock.call( rf"integrations.slo.{expected_termination}", tags={ "integration_domain": "messaging", "integration_name": "my_integration", "interaction_type": "my_interaction", }, sample_rate=1.0, ), ] @mock.patch("sentry.integrations.utils.metrics.logger") @mock.patch("sentry.integrations.utils.metrics.metrics") def test_recording_success( self, mock_metrics: mock.MagicMock, mock_logger: mock.MagicMock ) -> None: metric_obj = self.TestLifecycleMetric() with metric_obj.capture(assume_success=True): pass self._check_metrics_call_args(mock_metrics, "success") mock_logger.error.assert_not_called() mock_logger.warning.assert_not_called() @mock.patch("sentry.integrations.utils.metrics.logger") @mock.patch("sentry.integrations.utils.metrics.metrics") def test_recording_halt( self, mock_metrics: mock.MagicMock, mock_logger: mock.MagicMock ) -> None: metric_obj = self.TestLifecycleMetric() with metric_obj.capture(assume_success=False): pass self._check_metrics_call_args(mock_metrics, "halted") mock_logger.info.assert_called_once_with( "integrations.slo.halted", extra={ "integration_domain": "messaging", "integration_name": "my_integration", "interaction_type": "my_interaction", }, ) @mock.patch("sentry.integrations.utils.metrics.logger") @mock.patch("sentry.integrations.utils.metrics.metrics") def test_recording_explicit_halt_with_exception( self, mock_metrics: mock.MagicMock, mock_logger: mock.MagicMock ) -> None: metric_obj = self.TestLifecycleMetric() with metric_obj.capture() as lifecycle: lifecycle.add_extra("extra", "value") lifecycle.record_halt(ExampleException(""), extra={"even": "more"}) self._check_metrics_call_args(mock_metrics, "halted") mock_logger.info.assert_called_once_with( "integrations.slo.halted", extra={ "extra": "value", "even": "more", "integration_domain": "messaging", "integration_name": "my_integration", "interaction_type": "my_interaction", "exception_summary": repr(ExampleException("")), }, ) @mock.patch("sentry.integrations.utils.metrics.logger") @mock.patch("sentry.integrations.utils.metrics.metrics") def test_recording_explicit_halt_with_str( self, mock_metrics: mock.MagicMock, mock_logger: mock.MagicMock ) -> None: metric_obj = self.TestLifecycleMetric() with metric_obj.capture() as lifecycle: lifecycle.add_extra("extra", "value") lifecycle.record_halt("Integration went boom", extra={"even": "more"}) self._check_metrics_call_args(mock_metrics, "halted") mock_logger.info.assert_called_once_with( "integrations.slo.halted", extra={ "outcome_reason": "Integration went boom", "extra": "value", "even": "more", "integration_domain": "messaging", "integration_name": "my_integration", "interaction_type": "my_interaction", }, ) @mock.patch("sentry.integrations.utils.metrics.sentry_sdk") @mock.patch("sentry.integrations.utils.metrics.logger") @mock.patch("sentry.integrations.utils.metrics.metrics") def test_recording_failure( self, mock_metrics: mock.MagicMock, mock_logger: mock.MagicMock, mock_sentry_sdk: mock.MagicMock, ) -> None: mock_sentry_sdk.capture_exception.return_value = "test-event-id" metric_obj = self.TestLifecycleMetric() with pytest.raises(ExampleException): with metric_obj.capture() as lifecycle: lifecycle.add_extra("extra", "value") raise ExampleException() self._check_metrics_call_args(mock_metrics, "failure") mock_sentry_sdk.capture_exception.assert_called_once() mock_logger.warning.assert_called_once_with( "integrations.slo.failure", extra={ "extra": "value", "integration_domain": "messaging", "integration_name": "my_integration", "interaction_type": "my_interaction", "exception_summary": repr(ExampleException()), "slo_event_id": "test-event-id", }, ) @mock.patch("sentry.integrations.utils.metrics.sentry_sdk") @mock.patch("sentry.integrations.utils.metrics.logger") @mock.patch("sentry.integrations.utils.metrics.metrics") def test_recording_explicit_failure_with_exception( self, mock_metrics, mock_logger, mock_sentry_sdk ): mock_sentry_sdk.capture_exception.return_value = "test-event-id" metric_obj = self.TestLifecycleMetric() with metric_obj.capture() as lifecycle: try: lifecycle.add_extra("extra", "value") raise ExampleException() except ExampleException as exc: lifecycle.record_failure(exc, extra={"even": "more"}) self._check_metrics_call_args(mock_metrics, "failure") mock_sentry_sdk.capture_exception.assert_called_once() mock_logger.warning.assert_called_once_with( "integrations.slo.failure", extra={ "extra": "value", "even": "more", "integration_domain": "messaging", "integration_name": "my_integration", "interaction_type": "my_interaction", "exception_summary": repr(ExampleException()), "slo_event_id": "test-event-id", }, ) @mock.patch("sentry.integrations.utils.metrics.logger") @mock.patch("sentry.integrations.utils.metrics.metrics") def test_recording_explicit_failure_with_str( self, mock_metrics: mock.MagicMock, mock_logger: mock.MagicMock ) -> None: metric_obj = self.TestLifecycleMetric() with metric_obj.capture() as lifecycle: lifecycle.add_extra("extra", "value") lifecycle.record_failure("Integration went boom", extra={"even": "more"}) self._check_metrics_call_args(mock_metrics, "failure") mock_logger.warning.assert_called_once_with( "integrations.slo.failure", extra={ "outcome_reason": "Integration went boom", "extra": "value", "even": "more", "integration_domain": "messaging", "integration_name": "my_integration", "interaction_type": "my_interaction", }, ) @mock.patch("sentry.integrations.utils.metrics.sentry_sdk") @mock.patch("sentry.integrations.utils.metrics.logger") @mock.patch("sentry.integrations.utils.metrics.metrics") def test_recording_halt_with_create_issue_true( self, mock_metrics, mock_logger, mock_sentry_sdk ): """ Test that halt can create Sentry issues when create_issue=True """ mock_sentry_sdk.capture_exception.return_value = "test-event-id" metric_obj = self.TestLifecycleMetric() with metric_obj.capture() as lifecycle: lifecycle.add_extra("extra", "value") lifecycle.record_halt(ExampleException("test"), create_issue=True) self._check_metrics_call_args(mock_metrics, "halted") mock_sentry_sdk.capture_exception.assert_called_once() mock_logger.info.assert_called_once_with( "integrations.slo.halted", extra={ "extra": "value", "integration_domain": "messaging", "integration_name": "my_integration", "interaction_type": "my_interaction", "exception_summary": repr(ExampleException("test")), "slo_event_id": "test-event-id", }, ) @mock.patch("sentry.integrations.utils.metrics.logger") @mock.patch("sentry.integrations.utils.metrics.metrics") def test_recording_failure_with_create_issue_false( self, mock_metrics: mock.MagicMock, mock_logger: mock.MagicMock ) -> None: """ Test that failure can skip creating Sentry issues when create_issue=False """ metric_obj = self.TestLifecycleMetric() with metric_obj.capture() as lifecycle: lifecycle.add_extra("extra", "value") lifecycle.record_failure(ExampleException("test"), create_issue=False) self._check_metrics_call_args(mock_metrics, "failure") mock_logger.warning.assert_called_once_with( "integrations.slo.failure", extra={ "extra": "value", "integration_domain": "messaging", "integration_name": "my_integration", "interaction_type": "my_interaction", "exception_summary": repr(ExampleException("test")), }, ) @mock.patch("sentry.integrations.utils.metrics.random") @mock.patch("sentry.integrations.utils.metrics.logger") @mock.patch("sentry.integrations.utils.metrics.metrics") def test_sample_log_rate_always_logs_when_rate_is_one( self, mock_metrics, mock_logger, mock_random ): """Test that sample_log_rate=1.0 always logs (default behavior)""" metric_obj = self.TestLifecycleMetric() with metric_obj.capture(sample_log_rate=1.0) as lifecycle: lifecycle.record_failure("test failure") # Metrics should always be called self._check_metrics_call_args(mock_metrics, "failure") # Logger should be called since rate is 1.0 mock_logger.warning.assert_called_once() # random.random() should not be called when rate >= 1.0 mock_random.random.assert_not_called() @mock.patch("sentry.integrations.utils.metrics.random") @mock.patch("sentry.integrations.utils.metrics.logger") @mock.patch("sentry.integrations.utils.metrics.metrics") def test_sample_log_rate_logs_when_random_passes( self, mock_metrics: mock.MagicMock, mock_logger: mock.MagicMock, mock_random: mock.MagicMock ) -> None: """Test that logging occurs when random value is below sample rate""" mock_random.random.return_value = 0.05 # Below 0.1 threshold metric_obj = self.TestLifecycleMetric() with metric_obj.capture(sample_log_rate=0.1) as lifecycle: lifecycle.record_failure("test failure") # Metrics should always be called self._check_metrics_call_args(mock_metrics, "failure") # Logger should be called since 0.05 < 0.1 mock_logger.warning.assert_called_once() mock_random.random.assert_called_once() @mock.patch("sentry.integrations.utils.metrics.random") @mock.patch("sentry.integrations.utils.metrics.logger") @mock.patch("sentry.integrations.utils.metrics.metrics") def test_sample_log_rate_skips_when_random_fails( self, mock_metrics: mock.MagicMock, mock_logger: mock.MagicMock, mock_random: mock.MagicMock ) -> None: """Test that logging is skipped when random value is above sample rate""" mock_random.random.return_value = 0.15 # Above 0.1 threshold metric_obj = self.TestLifecycleMetric() with metric_obj.capture(sample_log_rate=0.1) as lifecycle: lifecycle.record_failure("test failure") # Metrics should always be called self._check_metrics_call_args(mock_metrics, "failure") # Logger should NOT be called since 0.15 > 0.1 mock_logger.warning.assert_not_called() mock_random.random.assert_called_once() @mock.patch("sentry.integrations.utils.metrics.random") @mock.patch("sentry.integrations.utils.metrics.logger") @mock.patch("sentry.integrations.utils.metrics.metrics") def test_sample_log_rate_halt_with_sampling( self, mock_metrics: mock.MagicMock, mock_logger: mock.MagicMock, mock_random: mock.MagicMock ) -> None: """Test that halt logging respects sample rate""" mock_random.random.return_value = 0.05 # Below 0.2 threshold metric_obj = self.TestLifecycleMetric() with metric_obj.capture(sample_log_rate=0.2) as lifecycle: lifecycle.record_halt("test halt") # Metrics should always be called self._check_metrics_call_args(mock_metrics, "halted") # Logger should be called since 0.05 < 0.2 mock_logger.info.assert_called_once() mock_random.random.assert_called_once() @mock.patch("sentry.integrations.utils.metrics.random") @mock.patch("sentry.integrations.utils.metrics.logger") @mock.patch("sentry.integrations.utils.metrics.metrics") def test_per_call_sample_log_rate_overrides_instance_rate( self, mock_metrics, mock_logger, mock_random ): """Test that per-call sample_log_rate overrides instance default""" mock_random.random.return_value = 0.15 # Between 0.1 and 0.3 metric_obj = self.TestLifecycleMetric() with metric_obj.capture(sample_log_rate=0.1) as lifecycle: # Per-call rate of 0.3 should override instance rate of 0.1 lifecycle.record_failure("test failure", sample_log_rate=0.3) # Metrics should always be called self._check_metrics_call_args(mock_metrics, "failure") # Logger should be called since 0.15 < 0.3 (per-call rate) mock_logger.warning.assert_called_once() mock_random.random.assert_called_once() @mock.patch("sentry.integrations.utils.metrics.random") @mock.patch("sentry.integrations.utils.metrics.logger") @mock.patch("sentry.integrations.utils.metrics.metrics") def test_per_call_sample_log_rate_skips_when_below_threshold( self, mock_metrics, mock_logger, mock_random ): """Test that per-call sample_log_rate can cause skipping even with higher instance rate""" mock_random.random.return_value = 0.15 # Between 0.05 and 1.0 metric_obj = self.TestLifecycleMetric() with metric_obj.capture(sample_log_rate=1.0) as lifecycle: # Per-call rate of 0.05 should override instance rate of 1.0 lifecycle.record_halt("test halt", sample_log_rate=0.05) # Metrics should always be called self._check_metrics_call_args(mock_metrics, "halted") # Logger should NOT be called since 0.15 > 0.05 (per-call rate) mock_logger.info.assert_not_called() mock_random.random.assert_called_once() @mock.patch("sentry.integrations.utils.metrics.random") @mock.patch("sentry.integrations.utils.metrics.logger") @mock.patch("sentry.integrations.utils.metrics.metrics") def test_zero_sample_log_rate_never_logs( self, mock_metrics: mock.MagicMock, mock_logger: mock.MagicMock, mock_random: mock.MagicMock ) -> None: """Test that sample_log_rate=0.0 never logs""" mock_random.random.return_value = 0.0 # Even lowest possible random value metric_obj = self.TestLifecycleMetric() with metric_obj.capture(sample_log_rate=0.0) as lifecycle: lifecycle.record_failure("test failure") # Metrics should always be called self._check_metrics_call_args(mock_metrics, "failure") # Logger should NOT be called since rate is 0.0 mock_logger.warning.assert_not_called() # Random should still be called for 0.0 < 1.0 check mock_random.random.assert_called_once() @mock.patch("sentry.integrations.utils.metrics.random") @mock.patch("sentry.integrations.utils.metrics.logger") @mock.patch("sentry.integrations.utils.metrics.metrics") def test_sample_log_rate_on_exception_exit( self, mock_metrics: mock.MagicMock, mock_logger: mock.MagicMock, mock_random: mock.MagicMock ) -> None: """Test that sample rate is respected when exiting context with exception""" mock_random.random.return_value = 0.15 # Above 0.1 threshold metric_obj = self.TestLifecycleMetric() with pytest.raises(ExampleException): with metric_obj.capture(sample_log_rate=0.1): raise ExampleException("test") # Metrics should always be called self._check_metrics_call_args(mock_metrics, "failure") # Logger should NOT be called since 0.15 > 0.1 mock_logger.warning.assert_not_called() mock_random.random.assert_called_once() @mock.patch("sentry.integrations.utils.metrics.random") @mock.patch("sentry.integrations.utils.metrics.logger") @mock.patch("sentry.integrations.utils.metrics.metrics") def test_sample_log_rate_on_assume_success_false_exit( self, mock_metrics, mock_logger, mock_random ): """Test that sample rate is respected when exiting context with assume_success=False""" mock_random.random.return_value = 0.25 # Above 0.2 threshold metric_obj = self.TestLifecycleMetric() with metric_obj.capture(assume_success=False, sample_log_rate=0.2): pass # Exit without explicit success/failure # Metrics should always be called self._check_metrics_call_args(mock_metrics, "halted") # Logger should NOT be called since 0.25 > 0.2 mock_logger.info.assert_not_called() mock_random.random.assert_called_once() @mock.patch("sentry.integrations.utils.metrics.logger") @mock.patch("sentry.integrations.utils.metrics.metrics") def test_default_sample_log_rate_is_one( self, mock_metrics: mock.MagicMock, mock_logger: mock.MagicMock ) -> None: """Test that default sample_log_rate is 1.0 (always log)""" metric_obj = self.TestLifecycleMetric() # Test default through capture() with metric_obj.capture() as lifecycle: lifecycle.record_failure("test failure") # Should log since default is 1.0 mock_logger.warning.assert_called_once() mock_logger.reset_mock() mock_metrics.reset_mock() # Test default through constructor with metric_obj.capture(assume_success=False): pass # Will record halt # Should log since default is 1.0 mock_logger.info.assert_called_once()
IntegrationEventLifecycleMetricTest
python
pypa__setuptools
setuptools/tests/test_build_clib.py
{ "start": 202, "end": 3123 }
class ____: @mock.patch('setuptools.command.build_clib.newer_pairwise_group') def test_build_libraries(self, mock_newer): dist = Distribution() cmd = build_clib(dist) # this will be a long section, just making sure all # exceptions are properly raised libs = [('example', {'sources': 'broken.c'})] with pytest.raises(DistutilsSetupError): cmd.build_libraries(libs) obj_deps = 'some_string' libs = [('example', {'sources': ['source.c'], 'obj_deps': obj_deps})] with pytest.raises(DistutilsSetupError): cmd.build_libraries(libs) obj_deps = {'': ''} libs = [('example', {'sources': ['source.c'], 'obj_deps': obj_deps})] with pytest.raises(DistutilsSetupError): cmd.build_libraries(libs) obj_deps = {'source.c': ''} libs = [('example', {'sources': ['source.c'], 'obj_deps': obj_deps})] with pytest.raises(DistutilsSetupError): cmd.build_libraries(libs) # with that out of the way, let's see if the crude dependency # system works cmd.compiler = mock.MagicMock(spec=cmd.compiler) mock_newer.return_value = ([], []) obj_deps = {'': ('global.h',), 'example.c': ('example.h',)} libs = [('example', {'sources': ['example.c'], 'obj_deps': obj_deps})] cmd.build_libraries(libs) assert [['example.c', 'global.h', 'example.h']] in mock_newer.call_args[0] assert not cmd.compiler.compile.called assert cmd.compiler.create_static_lib.call_count == 1 # reset the call numbers so we can test again cmd.compiler.reset_mock() mock_newer.return_value = '' # anything as long as it's not ([],[]) cmd.build_libraries(libs) assert cmd.compiler.compile.call_count == 1 assert cmd.compiler.create_static_lib.call_count == 1 @mock.patch('setuptools.command.build_clib.newer_pairwise_group') def test_build_libraries_reproducible(self, mock_newer): dist = Distribution() cmd = build_clib(dist) # with that out of the way, let's see if the crude dependency # system works cmd.compiler = mock.MagicMock(spec=cmd.compiler) mock_newer.return_value = ([], []) original_sources = ['a-example.c', 'example.c'] sources = original_sources obj_deps = {'': ('global.h',), 'example.c': ('example.h',)} libs = [('example', {'sources': sources, 'obj_deps': obj_deps})] cmd.build_libraries(libs) computed_call_args = mock_newer.call_args[0] while sources == original_sources: sources = random.sample(original_sources, len(original_sources)) libs = [('example', {'sources': sources, 'obj_deps': obj_deps})] cmd.build_libraries(libs) assert computed_call_args == mock_newer.call_args[0]
TestBuildCLib
python
ray-project__ray
python/ray/tune/registry.py
{ "start": 5669, "end": 8823 }
class ____: def __init__(self, prefix: Optional[str] = None): """If no prefix is given, use runtime context job ID.""" self._to_flush = {} self._prefix = prefix self._registered = set() self._atexit_handler_registered = False @property def prefix(self): if not self._prefix: self._prefix = ray.get_runtime_context().get_job_id() return self._prefix def _register_atexit(self): if self._atexit_handler_registered: # Already registered return if ray._private.worker.global_worker.mode != ray.SCRIPT_MODE: # Only cleanup on the driver return atexit.register(_unregister_all) self._atexit_handler_registered = True def register(self, category, key, value): """Registers the value with the global registry. Args: category: The category to register under. key: The key to register under. value: The value to register. Raises: PicklingError: If unable to pickle to provided file. """ if category not in KNOWN_CATEGORIES: from ray.tune import TuneError raise TuneError( "Unknown category {} not among {}".format(category, KNOWN_CATEGORIES) ) self._to_flush[(category, key)] = pickle.dumps_debug(value) if _internal_kv_initialized(): self.flush_values() def unregister(self, category, key): if _internal_kv_initialized(): _internal_kv_del(_make_key(self.prefix, category, key)) else: self._to_flush.pop((category, key), None) def unregister_all(self, category: Optional[str] = None): remaining = set() for cat, key in self._registered: if category and category == cat: self.unregister(cat, key) else: remaining.add((cat, key)) self._registered = remaining def contains(self, category, key): if _internal_kv_initialized(): value = _internal_kv_get(_make_key(self.prefix, category, key)) return value is not None else: return (category, key) in self._to_flush def get(self, category, key): if _internal_kv_initialized(): value = _internal_kv_get(_make_key(self.prefix, category, key)) if value is None: raise ValueError( "Registry value for {}/{} doesn't exist.".format(category, key) ) return pickle.loads(value) else: return pickle.loads(self._to_flush[(category, key)]) def flush_values(self): self._register_atexit() for (category, key), value in self._to_flush.items(): _internal_kv_put( _make_key(self.prefix, category, key), value, overwrite=True ) self._registered.add((category, key)) self._to_flush.clear() _global_registry = _Registry() ray._private.worker._post_init_hooks.append(_global_registry.flush_values)
_Registry
python
Pylons__pyramid
src/pyramid/authorization.py
{ "start": 1233, "end": 2665 }
class ____: """An :term:`authorization policy` which consults an :term:`ACL` object attached to a :term:`context` to determine authorization information about a :term:`principal` or multiple principals. This class is a wrapper around :class:`.ACLHelper`, refer to that class for more detailed documentation. Objects of this class implement the :class:`pyramid.interfaces.IAuthorizationPolicy` interface. .. deprecated:: 2.0 Authorization policies have been deprecated by the new security system. See :ref:`upgrading_auth_20` for more information. """ def __init__(self): self.helper = ACLHelper() def permits(self, context, principals, permission): """Return an instance of :class:`pyramid.authorization.ACLAllowed` instance if the policy permits access, return an instance of :class:`pyramid.authorization.ACLDenied` if not.""" return self.helper.permits(context, principals, permission) def principals_allowed_by_permission(self, context, permission): """Return the set of principals explicitly granted the permission named ``permission`` according to the ACL directly attached to the ``context`` as well as inherited ACLs based on the :term:`lineage`.""" return self.helper.principals_allowed_by_permission( context, permission )
ACLAuthorizationPolicy
python
networkx__networkx
networkx/generators/tests/test_directed.py
{ "start": 477, "end": 3117 }
class ____: def test_smoke_test_random_graphs(self): gn_graph(100) gnr_graph(100, 0.5) gnc_graph(100) scale_free_graph(100) gn_graph(100, seed=42) gnr_graph(100, 0.5, seed=42) gnc_graph(100, seed=42) scale_free_graph(100, seed=42) def test_create_using_keyword_arguments(self): pytest.raises(nx.NetworkXError, gn_graph, 100, create_using=Graph()) pytest.raises(nx.NetworkXError, gnr_graph, 100, 0.5, create_using=Graph()) pytest.raises(nx.NetworkXError, gnc_graph, 100, create_using=Graph()) G = gn_graph(100, seed=1) MG = gn_graph(100, create_using=MultiDiGraph(), seed=1) assert sorted(G.edges()) == sorted(MG.edges()) G = gnr_graph(100, 0.5, seed=1) MG = gnr_graph(100, 0.5, create_using=MultiDiGraph(), seed=1) assert sorted(G.edges()) == sorted(MG.edges()) G = gnc_graph(100, seed=1) MG = gnc_graph(100, create_using=MultiDiGraph(), seed=1) assert sorted(G.edges()) == sorted(MG.edges()) G = scale_free_graph( 100, alpha=0.3, beta=0.4, gamma=0.3, delta_in=0.3, delta_out=0.1, initial_graph=nx.cycle_graph(4, create_using=MultiDiGraph), seed=1, ) pytest.raises(ValueError, scale_free_graph, 100, 0.5, 0.4, 0.3) pytest.raises(ValueError, scale_free_graph, 100, alpha=-0.3) pytest.raises(ValueError, scale_free_graph, 100, beta=-0.3) pytest.raises(ValueError, scale_free_graph, 100, gamma=-0.3) def test_parameters(self): G = nx.DiGraph() G.add_node(0) def kernel(x): return x assert nx.is_isomorphic(gn_graph(1), G) assert nx.is_isomorphic(gn_graph(1, kernel=kernel), G) assert nx.is_isomorphic(gnc_graph(1), G) assert nx.is_isomorphic(gnr_graph(1, 0.5), G) def test_scale_free_graph_negative_delta(): with pytest.raises(ValueError, match="delta_in must be >= 0."): scale_free_graph(10, delta_in=-1) with pytest.raises(ValueError, match="delta_out must be >= 0."): scale_free_graph(10, delta_out=-1) def test_non_numeric_ordering(): G = MultiDiGraph([("a", "b"), ("b", "c"), ("c", "a")]) s = scale_free_graph(3, initial_graph=G) assert len(s) == 3 assert len(s.edges) == 3 @pytest.mark.parametrize("ig", (nx.Graph(), nx.DiGraph([(0, 1)]))) def test_scale_free_graph_initial_graph_kwarg(ig): with pytest.raises(nx.NetworkXError): scale_free_graph(100, initial_graph=ig)
TestGeneratorsDirected
python
huggingface__transformers
tests/models/olmoe/test_modeling_olmoe.py
{ "start": 1386, "end": 6401 }
class ____: def __init__( self, parent, batch_size=13, seq_length=7, is_training=True, use_input_mask=True, use_token_type_ids=False, use_labels=True, vocab_size=99, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, hidden_act="silu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=16, type_sequence_label_size=2, initializer_range=0.02, num_labels=3, num_choices=4, pad_token_id=0, scope=None, num_experts_per_tok=2, num_experts=8, norm_topk_prob=False, output_router_logits=False, router_aux_loss_coef=0.001, intermediate_size=12, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.use_input_mask = use_input_mask self.use_token_type_ids = use_token_type_ids self.use_labels = use_labels self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.type_sequence_label_size = type_sequence_label_size self.initializer_range = initializer_range self.num_labels = num_labels self.num_choices = num_choices self.pad_token_id = pad_token_id self.scope = scope self.num_experts_per_tok = num_experts_per_tok self.num_experts = num_experts self.norm_topk_prob = norm_topk_prob self.output_router_logits = output_router_logits self.router_aux_loss_coef = router_aux_loss_coef def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) input_mask = None if self.use_input_mask: input_mask = torch.tril(torch.ones_like(input_ids).to(torch_device)) token_type_ids = None if self.use_token_type_ids: token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) sequence_labels = None token_labels = None choice_labels = None if self.use_labels: sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) choice_labels = ids_tensor([self.batch_size], self.num_choices) config = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def get_config(self): return OlmoeConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, is_decoder=False, initializer_range=self.initializer_range, pad_token_id=self.pad_token_id, num_experts_per_tok=self.num_experts_per_tok, num_experts=self.num_experts, norm_topk_prob=self.norm_topk_prob, output_router_logits=self.output_router_logits, router_aux_loss_coef=self.router_aux_loss_coef, ) def create_and_check_model( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = OlmoeModel(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask) result = model(input_ids) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) = config_and_inputs inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch
OlmoeModelTester
python
apache__airflow
providers/papermill/tests/unit/papermill/operators/test_papermill.py
{ "start": 1379, "end": 7680 }
class ____: """Test PapermillOperator.""" def test_mandatory_attributes(self): """Test missing Input or Output notebooks.""" with pytest.raises(ValueError, match="Input notebook is not specified"): PapermillOperator(task_id="missing_input_nb", output_nb="foo-bar") with pytest.raises(ValueError, match="Output notebook is not specified"): PapermillOperator(task_id="missing_input_nb", input_nb="foo-bar") @pytest.mark.parametrize( ("output_nb_url", "output_as_object"), [ pytest.param(TEST_OUTPUT_URL, False, id="output-as-string"), pytest.param(TEST_OUTPUT_URL, True, id="output-as-notebook-object"), ], ) @pytest.mark.parametrize( ("input_nb_url", "input_as_object"), [ pytest.param(TEST_INPUT_URL, False, id="input-as-string"), pytest.param(TEST_INPUT_URL, True, id="input-as-notebook-object"), ], ) @patch("airflow.providers.papermill.operators.papermill.pm") @patch("airflow.providers.papermill.operators.papermill.PapermillOperator.hook") def test_notebooks_objects( self, mock_papermill, mock_hook, input_nb_url: str, output_nb_url: str, input_as_object: bool, output_as_object: bool, ): """Test different type of Input/Output notebooks arguments.""" from airflow.providers.papermill.operators.papermill import NoteBook, PapermillOperator input_nb: NoteBook | str = NoteBook(input_nb_url) if input_as_object else input_nb_url output_nb: NoteBook | str = NoteBook(output_nb_url) if output_as_object else output_nb_url op = PapermillOperator(task_id="test_notebooks_objects", input_nb=input_nb, output_nb=output_nb) op.execute(context={}) assert op.input_nb.url == TEST_INPUT_URL # type: ignore assert op.output_nb.url == TEST_OUTPUT_URL # type: ignore @patch("airflow.providers.papermill.operators.papermill.pm") def test_execute(self, mock_papermill): in_nb = "/tmp/does_not_exist" out_nb = "/tmp/will_not_exist" kernel_name = "python3" language_name = "python" parameters = {"msg": "hello_world", "train": 1} from airflow.providers.papermill.operators.papermill import PapermillOperator op = PapermillOperator( input_nb=in_nb, output_nb=out_nb, parameters=parameters, task_id="papermill_operator_test", kernel_name=kernel_name, language_name=language_name, dag=None, ) op.execute(context={}) mock_papermill.execute_notebook.assert_called_once_with( in_nb, out_nb, parameters=parameters, kernel_name=kernel_name, language=language_name, progress_bar=False, report_mode=True, engine_name=None, ) @patch("airflow.providers.papermill.hooks.kernel.KernelHook.get_connection") @patch("airflow.providers.papermill.operators.papermill.pm") def test_execute_remote_kernel(self, mock_papermill, kernel_hook): in_nb = "/tmp/does_not_exist" out_nb = "/tmp/will_not_exist" kernel_name = "python3" language_name = "python" parameters = {"msg": "hello_world", "train": 1} conn = MagicMock() conn.host = "127.0.0.1" conn.extra_dejson = {"session_key": "notebooks"} kernel_hook.return_value = conn from airflow.providers.papermill.operators.papermill import PapermillOperator op = PapermillOperator( input_nb=in_nb, output_nb=out_nb, parameters=parameters, task_id="papermill_operator_test", kernel_name=kernel_name, language_name=language_name, kernel_conn_id="jupyter_kernel_default", dag=None, ) op.execute(context={}) from airflow.providers.papermill.hooks.kernel import ( JUPYTER_KERNEL_CONTROL_PORT, JUPYTER_KERNEL_HB_PORT, JUPYTER_KERNEL_IOPUB_PORT, JUPYTER_KERNEL_SHELL_PORT, JUPYTER_KERNEL_STDIN_PORT, REMOTE_KERNEL_ENGINE, ) mock_papermill.execute_notebook.assert_called_once_with( in_nb, out_nb, parameters=parameters, kernel_name=kernel_name, language=language_name, progress_bar=False, report_mode=True, engine_name=REMOTE_KERNEL_ENGINE, kernel_session_key="notebooks", kernel_shell_port=JUPYTER_KERNEL_SHELL_PORT, kernel_iopub_port=JUPYTER_KERNEL_IOPUB_PORT, kernel_stdin_port=JUPYTER_KERNEL_STDIN_PORT, kernel_control_port=JUPYTER_KERNEL_CONTROL_PORT, kernel_hb_port=JUPYTER_KERNEL_HB_PORT, kernel_ip="127.0.0.1", ) @pytest.mark.db_test def test_render_template(self, create_task_instance_of_operator): """Test rendering fields.""" from airflow.providers.papermill.operators.papermill import PapermillOperator ti = create_task_instance_of_operator( PapermillOperator, input_nb="/tmp/{{ dag.dag_id }}.ipynb", output_nb="/tmp/out-{{ dag.dag_id }}.ipynb", parameters={"msgs": "dag id is {{ dag.dag_id }}!", "test_dt": "{{ ds }}"}, kernel_name="{{ params.kernel_name }}", language_name="{{ params.language_name }}", # Additional parameters for render fields params={ "kernel_name": "python3", "language_name": "python", }, # TI Settings dag_id="test_render_template", task_id="render_dag_test", ) task = ti.render_templates() # Test render Input/Output notebook attributes assert task.input_nb == "/tmp/test_render_template.ipynb" assert task.output_nb == "/tmp/out-test_render_template.ipynb" # Test render other templated attributes assert task.kernel_name == "python3" assert task.language_name == "python"
TestPapermillOperator
python
scipy__scipy
scipy/stats/tests/test_quantile.py
{ "start": 9255, "end": 11125 }
class ____: @pytest.mark.parametrize('side', ['left', 'right']) @pytest.mark.parametrize('ties', [False, True]) @pytest.mark.parametrize('shape', [0, 1, 2, 10, 11, 1000, 10001, (2, 0), (0, 2), (2, 10), (2, 3, 11)]) @pytest.mark.parametrize('nans_x', [False, True]) @pytest.mark.parametrize('infs_x', [False, True]) def test_nd(self, side, ties, shape, nans_x, infs_x, xp): if nans_x and is_torch(xp): pytest.skip('torch sorts NaNs differently') rng = np.random.default_rng(945298725498274853) if ties: x = rng.integers(5, size=shape) else: x = rng.random(shape) # float32 is to accommodate JAX - nextafter with `float64` is too small? x = np.asarray(x, dtype=np.float32) xr = np.nextafter(x, np.inf) xl = np.nextafter(x, -np.inf) x_ = np.asarray([-np.inf, np.inf, np.nan]) x_ = np.broadcast_to(x_, x.shape[:-1] + (3,)) y = rng.permuted(np.concatenate((xl, x, xr, x_), axis=-1), axis=-1) if nans_x: mask = rng.random(shape) < 0.1 x[mask] = np.nan if infs_x: mask = rng.random(shape) < 0.1 x[mask] = -np.inf mask = rng.random(shape) > 0.9 x[mask] = np.inf x = np.sort(x, axis=-1) x, y = np.asarray(x, dtype=np.float64), np.asarray(y, dtype=np.float64) xp_default_int = xp.asarray(1).dtype if xp_size(x) == 0 and x.ndim > 0 and x.shape[-1] != 0: ref = xp.empty(x.shape[:-1] + (y.shape[-1],), dtype=xp_default_int) else: ref = xp.asarray(np_searchsorted(x, y, side=side), dtype=xp_default_int) x, y = xp.asarray(x), xp.asarray(y) res = _xp_searchsorted(x, y, side=side) xp_assert_equal(res, ref)
Test_XPSearchsorted
python
keras-team__keras
keras/src/initializers/random_initializers.py
{ "start": 230, "end": 1071 }
class ____(Initializer): def __init__(self, seed=None): self._init_seed = seed if seed is None: seed = random.make_default_seed() elif isinstance(seed, dict): seed = serialization_lib.deserialize_keras_object(seed) elif not isinstance(seed, (int, random.SeedGenerator)): raise ValueError( "`seed` argument should be an instance of " "`keras.random.SeedGenerator()` or an integer. " f"Received: seed={seed}" ) self.seed = seed def get_config(self): seed_config = serialization_lib.serialize_keras_object(self._init_seed) return {"seed": seed_config} @keras_export( [ "keras.initializers.RandomNormal", "keras.initializers.random_normal", ] )
RandomInitializer
python
django__django
django/db/models/fields/related_lookups.py
{ "start": 5958, "end": 6036 }
class ____(RelatedLookupMixin, LessThanOrEqual): pass
RelatedLessThanOrEqual
python
coleifer__peewee
peewee.py
{ "start": 54622, "end": 55569 }
class ____(ColumnBase): def __init__(self, nodes, glue=' ', parens=False): self.nodes = nodes self.glue = glue self.parens = parens if parens and len(self.nodes) == 1 and \ isinstance(self.nodes[0], Expression) and \ not self.nodes[0].flat: # Hack to avoid double-parentheses. self.nodes = (self.nodes[0].clone(),) self.nodes[0].flat = True def __sql__(self, ctx): n_nodes = len(self.nodes) if n_nodes == 0: return ctx.literal('()') if self.parens else ctx with ctx(parentheses=self.parens): for i in range(n_nodes - 1): ctx.sql(self.nodes[i]) ctx.literal(self.glue) ctx.sql(self.nodes[n_nodes - 1]) return ctx def CommaNodeList(nodes): return NodeList(nodes, ', ') def EnclosedNodeList(nodes): return NodeList(nodes, ', ', True)
NodeList
python
getsentry__sentry
src/sentry/db/models/fields/hybrid_cloud_foreign_key.py
{ "start": 3835, "end": 5242 }
class ____(models.BigIntegerField[FieldSetType, FieldGetType]): @property def foreign_model(self) -> Any: parts = self.foreign_model_name.split(".") return apps.get_model(app_label=parts[0], model_name=parts[1]) @property def foreign_table_name(self) -> str: return self.foreign_model._meta.db_table def __init__( self, foreign_model: str, *, on_delete: HybridCloudForeignKeyCascadeBehavior | str, **kwds: Any, ): self.on_delete = ( on_delete if isinstance(on_delete, HybridCloudForeignKeyCascadeBehavior) else HybridCloudForeignKeyCascadeBehavior[on_delete.upper()] ).name.upper() parts = foreign_model.split(".") assert ( len(parts) == 2 ), f"{self.__class__.__name__} model reference must be <app>.<ModelName>, got {foreign_model}" self.foreign_model_name = foreign_model kwds.setdefault("db_index", True) super().__init__(**kwds) def deconstruct(self) -> tuple[Any, Any, Any, Any]: (name, path, args, kwds) = super().deconstruct() # This seems wrong, but due to the way django scrubs defaults, this will inevitably be wrong. kwds.setdefault("db_index", False) return name, path, [self.foreign_model_name], dict(on_delete=self.on_delete, **kwds)
HybridCloudForeignKey
python
python-markdown__markdown
markdown/extensions/abbr.py
{ "start": 2649, "end": 4911 }
class ____(Treeprocessor): """ Replace abbreviation text with `<abbr>` elements. """ def __init__(self, md: Markdown | None = None, abbrs: dict | None = None): self.abbrs: dict = abbrs if abbrs is not None else {} self.RE: re.RegexObject | None = None super().__init__(md) def create_element(self, title: str, text: str, tail: str) -> etree.Element: ''' Create an `abbr` element. ''' abbr = etree.Element('abbr', {'title': title}) abbr.text = AtomicString(text) abbr.tail = tail return abbr def iter_element(self, el: etree.Element, parent: etree.Element | None = None) -> None: ''' Recursively iterate over elements, run regex on text and wrap matches in `abbr` tags. ''' for child in reversed(el): self.iter_element(child, el) if text := el.text: if not isinstance(text, AtomicString): for m in reversed(list(self.RE.finditer(text))): if self.abbrs[m.group(0)]: abbr = self.create_element(self.abbrs[m.group(0)], m.group(0), text[m.end():]) el.insert(0, abbr) text = text[:m.start()] el.text = text if parent is not None and el.tail: tail = el.tail index = list(parent).index(el) + 1 if not isinstance(tail, AtomicString): for m in reversed(list(self.RE.finditer(tail))): abbr = self.create_element(self.abbrs[m.group(0)], m.group(0), tail[m.end():]) parent.insert(index, abbr) tail = tail[:m.start()] el.tail = tail def run(self, root: etree.Element) -> etree.Element | None: ''' Step through tree to find known abbreviations. ''' if not self.abbrs: # No abbreviations defined. Skip running processor. return # Build and compile regex abbr_list = list(self.abbrs.keys()) abbr_list.sort(key=len, reverse=True) self.RE = re.compile(f"\\b(?:{ '|'.join(re.escape(key) for key in abbr_list) })\\b") # Step through tree and modify on matches self.iter_element(root)
AbbrTreeprocessor
python
scipy__scipy
scipy/integrate/_ode.py
{ "start": 27432, "end": 27922 }
class ____(RuntimeError): """ Failure due to concurrent usage of an integrator that can be used only for a single problem at a time. """ def __init__(self, name): msg = (f"Integrator `{name}` can be used to solve only a single problem " "at a time. If you want to integrate multiple problems, " "consider using a different integrator (see `ode.set_integrator`)") RuntimeError.__init__(self, msg)
IntegratorConcurrencyError
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/torch_entities/networks.py
{ "start": 17430, "end": 18212 }
class ____(abc.ABC): @abc.abstractmethod def update_normalization(self, buffer: AgentBuffer) -> None: """ Updates normalization of Actor based on the provided List of vector obs. :param vector_obs: A List of vector obs as tensors. """ pass def critic_pass( self, inputs: List[torch.Tensor], memories: Optional[torch.Tensor] = None, sequence_length: int = 1, ) -> Tuple[Dict[str, torch.Tensor], torch.Tensor]: """ Get value outputs for the given obs. :param inputs: List of inputs as tensors. :param memories: Tensor of memories, if using memory. Otherwise, None. :returns: Dict of reward stream to output tensor for values. """ pass
Critic