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
pennersr__django-allauth
tests/apps/socialaccount/providers/clever/tests.py
{ "start": 240, "end": 1540 }
class ____(OAuth2TestsMixin, TestCase): provider_id = CleverProvider.id def get_mocked_response(self): return [ MockedResponse( HTTPStatus.OK, """{ "type": "user", "data": { "id": "62027798269867124d10259e", "district": "6202763c8243d2100123dae5", "type": "user", "authorized_by": "district" }, "links": [ { "rel": "self", "uri": "/me" }, { "rel": "canonical", "uri": "/v3.0/users/62027798269867124d10259e" }, { "rel": "district", "uri": "/v3.0/districts/6202763c8243d2100123dae5" } ] }""", ), MockedResponse( HTTPStatus.OK, """{ "data": { "id": "62027798269867124d10259e", "roles": { "district_admin": {}, "contact": {} } } }""", ), ] def get_expected_to_str(self): return "Clever"
CleverOAuth2Tests
python
davidhalter__jedi
jedi/inference/value/instance.py
{ "start": 2375, "end": 3100 }
class ____(BaseFunctionExecutionContext): def __init__(self, instance, value): super().__init__(value) self.instance = instance def get_filters(self, until_position=None, origin_scope=None): yield AnonymousMethodExecutionFilter( self.instance, self, self._value, until_position=until_position, origin_scope=origin_scope, ) def get_param_names(self): param_names = list(self._value.get_param_names()) # set the self name param_names[0] = InstanceExecutedParamName( self.instance, self._value, param_names[0].tree_name ) return param_names
AnonymousMethodExecutionContext
python
pydantic__pydantic
tests/test_forward_ref.py
{ "start": 40261, "end": 40715 }
class ____[T](TypedDict): t: 'T' """ ) with pytest.raises(ValidationError): TypeAdapter(mod_1.TD[str]).validate_python({'t': 1}) @pytest.mark.skipif(sys.version_info < (3, 12), reason='Test related to PEP 695 syntax.') def test_pep695_generics_class_locals_take_priority(create_module) -> None: # As per https://github.com/python/cpython/pull/120272 mod_1 = create_module( """ from pydantic import BaseModel
TD
python
getsentry__sentry
tests/sentry_plugins/trello/test_plugin.py
{ "start": 498, "end": 1663 }
class ____(TrelloPluginTestBase): def test_get_issue_label(self) -> None: group = self.create_group(message="Hello world", culprit="foo.bar") # test new and old format assert self.plugin.get_issue_label(group, "rPPDb") == "Trello-rPPDb" assert ( self.plugin.get_issue_label(group, "5dafd/https://trello.com/c/rPPDb/75-title") == "Trello-5dafd" ) def test_get_issue_url(self) -> None: group = self.create_group(message="Hello world", culprit="foo.bar") assert self.plugin.get_issue_url(group, "rPPDb") == "https://trello.com/c/rPPDb" assert ( self.plugin.get_issue_url(group, "5dafd/https://trello.com/c/rPPDb/75-title") == "https://trello.com/c/rPPDb/75-title" ) def test_is_configured(self) -> None: assert self.plugin.is_configured(self.project) is False self.plugin.set_option("token", "7c8951d1", self.project) assert self.plugin.is_configured(self.project) is False self.plugin.set_option("key", "39g", self.project) assert self.plugin.is_configured(self.project) is True
TrelloPluginTest
python
walkccc__LeetCode
solutions/2133. Check if Every Row and Column Contains All Numbers/2133.py
{ "start": 0, "end": 195 }
class ____: def checkValid(self, matrix: list[list[int]]) -> bool: return all(min(len(set(row)), len(set(col))) == len(matrix) for row, col in zip(matrix, zip(*matrix)))
Solution
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/triggers/test_lambda_function.py
{ "start": 925, "end": 1918 }
class ____: def test_serialization(self): function_name = "test_function_name" function_arn = "test_function_arn" waiter_delay = 60 waiter_max_attempts = 30 aws_conn_id = "aws_default" trigger = LambdaCreateFunctionCompleteTrigger( function_name=function_name, function_arn=function_arn, waiter_delay=waiter_delay, waiter_max_attempts=waiter_max_attempts, aws_conn_id=aws_conn_id, ) classpath, kwargs = trigger.serialize() assert ( classpath == "airflow.providers.amazon.aws.triggers.lambda_function.LambdaCreateFunctionCompleteTrigger" ) assert kwargs == { "function_name": "test_function_name", "function_arn": "test_function_arn", "waiter_delay": 60, "waiter_max_attempts": 30, "aws_conn_id": "aws_default", }
TestLambdaCreateFunctionCompleteTrigger
python
getsentry__sentry
tests/sentry/api/test_data_secrecy.py
{ "start": 162, "end": 2456 }
class ____(APITestCase): # Picked an endpoint with OrganizationAndStaffPermission endpoint = "sentry-api-0-organization-projects" method = "get" def setUp(self) -> None: super().setUp() self.login_as(self.user) self.organization.flags.prevent_superuser_access = True self.organization.save() @with_feature("organizations:data-secrecy") def test_superuser_no_access(self) -> None: superuser = self.create_user(is_superuser=True) self.login_as(superuser, superuser=True) # superuser cannot access orgs with data secrecy with self.settings(SENTRY_SELF_HOSTED=False): self.get_error_response(self.organization.slug, status_code=401) @with_feature("organizations:data-secrecy") def test_superuser_has_access(self) -> None: self.organization.flags.prevent_superuser_access = False self.organization.save() superuser = self.create_user(is_superuser=True) self.login_as(superuser, superuser=True) # superuser can access orgs without data secrecy with self.settings(SENTRY_SELF_HOSTED=False): self.get_success_response(self.organization.slug) def test_non_member_no_access(self) -> None: self.login_as(self.create_user()) with self.settings(SENTRY_SELF_HOSTED=False): self.get_error_response(self.organization.slug, status_code=403) def test_member_has_access(self) -> None: with self.settings(SENTRY_SELF_HOSTED=False): self.get_success_response(self.organization.slug) @with_feature("organizations:data-secrecy") @override_options({"staff.ga-rollout": True}) def test_admin_access_when_superuser_no_access(self) -> None: # When the superuser has no access, the admin should also still work superuser = self.create_user(is_superuser=True) self.login_as(superuser, superuser=True) with self.settings(SENTRY_SELF_HOSTED=False): self.get_error_response(self.organization.slug, status_code=401) admin = self.create_user(is_staff=True) self.login_as(admin, staff=True) with self.settings(SENTRY_SELF_HOSTED=False): self.get_success_response(self.organization.slug)
DataSecrecyTestCase
python
spack__spack
lib/spack/spack/oci/opener.py
{ "start": 5999, "end": 7342 }
class ____(NamedTuple): username: str password: str @property def basic_auth_header(self) -> str: encoded = base64.b64encode(f"{self.username}:{self.password}".encode("utf-8")).decode( "utf-8" ) return f"Basic {encoded}" def _get_bearer_challenge(challenges: List[Challenge]) -> Optional[RealmServiceScope]: """Return the realm/service/scope for a Bearer auth challenge, or None if not found.""" challenge = next((c for c in challenges if c.scheme == "Bearer"), None) if challenge is None: return None # Get realm / service / scope from challenge realm = next((v for k, v in challenge.params if k == "realm"), None) service = next((v for k, v in challenge.params if k == "service"), None) scope = next((v for k, v in challenge.params if k == "scope"), None) if realm is None or service is None or scope is None: return None return RealmServiceScope(realm, service, scope) def _get_basic_challenge(challenges: List[Challenge]) -> Optional[str]: """Return the realm for a Basic auth challenge, or None if not found.""" challenge = next((c for c in challenges if c.scheme == "Basic"), None) if challenge is None: return None return next((v for k, v in challenge.params if k == "realm"), None)
UsernamePassword
python
kubernetes-client__python
kubernetes/client/models/v1_network_policy_ingress_rule.py
{ "start": 383, "end": 5852 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { '_from': 'list[V1NetworkPolicyPeer]', 'ports': 'list[V1NetworkPolicyPort]' } attribute_map = { '_from': 'from', 'ports': 'ports' } def __init__(self, _from=None, ports=None, local_vars_configuration=None): # noqa: E501 """V1NetworkPolicyIngressRule - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self.__from = None self._ports = None self.discriminator = None if _from is not None: self._from = _from if ports is not None: self.ports = ports @property def _from(self): """Gets the _from of this V1NetworkPolicyIngressRule. # noqa: E501 from is a list of sources which should be able to access the pods selected for this rule. Items in this list are combined using a logical OR operation. If this field is empty or missing, this rule matches all sources (traffic not restricted by source). If this field is present and contains at least one item, this rule allows traffic only if the traffic matches at least one item in the from list. # noqa: E501 :return: The _from of this V1NetworkPolicyIngressRule. # noqa: E501 :rtype: list[V1NetworkPolicyPeer] """ return self.__from @_from.setter def _from(self, _from): """Sets the _from of this V1NetworkPolicyIngressRule. from is a list of sources which should be able to access the pods selected for this rule. Items in this list are combined using a logical OR operation. If this field is empty or missing, this rule matches all sources (traffic not restricted by source). If this field is present and contains at least one item, this rule allows traffic only if the traffic matches at least one item in the from list. # noqa: E501 :param _from: The _from of this V1NetworkPolicyIngressRule. # noqa: E501 :type: list[V1NetworkPolicyPeer] """ self.__from = _from @property def ports(self): """Gets the ports of this V1NetworkPolicyIngressRule. # noqa: E501 ports is a list of ports which should be made accessible on the pods selected for this rule. Each item in this list is combined using a logical OR. If this field is empty or missing, this rule matches all ports (traffic not restricted by port). If this field is present and contains at least one item, then this rule allows traffic only if the traffic matches at least one port in the list. # noqa: E501 :return: The ports of this V1NetworkPolicyIngressRule. # noqa: E501 :rtype: list[V1NetworkPolicyPort] """ return self._ports @ports.setter def ports(self, ports): """Sets the ports of this V1NetworkPolicyIngressRule. ports is a list of ports which should be made accessible on the pods selected for this rule. Each item in this list is combined using a logical OR. If this field is empty or missing, this rule matches all ports (traffic not restricted by port). If this field is present and contains at least one item, then this rule allows traffic only if the traffic matches at least one port in the list. # noqa: E501 :param ports: The ports of this V1NetworkPolicyIngressRule. # noqa: E501 :type: list[V1NetworkPolicyPort] """ self._ports = ports def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1NetworkPolicyIngressRule): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1NetworkPolicyIngressRule): return True return self.to_dict() != other.to_dict()
V1NetworkPolicyIngressRule
python
faif__python-patterns
patterns/behavioral/visitor.py
{ "start": 773, "end": 1698 }
class ____: def visit(self, node: Union[A, C, B], *args, **kwargs) -> None: meth = None for cls in node.__class__.__mro__: meth_name = "visit_" + cls.__name__ meth = getattr(self, meth_name, None) if meth: break if not meth: meth = self.generic_visit return meth(node, *args, **kwargs) def generic_visit(self, node: A, *args, **kwargs) -> None: print("generic_visit " + node.__class__.__name__) def visit_B(self, node: Union[C, B], *args, **kwargs) -> None: print("visit_B " + node.__class__.__name__) def main(): """ >>> a, b, c = A(), B(), C() >>> visitor = Visitor() >>> visitor.visit(a) 'generic_visit A' >>> visitor.visit(b) 'visit_B B' >>> visitor.visit(c) 'visit_B C' """ if __name__ == "__main__": import doctest doctest.testmod()
Visitor
python
spyder-ide__spyder
spyder/plugins/pylint/tests/test_pylint.py
{ "start": 2063, "end": 12212 }
class ____(QMainWindow): sig_editor_focus_changed = Signal(str) def __init__(self): super().__init__(None) self.editor = Mock() self.editor.sig_editor_focus_changed = self.sig_editor_focus_changed self.projects = MagicMock() PLUGIN_REGISTRY.plugin_registry = { 'editor': self.editor, 'projects': self.projects } def get_plugin(self, plugin_name, error=True): return PLUGIN_REGISTRY.get_plugin(plugin_name) @pytest.fixture def pylint_plugin(mocker, qtbot): main_window = MainWindowMock() qtbot.addWidget(main_window) main_window.resize(640, 480) main_window.projects.get_active_project_path = mocker.MagicMock( return_value=None) main_window.show() plugin = Pylint(parent=main_window, configuration=CONF) plugin._register() plugin.set_conf("history_filenames", []) # This avoids possible errors in our tests for not being available while # running them. plugin.set_conf('executable', get_python_executable(), section='main_interpreter') widget = plugin.get_widget() widget.resize(640, 480) widget.filecombo.clear() widget.show() yield plugin widget.close() plugin.on_close() @pytest.fixture def pylintrc_search_paths(tmp_path_factory): """Construct temporary .pylintrc search paths.""" search_paths = {dir_name: str(tmp_path_factory.mktemp(dir_name)) for dir_name in DIR_LIST} return search_paths @pytest.fixture def pylint_test_script(pylintrc_search_paths): """Write a script for testing Pylint to a temporary directory.""" script_path = osp.join( pylintrc_search_paths[SCRIPT_DIR], "test_script.py") with open(script_path, mode="w", encoding="utf-8", newline="\n") as script_file: script_file.write(PYLINT_TEST_SCRIPT) return script_path @pytest.fixture def pylint_test_scripts(pylintrc_search_paths): def _pylint_test_scripts(filenames): """Write scripts for testing Pylint to a temporary directory.""" script_paths = [] for filename in filenames: script_path = osp.join( pylintrc_search_paths[SCRIPT_DIR], filename) with open(script_path, mode="w", encoding="utf-8", newline="\n") as script_file: script_file.write(PYLINT_TEST_SCRIPT) script_paths.append(script_path) return script_paths return _pylint_test_scripts @pytest.fixture( params=[ [], [SCRIPT_DIR], [WORKING_DIR], [PROJECT_DIR], [HOME_DIR], [SCRIPT_DIR, HOME_DIR], [WORKING_DIR, PROJECT_DIR], [SCRIPT_DIR, PROJECT_DIR], [PROJECT_DIR, HOME_DIR], [SCRIPT_DIR, WORKING_DIR, PROJECT_DIR, HOME_DIR]], ids=["None", "Script", "Working", "Project", "Home", "Script & Home", "Working & Project", "Script & Working", "Project & Home", "All"]) def pylintrc_files(pylintrc_search_paths, request): """Store test .pylintrc files at the paths and determine the result.""" search_paths = pylintrc_search_paths # Determine the bad names that should be reported pylintrc_locations = request.param bad_names = [ALL_DIR] for search_path_name, search_path in search_paths.items(): if search_path_name in pylintrc_locations: expected_path = osp.join(search_path, PYLINTRC_FILENAME) bad_names += [search_path_name] break else: expected_path = None bad_names = [NO_DIR] # Store the selected pylintrc files at the designated paths for location in pylintrc_locations: pylintrc_test_contents = PYLINTRC_TEST_CONTENTS.format( bad_names=", ".join([location, ALL_DIR])) pylintrc_path = osp.join(search_paths[location], PYLINTRC_FILENAME) with open(pylintrc_path, mode="w", encoding="utf-8", newline="\n") as rc_file: rc_file.write(pylintrc_test_contents) print(search_paths) print(expected_path) print(bad_names) return search_paths, expected_path, bad_names def test_get_pylintrc_path(pylintrc_files, mocker): """Test that get_pylintrc_path finds the expected one in the hierarchy.""" search_paths, expected_path, __ = pylintrc_files mocker.patch("os.path.expanduser", return_value=search_paths[HOME_DIR]) actual_path = get_pylintrc_path( search_paths=list(search_paths.values()), home_path=search_paths[HOME_DIR], ) assert actual_path == expected_path def test_pylint_widget_noproject(pylint_plugin, pylint_test_script, mocker, qtbot): """Test that pylint works without errors with no project open.""" pylint_plugin.start_code_analysis(filename=pylint_test_script) pylint_widget = pylint_plugin.get_widget() qtbot.waitUntil( lambda: pylint_widget.get_data(pylint_test_script)[1] is not None, timeout=10000) pylint_data = pylint_widget.get_data(filename=pylint_test_script) print(pylint_data) assert pylint_data assert pylint_data[0] is not None assert pylint_data[1] is not None @flaky(max_runs=3) def test_pylint_widget_pylintrc( pylint_plugin, pylint_test_script, pylintrc_files, mocker, qtbot): """Test that entire pylint widget gets results depending on pylintrc.""" search_paths, __, bad_names = pylintrc_files mocker.patch("os.path.expanduser", return_value=search_paths[HOME_DIR]) mocker.patch("spyder.plugins.pylint.main_widget.getcwd_or_home", return_value=search_paths[WORKING_DIR]) mocker.patch("spyder.plugins.pylint.main_widget.osp.expanduser", return_value=search_paths[HOME_DIR]) pylint_plugin.set_conf("project_dir", search_paths[PROJECT_DIR]) pylint_widget = pylint_plugin.get_widget() pylint_plugin.start_code_analysis(filename=pylint_test_script) qtbot.waitUntil( lambda: pylint_widget.get_data(pylint_test_script)[1] is not None, timeout=5000) pylint_data = pylint_widget.get_data(filename=pylint_test_script) print(pylint_data) assert pylint_data conventions = pylint_data[1][3]["C:"] assert conventions assert len(conventions) == len(bad_names) assert all([sum([bad_name in message[2] for message in conventions]) == 1 for bad_name in bad_names]) def test_pylint_max_history_conf(pylint_plugin, pylint_test_scripts): """Regression test for checking max_entries configuration. For further information see spyder-ide/spyder#12884 """ pylint_widget = pylint_plugin.get_widget() script_0, script_1, script_2 = pylint_test_scripts( ["test_script_{}.py".format(n) for n in range(3)]) # Change the max_entry to 2 assert pylint_widget.filecombo.count() == 0 pylint_plugin.change_history_depth(2) assert pylint_plugin.get_conf('max_entries') == 2 assert pylint_widget.get_conf('max_entries') == 2 # Call to set_filename pylint_widget.set_filename(filename=script_0) assert pylint_widget.filecombo.count() == 1 # Add to more filenames pylint_widget.set_filename(filename=script_1) pylint_widget.set_filename(filename=script_2) assert pylint_widget.filecombo.count() == 2 assert 'test_script_2.py' in pylint_widget.curr_filenames[0] assert 'test_script_1.py' in pylint_widget.curr_filenames[1] # Change the max entry to 1 pylint_plugin.change_history_depth(1) assert pylint_widget.filecombo.count() == 1 assert 'test_script_2.py' in pylint_widget.curr_filenames[0] @flaky(max_runs=3) @pytest.mark.parametrize("custom_interpreter", [True, False]) @pytest.mark.skipif( not is_conda_env(sys.prefix), reason='Only works with Anaconda' ) @pytest.mark.skipif(not running_in_ci(), reason='Only works on CIs') def test_custom_interpreter(pylint_plugin, tmp_path, qtbot, custom_interpreter): """Test that the plugin works as expected with custom interpreters.""" # Get conda env to use conda_env = get_list_conda_envs()['Conda: jedi-test-env'][0] # Set custom interpreter if custom_interpreter: pylint_plugin.set_conf('default', False, section='main_interpreter') pylint_plugin.set_conf('executable', conda_env, section='main_interpreter') else: pylint_plugin.set_conf('default', True, section='main_interpreter') pylint_plugin.set_conf('executable', get_python_executable(), section='main_interpreter') # Write test code to file file_path = tmp_path / 'test_custom_interpreter.py' file_path.write_text('import flask') # Run analysis and get its data pylint_widget = pylint_plugin.get_widget() pylint_plugin.start_code_analysis(filename=str(file_path)) qtbot.waitUntil( lambda: pylint_widget.get_data(file_path)[1] is not None, timeout=5000) pylint_data = pylint_widget.get_data(filename=str(file_path)) # Assert no import errors are reported for custom interpreters errors = pylint_data[1][3]["E:"] if custom_interpreter: assert not errors else: assert errors def test_get_environment(mocker): """Test that the environment variables depend on the OS.""" if os.name == 'nt': mocker.patch( "spyder.plugins.pylint.main_widget.is_conda_env", return_value=False ) mocker.patch( "spyder.plugins.pylint.main_widget.get_home_dir", return_value='' ) expected_vars = { "nt": ["APPDATA", "PYTHONIOENCODING", "PYTHONPATH", "USERPROFILE"], "posix": ["PYTHONIOENCODING", "PYTHONPATH"] } process_environment = Pylint.WIDGET_CLASS.get_environment( pythonpath_manager_values=["project_dir"] ) assert process_environment.keys() == expected_vars[os.name] if __name__ == "__main__": pytest.main([osp.basename(__file__), '-vv', '-rw'])
MainWindowMock
python
scipy__scipy
scipy/optimize/_dual_annealing.py
{ "start": 8776, "end": 15609 }
class ____: """ Class that implements within a Markov chain the strategy for location acceptance and local search decision making. Parameters ---------- acceptance_param : float Parameter for acceptance distribution. It is used to control the probability of acceptance. The lower the acceptance parameter, the smaller the probability of acceptance. Default value is -5.0 with a range (-1e4, -5]. visit_dist : VisitingDistribution Instance of `VisitingDistribution` class. func_wrapper : ObjectiveFunWrapper Instance of `ObjectiveFunWrapper` class. minimizer_wrapper: LocalSearchWrapper Instance of `LocalSearchWrapper` class. rand_gen : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional If `seed` is None (or `np.random`), the `numpy.random.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with `seed`. If `seed` is already a ``Generator`` or ``RandomState`` instance then that instance is used. energy_state: EnergyState Instance of `EnergyState` class. """ def __init__(self, acceptance_param, visit_dist, func_wrapper, minimizer_wrapper, rand_gen, energy_state): # Local strategy chain minimum energy and location self.emin = energy_state.current_energy self.xmin = np.array(energy_state.current_location) # Global optimizer state self.energy_state = energy_state # Acceptance parameter self.acceptance_param = acceptance_param # Visiting distribution instance self.visit_dist = visit_dist # Wrapper to objective function self.func_wrapper = func_wrapper # Wrapper to the local minimizer self.minimizer_wrapper = minimizer_wrapper self.not_improved_idx = 0 self.not_improved_max_idx = 1000 self._rand_gen = rand_gen self.temperature_step = 0 self.K = 100 * len(energy_state.current_location) def accept_reject(self, j, e, x_visit): r = self._rand_gen.uniform() pqv_temp = 1.0 - ((1.0 - self.acceptance_param) * (e - self.energy_state.current_energy) / self.temperature_step) if pqv_temp <= 0.: pqv = 0. else: pqv = np.exp(np.log(pqv_temp) / ( 1. - self.acceptance_param)) if r <= pqv: # We accept the new location and update state self.energy_state.update_current(e, x_visit) self.xmin = np.copy(self.energy_state.current_location) # No improvement for a long time if self.not_improved_idx >= self.not_improved_max_idx: if j == 0 or self.energy_state.current_energy < self.emin: self.emin = self.energy_state.current_energy self.xmin = np.copy(self.energy_state.current_location) def run(self, step, temperature): self.temperature_step = temperature / float(step + 1) self.not_improved_idx += 1 for j in range(self.energy_state.current_location.size * 2): if j == 0: if step == 0: self.energy_state_improved = True else: self.energy_state_improved = False x_visit = self.visit_dist.visiting( self.energy_state.current_location, j, temperature) # Calling the objective function e = self.func_wrapper.fun(x_visit) if e < self.energy_state.current_energy: # We have got a better energy value self.energy_state.update_current(e, x_visit) if e < self.energy_state.ebest: val = self.energy_state.update_best(e, x_visit, 0) if val is not None: if val: return val self.energy_state_improved = True self.not_improved_idx = 0 else: # We have not improved but do we accept the new location? self.accept_reject(j, e, x_visit) if self.func_wrapper.nfev >= self.func_wrapper.maxfun: return ('Maximum number of function call reached ' 'during annealing') # End of StrategyChain loop def local_search(self): # Decision making for performing a local search # based on strategy chain results # If energy has been improved or no improvement since too long, # performing a local search with the best strategy chain location if self.energy_state_improved: # Global energy has improved, let's see if LS improves further e, x = self.minimizer_wrapper.local_search(self.energy_state.xbest, self.energy_state.ebest) if e < self.energy_state.ebest: self.not_improved_idx = 0 val = self.energy_state.update_best(e, x, 1) if val is not None: if val: return val self.energy_state.update_current(e, x) if self.func_wrapper.nfev >= self.func_wrapper.maxfun: return ('Maximum number of function call reached ' 'during local search') # Check probability of a need to perform a LS even if no improvement do_ls = False if self.K < 90 * len(self.energy_state.current_location): pls = np.exp(self.K * ( self.energy_state.ebest - self.energy_state.current_energy) / self.temperature_step) if pls >= self._rand_gen.uniform(): do_ls = True # Global energy not improved, let's see what LS gives # on the best strategy chain location if self.not_improved_idx >= self.not_improved_max_idx: do_ls = True if do_ls: e, x = self.minimizer_wrapper.local_search(self.xmin, self.emin) self.xmin = np.copy(x) self.emin = e self.not_improved_idx = 0 self.not_improved_max_idx = self.energy_state.current_location.size if e < self.energy_state.ebest: val = self.energy_state.update_best( self.emin, self.xmin, 2) if val is not None: if val: return val self.energy_state.update_current(e, x) if self.func_wrapper.nfev >= self.func_wrapper.maxfun: return ('Maximum number of function call reached ' 'during dual annealing')
StrategyChain
python
networkx__networkx
networkx/algorithms/shortest_paths/tests/test_weighted.py
{ "start": 739, "end": 3010 }
class ____: """Base class for test classes that test functions for computing shortest paths in weighted graphs. """ def setup_method(self): """Creates some graphs for use in the unit tests.""" cnlti = nx.convert_node_labels_to_integers self.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted") self.cycle = nx.cycle_graph(7) self.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph()) self.XG = nx.DiGraph() self.XG.add_weighted_edges_from( [ ("s", "u", 10), ("s", "x", 5), ("u", "v", 1), ("u", "x", 2), ("v", "y", 1), ("x", "u", 3), ("x", "v", 5), ("x", "y", 2), ("y", "s", 7), ("y", "v", 6), ] ) self.MXG = nx.MultiDiGraph(self.XG) self.MXG.add_edge("s", "u", weight=15) self.XG2 = nx.DiGraph() self.XG2.add_weighted_edges_from( [ [1, 4, 1], [4, 5, 1], [5, 6, 1], [6, 3, 1], [1, 3, 50], [1, 2, 100], [2, 3, 100], ] ) self.XG3 = nx.Graph() self.XG3.add_weighted_edges_from( [[0, 1, 2], [1, 2, 12], [2, 3, 1], [3, 4, 5], [4, 5, 1], [5, 0, 10]] ) self.XG4 = nx.Graph() self.XG4.add_weighted_edges_from( [ [0, 1, 2], [1, 2, 2], [2, 3, 1], [3, 4, 1], [4, 5, 1], [5, 6, 1], [6, 7, 1], [7, 0, 1], ] ) self.MXG4 = nx.MultiGraph(self.XG4) self.MXG4.add_edge(0, 1, weight=3) self.G = nx.DiGraph() # no weights self.G.add_edges_from( [ ("s", "u"), ("s", "x"), ("u", "v"), ("u", "x"), ("v", "y"), ("x", "u"), ("x", "v"), ("x", "y"), ("y", "s"), ("y", "v"), ] )
WeightedTestBase
python
explosion__spaCy
spacy/pipeline/spancat.py
{ "start": 2080, "end": 5386 }
class ____(Protocol): def __call__(self, docs: Iterable[Doc], *, ops: Optional[Ops] = None) -> Ragged: ... def ngram_suggester( docs: Iterable[Doc], sizes: List[int], *, ops: Optional[Ops] = None ) -> Ragged: if ops is None: ops = get_current_ops() spans = [] lengths = [] for doc in docs: starts = ops.xp.arange(len(doc), dtype="i") starts = starts.reshape((-1, 1)) length = 0 for size in sizes: if size <= len(doc): starts_size = starts[: len(doc) - (size - 1)] spans.append(ops.xp.hstack((starts_size, starts_size + size))) length += spans[-1].shape[0] if spans: assert spans[-1].ndim == 2, spans[-1].shape lengths.append(length) lengths_array = ops.asarray1i(lengths) if len(spans) > 0: output = Ragged(ops.xp.vstack(spans), lengths_array) else: output = Ragged(ops.xp.zeros((0, 0), dtype="i"), lengths_array) assert output.dataXd.ndim == 2 return output def preset_spans_suggester( docs: Iterable[Doc], spans_key: str, *, ops: Optional[Ops] = None ) -> Ragged: if ops is None: ops = get_current_ops() spans = [] lengths = [] for doc in docs: length = 0 if doc.spans[spans_key]: for span in doc.spans[spans_key]: spans.append([span.start, span.end]) length += 1 lengths.append(length) lengths_array = cast(Ints1d, ops.asarray(lengths, dtype="i")) if len(spans) > 0: output = Ragged(ops.asarray(spans, dtype="i"), lengths_array) else: output = Ragged(ops.xp.zeros((0, 0), dtype="i"), lengths_array) return output def build_ngram_suggester(sizes: List[int]) -> Suggester: """Suggest all spans of the given lengths. Spans are returned as a ragged array of integers. The array has two columns, indicating the start and end position.""" return partial(ngram_suggester, sizes=sizes) def build_ngram_range_suggester(min_size: int, max_size: int) -> Suggester: """Suggest all spans of the given lengths between a given min and max value - both inclusive. Spans are returned as a ragged array of integers. The array has two columns, indicating the start and end position.""" sizes = list(range(min_size, max_size + 1)) return build_ngram_suggester(sizes) def build_preset_spans_suggester(spans_key: str) -> Suggester: """Suggest all spans that are already stored in doc.spans[spans_key]. This is useful when an upstream component is used to set the spans on the Doc such as a SpanRuler or SpanFinder.""" return partial(preset_spans_suggester, spans_key=spans_key) def spancat_score(examples: Iterable[Example], **kwargs) -> Dict[str, Any]: kwargs = dict(kwargs) attr_prefix = "spans_" key = kwargs["spans_key"] kwargs.setdefault("attr", f"{attr_prefix}{key}") kwargs.setdefault("allow_overlap", True) kwargs.setdefault( "getter", lambda doc, key: doc.spans.get(key[len(attr_prefix) :], []) ) kwargs.setdefault("has_annotation", lambda doc: key in doc.spans) return Scorer.score_spans(examples, **kwargs) def make_spancat_scorer(): return spancat_score @dataclass
Suggester
python
pytest-dev__pytest
testing/test_capture.py
{ "start": 41058, "end": 54679 }
class ____: def test_stdcapture_fd_invalid_fd(self, pytester: Pytester) -> None: pytester.makepyfile( """ import os from fnmatch import fnmatch from _pytest import capture def StdCaptureFD(out=True, err=True, in_=True): return capture.MultiCapture( in_=capture.FDCapture(0) if in_ else None, out=capture.FDCapture(1) if out else None, err=capture.FDCapture(2) if err else None, ) def test_stdout(): os.close(1) cap = StdCaptureFD(out=True, err=False, in_=False) assert fnmatch(repr(cap.out), "<FDCapture 1 oldfd=* _state='initialized' tmpfile=*>") cap.start_capturing() os.write(1, b"stdout") assert cap.readouterr() == ("stdout", "") cap.stop_capturing() def test_stderr(): os.close(2) cap = StdCaptureFD(out=False, err=True, in_=False) assert fnmatch(repr(cap.err), "<FDCapture 2 oldfd=* _state='initialized' tmpfile=*>") cap.start_capturing() os.write(2, b"stderr") assert cap.readouterr() == ("", "stderr") cap.stop_capturing() def test_stdin(): os.close(0) cap = StdCaptureFD(out=False, err=False, in_=True) assert fnmatch(repr(cap.in_), "<FDCapture 0 oldfd=* _state='initialized' tmpfile=*>") cap.stop_capturing() """ ) result = pytester.runpytest_subprocess("--capture=fd") assert result.ret == 0 assert result.parseoutcomes()["passed"] == 3 def test_fdcapture_invalid_fd_with_fd_reuse(self, pytester: Pytester) -> None: with saved_fd(1): os.close(1) cap = capture.FDCaptureBinary(1) cap.start() os.write(1, b"started") cap.suspend() os.write(1, b" suspended") cap.resume() os.write(1, b" resumed") assert cap.snap() == b"started resumed" cap.done() with pytest.raises(OSError): os.write(1, b"done") def test_fdcapture_invalid_fd_without_fd_reuse(self, pytester: Pytester) -> None: with saved_fd(1), saved_fd(2): os.close(1) os.close(2) cap = capture.FDCaptureBinary(2) cap.start() os.write(2, b"started") cap.suspend() os.write(2, b" suspended") cap.resume() os.write(2, b" resumed") assert cap.snap() == b"started resumed" cap.done() with pytest.raises(OSError): os.write(2, b"done") def test_capture_not_started_but_reset() -> None: capsys = StdCapture() capsys.stop_capturing() def test_using_capsys_fixture_works_with_sys_stdout_encoding( capsys: CaptureFixture[str], ) -> None: test_text = "test text" print(test_text.encode(sys.stdout.encoding, "replace")) (out, err) = capsys.readouterr() assert out assert err == "" def test_capsys_results_accessible_by_attribute(capsys: CaptureFixture[str]) -> None: sys.stdout.write("spam") sys.stderr.write("eggs") capture_result = capsys.readouterr() assert capture_result.out == "spam" assert capture_result.err == "eggs" def test_fdcapture_tmpfile_remains_the_same() -> None: cap = StdCaptureFD(out=False, err=True) assert isinstance(cap.err, capture.FDCapture) try: cap.start_capturing() capfile = cap.err.tmpfile cap.readouterr() finally: cap.stop_capturing() capfile2 = cap.err.tmpfile assert capfile2 == capfile def test_close_and_capture_again(pytester: Pytester) -> None: pytester.makepyfile( """ import os def test_close(): os.close(1) def test_capture_again(): os.write(1, b"hello\\n") assert 0 """ ) result = pytester.runpytest_subprocess() result.stdout.fnmatch_lines( """ *test_capture_again* *assert 0* *stdout* *hello* """ ) @pytest.mark.parametrize( "method", ["SysCapture(2)", "SysCapture(2, tee=True)", "FDCapture(2)"] ) def test_capturing_and_logging_fundamentals(pytester: Pytester, method: str) -> None: # here we check a fundamental feature p = pytester.makepyfile( f""" import sys, os, logging from _pytest import capture cap = capture.MultiCapture( in_=None, out=None, err=capture.{method}, ) cap.start_capturing() logging.warning("hello1") outerr = cap.readouterr() print("suspend, captured %s" %(outerr,)) logging.warning("hello2") cap.pop_outerr_to_orig() logging.warning("hello3") outerr = cap.readouterr() print("suspend2, captured %s" % (outerr,)) """ ) result = pytester.runpython(p) result.stdout.fnmatch_lines( """ suspend, captured*hello1* suspend2, captured*WARNING:root:hello3* """ ) result.stderr.fnmatch_lines( """ WARNING:root:hello2 """ ) assert "atexit" not in result.stderr.str() def test_error_attribute_issue555(pytester: Pytester) -> None: pytester.makepyfile( """ import sys def test_capattr(): assert sys.stdout.errors == "replace" assert sys.stderr.errors == "replace" """ ) reprec = pytester.inline_run() reprec.assertoutcome(passed=1) @pytest.mark.skipif( not sys.platform.startswith("win"), reason="only on windows", ) def test_windowsconsoleio_workaround_non_standard_streams() -> None: """ Ensure _windowsconsoleio_workaround function works with objects that do not implement the full ``io``-based stream protocol, for example execnet channels (#2666). """ from _pytest.capture import _windowsconsoleio_workaround class DummyStream: def write(self, s): pass stream = cast(TextIO, DummyStream()) _windowsconsoleio_workaround(stream) def test_dontreadfrominput_has_encoding(pytester: Pytester) -> None: pytester.makepyfile( """ import sys def test_capattr(): # should not raise AttributeError assert sys.stdout.encoding assert sys.stderr.encoding """ ) reprec = pytester.inline_run() reprec.assertoutcome(passed=1) def test_crash_on_closing_tmpfile_py27( pytester: Pytester, monkeypatch: MonkeyPatch ) -> None: p = pytester.makepyfile( """ import threading import sys printing = threading.Event() def spam(): f = sys.stderr print('SPAMBEFORE', end='', file=f) printing.set() while True: try: f.flush() except (OSError, ValueError): break def test_spam_in_thread(): t = threading.Thread(target=spam) t.daemon = True t.start() printing.wait() """ ) # Do not consider plugins like hypothesis, which might output to stderr. monkeypatch.setenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "1") result = pytester.runpytest_subprocess(str(p)) assert result.ret == 0 assert result.stderr.str() == "" result.stdout.no_fnmatch_line("*OSError*") def test_global_capture_with_live_logging(pytester: Pytester) -> None: # Issue 3819 # capture should work with live cli logging # Teardown report seems to have the capture for the whole process (setup, capture, teardown) pytester.makeconftest( """ def pytest_runtest_logreport(report): if "test_global" in report.nodeid: if report.when == "teardown": with open("caplog", "w", encoding="utf-8") as f: f.write(report.caplog) with open("capstdout", "w", encoding="utf-8") as f: f.write(report.capstdout) """ ) pytester.makepyfile( """ import logging import sys import pytest logger = logging.getLogger(__name__) @pytest.fixture def fix1(): print("fix setup") logging.info("fix setup") yield logging.info("fix teardown") print("fix teardown") def test_global(fix1): print("begin test") logging.info("something in test") print("end test") """ ) result = pytester.runpytest_subprocess("--log-cli-level=INFO") assert result.ret == 0 with open("caplog", encoding="utf-8") as f: caplog = f.read() assert "fix setup" in caplog assert "something in test" in caplog assert "fix teardown" in caplog with open("capstdout", encoding="utf-8") as f: capstdout = f.read() assert "fix setup" in capstdout assert "begin test" in capstdout assert "end test" in capstdout assert "fix teardown" in capstdout @pytest.mark.parametrize("capture_fixture", ["capsys", "capfd"]) def test_capture_with_live_logging( pytester: Pytester, capture_fixture: CaptureFixture[str] ) -> None: # Issue 3819 # capture should work with live cli logging pytester.makepyfile( f""" import logging import sys logger = logging.getLogger(__name__) def test_capture({capture_fixture}): print("hello") sys.stderr.write("world\\n") captured = {capture_fixture}.readouterr() assert captured.out == "hello\\n" assert captured.err == "world\\n" logging.info("something") print("next") logging.info("something") captured = {capture_fixture}.readouterr() assert captured.out == "next\\n" """ ) result = pytester.runpytest_subprocess("--log-cli-level=INFO") assert result.ret == 0 def test_typeerror_encodedfile_write(pytester: Pytester) -> None: """It should behave the same with and without output capturing (#4861).""" p = pytester.makepyfile( """ def test_fails(): import sys sys.stdout.write(b"foo") """ ) result_without_capture = pytester.runpytest("-s", str(p)) result_with_capture = pytester.runpytest(str(p)) assert result_with_capture.ret == result_without_capture.ret out = result_with_capture.stdout.str() assert ("TypeError: write() argument must be str, not bytes" in out) or ( "TypeError: unicode argument expected, got 'bytes'" in out ) def test_stderr_write_returns_len(capsys: CaptureFixture[str]) -> None: """Write on Encoded files, namely captured stderr, should return number of characters written.""" assert sys.stderr.write("Foo") == 3 def test_encodedfile_writelines(tmpfile: BinaryIO) -> None: ef = capture.EncodedFile(tmpfile, encoding="utf-8") with pytest.raises(TypeError): ef.writelines([b"line1", b"line2"]) # type: ignore[list-item] assert ef.writelines(["line3", "line4"]) is None # type: ignore[func-returns-value] ef.flush() tmpfile.seek(0) assert tmpfile.read() == b"line3line4" tmpfile.close() with pytest.raises(ValueError): ef.read() def test__get_multicapture() -> None: assert isinstance(_get_multicapture("no"), MultiCapture) pytest.raises(ValueError, _get_multicapture, "unknown").match( r"^unknown capturing method: 'unknown'" ) def test_logging_while_collecting(pytester: Pytester) -> None: """Issue #6240: Calls to logging.xxx() during collection causes all logging calls to be duplicated to stderr""" p = pytester.makepyfile( """\ import logging logging.warning("during collection") def test_logging(): logging.warning("during call") assert False """ ) result = pytester.runpytest_subprocess(p) assert result.ret == ExitCode.TESTS_FAILED result.stdout.fnmatch_lines( [ "*test_*.py F*", "====* FAILURES *====", "____*____", "*--- Captured log call*", "WARNING * during call", "*1 failed*", ] ) result.stdout.no_fnmatch_line("*Captured stderr call*") result.stdout.no_fnmatch_line("*during collection*") def test_libedit_workaround(pytester: Pytester) -> None: pytester.makeconftest(""" import pytest def pytest_terminal_summary(config): capture = config.pluginmanager.getplugin("capturemanager") capture.suspend_global_capture(in_=True) print("Enter 'hi'") value = input() print(f"value: {value!r}") capture.resume_global_capture() """) readline = pytest.importorskip("readline") backend = getattr(readline, "backend", readline.__doc__) # added in Python 3.13 print(f"Readline backend: {backend}") child = pytester.spawn_pytest("") child.expect(r"Enter 'hi'") child.sendline("hi") rest = child.read().decode("utf8") print(rest) match = re.search(r"^value: '(.*)'\r?$", rest, re.MULTILINE) assert match is not None assert match.group(1) == "hi"
TestStdCaptureFDinvalidFD
python
numba__numba
numba/core/ir.py
{ "start": 20419, "end": 20798 }
class ____(Stmt): """ del target[index] """ def __init__(self, target, index, loc): assert isinstance(target, Var) assert isinstance(index, Var) assert isinstance(loc, Loc) self.target = target self.index = index self.loc = loc def __repr__(self): return 'del %s[%s]' % (self.target, self.index)
DelItem
python
dask__dask
dask/_expr.py
{ "start": 39839, "end": 41657 }
class ____(HLGExpr): def _simplify_down(self): if not self.postcompute: return self.dsk from dask.delayed import Delayed # Skip finalization for Delayed if self.dsk.postcompute == Delayed.__dask_postcompute__(self.dsk): return self.dsk return self @property def _name(self): return f"finalize-{super()._name}" def __dask_graph__(self): # The baseclass __dask_graph__ will not just materialize this layer but # also that of its dependencies, i.e. it will render the finalized and # the non-finalized graph and combine them. We only want the finalized # so we're overriding this. # This is an artifact generated since the wrapped expression is # identified automatically as a dependency but HLG expressions are not # working in this layered way. return self._layer() @property def hlg(self): expr = self.operand("dsk") layers = expr.dsk.layers.copy() deps = expr.dsk.dependencies.copy() keys = expr.__dask_keys__() if isinstance(expr.postcompute, list): postcomputes = expr.postcompute else: postcomputes = [expr.postcompute] tasks = [ Task(self._name, func, _convert_dask_keys(keys), *extra_args) for func, extra_args in postcomputes ] from dask.highlevelgraph import HighLevelGraph, MaterializedLayer leafs = set(deps) for val in deps.values(): leafs -= val for t in tasks: layers[t.key] = MaterializedLayer({t.key: t}) deps[t.key] = leafs return HighLevelGraph(layers, dependencies=deps) def __dask_keys__(self): return [self._name]
HLGFinalizeCompute
python
streamlit__streamlit
lib/tests/streamlit/elements/layout_test_utils.py
{ "start": 641, "end": 770 }
class ____(Enum): PIXEL_WIDTH = "pixel_width" USE_STRETCH = "use_stretch" USE_CONTENT = "use_content"
WidthConfigFields
python
astropy__astropy
astropy/cosmology/_src/tests/test_utils.py
{ "start": 2388, "end": 5588 }
class ____: @classmethod def setup_class(cls): def noop(a, b, c, d): # a minimal function that does nothing, # with multiple positional-or-keywords arguments return cls.base_func = noop cls.depr_funcs = { 1: deprecated_keywords("a", since="999.999.999")(noop), 2: deprecated_keywords("a", "b", since="999.999.999")(noop), 4: deprecated_keywords("a", "b", "c", "d", since="999.999.999")(noop), } def test_type_safety(self): dec = deprecated_keywords(b"a", since="999.999.999") with pytest.raises(TypeError, match=r"names\[0\] must be a string"): dec(self.base_func) dec = deprecated_keywords("a", since=b"999.999.999") with pytest.raises(TypeError, match=r"since must be a string"): dec(self.base_func) @pytest.mark.parametrize("n_deprecated_keywords", [1, 2, 4]) def test_no_warn(self, n_deprecated_keywords): func = self.depr_funcs[n_deprecated_keywords] func(1, 2, 3, 4) @pytest.mark.parametrize( "n_deprecated_keywords, args, kwargs, match", [ pytest.param( 1, (), {"a": 1, "b": 2, "c": 3, "d": 4}, r"Passing 'a' as keyword is deprecated since", id="1 deprecation, 1 warn", ), pytest.param( 2, (1,), {"b": 2, "c": 3, "d": 4}, r"Passing 'b' as keyword is deprecated since", id="2 deprecation, 1 warn", ), pytest.param( 2, (), {"a": 1, "b": 2, "c": 3, "d": 4}, r"Passing \['a', 'b'\] arguments as keywords is deprecated since", id="2 deprecations, 2 warns", ), pytest.param( 4, (), {"a": 1, "b": 2, "c": 3, "d": 4}, ( r"Passing \['a', 'b', 'c', 'd'\] arguments as keywords " "is deprecated since" ), id="4 deprecations, 4 warns", ), pytest.param( 4, (1,), {"b": 2, "c": 3, "d": 4}, r"Passing \['b', 'c', 'd'\] arguments as keywords is deprecated since", id="4 deprecations, 3 warns", ), pytest.param( 4, (1, 2), {"c": 3, "d": 4}, r"Passing \['c', 'd'\] arguments as keywords is deprecated since", id="4 deprecations, 2 warns", ), pytest.param( 4, (1, 2, 3), {"d": 4}, r"Passing 'd' as keyword is deprecated since", id="4 deprecations, 1 warn", ), ], ) def test_warn(self, n_deprecated_keywords, args, kwargs, match): func = self.depr_funcs[n_deprecated_keywords] with pytest.warns(FutureWarning, match=match): func(*args, **kwargs)
TestDeprecatedKeywords
python
airbytehq__airbyte
airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py
{ "start": 7018, "end": 7128 }
class ____(IncrementalShopifyGraphQlBulkStream): bulk_query: OrderAgreement = OrderAgreement
OrderAgreements
python
ray-project__ray
python/ray/tune/search/repeater.py
{ "start": 2468, "end": 7007 }
class ____(Searcher): """A wrapper algorithm for repeating trials of same parameters. Set tune.TuneConfig(num_samples=...) to be a multiple of `repeat`. For example, set num_samples=15 if you intend to obtain 3 search algorithm suggestions and repeat each suggestion 5 times. Any leftover trials (num_samples mod repeat) will be ignored. It is recommended that you do not run an early-stopping TrialScheduler simultaneously. Args: searcher: Searcher object that the Repeater will optimize. Note that the Searcher will only see 1 trial among multiple repeated trials. The result/metric passed to the Searcher upon trial completion will be averaged among all repeats. repeat: Number of times to generate a trial with a repeated configuration. Defaults to 1. set_index: Sets a tune.search.repeater.TRIAL_INDEX in Trainable/Function config which corresponds to the index of the repeated trial. This can be used for seeds. Defaults to True. Example: .. code-block:: python from ray.tune.search import Repeater search_alg = BayesOptSearch(...) re_search_alg = Repeater(search_alg, repeat=10) # Repeat 2 samples 10 times each. tuner = tune.Tuner( trainable, tune_config=tune.TuneConfig( search_alg=re_search_alg, num_samples=20, ), ) tuner.fit() """ def __init__(self, searcher: Searcher, repeat: int = 1, set_index: bool = True): self.searcher = searcher self.repeat = repeat self._set_index = set_index self._groups = [] self._trial_id_to_group = {} self._current_group = None super(Repeater, self).__init__( metric=self.searcher.metric, mode=self.searcher.mode ) def suggest(self, trial_id: str) -> Optional[Dict]: if self._current_group is None or self._current_group.full(): config = self.searcher.suggest(trial_id) if config is None: return config self._current_group = _TrialGroup( trial_id, copy.deepcopy(config), max_trials=self.repeat ) self._groups.append(self._current_group) index_in_group = 0 else: index_in_group = self._current_group.count() self._current_group.add(trial_id) config = self._current_group.config.copy() if self._set_index: config[TRIAL_INDEX] = index_in_group self._trial_id_to_group[trial_id] = self._current_group return config def on_trial_complete(self, trial_id: str, result: Optional[Dict] = None, **kwargs): """Stores the score for and keeps track of a completed trial. Stores the metric of a trial as nan if any of the following conditions are met: 1. ``result`` is empty or not provided. 2. ``result`` is provided but no metric was provided. """ if trial_id not in self._trial_id_to_group: logger.error( "Trial {} not in group; cannot report score. " "Seen trials: {}".format(trial_id, list(self._trial_id_to_group)) ) trial_group = self._trial_id_to_group[trial_id] if not result or self.searcher.metric not in result: score = np.nan else: score = result[self.searcher.metric] trial_group.report(trial_id, score) if trial_group.finished_reporting(): scores = trial_group.scores() self.searcher.on_trial_complete( trial_group.primary_trial_id, result={self.searcher.metric: np.nanmean(scores)}, **kwargs ) def get_state(self) -> Dict: self_state = self.__dict__.copy() del self_state["searcher"] return self_state def set_state(self, state: Dict): self.__dict__.update(state) def save(self, checkpoint_path: str): self.searcher.save(checkpoint_path) def restore(self, checkpoint_path: str): self.searcher.restore(checkpoint_path) def set_search_properties( self, metric: Optional[str], mode: Optional[str], config: Dict, **spec ) -> bool: return _set_search_properties_backwards_compatible( self.searcher.set_search_properties, metric, mode, config, **spec )
Repeater
python
pytorch__pytorch
torch/distributed/elastic/metrics/api.py
{ "start": 1066, "end": 1288 }
class ____(MetricHandler): def emit(self, metric_data: MetricData): print( f"[{metric_data.timestamp}][{metric_data.group_name}]: {metric_data.name}={metric_data.value}" )
ConsoleMetricHandler
python
jmcnamara__XlsxWriter
xlsxwriter/test/styles/test_write_mru_colors.py
{ "start": 330, "end": 952 }
class ____(unittest.TestCase): """ Test the Styles _write_mru_colors() method. """ def setUp(self): self.fh = StringIO() self.styles = Styles() self.styles._set_filehandle(self.fh) def test_write_mru_colors(self): """Test the _write_mru_colors() method""" self.styles._write_mru_colors( [Color("26DA55"), Color("792DC8"), Color("646462")] ) exp = """<mruColors><color rgb="FF646462"/><color rgb="FF792DC8"/><color rgb="FF26DA55"/></mruColors>""" got = self.fh.getvalue() self.assertEqual(exp, got)
TestWriteMruColors
python
huggingface__transformers
src/transformers/models/donut/modeling_donut_swin.py
{ "start": 30938, "end": 35251 }
class ____(nn.Module): def __init__(self, config, grid_size): super().__init__() self.num_layers = len(config.depths) self.config = config dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu")] self.layers = nn.ModuleList( [ DonutSwinStage( config=config, dim=int(config.embed_dim * 2**i_layer), input_resolution=(grid_size[0] // (2**i_layer), grid_size[1] // (2**i_layer)), depth=config.depths[i_layer], num_heads=config.num_heads[i_layer], drop_path=dpr[sum(config.depths[:i_layer]) : sum(config.depths[: i_layer + 1])], downsample=DonutSwinPatchMerging if (i_layer < self.num_layers - 1) else None, ) for i_layer in range(self.num_layers) ] ) self.gradient_checkpointing = False def forward( self, hidden_states: torch.Tensor, input_dimensions: tuple[int, int], output_attentions: Optional[bool] = False, output_hidden_states: Optional[bool] = False, output_hidden_states_before_downsampling: Optional[bool] = False, always_partition: Optional[bool] = False, return_dict: Optional[bool] = True, ) -> Union[tuple, DonutSwinEncoderOutput]: all_hidden_states = () if output_hidden_states else None all_reshaped_hidden_states = () if output_hidden_states else None all_self_attentions = () if output_attentions else None if output_hidden_states: batch_size, _, hidden_size = hidden_states.shape # rearrange b (h w) c -> b c h w reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size) reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2) all_hidden_states += (hidden_states,) all_reshaped_hidden_states += (reshaped_hidden_state,) for i, layer_module in enumerate(self.layers): layer_outputs = layer_module(hidden_states, input_dimensions, output_attentions, always_partition) hidden_states = layer_outputs[0] hidden_states_before_downsampling = layer_outputs[1] output_dimensions = layer_outputs[2] input_dimensions = (output_dimensions[-2], output_dimensions[-1]) if output_hidden_states and output_hidden_states_before_downsampling: batch_size, _, hidden_size = hidden_states_before_downsampling.shape # rearrange b (h w) c -> b c h w # here we use the original (not downsampled) height and width reshaped_hidden_state = hidden_states_before_downsampling.view( batch_size, *(output_dimensions[0], output_dimensions[1]), hidden_size ) reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2) all_hidden_states += (hidden_states_before_downsampling,) all_reshaped_hidden_states += (reshaped_hidden_state,) elif output_hidden_states and not output_hidden_states_before_downsampling: batch_size, _, hidden_size = hidden_states.shape # rearrange b (h w) c -> b c h w reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size) reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2) all_hidden_states += (hidden_states,) all_reshaped_hidden_states += (reshaped_hidden_state,) if output_attentions: all_self_attentions += layer_outputs[3:] if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None) return DonutSwinEncoderOutput( last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_self_attentions, reshaped_hidden_states=all_reshaped_hidden_states, ) @auto_docstring # Copied from transformers.models.swin.modeling_swin.SwinPreTrainedModel with Swin->DonutSwin,swin->donut
DonutSwinEncoder
python
huggingface__transformers
tests/models/nanochat/test_modeling_nanochat.py
{ "start": 1068, "end": 1283 }
class ____(CausalLMModelTester): config_class = NanoChatConfig if is_torch_available(): base_model_class = NanoChatModel causal_lm_class = NanoChatForCausalLM @require_torch
NanoChatModelTester
python
django__django
tests/template_backends/test_jinja2.py
{ "start": 443, "end": 5725 }
class ____(TemplateStringsTests): engine_class = Jinja2 backend_name = "jinja2" options = { "keep_trailing_newline": True, "context_processors": [ "django.template.context_processors.static", ], } def test_origin(self): template = self.engine.get_template("template_backends/hello.html") self.assertTrue(template.origin.name.endswith("hello.html")) self.assertEqual(template.origin.template_name, "template_backends/hello.html") def test_origin_from_string(self): template = self.engine.from_string("Hello!\n") self.assertEqual(template.origin.name, "<template>") self.assertIsNone(template.origin.template_name) def test_self_context(self): """ Using 'self' in the context should not throw errors (#24538). """ # self will be overridden to be a TemplateReference, so the self # variable will not come through. Attempting to use one though should # not throw an error. template = self.engine.from_string("hello {{ foo }}!") content = template.render(context={"self": "self", "foo": "world"}) self.assertEqual(content, "hello world!") def test_exception_debug_info_min_context(self): with self.assertRaises(TemplateSyntaxError) as e: self.engine.get_template("template_backends/syntax_error.html") debug = e.exception.template_debug self.assertEqual(debug["after"], "") self.assertEqual(debug["before"], "") self.assertEqual(debug["during"], "{% block %}") self.assertEqual(debug["bottom"], 1) self.assertEqual(debug["top"], 0) self.assertEqual(debug["line"], 1) self.assertEqual(debug["total"], 1) self.assertEqual(len(debug["source_lines"]), 1) self.assertTrue(debug["name"].endswith("syntax_error.html")) self.assertIn("message", debug) def test_exception_debug_info_max_context(self): with self.assertRaises(TemplateSyntaxError) as e: self.engine.get_template("template_backends/syntax_error2.html") debug = e.exception.template_debug self.assertEqual(debug["after"], "") self.assertEqual(debug["before"], "") self.assertEqual(debug["during"], "{% block %}") self.assertEqual(debug["bottom"], 26) self.assertEqual(debug["top"], 5) self.assertEqual(debug["line"], 16) self.assertEqual(debug["total"], 31) self.assertEqual(len(debug["source_lines"]), 21) self.assertTrue(debug["name"].endswith("syntax_error2.html")) self.assertIn("message", debug) def test_context_processors(self): request = RequestFactory().get("/") template = self.engine.from_string("Static URL: {{ STATIC_URL }}") content = template.render(request=request) self.assertEqual(content, "Static URL: /static/") with self.settings(STATIC_URL="/s/"): content = template.render(request=request) self.assertEqual(content, "Static URL: /s/") def test_dirs_pathlib(self): engine = Jinja2( { "DIRS": [Path(__file__).parent / "templates" / "template_backends"], "APP_DIRS": False, "NAME": "jinja2", "OPTIONS": {}, } ) template = engine.get_template("hello.html") self.assertEqual(template.render({"name": "Joe"}), "Hello Joe!") def test_template_render_nested_error(self): template = self.engine.get_template( "template_backends/syntax_error_include.html" ) with self.assertRaises(TemplateSyntaxError) as e: template.render(context={}) debug = e.exception.template_debug self.assertEqual(debug["after"], "") self.assertEqual(debug["before"], "") self.assertEqual(debug["during"], "{% block %}") self.assertEqual(debug["bottom"], 1) self.assertEqual(debug["top"], 0) self.assertEqual(debug["line"], 1) self.assertEqual(debug["total"], 1) self.assertEqual(len(debug["source_lines"]), 1) self.assertTrue(debug["name"].endswith("syntax_error.html")) self.assertIn("message", debug) def test_template_render_error_nonexistent_source(self): template = self.engine.get_template("template_backends/hello.html") with mock.patch( "jinja2.environment.Template.render", side_effect=jinja2.TemplateSyntaxError("", 1, filename="nonexistent.html"), ): with self.assertRaises(TemplateSyntaxError) as e: template.render(context={}) debug = e.exception.template_debug self.assertEqual(debug["after"], "") self.assertEqual(debug["before"], "") self.assertEqual(debug["during"], "") self.assertEqual(debug["bottom"], 0) self.assertEqual(debug["top"], 0) self.assertEqual(debug["line"], 1) self.assertEqual(debug["total"], 0) self.assertEqual(len(debug["source_lines"]), 0) self.assertTrue(debug["name"].endswith("nonexistent.html")) self.assertIn("message", debug) @skipIf(jinja2 is None, "this test requires jinja2")
Jinja2Tests
python
huggingface__transformers
src/transformers/models/vjepa2/modeling_vjepa2.py
{ "start": 2360, "end": 3319 }
class ____(ModelOutput): r""" masked_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*, returned when `context_mask` is provided which is applied on VJEPA2Encoder outputs): The masked hidden state of the model. predictor_output (`VJEPA2WithMaskedInputPredictorOutput`, *optional*): The output from the Predictor module. """ last_hidden_state: torch.FloatTensor masked_hidden_state: Optional[torch.FloatTensor] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None predictor_output: Optional[VJEPA2WithMaskedInputPredictorOutput] = None def to_tuple(self): output = list(super().to_tuple()) if isinstance(output[-1], VJEPA2WithMaskedInputPredictorOutput): output[-1] = output[-1].to_tuple() return tuple(output)
VJEPA2WithMaskedInputModelOutput
python
doocs__leetcode
solution/2500-2599/2502.Design Memory Allocator/Solution.py
{ "start": 0, "end": 774 }
class ____: def __init__(self, n: int): self.m = [0] * n def allocate(self, size: int, mID: int) -> int: cnt = 0 for i, v in enumerate(self.m): if v: cnt = 0 else: cnt += 1 if cnt == size: self.m[i - size + 1 : i + 1] = [mID] * size return i - size + 1 return -1 def freeMemory(self, mID: int) -> int: ans = 0 for i, v in enumerate(self.m): if v == mID: self.m[i] = 0 ans += 1 return ans # Your Allocator object will be instantiated and called as such: # obj = Allocator(n) # param_1 = obj.allocate(size,mID) # param_2 = obj.freeMemory(mID)
Allocator
python
urllib3__urllib3
test/test_response.py
{ "start": 56872, "end": 57070 }
class ____(MockChunkedEncodingResponse): def _encode_chunk(self, chunk: bytes) -> bytes: return f"{len(chunk):X};asd=qwe\r\n{chunk.decode()}\r\n".encode()
MockChunkedEncodingWithExtensions
python
scikit-learn__scikit-learn
sklearn/compose/tests/test_target.py
{ "start": 14100, "end": 14891 }
class ____(BaseEstimator): """A regressor that expects the target to have a specific number of dimensions.""" def __init__(self, ndim): self.ndim = ndim def fit(self, X, y): assert y.ndim == self.ndim def predict(self, X): pass # pragma: no cover @pytest.mark.parametrize("ndim", [1, 2]) def test_transform_target_regressor_preserves_input_shape(ndim): """Check that TransformedTargetRegressor internally preserves the shape of the input non-regression test for issue #26530. """ X, y = datasets.make_regression(n_samples=10, n_features=5, random_state=42) if ndim == 2: y = y.reshape(-1, 1) regr = TransformedTargetRegressor(regressor=ValidateDimensionRegressor(ndim)) regr.fit(X, y)
ValidateDimensionRegressor
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1464056, "end": 1467760 }
class ____(sgqlc.types.Type, Node): """A repository ruleset.""" __schema__ = github_schema __field_names__ = ( "bypass_actors", "bypass_mode", "conditions", "created_at", "database_id", "enforcement", "name", "rules", "source", "target", "updated_at", ) bypass_actors = sgqlc.types.Field( RepositoryRulesetBypassActorConnection, graphql_name="bypassActors", args=sgqlc.types.ArgDict( ( ("after", sgqlc.types.Arg(String, graphql_name="after", default=None)), ("before", sgqlc.types.Arg(String, graphql_name="before", default=None)), ("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)), ("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)), ) ), ) """The actors that can bypass this ruleset Arguments: * `after` (`String`): Returns the elements in the list that come after the specified cursor. * `before` (`String`): Returns the elements in the list that come before the specified cursor. * `first` (`Int`): Returns the first _n_ elements from the list. * `last` (`Int`): Returns the last _n_ elements from the list. """ bypass_mode = sgqlc.types.Field(sgqlc.types.non_null(RuleBypassMode), graphql_name="bypassMode") """The bypass mode of this ruleset""" conditions = sgqlc.types.Field(sgqlc.types.non_null(RepositoryRuleConditions), graphql_name="conditions") """The set of conditions that must evaluate to true for this ruleset to apply """ created_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="createdAt") """Identifies the date and time when the object was created.""" database_id = sgqlc.types.Field(Int, graphql_name="databaseId") """Identifies the primary key from the database.""" enforcement = sgqlc.types.Field(sgqlc.types.non_null(RuleEnforcement), graphql_name="enforcement") """The enforcement level of this ruleset""" name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name") """Name of the ruleset.""" rules = sgqlc.types.Field( RepositoryRuleConnection, graphql_name="rules", args=sgqlc.types.ArgDict( ( ("after", sgqlc.types.Arg(String, graphql_name="after", default=None)), ("before", sgqlc.types.Arg(String, graphql_name="before", default=None)), ("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)), ("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)), ("type", sgqlc.types.Arg(RepositoryRuleType, graphql_name="type", default=None)), ) ), ) """List of rules. Arguments: * `after` (`String`): Returns the elements in the list that come after the specified cursor. * `before` (`String`): Returns the elements in the list that come before the specified cursor. * `first` (`Int`): Returns the first _n_ elements from the list. * `last` (`Int`): Returns the last _n_ elements from the list. * `type` (`RepositoryRuleType`): The type of rule. """ source = sgqlc.types.Field(sgqlc.types.non_null("RuleSource"), graphql_name="source") """Source of ruleset.""" target = sgqlc.types.Field(RepositoryRulesetTarget, graphql_name="target") """Target of the ruleset.""" updated_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="updatedAt") """Identifies the date and time when the object was last updated."""
RepositoryRuleset
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/tab_rename.py
{ "start": 95, "end": 506 }
class ____(App[None]): def compose(self) -> ComposeResult: with TabbedContent(): yield TabPane("!", id="test") for n in range(5): yield TabPane(str(n) * (n+1)) def on_mount(self) -> None: self.query_one(TabbedContent).get_tab("test").label = "This is a much longer label for the tab" if __name__ == "__main__": TabRenameApp().run()
TabRenameApp
python
rapidsai__cudf
python/cudf/cudf/core/accessors/struct.py
{ "start": 547, "end": 3434 }
class ____(BaseAccessor): """ Struct methods for Series """ _column: StructColumn def __init__(self, parent: Series | Index): if not is_dtype_obj_struct(parent.dtype): raise AttributeError( "Can only use .struct accessor with a 'struct' dtype" ) super().__init__(parent=parent) def field(self, key) -> Series | Index: """ Extract children of the specified struct column in the Series Parameters ---------- key: int or str index/position or field name of the respective struct column Returns ------- Series Examples -------- >>> s = cudf.Series([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]) >>> s.struct.field(0) 0 1 1 3 dtype: int64 >>> s.struct.field('a') 0 1 1 3 dtype: int64 """ struct_dtype_fields = StructDtype.from_struct_dtype( self._column.dtype ).fields field_keys = list(struct_dtype_fields.keys()) if key in struct_dtype_fields: pos = field_keys.index(key) return self._return_or_inplace( self._column.children[pos]._with_type_metadata( get_dtype_of_same_kind( self._column.dtype, struct_dtype_fields[key] ) ) ) elif isinstance(key, int): try: return self._return_or_inplace(self._column.children[key]) except IndexError as err: raise IndexError(f"Index {key} out of range") from err else: raise KeyError( f"Field '{key}' is not found in the set of existing keys." ) def explode(self) -> DataFrame: """ Return a DataFrame whose columns are the fields of this struct Series. Notes ----- Note that a copy of the columns is made. Examples -------- >>> s 0 {'a': 1, 'b': 'x'} 1 {'a': 2, 'b': 'y'} 2 {'a': 3, 'b': 'z'} 3 {'a': 4, 'b': 'a'} dtype: struct >>> s.struct.explode() a b 0 1 x 1 2 y 2 3 z 3 4 a """ from cudf.core.column_accessor import ColumnAccessor from cudf.core.dataframe import DataFrame data = { name: col.copy(deep=True) for name, col in zip( self._column.dtype.fields, # type: ignore[arg-type] self._column.children, strict=True, ) } rangeindex = len(data) == 0 return DataFrame._from_data( ColumnAccessor(data, rangeindex=rangeindex) )
StructMethods
python
psf__black
tests/data/cases/allow_empty_first_line.py
{ "start": 620, "end": 1524 }
class ____: def method(self): pass async def async_fn(): """Docstring.""" @decorated async def async_fn(): """Docstring.""" def top_level( a: int, b: str, ) -> Whatever[Generic, Something]: def nested(x: int) -> int: pass # output def foo(): """ Docstring """ # Here we go if x: # This is also now fine a = 123 else: # But not necessary a = 123 if y: while True: """ Long comment here """ a = 123 if z: for _ in range(100): a = 123 else: try: # this should be ok a = 123 except: """also this""" a = 123 def bar(): if x: a = 123 def baz(): # OK if x: a = 123 def quux(): new_line = here
Cls
python
getsentry__sentry
tests/sentry/api/fields/test_serializedfile.py
{ "start": 323, "end": 1369 }
class ____(unittest.TestCase): def test_to_representation(self) -> None: field = SerializedFileField() assert field.to_representation(None) == "" assert field.to_representation("") == "" with pytest.raises(ValueError): assert field.to_representation(1) result = field.to_representation( FileUpload(name="filename.txt", content=BytesIO(b"hello world")) ) assert result == ["filename.txt", "aGVsbG8gd29ybGQ="] def test_to_internal_value(self) -> None: field = SerializedFileField() assert field.to_internal_value("") is None assert field.to_internal_value(None) is None with pytest.raises(serializers.ValidationError): assert field.to_internal_value(True) result = field.to_internal_value(["filename.txt", b64encode(b"hello world")]) assert isinstance(result, FileUpload) assert result.name == "filename.txt" assert result.content.getvalue() == b"hello world"
SerializedFileFieldTest
python
apache__thrift
lib/py/src/protocol/TBase.py
{ "start": 2093, "end": 2829 }
class ____(TBase): def __setitem__(self, *args): raise TypeError("Can't modify frozen struct") def __delitem__(self, *args): raise TypeError("Can't modify frozen struct") def __hash__(self, *args): return hash(self.__class__) ^ hash(self.__slots__) @classmethod def read(cls, iprot): if (iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and cls.thrift_spec is not None): self = cls() return iprot._fast_decode(None, iprot, [self.__class__, self.thrift_spec]) else: return iprot.readStruct(cls, cls.thrift_spec, True)
TFrozenBase
python
walkccc__LeetCode
solutions/471. Encode String with Shortest Length/471.py
{ "start": 0, "end": 905 }
class ____: def encode(self, s: str) -> str: n = len(s) @functools.lru_cache(None) def dp(i: int, j: int) -> str: """Returns the shortest encoded string of s[i..j].""" curr = s[i:j + 1] res = curr if len(res) < 5: return res # Try all possible partitions. for k in range(i, j): l = dp(i, k) r = dp(k + 1, j) if len(l) + len(r) < len(res): res = l + r # Try to compress the string. # e.g. s = aabaabaab -> 3[aab] for k in range(i, j): pattern = s[i:k + 1] if len(curr) % len(pattern) == 0 and pattern * (len(curr) // len(pattern)) == curr: candidate = f"{len(curr) // len(pattern)}[{dp(i, k)}]" if len(candidate) < len(res): res = candidate return res return dp(0, n - 1)
Solution
python
django__django
tests/messages_tests/tests.py
{ "start": 3542, "end": 3711 }
class ____: def __init__(self): request = RequestFactory().get("/") request._messages = DummyStorage() self.wsgi_request = request
FakeResponse
python
langchain-ai__langchain
libs/core/langchain_core/outputs/generation.py
{ "start": 1611, "end": 2564 }
class ____(Generation): """`GenerationChunk`, which can be concatenated with other Generation chunks.""" def __add__(self, other: GenerationChunk) -> GenerationChunk: """Concatenate two `GenerationChunk`s. Args: other: Another `GenerationChunk` to concatenate with. Raises: TypeError: If other is not a `GenerationChunk`. Returns: A new `GenerationChunk` concatenated from self and other. """ if isinstance(other, GenerationChunk): generation_info = merge_dicts( self.generation_info or {}, other.generation_info or {}, ) return GenerationChunk( text=self.text + other.text, generation_info=generation_info or None, ) msg = f"unsupported operand type(s) for +: '{type(self)}' and '{type(other)}'" raise TypeError(msg)
GenerationChunk
python
wandb__wandb
wandb/vendor/pygments/formatters/terminal.py
{ "start": 1981, "end": 4919 }
class ____(Formatter): r""" Format tokens with ANSI color sequences, for output in a text console. Color sequences are terminated at newlines, so that paging the output works correctly. The `get_style_defs()` method doesn't do anything special since there is no support for common styles. Options accepted: `bg` Set to ``"light"`` or ``"dark"`` depending on the terminal's background (default: ``"light"``). `colorscheme` A dictionary mapping token types to (lightbg, darkbg) color names or ``None`` (default: ``None`` = use builtin colorscheme). `linenos` Set to ``True`` to have line numbers on the terminal output as well (default: ``False`` = no line numbers). """ name = 'Terminal' aliases = ['terminal', 'console'] filenames = [] def __init__(self, **options): Formatter.__init__(self, **options) self.darkbg = get_choice_opt(options, 'bg', ['light', 'dark'], 'light') == 'dark' self.colorscheme = options.get('colorscheme', None) or TERMINAL_COLORS self.linenos = options.get('linenos', False) self._lineno = 0 def format(self, tokensource, outfile): # hack: if the output is a terminal and has an encoding set, # use that to avoid unicode encode problems if not self.encoding and hasattr(outfile, "encoding") and \ hasattr(outfile, "isatty") and outfile.isatty() and \ sys.version_info < (3,): self.encoding = outfile.encoding return Formatter.format(self, tokensource, outfile) def _write_lineno(self, outfile): self._lineno += 1 outfile.write("%s%04d: " % (self._lineno != 1 and '\n' or '', self._lineno)) def _get_color(self, ttype): # self.colorscheme is a dict containing usually generic types, so we # have to walk the tree of dots. The base Token type must be a key, # even if it's empty string, as in the default above. colors = self.colorscheme.get(ttype) while colors is None: ttype = ttype.parent colors = self.colorscheme.get(ttype) return colors[self.darkbg] def format_unencoded(self, tokensource, outfile): if self.linenos: self._write_lineno(outfile) for ttype, value in tokensource: color = self._get_color(ttype) for line in value.splitlines(True): if color: outfile.write(ansiformat(color, line.rstrip('\n'))) else: outfile.write(line.rstrip('\n')) if line.endswith('\n'): if self.linenos: self._write_lineno(outfile) else: outfile.write('\n') if self.linenos: outfile.write("\n")
TerminalFormatter
python
wandb__wandb
wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_fragment_names.py
{ "start": 69, "end": 597 }
class ____(ValidationRule): def enter_FragmentSpread(self, node, key, parent, path, ancestors): fragment_name = node.name.value fragment = self.context.get_fragment(fragment_name) if not fragment: self.context.report_error(GraphQLError( self.unknown_fragment_message(fragment_name), [node.name] )) @staticmethod def unknown_fragment_message(fragment_name): return 'Unknown fragment "{}".'.format(fragment_name)
KnownFragmentNames
python
davidhalter__parso
parso/python/tree.py
{ "start": 8203, "end": 8414 }
class ____(PythonLeaf): """ f-strings contain f-string expressions and normal python strings. These are the string parts of f-strings. """ type = 'fstring_start' __slots__ = ()
FStringStart
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/refurb/FURB180.py
{ "start": 587, "end": 681 }
class ____(metaclass=Meta, no_metaclass=ABCMeta): @abstractmethod def foo(self): pass
A4
python
huggingface__transformers
src/transformers/models/unispeech/modeling_unispeech.py
{ "start": 29125, "end": 37809 }
class ____(PreTrainedModel): config: UniSpeechConfig base_model_prefix = "unispeech" main_input_name = "input_values" input_modalities = "audio" supports_gradient_checkpointing = True _supports_flash_attn = True _supports_sdpa = True _supports_flex_attn = True @torch.no_grad() def _init_weights(self, module): """Initialize the weights""" # gumbel softmax requires special init if isinstance(module, UniSpeechGumbelVectorQuantizer): init.normal_(module.weight_proj.weight, mean=0.0, std=1) init.zeros_(module.weight_proj.bias) init.uniform_(module.codevectors) elif isinstance(module, UniSpeechPositionalConvEmbedding): init.normal_( module.conv.weight, mean=0, std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)), ) init.constant_(module.conv.bias, 0) elif isinstance(module, UniSpeechFeatureProjection): k = math.sqrt(1 / module.projection.in_features) init.uniform_(module.projection.weight, a=-k, b=k) init.uniform_(module.projection.bias, a=-k, b=k) elif isinstance(module, nn.Linear): init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) if module.bias is not None: init.zeros_(module.bias) elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)): init.zeros_(module.bias) init.ones_(module.weight) elif isinstance(module, nn.Conv1d): init.kaiming_normal_(module.weight) if module.bias is not None: k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0])) init.uniform_(module.bias, a=-k, b=k) def _get_feat_extract_output_lengths(self, input_lengths: Union[torch.LongTensor, int]): """ Computes the output length of the convolutional layers """ def _conv_out_length(input_length, kernel_size, stride): # 1D convolutional layer output length formula taken # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1 for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride): input_lengths = _conv_out_length(input_lengths, kernel_size, stride) return input_lengths def _get_feature_vector_attention_mask(self, feature_vector_length: int, attention_mask: torch.LongTensor): # Effectively attention_mask.sum(-1), but not inplace to be able to run # on inference mode. non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1] output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths).to(torch.long) batch_size = attention_mask.shape[0] attention_mask = torch.zeros( (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device ) # these two operations makes sure that all values before the output lengths idxs are attended to attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1 attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool() return attention_mask def _compute_mask_indices( shape: tuple[int, int], mask_prob: float, mask_length: int, attention_mask: Optional[torch.LongTensor] = None, min_masks: int = 0, ) -> np.ndarray: """ Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for ASR](https://huggingface.co/papers/1904.08779). Note that this method is not optimized to run on TPU and should be run on CPU as part of the preprocessing during training. Args: shape: The shape for which to compute masks. This should be of a tuple of size 2 where the first element is the batch size and the second element is the length of the axis to span. mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of independently generated mask spans of length `mask_length` is computed by `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the actual percentage will be smaller. mask_length: size of the mask min_masks: minimum number of masked spans attention_mask: A (right-padded) attention mask which independently shortens the feature axis of each batch dimension. """ batch_size, sequence_length = shape if mask_length < 1: raise ValueError("`mask_length` has to be bigger than 0.") if mask_length > sequence_length: raise ValueError( f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}" f" and `sequence_length`: {sequence_length}`" ) # epsilon is used for probabilistic rounding epsilon = np.random.rand(1).item() def compute_num_masked_span(input_length): """Given input length, compute how many spans should be masked""" num_masked_span = int(mask_prob * input_length / mask_length + epsilon) num_masked_span = max(num_masked_span, min_masks) # make sure num masked span <= sequence_length if num_masked_span * mask_length > sequence_length: num_masked_span = sequence_length // mask_length # make sure num_masked span is also <= input_length - (mask_length - 1) if input_length - (mask_length - 1) < num_masked_span: num_masked_span = max(input_length - (mask_length - 1), 0) return num_masked_span # compute number of masked spans in batch input_lengths = ( attention_mask.detach().sum(-1).tolist() if attention_mask is not None else [sequence_length for _ in range(batch_size)] ) # SpecAugment mask to fill spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool) spec_aug_mask_idxs = [] max_num_masked_span = compute_num_masked_span(sequence_length) if max_num_masked_span == 0: return spec_aug_mask for input_length in input_lengths: # compute num of masked spans for this input num_masked_span = compute_num_masked_span(input_length) # get random indices to mask spec_aug_mask_idx = np.random.choice( np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False ) # pick first sampled index that will serve as a dummy index to pad vector # to ensure same dimension for all batches due to probabilistic rounding # Picking first sample just pads those vectors twice. if len(spec_aug_mask_idx) == 0: # this case can only happen if `input_length` is strictly smaller then # `sequence_length` in which case the last token has to be a padding # token which we can use as a dummy mask id dummy_mask_idx = sequence_length - 1 else: dummy_mask_idx = spec_aug_mask_idx[0] spec_aug_mask_idx = np.concatenate( [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx] ) spec_aug_mask_idxs.append(spec_aug_mask_idx) spec_aug_mask_idxs = np.array(spec_aug_mask_idxs) # expand masked indices to masked spans spec_aug_mask_idxs = np.broadcast_to( spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length) ) spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length) # add offset to the starting indexes so that indexes now create a span offsets = np.arange(mask_length)[None, None, :] offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape( batch_size, max_num_masked_span * mask_length ) spec_aug_mask_idxs = spec_aug_mask_idxs + offsets # ensure that we cannot have indices larger than sequence_length if spec_aug_mask_idxs.max() > sequence_length - 1: spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1 # scatter indices to mask np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1) return spec_aug_mask UniSpeechBaseModelOutput = Wav2Vec2BaseModelOutput @auto_docstring
UniSpeechPreTrainedModel
python
facelessuser__pymdown-extensions
pymdownx/_bypassnorm.py
{ "start": 665, "end": 1018 }
class ____(Preprocessor): """Preprocessor to remove workaround symbols.""" def run(self, lines): """Remove workaround placeholder markers before adding actual workaround placeholders.""" source = '\n'.join(lines) source = source.replace(SOH, '').replace(EOT, '') return source.split('\n')
PreNormalizePreprocessor
python
pytorch__pytorch
test/distributed/checkpoint/test_pg_transport.py
{ "start": 10638, "end": 12707 }
class ____(TestCase): def test_prepare_tensor_basic(self): """Test basic tensor preparation.""" tensor = torch.tensor([1.0, 2.0, 3.0], dtype=torch.float32) prepared_tensor, meta = _prepare_tensor(tensor) # Check metadata self.assertEqual(meta.shape, tensor.shape) self.assertEqual(meta.dtype, tensor.dtype) self.assertEqual(meta.storage_offset, tensor.storage_offset()) self.assertEqual(meta.stride, tensor.stride()) self.assertEqual(meta.nbytes, tensor.untyped_storage().nbytes()) # Check prepared tensor self.assertEqual(prepared_tensor.dtype, torch.uint8) self.assertEqual(prepared_tensor.numel(), tensor.untyped_storage().nbytes()) def test_prepare_tensor_different_shapes(self): """Test preparing tensors with different shapes.""" shapes = [(3,), (2, 3), (2, 3, 4)] for shape in shapes: tensor = torch.randn(shape) prepared_tensor, meta = _prepare_tensor(tensor) # Check metadata self.assertEqual(meta.shape, tensor.shape) self.assertEqual(meta.dtype, tensor.dtype) self.assertEqual(meta.storage_offset, tensor.storage_offset()) self.assertEqual(meta.stride, tensor.stride()) self.assertEqual(meta.nbytes, tensor.untyped_storage().nbytes()) def test_prepare_tensor_with_stride(self): """Test preparing tensors with non-standard strides.""" tensor = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=torch.float32) transposed = tensor.t() # Transpose to get non-standard stride prepared_tensor, meta = _prepare_tensor(transposed) # Check metadata self.assertEqual(meta.shape, transposed.shape) self.assertEqual(meta.dtype, transposed.dtype) self.assertEqual(meta.storage_offset, transposed.storage_offset()) self.assertEqual(meta.stride, transposed.stride()) self.assertEqual(meta.nbytes, transposed.untyped_storage().nbytes())
TestPrepareTensor
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/metadata/metadata_set.py
{ "start": 6150, "end": 7317 }
class ____(NamespacedMetadataSet): """Metadata entries that apply to definitions, observations, or materializations of assets that are tables. Args: column_schema (Optional[TableSchema]): The schema of the columns in the table. column_lineage (Optional[TableColumnLineage]): The lineage of column inputs to column outputs for the table. row_count (Optional[int]): The number of rows in the table. partition_row_count (Optional[int]): The number of rows in the materialized or observed partition. table_name (Optional[str]): A unique identifier for the table/view, typically fully qualified. For example, `my_database.my_schema.my_table`. """ column_schema: Optional[TableSchema] = None column_lineage: Optional[TableColumnLineage] = None row_count: Optional[int] = None partition_row_count: Optional[int] = None table_name: Optional[str] = None @classmethod def namespace(cls) -> str: return "dagster" @classmethod def current_key_by_legacy_key(cls) -> Mapping[str, str]: return {"relation_identifier": "table_name"}
TableMetadataSet
python
rq__rq
rq/results.py
{ "start": 399, "end": 8058 }
class ____: class Type(Enum): SUCCESSFUL = 1 FAILED = 2 STOPPED = 3 RETRIED = 4 def __init__( self, job_id: str, type: Type, connection: Redis, id: Optional[str] = None, created_at: Optional[datetime] = None, return_value: Optional[Any] = None, exc_string: Optional[str] = None, worker_name: str = '', serializer=None, ): self.return_value = return_value self.exc_string = exc_string self.type = type self.created_at = created_at if created_at else now() self.serializer = resolve_serializer(serializer) self.connection = connection self.job_id = job_id self.id = id self.worker_name = worker_name def __repr__(self): return f'Result(id={self.id}, type={self.Type(self.type).name})' def __eq__(self, other): try: return self.id == other.id except AttributeError: return False def __bool__(self): return bool(self.id) @classmethod def create(cls, job, type, ttl, return_value=None, exc_string=None, worker_name='', pipeline=None) -> 'Result': result = cls( job_id=job.id, type=type, connection=job.connection, return_value=return_value, exc_string=exc_string, worker_name=worker_name, serializer=job.serializer, ) result.save(ttl=ttl, pipeline=pipeline) return result @classmethod def create_failure(cls, job, ttl, exc_string, worker_name='', pipeline=None) -> 'Result': result = cls( job_id=job.id, type=cls.Type.FAILED, connection=job.connection, exc_string=exc_string, worker_name=worker_name, serializer=job.serializer, ) result.save(ttl=ttl, pipeline=pipeline) return result @classmethod def create_retried(cls, job, ttl, worker_name='', pipeline=None) -> 'Result': result = cls( job_id=job.id, type=cls.Type.RETRIED, connection=job.connection, worker_name=worker_name, serializer=job.serializer, ) result.save(ttl=ttl, pipeline=pipeline) return result @classmethod def all(cls, job: Job, serializer=None): """Returns all results for job""" # response = job.connection.zrange(cls.get_key(job.id), 0, 10, desc=True, withscores=True) response = job.connection.xrevrange(cls.get_key(job.id), '+', '-') results = [] for result_id, payload in response: results.append( cls.restore(job.id, result_id.decode(), payload, connection=job.connection, serializer=serializer) ) return results @classmethod def count(cls, job: Job) -> int: """Returns the number of job results""" return job.connection.xlen(cls.get_key(job.id)) @classmethod def delete_all(cls, job: Job) -> None: """Delete all job results""" job.connection.delete(cls.get_key(job.id)) @classmethod def restore(cls, job_id: str, result_id: str, payload: dict, connection: Redis, serializer=None) -> 'Result': """Create a Result object from given Redis payload""" created_at = datetime.fromtimestamp(int(result_id.split('-')[0]) / 1000, tz=timezone.utc) payload = decode_redis_hash(payload) # data, timestamp = payload # result_data = json.loads(data) # created_at = datetime.fromtimestamp(timestamp, tz=timezone.utc) serializer = resolve_serializer(serializer) return_value = payload.get('return_value') if return_value is not None: return_value = serializer.loads(b64decode(return_value.decode())) exc_string = payload.get('exc_string') if exc_string: exc_string = zlib.decompress(b64decode(exc_string)).decode() worker_name = payload.get('worker_name', b'').decode() if payload.get('worker_name') else '' return Result( job_id, Result.Type(int(payload['type'])), connection=connection, id=result_id, created_at=created_at, return_value=return_value, exc_string=exc_string, worker_name=worker_name, ) @classmethod def fetch(cls, job: Job, serializer=None) -> Optional['Result']: """Fetch a result that matches a given job ID. The current sorted set based implementation does not allow us to fetch a given key by ID so we need to iterate through results, deserialize the payload and look for a matching ID. Future Redis streams based implementation may make this more efficient and scalable. """ return None @classmethod def fetch_latest(cls, job: Job, serializer=None, timeout: int = 0) -> Optional['Result']: """Returns the latest result for given job instance or ID. If a non-zero timeout is provided, block for a result until timeout is reached. """ if timeout: # Unlike blpop, xread timeout is in miliseconds. "0-0" is the special value for the # first item in the stream, like '-' for xrevrange. timeout_ms = timeout * 1000 response = job.connection.xread({cls.get_key(job.id): '0-0'}, block=timeout_ms) if not response: return None response = response[0] # Querying single stream only. response = response[1] # Xread also returns Result.id, which we don't need. result_id, payload = response[-1] # Take most recent result. else: # If not blocking, use xrevrange to load a single result (as xread will load them all). response = job.connection.xrevrange(cls.get_key(job.id), '+', '-', count=1) if not response: return None result_id, payload = response[0] res = cls.restore(job.id, result_id.decode(), payload, connection=job.connection, serializer=serializer) return res @classmethod def get_key(cls, job_id): return 'rq:results:%s' % job_id def save(self, ttl, pipeline=None): """Save result data to Redis""" key = self.get_key(self.job_id) connection = pipeline if pipeline is not None else self.connection # result = connection.zadd(key, {self.serialize(): self.created_at.timestamp()}) result = connection.xadd(key, self.serialize(), maxlen=10) # If xadd() is called in a pipeline, it returns a pipeline object instead of stream ID if pipeline is None: self.id = result.decode() if ttl is not None: if ttl == -1: connection.persist(key) else: connection.expire(key, ttl) return self.id def serialize(self) -> dict[str, Any]: data: dict[str, Any] = {'type': self.type.value, 'worker_name': self.worker_name} if self.exc_string is not None: data['exc_string'] = b64encode(zlib.compress(self.exc_string.encode())).decode() try: serialized = self.serializer.dumps(self.return_value) except: # noqa serialized = self.serializer.dumps(UNSERIALIZABLE_RETURN_VALUE_PAYLOAD) if self.return_value is not None: data['return_value'] = b64encode(serialized).decode() # return json.dumps(data) return data
Result
python
keras-team__keras
keras/src/layers/preprocessing/image_preprocessing/random_erasing_test.py
{ "start": 164, "end": 2800 }
class ____(testing.TestCase): @pytest.mark.requires_trainable_backend def test_layer(self): self.run_layer_test( layers.RandomErasing, init_kwargs={ "factor": 1.0, "scale": 0.5, "fill_value": 0, "value_range": (0, 255), "seed": 1, }, input_shape=(8, 3, 4, 3), supports_masking=False, expected_output_shape=(8, 3, 4, 3), ) def test_random_erasing_inference(self): seed = 3481 layer = layers.RandomErasing() np.random.seed(seed) inputs = np.random.randint(0, 255, size=(224, 224, 3)) output = layer(inputs, training=False) self.assertAllClose(inputs, output) def test_random_erasing_no_op(self): seed = 3481 layer = layers.RandomErasing(factor=0) np.random.seed(seed) inputs = np.random.randint(0, 255, size=(224, 224, 3)) output = layer(inputs) self.assertAllClose(inputs, output) layer = layers.RandomErasing(scale=0) np.random.seed(seed) inputs = np.random.randint(0, 255, size=(224, 224, 3)) output = layer(inputs) self.assertAllClose(inputs, output) def test_random_erasing_basic(self): data_format = backend.config.image_data_format() if data_format == "channels_last": inputs = np.ones((2, 2, 1)) expected_output = np.array([[[[0.0], [1.0]], [[1.0], [1.0]]]]) else: inputs = np.ones((1, 2, 2)) expected_output = np.array( [[[[0.0, 0.0], [1.0, 1.0]], [[1.0, 1.0], [1.0, 1.0]]]] ) layer = layers.RandomErasing(data_format=data_format) transformation = { "apply_erasing": np.asarray([True]), "batch_masks": np.asarray( [[[[True], [False]], [[False], [False]]]] ), "fill_value": 0, } output = layer.transform_images(inputs, transformation) print(output) self.assertAllClose(expected_output, output) def test_tf_data_compatibility(self): data_format = backend.config.image_data_format() if data_format == "channels_last": input_data = np.random.random((2, 8, 8, 3)) else: input_data = np.random.random((2, 3, 8, 8)) layer = layers.RandomErasing(data_format=data_format) ds = tf_data.Dataset.from_tensor_slices(input_data).batch(2).map(layer) for output in ds.take(1): output.numpy()
RandomErasingTest
python
pytorch__pytorch
tools/experimental/torchfuzz/operators/matrix_multiply.py
{ "start": 265, "end": 1246 }
class ____(Operator): """Base class for matrix multiplication operations.""" def __init__(self, name: str): super().__init__(name) def can_produce(self, output_spec: Spec) -> bool: """Matrix multiply operations can produce float/complex tensors of dimension >= 2.""" if not isinstance(output_spec, TensorSpec): return False # Must have at least 2 dimensions for matrix multiplication if len(output_spec.size) < 2: return False # Matrix multiply doesn't work with bool or integer types for gradients if output_spec.dtype in [ torch.bool, torch.int8, torch.int16, torch.int32, torch.int64, ]: return False return True def _get_compatible_dtype(self, output_dtype): """Get a compatible dtype for matrix multiplication.""" return [output_dtype, output_dtype]
MatrixMultiplyOperator
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 7637, "end": 7864 }
class ____(BaseModel): grpc_timeout_ms: int = Field(..., description="") p2p: "P2pConfigTelemetry" = Field(..., description="") consensus: "ConsensusConfigTelemetry" = Field(..., description="")
ClusterConfigTelemetry
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/resource_definition.py
{ "start": 1809, "end": 12306 }
class ____(AnonymousConfigurableDefinition, IHasInternalInit): """Core class for defining resources. Resources are scoped ways to make external resources (like database connections) available to ops and assets during job execution and to clean up after execution resolves. If resource_fn yields once rather than returning (in the manner of functions decorable with :py:func:`@contextlib.contextmanager <python:contextlib.contextmanager>`) then the body of the function after the yield will be run after execution resolves, allowing users to write their own teardown/cleanup logic. Depending on your executor, resources may be instantiated and cleaned up more than once in a job execution. Args: resource_fn (Callable[[InitResourceContext], Any]): User-provided function to instantiate the resource, which will be made available to executions keyed on the ``context.resources`` object. config_schema (Optional[ConfigSchema): The schema for the config. If set, Dagster will check that config provided for the resource matches this schema and fail if it does not. If not set, Dagster will accept any config provided for the resource. description (Optional[str]): A human-readable description of the resource. required_resource_keys: (Optional[Set[str]]) Keys for the resources required by this resource. A DagsterInvariantViolationError will be raised during initialization if dependencies are cyclic. version (Optional[str]): (Beta) The version of the resource's definition fn. Two wrapped resource functions should only have the same version if they produce the same resource definition when provided with the same inputs. """ def __init__( self, resource_fn: ResourceFunction, config_schema: CoercableToConfigSchema = None, description: Optional[str] = None, required_resource_keys: Optional[AbstractSet[str]] = None, version: Optional[str] = None, ): self._resource_fn = check.callable_param(resource_fn, "resource_fn") self._config_schema = convert_user_facing_definition_config_schema(config_schema) self._description = check.opt_str_param(description, "description") self._required_resource_keys = check.opt_set_param( required_resource_keys, "required_resource_keys" ) self._version = check.opt_str_param(version, "version") # this attribute will be updated by the @dagster_maintained_resource and @dagster_maintained_io_manager decorators self._dagster_maintained = False self._hardcoded_resource_type = None @staticmethod def dagster_internal_init( *, resource_fn: ResourceFunction, config_schema: CoercableToConfigSchema, description: Optional[str], required_resource_keys: Optional[AbstractSet[str]], version: Optional[str], ) -> "ResourceDefinition": return ResourceDefinition( resource_fn=resource_fn, config_schema=config_schema, description=description, required_resource_keys=required_resource_keys, version=version, ) @property def resource_fn(self) -> ResourceFunction: return self._resource_fn @property def config_schema(self) -> IDefinitionConfigSchema: return self._config_schema @public @property def description(self) -> Optional[str]: """A human-readable description of the resource.""" return self._description @public @property def version(self) -> Optional[str]: """A string which can be used to identify a particular code version of a resource definition.""" return self._version @public @property def required_resource_keys(self) -> AbstractSet[str]: """A set of the resource keys that this resource depends on. These keys will be made available to the resource's init context during execution, and the resource will not be instantiated until all required resources are available. """ return self._required_resource_keys def get_required_resource_keys( self, resource_defs: Mapping[str, "ResourceDefinition"] ) -> AbstractSet[str]: return self.required_resource_keys def _is_dagster_maintained(self) -> bool: return self._dagster_maintained @public @staticmethod def none_resource(description: Optional[str] = None) -> "ResourceDefinition": """A helper function that returns a none resource. Args: description ([Optional[str]]): The description of the resource. Defaults to None. Returns: [ResourceDefinition]: A resource that does nothing. """ return ResourceDefinition.hardcoded_resource(value=None, description=description) @public @staticmethod def hardcoded_resource(value: Any, description: Optional[str] = None) -> "ResourceDefinition": """A helper function that creates a ``ResourceDefinition`` with a hardcoded object. Args: value (Any): The value that will be accessible via context.resources.resource_name. description ([Optional[str]]): The description of the resource. Defaults to None. Returns: [ResourceDefinition]: A hardcoded resource. """ resource_def = ResourceDefinition( resource_fn=lambda _init_context: value, description=description ) # Make sure telemetry info gets passed in to hardcoded resources if hasattr(value, "_is_dagster_maintained"): resource_def._dagster_maintained = value._is_dagster_maintained() # noqa: SLF001 resource_def._hardcoded_resource_type = type(value) return resource_def @public @staticmethod def mock_resource(description: Optional[str] = None) -> "ResourceDefinition": """A helper function that creates a ``ResourceDefinition`` which wraps a ``mock.MagicMock``. Args: description ([Optional[str]]): The description of the resource. Defaults to None. Returns: [ResourceDefinition]: A resource that creates the magic methods automatically and helps you mock existing resources. """ from unittest import mock return ResourceDefinition( resource_fn=lambda _init_context: mock.MagicMock(), description=description ) @public @staticmethod def string_resource(description: Optional[str] = None) -> "ResourceDefinition": """Creates a ``ResourceDefinition`` which takes in a single string as configuration and returns this configured string to any ops or assets which depend on it. Args: description ([Optional[str]]): The description of the string resource. Defaults to None. Returns: [ResourceDefinition]: A resource that takes in a single string as configuration and returns that string. """ return ResourceDefinition( resource_fn=lambda init_context: init_context.resource_config, config_schema=str, description=description, ) def copy_for_configured( self, description: Optional[str], config_schema: CoercableToConfigSchema, ) -> "ResourceDefinition": resource_def = ResourceDefinition.dagster_internal_init( config_schema=config_schema, description=description or self.description, resource_fn=self.resource_fn, required_resource_keys=self.required_resource_keys, version=self.version, ) resource_def._dagster_maintained = self._is_dagster_maintained() # noqa: SLF001 return resource_def def __call__(self, *args, **kwargs): from dagster._core.execution.context.init import UnboundInitResourceContext if has_at_least_one_parameter(self.resource_fn): if len(args) + len(kwargs) == 0: raise DagsterInvalidInvocationError( "Resource initialization function has context argument, but no context was" " provided when invoking." ) if len(args) + len(kwargs) > 1: raise DagsterInvalidInvocationError( "Initialization of resource received multiple arguments. Only a first " "positional context parameter should be provided when invoking." ) context_param_name = get_function_params(self.resource_fn)[0].name if args: check.opt_inst_param(args[0], context_param_name, UnboundInitResourceContext) return resource_invocation_result( self, cast("Optional[UnboundInitResourceContext]", args[0]) ) else: if context_param_name not in kwargs: raise DagsterInvalidInvocationError( f"Resource initialization expected argument '{context_param_name}'." ) check.opt_inst_param( kwargs[context_param_name], context_param_name, UnboundInitResourceContext ) return resource_invocation_result( self, cast("Optional[UnboundInitResourceContext]", kwargs[context_param_name]) ) elif len(args) + len(kwargs) > 0: raise DagsterInvalidInvocationError( "Attempted to invoke resource with argument, but underlying function has no context" " argument. Either specify a context argument on the resource function, or remove" " the passed-in argument." ) else: return resource_invocation_result(self, None) def get_resource_requirements( self, source_key: Optional[str], ) -> Iterator[ResourceRequirement]: for resource_key in sorted(list(self.required_resource_keys)): yield ResourceDependencyRequirement(key=resource_key, source_key=source_key) def dagster_maintained_resource( resource_def: ResourceDefinition, ) -> ResourceDefinition: resource_def._dagster_maintained = True # noqa: SLF001 return resource_def
ResourceDefinition
python
openai__openai-python
src/openai/types/beta/threads/file_citation_annotation.py
{ "start": 326, "end": 595 }
class ____(BaseModel): end_index: int file_citation: FileCitation start_index: int text: str """The text in the message content that needs to be replaced.""" type: Literal["file_citation"] """Always `file_citation`."""
FileCitationAnnotation
python
huggingface__transformers
src/transformers/models/wav2vec2/configuration_wav2vec2.py
{ "start": 843, "end": 20077 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Wav2Vec2Model`]. It is used to instantiate an Wav2Vec2 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the Wav2Vec2 [facebook/wav2vec2-base-960h](https://huggingface.co/facebook/wav2vec2-base-960h) architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: vocab_size (`int`, *optional*, defaults to 32): Vocabulary size of the Wav2Vec2 model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`Wav2Vec2Model`]. Vocabulary size of the model. Defines the different tokens that can be represented by the *inputs_ids* passed to the forward method of [`Wav2Vec2Model`]. hidden_size (`int`, *optional*, defaults to 768): Dimensionality of the encoder layers and the pooler layer. num_hidden_layers (`int`, *optional*, defaults to 12): Number of hidden layers in the Transformer encoder. num_attention_heads (`int`, *optional*, defaults to 12): Number of attention heads for each attention layer in the Transformer encoder. intermediate_size (`int`, *optional*, defaults to 3072): Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`): The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported. hidden_dropout (`float`, *optional*, defaults to 0.1): The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. activation_dropout (`float`, *optional*, defaults to 0.1): The dropout ratio for activations inside the fully connected layer. attention_dropout (`float`, *optional*, defaults to 0.1): The dropout ratio for the attention probabilities. final_dropout (`float`, *optional*, defaults to 0.1): The dropout probability for the final projection layer of [`Wav2Vec2ForCTC`]. layerdrop (`float`, *optional*, defaults to 0.1): The LayerDrop probability. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556) for more details. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. layer_norm_eps (`float`, *optional*, defaults to 1e-12): The epsilon used by the layer normalization layers. feat_extract_norm (`str`, *optional*, defaults to `"group"`): The norm to be applied to 1D convolutional layers in feature encoder. One of `"group"` for group normalization of only the first 1D convolutional layer or `"layer"` for layer normalization of all 1D convolutional layers. feat_proj_dropout (`float`, *optional*, defaults to 0.0): The dropout probability for output of the feature encoder. feat_extract_activation (`str, `optional`, defaults to `"gelu"`): The non-linear activation function (function or string) in the 1D convolutional layers of the feature extractor. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported. feat_quantizer_dropout (`float`, *optional*, defaults to 0.0): The dropout probability for quantized feature encoder states. conv_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`): A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the feature encoder. The length of *conv_dim* defines the number of 1D convolutional layers. conv_stride (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`): A tuple of integers defining the stride of each 1D convolutional layer in the feature encoder. The length of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*. conv_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 3, 3)`): A tuple of integers defining the kernel size of each 1D convolutional layer in the feature encoder. The length of *conv_kernel* defines the number of convolutional layers and has to match the length of *conv_dim*. conv_bias (`bool`, *optional*, defaults to `False`): Whether the 1D convolutional layers have a bias. num_conv_pos_embeddings (`int`, *optional*, defaults to 128): Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional embeddings layer. num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16): Number of groups of 1D convolutional positional embeddings layer. do_stable_layer_norm (`bool`, *optional*, defaults to `False`): Whether to apply *stable* layer norm architecture of the Transformer encoder. `do_stable_layer_norm is True` corresponds to applying layer norm before the attention layer, whereas `do_stable_layer_norm is False` corresponds to applying layer norm after the attention layer. apply_spec_augment (`bool`, *optional*, defaults to `True`): Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see [SpecAugment: A Simple Data Augmentation Method for Automatic Speech Recognition](https://huggingface.co/papers/1904.08779). mask_time_prob (`float`, *optional*, defaults to 0.05): Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking procedure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector span to be masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`. mask_time_length (`int`, *optional*, defaults to 10): Length of vector span along the time axis. mask_time_min_masks (`int`, *optional*, defaults to 2),: The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step, irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length < mask_time_min_masks'' mask_feature_prob (`float`, *optional*, defaults to 0.0): Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The masking procedure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`. mask_feature_length (`int`, *optional*, defaults to 10): Length of vector span along the feature axis. mask_feature_min_masks (`int`, *optional*, defaults to 0),: The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time step, irrespectively of `mask_feature_prob`. Only relevant if ''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks'' num_codevectors_per_group (`int`, *optional*, defaults to 320): Number of entries in each quantization codebook (group). num_codevector_groups (`int`, *optional*, defaults to 2): Number of codevector groups for product codevector quantization. contrastive_logits_temperature (`float`, *optional*, defaults to 0.1): The temperature *kappa* in the contrastive loss. feat_quantizer_dropout (`float`, *optional*, defaults to 0.0): The dropout probability for the output of the feature encoder that's used by the quantizer. num_negatives (`int`, *optional*, defaults to 100): Number of negative samples for the contrastive loss. codevector_dim (`int`, *optional*, defaults to 256): Dimensionality of the quantized feature vectors. proj_codevector_dim (`int`, *optional*, defaults to 256): Dimensionality of the final projection of both the quantized and the transformer features. diversity_loss_weight (`int`, *optional*, defaults to 0.1): The weight of the codebook diversity loss component. ctc_loss_reduction (`str`, *optional*, defaults to `"sum"`): Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an instance of [`Wav2Vec2ForCTC`]. ctc_zero_infinity (`bool`, *optional*, defaults to `False`): Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance of [`Wav2Vec2ForCTC`]. use_weighted_layer_sum (`bool`, *optional*, defaults to `False`): Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an instance of [`Wav2Vec2ForSequenceClassification`]. classifier_proj_size (`int`, *optional*, defaults to 256): Dimensionality of the projection before token mean-pooling for classification. tdnn_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 1500)`): A tuple of integers defining the number of output channels of each 1D convolutional layer in the *TDNN* module of the *XVector* model. The length of *tdnn_dim* defines the number of *TDNN* layers. tdnn_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 3, 3, 1, 1)`): A tuple of integers defining the kernel size of each 1D convolutional layer in the *TDNN* module of the *XVector* model. The length of *tdnn_kernel* has to match the length of *tdnn_dim*. tdnn_dilation (`tuple[int]` or `list[int]`, *optional*, defaults to `(1, 2, 3, 1, 1)`): A tuple of integers defining the dilation factor of each 1D convolutional layer in *TDNN* module of the *XVector* model. The length of *tdnn_dilation* has to match the length of *tdnn_dim*. xvector_output_dim (`int`, *optional*, defaults to 512): Dimensionality of the *XVector* embedding vectors. add_adapter (`bool`, *optional*, defaults to `False`): Whether a convolutional network should be stacked on top of the Wav2Vec2 Encoder. Can be very useful for warm-starting Wav2Vec2 for SpeechEncoderDecoder models. adapter_kernel_size (`int`, *optional*, defaults to 3): Kernel size of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`. adapter_stride (`int`, *optional*, defaults to 2): Stride of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`. num_adapter_layers (`int`, *optional*, defaults to 3): Number of convolutional layers that should be used in the adapter network. Only relevant if `add_adapter is True`. adapter_attn_dim (`int`, *optional*): Dimension of the attention adapter weights to be used in each attention block. An example of a model using attention adapters is [facebook/mms-1b-all](https://huggingface.co/facebook/mms-1b-all). output_hidden_size (`int`, *optional*): Dimensionality of the encoder output layer. If not defined, this defaults to *hidden-size*. Only relevant if `add_adapter is True`. Example: ```python >>> from transformers import Wav2Vec2Config, Wav2Vec2Model >>> # Initializing a Wav2Vec2 facebook/wav2vec2-base-960h style configuration >>> configuration = Wav2Vec2Config() >>> # Initializing a model (with random weights) from the facebook/wav2vec2-base-960h style configuration >>> model = Wav2Vec2Model(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "wav2vec2" def __init__( self, vocab_size=32, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act="gelu", hidden_dropout=0.1, activation_dropout=0.1, attention_dropout=0.1, feat_proj_dropout=0.0, feat_quantizer_dropout=0.0, final_dropout=0.1, layerdrop=0.1, initializer_range=0.02, layer_norm_eps=1e-5, feat_extract_norm="group", feat_extract_activation="gelu", conv_dim=(512, 512, 512, 512, 512, 512, 512), conv_stride=(5, 2, 2, 2, 2, 2, 2), conv_kernel=(10, 3, 3, 3, 3, 2, 2), conv_bias=False, num_conv_pos_embeddings=128, num_conv_pos_embedding_groups=16, do_stable_layer_norm=False, apply_spec_augment=True, mask_time_prob=0.05, mask_time_length=10, mask_time_min_masks=2, mask_feature_prob=0.0, mask_feature_length=10, mask_feature_min_masks=0, num_codevectors_per_group=320, num_codevector_groups=2, contrastive_logits_temperature=0.1, num_negatives=100, codevector_dim=256, proj_codevector_dim=256, diversity_loss_weight=0.1, ctc_loss_reduction="sum", ctc_zero_infinity=False, use_weighted_layer_sum=False, classifier_proj_size=256, tdnn_dim=(512, 512, 512, 512, 1500), tdnn_kernel=(5, 3, 3, 1, 1), tdnn_dilation=(1, 2, 3, 1, 1), xvector_output_dim=512, pad_token_id=0, bos_token_id=1, eos_token_id=2, add_adapter=False, adapter_kernel_size=3, adapter_stride=2, num_adapter_layers=3, output_hidden_size=None, adapter_attn_dim=None, **kwargs, ): super().__init__(**kwargs, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id) self.hidden_size = hidden_size self.feat_extract_norm = feat_extract_norm self.feat_extract_activation = feat_extract_activation self.conv_dim = list(conv_dim) self.conv_stride = list(conv_stride) self.conv_kernel = list(conv_kernel) self.conv_bias = conv_bias self.num_conv_pos_embeddings = num_conv_pos_embeddings self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups self.num_feat_extract_layers = len(self.conv_dim) self.num_hidden_layers = num_hidden_layers self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.num_attention_heads = num_attention_heads self.hidden_dropout = hidden_dropout self.attention_dropout = attention_dropout self.activation_dropout = activation_dropout self.feat_proj_dropout = feat_proj_dropout self.final_dropout = final_dropout self.layerdrop = layerdrop self.layer_norm_eps = layer_norm_eps self.initializer_range = initializer_range self.vocab_size = vocab_size self.do_stable_layer_norm = do_stable_layer_norm self.use_weighted_layer_sum = use_weighted_layer_sum if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==" " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =" f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`," f" `len(config.conv_kernel) = {len(self.conv_kernel)}`." ) # fine-tuning config parameters for SpecAugment: https://huggingface.co/papers/1904.08779 self.apply_spec_augment = apply_spec_augment self.mask_time_prob = mask_time_prob self.mask_time_length = mask_time_length self.mask_time_min_masks = mask_time_min_masks self.mask_feature_prob = mask_feature_prob self.mask_feature_length = mask_feature_length self.mask_feature_min_masks = mask_feature_min_masks # parameters for pretraining with codevector quantized representations self.num_codevectors_per_group = num_codevectors_per_group self.num_codevector_groups = num_codevector_groups self.contrastive_logits_temperature = contrastive_logits_temperature self.feat_quantizer_dropout = feat_quantizer_dropout self.num_negatives = num_negatives self.codevector_dim = codevector_dim self.proj_codevector_dim = proj_codevector_dim self.diversity_loss_weight = diversity_loss_weight # ctc loss self.ctc_loss_reduction = ctc_loss_reduction self.ctc_zero_infinity = ctc_zero_infinity # adapter self.add_adapter = add_adapter self.adapter_kernel_size = adapter_kernel_size self.adapter_stride = adapter_stride self.num_adapter_layers = num_adapter_layers self.output_hidden_size = output_hidden_size or hidden_size self.adapter_attn_dim = adapter_attn_dim # SequenceClassification-specific parameter. Feel free to ignore for other classes. self.classifier_proj_size = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. self.tdnn_dim = list(tdnn_dim) self.tdnn_kernel = list(tdnn_kernel) self.tdnn_dilation = list(tdnn_dilation) self.xvector_output_dim = xvector_output_dim @property def inputs_to_logits_ratio(self): return functools.reduce(operator.mul, self.conv_stride, 1) __all__ = ["Wav2Vec2Config"]
Wav2Vec2Config
python
getsentry__sentry
src/sentry/preprod/pull_request/comment_types.py
{ "start": 1138, "end": 1507 }
class ____(BaseModel): """Reaction counts on a comment.""" url: str total_count: int plus_one: int = Field(alias="+1") minus_one: int = Field(alias="-1") laugh: int confused: int heart: int hooray: int eyes: int rocket: int class Config: populate_by_name = True # Allow both alias and field name
CommentReactions
python
realpython__materials
arcade-platformer/arcade_platformer/13_pause_view.py
{ "start": 6510, "end": 19359 }
class ____(arcade.View): def __init__(self) -> None: super().__init__() # These lists will hold different sets of sprites self.coins = None self.background = None self.walls = None self.ladders = None self.goals = None self.enemies = None # One sprite for the player, no more is needed self.player = None # We need a physics engine as well self.physics_engine = None # Someplace to keep score self.score = 0 # Which level are we on? self.level = 1 # Load up our sounds here self.coin_sound = arcade.load_sound( str(ASSETS_PATH / "sounds" / "coin.wav") ) self.jump_sound = arcade.load_sound( str(ASSETS_PATH / "sounds" / "jump.wav") ) self.victory_sound = arcade.load_sound( str(ASSETS_PATH / "sounds" / "victory.wav") ) # Check if a joystick is connected joysticks = arcade.get_joysticks() if joysticks: # If so, get the first one self.joystick = joysticks[0] self.joystick.open() else: # If not, flag it so we won't use it print("There are no Joysticks") self.joystick = None def setup(self) -> None: """Sets up the game for the current level""" # Get the current map based on the level map_name = f"platform_level_{self.level:02}.tmx" map_path = ASSETS_PATH / map_name # What are the names of the layers? wall_layer = "ground" coin_layer = "coins" goal_layer = "goal" background_layer = "background" ladders_layer = "ladders" # Load the current map game_map = arcade.tilemap.read_tmx(str(map_path)) # Load the layers self.background = arcade.tilemap.process_layer( game_map, layer_name=background_layer, scaling=MAP_SCALING ) self.goals = arcade.tilemap.process_layer( game_map, layer_name=goal_layer, scaling=MAP_SCALING ) self.walls = arcade.tilemap.process_layer( game_map, layer_name=wall_layer, scaling=MAP_SCALING ) self.ladders = arcade.tilemap.process_layer( game_map, layer_name=ladders_layer, scaling=MAP_SCALING ) self.coins = arcade.tilemap.process_layer( game_map, layer_name=coin_layer, scaling=MAP_SCALING ) # Set the background color background_color = arcade.color.FRESH_AIR if game_map.background_color: background_color = game_map.background_color arcade.set_background_color(background_color) # Find the edge of the map to control viewport scrolling self.map_width = ( game_map.map_size.width - 1 ) * game_map.tile_size.width # Create the player sprite, if they're not already setup if not self.player: self.player = self.create_player_sprite() # Move the player sprite back to the beginning self.player.center_x = PLAYER_START_X self.player.center_y = PLAYER_START_Y self.player.change_x = 0 self.player.change_y = 0 # Reset the viewport self.view_left = 0 self.view_bottom = 0 # Load the physics engine for this map self.physics_engine = arcade.PhysicsEnginePlatformer( player_sprite=self.player, platforms=self.walls, gravity_constant=GRAVITY, ladders=self.ladders, ) def create_player_sprite(self) -> arcade.AnimatedWalkingSprite: # Where are the player images stored? texture_path = ASSETS_PATH / "images" / "player" # Setup the appropriate textures walking_paths = [ texture_path / f"alienGreen_walk{x}.png" for x in (1, 2) ] climbing_paths = [ texture_path / f"alienGreen_climb{x}.png" for x in (1, 2) ] standing_path = texture_path / "alienGreen_stand.png" # Load them all now walking_right_textures = [ arcade.load_texture(texture) for texture in walking_paths ] walking_left_textures = [ arcade.load_texture(texture, mirrored=True) for texture in walking_paths ] walking_up_textures = [ arcade.load_texture(texture) for texture in climbing_paths ] walking_down_textures = [ arcade.load_texture(texture) for texture in climbing_paths ] standing_right_textures = [arcade.load_texture(standing_path)] standing_left_textures = [ arcade.load_texture(standing_path, mirrored=True) ] # Create the sprite player = arcade.AnimatedWalkingSprite() # Add the proper textures player.stand_left_textures = standing_left_textures player.stand_right_textures = standing_right_textures player.walk_left_textures = walking_left_textures player.walk_right_textures = walking_right_textures player.walk_up_textures = walking_up_textures player.walk_down_textures = walking_down_textures # Set the player defaults player.center_x = PLAYER_START_X player.center_y = PLAYER_START_Y player.state = arcade.FACE_RIGHT # Set the initial texture player.texture = player.stand_right_textures[0] return player def on_key_press(self, key: int, modifiers: int) -> None: """Arguments: key -- Which key was pressed modifiers -- Which modifiers were down at the time """ # Check for player left/right movement if key in [arcade.key.LEFT, arcade.key.J]: self.player.change_x = -PLAYER_MOVE_SPEED elif key in [arcade.key.RIGHT, arcade.key.L]: self.player.change_x = PLAYER_MOVE_SPEED # Check if player can climb up or down elif key in [arcade.key.UP, arcade.key.I]: if self.physics_engine.is_on_ladder(): self.player.change_y = PLAYER_MOVE_SPEED elif key in [arcade.key.DOWN, arcade.key.K]: if self.physics_engine.is_on_ladder(): self.player.change_y = -PLAYER_MOVE_SPEED # Check if we can jump elif key == arcade.key.SPACE: if self.physics_engine.can_jump(): self.player.change_y = PLAYER_JUMP_SPEED # Play the jump sound arcade.play_sound(self.jump_sound) # Did the user want to pause? elif key == arcade.key.ESCAPE: # Pass the current view to preserve this view's state pause = PauseView(self) self.window.show_view(pause) def on_key_release(self, key: int, modifiers: int) -> None: """Arguments: key -- The key which was released modifiers -- Which modifiers were down at the time """ # Check for player left/right movement if key in [ arcade.key.LEFT, arcade.key.J, arcade.key.RIGHT, arcade.key.L, ]: self.player.change_x = 0 # Check if player can climb up or down elif key in [ arcade.key.UP, arcade.key.I, arcade.key.DOWN, arcade.key.K, ]: if self.physics_engine.is_on_ladder(): self.player.change_y = 0 def on_update(self, delta_time: float) -> None: """Updates the position of all game objects Arguments: delta_time {float} -- How much time since the last call """ # First, check for joystick movement if self.joystick: # Check if we're in the dead zone if abs(self.joystick.x) > DEAD_ZONE: self.player.change_x = self.joystick.x * PLAYER_MOVE_SPEED else: self.player.change_x = 0 if abs(self.joystick.y) > DEAD_ZONE: if self.physics_engine.is_on_ladder(): self.player.change_y = self.joystick.y * PLAYER_MOVE_SPEED else: self.player.change_y = 0 # Did the user press the jump button? if self.joystick.buttons[0]: if self.physics_engine.can_jump(): self.player.change_y = PLAYER_JUMP_SPEED # Play the jump sound arcade.play_sound(self.jump_sound) # Update the player animation self.player.update_animation(delta_time) # Update player movement based on the physics engine self.physics_engine.update() # Restrict user movement so they can't walk off screen if self.player.left < 0: self.player.left = 0 # Check if we've picked up a coin coins_hit = arcade.check_for_collision_with_list( sprite=self.player, sprite_list=self.coins ) for coin in coins_hit: # Add the coin score to our score self.score += int(coin.properties["point_value"]) # Play the coin sound arcade.play_sound(self.coin_sound) # Remove the coin coin.remove_from_sprite_lists() # Now check if we're at the ending goal goals_hit = arcade.check_for_collision_with_list( sprite=self.player, sprite_list=self.goals ) if goals_hit: # Play the victory sound self.victory_sound.play() # Setup the next level self.level += 1 self.setup() # Set the viewport, scrolling if necessary self.scroll_viewport() def scroll_viewport(self) -> None: """Scrolls the viewport when the player gets close to the edges""" # Scroll left # Find the current left boundary left_boundary = self.view_left + LEFT_VIEWPORT_MARGIN # Are we to the left of this boundary? Then we should scroll left if self.player.left < left_boundary: self.view_left -= left_boundary - self.player.left # But don't scroll past the left edge of the map if self.view_left < 0: self.view_left = 0 # Scroll right # Find the current right boundary right_boundary = self.view_left + SCREEN_WIDTH - RIGHT_VIEWPORT_MARGIN # Are we right of this boundary? Then we should scroll right if self.player.right > right_boundary: self.view_left += self.player.right - right_boundary # Don't scroll past the right edge of the map if self.view_left > self.map_width - SCREEN_WIDTH: self.view_left = self.map_width - SCREEN_WIDTH # Scroll up top_boundary = self.view_bottom + SCREEN_HEIGHT - TOP_VIEWPORT_MARGIN if self.player.top > top_boundary: self.view_bottom += self.player.top - top_boundary # Scroll down bottom_boundary = self.view_bottom + BOTTOM_VIEWPORT_MARGIN if self.player.bottom < bottom_boundary: self.view_bottom -= bottom_boundary - self.player.bottom # Only scroll to integers. Otherwise we end up with pixels that # don't line up on the screen self.view_bottom = int(self.view_bottom) self.view_left = int(self.view_left) # Do the scrolling arcade.set_viewport( left=self.view_left, right=SCREEN_WIDTH + self.view_left, bottom=self.view_bottom, top=SCREEN_HEIGHT + self.view_bottom, ) def on_draw(self) -> None: arcade.start_render() # Draw all the sprites self.background.draw() self.walls.draw() self.coins.draw() self.goals.draw() self.ladders.draw() self.player.draw() # Draw the score in the lower left score_text = f"Score: {self.score}" # First a black background for a shadow effect arcade.draw_text( score_text, start_x=10 + self.view_left, start_y=10 + self.view_bottom, color=arcade.csscolor.BLACK, font_size=40, ) # Now in white slightly shifted arcade.draw_text( score_text, start_x=15 + self.view_left, start_y=15 + self.view_bottom, color=arcade.csscolor.WHITE, font_size=40, ) if __name__ == "__main__": window = arcade.Window( width=SCREEN_WIDTH, height=SCREEN_HEIGHT, title=SCREEN_TITLE ) title_view = TitleView() window.show_view(title_view) arcade.run()
PlatformerView
python
django__django
tests/backends/sqlite/test_functions.py
{ "start": 171, "end": 915 }
class ____(SimpleTestCase): def test_sqlite_date_trunc(self): msg = "Unsupported lookup type: 'unknown-lookup'" with self.assertRaisesMessage(ValueError, msg): _sqlite_date_trunc("unknown-lookup", "2005-08-11", None, None) def test_sqlite_datetime_trunc(self): msg = "Unsupported lookup type: 'unknown-lookup'" with self.assertRaisesMessage(ValueError, msg): _sqlite_datetime_trunc("unknown-lookup", "2005-08-11 1:00:00", None, None) def test_sqlite_time_trunc(self): msg = "Unsupported lookup type: 'unknown-lookup'" with self.assertRaisesMessage(ValueError, msg): _sqlite_time_trunc("unknown-lookup", "2005-08-11 1:00:00", None, None)
FunctionTests
python
ansible__ansible
test/lib/ansible_test/_internal/provider/__init__.py
{ "start": 1494, "end": 1858 }
class ____(ApplicationError): """Exception generated when a path based provider cannot be found for a given path.""" def __init__(self, provider_type: t.Type, path: str) -> None: super().__init__('No %s found for path: %s' % (provider_type.__name__, path)) self.provider_type = provider_type self.path = path
ProviderNotFoundForPath
python
python-excel__xlwt
xlwt/antlr.py
{ "start": 6495, "end": 6627 }
class ____(RecognitionException): def __init__(self, *args): RecognitionException.__init__(self, *args)
SemanticException
python
joblib__joblib
joblib/executor.py
{ "start": 4785, "end": 5229 }
class ____(MemmappingExecutor): """Wrapper around ReusableExecutor to ease memmapping testing with Pool and Executor. This is only for testing purposes. """ def apply_async(self, func, args): """Schedule a func to be run""" future = self.submit(func, *args) future.get = future.result return future def map(self, f, *args): return list(super().map(f, *args))
_TestingMemmappingExecutor
python
facelessuser__soupsieve
tests/test_level3/test_nth_last_of_type.py
{ "start": 63, "end": 1320 }
class ____(util.TestCase): """Test `nth` last of type selectors.""" def test_nth_last_of_type(self): """Test `nth` last of type.""" markup = """ <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id="5"></span> <span id="6"></span> <p id="7"></p> <p id="8"></p> <p id="9"></p> <p id="10"></p> <span id="11"></span> """ self.assert_selector( markup, "p:nth-last-of-type(3)", ['8'], flags=util.HTML ) def test_nth_last_of_type_complex(self): """Test `nth` last of type complex.""" markup = """ <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id="5"></span> <span id="6"></span> <p id="7"></p> <p id="8"></p> <p id="9"></p> <p id="10"></p> <span id="11"></span> """ self.assert_selector( markup, "p:nth-last-of-type(2n + 1)", ['1', '8', '10'], flags=util.HTML )
TestNthLastOfType
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 300948, "end": 301128 }
class ____(ColorScheme): """Cyclical schema wrapper.""" _schema = {"$ref": "#/definitions/Cyclical"} def __init__(self, *args): super().__init__(*args)
Cyclical
python
huggingface__transformers
tests/models/longformer/test_modeling_longformer.py
{ "start": 12855, "end": 17255 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( LongformerModel, LongformerForMaskedLM, LongformerForSequenceClassification, LongformerForQuestionAnswering, LongformerForTokenClassification, LongformerForMultipleChoice, ) if is_torch_available() else () ) pipeline_model_mapping = ( { "feature-extraction": LongformerModel, "fill-mask": LongformerForMaskedLM, "question-answering": LongformerForQuestionAnswering, "text-classification": LongformerForSequenceClassification, "token-classification": LongformerForTokenClassification, "zero-shot": LongformerForSequenceClassification, } if is_torch_available() else {} ) # Need to use `0.6` instead of `0.5` for `test_disk_offload` model_split_percents = [0.6, 0.7, 0.9] # TODO: Fix the failed tests def is_pipeline_test_to_skip( self, pipeline_test_case_name, config_class, model_architecture, tokenizer_name, image_processor_name, feature_extractor_name, processor_name, ): if ( pipeline_test_case_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("Fast") ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def setUp(self): self.model_tester = LongformerModelTester(self) self.config_tester = ConfigTester(self, config_class=LongformerConfig, hidden_size=37) # Without this, 0.01% failure rate. @is_flaky( max_attempts=2, description="When `inputs_dict['attention_mask'][:, -1]` is all `0`s, we get shorter length along the last dimension of the output's `attentions`.", ) def test_attention_outputs(self): super().test_attention_outputs() def test_config(self): self.config_tester.run_common_tests() def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_model_attention_mask_determinism(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_attention_mask_determinism(*config_and_inputs) def test_model_global_attention_mask(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_with_global_attention_mask(*config_and_inputs) def test_for_masked_lm(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*config_and_inputs) def test_for_question_answering(self): config_and_inputs = self.model_tester.prepare_config_and_inputs_for_question_answering() self.model_tester.create_and_check_for_question_answering(*config_and_inputs) def test_for_sequence_classification(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs) def test_for_token_classification(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*config_and_inputs) def test_for_multiple_choice(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs) @unittest.skip(reason="Longformer cannot keep gradients in attention or hidden states") def test_retain_grad_hidden_states_attentions(self): return @unittest.skip(reason="LongFormer calculates global attn only when attn_mask has non-zero elements") def test_batching_equivalence(self): return @require_torch @require_sentencepiece @require_tokenizers
LongformerModelTest
python
falconry__falcon
tests/test_app_initializers.py
{ "start": 241, "end": 1432 }
class ____(media.BaseHandler): def serialize(self, media, content_type): return str(media).encode() def deserialize(self, stream, content_type, content_length): return stream.read().decode() @pytest.fixture def client(request): app = request.param(media_type=falcon.MEDIA_XML) app.add_route('/', MediaResource()) app.resp_options.default_media_type = falcon.MEDIA_TEXT handlers = falcon.media.Handlers({'text/plain': PlainTextHandler()}) app.req_options.media_handlers = handlers app.resp_options.media_handlers = handlers return testing.TestClient(app) @pytest.mark.parametrize( 'client', ( falcon.App, falcon.API, ), indirect=True, ) @pytest.mark.filterwarnings('ignore:Call to deprecated function') def test_api_media_type_overriding(client): response = client.simulate_get('/') assert response.text == "{'foo': 'bar'}" assert response.headers['content-type'] == falcon.MEDIA_TEXT response = client.simulate_post('/', body='foobar', content_type=falcon.MEDIA_TEXT) assert response.text == 'foobar' assert response.headers['content-type'] == falcon.MEDIA_TEXT
PlainTextHandler
python
great-expectations__great_expectations
great_expectations/expectations/metrics/column_aggregate_metrics/column_distinct_values.py
{ "start": 5670, "end": 7725 }
class ____(ColumnAggregateMetricProvider): metric_name = "column.distinct_values.count.under_threshold" condition_keys = ("threshold",) @column_aggregate_value(engine=PandasExecutionEngine) # type: ignore[misc] # untyped-decorator def _pandas(cls, column: pd.Series, threshold: int, **kwargs) -> bool: return column.nunique() < threshold @metric_value(engine=SqlAlchemyExecutionEngine) def _sqlalchemy( cls, metric_value_kwargs: Dict[str, int], metrics: Dict[str, int], **kwargs, ) -> bool: return metrics["column.distinct_values.count"] < metric_value_kwargs["threshold"] @metric_value(engine=SparkDFExecutionEngine) def _spark( cls, metric_value_kwargs: Dict[str, int], metrics: Dict[str, int], **kwargs, ) -> bool: return metrics["column.distinct_values.count"] < metric_value_kwargs["threshold"] @classmethod @override def _get_evaluation_dependencies( cls, metric: MetricConfiguration, configuration: Optional[ExpectationConfiguration] = None, execution_engine: Optional[ExecutionEngine] = None, runtime_configuration: Optional[Dict] = None, ): """Returns a dictionary of given metric names and their corresponding configuration, specifying the metric types and their respective domains""" dependencies: dict = super()._get_evaluation_dependencies( metric=metric, configuration=configuration, execution_engine=execution_engine, runtime_configuration=runtime_configuration, ) if metric.metric_name == "column.distinct_values.count.under_threshold": dependencies["column.distinct_values.count"] = MetricConfiguration( metric_name="column.distinct_values.count", metric_domain_kwargs=metric.metric_domain_kwargs, metric_value_kwargs=None, ) return dependencies
ColumnDistinctValuesCountUnderThreshold
python
tensorflow__tensorflow
tensorflow/python/keras/utils/generic_utils.py
{ "start": 1601, "end": 4491 }
class ____(object): """Exposes custom classes/functions to Keras deserialization internals. Under a scope `with custom_object_scope(objects_dict)`, Keras methods such as `tf.keras.models.load_model` or `tf.keras.models.model_from_config` will be able to deserialize any custom object referenced by a saved config (e.g. a custom layer or metric). Example: Consider a custom regularizer `my_regularizer`: ```python layer = Dense(3, kernel_regularizer=my_regularizer) config = layer.get_config() # Config contains a reference to `my_regularizer` ... # Later: with custom_object_scope({'my_regularizer': my_regularizer}): layer = Dense.from_config(config) ``` Args: *args: Dictionary or dictionaries of `{name: object}` pairs. """ def __init__(self, *args): self.custom_objects = args self.backup = None def __enter__(self): self.backup = _GLOBAL_CUSTOM_OBJECTS.copy() for objects in self.custom_objects: _GLOBAL_CUSTOM_OBJECTS.update(objects) return self def __exit__(self, *args, **kwargs): _GLOBAL_CUSTOM_OBJECTS.clear() _GLOBAL_CUSTOM_OBJECTS.update(self.backup) def get_custom_objects(): """Retrieves a live reference to the global dictionary of custom objects. Updating and clearing custom objects using `custom_object_scope` is preferred, but `get_custom_objects` can be used to directly access the current collection of custom objects. Example: ```python get_custom_objects().clear() get_custom_objects()['MyObject'] = MyObject ``` Returns: Global dictionary of names to classes (`_GLOBAL_CUSTOM_OBJECTS`). """ return _GLOBAL_CUSTOM_OBJECTS # Store a unique, per-object ID for shared objects. # # We store a unique ID for each object so that we may, at loading time, # re-create the network properly. Without this ID, we would have no way of # determining whether a config is a description of a new object that # should be created or is merely a reference to an already-created object. SHARED_OBJECT_KEY = 'shared_object_id' SHARED_OBJECT_DISABLED = threading.local() SHARED_OBJECT_LOADING = threading.local() SHARED_OBJECT_SAVING = threading.local() # Attributes on the threadlocal variable must be set per-thread, thus we # cannot initialize these globally. Instead, we have accessor functions with # default values. def _shared_object_disabled(): """Get whether shared object handling is disabled in a threadsafe manner.""" return getattr(SHARED_OBJECT_DISABLED, 'disabled', False) def _shared_object_loading_scope(): """Get the current shared object saving scope in a threadsafe manner.""" return getattr(SHARED_OBJECT_LOADING, 'scope', NoopLoadingScope()) def _shared_object_saving_scope(): """Get the current shared object saving scope in a threadsafe manner.""" return getattr(SHARED_OBJECT_SAVING, 'scope', None)
CustomObjectScope
python
dagster-io__dagster
python_modules/dagster/dagster/_core/pipes/utils.py
{ "start": 7515, "end": 10154 }
class ____(PipesMessageReader): """Message reader that reads messages by tailing an automatically-generated temporary file.""" def __init__(self, include_stdio_in_messages: bool = False): self._include_stdio_in_messages = check.bool_param( include_stdio_in_messages, "include_stdio_in_messages" ) @contextmanager def read_messages( self, handler: "PipesMessageHandler", ) -> Iterator[PipesParams]: """Set up a thread to read streaming messages from the external process by an automatically-generated temporary file. Args: handler (PipesMessageHandler): object to process incoming messages Yields: PipesParams: A dict of parameters that specifies where a pipes process should write pipes protocol messages. """ with tempfile.TemporaryDirectory() as tempdir: with PipesFileMessageReader( os.path.join(tempdir, _MESSAGE_READER_FILENAME), include_stdio_in_messages=self._include_stdio_in_messages, ).read_messages(handler) as params: yield params def no_messages_debug_text(self) -> str: return "Attempted to read messages from a local temporary file." # Time in seconds to wait between attempts when polling for some condition. Default value that is # used in several places. DEFAULT_SLEEP_INTERVAL = 1 # Wait up to this many seconds for threads to finish executing during cleanup. Note that this must # be longer than WAIT_FOR_LOGS_TIMEOUT. THREAD_WAIT_TIMEOUT = 120 # Buffer period after the external process has completed before we attempt to close out the log # thread. The purpose of this is to allow an external system to update logs to their final state, # which may take some time after the external process has completed. This is subtly different than # `WAIT_FOR_LOGS_TIMEOUT`, which is the amount of time we will wait for targeted log files to exist # at all. In contrast, `WAIT_FOR_LOGS_AFTER_EXECUTION_SECONDS` is used to guard against the case # where log files exist but incomplete immediately after the external process has completed. WAIT_FOR_LOGS_AFTER_EXECUTION_INTERVAL = 10 # Number of seconds to wait after an external process has completed to close # out the log thread. This is necessary because the log thread contains two # points at which it waits indefinitely: (1) for the `opened` message to be # received; (2) for the log files to exist (which may not occur until some time # after the external process has completed). WAIT_FOR_LOGS_TIMEOUT = 60
PipesTempFileMessageReader
python
pappasam__jedi-language-server
jedi_language_server/initialization_options.py
{ "start": 730, "end": 906 }
class ____: disable_snippets: bool = False resolve_eagerly: bool = False ignore_patterns: List[Pattern[str]] = field(default_factory=list) @light_dataclass
Completion
python
ray-project__ray
python/ray/serve/_private/proxy_state.py
{ "start": 3462, "end": 10764 }
class ____(ProxyWrapper): def __init__( self, logging_config: LoggingConfig, actor_handle: Optional[ActorHandle] = None, http_options: Optional[HTTPOptions] = None, grpc_options: Optional[gRPCOptions] = None, name: Optional[str] = None, node_id: Optional[str] = None, node_ip_address: Optional[str] = None, port: Optional[int] = None, proxy_actor_class: Type[ProxyActor] = ProxyActor, ): # initialize with provided proxy actor handle or get or create a new one. self._actor_handle = actor_handle or self._get_or_create_proxy_actor( http_options=http_options, grpc_options=grpc_options, name=name, node_id=node_id, node_ip_address=node_ip_address, port=port, proxy_actor_class=proxy_actor_class, logging_config=logging_config, ) self._ready_check_future = None self._health_check_future = None self._drained_check_future = None self._update_draining_obj_ref = None self._node_id = node_id self.worker_id = None self.log_file_path = None @staticmethod def _get_or_create_proxy_actor( http_options: HTTPOptions, grpc_options: gRPCOptions, name: str, node_id: str, node_ip_address: str, port: int, logging_config: LoggingConfig, proxy_actor_class: Type[ProxyActor] = ProxyActor, ) -> ProxyWrapper: """Helper to start or reuse existing proxy. Takes the name of the proxy, the node id, and the node ip address, and look up or creates a new ProxyActor actor handle for the proxy. """ proxy = None try: proxy = ray.get_actor(name, namespace=SERVE_NAMESPACE) except ValueError: addr = build_address(http_options.host, http_options.port) logger.info( f"Starting proxy on node '{node_id}' listening on '{addr}'.", extra={"log_to_stderr": False}, ) return proxy or proxy_actor_class.options( num_cpus=http_options.num_cpus, name=name, namespace=SERVE_NAMESPACE, lifetime="detached", max_concurrency=ASYNC_CONCURRENCY, max_restarts=0, scheduling_strategy=NodeAffinitySchedulingStrategy(node_id, soft=False), enable_task_events=RAY_SERVE_ENABLE_TASK_EVENTS, ).remote( http_options, grpc_options=grpc_options, node_id=node_id, node_ip_address=node_ip_address, logging_config=logging_config, ) @property def actor_id(self) -> str: """Return the actor id of the proxy actor.""" return self._actor_handle._actor_id.hex() @property def actor_handle(self) -> ActorHandle: """Return the actor handle of the proxy actor. This is used in _start_controller() in _private/controller.py to check whether the proxies exist. It is also used in some tests to access proxy's actor handle. """ return self._actor_handle def is_ready(self, timeout_s: float) -> Optional[bool]: if self._ready_check_future is None: self._ready_check_future = wrap_as_future( self._actor_handle.ready.remote(), timeout_s=timeout_s ) if not self._ready_check_future.done(): return None try: worker_id, log_file_path = json.loads(self._ready_check_future.result()) self.worker_id = worker_id self.log_file_path = log_file_path return True except TimeoutError: logger.warning( f"Proxy actor readiness check for proxy on {self._node_id}" f" didn't complete in {timeout_s}s." ) except Exception: logger.exception( f"Unexpected error invoking readiness check for proxy" f" on {self._node_id}", ) finally: self._ready_check_future = None return False def is_healthy(self, timeout_s: float) -> Optional[bool]: if self._health_check_future is None: self._health_check_future = wrap_as_future( self._actor_handle.check_health.remote(), timeout_s=timeout_s ) if not self._health_check_future.done(): return None try: return self._health_check_future.result() except TimeoutError: logger.warning( f"Didn't receive health check response for proxy" f" on {self._node_id} after {timeout_s}s." ) except Exception: logger.exception( f"Unexpected error invoking health check for proxy " f"on {self._node_id}", ) finally: self._health_check_future = None return False def is_drained(self, timeout_s: float) -> Optional[bool]: if self._drained_check_future is None: self._drained_check_future = wrap_as_future( self._actor_handle.is_drained.remote(), timeout_s=timeout_s, ) if not self._drained_check_future.done(): return None try: is_drained = self._drained_check_future.result() return is_drained except TimeoutError: logger.warning( f"Didn't receive drain check response for proxy" f" on {self._node_id} after {timeout_s}s." ) except Exception: logger.exception( f"Unexpected error invoking drain-check for proxy " f"on {self._node_id}", ) finally: self._drained_check_future = None return False def is_shutdown(self) -> bool: """Return whether the proxy actor is shutdown. If the actor is dead, the health check will return RayActorError. """ try: ray.get(self._actor_handle.check_health.remote(), timeout=0) except RayActorError: # The actor is dead, so it's ready for shutdown. return True except GetTimeoutError: pass # The actor is still alive, so it's not ready for shutdown. return False def update_draining(self, draining: bool): """Update the draining status of the proxy actor.""" # NOTE: All update_draining calls are implicitly serialized, by specifying # `ObjectRef` of the previous call self._update_draining_obj_ref = self._actor_handle.update_draining.remote( draining, _after=self._update_draining_obj_ref ) # In case of cancelled draining, make sure pending draining check is cancelled # as well if not draining: future = self._drained_check_future self._drained_check_future = None if future: future.cancel() def kill(self): """Kill the proxy actor.""" ray.kill(self._actor_handle, no_restart=True)
ActorProxyWrapper
python
django__django
tests/db_utils/tests.py
{ "start": 346, "end": 2322 }
class ____(SimpleTestCase): def test_connection_handler_no_databases(self): """ Empty DATABASES and empty 'default' settings default to the dummy backend. """ for DATABASES in ( {}, # Empty DATABASES setting. {"default": {}}, # Empty 'default' database. ): with self.subTest(DATABASES=DATABASES): self.assertImproperlyConfigured(DATABASES) def assertImproperlyConfigured(self, DATABASES): conns = ConnectionHandler(DATABASES) self.assertEqual( conns[DEFAULT_DB_ALIAS].settings_dict["ENGINE"], "django.db.backends.dummy" ) msg = ( "settings.DATABASES is improperly configured. Please supply the " "ENGINE value. Check settings documentation for more details." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): conns[DEFAULT_DB_ALIAS].ensure_connection() def test_no_default_database(self): DATABASES = {"other": {}} conns = ConnectionHandler(DATABASES) msg = "You must define a 'default' database." with self.assertRaisesMessage(ImproperlyConfigured, msg): conns["other"].ensure_connection() def test_databases_property(self): # The "databases" property is maintained for backwards compatibility # with 3rd party packages. It should be an alias of the "settings" # property. conn = ConnectionHandler({}) self.assertNotEqual(conn.settings, {}) self.assertEqual(conn.settings, conn.databases) def test_nonexistent_alias(self): msg = "The connection 'nonexistent' doesn't exist." conns = ConnectionHandler( { DEFAULT_DB_ALIAS: {"ENGINE": "django.db.backends.dummy"}, } ) with self.assertRaisesMessage(ConnectionDoesNotExist, msg): conns["nonexistent"]
ConnectionHandlerTests
python
bokeh__bokeh
tests/unit/bokeh/embed/test_util__embed.py
{ "start": 5089, "end": 8866 }
class ____: def test_single_model_with_document(self) -> None: # should use existing doc in with-block p = SomeModel() d = Document() orig_theme = d.theme d.add_root(p) with beu.OutputDocumentFor([p]): assert p.document is d assert d.theme is orig_theme assert p.document is d assert d.theme is orig_theme def test_single_model_with_no_document(self) -> None: p = SomeModel() assert p.document is None with beu.OutputDocumentFor([p]): assert p.document is not None assert p.document is not None def test_list_of_model_with_no_documents(self) -> None: # should create new (permanent) doc for inputs p1 = SomeModel() p2 = SomeModel() assert p1.document is None assert p2.document is None with beu.OutputDocumentFor([p1, p2]): assert p1.document is not None assert p2.document is not None assert p1.document is p2.document new_doc = p1.document new_theme = p1.document.theme assert p1.document is new_doc assert p1.document is p2.document assert p1.document.theme is new_theme def test_list_of_model_same_as_roots(self) -> None: # should use existing doc in with-block p1 = SomeModel() p2 = SomeModel() d = Document() orig_theme = d.theme d.add_root(p1) d.add_root(p2) with beu.OutputDocumentFor([p1, p2]): assert p1.document is d assert p2.document is d assert d.theme is orig_theme assert p1.document is d assert p2.document is d assert d.theme is orig_theme def test_list_of_model_same_as_roots_with_always_new(self) -> None: # should use new temp doc for everything inside with-block p1 = SomeModel() p2 = SomeModel() d = Document() orig_theme = d.theme d.add_root(p1) d.add_root(p2) with beu.OutputDocumentFor([p1, p2], always_new=True): assert p1.document is not d assert p2.document is not d assert p1.document is p2.document assert p2.document.theme is orig_theme assert p1.document is d assert p2.document is d assert d.theme is orig_theme def test_list_of_model_subset_roots(self) -> None: # should use new temp doc for subset inside with-block p1 = SomeModel() p2 = SomeModel() d = Document() orig_theme = d.theme d.add_root(p1) d.add_root(p2) with beu.OutputDocumentFor([p1]): assert p1.document is not d assert p2.document is d assert p1.document.theme is orig_theme assert p2.document.theme is orig_theme assert p1.document is d assert p2.document is d assert d.theme is orig_theme def test_list_of_models_different_docs(self) -> None: # should use new temp doc for everything inside with-block d = Document() orig_theme = d.theme p1 = SomeModel() p2 = SomeModel() d.add_root(p2) assert p1.document is None assert p2.document is not None with beu.OutputDocumentFor([p1, p2]): assert p1.document is not None assert p2.document is not None assert p1.document is not d assert p2.document is not d assert p1.document == p2.document assert p1.document.theme is orig_theme assert p1.document is None assert p2.document is not None assert p2.document.theme is orig_theme
Test_OutputDocumentFor_default_apply_theme
python
python-poetry__poetry
src/poetry/mixology/incompatibility_cause.py
{ "start": 470, "end": 1027 }
class ____(IncompatibilityCauseError): """ The incompatibility was derived from two existing incompatibilities during conflict resolution. """ def __init__(self, conflict: Incompatibility, other: Incompatibility) -> None: self._conflict = conflict self._other = other @property def conflict(self) -> Incompatibility: return self._conflict @property def other(self) -> Incompatibility: return self._other def __str__(self) -> str: return str(self._conflict)
ConflictCauseError
python
mlflow__mlflow
mlflow/gateway/config.py
{ "start": 7163, "end": 7376 }
class ____(ConfigModel): mistral_api_key: str @field_validator("mistral_api_key", mode="before") def validate_mistral_api_key(cls, value): return _resolve_api_key_from_input(value)
MistralConfig
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 83943, "end": 84767 }
class ____(Head, Blockwise): """Take the first `n` rows of every partition Typically used after `Partitions(..., [0])` to take the first `n` rows of an entire collection. """ _parameters = ["frame", "n", "npartitions", "safe"] _preserves_partitioning_information = True def _simplify_down(self): return def _simplify_up(self, parent, dependents): return @functools.cached_property def npartitions(self): return len(self._divisions()) - 1 def _divisions(self): return self.frame.divisions[: len(self._partitions) + 1] def _task(self, name: Key, index: int) -> Task: if self.safe: op = safe_head else: op = M.head return Task(name, op, TaskRef((self.frame._name, index)), self.n)
BlockwiseHead
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/pretty_printer.py
{ "start": 784, "end": 4165 }
class ____(gast.NodeVisitor): """Print AST nodes.""" def __init__(self, color, noanno): self.indent_lvl = 0 self.result = '' self.color = color self.noanno = noanno def _color(self, string, color, attrs=None): if self.color: return termcolor.colored(string, color, attrs=attrs) return string def _type(self, node): return self._color(node.__class__.__name__, None, ['bold']) def _field(self, name): return self._color(name, 'blue') def _value(self, name): return self._color(name, 'magenta') def _warning(self, name): return self._color(name, 'red') def _indent(self): return self._color('| ' * self.indent_lvl, None, ['dark']) def _print(self, s): self.result += s self.result += '\n' def generic_visit(self, node, name=None): # In very rare instances, a list can contain something other than a Node. # e.g. Global contains a list of strings. if isinstance(node, str): if name: self._print('%s%s="%s"' % (self._indent(), name, node)) else: self._print('%s"%s"' % (self._indent(), node)) return if node._fields: cont = ':' else: cont = '()' if name: self._print('%s%s=%s%s' % (self._indent(), self._field(name), self._type(node), cont)) else: self._print('%s%s%s' % (self._indent(), self._type(node), cont)) self.indent_lvl += 1 for f in node._fields: if self.noanno and f.startswith('__'): continue if not hasattr(node, f): self._print('%s%s' % (self._indent(), self._warning('%s=<unset>' % f))) continue v = getattr(node, f) if isinstance(v, list): if v: self._print('%s%s=[' % (self._indent(), self._field(f))) self.indent_lvl += 1 for n in v: if n is not None: self.generic_visit(n) else: self._print('%sNone' % (self._indent())) self.indent_lvl -= 1 self._print('%s]' % (self._indent())) else: self._print('%s%s=[]' % (self._indent(), self._field(f))) elif isinstance(v, tuple): if v: self._print('%s%s=(' % (self._indent(), self._field(f))) self.indent_lvl += 1 for n in v: if n is not None: self.generic_visit(n) else: self._print('%sNone' % (self._indent())) self.indent_lvl -= 1 self._print('%s)' % (self._indent())) else: self._print('%s%s=()' % (self._indent(), self._field(f))) elif isinstance(v, gast.AST): self.generic_visit(v, f) elif isinstance(v, bytes): self._print('%s%s=%s' % (self._indent(), self._field(f), self._value('b"%s"' % v))) elif isinstance(v, str): self._print('%s%s=%s' % (self._indent(), self._field(f), self._value('u"%s"' % v))) else: self._print('%s%s=%s' % (self._indent(), self._field(f), self._value(v))) self.indent_lvl -= 1 def fmt(node, color=True, noanno=False): printer = PrettyPrinter(color, noanno) if isinstance(node, (list, tuple)): for n in node: printer.visit(n) else: printer.visit(node) return printer.result
PrettyPrinter
python
walkccc__LeetCode
solutions/2162. Minimum Cost to Set Cooking Time/2162.py
{ "start": 0, "end": 648 }
class ____: def minCostSetTime( self, startAt: int, moveCost: int, pushCost: int, targetSeconds: int, ) -> int: ans = math.inf mins = 99 if targetSeconds > 5999 else targetSeconds // 60 secs = targetSeconds - mins * 60 def getCost(mins: int, secs: int) -> int: cost = 0 curr = str(startAt) for c in str(mins * 100 + secs): if c == curr: cost += pushCost else: cost += moveCost + pushCost curr = c return cost while secs < 100: ans = min(ans, getCost(mins, secs)) mins -= 1 secs += 60 return ans
Solution
python
django-haystack__django-haystack
test_haystack/test_indexes.py
{ "start": 29959, "end": 30853 }
class ____(TestCase): def test_full_prepare(self): index = ModelWithManyToManyFieldAndAttributeLookupSearchIndex() left_model = ManyToManyLeftSideModel.objects.create() right_model_1 = ManyToManyRightSideModel.objects.create(name="Right side 1") right_model_2 = ManyToManyRightSideModel.objects.create() left_model.related_models.add(right_model_1) left_model.related_models.add(right_model_2) result = index.full_prepare(left_model) self.assertDictEqual( result, { "django_ct": "core.manytomanyleftsidemodel", "django_id": "1", "text": None, "id": "core.manytomanyleftsidemodel.1", "related_models": ["Right side 1", "Default name"], }, )
ModelWithManyToManyFieldAndAttributeLookupSearchIndexTestCase
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-file/llama_index/readers/file/video_audio/base.py
{ "start": 336, "end": 2164 }
class ____(BaseReader): """ Video audio parser. Extract text from transcript of video/audio files. """ def __init__(self, *args: Any, model_version: str = "base", **kwargs: Any) -> None: """Init parser.""" super().__init__(*args, **kwargs) self._model_version = model_version try: import whisper except ImportError: raise ImportError( "Please install OpenAI whisper model " "'pip install git+https://github.com/openai/whisper.git' " "to use the model" ) model = whisper.load_model(self._model_version) self.parser_config = {"model": model} def load_data( self, file: Path, extra_info: Optional[Dict] = None, fs: Optional[AbstractFileSystem] = None, ) -> List[Document]: """Parse file.""" import whisper if file.name.endswith("mp4"): try: from pydub import AudioSegment except ImportError: raise ImportError("Please install pydub 'pip install pydub' ") if fs: with fs.open(file, "rb") as f: video = AudioSegment.from_file(f, format="mp4") else: # open file video = AudioSegment.from_file(file, format="mp4") # Extract audio from video audio = video.split_to_mono()[0] file_str = str(file)[:-4] + ".mp3" # export file audio.export(file_str, format="mp3") model = cast(whisper.Whisper, self.parser_config["model"]) result = model.transcribe(str(file)) transcript = result["text"] return [Document(text=transcript, metadata=extra_info or {})]
VideoAudioReader
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 40705, "end": 41021 }
class ____(Blockwise): _parameters = ["frame", "_expr", "expr_kwargs"] _defaults: dict[str, Any] = {"expr_kwargs": {}} # type: ignore[dict-item] _keyword_only = ["expr_kwargs"] operation = M.query @functools.cached_property def _kwargs(self) -> dict: return {**self.expr_kwargs}
Query
python
encode__django-rest-framework
tests/test_validators.py
{ "start": 6024, "end": 6174 }
class ____(serializers.ModelSerializer): class Meta: model = UniquenessTogetherModel fields = '__all__'
UniquenessTogetherSerializer
python
chroma-core__chroma
chromadb/auth/token_authn/__init__.py
{ "start": 740, "end": 1884 }
class ____(str, Enum): """ Accceptable token transport headers. """ # I don't love having this enum here -- it's weird to have an enum # for just two values and it's weird to have users pass X_CHROMA_TOKEN # to configure "x-chroma-token". But I also like having a single source # of truth, so 🤷🏻‍♂️ AUTHORIZATION = "Authorization" X_CHROMA_TOKEN = "X-Chroma-Token" valid_token_chars = set(string.digits + string.ascii_letters + string.punctuation) def _check_token(token: str) -> None: token_str = str(token) if not all(c in valid_token_chars for c in token_str): raise ValueError( "Invalid token. Must contain only ASCII letters, digits, and punctuation." ) allowed_token_headers = [ TokenTransportHeader.AUTHORIZATION.value, TokenTransportHeader.X_CHROMA_TOKEN.value, ] def _check_allowed_token_headers(token_header: str) -> None: if token_header not in allowed_token_headers: raise ValueError( f"Invalid token transport header: {token_header}. " f"Must be one of {allowed_token_headers}" )
TokenTransportHeader
python
numpy__numpy
numpy/ma/tests/test_extras.py
{ "start": 6241, "end": 17360 }
class ____: # Several tests of average. Why so many ? Good point... def test_testAverage1(self): # Test of average. ott = array([0., 1., 2., 3.], mask=[True, False, False, False]) assert_equal(2.0, average(ott, axis=0)) assert_equal(2.0, average(ott, weights=[1., 1., 2., 1.])) result, wts = average(ott, weights=[1., 1., 2., 1.], returned=True) assert_equal(2.0, result) assert_(wts == 4.0) ott[:] = masked assert_equal(average(ott, axis=0).mask, [True]) ott = array([0., 1., 2., 3.], mask=[True, False, False, False]) ott = ott.reshape(2, 2) ott[:, 1] = masked assert_equal(average(ott, axis=0), [2.0, 0.0]) assert_equal(average(ott, axis=1).mask[0], [True]) assert_equal([2., 0.], average(ott, axis=0)) result, wts = average(ott, axis=0, returned=True) assert_equal(wts, [1., 0.]) def test_testAverage2(self): # More tests of average. w1 = [0, 1, 1, 1, 1, 0] w2 = [[0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 1]] x = arange(6, dtype=np.float64) assert_equal(average(x, axis=0), 2.5) assert_equal(average(x, axis=0, weights=w1), 2.5) y = array([arange(6, dtype=np.float64), 2.0 * arange(6)]) assert_equal(average(y, None), np.add.reduce(np.arange(6)) * 3. / 12.) assert_equal(average(y, axis=0), np.arange(6) * 3. / 2.) assert_equal(average(y, axis=1), [average(x, axis=0), average(x, axis=0) * 2.0]) assert_equal(average(y, None, weights=w2), 20. / 6.) assert_equal(average(y, axis=0, weights=w2), [0., 1., 2., 3., 4., 10.]) assert_equal(average(y, axis=1), [average(x, axis=0), average(x, axis=0) * 2.0]) m1 = zeros(6) m2 = [0, 0, 1, 1, 0, 0] m3 = [[0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0]] m4 = ones(6) m5 = [0, 1, 1, 1, 1, 1] assert_equal(average(masked_array(x, m1), axis=0), 2.5) assert_equal(average(masked_array(x, m2), axis=0), 2.5) assert_equal(average(masked_array(x, m4), axis=0).mask, [True]) assert_equal(average(masked_array(x, m5), axis=0), 0.0) assert_equal(count(average(masked_array(x, m4), axis=0)), 0) z = masked_array(y, m3) assert_equal(average(z, None), 20. / 6.) assert_equal(average(z, axis=0), [0., 1., 99., 99., 4.0, 7.5]) assert_equal(average(z, axis=1), [2.5, 5.0]) assert_equal(average(z, axis=0, weights=w2), [0., 1., 99., 99., 4.0, 10.0]) def test_testAverage3(self): # Yet more tests of average! a = arange(6) b = arange(6) * 3 r1, w1 = average([[a, b], [b, a]], axis=1, returned=True) assert_equal(shape(r1), shape(w1)) assert_equal(r1.shape, w1.shape) r2, w2 = average(ones((2, 2, 3)), axis=0, weights=[3, 1], returned=True) assert_equal(shape(w2), shape(r2)) r2, w2 = average(ones((2, 2, 3)), returned=True) assert_equal(shape(w2), shape(r2)) r2, w2 = average(ones((2, 2, 3)), weights=ones((2, 2, 3)), returned=True) assert_equal(shape(w2), shape(r2)) a2d = array([[1, 2], [0, 4]], float) a2dm = masked_array(a2d, [[False, False], [True, False]]) a2da = average(a2d, axis=0) assert_equal(a2da, [0.5, 3.0]) a2dma = average(a2dm, axis=0) assert_equal(a2dma, [1.0, 3.0]) a2dma = average(a2dm, axis=None) assert_equal(a2dma, 7. / 3.) a2dma = average(a2dm, axis=1) assert_equal(a2dma, [1.5, 4.0]) def test_testAverage4(self): # Test that `keepdims` works with average x = np.array([2, 3, 4]).reshape(3, 1) b = np.ma.array(x, mask=[[False], [False], [True]]) w = np.array([4, 5, 6]).reshape(3, 1) actual = average(b, weights=w, axis=1, keepdims=True) desired = masked_array([[2.], [3.], [4.]], [[False], [False], [True]]) assert_equal(actual, desired) def test_weight_and_input_dims_different(self): # this test mirrors a test for np.average() # in lib/test/test_function_base.py y = np.arange(12).reshape(2, 2, 3) w = np.array([0., 0., 1., .5, .5, 0., 0., .5, .5, 1., 0., 0.])\ .reshape(2, 2, 3) m = np.full((2, 2, 3), False) yma = np.ma.array(y, mask=m) subw0 = w[:, :, 0] actual = average(yma, axis=(0, 1), weights=subw0) desired = masked_array([7., 8., 9.], mask=[False, False, False]) assert_almost_equal(actual, desired) m = np.full((2, 2, 3), False) m[:, :, 0] = True m[0, 0, 1] = True yma = np.ma.array(y, mask=m) actual = average(yma, axis=(0, 1), weights=subw0) desired = masked_array( [np.nan, 8., 9.], mask=[True, False, False]) assert_almost_equal(actual, desired) m = np.full((2, 2, 3), False) yma = np.ma.array(y, mask=m) subw1 = w[1, :, :] actual = average(yma, axis=(1, 2), weights=subw1) desired = masked_array([2.25, 8.25], mask=[False, False]) assert_almost_equal(actual, desired) # here the weights have the wrong shape for the specified axes with pytest.raises( ValueError, match="Shape of weights must be consistent with " "shape of a along specified axis"): average(yma, axis=(0, 1, 2), weights=subw0) with pytest.raises( ValueError, match="Shape of weights must be consistent with " "shape of a along specified axis"): average(yma, axis=(0, 1), weights=subw1) # swapping the axes should be same as transposing weights actual = average(yma, axis=(1, 0), weights=subw0) desired = average(yma, axis=(0, 1), weights=subw0.T) assert_almost_equal(actual, desired) def test_onintegers_with_mask(self): # Test average on integers with mask a = average(array([1, 2])) assert_equal(a, 1.5) a = average(array([1, 2, 3, 4], mask=[False, False, True, True])) assert_equal(a, 1.5) def test_complex(self): # Test with complex data. # (Regression test for https://github.com/numpy/numpy/issues/2684) mask = np.array([[0, 0, 0, 1, 0], [0, 1, 0, 0, 0]], dtype=bool) a = masked_array([[0, 1 + 2j, 3 + 4j, 5 + 6j, 7 + 8j], [9j, 0 + 1j, 2 + 3j, 4 + 5j, 7 + 7j]], mask=mask) av = average(a) expected = np.average(a.compressed()) assert_almost_equal(av.real, expected.real) assert_almost_equal(av.imag, expected.imag) av0 = average(a, axis=0) expected0 = average(a.real, axis=0) + average(a.imag, axis=0) * 1j assert_almost_equal(av0.real, expected0.real) assert_almost_equal(av0.imag, expected0.imag) av1 = average(a, axis=1) expected1 = average(a.real, axis=1) + average(a.imag, axis=1) * 1j assert_almost_equal(av1.real, expected1.real) assert_almost_equal(av1.imag, expected1.imag) # Test with the 'weights' argument. wts = np.array([[0.5, 1.0, 2.0, 1.0, 0.5], [1.0, 1.0, 1.0, 1.0, 1.0]]) wav = average(a, weights=wts) expected = np.average(a.compressed(), weights=wts[~mask]) assert_almost_equal(wav.real, expected.real) assert_almost_equal(wav.imag, expected.imag) wav0 = average(a, weights=wts, axis=0) expected0 = (average(a.real, weights=wts, axis=0) + average(a.imag, weights=wts, axis=0) * 1j) assert_almost_equal(wav0.real, expected0.real) assert_almost_equal(wav0.imag, expected0.imag) wav1 = average(a, weights=wts, axis=1) expected1 = (average(a.real, weights=wts, axis=1) + average(a.imag, weights=wts, axis=1) * 1j) assert_almost_equal(wav1.real, expected1.real) assert_almost_equal(wav1.imag, expected1.imag) @pytest.mark.parametrize( 'x, axis, expected_avg, weights, expected_wavg, expected_wsum', [([1, 2, 3], None, [2.0], [3, 4, 1], [1.75], [8.0]), ([[1, 2, 5], [1, 6, 11]], 0, [[1.0, 4.0, 8.0]], [1, 3], [[1.0, 5.0, 9.5]], [[4, 4, 4]])], ) def test_basic_keepdims(self, x, axis, expected_avg, weights, expected_wavg, expected_wsum): avg = np.ma.average(x, axis=axis, keepdims=True) assert avg.shape == np.shape(expected_avg) assert_array_equal(avg, expected_avg) wavg = np.ma.average(x, axis=axis, weights=weights, keepdims=True) assert wavg.shape == np.shape(expected_wavg) assert_array_equal(wavg, expected_wavg) wavg, wsum = np.ma.average(x, axis=axis, weights=weights, returned=True, keepdims=True) assert wavg.shape == np.shape(expected_wavg) assert_array_equal(wavg, expected_wavg) assert wsum.shape == np.shape(expected_wsum) assert_array_equal(wsum, expected_wsum) def test_masked_weights(self): # Test with masked weights. # (Regression test for https://github.com/numpy/numpy/issues/10438) a = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0], [1, 0, 0], [0, 0, 0]]) weights_unmasked = masked_array([5, 28, 31], mask=False) weights_masked = masked_array([5, 28, 31], mask=[1, 0, 0]) avg_unmasked = average(a, axis=0, weights=weights_unmasked, returned=False) expected_unmasked = np.array([6.0, 5.21875, 6.21875]) assert_almost_equal(avg_unmasked, expected_unmasked) avg_masked = average(a, axis=0, weights=weights_masked, returned=False) expected_masked = np.array([6.0, 5.576271186440678, 6.576271186440678]) assert_almost_equal(avg_masked, expected_masked) # weights should be masked if needed # depending on the array mask. This is to avoid summing # masked nan or other values that are not cancelled by a zero a = np.ma.array([1.0, 2.0, 3.0, 4.0], mask=[False, False, True, True]) avg_unmasked = average(a, weights=[1, 1, 1, np.nan]) assert_almost_equal(avg_unmasked, 1.5) a = np.ma.array([ [1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 1.0, 2.0, 3.0], ], mask=[ [False, True, True, False], [True, False, True, True], [True, False, True, False], ]) avg_masked = np.ma.average(a, weights=[1, np.nan, 1], axis=0) avg_expected = np.ma.array([1.0, np.nan, np.nan, 3.5], mask=[False, True, True, False]) assert_almost_equal(avg_masked, avg_expected) assert_equal(avg_masked.mask, avg_expected.mask)
TestAverage
python
huggingface__transformers
src/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py
{ "start": 43079, "end": 63975 }
class ____(Qwen2_5_VLPreTrainedModel): base_model_prefix = "model" _checkpoint_conversion_mapping = {"^model": "language_model"} # Reference: fix gemma3 grad acc #37208 accepts_loss_kwargs = False config: Qwen2_5_VLConfig _no_split_modules = ["Qwen2_5_VLDecoderLayer", "Qwen2_5_VLVisionBlock"] def __init__(self, config): super().__init__(config) self.visual = Qwen2_5_VisionTransformerPretrainedModel._from_config(config.vision_config) self.language_model = Qwen2_5_VLTextModel._from_config(config.text_config) self.rope_deltas = None # cache rope_deltas here # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.language_model.get_input_embeddings() def set_input_embeddings(self, value): self.language_model.set_input_embeddings(value) def get_rope_index( self, input_ids: Optional[torch.LongTensor] = None, image_grid_thw: Optional[torch.LongTensor] = None, video_grid_thw: Optional[torch.LongTensor] = None, second_per_grid_ts: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, ) -> tuple[torch.Tensor, torch.Tensor]: """ Calculate the 3D rope index based on image and video's temporal, height and width in LLM. Explanation: Each embedding sequence contains vision embedding and text embedding or just contains text embedding. For pure text embedding sequence, the rotary position embedding has no difference with modern LLMs. Examples: input_ids: [T T T T T], here T is for text. temporal position_ids: [0, 1, 2, 3, 4] height position_ids: [0, 1, 2, 3, 4] width position_ids: [0, 1, 2, 3, 4] For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part and 1D rotary position embedding for text part. Examples: Temporal (Time): 3 patches, representing different segments of the video in time. Height: 2 patches, dividing each frame vertically. Width: 2 patches, dividing each frame horizontally. We also have some important parameters: fps (Frames Per Second): The video's frame rate, set to 1. This means one frame is processed each second. tokens_per_second: This is a crucial parameter. It dictates how many "time-steps" or "temporal tokens" are conceptually packed into a one-second interval of the video. In this case, we have 25 tokens per second. So each second of the video will be represented with 25 separate time points. It essentially defines the temporal granularity. temporal_patch_size: The number of frames that compose one temporal patch. Here, it's 2 frames. interval: The step size for the temporal position IDs, calculated as tokens_per_second * temporal_patch_size / fps. In this case, 25 * 2 / 1 = 50. This means that each temporal patch will be have a difference of 50 in the temporal position IDs. input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision. vision temporal position_ids: [0, 0, 0, 0, 50, 50, 50, 50, 100, 100, 100, 100] vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1] vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] text temporal position_ids: [101, 102, 103, 104, 105] text height position_ids: [101, 102, 103, 104, 105] text width position_ids: [101, 102, 103, 104, 105] Here we calculate the text start position_ids as the max vision position_ids plus 1. Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*): The temporal, height and width of feature shape of each image in LLM. video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*): The temporal, height and width of feature shape of each video in LLM. second_per_grid_ts (`torch.Tensor` of shape `(num_videos)`, *optional*): The time interval (in seconds) for each grid along the temporal dimension in the 3D position IDs. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. Returns: position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`) mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`) """ spatial_merge_size = self.config.vision_config.spatial_merge_size image_token_id = self.config.image_token_id video_token_id = self.config.video_token_id vision_start_token_id = self.config.vision_start_token_id mrope_position_deltas = [] if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None): total_input_ids = input_ids if attention_mask is not None: attention_mask = attention_mask == 1 position_ids = torch.ones( 3, input_ids.shape[0], input_ids.shape[1], dtype=input_ids.dtype, device=input_ids.device, ) image_index, video_index = 0, 0 for i, input_ids in enumerate(total_input_ids): if attention_mask is not None: input_ids = input_ids[attention_mask[i]] image_nums, video_nums = 0, 0 vision_start_indices = torch.argwhere(input_ids == vision_start_token_id).squeeze(1) vision_tokens = input_ids[vision_start_indices + 1] image_nums = (vision_tokens == image_token_id).sum() video_nums = (vision_tokens == video_token_id).sum() input_tokens = input_ids.tolist() llm_pos_ids_list: list = [] st = 0 remain_images, remain_videos = image_nums, video_nums for _ in range(image_nums + video_nums): if image_token_id in input_tokens and remain_images > 0: ed_image = input_tokens.index(image_token_id, st) else: ed_image = len(input_tokens) + 1 if video_token_id in input_tokens and remain_videos > 0: ed_video = input_tokens.index(video_token_id, st) else: ed_video = len(input_tokens) + 1 if ed_image < ed_video: t, h, w = ( image_grid_thw[image_index][0], image_grid_thw[image_index][1], image_grid_thw[image_index][2], ) second_per_grid_t = 0 image_index += 1 remain_images -= 1 ed = ed_image else: t, h, w = ( video_grid_thw[video_index][0], video_grid_thw[video_index][1], video_grid_thw[video_index][2], ) if second_per_grid_ts is not None: second_per_grid_t = second_per_grid_ts[video_index] else: second_per_grid_t = 1.0 video_index += 1 remain_videos -= 1 ed = ed_video llm_grid_t, llm_grid_h, llm_grid_w = ( t.item(), h.item() // spatial_merge_size, w.item() // spatial_merge_size, ) text_len = ed - st st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) range_tensor = torch.arange(llm_grid_t).view(-1, 1) expanded_range = range_tensor.expand(-1, llm_grid_h * llm_grid_w) ## normalize type, send to device. second_per_grid_t = torch.as_tensor( second_per_grid_t, dtype=range_tensor.dtype, device=range_tensor.device ) time_tensor = expanded_range * second_per_grid_t * self.config.vision_config.tokens_per_second time_tensor_long = time_tensor.long() t_index = time_tensor_long.flatten() h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten() w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten() llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx) st = ed + llm_grid_t * llm_grid_h * llm_grid_w if st < len(input_tokens): st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 text_len = len(input_tokens) - st llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1) if attention_mask is not None: position_ids[..., i, attention_mask[i]] = llm_positions.to(position_ids.device) else: position_ids[..., i, :] = llm_positions.to(position_ids.device) mrope_position_deltas.append(llm_positions.max() + 1 - len(total_input_ids[i])) mrope_position_deltas = torch.tensor(mrope_position_deltas).unsqueeze(1).to(device=input_ids.device) return position_ids, mrope_position_deltas else: if attention_mask is not None: position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) position_ids = position_ids.unsqueeze(0).expand(3, -1, -1).to(attention_mask.device) max_position_ids = position_ids.max(0, keepdim=False)[0].max(-1, keepdim=True)[0] mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1] else: position_ids = ( torch.arange(input_ids.shape[1], device=input_ids.device) .view(1, 1, -1) .expand(3, input_ids.shape[0], -1) ) mrope_position_deltas = torch.zeros( [input_ids.shape[0], 1], device=input_ids.device, dtype=input_ids.dtype, ) return position_ids, mrope_position_deltas def get_video_features( self, pixel_values_videos: torch.FloatTensor, video_grid_thw: Optional[torch.LongTensor] = None ): """ Encodes videos into continuous embeddings that can be forwarded to the language model. Args: pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`): The tensors corresponding to the input videos. video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*): The temporal, height and width of feature shape of each video in LLM. """ pixel_values_videos = pixel_values_videos.type(self.visual.dtype) video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw) split_sizes = (video_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist() video_embeds = torch.split(video_embeds, split_sizes) return video_embeds def get_image_features(self, pixel_values: torch.FloatTensor, image_grid_thw: Optional[torch.LongTensor] = None): """ Encodes images into continuous embeddings that can be forwarded to the language model. Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`): The tensors corresponding to the input images. image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*): The temporal, height and width of feature shape of each image in LLM. """ pixel_values = pixel_values.type(self.visual.dtype) image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw) split_sizes = (image_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist() image_embeds = torch.split(image_embeds, split_sizes) return image_embeds def get_placeholder_mask( self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: Optional[torch.FloatTensor] = None, video_features: Optional[torch.FloatTensor] = None, ): """ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is equal to the length of multimodal features. If the lengths are different, an error is raised. """ if input_ids is None: special_image_mask = inputs_embeds == self.get_input_embeddings()( torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device) ) special_image_mask = special_image_mask.all(-1) special_video_mask = inputs_embeds == self.get_input_embeddings()( torch.tensor(self.config.video_token_id, dtype=torch.long, device=inputs_embeds.device) ) special_video_mask = special_video_mask.all(-1) else: special_image_mask = input_ids == self.config.image_token_id special_video_mask = input_ids == self.config.video_token_id n_image_tokens = special_image_mask.sum() special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device) if image_features is not None and inputs_embeds[special_image_mask].numel() != image_features.numel(): raise ValueError( f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {image_features.shape[0]}" ) n_video_tokens = special_video_mask.sum() special_video_mask = special_video_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device) if video_features is not None and inputs_embeds[special_video_mask].numel() != video_features.numel(): raise ValueError( f"Videos features and video tokens do not match: tokens: {n_video_tokens}, features {video_features.shape[0]}" ) return special_image_mask, special_video_mask @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, pixel_values: Optional[torch.Tensor] = None, pixel_values_videos: Optional[torch.FloatTensor] = None, image_grid_thw: Optional[torch.LongTensor] = None, video_grid_thw: Optional[torch.LongTensor] = None, rope_deltas: Optional[torch.LongTensor] = None, cache_position: Optional[torch.LongTensor] = None, second_per_grid_ts: Optional[torch.Tensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple, Qwen2_5_VLModelOutputWithPast]: r""" image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*): The temporal, height and width of feature shape of each image in LLM. video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*): The temporal, height and width of feature shape of each video in LLM. rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*): The rope index difference between sequence length and multimodal rope. second_per_grid_ts (`torch.Tensor` of shape `(num_videos)`, *optional*): The time interval (in seconds) for each grid along the temporal dimension in the 3D position IDs. """ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict if inputs_embeds is None: inputs_embeds = self.get_input_embeddings()(input_ids) if pixel_values is not None: image_embeds = self.get_image_features(pixel_values, image_grid_thw) image_embeds = torch.cat(image_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype) image_mask, _ = self.get_placeholder_mask( input_ids, inputs_embeds=inputs_embeds, image_features=image_embeds ) inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds) if pixel_values_videos is not None: video_embeds = self.get_video_features(pixel_values_videos, video_grid_thw) video_embeds = torch.cat(video_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype) _, video_mask = self.get_placeholder_mask( input_ids, inputs_embeds=inputs_embeds, video_features=video_embeds ) inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds) if position_ids is None: if self.rope_deltas is None or cache_position is None or cache_position[0] == 0: position_ids, rope_deltas = self.get_rope_index( input_ids, image_grid_thw, video_grid_thw, second_per_grid_ts=second_per_grid_ts, attention_mask=attention_mask, ) self.rope_deltas = rope_deltas else: batch_size, seq_length, _ = inputs_embeds.shape position_ids = torch.arange(seq_length, device=inputs_embeds.device) position_ids = position_ids.view(1, 1, -1).expand(3, batch_size, -1) if cache_position is not None: delta = (cache_position[0] + self.rope_deltas).to(inputs_embeds.device) else: delta = torch.zeros((batch_size, seq_length), device=inputs_embeds.device) delta = delta.repeat_interleave(batch_size // delta.shape[0], dim=1) position_ids = position_ids + delta.to(position_ids.device) outputs = self.language_model( input_ids=None, position_ids=position_ids, attention_mask=attention_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=True, cache_position=cache_position, **kwargs, ) output = Qwen2_5_VLModelOutputWithPast( last_hidden_state=outputs.last_hidden_state, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, rope_deltas=self.rope_deltas, ) return output if return_dict else output.to_tuple() @dataclass @auto_docstring( custom_intro=""" Base class for Qwen2_5_VL causal language model (or autoregressive) outputs. """ )
Qwen2_5_VLModel
python
getsentry__sentry
src/sentry/snuba/metrics/naming_layer/mri.py
{ "start": 2128, "end": 5086 }
class ____(Enum): # Ingested # Do *not* use these metrics in product queries. Use the derived metrics below instead. # The raw metrics do not necessarily add up in intuitive ways. For example, `RAW_SESSION` # double-counts crashed sessions. RAW_SESSION = "c:sessions/session@none" RAW_ERROR = "s:sessions/error@none" RAW_USER = "s:sessions/user@none" RAW_DURATION = "d:sessions/duration@second" # Derived ALL = "e:sessions/all@none" HEALTHY = "e:sessions/healthy@none" ERRORED = "e:sessions/errored@none" ERRORED_PREAGGREGATED = "e:sessions/error.preaggr@none" ERRORED_SET = "e:sessions/error.unique@none" ERRORED_ALL = "e:sessions/all_errored@none" HANDLED = "e:sessions/handled.unique@none" # all sessions excluding handled and crashed UNHANDLED = "e:sessions/unhandled@none" # unhandled, does not include crashed CRASHED_AND_ABNORMAL = "e:sessions/crashed_abnormal@none" CRASHED = "e:sessions/crashed@none" CRASH_FREE = "e:sessions/crash_free@none" ABNORMAL = "e:sessions/abnormal@none" HANDLED_RATE = "e:sessions/handled_rate@ratio" # all sessions excluding handled and crashed UNHANDLED_RATE = "e:sessions/unhandled_rate@ratio" # unhandled, does not include crashed CRASH_RATE = "e:sessions/crash_rate@ratio" CRASH_FREE_RATE = "e:sessions/crash_free_rate@ratio" # includes handled and unhandled ERRORED_RATE = "e:sessions/errored_rate@ratio" ABNORMAL_RATE = "e:sessions/abnormal_rate@ratio" UNHEALTHY_RATE = "e:sessions/unhealthy_rate@ratio" ALL_USER = "e:sessions/user.all@none" HEALTHY_USER = "e:sessions/user.healthy@none" ERRORED_USER = "e:sessions/user.errored@none" ERRORED_USER_ALL = "e:sessions/user.all_errored@none" HANDLED_USER = "e:sessions/user.handled@none" # all sessions excluding handled and crashed UNHANDLED_USER = "e:sessions/user.unhandled@none" # unhandled, does not include crashed CRASHED_AND_ABNORMAL_USER = "e:sessions/user.crashed_abnormal@none" CRASHED_USER = "e:sessions/user.crashed@none" CRASH_FREE_USER = "e:sessions/user.crash_free@none" ABNORMAL_USER = "e:sessions/user.abnormal@none" HANDLED_USER_RATE = ( "e:sessions/user.handled_rate@ratio" # all sessions excluding handled and crashed ) UNHANDLED_USER_RATE = ( "e:sessions/user.unhandled_rate@ratio" # unhandled, does not include crashed ) CRASH_USER_RATE = "e:sessions/user.crash_rate@ratio" CRASH_FREE_USER_RATE = "e:sessions/user.crash_free_rate@ratio" ANR_USER = "e:sessions/user.anr@none" ANR_RATE = "e:sessions/user.anr_rate@ratio" FOREGROUND_ANR_USER = "e:sessions/user.foreground_anr@none" FOREGROUND_ANR_RATE = "e:sessions/user.foreground_anr_rate@ratio" ERRORED_USER_RATE = "e:sessions/user.errored_rate@ratio" ABNORMAL_USER_RATE = "e:sessions/user.abnormal_rate@ratio" DURATION = "d:sessions/duration.exited@second"
SessionMRI
python
Farama-Foundation__Gymnasium
tests/envs/registration/test_env_spec.py
{ "start": 6099, "end": 7262 }
class ____(gym.Env): def __init__(self, unpickleable_obj): self.action_space = gym.spaces.Discrete(2) self.observation_space = gym.spaces.Discrete(2) self.unpickleable_obj = unpickleable_obj def step(self, action): return self.observation_space.sample(), 0, False, False, {} def reset( self, *, seed: int | None = None, options: dict[str, Any] | None = None ) -> tuple[ObsType, dict[str, Any]]: super().reset(seed=seed, options=options) if seed is not None: self.observation_space.seed(seed) return self.observation_space.sample(), {} def test_spec_with_unpickleable_object(): gym.register( id="TestEnv-v0", entry_point=EnvWithUnpickleableObj, kwargs={}, ) env = gym.make("TestEnv-v0", unpickleable_obj=Unpickleable()) with pytest.warns( UserWarning, match=re.escape( "An exception occurred (Cannot pickle me!) while copying the environment spec=" ), ): env.spec check_env(env, skip_render_check=True) env.close() del gym.registry["TestEnv-v0"]
EnvWithUnpickleableObj
python
ray-project__ray
python/ray/serve/tests/test_config_files/use_custom_request_router.py
{ "start": 903, "end": 1184 }
class ____: def __init__(self): context = _get_internal_replica_context() self.replica_id: ReplicaID = context.replica_id async def __call__(self): return "hello_from_custom_request_router" app = UniformRequestRouterApp.bind()
UniformRequestRouterApp
python
PyCQA__pylint
tests/functional/u/unused/unused_private_member.py
{ "start": 2082, "end": 2370 }
class ____: """Regression test for issue 4638""" def __init__(self): type(self).__a() self.__b() Bla.__c() @classmethod def __a(cls): pass @classmethod def __b(cls): pass @classmethod def __c(cls): pass
Bla
python
plotly__plotly.py
plotly/graph_objs/scatterpolar/unselected/_marker.py
{ "start": 233, "end": 4076 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scatterpolar.unselected" _path_str = "scatterpolar.unselected.marker" _valid_props = {"color", "opacity", "size"} @property def color(self): """ Sets the marker color of unselected points, applied only when a selection exists. 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 opacity(self): """ Sets the marker opacity of unselected points, applied only when a selection exists. 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 size(self): """ Sets the marker size of unselected points, applied only when a selection exists. 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 _prop_descriptions(self): return """\ color Sets the marker color of unselected points, applied only when a selection exists. opacity Sets the marker opacity of unselected points, applied only when a selection exists. size Sets the marker size of unselected points, applied only when a selection exists. """ def __init__(self, arg=None, color=None, opacity=None, size=None, **kwargs): """ Construct a new Marker object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scatterpolar.u nselected.Marker` color Sets the marker color of unselected points, applied only when a selection exists. opacity Sets the marker opacity of unselected points, applied only when a selection exists. size Sets the marker size of unselected points, applied only when a selection exists. 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.scatterpolar.unselected.Marker constructor must be a dict or an instance of :class:`plotly.graph_objs.scatterpolar.unselected.Marker`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("color", arg, color) self._set_property("opacity", arg, opacity) self._set_property("size", arg, size) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Marker
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyflakes/F701.py
{ "start": 150, "end": 179 }
class ____: break break
Foo
python
tensorflow__tensorflow
tensorflow/python/ops/image_ops_test.py
{ "start": 203929, "end": 205222 }
class ____(test_util.TensorFlowTestCase): def testFormats(self): prefix = "tensorflow/core/lib" paths = ("png/testdata/lena_gray.png", "jpeg/testdata/jpeg_merge_test1.jpg", "gif/testdata/lena.gif") decoders = { "jpeg": functools.partial(image_ops.decode_jpeg, channels=3), "png": functools.partial(image_ops.decode_png, channels=3), "gif": lambda s: array_ops.squeeze(image_ops.decode_gif(s), axis=0), } with self.cached_session(): for path in paths: contents = self.evaluate(io_ops.read_file(os.path.join(prefix, path))) images = {} for name, decode in decoders.items(): image = self.evaluate(decode(contents)) self.assertEqual(image.ndim, 3) for prev_name, prev in images.items(): print("path %s, names %s %s, shapes %s %s" % (path, name, prev_name, image.shape, prev.shape)) self.assertAllEqual(image, prev) images[name] = image def testError(self): path = "tensorflow/core/lib/gif/testdata/scan.gif" with self.cached_session(): for decode in image_ops.decode_jpeg, image_ops.decode_png: with self.assertRaisesOpError(r"Got 12 frames"): decode(io_ops.read_file(path)).eval()
FormatTest
python
walkccc__LeetCode
solutions/733. Flood Fill/733.py
{ "start": 0, "end": 535 }
class ____: def floodFill(self, image: list[list[int]], sr: int, sc: int, newColor: int) -> list[list[int]]: startColor = image[sr][sc] seen = set() def dfs(i: int, j: int) -> None: if i < 0 or i == len(image) or j < 0 or j == len(image[0]): return if image[i][j] != startColor or (i, j) in seen: return image[i][j] = newColor seen.add((i, j)) dfs(i + 1, j) dfs(i - 1, j) dfs(i, j + 1) dfs(i, j - 1) dfs(sr, sc) return image
Solution
python
keras-team__keras
keras/src/callbacks/swap_ema_weights.py
{ "start": 202, "end": 6843 }
class ____(Callback): """Swaps model weights and EMA weights before and after evaluation. This callbacks replaces the model's weight values with the values of the optimizer's EMA weights (the exponential moving average of the past model weights values, implementing "Polyak averaging") before model evaluation, and restores the previous weights after evaluation. The `SwapEMAWeights` callback is to be used in conjunction with an optimizer that sets `use_ema=True`. Note that the weights are swapped in-place in order to save memory. The behavior is undefined if you modify the EMA weights or model weights in other callbacks. Example: ```python # Remember to set `use_ema=True` in the optimizer optimizer = SGD(use_ema=True) model.compile(optimizer=optimizer, loss=..., metrics=...) # Metrics will be computed with EMA weights model.fit(X_train, Y_train, callbacks=[SwapEMAWeights()]) # If you want to save model checkpoint with EMA weights, you can set # `swap_on_epoch=True` and place ModelCheckpoint after SwapEMAWeights. model.fit( X_train, Y_train, callbacks=[SwapEMAWeights(swap_on_epoch=True), ModelCheckpoint(...)] ) ``` Args: swap_on_epoch: whether to perform swapping at `on_epoch_begin()` and `on_epoch_end()`. This is useful if you want to use EMA weights for other callbacks such as `ModelCheckpoint`. Defaults to `False`. """ def __init__(self, swap_on_epoch=False): super().__init__() self.swap_on_epoch = swap_on_epoch self._ema_weights_in_model = False def _tf_swap_variables(self, optimizer): for var, average_var in zip( self.model.trainable_variables, optimizer._model_variables_moving_average, ): if isinstance(var, backend.Variable): var = var.value if isinstance(average_var, backend.Variable): average_var = average_var.value # swap using addition to prevent variable creation optimizer._distribution_strategy.extended.update( var, lambda a, b: a.assign_add(b), args=(average_var,), ) optimizer._distribution_strategy.extended.update( var, lambda a, b: b.assign(a - b), args=(average_var,), ) optimizer._distribution_strategy.extended.update( var, lambda a, b: a.assign(a - b), args=(average_var,), ) def _backend_swap_variables(self, optimizer): for var, average_var in zip( self.model.trainable_variables, optimizer._model_variables_moving_average, ): temporary_variable = ops.convert_to_numpy(var) var.assign(average_var) average_var.assign(temporary_variable) def _tf_finalize_ema_values(self, optimizer): for var, average_var in zip( self.model.trainable_variables, optimizer._model_variables_moving_average, ): if isinstance(var, backend.Variable): var = var.value if isinstance(average_var, backend.Variable): average_var = average_var.value optimizer._distribution_strategy.extended.update( average_var, lambda a, b: a.assign(b), args=(var,), ) def _backend_finalize_ema_values(self, optimizer): for var, average_var in zip( self.model.trainable_variables, optimizer._model_variables_moving_average, ): average_var.assign(var) def _swap_variables(self): if hasattr(self.model.optimizer, "inner_optimizer"): # LossScaleOptimizer optimizer = self.model.optimizer.inner_optimizer else: optimizer = self.model.optimizer if not hasattr(optimizer, "_model_variables_moving_average"): raise ValueError( "SwapEMAWeights must be used when " "`use_ema=True` is set on the optimizer. " f"Received: use_ema={optimizer.use_ema}" ) if backend.backend() == "tensorflow": self._tf_swap_variables(optimizer) else: self._backend_swap_variables(optimizer) def _finalize_ema_values(self): if hasattr(self.model.optimizer, "inner_optimizer"): # LossScaleOptimizer optimizer = self.model.optimizer.inner_optimizer else: optimizer = self.model.optimizer if not hasattr(optimizer, "_model_variables_moving_average"): raise ValueError( "SwapEMAWeights must be used when " "`use_ema=True` is set on the optimizer. " f"Received: use_ema={optimizer.use_ema}" ) if backend.backend() == "tensorflow": self._tf_finalize_ema_values(optimizer) else: self._backend_finalize_ema_values(optimizer) def on_epoch_begin(self, epoch, logs=None): if self.swap_on_epoch and self._ema_weights_in_model: self._swap_variables() self._ema_weights_in_model = False def on_epoch_end(self, epoch, logs=None): if self.swap_on_epoch and not self._ema_weights_in_model: self._swap_variables() self._ema_weights_in_model = True # We need to recover EMA weights from the previously swapped weights # in the last epoch. This is because, at the end of the fitting, # `finalize_variable_values` will be called to assign # `_model_variables_moving_average` to `trainable_variables`. if epoch == self.params["epochs"] - 1: self._finalize_ema_values() def on_test_begin(self, logs=None): if not self._ema_weights_in_model: self._swap_variables() self._ema_weights_in_model = True def on_test_end(self, logs=None): if self._ema_weights_in_model: self._swap_variables() self._ema_weights_in_model = False def on_predict_begin(self, logs=None): if not self._ema_weights_in_model: self._swap_variables() self._ema_weights_in_model = True def on_predict_end(self, logs=None): if not self._ema_weights_in_model: self._swap_variables() self._ema_weights_in_model = False
SwapEMAWeights
python
spyder-ide__spyder
spyder/plugins/run/confpage.py
{ "start": 6042, "end": 18578 }
class ____(PluginConfigPage): """Default Run Settings configuration page.""" def setup_page(self): self._params_to_delete = {} # --- Executors tab --- self.plugin_container: RunContainer = self.plugin.get_container() self.executor_model = RunExecutorNamesListModel( self, self.plugin_container.executor_model) self.table_model = ExecutorRunParametersTableModel(self) self.table_model.sig_data_changed.connect( self.on_table_data_changed ) self.all_executor_model: Dict[ str, Dict[Tuple[str, str, str], ExtendedRunExecutionParameters]] = {} self.previous_executor_index: int = 0 self.default_executor_conf_params: Dict[ str, Dict[Tuple[str, str, str], ExtendedRunExecutionParameters]] = {} about_label = QLabel( _( "The following are the global configuration presets of the " "different runners that can execute files in Spyder." ) ) about_label.setWordWrap(True) # The paremeters table needs to be created before the executor_combo # below, although is displayed after it. params_label = QLabel(_('Configuration presets:')) self.params_table = RunParametersTableView(self, self.table_model) self.params_table.setMaximumHeight(180) params_table_layout = QHBoxLayout() params_table_layout.addSpacing(2 * AppStyle.MarginSize) params_table_layout.addWidget(self.params_table) params_table_layout.addSpacing(2 * AppStyle.MarginSize) executor_label = QLabel(_("Runner:")) self.executor_combo = SpyderComboBox(self) self.executor_combo.setMinimumWidth(250) self.executor_combo.currentIndexChanged.connect( self.executor_index_changed ) self.executor_combo.setModel(self.executor_model) executor_layout = QHBoxLayout() executor_layout.addWidget(executor_label) executor_layout.addWidget(self.executor_combo) executor_layout.addStretch() # Buttons self.new_configuration_btn = self.create_button( icon=ima.icon("edit_add"), callback=self.create_new_configuration, tooltip=_("New parameters"), ) self.edit_configuration_btn = self.create_button( icon=ima.icon("edit"), callback=self.edit_configuration, tooltip=_("Edit selected"), ) self.clone_configuration_btn = self.create_button( icon=ima.icon("editcopy"), callback=self.clone_configuration, tooltip=_("Clone selected"), ) self.delete_configuration_btn = self.create_button( icon=ima.icon("editclear"), callback=self.delete_configuration, tooltip=_("Delete selected"), ) self.reset_changes_btn = self.create_button( icon=ima.icon("restart"), callback=self.reset_changes, tooltip=_("Reset current changes"), ) # Disable edition button at startup self.set_buttons_status(status=False) # Buttons layout buttons_layout = QHBoxLayout() buttons_layout.addStretch() btns = [ self.new_configuration_btn, self.edit_configuration_btn, self.delete_configuration_btn, self.clone_configuration_btn, self.reset_changes_btn, ] for btn in btns: buttons_layout.addWidget(btn) buttons_layout.addStretch() # Final layout presets_group = QGroupBox(_("Global presets")) presets_layout = QVBoxLayout() presets_group.setLayout(presets_layout) presets_layout.addWidget(about_label) presets_layout.addSpacing(3 * AppStyle.MarginSize) presets_layout.addLayout(executor_layout) presets_layout.addSpacing(3 * AppStyle.MarginSize) presets_layout.addWidget(params_label) presets_layout.addLayout(params_table_layout) presets_layout.addSpacing(AppStyle.MarginSize) presets_layout.addLayout(buttons_layout) # --- Editor interactions tab --- newcb = self.create_checkbox saveall_box = newcb(_("Save all files before running script"), 'save_all_before_run') run_cell_box = newcb(_("Copy full cell contents to the console when " "running code cells"), 'run_cell_copy') run_group = QGroupBox(_("Editor interactions")) run_layout = QVBoxLayout() run_group.setLayout(run_layout) run_layout.addWidget(saveall_box) run_layout.addWidget(run_cell_box) # --- Page layout ---- vlayout = QVBoxLayout() vlayout.addWidget(presets_group) vlayout.addWidget(run_group) vlayout.addStretch() self.setLayout(vlayout) def executor_index_changed(self, index: int): # Save previous executor configuration prev_executor_info = self.table_model.get_current_view() previous_executor_name, _ = self.executor_model.selected_executor( self.previous_executor_index) self.all_executor_model[previous_executor_name] = prev_executor_info # Handle current executor configuration executor, available_inputs = self.executor_model.selected_executor( index) container = self.plugin_container executor_conf_params = self.all_executor_model.get(executor, {}) if executor_conf_params == {}: for (ext, context) in available_inputs: params = container.get_executor_configuration_parameters( executor, ext, context ) params = params["params"] for exec_params_id in params: exec_params = params[exec_params_id] # Don't display configs set for specific files. Here # users are allowed to configure global configs, i.e. those # that can be used by any file. if exec_params.get("file_uuid") is not None: continue params_key = (ext, context, exec_params_id) executor_conf_params[params_key] = exec_params self.default_executor_conf_params[executor] = deepcopy( executor_conf_params) self.all_executor_model[executor] = deepcopy(executor_conf_params) self.table_model.set_parameters(executor_conf_params) self.previous_executor_index = index self.set_buttons_status() def on_table_data_changed(self): # Buttons need to be disabled because the table model is reset when # data is changed and focus is lost self.set_buttons_status(False) self.set_modified(True) def set_buttons_status(self, status=None, is_default=False): # We need to enclose the code below in a try/except because these # buttons might not be created yet, which gives an AttributeError. try: if status is None: status = ( self.table_model.rowCount() != 0 and self.params_table.currentIndex().isValid() ) # Don't allow to delete default configurations if is_default: self.delete_configuration_btn.setEnabled(False) else: self.delete_configuration_btn.setEnabled(status) self.edit_configuration_btn.setEnabled(status) self.clone_configuration_btn.setEnabled(status) except AttributeError: pass def get_executor_configurations(self) -> Dict[ str, SupportedExecutionRunConfiguration]: exec_index = self.executor_combo.currentIndex() executor_name, available_inputs = ( self.executor_model.selected_executor(exec_index) ) executor_params: Dict[str, SupportedExecutionRunConfiguration] = {} extensions: Set[str] = set({}) contexts: Dict[str, List[str]] = {} conf_indices = ( self.plugin_container.executor_model.executor_configurations ) for _input in available_inputs: extension, context = _input extensions |= {extension} ext_contexts = contexts.get(extension, []) ext_contexts.append(context) contexts[extension] = ext_contexts executors = conf_indices[_input] conf = executors[executor_name] executor_params[_input] = conf contexts = { ext: move_file_to_front(ctx) for ext, ctx in contexts.items() } # Localized version of the executor executor_loc_name = self.main.get_plugin(executor_name).get_name() return ( list(sorted(extensions)), contexts, executor_loc_name, executor_params ) def create_new_configuration(self): self.params_table.show_editor(new=True) def edit_configuration(self): self.params_table.show_editor() def clone_configuration(self): self.params_table.clone_configuration() def delete_configuration(self): executor_name, __ = self.executor_model.selected_executor( self.previous_executor_index ) index = self.params_table.currentIndex().row() conf_index = self.table_model.get_tuple_index(index) executor_params = self.table_model.executor_conf_params executor_params.pop(conf_index, None) if executor_name not in self._params_to_delete: self._params_to_delete[executor_name] = [] self._params_to_delete[executor_name].append(conf_index) self.table_model.set_parameters(executor_params) self.table_model.reset_model() self.set_modified(True) self.set_buttons_status() def reset_changes(self): """Reset changes to the parameters loaded when the page was created.""" self.all_executor_model = deepcopy(self.default_executor_conf_params) executor_name, _ = self.executor_model.selected_executor( self.previous_executor_index ) executor_params = self.all_executor_model[executor_name] self.table_model.set_parameters(executor_params) self.table_model.reset_model() self.set_modified(True) self.set_buttons_status() def apply_settings(self): prev_executor_info = self.table_model.get_current_view() previous_executor_name, _ = self.executor_model.selected_executor( self.previous_executor_index ) self.all_executor_model[previous_executor_name] = prev_executor_info # Save new parameters for executor in self.all_executor_model: executor_params = self.all_executor_model[executor] stored_execution_params: Dict[ Tuple[str, str], Dict[str, ExtendedRunExecutionParameters]] = {} for key in executor_params: (extension, context, params_id) = key params = executor_params[key] ext_ctx_list = stored_execution_params.get( (extension, context), {}) ext_ctx_list[params_id] = params stored_execution_params[(extension, context)] = ext_ctx_list for extension, context in stored_execution_params: ext_ctx_list = stored_execution_params[(extension, context)] self.plugin_container.set_executor_configuration_parameters( executor, extension, context, {'params': ext_ctx_list} ) # Delete removed parameters for executor in self._params_to_delete: executor_params_to_delete = self._params_to_delete[executor] for key in executor_params_to_delete: (extension, context, params_id) = key self.plugin_container.delete_executor_configuration_parameters( executor, extension, context, params_id ) self._params_to_delete = {} # This is necessary to prevent giving focus to the executor combobox, # which is odd. self.setFocus() return {'parameters'}
RunConfigPage
python
getsentry__sentry
src/sentry/services/eventstore/reprocessing/base.py
{ "start": 98, "end": 2279 }
class ____(Service): __all__ = ( "event_count_for_hashes", "pop_batched_events", "pop_batched_events_by_key", "get_old_primary_hashes", "expire_hash", "add_hash", "get_remaining_event_count", "rename_key", "mark_event_reprocessed", "start_reprocessing", "get_pending", "get_progress", ) def __init__(self, **options: Any) -> None: pass def event_count_for_hashes( self, project_id: int, group_id: int, old_primary_hashes: set[str] ) -> int: raise NotImplementedError() def pop_batched_events( self, project_id: int, group_id: int, primary_hash: str ) -> tuple[list[str], datetime | None, datetime | None]: raise NotImplementedError() def pop_batched_events_by_key( self, key: str ) -> tuple[list[str], datetime | None, datetime | None]: raise NotImplementedError() def get_old_primary_hashes(self, project_id: int, group_id: int) -> set[Any]: raise NotImplementedError() def expire_hash( self, project_id: int, group_id: int, event_id: str, date_val: datetime, old_primary_hash: str, ) -> None: raise NotImplementedError() def add_hash(self, project_id: int, group_id: int, hash: str) -> None: raise NotImplementedError() def get_remaining_event_count( self, project_id: int, old_group_id: int, datetime_to_event: list[tuple[datetime, str]] ) -> int: raise NotImplementedError() def rename_key(self, project_id: int, old_group_id: int) -> str | None: raise NotImplementedError() def mark_event_reprocessed(self, group_id: int, num_events: int) -> bool: raise NotImplementedError() def start_reprocessing( self, group_id: int, date_created: Any, sync_count: int, event_count: int ) -> None: raise NotImplementedError() def get_pending(self, group_id: int) -> Any: raise NotImplementedError() def get_progress(self, group_id: int) -> dict[str, Any] | None: raise NotImplementedError()
ReprocessingStore
python
numba__numba
numba/tests/test_listobject.py
{ "start": 24373, "end": 25252 }
class ____(MemoryLeakMixin, TestCase): """Test list contains. """ def test_list_contains_empty(self): @njit def foo(i): l = listobject.new_list(int32) return i in l self.assertFalse(foo(0)) self.assertFalse(foo(1)) def test_list_contains_singleton(self): @njit def foo(i): l = listobject.new_list(int32) l.append(0) return i in l self.assertTrue(foo(0)) self.assertFalse(foo(1)) def test_list_contains_multiple(self): @njit def foo(i): l = listobject.new_list(int32) for j in range(10, 20): l.append(j) return i in l for i in range(10, 20): self.assertTrue(foo(i)) for i in range(20, 30): self.assertFalse(foo(i))
TestContains
python
walkccc__LeetCode
solutions/116. Populating Next Right Pointers in Each Node/116.py
{ "start": 0, "end": 375 }
class ____: def connect(self, root: 'Node | None') -> 'Node | None': if not root: return None def connectTwoNodes(p, q) -> None: if not p: return p.next = q connectTwoNodes(p.left, p.right) connectTwoNodes(q.left, q.right) connectTwoNodes(p.right, q.left) connectTwoNodes(root.left, root.right) return root
Solution
python
readthedocs__readthedocs.org
readthedocs/projects/views/private.py
{ "start": 28540, "end": 28651 }
class ____(ProjectRedirectsMixin, CreateView): success_message = _("Redirect created")
ProjectRedirectsCreate
python
apache__airflow
providers/oracle/src/airflow/providers/oracle/hooks/oracle.py
{ "start": 1916, "end": 22250 }
class ____(DbApiHook): """ Interact with Oracle SQL. :param oracle_conn_id: The :ref:`Oracle connection id <howto/connection:oracle>` used for Oracle credentials. :param thick_mode: Specify whether to use python-oracledb in thick mode. Defaults to False. If set to True, you must have the Oracle Client libraries installed. See `oracledb docs<https://python-oracledb.readthedocs.io/en/latest/user_guide/initialization.html>` for more info. :param thick_mode_lib_dir: Path to use to find the Oracle Client libraries when using thick mode. If not specified, defaults to the standard way of locating the Oracle Client library on the OS. See `oracledb docs <https://python-oracledb.readthedocs.io/en/latest/user_guide/initialization.html#setting-the-oracle-client-library-directory>` for more info. :param thick_mode_config_dir: Path to use to find the Oracle Client library configuration files when using thick mode. If not specified, defaults to the standard way of locating the Oracle Client library configuration files on the OS. See `oracledb docs <https://python-oracledb.readthedocs.io/en/latest/user_guide/initialization.html#optional-oracle-net-configuration-files>` for more info. :param fetch_decimals: Specify whether numbers should be fetched as ``decimal.Decimal`` values. See `defaults.fetch_decimals <https://python-oracledb.readthedocs.io/en/latest/api_manual/defaults.html#defaults.fetch_decimals>` for more info. :param fetch_lobs: Specify whether to fetch strings/bytes for CLOBs or BLOBs instead of locators. See `defaults.fetch_lobs <https://python-oracledb.readthedocs.io/en/latest/api_manual/defaults.html#defaults.fetch_decimals>` for more info. """ conn_name_attr = "oracle_conn_id" default_conn_name = "oracle_default" conn_type = "oracle" hook_name = "Oracle" _test_connection_sql = "select 1 from dual" supports_autocommit = True def __init__( self, *args, thick_mode: bool | None = None, thick_mode_lib_dir: str | None = None, thick_mode_config_dir: str | None = None, fetch_decimals: bool | None = None, fetch_lobs: bool | None = None, **kwargs, ) -> None: super().__init__(*args, **kwargs) self.thick_mode = thick_mode self.thick_mode_lib_dir = thick_mode_lib_dir self.thick_mode_config_dir = thick_mode_config_dir self.fetch_decimals = fetch_decimals self.fetch_lobs = fetch_lobs self._service_name: str | None = None self._sid: str | None = None @property def service_name(self) -> str | None: if self._service_name is None: self._service_name = self.get_connection(self.get_conn_id()).extra_dejson.get("service_name") return self._service_name @property def sid(self) -> str | None: if self._sid is None: self._sid = self.get_connection(self.get_conn_id()).extra_dejson.get("sid") return self._sid def get_conn(self) -> oracledb.Connection: """ Get an Oracle connection object. Optional parameters for using a custom DSN connection (instead of using a server alias from tnsnames.ora) The dsn (data source name) is the TNS entry (from the Oracle names server or tnsnames.ora file), or is a string like the one returned from ``makedsn()``. :param dsn: the data source name for the Oracle server :param service_name: the db_unique_name of the database that you are connecting to (CONNECT_DATA part of TNS) :param sid: Oracle System ID that identifies a particular database on a system :param wallet_location: Specify the directory where the wallet can be found. :param wallet_password: the password to use to decrypt the wallet, if it is encrypted. For Oracle Autonomous Database this is the password created when downloading the wallet. :param ssl_server_cert_dn: Specify the distinguished name (DN) which should be matched with the server. This value is ignored if the ``ssl_server_dn_match`` parameter is not set to the value True. :param ssl_server_dn_match: Specify whether the server certificate distinguished name (DN) should be matched in addition to the regular certificate verification that is performed. :param cclass: the connection class to use for Database Resident Connection Pooling (DRCP). :param pool_name: the name of the DRCP pool when using multi-pool DRCP with Oracle Database 23.4, or higher. You can set these parameters in the extra fields of your connection as in .. code-block:: python {"dsn": ("(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=host)(PORT=1521))(CONNECT_DATA=(SID=sid)))")} see more param detail in `oracledb.connect <https://python-oracledb.readthedocs.io/en/latest/api_manual/module.html#oracledb.connect>`_ """ conn = self.get_connection(self.get_conn_id()) conn_config: dict[str, Any] = {"user": conn.login, "password": conn.password} sid = conn.extra_dejson.get("sid") mod = conn.extra_dejson.get("module") schema = conn.schema # Enable oracledb thick mode if thick_mode is set to True # Parameters take precedence over connection config extra # Defaults to use thin mode if not provided in params or connection config extra thick_mode = _get_first_bool(self.thick_mode, conn.extra_dejson.get("thick_mode")) if thick_mode is True: if self.thick_mode_lib_dir is None: self.thick_mode_lib_dir = conn.extra_dejson.get("thick_mode_lib_dir") if not isinstance(self.thick_mode_lib_dir, (str, type(None))): raise TypeError( f"thick_mode_lib_dir expected str or None, " f"got {type(self.thick_mode_lib_dir).__name__}" ) if self.thick_mode_config_dir is None: self.thick_mode_config_dir = conn.extra_dejson.get("thick_mode_config_dir") if not isinstance(self.thick_mode_config_dir, (str, type(None))): raise TypeError( f"thick_mode_config_dir expected str or None, " f"got {type(self.thick_mode_config_dir).__name__}" ) oracledb.init_oracle_client( lib_dir=self.thick_mode_lib_dir, config_dir=self.thick_mode_config_dir ) # Set oracledb Defaults Attributes if provided # (https://python-oracledb.readthedocs.io/en/latest/api_manual/defaults.html) fetch_decimals = _get_first_bool(self.fetch_decimals, conn.extra_dejson.get("fetch_decimals")) if isinstance(fetch_decimals, bool): oracledb.defaults.fetch_decimals = fetch_decimals fetch_lobs = _get_first_bool(self.fetch_lobs, conn.extra_dejson.get("fetch_lobs")) if isinstance(fetch_lobs, bool): oracledb.defaults.fetch_lobs = fetch_lobs # Set up DSN service_name = conn.extra_dejson.get("service_name") port = conn.port if conn.port else DEFAULT_DB_PORT if conn.host and sid and not service_name: conn_config["dsn"] = oracledb.makedsn(conn.host, port, sid) elif conn.host and service_name and not sid: conn_config["dsn"] = oracledb.makedsn(conn.host, port, service_name=service_name) else: dsn = conn.extra_dejson.get("dsn") if dsn is None: dsn = conn.host or "" if conn.port is not None: dsn += f":{conn.port}" if service_name: dsn += f"/{service_name}" conn_config["dsn"] = dsn if "events" in conn.extra_dejson: conn_config["events"] = conn.extra_dejson.get("events") # TODO: Replace mapping with oracledb.AuthMode enum once python-oracledb>=2.3 # mode = getattr(oracledb.AuthMode, conn.extra_dejson.get("mode", "").upper(), None) mode = conn.extra_dejson.get("mode", "").lower() if mode == "sysdba": conn_config["mode"] = oracledb.AUTH_MODE_SYSDBA elif mode == "sysasm": conn_config["mode"] = oracledb.AUTH_MODE_SYSASM elif mode == "sysoper": conn_config["mode"] = oracledb.AUTH_MODE_SYSOPER elif mode == "sysbkp": conn_config["mode"] = oracledb.AUTH_MODE_SYSBKP elif mode == "sysdgd": conn_config["mode"] = oracledb.AUTH_MODE_SYSDGD elif mode == "syskmt": conn_config["mode"] = oracledb.AUTH_MODE_SYSKMT elif mode == "sysrac": conn_config["mode"] = oracledb.AUTH_MODE_SYSRAC # TODO: Replace mapping with oracledb.Purity enum once python-oracledb>=2.3 # purity = getattr(oracledb.Purity, conn.extra_dejson.get("purity", "").upper(), None) purity = conn.extra_dejson.get("purity", "").lower() if purity == "new": conn_config["purity"] = oracledb.PURITY_NEW elif purity == "self": conn_config["purity"] = oracledb.PURITY_SELF elif purity == "default": conn_config["purity"] = oracledb.PURITY_DEFAULT expire_time = conn.extra_dejson.get("expire_time") if expire_time: conn_config["expire_time"] = expire_time for name in [ "wallet_location", "wallet_password", "ssl_server_cert_dn", "ssl_server_dn_match", "cclass", "pool_name", ]: value = conn.extra_dejson.get(name) if value is not None: conn_config[name] = value oracle_conn = oracledb.connect(**conn_config) if mod is not None: oracle_conn.module = mod # if Connection.schema is defined, set schema after connecting successfully # cannot be part of conn_config # https://python-oracledb.readthedocs.io/en/latest/api_manual/connection.html?highlight=schema#Connection.current_schema # Only set schema when not using conn.schema as Service Name if schema and service_name: oracle_conn.current_schema = schema return oracle_conn def insert_rows( self, table: str, rows: list[tuple], target_fields=None, commit_every: int = 1000, replace: bool | None = False, **kwargs, ) -> None: """ Insert a collection of tuples into a table. All data to insert are treated as one transaction. Changes from standard DbApiHook implementation: - Oracle SQL queries can not be terminated with a semicolon (``;``). - Replace NaN values with NULL using ``numpy.nan_to_num`` (not using ``is_nan()`` because of input types error for strings). - Coerce datetime cells to Oracle DATETIME format during insert. :param table: target Oracle table, use dot notation to target a specific database :param rows: the rows to insert into the table :param target_fields: the names of the columns to fill in the table :param commit_every: the maximum number of rows to insert in one transaction Default 1000, Set greater than 0. Set 1 to insert each row in each single transaction :param replace: Whether to replace instead of insert. Currently not implemented. """ if replace: warnings.warn( "Using 'replace=True' does not implement any replace functionality currently.", category=UserWarning, stacklevel=2, ) try: import numpy as np except ImportError: np = None # type: ignore if target_fields: target_fields = ", ".join(target_fields) target_fields = f"({target_fields})" else: target_fields = "" conn = self.get_conn() if self.supports_autocommit: self.set_autocommit(conn, False) cur = conn.cursor() i = 0 for row in rows: i += 1 lst = [] for cell in row: if isinstance(cell, str): lst.append("'" + str(cell).replace("'", "''") + "'") elif cell is None or isinstance(cell, float) and math.isnan(cell): # coerce numpy NaN to NULL lst.append("NULL") elif np and isinstance(cell, np.datetime64): lst.append(f"'{cell}'") elif isinstance(cell, datetime): lst.append(f"to_date('{cell:%Y-%m-%d %H:%M:%S}','YYYY-MM-DD HH24:MI:SS')") else: lst.append(str(cell)) values = tuple(lst) sql = f"INSERT /*+ APPEND */ INTO {table} {target_fields} VALUES ({','.join(values)})" cur.execute(sql) if i % commit_every == 0: conn.commit() self.log.info("Loaded %s into %s rows so far", i, table) conn.commit() cur.close() conn.close() self.log.info("Done loading. Loaded a total of %s rows", i) def bulk_insert_rows( self, table: str, rows: list[tuple], target_fields: list[str] | None = None, commit_every: int = 5000, sequence_column: str | None = None, sequence_name: str | None = None, ): """ Perform bulk inserts efficiently for Oracle DB. This uses prepared statements via `executemany()`. For best performance, pass in `rows` as an iterator. :param table: target Oracle table, use dot notation to target a specific database :param rows: the rows to insert into the table :param target_fields: the names of the columns to fill in the table, default None. If None, each rows should have some order as table columns name :param commit_every: the maximum number of rows to insert in one transaction Default 5000. Set greater than 0. Set 1 to insert each row in each transaction :param sequence_column: the column name to which the sequence will be applied, default None. :param sequence_name: the names of the sequence_name in the table, default None. """ if not rows: raise ValueError("parameter rows could not be None or empty iterable") conn = self.get_conn() if self.supports_autocommit: self.set_autocommit(conn, False) cursor = conn.cursor() values_base = target_fields or rows[0] if bool(sequence_column) ^ bool(sequence_name): raise ValueError( "Parameters 'sequence_column' and 'sequence_name' must be provided together or not at all." ) if sequence_column and sequence_name: columns = ( f"({', '.join([sequence_column] + target_fields)})" if target_fields else f"({sequence_column})" ) value_placeholders = ", ".join( [f"{sequence_name}.NEXTVAL"] + [f":{i}" for i in range(1, len(values_base) + 1)] ) else: columns = f"({', '.join(target_fields)})" if target_fields else "" value_placeholders = ", ".join(f":{i}" for i in range(1, len(values_base) + 1)) prepared_stm = f"insert into {table} {columns} values ({value_placeholders})" row_count = 0 # Chunk the rows row_chunk = [] for row in rows: row_chunk.append(row) row_count += 1 if row_count % commit_every == 0: cursor.prepare(prepared_stm) cursor.executemany(None, row_chunk) conn.commit() self.log.info("[%s] inserted %s rows", table, row_count) # Empty chunk row_chunk = [] # Commit the leftover chunk if row_chunk: cursor.prepare(prepared_stm) cursor.executemany(None, row_chunk) conn.commit() self.log.info("[%s] inserted %s rows", table, row_count) cursor.close() conn.close() def callproc( self, identifier: str, autocommit: bool = False, parameters: list | dict | None = None, ) -> list | dict | tuple | None: """ Call the stored procedure identified by the provided string. Any OUT parameters must be provided with a value of either the expected Python type (e.g., `int`) or an instance of that type. The return value is a list or mapping that includes parameters in both directions; the actual return type depends on the type of the provided `parameters` argument. See https://python-oracledb.readthedocs.io/en/latest/api_manual/cursor.html#Cursor.var for further reference. """ if parameters is None: parameters = [] args = ",".join( f":{name}" for name in (parameters if isinstance(parameters, dict) else range(1, len(parameters) + 1)) ) sql = f"BEGIN {identifier}({args}); END;" def handler(cursor): if cursor.bindvars is None: return if isinstance(cursor.bindvars, list): return [v.getvalue() for v in cursor.bindvars] if isinstance(cursor.bindvars, dict): return {n: v.getvalue() for (n, v) in cursor.bindvars.items()} raise TypeError(f"Unexpected bindvars: {cursor.bindvars!r}") result = self.run( sql, autocommit=autocommit, parameters=( {name: _map_param(value) for (name, value) in parameters.items()} if isinstance(parameters, dict) else [_map_param(value) for value in parameters] ), handler=handler, ) return result def get_openlineage_database_info(self, connection: Connection) -> DatabaseInfo: """Return Oracle specific information for OpenLineage.""" from airflow.providers.openlineage.sqlparser import DatabaseInfo return DatabaseInfo( scheme=self.get_openlineage_database_dialect(connection), authority=DbApiHook.get_openlineage_authority_part(connection, default_port=DEFAULT_DB_PORT), information_schema_table_name="ALL_TAB_COLUMNS", information_schema_columns=[ "owner", "table_name", "column_name", "column_id", "data_type", ], database=self.service_name or self.sid, normalize_name_method=lambda name: name.upper(), ) def get_openlineage_database_dialect(self, _) -> str: """Return database dialect.""" return "oracle" def get_openlineage_default_schema(self) -> str | None: """Return current schema.""" return self.get_first("SELECT SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA') FROM dual")[0] def get_uri(self) -> str: """Get the URI for the Oracle connection.""" conn = self.get_connection(self.get_conn_id()) login = conn.login password = conn.password host = conn.host port = conn.port or DEFAULT_DB_PORT service_name = conn.extra_dejson.get("service_name") sid = conn.extra_dejson.get("sid") if sid and service_name: raise ValueError("At most one allowed for 'sid', and 'service name'.") uri = f"oracle+oracledb://{login}:{password}@{host}:{port}" if service_name: uri = f"{uri}?service_name={service_name}" elif sid: uri = f"{uri}/{sid}" elif conn.schema: uri = f"{uri}/{conn.schema}" return uri
OracleHook
python
conda__conda
tests/plugins/test_env_specs.py
{ "start": 355, "end": 610 }
class ____(EnvironmentSpecBase): def __init__(self, source: str): self.source = source def can_handle(self): raise TypeError("This is a naughty spec") def env(self): raise TypeError("This is a naughty spec")
NaughtySpec
python
allegroai__clearml
clearml/backend_api/services/v2_13/models.py
{ "start": 18489, "end": 21098 }
class ____(Request): """ Add or update model metadata :param model: ID of the model :type model: str :param metadata: Metadata items to add or update :type metadata: Metadata """ _service = "models" _action = "add_or_update_metadata" _version = "2.13" _schema = { "definitions": { "metadata_item": { "properties": { "key": { "description": "The key uniquely identifying the metadata item inside the given entity", "type": "string", }, "type": { "description": "The type of the metadata item", "type": "string", }, "value": { "description": "The value stored in the metadata item", "type": "string", }, }, "type": "object", } }, "properties": { "metadata": { "type": "array", "items": {"$ref": "#/definitions/metadata_item"}, "description": "Metadata items to add or update", }, "model": {"description": "ID of the model", "type": "string"}, }, "required": ["model", "metadata"], "type": "object", } def __init__(self, model: str, metadata: List[Any], **kwargs: Any) -> None: super(AddOrUpdateMetadataRequest, self).__init__(**kwargs) self.model = model self.metadata = metadata @schema_property("model") def model(self) -> str: return self._property_model @model.setter def model(self, value: str) -> None: if value is None: self._property_model = None return self.assert_isinstance(value, "model", six.string_types) self._property_model = value @schema_property("metadata") def metadata(self) -> List[Any]: return self._property_metadata @metadata.setter def metadata(self, value: List[Any]) -> None: if value is None: self._property_metadata = None return self.assert_isinstance(value, "metadata", (list, tuple)) if any((isinstance(v, dict) for v in value)): value = [MetadataItem.from_dict(v) if isinstance(v, dict) else v for v in value] else: self.assert_isinstance(value, "metadata", MetadataItem, is_array=True) self._property_metadata = value
AddOrUpdateMetadataRequest