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
wandb__wandb
wandb/vendor/pygments/styles/manni.py
{ "start": 535, "end": 2374 }
class ____(Style): """ A colorful style, inspired by the terminal highlighting style. """ background_color = '#f0f3f3' styles = { Whitespace: '#bbbbbb', Comment: 'italic #0099FF', Comment.Preproc: 'noitalic #009999', Comment.Special: 'bold', Keyword: 'bold #006699', Keyword.Pseudo: 'nobold', Keyword.Type: '#007788', Operator: '#555555', Operator.Word: 'bold #000000', Name.Builtin: '#336666', Name.Function: '#CC00FF', Name.Class: 'bold #00AA88', Name.Namespace: 'bold #00CCFF', Name.Exception: 'bold #CC0000', Name.Variable: '#003333', Name.Constant: '#336600', Name.Label: '#9999FF', Name.Entity: 'bold #999999', Name.Attribute: '#330099', Name.Tag: 'bold #330099', Name.Decorator: '#9999FF', String: '#CC3300', String.Doc: 'italic', String.Interpol: '#AA0000', String.Escape: 'bold #CC3300', String.Regex: '#33AAAA', String.Symbol: '#FFCC33', String.Other: '#CC3300', Number: '#FF6600', Generic.Heading: 'bold #003300', Generic.Subheading: 'bold #003300', Generic.Deleted: 'border:#CC0000 bg:#FFCCCC', Generic.Inserted: 'border:#00CC00 bg:#CCFFCC', Generic.Error: '#FF0000', Generic.Emph: 'italic', Generic.Strong: 'bold', Generic.Prompt: 'bold #000099', Generic.Output: '#AAAAAA', Generic.Traceback: '#99CC66', Error: 'bg:#FFAAAA #AA0000' }
ManniStyle
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance11.py
{ "start": 202, "end": 357 }
class ____: p: type def func1(xs: list[X | Y]) -> None: for x in xs: if not isinstance(x, X): if x.p == X: pass
Y
python
pypa__setuptools
setuptools/_vendor/jaraco/text/__init__.py
{ "start": 989, "end": 6392 }
class ____(str): """ A case insensitive string class; behaves just like str except compares equal when the only variation is case. >>> s = FoldedCase('hello world') >>> s == 'Hello World' True >>> 'Hello World' == s True >>> s != 'Hello World' False >>> s.index('O') 4 >>> s.split('O') ['hell', ' w', 'rld'] >>> sorted(map(FoldedCase, ['GAMMA', 'alpha', 'Beta'])) ['alpha', 'Beta', 'GAMMA'] Sequence membership is straightforward. >>> "Hello World" in [s] True >>> s in ["Hello World"] True Allows testing for set inclusion, but candidate and elements must both be folded. >>> FoldedCase("Hello World") in {s} True >>> s in {FoldedCase("Hello World")} True String inclusion works as long as the FoldedCase object is on the right. >>> "hello" in FoldedCase("Hello World") True But not if the FoldedCase object is on the left: >>> FoldedCase('hello') in 'Hello World' False In that case, use ``in_``: >>> FoldedCase('hello').in_('Hello World') True >>> FoldedCase('hello') > FoldedCase('Hello') False >>> FoldedCase('ß') == FoldedCase('ss') True """ def __lt__(self, other): return self.casefold() < other.casefold() def __gt__(self, other): return self.casefold() > other.casefold() def __eq__(self, other): return self.casefold() == other.casefold() def __ne__(self, other): return self.casefold() != other.casefold() def __hash__(self): return hash(self.casefold()) def __contains__(self, other): return super().casefold().__contains__(other.casefold()) def in_(self, other): "Does self appear in other?" return self in FoldedCase(other) # cache casefold since it's likely to be called frequently. @method_cache def casefold(self): return super().casefold() def index(self, sub): return self.casefold().index(sub.casefold()) def split(self, splitter=' ', maxsplit=0): pattern = re.compile(re.escape(splitter), re.I) return pattern.split(self, maxsplit) # Python 3.8 compatibility _unicode_trap = ExceptionTrap(UnicodeDecodeError) @_unicode_trap.passes def is_decodable(value): r""" Return True if the supplied value is decodable (using the default encoding). >>> is_decodable(b'\xff') False >>> is_decodable(b'\x32') True """ value.decode() def is_binary(value): r""" Return True if the value appears to be binary (that is, it's a byte string and isn't decodable). >>> is_binary(b'\xff') True >>> is_binary('\xff') False """ return isinstance(value, bytes) and not is_decodable(value) def trim(s): r""" Trim something like a docstring to remove the whitespace that is common due to indentation and formatting. >>> trim("\n\tfoo = bar\n\t\tbar = baz\n") 'foo = bar\n\tbar = baz' """ return textwrap.dedent(s).strip() def wrap(s): """ Wrap lines of text, retaining existing newlines as paragraph markers. >>> print(wrap(lorem_ipsum)) Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. <BLANKLINE> Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam varius, turpis et commodo pharetra, est eros bibendum elit, nec luctus magna felis sollicitudin mauris. Integer in mauris eu nibh euismod gravida. Duis ac tellus et risus vulputate vehicula. Donec lobortis risus a elit. Etiam tempor. Ut ullamcorper, ligula eu tempor congue, eros est euismod turpis, id tincidunt sapien risus a quam. Maecenas fermentum consequat mi. Donec fermentum. Pellentesque malesuada nulla a mi. Duis sapien sem, aliquet nec, commodo eget, consequat quis, neque. Aliquam faucibus, elit ut dictum aliquet, felis nisl adipiscing sapien, sed malesuada diam lacus eget erat. Cras mollis scelerisque nunc. Nullam arcu. Aliquam consequat. Curabitur augue lorem, dapibus quis, laoreet et, pretium ac, nisi. Aenean magna nisl, mollis quis, molestie eu, feugiat in, orci. In hac habitasse platea dictumst. """ paragraphs = s.splitlines() wrapped = ('\n'.join(textwrap.wrap(para)) for para in paragraphs) return '\n\n'.join(wrapped) def unwrap(s): r""" Given a multi-line string, return an unwrapped version. >>> wrapped = wrap(lorem_ipsum) >>> wrapped.count('\n') 20 >>> unwrapped = unwrap(wrapped) >>> unwrapped.count('\n') 1 >>> print(unwrapped) Lorem ipsum dolor sit amet, consectetur adipiscing ... Curabitur pretium tincidunt lacus. Nulla gravida orci ... """ paragraphs = re.split(r'\n\n+', s) cleaned = (para.replace('\n', ' ') for para in paragraphs) return '\n'.join(cleaned) lorem_ipsum: str = ( files(__name__).joinpath('Lorem ipsum.txt').read_text(encoding='utf-8') )
FoldedCase
python
doocs__leetcode
lcof2/剑指 Offer II 004. 只出现一次的数字/Solution.py
{ "start": 0, "end": 321 }
class ____: def singleNumber(self, nums: List[int]) -> int: ans = 0 for i in range(32): cnt = sum(x >> i & 1 for x in nums) if cnt % 3: if i == 31: ans -= 1 << i else: ans |= 1 << i return ans
Solution
python
getsentry__sentry-python
tests/integrations/beam/test_beam.py
{ "start": 992, "end": 1293 }
class ____(A): def fa(self, x, element=False, another_element=False): if x or (element and not another_element): # print(self.r) return True 1 / 0 return False def __init__(self): self.r = "We are in B" super().__init__(self.fa)
B
python
langchain-ai__langchain
libs/langchain/langchain_classic/memory/readonly.py
{ "start": 79, "end": 763 }
class ____(BaseMemory): """Memory wrapper that is read-only and cannot be changed.""" memory: BaseMemory @property def memory_variables(self) -> list[str]: """Return memory variables.""" return self.memory.memory_variables def load_memory_variables(self, inputs: dict[str, Any]) -> dict[str, str]: """Load memory variables from memory.""" return self.memory.load_memory_variables(inputs) def save_context(self, inputs: dict[str, Any], outputs: dict[str, str]) -> None: """Nothing should be saved or changed.""" def clear(self) -> None: """Nothing to clear, got a memory like a vault."""
ReadOnlySharedMemory
python
facebook__pyre-check
client/commands/tests/server_event_test.py
{ "start": 373, "end": 7174 }
class ____(testslide.TestCase): def test_error_kind(self) -> None: self.assertEqual( server_event.ErrorKind.from_string("Watchman"), server_event.ErrorKind.WATCHMAN, ) self.assertEqual( server_event.ErrorKind.from_string("BuckInternal"), server_event.ErrorKind.BUCK_INTERNAL, ) self.assertEqual( server_event.ErrorKind.from_string("BuckUser"), server_event.ErrorKind.BUCK_USER, ) self.assertEqual( server_event.ErrorKind.from_string("Pyre"), server_event.ErrorKind.PYRE ) self.assertEqual( server_event.ErrorKind.from_string("Unknown"), server_event.ErrorKind.UNKNOWN, ) self.assertEqual( server_event.ErrorKind.from_string("derp"), server_event.ErrorKind.UNKNOWN ) def test_create(self) -> None: self.assertIsNone(server_event.create_from_string("derp")) self.assertIsNone(server_event.create_from_string("[]")) self.assertEqual( server_event.create_from_string('["SocketCreated", "/foo/bar"]'), server_event.SocketCreated(Path("/foo/bar")), ) self.assertIsNone(server_event.create_from_string('["SocketCreated"]')) self.assertEqual( server_event.create_from_string('["ServerInitialized"]'), server_event.ServerInitialized(), ) self.assertEqual( server_event.create_from_string('["Exception", "Burn baby burn!"]'), server_event.ServerException("Burn baby burn!"), ) self.assertEqual( server_event.create_from_string( '["Exception", "Burn baby burn!", ["BuckUser"]]' ), server_event.ServerException( message="Burn baby burn!", kind=server_event.ErrorKind.BUCK_USER ), ) self.assertEqual( server_event.create_from_string('["Exception", "Burn baby burn!", "derp"]'), server_event.ServerException( message="Burn baby burn!", kind=server_event.ErrorKind.UNKNOWN ), ) self.assertIsNone(server_event.create_from_string('["Exception"]')) self.assertIsNone(server_event.create_from_string('["Exception", 42]')) self.assertIsNone( server_event.create_from_string('["UNRECOGNIZABLE", "message"]') ) def test_waiter(self) -> None: def assert_ok(event_output: str, wait_on_initialization: bool) -> None: server_event.Waiter(wait_on_initialization=wait_on_initialization).wait_on( io.StringIO(event_output) ) def assert_raises( event_output: str, wait_on_initialization: bool, exception: Type[Exception] = server_event.EventParsingException, ) -> None: with self.assertRaises(exception): server_event.Waiter( wait_on_initialization=wait_on_initialization ).wait_on(io.StringIO(event_output)) assert_raises("garbage", wait_on_initialization=False) assert_raises("[]", wait_on_initialization=False) assert_ok( '["SocketCreated", "/path/to/socket"]', wait_on_initialization=False, ) assert_raises('["ServerInitialized"]', wait_on_initialization=False) assert_raises( '["Exception", "message"]', wait_on_initialization=False, exception=server_event.ServerStartException, ) assert_raises("garbage", wait_on_initialization=True) assert_raises("[]", wait_on_initialization=True) assert_raises( '["SocketCreated", "/path/to/socket"]', wait_on_initialization=True, ) assert_raises( '["Exception", "message"]', wait_on_initialization=True, exception=server_event.ServerStartException, ) assert_raises( '["SocketCreated", "/path/to/socket"]\n' + '["ServerException", "message"]', wait_on_initialization=True, ) assert_raises( '["SocketCreated", "/path/to/socket"]\n' + '["SocketCreated", "/path/to/socket"]', wait_on_initialization=True, ) assert_ok( '["SocketCreated", "/path/to/socket"]\n' + '["ServerInitialized"]', wait_on_initialization=True, ) @setup.async_test async def test_async_waiter(self) -> None: async def assert_ok(event_output: str, wait_on_initialization: bool) -> None: await server_event.Waiter( wait_on_initialization=wait_on_initialization ).async_wait_on(connections.create_memory_text_reader(event_output)) async def assert_raises( event_output: str, wait_on_initialization: bool, exception: Type[Exception] = server_event.EventParsingException, ) -> None: with self.assertRaises(exception): await server_event.Waiter( wait_on_initialization=wait_on_initialization ).async_wait_on(connections.create_memory_text_reader(event_output)) await assert_raises("garbage", wait_on_initialization=False) await assert_raises("[]", wait_on_initialization=False) await assert_ok( '["SocketCreated", "/path/to/socket"]', wait_on_initialization=False, ) await assert_raises('["ServerInitialized"]', wait_on_initialization=False) await assert_raises( '["Exception", "message"]', wait_on_initialization=False, exception=server_event.ServerStartException, ) await assert_raises("garbage", wait_on_initialization=True) await assert_raises("[]", wait_on_initialization=True) await assert_raises( '["SocketCreated", "/path/to/socket"]', wait_on_initialization=True, ) await assert_raises( '["Exception", "message"]', wait_on_initialization=True, exception=server_event.ServerStartException, ) await assert_raises( '["SocketCreated", "/path/to/socket"]\n' + '["ServerException", "message"]', wait_on_initialization=True, ) await assert_raises( '["SocketCreated", "/path/to/socket"]\n' + '["SocketCreated", "/path/to/socket"]', wait_on_initialization=True, ) await assert_ok( '["SocketCreated", "/path/to/socket"]\n' + '["ServerInitialized"]', wait_on_initialization=True, )
ServerEventTest
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/triggers/dataflow.py
{ "start": 17794, "end": 23479 }
class ____(BaseTrigger): """ Trigger that checks for metrics associated with a Dataflow job. :param job_id: Required. ID of the job. :param project_id: Required. The Google Cloud project ID in which the job was started. :param location: Optional. The location where the job is executed. If set to None then the value of DEFAULT_DATAFLOW_LOCATION will be used. :param gcp_conn_id: The connection ID to use for connecting to Google Cloud. :param poll_sleep: Time (seconds) to wait between two consecutive calls to check the job. :param impersonation_chain: Optional. Service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param fail_on_terminal_state: If set to True the trigger will yield a TriggerEvent with error status if the job reaches a terminal state. """ def __init__( self, job_id: str, project_id: str | None, location: str = DEFAULT_DATAFLOW_LOCATION, gcp_conn_id: str = "google_cloud_default", poll_sleep: int = 10, impersonation_chain: str | Sequence[str] | None = None, fail_on_terminal_state: bool = True, ): super().__init__() self.project_id = project_id self.job_id = job_id self.location = location self.gcp_conn_id = gcp_conn_id self.poll_sleep = poll_sleep self.impersonation_chain = impersonation_chain self.fail_on_terminal_state = fail_on_terminal_state def serialize(self) -> tuple[str, dict[str, Any]]: """Serialize class arguments and classpath.""" return ( "airflow.providers.google.cloud.triggers.dataflow.DataflowJobMetricsTrigger", { "project_id": self.project_id, "job_id": self.job_id, "location": self.location, "gcp_conn_id": self.gcp_conn_id, "poll_sleep": self.poll_sleep, "impersonation_chain": self.impersonation_chain, "fail_on_terminal_state": self.fail_on_terminal_state, }, ) async def run(self): """ Loop until a terminal job status or any job metrics are returned. Yields a TriggerEvent with success status, if the client returns any job metrics and fail_on_terminal_state attribute is False. Yields a TriggerEvent with error status, if the client returns a job status with a terminal state value and fail_on_terminal_state attribute is True. Yields a TriggerEvent with error status, if any exception is raised while looping. In any other case the Trigger will wait for a specified amount of time stored in self.poll_sleep variable. """ try: while True: job_status = await self.async_hook.get_job_status( job_id=self.job_id, project_id=self.project_id, location=self.location, ) job_metrics = await self.get_job_metrics() if self.fail_on_terminal_state and job_status.name in DataflowJobStatus.TERMINAL_STATES: yield TriggerEvent( { "status": "error", "message": f"Job with id '{self.job_id}' is already in terminal state: {job_status.name}", "result": None, } ) return if job_metrics: yield TriggerEvent( { "status": "success", "message": f"Detected {len(job_metrics)} metrics for job '{self.job_id}'", "result": job_metrics, } ) return self.log.info("Sleeping for %s seconds.", self.poll_sleep) await asyncio.sleep(self.poll_sleep) except Exception as e: self.log.error("Exception occurred while checking for job's metrics!") yield TriggerEvent({"status": "error", "message": str(e), "result": None}) async def get_job_metrics(self) -> list[dict[str, Any]]: """Wait for the Dataflow client response and then return it in a serialized list.""" job_response: JobMetrics = await self.async_hook.get_job_metrics( job_id=self.job_id, project_id=self.project_id, location=self.location, ) return self._get_metrics_from_job_response(job_response) def _get_metrics_from_job_response(self, job_response: JobMetrics) -> list[dict[str, Any]]: """Return a list of serialized MetricUpdate objects.""" return [MetricUpdate.to_dict(metric) for metric in job_response.metrics] @cached_property def async_hook(self) -> AsyncDataflowHook: return AsyncDataflowHook( gcp_conn_id=self.gcp_conn_id, poll_sleep=self.poll_sleep, impersonation_chain=self.impersonation_chain, )
DataflowJobMetricsTrigger
python
numpy__numpy
numpy/polynomial/hermite.py
{ "start": 52970, "end": 54571 }
class ____(ABCPolyBase): """A Hermite series class. The Hermite class provides the standard Python numerical methods '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the attributes and methods listed below. Parameters ---------- coef : array_like Hermite coefficients in order of increasing degree, i.e, ``(1, 2, 3)`` gives ``1*H_0(x) + 2*H_1(x) + 3*H_2(x)``. domain : (2,) array_like, optional Domain to use. The interval ``[domain[0], domain[1]]`` is mapped to the interval ``[window[0], window[1]]`` by shifting and scaling. The default value is [-1., 1.]. window : (2,) array_like, optional Window, see `domain` for its use. The default value is [-1., 1.]. symbol : str, optional Symbol used to represent the independent variable in string representations of the polynomial expression, e.g. for printing. The symbol must be a valid Python identifier. Default value is 'x'. .. versionadded:: 1.24 """ # Virtual Functions _add = staticmethod(hermadd) _sub = staticmethod(hermsub) _mul = staticmethod(hermmul) _div = staticmethod(hermdiv) _pow = staticmethod(hermpow) _val = staticmethod(hermval) _int = staticmethod(hermint) _der = staticmethod(hermder) _fit = staticmethod(hermfit) _line = staticmethod(hermline) _roots = staticmethod(hermroots) _fromroots = staticmethod(hermfromroots) # Virtual properties domain = np.array(hermdomain) window = np.array(hermdomain) basis_name = 'H'
Hermite
python
python-poetry__poetry
src/poetry/packages/transitive_package_info.py
{ "start": 329, "end": 783 }
class ____: depth: int # max depth in the dependency tree groups: set[NormalizedName] markers: dict[NormalizedName, BaseMarker] # group -> marker def get_marker(self, groups: Iterable[NormalizedName]) -> BaseMarker: marker: BaseMarker = EmptyMarker() for group in groups: if group_marker := self.markers.get(group): marker = marker.union(group_marker) return marker
TransitivePackageInfo
python
ansible__ansible
lib/ansible/plugins/netconf/__init__.py
{ "start": 1880, "end": 17094 }
class ____(AnsiblePlugin): """ A base class for implementing Netconf connections .. note:: Unlike most of Ansible, nearly all strings in :class:`TerminalBase` plugins are byte strings. This is because of how close to the underlying platform these plugins operate. Remember to mark literal strings as byte string (``b"string"``) and to use :func:`~ansible.module_utils.common.text.converters.to_bytes` and :func:`~ansible.module_utils.common.text.converters.to_text` to avoid unexpected problems. List of supported rpc's: :get: Retrieves running configuration and device state information :get_config: Retrieves the specified configuration from the device :edit_config: Loads the specified commands into the remote device :commit: Load configuration from candidate to running :discard_changes: Discard changes to candidate datastore :validate: Validate the contents of the specified configuration. :lock: Allows the client to lock the configuration system of a device. :unlock: Release a configuration lock, previously obtained with the lock operation. :copy_config: create or replace an entire configuration datastore with the contents of another complete configuration datastore. :get-schema: Retrieves the required schema from the device :get_capabilities: Retrieves device information and supported rpc methods For JUNOS: :execute_rpc: RPC to be execute on remote device :load_configuration: Loads given configuration on device Note: rpc support depends on the capabilities of remote device. :returns: Returns output received from remote device as byte string Note: the 'result' or 'error' from response should to be converted to object of ElementTree using 'fromstring' to parse output as xml doc 'get_capabilities()' returns 'result' as a json string. Usage: from ansible.module_utils.connection import Connection conn = Connection() data = conn.execute_rpc(rpc) reply = fromstring(reply) data = conn.get_capabilities() json.loads(data) conn.load_configuration(config=[''set system ntp server 1.1.1.1''], action='set', format='text') """ __rpc__ = ['rpc', 'get_config', 'get', 'edit_config', 'validate', 'copy_config', 'dispatch', 'lock', 'unlock', 'discard_changes', 'commit', 'get_schema', 'delete_config', 'get_device_operations'] def __init__(self, connection): super(NetconfBase, self).__init__() self._connection = connection @property def m(self): return self._connection.manager def rpc(self, name): """ RPC to be execute on remote device :param name: Name of rpc in string format :return: Received rpc response from remote host """ try: obj = to_ele(name) resp = self.m.rpc(obj) return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml except RPCError as exc: msg = exc.xml raise Exception(to_xml(msg)) def get_config(self, source=None, filter=None): """ Retrieve all or part of a specified configuration (by default entire configuration is retrieved). :param source: Name of the configuration datastore being queried, defaults to running datastore :param filter: This argument specifies the portion of the configuration data to retrieve :return: Returns xml string containing the RPC response received from remote host """ if isinstance(filter, list): filter = tuple(filter) if not source: source = 'running' resp = self.m.get_config(source=source, filter=filter) return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml def get(self, filter=None, with_defaults=None): """ Retrieve device configuration and state information. :param filter: This argument specifies the portion of the state data to retrieve (by default entire state data is retrieved) :param with_defaults: defines an explicit method of retrieving default values from the configuration :return: Returns xml string containing the RPC response received from remote host """ if isinstance(filter, list): filter = tuple(filter) resp = self.m.get(filter=filter, with_defaults=with_defaults) response = resp.data_xml if hasattr(resp, 'data_xml') else resp.xml return response def edit_config(self, config=None, format='xml', target='candidate', default_operation=None, test_option=None, error_option=None): """ Loads all or part of the specified *config* to the *target* configuration datastore. :param config: Is the configuration, which must be rooted in the `config` element. It can be specified either as a string or an :class:`~xml.etree.ElementTree.Element`. :param format: The format of configuration eg. xml, text :param target: Is the name of the configuration datastore being edited :param default_operation: If specified must be one of { `"merge"`, `"replace"`, or `"none"` } :param test_option: If specified must be one of { `"test_then_set"`, `"set"` } :param error_option: If specified must be one of { `"stop-on-error"`, `"continue-on-error"`, `"rollback-on-error"` } The `"rollback-on-error"` *error_option* depends on the `:rollback-on-error` capability. :return: Returns xml string containing the RPC response received from remote host """ if config is None: raise ValueError('config value must be provided') resp = self.m.edit_config(config, format=format, target=target, default_operation=default_operation, test_option=test_option, error_option=error_option) return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml def validate(self, source='candidate'): """ Validate the contents of the specified configuration. :param source: Is the name of the configuration datastore being validated or `config` element containing the configuration subtree to be validated :return: Returns xml string containing the RPC response received from remote host """ resp = self.m.validate(source=source) return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml def copy_config(self, source, target): """ Create or replace an entire configuration datastore with the contents of another complete configuration datastore. :param source: Is the name of the configuration datastore to use as the source of the copy operation or `config` element containing the configuration subtree to copy :param target: Is the name of the configuration datastore to use as the destination of the copy operation :return: Returns xml string containing the RPC response received from remote host """ resp = self.m.copy_config(source, target) return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml def dispatch(self, rpc_command=None, source=None, filter=None): """ Execute rpc on the remote device eg. dispatch('clear-arp-table') :param rpc_command: specifies rpc command to be dispatched either in plain text or in xml element format (depending on command) :param source: name of the configuration datastore being queried :param filter: specifies the portion of the configuration to retrieve (by default entire configuration is retrieved) :return: Returns xml string containing the RPC response received from remote host """ if rpc_command is None: raise ValueError('rpc_command value must be provided') resp = self.m.dispatch(fromstring(rpc_command), source=source, filter=filter) if isinstance(resp, NCElement): # In case xml reply is transformed or namespace is removed in # ncclient device specific handler return modified xml response result = resp.data_xml elif hasattr(resp, 'data_ele') and resp.data_ele: # if data node is present in xml response return the xml string # with data node as root result = resp.data_xml else: # return raw xml string received from host with rpc-reply as the root node result = resp.xml return result def lock(self, target="candidate"): """ Allows the client to lock the configuration system of a device. :param target: is the name of the configuration datastore to lock, defaults to candidate datastore :return: Returns xml string containing the RPC response received from remote host """ resp = self.m.lock(target=target) return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml def unlock(self, target="candidate"): """ Release a configuration lock, previously obtained with the lock operation. :param target: is the name of the configuration datastore to unlock, defaults to candidate datastore :return: Returns xml string containing the RPC response received from remote host """ resp = self.m.unlock(target=target) return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml def discard_changes(self): """ Revert the candidate configuration to the currently running configuration. Any uncommitted changes are discarded. :return: Returns xml string containing the RPC response received from remote host """ resp = self.m.discard_changes() return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml def commit(self, confirmed=False, timeout=None, persist=None): """ Commit the candidate configuration as the device's new current configuration. Depends on the `:candidate` capability. A confirmed commit (i.e. if *confirmed* is `True`) is reverted if there is no followup commit within the *timeout* interval. If no timeout is specified the confirm timeout defaults to 600 seconds (10 minutes). A confirming commit may have the *confirmed* parameter but this is not required. Depends on the `:confirmed-commit` capability. :param confirmed: whether this is a confirmed commit :param timeout: specifies the confirm timeout in seconds :param persist: make the confirmed commit survive a session termination, and set a token on the ongoing confirmed commit :return: Returns xml string containing the RPC response received from remote host """ resp = self.m.commit(confirmed=confirmed, timeout=timeout, persist=persist) return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml def get_schema(self, identifier=None, version=None, format=None): """ Retrieve a named schema, with optional revision and type. :param identifier: name of the schema to be retrieved :param version: version of schema to get :param format: format of the schema to be retrieved, yang is the default :return: Returns xml string containing the RPC response received from remote host """ resp = self.m.get_schema(identifier, version=version, format=format) return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml def delete_config(self, target): """ delete a configuration datastore :param target: specifies the name or URL of configuration datastore to delete :return: Returns xml string containing the RPC response received from remote host """ resp = self.m.delete_config(target) return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml def locked(self, target): return self.m.locked(target) @abstractmethod def get_capabilities(self): """ Retrieves device information and supported rpc methods by device platform and return result as a string :return: Netconf session capability """ pass @staticmethod def guess_network_os(obj): """ Identifies the operating system of network device. :param obj: ncclient manager connection instance :return: The name of network operating system. """ pass def get_base_rpc(self): """ Returns list of base rpc method supported by remote device :return: List of RPC supported """ return self.__rpc__ def put_file(self, source, destination): """ Copies file to remote host :param source: Source location of file :param destination: Destination file path :return: Returns xml string containing the RPC response received from remote host """ pass def fetch_file(self, source, destination): """ Fetch file from remote host :param source: Source location of file :param destination: Source location of file :return: Returns xml string containing the RPC response received from remote host """ pass def get_device_operations(self, server_capabilities): """ Retrieve remote host capability from Netconf server hello message. :param server_capabilities: Server capabilities received during Netconf session initialization :return: Remote host capabilities in dictionary format """ operations = {} capabilities = '\n'.join(server_capabilities) operations['supports_commit'] = ':candidate' in capabilities operations['supports_defaults'] = ':with-defaults' in capabilities operations['supports_confirm_commit'] = ':confirmed-commit' in capabilities operations['supports_startup'] = ':startup' in capabilities operations['supports_xpath'] = ':xpath' in capabilities operations['supports_writable_running'] = ':writable-running' in capabilities operations['supports_validate'] = ':validate' in capabilities operations['lock_datastore'] = [] if operations['supports_writable_running']: operations['lock_datastore'].append('running') if operations['supports_commit']: operations['lock_datastore'].append('candidate') if operations['supports_startup']: operations['lock_datastore'].append('startup') operations['supports_lock'] = bool(operations['lock_datastore']) return operations # TODO Restore .xml, when ncclient supports it for all platforms
NetconfBase
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/repository_origin.py
{ "start": 218, "end": 418 }
class ____(graphene.ObjectType): key = graphene.NonNull(graphene.String) value = graphene.NonNull(graphene.String) class Meta: name = "RepositoryMetadata"
GrapheneRepositoryMetadata
python
getsentry__sentry
tests/sentry/integrations/msteams/webhook/test_ms_teams_events.py
{ "start": 88, "end": 966 }
class ____: def test_handle_unsupported(self) -> None: unsupported_value = str(uuid4()) response = MsTeamsEvents.get_from_value(unsupported_value) assert response == MsTeamsEvents.UNKNOWN def test_message(self) -> None: response = MsTeamsEvents.get_from_value("message") assert response == MsTeamsEvents.MESSAGE def test_installation_update(self) -> None: response = MsTeamsEvents.get_from_value("installationUpdate") assert response == MsTeamsEvents.INSTALLATION_UPDATE def test_conversation_update(self) -> None: response = MsTeamsEvents.get_from_value("conversationUpdate") assert response == MsTeamsEvents.CONVERSATION_UPDATE def test_unknown(self) -> None: response = MsTeamsEvents.get_from_value("unknown") assert response == MsTeamsEvents.UNKNOWN
TestGetFromValue
python
lxml__lxml
src/lxml/tests/test_errors.py
{ "start": 311, "end": 2736 }
class ____(HelperTestCase): etree = etree def test_bad_element(self): # attrib argument of Element() should be a dictionary, so if # we pass a string we should get an error. self.assertRaises(TypeError, self.etree.Element, 'a', 'b') def test_empty_parse(self): self.assertRaises(etree.XMLSyntaxError, etree.fromstring, '') @unittest.skipIf(IS_PYPY, "needs sys.getrefcount()") def test_element_cyclic_gc_none(self): # test if cyclic reference can crash etree Element = self.etree.Element getrefcount = sys.getrefcount # must disable tracing as it could change the refcounts trace_func = sys.gettrace() try: sys.settrace(None) gc.collect() count = getrefcount(None) l = [Element('name'), Element('name')] l.append(l) del l gc.collect() count = getrefcount(None) - count if sys.version_info[:2] == (3, 11) and count == -1: # FIXME: it's currently unclear why this happens, but it's reproducible on Py3.11. self.assertEqual(count, -1) else: self.assertEqual(count, 0) finally: sys.settrace(trace_func) def test_xmlsyntaxerror_has_info(self): broken_xml_name = 'test_broken.xml' broken_xml_path = os.path.join(os.path.dirname(__file__), broken_xml_name) fail_msg = 'test_broken.xml should raise an etree.XMLSyntaxError' try: etree.parse(broken_xml_path) except etree.XMLSyntaxError as e: # invariant self.assertEqual(e.position, (e.lineno, e.offset + 1), 'position and lineno/offset out of sync') # SyntaxError info derived from file & contents self.assertTrue(e.filename.endswith(broken_xml_name), 'filename must be preserved') self.assertEqual(e.lineno, 1) self.assertEqual(e.offset, 10) except Exception as e: self.fail(f'{fail_msg}, not {type(e)}') else: self.fail('test_broken.xml should raise an etree.XMLSyntaxError') def test_suite(): suite = unittest.TestSuite() suite.addTests([unittest.defaultTestLoader.loadTestsFromTestCase(ErrorTestCase)]) return suite if __name__ == '__main__': print('to test use test.py %s' % __file__)
ErrorTestCase
python
pydata__xarray
asv_bench/benchmarks/merge.py
{ "start": 740, "end": 2443 }
class ____: # The idea here is to time how long it takes to go from numpy # and python data types, to a full dataset # See discussion # https://github.com/pydata/xarray/issues/7224#issuecomment-1292216344 param_names = ["strategy", "count"] params = [ ["dict_of_DataArrays", "dict_of_Variables", "dict_of_Tuples"], [0, 1, 10, 100, 1000], ] def setup(self, strategy, count): data = np.array(["0", "b"], dtype=str) self.dataset_coords = dict(time=np.array([0, 1])) self.dataset_attrs = dict(description="Test data") attrs = dict(units="Celsius") if strategy == "dict_of_DataArrays": def create_data_vars(): return { f"long_variable_name_{i}": xr.DataArray( data=data, dims=("time"), attrs=attrs ) for i in range(count) } elif strategy == "dict_of_Variables": def create_data_vars(): return { f"long_variable_name_{i}": xr.Variable("time", data, attrs=attrs) for i in range(count) } elif strategy == "dict_of_Tuples": def create_data_vars(): return { f"long_variable_name_{i}": ("time", data, attrs) for i in range(count) } self.create_data_vars = create_data_vars def time_dataset_creation(self, strategy, count): data_vars = self.create_data_vars() xr.Dataset( data_vars=data_vars, coords=self.dataset_coords, attrs=self.dataset_attrs )
DatasetCreation
python
huggingface__transformers
src/transformers/models/xlnet/modeling_xlnet.py
{ "start": 29982, "end": 31095 }
class ____(ModelOutput): r""" loss (`torch.FloatTensor` of shape *(1,)*, *optional*, returned when `labels` is provided): Classification loss. logits (`torch.FloatTensor` of shape `(batch_size, num_choices)`): *num_choices* is the second dimension of the input tensors. (see *input_ids* above). Classification scores (before SoftMax). mems (`list[torch.FloatTensor]` of length `config.n_layers`): Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as `input_ids` as they have already been computed. """ loss: Optional[torch.FloatTensor] = None logits: Optional[torch.FloatTensor] = None mems: Optional[list[torch.FloatTensor]] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None @dataclass @auto_docstring( custom_intro=""" Output type of [`XLNetForQuestionAnsweringSimple`]. """ )
XLNetForMultipleChoiceOutput
python
huggingface__transformers
src/transformers/models/longformer/modeling_longformer.py
{ "start": 55599, "end": 56558 }
class ____(nn.Module): def __init__(self, config, layer_id=0): super().__init__() self.self = LongformerSelfAttention(config, layer_id) self.output = LongformerSelfOutput(config) def forward( self, hidden_states, attention_mask=None, is_index_masked=None, is_index_global_attn=None, is_global_attn=None, output_attentions=False, ): self_outputs = self.self( hidden_states, attention_mask=attention_mask, is_index_masked=is_index_masked, is_index_global_attn=is_index_global_attn, is_global_attn=is_global_attn, output_attentions=output_attentions, ) attn_output = self.output(self_outputs[0], hidden_states) outputs = (attn_output,) + self_outputs[1:] return outputs # Copied from transformers.models.bert.modeling_bert.BertIntermediate
LongformerAttention
python
walkccc__LeetCode
solutions/3064. Guess the Number Using Bitwise Questions I/3064.py
{ "start": 74, "end": 208 }
class ____: def findNumber(self) -> int: return sum(1 << i for i in range(31) if commonSetBits(1 << i) == 1)
Solution
python
django__django
django/forms/widgets.py
{ "start": 12944, "end": 13053 }
class ____(Input): input_type = "hidden" template_name = "django/forms/widgets/hidden.html"
HiddenInput
python
google__pytype
pytype/errors/error_types.py
{ "start": 3443, "end": 3553 }
class ____(InvalidParameters): """E.g. if a function expecting 4 parameters is called with 3."""
WrongArgCount
python
getsentry__sentry
src/sentry/integrations/discord/views/linkage.py
{ "start": 272, "end": 1017 }
class ____(IdentityLinkageView, ABC): @property def parent_messaging_spec(self) -> MessagingIntegrationSpec: from sentry.integrations.discord.spec import DiscordMessagingSpec return DiscordMessagingSpec() @property def provider(self) -> ExternalProviders: return ExternalProviders.DISCORD @property def external_provider_enum(self) -> ExternalProviderEnum: return ExternalProviderEnum.DISCORD @property def salt(self) -> str: return SALT @property def external_id_parameter(self) -> str: return "discord_id" @property def expired_link_template(self) -> str: return "sentry/integrations/discord/expired-link.html"
DiscordIdentityLinkageView
python
tiangolo__fastapi
tests/test_include_router_defaults_overrides.py
{ "start": 571, "end": 367192 }
class ____(JSONResponse): media_type = "application/x-level-5" async def dep0(response: Response): response.headers["x-level0"] = "True" async def dep1(response: Response): response.headers["x-level1"] = "True" async def dep2(response: Response): response.headers["x-level2"] = "True" async def dep3(response: Response): response.headers["x-level3"] = "True" async def dep4(response: Response): response.headers["x-level4"] = "True" async def dep5(response: Response): response.headers["x-level5"] = "True" callback_router0 = APIRouter() @callback_router0.get("/") async def callback0(level0: str): pass # pragma: nocover callback_router1 = APIRouter() @callback_router1.get("/") async def callback1(level1: str): pass # pragma: nocover callback_router2 = APIRouter() @callback_router2.get("/") async def callback2(level2: str): pass # pragma: nocover callback_router3 = APIRouter() @callback_router3.get("/") async def callback3(level3: str): pass # pragma: nocover callback_router4 = APIRouter() @callback_router4.get("/") async def callback4(level4: str): pass # pragma: nocover callback_router5 = APIRouter() @callback_router5.get("/") async def callback5(level5: str): pass # pragma: nocover app = FastAPI( dependencies=[Depends(dep0)], responses={ 400: {"description": "Client error level 0"}, 500: {"description": "Server error level 0"}, }, default_response_class=ResponseLevel0, callbacks=callback_router0.routes, ) router2_override = APIRouter( prefix="/level2", tags=["level2a", "level2b"], dependencies=[Depends(dep2)], responses={ 402: {"description": "Client error level 2"}, 502: {"description": "Server error level 2"}, }, default_response_class=ResponseLevel2, callbacks=callback_router2.routes, deprecated=True, ) router2_default = APIRouter() router4_override = APIRouter( prefix="/level4", tags=["level4a", "level4b"], dependencies=[Depends(dep4)], responses={ 404: {"description": "Client error level 4"}, 504: {"description": "Server error level 4"}, }, default_response_class=ResponseLevel4, callbacks=callback_router4.routes, deprecated=True, ) router4_default = APIRouter() @app.get( "/override1", tags=["path1a", "path1b"], responses={ 401: {"description": "Client error level 1"}, 501: {"description": "Server error level 1"}, }, deprecated=True, callbacks=callback_router1.routes, dependencies=[Depends(dep1)], response_class=ResponseLevel1, ) async def path1_override(level1: str): return level1 @app.get("/default1") async def path1_default(level1: str): return level1 @router2_override.get( "/override3", tags=["path3a", "path3b"], responses={ 403: {"description": "Client error level 3"}, 503: {"description": "Server error level 3"}, }, deprecated=True, callbacks=callback_router3.routes, dependencies=[Depends(dep3)], response_class=ResponseLevel3, ) async def path3_override_router2_override(level3: str): return level3 @router2_override.get("/default3") async def path3_default_router2_override(level3: str): return level3 @router2_default.get( "/override3", tags=["path3a", "path3b"], responses={ 403: {"description": "Client error level 3"}, 503: {"description": "Server error level 3"}, }, deprecated=True, callbacks=callback_router3.routes, dependencies=[Depends(dep3)], response_class=ResponseLevel3, ) async def path3_override_router2_default(level3: str): return level3 @router2_default.get("/default3") async def path3_default_router2_default(level3: str): return level3 @router4_override.get( "/override5", tags=["path5a", "path5b"], responses={ 405: {"description": "Client error level 5"}, 505: {"description": "Server error level 5"}, }, deprecated=True, callbacks=callback_router5.routes, dependencies=[Depends(dep5)], response_class=ResponseLevel5, ) async def path5_override_router4_override(level5: str): return level5 @router4_override.get( "/default5", ) async def path5_default_router4_override(level5: str): return level5 @router4_default.get( "/override5", tags=["path5a", "path5b"], responses={ 405: {"description": "Client error level 5"}, 505: {"description": "Server error level 5"}, }, deprecated=True, callbacks=callback_router5.routes, dependencies=[Depends(dep5)], response_class=ResponseLevel5, ) async def path5_override_router4_default(level5: str): return level5 @router4_default.get( "/default5", ) async def path5_default_router4_default(level5: str): return level5 router2_override.include_router( router4_override, prefix="/level3", tags=["level3a", "level3b"], dependencies=[Depends(dep3)], responses={ 403: {"description": "Client error level 3"}, 503: {"description": "Server error level 3"}, }, default_response_class=ResponseLevel3, callbacks=callback_router3.routes, ) router2_override.include_router( router4_default, prefix="/level3", tags=["level3a", "level3b"], dependencies=[Depends(dep3)], responses={ 403: {"description": "Client error level 3"}, 503: {"description": "Server error level 3"}, }, default_response_class=ResponseLevel3, callbacks=callback_router3.routes, ) router2_override.include_router(router4_override) router2_override.include_router(router4_default) router2_default.include_router( router4_override, prefix="/level3", tags=["level3a", "level3b"], dependencies=[Depends(dep3)], responses={ 403: {"description": "Client error level 3"}, 503: {"description": "Server error level 3"}, }, default_response_class=ResponseLevel3, callbacks=callback_router3.routes, ) router2_default.include_router( router4_default, prefix="/level3", tags=["level3a", "level3b"], dependencies=[Depends(dep3)], responses={ 403: {"description": "Client error level 3"}, 503: {"description": "Server error level 3"}, }, default_response_class=ResponseLevel3, callbacks=callback_router3.routes, ) router2_default.include_router(router4_override) router2_default.include_router(router4_default) app.include_router( router2_override, prefix="/level1", tags=["level1a", "level1b"], dependencies=[Depends(dep1)], responses={ 401: {"description": "Client error level 1"}, 501: {"description": "Server error level 1"}, }, default_response_class=ResponseLevel1, callbacks=callback_router1.routes, ) app.include_router( router2_default, prefix="/level1", tags=["level1a", "level1b"], dependencies=[Depends(dep1)], responses={ 401: {"description": "Client error level 1"}, 501: {"description": "Server error level 1"}, }, default_response_class=ResponseLevel1, callbacks=callback_router1.routes, ) app.include_router(router2_override) app.include_router(router2_default) client = TestClient(app) def test_level1_override(): response = client.get("/override1?level1=foo") assert response.json() == "foo" assert response.headers["content-type"] == "application/x-level-1" assert "x-level0" in response.headers assert "x-level1" in response.headers assert "x-level2" not in response.headers assert "x-level3" not in response.headers assert "x-level4" not in response.headers assert "x-level5" not in response.headers def test_level1_default(): response = client.get("/default1?level1=foo") assert response.json() == "foo" assert response.headers["content-type"] == "application/x-level-0" assert "x-level0" in response.headers assert "x-level1" not in response.headers assert "x-level2" not in response.headers assert "x-level3" not in response.headers assert "x-level4" not in response.headers assert "x-level5" not in response.headers @pytest.mark.parametrize("override1", [True, False]) @pytest.mark.parametrize("override2", [True, False]) @pytest.mark.parametrize("override3", [True, False]) def test_paths_level3(override1, override2, override3): url = "" content_type_level = "0" if override1: url += "/level1" content_type_level = "1" if override2: url += "/level2" content_type_level = "2" if override3: url += "/override3" content_type_level = "3" else: url += "/default3" url += "?level3=foo" response = client.get(url) assert response.json() == "foo" assert ( response.headers["content-type"] == f"application/x-level-{content_type_level}" ) assert "x-level0" in response.headers assert not override1 or "x-level1" in response.headers assert not override2 or "x-level2" in response.headers assert not override3 or "x-level3" in response.headers @pytest.mark.parametrize("override1", [True, False]) @pytest.mark.parametrize("override2", [True, False]) @pytest.mark.parametrize("override3", [True, False]) @pytest.mark.parametrize("override4", [True, False]) @pytest.mark.parametrize("override5", [True, False]) def test_paths_level5(override1, override2, override3, override4, override5): url = "" content_type_level = "0" if override1: url += "/level1" content_type_level = "1" if override2: url += "/level2" content_type_level = "2" if override3: url += "/level3" content_type_level = "3" if override4: url += "/level4" content_type_level = "4" if override5: url += "/override5" content_type_level = "5" else: url += "/default5" url += "?level5=foo" response = client.get(url) assert response.json() == "foo" assert ( response.headers["content-type"] == f"application/x-level-{content_type_level}" ) assert "x-level0" in response.headers assert not override1 or "x-level1" in response.headers assert not override2 or "x-level2" in response.headers assert not override3 or "x-level3" in response.headers assert not override4 or "x-level4" in response.headers assert not override5 or "x-level5" in response.headers def test_openapi(): client = TestClient(app) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") response = client.get("/openapi.json") assert issubclass(w[-1].category, UserWarning) assert "Duplicate Operation ID" in str(w[-1].message) assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/override1": { "get": { "tags": ["path1a", "path1b"], "summary": "Path1 Override", "operationId": "path1_override_override1_get", "parameters": [ { "required": True, "schema": {"title": "Level1", "type": "string"}, "name": "level1", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-1": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "401": {"description": "Client error level 1"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "501": {"description": "Server error level 1"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback1": { "/": { "get": { "summary": "Callback1", "operationId": "callback1__get", "parameters": [ { "name": "level1", "in": "query", "required": True, "schema": { "title": "Level1", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/default1": { "get": { "summary": "Path1 Default", "operationId": "path1_default_default1_get", "parameters": [ { "required": True, "schema": {"title": "Level1", "type": "string"}, "name": "level1", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-0": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } } }, } }, "/level1/level2/override3": { "get": { "tags": [ "level1a", "level1b", "level2a", "level2b", "path3a", "path3b", ], "summary": "Path3 Override Router2 Override", "operationId": "path3_override_router2_override_level1_level2_override3_get", "parameters": [ { "required": True, "schema": {"title": "Level3", "type": "string"}, "name": "level3", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-3": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "401": {"description": "Client error level 1"}, "402": {"description": "Client error level 2"}, "403": {"description": "Client error level 3"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "501": {"description": "Server error level 1"}, "502": {"description": "Server error level 2"}, "503": {"description": "Server error level 3"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback1": { "/": { "get": { "summary": "Callback1", "operationId": "callback1__get", "parameters": [ { "name": "level1", "in": "query", "required": True, "schema": { "title": "Level1", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback2": { "/": { "get": { "summary": "Callback2", "operationId": "callback2__get", "parameters": [ { "name": "level2", "in": "query", "required": True, "schema": { "title": "Level2", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback3": { "/": { "get": { "summary": "Callback3", "operationId": "callback3__get", "parameters": [ { "name": "level3", "in": "query", "required": True, "schema": { "title": "Level3", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level1/level2/default3": { "get": { "tags": ["level1a", "level1b", "level2a", "level2b"], "summary": "Path3 Default Router2 Override", "operationId": "path3_default_router2_override_level1_level2_default3_get", "parameters": [ { "required": True, "schema": {"title": "Level3", "type": "string"}, "name": "level3", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-2": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "401": {"description": "Client error level 1"}, "402": {"description": "Client error level 2"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "501": {"description": "Server error level 1"}, "502": {"description": "Server error level 2"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback1": { "/": { "get": { "summary": "Callback1", "operationId": "callback1__get", "parameters": [ { "name": "level1", "in": "query", "required": True, "schema": { "title": "Level1", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback2": { "/": { "get": { "summary": "Callback2", "operationId": "callback2__get", "parameters": [ { "name": "level2", "in": "query", "required": True, "schema": { "title": "Level2", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level1/level2/level3/level4/override5": { "get": { "tags": [ "level1a", "level1b", "level2a", "level2b", "level3a", "level3b", "level4a", "level4b", "path5a", "path5b", ], "summary": "Path5 Override Router4 Override", "operationId": "path5_override_router4_override_level1_level2_level3_level4_override5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-5": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "401": {"description": "Client error level 1"}, "402": {"description": "Client error level 2"}, "403": {"description": "Client error level 3"}, "404": {"description": "Client error level 4"}, "405": {"description": "Client error level 5"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "501": {"description": "Server error level 1"}, "502": {"description": "Server error level 2"}, "503": {"description": "Server error level 3"}, "504": {"description": "Server error level 4"}, "505": {"description": "Server error level 5"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback1": { "/": { "get": { "summary": "Callback1", "operationId": "callback1__get", "parameters": [ { "name": "level1", "in": "query", "required": True, "schema": { "title": "Level1", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback2": { "/": { "get": { "summary": "Callback2", "operationId": "callback2__get", "parameters": [ { "name": "level2", "in": "query", "required": True, "schema": { "title": "Level2", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback3": { "/": { "get": { "summary": "Callback3", "operationId": "callback3__get", "parameters": [ { "name": "level3", "in": "query", "required": True, "schema": { "title": "Level3", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback4": { "/": { "get": { "summary": "Callback4", "operationId": "callback4__get", "parameters": [ { "name": "level4", "in": "query", "required": True, "schema": { "title": "Level4", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback5": { "/": { "get": { "summary": "Callback5", "operationId": "callback5__get", "parameters": [ { "name": "level5", "in": "query", "required": True, "schema": { "title": "Level5", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level1/level2/level3/level4/default5": { "get": { "tags": [ "level1a", "level1b", "level2a", "level2b", "level3a", "level3b", "level4a", "level4b", ], "summary": "Path5 Default Router4 Override", "operationId": "path5_default_router4_override_level1_level2_level3_level4_default5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-4": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "401": {"description": "Client error level 1"}, "402": {"description": "Client error level 2"}, "403": {"description": "Client error level 3"}, "404": {"description": "Client error level 4"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "501": {"description": "Server error level 1"}, "502": {"description": "Server error level 2"}, "503": {"description": "Server error level 3"}, "504": {"description": "Server error level 4"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback1": { "/": { "get": { "summary": "Callback1", "operationId": "callback1__get", "parameters": [ { "name": "level1", "in": "query", "required": True, "schema": { "title": "Level1", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback2": { "/": { "get": { "summary": "Callback2", "operationId": "callback2__get", "parameters": [ { "name": "level2", "in": "query", "required": True, "schema": { "title": "Level2", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback3": { "/": { "get": { "summary": "Callback3", "operationId": "callback3__get", "parameters": [ { "name": "level3", "in": "query", "required": True, "schema": { "title": "Level3", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback4": { "/": { "get": { "summary": "Callback4", "operationId": "callback4__get", "parameters": [ { "name": "level4", "in": "query", "required": True, "schema": { "title": "Level4", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level1/level2/level3/override5": { "get": { "tags": [ "level1a", "level1b", "level2a", "level2b", "level3a", "level3b", "path5a", "path5b", ], "summary": "Path5 Override Router4 Default", "operationId": "path5_override_router4_default_level1_level2_level3_override5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-5": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "401": {"description": "Client error level 1"}, "402": {"description": "Client error level 2"}, "403": {"description": "Client error level 3"}, "405": {"description": "Client error level 5"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "501": {"description": "Server error level 1"}, "502": {"description": "Server error level 2"}, "503": {"description": "Server error level 3"}, "505": {"description": "Server error level 5"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback1": { "/": { "get": { "summary": "Callback1", "operationId": "callback1__get", "parameters": [ { "name": "level1", "in": "query", "required": True, "schema": { "title": "Level1", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback2": { "/": { "get": { "summary": "Callback2", "operationId": "callback2__get", "parameters": [ { "name": "level2", "in": "query", "required": True, "schema": { "title": "Level2", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback3": { "/": { "get": { "summary": "Callback3", "operationId": "callback3__get", "parameters": [ { "name": "level3", "in": "query", "required": True, "schema": { "title": "Level3", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback5": { "/": { "get": { "summary": "Callback5", "operationId": "callback5__get", "parameters": [ { "name": "level5", "in": "query", "required": True, "schema": { "title": "Level5", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level1/level2/level3/default5": { "get": { "tags": [ "level1a", "level1b", "level2a", "level2b", "level3a", "level3b", ], "summary": "Path5 Default Router4 Default", "operationId": "path5_default_router4_default_level1_level2_level3_default5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-3": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "401": {"description": "Client error level 1"}, "402": {"description": "Client error level 2"}, "403": {"description": "Client error level 3"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "501": {"description": "Server error level 1"}, "502": {"description": "Server error level 2"}, "503": {"description": "Server error level 3"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback1": { "/": { "get": { "summary": "Callback1", "operationId": "callback1__get", "parameters": [ { "name": "level1", "in": "query", "required": True, "schema": { "title": "Level1", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback2": { "/": { "get": { "summary": "Callback2", "operationId": "callback2__get", "parameters": [ { "name": "level2", "in": "query", "required": True, "schema": { "title": "Level2", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback3": { "/": { "get": { "summary": "Callback3", "operationId": "callback3__get", "parameters": [ { "name": "level3", "in": "query", "required": True, "schema": { "title": "Level3", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level1/level2/level4/override5": { "get": { "tags": [ "level1a", "level1b", "level2a", "level2b", "level4a", "level4b", "path5a", "path5b", ], "summary": "Path5 Override Router4 Override", "operationId": "path5_override_router4_override_level1_level2_level4_override5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-5": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "401": {"description": "Client error level 1"}, "402": {"description": "Client error level 2"}, "404": {"description": "Client error level 4"}, "405": {"description": "Client error level 5"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "501": {"description": "Server error level 1"}, "502": {"description": "Server error level 2"}, "504": {"description": "Server error level 4"}, "505": {"description": "Server error level 5"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback1": { "/": { "get": { "summary": "Callback1", "operationId": "callback1__get", "parameters": [ { "name": "level1", "in": "query", "required": True, "schema": { "title": "Level1", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback2": { "/": { "get": { "summary": "Callback2", "operationId": "callback2__get", "parameters": [ { "name": "level2", "in": "query", "required": True, "schema": { "title": "Level2", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback4": { "/": { "get": { "summary": "Callback4", "operationId": "callback4__get", "parameters": [ { "name": "level4", "in": "query", "required": True, "schema": { "title": "Level4", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback5": { "/": { "get": { "summary": "Callback5", "operationId": "callback5__get", "parameters": [ { "name": "level5", "in": "query", "required": True, "schema": { "title": "Level5", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level1/level2/level4/default5": { "get": { "tags": [ "level1a", "level1b", "level2a", "level2b", "level4a", "level4b", ], "summary": "Path5 Default Router4 Override", "operationId": "path5_default_router4_override_level1_level2_level4_default5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-4": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "401": {"description": "Client error level 1"}, "402": {"description": "Client error level 2"}, "404": {"description": "Client error level 4"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "501": {"description": "Server error level 1"}, "502": {"description": "Server error level 2"}, "504": {"description": "Server error level 4"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback1": { "/": { "get": { "summary": "Callback1", "operationId": "callback1__get", "parameters": [ { "name": "level1", "in": "query", "required": True, "schema": { "title": "Level1", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback2": { "/": { "get": { "summary": "Callback2", "operationId": "callback2__get", "parameters": [ { "name": "level2", "in": "query", "required": True, "schema": { "title": "Level2", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback4": { "/": { "get": { "summary": "Callback4", "operationId": "callback4__get", "parameters": [ { "name": "level4", "in": "query", "required": True, "schema": { "title": "Level4", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level1/level2/override5": { "get": { "tags": [ "level1a", "level1b", "level2a", "level2b", "path5a", "path5b", ], "summary": "Path5 Override Router4 Default", "operationId": "path5_override_router4_default_level1_level2_override5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-5": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "401": {"description": "Client error level 1"}, "402": {"description": "Client error level 2"}, "405": {"description": "Client error level 5"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "501": {"description": "Server error level 1"}, "502": {"description": "Server error level 2"}, "505": {"description": "Server error level 5"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback1": { "/": { "get": { "summary": "Callback1", "operationId": "callback1__get", "parameters": [ { "name": "level1", "in": "query", "required": True, "schema": { "title": "Level1", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback2": { "/": { "get": { "summary": "Callback2", "operationId": "callback2__get", "parameters": [ { "name": "level2", "in": "query", "required": True, "schema": { "title": "Level2", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback5": { "/": { "get": { "summary": "Callback5", "operationId": "callback5__get", "parameters": [ { "name": "level5", "in": "query", "required": True, "schema": { "title": "Level5", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level1/level2/default5": { "get": { "tags": ["level1a", "level1b", "level2a", "level2b"], "summary": "Path5 Default Router4 Default", "operationId": "path5_default_router4_default_level1_level2_default5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-2": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "401": {"description": "Client error level 1"}, "402": {"description": "Client error level 2"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "501": {"description": "Server error level 1"}, "502": {"description": "Server error level 2"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback1": { "/": { "get": { "summary": "Callback1", "operationId": "callback1__get", "parameters": [ { "name": "level1", "in": "query", "required": True, "schema": { "title": "Level1", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback2": { "/": { "get": { "summary": "Callback2", "operationId": "callback2__get", "parameters": [ { "name": "level2", "in": "query", "required": True, "schema": { "title": "Level2", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level1/override3": { "get": { "tags": ["level1a", "level1b", "path3a", "path3b"], "summary": "Path3 Override Router2 Default", "operationId": "path3_override_router2_default_level1_override3_get", "parameters": [ { "required": True, "schema": {"title": "Level3", "type": "string"}, "name": "level3", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-3": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "401": {"description": "Client error level 1"}, "403": {"description": "Client error level 3"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "501": {"description": "Server error level 1"}, "503": {"description": "Server error level 3"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback1": { "/": { "get": { "summary": "Callback1", "operationId": "callback1__get", "parameters": [ { "name": "level1", "in": "query", "required": True, "schema": { "title": "Level1", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback3": { "/": { "get": { "summary": "Callback3", "operationId": "callback3__get", "parameters": [ { "name": "level3", "in": "query", "required": True, "schema": { "title": "Level3", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level1/default3": { "get": { "tags": ["level1a", "level1b"], "summary": "Path3 Default Router2 Default", "operationId": "path3_default_router2_default_level1_default3_get", "parameters": [ { "required": True, "schema": {"title": "Level3", "type": "string"}, "name": "level3", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-1": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "401": {"description": "Client error level 1"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "501": {"description": "Server error level 1"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback1": { "/": { "get": { "summary": "Callback1", "operationId": "callback1__get", "parameters": [ { "name": "level1", "in": "query", "required": True, "schema": { "title": "Level1", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, } }, "/level1/level3/level4/override5": { "get": { "tags": [ "level1a", "level1b", "level3a", "level3b", "level4a", "level4b", "path5a", "path5b", ], "summary": "Path5 Override Router4 Override", "operationId": "path5_override_router4_override_level1_level3_level4_override5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-5": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "401": {"description": "Client error level 1"}, "403": {"description": "Client error level 3"}, "404": {"description": "Client error level 4"}, "405": {"description": "Client error level 5"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "501": {"description": "Server error level 1"}, "503": {"description": "Server error level 3"}, "504": {"description": "Server error level 4"}, "505": {"description": "Server error level 5"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback1": { "/": { "get": { "summary": "Callback1", "operationId": "callback1__get", "parameters": [ { "name": "level1", "in": "query", "required": True, "schema": { "title": "Level1", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback3": { "/": { "get": { "summary": "Callback3", "operationId": "callback3__get", "parameters": [ { "name": "level3", "in": "query", "required": True, "schema": { "title": "Level3", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback4": { "/": { "get": { "summary": "Callback4", "operationId": "callback4__get", "parameters": [ { "name": "level4", "in": "query", "required": True, "schema": { "title": "Level4", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback5": { "/": { "get": { "summary": "Callback5", "operationId": "callback5__get", "parameters": [ { "name": "level5", "in": "query", "required": True, "schema": { "title": "Level5", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level1/level3/level4/default5": { "get": { "tags": [ "level1a", "level1b", "level3a", "level3b", "level4a", "level4b", ], "summary": "Path5 Default Router4 Override", "operationId": "path5_default_router4_override_level1_level3_level4_default5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-4": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "401": {"description": "Client error level 1"}, "403": {"description": "Client error level 3"}, "404": {"description": "Client error level 4"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "501": {"description": "Server error level 1"}, "503": {"description": "Server error level 3"}, "504": {"description": "Server error level 4"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback1": { "/": { "get": { "summary": "Callback1", "operationId": "callback1__get", "parameters": [ { "name": "level1", "in": "query", "required": True, "schema": { "title": "Level1", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback3": { "/": { "get": { "summary": "Callback3", "operationId": "callback3__get", "parameters": [ { "name": "level3", "in": "query", "required": True, "schema": { "title": "Level3", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback4": { "/": { "get": { "summary": "Callback4", "operationId": "callback4__get", "parameters": [ { "name": "level4", "in": "query", "required": True, "schema": { "title": "Level4", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level1/level3/override5": { "get": { "tags": [ "level1a", "level1b", "level3a", "level3b", "path5a", "path5b", ], "summary": "Path5 Override Router4 Default", "operationId": "path5_override_router4_default_level1_level3_override5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-5": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "401": {"description": "Client error level 1"}, "403": {"description": "Client error level 3"}, "405": {"description": "Client error level 5"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "501": {"description": "Server error level 1"}, "503": {"description": "Server error level 3"}, "505": {"description": "Server error level 5"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback1": { "/": { "get": { "summary": "Callback1", "operationId": "callback1__get", "parameters": [ { "name": "level1", "in": "query", "required": True, "schema": { "title": "Level1", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback3": { "/": { "get": { "summary": "Callback3", "operationId": "callback3__get", "parameters": [ { "name": "level3", "in": "query", "required": True, "schema": { "title": "Level3", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback5": { "/": { "get": { "summary": "Callback5", "operationId": "callback5__get", "parameters": [ { "name": "level5", "in": "query", "required": True, "schema": { "title": "Level5", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level1/level3/default5": { "get": { "tags": ["level1a", "level1b", "level3a", "level3b"], "summary": "Path5 Default Router4 Default", "operationId": "path5_default_router4_default_level1_level3_default5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-3": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "401": {"description": "Client error level 1"}, "403": {"description": "Client error level 3"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "501": {"description": "Server error level 1"}, "503": {"description": "Server error level 3"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback1": { "/": { "get": { "summary": "Callback1", "operationId": "callback1__get", "parameters": [ { "name": "level1", "in": "query", "required": True, "schema": { "title": "Level1", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback3": { "/": { "get": { "summary": "Callback3", "operationId": "callback3__get", "parameters": [ { "name": "level3", "in": "query", "required": True, "schema": { "title": "Level3", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, } }, "/level1/level4/override5": { "get": { "tags": [ "level1a", "level1b", "level4a", "level4b", "path5a", "path5b", ], "summary": "Path5 Override Router4 Override", "operationId": "path5_override_router4_override_level1_level4_override5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-5": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "401": {"description": "Client error level 1"}, "404": {"description": "Client error level 4"}, "405": {"description": "Client error level 5"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "501": {"description": "Server error level 1"}, "504": {"description": "Server error level 4"}, "505": {"description": "Server error level 5"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback1": { "/": { "get": { "summary": "Callback1", "operationId": "callback1__get", "parameters": [ { "name": "level1", "in": "query", "required": True, "schema": { "title": "Level1", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback4": { "/": { "get": { "summary": "Callback4", "operationId": "callback4__get", "parameters": [ { "name": "level4", "in": "query", "required": True, "schema": { "title": "Level4", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback5": { "/": { "get": { "summary": "Callback5", "operationId": "callback5__get", "parameters": [ { "name": "level5", "in": "query", "required": True, "schema": { "title": "Level5", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level1/level4/default5": { "get": { "tags": ["level1a", "level1b", "level4a", "level4b"], "summary": "Path5 Default Router4 Override", "operationId": "path5_default_router4_override_level1_level4_default5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-4": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "401": {"description": "Client error level 1"}, "404": {"description": "Client error level 4"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "501": {"description": "Server error level 1"}, "504": {"description": "Server error level 4"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback1": { "/": { "get": { "summary": "Callback1", "operationId": "callback1__get", "parameters": [ { "name": "level1", "in": "query", "required": True, "schema": { "title": "Level1", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback4": { "/": { "get": { "summary": "Callback4", "operationId": "callback4__get", "parameters": [ { "name": "level4", "in": "query", "required": True, "schema": { "title": "Level4", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level1/override5": { "get": { "tags": ["level1a", "level1b", "path5a", "path5b"], "summary": "Path5 Override Router4 Default", "operationId": "path5_override_router4_default_level1_override5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-5": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "401": {"description": "Client error level 1"}, "405": {"description": "Client error level 5"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "501": {"description": "Server error level 1"}, "505": {"description": "Server error level 5"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback1": { "/": { "get": { "summary": "Callback1", "operationId": "callback1__get", "parameters": [ { "name": "level1", "in": "query", "required": True, "schema": { "title": "Level1", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback5": { "/": { "get": { "summary": "Callback5", "operationId": "callback5__get", "parameters": [ { "name": "level5", "in": "query", "required": True, "schema": { "title": "Level5", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level1/default5": { "get": { "tags": ["level1a", "level1b"], "summary": "Path5 Default Router4 Default", "operationId": "path5_default_router4_default_level1_default5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-1": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "401": {"description": "Client error level 1"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "501": {"description": "Server error level 1"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback1": { "/": { "get": { "summary": "Callback1", "operationId": "callback1__get", "parameters": [ { "name": "level1", "in": "query", "required": True, "schema": { "title": "Level1", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, } }, "/level2/override3": { "get": { "tags": ["level2a", "level2b", "path3a", "path3b"], "summary": "Path3 Override Router2 Override", "operationId": "path3_override_router2_override_level2_override3_get", "parameters": [ { "required": True, "schema": {"title": "Level3", "type": "string"}, "name": "level3", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-3": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "402": {"description": "Client error level 2"}, "403": {"description": "Client error level 3"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "502": {"description": "Server error level 2"}, "503": {"description": "Server error level 3"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback2": { "/": { "get": { "summary": "Callback2", "operationId": "callback2__get", "parameters": [ { "name": "level2", "in": "query", "required": True, "schema": { "title": "Level2", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback3": { "/": { "get": { "summary": "Callback3", "operationId": "callback3__get", "parameters": [ { "name": "level3", "in": "query", "required": True, "schema": { "title": "Level3", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level2/default3": { "get": { "tags": ["level2a", "level2b"], "summary": "Path3 Default Router2 Override", "operationId": "path3_default_router2_override_level2_default3_get", "parameters": [ { "required": True, "schema": {"title": "Level3", "type": "string"}, "name": "level3", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-2": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "402": {"description": "Client error level 2"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "502": {"description": "Server error level 2"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback2": { "/": { "get": { "summary": "Callback2", "operationId": "callback2__get", "parameters": [ { "name": "level2", "in": "query", "required": True, "schema": { "title": "Level2", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level2/level3/level4/override5": { "get": { "tags": [ "level2a", "level2b", "level3a", "level3b", "level4a", "level4b", "path5a", "path5b", ], "summary": "Path5 Override Router4 Override", "operationId": "path5_override_router4_override_level2_level3_level4_override5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-5": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "402": {"description": "Client error level 2"}, "403": {"description": "Client error level 3"}, "404": {"description": "Client error level 4"}, "405": {"description": "Client error level 5"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "502": {"description": "Server error level 2"}, "503": {"description": "Server error level 3"}, "504": {"description": "Server error level 4"}, "505": {"description": "Server error level 5"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback2": { "/": { "get": { "summary": "Callback2", "operationId": "callback2__get", "parameters": [ { "name": "level2", "in": "query", "required": True, "schema": { "title": "Level2", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback3": { "/": { "get": { "summary": "Callback3", "operationId": "callback3__get", "parameters": [ { "name": "level3", "in": "query", "required": True, "schema": { "title": "Level3", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback4": { "/": { "get": { "summary": "Callback4", "operationId": "callback4__get", "parameters": [ { "name": "level4", "in": "query", "required": True, "schema": { "title": "Level4", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback5": { "/": { "get": { "summary": "Callback5", "operationId": "callback5__get", "parameters": [ { "name": "level5", "in": "query", "required": True, "schema": { "title": "Level5", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level2/level3/level4/default5": { "get": { "tags": [ "level2a", "level2b", "level3a", "level3b", "level4a", "level4b", ], "summary": "Path5 Default Router4 Override", "operationId": "path5_default_router4_override_level2_level3_level4_default5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-4": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "402": {"description": "Client error level 2"}, "403": {"description": "Client error level 3"}, "404": {"description": "Client error level 4"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "502": {"description": "Server error level 2"}, "503": {"description": "Server error level 3"}, "504": {"description": "Server error level 4"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback2": { "/": { "get": { "summary": "Callback2", "operationId": "callback2__get", "parameters": [ { "name": "level2", "in": "query", "required": True, "schema": { "title": "Level2", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback3": { "/": { "get": { "summary": "Callback3", "operationId": "callback3__get", "parameters": [ { "name": "level3", "in": "query", "required": True, "schema": { "title": "Level3", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback4": { "/": { "get": { "summary": "Callback4", "operationId": "callback4__get", "parameters": [ { "name": "level4", "in": "query", "required": True, "schema": { "title": "Level4", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level2/level3/override5": { "get": { "tags": [ "level2a", "level2b", "level3a", "level3b", "path5a", "path5b", ], "summary": "Path5 Override Router4 Default", "operationId": "path5_override_router4_default_level2_level3_override5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-5": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "402": {"description": "Client error level 2"}, "403": {"description": "Client error level 3"}, "405": {"description": "Client error level 5"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "502": {"description": "Server error level 2"}, "503": {"description": "Server error level 3"}, "505": {"description": "Server error level 5"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback2": { "/": { "get": { "summary": "Callback2", "operationId": "callback2__get", "parameters": [ { "name": "level2", "in": "query", "required": True, "schema": { "title": "Level2", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback3": { "/": { "get": { "summary": "Callback3", "operationId": "callback3__get", "parameters": [ { "name": "level3", "in": "query", "required": True, "schema": { "title": "Level3", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback5": { "/": { "get": { "summary": "Callback5", "operationId": "callback5__get", "parameters": [ { "name": "level5", "in": "query", "required": True, "schema": { "title": "Level5", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level2/level3/default5": { "get": { "tags": ["level2a", "level2b", "level3a", "level3b"], "summary": "Path5 Default Router4 Default", "operationId": "path5_default_router4_default_level2_level3_default5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-3": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "402": {"description": "Client error level 2"}, "403": {"description": "Client error level 3"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "502": {"description": "Server error level 2"}, "503": {"description": "Server error level 3"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback2": { "/": { "get": { "summary": "Callback2", "operationId": "callback2__get", "parameters": [ { "name": "level2", "in": "query", "required": True, "schema": { "title": "Level2", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback3": { "/": { "get": { "summary": "Callback3", "operationId": "callback3__get", "parameters": [ { "name": "level3", "in": "query", "required": True, "schema": { "title": "Level3", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level2/level4/override5": { "get": { "tags": [ "level2a", "level2b", "level4a", "level4b", "path5a", "path5b", ], "summary": "Path5 Override Router4 Override", "operationId": "path5_override_router4_override_level2_level4_override5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-5": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "402": {"description": "Client error level 2"}, "404": {"description": "Client error level 4"}, "405": {"description": "Client error level 5"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "502": {"description": "Server error level 2"}, "504": {"description": "Server error level 4"}, "505": {"description": "Server error level 5"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback2": { "/": { "get": { "summary": "Callback2", "operationId": "callback2__get", "parameters": [ { "name": "level2", "in": "query", "required": True, "schema": { "title": "Level2", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback4": { "/": { "get": { "summary": "Callback4", "operationId": "callback4__get", "parameters": [ { "name": "level4", "in": "query", "required": True, "schema": { "title": "Level4", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback5": { "/": { "get": { "summary": "Callback5", "operationId": "callback5__get", "parameters": [ { "name": "level5", "in": "query", "required": True, "schema": { "title": "Level5", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level2/level4/default5": { "get": { "tags": ["level2a", "level2b", "level4a", "level4b"], "summary": "Path5 Default Router4 Override", "operationId": "path5_default_router4_override_level2_level4_default5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-4": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "402": {"description": "Client error level 2"}, "404": {"description": "Client error level 4"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "502": {"description": "Server error level 2"}, "504": {"description": "Server error level 4"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback2": { "/": { "get": { "summary": "Callback2", "operationId": "callback2__get", "parameters": [ { "name": "level2", "in": "query", "required": True, "schema": { "title": "Level2", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback4": { "/": { "get": { "summary": "Callback4", "operationId": "callback4__get", "parameters": [ { "name": "level4", "in": "query", "required": True, "schema": { "title": "Level4", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level2/override5": { "get": { "tags": ["level2a", "level2b", "path5a", "path5b"], "summary": "Path5 Override Router4 Default", "operationId": "path5_override_router4_default_level2_override5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-5": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "402": {"description": "Client error level 2"}, "405": {"description": "Client error level 5"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "502": {"description": "Server error level 2"}, "505": {"description": "Server error level 5"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback2": { "/": { "get": { "summary": "Callback2", "operationId": "callback2__get", "parameters": [ { "name": "level2", "in": "query", "required": True, "schema": { "title": "Level2", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback5": { "/": { "get": { "summary": "Callback5", "operationId": "callback5__get", "parameters": [ { "name": "level5", "in": "query", "required": True, "schema": { "title": "Level5", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level2/default5": { "get": { "tags": ["level2a", "level2b"], "summary": "Path5 Default Router4 Default", "operationId": "path5_default_router4_default_level2_default5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-2": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "402": {"description": "Client error level 2"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "502": {"description": "Server error level 2"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback2": { "/": { "get": { "summary": "Callback2", "operationId": "callback2__get", "parameters": [ { "name": "level2", "in": "query", "required": True, "schema": { "title": "Level2", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/override3": { "get": { "tags": ["path3a", "path3b"], "summary": "Path3 Override Router2 Default", "operationId": "path3_override_router2_default_override3_get", "parameters": [ { "required": True, "schema": {"title": "Level3", "type": "string"}, "name": "level3", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-3": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "403": {"description": "Client error level 3"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "503": {"description": "Server error level 3"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback3": { "/": { "get": { "summary": "Callback3", "operationId": "callback3__get", "parameters": [ { "name": "level3", "in": "query", "required": True, "schema": { "title": "Level3", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/default3": { "get": { "summary": "Path3 Default Router2 Default", "operationId": "path3_default_router2_default_default3_get", "parameters": [ { "required": True, "schema": {"title": "Level3", "type": "string"}, "name": "level3", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-0": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } } }, } }, "/level3/level4/override5": { "get": { "tags": [ "level3a", "level3b", "level4a", "level4b", "path5a", "path5b", ], "summary": "Path5 Override Router4 Override", "operationId": "path5_override_router4_override_level3_level4_override5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-5": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "403": {"description": "Client error level 3"}, "404": {"description": "Client error level 4"}, "405": {"description": "Client error level 5"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "503": {"description": "Server error level 3"}, "504": {"description": "Server error level 4"}, "505": {"description": "Server error level 5"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback3": { "/": { "get": { "summary": "Callback3", "operationId": "callback3__get", "parameters": [ { "name": "level3", "in": "query", "required": True, "schema": { "title": "Level3", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback4": { "/": { "get": { "summary": "Callback4", "operationId": "callback4__get", "parameters": [ { "name": "level4", "in": "query", "required": True, "schema": { "title": "Level4", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback5": { "/": { "get": { "summary": "Callback5", "operationId": "callback5__get", "parameters": [ { "name": "level5", "in": "query", "required": True, "schema": { "title": "Level5", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level3/level4/default5": { "get": { "tags": ["level3a", "level3b", "level4a", "level4b"], "summary": "Path5 Default Router4 Override", "operationId": "path5_default_router4_override_level3_level4_default5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-4": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "403": {"description": "Client error level 3"}, "404": {"description": "Client error level 4"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "503": {"description": "Server error level 3"}, "504": {"description": "Server error level 4"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback3": { "/": { "get": { "summary": "Callback3", "operationId": "callback3__get", "parameters": [ { "name": "level3", "in": "query", "required": True, "schema": { "title": "Level3", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback4": { "/": { "get": { "summary": "Callback4", "operationId": "callback4__get", "parameters": [ { "name": "level4", "in": "query", "required": True, "schema": { "title": "Level4", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level3/override5": { "get": { "tags": ["level3a", "level3b", "path5a", "path5b"], "summary": "Path5 Override Router4 Default", "operationId": "path5_override_router4_default_level3_override5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-5": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "403": {"description": "Client error level 3"}, "405": {"description": "Client error level 5"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "503": {"description": "Server error level 3"}, "505": {"description": "Server error level 5"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback3": { "/": { "get": { "summary": "Callback3", "operationId": "callback3__get", "parameters": [ { "name": "level3", "in": "query", "required": True, "schema": { "title": "Level3", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback5": { "/": { "get": { "summary": "Callback5", "operationId": "callback5__get", "parameters": [ { "name": "level5", "in": "query", "required": True, "schema": { "title": "Level5", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level3/default5": { "get": { "tags": ["level3a", "level3b"], "summary": "Path5 Default Router4 Default", "operationId": "path5_default_router4_default_level3_default5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-3": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "403": {"description": "Client error level 3"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "503": {"description": "Server error level 3"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback3": { "/": { "get": { "summary": "Callback3", "operationId": "callback3__get", "parameters": [ { "name": "level3", "in": "query", "required": True, "schema": { "title": "Level3", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, } }, "/level4/override5": { "get": { "tags": ["level4a", "level4b", "path5a", "path5b"], "summary": "Path5 Override Router4 Override", "operationId": "path5_override_router4_override_level4_override5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-5": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "404": {"description": "Client error level 4"}, "405": {"description": "Client error level 5"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "504": {"description": "Server error level 4"}, "505": {"description": "Server error level 5"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback4": { "/": { "get": { "summary": "Callback4", "operationId": "callback4__get", "parameters": [ { "name": "level4", "in": "query", "required": True, "schema": { "title": "Level4", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback5": { "/": { "get": { "summary": "Callback5", "operationId": "callback5__get", "parameters": [ { "name": "level5", "in": "query", "required": True, "schema": { "title": "Level5", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/level4/default5": { "get": { "tags": ["level4a", "level4b"], "summary": "Path5 Default Router4 Override", "operationId": "path5_default_router4_override_level4_default5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-4": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "404": {"description": "Client error level 4"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "504": {"description": "Server error level 4"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback4": { "/": { "get": { "summary": "Callback4", "operationId": "callback4__get", "parameters": [ { "name": "level4", "in": "query", "required": True, "schema": { "title": "Level4", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/override5": { "get": { "tags": ["path5a", "path5b"], "summary": "Path5 Override Router4 Default", "operationId": "path5_override_router4_default_override5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-5": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "405": {"description": "Client error level 5"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, "505": {"description": "Server error level 5"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "callback5": { "/": { "get": { "summary": "Callback5", "operationId": "callback5__get", "parameters": [ { "name": "level5", "in": "query", "required": True, "schema": { "title": "Level5", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, }, "deprecated": True, } }, "/default5": { "get": { "summary": "Path5 Default Router4 Default", "operationId": "path5_default_router4_default_default5_get", "parameters": [ { "required": True, "schema": {"title": "Level5", "type": "string"}, "name": "level5", "in": "query", } ], "responses": { "200": { "description": "Successful Response", "content": {"application/x-level-0": {"schema": {}}}, }, "400": {"description": "Client error level 0"}, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, "500": {"description": "Server error level 0"}, }, "callbacks": { "callback0": { "/": { "get": { "summary": "Callback0", "operationId": "callback0__get", "parameters": [ { "name": "level0", "in": "query", "required": True, "schema": { "title": "Level0", "type": "string", }, } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": {"schema": {}} }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } } }, } }, }, "components": { "schemas": { "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, }
ResponseLevel5
python
davidhalter__parso
parso/python/tree.py
{ "start": 9084, "end": 9187 }
class ____(_LeafWithoutNewlines, _StringComparisonMixin): type = 'keyword' __slots__ = ()
Keyword
python
fastapi__sqlmodel
docs_src/tutorial/where/tutorial009.py
{ "start": 105, "end": 1609 }
class ____(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine = create_engine(sqlite_url, echo=True) def create_db_and_tables(): SQLModel.metadata.create_all(engine) def create_heroes(): hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson") hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador") hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48) hero_4 = Hero(name="Tarantula", secret_name="Natalia Roman-on", age=32) hero_5 = Hero(name="Black Lion", secret_name="Trevor Challa", age=35) hero_6 = Hero(name="Dr. Weird", secret_name="Steve Weird", age=36) hero_7 = Hero(name="Captain North America", secret_name="Esteban Rogelios", age=93) with Session(engine) as session: session.add(hero_1) session.add(hero_2) session.add(hero_3) session.add(hero_4) session.add(hero_5) session.add(hero_6) session.add(hero_7) session.commit() def select_heroes(): with Session(engine) as session: statement = select(Hero).where(or_(Hero.age <= 35, Hero.age > 90)) results = session.exec(statement) for hero in results: print(hero) def main(): create_db_and_tables() create_heroes() select_heroes() if __name__ == "__main__": main()
Hero
python
plotly__plotly.py
plotly/graph_objs/violin/_marker.py
{ "start": 233, "end": 14008 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "violin" _path_str = "violin.marker" _valid_props = { "angle", "color", "line", "opacity", "outliercolor", "size", "symbol", } @property def angle(self): """ Sets the marker angle in respect to `angleref`. The 'angle' property is a angle (in degrees) that may be specified as a number between -180 and 180. Numeric values outside this range are converted to the equivalent value (e.g. 270 is converted to -90). Returns ------- int|float """ return self["angle"] @angle.setter def angle(self, val): self["angle"] = val @property def color(self): """ Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `marker.cmin` and `marker.cmax` if set. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["color"] @color.setter def color(self, val): self["color"] = val @property def line(self): """ The 'line' property is an instance of Line that may be specified as: - An instance of :class:`plotly.graph_objs.violin.marker.Line` - A dict of string/value properties that will be passed to the Line constructor Returns ------- plotly.graph_objs.violin.marker.Line """ return self["line"] @line.setter def line(self, val): self["line"] = val @property def opacity(self): """ Sets the marker opacity. The 'opacity' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float """ return self["opacity"] @opacity.setter def opacity(self, val): self["opacity"] = val @property def outliercolor(self): """ Sets the color of the outlier sample points. The 'outliercolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["outliercolor"] @outliercolor.setter def outliercolor(self, val): self["outliercolor"] = val @property def size(self): """ Sets the marker size (in px). The 'size' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["size"] @size.setter def size(self, val): self["size"] = val @property def symbol(self): """ Sets the marker symbol type. Adding 100 is equivalent to appending "-open" to a symbol name. Adding 200 is equivalent to appending "-dot" to a symbol name. Adding 300 is equivalent to appending "-open-dot" or "dot-open" to a symbol name. The 'symbol' property is an enumeration that may be specified as: - One of the following enumeration values: [0, '0', 'circle', 100, '100', 'circle-open', 200, '200', 'circle-dot', 300, '300', 'circle-open-dot', 1, '1', 'square', 101, '101', 'square-open', 201, '201', 'square-dot', 301, '301', 'square-open-dot', 2, '2', 'diamond', 102, '102', 'diamond-open', 202, '202', 'diamond-dot', 302, '302', 'diamond-open-dot', 3, '3', 'cross', 103, '103', 'cross-open', 203, '203', 'cross-dot', 303, '303', 'cross-open-dot', 4, '4', 'x', 104, '104', 'x-open', 204, '204', 'x-dot', 304, '304', 'x-open-dot', 5, '5', 'triangle-up', 105, '105', 'triangle-up-open', 205, '205', 'triangle-up-dot', 305, '305', 'triangle-up-open-dot', 6, '6', 'triangle-down', 106, '106', 'triangle-down-open', 206, '206', 'triangle-down-dot', 306, '306', 'triangle-down-open-dot', 7, '7', 'triangle-left', 107, '107', 'triangle-left-open', 207, '207', 'triangle-left-dot', 307, '307', 'triangle-left-open-dot', 8, '8', 'triangle-right', 108, '108', 'triangle-right-open', 208, '208', 'triangle-right-dot', 308, '308', 'triangle-right-open-dot', 9, '9', 'triangle-ne', 109, '109', 'triangle-ne-open', 209, '209', 'triangle-ne-dot', 309, '309', 'triangle-ne-open-dot', 10, '10', 'triangle-se', 110, '110', 'triangle-se-open', 210, '210', 'triangle-se-dot', 310, '310', 'triangle-se-open-dot', 11, '11', 'triangle-sw', 111, '111', 'triangle-sw-open', 211, '211', 'triangle-sw-dot', 311, '311', 'triangle-sw-open-dot', 12, '12', 'triangle-nw', 112, '112', 'triangle-nw-open', 212, '212', 'triangle-nw-dot', 312, '312', 'triangle-nw-open-dot', 13, '13', 'pentagon', 113, '113', 'pentagon-open', 213, '213', 'pentagon-dot', 313, '313', 'pentagon-open-dot', 14, '14', 'hexagon', 114, '114', 'hexagon-open', 214, '214', 'hexagon-dot', 314, '314', 'hexagon-open-dot', 15, '15', 'hexagon2', 115, '115', 'hexagon2-open', 215, '215', 'hexagon2-dot', 315, '315', 'hexagon2-open-dot', 16, '16', 'octagon', 116, '116', 'octagon-open', 216, '216', 'octagon-dot', 316, '316', 'octagon-open-dot', 17, '17', 'star', 117, '117', 'star-open', 217, '217', 'star-dot', 317, '317', 'star-open-dot', 18, '18', 'hexagram', 118, '118', 'hexagram-open', 218, '218', 'hexagram-dot', 318, '318', 'hexagram-open-dot', 19, '19', 'star-triangle-up', 119, '119', 'star-triangle-up-open', 219, '219', 'star-triangle-up-dot', 319, '319', 'star-triangle-up-open-dot', 20, '20', 'star-triangle-down', 120, '120', 'star-triangle-down-open', 220, '220', 'star-triangle-down-dot', 320, '320', 'star-triangle-down-open-dot', 21, '21', 'star-square', 121, '121', 'star-square-open', 221, '221', 'star-square-dot', 321, '321', 'star-square-open-dot', 22, '22', 'star-diamond', 122, '122', 'star-diamond-open', 222, '222', 'star-diamond-dot', 322, '322', 'star-diamond-open-dot', 23, '23', 'diamond-tall', 123, '123', 'diamond-tall-open', 223, '223', 'diamond-tall-dot', 323, '323', 'diamond-tall-open-dot', 24, '24', 'diamond-wide', 124, '124', 'diamond-wide-open', 224, '224', 'diamond-wide-dot', 324, '324', 'diamond-wide-open-dot', 25, '25', 'hourglass', 125, '125', 'hourglass-open', 26, '26', 'bowtie', 126, '126', 'bowtie-open', 27, '27', 'circle-cross', 127, '127', 'circle-cross-open', 28, '28', 'circle-x', 128, '128', 'circle-x-open', 29, '29', 'square-cross', 129, '129', 'square-cross-open', 30, '30', 'square-x', 130, '130', 'square-x-open', 31, '31', 'diamond-cross', 131, '131', 'diamond-cross-open', 32, '32', 'diamond-x', 132, '132', 'diamond-x-open', 33, '33', 'cross-thin', 133, '133', 'cross-thin-open', 34, '34', 'x-thin', 134, '134', 'x-thin-open', 35, '35', 'asterisk', 135, '135', 'asterisk-open', 36, '36', 'hash', 136, '136', 'hash-open', 236, '236', 'hash-dot', 336, '336', 'hash-open-dot', 37, '37', 'y-up', 137, '137', 'y-up-open', 38, '38', 'y-down', 138, '138', 'y-down-open', 39, '39', 'y-left', 139, '139', 'y-left-open', 40, '40', 'y-right', 140, '140', 'y-right-open', 41, '41', 'line-ew', 141, '141', 'line-ew-open', 42, '42', 'line-ns', 142, '142', 'line-ns-open', 43, '43', 'line-ne', 143, '143', 'line-ne-open', 44, '44', 'line-nw', 144, '144', 'line-nw-open', 45, '45', 'arrow-up', 145, '145', 'arrow-up-open', 46, '46', 'arrow-down', 146, '146', 'arrow-down-open', 47, '47', 'arrow-left', 147, '147', 'arrow-left-open', 48, '48', 'arrow-right', 148, '148', 'arrow-right-open', 49, '49', 'arrow-bar-up', 149, '149', 'arrow-bar-up-open', 50, '50', 'arrow-bar-down', 150, '150', 'arrow-bar-down-open', 51, '51', 'arrow-bar-left', 151, '151', 'arrow-bar-left-open', 52, '52', 'arrow-bar-right', 152, '152', 'arrow-bar-right-open', 53, '53', 'arrow', 153, '153', 'arrow-open', 54, '54', 'arrow-wide', 154, '154', 'arrow-wide-open'] Returns ------- Any """ return self["symbol"] @symbol.setter def symbol(self, val): self["symbol"] = val @property def _prop_descriptions(self): return """\ angle Sets the marker angle in respect to `angleref`. color Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `marker.cmin` and `marker.cmax` if set. line :class:`plotly.graph_objects.violin.marker.Line` instance or dict with compatible properties opacity Sets the marker opacity. outliercolor Sets the color of the outlier sample points. size Sets the marker size (in px). symbol Sets the marker symbol type. Adding 100 is equivalent to appending "-open" to a symbol name. Adding 200 is equivalent to appending "-dot" to a symbol name. Adding 300 is equivalent to appending "-open-dot" or "dot- open" to a symbol name. """ def __init__( self, arg=None, angle=None, color=None, line=None, opacity=None, outliercolor=None, size=None, symbol=None, **kwargs, ): """ Construct a new Marker object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.violin.Marker` angle Sets the marker angle in respect to `angleref`. color Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `marker.cmin` and `marker.cmax` if set. line :class:`plotly.graph_objects.violin.marker.Line` instance or dict with compatible properties opacity Sets the marker opacity. outliercolor Sets the color of the outlier sample points. size Sets the marker size (in px). symbol Sets the marker symbol type. Adding 100 is equivalent to appending "-open" to a symbol name. Adding 200 is equivalent to appending "-dot" to a symbol name. Adding 300 is equivalent to appending "-open-dot" or "dot- open" to a symbol name. Returns ------- Marker """ super().__init__("marker") 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.violin.Marker constructor must be a dict or an instance of :class:`plotly.graph_objs.violin.Marker`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("angle", arg, angle) self._set_property("color", arg, color) self._set_property("line", arg, line) self._set_property("opacity", arg, opacity) self._set_property("outliercolor", arg, outliercolor) self._set_property("size", arg, size) self._set_property("symbol", arg, symbol) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Marker
python
pypa__build
src/build/env.py
{ "start": 4618, "end": 10222 }
class ____(_EnvBackend): def __init__(self) -> None: self._create_with_virtualenv = not self._has_valid_outer_pip and self._has_virtualenv @functools.cached_property def _has_valid_outer_pip(self) -> bool | None: """ This checks for a valid global pip. Returns None if pip is missing, False if pip is too old, and True if it can be used. """ # Version to have added the `--python` option. if not _has_dependency('pip', '22.3'): # pragma: no cover return False # `pip install --python` is nonfunctional on Gentoo debundled pip. # Detect that by checking if pip._vendor` module exists. However, # searching for pip could yield warnings from _distutils_hack, # so silence them. with warnings.catch_warnings(): warnings.simplefilter('ignore') if importlib.util.find_spec('pip._vendor') is None: return False # pragma: no cover return True @functools.cached_property def _has_virtualenv(self) -> bool: """ virtualenv might be incompatible if it was installed separately from build. This verifies that virtualenv and all of its dependencies are installed as required by build. """ from packaging.requirements import Requirement name = 'virtualenv' return importlib.util.find_spec(name) is not None and not any( Requirement(d[1]).name == name for d in check_dependency(f'build[{name}]') if len(d) > 1 ) @staticmethod def _get_minimum_pip_version_str() -> str: if platform.system() == 'Darwin': release, _, machine = platform.mac_ver() if int(release[: release.find('.')]) >= 11: # macOS 11+ name scheme change requires 20.3. Intel macOS 11.0 can be # told to report 10.16 for backwards compatibility; but that also fixes # earlier versions of pip so this is only needed for 11+. is_apple_silicon_python = machine != 'x86_64' return '21.0.1' if is_apple_silicon_python else '20.3.0' # PEP-517 and manylinux1 was first implemented in 19.1 return '19.1.0' def create(self, path: str) -> None: if self._create_with_virtualenv: import packaging.version import virtualenv from ._compat import importlib virtualenv_ver = packaging.version.Version(importlib.metadata.version('virtualenv')) opts = [ path, '--activators', '', '--no-setuptools', '--no-periodic-update', ] if virtualenv_ver < packaging.version.Version('20.31.0'): opts.append('--no-wheel') result = virtualenv.cli_run(opts, setup_logging=False) # The creator attributes are `pathlib.Path`s. self.python_executable = str(result.creator.exe) self.scripts_dir = str(result.creator.script_dir) else: import venv with_pip = not self._has_valid_outer_pip try: venv.EnvBuilder(symlinks=_fs_supports_symlink(), with_pip=with_pip).create(path) except subprocess.CalledProcessError as exc: _ctx.log_subprocess_error(exc) raise FailedProcessError(exc, 'Failed to create venv. Maybe try installing virtualenv.') from None self.python_executable, self.scripts_dir, purelib = _find_executable_and_scripts(path) if with_pip: minimum_pip_version_str = self._get_minimum_pip_version_str() if not _has_dependency( 'pip', minimum_pip_version_str, path=[purelib], ): run_subprocess([self.python_executable, '-Im', 'pip', 'install', f'pip>={minimum_pip_version_str}']) # Uninstall setuptools from the build env to prevent depending on it implicitly. # Pythons 3.12 and up do not install setuptools, check if it exists first. if _has_dependency( 'setuptools', path=[purelib], ): run_subprocess([self.python_executable, '-Im', 'pip', 'uninstall', '-y', 'setuptools']) def install_requirements(self, requirements: Collection[str]) -> None: # pip does not honour environment markers in command line arguments # but it does from requirement files. with tempfile.NamedTemporaryFile('w', prefix='build-reqs-', suffix='.txt', delete=False, encoding='utf-8') as req_file: req_file.write(os.linesep.join(requirements)) try: if self._has_valid_outer_pip: cmd = [sys.executable, '-m', 'pip', '--python', self.python_executable] else: cmd = [self.python_executable, '-Im', 'pip'] if _ctx.verbosity > 1: cmd += [f'-{"v" * (_ctx.verbosity - 1)}'] cmd += [ 'install', '--use-pep517', '--no-warn-script-location', '--no-compile', '-r', os.path.abspath(req_file.name), ] run_subprocess(cmd) finally: os.unlink(req_file.name) @property def display_name(self) -> str: return 'virtualenv+pip' if self._create_with_virtualenv else 'venv+pip'
_PipBackend
python
getsentry__sentry
tests/sentry/integrations/msteams/test_notifications.py
{ "start": 6898, "end": 8894 }
class ____(MSTeamsActivityNotificationTest): """ Test the MS Teams notification flow end to end without mocking out functions. """ def _setup_msteams_api(self) -> None: responses.add( method=responses.POST, url="https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token", body='{"access_token": "xoxb-xxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxx", "expires_in": "1234567890"}', status=200, content_type="application/json", ) responses.add( method=responses.POST, url="https://testserviceurl.com/testendpoint/v3/conversations", body='{"id": "some_conversation_id"}', status=200, content_type="application/json", ) responses.add( method=responses.POST, url="https://testserviceurl.com/testendpoint/v3/conversations/some_conversation_id/activities", body='{"ok": true}', status=200, content_type="application/json", ) def setUp(self) -> None: super().setUp() self._setup_msteams_api() @responses.activate def test_send_note_activity_notification(self) -> None: notification = NoteActivityNotification( Activity( project=self.project, group=self.group, user_id=self.user.id, type=ActivityType.NOTE, data={"text": "text", "mentions": []}, ) ) with self.tasks(): notification.send() data = orjson.loads(responses.calls[-1].request.body) attachment = data["attachments"][0] assert "AdaptiveCard" == attachment["content"]["type"] assert 4 == len(attachment["content"]["body"]) assert ( f"New comment by {self.user.get_display_name()}" == attachment["content"]["body"][0]["text"] )
MSTeamsNotificationIntegrationTest
python
dagster-io__dagster
python_modules/dagster-test/dagster_test/toys/user_computed_data_versions/external_system.py
{ "start": 774, "end": 856 }
class ____(TypedDict): data_version: str is_memoized: bool
MaterializeResult
python
openai__gym
gym/envs/mujoco/mujoco_rendering.py
{ "start": 7095, "end": 8532 }
class ____(RenderContext): """Offscreen rendering class with opengl context.""" def __init__(self, model, data): # We must make GLContext before MjrContext width = model.vis.global_.offwidth height = model.vis.global_.offheight self._get_opengl_backend(width, height) self.opengl_context.make_current() super().__init__(model, data, offscreen=True) def _get_opengl_backend(self, width, height): backend = os.environ.get("MUJOCO_GL") if backend is not None: try: self.opengl_context = _ALL_RENDERERS[backend](width, height) except KeyError: raise RuntimeError( "Environment variable {} must be one of {!r}: got {!r}.".format( "MUJOCO_GL", _ALL_RENDERERS.keys(), backend ) ) else: for name, _ in _ALL_RENDERERS.items(): try: self.opengl_context = _ALL_RENDERERS[name](width, height) backend = name break except: # noqa:E722 pass if backend is None: raise RuntimeError( "No OpenGL backend could be imported. Attempting to create a " "rendering context will result in a RuntimeError." )
RenderContextOffscreen
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/config_types.py
{ "start": 4981, "end": 6617 }
class ____(graphene.ObjectType): key_type = graphene.Field(graphene.NonNull(GrapheneConfigType)) value_type = graphene.Field(graphene.NonNull(GrapheneConfigType)) key_label_name = graphene.Field(graphene.String) class Meta: interfaces = (GrapheneConfigType,) name = "MapConfigType" def __init__( self, get_config_type: Callable[[str], ConfigTypeSnap], config_type_snap: ConfigTypeSnap, ): self._config_type_snap = check.inst_param( config_type_snap, "config_type_snap", ConfigTypeSnap ) self._get_config_type = get_config_type super().__init__(**_ctor_kwargs_for_snap(config_type_snap)) def resolve_recursive_config_types( self, graphene_info: ResolveInfo ) -> list[GrapheneConfigTypeUnion]: return [ to_config_type(self._get_config_type, config_type_key) for config_type_key in _recursive_config_type_keys( self._get_config_type, self._config_type_snap ) ] def resolve_key_type(self, graphene_info: ResolveInfo) -> GrapheneConfigTypeUnion: return to_config_type( self._get_config_type, self._config_type_snap.key_type_key, ) def resolve_value_type(self, graphene_info: ResolveInfo) -> GrapheneConfigTypeUnion: return to_config_type( self._get_config_type, self._config_type_snap.inner_type_key, ) def resolve_key_label_name(self, _graphene_info: ResolveInfo) -> Optional[str]: return self._config_type_snap.given_name
GrapheneMapConfigType
python
scrapy__scrapy
tests/test_crawler.py
{ "start": 38863, "end": 39928 }
class ____(TestCrawlerRunnerSubprocessBase): @property def script_dir(self) -> Path: return self.get_script_dir("CrawlerRunner") def test_explicit_default_reactor(self): log = self.run_script("explicit_default_reactor.py") assert "Spider closed (finished)" in log assert ( "Using reactor: twisted.internet.asyncioreactor.AsyncioSelectorReactor" not in log ) def test_response_ip_address(self): log = self.run_script("ip_address.py") assert "INFO: Spider closed (finished)" in log assert "INFO: Host: not.a.real.domain" in log assert "INFO: Type: <class 'ipaddress.IPv4Address'>" in log assert "INFO: IP address: 127.0.0.1" in log def test_change_default_reactor(self): log = self.run_script("change_reactor.py") assert ( "DEBUG: Using reactor: twisted.internet.asyncioreactor.AsyncioSelectorReactor" in log ) assert "DEBUG: Using asyncio event loop" in log
TestCrawlerRunnerSubprocess
python
spyder-ide__spyder
spyder/plugins/history/confpage.py
{ "start": 416, "end": 1489 }
class ____(PluginConfigPage): """Configuration page for History plugin.""" def get_icon(self): """Get icon to use in Configurations dialog.""" return ima.icon('history') def setup_page(self): """Setup config page widgets and options.""" sourcecode_group = QGroupBox(_("Display")) wrap_mode_box = self.create_checkbox(_("Wrap lines"), 'wrap') linenumbers_mode_box = self.create_checkbox(_("Show line numbers"), 'line_numbers') go_to_eof_box = self.create_checkbox( _("Scroll automatically to last entry"), 'go_to_eof') sourcecode_layout = QVBoxLayout() sourcecode_layout.addWidget(wrap_mode_box) sourcecode_layout.addWidget(linenumbers_mode_box) sourcecode_layout.addWidget(go_to_eof_box) sourcecode_group.setLayout(sourcecode_layout) vlayout = QVBoxLayout() vlayout.addWidget(sourcecode_group) vlayout.addStretch(1) self.setLayout(vlayout)
HistoryConfigPage
python
django__django
tests/template_tests/syntax_tests/test_basic.py
{ "start": 501, "end": 14429 }
class ____(SimpleTestCase): @setup(basic_templates) def test_basic_syntax01(self): """ Plain text should go through the template parser untouched. """ output = self.engine.render_to_string("basic-syntax01") self.assertEqual(output, "something cool") @setup(basic_templates) def test_basic_syntax02(self): """ Variables should be replaced with their value in the current context """ output = self.engine.render_to_string("basic-syntax02", {"headline": "Success"}) self.assertEqual(output, "Success") @setup(basic_templates) def test_basic_syntax03(self): """ More than one replacement variable is allowed in a template """ output = self.engine.render_to_string( "basic-syntax03", {"first": 1, "second": 2} ) self.assertEqual(output, "1 --- 2") @setup({"basic-syntax04": "as{{ missing }}df"}) def test_basic_syntax04(self): """ Fail silently when a variable is not found in the current context """ output = self.engine.render_to_string("basic-syntax04") if self.engine.string_if_invalid: self.assertEqual(output, "asINVALIDdf") else: self.assertEqual(output, "asdf") @setup({"basic-syntax06": "{{ multi word variable }}"}) def test_basic_syntax06(self): """ A variable may not contain more than one word """ with self.assertRaises(TemplateSyntaxError): self.engine.get_template("basic-syntax06") @setup({"basic-syntax07": "{{ }}"}) def test_basic_syntax07(self): """ Raise TemplateSyntaxError for empty variable tags. """ with self.assertRaisesMessage( TemplateSyntaxError, "Empty variable tag on line 1" ): self.engine.get_template("basic-syntax07") @setup({"basic-syntax08": "{{ }}"}) def test_basic_syntax08(self): """ Raise TemplateSyntaxError for empty variable tags. """ with self.assertRaisesMessage( TemplateSyntaxError, "Empty variable tag on line 1" ): self.engine.get_template("basic-syntax08") @setup({"basic-syntax09": "{{ var.method }}"}) def test_basic_syntax09(self): """ Attribute syntax allows a template to call an object's attribute """ output = self.engine.render_to_string("basic-syntax09", {"var": SomeClass()}) self.assertEqual(output, "SomeClass.method") @setup({"basic-syntax10": "{{ var.otherclass.method }}"}) def test_basic_syntax10(self): """ Multiple levels of attribute access are allowed. """ output = self.engine.render_to_string("basic-syntax10", {"var": SomeClass()}) self.assertEqual(output, "OtherClass.method") @setup({"basic-syntax11": "{{ var.blech }}"}) def test_basic_syntax11(self): """ Fail silently when a variable's attribute isn't found. """ output = self.engine.render_to_string("basic-syntax11", {"var": SomeClass()}) if self.engine.string_if_invalid: self.assertEqual(output, "INVALID") else: self.assertEqual(output, "") @setup({"basic-syntax12": "{{ var.__dict__ }}"}) def test_basic_syntax12(self): """ Raise TemplateSyntaxError when trying to access a variable beginning with an underscore. """ with self.assertRaises(TemplateSyntaxError): self.engine.get_template("basic-syntax12") # Raise TemplateSyntaxError when trying to access a variable # containing an illegal character. @setup({"basic-syntax13": "{{ va>r }}"}) def test_basic_syntax13(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template("basic-syntax13") @setup({"basic-syntax14": "{{ (var.r) }}"}) def test_basic_syntax14(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template("basic-syntax14") @setup({"basic-syntax15": "{{ sp%am }}"}) def test_basic_syntax15(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template("basic-syntax15") @setup({"basic-syntax16": "{{ eggs! }}"}) def test_basic_syntax16(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template("basic-syntax16") @setup({"basic-syntax17": "{{ moo? }}"}) def test_basic_syntax17(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template("basic-syntax17") @setup({"basic-syntax18": "{{ foo.bar }}"}) def test_basic_syntax18(self): """ Attribute syntax allows a template to call a dictionary key's value. """ output = self.engine.render_to_string("basic-syntax18", {"foo": {"bar": "baz"}}) self.assertEqual(output, "baz") @setup({"basic-syntax19": "{{ foo.spam }}"}) def test_basic_syntax19(self): """ Fail silently when a variable's dictionary key isn't found. """ output = self.engine.render_to_string("basic-syntax19", {"foo": {"bar": "baz"}}) if self.engine.string_if_invalid: self.assertEqual(output, "INVALID") else: self.assertEqual(output, "") @setup({"basic-syntax20": "{{ var.method2 }}"}) def test_basic_syntax20(self): """ Fail silently when accessing a non-simple method """ output = self.engine.render_to_string("basic-syntax20", {"var": SomeClass()}) if self.engine.string_if_invalid: self.assertEqual(output, "INVALID") else: self.assertEqual(output, "") @setup({"basic-syntax20b": "{{ var.method5 }}"}) def test_basic_syntax20b(self): """ Don't silence a TypeError if it was raised inside a callable. """ template = self.engine.get_template("basic-syntax20b") with self.assertRaises(TypeError): template.render(Context({"var": SomeClass()})) # Don't get confused when parsing something that is almost, but not # quite, a template tag. @setup({"basic-syntax21": "a {{ moo %} b"}) def test_basic_syntax21(self): output = self.engine.render_to_string("basic-syntax21") self.assertEqual(output, "a {{ moo %} b") @setup({"basic-syntax22": "{{ moo #}"}) def test_basic_syntax22(self): output = self.engine.render_to_string("basic-syntax22") self.assertEqual(output, "{{ moo #}") @setup({"basic-syntax23": "{{ moo #} {{ cow }}"}) def test_basic_syntax23(self): """ Treat "moo #} {{ cow" as the variable. Not ideal, but costly to work around, so this triggers an error. """ with self.assertRaises(TemplateSyntaxError): self.engine.get_template("basic-syntax23") @setup({"basic-syntax24": "{{ moo\n }}"}) def test_basic_syntax24(self): """ Embedded newlines make it not-a-tag. """ output = self.engine.render_to_string("basic-syntax24") self.assertEqual(output, "{{ moo\n }}") # Literal strings are permitted inside variables, mostly for i18n # purposes. @setup({"basic-syntax25": '{{ "fred" }}'}) def test_basic_syntax25(self): output = self.engine.render_to_string("basic-syntax25") self.assertEqual(output, "fred") @setup({"basic-syntax26": r'{{ "\"fred\"" }}'}) def test_basic_syntax26(self): output = self.engine.render_to_string("basic-syntax26") self.assertEqual(output, '"fred"') @setup({"basic-syntax27": r'{{ _("\"fred\"") }}'}) def test_basic_syntax27(self): output = self.engine.render_to_string("basic-syntax27") self.assertEqual(output, '"fred"') # #12554 -- Make sure a silent_variable_failure Exception is # suppressed on dictionary and attribute lookup. @setup({"basic-syntax28": "{{ a.b }}"}) def test_basic_syntax28(self): output = self.engine.render_to_string( "basic-syntax28", {"a": SilentGetItemClass()} ) if self.engine.string_if_invalid: self.assertEqual(output, "INVALID") else: self.assertEqual(output, "") @setup({"basic-syntax29": "{{ a.b }}"}) def test_basic_syntax29(self): output = self.engine.render_to_string( "basic-syntax29", {"a": SilentAttrClass()} ) if self.engine.string_if_invalid: self.assertEqual(output, "INVALID") else: self.assertEqual(output, "") # Something that starts like a number but has an extra lookup works # as a lookup. @setup({"basic-syntax30": "{{ 1.2.3 }}"}) def test_basic_syntax30(self): output = self.engine.render_to_string( "basic-syntax30", {"1": {"2": {"3": "d"}}} ) self.assertEqual(output, "d") @setup({"basic-syntax31": "{{ 1.2.3 }}"}) def test_basic_syntax31(self): output = self.engine.render_to_string( "basic-syntax31", {"1": {"2": ("a", "b", "c", "d")}}, ) self.assertEqual(output, "d") @setup({"basic-syntax32": "{{ 1.2.3 }}"}) def test_basic_syntax32(self): output = self.engine.render_to_string( "basic-syntax32", {"1": (("x", "x", "x", "x"), ("y", "y", "y", "y"), ("a", "b", "c", "d"))}, ) self.assertEqual(output, "d") @setup({"basic-syntax33": "{{ 1.2.3 }}"}) def test_basic_syntax33(self): output = self.engine.render_to_string( "basic-syntax33", {"1": ("xxxx", "yyyy", "abcd")}, ) self.assertEqual(output, "d") @setup({"basic-syntax34": "{{ 1.2.3 }}"}) def test_basic_syntax34(self): output = self.engine.render_to_string( "basic-syntax34", {"1": ({"x": "x"}, {"y": "y"}, {"z": "z", "3": "d"})} ) self.assertEqual(output, "d") # Numbers are numbers even if their digits are in the context. @setup({"basic-syntax35": "{{ 1 }}"}) def test_basic_syntax35(self): output = self.engine.render_to_string("basic-syntax35", {"1": "abc"}) self.assertEqual(output, "1") @setup({"basic-syntax36": "{{ 1.2 }}"}) def test_basic_syntax36(self): output = self.engine.render_to_string("basic-syntax36", {"1": "abc"}) self.assertEqual(output, "1.2") @setup({"basic-syntax37": "{{ callable }}"}) def test_basic_syntax37(self): """ Call methods in the top level of the context. """ output = self.engine.render_to_string( "basic-syntax37", {"callable": lambda: "foo bar"} ) self.assertEqual(output, "foo bar") @setup({"basic-syntax38": "{{ var.callable }}"}) def test_basic_syntax38(self): """ Call methods returned from dictionary lookups. """ output = self.engine.render_to_string( "basic-syntax38", {"var": {"callable": lambda: "foo bar"}} ) self.assertEqual(output, "foo bar") @setup({"template": "{% block content %}"}) def test_unclosed_block(self): msg = "Unclosed tag on line 1: 'block'. Looking for one of: endblock." with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("template") @setup({"template": "{% if a %}"}) def test_unclosed_block2(self): msg = "Unclosed tag on line 1: 'if'. Looking for one of: elif, else, endif." with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.render_to_string("template") @setup({"tpl-str": "%s", "tpl-percent": "%%", "tpl-weird-percent": "% %s"}) def test_ignores_strings_that_look_like_format_interpolation(self): output = self.engine.render_to_string("tpl-str") self.assertEqual(output, "%s") output = self.engine.render_to_string("tpl-percent") self.assertEqual(output, "%%") output = self.engine.render_to_string("tpl-weird-percent") self.assertEqual(output, "% %s") @setup( {"template": "{{ class_var.class_property }} | {{ class_var.class_method }}"} ) def test_subscriptable_class(self): class MyClass(list): # As of Python 3.9 list defines __class_getitem__ which makes it # subscriptable. class_property = "Example property" do_not_call_in_templates = True @classmethod def class_method(cls): return "Example method" for case in (MyClass, lambda: MyClass): with self.subTest(case=case): output = self.engine.render_to_string("template", {"class_var": case}) self.assertEqual(output, "Example property | Example method") @setup({"template": "{{ meals.lunch }}"}) def test_access_class_property_if_getitem_is_defined_in_metaclass(self): """ If the metaclass defines __getitem__, the template system should use it to resolve the dot notation. """ class MealMeta(type): def __getitem__(cls, name): return getattr(cls, name) + " is yummy." class Meals(metaclass=MealMeta): lunch = "soup" do_not_call_in_templates = True # Make class type subscriptable. def __class_getitem__(cls, key): from types import GenericAlias return GenericAlias(cls, key) self.assertEqual(Meals.lunch, "soup") self.assertEqual(Meals["lunch"], "soup is yummy.") output = self.engine.render_to_string("template", {"meals": Meals}) self.assertEqual(output, "soup is yummy.")
BasicSyntaxTests
python
django__django
tests/admin_views/test_autocomplete_view.py
{ "start": 1106, "end": 2061 }
class ____(admin.ModelAdmin): inlines = [AuthorshipInline] site = admin.AdminSite(name="autocomplete_admin") site.register(Question, QuestionAdmin) site.register(Answer, AnswerAdmin) site.register(Author, AuthorAdmin) site.register(Book, BookAdmin) site.register(Employee, search_fields=["name"]) site.register(WorkHour, autocomplete_fields=["employee"]) site.register(Manager, search_fields=["name"]) site.register(Bonus, autocomplete_fields=["recipient"]) site.register(PKChild, search_fields=["name"]) site.register(Toy, autocomplete_fields=["child"]) @contextmanager def model_admin(model, model_admin, admin_site=site): try: org_admin = admin_site.get_model_admin(model) except NotRegistered: org_admin = None else: admin_site.unregister(model) admin_site.register(model, model_admin) try: yield finally: if org_admin: admin_site._registry[model] = org_admin
BookAdmin
python
getsentry__sentry
tests/sentry/notifications/notifications/test_organization_request.py
{ "start": 472, "end": 717 }
class ____(RoleBasedRecipientStrategy): def determine_member_recipients(self) -> QuerySet[OrganizationMember, OrganizationMember]: return OrganizationMember.objects.filter(organization=self.organization)
DummyRoleBasedRecipientStrategy
python
fluentpython__example-code
06-dp-1class-func/strategy_best2.py
{ "start": 1565, "end": 3172 }
class ____: # the Context def __init__(self, customer, cart, promotion=None): self.customer = customer self.cart = list(cart) self.promotion = promotion def total(self): if not hasattr(self, '__total'): self.__total = sum(item.total() for item in self.cart) return self.__total def due(self): if self.promotion is None: discount = 0 else: discount = self.promotion(self) return self.total() - discount def __repr__(self): fmt = '<Order total: {:.2f} due: {:.2f}>' return fmt.format(self.total(), self.due()) def fidelity_promo(order): """5% discount for customers with 1000 or more fidelity points""" return order.total() * .05 if order.customer.fidelity >= 1000 else 0 def bulk_item_promo(order): """10% discount for each LineItem with 20 or more units""" discount = 0 for item in order.cart: if item.quantity >= 20: discount += item.total() * .1 return discount def large_order_promo(order): """7% discount for orders with 10 or more distinct items""" distinct_items = {item.product for item in order.cart} if len(distinct_items) >= 10: return order.total() * .07 return 0 # BEGIN STRATEGY_BEST2 promos = [globals()[name] for name in globals() # <1> if name.endswith('_promo') # <2> and name != 'best_promo'] # <3> def best_promo(order): """Select best discount available """ return max(promo(order) for promo in promos) # <4> # END STRATEGY_BEST2
Order
python
bokeh__bokeh
src/bokeh/colors/groups.py
{ "start": 1987, "end": 2823 }
class ____(ColorGroup): ''' CSS "Blue" Color Group as defined by https://www.w3schools.com/colors/colors_groups.asp .. bokeh-color:: lightsteelblue .. bokeh-color:: powderblue .. bokeh-color:: lightblue .. bokeh-color:: skyblue .. bokeh-color:: lightskyblue .. bokeh-color:: deepskyblue .. bokeh-color:: dodgerblue .. bokeh-color:: cornflowerblue .. bokeh-color:: steelblue .. bokeh-color:: royalblue .. bokeh-color:: blue .. bokeh-color:: mediumblue .. bokeh-color:: darkblue .. bokeh-color:: navy .. bokeh-color:: midnightblue ''' _colors = ('LightSteelBlue', 'PowderBlue', 'LightBlue', 'SkyBlue', 'LightSkyBlue', 'DeepSkyBlue', 'DodgerBlue', 'CornflowerBlue', 'SteelBlue', 'RoyalBlue', 'Blue', 'MediumBlue', 'DarkBlue', 'Navy', 'MidnightBlue')
blue
python
sqlalchemy__sqlalchemy
test/base/test_typing_utils.py
{ "start": 7592, "end": 8862 }
class ____(fixtures.TestBase): def test_unions_are_the_same(self): # the point of this test is to reduce the cases to test since # some symbols are the same in typing and typing_extensions. # If a test starts failing then additional cases should be added, # similar to what it's done for TypeAliasType # no need to test typing_extensions.Union, typing_extensions.Optional is_(typing.Union, typing_extensions.Union) is_(typing.Optional, typing_extensions.Optional) @requires.python312 def test_make_type_alias_type(self): # verify that TypeAliasType('foo', int) it the same as 'type foo = int' x_type = exec_code("type x = int", "x") x = typing.TypeAliasType("x", int) eq_(type(x_type), type(x)) eq_(x_type.__name__, x.__name__) eq_(x_type.__value__, x.__value__) def test_make_fw_ref(self): compare_type_by_string(make_fw_ref("str"), typing.ForwardRef("str")) compare_type_by_string( make_fw_ref("str|int"), typing.ForwardRef("str|int") ) compare_type_by_string( make_fw_ref("Optional[Union[str, int]]"), typing.ForwardRef("Optional[Union[str, int]]"), )
TestTestingThings
python
django__django
django/db/models/functions/math.py
{ "start": 2950, "end": 3041 }
class ____(NumericOutputFieldMixin, Transform): function = "LN" lookup_name = "ln"
Ln
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1041755, "end": 1042305 }
class ____(sgqlc.types.Type): """Autogenerated return type of UpdatePullRequestReviewComment""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "pull_request_review_comment") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation.""" pull_request_review_comment = sgqlc.types.Field("PullRequestReviewComment", graphql_name="pullRequestReviewComment") """The updated comment."""
UpdatePullRequestReviewCommentPayload
python
optuna__optuna
optuna/_gp/acqf.py
{ "start": 4705, "end": 5553 }
class ____(BaseAcquisitionFunc): def __init__( self, gpr: GPRegressor, search_space: SearchSpace, threshold: float, stabilizing_noise: float = 1e-12, ) -> None: self._gpr = gpr self._stabilizing_noise = stabilizing_noise self._threshold = threshold super().__init__(gpr.length_scales, search_space) def eval_acqf(self, x: torch.Tensor) -> torch.Tensor: mean, var = self._gpr.posterior(x) # If there are no feasible trials, max_Y is set to -np.inf. # If max_Y is set to -np.inf, we set logEI to zero to ignore it. return ( logei(mean=mean, var=var + self._stabilizing_noise, f0=self._threshold) if not np.isneginf(self._threshold) else torch.zeros(x.shape[:-1], dtype=torch.float64) )
LogEI
python
pytorch__pytorch
torch/testing/_internal/distributed/rpc/rpc_test.py
{ "start": 16078, "end": 16299 }
class ____(torch.nn.Module): def __init__(self, sparse): super().__init__() self.eb = torch.nn.EmbeddingBag(10, 10, sparse=sparse) def forward(self, x): return self.eb(x)
MyEmbeddingBagModel
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/models/reports.py
{ "start": 947, "end": 10780 }
class ____: """A dataclass to build reports to share pipelines executions results with the user.""" pipeline_context: PipelineContext steps_results: List[StepResult] created_at: datetime = field(default_factory=datetime.utcnow) name: str = "REPORT" filename: str = "output" @property def report_output_prefix(self) -> str: return self.pipeline_context.report_output_prefix @property def report_dir_path(self) -> Path: return Path(f"{LOCAL_REPORTS_PATH_ROOT}/{self.report_output_prefix}") @property def json_report_file_name(self) -> str: return self.filename + ".json" @property def json_report_remote_storage_key(self) -> str: return f"{self.report_output_prefix}/{self.json_report_file_name}" @property def failed_steps(self) -> List[StepResult]: return [step_result for step_result in self.steps_results if step_result.status is StepStatus.FAILURE] @property def considered_failed_steps(self) -> List[StepResult]: return [step_result for step_result in self.failed_steps if step_result.consider_in_overall_status] @property def successful_steps(self) -> List[StepResult]: return [step_result for step_result in self.steps_results if step_result.status is StepStatus.SUCCESS] @property def skipped_steps(self) -> List[StepResult]: return [step_result for step_result in self.steps_results if step_result.status is StepStatus.SKIPPED] @property def success(self) -> bool: return len(self.considered_failed_steps) == 0 and (len(self.skipped_steps) > 0 or len(self.successful_steps) > 0) @property def run_duration(self) -> timedelta: assert self.pipeline_context.started_at is not None, "The pipeline started_at timestamp must be set to save reports." assert self.pipeline_context.stopped_at is not None, "The pipeline stopped_at timestamp must be set to save reports." return self.pipeline_context.stopped_at - self.pipeline_context.started_at @property def lead_duration(self) -> timedelta: assert self.pipeline_context.started_at is not None, "The pipeline started_at timestamp must be set to save reports." assert self.pipeline_context.stopped_at is not None, "The pipeline stopped_at timestamp must be set to save reports." return self.pipeline_context.stopped_at - self.pipeline_context.created_at async def save(self) -> None: self.report_dir_path.mkdir(parents=True, exist_ok=True) await self.save_json_report() await self.save_step_result_artifacts() async def save_json_report(self) -> None: """Save the report as JSON, upload it to GCS if the pipeline is running in CI""" json_report_path = self.report_dir_path / self.json_report_file_name report_dir = self.pipeline_context.dagger_client.host().directory(str(self.report_dir_path)) local_json_report_file = report_dir.with_new_file(self.json_report_file_name, self.to_json()).file(self.json_report_file_name) json_report_artifact = Artifact(name="JSON Report", content_type="application/json", content=local_json_report_file) await json_report_artifact.save_to_local_path(json_report_path) absolute_path = json_report_path.absolute() self.pipeline_context.logger.info(f"Report saved locally at {absolute_path}") if self.pipeline_context.remote_storage_enabled: gcs_url = await json_report_artifact.upload_to_gcs( dagger_client=self.pipeline_context.dagger_client, bucket=self.pipeline_context.ci_report_bucket, # type: ignore key=self.json_report_remote_storage_key, gcs_credentials=self.pipeline_context.ci_gcp_credentials, # type: ignore ) self.pipeline_context.logger.info(f"JSON Report uploaded to {gcs_url}") else: self.pipeline_context.logger.info("JSON Report not uploaded to GCS because remote storage is disabled.") async def save_step_result_artifacts(self) -> None: local_artifacts_dir = self.report_dir_path / "artifacts" local_artifacts_dir.mkdir(parents=True, exist_ok=True) # TODO: concurrent save and upload for step_result in self.steps_results: for artifact in step_result.artifacts: step_artifacts_dir = local_artifacts_dir / slugify(step_result.step.title) step_artifacts_dir.mkdir(parents=True, exist_ok=True) await artifact.save_to_local_path(step_artifacts_dir / artifact.name) if self.pipeline_context.remote_storage_enabled: upload_time = int(time.time()) gcs_url = await artifact.upload_to_gcs( dagger_client=self.pipeline_context.dagger_client, bucket=self.pipeline_context.ci_report_bucket, # type: ignore key=f"{self.report_output_prefix}/artifacts/{slugify(step_result.step.title)}/{upload_time}_{artifact.name}", gcs_credentials=self.pipeline_context.ci_gcp_credentials, # type: ignore ) self.pipeline_context.logger.info(f"Artifact {artifact.name} for {step_result.step.title} uploaded to {gcs_url}") else: self.pipeline_context.logger.info( f"Artifact {artifact.name} for {step_result.step.title} not uploaded to GCS because remote storage is disabled." ) def to_json(self) -> str: """Create a JSON representation of the report. Returns: str: The JSON representation of the report. """ assert self.pipeline_context.pipeline_start_timestamp is not None, "The pipeline start timestamp must be set to save reports." assert self.pipeline_context.started_at is not None, "The pipeline started_at timestamp must be set to save reports." assert self.pipeline_context.stopped_at is not None, "The pipeline stopped_at timestamp must be set to save reports." return json.dumps( { "pipeline_name": self.pipeline_context.pipeline_name, "run_timestamp": self.pipeline_context.started_at.isoformat(), "run_duration": self.run_duration.total_seconds(), "success": self.success, "failed_steps": [s.step.__class__.__name__ for s in self.failed_steps], "successful_steps": [s.step.__class__.__name__ for s in self.successful_steps], "skipped_steps": [s.step.__class__.__name__ for s in self.skipped_steps], "gha_workflow_run_url": self.pipeline_context.gha_workflow_run_url, "pipeline_start_timestamp": self.pipeline_context.pipeline_start_timestamp, "pipeline_end_timestamp": round(self.pipeline_context.stopped_at.timestamp()), "pipeline_duration": round(self.pipeline_context.stopped_at.timestamp()) - self.pipeline_context.pipeline_start_timestamp, "git_branch": self.pipeline_context.git_branch, "git_revision": self.pipeline_context.git_revision, "ci_context": self.pipeline_context.ci_context, "pull_request_url": self.pipeline_context.pull_request.html_url if self.pipeline_context.pull_request else None, "dagger_cloud_url": self.pipeline_context.dagger_cloud_url, } ) def print(self) -> None: """Print the test report to the console in a nice way.""" pipeline_name = self.pipeline_context.pipeline_name main_panel_title = Text(f"{pipeline_name.upper()} - {self.name}") main_panel_title.stylize(Style(color="blue", bold=True)) duration_subtitle = Text(f"⏲️ Total pipeline duration for {pipeline_name}: {format_duration(self.run_duration)}") step_results_table = Table(title="Steps results") step_results_table.add_column("Step") step_results_table.add_column("Result") step_results_table.add_column("Finished after") for step_result in self.steps_results: step = Text(step_result.step.title) step.stylize(step_result.status.get_rich_style()) result = Text(step_result.status.value) result.stylize(step_result.status.get_rich_style()) if step_result.status is StepStatus.SKIPPED: step_results_table.add_row(step, result, "N/A") else: assert step_result.step.started_at is not None, "The step started_at timestamp must be set to print reports." run_time = format_duration((step_result.created_at - step_result.step.started_at)) step_results_table.add_row(step, result, run_time) to_render: List[RenderableType] = [step_results_table] if self.failed_steps: sub_panels = [] for failed_step in self.failed_steps: errors = Text(failed_step.stderr) if failed_step.stderr else Text("") panel_title = Text(f"{pipeline_name} {failed_step.step.title.lower()} failures") panel_title.stylize(Style(color="red", bold=True)) sub_panel = Panel(errors, title=panel_title) sub_panels.append(sub_panel) failures_group = Group(*sub_panels) to_render.append(failures_group) if self.pipeline_context.dagger_cloud_url: self.pipeline_context.logger.info(f"🔗 View runs for commit in Dagger Cloud: {self.pipeline_context.dagger_cloud_url}") main_panel = Panel(Group(*to_render), title=main_panel_title, subtitle=duration_subtitle) console.print(main_panel)
Report
python
pytorch__pytorch
test/distributed/_tools/test_sac_estimator.py
{ "start": 442, "end": 3142 }
class ____(TestCase): def _sac_estimation( self, estimate_mode: str, model: torch.nn.Module, inp: torch.Tensor, ): sace = SACEstimator() with sace(estimate_mode_type=estimate_mode): loss = model(inp).sum() loss.backward() sace.pwlf_sac_tradeoff_curve(n_segments=2, save_tradeoff_graphs=False) @skipIfTorchDynamo("https://github.com/pytorch/pytorch/issues/115653") @unittest.skipIf(not TEST_CUDA, "CUDA not available") def test_transformer_sac_estimation(self): """Runs a basic GPT-2 model""" dev = torch.cuda.current_device() vocab_size = 8192 bsz, seq_len = 8, 1024 model_args = ModelArgs( n_layers=4, n_heads=12, vocab_size=vocab_size, max_seq_len=seq_len, dim=768, dropout_p=0.1, ) with FakeTensorMode(): with torch.device(dev): model = Transformer(model_args) inp = torch.randint( 0, model_args.vocab_size, (bsz, model_args.max_seq_len), device=dev ) self._sac_estimation("operator-level-benchmark", model, inp) self._sac_estimation("operator-level-cost-model", model, inp) @skipIfTorchDynamo("https://github.com/pytorch/pytorch/issues/115653") @unittest.skipIf(not TEST_CUDA, "CUDA not available") def test_simple_model_sac_estimation(self): """This test checks the correctness of view_ops, random_ops and inplace_ops""" class Foo(torch.nn.Module): def __init__(self): super().__init__() self.fc1 = torch.nn.Linear(5, 10) self.relu1 = torch.nn.ReLU(inplace=True) def forward(self, x): x = self.fc1(x) x = self.relu1(x) x = torch.cos_(x) x = torch.sin_(x) return x dev = torch.cuda.current_device() with FakeTensorMode(): with torch.device(dev): model = Foo() x = torch.rand((10, 5), device=dev) sac_estimator = SACEstimator() with sac_estimator(estimate_mode_type="operator-level-benchmark"): loss = model(x).sum() loss.backward() self.assertEqual(sac_estimator.sac_mod_stats["Foo"].view_like_ops, [0]) self.assertEqual(sac_estimator.sac_mod_stats["Foo"].rand_ops, []) self.assertEqual( sac_estimator.sac_mod_stats["Foo"].inplace_ops, [(2, 1), (3, 1), (4, 1)] ) if __name__ == "__main__": run_tests()
TestSACEstimator
python
langchain-ai__langchain
libs/langchain/langchain_classic/retrievers/re_phraser.py
{ "start": 927, "end": 2807 }
class ____(BaseRetriever): """Given a query, use an LLM to re-phrase it. Then, retrieve docs for the re-phrased query. """ retriever: BaseRetriever llm_chain: Runnable @classmethod def from_llm( cls, retriever: BaseRetriever, llm: BaseLLM, prompt: BasePromptTemplate = DEFAULT_QUERY_PROMPT, ) -> "RePhraseQueryRetriever": """Initialize from llm using default template. The prompt used here expects a single input: `question` Args: retriever: retriever to query documents from llm: llm for query generation using DEFAULT_QUERY_PROMPT prompt: prompt template for query generation Returns: RePhraseQueryRetriever """ llm_chain = prompt | llm | StrOutputParser() return cls( retriever=retriever, llm_chain=llm_chain, ) def _get_relevant_documents( self, query: str, *, run_manager: CallbackManagerForRetrieverRun, ) -> list[Document]: """Get relevant documents given a user question. Args: query: user question run_manager: callback handler to use Returns: Relevant documents for re-phrased question """ re_phrased_question = self.llm_chain.invoke( query, {"callbacks": run_manager.get_child()}, ) logger.info("Re-phrased question: %s", re_phrased_question) return self.retriever.invoke( re_phrased_question, config={"callbacks": run_manager.get_child()}, ) async def _aget_relevant_documents( self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun, ) -> list[Document]: raise NotImplementedError
RePhraseQueryRetriever
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_print_area05.py
{ "start": 315, "end": 1194 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("print_area05.xlsx") self.ignore_files = [ "xl/printerSettings/printerSettings1.bin", "xl/worksheets/_rels/sheet1.xml.rels", ] self.ignore_elements = { "[Content_Types].xml": ['<Default Extension="bin"'], "xl/worksheets/sheet1.xml": ["<pageMargins", "<pageSetup"], } def test_create_file(self): """Test the creation of a simple XlsxWriter file with a print area.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.print_area("A1:A1048576") worksheet.write("A1", "Foo") workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
google__jax
docs/the-training-cookbook.py
{ "start": 7264, "end": 8979 }
class ____: prev_metrics = None def __call__(self, cur_metrics: dict): self.prev_metrics, log_metrics = cur_metrics, self.prev_metrics if log_metrics is None: return print(*it.starmap("{}: {}".format, log_metrics.items()), sep="\t") # tag: record-writer # tag: get-dataset def get_dataset(config: Config, single_batch=ode) -> Iterator[dict[str, np.ndarray]]: while True: observed_array = np.frombuffer(single_batch.encode("ascii"), dtype=np.uint8) target_array = np.roll(observed_array, -1) time.sleep(0.5) yield { # repeat the sequence across the batch size to simulate multiple data points "observed_ids": np.tile(observed_array[: config.seq_length], (config.host_batch_size, 1)), "target_ids": np.tile(target_array[: config.seq_length], (config.host_batch_size, 1)), } # tag: get-dataset # tag: get-dataset-on-device def get_dataset_on_device(config: Config) -> Iterator[dict[str, jax.Array]]: datset = get_dataset(config) sharding = jax.P(config.mesh_axis_names) return map(ft.partial(jax.make_array_from_process_local_data, sharding), datset) # tag: get-dataset-on-device # tag: train-loop def train_loop(config: Config): record_writer = RecordWriter() train_state = init_train_state(config) train_state = jax.tree.map(jax.ref.new_ref, train_state) batch = iter(get_dataset_on_device(config)) for step in range(config.num_train_steps): metrics = train_step(config, train_state, next(batch)) record_writer({"step": step} | metrics) # tag: train-loop if __name__ == "__main__": jax.config.update("jax_platform_name", "cpu") jax.config.update("jax_num_cpu_devices", 8) train_loop(config=Config())
RecordWriter
python
pytorch__pytorch
torch/_inductor/ir.py
{ "start": 69805, "end": 71601 }
class ____(Reduction): output_index: int def __init__( self, device: torch.device, dst_dtype: torch.dtype, inner_fns: Union[INNER_FN_TY, Sequence[INNER_FN_TY]], ranges: Sequence[Integer], reduction_ranges: Sequence[Integer], reduction_type: ReductionType, src_dtype: torch.dtype, reduction_hint: ReductionHint, output_index: int, ): if callable(inner_fns): inner_fns = (inner_fns,) loader: Callable[[Sequence[Expr], Sequence[Expr]], Any] if len(inner_fns) == 1: loader = inner_fns[0] else: def loader( idx: Sequence[Expr], reduction_idx: Sequence[Expr] ) -> tuple[OpsValue, ...]: return tuple(fn(idx, reduction_idx) for fn in inner_fns) super().__init__( device=device, dtype=dst_dtype, inner_fn=loader, ranges=ranges, reduction_ranges=reduction_ranges, reduction_type=reduction_type, src_dtype=src_dtype, reduction_hint=reduction_hint, ) self.output_index = output_index def store_reduction( self, output_name: Optional[str], indexer: Callable[[Sequence[Expr]], Never], vars: Sequence[Expr], reduction_vars: Sequence[Symbol], ) -> Any: values = ops.reduction( self.dtype, self.src_dtype, self.reduction_type, self.inner_fn(vars, reduction_vars), ) assert isinstance(values, (tuple, list)), type(values) value = values[self.output_index] return ops.store_reduction(output_name or "unnamed", indexer(vars), value)
MultiOutputReduction
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1368185, "end": 1368668 }
class ____(sgqlc.types.Type, Node, UniformResourceLocatable): """Represents a Git commit part of a pull request.""" __schema__ = github_schema __field_names__ = ("commit", "pull_request") commit = sgqlc.types.Field(sgqlc.types.non_null(Commit), graphql_name="commit") """The Git commit object""" pull_request = sgqlc.types.Field(sgqlc.types.non_null(PullRequest), graphql_name="pullRequest") """The pull request this commit belongs to"""
PullRequestCommit
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/cast_op_test.py
{ "start": 7803, "end": 8368 }
class ____(test.TestCase): def testCast(self): indices = constant_op.constant([[0], [1], [2]], dtypes.int64) values = constant_op.constant(np.array([1, 2, 3], np.int64)) shape = constant_op.constant([3], dtypes.int64) st = sparse_tensor.SparseTensor(indices, values, shape) st_cast = math_ops.cast(st, dtypes.float32) self.assertAllEqual(st_cast.indices, [[0], [1], [2]]) self.assertAllEqual(st_cast.values, np.array([1, 2, 3], np.float32)) self.assertAllEqual(st_cast.dense_shape, [3])
SparseTensorCastTest
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/distributions/util_test.py
{ "start": 19681, "end": 21147 }
class ____(test.TestCase): @test_util.run_deprecated_v1 def testNonEmptyConstantTensor(self): x = array_ops.zeros((2, 3, 4)) rank = du.prefer_static_rank(x) self.assertIsInstance(rank, np.ndarray) self.assertEqual(3, rank) @test_util.run_deprecated_v1 def testEmptyConstantTensor(self): x = constant_op.constant([]) rank = du.prefer_static_rank(x) self.assertIsInstance(rank, np.ndarray) self.assertEqual(1, rank) @test_util.run_deprecated_v1 def testScalarTensor(self): x = constant_op.constant(1.) rank = du.prefer_static_rank(x) self.assertIsInstance(rank, np.ndarray) self.assertEqual(0, rank) @test_util.run_deprecated_v1 def testDynamicRankEndsUpBeingNonEmpty(self): x = array_ops.placeholder(np.float64, shape=None) rank = du.prefer_static_rank(x) with self.cached_session(): self.assertAllEqual(2, rank.eval(feed_dict={x: np.zeros((2, 3))})) @test_util.run_deprecated_v1 def testDynamicRankEndsUpBeingEmpty(self): x = array_ops.placeholder(np.int32, shape=None) rank = du.prefer_static_rank(x) with self.cached_session(): self.assertAllEqual(1, rank.eval(feed_dict={x: []})) @test_util.run_deprecated_v1 def testDynamicRankEndsUpBeingScalar(self): x = array_ops.placeholder(np.int32, shape=None) rank = du.prefer_static_rank(x) with self.cached_session(): self.assertAllEqual(0, rank.eval(feed_dict={x: 1}))
PreferStaticRankTest
python
hynek__structlog
tests/test_frames.py
{ "start": 4000, "end": 4821 }
class ____: def test_returns_str(self, exc_info): """ Always returns a native string. """ assert isinstance(_format_exception(exc_info), str) def test_formats(self, exc_info): """ The passed exc_info is formatted. """ assert _format_exception(exc_info).startswith( "Traceback (most recent call last):\n" ) def test_no_trailing_nl(self, exc_info, monkeypatch): """ Trailing newlines are snipped off but if the string does not contain one nothing is removed. """ from structlog._frames import traceback monkeypatch.setattr( traceback, "print_exception", lambda *a: a[-1].write("foo") ) assert "foo" == _format_exception(exc_info)
TestFormatException
python
cherrypy__cherrypy
cherrypy/lib/encoding.py
{ "start": 1327, "end": 2302 }
class ____: """UTF8 Stream Encoder.""" def __init__(self, iterator): """Initialize a UTF-8 stream encoder instance.""" self._iterator = iterator def __iter__(self): """Make a UTF-8-encoded stream iterator.""" return self def next(self): """UTF-8-encode the next chunk of the stream.""" return self.__next__() def __next__(self): """UTF-8-encode the next chunk of the stream.""" res = next(self._iterator) if isinstance(res, str): res = res.encode('utf-8') return res def close(self): """Close the underlying byte stream.""" if is_closable_iterator(self._iterator): self._iterator.close() def __getattr__(self, attr): """Return the underlying byte stream attribute value.""" if attr.startswith('__'): raise AttributeError(self, attr) return getattr(self._iterator, attr)
UTF8StreamEncoder
python
huggingface__transformers
tests/models/swinv2/test_modeling_swinv2.py
{ "start": 20373, "end": 20619 }
class ____(unittest.TestCase, BackboneTesterMixin): all_model_classes = (Swinv2Backbone,) if is_torch_available() else () config_class = Swinv2Config def setUp(self): self.model_tester = Swinv2ModelTester(self)
Swinv2BackboneTest
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/stats.py
{ "start": 7032, "end": 10310 }
class ____(StatsWriter): def __init__( self, base_dir: str, clear_past_data: bool = False, hidden_keys: Optional[List[str]] = None, ): """ A StatsWriter that writes to a Tensorboard summary. :param base_dir: The directory within which to place all the summaries. Tensorboard files will be written to a {base_dir}/{category} directory. :param clear_past_data: Whether or not to clean up existing Tensorboard files associated with the base_dir and category. :param hidden_keys: If provided, Tensorboard Writer won't write statistics identified with these Keys in Tensorboard summary. """ self.summary_writers: Dict[str, SummaryWriter] = {} self.base_dir: str = base_dir self._clear_past_data = clear_past_data self.hidden_keys: List[str] = hidden_keys if hidden_keys is not None else [] def write_stats( self, category: str, values: Dict[str, StatsSummary], step: int ) -> None: self._maybe_create_summary_writer(category) for key, value in values.items(): if key in self.hidden_keys: continue self.summary_writers[category].add_scalar( f"{key}", value.aggregated_value, step ) if value.aggregation_method == StatsAggregationMethod.HISTOGRAM: self.summary_writers[category].add_histogram( f"{key}_hist", np.array(value.full_dist), step ) self.summary_writers[category].flush() def _maybe_create_summary_writer(self, category: str) -> None: if category not in self.summary_writers: filewriter_dir = "{basedir}/{category}".format( basedir=self.base_dir, category=category ) os.makedirs(filewriter_dir, exist_ok=True) if self._clear_past_data: self._delete_all_events_files(filewriter_dir) self.summary_writers[category] = SummaryWriter(filewriter_dir) def _delete_all_events_files(self, directory_name: str) -> None: for file_name in os.listdir(directory_name): if file_name.startswith("events.out"): logger.warning( f"Deleting TensorBoard data {file_name} that was left over from a " "previous run." ) full_fname = os.path.join(directory_name, file_name) try: os.remove(full_fname) except OSError: logger.error( "{} was left over from a previous run and " "not deleted.".format(full_fname) ) def add_property( self, category: str, property_type: StatsPropertyType, value: Any ) -> None: if property_type == StatsPropertyType.HYPERPARAMETERS: assert isinstance(value, dict) summary = _dict_to_str(value, 0) self._maybe_create_summary_writer(category) if summary is not None: self.summary_writers[category].add_text("Hyperparameters", summary) self.summary_writers[category].flush()
TensorboardWriter
python
sqlalchemy__sqlalchemy
test/base/test_utils.py
{ "start": 74499, "end": 74811 }
class ____: def _kw_only_fixture(self, a, *, b, c): pass def _kw_plus_posn_fixture(self, a, *args, b, c): pass def _kw_opt_fixture(self, a, *, b, c="c"): pass def _ret_annotation_fixture(self, a, b) -> int: return 1 py3k_fixtures = _Py3KFixtures()
_Py3KFixtures
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclassTransform4.py
{ "start": 1515, "end": 1724 }
class ____: id: int = field2() name: str = field2(init=True) # This should generate an error because kw_only is True # by default for field2. CustomerModel2(1) CustomerModel2(name="Fred")
CustomerModel2
python
pypa__warehouse
tests/unit/email/test_init.py
{ "start": 136172, "end": 140303 }
class ____: def test_role_changed_email(self, db_request, pyramid_config, monkeypatch): changed_user = UserFactory.create() EmailFactory.create(primary=True, verified=True, public=True, user=changed_user) submitter_user = UserFactory.create() EmailFactory.create( primary=True, verified=True, public=True, user=submitter_user ) db_request.user = submitter_user subject_renderer = pyramid_config.testing_add_renderer( "email/collaborator-role-changed/subject.txt" ) subject_renderer.string_response = "Email Subject" body_renderer = pyramid_config.testing_add_renderer( "email/collaborator-role-changed/body.txt" ) body_renderer.string_response = "Email Body" html_renderer = pyramid_config.testing_add_renderer( "email/collaborator-role-changed/body.html" ) html_renderer.string_response = "Email HTML Body" send_email = pretend.stub( delay=pretend.call_recorder(lambda *args, **kwargs: None) ) db_request.task = pretend.call_recorder(lambda *args, **kwargs: send_email) monkeypatch.setattr(email, "send_email", send_email) result = email.send_collaborator_role_changed_email( db_request, [changed_user, submitter_user], user=changed_user, submitter=submitter_user, project_name="test_project", role="Owner", ) assert result == { "username": changed_user.username, "project": "test_project", "role": "Owner", "submitter": submitter_user.username, } subject_renderer.assert_() body_renderer.assert_(username=changed_user.username) body_renderer.assert_(project="test_project") body_renderer.assert_(role="Owner") body_renderer.assert_(submitter=submitter_user.username) html_renderer.assert_(username=changed_user.username) html_renderer.assert_(project="test_project") html_renderer.assert_(role="Owner") html_renderer.assert_(submitter=submitter_user.username) assert db_request.task.calls == [ pretend.call(send_email), pretend.call(send_email), ] assert send_email.delay.calls == [ pretend.call( f"{changed_user.name} <{changed_user.primary_email.email}>", { "sender": None, "subject": "Email Subject", "body_text": "Email Body", "body_html": ( "<html>\n<head></head>\n" "<body><p>Email HTML Body</p></body>\n</html>\n" ), }, { "tag": "account:email:sent", "user_id": changed_user.id, "additional": { "from_": None, "to": changed_user.primary_email.email, "subject": "Email Subject", "redact_ip": True, }, }, ), pretend.call( f"{submitter_user.name} <{submitter_user.primary_email.email}>", { "sender": None, "subject": "Email Subject", "body_text": "Email Body", "body_html": ( "<html>\n<head></head>\n" "<body><p>Email HTML Body</p></body>\n</html>\n" ), }, { "tag": "account:email:sent", "user_id": submitter_user.id, "additional": { "from_": None, "to": submitter_user.primary_email.email, "subject": "Email Subject", "redact_ip": False, }, }, ), ]
TestRoleChangedEmail
python
numba__numba
numba/core/dispatcher.py
{ "start": 49307, "end": 51905 }
class ____(LiftedWith): def __init__(self, *args, **kwargs): self.output_types = kwargs.pop('output_types', None) super(LiftedWith, self).__init__(*args, **kwargs) if not self.flags.force_pyobject: raise ValueError("expecting `flags.force_pyobject`") if self.output_types is None: raise TypeError('`output_types` must be provided') # switch off rewrites, they have no effect self.flags.no_rewrites = True @property def _numba_type_(self): return types.ObjModeDispatcher(self) def get_call_template(self, args, kws): """ Get a typing.ConcreteTemplate for this dispatcher and the given *args* and *kws* types. This enables the resolving of the return type. A (template, pysig, args, kws) tuple is returned. """ assert not kws self._legalize_arg_types(args) # Coerce to object mode args = [types.ffi_forced_object] * len(args) if self._can_compile: self.compile(tuple(args)) signatures = [typing.signature(self.output_types, *args)] pysig = None func_name = self.py_func.__name__ name = "CallTemplate({0})".format(func_name) call_template = typing.make_concrete_template( name, key=func_name, signatures=signatures) return call_template, pysig, args, kws def _legalize_arg_types(self, args): for i, a in enumerate(args, start=1): if isinstance(a, types.List): msg = ( 'Does not support list type inputs into ' 'with-context for arg {}' ) raise errors.TypingError(msg.format(i)) elif isinstance(a, types.Dispatcher): msg = ( 'Does not support function type inputs into ' 'with-context for arg {}' ) raise errors.TypingError(msg.format(i)) @global_compiler_lock def compile(self, sig): args, _ = sigutils.normalize_signature(sig) sig = (types.ffi_forced_object,) * len(args) return super().compile(sig) if config.USE_LEGACY_TYPE_SYSTEM: # Old type system # Initialize typeof machinery _dispatcher.typeof_init( OmittedArg, dict((str(t), t._code) for t in types.number_domain)) else: # New type system # Initialize typeof machinery _dispatcher.typeof_init( OmittedArg, dict((str(t).split('_')[-1], t._code) for t in types.np_number_domain))
ObjModeLiftedWith
python
dask__distributed
distributed/tests/test_spill.py
{ "start": 10007, "end": 10468 }
class ____: """A class which 1. reports an arbitrary managed memory usage 2. does not support being targeted by weakref.ref() 3. has a property `id` which changes every time it is unpickled """ __slots__ = ("size", "id") def __init__(self, size): self.size = size self.id = uuid.uuid4() def __sizeof__(self): return self.size def __reduce__(self): return (type(self), (self.size,))
NoWeakRef
python
rapidsai__cudf
python/cudf/cudf/core/udf/udf_kernel_base.py
{ "start": 940, "end": 6904 }
class ____(ABC): """ Base class for kernels computing the result of `.apply` operations on Series or DataFrame objects. """ def __init__(self, frame, func, args): self.frame = frame self.func = func if not all(is_scalar(arg) for arg in args): raise TypeError("only scalar valued args are supported by apply") self.args = args self.nrt = False self.frame_type = self._get_frame_type() self.device_func = cuda.jit(device=True)(self.func) @property @abstractmethod def kernel_type(self): """ API type launching the kernel, used to break degenerecies in the cache. """ @abstractmethod def _get_frame_type(self): """ Numba type of the frame being passed to the kernel. """ @abstractmethod def _get_kernel_string(self): """ Generate executable string of python that defines a kernel we may retrieve from the context and compile with numba. """ @abstractmethod def _get_kernel_string_exec_context(self): """ Get a dict of globals needed to exec the kernel string. """ def _construct_signature(self, return_type): """ Build the signature of numba types that will be used to actually JIT the kernel itself later, accounting for types and offsets. Skips columns with unsupported dtypes. """ if not return_type.is_internal: return_type = CPointer(return_type) else: return_type = return_type[::1] # Tuple of arrays, first the output data array, then the mask return_type = Tuple((return_type, boolean[::1])) supported_cols = _supported_cols_from_frame(self.frame) offsets = [int64] * len(supported_cols) sig = ( [return_type, int64] + [ _masked_array_type_from_col(col) for col in supported_cols.values() ] + offsets + [typeof(arg) for arg in self.args] ) return void(*sig) @_performance_tracking def _get_udf_return_type(self): # present a row containing all fields to the UDF and try and compile compile_sig = (self.frame_type, *(typeof(arg) for arg in self.args)) # Get the return type. The PTX is also returned by compile_udf, but is not # needed here. with _CUDFNumbaConfig(): _, output_type = compile_udf(self.func, compile_sig) if isinstance(output_type, MaskedType): result = output_type.value_type else: result = numpy_support.from_dtype(np.dtype(output_type)) result = result if result.is_internal else result.return_as # _get_udf_return_type will throw a TypingError if the user tries to use # a field in the row containing an unsupported dtype, except in the # edge case where all the function does is return that element: # def f(row): # return row[<bad dtype key>] # In this case numba is happy to return MaskedType(<bad dtype key>) # because it relies on not finding overloaded operators for types to raise # the exception, so we have to explicitly check for that case. if isinstance(result, Poison): raise TypingError(str(result)) return result def compile_kernel(self): """ Compile the kernel and return it as well as the return type. """ # First compilation pass compiles the UDF alone # gets us the return type to allocate the output # and determines if NRT must be enabled capture_nrt_usage = CaptureNRTUsage() with capture_nrt_usage: return_type = self._get_udf_return_type() self.sig = self._construct_signature(return_type) kernel_string = self._get_kernel_string() kernel = self.compile_kernel_string( kernel_string, nrt=capture_nrt_usage.use_nrt ) return kernel, return_type def compile_kernel_string(self, kernel_string, nrt=False): global_exec_context = self._get_kernel_string_exec_context() global_exec_context["f_"] = self.device_func exec(kernel_string, global_exec_context) _kernel = global_exec_context["_kernel"] ctx = nrt_enabled() if nrt else nullcontext() with ctx: with warnings.catch_warnings(): warnings.simplefilter("default") warnings.filterwarnings( "ignore", message=DEPRECATED_SM_REGEX, category=UserWarning, module=r"^numba\.cuda(\.|$)", ) kernel = cuda.jit( self.sig, link=[UDF_SHIM_FILE], extensions=[str_view_arg_handler], )(_kernel) return kernel def get_kernel(self): return self._compile_or_get_kernel() def _compile_or_get_kernel(self): """ Check the cache for a kernel corresponding to this function, frame, arguments, and udf type. Else, compile the kernel and store it in the cache. """ cache_key = _generate_cache_key( self.frame, self.func, self.args, suffix=self.kernel_type ) if kernel_cache.get(cache_key) is not None: kernel, masked_or_scalar = kernel_cache[cache_key] return kernel, masked_or_scalar kernel, scalar_return_type = self.compile_kernel() np_return_type = ( numpy_support.as_dtype(scalar_return_type) if scalar_return_type.is_internal else scalar_return_type.np_dtype ) kernel_cache[cache_key] = (kernel, np_return_type) return kernel, np_return_type
ApplyKernelBase
python
langchain-ai__langchain
libs/core/langchain_core/utils/aiter.py
{ "start": 2368, "end": 5032 }
class ____: """Dummy lock that provides the proper interface but no protection.""" async def __aenter__(self) -> None: """Do nothing.""" async def __aexit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> bool: """Return False, exception not suppressed.""" return False async def tee_peer( iterator: AsyncIterator[T], # the buffer specific to this peer buffer: deque[T], # the buffers of all peers, including our own peers: list[deque[T]], lock: AbstractAsyncContextManager[Any], ) -> AsyncGenerator[T, None]: """An individual iterator of a `tee`. This function is a generator that yields items from the shared iterator `iterator`. It buffers items until the least advanced iterator has yielded them as well. The buffer is shared with all other peers. Args: iterator: The shared iterator. buffer: The buffer for this peer. peers: The buffers of all peers. lock: The lock to synchronise access to the shared buffers. Yields: The next item from the shared iterator. """ try: while True: if not buffer: async with lock: # Another peer produced an item while we were waiting for the lock. # Proceed with the next loop iteration to yield the item. if buffer: continue try: item = await iterator.__anext__() except StopAsyncIteration: break else: # Append to all buffers, including our own. We'll fetch our # item from the buffer again, instead of yielding it directly. # This ensures the proper item ordering if any of our peers # are fetching items concurrently. They may have buffered their # item already. for peer_buffer in peers: peer_buffer.append(item) yield buffer.popleft() finally: async with lock: # this peer is done - remove its buffer for idx, peer_buffer in enumerate(peers): # pragma: no branch if peer_buffer is buffer: peers.pop(idx) break # if we are the last peer, try and close the iterator if not peers and hasattr(iterator, "aclose"): await iterator.aclose()
NoLock
python
kamyu104__LeetCode-Solutions
Python/multiply-strings.py
{ "start": 1324, "end": 1519 }
class ____(object): def multiply(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ return str(int(num1) * int(num2))
Solution3
python
ethereum__web3.py
tests/core/providers/test_base_provider.py
{ "start": 219, "end": 1186 }
class ____(BaseProvider): def is_connected(self, show_traceback: bool = False): return False def test_is_connected_connected(): """ Web3.is_connected() returns True when connected to a node. """ w3 = Web3(ConnectedProvider()) assert w3.is_connected() is True def test_is_connected_disconnected(): """ Web3.is_connected() returns False when configured with a provider that's not connected to a node. """ w3 = Web3(DisconnectedProvider()) assert w3.is_connected() is False def test_autoprovider_detection(): def no_provider(): return None def must_not_call(): raise AssertionError auto = AutoProvider( [ no_provider, DisconnectedProvider, ConnectedProvider, must_not_call, ] ) w3 = Web3(auto) assert w3.is_connected() assert isinstance(auto._active_provider, ConnectedProvider)
DisconnectedProvider
python
dask__dask
dask/dataframe/dask_expr/_datetime.py
{ "start": 94, "end": 1474 }
class ____(Accessor): """Accessor object for datetimelike properties of the Series values. Examples -------- >>> s.dt.microsecond # doctest: +SKIP """ _accessor_name = "dt" _accessor_methods = ( "ceil", "day_name", "floor", "isocalendar", "month_name", "normalize", "round", "strftime", "to_period", "to_pydatetime", "to_pytimedelta", "to_timestamp", "total_seconds", "tz_convert", "tz_localize", ) _accessor_properties = ( "components", "date", "day", "day_of_week", "day_of_year", "dayofweek", "dayofyear", "days", "days_in_month", "daysinmonth", "end_time", "freq", "hour", "is_leap_year", "is_month_end", "is_month_start", "is_quarter_end", "is_quarter_start", "is_year_end", "is_year_start", "microsecond", "microseconds", "minute", "month", "nanosecond", "nanoseconds", "quarter", "qyear", "second", "seconds", "start_time", "time", "timetz", "tz", "week", "weekday", "weekofyear", "year", )
DatetimeAccessor
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/static_analysis/reaching_definitions.py
{ "start": 1303, "end": 1751 }
class ____(object): """Definition objects describe a unique definition of a variable. Subclasses of this may be used by passing an appropriate factory function to resolve. Attributes: param_of: Optional[ast.AST] directives: Dict, optional definition annotations """ def __init__(self): self.param_of = None self.directives = {} def __repr__(self): return '%s[%d]' % (self.__class__.__name__, id(self))
Definition
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 41232, "end": 42103 }
class ____(MixinSequenceOfValues): """ Legend key background Parameters ---------- theme_element : element_rect """ def apply_figure(self, figure: Figure, targets: ThemeTargets): super().apply_figure(figure, targets) properties = self.properties edgecolor = properties.get("edgecolor", None) if isinstance(self, rect) and edgecolor: del properties["edgecolor"] # Prevent invisible strokes from having any effect if edgecolor in ("none", "None"): properties["linewidth"] = 0 rects = [da.patch for da in targets.legend_key] self.set(rects, properties) def blank_figure(self, figure: Figure, targets: ThemeTargets): super().blank_figure(figure, targets) for da in targets.legend_key: da.patch.set_visible(False)
legend_key
python
pytorch__pytorch
torch/distributed/checkpoint/_async_process_executor.py
{ "start": 962, "end": 1116 }
class ____(Enum): INIT_COMPLETE = "init_complete" TERMINATE = "terminate" @dataclass(init=False, unsafe_hash=True)
_CheckpointSaveProcessControlOpts
python
google__pytype
pytype/pytd/optimize.py
{ "start": 3811, "end": 5570 }
class ____(visitors.Visitor): """Group function signatures that only differ in exceptions or return values. For example, this transforms def f(x: int) -> float: raise OverflowError() def f(x: int) -> int: raise IndexError() to def f(x: int) -> Union[float, int]: raise IndexError() raise OverflowError() """ def _GroupByArguments(self, signatures): """Groups signatures by arguments. Arguments: signatures: A list of function signatures (Signature instances). Returns: A dictionary mapping signatures (without return and exceptions) to a tuple of return values and exceptions. """ groups = {} # Signature -> ReturnsAndExceptions for sig in signatures: stripped_signature = sig.Replace(return_type=None, exceptions=None) ret = groups.get(stripped_signature) if not ret: ret = _ReturnsAndExceptions() groups[stripped_signature] = ret ret.Update(sig) return groups def VisitFunction(self, f): """Merge signatures of a function. This groups signatures by arguments and then for each group creates a single signature that joins the return values / exceptions using "or". Arguments: f: A pytd.Function instance Returns: Function with simplified / combined signatures. """ groups = self._GroupByArguments(f.signatures) new_signatures = [] for stripped_signature, ret_exc in groups.items(): ret = pytd_utils.JoinTypes(ret_exc.return_types) exc = tuple(ret_exc.exceptions) new_signatures.append( stripped_signature.Replace(return_type=ret, exceptions=exc) ) return f.Replace(signatures=tuple(new_signatures))
CombineReturnsAndExceptions
python
lepture__authlib
authlib/oauth1/rfc5849/errors.py
{ "start": 1491, "end": 1601 }
class ____(OAuth1Error): error = "duplicated_oauth_protocol_parameter"
DuplicatedOAuthProtocolParameterError
python
django__django
django/db/models/functions/datetime.py
{ "start": 5195, "end": 5254 }
class ____(Extract): lookup_name = "minute"
ExtractMinute
python
pytorch__pytorch
torch/_dynamo/convert_frame.py
{ "start": 39783, "end": 68221 }
class ____: code: types.CodeType globals: dict[str, object] locals: dict[str, object] builtins: dict[str, object] closure: tuple[CellType] argdefs: Optional[tuple[Any, ...]] def _fullgraph_capture_frame( frame: FrameInfo, *, constraints: Optional[list[Constraint]] = None, _is_export_deprecated_do_not_use: bool = False, ) -> CaptureOutput: from torch._guards import TracingContext backend_input: Optional[BackendInput] = None def fullgraph_compiler( gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] ) -> torch.fx.GraphModule: nonlocal backend_input tracing_context = TracingContext.get() fake_mode = tracing_context.fake_mode tensor_to_context = tracing_context.tensor_to_context assert fake_mode is not None assert isinstance(gm.meta["backend_id"], str) backend_input = BackendInput( gm.meta["backend_id"], gm, example_inputs, fake_mode, tensor_to_context ) return gm try: dynamo_output = compile_frame( frame.code, frame.globals, frame.locals, frame.builtins, frame.closure, compiler_fn=fullgraph_compiler, export=_is_export_deprecated_do_not_use, export_constraints=constraints, # type: ignore[arg-type] one_graph=True, restart_reasons=set(), ) # https://github.com/pytorch/pytorch/blob/main/torch/_dynamo/eval_frame.py#L831 except Unsupported as e: augment_exc_message(e) if config.verbose: raise # strip internal tracebacks from causes cur_exn: BaseException = e while cur_exn.__cause__ is not None: cur_exn.__cause__.with_traceback(None) cur_exn = cur_exn.__cause__ # pyrefly: ignore [invalid-inheritance] raise e.with_traceback(None) from e.__cause__ # User compiler error return CaptureOutput( dynamo_output.graph_capture_output(frame.argdefs), backend_input, ) def compile_frame( # type: ignore[return] code: types.CodeType, globals: dict[str, object], locals: dict[str, object], builtins: dict[str, object], closure: tuple[CellType], compiler_fn: CompilerFn, one_graph: bool, restart_reasons: set[str], *, export: bool = False, export_constraints: Optional[typing.Never] = None, frame_state: Optional[dict[str, Union[int, FrameStateSizeEntry]]] = None, distributed_state: Optional[DistributedState] = None, package: Optional[CompilePackage] = None, # pyrefly: ignore [bad-return] ) -> DynamoOutput: """ A helper function taking a frame and backend, then return the generated bytecode and guards as a common data structure. This is a shared interface for multiple compiler frontends (e.g. torch.compile, torch.export) that needs to capture a graph out of python code. """ # This is shared across restarts speculation_log = SpeculationLog() def transform( instructions: list[Instruction], code_options: dict[str, object] ) -> DynamoTracerOutput: tf_mode_stack: list[torch.overrides.TorchFunctionMode] = ( torch.overrides._get_current_function_mode_stack() ) tracer_output = trace_frame( code, globals, locals, builtins, closure, compiler_fn, tf_mode_stack, one_graph, speculation_log, instructions, code_options, export=export, export_constraints=export_constraints, frame_state=frame_state, distributed_state=distributed_state, package=package, ) assert tracer_output is not None return tracer_output last_attempt_start_time = None for attempt in itertools.count(): CompileContext.get().attempt = attempt try: with dynamo_timed(f"compile_attempt_{attempt}", log_pt2_compile_event=True): bytecode, tracer_output = transform_code_object(code, transform) assert tracer_output is not None return DynamoOutput( tracer_output=tracer_output, bytecode=bytecode, last_attempt_start_time=last_attempt_start_time, ) except exc.RestartAnalysis as e: if not isinstance(e, exc.TensorifyScalarRestartAnalysis): TensorifyState.clear() log.info( "Restarting analysis due to %s", LazyString(format_traceback_short, e.__traceback__), ) # If restart reason is None just log the type of the exception restart_reasons.add(e.restart_reason or str(type(e))) # We now have a new "last attempt", reset the clock last_attempt_start_time = time.time() if attempt > 100: unimplemented( gb_type="Excessive RestartAnalysis() calls", context="", explanation="Dynamo attempted to trace the same frame 100+ times. " "Giving up on compiling as the compile time tradeoff is likely not " "worth the performance gain.", hints=[], ) except exc.SkipFrame as e: if not isinstance(e, exc.TensorifyScalarRestartAnalysis): TensorifyState.clear() log.debug( # noqa: G200 "Skipping frame %s %s \ %s %s", e, code.co_name, code.co_filename, code.co_firstlineno, ) raise def _compile( code: CodeType, globals: dict[str, object], locals: dict[str, object], builtins: dict[str, object], closure: tuple[CellType], compiler_fn: CompilerFn, one_graph: bool, export: bool, export_constraints: Optional[typing.Never], hooks: Hooks, cache_entry: Optional[CacheEntry], cache_size: CacheSizeRelevantForFrame, frame: Optional[DynamoFrameType] = None, frame_state: Optional[dict[str, Union[int, FrameStateSizeEntry]]] = None, *, compile_id: CompileId, skip: int = 0, package: Optional[CompilePackage] = None, # Can be used to record things for the caller, both # in the case of normal and exception code paths convert_frame_box: Optional[ConvertFrameBox] = None, ) -> ConvertFrameReturn: from torch.fx.experimental.validator import ( BisectValidationException, ValidationException, ) # Only nonlocal defs here please! # Time spent compiling this frame before restarting or failing analysis dynamo_time_before_restart: float = 0.0 @compile_time_strobelight_meta(phase_name="compile_inner") def compile_inner( code: CodeType, one_graph: bool, hooks: Hooks ) -> tuple[ConvertFrameReturn, Optional[DynamoTracerOutput]]: with contextlib.ExitStack() as stack: stack.enter_context( torch._dynamo.callback_handler.install_callbacks( CallbackTrigger.DYNAMO, str(CompileContext.current_compile_id()) ) ) stack.enter_context(CompileTimeInstructionCounter.record()) return _compile_inner(code, one_graph, hooks) return ( ConvertFrameReturn(), None, ) # dead, but see https://github.com/python/mypy/issues/7577 @maybe_cprofile def _compile_inner( code: CodeType, one_graph: bool, hooks: Hooks, ) -> tuple[ConvertFrameReturn, DynamoTracerOutput]: nonlocal dynamo_time_before_restart last_attempt_start_time = start_time = time.time() def log_bytecode( prefix: str, name: str, filename: str, line_no: int, code: CodeType ) -> None: if bytecode_log.isEnabledFor(logging.DEBUG): bytecode_log.debug( format_bytecode(prefix, name, filename, line_no, code) ) log_bytecode( "ORIGINAL BYTECODE", code.co_name, code.co_filename, code.co_firstlineno, code, ) out_code = None try: dynamo_output = compile_frame( code, globals, locals, builtins, closure, compiler_fn, one_graph, restart_reasons, export=export, export_constraints=export_constraints, frame_state=frame_state, distributed_state=distributed_state, package=package, ) except exc.SkipFrame as e: if one_graph: log.debug("No graph captured with export/fullgraph=True") assert e._torch_dynamo_tracer_output is not None return ConvertFrameReturn(), e._torch_dynamo_tracer_output assert distributed_state is None or distributed_state.all_states is not None, ( # type: ignore[has-type] "compiler collective wasn't run before compilation completed" ) out_code = dynamo_output.bytecode tracer_output = dynamo_output.tracer_output if dynamo_output.last_attempt_start_time is not None: last_attempt_start_time = dynamo_output.last_attempt_start_time assert out_code is not None log_bytecode( "MODIFIED BYTECODE", code.co_name, code.co_filename, code.co_firstlineno, out_code, ) for idx, hook in enumerate(_bytecode_hooks.values()): with dynamo_timed(f"bytecode_hooks_{idx}", log_pt2_compile_event=True): hook_output = hook(code, out_code) if hook_output is not None: out_code = hook_output orig_code_map[out_code] = code output_codes.add(out_code) dynamo_time_before_restart = last_attempt_start_time - start_time assert tracer_output.output_graph is not None output = tracer_output.output_graph # Tests for new code objects. # The rationale for these tests can be found in torch/csrc/dynamo/eval_frame.c # Only test once the code object is created. # They are not tested during runtime. def count_args(code: CodeType) -> int: import inspect return ( code.co_argcount + code.co_kwonlyargcount + bool(code.co_flags & inspect.CO_VARARGS) + bool(code.co_flags & inspect.CO_VARKEYWORDS) ) assert out_code is not None total_argcount_old = count_args(code) total_argcount_new = count_args(out_code) msg = "arg mismatch: " msg += f"old code object has args {code.co_varnames[:total_argcount_old]}, " msg += f"new code object has args {out_code.co_varnames[:total_argcount_new]}" assert ( code.co_varnames[:total_argcount_old] == out_code.co_varnames[:total_argcount_new] ), msg msg = "free var mismatch: " msg += f"old code object has free var {code.co_freevars}, " msg += f"new code object has free var {out_code.co_freevars}" assert code.co_freevars == out_code.co_freevars, msg msg = "cell var mismatch: " msg += f"old code object has cell var {code.co_cellvars}, " msg += f"new code object has cell var {out_code.co_cellvars}" assert code.co_cellvars == out_code.co_cellvars, msg # Skipping Dynamo on a frame without any extracted graph. # This does not affect eager functionality. But this is necessary # for export for cases where Dynamo-reconstructed bytecode can create # new function frames, confusing export in thinking that there # are extra graphs now. if output.export and output.is_empty_graph(): return ConvertFrameReturn(), tracer_output assert output.guards is not None CleanupManager.instance[out_code] = output.cleanups nonlocal cache_entry with dynamo_timed("build_guards", log_pt2_compile_event=True): check_fn = dynamo_output.build_guards( code, hooks=hooks, save=package is not None, cache_entry=cache_entry, ) if package is not None: assert check_fn.guards_state is not None package.add_guarded_code(check_fn.guards_state, out_code) package.add_inlined_source(output.tracing_context.traced_code) package.update_device_type(output.current_tracer.graph) compile_id_str = str(compile_id) if compile_id is not None else "Unknown" annotation_str = "Torch-Compiled Region: " + compile_id_str guarded_code = GuardedCode( out_code, check_fn.guard_manager, # type: ignore[arg-type] compile_id, annotation_str, ) if not output.is_empty_graph() and hooks.guard_export_fn is not None: # We should not run the guard_export_fn when Dynamo does not # generate any graph. This can happen in export when TorchDynamo # generated bytecode has some reconstruction logic for mutated # variables which can trigger TorchDynamo on the children frames but # they are benign and do not generate any new graphs. hooks.guard_export_fn(output.guards) return wrap_guarded_code(guarded_code), tracer_output metrics_context = get_metrics_context() code_context = ( package.code_context(code) if package is not None else contextlib.nullcontext() ) with ( _use_lazy_graph_module(config.use_lazy_graph_module), compile_context(CompileContext(compile_id)), chromium_event_timed( "dynamo", reset_event_log_on_exit=True, log_pt2_compile_event=True ), _WaitCounter("pytorch.wait_counter.entire_forward_compile").guard(), metrics_context, dynamo_timed( "_compile.compile_inner", phase_name="entire_frame_compile", dynamo_compile_column_us="dynamo_cumulative_compile_time_us", ), code_context, ): restart_reasons: set[str] = set() if compile_pg := get_compile_pg(): distributed_state = DistributedState(compile_pg, LocalState()) else: distributed_state = None # Check recompilations recompile_reason: Optional[str] = None if is_recompilation(cache_size) and frame: reasons = get_and_maybe_log_recompilation_reasons( cache_entry, frame, innermost_fn(compiler_fn) ) recompile_reason = ( "Unable to find recompilation reasons" if not reasons else reasons[0] ) # Recheck for recompilation, for when inline_inbuilt_nn_modules is set to False inline_inbuilt_nn_modules_candidate = False if not config.inline_inbuilt_nn_modules and frame: inbuilt_nn_reasons = get_and_maybe_log_recompilation_reasons( cache_entry, frame, innermost_fn(compiler_fn), skip_logging=True ) inbuilt_nn_recompile_reason = ( None if not inbuilt_nn_reasons else inbuilt_nn_reasons[0] ) if ( inbuilt_nn_recompile_reason is not None and "[inline-inbuilt-nn-modules-candidate]" in inbuilt_nn_recompile_reason ): inline_inbuilt_nn_modules_candidate = True # Set if the recompile is a candidate for inline_inbuilt_nn_modules # regardless of whether inline_inbuilt_nn_modules is set or not metrics_context.update_outer( { "recompile_reason": recompile_reason, "inline_inbuilt_nn_modules_candidate": inline_inbuilt_nn_modules_candidate, } ) recompile_user_contexts = get_hook_for_recompile_user_context() if recompile_user_contexts: # cap each user context to N chars for data retention purposes. N=256 # is chosen to be large enough to capture the most important info. user_contexts_msg = { user_context()[:256] for user_context in recompile_user_contexts } metrics_context.set("recompile_user_contexts", user_contexts_msg) exceeded, limit_type = exceeds_recompile_limit(cache_size, compile_id) if exceeded: def format_func_info(code: CodeType) -> str: return f"'{code.co_name}' ({code.co_filename}:{code.co_firstlineno})" # NS: Don't add period at the end of string, as it'll be added to URL # rendering it incorrect log.warning( "torch._dynamo hit config.%s (%s)\n" " function: %s\n" " last reason: %s\n" 'To log all recompilation reasons, use TORCH_LOGS="recompiles".\n' "To diagnose recompilation issues, see %s", limit_type, getattr(config, limit_type), format_func_info(code), recompile_reason, troubleshooting_url, ) if config.fail_on_recompile_limit_hit: raise FailOnRecompileLimitHit( f"{limit_type} reached, because fail_on_recompile_limit_hit = True this is a HARD failure" ) elif one_graph: raise FailOnRecompileLimitHit( f"{limit_type} reached with fullgraph=True. Excessive recompilations can degrade " "performance due to the compilation overhead of each recompilation. To monitor " "recompilations, enable TORCH_LOGS=recompiles. If recompilations are expected, consider " "increasing torch._dynamo.config.cache_size_limit to an appropriate value." ) elif justknobs_check( "pytorch/compiler:skip_code_recursive_on_recompile_limit_hit" ): raise RecompileLimitExceeded(f"{limit_type} reached") else: # do not recursively skip frames unimplemented( gb_type="Dynamo cache limit exceeded", context=f"Limit type: {limit_type}", explanation="Dynamo attempted to recompile the code object too many times, " f"exceeding the {limit_type} cache size limit." "Giving up on compiling as the compile time tradeoff is likely not " "worth the performance gain.", hints=[], ) log.debug( "torchdynamo start compiling %s %s:%s, stack (elided %s frames):\n%s", code.co_name, code.co_filename, code.co_firstlineno, skip + 2, # -2: omit current frame, omit contextlib decorator "".join(CapturedTraceback.extract(skip=2 + skip).format()), ) # -4: -2 as above, plus trace_structured frames # # NB: the frame looks like this: # # # handled by skip argument # torch/_dynamo/convert_frame.py:1069 in catch_errors # torch/_dynamo/convert_frame.py:910 in _convert_frame # torch/_dynamo/convert_frame.py:464 in _convert_frame_assert # torch/_utils_internal.py:70 in wrapper_function # # # 2 current frame and context lib # env/lib/python3.10/contextlib.py:79 in inner # torch/_dynamo/convert_frame.py:776 in _compile # # # 2 extra here # torch/_logging/_internal.py:1064 in trace_structured # torch/_dynamo/convert_frame.py:780 in <lambda> stack_trace = log_dynamo_start(code, skip) start_time_ns = time.time_ns() fail_type: Optional[str] = None fail_reason: Optional[str] = None exception_stack_trace: Optional[list[str]] = None fail_user_frame_filename: Optional[str] = None fail_user_frame_lineno: Optional[int] = None torch._dynamo.utils.ReinplaceCounters.clear() guarded_code = None tracer_output = None try: guarded_code, tracer_output = compile_inner(code, one_graph, hooks) # NB: We only put_code_state in success case. Success case here # does include graph breaks; specifically, if a graph break still # resulted in a partially compiled graph, we WILL return here. An # Unsupported exception will only bubble to the top level if we # are unable to compile the frame at all. In this case, there's # no point in uploading the code state, because we will always # fail exactly the same way even without the update. (It's useful # to upload for graph break though, because this can prevent # extra graph break compilations.) put_code_state() if ( tracer_output and (output_graph := tracer_output.output_graph) and output_graph.has_outputs() ): log_frame_dynamic_whitelist(code) if recompile_reason and "size mismatch at index" in recompile_reason: _log_size_mismatch_recompile() return guarded_code except Exception as e: # NB: e's msg is mutated here to add user stack, but we DON'T want # that stack in the Scuba logged fail_reason. So we grab the fail # info here and add it to the metrics context below. fail_type = type(e).__qualname__ fail_reason = str(e) exception_stack_trace = [traceback.format_exc()] exception_handler(e, code, frame, export=export) # NB: this is the post-mutation exception torch._logging.trace_structured( "artifact", metadata_fn=lambda: { "name": "dynamo_error", "encoding": "string", }, payload_fn=lambda: traceback.format_exc(), ) fail_user_frame_filename, fail_user_frame_lineno = exc.get_exc_message( e, compile_id ) tracer_output = getattr(e, "_torch_dynamo_tracer_output", None) if isinstance( e, ( Unsupported, TorchRuntimeError, BackendCompilerFailed, AssertionError, ConstraintViolationError, GuardOnDataDependentSymNode, ValidationException, UncapturedHigherOrderOpError, BisectValidationException, ShortenTraceback, PackageError, ResumePrologueTracingError, ), ): raise else: # Rewrap for clarity raise InternalTorchDynamoError( f"{type(e).__qualname__}: {str(e)}" ).with_traceback(e.__traceback__) from None finally: # === WARNING WARNING WARNING === # If you commit a bug here, it will suppress writing to # dynamo_compile table, and we will not have telemetry. # Be extra careful when making changes here! if torch._dynamo.config.run_gc_after_compile: with dynamo_timed("gc", dynamo_compile_column_us="gc_time_us"): log.info("run_gc_after_compile: running gc") gc.collect(1) output = None if tracer_output: output = tracer_output.output_graph if output: output.local_scope = {} # tracer should already be None, keep an extra check here just in case. if tracer := output.root_tx: tracer.f_locals = {} from .utils import curr_frame frame_key = str(curr_frame) if fail_reason is None and output is not None: guard_count = len(output.guards) shape_env_guard_count = len(output.shape_env.guards) graph_op_count = output.count_calls() graph_node_count = len(output.graph.nodes) graph_node_shapes = output.get_graph_sizes_structured() graph_input_count = len(output.placeholders) non_compliant_ops = {op.__qualname__ for op in output.non_compliant_ops} compliant_custom_ops = { op.__qualname__ for op in output.compliant_custom_ops } torch._dynamo.utils.ReinplaceCounters.log() else: guard_count = None shape_env_guard_count = None graph_op_count = None graph_node_count = None graph_node_shapes = {} graph_input_count = None non_compliant_ops = set({}) compliant_custom_ops = set({}) restart_reasons = set() # If compilation failed, the entire time is wasted dynamo_time_before_restart = (time.time_ns() - start_time_ns) / 1e9 metrics = { "frame_key": frame_key, "co_name": code.co_name, "co_filename": code.co_filename, "co_firstlineno": code.co_firstlineno, "cache_size": cache_size.num_cache_entries_with_same_id_matched_objs, "accumulated_cache_size": cache_size.num_cache_entries, "guard_count": guard_count, "shape_env_guard_count": shape_env_guard_count, "graph_op_count": graph_op_count, "graph_node_count": graph_node_count, "graph_input_count": graph_input_count, "fail_type": fail_type, "fail_reason": fail_reason, "fail_user_frame_filename": fail_user_frame_filename, "fail_user_frame_lineno": fail_user_frame_lineno, "non_compliant_ops": non_compliant_ops, "compliant_custom_ops": compliant_custom_ops, "restart_reasons": restart_reasons, "dynamo_time_before_restart_s": dynamo_time_before_restart, "has_guarded_code": guarded_code is not None, "specialize_float": config.specialize_float, "is_forward": True, "dynamo_compile_time_before_restart_us": to_int_us( dynamo_time_before_restart ), "stack_trace": stack_trace, "graph_node_shapes": str(graph_node_shapes), "exception_stack_trace": exception_stack_trace, } # TODO: replace with CompileEventLogger.compilation_metrics # There are some columns here not in PT2 Compile Events # so we need to slightly change it metrics_context.update_outer(metrics) # === END WARNING WARNING WARNING === # If tracer is available, then tracer.error_on_graph_break reflects value of # global symbolic_convert.error_on_graph_break at the time of the graph break - # symbolic_convert.error_on_graph_break may have been (correctly) changed during cleanup. # If tracer is unavailable, then fallback to symbolic_convert.error_on_graph_break. if convert_frame_box: convert_frame_box.error_on_graph_break = ( tracer_output.error_on_graph_break if tracer_output else _get_error_on_graph_break() )
FrameInfo
python
doocs__leetcode
lcof2/剑指 Offer II 067. 最大的异或/Solution.py
{ "start": 0, "end": 575 }
class ____: def findMaximumXOR(self, nums: List[int]) -> int: max = 0 mask = 0 for i in range(30, -1, -1): current = 1 << i # 期望的二进制前缀 mask = mask ^ current # 在当前前缀下, 数组内的前缀位数所有情况集合 s = set() for num in nums: s.add(num & mask) # 期望最终异或值的从右数第i位为1, 再根据异或运算的特性推算假设是否成立 flag = max | current for prefix in s: if prefix ^ flag in s: max = flag break return max
Solution
python
getsentry__sentry
tests/sentry/utils/email/test_signer.py
{ "start": 107, "end": 667 }
class ____(TestCase): def test_it_works(self) -> None: with self.settings(SECRET_KEY="a"): # the default salt is the module path # the class was moved at some point so this sets a constant salt signer = _CaseInsensitiveSigner(salt="sentry.utils.email._CaseInsensitiveSigner") assert signer.unsign(signer.sign("foo")) == "foo" assert signer.sign("foo") == "foo:wkpxg5djz3d4m0zktktfl9hdzw4" assert signer.unsign("foo:WKPXG5DJZ3D4M0ZKTKTFL9HDZW4") == "foo"
CaseInsensitiveSignerTests
python
sympy__sympy
sympy/physics/quantum/tests/test_represent.py
{ "start": 1577, "end": 1660 }
class ____(Bra): @classmethod def dual_class(self): return AKet
ABra
python
allegroai__clearml
clearml/backend_api/services/v2_13/workers.py
{ "start": 43268, "end": 46028 }
class ____(Request): """ Returns count of active company workers in the selected time range. :param from_date: Starting time (in seconds from epoch) for collecting statistics :type from_date: float :param to_date: Ending time (in seconds from epoch) for collecting statistics :type to_date: float :param interval: Time interval in seconds for a single statistics point. The minimal value is 1 :type interval: int """ _service = "workers" _action = "get_activity_report" _version = "2.13" _schema = { "definitions": {}, "properties": { "from_date": { "description": "Starting time (in seconds from epoch) for collecting statistics", "type": "number", }, "interval": { "description": "Time interval in seconds for a single statistics point. The minimal value is 1", "type": "integer", }, "to_date": { "description": "Ending time (in seconds from epoch) for collecting statistics", "type": "number", }, }, "required": ["from_date", "to_date", "interval"], "type": "object", } def __init__(self, from_date: float, to_date: float, interval: int, **kwargs: Any) -> None: super(GetActivityReportRequest, self).__init__(**kwargs) self.from_date = from_date self.to_date = to_date self.interval = interval @schema_property("from_date") def from_date(self) -> float: return self._property_from_date @from_date.setter def from_date(self, value: float) -> None: if value is None: self._property_from_date = None return self.assert_isinstance(value, "from_date", six.integer_types + (float,)) self._property_from_date = value @schema_property("to_date") def to_date(self) -> float: return self._property_to_date @to_date.setter def to_date(self, value: float) -> None: if value is None: self._property_to_date = None return self.assert_isinstance(value, "to_date", six.integer_types + (float,)) self._property_to_date = value @schema_property("interval") def interval(self) -> int: return self._property_interval @interval.setter def interval(self, value: int) -> None: if value is None: self._property_interval = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "interval", six.integer_types) self._property_interval = value
GetActivityReportRequest
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/line_api_scrollbars.py
{ "start": 189, "end": 414 }
class ____(Widget): def render(self): return Text( "\n".join(f"{n} 0123456789" for n in range(20)), no_wrap=True, overflow="hidden", justify="left", )
MyWidget
python
huggingface__transformers
src/transformers/models/phimoe/modeling_phimoe.py
{ "start": 12328, "end": 14191 }
class ____(torch.autograd.Function): @staticmethod def forward( ctx, scores: torch.Tensor, multiplier: torch.Tensor, selected_experts: torch.Tensor, masked_gates: torch.Tensor, mask_for_one: torch.Tensor, ): """ Forward pass for the custom autograd function. Args: ctx: Context object to save information for backward computation. scores (torch.Tensor): Input scores tensor. multiplier (torch.Tensor): Multiplier tensor. selected_experts (torch.Tensor): Tensor of selected experts. masked_gates (torch.Tensor): Masked gates tensor. mask_for_one (torch.Tensor): Mask for one tensor. Returns: torch.Tensor: Result of the forward pass. """ ctx.save_for_backward(multiplier, selected_experts, masked_gates) return multiplier * mask_for_one @staticmethod def backward( ctx, grad_at_output: torch.Tensor, ): """ Backward pass for the custom autograd function. Args: ctx: Context object with saved tensors from the forward pass. grad_at_output (torch.Tensor): Gradient at the output. Returns: tuple[torch.Tensor, None, None, None, None]: Gradients for the inputs. """ multiplier, selected_experts, masked_gates = ctx.saved_tensors grad_at_output = grad_at_output * multiplier grad_at_scores_expanded = masked_gates * grad_at_output.mul(-1) grad_at_scores_expanded.scatter_add_( dim=-1, index=selected_experts, src=grad_at_output, ) return ( grad_at_scores_expanded, None, None, None, None, )
PhimoeMultiplier
python
dagster-io__dagster
python_modules/libraries/dagster-databricks/dagster_databricks/components/databricks_asset_bundle/configs.py
{ "start": 3578, "end": 3670 }
class ____: task_key: str outcome: Optional[str] @record
DatabricksTaskDependsOnConfig
python
pytorch__pytorch
torch/distributed/elastic/agent/server/api.py
{ "start": 14149, "end": 16457 }
class ____(abc.ABC): """An agent process responsible for managing one or more worker processes. The worker processes are assumed to be regular distributed PyTorch scripts. When the worker process is created by the agent, the agent provides the necessary information for the worker processes to properly initialize a torch process group. The exact deployment topology and ratio of agent-to-worker is dependent on the specific implementation of the agent and the user's job placement preferences. For instance, to run a distributed training job on GPU with 8 trainers (one per GPU) one can: 1. Use 8 x single GPU instances, place an agent per instance, managing 1 worker per agent. 2. Use 4 x double GPU instances, place an agent per instance, managing 2 workers per agent. 3. Use 2 x quad GPU instances, place an agent per instance, managing 4 workers per agent. 4. Use 1 x 8 GPU instance, place an agent per instance, managing 8 workers per agent. Usage :: group_result = agent.run() if group_result.is_failed(): # workers failed failure = group_result.failures[0] logger.exception("worker 0 failed with exit code : %s", failure.exit_code) else: return group_result.return_values[0] # return rank 0's results """ @abc.abstractmethod def run(self, role: str = DEFAULT_ROLE) -> RunResult: """Run the agent. Supports retrying the worker group on failures up to ``max_restarts``. Returns: The result of the execution, containing the return values or failure details for each worker mapped by the worker's global rank. Raises: Exception - any other failures NOT related to worker process """ raise NotImplementedError @abc.abstractmethod def get_worker_group(self, role: str = DEFAULT_ROLE) -> WorkerGroup: """Return the ``WorkerGroup`` for the given ``role``. Note that the worker group is a mutable object and hence in a multi-threaded/process environment it may change state. Implementers are encouraged (but not required) to return a defensive read-only copy. """ raise NotImplementedError
ElasticAgent
python
walkccc__LeetCode
solutions/1230. Toss Strange Coins/1230-2.py
{ "start": 0, "end": 341 }
class ____: def probabilityOfHeads(self, prob: list[float], target: int) -> float: # dp[j] := the probability of tossing the coins so far with j heads dp = [1.0] + [0] * len(prob) for p in prob: for j in range(target, -1, -1): dp[j] = (dp[j - 1] * p if j > 0 else 0) + dp[j] * (1 - p) return dp[target]
Solution
python
django__django
django/contrib/postgres/fields/ranges.py
{ "start": 4139, "end": 5222 }
class ____(RangeField): """ Continuous range field. It allows specifying default bounds for list and tuple inputs. """ def __init__(self, *args, default_bounds=CANONICAL_RANGE_BOUNDS, **kwargs): if default_bounds not in ("[)", "(]", "()", "[]"): raise ValueError("default_bounds must be one of '[)', '(]', '()', or '[]'.") self.default_bounds = default_bounds super().__init__(*args, **kwargs) def get_prep_value(self, value): if isinstance(value, (list, tuple)): return self.range_type(value[0], value[1], self.default_bounds) return super().get_prep_value(value) def formfield(self, **kwargs): kwargs.setdefault("default_bounds", self.default_bounds) return super().formfield(**kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.default_bounds and self.default_bounds != CANONICAL_RANGE_BOUNDS: kwargs["default_bounds"] = self.default_bounds return name, path, args, kwargs
ContinuousRangeField
python
pyca__cryptography
tests/x509/test_x509_ext.py
{ "start": 4390, "end": 6958 }
class ____: def test_not_enum_type(self): with pytest.raises(TypeError): x509.TLSFeature([3]) # type:ignore[list-item] def test_empty_list(self): with pytest.raises(TypeError): x509.TLSFeature([]) def test_repr(self): ext1 = x509.TLSFeature([x509.TLSFeatureType.status_request]) assert repr(ext1) == ( "<TLSFeature(features=[<TLSFeatureType.status_request: 5>])>" ) def test_eq(self): ext1 = x509.TLSFeature([x509.TLSFeatureType.status_request]) ext2 = x509.TLSFeature([x509.TLSFeatureType.status_request]) assert ext1 == ext2 def test_ne(self): ext1 = x509.TLSFeature([x509.TLSFeatureType.status_request]) ext2 = x509.TLSFeature([x509.TLSFeatureType.status_request_v2]) ext3 = x509.TLSFeature( [ x509.TLSFeatureType.status_request, x509.TLSFeatureType.status_request_v2, ] ) assert ext1 != ext2 assert ext1 != ext3 assert ext1 != object() def test_hash(self): ext1 = x509.TLSFeature([x509.TLSFeatureType.status_request]) ext2 = x509.TLSFeature([x509.TLSFeatureType.status_request]) ext3 = x509.TLSFeature( [ x509.TLSFeatureType.status_request, x509.TLSFeatureType.status_request_v2, ] ) assert hash(ext1) == hash(ext2) assert hash(ext1) != hash(ext3) def test_iter(self): ext1_features = [x509.TLSFeatureType.status_request] ext1 = x509.TLSFeature(ext1_features) assert len(ext1) == 1 assert list(ext1) == ext1_features ext2_features = [ x509.TLSFeatureType.status_request, x509.TLSFeatureType.status_request_v2, ] ext2 = x509.TLSFeature(ext2_features) assert len(ext2) == 2 assert list(ext2) == ext2_features def test_indexing(self): ext = x509.TLSFeature( [ x509.TLSFeatureType.status_request, x509.TLSFeatureType.status_request_v2, ] ) assert ext[-1] == ext[1] assert ext[0] == x509.TLSFeatureType.status_request def test_public_bytes(self): ext1 = x509.TLSFeature([x509.TLSFeatureType.status_request]) assert ext1.public_bytes() == b"\x30\x03\x02\x01\x05" ext2 = x509.TLSFeature([x509.TLSFeatureType.status_request_v2]) assert ext2.public_bytes() == b"\x30\x03\x02\x01\x11"
TestTLSFeature
python
PyCQA__pylint
tests/functional/n/non/non_init_parent_called.py
{ "start": 909, "end": 1114 }
class ____(AAAA): """call superclass constructor in disjunct branches""" def __init__(self, value): if value: AAAA.__init__(self) else: AAAA.__init__(self)
DDDD
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/view_symlinked_dir/package.py
{ "start": 228, "end": 780 }
class ____(Package): """Installs <prefix>/bin/x/file_in_symlinked_dir where x -> y is a symlinked dir. This should be mergeable with view-dir, but not with view-file.""" has_code = False version("0.1.0") def install(self, spec, prefix): os.mkdir(os.path.join(prefix, "bin")) os.mkdir(os.path.join(prefix, "bin", "y")) with open(os.path.join(prefix, "bin", "y", "file_in_symlinked_dir"), "wb") as f: f.write(b"hello world") os.symlink("y", os.path.join(prefix, "bin", "x"))
ViewSymlinkedDir
python
huggingface__transformers
src/transformers/models/swin2sr/modeling_swin2sr.py
{ "start": 24791, "end": 27215 }
class ____(GradientCheckpointingLayer): """ This corresponds to the Residual Swin Transformer Block (RSTB) in the original implementation. """ def __init__(self, config, dim, input_resolution, depth, num_heads, drop_path, pretrained_window_size=0): super().__init__() self.config = config self.dim = dim self.layers = nn.ModuleList( [ Swin2SRLayer( config=config, dim=dim, input_resolution=input_resolution, num_heads=num_heads, shift_size=0 if (i % 2 == 0) else config.window_size // 2, pretrained_window_size=pretrained_window_size, ) for i in range(depth) ] ) if config.resi_connection == "1conv": self.conv = nn.Conv2d(dim, dim, 3, 1, 1) elif config.resi_connection == "3conv": # to save parameters and memory self.conv = nn.Sequential( nn.Conv2d(dim, dim // 4, 3, 1, 1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(dim // 4, dim // 4, 1, 1, 0), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(dim // 4, dim, 3, 1, 1), ) self.patch_embed = Swin2SRPatchEmbeddings(config, normalize_patches=False) self.patch_unembed = Swin2SRPatchUnEmbeddings(config) def forward( self, hidden_states: torch.Tensor, input_dimensions: tuple[int, int], output_attentions: Optional[bool] = False, ) -> tuple[torch.Tensor]: residual = hidden_states height, width = input_dimensions for i, layer_module in enumerate(self.layers): layer_outputs = layer_module(hidden_states, input_dimensions, output_attentions) hidden_states = layer_outputs[0] output_dimensions = (height, width, height, width) hidden_states = self.patch_unembed(hidden_states, input_dimensions) hidden_states = self.conv(hidden_states) hidden_states, _ = self.patch_embed(hidden_states) hidden_states = hidden_states + residual stage_outputs = (hidden_states, output_dimensions) if output_attentions: stage_outputs += layer_outputs[1:] return stage_outputs
Swin2SRStage
python
getsentry__sentry
tests/relay_integration/test_metrics_extraction.py
{ "start": 589, "end": 6913 }
class ____(RelayStoreHelper, TransactionTestCase): @pytest.mark.skip("breaks in Relay for unknown reasons") @override_options({"relay.transaction-names-client-based": 1.0}) def test_all_transaction_metrics_emitted(self) -> None: with Feature( { "organizations:transaction-metrics-extraction": True, } ): event_data = { "type": "transaction", "transaction": "foo", "transaction_info": {"source": "url"}, # 'transaction' tag not extracted "timestamp": before_now(seconds=1), "start_timestamp": before_now(seconds=2), "contexts": { "trace": { "trace_id": 32 * "b", "span_id": 16 * "c", "type": "trace", } }, "user": {"id": 123}, "measurements": { "fp": {"value": 2258.060000000114}, "fcp": {"value": 2258.060000000114}, "lcp": {"value": 2807.335}, "inp": {"value": 51.318}, "fid": {"value": 3.4900000027846545}, "cls": {"value": 0.0382}, "frames_total": {"value": 100}, "frames_slow": {"value": 10}, "frames_frozen": {"value": 5}, "stall_count": {"value": 2}, "stall_total_time": {"value": 12}, "stall_longest_time": {"value": 7}, "app_start_warm": {"value": 0.001}, "app_start_cold": {"value": 0.001}, "ttfb": {"value": 5}, "ttfb.requesttime": {"value": 6}, }, "spans": [ { "op": op, "trace_id": 32 * "b", "span_id": 16 * "1", "start_timestamp": before_now(seconds=2), "timestamp": before_now(seconds=1), } for op in ("db", "http", "resource", "browser", "ui") ], } settings = { "bootstrap.servers": "127.0.0.1:9092", # TODO: read from django settings here "group.id": "test-consumer-%s" % uuid.uuid4().hex, "enable.auto.commit": True, "auto.offset.reset": "earliest", } consumer = kafka.Consumer(settings) consumer.assign([kafka.TopicPartition("ingest-metrics", 0)]) self.post_and_retrieve_event(event_data) strings_emitted = set() for attempt in range(1000): message = consumer.poll(timeout=5.0 if attempt == 0 else 0.1) if message is None: break message = json.loads(message.value()) if message["project_id"] == self.project.id: strings_emitted.add(message["name"]) for key, value in message["tags"].items(): strings_emitted.add(key) strings_emitted.add(value) consumer.close() #: These strings should be common strings, but we cannot add them #: to the indexer because they already exist in the release health #: indexer db. known_non_common_strings = { "other", "platform", "d:transactions/measurements.inp@millisecond", } # Make sure that all the standard strings are part of the list of common strings: non_common_strings = strings_emitted - SHARED_STRINGS.keys() assert non_common_strings == known_non_common_strings @thread_leak_allowlist(reason="sentry sdk background worker", issue=97042) def test_histogram_outliers(self) -> None: with Feature( { "organizations:transaction-metrics-extraction": True, } ): event_data = { "type": "transaction", "transaction": "foo", "transaction_info": {"source": "url"}, # 'transaction' tag not extracted "timestamp": before_now(seconds=1).isoformat(), "start_timestamp": before_now(seconds=2).isoformat(), "platform": "javascript", "contexts": { "trace": { "op": "pageload", "trace_id": 32 * "b", "span_id": 16 * "c", "type": "trace", } }, "user": {"id": 123}, "measurements": { "fcp": {"value": 999999999.0}, "lcp": {"value": 0.0}, }, } settings = { "bootstrap.servers": "127.0.0.1:9092", # TODO: read from django settings here "group.id": "test-consumer-%s" % uuid.uuid4().hex, "enable.auto.commit": True, "auto.offset.reset": "earliest", } consumer = kafka.Consumer(settings) consumer.assign([kafka.TopicPartition("ingest-performance-metrics", 0)]) self.post_and_retrieve_event(event_data) histogram_outlier_tags = {} buckets = [] for attempt in range(1000): message = consumer.poll(timeout=5.0 if attempt == 0 else 0.1) if message is None: break bucket = json.loads(message.value()) buckets.append(bucket) try: histogram_outlier_tags[bucket["name"]] = bucket["tags"]["histogram_outlier"] except KeyError: pass consumer.close() assert histogram_outlier_tags == { "d:transactions/duration@millisecond": "inlier", "d:transactions/measurements.fcp@millisecond": "outlier", "d:transactions/measurements.lcp@millisecond": "inlier", }
MetricsExtractionTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1403234, "end": 1403992 }
class ____(sgqlc.types.Type, Node): """Represents a 'reopened' event on any `Closable`.""" __schema__ = github_schema __field_names__ = ("actor", "closable", "created_at", "state_reason") actor = sgqlc.types.Field(Actor, graphql_name="actor") """Identifies the actor who performed the event.""" closable = sgqlc.types.Field(sgqlc.types.non_null(Closable), graphql_name="closable") """Object that was reopened.""" created_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="createdAt") """Identifies the date and time when the object was created.""" state_reason = sgqlc.types.Field(IssueStateReason, graphql_name="stateReason") """The reason the issue state was changed to open."""
ReopenedEvent
python
realpython__materials
python-312/typing/accounts.py
{ "start": 701, "end": 1138 }
class ____(BankAccount): interest: float def add_interest(self) -> None: self.balance *= 1 + self.interest / 100 @classmethod @override def from_balance(cls, balance: float, interest: float = 1.0) -> Self: return cls(generate_account_number(), balance, interest) @override def withdraw(self, amount: float) -> None: self.balance -= int(amount) if amount > 100 else amount
SavingsAccount
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 73044, "end": 73312 }
class ____(BaseModel): model_config = ConfigDict( extra="forbid", ) actions: Annotated[ list[BulkCreateActionVariableBody | BulkUpdateActionVariableBody | BulkDeleteActionVariableBody], Field(title="Actions"), ]
BulkBodyVariableBody
python
huggingface__transformers
src/transformers/models/udop/modeling_udop.py
{ "start": 19222, "end": 19976 }
class ____(nn.Module): def __init__(self, config: UdopConfig): super().__init__() if config.is_gated_act: self.DenseReluDense = UdopDenseGatedActDense(config) else: self.DenseReluDense = UdopDenseActDense(config) self.layer_norm = UdopLayerNorm(config.d_model, eps=config.layer_norm_epsilon) self.dropout = nn.Dropout(config.dropout_rate) def forward(self, hidden_states): forwarded_states = self.layer_norm(hidden_states) forwarded_states = self.DenseReluDense(forwarded_states) hidden_states = hidden_states + self.dropout(forwarded_states) return hidden_states # Copied from transformers.models.t5.modeling_t5.T5Attention with T5->Udop
UdopLayerFF
python
neetcode-gh__leetcode
python/0094-binary-tree-inorder-traversal.py
{ "start": 0, "end": 628 }
class ____: def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: # Iterative res, stack = [], [] cur = root while cur or stack: while cur: stack.append(cur) cur = cur.left cur = stack.pop() res.append(cur.val) cur = cur.right return res # Recursive res = [] def helper(root): if not root: return helper(root.left) res.append(root.val) helper(root.right) helper(root) return res
Solution
python
django__django
django/contrib/postgres/fields/ranges.py
{ "start": 11379, "end": 11516 }
class ____(models.Transform): lookup_name = "upper_inf" function = "UPPER_INF" output_field = models.BooleanField()
UpperInfinite
python
sqlalchemy__sqlalchemy
test/orm/test_session.py
{ "start": 60657, "end": 63313 }
class ____(fixtures.MappedTest): run_setup_mappers = "once" run_inserts = "once" run_deletes = None @classmethod def define_tables(cls, metadata): Table( "t1", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("data", String(50)), ) @classmethod def setup_mappers(cls): class T(cls.Basic): def __init__(self, data): self.data = data cls.mapper_registry.map_imperatively(T, cls.tables.t1) def teardown_test(self): from sqlalchemy.orm.session import _sessions _sessions.clear() def _set_imap_in_disposal(self, sess, *objs): """remove selected objects from the given session, as though they were dereferenced and removed from WeakIdentityMap. Hardcodes the identity map's "all_states()" method to return the full list of states. This simulates the all_states() method returning results, afterwhich some of the states get garbage collected (this normally only happens during asynchronous gc). The Session now has one or more InstanceState's which have been removed from the identity map and disposed. Will the Session not trip over this ??? Stay tuned. """ all_states = sess.identity_map.all_states() sess.identity_map.all_states = lambda: all_states for obj in objs: state = attributes.instance_state(obj) sess.identity_map.discard(state) state._dispose() def _test_session(self, **kwargs): T = self.classes.T sess = Session(config.db, **kwargs) data = o1, o2, o3, o4, o5 = [ T("t1"), T("t2"), T("t3"), T("t4"), T("t5"), ] sess.add_all(data) sess.commit() o1.data = "t1modified" o5.data = "t5modified" self._set_imap_in_disposal(sess, o2, o4, o5) return sess def test_flush(self): self._test_session().flush() def test_clear(self): self._test_session().expunge_all() def test_close(self): self._test_session().close() def test_invalidate(self): self._test_session().invalidate() def test_expunge_all(self): self._test_session().expunge_all() def test_expire_all(self): self._test_session().expire_all() def test_rollback(self): sess = self._test_session(expire_on_commit=True) sess.commit() sess.rollback()
DisposedStates
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/common.py
{ "start": 1912, "end": 2284 }
class ____(BulkBaseAction[T]): """Bulk Create entity serializer for request bodies.""" action: Literal[BulkAction.CREATE] = Field(description="The action to be performed on the entities.") entities: list[T] = Field(..., description="A list of entities to be created.") action_on_existence: BulkActionOnExistence = BulkActionOnExistence.FAIL
BulkCreateAction
python
django-haystack__django-haystack
test_haystack/test_indexes.py
{ "start": 3957, "end": 4144 }
class ____(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, model_attr="test_a") def get_model(self): return MockModel
MROFieldsSearchIndexA
python
ray-project__ray
rllib/utils/checkpoints.py
{ "start": 2119, "end": 43455 }
class ____(abc.ABC): """Abstract base class for a component of RLlib that can be checkpointed to disk. Subclasses must implement the following APIs: - save_to_path() - restore_from_path() - from_checkpoint() - get_state() - set_state() - get_ctor_args_and_kwargs() - get_metadata() - get_checkpointable_components() """ # The state file for the implementing class. # This file contains any state information that does NOT belong to any subcomponent # of the implementing class (which are `Checkpointable` themselves and thus should # have their own state- and metadata files). # After a `save_to_path([path])` this file can be found directly in: `path/`. STATE_FILE_NAME = "state" # The filename of the pickle file that contains the class information of the # Checkpointable as well as all constructor args to be passed to such a class in # order to construct a new instance. CLASS_AND_CTOR_ARGS_FILE_NAME = "class_and_ctor_args.pkl" # Subclasses may set this to their own metadata filename. # The dict returned by self.get_metadata() is stored in this JSON file. METADATA_FILE_NAME = "metadata.json" def save_to_path( self, path: Optional[Union[str, pathlib.Path]] = None, *, state: Optional[StateDict] = None, filesystem: Optional["pyarrow.fs.FileSystem"] = None, use_msgpack: bool = False, ) -> str: """Saves the state of the implementing class (or `state`) to `path`. The state of the implementing class is always saved in the following format: .. testcode:: :skipif: True path/ [component1]/ [component1 subcomponentA]/ ... [component1 subcomponentB]/ ... [component2]/ ... [cls.METADATA_FILE_NAME] (json) [cls.STATE_FILE_NAME] (pkl|msgpack) The main logic is to loop through all subcomponents of this Checkpointable and call their respective `save_to_path` methods. Then save the remaining (non subcomponent) state to this Checkpointable's STATE_FILE_NAME. In the exception that a component is a FaultTolerantActorManager instance, instead of calling `save_to_path` directly on that manager, the first healthy actor is interpreted as the component and its `save_to_path` method is called. Even if that actor is located on another node, the created file is automatically synced to the local node. Args: path: The path to the directory to save the state of the implementing class to. If `path` doesn't exist or is None, then a new directory will be created (and returned). state: An optional state dict to be used instead of getting a new state of the implementing class through `self.get_state()`. filesystem: PyArrow FileSystem to use to access data at the `path`. If not specified, this is inferred from the URI scheme of `path`. use_msgpack: Whether the state file should be written using msgpack and msgpack_numpy (file extension is `.msgpack`), rather than pickle (file extension is `.pkl`). Returns: The path (str) where the state has been saved. """ # If no path is given create a local temporary directory. if path is None: import uuid # Get the location of the temporary directory on the OS. tmp_dir = pathlib.Path(tempfile.gettempdir()) # Create a random directory name. random_dir_name = str(uuid.uuid4()) # Create the path, but do not craet the directory on the # filesystem, yet. This is done by `PyArrow`. path = path or tmp_dir / random_dir_name # We need a string path for `pyarrow.fs.FileSystem.from_uri`. path = path if isinstance(path, str) else path.as_posix() # If we have no filesystem, figure it out. if path and not filesystem: # Note the path needs to be a path that is relative to the # filesystem (e.g. `gs://tmp/...` -> `tmp/...`). filesystem, path = pyarrow.fs.FileSystem.from_uri(path) # Make sure, path exists. filesystem.create_dir(path, recursive=True) # Convert to `pathlib.Path` for easy handling. path = pathlib.Path(path) # Write metadata file to disk. metadata = self.get_metadata() if "checkpoint_version" not in metadata: metadata["checkpoint_version"] = str( CHECKPOINT_VERSION_LEARNER_AND_ENV_RUNNER ) with filesystem.open_output_stream( (path / self.METADATA_FILE_NAME).as_posix() ) as f: f.write(json.dumps(metadata).encode("utf-8")) # Write the class and constructor args information to disk. Always use pickle # for this, because this information contains classes and maybe other # non-serializable data. with filesystem.open_output_stream( (path / self.CLASS_AND_CTOR_ARGS_FILE_NAME).as_posix() ) as f: pickle.dump( { "class": type(self), "ctor_args_and_kwargs": self.get_ctor_args_and_kwargs(), }, f, ) # Get the entire state of this Checkpointable, or use provided `state`. _state_provided = state is not None # Get only the non-checkpointable components of the state. Checkpointable # components are saved to path by their own `save_to_path` in the loop below. state = state or self.get_state( not_components=[c[0] for c in self.get_checkpointable_components()] ) # Write components of `self` that themselves are `Checkpointable`. for comp_name, comp in self.get_checkpointable_components(): # If subcomponent's name is not in `state`, ignore it and don't write this # subcomponent's state to disk. if _state_provided and comp_name not in state: continue comp_path = path / comp_name # If component is an ActorManager, save the manager's first healthy # actor's state to disk (even if it's on another node, in which case, we'll # sync the generated file(s) back to this node). if isinstance(comp, FaultTolerantActorManager): actor_to_use = comp.healthy_actor_ids()[0] def _get_ip(_=None): import ray return ray.util.get_node_ip_address() _result = next( iter( comp.foreach_actor( _get_ip, remote_actor_ids=[actor_to_use], ) ) ) if not _result.ok: raise _result.get() worker_ip_addr = _result.get() self_ip_addr = _get_ip() # Save the state to a temporary location on the `actor_to_use`'s # node. comp_state_ref = None if _state_provided: comp_state_ref = ray.put(state.pop(comp_name)) if worker_ip_addr == self_ip_addr: comp.foreach_actor( lambda w, _path=comp_path, _state=comp_state_ref, _use_msgpack=use_msgpack: ( # noqa w.save_to_path( _path, state=( ray.get(_state) if _state is not None else w.get_state() ), use_msgpack=_use_msgpack, ) ), remote_actor_ids=[actor_to_use], ) else: # Save the checkpoint to the temporary directory on the worker. def _save(w, _state=comp_state_ref, _use_msgpack=use_msgpack): import tempfile # Create a temporary directory on the worker. tmpdir = tempfile.mkdtemp() w.save_to_path( tmpdir, state=( ray.get(_state) if _state is not None else w.get_state() ), use_msgpack=_use_msgpack, ) return tmpdir _result = next( iter(comp.foreach_actor(_save, remote_actor_ids=[actor_to_use])) ) if not _result.ok: raise _result.get() worker_temp_dir = _result.get() # Sync the temporary directory from the worker to this node. sync_dir_between_nodes( worker_ip_addr, worker_temp_dir, self_ip_addr, str(comp_path), ) # Remove the temporary directory on the worker. def _rmdir(_, _dir=worker_temp_dir): import shutil shutil.rmtree(_dir) comp.foreach_actor(_rmdir, remote_actor_ids=[actor_to_use]) # Local component (instance stored in a property of `self`). else: if _state_provided: comp_state = state.pop(comp_name) else: comp_state = self.get_state(components=comp_name)[comp_name] # By providing the `state` arg, we make sure that the component does not # have to call its own `get_state()` anymore, but uses what's provided # here. comp.save_to_path( comp_path, filesystem=filesystem, state=comp_state, use_msgpack=use_msgpack, ) # Write all the remaining state to disk. filename = path / ( self.STATE_FILE_NAME + (".msgpack" if use_msgpack else ".pkl") ) with filesystem.open_output_stream(filename.as_posix()) as f: if use_msgpack: msgpack = try_import_msgpack(error=True) msgpack.dump(state, f) else: pickle.dump(state, f) return str(path) def restore_from_path( self, path: Union[str, pathlib.Path], *, component: Optional[str] = None, filesystem: Optional["pyarrow.fs.FileSystem"] = None, **kwargs, ) -> None: """Restores the state of the implementing class from the given path. If the `component` arg is provided, `path` refers to a checkpoint of a subcomponent of `self`, thus allowing the user to load only the subcomponent's state into `self` without affecting any of the other state information (for example, loading only the NN state into a Checkpointable, which contains such an NN, but also has other state information that should NOT be changed by calling this method). The given `path` should have the following structure and contain the following files: .. testcode:: :skipif: True path/ [component1]/ [component1 subcomponentA]/ ... [component1 subcomponentB]/ ... [component2]/ ... [cls.METADATA_FILE_NAME] (json) [cls.STATE_FILE_NAME] (pkl|msgpack) Note that the self.METADATA_FILE_NAME file is not required to restore the state. Args: path: The path to load the implementing class' state from or to load the state of only one subcomponent's state of the implementing class (if `component` is provided). component: If provided, `path` is interpreted as the checkpoint path of only the subcomponent and thus, only that subcomponent's state is restored/loaded. All other state of `self` remains unchanged in this case. filesystem: PyArrow FileSystem to use to access data at the `path`. If not specified, this is inferred from the URI scheme of `path`. **kwargs: Forward compatibility kwargs. """ path = path if isinstance(path, str) else path.as_posix() if path and not filesystem: # Note the path needs to be a path that is relative to the # filesystem (e.g. `gs://tmp/...` -> `tmp/...`). filesystem, path = pyarrow.fs.FileSystem.from_uri(path) # Only here convert to a `Path` instance b/c otherwise # cloud path gets broken (i.e. 'gs://' -> 'gs:/'). path = pathlib.Path(path) if not _exists_at_fs_path(filesystem, path.as_posix()): raise FileNotFoundError(f"`path` ({path}) not found!") # Restore components of `self` that themselves are `Checkpointable`. orig_comp_names = {c[0] for c in self.get_checkpointable_components()} self._restore_all_subcomponents_from_path( path, filesystem, component=component, **kwargs ) # Restore the "base" state (not individual subcomponents). if component is None: filename = path / self.STATE_FILE_NAME if filename.with_suffix(".msgpack").is_file(): msgpack = try_import_msgpack(error=True) with filesystem.open_input_stream( filename.with_suffix(".msgpack").as_posix() ) as f: state = msgpack.load(f, strict_map_key=False) else: with filesystem.open_input_stream( filename.with_suffix(".pkl").as_posix() ) as f: state = pickle.load(f) self.set_state(state) new_comp_names = {c[0] for c in self.get_checkpointable_components()} diff_comp_names = new_comp_names - orig_comp_names if diff_comp_names: self._restore_all_subcomponents_from_path( path, filesystem, only_comp_names=diff_comp_names, **kwargs ) @classmethod def from_checkpoint( cls, path: Union[str, pathlib.Path], filesystem: Optional["pyarrow.fs.FileSystem"] = None, **kwargs, ) -> "Checkpointable": """Creates a new Checkpointable instance from the given location and returns it. Args: path: The checkpoint path to load (a) the information on how to construct a new instance of the implementing class and (b) the state to restore the created instance to. filesystem: PyArrow FileSystem to use to access data at the `path`. If not specified, this is inferred from the URI scheme of `path`. kwargs: Forward compatibility kwargs. Note that these kwargs are sent to each subcomponent's `from_checkpoint()` call. Returns: A new instance of the implementing class, already set to the state stored under `path`. """ # We need a string path for the `PyArrow` filesystem. path = path if isinstance(path, str) else path.as_posix() # If no filesystem is passed in create one. if path and not filesystem: # Note the path needs to be a path that is relative to the # filesystem (e.g. `gs://tmp/...` -> `tmp/...`). filesystem, path = pyarrow.fs.FileSystem.from_uri(path) # Only here convert to a `Path` instance b/c otherwise # cloud path gets broken (i.e. 'gs://' -> 'gs:/'). path = pathlib.Path(path) # Get the class constructor to call and its args/kwargs. # Try reading the pickle file first. try: with filesystem.open_input_stream( (path / cls.CLASS_AND_CTOR_ARGS_FILE_NAME).as_posix() ) as f: ctor_info = pickle.load(f) ctor = ctor_info["class"] ctor_args = force_list(ctor_info["ctor_args_and_kwargs"][0]) ctor_kwargs = ctor_info["ctor_args_and_kwargs"][1] # Inspect the ctor to see, which arguments in ctor_info should be replaced # with the user provided **kwargs. for i, (param_name, param) in enumerate( inspect.signature(ctor).parameters.items() ): if param_name in kwargs: val = kwargs.pop(param_name) if ( param.kind == inspect._ParameterKind.POSITIONAL_OR_KEYWORD and len(ctor_args) > i ): ctor_args[i] = val else: ctor_kwargs[param_name] = val # If the pickle file is from another python version, use provided # args instead. except Exception: # Use class that this method was called on. ctor = cls # Use only user provided **kwargs. ctor_args = [] ctor_kwargs = kwargs # Check, whether the constructor actually goes together with `cls`. if not issubclass(ctor, cls): raise ValueError( f"The class ({ctor}) stored in checkpoint ({path}) does not seem to be " f"a subclass of `cls` ({cls})!" ) elif not issubclass(ctor, Checkpointable): raise ValueError( f"The class ({ctor}) stored in checkpoint ({path}) does not seem to be " "an implementer of the `Checkpointable` API!" ) # Construct the initial object (without any particular state). obj = ctor(*ctor_args, **ctor_kwargs) # Restore the state of the constructed object. obj.restore_from_path(path, filesystem=filesystem, **kwargs) # Return the new object. return obj @abc.abstractmethod def get_state( self, components: Optional[Union[str, Collection[str]]] = None, *, not_components: Optional[Union[str, Collection[str]]] = None, **kwargs, ) -> StateDict: """Returns the implementing class's current state as a dict. The returned dict must only contain msgpack-serializable data if you want to use the `AlgorithmConfig._msgpack_checkpoints` option. Consider returning your non msgpack-serializable data from the `Checkpointable.get_ctor_args_and_kwargs` method, instead. Args: components: An optional collection of string keys to be included in the returned state. This might be useful, if getting certain components of the state is expensive (e.g. reading/compiling the weights of a large NN) and at the same time, these components are not required by the caller. not_components: An optional list of string keys to be excluded in the returned state, even if the same string is part of `components`. This is useful to get the complete state of the class, except one or a few components. kwargs: Forward-compatibility kwargs. Returns: The current state of the implementing class (or only the `components` specified, w/o those in `not_components`). """ @abc.abstractmethod def set_state(self, state: StateDict) -> None: """Sets the implementing class' state to the given state dict. If component keys are missing in `state`, these components of the implementing class will not be updated/set. Args: state: The state dict to restore the state from. Maps component keys to the corresponding subcomponent's own state. """ @abc.abstractmethod def get_ctor_args_and_kwargs(self) -> Tuple[Tuple, Dict[str, Any]]: """Returns the args/kwargs used to create `self` from its constructor. Returns: A tuple of the args (as a tuple) and kwargs (as a Dict[str, Any]) used to construct `self` from its class constructor. """ @OverrideToImplementCustomLogic_CallToSuperRecommended def get_metadata(self) -> Dict: """Returns JSON writable metadata further describing the implementing class. Note that this metadata is NOT part of any state and is thus NOT needed to restore the state of a Checkpointable instance from a directory. Rather, the metadata will be written into `self.METADATA_FILE_NAME` when calling `self.save_to_path()` for the user's convenience. Returns: A JSON-encodable dict of metadata information. """ return { "class_and_ctor_args_file": self.CLASS_AND_CTOR_ARGS_FILE_NAME, "state_file": self.STATE_FILE_NAME, "ray_version": ray.__version__, "ray_commit": ray.__commit__, } def get_checkpointable_components(self) -> List[Tuple[str, "Checkpointable"]]: """Returns the implementing class's own Checkpointable subcomponents. Returns: A list of 2-tuples (name, subcomponent) describing the implementing class' subcomponents, all of which have to be `Checkpointable` themselves and whose state is therefore written into subdirectories (rather than the main state file (self.STATE_FILE_NAME) when calling `self.save_to_path()`). """ return [] def _check_component(self, name, components, not_components) -> bool: """Returns True if a component should be checkpointed. Args: name: The checkpoint name. components: A list of components that should be checkpointed. non_components: A list of components that should not be checkpointed. Returns: True, if the component should be checkpointed and otherwise False. """ comp_list = force_list(components) not_comp_list = force_list(not_components) if ( components is None or any(c.startswith(name + "/") for c in comp_list) or name in comp_list ) and (not_components is None or name not in not_comp_list): return True return False def _get_subcomponents(self, name, components): if components is None: return None components = force_list(components) subcomponents = [] for comp in components: if comp.startswith(name + "/"): subcomponents.append(comp[len(name) + 1 :]) return None if not subcomponents else subcomponents def _restore_all_subcomponents_from_path( self, path, filesystem, only_comp_names=None, component=None, **kwargs ): for comp_name, comp in self.get_checkpointable_components(): if only_comp_names is not None and comp_name not in only_comp_names: continue # The value of the `component` argument for the upcoming # `[subcomponent].restore_from_path(.., component=..)` call. comp_arg = None if component is None: comp_dir = path / comp_name # If subcomponent's dir is not in path, ignore it and don't restore this # subcomponent's state from disk. if not _exists_at_fs_path(filesystem, comp_dir.as_posix()): continue else: comp_dir = path # `component` is a path that starts with `comp` -> Remove the name of # `comp` from the `component` arg in the upcoming call to `restore_..`. if component.startswith(comp_name + "/"): comp_arg = component[len(comp_name) + 1 :] # `component` has nothing to do with `comp` -> Skip. elif component != comp_name: continue # If component is an ActorManager, restore all the manager's healthy # actors' states from disk (even if they are on another node, in which case, # we'll sync checkpoint file(s) to the respective node). if isinstance(comp, FaultTolerantActorManager): head_node_ip = ray.util.get_node_ip_address() all_healthy_actors = comp.healthy_actor_ids() def _restore( w, _kwargs=MappingProxyType(kwargs), _path=comp_dir, _head_ip=head_node_ip, _comp_arg=comp_arg, ): import tempfile import ray worker_node_ip = ray.util.get_node_ip_address() # If the worker is on the same node as the head, load the checkpoint # directly from the path otherwise sync the checkpoint from the head # to the worker and load it from there. if worker_node_ip == _head_ip: w.restore_from_path(_path, component=_comp_arg, **_kwargs) else: with tempfile.TemporaryDirectory() as temp_dir: sync_dir_between_nodes( _head_ip, _path, worker_node_ip, temp_dir ) w.restore_from_path( temp_dir, component=_comp_arg, **_kwargs ) comp.foreach_actor(_restore, remote_actor_ids=all_healthy_actors) # Call `restore_from_path()` on local subcomponent, thereby passing in the # **kwargs. else: comp.restore_from_path( comp_dir, filesystem=filesystem, component=comp_arg, **kwargs ) def _exists_at_fs_path(fs: pyarrow.fs.FileSystem, path: str) -> bool: """Returns `True` if the path can be found in the filesystem.""" valid = fs.get_file_info(path) return valid.type != pyarrow.fs.FileType.NotFound def _is_dir(file_info: pyarrow.fs.FileInfo) -> bool: """Returns `True`, if the file info is from a directory.""" return file_info.type == pyarrow.fs.FileType.Directory @OldAPIStack def get_checkpoint_info( checkpoint: Union[str, Checkpoint_train, Checkpoint_tune], filesystem: Optional["pyarrow.fs.FileSystem"] = None, ) -> Dict[str, Any]: """Returns a dict with information about an Algorithm/Policy checkpoint. If the given checkpoint is a >=v1.0 checkpoint directory, try reading all information from the contained `rllib_checkpoint.json` file. Args: checkpoint: The checkpoint directory (str) or a Checkpoint object. filesystem: PyArrow FileSystem to use to access data at the `checkpoint`. If not specified, this is inferred from the URI scheme provided by `checkpoint`. Returns: A dict containing the keys: "type": One of "Policy" or "Algorithm". "checkpoint_version": A version tuple, e.g. v1.0, indicating the checkpoint version. This will help RLlib to remain backward compatible wrt. future Ray and checkpoint versions. "checkpoint_dir": The directory with all the checkpoint files in it. This might be the same as the incoming `checkpoint` arg. "state_file": The main file with the Algorithm/Policy's state information in it. This is usually a pickle-encoded file. "policy_ids": An optional set of PolicyIDs in case we are dealing with an Algorithm checkpoint. None if `checkpoint` is a Policy checkpoint. """ # Default checkpoint info. info = { "type": "Algorithm", "format": "cloudpickle", "checkpoint_version": CHECKPOINT_VERSION, "checkpoint_dir": None, "state_file": None, "policy_ids": None, "module_ids": None, } # `checkpoint` is a Checkpoint instance: Translate to directory and continue. if isinstance(checkpoint, (Checkpoint_train, Checkpoint_tune)): checkpoint = checkpoint.to_directory() if checkpoint and not filesystem: # Note the path needs to be a path that is relative to the # filesystem (e.g. `gs://tmp/...` -> `tmp/...`). filesystem, checkpoint = pyarrow.fs.FileSystem.from_uri(checkpoint) # Only here convert to a `Path` instance b/c otherwise # cloud path gets broken (i.e. 'gs://' -> 'gs:/'). checkpoint = pathlib.Path(checkpoint) # Checkpoint is dir. if _exists_at_fs_path(filesystem, checkpoint.as_posix()) and _is_dir( filesystem.get_file_info(checkpoint.as_posix()) ): info.update({"checkpoint_dir": str(checkpoint)}) # Figure out whether this is an older checkpoint format # (with a `checkpoint-\d+` file in it). file_info_list = filesystem.get_file_info( pyarrow.fs.FileSelector(checkpoint.as_posix(), recursive=False) ) for file_info in file_info_list: if file_info.is_file: if re.match("checkpoint-\\d+", file_info.base_name): info.update( { "checkpoint_version": version.Version("0.1"), "state_file": str(file_info.base_name), } ) return info # No old checkpoint file found. # If rllib_checkpoint.json file present, read available information from it # and then continue with the checkpoint analysis (possibly overriding further # information). if _exists_at_fs_path( filesystem, (checkpoint / "rllib_checkpoint.json").as_posix() ): # if (checkpoint / "rllib_checkpoint.json").is_file(): with filesystem.open_input_stream( (checkpoint / "rllib_checkpoint.json").as_posix() ) as f: # with open(checkpoint / "rllib_checkpoint.json") as f: rllib_checkpoint_info = json.load(fp=f) if "checkpoint_version" in rllib_checkpoint_info: rllib_checkpoint_info["checkpoint_version"] = version.Version( rllib_checkpoint_info["checkpoint_version"] ) info.update(rllib_checkpoint_info) else: # No rllib_checkpoint.json file present: Warn and continue trying to figure # out checkpoint info ourselves. if log_once("no_rllib_checkpoint_json_file"): logger.warning( "No `rllib_checkpoint.json` file found in checkpoint directory " f"{checkpoint}! Trying to extract checkpoint info from other files " f"found in that dir." ) # Policy checkpoint file found. for extension in ["pkl", "msgpck"]: if _exists_at_fs_path( filesystem, (checkpoint / ("policy_state." + extension)).as_posix() ): # if (checkpoint / ("policy_state." + extension)).is_file(): info.update( { "type": "Policy", "format": "cloudpickle" if extension == "pkl" else "msgpack", "checkpoint_version": CHECKPOINT_VERSION, "state_file": str(checkpoint / f"policy_state.{extension}"), } ) return info # Valid Algorithm checkpoint >v0 file found? format = None for extension in ["pkl", "msgpck", "msgpack"]: state_file = checkpoint / f"algorithm_state.{extension}" if ( _exists_at_fs_path(filesystem, state_file.as_posix()) and filesystem.get_file_info(state_file.as_posix()).is_file ): format = "cloudpickle" if extension == "pkl" else "msgpack" break if format is None: raise ValueError( "Given checkpoint does not seem to be valid! No file with the name " "`algorithm_state.[pkl|msgpack|msgpck]` (or `checkpoint-[0-9]+`) found." ) info.update( { "format": format, "state_file": str(state_file), } ) # Collect all policy IDs in the sub-dir "policies/". policies_dir = checkpoint / "policies" if _exists_at_fs_path(filesystem, policies_dir.as_posix()) and _is_dir( filesystem.get_file_info(policies_dir.as_posix()) ): policy_ids = set() file_info_list = filesystem.get_file_info( pyarrow.fs.FileSelector(policies_dir.as_posix(), recursive=False) ) for file_info in file_info_list: policy_ids.add(file_info.base_name) info.update({"policy_ids": policy_ids}) # Collect all module IDs in the sub-dir "learner/module_state/". modules_dir = ( checkpoint / COMPONENT_LEARNER_GROUP / COMPONENT_LEARNER / COMPONENT_RL_MODULE ) if _exists_at_fs_path(filesystem, checkpoint.as_posix()) and _is_dir( filesystem.get_file_info(modules_dir.as_posix()) ): module_ids = set() file_info_list = filesystem.get_file_info( pyarrow.fs.FileSelector(modules_dir.as_posix(), recursive=False) ) for file_info in file_info_list: # Only add subdirs (those are the ones where the RLModule data # is stored, not files (could be json metadata files). module_dir = modules_dir / file_info.base_name if _is_dir(filesystem.get_file_info(module_dir.as_posix())): module_ids.add(file_info.base_name) info.update({"module_ids": module_ids}) # Checkpoint is a file: Use as-is (interpreting it as old Algorithm checkpoint # version). elif ( _exists_at_fs_path(filesystem, checkpoint.as_posix()) and filesystem.get_file_info(checkpoint.as_posix()).is_file ): info.update( { "checkpoint_version": version.Version("0.1"), "checkpoint_dir": str(checkpoint.parent), "state_file": str(checkpoint), } ) else: raise ValueError( f"Given checkpoint ({str(checkpoint)}) not found! Must be a " "checkpoint directory (or a file for older checkpoint versions)." ) return info @OldAPIStack def convert_to_msgpack_checkpoint( checkpoint: Union[str, Checkpoint_train, Checkpoint_tune], msgpack_checkpoint_dir: str, ) -> str: """Converts an Algorithm checkpoint (pickle based) to a msgpack based one. Msgpack has the advantage of being python version independent. Args: checkpoint: The directory, in which to find the Algorithm checkpoint (pickle based). msgpack_checkpoint_dir: The directory, in which to create the new msgpack based checkpoint. Returns: The directory in which the msgpack checkpoint has been created. Note that this is the same as `msgpack_checkpoint_dir`. """ from ray.rllib.algorithms import Algorithm from ray.rllib.algorithms.algorithm_config import AlgorithmConfig from ray.rllib.core.rl_module import validate_module_id # Try to import msgpack and msgpack_numpy. msgpack = try_import_msgpack(error=True) # Restore the Algorithm using the python version dependent checkpoint. algo = Algorithm.from_checkpoint(checkpoint) state = algo.__getstate__() # Convert all code in state into serializable data. # Serialize the algorithm class. state["algorithm_class"] = serialize_type(state["algorithm_class"]) # Serialize the algorithm's config object. if not isinstance(state["config"], dict): state["config"] = state["config"].serialize() else: state["config"] = AlgorithmConfig._serialize_dict(state["config"]) # Extract policy states from worker state (Policies get their own # checkpoint sub-dirs). policy_states = {} if "worker" in state and "policy_states" in state["worker"]: policy_states = state["worker"].pop("policy_states", {}) # Policy mapping fn. state["worker"]["policy_mapping_fn"] = NOT_SERIALIZABLE # Is Policy to train function. state["worker"]["is_policy_to_train"] = NOT_SERIALIZABLE # Add RLlib checkpoint version (as string). state["checkpoint_version"] = str(CHECKPOINT_VERSION) # Write state (w/o policies) to disk. state_file = os.path.join(msgpack_checkpoint_dir, "algorithm_state.msgpck") with open(state_file, "wb") as f: msgpack.dump(state, f) # Write rllib_checkpoint.json. with open(os.path.join(msgpack_checkpoint_dir, "rllib_checkpoint.json"), "w") as f: json.dump( { "type": "Algorithm", "checkpoint_version": state["checkpoint_version"], "format": "msgpack", "state_file": state_file, "policy_ids": list(policy_states.keys()), "ray_version": ray.__version__, "ray_commit": ray.__commit__, }, f, ) # Write individual policies to disk, each in their own subdirectory. for pid, policy_state in policy_states.items(): # From here on, disallow policyIDs that would not work as directory names. validate_module_id(pid, error=True) policy_dir = os.path.join(msgpack_checkpoint_dir, "policies", pid) os.makedirs(policy_dir, exist_ok=True) policy = algo.get_policy(pid) policy.export_checkpoint( policy_dir, policy_state=policy_state, checkpoint_format="msgpack", ) # Release all resources used by the Algorithm. algo.stop() return msgpack_checkpoint_dir @OldAPIStack def convert_to_msgpack_policy_checkpoint( policy_checkpoint: Union[str, Checkpoint_train, Checkpoint_tune], msgpack_checkpoint_dir: str, ) -> str: """Converts a Policy checkpoint (pickle based) to a msgpack based one. Msgpack has the advantage of being python version independent. Args: policy_checkpoint: The directory, in which to find the Policy checkpoint (pickle based). msgpack_checkpoint_dir: The directory, in which to create the new msgpack based checkpoint. Returns: The directory in which the msgpack checkpoint has been created. Note that this is the same as `msgpack_checkpoint_dir`. """ from ray.rllib.policy.policy import Policy policy = Policy.from_checkpoint(policy_checkpoint) os.makedirs(msgpack_checkpoint_dir, exist_ok=True) policy.export_checkpoint( msgpack_checkpoint_dir, policy_state=policy.get_state(), checkpoint_format="msgpack", ) # Release all resources used by the Policy. del policy return msgpack_checkpoint_dir @PublicAPI def try_import_msgpack(error: bool = False): """Tries importing msgpack and msgpack_numpy and returns the patched msgpack module. Returns None if error is False and msgpack or msgpack_numpy is not installed. Raises an error, if error is True and the modules could not be imported. Args: error: Whether to raise an error if msgpack/msgpack_numpy cannot be imported. Returns: The `msgpack` module, with the msgpack_numpy module already patched in. This means you can already encde and decode numpy arrays with the returned module. Raises: ImportError: If error=True and msgpack/msgpack_numpy is not installed. """ try: import msgpack import msgpack_numpy # Make msgpack_numpy look like msgpack. msgpack_numpy.patch() return msgpack except Exception: if error: raise ImportError( "Could not import or setup msgpack and msgpack_numpy! " "Try running `pip install msgpack msgpack_numpy` first." )
Checkpointable
python
bokeh__bokeh
tests/unit/bokeh/embed/test_standalone.py
{ "start": 2488, "end": 6979 }
class ____: def test_return_type(self, test_plot: figure) -> None: r = bes.autoload_static(test_plot, CDN, "some/path") assert len(r) == 2 def test_script_attrs(self, test_plot: figure) -> None: bs4 = pytest.importorskip("bs4") _, tag = bes.autoload_static(test_plot, CDN, "some/path") html = bs4.BeautifulSoup(tag, "html.parser") scripts = html.find_all(name='script') assert len(scripts) == 1 attrs = scripts[0].attrs assert set(attrs) == {"src", "id"} assert attrs["src"] == "some/path" @pytest.mark.selenium def test_by_css_selector(self) -> None: # Should match upstream, this is to avoid importing it pytest.importorskip("selenium") from selenium.webdriver.common.by import By assert By.CSS_SELECTOR == CSS_SELECTOR @pytest.mark.parametrize("version", ["1.4.0rc1", "2.0.0dev3"]) @pytest.mark.selenium def test_js_dev_cdn(self, version: str, monkeypatch: pytest.MonkeyPatch, driver: WebDriver, test_file_path_and_url: tuple[str, str], test_plot: figure) -> None: monkeypatch.setattr(buv, "__version__", "1.4.0rc1") monkeypatch.setattr(resources, "__version__", "1.4.0rc1") js, tag = bes.autoload_static(test_plot, CDN, "some/path") page = PAGE.render(js=js, tag=tag) path, url = test_file_path_and_url with open(path, "w") as f: f.write(page) driver.get(url) scripts = driver.find_elements(CSS_SELECTOR, 'head script') assert len(scripts) == 5 for script in scripts: assert script.get_attribute("crossorigin") is None assert script.get_attribute("integrity") == "" @pytest.mark.selenium def test_js_release_cdn(self, monkeypatch: pytest.MonkeyPatch, driver: WebDriver, test_file_path_and_url: tuple[str, str], test_plot: figure) -> None: monkeypatch.setattr(buv, "__version__", "2.0.0") monkeypatch.setattr(resources, "__version__", "2.0.0") r = CDN.clone() # Skip bokeh-mathjax for older versions r.components.remove("bokeh-mathjax") js, tag = bes.autoload_static(test_plot, r, "some/path") page = PAGE.render(js=js, tag=tag) path, url = test_file_path_and_url with open(path, "w") as f: f.write(page) driver.get(url) scripts = driver.find_elements(CSS_SELECTOR, 'head script') for x in scripts: print(x.get_attribute("src")) assert len(scripts) == 4 for script in scripts: assert script.get_attribute("crossorigin") is None assert script.get_attribute("integrity") == "" @pytest.mark.selenium def test_js_release_dev_cdn(self, monkeypatch: pytest.MonkeyPatch, driver: WebDriver, test_file_path_and_url: tuple[str, str], test_plot: figure) -> None: monkeypatch.setattr(buv, "__version__", "2.0.0-foo") monkeypatch.setattr(resources, "__version__", "2.0.0-foo") js, tag = bes.autoload_static(test_plot, CDN, "some/path") page = PAGE.render(js=js, tag=tag) path, url = test_file_path_and_url with open(path, "w") as f: f.write(page) driver.get(url) scripts = driver.find_elements(CSS_SELECTOR, 'head script') for x in scripts: print(x.get_attribute("src")) assert len(scripts) == 5 for script in scripts: assert script.get_attribute("crossorigin") is None assert script.get_attribute("integrity") == "" @pytest.mark.selenium def test_js_release_server(self, monkeypatch: pytest.MonkeyPatch, driver: WebDriver, test_file_path_and_url: tuple[str, str], test_plot: figure) -> None: monkeypatch.setattr(buv, "__version__", "2.0.0") monkeypatch.setattr(resources, "__version__", "2.0.0") js, tag = bes.autoload_static(test_plot, resources.Resources(mode="server"), "some/path") page = PAGE.render(js=js, tag=tag) path, url = test_file_path_and_url with open(path, "w") as f: f.write(page) driver.get(url) scripts = driver.find_elements(CSS_SELECTOR, 'head script') assert len(scripts) == 5 for script in scripts: assert script.get_attribute("crossorigin") is None assert script.get_attribute("integrity") == ""
Test_autoload_static
python
pytorch__pytorch
test/test_cuda_sanitizer.py
{ "start": 16552, "end": 21122 }
class ____(TestCase): def setUp(self): super().setUp() self.handler = csan.EventHandler() def test_ensure_exists(self): ARG = 0 for func, out in [ ( self.handler._handle_event_deletion, f"Found Event with id: {ARG}, but no matching event " "creation in the trace. Backfilling the trace now. " "Perhaps the sanitizer was enabled after some torch operations?", ), ( self.handler._handle_memory_deallocation, f"Found tensor with pointer: {ARG}, but no matching tensor " "allocation in the trace. Backfilling the trace now. " "Perhaps the sanitizer was enabled after some torch operations?", ), ]: with self.subTest(func=func, out=out): with self.assertLogs() as captured: func(ARG) self.assertEqual(captured.records[0].getMessage(), out) def test_ensure_does_not_exist(self): ARG = 0 self.handler._handle_event_creation(ARG) self.handler._handle_stream_creation(ARG) for func, out in [ ( self.handler._handle_event_creation, "Found duplicate event creation in the trace for event with " f"id: {ARG}. Assuming the trace for event deletion wasn't caught " "and backfilling it now. " "Perhaps the sanitizer was enabled after some torch operations?", ), ( self.handler._handle_stream_creation, "Found duplicate Stream creation in the trace for Stream with " f"id: {ARG}. PyTorch Streams are only created once, so this " "trace entry is ignored.", ), ]: with self.subTest(func=func, out=out): with self.assertLogs() as captured: func(ARG) self.assertEqual(captured.records[0].getMessage(), out) def test_error_message(self): current_access = csan.Access( type=csan.AccessType.WRITE, seq_num=1, stream=stream_id(1), operator="schema", aliases=["b"], is_output=True, stack_trace=traceback.StackSummary.from_list( [("file", 0, "name", "trace a")] ), ) previous_access = csan.Access( type=csan.AccessType.READ, seq_num=2, stream=stream_id(0), operator="schema", aliases=["a"], is_output=False, stack_trace=traceback.StackSummary.from_list( [("file", 0, "name", "trace b")] ), ) error = csan.UnsynchronizedAccessError( data_ptr=tensor_id(1), allocation_stack_trace=traceback.StackSummary.from_list( [("file", 0, "name", "alloc")] ), current_access=current_access, previous_access=previous_access, ) self.assertEqual( str(error), textwrap.dedent( """\ ============================ CSAN detected a possible data race on tensor with data pointer 1 Access by stream 1001 during kernel: schema writing to argument(s) b, and to the output With stack trace: File "file", line 0, in name trace a Previous access by stream 1000 during kernel: schema reading from argument(s) a With stack trace: File "file", line 0, in name trace b Tensor was allocated with stack trace: File "file", line 0, in name alloc """ ), ) def test_subclass(self): class MyT(torch.Tensor): def __new__(cls, data): new_data = data.clone() return new_data.as_subclass(cls) try: csan.enable_cuda_sanitizer() # These two tests ensure that subclass creation # happens smoothly under the mode used by csan TwoTensor(torch.rand(2), torch.rand(2)) MyT(torch.rand(2)) finally: csan.cuda_sanitizer.disable() if __name__ == "__main__": run_tests()
TestMessages
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/ray.py
{ "start": 16399, "end": 18260 }
class ____(RayBaseOperator): """ Delete Ray cluster. :param project_id: Required. The ID of the Google Cloud project that the service belongs to. :param location: Required. The ID of the Google Cloud region that the service belongs to. :param cluster_id: Cluster resource ID. :param gcp_conn_id: The connection ID to use connecting to Google Cloud. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). """ template_fields: Sequence[str] = tuple({"cluster_id"} | set(RayBaseOperator.template_fields)) def __init__( self, cluster_id: str, *args, **kwargs, ) -> None: super().__init__(*args, **kwargs) self.cluster_id = cluster_id def execute(self, context: Context): try: self.log.info("Deleting Ray cluster: %s", self.cluster_id) self.hook.delete_ray_cluster( project_id=self.project_id, location=self.location, cluster_id=self.cluster_id, ) self.log.info("Ray cluster was deleted.") except NotFound as not_found_err: self.log.info("The Ray cluster ID %s does not exist.", self.cluster_id) raise AirflowException(not_found_err)
DeleteRayClusterOperator