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
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/schema.py
{ "start": 169308, "end": 173227 }
class ____(ColumnCollectionMixin, Constraint): """A constraint that proxies a ColumnCollection.""" def __init__( self, *columns: _DDLColumnArgument, name: _ConstraintNameArgument = None, deferrable: Optional[bool] = None, initially: Optional[str] = None, info: Optional[_InfoType] = None, _autoattach: bool = True, _column_flag: bool = False, _gather_expressions: Optional[List[_DDLColumnArgument]] = None, **dialect_kw: Any, ) -> None: r""" :param \*columns: A sequence of column names or Column objects. :param name: Optional, the in-database name of this constraint. :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint. :param initially: Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint. :param \**dialect_kw: other keyword arguments including dialect-specific arguments are propagated to the :class:`.Constraint` superclass. """ Constraint.__init__( self, name=name, deferrable=deferrable, initially=initially, info=info, **dialect_kw, ) ColumnCollectionMixin.__init__( self, *columns, _autoattach=_autoattach, _column_flag=_column_flag ) columns: ReadOnlyColumnCollection[str, Column[Any]] """A :class:`_expression.ColumnCollection` representing the set of columns for this constraint. """ def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None: assert isinstance(parent, (Column, Table)) Constraint._set_parent(self, parent) ColumnCollectionMixin._set_parent(self, parent) def __contains__(self, x: Any) -> bool: return x in self._columns @util.deprecated( "1.4", "The :meth:`_schema.ColumnCollectionConstraint.copy` method " "is deprecated and will be removed in a future release.", ) def copy( self, *, target_table: Optional[Table] = None, **kw: Any, ) -> ColumnCollectionConstraint: return self._copy(target_table=target_table, **kw) def _copy( self, *, target_table: Optional[Table] = None, **kw: Any, ) -> ColumnCollectionConstraint: # ticket #5276 constraint_kwargs = {} for dialect_name in self.dialect_options: dialect_options = self.dialect_options[dialect_name]._non_defaults for ( dialect_option_key, dialect_option_value, ) in dialect_options.items(): constraint_kwargs[dialect_name + "_" + dialect_option_key] = ( dialect_option_value ) assert isinstance(self.parent, Table) c = self.__class__( name=self.name, deferrable=self.deferrable, initially=self.initially, *[ _copy_expression(expr, self.parent, target_table) for expr in self._columns ], comment=self.comment, **constraint_kwargs, ) return self._schema_item_copy(c) def contains_column(self, col: Column[Any]) -> bool: """Return True if this constraint contains the given column. Note that this object also contains an attribute ``.columns`` which is a :class:`_expression.ColumnCollection` of :class:`_schema.Column` objects. """ return self._columns.contains_column(col) def __iter__(self) -> Iterator[Column[Any]]: return iter(self._columns) def __len__(self) -> int: return len(self._columns)
ColumnCollectionConstraint
python
django__django
tests/delete/models.py
{ "start": 7090, "end": 7384 }
class ____(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() generic_delete_top = GenericForeignKey("content_type", "object_id") generic_delete_bottom = GenericRelation("GenericDeleteBottom")
GenericB2
python
google__jax
tests/pallas/tpu_pallas_interpret_thread_map_test.py
{ "start": 1085, "end": 2125 }
class ____(jtu.JaxTestCase): def setUp(self): super().setUp() if not jtu.test_device_matches(['cpu']): self.skipTest('CPU-only test') self.num_devices = jax.device_count() if self.num_devices > 1: # Workaround for https://github.com/jax-ml/jax/issues/25671 self.skipTest(f'requires 1 device, found {self.num_devices}') def test_thread_map(self): barrier = threading.Barrier(8) lock = threading.Lock() concurrent_calls = [0] max_concurrent_calls = [0] def _barrier(): with lock: concurrent_calls[0] += 1 max_concurrent_calls[0] = max( max_concurrent_calls[0], concurrent_calls[0]) barrier.wait() with lock: concurrent_calls[0] -= 1 def f(core_index): del core_index jax.experimental.io_callback(_barrier, (), ordered=True) mosaic_interpret._thread_map(f, 8) self.assertEqual(max_concurrent_calls[0], 8) if __name__ == '__main__': absltest.main(testLoader=jtu.JaxTestLoader())
InterpretThreadMapTest
python
numpy__numpy
numpy/_core/code_generators/genapi.py
{ "start": 4890, "end": 5884 }
class ____: def __init__(self, name, return_type, args, doc=''): self.name = name self.return_type = _repl(return_type) self.args = args self.doc = doc def _format_arg(self, typename, name): if typename.endswith('*'): return typename + name else: return typename + ' ' + name def __str__(self): argstr = ', '.join([self._format_arg(*a) for a in self.args]) if self.doc: doccomment = f'/* {self.doc} */\n' else: doccomment = '' return f'{doccomment}{self.return_type} {self.name}({argstr})' def api_hash(self): m = hashlib.md5(usedforsecurity=False) m.update(remove_whitespace(self.return_type)) m.update('\000') m.update(self.name) m.update('\000') for typename, name in self.args: m.update(remove_whitespace(typename)) m.update('\000') return m.hexdigest()[:8]
Function
python
numba__numba
numba/core/dispatcher.py
{ "start": 4150, "end": 6015 }
class ____(_FunctionCompiler): def __init__(self, py_func, targetdescr, targetoptions, locals, pipeline_class): super(_GeneratedFunctionCompiler, self).__init__( py_func, targetdescr, targetoptions, locals, pipeline_class) self.impls = set() def get_globals_for_reduction(self): # This will recursively get the globals used by any nested # implementation function. return serialize._get_function_globals_for_reduction(self.py_func) def _get_implementation(self, args, kws): impl = self.py_func(*args, **kws) # Check the generating function and implementation signatures are # compatible, otherwise compiling would fail later. pysig = utils.pysignature(self.py_func) implsig = utils.pysignature(impl) ok = len(pysig.parameters) == len(implsig.parameters) if ok: for pyparam, implparam in zip(pysig.parameters.values(), implsig.parameters.values()): # We allow the implementation to omit default values, but # if it mentions them, they should have the same value... if (pyparam.name != implparam.name or pyparam.kind != implparam.kind or (implparam.default is not implparam.empty and implparam.default != pyparam.default)): ok = False if not ok: raise TypeError("generated implementation %s should be compatible " "with signature '%s', but has signature '%s'" % (impl, pysig, implsig)) self.impls.add(impl) return impl _CompileStats = collections.namedtuple( '_CompileStats', ('cache_path', 'cache_hits', 'cache_misses'))
_GeneratedFunctionCompiler
python
apache__thrift
lib/py/src/protocol/TJSONProtocol.py
{ "start": 3285, "end": 3752 }
class ____(): hasData = False data = '' def __init__(self, protocol): self.protocol = protocol def read(self): if self.hasData is True: self.hasData = False else: self.data = self.protocol.trans.read(1) return self.data def peek(self): if self.hasData is False: self.data = self.protocol.trans.read(1) self.hasData = True return self.data
LookaheadReader
python
spyder-ide__spyder
spyder/plugins/completion/confpage.py
{ "start": 400, "end": 4694 }
class ____(PluginConfigPage): def __init__(self, plugin, parent, providers=None): super().__init__(plugin, parent) providers = [] if providers is None else providers self.providers = providers def setup_page(self): newcb = self.create_checkbox # ------------------- Providers status group --------------------------- self.provider_checkboxes = [] providers_layout = QGridLayout() self.providers_group = QGroupBox(_("Providers")) for i, (provider_key, provider_name) in enumerate(self.providers): cb = newcb(_('Enable {0} provider').format(provider_name), ('enabled_providers', provider_key), default=True) providers_layout.addWidget(cb, i, 0) self.provider_checkboxes.append(cb) self.providers_group.setLayout(providers_layout) completions_wait_for_ms = self.create_spinbox( _("Time to wait for all providers to return (ms):"), None, 'completions_wait_for_ms', min_=0, max_=10000, step=10, tip=_("Beyond this timeout the first available provider " "will be returned")) completion_hint_box = newcb( _("Show completion details"), 'completions_hint', section='editor') automatic_completion_box = newcb( _("Show completions on the fly"), 'automatic_completions', section='editor') completions_after_characters = self.create_spinbox( _("Show automatic completions after characters entered:"), None, 'automatic_completions_after_chars', min_=1, step=1, tip=_("Default is 1"), section='editor') code_snippets_box = newcb( _("Enable code snippets"), 'enable_code_snippets') completions_hint_after_idle = self.create_spinbox( _("Show completion details after keyboard idle (ms):"), None, 'completions_hint_after_ms', min_=0, max_=10000, step=10, tip=_("Default is 500 milliseconds"), section='editor') # ------------------- Completions group --------------------------- self.completions_group = QGroupBox(_('Completions')) completions_layout = QGridLayout() completions_layout.addWidget(completion_hint_box, 0, 0) completions_layout.addWidget(code_snippets_box, 1, 0) completions_layout.addWidget(automatic_completion_box, 2, 0) completions_layout.addWidget(completions_after_characters.plabel, 3, 0) completions_layout.addWidget( completions_after_characters.spinbox, 3, 1) completions_layout.addWidget( completions_after_characters.help_label, 3, 2) completions_layout.addWidget(completions_hint_after_idle.plabel, 5, 0) completions_layout.addWidget(completions_hint_after_idle.spinbox, 5, 1) completions_layout.addWidget( completions_hint_after_idle.help_label, 5, 2) completions_layout.addWidget(completions_wait_for_ms.plabel, 6, 0) completions_layout.addWidget(completions_wait_for_ms.spinbox, 6, 1) completions_layout.addWidget(completions_wait_for_ms.help_label, 6, 2) completions_layout.setColumnStretch(3, 6) self.completions_group.setLayout(completions_layout) def disable_completion_after_characters(state): completions_after_characters.plabel.setEnabled(state) completions_after_characters.spinbox.setEnabled(state) automatic_completion_box.checkbox.toggled.connect( disable_completion_after_characters) layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self.completions_group) layout.addWidget(self.providers_group) layout.addStretch(1) self.setLayout(layout) def enable_disable_plugin(self, state): self.providers_group.setEnabled(state) self.completions_group.setEnabled(state) if self.tabs is not None: num_tabs = self.tabs.count() index = 1 while index < num_tabs: tab_widget = self.tabs.widget(index) tab_widget.setEnabled(state) index += 1
CompletionConfigPage
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 926600, "end": 927370 }
class ____(sgqlc.types.Type): """Autogenerated return type of RemoveEnterpriseOrganization""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "enterprise", "organization", "viewer") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation.""" enterprise = sgqlc.types.Field("Enterprise", graphql_name="enterprise") """The updated enterprise.""" organization = sgqlc.types.Field("Organization", graphql_name="organization") """The organization that was removed from the enterprise.""" viewer = sgqlc.types.Field("User", graphql_name="viewer") """The viewer performing the mutation."""
RemoveEnterpriseOrganizationPayload
python
python-openxml__python-docx
tests/test_comments.py
{ "start": 6562, "end": 10068 }
class ____: """Unit-test suite for `docx.comments.Comment`.""" def it_knows_its_comment_id(self, comments_part_: Mock): comment_elm = cast(CT_Comment, element("w:comment{w:id=42}")) comment = Comment(comment_elm, comments_part_) assert comment.comment_id == 42 def it_knows_its_author(self, comments_part_: Mock): comment_elm = cast(CT_Comment, element("w:comment{w:id=42,w:author=Steve Canny}")) comment = Comment(comment_elm, comments_part_) assert comment.author == "Steve Canny" def it_knows_the_initials_of_its_author(self, comments_part_: Mock): comment_elm = cast(CT_Comment, element("w:comment{w:id=42,w:initials=SJC}")) comment = Comment(comment_elm, comments_part_) assert comment.initials == "SJC" def it_knows_the_date_and_time_it_was_authored(self, comments_part_: Mock): comment_elm = cast( CT_Comment, element("w:comment{w:id=42,w:date=2023-10-01T12:34:56Z}"), ) comment = Comment(comment_elm, comments_part_) assert comment.timestamp == dt.datetime(2023, 10, 1, 12, 34, 56, tzinfo=dt.timezone.utc) @pytest.mark.parametrize( ("cxml", "expected_value"), [ ("w:comment{w:id=42}", ""), ('w:comment{w:id=42}/w:p/w:r/w:t"Comment text."', "Comment text."), ( 'w:comment{w:id=42}/(w:p/w:r/w:t"First para",w:p/w:r/w:t"Second para")', "First para\nSecond para", ), ( 'w:comment{w:id=42}/(w:p/w:r/w:t"First para",w:p,w:p/w:r/w:t"Second para")', "First para\n\nSecond para", ), ], ) def it_can_summarize_its_content_as_text( self, cxml: str, expected_value: str, comments_part_: Mock ): assert Comment(cast(CT_Comment, element(cxml)), comments_part_).text == expected_value def it_provides_access_to_the_paragraphs_it_contains(self, comments_part_: Mock): comment_elm = cast( CT_Comment, element('w:comment{w:id=42}/(w:p/w:r/w:t"First para",w:p/w:r/w:t"Second para")'), ) comment = Comment(comment_elm, comments_part_) paragraphs = comment.paragraphs assert len(paragraphs) == 2 assert [para.text for para in paragraphs] == ["First para", "Second para"] def it_can_update_the_comment_author(self, comments_part_: Mock): comment_elm = cast(CT_Comment, element("w:comment{w:id=42,w:author=Old Author}")) comment = Comment(comment_elm, comments_part_) comment.author = "New Author" assert comment.author == "New Author" @pytest.mark.parametrize( "initials", [ # -- valid initials -- "XYZ", # -- empty string is valid "", # -- None is valid, removes existing initials None, ], ) def it_can_update_the_comment_initials(self, initials: str | None, comments_part_: Mock): comment_elm = cast(CT_Comment, element("w:comment{w:id=42,w:initials=ABC}")) comment = Comment(comment_elm, comments_part_) comment.initials = initials assert comment.initials == initials # -- fixtures -------------------------------------------------------------------------------- @pytest.fixture def comments_part_(self, request: FixtureRequest): return instance_mock(request, CommentsPart)
DescribeComment
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 437878, "end": 442325 }
class ____(ExprNode): # Create a PyCodeObject for a CyFunction instance. # # def_node DefNode the Python function node # varnames [IdentifierStringNode] a list of all local variable names subexprs = ['varnames'] is_temp = False result_code = None def __init__(self, def_node): ExprNode.__init__(self, def_node.pos, def_node=def_node) args = list(def_node.args) # if we have args/kwargs, then the first two in var_entries are those local_vars = [arg for arg in def_node.local_scope.var_entries if arg.name] self.varnames = [ IdentifierStringNode(arg.pos, value=arg.name) for arg in args + local_vars ] @classmethod def for_cfunc(cls, cfuncdef_node): return cls(DefFuncLikeNode(cfuncdef_node)) def may_be_none(self): return False def calculate_result_code(self, code=None): if self.result_code is None: self.result_code = code.get_py_codeobj_const(self) return self.result_code def generate_result_code(self, code): if self.result_code is None: self.result_code = code.get_py_codeobj_const(self) def generate_codeobj(self, code, error_label): func = self.def_node first_lineno = self.pos[1] func_name_result = code.get_py_string_const(func.name, identifier=True) # FIXME: better way to get the module file path at module init time? Encoding to use? file_path = func.pos[0].get_filenametable_entry() if os.path.isabs(file_path): file_path = func.pos[0].get_description() # Always use / as separator file_path = StringEncoding.EncodedString(pathlib.Path(file_path).as_posix()) file_path_result = code.get_py_string_const(file_path) if func.node_positions: line_table = StringEncoding.bytes_literal(build_line_table(func.node_positions, first_lineno).encode('iso8859-1'), 'iso8859-1') line_table_result = code.get_py_string_const(line_table) line_table_length = len(line_table) else: line_table_result = "NULL" line_table_length = 0 # '(CO_OPTIMIZED | CO_NEWLOCALS)' makes CPython create a new dict for "frame.f_locals". # See https://github.com/cython/cython/pull/1836 flags = ['CO_OPTIMIZED', 'CO_NEWLOCALS'] if func.star_arg: flags.append('CO_VARARGS') if func.starstar_arg: flags.append('CO_VARKEYWORDS') if func.is_asyncgen: flags.append('CO_ASYNC_GENERATOR') elif func.is_coroutine: flags.append('CO_COROUTINE') elif func.is_generator: flags.append('CO_GENERATOR') if func.is_generator_expression: # Only generated arguments from the outermost iterable, nothing user visible. # 'func.args' is constructed late for these, and they (rightfully) do not appear in 'varnames'. argcount = 0 else: argcount = len(func.args) num_posonly_args = func.num_posonly_args # Py3.8+ only kwonly_argcount = func.num_kwonly_args nlocals = len(self.varnames) flags = '(unsigned int)(%s)' % '|'.join(flags) or '0' # See "generate_codeobject_constants()" in Code.py. code.putln("{") code.putln( "const __Pyx_PyCode_New_function_description descr = {" f"{argcount - kwonly_argcount}, " f"{num_posonly_args}, " f"{kwonly_argcount}, " f"{nlocals}, " f"{flags}, " f"{first_lineno}" "};" ) for var in self.varnames: var.generate_evaluation_code(code) varnames = [var.py_result() for var in self.varnames] or ['0'] code.putln("PyObject* const varnames[] = {%s};" % ', '.join(varnames)) for var in self.varnames: var.generate_disposal_code(code) var.free_temps(code) code.putln( f"{self.result_code} = __Pyx_PyCode_New(" f"descr, " f"varnames, " f"{file_path_result}, " f"{func_name_result}, " f"{line_table_result}, " f"tuple_dedup_map" f"); " f"if (unlikely(!{self.result_code})) goto {error_label};" ) code.putln("}")
CodeObjectNode
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_relationship.py
{ "start": 66310, "end": 76222 }
class ____( fixtures.DeclarativeMappedTest, testing.AssertsCompiledSQL ): """exercise issues in #3593 and #3611""" run_setup_mappers = "each" run_setup_classes = "each" run_define_tables = "each" __dialect__ = "default" @classmethod def setup_classes(cls): Base = cls.DeclarativeBasic class Owner(Base): __tablename__ = "owner" id = Column(Integer, primary_key=True) type = Column(String(20)) __mapper_args__ = { "polymorphic_on": type, "with_polymorphic": ("*", None), } class SubOwner(Owner): __mapper_args__ = {"polymorphic_identity": "so"} class Parent(Base): __tablename__ = "parent" id = Column(Integer, primary_key=True) type = Column(String(20)) __mapper_args__ = { "polymorphic_on": type, "polymorphic_identity": "parent", "with_polymorphic": ("*", None), } class Sub1(Parent): __mapper_args__ = {"polymorphic_identity": "s1"} class Link(Base): __tablename__ = "link" parent_id = Column( Integer, ForeignKey("parent.id"), primary_key=True ) child_id = Column( Integer, ForeignKey("parent.id"), primary_key=True ) def _fixture_from_base(self): Parent = self.classes.Parent Link = self.classes.Link Link.child = relationship( Parent, primaryjoin=Link.child_id == Parent.id ) Parent.links = relationship( Link, primaryjoin=Parent.id == Link.parent_id ) return Parent def _fixture_from_subclass(self): Sub1 = self.classes.Sub1 Link = self.classes.Link Parent = self.classes.Parent Link.child = relationship( Parent, primaryjoin=Link.child_id == Parent.id ) Sub1.links = relationship(Link, primaryjoin=Sub1.id == Link.parent_id) return Sub1 def _fixture_to_subclass_to_base(self): Owner = self.classes.Owner Parent = self.classes.Parent Sub1 = self.classes.Sub1 Link = self.classes.Link # Link -> Sub1 -> Owner Link.child = relationship(Sub1, primaryjoin=Link.child_id == Sub1.id) Parent.owner_id = Column(ForeignKey("owner.id")) Parent.owner = relationship(Owner) return Parent def _fixture_to_base_to_base(self): Owner = self.classes.Owner Parent = self.classes.Parent Link = self.classes.Link # Link -> Parent -> Owner Link.child = relationship( Parent, primaryjoin=Link.child_id == Parent.id ) Parent.owner_id = Column(ForeignKey("owner.id")) Parent.owner = relationship(Owner) return Parent def test_from_base(self): self._test_poly_single_poly(self._fixture_from_base) def test_from_sub(self): self._test_poly_single_poly(self._fixture_from_subclass) def test_to_sub_to_base(self): self._test_single_poly_poly(self._fixture_to_subclass_to_base) def test_to_base_to_base(self): self._test_single_poly_poly(self._fixture_to_base_to_base) def _test_poly_single_poly(self, fn): cls = fn() Link = self.classes.Link session = fixture_session() if ( cls is self.classes.Sub1 and Link.child.entity.class_ is self.classes.Parent ): # in 1.x we weren't checking for this: # query(Sub1).options( # joinedload(Sub1.links).joinedload(Link.child).joinedload(Sub1.links) # ) # # where Link.child points to Parent. the above is illegal because # Link.child will return Parent instances that are not Sub1, # so we cannot assume we will have Sub1.links available. this now # raises with expect_raises_message( exc.ArgumentError, r'ORM mapped entity or attribute "Sub1.links" does not ' r'link from relationship "Link.child". Did you mean to use ' r'"Link.child.of_type\(Sub1\)"\ or ' r'"loadopt.options' r'\(selectin_polymorphic\(Parent, \[Sub1\]\), ...\)" \?', ): session.query(cls).options( joinedload(cls.links) .joinedload(Link.child) .joinedload(cls.links) ) q = session.query(cls).options( joinedload(cls.links) .joinedload(Link.child.of_type(cls)) .joinedload(cls.links) ) else: q = session.query(cls).options( joinedload(cls.links) .joinedload(Link.child) .joinedload(cls.links) ) if cls is self.classes.Sub1: extra = " WHERE parent.type IN (__[POSTCOMPILE_type_1])" else: extra = "" self.assert_compile( q, "SELECT parent.id AS parent_id, parent.type AS parent_type, " "link_1.parent_id AS link_1_parent_id, " "link_1.child_id AS link_1_child_id, " "parent_1.id AS parent_1_id, parent_1.type AS parent_1_type, " "link_2.parent_id AS link_2_parent_id, " "link_2.child_id AS link_2_child_id " "FROM parent " "LEFT OUTER JOIN link AS link_1 ON parent.id = link_1.parent_id " "LEFT OUTER JOIN parent " "AS parent_1 ON link_1.child_id = parent_1.id " "LEFT OUTER JOIN link AS link_2 " "ON parent_1.id = link_2.parent_id" + extra, ) def _test_single_poly_poly(self, fn): parent_cls = fn() Link = self.classes.Link session = fixture_session() q = session.query(Link).options( joinedload(Link.child).joinedload(parent_cls.owner) ) if Link.child.property.mapper.class_ is self.classes.Sub1: extra = "AND parent_1.type IN (__[POSTCOMPILE_type_1]) " else: extra = "" self.assert_compile( q, "SELECT link.parent_id AS link_parent_id, " "link.child_id AS link_child_id, parent_1.id AS parent_1_id, " "parent_1.type AS parent_1_type, " "parent_1.owner_id AS parent_1_owner_id, " "owner_1.id AS owner_1_id, owner_1.type AS owner_1_type " "FROM link LEFT OUTER JOIN parent AS parent_1 " "ON link.child_id = parent_1.id " + extra + "LEFT OUTER JOIN owner AS owner_1 " "ON owner_1.id = parent_1.owner_id", ) def test_local_wpoly(self): Sub1 = self._fixture_from_subclass() Parent = self.classes.Parent Link = self.classes.Link poly = with_polymorphic(Parent, [Sub1]) session = fixture_session() q = session.query(poly).options( joinedload(poly.Sub1.links) .joinedload(Link.child.of_type(Sub1)) .joinedload(Sub1.links) ) self.assert_compile( q, "SELECT parent.id AS parent_id, parent.type AS parent_type, " "link_1.parent_id AS link_1_parent_id, " "link_1.child_id AS link_1_child_id, " "parent_1.id AS parent_1_id, parent_1.type AS parent_1_type, " "link_2.parent_id AS link_2_parent_id, " "link_2.child_id AS link_2_child_id FROM parent " "LEFT OUTER JOIN link AS link_1 ON parent.id = link_1.parent_id " "LEFT OUTER JOIN parent AS parent_1 " "ON link_1.child_id = parent_1.id " "LEFT OUTER JOIN link AS link_2 ON parent_1.id = link_2.parent_id", ) def test_local_wpoly_innerjoins(self): # test for issue #3988 Sub1 = self._fixture_from_subclass() Parent = self.classes.Parent Link = self.classes.Link poly = with_polymorphic(Parent, [Sub1]) session = fixture_session() q = session.query(poly).options( joinedload(poly.Sub1.links, innerjoin=True) .joinedload(Link.child.of_type(Sub1), innerjoin=True) .joinedload(Sub1.links, innerjoin=True) ) self.assert_compile( q, "SELECT parent.id AS parent_id, parent.type AS parent_type, " "link_1.parent_id AS link_1_parent_id, " "link_1.child_id AS link_1_child_id, " "parent_1.id AS parent_1_id, parent_1.type AS parent_1_type, " "link_2.parent_id AS link_2_parent_id, " "link_2.child_id AS link_2_child_id FROM parent " "LEFT OUTER JOIN link AS link_1 ON parent.id = link_1.parent_id " "LEFT OUTER JOIN parent AS parent_1 " "ON link_1.child_id = parent_1.id " "LEFT OUTER JOIN link AS link_2 ON parent_1.id = link_2.parent_id", ) def test_local_wpoly_innerjoins_roundtrip(self): # test for issue #3988 Sub1 = self._fixture_from_subclass() Parent = self.classes.Parent Link = self.classes.Link session = fixture_session() session.add_all([Parent(), Parent()]) # represents "Parent" and "Sub1" rows poly = with_polymorphic(Parent, [Sub1]) # innerjoin for Sub1 only, but this needs # to be cancelled because the Parent rows # would be omitted q = session.query(poly).options( joinedload(poly.Sub1.links, innerjoin=True).joinedload( Link.child.of_type(Sub1), innerjoin=True ) ) eq_(len(q.all()), 2)
JoinedloadOverWPolyAliased
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 42178, "end": 42332 }
class ____(sgqlc.types.Enum): """ See source code for more info. """ __schema__ = graphql_schema __choices__ = ("NAME",)
TeamOrderField
python
pyinstaller__pyinstaller
tests/unit/test_pyimodulegraph.py
{ "start": 8309, "end": 9489 }
class ____(analysis.PyiModuleGraph): """ A simplified module graph containing a single node module *foo* with user-defined content. """ def __init__(self, source): self.code = compile(source, "<>", "exec") def get_code_using(self, package): return {"foo": self.code} def test_metadata_searching(): """ Test the top level for bytecode scanning for metadata requirements. """ from PyInstaller.utils.hooks import copy_metadata # This test analyses code which implies that PyInstaller's own metadata (and possibly that of its dependencies) is # required. pyinstaller = set(copy_metadata("pyinstaller")) with_dependencies = set(copy_metadata("pyinstaller", recursive=True)) self = FakeGraph("from importlib.metadata import distribution; distribution('pyinstaller')") assert pyinstaller == self.metadata_required() self = FakeGraph("import pkg_resources; pkg_resources.get_distribution('pyinstaller')") assert pyinstaller == self.metadata_required() self = FakeGraph("import pkg_resources; pkg_resources.require('pyinstaller')") assert with_dependencies == self.metadata_required()
FakeGraph
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/endpoints/backend/main.py
{ "start": 1368, "end": 4752 }
class ____(remote.Service): @endpoints.method( # This method does not take a request message. message_types.VoidMessage, # This method returns a GreetingCollection message. GreetingCollection, path="greetings", http_method="GET", name="greetings.list", ) def list_greetings(self, unused_request): return STORED_GREETINGS # ResourceContainers are used to encapsuate a request body and url # parameters. This one is used to represent the Greeting ID for the # greeting_get method. GET_RESOURCE = endpoints.ResourceContainer( # The request body should be empty. message_types.VoidMessage, # Accept one url parameter: an integer named 'id' id=messages.IntegerField(1, variant=messages.Variant.INT32), ) @endpoints.method( # Use the ResourceContainer defined above to accept an empty body # but an ID in the query string. GET_RESOURCE, # This method returns a Greeting message. Greeting, # The path defines the source of the URL parameter 'id'. If not # specified here, it would need to be in the query string. path="greetings/{id}", http_method="GET", name="greetings.get", ) def get_greeting(self, request): try: # request.id is used to access the URL parameter. return STORED_GREETINGS.items[request.id] except (IndexError, TypeError): raise endpoints.NotFoundException( "Greeting {} not found".format(request.id) ) # [END endpoints_greeting_api] # [START endpoints_multiply] # This ResourceContainer is similar to the one used for get_greeting, but # this one also contains a request body in the form of a Greeting message. MULTIPLY_RESOURCE = endpoints.ResourceContainer( Greeting, times=messages.IntegerField(2, variant=messages.Variant.INT32, required=True), ) @endpoints.method( # This method accepts a request body containing a Greeting message # and a URL parameter specifying how many times to multiply the # message. MULTIPLY_RESOURCE, # This method returns a Greeting message. Greeting, path="greetings/multiply/{times}", http_method="POST", name="greetings.multiply", ) def multiply_greeting(self, request): return Greeting(message=request.message * request.times) # [END endpoints_multiply] # [START endpoints_auth_config] WEB_CLIENT_ID = "replace this with your web client application ID" ANDROID_CLIENT_ID = "replace this with your Android client ID" IOS_CLIENT_ID = "replace this with your iOS client ID" ANDROID_AUDIENCE = WEB_CLIENT_ID ALLOWED_CLIENT_IDS = [ WEB_CLIENT_ID, ANDROID_CLIENT_ID, IOS_CLIENT_ID, endpoints.API_EXPLORER_CLIENT_ID, ] # [END endpoints_auth_config] # [START endpoints_authed_greeting_api] @endpoints.api( name="authed_greeting", version="v1", # Only allowed configured Client IDs to access this API. allowed_client_ids=ALLOWED_CLIENT_IDS, # Only allow auth tokens with the given audience to access this API. audiences=[ANDROID_AUDIENCE], # Require auth tokens to have the following scopes to access this API. scopes=[endpoints.EMAIL_SCOPE], )
GreetingApi
python
Lightning-AI__lightning
src/lightning/fabric/plugins/io/xla.py
{ "start": 1102, "end": 3004 }
class ____(TorchCheckpointIO): """CheckpointIO that utilizes ``xm.save`` to save checkpoints for TPU training strategies. .. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature. """ def __init__(self, *args: Any, **kwargs: Any) -> None: if not _XLA_AVAILABLE: raise ModuleNotFoundError(str(_XLA_AVAILABLE)) super().__init__(*args, **kwargs) @override def save_checkpoint(self, checkpoint: dict[str, Any], path: _PATH, storage_options: Optional[Any] = None) -> None: """Save model/training states as a checkpoint file through state-dump and file-write. Args: checkpoint: dict containing model and trainer state path: write-target path storage_options: not used in ``XLACheckpointIO.save_checkpoint`` Raises: TypeError: If ``storage_options`` arg is passed in """ if storage_options is not None: raise TypeError( "`Trainer.save_checkpoint(..., storage_options=...)` with `storage_options` arg" f" is not supported for `{self.__class__.__name__}`. Please implement your custom `CheckpointIO`" " to define how you'd like to use `storage_options`." ) fs = get_filesystem(path) fs.makedirs(os.path.dirname(path), exist_ok=True) if RequirementCache("omegaconf"): # workaround for https://github.com/pytorch/xla/issues/2773 from omegaconf import DictConfig, ListConfig, OmegaConf checkpoint = apply_to_collection(checkpoint, (DictConfig, ListConfig), OmegaConf.to_container) import torch_xla.core.xla_model as xm cpu_data = xm._maybe_convert_to_cpu(checkpoint, convert=True) log.debug(f"Saving checkpoint: {path}") torch.save(cpu_data, path)
XLACheckpointIO
python
scipy__scipy
scipy/optimize/tests/test_linprog.py
{ "start": 103558, "end": 103627 }
class ____(AutoscaleTests): method = "simplex"
TestAutoscaleSimplex
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/data_version.py
{ "start": 1147, "end": 1232 }
class ____: pass UNKNOWN_VALUE: Final[UnknownValue] = UnknownValue()
UnknownValue
python
tornadoweb__tornado
tornado/test/auth_test.py
{ "start": 4111, "end": 4249 }
class ____(RequestHandler): def get(self): self.write("oauth_token=uiop&oauth_token_secret=5678")
OAuth1ServerAccessTokenHandler
python
pytorch__pytorch
test/quantization/eager/test_numeric_suite_eager.py
{ "start": 2607, "end": 24511 }
class ____(QuantizationTestCase): @override_qengines def test_compare_weights_conv_static(self): r"""Compare the weights of float and static quantized conv layer""" qengine = torch.backends.quantized.engine def compare_and_validate_results(float_model, q_model): weight_dict = compare_weights( float_model.state_dict(), q_model.state_dict() ) self.assertEqual(len(weight_dict), 1) for v in weight_dict.values(): self.assertTrue(v["float"].shape == v["quantized"].shape) model_list = [AnnotatedConvModel(qengine), AnnotatedConvBnReLUModel(qengine)] for model in model_list: model.eval() if hasattr(model, "fuse_model"): model.fuse_model() q_model = quantize(model, test_only_eval_fn, [self.img_data_2d]) compare_and_validate_results(model, q_model) @override_qengines def test_compare_weights_linear_static(self): r"""Compare the weights of float and static quantized linear layer""" qengine = torch.backends.quantized.engine def compare_and_validate_results(float_model, q_model): weight_dict = compare_weights( float_model.state_dict(), q_model.state_dict() ) self.assertEqual(len(weight_dict), 1) for v in weight_dict.values(): self.assertTrue(v["float"].shape == v["quantized"].shape) model_list = [AnnotatedSingleLayerLinearModel(qengine)] for model in model_list: model.eval() if hasattr(model, "fuse_model"): model.fuse_model() q_model = quantize(model, test_only_eval_fn, [self.calib_data]) compare_and_validate_results(model, q_model) @override_qengines def test_compare_weights_linear_dynamic(self): r"""Compare the weights of float and dynamic quantized linear layer""" qengine = torch.backends.quantized.engine def compare_and_validate_results(float_model, q_model): weight_dict = compare_weights( float_model.state_dict(), q_model.state_dict() ) self.assertEqual(len(weight_dict), 1) for v in weight_dict.values(): self.assertTrue(len(v["float"]) == len(v["quantized"])) for i, val in enumerate(v["quantized"]): self.assertTrue(v["float"][i].shape == val.shape) model_list = [SingleLayerLinearDynamicModel(qengine)] for model in model_list: model.eval() if hasattr(model, "fuse_model"): model.fuse_model() q_model = quantize_dynamic(model) compare_and_validate_results(model, q_model) @override_qengines def test_compare_weights_lstm_dynamic(self): r"""Compare the weights of float and dynamic quantized LSTM layer""" qengine = torch.backends.quantized.engine def compare_and_validate_results(float_model, q_model): weight_dict = compare_weights( float_model.state_dict(), q_model.state_dict() ) self.assertEqual(len(weight_dict), 1) for v in weight_dict.values(): self.assertTrue(len(v["float"]) == len(v["quantized"])) for i, val in enumerate(v["quantized"]): self.assertTrue(v["float"][i].shape == val.shape) model_list = [LSTMwithHiddenDynamicModel(qengine)] for model in model_list: model.eval() if hasattr(model, "fuse_model"): model.fuse_model() q_model = quantize_dynamic(model) compare_and_validate_results(model, q_model) @override_qengines def test_compare_model_stub_conv_static(self): r"""Compare the output of static quantized conv layer and its float shadow module""" qengine = torch.backends.quantized.engine def compare_and_validate_results(float_model, q_model, module_swap_list, data): ob_dict = compare_model_stub(float_model, q_model, module_swap_list, data) self.assertEqual(len(ob_dict), 1) for v in ob_dict.values(): self.assertTrue(len(v["float"]) == len(v["quantized"])) for i, val in enumerate(v["quantized"]): self.assertTrue(v["float"][i].shape == val.shape) model_list = [ AnnotatedConvModel(qengine), AnnotatedConvTransposeModel( "qnnpack" ), # ConvT cannot use per channel weights AnnotatedConvBnReLUModel(qengine), ] module_swap_list = [ nn.Conv2d, nn.intrinsic.modules.fused.ConvReLU2d, nn.ConvTranspose2d, ] for model in model_list: model.eval() if hasattr(model, "fuse_model"): model.fuse_model() q_model = quantize(model, test_only_eval_fn, [self.img_data_2d]) compare_and_validate_results( model, q_model, module_swap_list, self.img_data_2d[0][0] ) @override_qengines def test_compare_model_stub_linear_static(self): r"""Compare the output of static quantized linear layer and its float shadow module""" qengine = torch.backends.quantized.engine def compare_and_validate_results(float_model, q_model, module_swap_list, data): ob_dict = compare_model_stub(float_model, q_model, module_swap_list, data) self.assertEqual(len(ob_dict), 1) for v in ob_dict.values(): self.assertTrue(len(v["float"]) == len(v["quantized"])) for i, val in enumerate(v["quantized"]): self.assertTrue(v["float"][i].shape == val.shape) linear_data = self.calib_data[0][0] module_swap_list = [nn.Linear] model_list = [AnnotatedSingleLayerLinearModel(qengine)] for model in model_list: model.eval() if hasattr(model, "fuse_model"): model.fuse_model() q_model = quantize(model, test_only_eval_fn, [self.calib_data]) compare_and_validate_results(model, q_model, module_swap_list, linear_data) @override_qengines def test_compare_model_stub_partial(self): r"""Compare the output of static quantized linear layer and its float shadow module""" qengine = torch.backends.quantized.engine # TODO: Rebase on top of PR to remove compare and validate results here def compare_and_validate_results(float_model, q_model, module_swap_list, data): ob_dict = compare_model_stub(float_model, q_model, module_swap_list, data) self.assertEqual(len(ob_dict), 1) for v in ob_dict.values(): self.assertTrue(len(v["float"]) == len(v["quantized"])) for i, val in enumerate(v["quantized"]): self.assertTrue(v["float"][i].shape == val.shape) linear_data = self.calib_data[0][0] module_swap_list = [nn.Linear] model_list = [AnnotatedTwoLayerLinearModel()] for model in model_list: model.eval() if hasattr(model, "fuse_model"): model.fuse_model() q_model = quantize(model, test_only_eval_fn, [self.calib_data]) compare_and_validate_results(model, q_model, module_swap_list, linear_data) @override_qengines def test_compare_model_stub_submodule_static(self): r"""Compare the output of static quantized submodule and its float shadow module""" qengine = torch.backends.quantized.engine model = ModelWithSubModules().eval() q_model = quantize(model, test_only_eval_fn, [self.img_data_2d]) module_swap_list = [SubModule, nn.Conv2d] ob_dict = compare_model_stub( model, q_model, module_swap_list, self.img_data_2d[0][0] ) # Since conv is not quantized, we do not insert a shadow module # mod1 contains a linear that is quantized, so we insert a shadow module self.assertTrue(isinstance(q_model.mod1, Shadow)) self.assertFalse(isinstance(q_model.conv, Shadow)) @override_qengines def test_compare_model_stub_functional_static(self): r"""Compare the output of static quantized functional layer and its float shadow module""" qengine = torch.backends.quantized.engine model = ModelWithFunctionals().eval() model.qconfig = torch.ao.quantization.get_default_qconfig("fbgemm") q_model = prepare(model, inplace=False) q_model(self.img_data_2d[0][0]) q_model = convert(q_model) module_swap_list = [nnq.FloatFunctional] ob_dict = compare_model_stub( model, q_model, module_swap_list, self.img_data_2d[0][0] ) self.assertEqual(len(ob_dict), 6) self.assertTrue(isinstance(q_model.mycat, Shadow)) self.assertTrue(isinstance(q_model.myadd, Shadow)) self.assertTrue(isinstance(q_model.mymul, Shadow)) self.assertTrue(isinstance(q_model.myadd_relu, Shadow)) self.assertTrue(isinstance(q_model.my_scalar_add, Shadow)) self.assertTrue(isinstance(q_model.my_scalar_mul, Shadow)) for v in ob_dict.values(): self.assertTrue(len(v["float"]) == len(v["quantized"])) for i, val in enumerate(v["quantized"]): self.assertTrue(v["float"][i].shape == val.shape) @override_qengines def test_compare_model_stub_linear_dynamic(self): r"""Compare the output of dynamic quantized linear layer and its float shadow module""" qengine = torch.backends.quantized.engine def compare_and_validate_results(float_model, q_model, module_swap_list, data): ob_dict = compare_model_stub(float_model, q_model, module_swap_list, data) self.assertEqual(len(ob_dict), 1) for v in ob_dict.values(): self.assertTrue(len(v["float"]) == len(v["quantized"])) for i, val in enumerate(v["quantized"]): self.assertTrue(v["float"][i].shape == val.shape) linear_data = self.calib_data[0][0] model_list = [SingleLayerLinearDynamicModel(qengine)] module_swap_list = [nn.Linear, nn.LSTM] for model in model_list: model.eval() if hasattr(model, "fuse_model"): model.fuse_model() q_model = quantize_dynamic(model) compare_and_validate_results(model, q_model, module_swap_list, linear_data) @override_qengines def test_compare_model_stub_lstm_dynamic(self): r"""Compare the output of dynamic quantized LSTM layer and its float shadow module""" qengine = torch.backends.quantized.engine def compare_and_validate_results( float_model, q_model, module_swap_list, input, hidden ): ob_dict = compare_model_stub( float_model, q_model, module_swap_list, input, hidden ) self.assertEqual(len(ob_dict), 1) for v in ob_dict.values(): self.assertTrue(len(v["float"]) == len(v["quantized"])) for i, val in enumerate(v["quantized"]): self.assertTrue(v["float"][i].shape == val.shape) lstm_input = torch.rand((1, 1, 2)) lstm_hidden = (torch.rand(1, 1, 2), torch.rand(1, 1, 2)) model_list = [LSTMwithHiddenDynamicModel(qengine)] module_swap_list = [nn.Linear, nn.LSTM] for model in model_list: model.eval() if hasattr(model, "fuse_model"): model.fuse_model() q_model = quantize_dynamic(model) compare_and_validate_results( model, q_model, module_swap_list, lstm_input, lstm_hidden ) @override_qengines def test_compare_model_outputs_conv_static(self): r"""Compare the output of conv layer in stataic quantized model and corresponding output of conv layer in float model """ qengine = torch.backends.quantized.engine def compare_and_validate_results(float_model, q_model, data): act_compare_dict = compare_model_outputs(float_model, q_model, data) expected_act_compare_dict_keys = {"conv.stats", "quant.stats"} self.assertTrue(act_compare_dict.keys() == expected_act_compare_dict_keys) for v in act_compare_dict.values(): self.assertTrue(v["float"][0].shape == v["quantized"][0].shape) model_list = [AnnotatedConvModel(qengine), AnnotatedConvBnReLUModel(qengine)] for model in model_list: model.eval() if hasattr(model, "fuse_model"): model.fuse_model() q_model = quantize(model, test_only_eval_fn, [self.img_data_2d]) compare_and_validate_results(model, q_model, self.img_data_2d[0][0]) @override_qengines def test_compare_model_outputs_linear_static(self): r"""Compare the output of linear layer in static quantized model and corresponding output of conv layer in float model """ qengine = torch.backends.quantized.engine def compare_and_validate_results(float_model, q_model, data): act_compare_dict = compare_model_outputs(float_model, q_model, data) expected_act_compare_dict_keys = {"fc1.quant.stats", "fc1.module.stats"} self.assertTrue(act_compare_dict.keys() == expected_act_compare_dict_keys) for v in act_compare_dict.values(): self.assertTrue(len(v["float"]) == len(v["quantized"])) for i, val in enumerate(v["quantized"]): self.assertTrue(v["float"][i].shape == val.shape) linear_data = self.calib_data[0][0] model_list = [AnnotatedSingleLayerLinearModel(qengine)] for model in model_list: model.eval() if hasattr(model, "fuse_model"): model.fuse_model() q_model = quantize(model, test_only_eval_fn, [self.calib_data]) compare_and_validate_results(model, q_model, linear_data) @override_qengines def test_compare_model_outputs_functional_static(self): r"""Compare the output of functional layer in static quantized model and corresponding output of conv layer in float model """ qengine = torch.backends.quantized.engine model = ModelWithFunctionals().eval() model.qconfig = torch.ao.quantization.get_default_qconfig("fbgemm") q_model = prepare(model, inplace=False) q_model(self.img_data_2d[0][0]) q_model = convert(q_model) act_compare_dict = compare_model_outputs(model, q_model, self.img_data_2d[0][0]) self.assertEqual(len(act_compare_dict), 5) expected_act_compare_dict_keys = { "mycat.stats", "myadd.stats", "mymul.stats", "myadd_relu.stats", "quant.stats", } self.assertTrue(act_compare_dict.keys() == expected_act_compare_dict_keys) for v in act_compare_dict.values(): self.assertTrue(len(v["float"]) == len(v["quantized"])) for i, val in enumerate(v["quantized"]): self.assertTrue(v["float"][i].shape == val.shape) @override_qengines def test_compare_model_outputs_linear_dynamic(self): r"""Compare the output of linear layer in dynamic quantized model and corresponding output of conv layer in float model """ qengine = torch.backends.quantized.engine def compare_and_validate_results(float_model, q_model, data): act_compare_dict = compare_model_outputs(float_model, q_model, data) expected_act_compare_dict_keys = {"fc1.stats"} self.assertTrue(act_compare_dict.keys() == expected_act_compare_dict_keys) for v in act_compare_dict.values(): self.assertTrue(len(v["float"]) == len(v["quantized"])) for i, val in enumerate(v["quantized"]): self.assertTrue(v["float"][i].shape == val.shape) linear_data = self.calib_data[0][0] model_list = [SingleLayerLinearDynamicModel(qengine)] for model in model_list: model.eval() if hasattr(model, "fuse_model"): model.fuse_model() q_model = quantize_dynamic(model) compare_and_validate_results(model, q_model, linear_data) @override_qengines def test_compare_model_outputs_lstm_dynamic(self): r"""Compare the output of LSTM layer in dynamic quantized model and corresponding output of conv layer in float model """ qengine = torch.backends.quantized.engine def compare_and_validate_results(float_model, q_model, input, hidden): act_compare_dict = compare_model_outputs( float_model, q_model, input, hidden ) expected_act_compare_dict_keys = {"lstm.stats"} self.assertTrue(act_compare_dict.keys() == expected_act_compare_dict_keys) for v in act_compare_dict.values(): self.assertTrue(len(v["float"]) == len(v["quantized"])) for i, val in enumerate(v["quantized"]): self.assertTrue(len(v["float"][i]) == len(val)) if i == 0: self.assertTrue(v["float"][i][0].shape == val[0].shape) else: self.assertTrue(v["float"][i][0].shape == val[0].shape) self.assertTrue(v["float"][i][1].shape == val[1].shape) lstm_input = torch.rand((1, 1, 2)) lstm_hidden = (torch.rand(1, 1, 2), torch.rand(1, 1, 2)) model_list = [LSTMwithHiddenDynamicModel(qengine)] for model in model_list: model.eval() if hasattr(model, "fuse_model"): model.fuse_model() q_model = quantize_dynamic(model) compare_and_validate_results(model, q_model, lstm_input, lstm_hidden) @override_qengines def test_output_logger(self): r"""Compare output from OutputLogger with the expected results""" x = torch.rand(2, 2) y = torch.rand(2, 1) l = [] l.append(x) l.append(y) logger = OutputLogger() logger.forward(x) logger.forward(y) self.assertEqual(l, logger.stats["tensor_val"]) @override_qengines def test_shadow_logger(self): r"""Compare output from ShawdowLogger with the expected results""" a_float = torch.rand(2, 2) a_quantized = torch.rand(2, 2) b_float = torch.rand(3, 2, 2) b_quantized = torch.rand(3, 2, 2) logger = ShadowLogger() logger.forward(a_float, a_quantized) logger.forward(b_float, b_quantized) self.assertEqual(len(logger.stats["float"]), 2) self.assertEqual(len(logger.stats["quantized"]), 2) @skip_if_no_torchvision def _test_vision_model(self, float_model): float_model.to("cpu") float_model.eval() float_model.fuse_model() float_model.qconfig = torch.ao.quantization.default_qconfig img_data = [ ( torch.rand(2, 3, 224, 224, dtype=torch.float), torch.randint(0, 1, (2,), dtype=torch.long), ) for _ in range(2) ] qmodel = quantize( float_model, torch.ao.quantization.default_eval_fn, [img_data], inplace=False, ) wt_compare_dict = compare_weights(float_model.state_dict(), qmodel.state_dict()) def compute_error(x, y): Ps = torch.norm(x) Pn = torch.norm(x - y) return 20 * torch.log10(Ps / Pn) data = img_data[0][0] # Take in floating point and quantized model as well as input data, and returns a dict, with keys # corresponding to the quantized module names and each entry being a dictionary with two keys 'float' and # 'quantized', containing the activations of floating point and quantized model at matching locations. act_compare_dict = compare_model_outputs(float_model, qmodel, data) for key in act_compare_dict: compute_error( act_compare_dict[key]["float"][0], act_compare_dict[key]["quantized"][0].dequantize(), ) prepare_model_outputs(float_model, qmodel) for data in img_data: float_model(data[0]) qmodel(data[0]) # Find the matching activation between floating point and quantized modules, and return a dict with key # corresponding to quantized module names and each entry being a dictionary with two keys 'float' # and 'quantized', containing the matching floating point and quantized activations logged by the logger act_compare_dict = get_matching_activations(float_model, qmodel) @skip_if_no_torchvision @unittest.skipIf(IS_ARM64, "Not working on arm right now") def test_mobilenet_v2(self): from torchvision.models.quantization import mobilenet_v2 self._test_vision_model(mobilenet_v2(pretrained=True, quantize=False)) @skip_if_no_torchvision @unittest.skipIf(IS_ARM64, "Not working on arm right now") def test_mobilenet_v3(self): from torchvision.models.quantization import mobilenet_v3_large self._test_vision_model(mobilenet_v3_large(pretrained=True, quantize=False)) if __name__ == "__main__": raise_on_run_directly("test/test_quantization.py")
TestNumericSuiteEager
python
apache__airflow
providers/alibaba/tests/unit/alibaba/cloud/operators/test_oss.py
{ "start": 3077, "end": 3764 }
class ____: @mock.patch("airflow.providers.alibaba.cloud.operators.oss.OSSHook") def test_execute(self, mock_hook): operator = OSSDownloadObjectOperator( task_id=MOCK_TASK_ID, region=MOCK_REGION, bucket_name=MOCK_BUCKET, oss_conn_id=MOCK_OSS_CONN_ID, key=MOCK_KEY, file=MOCK_CONTENT, ) operator.execute(None) mock_hook.assert_called_once_with(oss_conn_id=MOCK_OSS_CONN_ID, region=MOCK_REGION) mock_hook.return_value.download_file.assert_called_once_with( bucket_name=MOCK_BUCKET, key=MOCK_KEY, local_file=MOCK_CONTENT )
TestOSSDownloadObjectOperator
python
protocolbuffers__protobuf
python/google/protobuf/internal/proto_builder_test.py
{ "start": 622, "end": 3503 }
class ____(unittest.TestCase): def setUp(self): super().setUp() self.ordered_fields = collections.OrderedDict([ ('foo', descriptor_pb2.FieldDescriptorProto.TYPE_INT64), ('bar', descriptor_pb2.FieldDescriptorProto.TYPE_STRING), ]) self._fields = dict(self.ordered_fields) def testMakeSimpleProtoClass(self): """Test that we can create a proto class.""" proto_cls = proto_builder.MakeSimpleProtoClass( self._fields, full_name='net.proto2.python.public.proto_builder_test.Test') proto = proto_cls() proto.foo = 12345 proto.bar = 'asdf' self.assertMultiLineEqual( 'bar: "asdf"\nfoo: 12345\n', text_format.MessageToString(proto)) def testOrderedFields(self): """Test that the field order is maintained when given an OrderedDict.""" proto_cls = proto_builder.MakeSimpleProtoClass( self.ordered_fields, full_name='net.proto2.python.public.proto_builder_test.OrderedTest') proto = proto_cls() proto.foo = 12345 proto.bar = 'asdf' self.assertMultiLineEqual( 'foo: 12345\nbar: "asdf"\n', text_format.MessageToString(proto)) def testMakeSameProtoClassTwice(self): """Test that the DescriptorPool is used.""" pool = descriptor_pool.DescriptorPool() proto_cls1 = proto_builder.MakeSimpleProtoClass( self._fields, full_name='net.proto2.python.public.proto_builder_test.Test', pool=pool) proto_cls2 = proto_builder.MakeSimpleProtoClass( self._fields, full_name='net.proto2.python.public.proto_builder_test.Test', pool=pool) self.assertIs(proto_cls1.DESCRIPTOR, proto_cls2.DESCRIPTOR) def testMakeLargeProtoClass(self): """Test that large created protos don't use reserved field numbers.""" num_fields = 65000 fields = { 'foo%d' % i: descriptor_pb2.FieldDescriptorProto.TYPE_INT64 for i in range(num_fields) } if api_implementation.Type() == 'upb': with self.assertRaisesRegex( TypeError, "Couldn't build proto file into descriptor pool" ): proto_cls = proto_builder.MakeSimpleProtoClass( fields, full_name=( 'net.proto2.python.public.proto_builder_test.LargeProtoTest' ), ) return proto_cls = proto_builder.MakeSimpleProtoClass( fields, full_name='net.proto2.python.public.proto_builder_test.LargeProtoTest', ) reserved_field_numbers = set( range( descriptor.FieldDescriptor.FIRST_RESERVED_FIELD_NUMBER, descriptor.FieldDescriptor.LAST_RESERVED_FIELD_NUMBER + 1, ) ) proto_field_numbers = set(proto_cls.DESCRIPTOR.fields_by_number) self.assertFalse(reserved_field_numbers.intersection(proto_field_numbers)) if __name__ == '__main__': unittest.main()
ProtoBuilderTest
python
kamyu104__LeetCode-Solutions
Python/time-needed-to-buy-tickets.py
{ "start": 29, "end": 294 }
class ____(object): def timeRequiredToBuy(self, tickets, k): """ :type tickets: List[int] :type k: int :rtype: int """ return sum(min(x, tickets[k] if i <= k else tickets[k]-1) for i, x in enumerate(tickets))
Solution
python
dagster-io__dagster
python_modules/libraries/dagster-pandas/dagster_pandas/constraints.py
{ "start": 10001, "end": 11626 }
class ____(ConstraintWithMetadata): def __init__(self, column_list, enforce_ordering=False, raise_or_typecheck=True, name=None): self.enforce_ordering = check.bool_param(enforce_ordering, "enforce_ordering") self.column_list = check.list_param(column_list, "strict_column_list", of_type=str) def validation_fcn(inframe): if list(inframe.columns) == column_list: return (True, {}) else: if self.enforce_ordering: resdict = {"expectation": self.column_list, "actual": list(inframe.columns)} return (False, resdict) else: if set(inframe.columns) == set(column_list): return (True, {}) else: extra = [x for x in inframe.columns if x not in set(column_list)] missing = [x for x in set(column_list) if x not in inframe.columns] resdict = { "expectation": self.column_list, "actual": {"extra_columns": extra, "missing_columns": missing}, } return (False, resdict) basestr = f"ensuring that the right columns, {self.column_list} were present" if enforce_ordering: basestr += " in the right order" super().__init__( basestr, validation_fcn, DataFrameWithMetadataException, raise_or_typecheck=raise_or_typecheck, name=name, )
StrictColumnsWithMetadata
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/auto-table.py
{ "start": 3078, "end": 3614 }
class ____(Screen): DEFAULT_CSS = """ #main-content { layout: grid; grid-size: 2; grid-columns: 1fr 5fr; grid-rows: 1fr; } #main-content-sidebar { height: 100%; } #main-content-rendering { height: 100%; } """ def compose(self): yield Header() yield Container( Container(Sidebar(), id="main-content-sidebar"), Container(Rendering(), id="main-content-rendering"), id="main-content", )
MyScreen
python
kamyu104__LeetCode-Solutions
Python/number-of-nodes-with-value-one.py
{ "start": 742, "end": 1374 }
class ____(object): def numberOfNodes(self, n, queries): """ :type n: int :type queries: List[int] :rtype: int """ def iter_dfs(): result = 0 stk = [(1, 0)] while stk: u, curr = stk.pop() curr ^= cnt[u]%2 result += curr for v in reversed(xrange(2*u, min(2*u+1, n)+1)): stk.append((v, curr)) return result cnt = collections.Counter(queries) return iter_dfs() # Time: O(q + n) # Space: O(q + logn) import collections # dfs
Solution2
python
facebook__pyre-check
tools/typeshed_patcher/patching.py
{ "start": 3493, "end": 5458 }
class ____: patched_typeshed: typeshed.Typeshed # This is an unexpected hack - Typshed isn't really modeling a typeshed # per-se, just a directory of files. It's convenient to use the same code # for storing and dumping the diffs from patching. patch_diffs: dict[pathlib.Path, str] def patch_typeshed( original_typeshed: typeshed.Typeshed, file_patches: list[patch_specs.FilePatch], ) -> PatchResult: patch_outputs = { file_patch.path: patch_one_file(original_typeshed, file_patch) for file_patch in file_patches } patch_results = { path: patched_code for path, (patched_code, _) in patch_outputs.items() } patch_diffs = { path: patched_code for path, (patched_code, _) in patch_outputs.items() } return PatchResult( patched_typeshed=typeshed.PatchedTypeshed( base=original_typeshed, patch_results=patch_results, ), patch_diffs=patch_diffs, ) def patch_typeshed_directory( source_root: pathlib.Path, patch_specs_toml: pathlib.Path, destination_root: pathlib.Path, diffs_directory: pathlib.Path | None, ) -> None: file_patches = patch_specs.FilePatch.from_toml_path(patch_specs_toml) original_typeshed = typeshed.DirectoryBackedTypeshed(source_root) result = patch_typeshed( original_typeshed=original_typeshed, file_patches=file_patches, ) typeshed.write_to_directory(result.patched_typeshed, destination_root) logger.info(f"Wrote patched typeshed to {destination_root}") buck.write_buck_file_to_directory( buck.generate_buck_file(result.patched_typeshed), destination_root, ) logger.info(f"Wrote Buck file to {destination_root}") if diffs_directory is not None: typeshed.write_content_map_to_directory(result.patch_diffs, diffs_directory) logger.info(f"Wrote diffs of all patched stubs to {diffs_directory}")
PatchResult
python
ray-project__ray
rllib/examples/multi_agent/utils/self_play_callback.py
{ "start": 230, "end": 3722 }
class ____(RLlibCallback): def __init__(self, win_rate_threshold): super().__init__() # 0=RandomPolicy, 1=1st main policy snapshot, # 2=2nd main policy snapshot, etc.. self.current_opponent = 0 self.win_rate_threshold = win_rate_threshold # Report the matchup counters (who played against whom?). self._matching_stats = defaultdict(int) def on_episode_end( self, *, episode, env_runner, metrics_logger, env, env_index, rl_module, **kwargs, ) -> None: # Compute the win rate for this episode and log it with a window of 100. main_agent = 0 if episode.module_for(0) == "main" else 1 rewards = episode.get_rewards() if main_agent in rewards: main_won = rewards[main_agent][-1] == 1.0 metrics_logger.log_value( "win_rate", main_won, reduce="mean", window=100, ) def on_train_result(self, *, algorithm, metrics_logger=None, result, **kwargs): win_rate = result[ENV_RUNNER_RESULTS]["win_rate"] print(f"Iter={algorithm.iteration} win-rate={win_rate} -> ", end="") # If win rate is good -> Snapshot current policy and play against # it next, keeping the snapshot fixed and only improving the "main" # policy. if win_rate > self.win_rate_threshold: self.current_opponent += 1 new_module_id = f"main_v{self.current_opponent}" print(f"adding new opponent to the mix ({new_module_id}).") # Re-define the mapping function, such that "main" is forced # to play against any of the previously played modules # (excluding "random"). def agent_to_module_mapping_fn(agent_id, episode, **kwargs): # agent_id = [0|1] -> policy depends on episode ID # This way, we make sure that both modules sometimes play # (start player) and sometimes agent1 (player to move 2nd). opponent = "main_v{}".format( np.random.choice(list(range(1, self.current_opponent + 1))) ) if hash(episode.id_) % 2 == agent_id: self._matching_stats[("main", opponent)] += 1 return "main" else: return opponent main_module = algorithm.get_module("main") algorithm.add_module( module_id=new_module_id, module_spec=RLModuleSpec.from_module(main_module), new_agent_to_module_mapping_fn=agent_to_module_mapping_fn, ) # TODO (sven): Maybe we should move this convenience step back into # `Algorithm.add_module()`? Would be less explicit, but also easier. algorithm.set_state( { "learner_group": { "learner": { "rl_module": { new_module_id: main_module.get_state(), } } } } ) else: print("not good enough; will keep learning ...") # +2 = main + random result["league_size"] = self.current_opponent + 2 print(f"Matchups:\n{self._matching_stats}")
SelfPlayCallback
python
scipy__scipy
scipy/optimize/_constraints.py
{ "start": 589, "end": 5483 }
class ____: """Nonlinear constraint on the variables. The constraint has the general inequality form:: lb <= fun(x) <= ub Here the vector of independent variables x is passed as ndarray of shape (n,) and ``fun`` returns a vector with m components. It is possible to use equal bounds to represent an equality constraint or infinite bounds to represent a one-sided constraint. Parameters ---------- fun : callable The function defining the constraint. The signature is ``fun(x) -> array_like, shape (m,)``. lb, ub : array_like Lower and upper bounds on the constraint. Each array must have the shape (m,) or be a scalar, in the latter case a bound will be the same for all components of the constraint. Use ``np.inf`` with an appropriate sign to specify a one-sided constraint. Set components of `lb` and `ub` equal to represent an equality constraint. Note that you can mix constraints of different types: interval, one-sided or equality, by setting different components of `lb` and `ub` as necessary. jac : {callable, '2-point', '3-point', 'cs'}, optional Method of computing the Jacobian matrix (an m-by-n matrix, where element (i, j) is the partial derivative of f[i] with respect to x[j]). The keywords {'2-point', '3-point', 'cs'} select a finite difference scheme for the numerical estimation. A callable must have the following signature:: jac(x) -> {ndarray, sparse array}, shape (m, n) Default is '2-point'. hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy, None}, optional Method for computing the Hessian matrix. The keywords {'2-point', '3-point', 'cs'} select a finite difference scheme for numerical estimation. Alternatively, objects implementing `HessianUpdateStrategy` interface can be used to approximate the Hessian. Currently available implementations are: - `BFGS` (default option) - `SR1` A callable must return the Hessian matrix of ``dot(fun, v)`` and must have the following signature: ``hess(x, v) -> {LinearOperator, sparse array, array_like}, shape (n, n)``. Here ``v`` is ndarray with shape (m,) containing Lagrange multipliers. keep_feasible : array_like of bool, optional Whether to keep the constraint components feasible throughout iterations. A single value sets this property for all components. Default is False. Has no effect for equality constraints. finite_diff_rel_step: None or array_like, optional Relative step size for the finite difference approximation. Default is None, which will select a reasonable value automatically depending on a finite difference scheme. finite_diff_jac_sparsity: {None, array_like, sparse array}, optional Defines the sparsity structure of the Jacobian matrix for finite difference estimation, its shape must be (m, n). If the Jacobian has only few non-zero elements in *each* row, providing the sparsity structure will greatly speed up the computations. A zero entry means that a corresponding element in the Jacobian is identically zero. If provided, forces the use of 'lsmr' trust-region solver. If None (default) then dense differencing will be used. Notes ----- Finite difference schemes {'2-point', '3-point', 'cs'} may be used for approximating either the Jacobian or the Hessian. We, however, do not allow its use for approximating both simultaneously. Hence whenever the Jacobian is estimated via finite-differences, we require the Hessian to be estimated using one of the quasi-Newton strategies. The scheme 'cs' is potentially the most accurate, but requires the function to correctly handles complex inputs and be analytically continuable to the complex plane. The scheme '3-point' is more accurate than '2-point' but requires twice as many operations. Examples -------- Constrain ``x[0] < sin(x[1]) + 1.9`` >>> from scipy.optimize import NonlinearConstraint >>> import numpy as np >>> con = lambda x: x[0] - np.sin(x[1]) >>> nlc = NonlinearConstraint(con, -np.inf, 1.9) """ def __init__(self, fun, lb, ub, jac='2-point', hess=None, keep_feasible=False, finite_diff_rel_step=None, finite_diff_jac_sparsity=None): if hess is None: hess = BFGS() self.fun = fun self.lb = lb self.ub = ub self.finite_diff_rel_step = finite_diff_rel_step self.finite_diff_jac_sparsity = finite_diff_jac_sparsity self.jac = jac self.hess = hess self.keep_feasible = keep_feasible
NonlinearConstraint
python
matplotlib__matplotlib
lib/matplotlib/tests/test_mlab.py
{ "start": 36665, "end": 39876 }
class ____: def test_no_data(self): """Pass no data into the GaussianKDE class.""" with pytest.raises(ValueError): mlab.GaussianKDE([]) def test_single_dataset_element(self): """Pass a single dataset element into the GaussianKDE class.""" with pytest.raises(ValueError): mlab.GaussianKDE([42]) def test_silverman_multidim_dataset(self): """Test silverman's for a multi-dimensional array.""" x1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) with pytest.raises(np.linalg.LinAlgError): mlab.GaussianKDE(x1, "silverman") def test_silverman_singledim_dataset(self): """Test silverman's output for a single dimension list.""" x1 = np.array([-7, -5, 1, 4, 5]) mygauss = mlab.GaussianKDE(x1, "silverman") y_expected = 0.76770389927475502 assert_almost_equal(mygauss.covariance_factor(), y_expected, 7) def test_scott_multidim_dataset(self): """Test scott's output for a multi-dimensional array.""" x1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) with pytest.raises(np.linalg.LinAlgError): mlab.GaussianKDE(x1, "scott") def test_scott_singledim_dataset(self): """Test scott's output a single-dimensional array.""" x1 = np.array([-7, -5, 1, 4, 5]) mygauss = mlab.GaussianKDE(x1, "scott") y_expected = 0.72477966367769553 assert_almost_equal(mygauss.covariance_factor(), y_expected, 7) def test_scalar_empty_dataset(self): """Test the scalar's cov factor for an empty array.""" with pytest.raises(ValueError): mlab.GaussianKDE([], bw_method=5) def test_scalar_covariance_dataset(self): """Test a scalar's cov factor.""" np.random.seed(8765678) n_basesample = 50 multidim_data = [np.random.randn(n_basesample) for i in range(5)] kde = mlab.GaussianKDE(multidim_data, bw_method=0.5) assert kde.covariance_factor() == 0.5 def test_callable_covariance_dataset(self): """Test the callable's cov factor for a multi-dimensional array.""" np.random.seed(8765678) n_basesample = 50 multidim_data = [np.random.randn(n_basesample) for i in range(5)] def callable_fun(x): return 0.55 kde = mlab.GaussianKDE(multidim_data, bw_method=callable_fun) assert kde.covariance_factor() == 0.55 def test_callable_singledim_dataset(self): """Test the callable's cov factor for a single-dimensional array.""" np.random.seed(8765678) n_basesample = 50 multidim_data = np.random.randn(n_basesample) kde = mlab.GaussianKDE(multidim_data, bw_method='silverman') y_expected = 0.48438841363348911 assert_almost_equal(kde.covariance_factor(), y_expected, 7) def test_wrong_bw_method(self): """Test the error message that should be called when bw is invalid.""" np.random.seed(8765678) n_basesample = 50 data = np.random.randn(n_basesample) with pytest.raises(ValueError): mlab.GaussianKDE(data, bw_method="invalid")
TestGaussianKDECustom
python
openai__openai-python
src/openai/types/conversations/conversation_deleted_resource.py
{ "start": 204, "end": 326 }
class ____(BaseModel): id: str deleted: bool object: Literal["conversation.deleted"]
ConversationDeletedResource
python
optuna__optuna
tests/storages_tests/rdb_tests/test_models.py
{ "start": 15185, "end": 16452 }
class ____: @staticmethod def _create_model(session: Session) -> TrialModel: direction = StudyDirectionModel(direction=StudyDirection.MINIMIZE, objective=0) study = StudyModel(study_id=1, study_name="test-study", directions=[direction]) trial = TrialModel(trial_id=1, study_id=study.study_id, state=TrialState.COMPLETE) session.add(study) session.add(trial) session.add(TrialHeartbeatModel(trial_id=trial.trial_id)) session.commit() return trial @staticmethod def test_where_trial_id(session: Session) -> None: trial = TestTrialHeartbeatModel._create_model(session) trial_heartbeat = TrialHeartbeatModel.where_trial_id(trial.trial_id, session) assert trial_heartbeat is not None assert isinstance(trial_heartbeat.heartbeat, datetime) @staticmethod def test_cascade_delete_on_trial(session: Session) -> None: trial = TestTrialHeartbeatModel._create_model(session) session.commit() assert TrialHeartbeatModel.where_trial_id(trial.trial_id, session) is not None session.delete(trial) session.commit() assert TrialHeartbeatModel.where_trial_id(trial.trial_id, session) is None
TestTrialHeartbeatModel
python
getsentry__sentry
tests/sentry/api/endpoints/test_organization_auth_tokens.py
{ "start": 467, "end": 4062 }
class ____(APITestCase): endpoint = "sentry-api-0-org-auth-tokens" def test_simple(self) -> None: other_org = self.create_organization() token1 = OrgAuthToken.objects.create( organization_id=self.organization.id, name="token 1", token_hashed="ABCDEF", token_last_characters="xyz1", scope_list=["org:ci"], date_last_used=None, ) token2 = OrgAuthToken.objects.create( organization_id=self.organization.id, name="token 2", token_hashed="ABCDEF2", token_last_characters="xyz2", scope_list=["org:ci"], date_last_used="2023-01-02T00:00:00.000Z", ) token3 = OrgAuthToken.objects.create( organization_id=self.organization.id, name="token 3", token_hashed="ABCDEF3", token_last_characters="xyz3", scope_list=["org:ci"], date_last_used="2023-01-01T00:00:00.000Z", ) # Deleted tokens are not returned OrgAuthToken.objects.create( organization_id=self.organization.id, name="token 4", token_hashed="ABCDEF4", token_last_characters="xyz3", scope_list=["org:ci"], date_deactivated="2023-01-01T00:00:00.000Z", ) # tokens from other org are not returned OrgAuthToken.objects.create( organization_id=other_org.id, name="token 5", token_hashed="ABCDEF5", token_last_characters="xyz3", scope_list=["org:ci"], ) self.login_as(self.user) response = self.get_success_response(self.organization.slug, status_code=status.HTTP_200_OK) assert response.content assert len(response.data) == 3 assert list(map(lambda token: token.get("id"), response.data)) == [ str(token2.id), str(token3.id), str(token1.id), ] assert response.data[0].get("token") is None assert response.data[1].get("token") is None assert response.data[2].get("token") is None def test_never_cache(self) -> None: OrgAuthToken.objects.create( organization_id=self.organization.id, name="token 1", token_hashed="ABCDEF", token_last_characters="xyz1", scope_list=["org:ci"], date_last_used=None, ) OrgAuthToken.objects.create( organization_id=self.organization.id, name="token 2", token_hashed="ABCDEF2", token_last_characters="xyz2", scope_list=["org:ci"], date_last_used="2023-01-02T00:00:00.000Z", ) self.login_as(self.user) response = self.get_success_response(self.organization.slug, status_code=status.HTTP_200_OK) assert response.content assert ( response.get("cache-control") == "max-age=0, no-cache, no-store, must-revalidate, private" ) def test_no_auth(self) -> None: response = self.get_error_response(self.organization.slug) assert response.status_code == status.HTTP_403_FORBIDDEN def test_other_org(self) -> None: other_org = self.create_organization() self.login_as(self.user) response = self.get_error_response(other_org.slug) assert response.status_code == status.HTTP_403_FORBIDDEN @control_silo_test(regions=create_test_regions("us"))
OrganizationAuthTokensListTest
python
joke2k__faker
tests/providers/test_job.py
{ "start": 4555, "end": 4806 }
class ____: """Test sk_SK job provider""" def test_job(self, faker, num_samples): for _ in range(num_samples): job = faker.job() assert isinstance(job, str) assert job in SkSkJobProvider.jobs
TestSkSk
python
mlflow__mlflow
mlflow/tracking/context/registry.py
{ "start": 858, "end": 4081 }
class ____: """Registry for run context provider implementations This class allows the registration of a run context provider which can be used to infer meta information about the context of an MLflow experiment run. Implementations declared though the entrypoints `mlflow.run_context_provider` group can be automatically registered through the `register_entrypoints` method. Registered run context providers can return tags that override those implemented in the core library, however the order in which plugins are resolved is undefined. """ def __init__(self): self._registry = [] def register(self, run_context_provider_cls): self._registry.append(run_context_provider_cls()) def register_entrypoints(self): """Register tracking stores provided by other packages""" for entrypoint in get_entry_points("mlflow.run_context_provider"): try: self.register(entrypoint.load()) except (AttributeError, ImportError) as exc: warnings.warn( 'Failure attempting to register context provider "{}": {}'.format( entrypoint.name, str(exc) ), stacklevel=2, ) def __iter__(self): return iter(self._registry) _run_context_provider_registry = RunContextProviderRegistry() _run_context_provider_registry.register(DefaultRunContext) _run_context_provider_registry.register(GitRunContext) _run_context_provider_registry.register(DatabricksNotebookRunContext) _run_context_provider_registry.register(DatabricksJobRunContext) _run_context_provider_registry.register(DatabricksClusterRunContext) _run_context_provider_registry.register(DatabricksCommandRunContext) _run_context_provider_registry.register(DatabricksRepoRunContext) _run_context_provider_registry.register(SystemEnvironmentContext) _run_context_provider_registry.register_entrypoints() def resolve_tags(tags=None, ignore: list[RunContextProvider] | None = None): """Generate a set of tags for the current run context. Tags are resolved in the order, contexts are registered. Argument tags are applied last. This function iterates through all run context providers in the registry. Additional context providers can be registered as described in :py:class:`mlflow.tracking.context.RunContextProvider`. Args: tags: A dictionary of tags to override. If specified, tags passed in this argument will override those inferred from the context. ignore: A list of RunContextProvider classes to exclude from the resolution. Returns: A dictionary of resolved tags. """ ignore = ignore or [] all_tags = {} for provider in _run_context_provider_registry: if any(isinstance(provider, ig) for ig in ignore): continue try: if provider.in_context(): all_tags.update(provider.tags()) except Exception as e: _logger.warning("Encountered unexpected error during resolving tags: %s", e) if tags is not None: all_tags.update(tags) return all_tags
RunContextProviderRegistry
python
django__django
django/contrib/auth/management/commands/changepassword.py
{ "start": 334, "end": 2686 }
class ____(BaseCommand): help = "Change a user's password for django.contrib.auth." requires_migrations_checks = True requires_system_checks = [] def _get_pass(self, prompt="Password: "): p = getpass.getpass(prompt=prompt) if not p: raise CommandError("aborted") return p def add_arguments(self, parser): parser.add_argument( "username", nargs="?", help=( "Username to change password for; by default, it's the current " "username." ), ) parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, choices=tuple(connections), help='Specifies the database to use. Default is "default".', ) def handle(self, *args, **options): if options["username"]: username = options["username"] else: username = getpass.getuser() try: u = UserModel._default_manager.using(options["database"]).get( **{UserModel.USERNAME_FIELD: username} ) except UserModel.DoesNotExist: raise CommandError("user '%s' does not exist" % username) self.stdout.write("Changing password for user '%s'" % u) MAX_TRIES = 3 count = 0 p1, p2 = 1, 2 # To make them initially mismatch. password_validated = False while (p1 != p2 or not password_validated) and count < MAX_TRIES: p1 = self._get_pass() p2 = self._get_pass("Password (again): ") if p1 != p2: self.stdout.write("Passwords do not match. Please try again.") count += 1 # Don't validate passwords that don't match. continue try: validate_password(p2, u) except ValidationError as err: self.stderr.write("\n".join(err.messages)) count += 1 else: password_validated = True if count == MAX_TRIES: raise CommandError( "Aborting password change for user '%s' after %s attempts" % (u, count) ) u.set_password(p1) u.save() return "Password changed successfully for user '%s'" % u
Command
python
ipython__ipython
tests/test_display.py
{ "start": 6346, "end": 8437 }
class ____(TestCase): @skipif_not_numpy def test_audio_from_numpy_array(self): test_tone = get_test_tone() audio = display.Audio(test_tone, rate=44100) assert len(read_wav(audio.data)) == len(test_tone) @skipif_not_numpy def test_audio_from_list(self): test_tone = get_test_tone() audio = display.Audio(list(test_tone), rate=44100) assert len(read_wav(audio.data)) == len(test_tone) @skipif_not_numpy def test_audio_from_numpy_array_without_rate_raises(self): self.assertRaises(ValueError, display.Audio, get_test_tone()) @skipif_not_numpy def test_audio_data_normalization(self): expected_max_value = numpy.iinfo(numpy.int16).max for scale in [1, 0.5, 2]: audio = display.Audio(get_test_tone(scale), rate=44100) actual_max_value = numpy.max(numpy.abs(read_wav(audio.data))) assert actual_max_value == expected_max_value @skipif_not_numpy def test_audio_data_without_normalization(self): max_int16 = numpy.iinfo(numpy.int16).max for scale in [1, 0.5, 0.2]: test_tone = get_test_tone(scale) test_tone_max_abs = numpy.max(numpy.abs(test_tone)) expected_max_value = int(max_int16 * test_tone_max_abs) audio = display.Audio(test_tone, rate=44100, normalize=False) actual_max_value = numpy.max(numpy.abs(read_wav(audio.data))) assert actual_max_value == expected_max_value def test_audio_data_without_normalization_raises_for_invalid_data(self): self.assertRaises( ValueError, lambda: display.Audio([1.001], rate=44100, normalize=False) ) self.assertRaises( ValueError, lambda: display.Audio([-1.001], rate=44100, normalize=False) ) def simulate_numpy_not_installed(): try: import numpy return mock.patch("numpy.array", mock.MagicMock(side_effect=ImportError)) except ModuleNotFoundError: return lambda x: x @simulate_numpy_not_installed()
TestAudioDataWithNumpy
python
doocs__leetcode
solution/0300-0399/0354.Russian Doll Envelopes/Solution.py
{ "start": 0, "end": 357 }
class ____: def maxEnvelopes(self, envelopes: List[List[int]]) -> int: envelopes.sort(key=lambda x: (x[0], -x[1])) d = [envelopes[0][1]] for _, h in envelopes[1:]: if h > d[-1]: d.append(h) else: idx = bisect_left(d, h) d[idx] = h return len(d)
Solution
python
plotly__plotly.py
plotly/graph_objs/layout/xaxis/_title.py
{ "start": 235, "end": 4975 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout.xaxis" _path_str = "layout.xaxis.title" _valid_props = {"font", "standoff", "text"} @property def font(self): """ Sets this axis' title font. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.layout.xaxis.title.Font` - A dict of string/value properties that will be passed to the Font constructor Returns ------- plotly.graph_objs.layout.xaxis.title.Font """ return self["font"] @font.setter def font(self, val): self["font"] = val @property def standoff(self): """ Sets the standoff distance (in px) between the axis labels and the title text The default value is a function of the axis tick labels, the title `font.size` and the axis `linewidth`. Note that the axis title position is always constrained within the margins, so the actual standoff distance is always less than the set or default value. By setting `standoff` and turning on `automargin`, plotly.js will push the margins to fit the axis title at given standoff distance. The 'standoff' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["standoff"] @standoff.setter def standoff(self, val): self["standoff"] = val @property def text(self): """ Sets the title of this axis. The 'text' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["text"] @text.setter def text(self, val): self["text"] = val @property def _prop_descriptions(self): return """\ font Sets this axis' title font. standoff Sets the standoff distance (in px) between the axis labels and the title text The default value is a function of the axis tick labels, the title `font.size` and the axis `linewidth`. Note that the axis title position is always constrained within the margins, so the actual standoff distance is always less than the set or default value. By setting `standoff` and turning on `automargin`, plotly.js will push the margins to fit the axis title at given standoff distance. text Sets the title of this axis. """ def __init__(self, arg=None, font=None, standoff=None, text=None, **kwargs): """ Construct a new Title object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.layout.xaxis.Title` font Sets this axis' title font. standoff Sets the standoff distance (in px) between the axis labels and the title text The default value is a function of the axis tick labels, the title `font.size` and the axis `linewidth`. Note that the axis title position is always constrained within the margins, so the actual standoff distance is always less than the set or default value. By setting `standoff` and turning on `automargin`, plotly.js will push the margins to fit the axis title at given standoff distance. text Sets the title of this axis. Returns ------- Title """ super().__init__("title") 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.layout.xaxis.Title constructor must be a dict or an instance of :class:`plotly.graph_objs.layout.xaxis.Title`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("font", arg, font) self._set_property("standoff", arg, standoff) self._set_property("text", arg, text) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Title
python
airbytehq__airbyte
airbyte-integrations/connectors/source-shopify/source_shopify/shopify_graphql/bulk/query.py
{ "start": 13462, "end": 14206 }
class ____(Metafield): """ { locations { edges { node { id metafields { edges { node { id namespace value key description createdAt updatedAt type } } } } } } } """ sort_key = None type = MetafieldType.LOCATIONS
MetafieldLocation
python
doocs__leetcode
solution/0800-0899/0868.Binary Gap/Solution.py
{ "start": 0, "end": 265 }
class ____: def binaryGap(self, n: int) -> int: ans = 0 pre, cur = inf, 0 while n: if n & 1: ans = max(ans, cur - pre) pre = cur cur += 1 n >>= 1 return ans
Solution
python
RaRe-Technologies__gensim
gensim/test/test_ldamodel.py
{ "start": 21116, "end": 21720 }
class ____(TestLdaModel): def setUp(self): self.corpus = mmcorpus.MmCorpus(datapath('testcorpus.mm')) self.class_ = ldamulticore.LdaMulticore self.model = self.class_(corpus, id2word=dictionary, num_topics=2, passes=100) # override LdaModel because multicore does not allow alpha=auto def test_alpha_auto(self): self.assertRaises(RuntimeError, self.class_, alpha='auto') # endclass TestLdaMulticore if __name__ == '__main__': logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.DEBUG) unittest.main()
TestLdaMulticore
python
pyodide__pyodide
src/py/webbrowser.py
{ "start": 883, "end": 2105 }
class ____(Exception): pass _browsers: dict[str, list[Any]] = {} def open(url: str, new: int = 0, autoraise: bool = True) -> None: from js import window window.open(url, "_blank") def open_new(url: str) -> None: return open(url, 1) def open_new_tab(url: str) -> None: return open(url, 2) def register( name: str, constructor: Callable[[], BaseBrowser] | None, instance: BaseBrowser | None = None, *, preferred: bool = False, ) -> None: if instance is None: _browsers[name.lower()] = [constructor, None] else: _browsers[name.lower()] = [None, instance] def get(using: str | None = None) -> BaseBrowser: if using is None: return cast(BaseBrowser, _browsers["default"][1]) try: browser = _browsers[using.lower()] except KeyError: raise Error(f"could not locate runnable browser type '{using}'") from None if browser[1] is None: constructor = browser[0] if constructor: browser[1] = constructor() else: raise Error(f"no constructor available for browser type '{using}'") return cast(BaseBrowser, browser[1]) register("default", None, GenericBrowser())
Error
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_multiarray.py
{ "start": 108769, "end": 108956 }
class ____(TestCase): def test_array_contains(self): assert_(4.0 in np.arange(16.0).reshape(4, 4)) assert_(20.0 not in np.arange(16.0).reshape(4, 4))
TestCequenceMethods
python
getsentry__sentry
tests/sentry/services/test_organization_actions.py
{ "start": 1339, "end": 2155 }
class ____(TestCase): def setUp(self) -> None: self.org: Organization = self.create_organization(slug="sluggy", name="barfoo") def test_update_organization_with_outbox_message(self) -> None: with outbox_context(flush=False): update_organization_with_outbox_message( org_id=self.org.id, update_data={"name": "foobar"} ) self.org.refresh_from_db() assert self.org.name == "foobar" assert self.org.slug == "sluggy" assert_outbox_update_message_exists(org=self.org, expected_count=1) def test_update_with_missing_org_id(self) -> None: with pytest.raises(Organization.DoesNotExist): update_organization_with_outbox_message(org_id=1234, update_data={"name": "foobar"})
OrganizationUpdateWithOutboxTest
python
huggingface__transformers
src/transformers/models/lfm2_vl/modeling_lfm2_vl.py
{ "start": 6411, "end": 12988 }
class ____(Lfm2VlPreTrainedModel): _checkpoint_conversion_mapping = {} def __init__(self, config: Lfm2VlConfig): super().__init__(config) self.vision_tower = AutoModel.from_config(config.vision_config) self.multi_modal_projector = Lfm2VlMultiModalProjector(config) self.language_model = AutoModel.from_config(config.text_config) self.post_init() def get_input_embeddings(self): return self.language_model.get_input_embeddings() def set_input_embeddings(self, value): self.language_model.set_input_embeddings(value) def get_image_features( self, pixel_values: torch.FloatTensor, spatial_shapes: torch.Tensor, pixel_attention_mask: torch.Tensor, **kwargs, ) -> list[torch.Tensor]: """ Obtains image last hidden states from the vision tower and apply multimodal projection. Args: pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`): The tensors corresponding to the input images. spatial_shapes (`torch.Tensor` of shape `(batch_size, 2)`): The spatial shapes of the input images. pixel_attention_mask (`torch.Tensor` of shape `(batch_size, height, width)`): The pixel attention mask of the input images. Returns: image_features (`list[torch.Tensor]`): Image feature tensor of shape `(num_images, image_length, embed_dim)`). """ image_outputs = self.vision_tower( pixel_values=pixel_values, spatial_shapes=spatial_shapes, pixel_attention_mask=pixel_attention_mask, ).last_hidden_state img_feature_lengths = pixel_attention_mask.sum(dim=1) image_features = [] for img_idx in range(image_outputs.size(0)): feature = image_outputs[img_idx] # unpad the image representation feature = feature[: img_feature_lengths[img_idx], :].unsqueeze(0) # reshape to original height and width feature_org_h, feature_org_w = spatial_shapes[img_idx] feature = feature.reshape(1, feature_org_h, feature_org_w, -1) # project the image representation img_embedding = self.multi_modal_projector(feature) # flatten here to handle variable length in naflex img_embedding = img_embedding.reshape(-1, img_embedding.size(-1)) image_features.append(img_embedding) return image_features def get_placeholder_mask( self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor ): """ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is equal to the length of multimodal features. If the lengths are different, an error is raised. """ if input_ids is None: special_image_mask = inputs_embeds == self.get_input_embeddings()( torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device) ) special_image_mask = special_image_mask.all(-1) else: special_image_mask = input_ids == self.config.image_token_id n_image_tokens = special_image_mask.sum() special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device) n_image_features = image_features.shape[0] if inputs_embeds[special_image_mask].numel() != image_features.numel(): raise ValueError( f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}" ) return special_image_mask @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, pixel_values: Optional[torch.FloatTensor] = None, spatial_shapes: Optional[torch.Tensor] = None, pixel_attention_mask: Optional[torch.Tensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple, Lfm2VlModelOutputWithPast]: r""" spatial_shapes (`torch.Tensor` of shape `(batch_size, 2)`, *optional*): The spatial shapes of the input images. pixel_attention_mask (`torch.Tensor` of shape `(batch_size, height, width)`, *optional*): The pixel attention mask of the input images. """ if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if inputs_embeds is None: inputs_embeds = self.get_input_embeddings()(input_ids) if pixel_values is not None: image_features = self.get_image_features( pixel_values=pixel_values, spatial_shapes=spatial_shapes, pixel_attention_mask=pixel_attention_mask, ) image_features = torch.cat(image_features, dim=0).to(inputs_embeds.device, inputs_embeds.dtype) special_image_mask = self.get_placeholder_mask( input_ids=input_ids, inputs_embeds=inputs_embeds, image_features=image_features, ) inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features) outputs = self.language_model( attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, cache_position=cache_position, **kwargs, ) return Lfm2VlModelOutputWithPast( last_hidden_state=outputs.last_hidden_state, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, image_hidden_states=image_features if pixel_values is not None else None, ) @auto_docstring( custom_intro=""" The LFM2_VL model which consists of a vision backbone and a language model. """ )
Lfm2VlModel
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP008.py
{ "start": 3860, "end": 4002 }
class ____(ParentD): def f(self): builtins_alias.super(ChildD4, self).f() super # Python injects __class__ into scope
ChildD4
python
huggingface__transformers
tests/models/tvp/test_image_processing_tvp.py
{ "start": 4409, "end": 16794 }
class ____(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = TvpImageProcessor if is_vision_available() else None fast_image_processing_class = ( TvpImageProcessorFast if is_vision_available() and is_torchvision_available() else None ) def setUp(self): super().setUp() self.image_processor_tester = TvpImageProcessingTester(self) @property def image_processor_dict(self): return self.image_processor_tester.prepare_image_processor_dict() def test_image_processor_properties(self): for image_processing_class in self.image_processor_list: image_processing = image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(image_processing, "image_mean")) self.assertTrue(hasattr(image_processing, "image_std")) self.assertTrue(hasattr(image_processing, "do_normalize")) self.assertTrue(hasattr(image_processing, "do_resize")) self.assertTrue(hasattr(image_processing, "do_center_crop")) self.assertTrue(hasattr(image_processing, "size")) self.assertTrue(hasattr(image_processing, "do_rescale")) self.assertTrue(hasattr(image_processing, "do_pad")) self.assertTrue(hasattr(image_processing, "pad_size")) def test_image_processor_from_dict_with_kwargs(self): for image_processing_class in self.image_processor_list: image_processor = image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size, {"longest_edge": 40}) image_processor = image_processing_class.from_dict(self.image_processor_dict, size={"longest_edge": 12}) self.assertEqual(image_processor.size, {"longest_edge": 12}) def test_call_pil(self): for image_processing_class in self.image_processor_list: # Initialize image_processing image_processing = image_processing_class(**self.image_processor_dict) # create random PIL videos video_inputs = self.image_processor_tester.prepare_video_inputs(equal_resolution=False) for video in video_inputs: self.assertIsInstance(video, list) self.assertIsInstance(video[0], Image.Image) # Test not batched input expected_height, expected_width = self.image_processor_tester.get_expected_values(video_inputs) encoded_videos = image_processing(video_inputs[0], return_tensors="pt").pixel_values self.assertEqual( encoded_videos.shape, ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, expected_height, expected_width, ), ) # Test batched expected_height, expected_width = self.image_processor_tester.get_expected_values( video_inputs, batched=True ) encoded_videos = image_processing(video_inputs, return_tensors="pt").pixel_values self.assertEqual( encoded_videos.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, expected_height, expected_width, ), ) def test_call_numpy(self): # Test numpy with both processors for image_processing_class in self.image_processor_list: # Initialize image_processing image_processing = image_processing_class(**self.image_processor_dict) # create random numpy tensors video_inputs = self.image_processor_tester.prepare_video_inputs(equal_resolution=False, numpify=True) for video in video_inputs: self.assertIsInstance(video, list) self.assertIsInstance(video[0], np.ndarray) # For fast processor, convert numpy to tensor if image_processing_class == self.fast_image_processing_class: # Convert numpy arrays to tensors for fast processor tensor_video_inputs = [] for video in video_inputs: tensor_video = [torch.from_numpy(frame) for frame in video] tensor_video_inputs.append(tensor_video) test_inputs = tensor_video_inputs else: test_inputs = video_inputs # Test not batched input expected_height, expected_width = self.image_processor_tester.get_expected_values(video_inputs) encoded_videos = image_processing(test_inputs[0], return_tensors="pt").pixel_values self.assertListEqual( list(encoded_videos.shape), [ 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, expected_height, expected_width, ], ) # Test batched expected_height, expected_width = self.image_processor_tester.get_expected_values( video_inputs, batched=True ) encoded_videos = image_processing(test_inputs, return_tensors="pt").pixel_values self.assertListEqual( list(encoded_videos.shape), [ self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, expected_height, expected_width, ], ) def test_call_numpy_4_channels(self): # Test numpy with both processors for image_processing_class in self.image_processor_list: # Initialize image_processing image_processing = image_processing_class(**self.image_processor_dict) # create random numpy tensors video_inputs = self.image_processor_tester.prepare_video_inputs(equal_resolution=False, numpify=True) for video in video_inputs: self.assertIsInstance(video, list) self.assertIsInstance(video[0], np.ndarray) # For fast processor, convert numpy to tensor if image_processing_class == self.fast_image_processing_class: # Convert numpy arrays to tensors for fast processor tensor_video_inputs = [] for video in video_inputs: tensor_video = [torch.from_numpy(frame) for frame in video] tensor_video_inputs.append(tensor_video) test_inputs = tensor_video_inputs else: test_inputs = video_inputs # Test not batched input expected_height, expected_width = self.image_processor_tester.get_expected_values(video_inputs) encoded_videos = image_processing( test_inputs[0], return_tensors="pt", image_mean=(0.0, 0.0, 0.0), image_std=(1.0, 1.0, 1.0), input_data_format="channels_first", ).pixel_values self.assertListEqual( list(encoded_videos.shape), [ 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, expected_height, expected_width, ], ) # Test batched expected_height, expected_width = self.image_processor_tester.get_expected_values( video_inputs, batched=True ) encoded_videos = image_processing( test_inputs, return_tensors="pt", image_mean=(0.0, 0.0, 0.0), image_std=(1.0, 1.0, 1.0), input_data_format="channels_first", ).pixel_values self.assertListEqual( list(encoded_videos.shape), [ self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, expected_height, expected_width, ], ) self.image_processor_tester.num_channels = 3 def test_call_pytorch(self): # Test PyTorch tensors with both processors for image_processing_class in self.image_processor_list: # Initialize image_processing image_processing = image_processing_class(**self.image_processor_dict) # create random PyTorch tensors video_inputs = self.image_processor_tester.prepare_video_inputs(equal_resolution=False, torchify=True) for video in video_inputs: self.assertIsInstance(video, list) self.assertIsInstance(video[0], torch.Tensor) # Test not batched input expected_height, expected_width = self.image_processor_tester.get_expected_values(video_inputs) encoded_videos = image_processing(video_inputs[0], return_tensors="pt").pixel_values self.assertEqual( encoded_videos.shape, ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, expected_height, expected_width, ), ) # Test batched expected_height, expected_width = self.image_processor_tester.get_expected_values( video_inputs, batched=True ) encoded_videos = image_processing(video_inputs, return_tensors="pt").pixel_values self.assertEqual( encoded_videos.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, expected_height, expected_width, ), ) @require_vision @require_torch @unittest.skip( reason="FIXME: @yoni probably because of an extra 'time' dimension and since image processors don't handle it well?" ) def test_slow_fast_equivalence(self): super().test_slow_fast_equivalence() @require_vision @require_torch @unittest.skip( reason="FIXME: @yoni probably because of an extra 'time' dimension and since image processors don't handle it well?" ) def test_slow_fast_equivalence_batched(self): if not self.test_slow_image_processor or not self.test_fast_image_processor: self.skipTest(reason="Skipping slow/fast equivalence test") if self.image_processing_class is None or self.fast_image_processing_class is None: self.skipTest(reason="Skipping slow/fast equivalence test as one of the image processors is not defined") if hasattr(self.image_processor_tester, "do_center_crop") and self.image_processor_tester.do_center_crop: self.skipTest( reason="Skipping as do_center_crop is True and center_crop functions are not equivalent for fast and slow processors" ) dummy_images = self.image_processor_tester.prepare_video_inputs(equal_resolution=False, torchify=True) image_processor_slow = self.image_processing_class(**self.image_processor_dict) image_processor_fast = self.fast_image_processing_class(**self.image_processor_dict) encoding_slow = image_processor_slow(dummy_images, return_tensors="pt") encoding_fast = image_processor_fast(dummy_images, return_tensors="pt") # Higher max atol for video processing, mean_atol still 5e-3 -> 1e-2 self._assert_slow_fast_tensors_equivalence( encoding_slow.pixel_values, encoding_fast.pixel_values, atol=10.0, mean_atol=1e-2 )
TvpImageProcessingTest
python
pytorch__pytorch
torch/utils/data/datapipes/dataframe/dataframes.py
{ "start": 6523, "end": 7215 }
class ____: def __init__(self, name) -> None: import unittest.mock as mock # TODO(VitalyFedyunin): Do not use private function here, copy own implementation instead. get_target, attribute = mock._get_target(name) # type: ignore[attr-defined] self.get_target = get_target self.attribute = attribute self.name = name def __enter__(self): self.save = getattr(self.get_target(), self.attribute) capt = CaptureA(name=self.name, real_attribute=self.save) setattr(self.get_target(), self.attribute, capt) def __exit__(self, *exc_info): setattr(self.get_target(), self.attribute, self.save)
CaptureLikeMock
python
django__django
tests/model_formsets/models.py
{ "start": 6327, "end": 6481 }
class ____(models.Model): name = models.CharField(max_length=255) parent = models.ForeignKey(UUIDPKParent, models.CASCADE)
AutoPKChildOfUUIDPKParent
python
pytorch__pytorch
torch/_export/db/examples/dynamic_shape_round.py
{ "start": 118, "end": 525 }
class ____(torch.nn.Module): """ Calling round on dynamic shapes is not supported. """ def forward(self, x): return x[: round(x.shape[0] / 2)] x = torch.randn(3, 2) dim0_x = Dim("dim0_x") example_args = (x,) tags = {"torch.dynamic-shape", "python.builtin"} support_level = SupportLevel.NOT_SUPPORTED_YET dynamic_shapes = {"x": {0: dim0_x}} model = DynamicShapeRound()
DynamicShapeRound
python
getsentry__sentry
tests/snuba/api/endpoints/test_organization_events_span_indexed.py
{ "start": 885, "end": 239202 }
class ____(OrganizationEventsEndpointTestBase): def do_request(self, query, features=None, **kwargs): return super().do_request(query, features, **kwargs) def setUp(self) -> None: super().setUp() self.features = { "organizations:starfish-view": True, } @pytest.mark.xfail(reason="spm is not implemented, as spm will be replaced with spm") def test_spm(self) -> None: self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["description", "spm()"], "query": "", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { "description": "foo", "spm()": 1 / (90 * 24 * 60), }, ] assert meta["dataset"] == "spans" def test_id_fields(self) -> None: self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "bar", "sentry_tags": {"status": "invalid_argument"}, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["id", "span_id"], "query": "", "orderby": "id", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 for obj in data: assert obj["id"] == obj["span_id"] assert meta["dataset"] == "spans" def test_sentry_tags_vs_tags(self) -> None: self.store_spans( [ self.create_span( {"sentry_tags": {"transaction.method": "foo"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["transaction.method", "count()"], "query": "", "orderby": "count()", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["transaction.method"] == "foo" assert meta["dataset"] == "spans" def test_sentry_tags_syntax(self) -> None: self.store_spans( [ self.create_span( {"sentry_tags": {"transaction.method": "foo"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["sentry_tags[transaction.method]", "count()"], "query": "", "orderby": "count()", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["sentry_tags[transaction.method]"] == "foo" assert meta["dataset"] == "spans" @pytest.mark.skip(reason="module not migrated over") def test_module_alias(self) -> None: # Delegates `span.module` to `sentry_tags[category]`. Maps `"db.redis"` spans to the `"cache"` module self.store_spans( [ self.create_span( { "op": "db.redis", "description": "EXEC *", "sentry_tags": { "description": "EXEC *", "category": "db", "op": "db.redis", "transaction": "/app/index", }, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["span.module", "span.description"], "query": "span.module:cache", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["span.module"] == "cache" assert data[0]["span.description"] == "EXEC *" assert meta["dataset"] == "spans" def test_device_class_filter(self): self.store_spans( [ self.create_span( {"sentry_tags": {"device.class": "3"}}, start_ts=self.ten_mins_ago ), self.create_span( {"sentry_tags": {"device.class": "2"}}, start_ts=self.ten_mins_ago ), self.create_span( {"sentry_tags": {"device.class": "1"}}, start_ts=self.ten_mins_ago ), self.create_span({"sentry_tags": {"device.class": ""}}, start_ts=self.ten_mins_ago), self.create_span({}, start_ts=self.ten_mins_ago), ], is_eap=True, ) response = self.do_request( { "field": ["device.class", "count()"], "query": 'device.class:"high"', "orderby": "count()", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content meta = response.data["meta"] assert meta["dataset"] == "spans" data = response.data["data"] assert len(data) == 1 assert data[0]["device.class"] == "high" assert data[0]["count()"] == 1 def test_device_class_filter_for_empty(self): self.store_spans( [ self.create_span( {"sentry_tags": {"device.class": "3"}}, start_ts=self.ten_mins_ago ), self.create_span( {"sentry_tags": {"device.class": "2"}}, start_ts=self.ten_mins_ago ), self.create_span( {"sentry_tags": {"device.class": "1"}}, start_ts=self.ten_mins_ago ), self.create_span({"sentry_tags": {"device.class": ""}}, start_ts=self.ten_mins_ago), self.create_span({}, start_ts=self.ten_mins_ago), ], is_eap=True, ) response = self.do_request( { "field": ["device.class", "count()"], "query": 'device.class:""', "orderby": "count()", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content meta = response.data["meta"] assert meta["dataset"] == "spans" data = response.data["data"] assert len(data) == 1 assert data[0]["device.class"] == "Unknown" assert data[0]["count()"] == 2 def test_device_class_filter_for_unknown(self): self.store_spans( [ self.create_span( {"sentry_tags": {"device.class": "3"}}, start_ts=self.ten_mins_ago ), self.create_span( {"sentry_tags": {"device.class": "2"}}, start_ts=self.ten_mins_ago ), self.create_span( {"sentry_tags": {"device.class": "1"}}, start_ts=self.ten_mins_ago ), self.create_span({"sentry_tags": {"device.class": ""}}, start_ts=self.ten_mins_ago), self.create_span({}, start_ts=self.ten_mins_ago), ], is_eap=True, ) response = self.do_request( { "field": ["device.class", "count()"], "query": "device.class:Unknown", "orderby": "count()", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content meta = response.data["meta"] assert meta["dataset"] == "spans" data = response.data["data"] assert len(data) == 1 assert data[0]["device.class"] == "Unknown" assert data[0]["count()"] == 2 def test_device_class_filter_out_unknown(self): self.store_spans( [ self.create_span( {"sentry_tags": {"device.class": "3"}}, start_ts=self.ten_mins_ago ), self.create_span( {"sentry_tags": {"device.class": "2"}}, start_ts=self.ten_mins_ago ), self.create_span( {"sentry_tags": {"device.class": "1"}}, start_ts=self.ten_mins_ago ), self.create_span({"sentry_tags": {"device.class": ""}}, start_ts=self.ten_mins_ago), self.create_span({}, start_ts=self.ten_mins_ago), ], is_eap=True, ) response = self.do_request( { "field": ["device.class", "count()"], "query": "!device.class:Unknown", "orderby": "device.class", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content meta = response.data["meta"] assert meta["dataset"] == "spans" data = response.data["data"] assert len(data) == 3 assert data[0]["device.class"] == "high" assert data[0]["count()"] == 1 assert data[1]["device.class"] == "low" assert data[1]["count()"] == 1 assert data[2]["device.class"] == "medium" assert data[2]["count()"] == 1 @pytest.mark.xfail( reason="wip: depends on rpc having a way to set a different default in virtual contexts" ) def test_span_module(self) -> None: self.store_spans( [ self.create_span( { "sentry_tags": { "op": "http", "category": "http", } }, start_ts=self.ten_mins_ago, ), self.create_span( { "sentry_tags": { "op": "alternative", "category": "other", } }, start_ts=self.ten_mins_ago, ), self.create_span( { "sentry_tags": { "op": "alternative", "category": "other", } }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["span.module", "count()"], "query": "", "orderby": "-count()", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 assert data[0]["span.module"] == "other" assert data[1]["span.module"] == "http" assert meta["dataset"] == "spans" def test_network_span(self) -> None: self.store_spans( [ self.create_span( { "sentry_tags": { "action": "GET", "category": "http", "description": "GET https://*.resource.com", "domain": "*.resource.com", "op": "http.client", "status_code": "200", "transaction": "/api/0/data/", "transaction.method": "GET", "transaction.op": "http.server", } }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["span.op", "span.status_code"], "query": "span.status_code:200", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["span.op"] == "http.client" assert data[0]["span.status_code"] == "200" assert meta["dataset"] == "spans" @pytest.mark.xfail( reason="wip: depends on rpc having a way to set a different default in virtual contexts" ) # https://github.com/getsentry/projects/issues/215?issue=getsentry%7Cprojects%7C488 def test_other_category_span(self) -> None: self.store_spans( [ self.create_span( { "sentry_tags": { "action": "GET", "category": "alternative", "description": "GET https://*.resource.com", "domain": "*.resource.com", "op": "alternative", "status_code": "200", "transaction": "/api/0/data/", "transaction.method": "GET", "transaction.op": "http.server", } }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["span.op", "span.status_code"], "query": "span.module:other span.status_code:200", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["span.op"] == "alternative" assert data[0]["span.status_code"] == "200" assert meta["dataset"] == "spans" def test_inp_span(self) -> None: replay_id = uuid.uuid4().hex self.store_spans( [ self.create_span( { "sentry_tags": { "replay_id": replay_id, "browser.name": "Chrome", "transaction": "/pageloads/", } }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { # Not moving origin.transaction to RPC, its equivalent to transaction and just represents the # transaction that's related to the span "field": ["replay.id", "browser.name", "transaction", "count()"], "query": f"replay.id:{replay_id} AND browser.name:Chrome AND transaction:/pageloads/", "orderby": "count()", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["replay.id"] == replay_id assert data[0]["browser.name"] == "Chrome" assert data[0]["transaction"] == "/pageloads/" assert meta["dataset"] == "spans" @pytest.mark.xfail(reason="event_id isn't being written to the new table") def test_id_filtering(self) -> None: span = self.create_span({"description": "foo"}, start_ts=self.ten_mins_ago) self.store_span(span, is_eap=True) response = self.do_request( { "field": ["description", "count()"], "query": f"id:{span['span_id']}", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["description"] == "foo" assert meta["dataset"] == "spans" response = self.do_request( { "field": ["description", "count()"], "query": f"transaction.id:{span['event_id']}", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["description"] == "foo" assert meta["dataset"] == "spans" @pytest.mark.xfail( reason="wip: not implemented yet, depends on rpc having a way to filter based on casing" ) # https://github.com/getsentry/projects/issues/215?issue=getsentry%7Cprojects%7C489 def test_span_op_casing(self) -> None: self.store_spans( [ self.create_span( { "sentry_tags": { "replay_id": "abc123", "browser.name": "Chrome", "transaction": "/pageloads/", "op": "this is a transaction", } }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["span.op", "count()"], "query": 'span.op:"ThIs Is a TraNSActiON"', "orderby": "count()", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["span.op"] == "this is a transaction" assert meta["dataset"] == "spans" def test_queue_span(self) -> None: self.store_spans( [ self.create_span( { "measurements": { "messaging.message.body.size": { "value": 1024, "unit": "byte", }, "messaging.message.receive.latency": { "value": 1000, "unit": "millisecond", }, "messaging.message.retry.count": { "value": 2, "unit": "none", }, }, "sentry_tags": { "transaction": "queue-processor", "messaging.destination.name": "events", "messaging.message.id": "abc123", "trace.status": "ok", }, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": [ "transaction", "messaging.destination.name", "messaging.message.id", "measurements.messaging.message.receive.latency", "measurements.messaging.message.body.size", "measurements.messaging.message.retry.count", "trace.status", "count()", ], "query": 'messaging.destination.name:"events"', "orderby": "count()", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["transaction"] == "queue-processor" assert data[0]["messaging.destination.name"] == "events" assert data[0]["messaging.message.id"] == "abc123" assert data[0]["trace.status"] == "ok" assert data[0]["measurements.messaging.message.receive.latency"] == 1000 assert data[0]["measurements.messaging.message.body.size"] == 1024 assert data[0]["measurements.messaging.message.retry.count"] == 2 assert meta["dataset"] == "spans" def test_tag_wildcards(self) -> None: self.store_spans( [ self.create_span( {"description": "foo", "tags": {"foo": "bar"}}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "qux", "tags": {"foo": "qux"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) for query in [ "foo:b*", "foo:*r", "foo:*a*", "foo:b*r", ]: response = self.do_request( { "field": ["foo", "count()"], "query": query, "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content assert response.data["data"] == [{"foo": "bar", "count()": 1}] def test_query_for_missing_tag(self) -> None: self.store_spans( [ self.create_span( {"description": "foo"}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "qux", "tags": {"foo": "bar"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["foo", "count()"], "query": "has:foo", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content assert response.data["data"] == [{"foo": "bar", "count()": 1}] def test_count_field_type(self) -> None: response = self.do_request( { "field": ["count()"], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content assert response.data["meta"]["fields"] == {"count()": "integer"} assert response.data["meta"]["units"] == {"count()": None} assert response.data["data"] == [{"count()": 0}] def _test_simple_measurements(self, keys): self.store_spans( [ self.create_span( { "description": "foo", "sentry_tags": {"status": "success"}, "tags": {"bar": "bar2"}, }, measurements={k: {"value": (i + 1) / 10} for i, (k, _, _) in enumerate(keys)}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) for i, (k, type, unit) in enumerate(keys): key = f"measurements.{k}" response = self.do_request( { "field": [key], "query": "description:foo", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content expected = { "bytesScanned": mock.ANY, "dataScanned": "full", "dataset": mock.ANY, "datasetReason": "unchanged", "fields": { key: type, "id": "string", "project.name": "string", }, "isMetricsData": False, "isMetricsExtractedData": False, "tips": {}, "units": { key: unit, "id": None, "project.name": None, }, } if True: expected["accuracy"] = { "confidence": [{}], } assert response.data["meta"] == expected assert response.data["data"] == [ { key: pytest.approx((i + 1) / 10), "id": mock.ANY, "project.name": self.project.slug, } ] def test_simple_measurements(self) -> None: keys = [ ("app_start_cold", "duration", "millisecond"), ("app_start_warm", "duration", "millisecond"), ( "frames_frozen", "number", None, ), # should be integer but keeping it consistent ("frames_frozen_rate", "percentage", None), ( "frames_slow", "number", None, ), # should be integer but keeping it consistent ("frames_slow_rate", "percentage", None), ( "frames_total", "number", None, ), # should be integer but keeping it consistent ("time_to_initial_display", "duration", "millisecond"), ("time_to_full_display", "duration", "millisecond"), ( "stall_count", "number", None, ), # should be integer but keeping it consistent ("stall_percentage", "percentage", None), ("stall_stall_longest_time", "number", None), ("stall_stall_total_time", "number", None), ("cls", "number", None), ("fcp", "duration", "millisecond"), ("fid", "duration", "millisecond"), ("fp", "duration", "millisecond"), ("inp", "duration", "millisecond"), ("lcp", "duration", "millisecond"), ("ttfb", "duration", "millisecond"), ("ttfb.requesttime", "duration", "millisecond"), ("score.cls", "number", None), ("score.fcp", "number", None), ("score.fid", "number", None), ("score.inp", "number", None), ("score.lcp", "number", None), ("score.ttfb", "number", None), ("score.total", "number", None), ("score.weight.cls", "number", None), ("score.weight.fcp", "number", None), ("score.weight.fid", "number", None), ("score.weight.inp", "number", None), ("score.weight.lcp", "number", None), ("score.weight.ttfb", "number", None), ("cache.item_size", "size", "byte"), ("messaging.message.body.size", "size", "byte"), ("messaging.message.receive.latency", "duration", "millisecond"), ("messaging.message.retry.count", "number", None), ] self._test_simple_measurements(keys) def test_environment(self) -> None: self.create_environment(self.project, name="prod") self.create_environment(self.project, name="test") self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"environment": "prod"}}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "foo", "sentry_tags": {"environment": "test"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["environment", "count()"], "project": self.project.id, "environment": "prod", "orderby": "environment", "dataset": "spans", } ) assert response.status_code == 200, response.content assert response.data["data"] == [ {"environment": "prod", "count()": 1}, ] response = self.do_request( { "field": ["environment", "count()"], "project": self.project.id, "environment": ["prod", "test"], "orderby": "environment", "dataset": "spans", } ) assert response.status_code == 200, response.content assert response.data["data"] == [ {"environment": "prod", "count()": 1}, {"environment": "test", "count()": 1}, ] def test_transaction(self) -> None: self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"transaction": "bar"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["description", "count()"], "query": "transaction:bar", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { "description": "foo", "count()": 1, }, ] assert meta["dataset"] == "spans" def test_orderby_alias(self) -> None: self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "bar", "sentry_tags": {"status": "invalid_argument"}, }, duration=2000, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["span.description", "sum(span.self_time)"], "query": "", "orderby": "sum_span_self_time", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 assert data == [ { "span.description": "foo", "sum(span.self_time)": 1000, }, { "span.description": "bar", "sum(span.self_time)": 2000, }, ] assert meta["dataset"] == "spans" @pytest.mark.querybuilder def test_explore_sample_query(self) -> None: spans = [ self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "bar", "sentry_tags": {"status": "invalid_argument"}}, start_ts=self.nine_mins_ago, ), ] self.store_spans( spans, is_eap=True, ) response = self.do_request( { "field": [ "id", "project", "span.op", "span.description", "span.duration", "timestamp", "trace", "transaction.span_id", ], "orderby": "timestamp", "statsPeriod": "1h", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 for source, result in zip(spans, data): assert result["id"] == source["span_id"], "id" assert result["span.duration"] == 1000.0, "duration" # TODO: once the snuba change to return Nones has merged remove the or assert result["span.op"] is None or result["span.op"] == "", "op" assert result["span.description"] == source["description"], "description" ts = datetime.fromisoformat(result["timestamp"]) assert ts.tzinfo == timezone.utc assert ts.timestamp() == pytest.approx( source["end_timestamp_precise"], abs=5 ), "timestamp" assert result["transaction.span_id"] == source["segment_id"], "transaction.span_id" assert result["project"] == result["project.name"] == self.project.slug, "project" assert meta["dataset"] == "spans" def test_span_status(self) -> None: self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"status": "internal_error"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["description", "count()"], "query": "span.status:internal_error", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { "description": "foo", "count()": 1, }, ] assert meta["dataset"] == "spans" def test_handle_nans_from_snuba(self) -> None: self.store_spans( [self.create_span({"description": "foo"}, start_ts=self.ten_mins_ago)], is_eap=True, ) response = self.do_request( { "field": ["description", "count()"], "query": "span.status:internal_error", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content def test_in_filter(self) -> None: self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"transaction": "bar"}}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "foo", "sentry_tags": {"transaction": "baz"}}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "foo", "sentry_tags": {"transaction": "bat"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["transaction", "count()"], "query": "transaction:[bar, baz]", "orderby": "transaction", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 assert data == [ { "transaction": "bar", "count()": 1, }, { "transaction": "baz", "count()": 1, }, ] assert meta["dataset"] == "spans" def _test_aggregate_filter(self, queries): self.store_spans( [ self.create_span( {"sentry_tags": {"transaction": "foo"}}, measurements={ "lcp": {"value": 5000}, "http.response_content_length": {"value": 5000}, }, start_ts=self.ten_mins_ago, ), self.create_span( {"sentry_tags": {"transaction": "foo"}}, measurements={ "lcp": {"value": 5000}, "http.response_content_length": {"value": 5000}, }, start_ts=self.ten_mins_ago, ), self.create_span( {"sentry_tags": {"transaction": "bar"}}, measurements={ "lcp": {"value": 1000}, "http.response_content_length": {"value": 1000}, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) for query in queries: response = self.do_request( { "field": ["transaction", "count()"], "query": query, "orderby": "transaction", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["transaction"] == "foo" assert data[0]["count()"] == 2 assert meta["dataset"] == "spans" def test_pagination_samples(self) -> None: self.store_spans( [ self.create_span( {"description": "a"}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "b"}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["description"], "query": "", "orderby": "description", "project": self.project.id, "dataset": "spans", "per_page": 1, } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": mock.ANY, "project.name": self.project.slug, "description": "a", }, ] links = {} for url, attrs in parse_link_header(response["Link"]).items(): links[attrs["rel"]] = attrs attrs["href"] = url assert links["previous"]["results"] == "false" assert links["next"]["results"] == "true" assert links["next"]["href"] is not None response = self.client.get(links["next"]["href"], format="json") assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": mock.ANY, "project.name": self.project.slug, "description": "b", }, ] links = {} for url, attrs in parse_link_header(response["Link"]).items(): links[attrs["rel"]] = attrs attrs["href"] = url assert links["previous"]["results"] == "true" assert links["next"]["results"] == "false" assert links["previous"]["href"] is not None response = self.client.get(links["previous"]["href"], format="json") assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": mock.ANY, "project.name": self.project.slug, "description": "a", }, ] links = {} for url, attrs in parse_link_header(response["Link"]).items(): links[attrs["rel"]] = attrs attrs["href"] = url assert links["previous"]["results"] == "false" assert links["next"]["results"] == "true" def test_precise_timestamps(self) -> None: self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["precise.start_ts", "precise.finish_ts"], "project": self.project.id, "dataset": "spans", "statsPeriod": "1h", } ) start = self.ten_mins_ago.timestamp() finish = start + 1 assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": mock.ANY, "project.name": self.project.slug, "precise.start_ts": start, "precise.finish_ts": finish, }, ] def test_case_sensitivity_filtering(self): self.store_spans( [ self.create_span( {"description": "FoOoOoO"}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "FooOOoo"}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "foooooo"}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["span.description", "count()"], "query": "span.description:FoOoOoO", "project": self.project.id, "dataset": "spans", "statsPeriod": "1h", } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "span.description": "FoOoOoO", "count()": 1.0, }, ] response = self.do_request( { "field": ["span.description", "count()"], "orderby": ["span.description"], "query": "span.description:FOOOOOO", "project": self.project.id, "dataset": "spans", "statsPeriod": "1h", "caseInsensitive": 1, } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "span.description": "FoOoOoO", "count()": 1.0, }, { "span.description": "FooOOoo", "count()": 1.0, }, { "span.description": "foooooo", "count()": 1.0, }, ] def test_case_sensitivity_filtering_with_list(self): self.store_spans( [ self.create_span( {"description": "FoOoOoO"}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "FooOOoo"}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "foooooo"}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["span.description", "count()"], "orderby": ["span.description"], "query": "span.description:[FoOoOoO, FooOOoo]", "project": self.project.id, "dataset": "spans", "statsPeriod": "1h", } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "span.description": "FoOoOoO", "count()": 1.0, }, { "span.description": "FooOOoo", "count()": 1.0, }, ] response = self.do_request( { "field": ["span.description", "count()"], "orderby": ["span.description"], "query": "span.description:[FOOOOOO]", "project": self.project.id, "dataset": "spans", "statsPeriod": "1h", "caseInsensitive": 1, } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "span.description": "FoOoOoO", "count()": 1.0, }, { "span.description": "FooOOoo", "count()": 1.0, }, { "span.description": "foooooo", "count()": 1.0, }, ] def test_case_sensitivity_with_wildcards(self): self.store_spans( [ self.create_span( {"description": "FoOoOoO"}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "FooOOoo"}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "foooooo"}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "boooooo"}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["span.description", "count()"], "orderby": ["span.description"], "query": "span.description:Foo*", "project": self.project.id, "dataset": "spans", "statsPeriod": "1h", "caseInsensitive": 1, } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "span.description": "FoOoOoO", "count()": 1.0, }, { "span.description": "FooOOoo", "count()": 1.0, }, { "span.description": "foooooo", "count()": 1.0, }, ] response = self.do_request( { "field": ["span.description", "count()"], "orderby": ["span.description"], "query": "!span.description:Foo*", "project": self.project.id, "dataset": "spans", "statsPeriod": "1h", "caseInsensitive": 1, } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "span.description": "boooooo", "count()": 1.0, }, ] @pytest.mark.skip(reason="replay id alias not migrated over") def test_replay_id(self) -> None: self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"replay_id": "123"}}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "foo", "tags": {"replayId": "321"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["replay"], "project": self.project.id, "dataset": "spans", "orderby": "replay", } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": mock.ANY, "project.name": self.project.slug, "replay": "123", }, { "id": mock.ANY, "project.name": self.project.slug, "replay": "321", }, ] @pytest.mark.skip(reason="user display alias not migrated over") def test_user_display(self) -> None: self.store_spans( [ self.create_span( { "description": "foo", "sentry_tags": {"user.email": "test@test.com"}, }, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "foo", "sentry_tags": {"user.username": "test"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["user.display"], "project": self.project.id, "dataset": "spans", "orderby": "user.display", } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": mock.ANY, "project.name": self.project.slug, "user.display": "test", }, { "id": mock.ANY, "project.name": self.project.slug, "user.display": "test@test.com", }, ] def test_query_with_asterisk(self) -> None: self.store_spans( [ self.create_span( {"description": "select * from database"}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["span.description"], "query": 'span.description:"select \\* from database"', "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content assert len(response.data["data"]) == 1 assert response.data["data"][0]["span.description"] == "select * from database" def test_wildcard_queries_with_asterisk_literals(self) -> None: self.store_spans( [ self.create_span( {"description": "select * from database"}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["span.description"], "query": 'span.description:"select \\* * database"', "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content assert len(response.data["data"]) == 1 assert response.data["data"][0]["span.description"] == "select * from database" def test_free_text_wildcard_filter(self) -> None: spans = [ self.create_span( { "description": "barbarbar", "sentry_tags": {"status": "invalid_argument"}, }, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "foofoofoo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), ] self.store_spans(spans, is_eap=True) response = self.do_request( { "field": ["count()", "description"], "query": "oof", "orderby": "-count()", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { "count()": 1, "description": "foofoofoo", }, ] assert meta["dataset"] == "spans" def test_simple(self) -> None: self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "bar", "sentry_tags": {"status": "invalid_argument"}, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["span.status", "description", "count()"], "query": "", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 assert data == [ { "span.status": "invalid_argument", "description": "bar", "count()": 1, }, { "span.status": "success", "description": "foo", "count()": 1, }, ] assert meta["dataset"] == "spans" def test_numeric_attr_without_space(self) -> None: self.store_spans( [ self.create_span( { "description": "foo", "sentry_tags": {"status": "success"}, }, measurements={"foo": {"value": 5}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": [ "description", "tags[foo,number]", ], "query": "", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content assert len(response.data["data"]) == 1 data = response.data["data"] assert data[0]["tags[foo,number]"] == 5 def test_numeric_attr_overlap_string_attr(self) -> None: self.store_spans( [ self.create_span( { "description": "foo", "sentry_tags": {"status": "success"}, }, measurements={"foo": {"value": 5}}, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "bar", "sentry_tags": {"status": "success"}, "tags": {"foo": "five"}, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": [ "description", "tags[foo,number]", "tags[foo,string]", "tags[foo]", ], "query": "", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content assert len(response.data["data"]) == 2 data = response.data["data"] assert data[0]["tags[foo,number]"] is None assert data[0]["tags[foo,string]"] == "five" assert data[0]["tags[foo]"] == "five" assert data[1]["tags[foo,number]"] == 5 assert data[1]["tags[foo,string]"] is None assert data[1]["tags[foo]"] is None def test_numeric_attr_with_spaces(self) -> None: self.store_spans( [ self.create_span( { "description": "zoo", "sentry_tags": {"status": "success"}, }, measurements={"foo": {"value": 5}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": [ "description", "tags[foo, number]", ], "query": "", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content assert len(response.data["data"]) == 1 data = response.data["data"] assert data[0]["tags[foo, number]"] == 5 def test_numeric_attr_filtering(self) -> None: self.store_spans( [ self.create_span( { "description": "foo", "sentry_tags": {"status": "success"}, }, measurements={"foo": {"value": 5}}, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "bar", "sentry_tags": {"status": "success"}, }, measurements={"foo": {"value": 8}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["description", "tags[foo,number]"], "query": "tags[foo,number]:5", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content assert len(response.data["data"]) == 1 data = response.data["data"] assert data[0]["tags[foo,number]"] == 5 assert data[0]["description"] == "foo" def test_long_attr_name(self) -> None: response = self.do_request( { "field": ["description", "z" * 201], "query": "", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 400, response.content assert "Is Too Long" in response.data["detail"].title() def test_numeric_attr_orderby(self) -> None: self.store_spans( [ self.create_span( { "description": "baz", "sentry_tags": {"status": "success"}, "tags": {"foo": "five"}, }, measurements={"foo": {"value": 71}}, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "foo", "sentry_tags": {"status": "success"}, "tags": {"foo": "five"}, }, measurements={"foo": {"value": 5}}, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "bar", "sentry_tags": {"status": "success"}, "tags": {"foo": "five"}, }, measurements={"foo": {"value": 8}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["description", "tags[foo,number]"], "query": "", "orderby": ["tags[foo,number]"], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content assert len(response.data["data"]) == 3 data = response.data["data"] assert data[0]["tags[foo,number]"] == 5 assert data[0]["description"] == "foo" assert data[1]["tags[foo,number]"] == 8 assert data[1]["description"] == "bar" assert data[2]["tags[foo,number]"] == 71 assert data[2]["description"] == "baz" def test_skip_aggregate_conditions_option(self) -> None: span_1 = self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ) span_2 = self.create_span( {"description": "bar", "sentry_tags": {"status": "invalid_argument"}}, start_ts=self.ten_mins_ago, ) self.store_spans( [span_1, span_2], is_eap=True, ) response = self.do_request( { "field": ["description"], "query": "description:foo count():>1", "orderby": "description", "project": self.project.id, "dataset": "spans", "allowAggregateConditions": "0", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { "description": "foo", "project.name": self.project.slug, "id": span_1["span_id"], }, ] assert meta["dataset"] == "spans" def test_span_data_fields_http_resource(self) -> None: self.store_spans( [ self.create_span( { "op": "resource.img", "description": "/image/", "data": { "http.decoded_response_content_length": 1, "http.response_content_length": 2, "http.response_transfer_size": 3, }, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": [ "http.decoded_response_content_length", "http.response_content_length", "http.response_transfer_size", ], "query": "http.decoded_response_content_length:>0 http.response_content_length:>0 http.response_transfer_size:>0", "project": self.project.id, "dataset": "spans", "allowAggregateConditions": "0", } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "http.decoded_response_content_length": 1, "http.response_content_length": 2, "http.response_transfer_size": 3, "project.name": self.project.slug, "id": mock.ANY, }, ] expected = { "bytesScanned": mock.ANY, "dataScanned": "full", "dataset": mock.ANY, "datasetReason": "unchanged", "fields": { "http.decoded_response_content_length": "size", "http.response_content_length": "size", "http.response_transfer_size": "size", "id": "string", "project.name": "string", }, "isMetricsData": False, "isMetricsExtractedData": False, "tips": {}, "units": { "http.decoded_response_content_length": "byte", "http.response_content_length": "byte", "http.response_transfer_size": "byte", "id": None, "project.name": None, }, } if True: expected["accuracy"] = { "confidence": [{}], } assert response.data["meta"] == expected def test_filtering_numeric_attr(self) -> None: span_1 = self.create_span( {"description": "foo"}, measurements={"foo": {"value": 30}}, start_ts=self.ten_mins_ago, ) span_2 = self.create_span( {"description": "foo"}, measurements={"foo": {"value": 10}}, start_ts=self.ten_mins_ago, ) self.store_spans([span_1, span_2], is_eap=True) response = self.do_request( { "field": ["tags[foo,number]"], "query": "span.duration:>=0 tags[foo,number]:>20", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span_1["span_id"], "project.name": self.project.slug, "tags[foo,number]": 30, }, ] def test_aggregate_filter(self) -> None: self._test_aggregate_filter( [ "count():2", "count():>1", "avg(measurements.lcp):>3000", "avg(measurements.lcp):>3s", "count():>1 avg(measurements.lcp):>3000", "count():>1 AND avg(measurements.lcp):>3000", "count():>1 OR avg(measurements.lcp):>3000", "(count():>1 AND avg(http.response_content_length):>3000) OR (count():>1 AND avg(measurements.lcp):>3000)", ] ) @mock.patch( "sentry.utils.snuba_rpc._snuba_pool.urlopen", side_effect=urllib3.exceptions.TimeoutError, ) def test_timeout(self, mock_rpc: mock.MagicMock) -> None: response = self.do_request( { "field": ["span.status", "description", "count()"], "query": "", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 504, response.content assert "Query timeout" in response.data["detail"] def test_extrapolation(self) -> None: """Extrapolation only changes the number when there's a sample rate""" spans = [] spans.append( self.create_span( { "description": "foo", "sentry_tags": {"status": "success"}, "measurements": {"client_sample_rate": {"value": 0.1}}, }, start_ts=self.ten_mins_ago, ) ) spans.append( self.create_span( { "description": "bar", "sentry_tags": {"status": "success"}, }, start_ts=self.ten_mins_ago, ) ) self.store_spans(spans, is_eap=True) response = self.do_request( { "field": ["description", "count()"], "orderby": "-count()", "query": "", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] confidence = meta["accuracy"]["confidence"] assert len(data) == 2 assert len(confidence) == 2 assert data[0]["count()"] == 10 assert confidence[0]["count()"] == "low" assert data[1]["count()"] == 1 assert confidence[1]["count()"] in ("high", "low") @mock.patch( "sentry.utils.snuba_rpc._make_rpc_requests", wraps=_make_rpc_requests, ) def test_extrapolation_mode_server_only(self, mock_rpc_request: mock.MagicMock) -> None: spans = [] spans.append( self.create_span( { "description": "foo", "sentry_tags": {"status": "success"}, "measurements": {"server_sample_rate": {"value": 0.1}}, }, start_ts=self.ten_mins_ago, ) ) spans.append( self.create_span( { "description": "bar", "sentry_tags": {"status": "success"}, }, start_ts=self.ten_mins_ago, ) ) self.store_spans(spans, is_eap=True) response = self.do_request( { "field": ["description", "count()"], "orderby": "-count()", "query": "", "project": self.project.id, "dataset": "spans", "extrapolationMode": "serverOnly", } ) assert response.status_code == 200, response.content assert ( mock_rpc_request.call_args.kwargs["table_requests"][0] .columns[1] .aggregation.extrapolation_mode == ExtrapolationMode.EXTRAPOLATION_MODE_SERVER_ONLY ) # TODO: Ensure server only extrapolation actually gets applied data = response.data["data"] assert len(data) == 2 def test_span_duration(self) -> None: spans = [ self.create_span( {"description": "bar", "sentry_tags": {"status": "invalid_argument"}}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), ] self.store_spans(spans, is_eap=True) response = self.do_request( { "field": ["span.duration", "description"], "query": "", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 assert data == [ { "span.duration": 1000.0, "description": "bar", "project.name": self.project.slug, "id": spans[0]["span_id"], }, { "span.duration": 1000.0, "description": "foo", "project.name": self.project.slug, "id": spans[1]["span_id"], }, ] assert meta["dataset"] == "spans" def test_aggregate_numeric_attr(self) -> None: self.store_spans( [ self.create_span( { "description": "foo", "sentry_tags": {"status": "success"}, "tags": {"bar": "bar1"}, }, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "foo", "sentry_tags": {"status": "success"}, "tags": {"bar": "bar2"}, }, measurements={"foo": {"value": 5}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": [ "description", "count_unique(bar)", "count_unique(tags[bar])", "count_unique(tags[bar,string])", "count_unique(tags[foo,number])", "count()", "count(span.duration)", "count(tags[foo, number])", "sum(tags[foo,number])", "avg(tags[foo,number])", "p50(tags[foo,number])", "p75(tags[foo,number])", "p95(tags[foo,number])", "p99(tags[foo,number])", "p100(tags[foo,number])", "min(tags[foo,number])", "max(tags[foo,number])", ], "query": "", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content assert len(response.data["data"]) == 1 data = response.data["data"] assert data[0] == { "description": "foo", "count_unique(bar)": 2, "count_unique(tags[bar])": 2, "count_unique(tags[bar,string])": 2, "count_unique(tags[foo,number])": 1, "count()": 2, "count(span.duration)": 2, "count(tags[foo, number])": 1, "sum(tags[foo,number])": 5.0, "avg(tags[foo,number])": 5.0, "p50(tags[foo,number])": 5.0, "p75(tags[foo,number])": 5.0, "p95(tags[foo,number])": 5.0, "p99(tags[foo,number])": 5.0, "p100(tags[foo,number])": 5.0, "min(tags[foo,number])": 5.0, "max(tags[foo,number])": 5.0, } def test_epm(self) -> None: self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["description", "epm()"], "query": "", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { "description": "foo", "epm()": 1 / (90 * 24 * 60), }, ] assert meta["dataset"] == "spans" assert meta["units"] == {"description": None, "epm()": "1/minute"} assert meta["fields"] == {"description": "string", "epm()": "rate"} def test_tpm(self) -> None: self.store_spans( [ self.create_span( { "description": "foo", "sentry_tags": {"status": "success"}, "is_segment": True, }, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["description", "tpm()"], "query": "", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) segment_span_count = 1 total_time = 90 * 24 * 60 assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { "description": "foo", "tpm()": segment_span_count / total_time, }, ] assert meta["dataset"] == "spans" assert meta["units"] == {"description": None, "tpm()": "1/minute"} assert meta["fields"] == {"description": "string", "tpm()": "rate"} def test_p75_if(self) -> None: self.store_spans( [ self.create_span( {"is_segment": is_segment}, start_ts=self.ten_mins_ago, duration=duration ) for is_segment, duration in [ *[(True, 1000)] * 2, *[(True, 2000)] * 2, *[(True, 3000)] * 3, (True, 4000), *[(False, 5000)] * 4, ] ], is_eap=True, ) response = self.do_request( { "field": ["p75_if(span.duration, is_transaction, equals, true)"], "query": "", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { "p75_if(span.duration, is_transaction, equals, true)": 3000, }, ] assert meta["dataset"] == "spans" assert meta["units"] == { "p75_if(span.duration, is_transaction, equals, true)": "millisecond" } assert meta["fields"] == {"p75_if(span.duration, is_transaction, equals, true)": "duration"} def test_is_transaction(self) -> None: self.store_spans( [ self.create_span( { "description": "foo", "sentry_tags": {"status": "success"}, "is_segment": True, }, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "bar", "sentry_tags": {"status": "success"}, "is_segment": False, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["span.status", "description", "count()", "is_transaction"], "query": "is_transaction:true", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { "is_transaction": True, "span.status": "success", "description": "foo", "count()": 1, }, ] assert meta["dataset"] == "spans" def test_is_not_transaction(self) -> None: self.store_spans( [ self.create_span( { "description": "foo", "sentry_tags": {"status": "success"}, "is_segment": True, }, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "bar", "sentry_tags": {"status": "success"}, "is_segment": False, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["span.status", "description", "count()", "is_transaction"], "query": "is_transaction:0", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { "is_transaction": False, "span.status": "success", "description": "bar", "count()": 1, }, ] assert meta["dataset"] == "spans" def test_byte_fields(self) -> None: self.store_spans( [ self.create_span( { "description": "foo", "data": { "cache.item_size": 1, "messaging.message.body.size": 2, }, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": [ "cache.item_size", "measurements.cache.item_size", "messaging.message.body.size", "measurements.messaging.message.body.size", ], "project": self.project.id, "dataset": "spans", } ) assert response.data["data"] == [ { "id": mock.ANY, "project.name": self.project.slug, "cache.item_size": 1.0, "measurements.cache.item_size": 1.0, "measurements.messaging.message.body.size": 2.0, "messaging.message.body.size": 2.0, }, ] assert response.data["meta"]["fields"] == { "id": "string", "project.name": "string", "cache.item_size": "size", "measurements.cache.item_size": "size", "measurements.messaging.message.body.size": "size", "messaging.message.body.size": "size", } assert response.data["meta"]["units"] == { "id": None, "project.name": None, "cache.item_size": "byte", "measurements.cache.item_size": "byte", "measurements.messaging.message.body.size": "byte", "messaging.message.body.size": "byte", } def test_query_for_missing_tag_negated(self) -> None: self.store_spans( [ self.create_span( {"description": "foo"}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "qux", "tags": {"foo": "bar"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["foo", "count()"], "query": "!has:foo", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] assert len(data) == 1 assert data[0]["foo"] == "" or data[0]["foo"] is None assert data[0]["count()"] == 1 def test_device_class_column(self) -> None: self.store_spans( [ self.create_span( {"sentry_tags": {"device.class": "1"}}, start_ts=self.ten_mins_ago ), ], is_eap=True, ) response = self.do_request( { "field": ["device.class", "count()"], "query": "device.class:low", "orderby": "count()", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["device.class"] == "low" assert meta["dataset"] == "spans" def test_http_response_count(self) -> None: self.store_spans( [ self.create_span( {"sentry_tags": {"status_code": "500"}}, start_ts=self.ten_mins_ago ), ], is_eap=True, ) self.store_spans( [ self.create_span( {"sentry_tags": {"status_code": "500"}}, start_ts=self.ten_mins_ago ), ], is_eap=True, ) self.store_spans( [ self.create_span( {"sentry_tags": {"status_code": "404"}}, start_ts=self.ten_mins_ago ), ], is_eap=True, ) self.store_spans( [ self.create_span( {"sentry_tags": {"status_code": "200"}}, start_ts=self.ten_mins_ago ), ], is_eap=True, ) response = self.do_request( { "field": [ "http_response_count(5)", "http_response_count(4)", "http_response_count(2)", ], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["http_response_count(5)"] == 2 assert data[0]["http_response_count(4)"] == 1 assert data[0]["http_response_count(2)"] == 1 assert meta["dataset"] == "spans" def test_http_response_rate(self) -> None: self.store_spans( [ self.create_span( {"sentry_tags": {"status_code": "500"}}, start_ts=self.ten_mins_ago ), ], is_eap=True, ) self.store_spans( [ self.create_span( {"sentry_tags": {"status_code": "500"}}, start_ts=self.ten_mins_ago ), ], is_eap=True, ) self.store_spans( [ self.create_span( {"sentry_tags": {"status_code": "404"}}, start_ts=self.ten_mins_ago ), ], is_eap=True, ) self.store_spans( [ self.create_span( {"sentry_tags": {"status_code": "200"}}, start_ts=self.ten_mins_ago ), ], is_eap=True, ) response = self.do_request( { "field": [ "http_response_rate(5)", "http_response_rate(4)", "http_response_rate(2)", ], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["http_response_rate(5)"] == 0.5 assert data[0]["http_response_rate(4)"] == 0.25 assert data[0]["http_response_rate(2)"] == 0.25 assert meta["dataset"] == "spans" assert meta["fields"] == { "http_response_rate(5)": "percentage", "http_response_rate(4)": "percentage", "http_response_rate(2)": "percentage", } assert meta["units"] == { "http_response_rate(5)": None, "http_response_rate(4)": None, "http_response_rate(2)": None, } def test_http_response_rate_missing_status_code(self) -> None: self.store_spans( [ self.create_span({"sentry_tags": {}}, start_ts=self.ten_mins_ago), ], is_eap=True, ) response = self.do_request( { "field": [ "http_response_rate(5)", ], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["http_response_rate(5)"] is None assert meta["dataset"] == "spans" def test_http_response_rate_invalid_param(self) -> None: self.store_spans( [ self.create_span( {"sentry_tags": {"status_code": "500"}}, start_ts=self.ten_mins_ago ), ], is_eap=True, ) response = self.do_request( { "field": [ "http_response_rate(a)", ], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 400, response.content assert ( "Invalid Parameter A. Must Be One Of ['1', '2', '3', '4', '5']" == response.data["detail"].title() ) def test_http_response_rate_group_by(self) -> None: self.store_spans( [ self.create_span( { "description": "description 1", "sentry_tags": {"status_code": "500"}, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) self.store_spans( [ self.create_span( { "description": "description 1", "sentry_tags": {"status_code": "200"}, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) self.store_spans( [ self.create_span( { "description": "description 2", "sentry_tags": {"status_code": "500"}, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) self.store_spans( [ self.create_span( { "description": "description 2", "sentry_tags": {"status_code": "500"}, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["http_response_rate(5)", "description"], "project": self.project.id, "dataset": "spans", "orderby": "description", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 assert data[0]["http_response_rate(5)"] == 0.5 assert data[0]["description"] == "description 1" assert data[1]["http_response_rate(5)"] == 1.0 assert data[1]["description"] == "description 2" assert meta["dataset"] == "spans" def test_cache_miss_rate(self) -> None: self.store_spans( [ self.create_span( { "data": {"cache.hit": False}, }, start_ts=self.ten_mins_ago, ), self.create_span( { "data": {"cache.hit": True}, }, start_ts=self.ten_mins_ago, ), self.create_span( { "data": {"cache.hit": True}, }, start_ts=self.ten_mins_ago, ), self.create_span( { "data": {"cache.hit": True}, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["cache_miss_rate()"], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["cache_miss_rate()"] == 0.25 assert meta["dataset"] == "spans" def test_cache_hit(self) -> None: self.store_spans( [ self.create_span( { "description": "get cache 1", "data": {"cache.hit": False}, }, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "get cache 2", "data": {"cache.hit": True}, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["cache.hit", "description"], "project": self.project.id, "dataset": "spans", "orderby": "description", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 assert data[0]["cache.hit"] is False assert data[1]["cache.hit"] is True assert meta["dataset"] == "spans" def test_searchable_contexts(self) -> None: self.store_spans( [ self.create_span( {"sentry_tags": {"device.model": "Apple"}}, start_ts=self.ten_mins_ago, ), self.create_span( {"sentry_tags": {"request.url": "https://sentry/api/0/foo"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["device.model", "request.url"], "project": self.project.id, "dataset": "spans", "orderby": "device.model", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 assert data[0]["device.model"] == "Apple" assert data[1]["request.url"] == "https://sentry/api/0/foo" assert meta["dataset"] == "spans" def test_trace_status_rate(self) -> None: statuses = ["unknown", "internal_error", "unauthenticated", "ok", "ok"] self.store_spans( [ self.create_span( {"sentry_tags": {"trace.status": status}}, start_ts=self.ten_mins_ago, ) for status in statuses ], is_eap=True, ) response = self.do_request( { "field": [ "trace_status_rate(ok)", "trace_status_rate(unknown)", "trace_status_rate(internal_error)", "trace_status_rate(unauthenticated)", ], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["trace_status_rate(ok)"] == 0.4 assert data[0]["trace_status_rate(unknown)"] == 0.2 assert data[0]["trace_status_rate(internal_error)"] == 0.2 assert data[0]["trace_status_rate(unauthenticated)"] == 0.2 assert meta["dataset"] == "spans" def test_failure_rate(self) -> None: trace_statuses = ["ok", "cancelled", "unknown", "failure"] self.store_spans( [ self.create_span( {"sentry_tags": {"status": status}}, start_ts=self.ten_mins_ago, ) for status in trace_statuses ], is_eap=True, ) response = self.do_request( { "field": ["failure_rate()"], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["failure_rate()"] == 0.25 assert meta["dataset"] == "spans" def test_failure_rate_if(self) -> None: trace_statuses = ["ok", "cancelled", "unknown", "failure"] spans = [ self.create_span( { "sentry_tags": {"status": status}, "is_segment": True, }, start_ts=self.ten_mins_ago, ) for status in trace_statuses ] spans.append( self.create_span( { "sentry_tags": {"status": "ok"}, "is_segment": False, }, start_ts=self.ten_mins_ago, ) ) self.store_spans(spans, is_eap=True) response = self.do_request( { "field": ["failure_rate_if(is_transaction, equals, true)"], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["failure_rate_if(is_transaction, equals, true)"] == 0.25 assert meta["dataset"] == "spans" assert meta["fields"] == { "failure_rate_if(is_transaction, equals, true)": "percentage", } assert meta["units"] == { "failure_rate_if(is_transaction, equals, true)": None, } def test_count_op(self) -> None: self.store_spans( [ self.create_span( {"op": "queue.process", "sentry_tags": {"op": "queue.process"}}, start_ts=self.ten_mins_ago, ), self.create_span( {"op": "queue.process", "sentry_tags": {"op": "queue.process"}}, start_ts=self.ten_mins_ago, ), self.create_span( {"op": "queue.publish", "sentry_tags": {"op": "queue.publish"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": [ "count_op(queue.process)", "count_op(queue.publish)", ], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["count_op(queue.process)"] == 2 assert data[0]["count_op(queue.publish)"] == 1 assert meta["dataset"] == "spans" def test_avg_if(self) -> None: self.store_spans( [ self.create_span( {"op": "queue.process", "sentry_tags": {"op": "queue.process"}}, duration=1000, start_ts=self.ten_mins_ago, ), self.create_span( {"op": "queue.process", "sentry_tags": {"op": "queue.process"}}, duration=2000, start_ts=self.ten_mins_ago, ), self.create_span( {"op": "queue.publish", "sentry_tags": {"op": "queue.publish"}}, duration=3000, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": [ "avg_if(span.duration, span.op, equals, queue.process)", "avg_if(span.duration, span.op, equals, queue.publish)", ], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["avg_if(span.duration, span.op, equals, queue.process)"] == 1500.0 assert data[0]["avg_if(span.duration, span.op, equals, queue.publish)"] == 3000.0 assert meta["dataset"] == "spans" def test_avg_compare(self) -> None: self.store_spans( [ self.create_span( {"sentry_tags": {"release": "foo"}}, duration=100, start_ts=self.ten_mins_ago, ), self.create_span( {"sentry_tags": {"release": "bar"}}, duration=10, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["avg_compare(span.self_time, release, foo, bar)"], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["avg_compare(span.self_time, release, foo, bar)"] == -0.9 assert meta["dataset"] == "spans" assert meta["fields"] == { "avg_compare(span.self_time, release, foo, bar)": "percentage", } assert meta["units"] == { "avg_compare(span.self_time, release, foo, bar)": None, } def test_avg_if_invalid_param(self) -> None: self.store_spans( [ self.create_span( {"op": "queue.process", "sentry_tags": {"op": "queue.process"}}, duration=1000, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": [ "avg_if(span.duration, span.duration, equals, queue.process)", ], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 400, response.content assert ( "Span.Duration Is Invalid For Parameter 2 In Avg_If. Its A Millisecond Type Field, But It Must Be One Of These Types: {'String'}" == response.data["detail"].title() ) def test_count_if_invalid_param(self) -> None: response = self.do_request( { "field": [ "count_if(span.description, snequals, queue.process)", ], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 400, response.content assert "Invalid parameter snequals" in response.data["detail"] def test_ttif_ttfd_contribution_rate(self) -> None: spans = [] for _ in range(8): spans.append( self.create_span( {"sentry_tags": {"ttid": "ttid", "ttfd": "ttfd"}}, start_ts=self.ten_mins_ago, ), ) spans.extend( [ self.create_span( {"sentry_tags": {"ttfd": "ttfd", "ttid": ""}}, start_ts=self.ten_mins_ago, ), self.create_span( {"sentry_tags": {"ttfd": "", "ttid": ""}}, start_ts=self.ten_mins_ago, ), ] ) self.store_spans(spans, is_eap=True) response = self.do_request( { "field": [ "ttid_contribution_rate()", "ttfd_contribution_rate()", ], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["ttid_contribution_rate()"] == 0.8 assert data[0]["ttfd_contribution_rate()"] == 0.9 assert meta["dataset"] == "spans" def test_count_scores(self) -> None: self.store_spans( [ self.create_span( { "measurements": { "score.ratio.lcp": {"value": 0.03}, "score.total": {"value": 0.43}, } }, start_ts=self.ten_mins_ago, ), self.create_span( { "measurements": { "score.total": {"value": 1.0}, } }, start_ts=self.ten_mins_ago, ), self.create_span( { "measurements": { "score.total": {"value": 0.0}, } }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": [ "count_scores(measurements.score.lcp)", "count_scores(measurements.score.total)", ], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["count_scores(measurements.score.lcp)"] == 1 assert data[0]["count_scores(measurements.score.total)"] == 3 assert meta["dataset"] == "spans" def test_count_scores_filter(self) -> None: self.store_spans( [ self.create_span( { "measurements": { "score.ratio.lcp": {"value": 0.03}, "score.total": {"value": 0.43}, }, "sentry_tags": {"transaction": "foo_transaction"}, }, start_ts=self.ten_mins_ago, ), self.create_span( { "measurements": { "score.total": {"value": 1.0}, "score.ratio.lcp": {"value": 0.03}, }, "sentry_tags": {"transaction": "foo_transaction"}, }, start_ts=self.ten_mins_ago, ), self.create_span( { "measurements": { "score.total": {"value": 0.0}, "score.ratio.lcp": {"value": 0.03}, }, "sentry_tags": {"transaction": "bar_transaction"}, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["count_scores(measurements.score.lcp)", "transaction"], "query": "count_scores(measurements.score.lcp):>1", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["count_scores(measurements.score.lcp)"] == 2 assert data[0]["transaction"] == "foo_transaction" assert meta["dataset"] == "spans" def test_time_spent_percentage(self) -> None: spans = [] for _ in range(4): spans.append( self.create_span({"sentry_tags": {"transaction": "foo_transaction"}}, duration=1), ) spans.append( self.create_span({"sentry_tags": {"transaction": "bar_transaction"}}, duration=1) ) self.store_spans(spans, is_eap=True) response = self.do_request( { "field": ["transaction", "time_spent_percentage()"], "query": "", "orderby": ["-time_spent_percentage()"], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 assert data[0]["time_spent_percentage()"] == 0.8 assert data[0]["transaction"] == "foo_transaction" assert data[1]["time_spent_percentage()"] == 0.2 assert data[1]["transaction"] == "bar_transaction" assert meta["dataset"] == "spans" def test_performance_score(self) -> None: self.store_spans( [ self.create_span( { "measurements": { "score.ratio.lcp": {"value": 0.02}, } }, start_ts=self.ten_mins_ago, ), self.create_span( { "measurements": { "score.ratio.lcp": {"value": 0.08}, } }, start_ts=self.ten_mins_ago, ), self.create_span( { "measurements": { "score.ratio.lcp": {"value": 0.08}, } }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": [ "performance_score(measurements.score.lcp)", ], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["performance_score(measurements.score.lcp)"] == 0.06 assert meta["dataset"] == "spans" def test_performance_score_zero(self) -> None: response = self.do_request( { "field": [ "performance_score(measurements.score.lcp)", ], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["performance_score(measurements.score.lcp)"] is None assert meta["dataset"] == "spans" def test_division_if(self) -> None: self.store_spans( [ self.create_span( { "measurements": { "frames.total": {"value": 100}, "frames.slow": {"value": 10}, "frames.frozen": {"value": 20}, }, "sentry_tags": {"browser.name": "Chrome"}, } ), self.create_span( { "measurements": { "frames.total": {"value": 100}, "frames.slow": {"value": 50}, "frames.frozen": {"value": 60}, }, "sentry_tags": {"browser.name": "Firefox"}, } ), ], is_eap=True, ) response = self.do_request( { "field": [ "division_if(mobile.slow_frames,mobile.total_frames,browser.name,equals,Chrome)", "division_if(mobile.slow_frames,mobile.total_frames,browser.name,equals,Firefox)", ], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert ( data[0][ "division_if(mobile.slow_frames,mobile.total_frames,browser.name,equals,Chrome)" ] == 10 / 100 ) assert ( data[0][ "division_if(mobile.slow_frames,mobile.total_frames,browser.name,equals,Firefox)" ] == 50 / 100 ) assert meta["dataset"] == "spans" assert meta["fields"] == { "division_if(mobile.slow_frames,mobile.total_frames,browser.name,equals,Chrome)": "percentage", "division_if(mobile.slow_frames,mobile.total_frames,browser.name,equals,Firefox)": "percentage", } def test_total_performance_score(self) -> None: self.store_spans( [ self.create_span( { "measurements": { "score.ratio.lcp": {"value": 0.0}, } }, start_ts=self.ten_mins_ago, ), self.create_span( { "measurements": { "score.ratio.lcp": {"value": 0.02}, } }, start_ts=self.ten_mins_ago, ), self.create_span( { "measurements": { "score.ratio.lcp": {"value": 0.04}, } }, start_ts=self.ten_mins_ago, ), self.create_span( { "measurements": { "score.ratio.cls": {"value": 0.08}, } }, start_ts=self.ten_mins_ago, ), self.create_span( { "measurements": { "score.ratio.inp": {"value": 0.5}, } }, start_ts=self.ten_mins_ago, ), self.create_span( { "measurements": { "score.ratio.fcp": {"value": 0.08}, } }, start_ts=self.ten_mins_ago, ), self.create_span( { "measurements": { "score.ratio.ttfb": {"value": 0.5}, } }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": [ "performance_score(measurements.score.lcp)", "performance_score(measurements.score.cls)", "performance_score(measurements.score.ttfb)", "performance_score(measurements.score.fcp)", "performance_score(measurements.score.inp)", "performance_score(measurements.score.total)", ], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["performance_score(measurements.score.lcp)"] == 0.02 assert data[0]["performance_score(measurements.score.cls)"] == 0.08 assert data[0]["performance_score(measurements.score.ttfb)"] == 0.5 assert data[0]["performance_score(measurements.score.fcp)"] == 0.08 assert data[0]["performance_score(measurements.score.inp)"] == 0.5 self.assertAlmostEqual(data[0]["performance_score(measurements.score.total)"], 0.23) assert meta["dataset"] == "spans" def test_total_performance_score_missing_vital(self) -> None: self.store_spans( [ self.create_span( { "measurements": { "score.ratio.lcp": {"value": 0.0}, } }, start_ts=self.ten_mins_ago, ), self.create_span( { "measurements": { "score.ratio.lcp": {"value": 0.02}, } }, start_ts=self.ten_mins_ago, ), self.create_span( { "measurements": { "score.ratio.lcp": {"value": 0.04}, } }, start_ts=self.ten_mins_ago, ), self.create_span( { "measurements": { "score.ratio.cls": {"value": 0.08}, } }, start_ts=self.ten_mins_ago, ), self.create_span( { "measurements": { "score.ratio.inp": {"value": 0.5}, } }, start_ts=self.ten_mins_ago, ), self.create_span( { "measurements": { "score.ratio.fcp": {"value": 0.08}, } }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": [ "performance_score(measurements.score.lcp)", "performance_score(measurements.score.cls)", "performance_score(measurements.score.ttfb)", "performance_score(measurements.score.fcp)", "performance_score(measurements.score.inp)", "performance_score(measurements.score.total)", ], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["performance_score(measurements.score.lcp)"] == 0.02 assert data[0]["performance_score(measurements.score.cls)"] == 0.08 assert data[0]["performance_score(measurements.score.ttfb)"] is None assert data[0]["performance_score(measurements.score.fcp)"] == 0.08 assert data[0]["performance_score(measurements.score.inp)"] == 0.5 self.assertAlmostEqual(data[0]["performance_score(measurements.score.total)"], 0.20) assert meta["dataset"] == "spans" def test_total_performance_score_multiple_transactions(self) -> None: self.store_spans( [ self.create_span( { "measurements": { "score.ratio.lcp": {"value": 0.8}, }, "sentry_tags": {"transaction": "foo_transaction"}, }, start_ts=self.ten_mins_ago, ), self.create_span( { "measurements": { "score.ratio.cls": {"value": 0.7}, }, "sentry_tags": {"transaction": "bar_transaction"}, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": [ "transaction", "performance_score(measurements.score.total)", "performance_score(measurements.score.lcp)", "performance_score(measurements.score.cls)", "performance_score(measurements.score.fcp)", "opportunity_score(measurements.score.total)", "opportunity_score(measurements.score.lcp)", "opportunity_score(measurements.score.cls)", "opportunity_score(measurements.score.fcp)", ], "project": self.project.id, "dataset": "spans", "orderby": "-transaction", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 assert data[0]["transaction"] == "foo_transaction" self.assertAlmostEqual(data[0]["performance_score(measurements.score.total)"], 0.8) assert data[0]["performance_score(measurements.score.lcp)"] == 0.8 assert data[0]["performance_score(measurements.score.cls)"] is None assert data[0]["performance_score(measurements.score.fcp)"] is None self.assertAlmostEqual( data[0]["opportunity_score(measurements.score.total)"], 0.13333333333333333 ) self.assertAlmostEqual(data[0]["opportunity_score(measurements.score.lcp)"], 0.2) assert data[0]["opportunity_score(measurements.score.cls)"] == 0.0 assert data[0]["opportunity_score(measurements.score.fcp)"] == 0.0 assert data[1]["transaction"] == "bar_transaction" self.assertAlmostEqual(data[1]["performance_score(measurements.score.total)"], 0.7) assert data[1]["performance_score(measurements.score.lcp)"] is None assert data[1]["performance_score(measurements.score.cls)"] == 0.7 assert data[1]["performance_score(measurements.score.fcp)"] is None self.assertAlmostEqual(data[1]["opportunity_score(measurements.score.total)"], 0.1) assert data[1]["opportunity_score(measurements.score.lcp)"] == 0.0 self.assertAlmostEqual(data[1]["opportunity_score(measurements.score.cls)"], 0.3) assert data[1]["opportunity_score(measurements.score.fcp)"] == 0.0 assert meta["dataset"] == "spans" def test_division(self) -> None: self.store_spans( [ self.create_span( { "measurements": { "frames.total": {"value": 100}, "frames.slow": {"value": 10}, "frames.frozen": {"value": 20}, } } ), ], is_eap=True, ) response = self.do_request( { "field": [ "division(mobile.slow_frames,mobile.total_frames)", "division(mobile.frozen_frames,mobile.total_frames)", ], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["division(mobile.slow_frames,mobile.total_frames)"] == 10 / 100 assert data[0]["division(mobile.frozen_frames,mobile.total_frames)"] == 20 / 100 assert meta["dataset"] == "spans" assert meta["fields"] == { "division(mobile.slow_frames,mobile.total_frames)": "percentage", "division(mobile.frozen_frames,mobile.total_frames)": "percentage", } def test_division_with_groupby(self) -> None: self.store_spans( [ self.create_span( { "measurements": { "frames.total": {"value": 100}, "frames.slow": {"value": 10}, "frames.frozen": {"value": 20}, }, "sentry_tags": {"transaction": "foo_transaction"}, } ), ], is_eap=True, ) response = self.do_request( { "field": [ "transaction", "division(mobile.slow_frames,mobile.total_frames)", "division(mobile.frozen_frames,mobile.total_frames)", ], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["division(mobile.slow_frames,mobile.total_frames)"] == 10 / 100 assert data[0]["division(mobile.frozen_frames,mobile.total_frames)"] == 20 / 100 assert data[0]["transaction"] == "foo_transaction" assert meta["dataset"] == "spans" def test_opportunity_score_zero_scores(self) -> None: self.store_spans( [ self.create_span( { "measurements": { "score.ratio.fcp": {"value": 0.0}, "score.ratio.cls": {"value": 0.0}, "score.ratio.ttfb": {"value": 0.0}, "score.ratio.lcp": {"value": 0.0}, "score.ratio.inp": {"value": 0.0}, }, "sentry_tags": {"transaction": "foo_transaction"}, } ), self.create_span( { "measurements": { "score.ratio.fcp": {"value": 0.0}, "score.ratio.cls": {"value": 0.0}, "score.ratio.ttfb": {"value": 0.0}, "score.ratio.lcp": {"value": 0.0}, "score.ratio.inp": {"value": 0.0}, }, "sentry_tags": {"transaction": "bar_transaction"}, } ), ], is_eap=True, ) response = self.do_request( { "field": [ "transaction", "opportunity_score(measurements.score.total)", "opportunity_score(measurements.score.lcp)", "opportunity_score(measurements.score.inp)", "opportunity_score(measurements.score.cls)", "opportunity_score(measurements.score.ttfb)", "opportunity_score(measurements.score.fcp)", ], "orderby": "transaction", "dataset": "spans", "project": self.project.id, } ) assert response.status_code == 200, response.content data = response.data["data"] assert len(data) == 2 assert data[0]["opportunity_score(measurements.score.lcp)"] == 0.5 assert data[0]["opportunity_score(measurements.score.inp)"] == 0.5 assert data[0]["opportunity_score(measurements.score.cls)"] == 0.5 assert data[0]["opportunity_score(measurements.score.ttfb)"] == 0.5 assert data[0]["opportunity_score(measurements.score.fcp)"] == 0.5 assert data[0]["opportunity_score(measurements.score.total)"] == 0.5 assert data[1]["opportunity_score(measurements.score.lcp)"] == 0.5 assert data[1]["opportunity_score(measurements.score.inp)"] == 0.5 assert data[1]["opportunity_score(measurements.score.cls)"] == 0.5 assert data[1]["opportunity_score(measurements.score.ttfb)"] == 0.5 assert data[1]["opportunity_score(measurements.score.fcp)"] == 0.5 assert data[1]["opportunity_score(measurements.score.total)"] == 0.5 def test_opportunity_score_simple(self) -> None: self.store_spans( [ self.create_span( { "measurements": { "score.ratio.fcp": {"value": 0.0}, "score.ratio.cls": {"value": 0.0}, "score.ratio.ttfb": {"value": 0.0}, "score.ratio.lcp": {"value": 1.0}, "score.ratio.inp": {"value": 0.0}, }, } ), self.create_span( { "measurements": { "score.ratio.fcp": {"value": 0.0}, "score.ratio.cls": {"value": 0.0}, "score.ratio.ttfb": {"value": 0.0}, "score.ratio.lcp": {"value": 0.0}, "score.ratio.inp": {"value": 0.0}, }, } ), ], is_eap=True, ) response = self.do_request( { "field": [ "transaction", "opportunity_score(measurements.score.lcp)", "opportunity_score(measurements.score.inp)", "opportunity_score(measurements.score.cls)", "opportunity_score(measurements.score.ttfb)", "opportunity_score(measurements.score.fcp)", "opportunity_score(measurements.score.total)", ], "orderby": "transaction", "dataset": "spans", "project": self.project.id, } ) assert response.status_code == 200, response.content data = response.data["data"] assert len(data) == 1 assert data[0]["opportunity_score(measurements.score.lcp)"] == 0.5 assert data[0]["opportunity_score(measurements.score.inp)"] == 1.0 assert data[0]["opportunity_score(measurements.score.cls)"] == 1.0 assert data[0]["opportunity_score(measurements.score.ttfb)"] == 1.0 assert data[0]["opportunity_score(measurements.score.fcp)"] == 1.0 self.assertAlmostEqual(data[0]["opportunity_score(measurements.score.total)"], 0.85) def test_opportunity_score_with_transaction(self) -> None: self.store_spans( [ self.create_span( { "measurements": { "score.ratio.fcp": {"value": 0.0}, "score.ratio.cls": {"value": 0.0}, "score.ratio.ttfb": {"value": 0.0}, "score.ratio.lcp": {"value": 1.0}, "score.ratio.inp": {"value": 0.0}, }, "sentry_tags": {"transaction": "foo_transaction"}, } ), self.create_span( { "measurements": { "score.ratio.fcp": {"value": 0.0}, "score.ratio.cls": {"value": 0.0}, "score.ratio.ttfb": {"value": 0.0}, "score.ratio.lcp": {"value": 0.0}, "score.ratio.inp": {"value": 0.0}, }, "sentry_tags": {"transaction": "bar_transaction"}, } ), ], is_eap=True, ) response = self.do_request( { "field": [ "transaction", "opportunity_score(measurements.score.lcp)", "opportunity_score(measurements.score.inp)", "opportunity_score(measurements.score.cls)", "opportunity_score(measurements.score.ttfb)", "opportunity_score(measurements.score.fcp)", "opportunity_score(measurements.score.total)", ], "orderby": "transaction", "dataset": "spans", "project": self.project.id, } ) assert response.status_code == 200, response.content data = response.data["data"] assert len(data) == 2 assert data[0]["opportunity_score(measurements.score.lcp)"] == 0.5 assert data[0]["opportunity_score(measurements.score.inp)"] == 0.5 assert data[0]["opportunity_score(measurements.score.cls)"] == 0.5 assert data[0]["opportunity_score(measurements.score.ttfb)"] == 0.5 assert data[0]["opportunity_score(measurements.score.fcp)"] == 0.5 assert data[0]["opportunity_score(measurements.score.total)"] == 0.5 assert data[1]["opportunity_score(measurements.score.lcp)"] == 0 assert data[1]["opportunity_score(measurements.score.inp)"] == 0.5 assert data[1]["opportunity_score(measurements.score.cls)"] == 0.5 assert data[1]["opportunity_score(measurements.score.ttfb)"] == 0.5 assert data[1]["opportunity_score(measurements.score.fcp)"] == 0.5 self.assertAlmostEqual(data[1]["opportunity_score(measurements.score.total)"], 0.35) def test_opportunity_score_with_filter(self) -> None: self.store_spans( [ self.create_span( { "measurements": { "score.ratio.fcp": {"value": 0.0}, "score.ratio.cls": {"value": 0.0}, "score.ratio.ttfb": {"value": 0.0}, "score.ratio.lcp": {"value": 1.0}, "score.ratio.inp": {"value": 0.0}, }, "sentry_tags": { "transaction": "foo_transaction", "browser.name": "Chrome", }, } ), self.create_span( { "measurements": { "score.ratio.fcp": {"value": 0.0}, "score.ratio.cls": {"value": 0.0}, "score.ratio.ttfb": {"value": 0.0}, "score.ratio.lcp": {"value": 0.0}, "score.ratio.inp": {"value": 0.0}, }, "sentry_tags": { "transaction": "bar_transaction", "browser.name": "Chrome", }, } ), self.create_span( { "measurements": { "score.ratio.fcp": {"value": 0.0}, "score.ratio.cls": {"value": 0.0}, "score.ratio.ttfb": {"value": 0.0}, "score.ratio.lcp": {"value": 0.0}, "score.ratio.inp": {"value": 0.0}, }, "sentry_tags": { "transaction": "bar_transaction", "browser.name": "Firefox", }, } ), ], is_eap=True, ) response = self.do_request( { "field": [ "transaction", "opportunity_score(measurements.score.lcp)", "opportunity_score(measurements.score.inp)", "opportunity_score(measurements.score.cls)", "opportunity_score(measurements.score.ttfb)", "opportunity_score(measurements.score.fcp)", "opportunity_score(measurements.score.total)", ], "query": "browser.name:Chrome", "orderby": "transaction", "dataset": "spans", "project": self.project.id, } ) assert response.status_code == 200, response.content data = response.data["data"] assert len(data) == 2 assert data[0]["opportunity_score(measurements.score.lcp)"] == 0.5 assert data[0]["opportunity_score(measurements.score.inp)"] == 0.5 assert data[0]["opportunity_score(measurements.score.cls)"] == 0.5 assert data[0]["opportunity_score(measurements.score.ttfb)"] == 0.5 assert data[0]["opportunity_score(measurements.score.fcp)"] == 0.5 assert data[0]["opportunity_score(measurements.score.total)"] == 0.5 assert data[1]["opportunity_score(measurements.score.lcp)"] == 0 assert data[1]["opportunity_score(measurements.score.inp)"] == 0.5 assert data[1]["opportunity_score(measurements.score.cls)"] == 0.5 assert data[1]["opportunity_score(measurements.score.ttfb)"] == 0.5 assert data[1]["opportunity_score(measurements.score.fcp)"] == 0.5 self.assertAlmostEqual(data[1]["opportunity_score(measurements.score.total)"], 0.35) def test_total_opportunity_score_passes_with_bad_query(self) -> None: self.store_spans( [ self.create_span( { "measurements": { "score.ratio.fcp": {"value": 0.0}, "score.ratio.cls": {"value": 0.0}, "score.ratio.ttfb": {"value": 0.0}, "score.ratio.lcp": {"value": 1.0}, "score.ratio.inp": {"value": 0.0}, }, "sentry_tags": { "transaction": "foo_transaction", "browser.name": "Chrome", }, } ), ], is_eap=True, ) response = self.do_request( { "field": [ "transaction", "opportunity_score(measurements.score.total)", ], "query": 'transaction.op:foo_transaction span.op:foo_transaction !transaction:"<< unparameterized >>" avg(measurements.score.total):>=0', "orderby": "transaction", "dataset": "spans", "project": self.project.id, } ) assert response.status_code == 200, response.content def test_total_opportunity_score_missing_data(self) -> None: self.store_spans( [ self.create_span( { "measurements": { "score.ratio.fcp": {"value": 0.0}, "score.ratio.cls": {"value": 0.0}, "score.ratio.ttfb": {"value": 0.0}, "score.ratio.lcp": {"value": 1.0}, }, } ), self.create_span( { "measurements": { "score.ratio.fcp": {"value": 0.0}, "score.ratio.cls": {"value": 0.0}, "score.ratio.ttfb": {"value": 0.0}, "score.ratio.lcp": {"value": 0.0}, }, } ), self.create_span( { "measurements": { "score.ratio.fcp": {"value": 0.0}, "score.ratio.cls": {"value": 0.0}, "score.ratio.ttfb": {"value": 0.0}, "score.ratio.lcp": {"value": 0.0}, }, } ), ], is_eap=True, ) response = self.do_request( { "field": [ "opportunity_score(measurements.score.total)", ], "dataset": "spans", "project": self.project.id, } ) assert response.status_code == 200, response.content data = response.data["data"] assert len(data) == 1 assert data[0]["opportunity_score(measurements.score.total)"] == 0.8571428571428572 def test_count_starts(self) -> None: self.store_spans( [ self.create_span( { "measurements": {"app_start_warm": {"value": 200}}, "sentry_tags": {"transaction": "foo_transaction"}, } ), self.create_span( { "measurements": {"app_start_warm": {"value": 100}}, "sentry_tags": {"transaction": "foo_transaction"}, } ), self.create_span( { "measurements": {"app_start_cold": {"value": 10}}, "sentry_tags": {"transaction": "foo_transaction"}, } ), ], is_eap=True, ) response = self.do_request( { "field": [ "transaction", "count_starts(measurements.app_start_warm)", "count_starts(measurements.app_start_cold)", ], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["count_starts(measurements.app_start_warm)"] == 2 assert data[0]["count_starts(measurements.app_start_cold)"] == 1 assert meta["dataset"] == "spans" def test_unit_aggregate_filtering(self) -> None: spans = [ self.create_span( {"description": "bar", "sentry_tags": {"status": "invalid_argument"}}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), ] self.store_spans(spans, is_eap=True) response = self.do_request( { "field": ["avg(span.duration)", "description"], "query": "avg(span.duration):>0.5s", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 assert data == [ { "avg(span.duration)": 1000.0, "description": "bar", }, { "avg(span.duration)": 1000.0, "description": "foo", }, ] assert meta["dataset"] == "spans" def test_trace_id_in_filter(self) -> None: spans = [ self.create_span( {"description": "bar", "trace_id": "1" * 32}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "foo", "trace_id": "2" * 32}, start_ts=self.ten_mins_ago, ), ] self.store_spans(spans, is_eap=True) response = self.do_request( { "field": ["description"], "query": f"trace:[{'1' * 32}, {'2' * 32}]", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 assert data == [ { "description": "bar", "id": mock.ANY, "project.name": self.project.slug, }, { "description": "foo", "id": mock.ANY, "project.name": self.project.slug, }, ] assert meta["dataset"] == "spans" def test_filtering_null_numeric_attr(self) -> None: spans = [ self.create_span( { "description": "bar", "measurements": {"http.response.status_code": {"value": 200}}, }, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "foo", }, start_ts=self.ten_mins_ago, ), ] self.store_spans(spans, is_eap=True) response = self.do_request( { "field": [ "description", "tags[http.response.status_code,number]", "count()", ], "query": "!tags[http.response.status_code,number]:200", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { "tags[http.response.status_code,number]": None, "description": "foo", "count()": 1, }, ] assert meta["dataset"] == "spans" def test_internal_fields(self) -> None: self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "zoo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) for private_field in [ "sentry.organization_id", "sentry.item_type", ]: response = self.do_request( { "field": [private_field, "count()"], "query": "", "orderby": private_field, "project": self.project.id, "dataset": "spans", "statsPeriod": "1h", } ) assert response.status_code == 400, response.content def test_transaction_profile_attributes(self) -> None: span_with_profile = self.create_span(start_ts=before_now(minutes=10)) span_without_profile = self.create_span( {"profile_id": None}, start_ts=before_now(minutes=20) ) self.store_spans( [span_with_profile, span_without_profile], is_eap=True, ) response = self.do_request( { "field": ["id", "profile.id", "timestamp"], "query": "", "orderby": "-timestamp", "project": self.project.id, "dataset": "spans", "statsPeriod": "1h", } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span_with_profile["span_id"], "profile.id": span_with_profile["profile_id"], "project.name": self.project.slug, "timestamp": mock.ANY, }, { "id": span_without_profile["span_id"], "profile.id": None, "project.name": self.project.slug, "timestamp": mock.ANY, }, ] response = self.do_request( { "field": ["id", "profile.id", "timestamp"], "query": "has:profile.id", "orderby": "-timestamp", "project": self.project.id, "dataset": "spans", "statsPeriod": "1h", } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span_with_profile["span_id"], "profile.id": span_with_profile["profile_id"], "project.name": self.project.slug, "timestamp": mock.ANY, }, ] def test_continuous_profile_attributes(self) -> None: span_with_profile = self.create_span( { "profile_id": None, "sentry_tags": { "profiler_id": uuid4().hex, "thread.id": "123", "thread.name": "main", }, }, start_ts=before_now(minutes=10), ) span_without_profile = self.create_span( {"profile_id": None}, start_ts=before_now(minutes=20) ) self.store_spans( [span_with_profile, span_without_profile], is_eap=True, ) response = self.do_request( { "field": ["id", "profiler.id", "thread.id", "thread.name", "timestamp"], "query": "", "orderby": "-timestamp", "project": self.project.id, "dataset": "spans", "statsPeriod": "1h", } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span_with_profile["span_id"], "profiler.id": span_with_profile["sentry_tags"]["profiler_id"], "project.name": self.project.slug, "thread.id": span_with_profile["sentry_tags"]["thread.id"], "thread.name": span_with_profile["sentry_tags"]["thread.name"], "timestamp": mock.ANY, }, { "id": span_without_profile["span_id"], "profiler.id": None, "project.name": self.project.slug, "thread.id": None, "thread.name": None, "timestamp": mock.ANY, }, ] response = self.do_request( { "field": ["id", "profiler.id", "thread.id", "thread.name", "timestamp"], "query": "has:profiler.id", "orderby": "-timestamp", "project": self.project.id, "dataset": "spans", "statsPeriod": "1h", } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span_with_profile["span_id"], "profiler.id": span_with_profile["sentry_tags"]["profiler_id"], "project.name": self.project.slug, "thread.id": span_with_profile["sentry_tags"]["thread.id"], "thread.name": span_with_profile["sentry_tags"]["thread.name"], "timestamp": mock.ANY, }, ] def test_sampling_weight_does_not_fail(self) -> None: span = self.create_span( { "profile_id": None, "sentry_tags": { "profiler_id": uuid4().hex, "thread.id": "123", "thread.name": "main", }, "measurements": {"client_sample_rate": {"value": 0.5}}, }, start_ts=before_now(minutes=10), ) self.store_spans([span], is_eap=True) response = self.do_request( { "field": ["sentry.sampling_weight"], "query": "", "orderby": "sentry.sampling_weight", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 # Sampling weight is 1 / client_sample_rate assert data[0]["sentry.sampling_weight"] == 2.0 assert meta["dataset"] == "spans" def test_sampling_factor_does_not_fail(self) -> None: span = self.create_span( { "profile_id": None, "sentry_tags": { "profiler_id": uuid4().hex, "thread.id": "123", "thread.name": "main", }, "measurements": {"client_sample_rate": {"value": 0.01}}, }, start_ts=before_now(minutes=10), ) self.store_spans([span], is_eap=True) response = self.do_request( { "field": ["sentry.sampling_factor"], "query": "", "orderby": "sentry.sampling_factor", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["sentry.sampling_factor"] == 0.01 assert meta["dataset"] == "spans" def test_is_starred_transaction(self) -> None: InsightsStarredSegment.objects.create( organization=self.organization, project=self.project, segment_name="foo", user_id=self.user.id, ) self.store_spans( [ self.create_span( { "description": "foo", "sentry_tags": {"status": "success", "transaction": "foo"}, "is_segment": True, }, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "bar", "sentry_tags": {"status": "success", "transaction": "bar"}, "is_segment": True, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["is_starred_transaction", "transaction"], "query": "", "project": self.project.id, "dataset": "spans", "orderby": "-is_starred_transaction", } ) assert response.status_code == 200, response.content data = response.data["data"] assert len(data) == 2 assert data[0]["is_starred_transaction"] is True assert data[0]["transaction"] == "foo" assert data[1]["is_starred_transaction"] is False assert data[1]["transaction"] == "bar" @mock.patch("sentry.api.utils.sentry_sdk.capture_exception") @mock.patch("sentry.utils.snuba_rpc._snuba_pool.urlopen") def test_snuba_error_handles_correctly( self, mock_sdk: mock.MagicMock, mock_rpc_query: mock.MagicMock ) -> None: mock_rpc_query.side_effect = urllib3.exceptions.HTTPError() response = self.do_request( { "field": ["count()"], "query": "", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 500, response.content mock_sdk.assert_called_once() def test_empty_string_equal(self) -> None: self.store_spans( [ self.create_span( { "description": "foo", "sentry_tags": {"user.email": "test@test.com"}, }, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "bar", "sentry_tags": {"user.email": ""}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["user.email", "description", "count()"], "query": '!user.email:""', "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { "user.email": "test@test.com", "description": "foo", "count()": 1, }, ] assert meta["dataset"] == "spans" def test_empty_string_negation(self) -> None: self.store_spans( [ self.create_span( { "description": "foo", "sentry_tags": {"user.email": "test@test.com"}, }, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "bar", "sentry_tags": {"user.email": ""}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["user.email", "description", "count()"], "query": 'user.email:""', "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { "user.email": "", "description": "bar", "count()": 1, }, ] assert meta["dataset"] == "spans" def test_has_parent_span_filter(self) -> None: spans = [ self.create_span( {"parent_span_id": None}, start_ts=self.ten_mins_ago, ), self.create_span( {}, start_ts=self.ten_mins_ago, ), ] self.store_spans(spans, is_eap=True) response = self.do_request( { "field": ["parent_span"], "query": "!has:parent_span", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { "id": spans[0]["span_id"], "parent_span": None, "project.name": self.project.slug, } ] assert meta["dataset"] == "spans" response = self.do_request( { "field": ["parent_span"], "query": "has:parent_span", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { "id": spans[1]["span_id"], "parent_span": spans[1]["parent_span_id"], "project.name": self.project.slug, } ] assert meta["dataset"] == "spans" def test_app_start_fields(self) -> None: self.store_spans( [ self.create_span( { "description": "foo", "sentry_tags": { "ttid": "ttid", "app_start_type": "cold", "os.name": "Android", }, }, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "foo", "sentry_tags": { "ttid": "ttid", "app_start_type": "warm", "os.name": "iOS", }, }, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "foo", "sentry_tags": {"app_start_type": "cold", "os.name": "Android"}, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["app_start_type", "ttid", "os.name"], "query": "has:ttid", "orderby": "app_start_type", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 assert data[0]["app_start_type"] == "cold" assert data[0]["ttid"] == "ttid" assert data[0]["os.name"] == "Android" assert data[1]["app_start_type"] == "warm" assert data[1]["ttid"] == "ttid" assert data[1]["os.name"] == "iOS" assert meta["dataset"] == "spans" assert meta["dataset"] == "spans" def test_typed_attributes_with_colons(self) -> None: span = self.create_span( { "data": { "flag.evaluation.feature.organizations:foo": True, }, }, start_ts=self.ten_mins_ago, ) self.store_spans( [ self.create_span(start_ts=self.ten_mins_ago), span, ], is_eap=True, ) response = self.do_request( { "field": ["tags[flag.evaluation.feature.organizations:foo,number]"], "query": "has:tags[flag.evaluation.feature.organizations:foo,number] tags[flag.evaluation.feature.organizations:foo,number]:1", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span["span_id"], "project.name": self.project.slug, "tags[flag.evaluation.feature.organizations:foo,number]": 1, }, ] def test_count_if_two_args(self): """count_if should have an operator""" self.store_spans( [ self.create_span({"sentry_tags": {"release": "foo"}}), self.create_span( {"sentry_tags": {"release": "bar"}}, duration=10, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["count_if(release,foo)"], "query": "", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 400, response.content def test_span_ops_breakdown(self) -> None: self.store_spans( [ self.create_span( { "measurements": {"span_ops.ops.http": {"value": 100}}, }, ), ], is_eap=True, ) response = self.do_request( { "field": ["spans.http"], "query": "", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["spans.http"] == 100 assert meta["dataset"] == "spans" def test_special_characters(self) -> None: characters = "_.-" span = self.create_span( {"tags": {f"tag{c}": c for c in characters}}, start_ts=self.ten_mins_ago, ) self.store_spans( [ span, self.create_span(start_ts=self.ten_mins_ago), ], is_eap=True, ) for c in characters: response = self.do_request( { "field": [f"tag{c}"], "query": f"tag{c}:{c}", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span["span_id"], "project.name": self.project.slug, f"tag{c}": c, } ] def test_ai_total_tokens_returns_integer_meta(self) -> None: self.store_spans( [ self.create_span( {"data": {"ai_total_tokens_used": 100}}, start_ts=self.ten_mins_ago, ), self.create_span( {"data": {"ai_total_tokens_used": 50}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["sum(ai.total_tokens.used)"], "query": "", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data, meta = response.data["data"], response.data["meta"] assert len(data) == 1 assert data[0]["sum(ai.total_tokens.used)"] == 150 assert meta["dataset"] == "spans" assert meta["fields"]["sum(ai.total_tokens.used)"] == "integer" def test_equation_simple(self) -> None: self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "bar", "sentry_tags": {"status": "invalid_argument"}, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) equation = "equation|count() * 2" response = self.do_request( { "field": ["span.status", "description", equation], "query": "", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 assert data == [ { "span.status": "invalid_argument", "description": "bar", equation: 2, }, { "span.status": "success", "description": "foo", equation: 2, }, ] assert meta["dataset"] == "spans" assert meta["fields"][equation] == "number" def test_equation_with_orderby_using_same_alias(self) -> None: self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "bar", "sentry_tags": {"status": "invalid_argument"}, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) equation = "equation|count(span.duration)" response = self.do_request( { "field": ["count(span.duration)", equation], "query": "", "orderby": "count_span_duration", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { "count(span.duration)": 2, equation: 2, }, ] assert meta["dataset"] == "spans" assert meta["fields"][equation] == "integer" def test_equation_single_function_term(self) -> None: self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "bar", "sentry_tags": {"status": "invalid_argument"}, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) equation = "equation|count()" response = self.do_request( { "field": ["span.status", "description", equation], "query": "", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 assert data == [ { "span.status": "invalid_argument", "description": "bar", equation: 1, }, { "span.status": "success", "description": "foo", equation: 1, }, ] assert meta["dataset"] == "spans" assert meta["fields"][equation] == "integer" def test_equation_single_field_term(self) -> None: self.store_spans( [ self.create_span( { "description": "foo", "sentry_tags": {"status": "success"}, "measurements": {"lcp": {"value": 1}}, }, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "bar", "sentry_tags": {"status": "success"}, "measurements": {"lcp": {"value": 1}}, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) equation = "equation|measurements.lcp" response = self.do_request( { "field": ["span.status", "description", equation, "count()"], "query": "", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 assert data == [ { "span.status": "success", "description": "bar", "count()": 1, equation: 1, }, { "span.status": "success", "description": "foo", "count()": 1, equation: 1, }, ] assert meta["dataset"] == "spans" assert meta["fields"][equation] == "duration" def test_equation_single_literal(self) -> None: self.store_spans( [ self.create_span( { "description": "foo", "sentry_tags": {"status": "success"}, }, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "bar", "sentry_tags": {"status": "success"}, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) equation = "equation|3.14159" response = self.do_request( { "field": ["span.status", "description", equation, "count()"], "query": "", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 assert data == [ { "span.status": "success", "description": "bar", "count()": 1, equation: 3.14159, }, { "span.status": "success", "description": "foo", "count()": 1, equation: 3.14159, }, ] assert meta["dataset"] == "spans" assert meta["fields"][equation] == "number" @pytest.mark.xfail(reason="Confidence isn't being returned by the RPC currently") def test_equation_with_extrapolation(self) -> None: """Extrapolation only changes the number when there's a sample rate""" spans = [] spans.append( self.create_span( { "description": "foo", "sentry_tags": {"status": "success"}, "measurements": {"client_sample_rate": {"value": 0.1}}, }, start_ts=self.ten_mins_ago, ) ) spans.append( self.create_span( { "description": "bar", "sentry_tags": {"status": "success"}, }, start_ts=self.ten_mins_ago, ) ) self.store_spans(spans, is_eap=True) equation = "equation|count() * (2)" response = self.do_request( { "field": ["description", equation], "orderby": f"-{equation}", "query": "", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] confidence = meta["accuracy"]["confidence"] assert len(data) == 2 assert len(confidence) == 2 assert data[0][equation] == 20 assert confidence[0][equation] == "low" assert data[1][equation] == 2 assert confidence[1][equation] in ("high", "low") def test_equation_all_symbols(self) -> None: self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "bar", "sentry_tags": {"status": "invalid_argument"}, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) equation = "equation|count() * 2 + 2 - 2 / 2" response = self.do_request( { "field": ["span.status", "description", equation], "query": "", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 assert data == [ { "span.status": "invalid_argument", "description": "bar", equation: 3, }, { "span.status": "success", "description": "foo", equation: 3, }, ] assert meta["dataset"] == "spans" assert meta["fields"][equation] == "number" def test_release(self) -> None: span1 = self.create_span( { "sentry_tags": { "release": "1.0.8", "environment": self.environment.name, }, }, start_ts=self.ten_mins_ago, ) span2 = self.create_span( { "sentry_tags": { "release": "1.0.9", "environment": self.environment.name, }, }, start_ts=self.ten_mins_ago, ) self.store_spans([span1, span2], is_eap=True) response = self.do_request( { "field": ["release"], "query": "release:1.0.8", "project": self.project.id, "environment": self.environment.name, "dataset": "spans", "orderby": "release", } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span1["span_id"], "project.name": self.project.slug, "release": "1.0.8", }, ] response = self.do_request( { "field": ["release"], "query": "release:1*", "project": self.project.id, "dataset": "spans", "orderby": "release", } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span1["span_id"], "project.name": self.project.slug, "release": "1.0.8", }, { "id": span2["span_id"], "project.name": self.project.slug, "release": "1.0.9", }, ] def test_latest_release_alias(self) -> None: self.create_release(version="0.8") span1 = self.create_span({"sentry_tags": {"release": "0.8"}}, start_ts=self.ten_mins_ago) self.store_spans([span1], is_eap=True) response = self.do_request( { "field": ["release"], "query": "release:latest", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span1["span_id"], "project.name": self.project.slug, "release": "0.8", } ] self.create_release(version="0.9") span2 = self.create_span({"sentry_tags": {"release": "0.9"}}, start_ts=self.ten_mins_ago) self.store_spans([span2], is_eap=True) response = self.do_request( { "field": ["release"], "query": "release:latest", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span2["span_id"], "project.name": self.project.slug, "release": "0.9", } ] def test_release_stage(self) -> None: replaced_release = self.create_release( version="replaced_release", environments=[self.environment], adopted=now(), unadopted=now(), ) adopted_release = self.create_release( version="adopted_release", environments=[self.environment], adopted=now(), ) self.create_release(version="not_adopted_release", environments=[self.environment]) adopted_span = self.create_span( { "sentry_tags": { "environment": self.environment.name, "release": adopted_release.version, }, }, start_ts=self.ten_mins_ago, ) replaced_span = self.create_span( { "sentry_tags": { "environment": self.environment.name, "release": replaced_release.version, }, }, start_ts=self.ten_mins_ago, ) self.store_spans([adopted_span, replaced_span], is_eap=True) request = { "field": ["release"], "project": self.project.id, "dataset": "spans", "orderby": "release", "environment": self.environment.name, } response = self.do_request({**request, "query": "release.stage:adopted"}) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": adopted_span["span_id"], "project.name": self.project.slug, "release": "adopted_release", }, ] response = self.do_request({**request, "query": "!release.stage:low_adoption"}) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": adopted_span["span_id"], "project.name": self.project.slug, "release": "adopted_release", }, { "id": replaced_span["span_id"], "project.name": self.project.slug, "release": "replaced_release", }, ] response = self.do_request({**request, "query": "release.stage:[adopted,replaced]"}) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": adopted_span["span_id"], "project.name": self.project.slug, "release": "adopted_release", }, { "id": replaced_span["span_id"], "project.name": self.project.slug, "release": "replaced_release", }, ] def test_semver(self) -> None: release_1 = self.create_release(version="test@1.2.1") release_2 = self.create_release(version="test@1.2.2") release_3 = self.create_release(version="test@1.2.3") span1 = self.create_span( {"sentry_tags": {"release": release_1.version}}, start_ts=self.ten_mins_ago ) span2 = self.create_span( {"sentry_tags": {"release": release_2.version}}, start_ts=self.ten_mins_ago ) span3 = self.create_span( {"sentry_tags": {"release": release_3.version}}, start_ts=self.ten_mins_ago ) self.store_spans([span1, span2, span3], is_eap=True) request = { "field": ["release"], "project": self.project.id, "dataset": "spans", "orderby": "release", } response = self.do_request({**request, "query": "release.version:>1.2.1"}) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span2["span_id"], "project.name": self.project.slug, "release": "test@1.2.2", }, { "id": span3["span_id"], "project.name": self.project.slug, "release": "test@1.2.3", }, ] with mock.patch("sentry.search.eap.spans.filter_aliases.constants.MAX_SEARCH_RELEASES", 2): response = self.do_request({**request, "query": "release.version:>1.2.1"}) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span2["span_id"], "project.name": self.project.slug, "release": "test@1.2.2", }, { "id": span3["span_id"], "project.name": self.project.slug, "release": "test@1.2.3", }, ] response = self.do_request({**request, "query": "release.version:>=1.2.1"}) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span1["span_id"], "project.name": self.project.slug, "release": "test@1.2.1", }, { "id": span2["span_id"], "project.name": self.project.slug, "release": "test@1.2.2", }, { "id": span3["span_id"], "project.name": self.project.slug, "release": "test@1.2.3", }, ] response = self.do_request({**request, "query": "release.version:<1.2.2"}) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span1["span_id"], "project.name": self.project.slug, "release": "test@1.2.1", } ] response = self.do_request({**request, "query": "release.version:1.2.2"}) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span2["span_id"], "project.name": self.project.slug, "release": "test@1.2.2", } ] response = self.do_request({**request, "query": "!release.version:1.2.2"}) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span1["span_id"], "project.name": self.project.slug, "release": "test@1.2.1", }, { "id": span3["span_id"], "project.name": self.project.slug, "release": "test@1.2.3", }, ] def test_semver_package(self) -> None: release_1 = self.create_release(version="test1@1.2.1") release_2 = self.create_release(version="test2@1.2.1") span1 = self.create_span( {"sentry_tags": {"release": release_1.version}}, start_ts=self.ten_mins_ago ) span2 = self.create_span( {"sentry_tags": {"release": release_2.version}}, start_ts=self.ten_mins_ago ) self.store_spans([span1, span2], is_eap=True) request = { "field": ["release"], "project": self.project.id, "dataset": "spans", "orderby": "release", } response = self.do_request({**request, "query": "release.package:test1"}) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span1["span_id"], "project.name": self.project.slug, "release": "test1@1.2.1", }, ] response = self.do_request({**request, "query": "release.package:test2"}) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span2["span_id"], "project.name": self.project.slug, "release": "test2@1.2.1", }, ] def test_semver_build(self) -> None: release_1 = self.create_release(version="test@1.2.3+121") release_2 = self.create_release(version="test@1.2.3+122") span1 = self.create_span( {"sentry_tags": {"release": release_1.version}}, start_ts=self.ten_mins_ago ) span2 = self.create_span( {"sentry_tags": {"release": release_2.version}}, start_ts=self.ten_mins_ago ) self.store_spans([span1, span2], is_eap=True) request = { "field": ["release"], "project": self.project.id, "dataset": "spans", "orderby": "release", } response = self.do_request({**request, "query": "release.build:121"}) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span1["span_id"], "project.name": self.project.slug, "release": "test@1.2.3+121", }, ] response = self.do_request({**request, "query": "release.build:122"}) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span2["span_id"], "project.name": self.project.slug, "release": "test@1.2.3+122", }, ] response = self.do_request({**request, "query": "!release.build:121"}) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span2["span_id"], "project.name": self.project.slug, "release": "test@1.2.3+122", }, ] def test_file_extension(self) -> None: self.store_spans( [ self.create_span( {"sentry_tags": {"file_extension": "css"}}, start_ts=self.ten_mins_ago, ), self.create_span( {"sentry_tags": {"file_extension": "js"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": [ "file_extension", ], "orderby": "file_extension", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 assert data[0]["file_extension"] == "css" assert data[1]["file_extension"] == "js" assert meta["dataset"] == "spans" def test_filter_timestamp(self) -> None: one_day_ago = before_now(days=1).replace(microsecond=0) three_days_ago = before_now(days=3).replace(microsecond=0) span1 = self.create_span({}, start_ts=one_day_ago) span2 = self.create_span({}, start_ts=three_days_ago) self.store_spans([span1, span2], is_eap=True) request = { "field": ["timestamp"], "project": self.project.id, "dataset": "spans", } response = self.do_request( { **request, "query": "timestamp:-2d", } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span1["span_id"], "project.name": self.project.slug, "timestamp": one_day_ago.isoformat(), }, ] timestamp = before_now(days=2).isoformat() timestamp = timestamp.split("T", 2)[0] response = self.do_request( { **request, "query": f"timestamp:>{timestamp}", } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span1["span_id"], "project.name": self.project.slug, "timestamp": one_day_ago.isoformat(), }, ] response = self.do_request( { **request, "query": f"timestamp:<{timestamp}", } ) assert response.status_code == 200, response.content assert response.data["data"] == [ { "id": span2["span_id"], "project.name": self.project.slug, "timestamp": three_days_ago.isoformat(), }, ] def test_tag_wildcards_with_in_filter(self) -> None: self.store_spans( [ self.create_span( {"description": "foo", "tags": {"foo": "bar"}}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "qux", "tags": {"foo": "qux"}}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "bux", "tags": {"foo": "bux"}}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "qar", "tags": {"foo": "qar"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["foo", "count()"], "query": "foo:[b*,*ux]", "project": self.project.id, "orderby": "foo", "dataset": "spans", } ) assert response.status_code == 200, response.content assert len(response.data["data"]) == 3 assert response.data["data"] == [ {"foo": "bar", "count()": 1}, {"foo": "bux", "count()": 1}, {"foo": "qux", "count()": 1}, ] def test_tag_wildcards_with_not_in_filter(self) -> None: self.store_spans( [ self.create_span( {"description": "bar", "tags": {"foo": "bar"}}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "qux", "tags": {"foo": "qux"}}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "bux", "tags": {"foo": "bux"}}, start_ts=self.ten_mins_ago, ), self.create_span( {"description": "qar", "tags": {"foo": "qar"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["foo", "count()"], "query": "!foo:[ba*,*ux]", "project": self.project.id, "orderby": "foo", "dataset": "spans", } ) assert response.status_code == 200, response.content assert len(response.data["data"]) == 1 assert response.data["data"] == [ {"foo": "qar", "count()": 1}, ] def test_disable_extrapolation(self) -> None: spans = [] spans.append( self.create_span( { "description": "foo", "sentry_tags": {"status": "success"}, "measurements": {"client_sample_rate": {"value": 0.1}}, }, start_ts=self.ten_mins_ago, ) ) spans.append( self.create_span( { "description": "bar", "sentry_tags": {"status": "success"}, }, start_ts=self.ten_mins_ago, ) ) self.store_spans(spans, is_eap=True) response = self.do_request( { "field": ["description", "count()"], "orderby": "-count()", "query": "", "project": self.project.id, "dataset": "spans", "disableAggregateExtrapolation": 1, } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] confidence = meta["accuracy"]["confidence"] assert len(data) == 2 assert len(confidence) == 2 assert data[0]["count()"] == 1 assert "count()" not in confidence[0] assert data[1]["count()"] == 1 assert "count()" not in confidence[1] def test_failure_count(self) -> None: trace_statuses = ["ok", "cancelled", "unknown", "failure"] self.store_spans( [ self.create_span( {"sentry_tags": {"status": status}}, start_ts=self.ten_mins_ago, ) for status in trace_statuses ], is_eap=True, ) response = self.do_request( { "field": ["failure_count()"], "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["failure_count()"] == 1 assert meta["dataset"] == "spans" assert meta["fields"]["failure_count()"] == "integer" assert meta["units"]["failure_count()"] is None def test_trace_id_glob(self) -> None: response = self.do_request( { "field": ["trace"], "project": self.project.id, "dataset": "spans", "query": "trace:test*", "orderby": "trace", } ) assert response.status_code == 400, response.content assert response.data["detail"] == "test% is an invalid value for trace" def test_short_trace_id_filter(self) -> None: trace_ids = [ "0" * 32, ("7" * 31) + "0", "7" * 32, ("7" * 31) + "f", "f" * 32, ] self.store_spans( [ self.create_span( {"trace_id": trace_id}, start_ts=self.ten_mins_ago, ) for trace_id in trace_ids ], is_eap=True, ) for i in range(8, 32): response = self.do_request( { "field": ["trace"], "project": self.project.id, "dataset": "spans", "query": f"trace:{'7' * i}", "orderby": "trace", } ) assert response.status_code == 200, response.content data = response.data["data"] assert len(data) == 3 assert {row["trace"] for row in data} == { ("7" * 31) + "0", "7" * 32, ("7" * 31) + "f", } def test_eps(self) -> None: self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["description", "eps()"], "query": "", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { "description": "foo", "eps()": 1 / (90 * 24 * 60 * 60), }, ] assert meta["dataset"] == "spans" assert meta["units"] == {"description": None, "eps()": "1/second"} assert meta["fields"] == {"description": "string", "eps()": "rate"} def test_count_if_span_status(self) -> None: self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "bar", "sentry_tags": {"status": "invalid_argument"}, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["count_if(span.status,equals,success)"], "query": "", "orderby": "count_if(span.status,equals,success)", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { "count_if(span.status,equals,success)": 1, }, ] assert meta["dataset"] == "spans" assert meta["fields"]["count_if(span.status,equals,success)"] == "integer" assert meta["units"]["count_if(span.status,equals,success)"] is None def test_count_if_span_status_equation_quoted(self) -> None: self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "bar", "sentry_tags": {"status": ""}, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) equation = 'equation|count_if(span.status,equals,"success")' response = self.do_request( { "field": [equation], "query": "", "orderby": equation, "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { equation: 1.0, }, ] assert meta["dataset"] == "spans" assert meta["fields"][equation] == "integer" assert meta["units"][equation] is None equation = 'equation|count_if(span.status,equals,"")' response = self.do_request( { "field": [equation], "query": "", "orderby": equation, "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { equation: 1.0, }, ] assert meta["dataset"] == "spans" assert meta["fields"][equation] == "integer" assert meta["units"][equation] is None def test_count_if_numeric(self) -> None: self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, duration=400, ), self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, duration=400, ), self.create_span( { "description": "bar", "sentry_tags": {"status": "invalid_argument"}, }, start_ts=self.ten_mins_ago, duration=200, ), ], is_eap=True, ) response = self.do_request( { "field": ["count_if(span.duration,greater,300)"], "query": "", "orderby": "count_if(span.duration,greater,300)", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { "count_if(span.duration,greater,300)": 2, }, ] assert meta["dataset"] == "spans" def test_count_if_numeric_raises_invalid_search_query_with_bad_value(self) -> None: response = self.do_request( { "field": ["count_if(span.duration,greater,three)"], "query": "", "orderby": "count_if(span.duration,greater,three)", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 400, response.content assert "Invalid Parameter " in response.data["detail"].title() def test_count_if_integer(self) -> None: self.store_spans( [ self.create_span( {"description": "foo"}, measurements={"gen_ai.usage.total_tokens": {"value": 100}}, start_ts=self.ten_mins_ago, duration=400, ), self.create_span( {"description": "bar"}, measurements={"gen_ai.usage.total_tokens": {"value": 200}}, start_ts=self.ten_mins_ago, duration=400, ), self.create_span( {"description": "baz"}, measurements={"gen_ai.usage.total_tokens": {"value": 300}}, start_ts=self.ten_mins_ago, duration=200, ), ], is_eap=True, ) response = self.do_request( { "field": ["count_if(gen_ai.usage.total_tokens,greater,200)"], "query": "", "orderby": "count_if(gen_ai.usage.total_tokens,greater,200)", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { "count_if(gen_ai.usage.total_tokens,greater,200)": 1, }, ] assert meta["dataset"] == "spans" def test_apdex_function(self) -> None: """Test the apdex function with span.duration and threshold.""" # Create spans with different durations to test apdex calculation # Threshold = 1000ms (1 second) # Satisfactory: ≤ 1000ms # Tolerable: > 1000ms and ≤ 4000ms # Frustrated: > 4000ms spans = [ # Satisfactory spans (≤ 1000ms) self.create_span( {"description": "http.server", "is_segment": True}, start_ts=self.ten_mins_ago, duration=500, # 500ms - satisfactory ), self.create_span( {"description": "http.server", "is_segment": True}, start_ts=self.ten_mins_ago, duration=1000, # 1000ms - satisfactory (at threshold) ), # Tolerable spans (> 1000ms and ≤ 4000ms) self.create_span( {"description": "http.server", "is_segment": True}, start_ts=self.ten_mins_ago, duration=2000, # 2000ms - tolerable ), self.create_span( {"description": "http.server", "is_segment": True}, start_ts=self.ten_mins_ago, duration=4000, # 4000ms - tolerable (at 4T) ), # Frustrated spans (> 4000ms) self.create_span( {"description": "http.server", "is_segment": True}, start_ts=self.ten_mins_ago, duration=5000, # 5000ms - frustrated ), # Non-segment span self.create_span( {"description": "http.server", "is_segment": False}, start_ts=self.ten_mins_ago, duration=5000, # 5000ms - frustrated ), ] self.store_spans(spans, is_eap=True) response = self.do_request( { "field": ["apdex(span.duration,1000)"], "query": "", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] # Expected apdex calculation: # Satisfactory: 2 spans (500ms, 1000ms) # Tolerable: 2 spans (2000ms, 4000ms) # Frustrated: 1 span (5000ms) # Total: 5 spans # Apdex = (2 + 2/2) / 5 = (2 + 1) / 5 = 3/5 = 0.6 expected_apdex = 0.6 assert len(data) == 1 assert data[0]["apdex(span.duration,1000)"] == expected_apdex assert meta["dataset"] == "spans" assert meta["fields"] == {"apdex(span.duration,1000)": "number"} def test_apdex_function_with_filter(self) -> None: """Test the apdex function with filtering.""" # Create spans with different descriptions and durations # Only segments (transactions) will be counted in apdex calculation spans = [ # Satisfactory spans for "api" operations (segments) self.create_span( { "description": "http.server", "sentry_tags": {"status": "success"}, "is_segment": True, }, start_ts=self.ten_mins_ago, duration=500, ), self.create_span( { "description": "http.server", "sentry_tags": {"status": "success"}, "is_segment": True, }, start_ts=self.ten_mins_ago, duration=800, ), # Tolerable span for "api" operations (segment) self.create_span( { "description": "http.server", "sentry_tags": {"status": "success"}, "is_segment": True, }, start_ts=self.ten_mins_ago, duration=2000, ), # Frustrated span for "api" operations (segment) self.create_span( { "description": "http.server", "sentry_tags": {"status": "success"}, "is_segment": True, }, start_ts=self.ten_mins_ago, duration=5000, ), # Other spans that should be filtered out self.create_span( { "description": "task", "sentry_tags": {"status": "success"}, "is_segment": True, }, start_ts=self.ten_mins_ago, duration=100, ), ] self.store_spans(spans, is_eap=True) response = self.do_request( { "field": ["apdex(span.duration,1000)"], "query": "description:http.server", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] # Expected apdex calculation for filtered results: # Only segments (transactions) are counted in apdex # Satisfactory: 2 spans (500ms, 800ms) - both are segments # Tolerable: 1 span (2000ms) - is a segment # Frustrated: 1 span (5000ms) - is a segment # Total: 4 spans (all segments) # Apdex = (2 + 1/2) / 4 = (2 + 0.5) / 4 = 2.5/4 = 0.625 expected_apdex = 0.625 assert len(data) == 1 assert data[0]["apdex(span.duration,1000)"] == expected_apdex def test_user_misery_function(self) -> None: """Test the user_misery function with span.duration and threshold.""" # Create spans with different durations and users to test user misery calculation # Threshold = 1000ms (1 second) # Miserable threshold = 4000ms (4x threshold) # Users are considered miserable when response time > 4000ms spans = [ # Happy users (≤ 4000ms) - segments self.create_span( { "description": "http.server", "sentry_tags": {"user": "user1"}, "is_segment": True, }, start_ts=self.ten_mins_ago, duration=500, # 500ms - happy ), self.create_span( { "description": "http.server", "sentry_tags": {"user": "user2"}, "is_segment": True, }, start_ts=self.ten_mins_ago, duration=2000, # 2000ms - happy ), self.create_span( { "description": "http.server", "sentry_tags": {"user": "user3"}, "is_segment": True, }, start_ts=self.ten_mins_ago, duration=4000, # 4000ms - happy (at 4T) ), # Miserable users (> 4000ms) - segments self.create_span( { "description": "http.server", "sentry_tags": {"user": "user4"}, "is_segment": True, }, start_ts=self.ten_mins_ago, duration=5000, # 5000ms - miserable ), self.create_span( { "description": "http.server", "sentry_tags": {"user": "user2"}, "is_segment": True, }, start_ts=self.ten_mins_ago, duration=6000, # 6000ms - miserable ), # Non-segment span (should not be counted) self.create_span( { "description": "http.server", "sentry_tags": {"user": "user5"}, "is_segment": False, }, start_ts=self.ten_mins_ago, duration=5000, # 5000ms - miserable but not a segment ), ] self.store_spans(spans, is_eap=True) response = self.do_request( { "field": ["user_misery(span.duration,1000)"], "query": "", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] # Expected user misery calculation: # Miserable users: 2 (user4, user2) - both are segments # Total unique users: 5 (user1, user2, user3, user4) - all segments # MISERY_ALPHA = 5.8875, MISERY_BETA = 111.8625 # User Misery = (2 + 5.8875) / (5 + 5.8875 + 111.8625) = 7.8875 / 122.75 ≈ 0.0643 expected_user_misery = (2 + 5.8875) / (4 + 5.8875 + 111.8625) assert len(data) == 1 assert data[0]["user_misery(span.duration,1000)"] == pytest.approx( expected_user_misery, rel=1e-3 ) assert meta["dataset"] == "spans" assert meta["fields"] == {"user_misery(span.duration,1000)": "number"} def test_user_misery_function_with_filter(self) -> None: """Test the user_misery function with filtering.""" # Create spans with different descriptions, durations, and users # Only segments (transactions) will be counted in user misery calculation spans = [ # Happy users for "api" operations (segments) self.create_span( { "description": "http.server", "sentry_tags": {"user": "user1", "status": "success"}, "is_segment": True, }, start_ts=self.ten_mins_ago, duration=500, ), self.create_span( { "description": "http.server", "sentry_tags": {"user": "user2", "status": "success"}, "is_segment": True, }, start_ts=self.ten_mins_ago, duration=2000, ), # Miserable user for "api" operations (segment) self.create_span( { "description": "http.server", "sentry_tags": {"user": "user3", "status": "success"}, "is_segment": True, }, start_ts=self.ten_mins_ago, duration=5000, ), # Other spans that should be filtered out self.create_span( { "description": "task", "sentry_tags": {"user": "user4", "status": "success"}, "is_segment": True, }, start_ts=self.ten_mins_ago, duration=100, ), ] self.store_spans(spans, is_eap=True) response = self.do_request( { "field": ["user_misery(span.duration,1000)"], "query": "description:http.server", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] # Expected user misery calculation for filtered results: # Only segments (transactions) are counted in user misery # Miserable users: 1 (user3) - is a segment # Total unique users: 3 (user1, user2, user3) - all segments # MISERY_ALPHA = 5.8875, MISERY_BETA = 111.8625 # User Misery = (1 + 5.8875) / (3 + 5.8875 + 111.8625) = 6.8875 / 120.75 ≈ 0.0570 expected_user_misery = (1 + 5.8875) / (3 + 5.8875 + 111.8625) assert len(data) == 1 assert data[0]["user_misery(span.duration,1000)"] == pytest.approx( expected_user_misery, rel=1e-3 ) def test_link_field_fails(self) -> None: response = self.do_request( { "field": ["span.status", "description", "count()"], "query": "sentry.links:foo", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 400, response.content response = self.do_request( { "field": ["sentry.links", "description", "count()"], "query": "", "orderby": "description", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 400, response.content def test_formula_filtering(self) -> None: self.store_spans( [ self.create_span( { "sentry_tags": {"transaction": "transactionA", "browser.name": "Chrome"}, "measurements": { "frames.total": {"value": 100}, "frames.frozen": {"value": 70}, }, }, start_ts=self.ten_mins_ago, ), self.create_span( { "sentry_tags": {"transaction": "transactionA", "browser.name": "Chrome"}, "measurements": { "frames.total": {"value": 100}, "frames.frozen": {"value": 70}, }, }, start_ts=self.ten_mins_ago, ), self.create_span( { "sentry_tags": {"transaction": "transactionB", "browser.name": "Chrome"}, "measurements": { "frames.total": {"value": 100}, "frames.frozen": {"value": 20}, }, }, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": [ "division_if(mobile.frozen_frames,mobile.total_frames,browser.name,equals,Chrome)", "transaction", ], "query": "division_if(mobile.frozen_frames,mobile.total_frames,browser.name,equals,Chrome):>0.5", "project": self.project.id, "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert ( data[0][ "division_if(mobile.frozen_frames,mobile.total_frames,browser.name,equals,Chrome)" ] == 0.7 ) assert data[0]["transaction"] == "transactionA" assert meta["dataset"] == "spans" @pytest.mark.xfail( reason="https://linear.app/getsentry/issue/EAP-255/aggregationcomparisonfilter-does-not-work-with-binaryformula" ) def test_formula_filtering_attribute_aggregation_only(self) -> None: self.store_spans( [ self.create_span( {"sentry_tags": {"status": "ok", "transaction": "transactionA"}}, start_ts=self.ten_mins_ago, ), self.create_span( {"sentry_tags": {"status": "failure", "transaction": "transactionA"}}, start_ts=self.ten_mins_ago, ), self.create_span( {"sentry_tags": {"status": "ok", "transaction": "transactionB"}}, start_ts=self.ten_mins_ago, ), ], ) response = self.do_request( { "field": ["failure_rate()", "transaction"], "query": "failure_rate():>0.4", "project": self.project.id, "dataset": "spans", } ) data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data[0]["failure_rate()"] == 0.5 assert data[0]["transaction"] == "transactionA" assert meta["dataset"] == "spans" def test_project_filter(self) -> None: project2 = self.create_project() self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "bar", "sentry_tags": {"status": "invalid_argument"}, }, project=project2, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["project", "description", "count()"], "query": f"project:[{self.project.slug}, {project2.slug}]", "orderby": "description", "project": [self.project.id, project2.id], "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 2 assert data == [ { "project": project2.slug, "description": "bar", "count()": 1, }, { "project": self.project.slug, "description": "foo", "count()": 1, }, ] assert meta["dataset"] == "spans" response = self.do_request( { "field": ["project", "description", "count()"], "query": f"project:{self.project.slug}", "orderby": "description", "project": [self.project.id, project2.id], "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 1 assert data == [ { "project": self.project.slug, "description": "foo", "count()": 1, }, ] assert meta["dataset"] == "spans" def test_non_org_project_filter(self): organization2 = self.create_organization() project2 = self.create_project(organization=organization2) self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), self.create_span( { "description": "bar", "sentry_tags": {"status": "invalid_argument"}, }, project=project2, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) response = self.do_request( { "field": ["project", "description", "count()"], "query": f"project:[{project2.slug}]", "orderby": "description", "project": [self.project.id], "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 0 assert data == [] assert meta["dataset"] == "spans" response = self.do_request( { "field": ["project", "description", "count()"], "query": f"project.id:[{project2.id}]", "orderby": "description", "project": [self.project.id], "dataset": "spans", } ) assert response.status_code == 200, response.content data = response.data["data"] meta = response.data["meta"] assert len(data) == 0 assert data == [] assert meta["dataset"] == "spans" def test_count_span_duration(self): self.store_spans( [ self.create_span( {"description": "foo", "sentry_tags": {"status": "success"}}, start_ts=self.ten_mins_ago, ), ], is_eap=True, ) request = { "field": ["count(span.duration)"], "project": self.project.id, "dataset": "spans", "statsPeriod": "1h", } response = self.do_request(request) assert response.status_code == 200 assert response.data["data"] == [{"count(span.duration)": 1}] def test_wildcard_operator_with_backslash(self): span = self.create_span({"description": r"foo\bar"}, start_ts=self.ten_mins_ago) self.store_spans([span], is_eap=True) base_request = { "field": ["project.name", "id"], "project": self.project.id, "dataset": "spans", "statsPeriod": "1h", } response = self.do_request({**base_request, "query": r"span.description:foo\bar"}) assert response.status_code == 200, response.data assert response.data["data"] == [{"project.name": self.project.slug, "id": span["span_id"]}] response = self.do_request({**base_request, "query": r"span.description:*foo\\bar*"}) assert response.status_code == 200, response.data assert response.data["data"] == [{"project.name": self.project.slug, "id": span["span_id"]}] response = self.do_request( {**base_request, "query": "span.description:\uf00dContains\uf00dfoo\\bar"} ) assert response.status_code == 200, response.data assert response.data["data"] == [{"project.name": self.project.slug, "id": span["span_id"]}] response = self.do_request( {**base_request, "query": "span.description:\uf00dStartsWith\uf00dfoo\\bar"} ) assert response.status_code == 200, response.data assert response.data["data"] == [{"project.name": self.project.slug, "id": span["span_id"]}] response = self.do_request( {**base_request, "query": "span.description:\uf00dEndsWith\uf00dfoo\\bar"} ) assert response.status_code == 200, response.data assert response.data["data"] == [{"project.name": self.project.slug, "id": span["span_id"]}]
OrganizationEventsSpansEndpointTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/metaclass2.py
{ "start": 651, "end": 740 }
class ____(metaclass=Meta): # This should generate an error inst_var1 = ""
MyClass2
python
redis__redis-py
redis/client.py
{ "start": 27094, "end": 29864 }
class ____: """ Monitor is useful for handling the MONITOR command to the redis server. next_command() method returns one command from monitor listen() method yields commands from monitor. """ monitor_re = re.compile(r"\[(\d+) (.*?)\] (.*)") command_re = re.compile(r'"(.*?)(?<!\\)"') def __init__(self, connection_pool): self.connection_pool = connection_pool self.connection = self.connection_pool.get_connection() def __enter__(self): self._start_monitor() return self def __exit__(self, *args): self.connection.disconnect() self.connection_pool.release(self.connection) def next_command(self): """Parse the response from a monitor command""" response = self.connection.read_response() if response is None: return None if isinstance(response, bytes): response = self.connection.encoder.decode(response, force=True) command_time, command_data = response.split(" ", 1) m = self.monitor_re.match(command_data) db_id, client_info, command = m.groups() command = " ".join(self.command_re.findall(command)) # Redis escapes double quotes because each piece of the command # string is surrounded by double quotes. We don't have that # requirement so remove the escaping and leave the quote. command = command.replace('\\"', '"') if client_info == "lua": client_address = "lua" client_port = "" client_type = "lua" elif client_info.startswith("unix"): client_address = "unix" client_port = client_info[5:] client_type = "unix" else: if client_info == "": client_address = "" client_port = "" client_type = "unknown" else: # use rsplit as ipv6 addresses contain colons client_address, client_port = client_info.rsplit(":", 1) client_type = "tcp" return { "time": float(command_time), "db": int(db_id), "client_address": client_address, "client_port": client_port, "client_type": client_type, "command": command, } def listen(self): """Listen for commands coming to the server.""" while True: yield self.next_command() def _start_monitor(self): self.connection.send_command("MONITOR") # check that monitor returns 'OK', but don't return it to user response = self.connection.read_response() if not bool_ok(response): raise RedisError(f"MONITOR failed: {response}")
Monitor
python
ansible__ansible
lib/ansible/module_utils/common/collections.py
{ "start": 520, "end": 4074 }
class ____(Hashable, Mapping): """Dictionary that cannot be updated""" def __init__(self, *args, **kwargs): self._store = dict(*args, **kwargs) def __getitem__(self, key): return self._store[key] def __iter__(self): return self._store.__iter__() def __len__(self): return self._store.__len__() def __hash__(self): return hash(frozenset(self.items())) def __eq__(self, other): try: if self.__hash__() == hash(other): return True except TypeError: pass return False def __repr__(self): return 'ImmutableDict({0})'.format(repr(self._store)) def union(self, overriding_mapping): """ Create an ImmutableDict as a combination of the original and overriding_mapping :arg overriding_mapping: A Mapping of replacement and additional items :return: A copy of the ImmutableDict with key-value pairs from the overriding_mapping added If any of the keys in overriding_mapping are already present in the original ImmutableDict, the overriding_mapping item replaces the one in the original ImmutableDict. """ return ImmutableDict(self._store, **overriding_mapping) def difference(self, subtractive_iterable): """ Create an ImmutableDict as a combination of the original minus keys in subtractive_iterable :arg subtractive_iterable: Any iterable containing keys that should not be present in the new ImmutableDict :return: A copy of the ImmutableDict with keys from the subtractive_iterable removed """ remove_keys = frozenset(subtractive_iterable) keys = (k for k in self._store.keys() if k not in remove_keys) return ImmutableDict((k, self._store[k]) for k in keys) def is_string(seq): """Identify whether the input has a string-like type (including bytes).""" return isinstance(seq, (str, bytes)) def is_iterable(seq, include_strings=False): """Identify whether the input is an iterable.""" if not include_strings and is_string(seq): return False try: iter(seq) return True except TypeError: return False def is_sequence(seq, include_strings=False): """Identify whether the input is a sequence. Strings and bytes are not sequences here, unless ``include_string`` is ``True``. Non-indexable things are never of a sequence type. """ if not include_strings and is_string(seq): return False return isinstance(seq, Sequence) def count(seq): """Returns a dictionary with the number of appearances of each element of the iterable. Resembles the collections.Counter class functionality. It is meant to be used when the code is run on Python 2.6.* where collections.Counter is not available. It should be deprecated and replaced when support for Python < 2.7 is dropped. """ _warnings.deprecate( msg="The `ansible.module_utils.common.collections.count` function is deprecated.", version="2.23", help_text="Use `collections.Counter` from the Python standard library instead.", ) if not is_iterable(seq): raise Exception('Argument provided is not an iterable') counters = dict() for elem in seq: counters[elem] = counters.get(elem, 0) + 1 return counters def __getattr__(importable_name): return _no_six.deprecate(importable_name, __name__, "binary_type", "text_type")
ImmutableDict
python
pandas-dev__pandas
pandas/io/json/_json.py
{ "start": 26178, "end": 35668 }
class ____(abc.Iterator, Generic[FrameSeriesStrT]): """ JsonReader provides an interface for reading in a JSON file. If initialized with ``lines=True`` and ``chunksize``, can be iterated over ``chunksize`` lines at a time. Otherwise, calling ``read`` reads in the whole document. """ def __init__( self, filepath_or_buffer, orient, typ: FrameSeriesStrT, dtype, convert_axes: bool | None, convert_dates, keep_default_dates: bool, precise_float: bool, date_unit, encoding, lines: bool, chunksize: int | None, compression: CompressionOptions, nrows: int | None, storage_options: StorageOptions | None = None, encoding_errors: str | None = "strict", dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default, engine: JSONEngine = "ujson", ) -> None: self.orient = orient self.typ = typ self.dtype = dtype self.convert_axes = convert_axes self.convert_dates = convert_dates self.keep_default_dates = keep_default_dates self.precise_float = precise_float self.date_unit = date_unit self.encoding = encoding self.engine = engine self.compression = compression self.storage_options = storage_options self.lines = lines self.chunksize = chunksize self.nrows_seen = 0 self.nrows = nrows self.encoding_errors = encoding_errors self.handles: IOHandles[str] | None = None self.dtype_backend = dtype_backend if self.engine not in {"pyarrow", "ujson"}: raise ValueError( f"The engine type {self.engine} is currently not supported." ) if self.chunksize is not None: self.chunksize = validate_integer("chunksize", self.chunksize, 1) if not self.lines: raise ValueError("chunksize can only be passed if lines=True") if self.engine == "pyarrow": raise ValueError( "currently pyarrow engine doesn't support chunksize parameter" ) if self.nrows is not None: self.nrows = validate_integer("nrows", self.nrows, 0) if not self.lines: raise ValueError("nrows can only be passed if lines=True") if self.engine == "pyarrow": if not self.lines: raise ValueError( "currently pyarrow engine only supports " "the line-delimited JSON format" ) self.data = filepath_or_buffer elif self.engine == "ujson": data = self._get_data_from_filepath(filepath_or_buffer) # If self.chunksize, we prepare the data for the `__next__` method. # Otherwise, we read it into memory for the `read` method. if not (self.chunksize or self.nrows): with self: self.data = data.read() else: self.data = data def _get_data_from_filepath(self, filepath_or_buffer): """ The function read_json accepts three input types: 1. filepath (string-like) 2. file-like object (e.g. open file object, StringIO) """ filepath_or_buffer = stringify_path(filepath_or_buffer) try: self.handles = get_handle( filepath_or_buffer, "r", encoding=self.encoding, compression=self.compression, storage_options=self.storage_options, errors=self.encoding_errors, ) except OSError as err: raise FileNotFoundError( f"File {filepath_or_buffer} does not exist" ) from err filepath_or_buffer = self.handles.handle return filepath_or_buffer def _combine_lines(self, lines) -> str: """ Combines a list of JSON objects into one JSON object. """ return ( f"[{','.join([line for line in (line.strip() for line in lines) if line])}]" ) @overload def read(self: JsonReader[Literal["frame"]]) -> DataFrame: ... @overload def read(self: JsonReader[Literal["series"]]) -> Series: ... @overload def read(self: JsonReader[Literal["frame", "series"]]) -> DataFrame | Series: ... def read(self) -> DataFrame | Series: """ Read the whole JSON input into a pandas object. """ obj: DataFrame | Series with self: if self.engine == "pyarrow": obj = self._read_pyarrow() elif self.engine == "ujson": obj = self._read_ujson() return obj def _read_pyarrow(self) -> DataFrame: """ Read JSON using the pyarrow engine. """ pyarrow_json = import_optional_dependency("pyarrow.json") options = None if isinstance(self.dtype, dict): pa = import_optional_dependency("pyarrow") fields = [] for field, dtype in self.dtype.items(): pd_dtype = pandas_dtype(dtype) if isinstance(pd_dtype, ArrowDtype): fields.append((field, pd_dtype.pyarrow_dtype)) schema = pa.schema(fields) options = pyarrow_json.ParseOptions( explicit_schema=schema, unexpected_field_behavior="infer" ) pa_table = pyarrow_json.read_json(self.data, parse_options=options) df = arrow_table_to_pandas(pa_table, dtype_backend=self.dtype_backend) return df def _read_ujson(self) -> DataFrame | Series: """ Read JSON using the ujson engine. """ obj: DataFrame | Series if self.lines: if self.chunksize: obj = concat(self) elif self.nrows: lines = list(islice(self.data, self.nrows)) lines_json = self._combine_lines(lines) obj = self._get_object_parser(lines_json) else: data = ensure_str(self.data) data_lines = data.split("\n") obj = self._get_object_parser(self._combine_lines(data_lines)) else: obj = self._get_object_parser(self.data) if self.dtype_backend is not lib.no_default: with option_context("mode.nan_is_na", True): return obj.convert_dtypes( infer_objects=False, dtype_backend=self.dtype_backend ) else: return obj def _get_object_parser(self, json: str) -> DataFrame | Series: """ Parses a json document into a pandas object. """ typ = self.typ dtype = self.dtype kwargs = { "orient": self.orient, "dtype": self.dtype, "convert_axes": self.convert_axes, "convert_dates": self.convert_dates, "keep_default_dates": self.keep_default_dates, "precise_float": self.precise_float, "date_unit": self.date_unit, "dtype_backend": self.dtype_backend, } if typ == "frame": return FrameParser(json, **kwargs).parse() elif typ == "series": if not isinstance(dtype, bool): kwargs["dtype"] = dtype return SeriesParser(json, **kwargs).parse() else: raise ValueError(f"{typ=} must be 'frame' or 'series'.") def close(self) -> None: """ If we opened a stream earlier, in _get_data_from_filepath, we should close it. If an open stream or file was passed, we leave it open. """ if self.handles is not None: self.handles.close() def __iter__(self) -> Self: return self @overload def __next__(self: JsonReader[Literal["frame"]]) -> DataFrame: ... @overload def __next__(self: JsonReader[Literal["series"]]) -> Series: ... @overload def __next__( self: JsonReader[Literal["frame", "series"]], ) -> DataFrame | Series: ... def __next__(self) -> DataFrame | Series: if self.nrows and self.nrows_seen >= self.nrows: self.close() raise StopIteration lines = list(islice(self.data, self.chunksize)) if not lines: self.close() raise StopIteration try: lines_json = self._combine_lines(lines) obj = self._get_object_parser(lines_json) # Make sure that the returned objects have the right index. obj.index = range(self.nrows_seen, self.nrows_seen + len(obj)) self.nrows_seen += len(obj) except Exception as ex: self.close() raise ex if self.dtype_backend is not lib.no_default: with option_context("mode.nan_is_na", True): return obj.convert_dtypes( infer_objects=False, dtype_backend=self.dtype_backend ) else: return obj def __enter__(self) -> Self: return self def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> None: self.close()
JsonReader
python
pydantic__pydantic
tests/typechecking/with_config_decorator.py
{ "start": 386, "end": 509 }
class ____(TypedDict): pass assert_type(Model1, type[Model1]) model = Model1(a='ABC') assert_type(model, Model1)
Model3
python
walkccc__LeetCode
solutions/3431. Minimum Unlocked Indices to Sort Nums/3431.py
{ "start": 0, "end": 676 }
class ____: def minUnlockedIndices(self, nums: list[int], locked: list[int]) -> int: first2 = next((i for i, x in enumerate(nums) if x == 2), -1) first3 = next((i for i, x in enumerate(nums) if x == 3), -1) last1 = next((i for i, x in reversed(list(enumerate(nums))) if x == 1), -1) last2 = next((i for i, x in reversed(list(enumerate(nums))) if x == 2), -1) if first3 != -1 and last1 != -1 and first3 < last1: return -1 return (sum(locked[i] == 1 for i in range(first2, last1) if first2 != -1 and last1 != -1) + sum(locked[i] == 1 for i in range(first3, last2) if first3 != -1 and last2 != -1))
Solution
python
huggingface__transformers
tests/models/sam/test_modeling_sam.py
{ "start": 10646, "end": 12308 }
class ____: def __init__( self, hidden_size=32, hidden_act="relu", mlp_dim=64, num_hidden_layers=2, num_attention_heads=4, attention_downsample_rate=2, num_multimask_outputs=3, iou_head_depth=3, iou_head_hidden_dim=32, layer_norm_eps=1e-6, ): self.hidden_size = hidden_size self.hidden_act = hidden_act self.mlp_dim = mlp_dim self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.attention_downsample_rate = attention_downsample_rate self.num_multimask_outputs = num_multimask_outputs self.iou_head_depth = iou_head_depth self.iou_head_hidden_dim = iou_head_hidden_dim self.layer_norm_eps = layer_norm_eps def get_config(self): return SamMaskDecoderConfig( hidden_size=self.hidden_size, hidden_act=self.hidden_act, mlp_dim=self.mlp_dim, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, attention_downsample_rate=self.attention_downsample_rate, num_multimask_outputs=self.num_multimask_outputs, iou_head_depth=self.iou_head_depth, iou_head_hidden_dim=self.iou_head_hidden_dim, layer_norm_eps=self.layer_norm_eps, ) def prepare_config_and_inputs(self): config = self.get_config() dummy_inputs = { "image_embedding": floats_tensor([self.batch_size, self.hidden_size]), } return config, dummy_inputs
SamMaskDecoderTester
python
bokeh__bokeh
src/bokeh/core/property/override.py
{ "start": 1443, "end": 3445 }
class ____(Generic[T]): """ Override attributes of Bokeh property in derived Models. When subclassing a Bokeh Model, it may be desirable to change some of the attributes of the property itself, from those on the base class. This is accomplished using the ``Override`` class. Currently, ``Override`` can only be use to override the ``default`` value for the property. Keyword Args: default (obj) : a default value for this property on a subclass Example: Consider the following class definitions: .. code-block:: python from bokeh.model import Model from bokeh.properties import Int, Override class Parent(Model): foo = Int(default=10) class Child(Parent): foo = Override(default=20) The parent class has an integer property ``foo`` with default value 10. The child class uses the following code: .. code-block:: python foo = Override(default=20) to specify that the default value for the ``foo`` property should be 20 on instances of the child class: .. code-block:: python >>> p = Parent() >>> p.foo 10 >>> c = Child() >>> c.foo 20 """ default_overridden: bool default: T def __init__(self, *, default: T) -> None: self.default_overridden = True self.default = default #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
Override
python
docker__docker-py
docker/utils/socket.py
{ "start": 198, "end": 5073 }
class ____(Exception): pass # NpipeSockets have their own error types # pywintypes.error: (109, 'ReadFile', 'The pipe has been ended.') NPIPE_ENDED = 109 def read(socket, n=4096): """ Reads at most n bytes from socket """ recoverable_errors = (errno.EINTR, errno.EDEADLK, errno.EWOULDBLOCK) if not isinstance(socket, NpipeSocket): if not hasattr(select, "poll"): # Limited to 1024 select.select([socket], [], []) else: poll = select.poll() poll.register(socket, select.POLLIN | select.POLLPRI) poll.poll() try: if hasattr(socket, 'recv'): return socket.recv(n) if isinstance(socket, pysocket.SocketIO): return socket.read(n) return os.read(socket.fileno(), n) except OSError as e: if e.errno not in recoverable_errors: raise except Exception as e: is_pipe_ended = (isinstance(socket, NpipeSocket) and len(e.args) > 0 and e.args[0] == NPIPE_ENDED) if is_pipe_ended: # npipes don't support duplex sockets, so we interpret # a PIPE_ENDED error as a close operation (0-length read). return '' raise def read_exactly(socket, n): """ Reads exactly n bytes from socket Raises SocketError if there isn't enough data """ data = b"" while len(data) < n: next_data = read(socket, n - len(data)) if not next_data: raise SocketError("Unexpected EOF") data += next_data return data def next_frame_header(socket): """ Returns the stream and size of the next frame of data waiting to be read from socket, according to the protocol defined here: https://docs.docker.com/engine/api/v1.24/#attach-to-a-container """ try: data = read_exactly(socket, 8) except SocketError: return (-1, -1) stream, actual = struct.unpack('>BxxxL', data) return (stream, actual) def frames_iter(socket, tty): """ Return a generator of frames read from socket. A frame is a tuple where the first item is the stream number and the second item is a chunk of data. If the tty setting is enabled, the streams are multiplexed into the stdout stream. """ if tty: return ((STDOUT, frame) for frame in frames_iter_tty(socket)) else: return frames_iter_no_tty(socket) def frames_iter_no_tty(socket): """ Returns a generator of data read from the socket when the tty setting is not enabled. """ while True: (stream, n) = next_frame_header(socket) if n < 0: break while n > 0: result = read(socket, n) if result is None: continue data_length = len(result) if data_length == 0: # We have reached EOF return n -= data_length yield (stream, result) def frames_iter_tty(socket): """ Return a generator of data read from the socket when the tty setting is enabled. """ while True: result = read(socket) if len(result) == 0: # We have reached EOF return yield result def consume_socket_output(frames, demux=False): """ Iterate through frames read from the socket and return the result. Args: demux (bool): If False, stdout and stderr are multiplexed, and the result is the concatenation of all the frames. If True, the streams are demultiplexed, and the result is a 2-tuple where each item is the concatenation of frames belonging to the same stream. """ if demux is False: # If the streams are multiplexed, the generator returns strings, that # we just need to concatenate. return b"".join(frames) # If the streams are demultiplexed, the generator yields tuples # (stdout, stderr) out = [None, None] for frame in frames: # It is guaranteed that for each frame, one and only one stream # is not None. assert frame != (None, None) if frame[0] is not None: if out[0] is None: out[0] = frame[0] else: out[0] += frame[0] else: if out[1] is None: out[1] = frame[1] else: out[1] += frame[1] return tuple(out) def demux_adaptor(stream_id, data): """ Utility to demultiplex stdout and stderr when reading frames from the socket. """ if stream_id == STDOUT: return (data, None) elif stream_id == STDERR: return (None, data) else: raise ValueError(f'{stream_id} is not a valid stream')
SocketError
python
cython__cython
tests/errors/pure_cclass_without_body.py
{ "start": 15, "end": 112 }
class ____(object): pass _ERRORS = u""" 3:0: C class 'Test' is declared but not defined """
Test
python
doocs__leetcode
solution/1600-1699/1663.Smallest String With A Given Numeric Value/Solution.py
{ "start": 0, "end": 276 }
class ____: def getSmallestString(self, n: int, k: int) -> str: ans = ['a'] * n i, d = n - 1, k - n while d > 25: ans[i] = 'z' d -= 25 i -= 1 ans[i] = chr(ord(ans[i]) + d) return ''.join(ans)
Solution
python
dask__dask
dask/dataframe/tseries/resample.py
{ "start": 3088, "end": 5094 }
class ____(Expr): _parameters = [ "frame", "rule", "kwargs", "how_args", "how_kwargs", ] _defaults = { "closed": None, "label": None, "kwargs": None, "how_args": (), "how_kwargs": None, } how: str | None = None fill_value = np.nan @functools.cached_property def npartitions(self): return self.frame.npartitions def _divisions(self): return self._resample_divisions[1] @functools.cached_property def _meta(self): resample = meta_nonempty(self.frame._meta).resample(self.rule, **self.kwargs) meta = getattr(resample, self.how)(*self.how_args, **self.how_kwargs or {}) return make_meta(meta) @functools.cached_property def kwargs(self): return {} if self.operand("kwargs") is None else self.operand("kwargs") @functools.cached_property def how_kwargs(self): return {} if self.operand("how_kwargs") is None else self.operand("how_kwargs") @functools.cached_property def _resample_divisions(self): return _resample_bin_and_out_divs( self.frame.divisions, self.rule, **self.kwargs or {} ) def _simplify_up(self, parent, dependents): if isinstance(parent, Projection): return plain_column_projection(self, parent, dependents) def _lower(self): partitioned = Repartition( self.frame, new_divisions=self._resample_divisions[0], force=True ) output_divisions = self._resample_divisions[1] return ResampleAggregation( partitioned, BlockwiseDep(output_divisions[:-1]), BlockwiseDep(output_divisions[1:]), BlockwiseDep(["left"] * (len(output_divisions[1:]) - 1) + [None]), self.rule, self.kwargs, self.how, self.fill_value, list(self.how_args), self.how_kwargs, )
ResampleReduction
python
ray-project__ray
rllib/models/tests/test_catalog.py
{ "start": 1118, "end": 2169 }
class ____(TFActionDistribution): def __init__(self, inputs, model): # Store our output shape. custom_model_config = model.model_config["custom_model_config"] if "output_dim" in custom_model_config: self.output_shape = tf.concat( [tf.shape(inputs)[:1], custom_model_config["output_dim"]], axis=0 ) else: self.output_shape = tf.shape(inputs) super().__init__(inputs, model) @staticmethod def required_model_output_shape(action_space, model_config=None): custom_model_config = model_config["custom_model_config"] or {} if custom_model_config is not None and custom_model_config.get("output_dim"): return custom_model_config.get("output_dim") return action_space.shape @override(TFActionDistribution) def _build_sample_op(self): return tf.random.uniform(self.output_shape) @override(ActionDistribution) def logp(self, x): return tf.zeros(self.output_shape)
CustomActionDistribution
python
qdrant__qdrant-client
tests/congruence_tests/test_search.py
{ "start": 491, "end": 13825 }
class ____: __test__ = False def __init__(self): self.query_text = np.random.random(text_vector_size).tolist() self.query_image = np.random.random(image_vector_size).tolist() self.query_code = np.random.random(code_vector_size).tolist() def simple_search_text(self, client: QdrantBase) -> list[models.ScoredPoint]: return client.query_points( collection_name=COLLECTION_NAME, query=self.query_text, using="text", with_payload=True, limit=10, ).points def simple_search_image(self, client: QdrantBase) -> list[models.ScoredPoint]: return client.query_points( collection_name=COLLECTION_NAME, using="image", query=self.query_image, with_payload=True, limit=10, ).points def simple_search_code(self, client: QdrantBase) -> list[models.ScoredPoint]: return client.query_points( collection_name=COLLECTION_NAME, query=self.query_code, using="code", with_payload=True, limit=10, ).points def simple_search_text_offset(self, client: QdrantBase) -> list[models.ScoredPoint]: return client.query_points( collection_name=COLLECTION_NAME, using="text", query=self.query_text, with_payload=True, limit=10, offset=10, ).points def simple_search_text_with_vector(self, client: QdrantBase) -> list[models.ScoredPoint]: return client.query_points( collection_name=COLLECTION_NAME, using="text", query=self.query_text, with_payload=True, with_vectors=True, limit=10, offset=10, ).points def search_score_threshold(self, client: QdrantBase) -> list[models.ScoredPoint]: res1 = client.query_points( collection_name=COLLECTION_NAME, query=self.query_text, using="text", with_payload=True, limit=10, score_threshold=0.9, ).points res2 = client.query_points( collection_name=COLLECTION_NAME, query=self.query_text, using="text", with_payload=True, limit=10, score_threshold=0.95, ).points res3 = client.query_points( collection_name=COLLECTION_NAME, query=self.query_text, using="text", with_payload=True, limit=10, score_threshold=0.1, ).points return res1 + res2 + res3 def simple_search_text_select_payload(self, client: QdrantBase) -> list[models.ScoredPoint]: return client.query_points( collection_name=COLLECTION_NAME, using="text", query=self.query_text, with_payload=["text_array", "nested.id"], limit=10, ).points def search_payload_exclude(self, client: QdrantBase) -> list[models.ScoredPoint]: return client.query_points( collection_name=COLLECTION_NAME, using="text", query=self.query_text, with_payload=models.PayloadSelectorExclude(exclude=["text_array", "nested.id"]), limit=10, ).points def simple_search_image_select_vector(self, client: QdrantBase) -> list[models.ScoredPoint]: return client.query_points( collection_name=COLLECTION_NAME, using="image", query=self.query_image, with_payload=False, with_vectors=["image", "code"], limit=10, ).points def filter_search_text( self, client: QdrantBase, query_filter: models.Filter ) -> list[models.ScoredPoint]: return client.query_points( collection_name=COLLECTION_NAME, using="text", query=self.query_text, query_filter=query_filter, with_payload=True, limit=10, ).points def filter_search_text_single( self, client: QdrantBase, query_filter: models.Filter ) -> list[models.ScoredPoint]: return client.query_points( collection_name=COLLECTION_NAME, query=self.query_text, query_filter=query_filter, with_payload=True, with_vectors=True, limit=10, ).points def test_simple_search(): fixture_points = generate_fixtures() searcher = TestSimpleSearcher() local_client = init_local() init_client(local_client, fixture_points) remote_client = init_remote() init_client(remote_client, fixture_points) compare_client_results(local_client, remote_client, searcher.simple_search_text) compare_client_results(local_client, remote_client, searcher.simple_search_image) compare_client_results(local_client, remote_client, searcher.simple_search_code) compare_client_results(local_client, remote_client, searcher.simple_search_text_offset) compare_client_results(local_client, remote_client, searcher.simple_search_text_with_vector) compare_client_results(local_client, remote_client, searcher.search_score_threshold) compare_client_results(local_client, remote_client, searcher.simple_search_text_select_payload) compare_client_results(local_client, remote_client, searcher.simple_search_image_select_vector) compare_client_results(local_client, remote_client, searcher.search_payload_exclude) for i in range(100): query_filter = one_random_filter_please() try: compare_client_results( local_client, remote_client, searcher.filter_search_text, query_filter=query_filter ) except AssertionError as e: print(f"\nFailed with filter {query_filter}") raise e def test_simple_opt_vectors_search(): fixture_points = generate_fixtures(skip_vectors=True) searcher = TestSimpleSearcher() local_client = init_local() init_client(local_client, fixture_points) remote_client = init_remote() init_client(remote_client, fixture_points) compare_client_results(local_client, remote_client, searcher.simple_search_text) compare_client_results(local_client, remote_client, searcher.simple_search_image) compare_client_results(local_client, remote_client, searcher.simple_search_code) compare_client_results(local_client, remote_client, searcher.simple_search_text_offset) compare_client_results(local_client, remote_client, searcher.simple_search_text_with_vector) compare_client_results(local_client, remote_client, searcher.search_score_threshold) compare_client_results(local_client, remote_client, searcher.simple_search_text_select_payload) compare_client_results(local_client, remote_client, searcher.simple_search_image_select_vector) compare_client_results(local_client, remote_client, searcher.search_payload_exclude) for i in range(100): query_filter = one_random_filter_please() try: compare_client_results( local_client, remote_client, searcher.filter_search_text, query_filter=query_filter ) except AssertionError as e: print(f"\nFailed with filter {query_filter}") raise e def test_single_vector(): fixture_points = generate_fixtures(num=200, vectors_sizes=text_vector_size) searcher = TestSimpleSearcher() vectors_config = models.VectorParams( size=text_vector_size, distance=models.Distance.DOT, ) local_client = init_local() init_client(local_client, fixture_points, vectors_config=vectors_config) remote_client = init_remote() init_client(remote_client, fixture_points, vectors_config=vectors_config) for i in range(100): query_filter = one_random_filter_please() try: compare_client_results( local_client, remote_client, searcher.filter_search_text_single, query_filter=query_filter, ) except AssertionError as e: print(f"\nFailed with filter {query_filter}") raise e def test_search_with_persistence(): import tempfile fixture_points = generate_fixtures() searcher = TestSimpleSearcher() with tempfile.TemporaryDirectory() as tmpdir: local_client = init_local(tmpdir) init_client(local_client, fixture_points) payload_update_filter = one_random_filter_please() local_client.set_payload(COLLECTION_NAME, {"test": f"test"}, payload_update_filter) del local_client local_client_2 = init_local(tmpdir) remote_client = init_remote() init_client(remote_client, fixture_points) remote_client.set_payload(COLLECTION_NAME, {"test": f"test"}, payload_update_filter) payload_update_filter = one_random_filter_please() local_client_2.set_payload(COLLECTION_NAME, {"test": "test2"}, payload_update_filter) remote_client.set_payload(COLLECTION_NAME, {"test": "test2"}, payload_update_filter) for i in range(10): query_filter = one_random_filter_please() try: compare_client_results( local_client_2, remote_client, searcher.filter_search_text, query_filter=query_filter, ) except AssertionError as e: print(f"\nFailed with filter {query_filter}") raise e def test_search_with_persistence_and_skipped_vectors(): import tempfile fixture_points = generate_fixtures(skip_vectors=True) searcher = TestSimpleSearcher() with tempfile.TemporaryDirectory() as tmpdir: local_client = init_local(tmpdir) init_client(local_client, fixture_points) payload_update_filter = one_random_filter_please() local_client.set_payload(COLLECTION_NAME, {"test": f"test"}, payload_update_filter) count_before_load = local_client.count(COLLECTION_NAME) del local_client local_client_2 = init_local(tmpdir) count_after_load = local_client_2.count(COLLECTION_NAME) assert count_after_load == count_before_load remote_client = init_remote() init_client(remote_client, fixture_points) remote_client.set_payload(COLLECTION_NAME, {"test": f"test"}, payload_update_filter) payload_update_filter = one_random_filter_please() local_client_2.set_payload(COLLECTION_NAME, {"test": "test2"}, payload_update_filter) remote_client.set_payload(COLLECTION_NAME, {"test": "test2"}, payload_update_filter) for i in range(10): query_filter = one_random_filter_please() try: compare_client_results( local_client_2, remote_client, searcher.filter_search_text, query_filter=query_filter, ) except AssertionError as e: print(f"\nFailed with filter {query_filter}") raise e def test_search_invalid_vector_type(): fixture_points = generate_fixtures() local_client = init_local() init_client(local_client, fixture_points) remote_client = init_remote() init_client(remote_client, fixture_points) vector_invalid_type = {"text": [1, 2, 3, 4]} with pytest.raises(ValueError): local_client.query_points(collection_name=COLLECTION_NAME, query=vector_invalid_type) with pytest.raises(ValueError): remote_client.query_points(collection_name=COLLECTION_NAME, query=vector_invalid_type) def test_query_with_nan(): fixture_points = generate_fixtures() local_client = init_local() init_client(local_client, fixture_points) remote_client = init_remote() init_client(remote_client, fixture_points) vector = np.random.random(text_vector_size) vector[4] = np.nan query_vector = vector.tolist() with pytest.raises(AssertionError): local_client.query_points(COLLECTION_NAME, query_vector, using="text") with pytest.raises(UnexpectedResponse): remote_client.query_points(COLLECTION_NAME, query_vector, using="text") single_vector_config = models.VectorParams( size=text_vector_size, distance=models.Distance.COSINE ) local_client.delete_collection(COLLECTION_NAME) local_client.create_collection(COLLECTION_NAME, vectors_config=single_vector_config) remote_client.delete_collection(COLLECTION_NAME) remote_client.create_collection(COLLECTION_NAME, vectors_config=single_vector_config) fixture_points = generate_fixtures(vectors_sizes=text_vector_size) init_client(local_client, fixture_points, vectors_config=single_vector_config) init_client(remote_client, fixture_points, vectors_config=single_vector_config) with pytest.raises(AssertionError): local_client.query_points(COLLECTION_NAME, vector.tolist()) with pytest.raises(UnexpectedResponse): remote_client.query_points(COLLECTION_NAME, vector.tolist())
TestSimpleSearcher
python
allegroai__clearml
clearml/backend_api/services/v2_20/queues.py
{ "start": 56028, "end": 56291 }
class ____(Request): """ """ _service = "queues" _action = "get_default" _version = "2.20" _schema = { "additionalProperties": False, "definitions": {}, "properties": {}, "type": "object", }
GetDefaultRequest
python
dagster-io__dagster
python_modules/dagster/dagster/_core/remote_representation/grpc_server_state_subscriber.py
{ "start": 1132, "end": 1485 }
class ____: def __init__(self, callback: Callable[[LocationStateChangeEvent], None]): check.callable_param(callback, "callback") self._callback = callback def handle_event(self, event: LocationStateChangeEvent): check.inst_param(event, "event", LocationStateChangeEvent) self._callback(event)
LocationStateSubscriber
python
ray-project__ray
python/ray/tune/tests/test_api.py
{ "start": 1815, "end": 48849 }
class ____(unittest.TestCase): def setUp(self): ray.init(num_cpus=4, num_gpus=0, object_store_memory=150 * 1024 * 1024) self.tmpdir = tempfile.mkdtemp() def tearDown(self): ray.shutdown() # _register_all() # re-register the evicted objects shutil.rmtree(self.tmpdir) def checkAndReturnConsistentLogs(self, results, sleep_per_iter=None): """Checks logging is the same between APIs. Ignore "DONE" for logging but checks that the scheduler is notified properly with the last result. """ class_results = copy.deepcopy(results) function_results = copy.deepcopy(results) class_output = [] function_output = [] scheduler_notif = [] class MockScheduler(FIFOScheduler): def on_trial_complete(self, runner, trial, result): scheduler_notif.append(result) class ClassAPILogger(Logger): def on_result(self, result): class_output.append(result) class FunctionAPILogger(Logger): def on_result(self, result): function_output.append(result) class _WrappedTrainable(Trainable): def setup(self, config): del config self._result_iter = copy.deepcopy(class_results) def step(self): if sleep_per_iter: time.sleep(sleep_per_iter) res = self._result_iter.pop(0) # This should not fail if not self._result_iter: # Mark "Done" for last result res[DONE] = True return res def _function_trainable(config): for result in function_results: if sleep_per_iter: time.sleep(sleep_per_iter) tune.report(result) class_trainable_name = "class_trainable" register_trainable(class_trainable_name, _WrappedTrainable) [trial1] = run( _function_trainable, callbacks=[LegacyLoggerCallback([FunctionAPILogger])], raise_on_failed_trial=False, scheduler=MockScheduler(), ).trials [trial2] = run( class_trainable_name, callbacks=[LegacyLoggerCallback([ClassAPILogger])], raise_on_failed_trial=False, scheduler=MockScheduler(), ).trials trials = [trial1, trial2] # Ignore these fields NO_COMPARE_FIELDS = { HOSTNAME, NODE_IP, TRIAL_ID, EXPERIMENT_TAG, PID, TIME_THIS_ITER_S, TIME_TOTAL_S, DONE, # This is ignored because FunctionAPI has different handling CHECKPOINT_DIR_NAME, "timestamp", "time_since_restore", "experiment_id", "date", } self.assertEqual(len(class_output), len(results)) self.assertEqual(len(function_output), len(results)) def as_comparable_result(result): return {k: v for k, v in result.items() if k not in NO_COMPARE_FIELDS} function_comparable = [ as_comparable_result(result) for result in function_output ] class_comparable = [as_comparable_result(result) for result in class_output] self.assertEqual(function_comparable, class_comparable) self.assertEqual(sum(t.get(DONE) for t in scheduler_notif), 2) self.assertEqual( as_comparable_result(scheduler_notif[0]), as_comparable_result(scheduler_notif[1]), ) # Make sure the last result is the same. self.assertEqual( as_comparable_result(trials[0].last_result), as_comparable_result(trials[1].last_result), ) return function_output, trials def testRegisterEnv(self): register_env("foo", lambda: None) self.assertRaises(TypeError, lambda: register_env("foo", 2)) def testRegisterEnvOverwrite(self): def train_fn(config): tune.report(dict(timesteps_total=100, done=True)) def train_fn2(config): tune.report(dict(timesteps_total=200, done=True)) register_trainable("f1", train_fn) register_trainable("f1", train_fn2) [trial] = run_experiments( { "foo": { "run": "f1", } } ) self.assertEqual(trial.status, Trial.TERMINATED) self.assertEqual(trial.last_result[TIMESTEPS_TOTAL], 200) def testRegisterTrainable(self): def train_fn(config): pass class A: pass class B(Trainable): pass register_trainable("foo", train_fn) Experiment("test", train_fn) register_trainable("foo", B) Experiment("test", B) self.assertRaises(TypeError, lambda: register_trainable("foo", B())) self.assertRaises(TuneError, lambda: Experiment("foo", B())) self.assertRaises(TypeError, lambda: register_trainable("foo", A)) self.assertRaises(TypeError, lambda: Experiment("foo", A)) def testRegisterTrainableThrice(self): def train_fn(config): pass register_trainable("foo", train_fn) register_trainable("foo", train_fn) register_trainable("foo", train_fn) def testTrainableCallable(self): def dummy_fn(config, steps): tune.report(dict(timesteps_total=steps, done=True)) steps = 500 register_trainable("test", partial(dummy_fn, steps=steps)) [trial] = run_experiments( { "foo": { "run": "test", } } ) self.assertEqual(trial.status, Trial.TERMINATED) self.assertEqual(trial.last_result[TIMESTEPS_TOTAL], steps) [trial] = tune.run(partial(dummy_fn, steps=steps)).trials self.assertEqual(trial.status, Trial.TERMINATED) self.assertEqual(trial.last_result[TIMESTEPS_TOTAL], steps) def testBuiltInTrainableResources(self): class B(Trainable): @classmethod def default_resource_request(cls, config): return PlacementGroupFactory( [{"CPU": config["cpu"], "GPU": config["gpu"]}] ) def step(self): return {"timesteps_this_iter": 1, "done": True} register_trainable("B", B) def f(cpus, gpus): return run_experiments( { "foo": { "run": "B", "config": { "cpu": cpus, "gpu": gpus, }, } }, )[0] # TODO(xwjiang): https://github.com/ray-project/ray/issues/19959 # self.assertEqual(f(0, 0).status, Trial.TERMINATED) # TODO(xwjiang): Make FailureInjectorCallback a test util. class FailureInjectorCallback(Callback): """Adds random failure injection to the TrialExecutor.""" def __init__(self, steps=4): self._step = 0 self.steps = steps def on_step_begin(self, iteration, trials, **info): self._step += 1 if self._step >= self.steps: raise RuntimeError def g(cpus, gpus): return run_experiments( { "foo": { "run": "B", "config": { "cpu": cpus, "gpu": gpus, }, } }, callbacks=[FailureInjectorCallback()], )[0] # Too large resource requests are infeasible # TODO(xwjiang): Throw TuneError after https://github.com/ray-project/ray/issues/19985. # noqa os.environ["TUNE_WARN_INSUFFICENT_RESOURCE_THRESHOLD_S"] = "0" with self.assertRaises(RuntimeError), patch( "ray.tune.execution.tune_controller.logger.warning" ) as warn_mock: self.assertRaises(TuneError, lambda: g(100, 100)) assert warn_mock.assert_called_once() with self.assertRaises(RuntimeError), patch( "ray.tune.execution.tune_controller.logger.warning" ) as warn_mock: self.assertRaises(TuneError, lambda: g(0, 100)) assert warn_mock.assert_called_once() with self.assertRaises(RuntimeError), patch( "ray.tune.execution.tune_controller.logger.warning" ) as warn_mock: self.assertRaises(TuneError, lambda: g(100, 0)) assert warn_mock.assert_called_once() def testRewriteEnv(self): def train_fn(config): tune.report(dict(timesteps_total=1)) register_trainable("f1", train_fn) [trial] = run_experiments( { "foo": { "run": "f1", "env": "CartPole-v0", } } ) self.assertEqual(trial.config["env"], "CartPole-v0") def testConfigPurity(self): def train_fn(config): assert config == {"a": "b"}, config tune.report(dict(timesteps_total=1)) register_trainable("f1", train_fn) run_experiments( { "foo": { "run": "f1", "config": {"a": "b"}, } } ) def testLongFilename(self): def train_fn(config): tune.report(dict(timesteps_total=1)) register_trainable("f1", train_fn) run_experiments( { "foo": { "run": "f1", "config": { "a" * 50: tune.sample_from(lambda spec: 5.0 / 7), "b" * 50: tune.sample_from(lambda spec: "long" * 40), }, } } ) def testBadParams(self): def f(): run_experiments({"foo": {}}) self.assertRaises(TuneError, f) def testBadParams2(self): def f(): run_experiments( { "foo": { "run": "asdf", "bah": "this param is not allowed", } } ) self.assertRaises(TuneError, f) def testBadParams3(self): def f(): run_experiments( { "foo": { "run": grid_search("invalid grid search"), } } ) self.assertRaises(TuneError, f) def testBadParams4(self): def f(): run_experiments( { "foo": { "run": "asdf", } } ) self.assertRaises(TuneError, f) def testBadParams6(self): register_trainable("f1", lambda x: x) def f(): run_experiments({"foo": {"run": "f1", "invalid_key": {"asdf": 1}}}) self.assertRaises(TuneError, f) def testNestedStoppingReturn(self): def train_fn(config): for i in range(10): tune.report(dict(test={"test1": {"test2": i}})) [trial] = tune.run(train_fn, stop={"test": {"test1": {"test2": 6}}}).trials self.assertTrue( "test" in trial.last_result and "test1" in trial.last_result["test"] and "test2" in trial.last_result["test"]["test1"] ) [trial] = tune.run(train_fn, stop={"test/test1/test2": 6}).trials self.assertEqual(trial.last_result["training_iteration"], 7) def testStoppingFunction(self): def train_fn(config): for i in range(10): tune.report(dict(test=i)) def stop(trial_id, result): return result["test"] > 6 [trial] = tune.run(train_fn, stop=stop).trials self.assertEqual(trial.last_result["training_iteration"], 8) def testStoppingMemberFunction(self): def train_fn(config): for i in range(10): tune.report(dict(test=i)) class Stopclass: def stop(self, trial_id, result): return result["test"] > 6 [trial] = tune.run(train_fn, stop=Stopclass().stop).trials self.assertEqual(trial.last_result["training_iteration"], 8) def testStopper(self): def train_fn(config): for i in range(10): tune.report(dict(test=i)) class CustomStopper(Stopper): def __init__(self): self._count = 0 def __call__(self, trial_id, result): print("called") self._count += 1 return result["test"] > 6 def stop_all(self): return self._count > 5 trials = tune.run(train_fn, num_samples=5, stop=CustomStopper()).trials self.assertTrue(all(t.status == Trial.TERMINATED for t in trials)) self.assertTrue( any(t.last_result.get("training_iteration") is None for t in trials) ) def testEarlyStopping(self): def train_fn(config): tune.report(dict(test=0)) top = 3 with self.assertRaises(ValueError): ExperimentPlateauStopper("test", top=0) with self.assertRaises(ValueError): ExperimentPlateauStopper("test", top="0") with self.assertRaises(ValueError): ExperimentPlateauStopper("test", std=0) with self.assertRaises(ValueError): ExperimentPlateauStopper("test", patience=-1) with self.assertRaises(ValueError): ExperimentPlateauStopper("test", std="0") with self.assertRaises(ValueError): ExperimentPlateauStopper("test", mode="0") stopper = ExperimentPlateauStopper("test", top=top, mode="min") analysis = tune.run(train_fn, num_samples=10, stop=stopper) self.assertTrue(all(t.status == Trial.TERMINATED for t in analysis.trials)) self.assertTrue(len(analysis.dataframe(metric="test", mode="max")) <= top) patience = 5 stopper = ExperimentPlateauStopper( "test", top=top, mode="min", patience=patience ) analysis = tune.run(train_fn, num_samples=20, stop=stopper) self.assertTrue(all(t.status == Trial.TERMINATED for t in analysis.trials)) self.assertTrue(len(analysis.dataframe(metric="test", mode="max")) <= patience) stopper = ExperimentPlateauStopper("test", top=top, mode="min") analysis = tune.run(train_fn, num_samples=10, stop=stopper) self.assertTrue(all(t.status == Trial.TERMINATED for t in analysis.trials)) self.assertTrue(len(analysis.dataframe(metric="test", mode="max")) <= top) def testBadStoppingFunction(self): def train_fn(config): for i in range(10): tune.report(dict(test=i)) class CustomStopper: def stop(self, result): return result["test"] > 6 def stop(result): return result["test"] > 6 with self.assertRaises(TuneError): tune.run(train_fn, stop=CustomStopper().stop) with self.assertRaises(TuneError): tune.run(train_fn, stop=stop) def testMaximumIterationStopper(self): def train_fn(config): for i in range(10): tune.report(dict(it=i)) stopper = MaximumIterationStopper(max_iter=6) out = tune.run(train_fn, stop=stopper) self.assertEqual(out.trials[0].last_result[TRAINING_ITERATION], 6) def testTrialPlateauStopper(self): def train_fn(config): tune.report(dict(_metric=10.0)) tune.report(dict(_metric=11.0)) tune.report(dict(_metric=12.0)) for i in range(10): tune.report(dict(_metric=20.0)) # num_results = 4, no other constraints --> early stop after 7 stopper = TrialPlateauStopper(metric="_metric", num_results=4) out = tune.run(train_fn, stop=stopper) self.assertEqual(out.trials[0].last_result[TRAINING_ITERATION], 7) # num_results = 4, grace period 9 --> early stop after 9 stopper = TrialPlateauStopper(metric="_metric", num_results=4, grace_period=9) out = tune.run(train_fn, stop=stopper) self.assertEqual(out.trials[0].last_result[TRAINING_ITERATION], 9) # num_results = 4, min_metric = 22 --> full 13 iterations stopper = TrialPlateauStopper( metric="_metric", num_results=4, metric_threshold=22.0, mode="max" ) out = tune.run(train_fn, stop=stopper) self.assertEqual(out.trials[0].last_result[TRAINING_ITERATION], 13) def testCustomTrialDir(self): def train_fn(config): for i in range(10): tune.report(dict(test=i)) custom_name = "TRAIL_TRIAL" def custom_trial_dir(trial): return custom_name trials = tune.run( train_fn, config={"t1": tune.grid_search([1, 2, 3])}, trial_dirname_creator=custom_trial_dir, storage_path=self.tmpdir, ).trials logdirs = {t.local_path for t in trials} assert len(logdirs) == 3 assert all(custom_name in dirpath for dirpath in logdirs) def testTrialDirRegression(self): def train_fn(config): for i in range(10): tune.report(dict(test=i)) trials = tune.run( train_fn, config={"t1": tune.grid_search([1, 2, 3])}, storage_path=self.tmpdir, ).trials logdirs = {t.local_path for t in trials} for i in [1, 2, 3]: assert any(f"t1={i}" in dirpath for dirpath in logdirs) for t in trials: assert any(t.trainable_name in dirpath for dirpath in logdirs) def testEarlyReturn(self): def train_fn(config): tune.report(dict(timesteps_total=100, done=True)) time.sleep(99999) register_trainable("f1", train_fn) [trial] = run_experiments( { "foo": { "run": "f1", } } ) self.assertEqual(trial.status, Trial.TERMINATED) self.assertEqual(trial.last_result[TIMESTEPS_TOTAL], 100) def testReporterNoUsage(self): def run_task(config): print("hello") experiment = Experiment(run=run_task, name="ray_crash_repro") [trial] = ray.tune.run(experiment).trials print(trial.last_result) self.assertEqual(trial.last_result[DONE], True) def testRerun(self): tmpdir = tempfile.mkdtemp() self.addCleanup(lambda: shutil.rmtree(tmpdir)) def test(config): tid = config["id"] fail = config["fail"] marker = os.path.join(tmpdir, f"t{tid}-{fail}.log") if not os.path.exists(marker) and fail: open(marker, "w").close() raise ValueError for i in range(10): time.sleep(0.1) tune.report(dict(hello=123)) config = dict( name="hi-2", config={ "fail": tune.grid_search([True, False]), "id": tune.grid_search(list(range(5))), }, verbose=1, storage_path=tmpdir, ) trials = tune.run(test, raise_on_failed_trial=False, **config).trials self.assertEqual(Counter(t.status for t in trials)["ERROR"], 5) new_trials = tune.run(test, resume="AUTO+ERRORED_ONLY", **config).trials self.assertEqual(Counter(t.status for t in new_trials)["ERROR"], 0) def testTrialInfoAccess(self): class TestTrainable(Trainable): def step(self): result = { "name": self.trial_name, "trial_id": self.trial_id, "trial_resources": self.trial_resources, } print(result) return result analysis = tune.run( TestTrainable, stop={TRAINING_ITERATION: 1}, resources_per_trial=PlacementGroupFactory([{"CPU": 1}]), ) trial = analysis.trials[0] self.assertEqual(trial.last_result.get("name"), str(trial)) self.assertEqual(trial.last_result.get("trial_id"), trial.trial_id) self.assertEqual( trial.last_result.get("trial_resources"), trial.placement_group_factory ) def testTrialInfoAccessFunction(self): def train_fn(config): tune.report( dict( name=tune.get_context().get_trial_name(), trial_id=tune.get_context().get_trial_id(), trial_resources=tune.get_context().get_trial_resources(), ) ) analysis = tune.run( train_fn, stop={TRAINING_ITERATION: 1}, resources_per_trial=PlacementGroupFactory([{"CPU": 1}]), ) trial = analysis.trials[0] self.assertEqual(trial.last_result.get("name"), str(trial)) self.assertEqual(trial.last_result.get("trial_id"), trial.trial_id) self.assertEqual( trial.last_result.get("trial_resources"), trial.placement_group_factory ) def track_train(config): tune.report( dict( name=tune.get_context().get_trial_name(), trial_id=tune.get_context().get_trial_id(), trial_resources=tune.get_context().get_trial_resources(), ) ) analysis = tune.run( track_train, stop={TRAINING_ITERATION: 1}, resources_per_trial=PlacementGroupFactory([{"CPU": 1}]), ) trial = analysis.trials[0] self.assertEqual(trial.last_result.get("name"), str(trial)) self.assertEqual(trial.last_result.get("trial_id"), trial.trial_id) self.assertEqual( trial.last_result.get("trial_resources"), trial.placement_group_factory ) def testLotsOfStops(self): tmpdir = self.tmpdir class TestTrainable(Trainable): def step(self): result = {"name": self.trial_name, "trial_id": self.trial_id} return result def cleanup(self): time.sleep(0.3) open(os.path.join(tmpdir, f"marker-{self.trial_id}"), "a").close() return 1 num_samples = 10 tune.run(TestTrainable, num_samples=num_samples, stop={TRAINING_ITERATION: 1}) markers = [m for m in os.listdir(tmpdir) if "marker" in m] assert len(markers) == num_samples def testReportTimeStep(self): # Test that no timestep count are logged if never the Trainable never # returns any. results1 = [dict(mean_accuracy=5, done=i == 99) for i in range(100)] logs1, _ = self.checkAndReturnConsistentLogs(results1) self.assertTrue(all(TIMESTEPS_TOTAL not in log for log in logs1)) # Test that no timesteps_this_iter are logged if only timesteps_total # are returned. results2 = [dict(timesteps_total=5, done=i == 9) for i in range(10)] logs2, _ = self.checkAndReturnConsistentLogs(results2) # Re-run the same trials but with added delay. This is to catch some # inconsistent timestep counting that was present in the multi-threaded # FunctionTrainable. This part of the test can be removed once the # multi-threaded FunctionTrainable is removed from ray/tune. # TODO: remove once the multi-threaded function runner is gone. logs2, _ = self.checkAndReturnConsistentLogs(results2, 0.5) # check all timesteps_total report the same value self.assertTrue(all(log[TIMESTEPS_TOTAL] == 5 for log in logs2)) # check that none of the logs report timesteps_this_iter self.assertFalse(any(hasattr(log, TIMESTEPS_THIS_ITER) for log in logs2)) # Test that timesteps_total and episodes_total are reported when # timesteps_this_iter and episodes_this_iter are provided by user, # despite only return zeros. results3 = [ dict(timesteps_this_iter=0, episodes_this_iter=0) for i in range(10) ] logs3, _ = self.checkAndReturnConsistentLogs(results3) self.assertTrue(all(log[TIMESTEPS_TOTAL] == 0 for log in logs3)) self.assertTrue(all(log[EPISODES_TOTAL] == 0 for log in logs3)) # Test that timesteps_total and episodes_total are properly counted # when timesteps_this_iter and episodes_this_iter report non-zero # values. results4 = [ dict(timesteps_this_iter=3, episodes_this_iter=i) for i in range(10) ] logs4, _ = self.checkAndReturnConsistentLogs(results4) # The last reported result should not be double-logged. self.assertEqual(logs4[-1][TIMESTEPS_TOTAL], 30) self.assertNotEqual(logs4[-2][TIMESTEPS_TOTAL], logs4[-1][TIMESTEPS_TOTAL]) self.assertEqual(logs4[-1][EPISODES_TOTAL], 45) self.assertNotEqual(logs4[-2][EPISODES_TOTAL], logs4[-1][EPISODES_TOTAL]) def testAllValuesReceived(self): results1 = [ dict(timesteps_total=(i + 1), my_score=i**2, done=i == 4) for i in range(5) ] logs1, _ = self.checkAndReturnConsistentLogs(results1) # check if the correct number of results were reported self.assertEqual(len(logs1), len(results1)) def check_no_missing(reported_result, result): common_results = [reported_result[k] == result[k] for k in result] return all(common_results) # check that no result was dropped or modified complete_results = [ check_no_missing(log, result) for log, result in zip(logs1, results1) ] self.assertTrue(all(complete_results)) # check if done was logged exactly once self.assertEqual(len([r for r in logs1 if r.get("done")]), 1) def testNoDoneReceived(self): # repeat same test but without explicitly reporting done=True results1 = [dict(timesteps_total=(i + 1), my_score=i**2) for i in range(5)] logs1, trials = self.checkAndReturnConsistentLogs(results1) # check if the correct number of results were reported. self.assertEqual(len(logs1), len(results1)) def check_no_missing(reported_result, result): common_results = [reported_result[k] == result[k] for k in result] return all(common_results) # check that no result was dropped or modified complete_results1 = [ check_no_missing(log, result) for log, result in zip(logs1, results1) ] self.assertTrue(all(complete_results1)) def _testDurableTrainable(self, trainable, function=False, cleanup=True): remote_checkpoint_dir = "mock:///unit-test/bucket" fs, fs_path = get_fs_and_path(remote_checkpoint_dir) tempdir = tempfile.mkdtemp() _create_directory(fs=fs, fs_path=fs_path) storage = StorageContext( storage_path=remote_checkpoint_dir, experiment_dir_name="exp", trial_dir_name="trial", ) storage.storage_local_path = tempdir test_trainable = trainable(storage=storage) result = test_trainable.train() self.assertEqual(result["metric"], 1) checkpoint_path = test_trainable.save() result = test_trainable.train() self.assertEqual(result["metric"], 2) result = test_trainable.train() self.assertEqual(result["metric"], 3) result = test_trainable.train() self.assertEqual(result["metric"], 4) shutil.rmtree(tempdir) shutdown_session() if not function: test_trainable.state["hi"] = 2 test_trainable.restore(checkpoint_path) self.assertEqual(test_trainable.state["hi"], 1) else: # Cannot re-use function trainable, create new test_trainable = trainable(storage=storage) test_trainable.restore(checkpoint_path) result = test_trainable.train() self.assertEqual(result["metric"], 2) def testDurableTrainableClass(self): class TestTrain(Trainable): def setup(self, config): self.state = {"hi": 1, "iter": 0} def step(self): self.state["iter"] += 1 return { "timesteps_this_iter": 1, "metric": self.state["iter"], "done": self.state["iter"] > 3, } def save_checkpoint(self, path): return self.state def load_checkpoint(self, state): self.state = state self._testDurableTrainable(TestTrain) def testDurableTrainableFunction(self): def test_train(config): state = {"hi": 1, "iter": 0} if tune.get_checkpoint(): state = load_dict_checkpoint(tune.get_checkpoint()) for i in range(4): state["iter"] += 1 with create_dict_checkpoint(state) as checkpoint: tune.report( { "timesteps_this_iter": 1, "metric": state["iter"], "done": state["iter"] > 3, }, checkpoint=checkpoint, ) self._testDurableTrainable(wrap_function(test_train), function=True) def testCheckpointDict(self): class TestTrain(Trainable): def setup(self, config): self.state = {"hi": 1} def step(self): return {"timesteps_this_iter": 1, "done": True} def save_checkpoint(self, path): return self.state def load_checkpoint(self, state): self.state = state test_trainable = TestTrain() result = test_trainable.train() result = test_trainable.save() test_trainable.state["hi"] = 2 test_trainable.restore(result) self.assertEqual(test_trainable.state["hi"], 1) trials = run_experiments( { "foo": { "run": TestTrain, "checkpoint_config": CheckpointConfig(checkpoint_at_end=True), } } ) for trial in trials: self.assertEqual(trial.status, Trial.TERMINATED) self.assertTrue(trial.has_checkpoint()) def testMultipleCheckpoints(self): class TestTrain(Trainable): def setup(self, config): self.state = {"hi": 1, "iter": 0} def step(self): self.state["iter"] += 1 return {"timesteps_this_iter": 1, "done": True} def save_checkpoint(self, path): return self.state def load_checkpoint(self, state): self.state = state test_trainable = TestTrain() test_trainable.train() checkpoint_1 = test_trainable.save() test_trainable.train() checkpoint_2 = test_trainable.save() self.assertNotEqual(checkpoint_1, checkpoint_2) test_trainable.restore(checkpoint_2) self.assertEqual(test_trainable.state["iter"], 2) test_trainable.restore(checkpoint_1) self.assertEqual(test_trainable.state["iter"], 1) trials = run_experiments( { "foo": { "run": TestTrain, "checkpoint_config": CheckpointConfig(checkpoint_at_end=True), } } ) for trial in trials: self.assertEqual(trial.status, Trial.TERMINATED) self.assertTrue(trial.has_checkpoint()) def testLogToFile(self): def train_fn(config): import sys from ray import logger for i in range(10): tune.report(dict(timesteps_total=i)) print("PRINT_STDOUT") print("PRINT_STDERR", file=sys.stderr) logger.info("LOG_STDERR") register_trainable("f1", train_fn) # Do not log to file [trial] = tune.run("f1", log_to_file=False).trials trial_working_dir = trial.storage.trial_working_directory self.assertFalse( os.path.exists( os.path.join(trial.storage.trial_working_directory, "stdout") ) ) self.assertFalse( os.path.exists( os.path.join(trial.storage.trial_working_directory, "stderr") ) ) # Log to default files [trial] = tune.run("f1", log_to_file=True).trials trial_working_dir = trial.storage.trial_working_directory self.assertTrue(os.path.exists(os.path.join(trial_working_dir, "stdout"))) self.assertTrue(os.path.exists(os.path.join(trial_working_dir, "stderr"))) with open(os.path.join(trial_working_dir, "stdout"), "rt") as fp: content = fp.read() self.assertIn("PRINT_STDOUT", content) with open(os.path.join(trial_working_dir, "stderr"), "rt") as fp: content = fp.read() self.assertIn("PRINT_STDERR", content) self.assertIn("LOG_STDERR", content) # Log to one file [trial] = tune.run("f1", log_to_file="combined").trials trial_working_dir = trial.storage.trial_working_directory self.assertFalse(os.path.exists(os.path.join(trial_working_dir, "stdout"))) self.assertFalse(os.path.exists(os.path.join(trial_working_dir, "stderr"))) self.assertTrue(os.path.exists(os.path.join(trial_working_dir, "combined"))) with open(os.path.join(trial_working_dir, "combined"), "rt") as fp: content = fp.read() self.assertIn("PRINT_STDOUT", content) self.assertIn("PRINT_STDERR", content) self.assertIn("LOG_STDERR", content) # Log to two files [trial] = tune.run("f1", log_to_file=("alt.stdout", "alt.stderr")).trials trial_working_dir = trial.storage.trial_working_directory self.assertFalse(os.path.exists(os.path.join(trial_working_dir, "stdout"))) self.assertFalse(os.path.exists(os.path.join(trial_working_dir, "stderr"))) self.assertTrue(os.path.exists(os.path.join(trial_working_dir, "alt.stdout"))) self.assertTrue(os.path.exists(os.path.join(trial_working_dir, "alt.stderr"))) with open(os.path.join(trial_working_dir, "alt.stdout"), "rt") as fp: content = fp.read() self.assertIn("PRINT_STDOUT", content) with open(os.path.join(trial_working_dir, "alt.stderr"), "rt") as fp: content = fp.read() self.assertIn("PRINT_STDERR", content) self.assertIn("LOG_STDERR", content) def testTimeout(self): import datetime from ray.tune.stopper import TimeoutStopper def train_fn(config): for i in range(20): tune.report(dict(metric=i)) time.sleep(1) register_trainable("f1", train_fn) start = time.time() tune.run("f1", time_budget_s=5) diff = time.time() - start self.assertLess(diff, 10) # Metric should fire first start = time.time() tune.run("f1", stop={"metric": 3}, time_budget_s=7) diff = time.time() - start self.assertLess(diff, 7) # Timeout should fire first start = time.time() tune.run("f1", stop={"metric": 10}, time_budget_s=5) diff = time.time() - start self.assertLess(diff, 10) # Combined stopper. Shorter timeout should win. start = time.time() tune.run( "f1", stop=TimeoutStopper(10), time_budget_s=datetime.timedelta(seconds=3) ) diff = time.time() - start self.assertLess(diff, 9) def testInfiniteTrials(self): def train_fn(config): time.sleep(0.5) tune.report(dict(_metric=np.random.uniform(-10.0, 10.0))) start = time.time() out = tune.run(train_fn, num_samples=-1, time_budget_s=10) taken = time.time() - start # Allow for init time overhead self.assertLessEqual(taken, 20.0) self.assertGreaterEqual(len(out.trials), 0) status = dict(Counter([trial.status for trial in out.trials])) self.assertGreaterEqual(status["TERMINATED"], 1) self.assertLessEqual(status.get("PENDING", 0), 1) def testMetricCheckingEndToEnd(self): def train_fn(config): tune.report(dict(val=4, second=8)) def train2(config): return os.environ["TUNE_DISABLE_STRICT_METRIC_CHECKING"] = "0" # `acc` is not reported, should raise with self.assertRaises(TuneError): # The trial runner raises a ValueError, but the experiment fails # with a TuneError tune.run(train_fn, metric="acc") # `val` is reported, should not raise tune.run(train_fn, metric="val") # Run does not report anything, should not raise tune.run(train2, metric="val") # Only the scheduler requires a metric with self.assertRaises(TuneError): tune.run( train_fn, scheduler=AsyncHyperBandScheduler(metric="acc", mode="max") ) tune.run(train_fn, scheduler=AsyncHyperBandScheduler(metric="val", mode="max")) # Only the search alg requires a metric with self.assertRaises(TuneError): tune.run( train_fn, config={"a": tune.choice([1, 2])}, search_alg=HyperOptSearch(metric="acc", mode="max"), ) # Metric is passed tune.run( train_fn, config={"a": tune.choice([1, 2])}, search_alg=HyperOptSearch(metric="val", mode="max"), ) os.environ["TUNE_DISABLE_STRICT_METRIC_CHECKING"] = "1" # With strict metric checking disabled, this should not raise tune.run(train_fn, metric="acc") def testTrialDirCreation(self): def test_trial_dir(config): return 1.0 # Per default, the directory should be named `test_trial_dir_{date}` with tempfile.TemporaryDirectory() as tmp_dir: tune.run(test_trial_dir, storage_path=tmp_dir) subdirs = list(os.listdir(tmp_dir)) self.assertNotIn("test_trial_dir", subdirs) found = False for subdir in subdirs: if subdir.startswith("test_trial_dir_"): # Date suffix found = True break self.assertTrue(found) # If we set an explicit name, no date should be appended with tempfile.TemporaryDirectory() as tmp_dir: tune.run(test_trial_dir, storage_path=tmp_dir, name="my_test_exp") subdirs = list(os.listdir(tmp_dir)) self.assertIn("my_test_exp", subdirs) found = False for subdir in subdirs: if subdir.startswith("my_test_exp_"): # Date suffix found = True break self.assertFalse(found) # Don't append date if we set the env variable os.environ["TUNE_DISABLE_DATED_SUBDIR"] = "1" with tempfile.TemporaryDirectory() as tmp_dir: tune.run(test_trial_dir, storage_path=tmp_dir) subdirs = list(os.listdir(tmp_dir)) self.assertIn("test_trial_dir", subdirs) found = False for subdir in subdirs: if subdir.startswith("test_trial_dir_"): # Date suffix found = True break self.assertFalse(found) def testWithParameters(self): class Data: def __init__(self): self.data = [0] * 500_000 data = Data() data.data[100] = 1 class TestTrainable(Trainable): def setup(self, config, data): self.data = data.data self.data[101] = 2 # Changes are local def step(self): return dict(metric=len(self.data), hundred=self.data[100], done=True) trial_1, trial_2 = tune.run( tune.with_parameters(TestTrainable, data=data), num_samples=2 ).trials self.assertEqual(data.data[101], 0) self.assertEqual(trial_1.last_result["metric"], 500_000) self.assertEqual(trial_1.last_result["hundred"], 1) self.assertEqual(trial_2.last_result["metric"], 500_000) self.assertEqual(trial_2.last_result["hundred"], 1) self.assertTrue(str(trial_1).startswith("TestTrainable")) def testWithParameters2(self): class Data: def __init__(self): import numpy as np self.data = np.random.rand((2 * 1024 * 1024)) class TestTrainable(Trainable): def setup(self, config, data): self.data = data.data def step(self): return dict(metric=len(self.data), done=True) trainable = tune.with_parameters(TestTrainable, data=Data()) # ray.cloudpickle will crash for some reason import cloudpickle as cp dumped = cp.dumps(trainable) assert sys.getsizeof(dumped) < 100 * 1024 def testWithParameters3(self): class Data: def __init__(self): import numpy as np self.data = np.random.rand((2 * 1024 * 1024)) class TestTrainable(Trainable): def setup(self, config, data): self.data = data.data def step(self): return dict(metric=len(self.data), done=True) new_data = Data() ref = ray.put(new_data) trainable = tune.with_parameters(TestTrainable, data=ref) # ray.cloudpickle will crash for some reason import cloudpickle as cp dumped = cp.dumps(trainable) assert sys.getsizeof(dumped) < 100 * 1024 @pytest.fixture def ray_start_2_cpus(): address_info = ray.init(num_cpus=2) yield address_info # The code after the yield will run as teardown code. ray.shutdown() @pytest.fixture def ray_start_2_cpus_2_gpus(): address_info = ray.init(num_cpus=2, num_gpus=2) yield address_info # The code after the yield will run as teardown code. ray.shutdown() @pytest.mark.parametrize("num_gpus", [1, 2]) def test_with_resources_dict(ray_start_2_cpus_2_gpus, num_gpus): def train_fn(config): return len(ray.get_gpu_ids()) [trial] = tune.run( tune.with_resources(train_fn, resources={"gpu": num_gpus}) ).trials assert trial.last_result["_metric"] == num_gpus @pytest.mark.parametrize("num_gpus", [1, 2]) def test_with_resources_pgf(ray_start_2_cpus_2_gpus, num_gpus): def train_fn(config): return len(ray.get_gpu_ids()) [trial] = tune.run( tune.with_resources( train_fn, resources=PlacementGroupFactory([{"GPU": num_gpus}]) ) ).trials assert trial.last_result["_metric"] == num_gpus @pytest.mark.parametrize("num_gpus", [1, 2]) def test_with_resources_fn(ray_start_2_cpus_2_gpus, num_gpus): def train_fn(config): return len(ray.get_gpu_ids()) [trial] = tune.run( tune.with_resources( train_fn, resources=lambda config: PlacementGroupFactory( [{"GPU": config["use_gpus"]}] ), ), config={"use_gpus": num_gpus}, ).trials assert trial.last_result["_metric"] == num_gpus @pytest.mark.parametrize("num_gpus", [1, 2]) def test_with_resources_class_fn(ray_start_2_cpus_2_gpus, num_gpus): class MyTrainable(tune.Trainable): def step(self): return {"_metric": len(ray.get_gpu_ids()), "done": True} def save_checkpoint(self, checkpoint_dir: str): pass def load_checkpoint(self, checkpoint): pass @classmethod def default_resource_request(cls, config): # This will be overwritten by tune.with_trainables() return PlacementGroupFactory([{"CPU": 2, "GPU": 0}]) [trial] = tune.run( tune.with_resources( MyTrainable, resources=lambda config: PlacementGroupFactory( [{"GPU": config["use_gpus"]}] ), ), config={"use_gpus": num_gpus}, ).trials assert trial.last_result["_metric"] == num_gpus @pytest.mark.parametrize("num_gpus", [1, 2]) def test_with_resources_class_method(ray_start_2_cpus_2_gpus, num_gpus): class Worker: def train_fn(self, config): return len(ray.get_gpu_ids()) worker = Worker() [trial] = tune.run( tune.with_resources( worker.train_fn, resources=lambda config: PlacementGroupFactory( [{"GPU": config["use_gpus"]}] ), ), config={"use_gpus": num_gpus}, ).trials assert trial.last_result["_metric"] == num_gpus @pytest.mark.parametrize("num_gpus", [1, 2]) def test_with_resources_and_parameters_fn(ray_start_2_cpus_2_gpus, num_gpus): def train_fn(config, extra_param=None): assert extra_param is not None, "Missing extra parameter." print(ray.get_runtime_context().get_assigned_resources()) return {"num_gpus": len(ray.get_gpu_ids())} # Nesting `tune.with_parameters` and `tune.with_resources` should respect # the resource specifications. trainable = tune.with_resources( tune.with_parameters(train_fn, extra_param="extra"), {"gpu": num_gpus}, ) tuner = tune.Tuner(trainable) results = tuner.fit() print(results[0].metrics) assert results[0].metrics["num_gpus"] == num_gpus # The other order of nesting should work the same. trainable = tune.with_parameters( tune.with_resources(train_fn, {"gpu": num_gpus}), extra_param="extra" ) tuner = tune.Tuner(trainable) results = tuner.fit() assert results[0].metrics["num_gpus"] == num_gpus
TrainableFunctionApiTest
python
getsentry__sentry
src/sentry/core/endpoints/organization_details.py
{ "start": 37405, "end": 51952 }
class ____(OrganizationEndpoint): publish_status = { "DELETE": ApiPublishStatus.PRIVATE, "GET": ApiPublishStatus.PUBLIC, "PUT": ApiPublishStatus.PUBLIC, } @extend_schema( operation_id="Retrieve an Organization", parameters=[GlobalParams.ORG_ID_OR_SLUG, OrganizationParams.DETAILED], request=None, responses={ 200: org_serializers.OrganizationSerializer, 401: RESPONSE_UNAUTHORIZED, 403: RESPONSE_FORBIDDEN, 404: RESPONSE_NOT_FOUND, }, examples=OrganizationExamples.RETRIEVE_ORGANIZATION, ) def get(self, request: Request, organization: Organization) -> Response: """ Return details on an individual organization, including various details such as membership access and teams. """ # This param will be used to determine if we should include feature flags in the response include_feature_flags = request.GET.get("include_feature_flags", "0") != "0" serializer = org_serializers.OrganizationSerializer if request.access.has_scope("org:read") or is_active_staff(request): is_detailed = request.GET.get("detailed", "1") != "0" serializer = org_serializers.DetailedOrganizationSerializer if is_detailed: serializer = org_serializers.DetailedOrganizationSerializerWithProjectsAndTeams context = serialize( organization, request.user, serializer(), access=request.access, include_feature_flags=include_feature_flags, ) return self.respond(context) @extend_schema( operation_id="Update an Organization", parameters=[ GlobalParams.ORG_ID_OR_SLUG, ], request=OrganizationDetailsPutSerializer, responses={ 200: DetailedOrganizationSerializerWithProjectsAndTeams, 400: RESPONSE_BAD_REQUEST, 401: RESPONSE_UNAUTHORIZED, 403: RESPONSE_FORBIDDEN, 404: RESPONSE_NOT_FOUND, 409: RESPONSE_CONFLICT, 413: OpenApiResponse(description="Image too large."), }, examples=OrganizationExamples.UPDATE_ORGANIZATION, ) def put(self, request: Request, organization: Organization) -> Response: """ Update various attributes and configurable settings for the given organization. """ from sentry import features # This param will be used to determine if we should include feature flags in the response include_feature_flags = request.GET.get("include_feature_flags", "0") != "0" # We don't need to check for staff here b/c the _admin portal uses another endpoint to update orgs serializer_cls: type[OwnerOrganizationSerializer | OrganizationSerializer] = ( OwnerOrganizationSerializer if request.access.has_scope("org:admin") else OrganizationSerializer ) was_pending_deletion = organization.status in DELETION_STATUSES enabling_codecov = "codecovAccess" in request.data and request.data["codecovAccess"] if enabling_codecov: if not features.has("organizations:codecov-integration", organization): return self.respond({"detail": ERR_PLAN_REQUIRED}, status=status.HTTP_403_FORBIDDEN) has_integration, error = has_codecov_integration(organization) if not has_integration: return self.respond( {"codecovAccess": [error]}, status=status.HTTP_400_BAD_REQUEST, ) serializer = serializer_cls( data=request.data, partial=True, context={"organization": organization, "user": request.user, "request": request}, ) if serializer.is_valid(): slug_change_requested = "slug" in request.data and request.data["slug"] # Capture previous console platforms before serializer.save() updates them previous_console_platforms = None if "enabledConsolePlatforms" in request.data: previous_console_platforms = organization.get_option( "sentry:enabled_console_platforms", [] ) # Attempt slug change first as it's a more complex, control-silo driven workflow. if slug_change_requested: slug = request.data["slug"] try: organization_provisioning_service.change_organization_slug( organization_id=organization.id, slug=slug ) except OrganizationSlugCollisionException: return self.respond( {"slug": ["An organization with this slug already exists."]}, status=status.HTTP_409_CONFLICT, ) with transaction.atomic(router.db_for_write(Organization)): organization, changed_data = serializer.save() if request.access.has_scope("org:write") and has_custom_dynamic_sampling(organization): is_org_mode = is_organization_mode_sampling(organization) # If the sampling mode was changed, adapt the project and org options accordingly if "samplingMode" in changed_data: with transaction.atomic(router.db_for_write(ProjectOption)): if is_project_mode_sampling(organization): self._compute_project_target_sample_rates(request, organization) organization.delete_option("sentry:target_sample_rate") changed_data["samplingMode"] = "to Advanced Mode" elif is_org_mode: if "targetSampleRate" in changed_data: organization.update_option( "sentry:target_sample_rate", serializer.validated_data["targetSampleRate"], ) changed_data["samplingMode"] = "to Default Mode" ProjectOption.objects.filter( project__organization_id=organization.id, key="sentry:target_sample_rate", ).delete() # If the target sample rate for the org was changed, update the org option if is_org_mode and "targetSampleRate" in changed_data: organization.update_option( "sentry:target_sample_rate", serializer.validated_data["targetSampleRate"] ) # If the sampling mode was changed to org mode or the target sample rate was changed (or both), # trigger the rebalancing of project sample rates. if is_org_mode and ( "samplingMode" in changed_data or "targetSampleRate" in changed_data ): boost_low_volume_projects_of_org_with_query.delay( organization.id, ) if is_org_mode and "defaultAutofixAutomationTuning" in changed_data: organization.update_option( "sentry:default_autofix_automation_tuning", serializer.validated_data["defaultAutofixAutomationTuning"], ) if is_org_mode and "defaultSeerScannerAutomation" in changed_data: organization.update_option( "sentry:default_seer_scanner_automation", serializer.validated_data["defaultSeerScannerAutomation"], ) if was_pending_deletion: self.create_audit_entry( request=request, organization=organization, target_object=organization.id, event=audit_log.get_event_id("ORG_RESTORE"), data=organization.get_audit_log_data(), ) RegionScheduledDeletion.cancel(organization) elif changed_data: if "enabledConsolePlatforms" in changed_data: create_console_platform_audit_log( request, organization, previous_console_platforms, serializer.validated_data.get("enabledConsolePlatforms", []), ) del changed_data["enabledConsolePlatforms"] if changed_data: self.create_audit_entry( request=request, organization=organization, target_object=organization.id, event=audit_log.get_event_id("ORG_EDIT"), data=changed_data, ) context = serialize( organization, request.user, org_serializers.DetailedOrganizationSerializerWithProjectsAndTeams(), access=request.access, include_feature_flags=include_feature_flags, ) return self.respond(context) return self.respond(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def _compute_project_target_sample_rates(self, request: Request, organization: Organization): # TODO: this will take a long time for organizations with a lot of projects # so we need to refactor this into an async task we can run and observe org_id = organization.id measure = SamplingMeasure.TRANSACTIONS if options.get("dynamic-sampling.check_span_feature_flag"): span_org_ids = options.get("dynamic-sampling.measure.spans") or [] if org_id in span_org_ids: measure = SamplingMeasure.SPANS projects_with_tx_count_and_rates = [] for chunk in query_project_counts_by_org( [org_id], measure, query_interval=timedelta(days=30) ): for row in chunk: projects_with_tx_count_and_rates.append(row[1:]) rebalanced_projects = calculate_sample_rates_of_projects( org_id, projects_with_tx_count_and_rates ) project_ids = set( Project.objects.filter(organization_id=org_id, status=ObjectStatus.ACTIVE).values_list( "id", flat=True ) ) if rebalanced_projects is not None: for rebalanced_item in rebalanced_projects: if int(rebalanced_item.id) in project_ids: ProjectOption.objects.create_or_update( project_id=rebalanced_item.id, key="sentry:target_sample_rate", values={"value": round(rebalanced_item.new_sample_rate, 4)}, ) def handle_delete(self, request: Request, organization: Organization): """ This method exists as a way for getsentry to override this endpoint with less duplication. """ if not request.user.is_authenticated: return self.respond({"detail": ERR_NO_USER}, status=401) org_delete_response = organization_service.delete_organization( organization_id=organization.id, user=serialize_generic_user(request.user) ) if ( org_delete_response.response_state == RpcOrganizationDeleteState.CANNOT_REMOVE_DEFAULT_ORG or organization.is_default ): return self.respond({"detail": ERR_DEFAULT_ORG}, status=400) if ( org_delete_response.response_state == RpcOrganizationDeleteState.OWNS_PUBLISHED_INTEGRATION ): return self.respond({"detail": ERR_3RD_PARTY_PUBLISHED_APP}, status=400) if org_delete_response.response_state == RpcOrganizationDeleteState.PENDING_DELETION: organization.status = OrganizationStatus.PENDING_DELETION post_org_pending_deletion( request=request, org_delete_response=org_delete_response, ) context = serialize( organization, request.user, org_serializers.DetailedOrganizationSerializerWithProjectsAndTeams(), access=request.access, ) return self.respond(context, status=202) @sudo_required def delete(self, request: Request, organization) -> Response: """ Delete an Organization `````````````````````` Schedules an organization for deletion. This API endpoint cannot be invoked without a user context for security reasons. This means that at present an organization can only be deleted from the Sentry UI. Deletion happens asynchronously and therefore is not immediate. However once deletion has begun the state of an organization changes and will be hidden from most public views. :pparam string organization_id_or_slug: the id or slug of the organization the team should be created for. :auth: required, user-context-needed """ return self.handle_delete(request, organization) def flag_has_changed(org, flag_name): "Returns ``True`` if ``flag`` has changed since initialization." return getattr(old_value(org, "flags"), flag_name, None) != getattr(org.flags, flag_name) def update_tracked_data(model): "Updates a local copy of attributes values" if model.id: data = {} for f in model._meta.fields: # XXX(dcramer): this is how Django determines this (copypasta from Model) if isinstance(type(f).__dict__.get(f.attname), DeferredAttribute) or f.column is None: continue try: v = get_field_value(model, f) except AttributeError as e: # this case can come up from pickling logging.exception(str(e)) else: if isinstance(v, BitHandler): v = copy(v) data[f.column] = v model.__data = data else: model.__data = UNSAVED
OrganizationDetailsEndpoint
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/errors.py
{ "start": 6427, "end": 7287 }
class ____(graphene.ObjectType): class Meta: interfaces = (GrapheneError,) name = "PipelineNotFoundError" pipeline_name = graphene.NonNull(graphene.String) repository_name = graphene.NonNull(graphene.String) repository_location_name = graphene.NonNull(graphene.String) def __init__(self, selector): from dagster_graphql.implementation.utils import JobSubsetSelector super().__init__() check.inst_param(selector, "selector", JobSubsetSelector) self.pipeline_name = selector.job_name self.repository_name = selector.repository_name self.repository_location_name = selector.location_name self.message = ( "Could not find Pipeline " f"{selector.location_name}.{selector.repository_name}.{selector.job_name}" )
GraphenePipelineNotFoundError
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 257033, "end": 257521 }
class ____(_PrintableStructure): _fields_ = [ ('version', c_uint), ('perfProfilesMask', c_nvmlMask255_t), ('requestedProfilesMask', c_nvmlMask255_t), ('enforcedProfilesMask', c_nvmlMask255_t) ] def __init__(self): super(c_nvmlWorkloadPowerProfileCurrentProfiles_v1_t, self).__init__(version=nvmlWorkloadPowerProfileCurrentProfiles_v1) nvmlWorkloadPowerProfileRequestedProfiles_v1 = 0x1000024
c_nvmlWorkloadPowerProfileCurrentProfiles_v1_t
python
eriklindernoren__ML-From-Scratch
mlfromscratch/deep_learning/optimizers.py
{ "start": 1580, "end": 2161 }
class ____(): def __init__(self, learning_rate=0.01): self.learning_rate = learning_rate self.G = None # Sum of squares of the gradients self.eps = 1e-8 def update(self, w, grad_wrt_w): # If not initialized if self.G is None: self.G = np.zeros(np.shape(w)) # Add the square of the gradient of the loss function at w self.G += np.power(grad_wrt_w, 2) # Adaptive gradient with higher learning rate for sparse data return w - self.learning_rate * grad_wrt_w / np.sqrt(self.G + self.eps)
Adagrad
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 172465, "end": 173794 }
class ____: # Base class for interrupted send/receive tests. Installs an # empty handler for SIGALRM and removes it on teardown, along with # any scheduled alarms. def setUp(self): super().setUp() orig_alrm_handler = signal.signal(signal.SIGALRM, lambda signum, frame: 1 / 0) self.addCleanup(signal.signal, signal.SIGALRM, orig_alrm_handler) # Timeout for socket operations timeout = support.LOOPBACK_TIMEOUT # Provide setAlarm() method to schedule delivery of SIGALRM after # given number of seconds, or cancel it if zero, and an # appropriate time value to use. Use setitimer() if available. if hasattr(signal, "setitimer"): alarm_time = 0.05 def setAlarm(self, seconds): signal.setitimer(signal.ITIMER_REAL, seconds) else: # Old systems may deliver the alarm up to one second early alarm_time = 2 def setAlarm(self, seconds): signal.alarm(seconds) # Require siginterrupt() in order to ensure that system calls are # interrupted by default. @requireAttrs(signal, "siginterrupt") @unittest.skipUnless(hasattr(signal, "alarm") or hasattr(signal, "setitimer"), "Don't have signal.alarm or signal.setitimer")
InterruptedTimeoutBase
python
aio-libs__aiohttp
aiohttp/helpers.py
{ "start": 25952, "end": 27920 }
class ____(Generic[_T]): """Base for concrete context storage key classes. Each storage is provided with its own sub-class for the sake of some additional type safety. """ __slots__ = ("_name", "_t", "__orig_class__") # This may be set by Python when instantiating with a generic type. We need to # support this, in order to support types that are not concrete classes, # like Iterable, which can't be passed as the second parameter to __init__. __orig_class__: type[object] # TODO(PY314): Change Type to TypeForm (this should resolve unreachable below). def __init__(self, name: str, t: type[_T] | None = None): # Prefix with module name to help deduplicate key names. frame = inspect.currentframe() while frame: if frame.f_code.co_name == "<module>": module: str = frame.f_globals["__name__"] break frame = frame.f_back else: raise RuntimeError("Failed to get module name.") # https://github.com/python/mypy/issues/14209 self._name = module + "." + name # type: ignore[possibly-undefined] self._t = t def __lt__(self, other: object) -> bool: if isinstance(other, BaseKey): return self._name < other._name return True # Order BaseKey above other types. def __repr__(self) -> str: t = self._t if t is None: with suppress(AttributeError): # Set to type arg. t = get_args(self.__orig_class__)[0] if t is None: t_repr = "<<Unknown>>" elif isinstance(t, type): if t.__module__ == "builtins": t_repr = t.__qualname__ else: t_repr = f"{t.__module__}.{t.__qualname__}" else: t_repr = repr(t) # type: ignore[unreachable] return f"<{self.__class__.__name__}({self._name}, type={t_repr})>"
BaseKey
python
networkx__networkx
networkx/classes/reportviews.py
{ "start": 21836, "end": 22857 }
class ____(DiDegreeView): """A DegreeView class for inward degree of MultiDiGraph; See DegreeView""" def __getitem__(self, n): weight = self._weight nbrs = self._pred[n] if weight is None: return sum(len(data) for data in nbrs.values()) # edge weighted graph - degree is sum of nbr edge weights return sum( d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values() ) def __iter__(self): weight = self._weight if weight is None: for n in self._nodes: nbrs = self._pred[n] deg = sum(len(data) for data in nbrs.values()) yield (n, deg) else: for n in self._nodes: nbrs = self._pred[n] deg = sum( d.get(weight, 1) for key_dict in nbrs.values() for d in key_dict.values() ) yield (n, deg)
InMultiDegreeView
python
allegroai__clearml
clearml/backend_interface/task/repo/scriptinfo.py
{ "start": 62785, "end": 62946 }
class ____(object): script = attr.ib(default=None) warning_messages = attr.ib(factory=list) auxiliary_git_diff = attr.ib(default=None)
ScriptInfoResult
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/transfers/s3_to_dynamodb.py
{ "start": 1484, "end": 11702 }
class ____(BaseOperator): """ Load Data from S3 into a DynamoDB. Data stored in S3 can be uploaded to a new or existing DynamoDB. Supported file formats CSV, DynamoDB JSON and Amazon ION. :param s3_bucket: The S3 bucket that is imported :param s3_key: Key prefix that imports single or multiple objects from S3 :param dynamodb_table_name: Name of the table that shall be created :param dynamodb_key_schema: Primary key and sort key. Each element represents one primary key attribute. AttributeName is the name of the attribute. KeyType is the role for the attribute. Valid values HASH or RANGE :param dynamodb_attributes: Name of the attributes of a table. AttributeName is the name for the attribute AttributeType is the data type for the attribute. Valid values for AttributeType are S - attribute is of type String N - attribute is of type Number B - attribute is of type Binary :param dynamodb_tmp_table_prefix: Prefix for the temporary DynamoDB table :param delete_on_error: If set, the new DynamoDB table will be deleted in case of import errors :param use_existing_table: Whether to import to an existing non new DynamoDB table. If set to true data is loaded first into a temporary DynamoDB table (using the AWS ImportTable Service), then retrieved as chunks into memory and loaded into the target table. If set to false, a new DynamoDB table will be created and S3 data is bulk loaded by the AWS ImportTable Service. :param input_format: The format for the imported data. Valid values for InputFormat are CSV, DYNAMODB_JSON or ION :param billing_mode: Billing mode for the table. Valid values are PROVISIONED or PAY_PER_REQUEST :param on_demand_throughput: Extra options for maximum number of read and write units :param import_table_kwargs: Any additional optional import table parameters to pass, such as ClientToken, InputCompressionType, or InputFormatOptions. See: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb/client/import_table.html :param import_table_creation_kwargs: Any additional optional import table creation parameters to pass, such as ProvisionedThroughput, SSESpecification, or GlobalSecondaryIndexes. See: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb/client/import_table.html :param wait_for_completion: Whether to wait for cluster to stop :param check_interval: Time in seconds to wait between status checks :param max_attempts: Maximum number of attempts to check for job completion :param aws_conn_id: The reference to the AWS connection details """ template_fields: Sequence[str] = ( "s3_bucket", "s3_key", "dynamodb_table_name", "dynamodb_key_schema", "dynamodb_attributes", "dynamodb_tmp_table_prefix", "delete_on_error", "use_existing_table", "input_format", "billing_mode", "import_table_kwargs", "import_table_creation_kwargs", ) ui_color = "#e2e8f0" def __init__( self, *, s3_bucket: str, s3_key: str, dynamodb_table_name: str, dynamodb_key_schema: list[KeySchema], dynamodb_attributes: list[AttributeDefinition] | None = None, dynamodb_tmp_table_prefix: str = "tmp", delete_on_error: bool = False, use_existing_table: bool = False, input_format: Literal["CSV", "DYNAMODB_JSON", "ION"] = "DYNAMODB_JSON", billing_mode: Literal["PROVISIONED", "PAY_PER_REQUEST"] = "PAY_PER_REQUEST", import_table_kwargs: dict[str, Any] | None = None, import_table_creation_kwargs: dict[str, Any] | None = None, wait_for_completion: bool = True, check_interval: int = 30, max_attempts: int = 240, aws_conn_id: str | None = "aws_default", **kwargs, ) -> None: super().__init__(**kwargs) self.s3_bucket = s3_bucket self.s3_key = s3_key self.dynamodb_table_name = dynamodb_table_name self.dynamodb_attributes = dynamodb_attributes self.dynamodb_tmp_table_prefix = dynamodb_tmp_table_prefix self.delete_on_error = delete_on_error self.use_existing_table = use_existing_table self.dynamodb_key_schema = dynamodb_key_schema self.input_format = input_format self.billing_mode = billing_mode self.import_table_kwargs = import_table_kwargs self.import_table_creation_kwargs = import_table_creation_kwargs self.wait_for_completion = wait_for_completion self.check_interval = check_interval self.max_attempts = max_attempts self.aws_conn_id = aws_conn_id @property def tmp_table_name(self): """Temporary table name.""" return f"{self.dynamodb_tmp_table_prefix}_{self.dynamodb_table_name}" def _load_into_new_table(self, table_name: str, delete_on_error: bool) -> str: """ Import S3 key or keys into a new DynamoDB table. :param table_name: Name of the table that shall be created :param delete_on_error: If set, the new DynamoDB table will be deleted in case of import errors :return: The Amazon resource number (ARN) """ dynamodb_hook = DynamoDBHook(aws_conn_id=self.aws_conn_id) client = dynamodb_hook.client import_table_config = self.import_table_kwargs or {} import_table_creation_config = self.import_table_creation_kwargs or {} try: response = client.import_table( S3BucketSource={ "S3Bucket": self.s3_bucket, "S3KeyPrefix": self.s3_key, }, InputFormat=self.input_format, TableCreationParameters={ "TableName": table_name, "AttributeDefinitions": self.dynamodb_attributes, "KeySchema": self.dynamodb_key_schema, "BillingMode": self.billing_mode, **import_table_creation_config, }, **import_table_config, ) except ClientError as e: self.log.error("Error: failed to load from S3 into DynamoDB table. Error: %s", str(e)) raise AirflowException(f"S3 load into DynamoDB table failed with error: {e}") if response["ImportTableDescription"]["ImportStatus"] == "FAILED": raise AirflowException( "S3 into Dynamodb job creation failed. Code: " f"{response['ImportTableDescription']['FailureCode']}. " f"Failure: {response['ImportTableDescription']['FailureMessage']}" ) if self.wait_for_completion: self.log.info("Waiting for S3 into Dynamodb job to complete") waiter = dynamodb_hook.get_waiter("import_table") try: waiter.wait( ImportArn=response["ImportTableDescription"]["ImportArn"], WaiterConfig={"Delay": self.check_interval, "MaxAttempts": self.max_attempts}, ) except WaiterError: status, error_code, error_msg = dynamodb_hook.get_import_status( response["ImportTableDescription"]["ImportArn"] ) if delete_on_error: client.delete_table(TableName=table_name) raise AirflowException( f"S3 import into Dynamodb job failed: Status: {status}. Error: {error_code}. Error message: {error_msg}" ) return response["ImportTableDescription"]["ImportArn"] def _load_into_existing_table(self) -> str: """ Import S3 key or keys in an existing DynamoDB table. :return:The Amazon resource number (ARN) """ if not self.wait_for_completion: raise ValueError("wait_for_completion must be set to True when loading into an existing table") table_keys = [key["AttributeName"] for key in self.dynamodb_key_schema] dynamodb_hook = DynamoDBHook( aws_conn_id=self.aws_conn_id, table_name=self.dynamodb_table_name, table_keys=table_keys ) client = dynamodb_hook.client self.log.info("Loading from S3 into a tmp DynamoDB table %s", self.tmp_table_name) self._load_into_new_table(table_name=self.tmp_table_name, delete_on_error=self.delete_on_error) total_items = 0 try: paginator = client.get_paginator("scan") paginate = paginator.paginate( TableName=self.tmp_table_name, Select="ALL_ATTRIBUTES", ReturnConsumedCapacity="NONE", ConsistentRead=True, ) self.log.info( "Loading data from %s to %s DynamoDB table", self.tmp_table_name, self.dynamodb_table_name ) for page in paginate: total_items += page.get("Count", 0) dynamodb_hook.write_batch_data(items=page["Items"]) self.log.info("Number of items loaded: %s", total_items) finally: self.log.info("Delete tmp DynamoDB table %s", self.tmp_table_name) client.delete_table(TableName=self.tmp_table_name) return dynamodb_hook.get_conn().Table(self.dynamodb_table_name).table_arn def execute(self, context: Context) -> str: """ Execute S3 to DynamoDB Job from Airflow. :param context: The current context of the task instance :return: The Amazon resource number (ARN) """ if self.use_existing_table: self.log.info("Loading from S3 into new DynamoDB table %s", self.dynamodb_table_name) return self._load_into_existing_table() self.log.info("Loading from S3 into existing DynamoDB table %s", self.dynamodb_table_name) return self._load_into_new_table( table_name=self.dynamodb_table_name, delete_on_error=self.delete_on_error )
S3ToDynamoDBOperator
python
jschneier__django-storages
tests/test_utils.py
{ "start": 5140, "end": 7862 }
class ____(TestCase): def test_with_bytes_file(self): file = io.BytesIO(b"abcd") file_wrapped = utils.ReadBytesWrapper(file) # test read() with default args self.assertEqual(b"abcd", file_wrapped.read()) # test seek() with default args self.assertEqual(0, file_wrapped.seek(0)) self.assertEqual(b"abcd", file_wrapped.read()) # test read() with custom args file_wrapped.seek(0) self.assertEqual(b"ab", file_wrapped.read(2)) # test seek() with custom args self.assertEqual(1, file_wrapped.seek(-1, io.SEEK_CUR)) self.assertEqual(b"bcd", file_wrapped.read()) def test_with_string_file(self): file = io.StringIO("wxyz") file_wrapped = utils.ReadBytesWrapper(file) # test read() with default args self.assertEqual(b"wxyz", file_wrapped.read()) # test seek() with default args self.assertEqual(0, file_wrapped.seek(0)) self.assertEqual(b"wxyz", file_wrapped.read()) # test read() with custom args file_wrapped.seek(0) self.assertEqual(b"wx", file_wrapped.read(2)) # test seek() with custom args self.assertEqual(2, file_wrapped.seek(0, io.SEEK_CUR)) self.assertEqual(b"yz", file_wrapped.read()) # I chose the characters ™€‰ for the following tests because they produce different # bytes when encoding with utf-8 vs windows-1252 vs utf-16 def test_with_string_file_specified_encoding(self): content = "\u2122\u20AC\u2030" file = io.StringIO(content) file_wrapped = utils.ReadBytesWrapper(file, encoding="utf-16") # test read() returns specified encoding self.assertEqual(file_wrapped.read(), content.encode("utf-16")) def test_with_string_file_detect_encoding(self): content = "\u2122\u20AC\u2030" with open( file=os.path.join( os.path.dirname(__file__), "test_files", "windows-1252-encoded.txt" ), mode="r", encoding="windows-1252", ) as file: self.assertEqual(file.read(), content) file.seek(0) file_wrapped = utils.ReadBytesWrapper(file) # test read() returns encoding detected from file object. self.assertEqual(file_wrapped.read(), content.encode("windows-1252")) def test_with_string_file_fallback_encoding(self): content = "\u2122\u20AC\u2030" file = io.StringIO(content) file_wrapped = utils.ReadBytesWrapper(file) # test read() returns fallback utf-8 encoding self.assertEqual(file_wrapped.read(), content.encode("utf-8"))
TestReadBytesWrapper
python
django__django
tests/delete/models.py
{ "start": 4926, "end": 5058 }
class ____(models.Model): m = models.ForeignKey(M, models.CASCADE) r = models.ForeignKey(R, models.SET_NULL, null=True)
MRNull
python
urllib3__urllib3
src/urllib3/connectionpool.py
{ "start": 3394, "end": 35617 }
class ____(ConnectionPool, RequestMethods): """ Thread-safe connection pool for one host. :param host: Host used for this HTTP Connection (e.g. "localhost"), passed into :class:`http.client.HTTPConnection`. :param port: Port used for this HTTP Connection (None is equivalent to 80), passed into :class:`http.client.HTTPConnection`. :param timeout: Socket timeout in seconds for each individual connection. This can be a float or integer, which sets the timeout for the HTTP request, or an instance of :class:`urllib3.util.Timeout` which gives you more fine-grained control over request timeouts. After the constructor has been parsed, this is always a `urllib3.util.Timeout` object. :param maxsize: Number of connections to save that can be reused. More than 1 is useful in multithreaded situations. If ``block`` is set to False, more connections will be created but they will not be saved once they've been used. :param block: If set to True, no more than ``maxsize`` connections will be used at a time. When no free connections are available, the call will block until a connection has been released. This is a useful side effect for particular multithreaded situations where one does not want to use more than maxsize connections per host to prevent flooding. :param headers: Headers to include with all requests, unless other headers are given explicitly. :param retries: Retry configuration to use by default with requests in this pool. :param _proxy: Parsed proxy URL, should not be used directly, instead, see :class:`urllib3.ProxyManager` :param _proxy_headers: A dictionary with proxy headers, should not be used directly, instead, see :class:`urllib3.ProxyManager` :param \\**conn_kw: Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`, :class:`urllib3.connection.HTTPSConnection` instances. """ scheme = "http" ConnectionCls: type[BaseHTTPConnection] | type[BaseHTTPSConnection] = HTTPConnection def __init__( self, host: str, port: int | None = None, timeout: _TYPE_TIMEOUT | None = _DEFAULT_TIMEOUT, maxsize: int = 1, block: bool = False, headers: typing.Mapping[str, str] | None = None, retries: Retry | bool | int | None = None, _proxy: Url | None = None, _proxy_headers: typing.Mapping[str, str] | None = None, _proxy_config: ProxyConfig | None = None, **conn_kw: typing.Any, ): ConnectionPool.__init__(self, host, port) RequestMethods.__init__(self, headers) if not isinstance(timeout, Timeout): timeout = Timeout.from_float(timeout) if retries is None: retries = Retry.DEFAULT self.timeout = timeout self.retries = retries self.pool: queue.LifoQueue[typing.Any] | None = self.QueueCls(maxsize) self.block = block self.proxy = _proxy self.proxy_headers = _proxy_headers or {} self.proxy_config = _proxy_config # Fill the queue up so that doing get() on it will block properly for _ in range(maxsize): self.pool.put(None) # These are mostly for testing and debugging purposes. self.num_connections = 0 self.num_requests = 0 self.conn_kw = conn_kw if self.proxy: # Enable Nagle's algorithm for proxies, to avoid packet fragmentation. # We cannot know if the user has added default socket options, so we cannot replace the # list. self.conn_kw.setdefault("socket_options", []) self.conn_kw["proxy"] = self.proxy self.conn_kw["proxy_config"] = self.proxy_config # Do not pass 'self' as callback to 'finalize'. # Then the 'finalize' would keep an endless living (leak) to self. # By just passing a reference to the pool allows the garbage collector # to free self if nobody else has a reference to it. pool = self.pool # Close all the HTTPConnections in the pool before the # HTTPConnectionPool object is garbage collected. weakref.finalize(self, _close_pool_connections, pool) def _new_conn(self) -> BaseHTTPConnection: """ Return a fresh :class:`HTTPConnection`. """ self.num_connections += 1 log.debug( "Starting new HTTP connection (%d): %s:%s", self.num_connections, self.host, self.port or "80", ) conn = self.ConnectionCls( host=self.host, port=self.port, timeout=self.timeout.connect_timeout, **self.conn_kw, ) return conn def _get_conn(self, timeout: float | None = None) -> BaseHTTPConnection: """ Get a connection. Will return a pooled connection if one is available. If no connections are available and :prop:`.block` is ``False``, then a fresh connection is returned. :param timeout: Seconds to wait before giving up and raising :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and :prop:`.block` is ``True``. """ conn = None if self.pool is None: raise ClosedPoolError(self, "Pool is closed.") try: conn = self.pool.get(block=self.block, timeout=timeout) except AttributeError: # self.pool is None raise ClosedPoolError(self, "Pool is closed.") from None # Defensive: except queue.Empty: if self.block: raise EmptyPoolError( self, "Pool is empty and a new connection can't be opened due to blocking mode.", ) from None pass # Oh well, we'll create a new connection then # If this is a persistent connection, check if it got disconnected if conn and is_connection_dropped(conn): log.debug("Resetting dropped connection: %s", self.host) conn.close() return conn or self._new_conn() def _put_conn(self, conn: BaseHTTPConnection | None) -> None: """ Put a connection back into the pool. :param conn: Connection object for the current host and port as returned by :meth:`._new_conn` or :meth:`._get_conn`. If the pool is already full, the connection is closed and discarded because we exceeded maxsize. If connections are discarded frequently, then maxsize should be increased. If the pool is closed, then the connection will be closed and discarded. """ if self.pool is not None: try: self.pool.put(conn, block=False) return # Everything is dandy, done. except AttributeError: # self.pool is None. pass except queue.Full: # Connection never got put back into the pool, close it. if conn: conn.close() if self.block: # This should never happen if you got the conn from self._get_conn raise FullPoolError( self, "Pool reached maximum size and no more connections are allowed.", ) from None log.warning( "Connection pool is full, discarding connection: %s. Connection pool size: %s", self.host, self.pool.qsize(), ) # Connection never got put back into the pool, close it. if conn: conn.close() def _validate_conn(self, conn: BaseHTTPConnection) -> None: """ Called right before a request is made, after the socket is created. """ def _prepare_proxy(self, conn: BaseHTTPConnection) -> None: # Nothing to do for HTTP connections. pass def _get_timeout(self, timeout: _TYPE_TIMEOUT) -> Timeout: """Helper that always returns a :class:`urllib3.util.Timeout`""" if timeout is _DEFAULT_TIMEOUT: return self.timeout.clone() if isinstance(timeout, Timeout): return timeout.clone() else: # User passed us an int/float. This is for backwards compatibility, # can be removed later return Timeout.from_float(timeout) def _raise_timeout( self, err: BaseSSLError | OSError | SocketTimeout, url: str, timeout_value: _TYPE_TIMEOUT | None, ) -> None: """Is the error actually a timeout? Will raise a ReadTimeout or pass""" if isinstance(err, SocketTimeout): raise ReadTimeoutError( self, url, f"Read timed out. (read timeout={timeout_value})" ) from err # See the above comment about EAGAIN in Python 3. if hasattr(err, "errno") and err.errno in _blocking_errnos: raise ReadTimeoutError( self, url, f"Read timed out. (read timeout={timeout_value})" ) from err def _make_request( self, conn: BaseHTTPConnection, method: str, url: str, body: _TYPE_BODY | None = None, headers: typing.Mapping[str, str] | None = None, retries: Retry | None = None, timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, chunked: bool = False, response_conn: BaseHTTPConnection | None = None, preload_content: bool = True, decode_content: bool = True, enforce_content_length: bool = True, ) -> BaseHTTPResponse: """ Perform a request on a given urllib connection object taken from our pool. :param conn: a connection from one of our connection pools :param method: HTTP request method (such as GET, POST, PUT, etc.) :param url: The URL to perform the request on. :param body: Data to send in the request body, either :class:`str`, :class:`bytes`, an iterable of :class:`str`/:class:`bytes`, or a file-like object. :param headers: Dictionary of custom headers to send, such as User-Agent, If-None-Match, etc. If None, pool headers are used. If provided, these headers completely replace any pool-specific headers. :param retries: Configure the number of retries to allow before raising a :class:`~urllib3.exceptions.MaxRetryError` exception. Pass ``None`` to retry until you receive a response. Pass a :class:`~urllib3.util.retry.Retry` object for fine-grained control over different types of retries. Pass an integer number to retry connection errors that many times, but no other types of errors. Pass zero to never retry. If ``False``, then retries are disabled and any exception is raised immediately. Also, instead of raising a MaxRetryError on redirects, the redirect response will be returned. :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int. :param timeout: If specified, overrides the default timeout for this one request. It may be a float (in seconds) or an instance of :class:`urllib3.util.Timeout`. :param chunked: If True, urllib3 will send the body using chunked transfer encoding. Otherwise, urllib3 will send the body using the standard content-length form. Defaults to False. :param response_conn: Set this to ``None`` if you will handle releasing the connection or set the connection to have the response release it. :param preload_content: If True, the response's body will be preloaded during construction. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. :param enforce_content_length: Enforce content length checking. Body returned by server must match value of Content-Length header, if present. Otherwise, raise error. """ self.num_requests += 1 timeout_obj = self._get_timeout(timeout) timeout_obj.start_connect() conn.timeout = Timeout.resolve_default_timeout(timeout_obj.connect_timeout) try: # Trigger any extra validation we need to do. try: self._validate_conn(conn) except (SocketTimeout, BaseSSLError) as e: self._raise_timeout(err=e, url=url, timeout_value=conn.timeout) raise # _validate_conn() starts the connection to an HTTPS proxy # so we need to wrap errors with 'ProxyError' here too. except ( OSError, NewConnectionError, TimeoutError, BaseSSLError, CertificateError, SSLError, ) as e: new_e: Exception = e if isinstance(e, (BaseSSLError, CertificateError)): new_e = SSLError(e) # If the connection didn't successfully connect to it's proxy # then there if isinstance( new_e, (OSError, NewConnectionError, TimeoutError, SSLError) ) and (conn and conn.proxy and not conn.has_connected_to_proxy): new_e = _wrap_proxy_error(new_e, conn.proxy.scheme) raise new_e # conn.request() calls http.client.*.request, not the method in # urllib3.request. It also calls makefile (recv) on the socket. try: conn.request( method, url, body=body, headers=headers, chunked=chunked, preload_content=preload_content, decode_content=decode_content, enforce_content_length=enforce_content_length, ) # We are swallowing BrokenPipeError (errno.EPIPE) since the server is # legitimately able to close the connection after sending a valid response. # With this behaviour, the received response is still readable. except BrokenPipeError: pass except OSError as e: # MacOS/Linux # EPROTOTYPE and ECONNRESET are needed on macOS # https://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/ # Condition changed later to emit ECONNRESET instead of only EPROTOTYPE. if e.errno != errno.EPROTOTYPE and e.errno != errno.ECONNRESET: raise # Reset the timeout for the recv() on the socket read_timeout = timeout_obj.read_timeout if not conn.is_closed: # In Python 3 socket.py will catch EAGAIN and return None when you # try and read into the file pointer created by http.client, which # instead raises a BadStatusLine exception. Instead of catching # the exception and assuming all BadStatusLine exceptions are read # timeouts, check for a zero timeout before making the request. if read_timeout == 0: raise ReadTimeoutError( self, url, f"Read timed out. (read timeout={read_timeout})" ) conn.timeout = read_timeout # Receive the response from the server try: response = conn.getresponse() except (BaseSSLError, OSError) as e: self._raise_timeout(err=e, url=url, timeout_value=read_timeout) raise # Set properties that are used by the pooling layer. response.retries = retries response._connection = response_conn # type: ignore[attr-defined] response._pool = self # type: ignore[attr-defined] log.debug( '%s://%s:%s "%s %s %s" %s %s', self.scheme, self.host, self.port, method, url, response.version_string, response.status, response.length_remaining, ) return response def close(self) -> None: """ Close all pooled connections and disable the pool. """ if self.pool is None: return # Disable access to the pool old_pool, self.pool = self.pool, None # Close all the HTTPConnections in the pool. _close_pool_connections(old_pool) def is_same_host(self, url: str) -> bool: """ Check if the given ``url`` is a member of the same host as this connection pool. """ if url.startswith("/"): return True # TODO: Add optional support for socket.gethostbyname checking. scheme, _, host, port, *_ = parse_url(url) scheme = scheme or "http" if host is not None: host = _normalize_host(host, scheme=scheme) # Use explicit default port for comparison when none is given if self.port and not port: port = port_by_scheme.get(scheme) elif not self.port and port == port_by_scheme.get(scheme): port = None return (scheme, host, port) == (self.scheme, self.host, self.port) def urlopen( # type: ignore[override] self, method: str, url: str, body: _TYPE_BODY | None = None, headers: typing.Mapping[str, str] | None = None, retries: Retry | bool | int | None = None, redirect: bool = True, assert_same_host: bool = True, timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, pool_timeout: int | None = None, release_conn: bool | None = None, chunked: bool = False, body_pos: _TYPE_BODY_POSITION | None = None, preload_content: bool = True, decode_content: bool = True, **response_kw: typing.Any, ) -> BaseHTTPResponse: """ Get a connection from the pool and perform an HTTP request. This is the lowest level call for making a request, so you'll need to specify all the raw details. .. note:: More commonly, it's appropriate to use a convenience method such as :meth:`request`. .. note:: `release_conn` will only behave as expected if `preload_content=False` because we want to make `preload_content=False` the default behaviour someday soon without breaking backwards compatibility. :param method: HTTP request method (such as GET, POST, PUT, etc.) :param url: The URL to perform the request on. :param body: Data to send in the request body, either :class:`str`, :class:`bytes`, an iterable of :class:`str`/:class:`bytes`, or a file-like object. :param headers: Dictionary of custom headers to send, such as User-Agent, If-None-Match, etc. If None, pool headers are used. If provided, these headers completely replace any pool-specific headers. :param retries: Configure the number of retries to allow before raising a :class:`~urllib3.exceptions.MaxRetryError` exception. If ``None`` (default) will retry 3 times, see ``Retry.DEFAULT``. Pass a :class:`~urllib3.util.retry.Retry` object for fine-grained control over different types of retries. Pass an integer number to retry connection errors that many times, but no other types of errors. Pass zero to never retry. If ``False``, then retries are disabled and any exception is raised immediately. Also, instead of raising a MaxRetryError on redirects, the redirect response will be returned. :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int. :param redirect: If True, automatically handle redirects (status codes 301, 302, 303, 307, 308). Each redirect counts as a retry. Disabling retries will disable redirect, too. :param assert_same_host: If ``True``, will make sure that the host of the pool requests is consistent else will raise HostChangedError. When ``False``, you can use the pool on an HTTP proxy and request foreign hosts. :param timeout: If specified, overrides the default timeout for this one request. It may be a float (in seconds) or an instance of :class:`urllib3.util.Timeout`. :param pool_timeout: If set and the pool is set to block=True, then this method will block for ``pool_timeout`` seconds and raise EmptyPoolError if no connection is available within the time period. :param bool preload_content: If True, the response's body will be preloaded into memory. :param bool decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. :param release_conn: If False, then the urlopen call will not release the connection back into the pool once a response is received (but will release if you read the entire contents of the response such as when `preload_content=True`). This is useful if you're not preloading the response's content immediately. You will need to call ``r.release_conn()`` on the response ``r`` to return the connection back into the pool. If None, it takes the value of ``preload_content`` which defaults to ``True``. :param bool chunked: If True, urllib3 will send the body using chunked transfer encoding. Otherwise, urllib3 will send the body using the standard content-length form. Defaults to False. :param int body_pos: Position to seek to in file-like body in the event of a retry or redirect. Typically this won't need to be set because urllib3 will auto-populate the value when needed. """ parsed_url = parse_url(url) destination_scheme = parsed_url.scheme if headers is None: headers = self.headers if not isinstance(retries, Retry): retries = Retry.from_int(retries, redirect=redirect, default=self.retries) if release_conn is None: release_conn = preload_content # Check host if assert_same_host and not self.is_same_host(url): raise HostChangedError(self, url, retries) # Ensure that the URL we're connecting to is properly encoded if url.startswith("/"): url = to_str(_encode_target(url)) else: url = to_str(parsed_url.url) conn = None # Track whether `conn` needs to be released before # returning/raising/recursing. Update this variable if necessary, and # leave `release_conn` constant throughout the function. That way, if # the function recurses, the original value of `release_conn` will be # passed down into the recursive call, and its value will be respected. # # See issue #651 [1] for details. # # [1] <https://github.com/urllib3/urllib3/issues/651> release_this_conn = release_conn http_tunnel_required = connection_requires_http_tunnel( self.proxy, self.proxy_config, destination_scheme ) # Merge the proxy headers. Only done when not using HTTP CONNECT. We # have to copy the headers dict so we can safely change it without those # changes being reflected in anyone else's copy. if not http_tunnel_required: headers = headers.copy() # type: ignore[attr-defined] headers.update(self.proxy_headers) # type: ignore[union-attr] # Must keep the exception bound to a separate variable or else Python 3 # complains about UnboundLocalError. err = None # Keep track of whether we cleanly exited the except block. This # ensures we do proper cleanup in finally. clean_exit = False # Rewind body position, if needed. Record current position # for future rewinds in the event of a redirect/retry. body_pos = set_file_position(body, body_pos) try: # Request a connection from the queue. timeout_obj = self._get_timeout(timeout) conn = self._get_conn(timeout=pool_timeout) conn.timeout = timeout_obj.connect_timeout # type: ignore[assignment] # Is this a closed/new connection that requires CONNECT tunnelling? if self.proxy is not None and http_tunnel_required and conn.is_closed: try: self._prepare_proxy(conn) except (BaseSSLError, OSError, SocketTimeout) as e: self._raise_timeout( err=e, url=self.proxy.url, timeout_value=conn.timeout ) raise # If we're going to release the connection in ``finally:``, then # the response doesn't need to know about the connection. Otherwise # it will also try to release it and we'll have a double-release # mess. response_conn = conn if not release_conn else None # Make the request on the HTTPConnection object response = self._make_request( conn, method, url, timeout=timeout_obj, body=body, headers=headers, chunked=chunked, retries=retries, response_conn=response_conn, preload_content=preload_content, decode_content=decode_content, **response_kw, ) # Everything went great! clean_exit = True except EmptyPoolError: # Didn't get a connection from the pool, no need to clean up clean_exit = True release_this_conn = False raise except ( TimeoutError, HTTPException, OSError, ProtocolError, BaseSSLError, SSLError, CertificateError, ProxyError, ) as e: # Discard the connection for these exceptions. It will be # replaced during the next _get_conn() call. clean_exit = False new_e: Exception = e if isinstance(e, (BaseSSLError, CertificateError)): new_e = SSLError(e) if isinstance( new_e, ( OSError, NewConnectionError, TimeoutError, SSLError, HTTPException, ), ) and (conn and conn.proxy and not conn.has_connected_to_proxy): new_e = _wrap_proxy_error(new_e, conn.proxy.scheme) elif isinstance(new_e, (OSError, HTTPException)): new_e = ProtocolError("Connection aborted.", new_e) retries = retries.increment( method, url, error=new_e, _pool=self, _stacktrace=sys.exc_info()[2] ) retries.sleep() # Keep track of the error for the retry warning. err = e finally: if not clean_exit: # We hit some kind of exception, handled or otherwise. We need # to throw the connection away unless explicitly told not to. # Close the connection, set the variable to None, and make sure # we put the None back in the pool to avoid leaking it. if conn: conn.close() conn = None release_this_conn = True if release_this_conn: # Put the connection back to be reused. If the connection is # expired then it will be None, which will get replaced with a # fresh connection during _get_conn. self._put_conn(conn) if not conn: # Try again log.warning( "Retrying (%r) after connection broken by '%r': %s", retries, err, url ) return self.urlopen( method, url, body, headers, retries, redirect, assert_same_host, timeout=timeout, pool_timeout=pool_timeout, release_conn=release_conn, chunked=chunked, body_pos=body_pos, preload_content=preload_content, decode_content=decode_content, **response_kw, ) # Handle redirect? redirect_location = redirect and response.get_redirect_location() if redirect_location: if response.status == 303: # Change the method according to RFC 9110, Section 15.4.4. method = "GET" # And lose the body not to transfer anything sensitive. body = None headers = HTTPHeaderDict(headers)._prepare_for_method_change() try: retries = retries.increment(method, url, response=response, _pool=self) except MaxRetryError: if retries.raise_on_redirect: response.drain_conn() raise return response response.drain_conn() retries.sleep_for_retry(response) log.debug("Redirecting %s -> %s", url, redirect_location) return self.urlopen( method, redirect_location, body, headers, retries=retries, redirect=redirect, assert_same_host=assert_same_host, timeout=timeout, pool_timeout=pool_timeout, release_conn=release_conn, chunked=chunked, body_pos=body_pos, preload_content=preload_content, decode_content=decode_content, **response_kw, ) # Check if we should retry the HTTP response. has_retry_after = bool(response.headers.get("Retry-After")) if retries.is_retry(method, response.status, has_retry_after): try: retries = retries.increment(method, url, response=response, _pool=self) except MaxRetryError: if retries.raise_on_status: response.drain_conn() raise return response response.drain_conn() retries.sleep(response) log.debug("Retry: %s", url) return self.urlopen( method, url, body, headers, retries=retries, redirect=redirect, assert_same_host=assert_same_host, timeout=timeout, pool_timeout=pool_timeout, release_conn=release_conn, chunked=chunked, body_pos=body_pos, preload_content=preload_content, decode_content=decode_content, **response_kw, ) return response
HTTPConnectionPool
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-yahoo-finance/llama_index/tools/yahoo_finance/base.py
{ "start": 107, "end": 2527 }
class ____(BaseToolSpec): """Yahoo Finance tool spec.""" spec_functions = [ "balance_sheet", "income_statement", "cash_flow", "stock_basic_info", "stock_analyst_recommendations", "stock_news", ] def __init__(self) -> None: """Initialize the Yahoo Finance tool spec.""" def balance_sheet(self, ticker: str) -> str: """ Return the balance sheet of the stock. Args: ticker (str): the stock ticker to be given to yfinance """ stock = yf.Ticker(ticker) balance_sheet = pd.DataFrame(stock.balance_sheet) return "Balance Sheet: \n" + balance_sheet.to_string() def income_statement(self, ticker: str) -> str: """ Return the income statement of the stock. Args: ticker (str): the stock ticker to be given to yfinance """ stock = yf.Ticker(ticker) income_statement = pd.DataFrame(stock.income_stmt) return "Income Statement: \n" + income_statement.to_string() def cash_flow(self, ticker: str) -> str: """ Return the cash flow of the stock. Args: ticker (str): the stock ticker to be given to yfinance """ stock = yf.Ticker(ticker) cash_flow = pd.DataFrame(stock.cashflow) return "Cash Flow: \n" + cash_flow.to_string() def stock_basic_info(self, ticker: str) -> str: """ Return the basic info of the stock. Ex: price, description, name. Args: ticker (str): the stock ticker to be given to yfinance """ stock = yf.Ticker(ticker) return "Info: \n" + str(stock.info) def stock_analyst_recommendations(self, ticker: str) -> str: """ Get the analyst recommendations for a stock. Args: ticker (str): the stock ticker to be given to yfinance """ stock = yf.Ticker(ticker) return "Recommendations: \n" + str(stock.recommendations) def stock_news(self, ticker: str) -> str: """ Get the most recent news titles of a stock. Args: ticker (str): the stock ticker to be given to yfinance """ stock = yf.Ticker(ticker) news = stock.news out = "News: \n" for i in news: out += i["title"] + "\n" return out
YahooFinanceToolSpec
python
numpy__numpy
numpy/distutils/command/config_compiler.py
{ "start": 2935, "end": 4371 }
class ____(Command): """ Distutils command to hold user specified options to C/C++ compilers. """ description = "specify C/C++ compiler information" user_options = [ ('compiler=', None, "specify C/C++ compiler type"), ] def initialize_options(self): self.compiler = None def finalize_options(self): log.info('unifying config_cc, config, build_clib, build_ext, build commands --compiler options') build_clib = self.get_finalized_command('build_clib') build_ext = self.get_finalized_command('build_ext') config = self.get_finalized_command('config') build = self.get_finalized_command('build') cmd_list = [self, config, build_clib, build_ext, build] for a in ['compiler']: l = [] for c in cmd_list: v = getattr(c, a) if v is not None: if not isinstance(v, str): v = v.compiler_type if v not in l: l.append(v) if not l: v1 = None else: v1 = l[0] if len(l)>1: log.warn(' commands have different --%s options: %s'\ ', using first in list as default' % (a, l)) if v1: for c in cmd_list: if getattr(c, a) is None: setattr(c, a, v1) return def run(self): # Do nothing. return
config_cc
python
python-pillow__Pillow
src/PIL/TiffImagePlugin.py
{ "start": 18708, "end": 38988 }
class ____(_IFDv2Base): """This class represents a TIFF tag directory. To speed things up, we don't decode tags unless they're asked for. Exposes a dictionary interface of the tags in the directory:: ifd = ImageFileDirectory_v2() ifd[key] = 'Some Data' ifd.tagtype[key] = TiffTags.ASCII print(ifd[key]) 'Some Data' Individual values are returned as the strings or numbers, sequences are returned as tuples of the values. The tiff metadata type of each item is stored in a dictionary of tag types in :attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype`. The types are read from a tiff file, guessed from the type added, or added manually. Data Structures: * ``self.tagtype = {}`` * Key: numerical TIFF tag number * Value: integer corresponding to the data type from :py:data:`.TiffTags.TYPES` .. versionadded:: 3.0.0 'Internal' data structures: * ``self._tags_v2 = {}`` * Key: numerical TIFF tag number * Value: decoded data, as tuple for multiple values * ``self._tagdata = {}`` * Key: numerical TIFF tag number * Value: undecoded byte string from file * ``self._tags_v1 = {}`` * Key: numerical TIFF tag number * Value: decoded data in the v1 format Tags will be found in the private attributes ``self._tagdata``, and in ``self._tags_v2`` once decoded. ``self.legacy_api`` is a value for internal use, and shouldn't be changed from outside code. In cooperation with :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`, if ``legacy_api`` is true, then decoded tags will be populated into both ``_tags_v1`` and ``_tags_v2``. ``_tags_v2`` will be used if this IFD is used in the TIFF save routine. Tags should be read from ``_tags_v1`` if ``legacy_api == true``. """ _load_dispatch: dict[int, tuple[int, _LoaderFunc]] = {} _write_dispatch: dict[int, Callable[..., Any]] = {} def __init__( self, ifh: bytes = b"II\x2a\x00\x00\x00\x00\x00", prefix: bytes | None = None, group: int | None = None, ) -> None: """Initialize an ImageFileDirectory. To construct an ImageFileDirectory from a real file, pass the 8-byte magic header to the constructor. To only set the endianness, pass it as the 'prefix' keyword argument. :param ifh: One of the accepted magic headers (cf. PREFIXES); also sets endianness. :param prefix: Override the endianness of the file. """ if not _accept(ifh): msg = f"not a TIFF file (header {repr(ifh)} not valid)" raise SyntaxError(msg) self._prefix = prefix if prefix is not None else ifh[:2] if self._prefix == MM: self._endian = ">" elif self._prefix == II: self._endian = "<" else: msg = "not a TIFF IFD" raise SyntaxError(msg) self._bigtiff = ifh[2] == 43 self.group = group self.tagtype: dict[int, int] = {} """ Dictionary of tag types """ self.reset() self.next = ( self._unpack("Q", ifh[8:])[0] if self._bigtiff else self._unpack("L", ifh[4:])[0] ) self._legacy_api = False prefix = property(lambda self: self._prefix) offset = property(lambda self: self._offset) @property def legacy_api(self) -> bool: return self._legacy_api @legacy_api.setter def legacy_api(self, value: bool) -> NoReturn: msg = "Not allowing setting of legacy api" raise Exception(msg) def reset(self) -> None: self._tags_v1: dict[int, Any] = {} # will remain empty if legacy_api is false self._tags_v2: dict[int, Any] = {} # main tag storage self._tagdata: dict[int, bytes] = {} self.tagtype = {} # added 2008-06-05 by Florian Hoech self._next = None self._offset: int | None = None def __str__(self) -> str: return str(dict(self)) def named(self) -> dict[str, Any]: """ :returns: dict of name|key: value Returns the complete tag dictionary, with named tags where possible. """ return { TiffTags.lookup(code, self.group).name: value for code, value in self.items() } def __len__(self) -> int: return len(set(self._tagdata) | set(self._tags_v2)) def __getitem__(self, tag: int) -> Any: if tag not in self._tags_v2: # unpack on the fly data = self._tagdata[tag] typ = self.tagtype[tag] size, handler = self._load_dispatch[typ] self[tag] = handler(self, data, self.legacy_api) # check type val = self._tags_v2[tag] if self.legacy_api and not isinstance(val, (tuple, bytes)): val = (val,) return val def __contains__(self, tag: object) -> bool: return tag in self._tags_v2 or tag in self._tagdata def __setitem__(self, tag: int, value: Any) -> None: self._setitem(tag, value, self.legacy_api) def _setitem(self, tag: int, value: Any, legacy_api: bool) -> None: basetypes = (Number, bytes, str) info = TiffTags.lookup(tag, self.group) values = [value] if isinstance(value, basetypes) else value if tag not in self.tagtype: if info.type: self.tagtype[tag] = info.type else: self.tagtype[tag] = TiffTags.UNDEFINED if all(isinstance(v, IFDRational) for v in values): for v in values: assert isinstance(v, IFDRational) if v < 0: self.tagtype[tag] = TiffTags.SIGNED_RATIONAL break else: self.tagtype[tag] = TiffTags.RATIONAL elif all(isinstance(v, int) for v in values): short = True signed_short = True long = True for v in values: assert isinstance(v, int) if short and not (0 <= v < 2**16): short = False if signed_short and not (-(2**15) < v < 2**15): signed_short = False if long and v < 0: long = False if short: self.tagtype[tag] = TiffTags.SHORT elif signed_short: self.tagtype[tag] = TiffTags.SIGNED_SHORT elif long: self.tagtype[tag] = TiffTags.LONG else: self.tagtype[tag] = TiffTags.SIGNED_LONG elif all(isinstance(v, float) for v in values): self.tagtype[tag] = TiffTags.DOUBLE elif all(isinstance(v, str) for v in values): self.tagtype[tag] = TiffTags.ASCII elif all(isinstance(v, bytes) for v in values): self.tagtype[tag] = TiffTags.BYTE if self.tagtype[tag] == TiffTags.UNDEFINED: values = [ v.encode("ascii", "replace") if isinstance(v, str) else v for v in values ] elif self.tagtype[tag] == TiffTags.RATIONAL: values = [float(v) if isinstance(v, int) else v for v in values] is_ifd = self.tagtype[tag] == TiffTags.LONG and isinstance(values, dict) if not is_ifd: values = tuple( info.cvt_enum(value) if isinstance(value, str) else value for value in values ) dest = self._tags_v1 if legacy_api else self._tags_v2 # Three branches: # Spec'd length == 1, Actual length 1, store as element # Spec'd length == 1, Actual > 1, Warn and truncate. Formerly barfed. # No Spec, Actual length 1, Formerly (<4.2) returned a 1 element tuple. # Don't mess with the legacy api, since it's frozen. if not is_ifd and ( (info.length == 1) or self.tagtype[tag] == TiffTags.BYTE or (info.length is None and len(values) == 1 and not legacy_api) ): # Don't mess with the legacy api, since it's frozen. if legacy_api and self.tagtype[tag] in [ TiffTags.RATIONAL, TiffTags.SIGNED_RATIONAL, ]: # rationals values = (values,) try: (dest[tag],) = values except ValueError: # We've got a builtin tag with 1 expected entry warnings.warn( f"Metadata Warning, tag {tag} had too many entries: " f"{len(values)}, expected 1" ) dest[tag] = values[0] else: # Spec'd length > 1 or undefined # Unspec'd, and length > 1 dest[tag] = values def __delitem__(self, tag: int) -> None: self._tags_v2.pop(tag, None) self._tags_v1.pop(tag, None) self._tagdata.pop(tag, None) def __iter__(self) -> Iterator[int]: return iter(set(self._tagdata) | set(self._tags_v2)) def _unpack(self, fmt: str, data: bytes) -> tuple[Any, ...]: return struct.unpack(self._endian + fmt, data) def _pack(self, fmt: str, *values: Any) -> bytes: return struct.pack(self._endian + fmt, *values) list( map( _register_basic, [ (TiffTags.SHORT, "H", "short"), (TiffTags.LONG, "L", "long"), (TiffTags.SIGNED_BYTE, "b", "signed byte"), (TiffTags.SIGNED_SHORT, "h", "signed short"), (TiffTags.SIGNED_LONG, "l", "signed long"), (TiffTags.FLOAT, "f", "float"), (TiffTags.DOUBLE, "d", "double"), (TiffTags.IFD, "L", "long"), (TiffTags.LONG8, "Q", "long8"), ], ) ) @_register_loader(1, 1) # Basic type, except for the legacy API. def load_byte(self, data: bytes, legacy_api: bool = True) -> bytes: return data @_register_writer(1) # Basic type, except for the legacy API. def write_byte(self, data: bytes | int | IFDRational) -> bytes: if isinstance(data, IFDRational): data = int(data) if isinstance(data, int): data = bytes((data,)) return data @_register_loader(2, 1) def load_string(self, data: bytes, legacy_api: bool = True) -> str: if data.endswith(b"\0"): data = data[:-1] return data.decode("latin-1", "replace") @_register_writer(2) def write_string(self, value: str | bytes | int) -> bytes: # remerge of https://github.com/python-pillow/Pillow/pull/1416 if isinstance(value, int): value = str(value) if not isinstance(value, bytes): value = value.encode("ascii", "replace") return value + b"\0" @_register_loader(5, 8) def load_rational( self, data: bytes, legacy_api: bool = True ) -> tuple[tuple[int, int] | IFDRational, ...]: vals = self._unpack(f"{len(data) // 4}L", data) def combine(a: int, b: int) -> tuple[int, int] | IFDRational: return (a, b) if legacy_api else IFDRational(a, b) return tuple(combine(num, denom) for num, denom in zip(vals[::2], vals[1::2])) @_register_writer(5) def write_rational(self, *values: IFDRational) -> bytes: return b"".join( self._pack("2L", *_limit_rational(frac, 2**32 - 1)) for frac in values ) @_register_loader(7, 1) def load_undefined(self, data: bytes, legacy_api: bool = True) -> bytes: return data @_register_writer(7) def write_undefined(self, value: bytes | int | IFDRational) -> bytes: if isinstance(value, IFDRational): value = int(value) if isinstance(value, int): value = str(value).encode("ascii", "replace") return value @_register_loader(10, 8) def load_signed_rational( self, data: bytes, legacy_api: bool = True ) -> tuple[tuple[int, int] | IFDRational, ...]: vals = self._unpack(f"{len(data) // 4}l", data) def combine(a: int, b: int) -> tuple[int, int] | IFDRational: return (a, b) if legacy_api else IFDRational(a, b) return tuple(combine(num, denom) for num, denom in zip(vals[::2], vals[1::2])) @_register_writer(10) def write_signed_rational(self, *values: IFDRational) -> bytes: return b"".join( self._pack("2l", *_limit_signed_rational(frac, 2**31 - 1, -(2**31))) for frac in values ) def _ensure_read(self, fp: IO[bytes], size: int) -> bytes: ret = fp.read(size) if len(ret) != size: msg = ( "Corrupt EXIF data. " f"Expecting to read {size} bytes but only got {len(ret)}. " ) raise OSError(msg) return ret def load(self, fp: IO[bytes]) -> None: self.reset() self._offset = fp.tell() try: tag_count = ( self._unpack("Q", self._ensure_read(fp, 8)) if self._bigtiff else self._unpack("H", self._ensure_read(fp, 2)) )[0] for i in range(tag_count): tag, typ, count, data = ( self._unpack("HHQ8s", self._ensure_read(fp, 20)) if self._bigtiff else self._unpack("HHL4s", self._ensure_read(fp, 12)) ) tagname = TiffTags.lookup(tag, self.group).name typname = TYPES.get(typ, "unknown") msg = f"tag: {tagname} ({tag}) - type: {typname} ({typ})" try: unit_size, handler = self._load_dispatch[typ] except KeyError: logger.debug("%s - unsupported type %s", msg, typ) continue # ignore unsupported type size = count * unit_size if size > (8 if self._bigtiff else 4): here = fp.tell() (offset,) = self._unpack("Q" if self._bigtiff else "L", data) msg += f" Tag Location: {here} - Data Location: {offset}" fp.seek(offset) data = ImageFile._safe_read(fp, size) fp.seek(here) else: data = data[:size] if len(data) != size: warnings.warn( "Possibly corrupt EXIF data. " f"Expecting to read {size} bytes but only got {len(data)}." f" Skipping tag {tag}" ) logger.debug(msg) continue if not data: logger.debug(msg) continue self._tagdata[tag] = data self.tagtype[tag] = typ msg += " - value: " msg += f"<table: {size} bytes>" if size > 32 else repr(data) logger.debug(msg) (self.next,) = ( self._unpack("Q", self._ensure_read(fp, 8)) if self._bigtiff else self._unpack("L", self._ensure_read(fp, 4)) ) except OSError as msg: warnings.warn(str(msg)) return def _get_ifh(self) -> bytes: ifh = self._prefix + self._pack("H", 43 if self._bigtiff else 42) if self._bigtiff: ifh += self._pack("HH", 8, 0) ifh += self._pack("Q", 16) if self._bigtiff else self._pack("L", 8) return ifh def tobytes(self, offset: int = 0) -> bytes: # FIXME What about tagdata? result = self._pack("Q" if self._bigtiff else "H", len(self._tags_v2)) entries: list[tuple[int, int, int, bytes, bytes]] = [] fmt = "Q" if self._bigtiff else "L" fmt_size = 8 if self._bigtiff else 4 offset += ( len(result) + len(self._tags_v2) * (20 if self._bigtiff else 12) + fmt_size ) stripoffsets = None # pass 1: convert tags to binary format # always write tags in ascending order for tag, value in sorted(self._tags_v2.items()): if tag == STRIPOFFSETS: stripoffsets = len(entries) typ = self.tagtype[tag] logger.debug("Tag %s, Type: %s, Value: %s", tag, typ, repr(value)) is_ifd = typ == TiffTags.LONG and isinstance(value, dict) if is_ifd: ifd = ImageFileDirectory_v2(self._get_ifh(), group=tag) values = self._tags_v2[tag] for ifd_tag, ifd_value in values.items(): ifd[ifd_tag] = ifd_value data = ifd.tobytes(offset) else: values = value if isinstance(value, tuple) else (value,) data = self._write_dispatch[typ](self, *values) tagname = TiffTags.lookup(tag, self.group).name typname = "ifd" if is_ifd else TYPES.get(typ, "unknown") msg = f"save: {tagname} ({tag}) - type: {typname} ({typ}) - value: " msg += f"<table: {len(data)} bytes>" if len(data) >= 16 else str(values) logger.debug(msg) # count is sum of lengths for string and arbitrary data if is_ifd: count = 1 elif typ in [TiffTags.BYTE, TiffTags.ASCII, TiffTags.UNDEFINED]: count = len(data) else: count = len(values) # figure out if data fits into the entry if len(data) <= fmt_size: entries.append((tag, typ, count, data.ljust(fmt_size, b"\0"), b"")) else: entries.append((tag, typ, count, self._pack(fmt, offset), data)) offset += (len(data) + 1) // 2 * 2 # pad to word # update strip offset data to point beyond auxiliary data if stripoffsets is not None: tag, typ, count, value, data = entries[stripoffsets] if data: size, handler = self._load_dispatch[typ] values = [val + offset for val in handler(self, data, self.legacy_api)] data = self._write_dispatch[typ](self, *values) else: value = self._pack(fmt, self._unpack(fmt, value)[0] + offset) entries[stripoffsets] = tag, typ, count, value, data # pass 2: write entries to file for tag, typ, count, value, data in entries: logger.debug("%s %s %s %s %s", tag, typ, count, repr(value), repr(data)) result += self._pack( "HHQ8s" if self._bigtiff else "HHL4s", tag, typ, count, value ) # -- overwrite here for multi-page -- result += self._pack(fmt, 0) # end of entries # pass 3: write auxiliary data to file for tag, typ, count, value, data in entries: result += data if len(data) & 1: result += b"\0" return result def save(self, fp: IO[bytes]) -> int: if fp.tell() == 0: # skip TIFF header on subsequent pages fp.write(self._get_ifh()) offset = fp.tell() result = self.tobytes(offset) fp.write(result) return offset + len(result) ImageFileDirectory_v2._load_dispatch = _load_dispatch ImageFileDirectory_v2._write_dispatch = _write_dispatch for idx, name in TYPES.items(): name = name.replace(" ", "_") setattr(ImageFileDirectory_v2, f"load_{name}", _load_dispatch[idx][1]) setattr(ImageFileDirectory_v2, f"write_{name}", _write_dispatch[idx]) del _load_dispatch, _write_dispatch, idx, name # Legacy ImageFileDirectory support.
ImageFileDirectory_v2
python
pypa__pipenv
pipenv/vendor/packaging/tags.py
{ "start": 805, "end": 18883 }
class ____: """ A representation of the tag triple for a wheel. Instances are considered immutable and thus are hashable. Equality checking is also supported. """ __slots__ = ["_interpreter", "_abi", "_platform", "_hash"] def __init__(self, interpreter: str, abi: str, platform: str) -> None: self._interpreter = interpreter.lower() self._abi = abi.lower() self._platform = platform.lower() # The __hash__ of every single element in a Set[Tag] will be evaluated each time # that a set calls its `.disjoint()` method, which may be called hundreds of # times when scanning a page of links for packages with tags matching that # Set[Tag]. Pre-computing the value here produces significant speedups for # downstream consumers. self._hash = hash((self._interpreter, self._abi, self._platform)) @property def interpreter(self) -> str: return self._interpreter @property def abi(self) -> str: return self._abi @property def platform(self) -> str: return self._platform def __eq__(self, other: object) -> bool: if not isinstance(other, Tag): return NotImplemented return ( (self._hash == other._hash) # Short-circuit ASAP for perf reasons. and (self._platform == other._platform) and (self._abi == other._abi) and (self._interpreter == other._interpreter) ) def __hash__(self) -> int: return self._hash def __str__(self) -> str: return f"{self._interpreter}-{self._abi}-{self._platform}" def __repr__(self) -> str: return f"<{self} @ {id(self)}>" def parse_tag(tag: str) -> frozenset[Tag]: """ Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances. Returning a set is required due to the possibility that the tag is a compressed tag set. """ tags = set() interpreters, abis, platforms = tag.split("-") for interpreter in interpreters.split("."): for abi in abis.split("."): for platform_ in platforms.split("."): tags.add(Tag(interpreter, abi, platform_)) return frozenset(tags) def _get_config_var(name: str, warn: bool = False) -> int | str | None: value: int | str | None = sysconfig.get_config_var(name) if value is None and warn: logger.debug( "Config variable '%s' is unset, Python ABI tag may be incorrect", name ) return value def _normalize_string(string: str) -> str: return string.replace(".", "_").replace("-", "_").replace(" ", "_") def _is_threaded_cpython(abis: list[str]) -> bool: """ Determine if the ABI corresponds to a threaded (`--disable-gil`) build. The threaded builds are indicated by a "t" in the abiflags. """ if len(abis) == 0: return False # expect e.g., cp313 m = re.match(r"cp\d+(.*)", abis[0]) if not m: return False abiflags = m.group(1) return "t" in abiflags def _abi3_applies(python_version: PythonVersion, threading: bool) -> bool: """ Determine if the Python version supports abi3. PEP 384 was first implemented in Python 3.2. The threaded (`--disable-gil`) builds do not support abi3. """ return len(python_version) > 1 and tuple(python_version) >= (3, 2) and not threading def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> list[str]: py_version = tuple(py_version) # To allow for version comparison. abis = [] version = _version_nodot(py_version[:2]) threading = debug = pymalloc = ucs4 = "" with_debug = _get_config_var("Py_DEBUG", warn) has_refcount = hasattr(sys, "gettotalrefcount") # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled # extension modules is the best option. # https://github.com/pypa/pip/issues/3383#issuecomment-173267692 has_ext = "_d.pyd" in EXTENSION_SUFFIXES if with_debug or (with_debug is None and (has_refcount or has_ext)): debug = "d" if py_version >= (3, 13) and _get_config_var("Py_GIL_DISABLED", warn): threading = "t" if py_version < (3, 8): with_pymalloc = _get_config_var("WITH_PYMALLOC", warn) if with_pymalloc or with_pymalloc is None: pymalloc = "m" if py_version < (3, 3): unicode_size = _get_config_var("Py_UNICODE_SIZE", warn) if unicode_size == 4 or ( unicode_size is None and sys.maxunicode == 0x10FFFF ): ucs4 = "u" elif debug: # Debug builds can also load "normal" extension modules. # We can also assume no UCS-4 or pymalloc requirement. abis.append(f"cp{version}{threading}") abis.insert(0, f"cp{version}{threading}{debug}{pymalloc}{ucs4}") return abis def cpython_tags( python_version: PythonVersion | None = None, abis: Iterable[str] | None = None, platforms: Iterable[str] | None = None, *, warn: bool = False, ) -> Iterator[Tag]: """ Yields the tags for a CPython interpreter. The tags consist of: - cp<python_version>-<abi>-<platform> - cp<python_version>-abi3-<platform> - cp<python_version>-none-<platform> - cp<less than python_version>-abi3-<platform> # Older Python versions down to 3.2. If python_version only specifies a major version then user-provided ABIs and the 'none' ABItag will be used. If 'abi3' or 'none' are specified in 'abis' then they will be yielded at their normal position and not at the beginning. """ if not python_version: python_version = sys.version_info[:2] interpreter = f"cp{_version_nodot(python_version[:2])}" if abis is None: if len(python_version) > 1: abis = _cpython_abis(python_version, warn) else: abis = [] abis = list(abis) # 'abi3' and 'none' are explicitly handled later. for explicit_abi in ("abi3", "none"): try: abis.remove(explicit_abi) except ValueError: pass platforms = list(platforms or platform_tags()) for abi in abis: for platform_ in platforms: yield Tag(interpreter, abi, platform_) threading = _is_threaded_cpython(abis) use_abi3 = _abi3_applies(python_version, threading) if use_abi3: yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms) yield from (Tag(interpreter, "none", platform_) for platform_ in platforms) if use_abi3: for minor_version in range(python_version[1] - 1, 1, -1): for platform_ in platforms: interpreter = "cp{version}".format( version=_version_nodot((python_version[0], minor_version)) ) yield Tag(interpreter, "abi3", platform_) def _generic_abi() -> list[str]: """ Return the ABI tag based on EXT_SUFFIX. """ # The following are examples of `EXT_SUFFIX`. # We want to keep the parts which are related to the ABI and remove the # parts which are related to the platform: # - linux: '.cpython-310-x86_64-linux-gnu.so' => cp310 # - mac: '.cpython-310-darwin.so' => cp310 # - win: '.cp310-win_amd64.pyd' => cp310 # - win: '.pyd' => cp37 (uses _cpython_abis()) # - pypy: '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73 # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib' # => graalpy_38_native ext_suffix = _get_config_var("EXT_SUFFIX", warn=True) if not isinstance(ext_suffix, str) or ext_suffix[0] != ".": raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')") parts = ext_suffix.split(".") if len(parts) < 3: # CPython3.7 and earlier uses ".pyd" on Windows. return _cpython_abis(sys.version_info[:2]) soabi = parts[1] if soabi.startswith("cpython"): # non-windows abi = "cp" + soabi.split("-")[1] elif soabi.startswith("cp"): # windows abi = soabi.split("-")[0] elif soabi.startswith("pypy"): abi = "-".join(soabi.split("-")[:2]) elif soabi.startswith("graalpy"): abi = "-".join(soabi.split("-")[:3]) elif soabi: # pyston, ironpython, others? abi = soabi else: return [] return [_normalize_string(abi)] def generic_tags( interpreter: str | None = None, abis: Iterable[str] | None = None, platforms: Iterable[str] | None = None, *, warn: bool = False, ) -> Iterator[Tag]: """ Yields the tags for a generic interpreter. The tags consist of: - <interpreter>-<abi>-<platform> The "none" ABI will be added if it was not explicitly provided. """ if not interpreter: interp_name = interpreter_name() interp_version = interpreter_version(warn=warn) interpreter = "".join([interp_name, interp_version]) if abis is None: abis = _generic_abi() else: abis = list(abis) platforms = list(platforms or platform_tags()) if "none" not in abis: abis.append("none") for abi in abis: for platform_ in platforms: yield Tag(interpreter, abi, platform_) def _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]: """ Yields Python versions in descending order. After the latest version, the major-only version will be yielded, and then all previous versions of that major version. """ if len(py_version) > 1: yield f"py{_version_nodot(py_version[:2])}" yield f"py{py_version[0]}" if len(py_version) > 1: for minor in range(py_version[1] - 1, -1, -1): yield f"py{_version_nodot((py_version[0], minor))}" def compatible_tags( python_version: PythonVersion | None = None, interpreter: str | None = None, platforms: Iterable[str] | None = None, ) -> Iterator[Tag]: """ Yields the sequence of tags that are compatible with a specific version of Python. The tags consist of: - py*-none-<platform> - <interpreter>-none-any # ... if `interpreter` is provided. - py*-none-any """ if not python_version: python_version = sys.version_info[:2] platforms = list(platforms or platform_tags()) for version in _py_interpreter_range(python_version): for platform_ in platforms: yield Tag(version, "none", platform_) if interpreter: yield Tag(interpreter, "none", "any") for version in _py_interpreter_range(python_version): yield Tag(version, "none", "any") def _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str: if not is_32bit: return arch if arch.startswith("ppc"): return "ppc" return "i386" def _mac_binary_formats(version: MacVersion, cpu_arch: str) -> list[str]: formats = [cpu_arch] if cpu_arch == "x86_64": if version < (10, 4): return [] formats.extend(["intel", "fat64", "fat32"]) elif cpu_arch == "i386": if version < (10, 4): return [] formats.extend(["intel", "fat32", "fat"]) elif cpu_arch == "ppc64": # TODO: Need to care about 32-bit PPC for ppc64 through 10.2? if version > (10, 5) or version < (10, 4): return [] formats.append("fat64") elif cpu_arch == "ppc": if version > (10, 6): return [] formats.extend(["fat32", "fat"]) if cpu_arch in {"arm64", "x86_64"}: formats.append("universal2") if cpu_arch in {"x86_64", "i386", "ppc64", "ppc", "intel"}: formats.append("universal") return formats def mac_platforms( version: MacVersion | None = None, arch: str | None = None ) -> Iterator[str]: """ Yields the platform tags for a macOS system. The `version` parameter is a two-item tuple specifying the macOS version to generate platform tags for. The `arch` parameter is the CPU architecture to generate platform tags for. Both parameters default to the appropriate value for the current system. """ version_str, _, cpu_arch = platform.mac_ver() if version is None: version = cast("MacVersion", tuple(map(int, version_str.split(".")[:2]))) if version == (10, 16): # When built against an older macOS SDK, Python will report macOS 10.16 # instead of the real version. version_str = subprocess.run( [ sys.executable, "-sS", "-c", "import platform; print(platform.mac_ver()[0])", ], check=True, env={"SYSTEM_VERSION_COMPAT": "0"}, stdout=subprocess.PIPE, text=True, ).stdout version = cast("MacVersion", tuple(map(int, version_str.split(".")[:2]))) else: version = version if arch is None: arch = _mac_arch(cpu_arch) else: arch = arch if (10, 0) <= version and version < (11, 0): # Prior to Mac OS 11, each yearly release of Mac OS bumped the # "minor" version number. The major version was always 10. for minor_version in range(version[1], -1, -1): compat_version = 10, minor_version binary_formats = _mac_binary_formats(compat_version, arch) for binary_format in binary_formats: yield "macosx_{major}_{minor}_{binary_format}".format( major=10, minor=minor_version, binary_format=binary_format ) if version >= (11, 0): # Starting with Mac OS 11, each yearly release bumps the major version # number. The minor versions are now the midyear updates. for major_version in range(version[0], 10, -1): compat_version = major_version, 0 binary_formats = _mac_binary_formats(compat_version, arch) for binary_format in binary_formats: yield "macosx_{major}_{minor}_{binary_format}".format( major=major_version, minor=0, binary_format=binary_format ) if version >= (11, 0): # Mac OS 11 on x86_64 is compatible with binaries from previous releases. # Arm64 support was introduced in 11.0, so no Arm binaries from previous # releases exist. # # However, the "universal2" binary format can have a # macOS version earlier than 11.0 when the x86_64 part of the binary supports # that version of macOS. if arch == "x86_64": for minor_version in range(16, 3, -1): compat_version = 10, minor_version binary_formats = _mac_binary_formats(compat_version, arch) for binary_format in binary_formats: yield "macosx_{major}_{minor}_{binary_format}".format( major=compat_version[0], minor=compat_version[1], binary_format=binary_format, ) else: for minor_version in range(16, 3, -1): compat_version = 10, minor_version binary_format = "universal2" yield "macosx_{major}_{minor}_{binary_format}".format( major=compat_version[0], minor=compat_version[1], binary_format=binary_format, ) def _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]: linux = _normalize_string(sysconfig.get_platform()) if not linux.startswith("linux_"): # we should never be here, just yield the sysconfig one and return yield linux return if is_32bit: if linux == "linux_x86_64": linux = "linux_i686" elif linux == "linux_aarch64": linux = "linux_armv8l" _, arch = linux.split("_", 1) archs = {"armv8l": ["armv8l", "armv7l"]}.get(arch, [arch]) yield from _manylinux.platform_tags(archs) yield from _musllinux.platform_tags(archs) for arch in archs: yield f"linux_{arch}" def _generic_platforms() -> Iterator[str]: yield _normalize_string(sysconfig.get_platform()) def platform_tags() -> Iterator[str]: """ Provides the platform tags for this installation. """ if platform.system() == "Darwin": return mac_platforms() elif platform.system() == "Linux": return _linux_platforms() else: return _generic_platforms() def interpreter_name() -> str: """ Returns the name of the running interpreter. Some implementations have a reserved, two-letter abbreviation which will be returned when appropriate. """ name = sys.implementation.name return INTERPRETER_SHORT_NAMES.get(name) or name def interpreter_version(*, warn: bool = False) -> str: """ Returns the version of the running interpreter. """ version = _get_config_var("py_version_nodot", warn=warn) if version: version = str(version) else: version = _version_nodot(sys.version_info[:2]) return version def _version_nodot(version: PythonVersion) -> str: return "".join(map(str, version)) def sys_tags(*, warn: bool = False) -> Iterator[Tag]: """ Returns the sequence of tag triples for the running interpreter. The order of the sequence corresponds to priority order for the interpreter, from most to least important. """ interp_name = interpreter_name() if interp_name == "cp": yield from cpython_tags(warn=warn) else: yield from generic_tags() if interp_name == "pp": interp = "pp3" elif interp_name == "cp": interp = "cp" + interpreter_version(warn=warn) else: interp = None yield from compatible_tags(interpreter=interp)
Tag
python
getsentry__sentry
src/sentry/testutils/outbox.py
{ "start": 545, "end": 4901 }
class ____(Exception): pass @contextlib.contextmanager def outbox_runner(wrapped: Any | None = None) -> Any: """ A context manager that, upon *successful exit*, executes all pending outbox jobs that are scheduled for the current time, synchronously. Exceptions block further processing as written -- to test retry cases, use the inner implementation functions directly. """ if callable(wrapped): def wrapper(*args: Any, **kwargs: Any) -> Any: assert callable(wrapped) with outbox_runner(): return wrapped(*args, **kwargs) functools.update_wrapper(wrapper, wrapped) return wrapper yield from sentry.testutils.helpers.task_runner import TaskRunner with TaskRunner(), assume_test_silo_mode(SiloMode.MONOLITH): for i in range(10): enqueue_outbox_jobs(concurrency=1, process_outbox_backfills=False) enqueue_outbox_jobs_control(concurrency=1, process_outbox_backfills=False) if not any( OutboxBase.from_outbox_name(outbox_name).find_scheduled_shards() for outbox_names in settings.SENTRY_OUTBOX_MODELS.values() for outbox_name in outbox_names ): break else: raise OutboxRecursionLimitError def assert_no_webhook_payloads() -> None: messages = WebhookPayload.objects.filter().count() assert messages == 0, "No webhookpayload messages should be created" def assert_webhook_payloads_for_mailbox( request: WSGIRequest, mailbox_name: str, region_names: list[str], destination_types: dict[DestinationType, int] | None = None, ) -> None: """ A test method for asserting that a webhook payload is properly queued for the given request :param request: :param mailbox_name: The mailbox name that messages should be found in. :param region_names: Optional list of regions each messages should be queued for :param destination_types: Optional Mapping of destination types to the number of messages that should be found for that destination type """ expected_payload = WebhookPayload.get_attributes_from_request(request=request) region_names_set = set(region_names) messages = WebhookPayload.objects.filter(mailbox_name=mailbox_name) messages_with_region_count = messages.filter(region_name__isnull=False).count() if messages_with_region_count != len(region_names_set): raise Exception( f"Mismatch: Found {messages_with_region_count} WebhookPayload but {len(region_names_set)} region_names" ) for message in messages: assert message.request_method == expected_payload["request_method"] assert message.request_path == expected_payload["request_path"] assert message.request_headers == expected_payload["request_headers"] assert message.request_body == expected_payload["request_body"] assert message.schedule_for == THE_PAST assert message.attempts == 0 if destination_types: destination_type = DestinationType(message.destination_type) assert destination_type in destination_types destination_types[destination_type] -= 1 if destination_types[destination_type] == 0: del destination_types[destination_type] if message.destination_type == DestinationType.CODECOV: assert message.region_name is None else: assert message.region_name is not None try: region_names_set.remove(message.region_name) except KeyError: raise Exception( f"Found ControlOutbox for '{message.region_name}', which was not in region_names: {str(region_names_set)}" ) if len(region_names_set) != 0: raise Exception(f"WebhookPayload not found for some region_names: {str(region_names_set)}") if destination_types and len(destination_types) != 0: exc_strs = [ f"Missing {count} WebhookPayloads for {destination_type}" for destination_type, count in destination_types.items() ] raise Exception( f"Not enough WebhookPayloads found for some destination_types:\n{"\n".join(exc_strs)}" )
OutboxRecursionLimitError
python
walkccc__LeetCode
solutions/3153. Sum of Digit Differences of All Pairs/3153.py
{ "start": 0, "end": 378 }
class ____: def sumDigitDifferences(self, nums: list[int]) -> int: n = len(nums) digitSize = len(str(nums[0])) ans = 0 denominator = 1 for _ in range(digitSize): count = [0] * 10 for num in nums: count[num // denominator % 10] += 1 ans += sum(freq * (n - freq) for freq in count) denominator *= 10 return ans // 2
Solution
python
joerick__pyinstrument
pyinstrument/context_manager.py
{ "start": 438, "end": 646 }
class ____(typing.TypedDict, total=False): interval: float async_mode: AsyncMode use_timing_thread: bool | None renderer: Renderer | None target_description: str | None
ProfileContextOptions
python
wandb__wandb
wandb/sdk/launch/runner/kubernetes_monitor.py
{ "start": 1026, "end": 5578 }
class ____: """Class for custom resources.""" def __init__(self, group: str, version: str, plural: str) -> None: """Initialize the CustomResource.""" self.group = group self.version = version self.plural = plural def __str__(self) -> str: """Return a string representation of the CustomResource.""" return f"{self.group}/{self.version}/{self.plural}" def __hash__(self) -> int: """Return a hash of the CustomResource.""" return hash(str(self)) # Maps phases and conditions of custom objects to agent's internal run states. CRD_STATE_DICT: Dict[str, State] = { "created": "starting", "pending": "starting", "running": "running", "completing": "running", "succeeded": "finished", "completed": "finished", "failed": "failed", "aborted": "failed", "timeout": "failed", "terminated": "failed", "terminating": "stopping", } _logger = logging.getLogger(__name__) def create_named_task(name: str, coro: Any, *args: Any, **kwargs: Any) -> asyncio.Task: """Create a named task.""" task = asyncio.create_task(coro(*args, **kwargs)) task.set_name(name) task.add_done_callback(_log_err_task_callback) return task def _log_err_task_callback(task: asyncio.Task) -> None: """Callback to log exceptions from tasks.""" exec = task.exception() if exec is not None: if isinstance(exec, asyncio.CancelledError): wandb.termlog(f"Task {task.get_name()} was cancelled") return name = task.get_name() wandb.termerror(f"Exception in task {name}") tb = exec.__traceback__ tb_str = "".join(traceback.format_tb(tb)) wandb.termerror(tb_str) def _is_preempted(status: "V1PodStatus") -> bool: """Check if this pod has been preempted.""" if hasattr(status, "conditions") and status.conditions is not None: for condition in status.conditions: if condition.type == "DisruptionTarget" and condition.reason in [ "EvictionByEvictionAPI", "PreemptionByScheduler", "TerminationByKubelet", ]: return True return False def _is_container_creating(status: "V1PodStatus") -> bool: """Check if this pod has started creating containers.""" for container_status in status.container_statuses or []: if ( container_status.state and container_status.state.waiting and container_status.state.waiting.reason == "ContainerCreating" ): return True return False def _is_pod_unschedulable(status: "V1PodStatus") -> Tuple[bool, str]: """Return whether the pod is unschedulable along with the reason message.""" if not status.conditions: return False, "" for condition in status.conditions: if ( condition.type == "PodScheduled" and condition.status == "False" and condition.reason == "Unschedulable" ): return True, condition.message return False, "" def _get_crd_job_name(object: "V1Pod") -> Optional[str]: refs = object.metadata.owner_references if refs: return refs[0].name return None def _state_from_conditions(conditions: List[Dict[str, Any]]) -> Optional[State]: """Get the status from the pod conditions.""" true_conditions = [ c.get("type", "").lower() for c in conditions if c.get("status") == "True" ] detected_states = { CRD_STATE_DICT[c] for c in true_conditions if c in CRD_STATE_DICT } # The list below is ordered so that returning the first state detected # will accurately reflect the state of the job. states_in_order: List[State] = [ "finished", "failed", "stopping", "running", "starting", ] for state in states_in_order: if state in detected_states: return state return None def _state_from_replicated_status(status_dict: Dict[str, int]) -> Optional[State]: """Infer overall job status from replicated job status for jobsets. More info on jobset: https://github.com/kubernetes-sigs/jobset/blob/main/docs/concepts/README.md This is useful for detecting when jobsets are starting. """ pods_ready = status_dict.get("ready", 0) pods_active = status_dict.get("active", 0) if pods_ready >= 1: return "running" elif pods_active >= 1: return "starting" return None
CustomResource
python
huggingface__transformers
tests/models/clvp/test_modeling_clvp.py
{ "start": 20710, "end": 24731 }
class ____(unittest.TestCase): def setUp(self): self.text = "This is an example text." ds = datasets.load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") ds = ds.cast_column("audio", datasets.Audio(sampling_rate=22050)) audio = ds.sort("id")["audio"][0] self.speech_samples, self.sr = audio["array"], audio["sampling_rate"] self.model = ClvpModelForConditionalGeneration.from_pretrained("susnato/clvp_dev").to(torch_device) self.model.eval() tokenizer = ClvpTokenizer.from_pretrained("susnato/clvp_dev") feature_extractor = ClvpFeatureExtractor.from_pretrained("susnato/clvp_dev") tokenizer_output = tokenizer(self.text, return_tensors="pt") self.text_tokens = tokenizer_output["input_ids"].to(torch_device) self.input_features = feature_extractor( raw_speech=self.speech_samples, sampling_rate=self.sr, return_tensors="pt" )["input_features"].to(torch_device) def tearDown(self): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch cleanup(torch_device, gc_collect=True) def test_conditional_encoder(self): with torch.no_grad(): conditioning_encoder_outputs = self.model.conditioning_encoder( input_features=self.input_features, input_ids=self.text_tokens ).to("cpu") self.assertEqual( conditioning_encoder_outputs.shape, torch.Size((self.input_features.shape[0], 18, self.model.config.decoder_config.hidden_size)), ) EXPECTED_OUTPUTS = torch.tensor( [[-0.8582, 0.5228, 1.9944], [-0.0465, -1.1017, -0.0093], [-0.0466, -0.6030, -0.1280]] ) torch.testing.assert_close(conditioning_encoder_outputs[0, :3, :3], EXPECTED_OUTPUTS, rtol=1e-4, atol=1e-4) def test_decoder_model_generate(self): autoregressive_model_output = self.model.speech_decoder_model.generate(input_ids=self.text_tokens).cpu() EXPECTED_OUTPUTS = torch.tensor([[147, 2, 54, 2, 43, 2, 169, 122, 29, 64, 2, 136, 37, 33, 9, 8193]]) torch.testing.assert_close(autoregressive_model_output, EXPECTED_OUTPUTS) def test_text_and_speech_encoder_models(self): # check for text embeds text_embeds = self.model.text_encoder_model(input_ids=self.text_tokens, return_dict=True)[0].cpu() # fmt: off EXPECTED_TEXT_EMBEDS = torch.tensor([1.4798, -2.0005, 2.3902, -0.5042, 1.6401, -2.4135, -1.4800, 3.0118, -2.4422, 1.3266, 2.2339, 1.4761, -4.8983, -1.3592, 6.0251, 6.7364, 2.2576, 3.7229, -10.0436, 4.6676]) # fmt: on torch.testing.assert_close(text_embeds[0, :20], EXPECTED_TEXT_EMBEDS, rtol=1e-4, atol=1e-4) # check for speech embeds speech_embeds = self.model.speech_encoder_model(input_ids=self.text_tokens, return_dict=True)[0].cpu() # fmt: off EXPECTED_SPEECH_EMBEDS = torch.tensor([3.1202, -3.1183, -1.4264, -6.1339, 1.8885, -0.1983, 0.9461, -1.7414, 0.3320, -3.8400, -1.5715, 1.5096, -1.7576, 0.2387, 4.9758, 5.8450, -6.2534, 2.8587, -5.5816, 4.7821]) # fmt: on torch.testing.assert_close(speech_embeds[0, :20], EXPECTED_SPEECH_EMBEDS, rtol=1e-4, atol=1e-4) def test_full_model_integration(self): full_model_output = self.model.generate( input_ids=self.text_tokens, input_features=self.input_features, do_sample=False, num_beams=4, num_return_sequences=4, max_new_tokens=10, ) EXPECTED_SPEECH_IDS = torch.tensor([[1953, 1080, 612], [1953, 612, 493], [1953, 612, 716]]) EXPECTED_SIMILARITY_SCORES = torch.tensor([[14.7660, 14.4569, 13.6472, 13.5683]]) torch.testing.assert_close(full_model_output.speech_ids.cpu()[-3:, -3:], EXPECTED_SPEECH_IDS) torch.testing.assert_close(full_model_output.logits_per_text.cpu(), EXPECTED_SIMILARITY_SCORES)
ClvpIntegrationTest
python
pypa__pipenv
pipenv/vendor/click_didyoumean/__init__.py
{ "start": 160, "end": 1683 }
class ____: """ Mixin class for click MultiCommand inherited classes to provide git-like *did-you-mean* functionality when a certain command is not registered. """ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: self.max_suggestions = kwargs.pop("max_suggestions", 3) self.cutoff = kwargs.pop("cutoff", 0.5) super().__init__(*args, **kwargs) # type: ignore def resolve_command( self, ctx: click.Context, args: typing.List[str] ) -> typing.Tuple[ typing.Optional[str], typing.Optional[click.Command], typing.List[str] ]: """ Overrides clicks ``resolve_command`` method and appends *Did you mean ...* suggestions to the raised exception message. """ try: return super(DYMMixin, self).resolve_command(ctx, args) # type: ignore except click.exceptions.UsageError as error: error_msg = str(error) original_cmd_name = click.utils.make_str(args[0]) matches = difflib.get_close_matches( original_cmd_name, self.list_commands(ctx), # type: ignore self.max_suggestions, self.cutoff, ) if matches: fmt_matches = "\n ".join(matches) error_msg += "\n\n" error_msg += f"Did you mean one of these?\n {fmt_matches}" raise click.exceptions.UsageError(error_msg, error.ctx)
DYMMixin
python
django__django
django/contrib/admin/helpers.py
{ "start": 15214, "end": 17483 }
class ____(AdminForm): """ A wrapper around an inline form for use in the admin system. """ def __init__( self, formset, form, fieldsets, prepopulated_fields, original, readonly_fields=None, model_admin=None, view_on_site_url=None, ): self.formset = formset self.model_admin = model_admin self.original = original self.show_url = original and view_on_site_url is not None self.absolute_url = view_on_site_url super().__init__( form, fieldsets, prepopulated_fields, readonly_fields, model_admin ) def __iter__(self): for name, options in self.fieldsets: yield InlineFieldset( self.formset, self.form, name, self.readonly_fields, model_admin=self.model_admin, **options, ) def needs_explicit_pk_field(self): return ( # Auto fields are editable, so check for auto or non-editable pk. self.form._meta.model._meta.auto_field or not self.form._meta.model._meta.pk.editable # The pk can be editable, but excluded from the inline. or ( self.form._meta.exclude and self.form._meta.model._meta.pk.name in self.form._meta.exclude ) or # Also search any parents for an auto field. (The pk info is # propagated to child models so that does not need to be checked # in parents.) any( parent._meta.auto_field or not parent._meta.model._meta.pk.editable for parent in self.form._meta.model._meta.all_parents ) ) def pk_field(self): return AdminField(self.form, self.formset._pk_field.name, False) def fk_field(self): fk = getattr(self.formset, "fk", None) if fk: return AdminField(self.form, fk.name, False) else: return "" def deletion_field(self): from django.forms.formsets import DELETION_FIELD_NAME return AdminField(self.form, DELETION_FIELD_NAME, False)
InlineAdminForm
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1162146, "end": 1162789 }
class ____(sgqlc.types.Type, Node): """A subset of repository information queryable from an enterprise.""" __schema__ = github_schema __field_names__ = ("is_private", "name", "name_with_owner") is_private = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="isPrivate") """Identifies if the repository is private or internal.""" name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name") """The repository's name.""" name_with_owner = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="nameWithOwner") """The repository's name with owner."""
EnterpriseRepositoryInfo
python
tensorflow__tensorflow
tensorflow/python/framework/function_test.py
{ "start": 47282, "end": 48126 }
class ____(test.TestCase): @test_util.run_deprecated_v1 def testCaptureByValue(self): g = ops.Graph() with g.as_default(): w = constant_op.constant([[1.0]]) b = constant_op.constant([2.0]) # Foo() captures w and b. @function.Defun(dtypes.float32, capture_by_value=True) def Foo(x): # Plus() captures b. @function.Defun(dtypes.float32, capture_by_value=True) def Plus(y): return y + b self.assertEqual(0, len(Plus.captured_inputs)) return Plus(math_ops.matmul(w, x)) y = Foo(constant_op.constant([[10.]])) self.assertEqual(0, len(Foo.captured_inputs)) with self.session(graph=g): self.assertAllEqual(y, [[12.0]]) @test_util.run_all_without_tensor_float_32( "Calls matmul in custom LSTM function")
FunctionCaptureByValueTest
python
run-llama__llama_index
llama-index-integrations/protocols/llama-index-protocols-ag-ui/llama_index/protocols/ag_ui/events.py
{ "start": 929, "end": 1043 }
class ____(TextMessageEndEvent, Event): type: EventType = EventType.TEXT_MESSAGE_END
TextMessageEndWorkflowEvent
python
spack__spack
lib/spack/spack/vendor/macholib/mach_o.py
{ "start": 12946, "end": 13047 }
class ____(mach_header): _fields_ = mach_header._fields_ + (("reserved", p_uint32),)
mach_header_64
python
django__django
django/contrib/contenttypes/migrations/0002_remove_content_type_name.py
{ "start": 411, "end": 1199 }
class ____(migrations.Migration): dependencies = [ ("contenttypes", "0001_initial"), ] operations = [ migrations.AlterModelOptions( name="contenttype", options={ "verbose_name": "content type", "verbose_name_plural": "content types", }, ), migrations.AlterField( model_name="contenttype", name="name", field=models.CharField(max_length=100, null=True), ), migrations.RunPython( migrations.RunPython.noop, add_legacy_name, hints={"model_name": "contenttype"}, ), migrations.RemoveField( model_name="contenttype", name="name", ), ]
Migration
python
ray-project__ray
python/ray/tests/unit/test_runtime_env_validation.py
{ "start": 5696, "end": 6226 }
class ____: def test_validate_excludes_invalid_types(self): with pytest.raises(TypeError): parse_and_validate_excludes(1) with pytest.raises(TypeError): parse_and_validate_excludes(True) with pytest.raises(TypeError): parse_and_validate_excludes("string") with pytest.raises(TypeError): parse_and_validate_excludes(["string", 1]) def test_validate_excludes_empty_list(self): assert RuntimeEnv(excludes=[]) == {}
TestValidateExcludes
python
pypa__virtualenv
docs/render_cli.py
{ "start": 395, "end": 499 }
class ____(NamedTuple): names: list[str] default: str choices: set[str] help: str
TableRow
python
pandas-dev__pandas
pandas/tests/frame/test_repr.py
{ "start": 371, "end": 15888 }
class ____: def test_repr_should_return_str(self): # https://docs.python.org/3/reference/datamodel.html#object.__repr__ # "...The return value must be a string object." # (str on py2.x, str (unicode) on py3) data = [8, 5, 3, 5] index1 = ["\u03c3", "\u03c4", "\u03c5", "\u03c6"] cols = ["\u03c8"] df = DataFrame(data, columns=cols, index=index1) assert type(df.__repr__()) is str ser = df[cols[0]] assert type(ser.__repr__()) is str def test_repr_bytes_61_lines(self): # GH#12857 lets = list("ACDEFGHIJKLMNOP") words = np.random.default_rng(2).choice(lets, (1000, 50)) df = DataFrame(words).astype("U1") assert (df.dtypes == object).all() # smoke tests; at one point this raised with 61 but not 60 repr(df) repr(df.iloc[:60, :]) repr(df.iloc[:61, :]) def test_repr_unicode_level_names(self, frame_or_series): index = MultiIndex.from_tuples([(0, 0), (1, 1)], names=["\u0394", "i1"]) obj = DataFrame(np.random.default_rng(2).standard_normal((2, 4)), index=index) obj = tm.get_obj(obj, frame_or_series) repr(obj) def test_assign_index_sequences(self): # GH#2200 df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}).set_index( ["a", "b"] ) index = list(df.index) index[0] = ("faz", "boo") df.index = index repr(df) # this travels an improper code path index[0] = ["faz", "boo"] df.index = index repr(df) def test_repr_with_mi_nat(self): df = DataFrame({"X": [1, 2]}, index=[[NaT, Timestamp("20130101")], ["a", "b"]]) result = repr(df) expected = " X\nNaT a 1\n2013-01-01 b 2" assert result == expected def test_repr_with_different_nulls(self): # GH45263 df = DataFrame([1, 2, 3, 4], [True, None, np.nan, NaT]) result = repr(df) expected = """ 0 True 1 None 2 NaN 3 NaT 4""" assert result == expected def test_repr_with_different_nulls_cols(self): # GH45263 d = {np.nan: [1, 2], None: [3, 4], NaT: [6, 7], True: [8, 9]} df = DataFrame(data=d) result = repr(df) expected = """ NaN None NaT True 0 1 3 6 8 1 2 4 7 9""" assert result == expected def test_multiindex_na_repr(self): # only an issue with long columns df3 = DataFrame( { "A" * 30: {("A", "A0006000", "nuit"): "A0006000"}, "B" * 30: {("A", "A0006000", "nuit"): np.nan}, "C" * 30: {("A", "A0006000", "nuit"): np.nan}, "D" * 30: {("A", "A0006000", "nuit"): np.nan}, "E" * 30: {("A", "A0006000", "nuit"): "A"}, "F" * 30: {("A", "A0006000", "nuit"): np.nan}, } ) idf = df3.set_index(["A" * 30, "C" * 30]) repr(idf) def test_repr_name_coincide(self): index = MultiIndex.from_tuples( [("a", 0, "foo"), ("b", 1, "bar")], names=["a", "b", "c"] ) df = DataFrame({"value": [0, 1]}, index=index) lines = repr(df).split("\n") assert lines[2].startswith("a 0 foo") def test_repr_to_string( self, multiindex_year_month_day_dataframe_random_data, multiindex_dataframe_random_data, ): ymd = multiindex_year_month_day_dataframe_random_data frame = multiindex_dataframe_random_data repr(frame) repr(ymd) repr(frame.T) repr(ymd.T) buf = StringIO() frame.to_string(buf=buf) ymd.to_string(buf=buf) frame.T.to_string(buf=buf) ymd.T.to_string(buf=buf) def test_repr_empty(self): # empty repr(DataFrame()) # empty with index frame = DataFrame(index=np.arange(1000)) repr(frame) def test_repr_mixed(self, float_string_frame): # mixed repr(float_string_frame) @pytest.mark.slow def test_repr_mixed_big(self): # big mixed biggie = DataFrame( { "A": np.random.default_rng(2).standard_normal(200), "B": [str(i) for i in range(200)], }, index=range(200), ) biggie.loc[:20, "A"] = np.nan biggie.loc[:20, "B"] = np.nan repr(biggie) def test_repr(self): # columns but no index no_index = DataFrame(columns=[0, 1, 3]) repr(no_index) df = DataFrame(["a\n\r\tb"], columns=["a\n\r\td"], index=["a\n\r\tf"]) assert "\t" not in repr(df) assert "\r" not in repr(df) assert "a\n" not in repr(df) def test_repr_dimensions(self): df = DataFrame([[1, 2], [3, 4]]) with option_context("display.show_dimensions", True): assert "2 rows x 2 columns" in repr(df) with option_context("display.show_dimensions", False): assert "2 rows x 2 columns" not in repr(df) with option_context("display.show_dimensions", "truncate"): assert "2 rows x 2 columns" not in repr(df) @pytest.mark.slow def test_repr_big(self): # big one biggie = DataFrame(np.zeros((200, 4)), columns=range(4), index=range(200)) repr(biggie) def test_repr_unsortable(self): # columns are not sortable unsortable = DataFrame( { "foo": [1] * 50, datetime.today(): [1] * 50, "bar": ["bar"] * 50, datetime.today() + timedelta(1): ["bar"] * 50, }, index=np.arange(50), ) repr(unsortable) def test_repr_float_frame_options(self, float_frame): repr(float_frame) with option_context("display.precision", 3): repr(float_frame) with option_context("display.max_rows", 10, "display.max_columns", 2): repr(float_frame) with option_context("display.max_rows", 1000, "display.max_columns", 1000): repr(float_frame) def test_repr_unicode(self): uval = "\u03c3\u03c3\u03c3\u03c3" df = DataFrame({"A": [uval, uval]}) result = repr(df) ex_top = " A" assert result.split("\n")[0].rstrip() == ex_top df = DataFrame({"A": [uval, uval]}) result = repr(df) assert result.split("\n")[0].rstrip() == ex_top def test_unicode_string_with_unicode(self): df = DataFrame({"A": ["\u05d0"]}) str(df) def test_repr_unicode_columns(self): df = DataFrame({"\u05d0": [1, 2, 3], "\u05d1": [4, 5, 6], "c": [7, 8, 9]}) repr(df.columns) # should not raise UnicodeDecodeError def test_str_to_bytes_raises(self): # GH 26447 df = DataFrame({"A": ["abc"]}) msg = "^'str' object cannot be interpreted as an integer$" with pytest.raises(TypeError, match=msg): bytes(df) def test_very_wide_repr(self): df = DataFrame( np.random.default_rng(2).standard_normal((10, 20)), columns=np.array(["a" * 10] * 20, dtype=object), ) repr(df) def test_repr_column_name_unicode_truncation_bug(self): # #1906 df = DataFrame( { "Id": [7117434], "StringCol": ( "Is it possible to modify drop plot code" "so that the output graph is displayed " "in iphone simulator, Is it possible to " "modify drop plot code so that the " "output graph is \xe2\x80\xa8displayed " "in iphone simulator.Now we are adding " "the CSV file externally. I want to Call " "the File through the code.." ), } ) with option_context("display.max_columns", 20): assert "StringCol" in repr(df) def test_latex_repr(self): pytest.importorskip("jinja2") expected = r"""\begin{tabular}{llll} \toprule & 0 & 1 & 2 \\ \midrule 0 & $\alpha$ & b & c \\ 1 & 1 & 2 & 3 \\ \bottomrule \end{tabular} """ with option_context( "styler.format.escape", None, "styler.render.repr", "latex" ): df = DataFrame([[r"$\alpha$", "b", "c"], [1, 2, 3]]) result = df._repr_latex_() assert result == expected # GH 12182 assert df._repr_latex_() is None def test_repr_with_datetimeindex(self): df = DataFrame({"A": [1, 2, 3]}, index=date_range("2000", periods=3)) result = repr(df) expected = " A\n2000-01-01 1\n2000-01-02 2\n2000-01-03 3" assert result == expected def test_repr_with_intervalindex(self): # https://github.com/pandas-dev/pandas/pull/24134/files df = DataFrame( {"A": [1, 2, 3, 4]}, index=IntervalIndex.from_breaks([0, 1, 2, 3, 4]) ) result = repr(df) expected = " A\n(0, 1] 1\n(1, 2] 2\n(2, 3] 3\n(3, 4] 4" assert result == expected def test_repr_with_categorical_index(self): df = DataFrame({"A": [1, 2, 3]}, index=CategoricalIndex(["a", "b", "c"])) result = repr(df) expected = " A\na 1\nb 2\nc 3" assert result == expected def test_repr_categorical_dates_periods(self): # normal DataFrame dt = date_range("2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern") p = period_range("2011-01", freq="M", periods=5) df = DataFrame({"dt": dt, "p": p}) exp = """ dt p 0 2011-01-01 09:00:00-05:00 2011-01 1 2011-01-01 10:00:00-05:00 2011-02 2 2011-01-01 11:00:00-05:00 2011-03 3 2011-01-01 12:00:00-05:00 2011-04 4 2011-01-01 13:00:00-05:00 2011-05""" assert repr(df) == exp df2 = DataFrame({"dt": Categorical(dt), "p": Categorical(p)}) assert repr(df2) == exp @pytest.mark.parametrize("arg", [np.datetime64, np.timedelta64]) @pytest.mark.parametrize( "box, expected", [[Series, "0 NaT\ndtype: object"], [DataFrame, " 0\n0 NaT"]], ) def test_repr_np_nat_with_object(self, arg, box, expected): # GH 25445 result = repr(box([arg("NaT")], dtype=object)) assert result == expected def test_frame_datetime64_pre1900_repr(self): df = DataFrame({"year": date_range("1/1/1700", periods=50, freq="YE-DEC")}) # it works! repr(df) def test_frame_to_string_with_periodindex(self): index = PeriodIndex(["2011-1", "2011-2", "2011-3"], freq="M") frame = DataFrame(np.random.default_rng(2).standard_normal((3, 4)), index=index) # it works! frame.to_string() def test_to_string_ea_na_in_multiindex(self): # GH#47986 df = DataFrame( {"a": [1, 2]}, index=MultiIndex.from_arrays([Series([NA, 1], dtype="Int64")]), ) result = df.to_string() expected = """ a <NA> 1 1 2""" assert result == expected def test_datetime64tz_slice_non_truncate(self): # GH 30263 df = DataFrame({"x": date_range("2019", periods=10, tz="UTC")}) expected = repr(df) df = df.iloc[:, :5] result = repr(df) assert result == expected def test_to_records_no_typeerror_in_repr(self): # GH 48526 df = DataFrame([["a", "b"], ["c", "d"], ["e", "f"]], columns=["left", "right"]) df["record"] = df[["left", "right"]].to_records() expected = """ left right record 0 a b [0, a, b] 1 c d [1, c, d] 2 e f [2, e, f]""" result = repr(df) assert result == expected def test_to_records_with_na_record_value(self): # GH 48526 df = DataFrame( [["a", np.nan], ["c", "d"], ["e", "f"]], columns=["left", "right"] ) df["record"] = df[["left", "right"]].to_records() expected = """ left right record 0 a NaN [0, a, nan] 1 c d [1, c, d] 2 e f [2, e, f]""" result = repr(df) assert result == expected def test_to_records_with_na_record(self): # GH 48526 df = DataFrame( [["a", "b"], [np.nan, np.nan], ["e", "f"]], columns=[np.nan, "right"] ) df["record"] = df[[np.nan, "right"]].to_records() expected = """ NaN right record 0 a b [0, a, b] 1 NaN NaN [1, nan, nan] 2 e f [2, e, f]""" result = repr(df) assert result == expected def test_to_records_with_inf_record(self): # GH 48526 expected = """ NaN inf record 0 inf b [0, inf, b] 1 NaN NaN [1, nan, nan] 2 e f [2, e, f]""" df = DataFrame( [[np.inf, "b"], [np.nan, np.nan], ["e", "f"]], columns=[np.nan, np.inf], ) df["record"] = df[[np.nan, np.inf]].to_records() result = repr(df) assert result == expected def test_masked_ea_with_formatter(self): # GH#39336 df = DataFrame( { "a": Series([0.123456789, 1.123456789], dtype="Float64"), "b": Series([1, 2], dtype="Int64"), } ) result = df.to_string(formatters=["{:.2f}".format, "{:.2f}".format]) expected = """ a b 0 0.12 1.00 1 1.12 2.00""" assert result == expected def test_repr_ea_columns(self, any_string_dtype): # GH#54797 pytest.importorskip("pyarrow") df = DataFrame({"long_column_name": [1, 2, 3], "col2": [4, 5, 6]}) df.columns = df.columns.astype(any_string_dtype) expected = """ long_column_name col2 0 1 4 1 2 5 2 3 6""" assert repr(df) == expected @pytest.mark.parametrize( "data,output", [ ([2, complex("nan"), 1], [" 2.0+0.0j", " NaN+0.0j", " 1.0+0.0j"]), ([2, complex("nan"), -1], [" 2.0+0.0j", " NaN+0.0j", "-1.0+0.0j"]), ([-2, complex("nan"), -1], ["-2.0+0.0j", " NaN+0.0j", "-1.0+0.0j"]), ([-1.23j, complex("nan"), -1], ["-0.00-1.23j", " NaN+0.00j", "-1.00+0.00j"]), ([1.23j, complex("nan"), 1.23], [" 0.00+1.23j", " NaN+0.00j", " 1.23+0.00j"]), ( [-1.23j, complex(np.nan, np.nan), 1], ["-0.00-1.23j", " NaN+ NaNj", " 1.00+0.00j"], ), ( [-1.23j, complex(1.2, np.nan), 1], ["-0.00-1.23j", " 1.20+ NaNj", " 1.00+0.00j"], ), ( [-1.23j, complex(np.nan, -1.2), 1], ["-0.00-1.23j", " NaN-1.20j", " 1.00+0.00j"], ), ], ) @pytest.mark.parametrize("as_frame", [True, False]) def test_repr_with_complex_nans(data, output, as_frame): # GH#53762, GH#53841 obj = Series(np.array(data)) if as_frame: obj = obj.to_frame(name="val") reprs = [f"{i} {val}" for i, val in enumerate(output)] expected = f"{'val': >{len(reprs[0])}}\n" + "\n".join(reprs) else: reprs = [f"{i} {val}" for i, val in enumerate(output)] expected = "\n".join(reprs) + "\ndtype: complex128" assert str(obj) == expected, f"\n{obj!s}\n\n{expected}"
TestDataFrameRepr
python
pypa__pip
src/pip/_internal/req/req_file.py
{ "start": 3185, "end": 9974 }
class ____: __slots__ = ("filename", "lineno", "args", "opts", "constraint") filename: str lineno: int args: str opts: Values constraint: bool @property def is_editable(self) -> bool: return bool(self.opts.editables) @property def requirement(self) -> str | None: if self.args: return self.args elif self.is_editable: # We don't support multiple -e on one line return self.opts.editables[0] return None def parse_requirements( filename: str, session: PipSession, finder: PackageFinder | None = None, options: optparse.Values | None = None, constraint: bool = False, ) -> Generator[ParsedRequirement, None, None]: """Parse a requirements file and yield ParsedRequirement instances. :param filename: Path or url of requirements file. :param session: PipSession instance. :param finder: Instance of pip.index.PackageFinder. :param options: cli options. :param constraint: If true, parsing a constraint file rather than requirements file. """ line_parser = get_line_parser(finder) parser = RequirementsFileParser(session, line_parser) for parsed_line in parser.parse(filename, constraint): parsed_req = handle_line( parsed_line, options=options, finder=finder, session=session ) if parsed_req is not None: yield parsed_req def preprocess(content: str) -> ReqFileLines: """Split, filter, and join lines, and return a line iterator :param content: the content of the requirements file """ lines_enum: ReqFileLines = enumerate(content.splitlines(), start=1) lines_enum = join_lines(lines_enum) lines_enum = ignore_comments(lines_enum) lines_enum = expand_env_variables(lines_enum) return lines_enum def handle_requirement_line( line: ParsedLine, options: optparse.Values | None = None, ) -> ParsedRequirement: # preserve for the nested code path line_comes_from = "{} {} (line {})".format( "-c" if line.constraint else "-r", line.filename, line.lineno, ) assert line.requirement is not None # get the options that apply to requirements if line.is_editable: supported_dest = SUPPORTED_OPTIONS_EDITABLE_REQ_DEST else: supported_dest = SUPPORTED_OPTIONS_REQ_DEST req_options = {} for dest in supported_dest: if dest in line.opts.__dict__ and line.opts.__dict__[dest]: req_options[dest] = line.opts.__dict__[dest] line_source = f"line {line.lineno} of {line.filename}" return ParsedRequirement( requirement=line.requirement, is_editable=line.is_editable, comes_from=line_comes_from, constraint=line.constraint, options=req_options, line_source=line_source, ) def handle_option_line( opts: Values, filename: str, lineno: int, finder: PackageFinder | None = None, options: optparse.Values | None = None, session: PipSession | None = None, ) -> None: if opts.hashes: logger.warning( "%s line %s has --hash but no requirement, and will be ignored.", filename, lineno, ) if options: # percolate options upward if opts.require_hashes: options.require_hashes = opts.require_hashes if opts.features_enabled: options.features_enabled.extend( f for f in opts.features_enabled if f not in options.features_enabled ) # set finder options if finder: find_links = finder.find_links index_urls = finder.index_urls no_index = finder.search_scope.no_index if opts.no_index is True: no_index = True index_urls = [] if opts.index_url and not no_index: index_urls = [opts.index_url] if opts.extra_index_urls and not no_index: index_urls.extend(opts.extra_index_urls) if opts.find_links: # FIXME: it would be nice to keep track of the source # of the find_links: support a find-links local path # relative to a requirements file. value = opts.find_links[0] req_dir = os.path.dirname(os.path.abspath(filename)) relative_to_reqs_file = os.path.join(req_dir, value) if os.path.exists(relative_to_reqs_file): value = relative_to_reqs_file find_links.append(value) if session: # We need to update the auth urls in session session.update_index_urls(index_urls) search_scope = SearchScope( find_links=find_links, index_urls=index_urls, no_index=no_index, ) finder.search_scope = search_scope if opts.pre: finder.set_allow_all_prereleases() if opts.prefer_binary: finder.set_prefer_binary() if session: for host in opts.trusted_hosts or []: source = f"line {lineno} of {filename}" session.add_trusted_host(host, source=source) def handle_line( line: ParsedLine, options: optparse.Values | None = None, finder: PackageFinder | None = None, session: PipSession | None = None, ) -> ParsedRequirement | None: """Handle a single parsed requirements line; This can result in creating/yielding requirements, or updating the finder. :param line: The parsed line to be processed. :param options: CLI options. :param finder: The finder - updated by non-requirement lines. :param session: The session - updated by non-requirement lines. Returns a ParsedRequirement object if the line is a requirement line, otherwise returns None. For lines that contain requirements, the only options that have an effect are from SUPPORTED_OPTIONS_REQ, and they are scoped to the requirement. Other options from SUPPORTED_OPTIONS may be present, but are ignored. For lines that do not contain requirements, the only options that have an effect are from SUPPORTED_OPTIONS. Options from SUPPORTED_OPTIONS_REQ may be present, but are ignored. These lines may contain multiple options (although our docs imply only one is supported), and all our parsed and affect the finder. """ if line.requirement is not None: parsed_req = handle_requirement_line(line, options) return parsed_req else: handle_option_line( line.opts, line.filename, line.lineno, finder, options, session, ) return None
ParsedLine