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
crytic__slither
slither/tools/mutator/mutators/RR.py
{ "start": 214, "end": 1748 }
class ____(AbstractMutator): # pylint: disable=too-few-public-methods NAME = "RR" HELP = "Revert Replacement" def _mutate(self) -> Dict: result: Dict = {} for function in self.contract.functions_and_modifiers_declared: for node in function.nodes: if not self.should_mutate_node(node): continue if node.type not in ( NodeType.ENTRYPOINT, NodeType.IF, NodeType.ENDIF, NodeType.ENDLOOP, NodeType.PLACEHOLDER, ): # Get the string start = node.source_mapping.start stop = start + node.source_mapping.length old_str = node.source_mapping.content line_no = node.source_mapping.lines[0] if node.type == NodeType.RETURN and not old_str.lstrip().startswith("return"): continue # skip the return declarations in fn signatures if not old_str.lstrip().startswith("revert"): new_str = "revert()" create_patch_with_line( result, self.in_file, start, stop, old_str, new_str, line_no, ) return result
RR
python
joke2k__faker
tests/providers/test_lorem.py
{ "start": 30588, "end": 33409 }
class ____: """Test vi_VN lorem provider""" word_list = [word.lower() for word in ViVNLoremProvider.word_list] def test_paragraph(self, faker, num_samples): num_sentences = 10 for _ in range(num_samples): paragraph = faker.paragraph(nb_sentences=num_sentences) assert isinstance(paragraph, str) words = paragraph.replace(".", "").split() assert all(word.lower() in self.word_list for word in words) def test_paragraphs(self, faker, num_samples): num_paragraphs = 5 for _ in range(num_samples): paragraphs = faker.paragraphs(nb=num_paragraphs) for paragraph in paragraphs: assert isinstance(paragraph, str) words = paragraph.replace(".", "").split() assert all(word.lower() in self.word_list for word in words) def test_sentence(self, faker, num_samples): num_words = 10 for _ in range(num_samples): sentence = faker.sentence(nb_words=num_words) assert isinstance(sentence, str) words = sentence.replace(".", "").split() assert all(word.lower() in self.word_list for word in words) def test_sentences(self, faker, num_samples): num_sentences = 5 for _ in range(num_samples): sentences = faker.sentences(nb=num_sentences) for sentence in sentences: assert isinstance(sentence, str) words = sentence.replace(".", "").split() assert all(word.lower() in self.word_list for word in words) def test_text(self, faker, num_samples): num_chars = 25 for _ in range(num_samples): text = faker.text(max_nb_chars=num_chars) assert isinstance(text, str) words = re.sub(r"[.\n]+", " ", text).split() assert all(word.lower() in self.word_list for word in words) def test_texts(self, faker, num_samples): num_texts = 5 num_chars = 25 for _ in range(num_samples): texts = faker.texts(max_nb_chars=num_chars, nb_texts=num_texts) for text in texts: assert isinstance(text, str) words = re.sub(r"[.\n]+", " ", text).split() assert all(word.lower() in self.word_list for word in words) def test_word(self, faker, num_samples): for _ in range(num_samples): word = faker.word() assert isinstance(word, str) and word in ViVNLoremProvider.word_list def test_words(self, faker, num_samples): num_words = 5 for _ in range(num_samples): words = faker.words(num_words) assert all(isinstance(word, str) and word in ViVNLoremProvider.word_list for word in words)
TestViVn
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataproc_metastore.py
{ "start": 23039, "end": 26074 }
class ____(GoogleCloudBaseOperator): """ Delete a single service. :param region: Required. The ID of the Google Cloud region that the service belongs to. :param project_id: Required. The ID of the Google Cloud project that the service belongs to. :param service_id: Required. The ID of the metastore service, which is used as the final component of the metastore service's name. This value must be between 2 and 63 characters long inclusive, begin with a letter, end with a letter or number, and consist of alphanumeric ASCII characters or hyphens. :param retry: Designation of what errors, if any, should be retried. :param timeout: The timeout for this request. :param metadata: Strings which should be sent along with the request as metadata. :param gcp_conn_id: The connection ID to use connecting to Google Cloud. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). """ template_fields: Sequence[str] = ( "project_id", "impersonation_chain", ) def __init__( self, *, region: str, project_id: str, service_id: str, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: super().__init__(**kwargs) self.region = region self.project_id = project_id self.service_id = service_id self.retry = retry self.timeout = timeout self.metadata = metadata self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain def execute(self, context: Context): hook = DataprocMetastoreHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain ) self.log.info("Deleting Dataproc Metastore service: %s", self.service_id) operation = hook.delete_service( region=self.region, project_id=self.project_id, service_id=self.service_id, retry=self.retry, timeout=self.timeout, metadata=self.metadata, ) hook.wait_for_operation(self.timeout, operation) self.log.info("Service %s deleted successfully", self.service_id)
DataprocMetastoreDeleteServiceOperator
python
huggingface__transformers
src/transformers/models/edgetam/modular_edgetam.py
{ "start": 6115, "end": 6165 }
class ____(Sam2LayerNorm): pass
EdgeTamLayerNorm
python
jazzband__django-model-utils
tests/test_fields/test_field_tracker.py
{ "start": 34087, "end": 35168 }
class ____(FieldTrackedModelMultiTests): tracked_class = ModelTrackedMultiple def test_pre_save_has_changed(self) -> None: self.tracker = self.instance.name_tracker self.assertHasChanged(name=True, number=True) self.instance.name = 'new age' self.assertHasChanged(name=True, number=True) self.tracker = self.instance.number_tracker self.assertHasChanged(name=True, number=True) self.instance.name = 'new age' self.assertHasChanged(name=True, number=True) def test_pre_save_changed(self) -> None: self.tracker = self.instance.name_tracker self.assertChanged() self.instance.name = 'new age' self.assertChanged() self.instance.number = 8 self.assertChanged() self.instance.name = '' self.assertChanged() self.tracker = self.instance.number_tracker self.assertChanged() self.instance.name = 'new age' self.assertChanged() self.instance.number = 8 self.assertChanged()
ModelTrackedModelMultiTests
python
readthedocs__readthedocs.org
readthedocs/rtd_tests/tests/test_projects_tasks.py
{ "start": 1938, "end": 3735 }
class ____(TestCase): @patch("readthedocs.projects.tasks.utils.app") def test_finish_unhealthy_builds_task(self, mocked_app): project = get(Project) feature = get(Feature, feature_id=Feature.BUILD_HEALTHCHECK) feature.projects.add(project) # Build just started with the default time and healthcheck now build_1 = get( Build, project=project, version=project.get_stable_version(), state=BUILD_STATE_CLONING, healthcheck=timezone.now(), ) # Build started an hour ago with default time and healthcheck 59s ago build_2 = get( Build, project=project, version=project.get_stable_version(), state=BUILD_STATE_TRIGGERED, date=timezone.now() - datetime.timedelta(hours=1), healthcheck=timezone.now() - datetime.timedelta(seconds=59), ) # Build started an hour ago with custom time (2 hours) and healthcheck 15m ago build_3 = get( Build, project=project, version=project.get_stable_version(), state=BUILD_STATE_TRIGGERED, date=timezone.now() - datetime.timedelta(hours=2), healthcheck=timezone.now() - datetime.timedelta(minutes=15), ) finish_unhealthy_builds() build_1.refresh_from_db() self.assertEqual(build_1.state, BUILD_STATE_CLONING) build_2.refresh_from_db() self.assertEqual(build_2.state, BUILD_STATE_TRIGGERED) build_3.refresh_from_db() self.assertEqual(build_3.state, BUILD_STATE_CANCELLED) self.assertEqual(build_3.success, False) self.assertEqual(build_3.notifications.count(), 1)
TestFinishInactiveBuildsTask
python
django__django
django/views/generic/dates.py
{ "start": 22209, "end": 26913 }
class ____(SingleObjectTemplateResponseMixin, BaseDateDetailView): """ Detail view of a single object on a single date; this differs from the standard DetailView by accepting a year/month/day in the URL. """ template_name_suffix = "_detail" def _date_from_string( year, year_format, month="", month_format="", day="", day_format="", delim="__" ): """ Get a datetime.date object given a format string and a year, month, and day (only year is mandatory). Raise a 404 for an invalid date. """ format = year_format + delim + month_format + delim + day_format datestr = str(year) + delim + str(month) + delim + str(day) try: return datetime.datetime.strptime(datestr, format).date() except ValueError: raise Http404( _("Invalid date string “%(datestr)s” given format “%(format)s”") % { "datestr": datestr, "format": format, } ) def _get_next_prev(generic_view, date, is_previous, period): """ Get the next or the previous valid date. The idea is to allow links on month/day views to never be 404s by never providing a date that'll be invalid for the given view. This is a bit complicated since it handles different intervals of time, hence the coupling to generic_view. However in essence the logic comes down to: * If allow_empty and allow_future are both true, this is easy: just return the naive result (just the next/previous day/week/month, regardless of object existence.) * If allow_empty is true, allow_future is false, and the naive result isn't in the future, then return it; otherwise return None. * If allow_empty is false and allow_future is true, return the next date *that contains a valid object*, even if it's in the future. If there are no next objects, return None. * If allow_empty is false and allow_future is false, return the next date that contains a valid object. If that date is in the future, or if there are no next objects, return None. """ date_field = generic_view.get_date_field() allow_empty = generic_view.get_allow_empty() allow_future = generic_view.get_allow_future() get_current = getattr(generic_view, "_get_current_%s" % period) get_next = getattr(generic_view, "_get_next_%s" % period) # Bounds of the current interval start, end = get_current(date), get_next(date) # If allow_empty is True, the naive result will be valid if allow_empty: if is_previous: result = get_current(start - datetime.timedelta(days=1)) else: result = end if allow_future or result <= timezone_today(): return result else: return None # Otherwise, we'll need to go to the database to look for an object # whose date_field is at least (greater than/less than) the given # naive result else: # Construct a lookup and an ordering depending on whether we're doing # a previous date or a next date lookup. if is_previous: lookup = {"%s__lt" % date_field: generic_view._make_date_lookup_arg(start)} ordering = "-%s" % date_field else: lookup = {"%s__gte" % date_field: generic_view._make_date_lookup_arg(end)} ordering = date_field # Filter out objects in the future if appropriate. if not allow_future: # Fortunately, to match the implementation of allow_future, # we need __lte, which doesn't conflict with __lt above. if generic_view.uses_datetime_field: now = timezone.now() else: now = timezone_today() lookup["%s__lte" % date_field] = now qs = generic_view.get_queryset().filter(**lookup).order_by(ordering) # Snag the first object from the queryset; if it doesn't exist that # means there's no next/previous link available. try: result = getattr(qs[0], date_field) except IndexError: return None # Convert datetimes to dates in the current time zone. if generic_view.uses_datetime_field: if settings.USE_TZ: result = timezone.localtime(result) result = result.date() # Return the first day of the period. return get_current(result) def timezone_today(): """Return the current date in the current time zone.""" if settings.USE_TZ: return timezone.localdate() else: return datetime.date.today()
DateDetailView
python
apache__airflow
providers/standard/tests/unit/standard/sensors/test_time_delta.py
{ "start": 1964, "end": 5274 }
class ____: def setup_method(self): self.dagbag = DagBag(dag_folder=DEV_NULL, include_examples=False) self.dag = DAG(TEST_DAG_ID, schedule=timedelta(days=1), start_date=DEFAULT_DATE) def test_timedelta_sensor(self, mocker): op = TimeDeltaSensor(task_id="timedelta_sensor_check", delta=timedelta(seconds=2), dag=self.dag) op.execute({"dag_run": mocker.MagicMock(run_after=DEFAULT_DATE), "data_interval_end": DEFAULT_DATE}) @pytest.mark.parametrize( ("run_after", "interval_end"), [ (timezone.utcnow() + timedelta(days=1), timezone.utcnow() + timedelta(days=2)), (timezone.utcnow() + timedelta(days=1), None), ], ) def test_timedelta_sensor_run_after_vs_interval(run_after, interval_end, dag_maker, session): """Interval end should be used as base time when present else run_after""" if not AIRFLOW_V_3_0_PLUS and not interval_end: pytest.skip("not applicable") context = {} if interval_end: context["data_interval_end"] = interval_end delta = timedelta(seconds=1) with dag_maker(): op = TimeDeltaSensor(task_id="wait_sensor_check", delta=delta, mode="reschedule") kwargs = {} if AIRFLOW_V_3_0_PLUS: from airflow.utils.types import DagRunTriggeredByType kwargs.update(triggered_by=DagRunTriggeredByType.TEST, run_after=run_after) dr = dag_maker.create_dagrun( run_id="abcrhroceuh", run_type=DagRunType.MANUAL, state=None, session=session, **kwargs, ) ti = dr.task_instances[0] context.update(dag_run=dr, ti=ti) expected = interval_end or run_after actual = op._derive_base_time(context) assert actual == expected @pytest.mark.parametrize( ("run_after", "interval_end"), [ (timezone.utcnow() + timedelta(days=1), timezone.utcnow() + timedelta(days=2)), (timezone.utcnow() + timedelta(days=1), None), ], ) def test_timedelta_sensor_deferrable_run_after_vs_interval(run_after, interval_end, dag_maker): """Test that TimeDeltaSensor defers correctly when flag is enabled.""" if not AIRFLOW_V_3_0_PLUS and not interval_end: pytest.skip("not applicable") context: dict[str, Any] = {} if interval_end: context["data_interval_end"] = interval_end with dag_maker(): kwargs = {} if AIRFLOW_V_3_0_PLUS: from airflow.utils.types import DagRunTriggeredByType kwargs.update(triggered_by=DagRunTriggeredByType.TEST, run_after=run_after) delta = timedelta(minutes=5) sensor = TimeDeltaSensor( task_id="timedelta_sensor_deferrable", delta=delta, deferrable=True, # <-- the feature under test ) dr = dag_maker.create_dagrun( run_id="abcrhroceuh", run_type=DagRunType.MANUAL, state=None, **kwargs, ) context.update(dag_run=dr) expected_base = interval_end or run_after expected_fire_time = expected_base + delta with pytest.raises(TaskDeferred) as td: sensor.execute(context) # The sensor should defer once with a DateTimeTrigger trigger = td.value.trigger assert isinstance(trigger, DateTimeTrigger) assert trigger.moment == expected_fire_time
TestTimedeltaSensor
python
google__jax
jax/_src/internal_test_util/export_back_compat_test_util.py
{ "start": 6222, "end": 16339 }
class ____(jtu.JaxTestCase): """Base class with helper functions for backward compatibility tests.""" def default_jax_backend(self) -> str: # Canonicalize to turn into "cuda" or "rocm" return xb.canonicalize_platform(xb.default_backend()) def starter_data(self, inputs: Sequence[np.ndarray]) -> CompatTestData: # Helper for starting a test, see module docstring. assert isinstance(inputs, Sequence), f"{inputs}" return dataclasses.replace(self.load_testdata(dummy_data_dict), inputs=inputs, platform=self.default_jax_backend()) def load_testdata(self, testdata_dict: dict[str, Any]) -> CompatTestData: if testdata_dict["testdata_version"] == CURRENT_TESTDATA_VERSION: return CompatTestData(**testdata_dict) else: raise NotImplementedError("testdata_version not recognized: " + testdata_dict["testdata_version"]) def load_testdata_nested(self, testdata_nest) -> Iterable[CompatTestData]: # Load all the CompatTestData in a Python nest. if isinstance(testdata_nest, dict) and "testdata_version" in testdata_nest: yield self.load_testdata(testdata_nest) elif isinstance(testdata_nest, dict): for e in testdata_nest.values(): yield from self.load_testdata_nested(e) elif isinstance(testdata_nest, list): for e in testdata_nest: yield from self.load_testdata_nested(e) else: assert False, testdata_nest def run_one_test(self, func: Callable[..., Array] | stages.Wrapped, data: CompatTestData, polymorphic_shapes: Sequence[str] | None = None, rtol: float | None = None, atol: float | None = None, allow_unstable_custom_call_targets: Sequence[str] = (), check_results: Callable[..., None] | None = None, expect_current_custom_calls: Sequence[str] | None = None): """Run one compatibility test. Args: func: the JAX function to serialize and run, either as a Python Callable or as a `jax.jit(callable)`. data: the test data polymorphic_shapes: when using shape polymorphism, the specification for each argument of `func`. rtol: relative tolerance for numerical comparisons atol: absolute tolerance for numerical comparisons check_results: invoked with the results obtained from running the serialized code, and those stored in the test data, and the kwargs rtol and atol. allow_unstable_custom_call_targets: additional custom call targets to allow. expect_current_custom_calls: if `None` checks that the current serialization has the same custom calls as the saved one. This is the default, and will fail when the serialization changes. Otherwise, when checking old serializations you can specify what custom calls are expected in the current serialization. nr_devices: the number of devices for which the data was serialized. """ if not isinstance(data, CompatTestData): raise ValueError(f"Expecting data: CompatTestData but got {data}. " "Did you forget to `self.load_testdata`?") if self.default_jax_backend() != data.platform: self.skipTest(f"Test enabled only for {data.platform}") logging.info("Lowering and running the function at the current version") res_run_current = self.run_current(func, data) if not isinstance(res_run_current, (list, tuple)): res_run_current = (res_run_current,) res_run_current = tuple(np.array(a) for a in res_run_current) logging.info("Result of current version run is %s", res_run_current) serialized, module_str, module_version, nr_devices = self.serialize( func, data, polymorphic_shapes=polymorphic_shapes, allow_unstable_custom_call_targets=allow_unstable_custom_call_targets) custom_call_re = r"stablehlo.custom_call\s*@([^\(]+)\(" current_custom_call_targets = sorted( set(re.findall(custom_call_re, module_str))) np.set_printoptions(threshold=sys.maxsize, floatmode="unique") # Print the current test data to simplify updating the test. updated_testdata = f""" # Pasted from the test output (see export_back_compat_test_util.py module docstring) data_{datetime.date.today().strftime('%Y_%m_%d')} = dict( testdata_version={CURRENT_TESTDATA_VERSION}, platform={self.default_jax_backend()!r}, custom_call_targets={current_custom_call_targets!r}, serialized_date={datetime.date.today()!r}, inputs={data.inputs!r}, expected_outputs={res_run_current!r}, mlir_module_text=r\"\"\"\n{module_str}\"\"\", mlir_module_serialized={serialized!r}, xla_call_module_version={module_version}, nr_devices={nr_devices}, ) # End paste """ # Replace the word that should not appear. updated_testdata = re.sub(r"google.", "googlex", updated_testdata) output_dir = os.getenv("TEST_UNDECLARED_OUTPUTS_DIR", "/tmp/back_compat_testdata") if not os.path.exists(output_dir): os.makedirs(output_dir) output_file = os.path.join(output_dir, f"{self._testMethodName}.py") logging.info("Writing the updated testdata at %s", output_file) with open(output_file, "w") as f: f.write(updated_testdata) if rtol is None: rtol = 1.e-7 if check_results is not None: check_results(res_run_current, data.expected_outputs, rtol=rtol, atol=atol) else: self.assertAllClose(res_run_current, data.expected_outputs, rtol=rtol, atol=atol) logging.info("Running the serialized module") res_run_serialized = self.run_serialized( data, polymorphic_shapes=polymorphic_shapes) logging.info("Result of serialized run is %s", res_run_serialized) if check_results is not None: check_results(res_run_serialized, data.expected_outputs, rtol=rtol, atol=atol) else: self.assertAllClose(res_run_serialized, data.expected_outputs, rtol=rtol, atol=atol) if expect_current_custom_calls is None: expect_current_custom_calls = data.custom_call_targets self.assertItemsEqual(expect_current_custom_calls, current_custom_call_targets) def run_current(self, func: Callable | stages.Wrapped, data: CompatTestData): """Lowers and runs the test function at the current JAX version.""" jit_func = func if isinstance(func, stages.Wrapped) else api.jit(func) return jit_func(*data.inputs) def serialize(self, func: Callable | stages.Wrapped, data: CompatTestData, *, polymorphic_shapes: Sequence[str] | None = None, allow_unstable_custom_call_targets: Sequence[str] = () ) -> tuple[bytes, str, int, int]: """Serializes the test function. Args: func: the function to serialize. polymorphic_shapes: the polymorphic_shapes to use for serialization allow_unstable_custom_call_targets: whether to allow additional custom call targets besides those known as stable. Returns: a tuple with the (a) serialization, (b) the module contents as a string (for debugging), (c) the module serialization version, (d) the number of devices for which the module was serialized. """ # Use the native exporter, to make sure we get the proper serialization. args_specs = shape_poly.symbolic_args_specs(data.inputs, polymorphic_shapes) jit_func = func if isinstance(func, stages.Wrapped) else api.jit(func) exported = _export.export( jit_func, platforms=(self.default_jax_backend(),), disabled_checks=tuple( _export.DisabledSafetyCheck.custom_call(target) for target in allow_unstable_custom_call_targets) )(*args_specs) module_str = str(exported.mlir_module()) serialized = exported.mlir_module_serialized module_version = exported.calling_convention_version nr_devices = exported.nr_devices return serialized, module_str, module_version, nr_devices def run_serialized(self, data: CompatTestData, polymorphic_shapes: Sequence[str] | None = None): args_specs = shape_poly.symbolic_args_specs(data.inputs, polymorphic_shapes) def ndarray_to_aval(a: np.ndarray) -> core.ShapedArray: return core.ShapedArray(a.shape, a.dtype) in_avals_tree = tree_util.tree_map(ndarray_to_aval, args_specs) # TODO: we ought to ensure that out_avals are polymorphic if need be. We # could either save the in/out_avals (but we need to first implement that # support in export), or we can just reuse them from the current # exported. out_avals_tree = tree_util.tree_map(ndarray_to_aval, data.expected_outputs) # in_tree must be for (args, kwargs) in_avals, in_tree = tree_util.tree_flatten((in_avals_tree, {})) out_avals, out_tree = tree_util.tree_flatten(out_avals_tree) def _get_vjp(_): assert False # We do not have and do not need VJP exported = _export.Exported( fun_name="run_serialized", in_tree=in_tree, in_avals=tuple(in_avals), out_tree=out_tree, out_avals=tuple(out_avals), in_shardings_hlo=(None,) * len(in_avals), out_shardings_hlo=(None,) * len(out_avals), platforms=(data.platform,), ordered_effects=(), unordered_effects=(), disabled_safety_checks=(), mlir_module_serialized=data.mlir_module_serialized, calling_convention_version=data.xla_call_module_version, nr_devices=data.nr_devices, module_kept_var_idx=tuple(range(len(in_avals))), uses_global_constants=any(not core.is_constant_shape(a.shape) for a in in_avals), _get_vjp=_get_vjp) # We use pjit in case there are shardings in the exported module. return pjit.pjit(exported.call)(*data.inputs)
CompatTestBase
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_float.py
{ "start": 32760, "end": 36911 }
class ____(__TestCase): def test_format(self): # these should be rewritten to use both format(x, spec) and # x.__format__(spec) self.assertEqual(format(0.0, 'f'), '0.000000') # the default is 'g', except for empty format spec self.assertEqual(format(0.0, ''), '0.0') self.assertEqual(format(0.01, ''), '0.01') self.assertEqual(format(0.01, 'g'), '0.01') # empty presentation type should format in the same way as str # (issue 5920) x = 100/7. self.assertEqual(format(x, ''), str(x)) self.assertEqual(format(x, '-'), str(x)) self.assertEqual(format(x, '>'), str(x)) self.assertEqual(format(x, '2'), str(x)) self.assertEqual(format(1.0, 'f'), '1.000000') self.assertEqual(format(-1.0, 'f'), '-1.000000') self.assertEqual(format( 1.0, ' f'), ' 1.000000') self.assertEqual(format(-1.0, ' f'), '-1.000000') self.assertEqual(format( 1.0, '+f'), '+1.000000') self.assertEqual(format(-1.0, '+f'), '-1.000000') # % formatting self.assertEqual(format(-1.0, '%'), '-100.000000%') # conversion to string should fail self.assertRaises(ValueError, format, 3.0, "s") # confirm format options expected to fail on floats, such as integer # presentation types for format_spec in 'sbcdoxX': self.assertRaises(ValueError, format, 0.0, format_spec) self.assertRaises(ValueError, format, 1.0, format_spec) self.assertRaises(ValueError, format, -1.0, format_spec) self.assertRaises(ValueError, format, 1e100, format_spec) self.assertRaises(ValueError, format, -1e100, format_spec) self.assertRaises(ValueError, format, 1e-100, format_spec) self.assertRaises(ValueError, format, -1e-100, format_spec) # issue 3382 self.assertEqual(format(NAN, 'f'), 'nan') self.assertEqual(format(NAN, 'F'), 'NAN') self.assertEqual(format(INF, 'f'), 'inf') self.assertEqual(format(INF, 'F'), 'INF') @support.requires_IEEE_754 def test_format_testfile(self): with open(format_testfile, encoding="utf-8") as testfile: for line in testfile: if line.startswith('--'): continue line = line.strip() if not line: continue lhs, rhs = map(str.strip, line.split('->')) fmt, arg = lhs.split() f = float(arg) self.assertEqual(fmt % f, rhs) self.assertEqual(fmt % -f, '-' + rhs) if fmt != '%r': fmt2 = fmt[1:] self.assertEqual(format(f, fmt2), rhs) self.assertEqual(format(-f, fmt2), '-' + rhs) def test_issue5864(self): self.assertEqual(format(123.456, '.4'), '123.5') self.assertEqual(format(1234.56, '.4'), '1.235e+03') self.assertEqual(format(12345.6, '.4'), '1.235e+04') def test_issue35560(self): self.assertEqual(format(123.0, '00'), '123.0') self.assertEqual(format(123.34, '00f'), '123.340000') self.assertEqual(format(123.34, '00e'), '1.233400e+02') self.assertEqual(format(123.34, '00g'), '123.34') self.assertEqual(format(123.34, '00.10f'), '123.3400000000') self.assertEqual(format(123.34, '00.10e'), '1.2334000000e+02') self.assertEqual(format(123.34, '00.10g'), '123.34') self.assertEqual(format(123.34, '01f'), '123.340000') self.assertEqual(format(-123.0, '00'), '-123.0') self.assertEqual(format(-123.34, '00f'), '-123.340000') self.assertEqual(format(-123.34, '00e'), '-1.233400e+02') self.assertEqual(format(-123.34, '00g'), '-123.34') self.assertEqual(format(-123.34, '00.10f'), '-123.3400000000') self.assertEqual(format(-123.34, '00.10f'), '-123.3400000000') self.assertEqual(format(-123.34, '00.10e'), '-1.2334000000e+02') self.assertEqual(format(-123.34, '00.10g'), '-123.34')
FormatTestCase
python
paramiko__paramiko
paramiko/ssh_exception.py
{ "start": 7323, "end": 7494 }
class ____(SSHException): """ Out-of-order protocol messages were received, violating "strict kex" mode. .. versionadded:: 3.4 """ pass
MessageOrderError
python
getsentry__sentry
src/sentry/uptime/types.py
{ "start": 3405, "end": 3674 }
class ____(enum.IntEnum): # Manually created by a user MANUAL = 1 # Auto-detected by our system and in the onboarding stage AUTO_DETECTED_ONBOARDING = 2 # Auto-detected by our system and actively monitoring AUTO_DETECTED_ACTIVE = 3
UptimeMonitorMode
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/internal/scrutineer.py
{ "start": 1696, "end": 8729 }
class ____: """A super-simple branch coverage tracer.""" __slots__ = ( "_previous_location", "_should_trace", "_tried_and_failed_to_trace", "branches", ) def __init__(self, *, should_trace: bool) -> None: self.branches: Trace = set() self._previous_location: Location | None = None self._tried_and_failed_to_trace = False self._should_trace = should_trace and self.can_trace() @staticmethod def can_trace() -> bool: if PYPY: return False if hasattr(sys, "monitoring"): return sys.monitoring.get_tool(MONITORING_TOOL_ID) is None return sys.gettrace() is None def trace(self, frame, event, arg): try: if event == "call": return self.trace elif event == "line": fname = frame.f_code.co_filename if should_trace_file(fname): current_location = (fname, frame.f_lineno) self.branches.add((self._previous_location, current_location)) self._previous_location = current_location except RecursionError: pass def trace_line(self, code: types.CodeType, line_number: int) -> None: fname = code.co_filename if not should_trace_file(fname): # this function is only called on 3.12+, but we want to avoid an # assertion to that effect for performance. return sys.monitoring.DISABLE # type: ignore current_location = (fname, line_number) self.branches.add((self._previous_location, current_location)) self._previous_location = current_location def __enter__(self): self._tried_and_failed_to_trace = False if not self._should_trace: return self if not hasattr(sys, "monitoring"): sys.settrace(self.trace) return self try: sys.monitoring.use_tool_id(MONITORING_TOOL_ID, "scrutineer") except ValueError: # another thread may have registered a tool for MONITORING_TOOL_ID # since we checked in can_trace. self._tried_and_failed_to_trace = True return self for event, callback_name in MONITORING_EVENTS.items(): sys.monitoring.set_events(MONITORING_TOOL_ID, event) callback = getattr(self, callback_name) sys.monitoring.register_callback(MONITORING_TOOL_ID, event, callback) return self def __exit__(self, *args, **kwargs): if not self._should_trace: return if not hasattr(sys, "monitoring"): sys.settrace(None) return if self._tried_and_failed_to_trace: return sys.monitoring.free_tool_id(MONITORING_TOOL_ID) for event in MONITORING_EVENTS: sys.monitoring.register_callback(MONITORING_TOOL_ID, event, None) UNHELPFUL_LOCATIONS = ( # There's a branch which is only taken when an exception is active while exiting # a contextmanager; this is probably after the fault has been triggered. # Similar reasoning applies to a few other standard-library modules: even # if the fault was later, these still aren't useful locations to report! # Note: The list is post-processed, so use plain "/" for separator here. "/contextlib.py", "/inspect.py", "/re.py", "/re/__init__.py", # refactored in Python 3.11 "/warnings.py", # Quite rarely, the first AFNP line is in Pytest's internals. "/_pytest/**", "/pluggy/_*.py", # used by pytest for failure formatting in the terminal. # seen: pygments/lexer.py, pygments/formatters/, pygments/filter.py. "/pygments/*", # used by pytest for failure formatting "/difflib.py", "/reprlib.py", "/typing.py", "/conftest.py", "/pprint.py", ) def _glob_to_re(locs: Iterable[str]) -> str: """Translate a list of glob patterns to a combined regular expression. Only the * and ** wildcards are supported, and patterns including special characters will only work by chance.""" # fnmatch.translate is not an option since its "*" consumes path sep return "|".join( loc.replace(".", re.escape(".")) .replace("**", r".+") .replace("*", r"[^/]+") .replace("/", re.escape(sep)) + r"\Z" # right anchored for loc in locs ) def get_explaining_locations(traces): # Traces is a dict[interesting_origin | None, set[frozenset[tuple[str, int]]]] # Each trace in the set might later become a Counter instead of frozenset. if not traces: return {} unions = {origin: set().union(*values) for origin, values in traces.items()} seen_passing = {None}.union(*unions.pop(None, set())) always_failing_never_passing = { origin: reduce(set.intersection, [set().union(*v) for v in values]) - seen_passing for origin, values in traces.items() if origin is not None } # Build the observed parts of the control-flow graph for each origin cf_graphs = {origin: defaultdict(set) for origin in unions} for origin, seen_arcs in unions.items(): for src, dst in seen_arcs: cf_graphs[origin][src].add(dst) assert cf_graphs[origin][None], "Expected start node with >=1 successor" # For each origin, our explanation is the always_failing_never_passing lines # which are reachable from the start node (None) without passing through another # AFNP line. So here's a whatever-first search with early stopping: explanations = defaultdict(set) for origin in unions: queue = {None} seen = set() while queue: assert queue.isdisjoint(seen), f"Intersection: {queue & seen}" src = queue.pop() seen.add(src) if src in always_failing_never_passing[origin]: explanations[origin].add(src) else: queue.update(cf_graphs[origin][src] - seen) # The last step is to filter out explanations that we know would be uninformative. # When this is the first AFNP location, we conclude that Scrutineer missed the # real divergence (earlier in the trace) and drop that unhelpful explanation. filter_regex = re.compile(_glob_to_re(UNHELPFUL_LOCATIONS)) return { origin: {loc for loc in afnp_locs if not filter_regex.search(loc[0])} for origin, afnp_locs in explanations.items() } # see e.g. https://docs.python.org/3/library/sysconfig.html#posix-user # for examples of these path schemes STDLIB_DIRS = { Path(sysconfig.get_path("platstdlib")).resolve(), Path(sysconfig.get_path("stdlib")).resolve(), } SITE_PACKAGES_DIRS = { Path(sysconfig.get_path("purelib")).resolve(), Path(sysconfig.get_path("platlib")).resolve(), } EXPLANATION_STUB = ( "Explanation:", " These lines were always and only run by failing examples:", )
Tracer
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1101294, "end": 1108494 }
class ____(OffsetDef): """ ScaleDatumDef schema wrapper. Parameters ---------- bandPosition : float Relative position on a band of a stacked, binned, time unit, or band scale. For example, the marks will be positioned at the beginning of the band if set to ``0``, and at the middle of the band if set to ``0.5``. datum : str, bool, dict, float, :class:`ExprRef`, :class:`DateTime`, :class:`RepeatRef`, :class:`PrimitiveValue`, None A constant value in data domain. scale : dict, :class:`Scale`, None An object defining properties of the channel's scale, which is the function that transforms values in the data domain (numbers, dates, strings, etc) to visual values (pixels, colors, sizes) of the encoding channels. If ``null``, the scale will be `disabled and the data value will be directly encoded <https://vega.github.io/vega-lite/docs/scale.html#disable>`__. **Default value:** If undefined, default `scale properties <https://vega.github.io/vega-lite/docs/scale.html>`__ are applied. **See also:** `scale <https://vega.github.io/vega-lite/docs/scale.html>`__ documentation. title : str, :class:`Text`, Sequence[str], None A title for the field. If ``null``, the title will be removed. **Default value:** derived from the field's name and transformation function (``aggregate``, ``bin`` and ``timeUnit``). If the field has an aggregate function, the function is displayed as part of the title (e.g., ``"Sum of Profit"``). If the field is binned or has a time unit applied, the applied function is shown in parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"``). Otherwise, the title is simply the field name. **Notes**: 1) You can customize the default field title format by providing the `fieldTitle <https://vega.github.io/vega-lite/docs/config.html#top-level-config>`__ property in the `config <https://vega.github.io/vega-lite/docs/config.html>`__ or `fieldTitle function via the compile function's options <https://vega.github.io/vega-lite/usage/compile.html#field-title>`__. 2) If both field definition's ``title`` and axis, header, or legend ``title`` are defined, axis/header/legend title will be used. type : :class:`Type`, Literal['quantitative', 'ordinal', 'temporal', 'nominal', 'geojson'] The type of measurement (``"quantitative"``, ``"temporal"``, ``"ordinal"``, or ``"nominal"``) for the encoded field or constant value (``datum``). It can also be a ``"geojson"`` type for encoding `'geoshape' <https://vega.github.io/vega-lite/docs/geoshape.html>`__. Vega-Lite automatically infers data types in many cases as discussed below. However, type is required for a field if: (1) the field is not nominal and the field encoding has no specified ``aggregate`` (except ``argmin`` and ``argmax``), ``bin``, scale type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal scale for a field with ``bin`` or ``timeUnit``. **Default value:** 1) For a data ``field``, ``"nominal"`` is the default data type unless the field encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or ``timeUnit`` that satisfies the following criteria: * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a quantitative scale <https://vega.github.io/vega-lite/docs/scale.html#type>`__. * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` or (2) the specified scale type is a time or utc scale * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort order <https://vega.github.io/vega-lite/docs/sort.html#specifying-custom-sort-order>`__, (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding channel is ``order``. 2) For a constant value in data domain (``datum``): * ``"quantitative"`` if the datum is a number * ``"nominal"`` if the datum is a string * ``"temporal"`` if the datum is `a date time object <https://vega.github.io/vega-lite/docs/datetime.html>`__ **Note:** * Data ``type`` describes the semantics of the data rather than the primitive data types (number, string, etc.). The same primitive data type can have different types of measurement. For example, numeric data can represent quantitative, ordinal, or nominal data. * Data values for a temporal field can be either a date-time string (e.g., ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"``) or a timestamp number (e.g., ``1552199579097``). * When using with `bin <https://vega.github.io/vega-lite/docs/bin.html>`__, the ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) or `"ordinal" (for using an ordinal bin scale) <https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__. * When using with `timeUnit <https://vega.github.io/vega-lite/docs/timeunit.html>`__, the ``type`` property can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" (for using an ordinal scale) <https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__. * When using with `aggregate <https://vega.github.io/vega-lite/docs/aggregate.html>`__, the ``type`` property refers to the post-aggregation data type. For example, we can calculate count ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError``) do not have ``type`` as they must have exactly the same type as their primary channels (e.g., ``x``, ``y``). **See also:** `type <https://vega.github.io/vega-lite/docs/type.html>`__ documentation. """ _schema = {"$ref": "#/definitions/ScaleDatumDef"} def __init__( self, bandPosition: Optional[float] = Undefined, datum: Optional[ Temporal | Parameter | SchemaBase | Map | PrimitiveValue_T ] = Undefined, scale: Optional[SchemaBase | Map | None] = Undefined, title: Optional[str | SchemaBase | Sequence[str] | None] = Undefined, type: Optional[SchemaBase | Type_T] = Undefined, **kwds, ): super().__init__( bandPosition=bandPosition, datum=datum, scale=scale, title=title, type=type, **kwds, )
ScaleDatumDef
python
Textualize__textual
src/textual/containers.py
{ "start": 4317, "end": 4582 }
class ____(Widget): """A non-expanding container with vertical layout and no scrollbars.""" DEFAULT_CSS = """ VerticalGroup { width: 1fr; height: auto; layout: vertical; overflow: hidden hidden; } """
VerticalGroup
python
fluentpython__example-code
19-dyn-attr-prop/oscon/schedule2.py
{ "start": 1125, "end": 1238 }
class ____(RuntimeError): """Raised when a database is required but was not set.""" # <1>
MissingDatabaseError
python
jazzband__django-oauth-toolkit
tests/custom_hasher.py
{ "start": 63, "end": 251 }
class ____(PBKDF2PasswordHasher): """ A subclass of PBKDF2PasswordHasher that uses less iterations. """ algorithm = "fast_pbkdf2" iterations = 10000
MyPBKDF2PasswordHasher
python
Netflix__metaflow
metaflow/plugins/aws/batch/batch_client.py
{ "start": 25468, "end": 25554 }
class ____(Exception): def __init__(self, ex): self.ex = ex
TriableException
python
certifi__python-certifi
certifi/tests/test_certify.py
{ "start": 44, "end": 467 }
class ____(unittest.TestCase): def test_cabundle_exists(self) -> None: assert os.path.exists(certifi.where()) def test_read_contents(self) -> None: content = certifi.contents() assert "-----BEGIN CERTIFICATE-----" in content def test_py_typed_exists(self) -> None: assert os.path.exists( os.path.join(os.path.dirname(certifi.__file__), 'py.typed') )
TestCertifi
python
numpy__numpy
tools/swig/test/testVector.py
{ "start": 11956, "end": 12219 }
class ____(VectorTestCase): def __init__(self, methodName="runTest"): VectorTestCase.__init__(self, methodName) self.typeStr = "uint" self.typeCode = "I" ######################################################################
uintTestCase
python
openai__openai-python
tests/api_resources/chat/test_completions.py
{ "start": 495, "end": 15982 }
class ____: parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_create_overload_1(self, client: OpenAI) -> None: completion = client.chat.completions.create( messages=[ { "content": "string", "role": "developer", } ], model="gpt-4o", ) assert_matches_type(ChatCompletion, completion, path=["response"]) @parametrize def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: completion = client.chat.completions.create( messages=[ { "content": "string", "role": "developer", "name": "name", } ], model="gpt-4o", audio={ "format": "wav", "voice": "ash", }, frequency_penalty=-2, function_call="none", functions=[ { "name": "name", "description": "description", "parameters": {"foo": "bar"}, } ], logit_bias={"foo": 0}, logprobs=True, max_completion_tokens=0, max_tokens=0, metadata={"foo": "string"}, modalities=["text"], n=1, parallel_tool_calls=True, prediction={ "content": "string", "type": "content", }, presence_penalty=-2, prompt_cache_key="prompt-cache-key-1234", prompt_cache_retention="in-memory", reasoning_effort="none", response_format={"type": "text"}, safety_identifier="safety-identifier-1234", seed=-9007199254740991, service_tier="auto", stop="\n", store=True, stream=False, stream_options={ "include_obfuscation": True, "include_usage": True, }, temperature=1, tool_choice="none", tools=[ { "function": { "name": "name", "description": "description", "parameters": {"foo": "bar"}, "strict": True, }, "type": "function", } ], top_logprobs=0, top_p=1, user="user-1234", verbosity="low", web_search_options={ "search_context_size": "low", "user_location": { "approximate": { "city": "city", "country": "country", "region": "region", "timezone": "timezone", }, "type": "approximate", }, }, ) assert_matches_type(ChatCompletion, completion, path=["response"]) @parametrize def test_raw_response_create_overload_1(self, client: OpenAI) -> None: response = client.chat.completions.with_raw_response.create( messages=[ { "content": "string", "role": "developer", } ], model="gpt-4o", ) assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" completion = response.parse() assert_matches_type(ChatCompletion, completion, path=["response"]) @parametrize def test_streaming_response_create_overload_1(self, client: OpenAI) -> None: with client.chat.completions.with_streaming_response.create( messages=[ { "content": "string", "role": "developer", } ], model="gpt-4o", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" completion = response.parse() assert_matches_type(ChatCompletion, completion, path=["response"]) assert cast(Any, response.is_closed) is True @parametrize def test_method_create_overload_2(self, client: OpenAI) -> None: completion_stream = client.chat.completions.create( messages=[ { "content": "string", "role": "developer", } ], model="gpt-4o", stream=True, ) completion_stream.response.close() @parametrize def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: completion_stream = client.chat.completions.create( messages=[ { "content": "string", "role": "developer", "name": "name", } ], model="gpt-4o", stream=True, audio={ "format": "wav", "voice": "ash", }, frequency_penalty=-2, function_call="none", functions=[ { "name": "name", "description": "description", "parameters": {"foo": "bar"}, } ], logit_bias={"foo": 0}, logprobs=True, max_completion_tokens=0, max_tokens=0, metadata={"foo": "string"}, modalities=["text"], n=1, parallel_tool_calls=True, prediction={ "content": "string", "type": "content", }, presence_penalty=-2, prompt_cache_key="prompt-cache-key-1234", prompt_cache_retention="in-memory", reasoning_effort="none", response_format={"type": "text"}, safety_identifier="safety-identifier-1234", seed=-9007199254740991, service_tier="auto", stop="\n", store=True, stream_options={ "include_obfuscation": True, "include_usage": True, }, temperature=1, tool_choice="none", tools=[ { "function": { "name": "name", "description": "description", "parameters": {"foo": "bar"}, "strict": True, }, "type": "function", } ], top_logprobs=0, top_p=1, user="user-1234", verbosity="low", web_search_options={ "search_context_size": "low", "user_location": { "approximate": { "city": "city", "country": "country", "region": "region", "timezone": "timezone", }, "type": "approximate", }, }, ) completion_stream.response.close() @parametrize def test_raw_response_create_overload_2(self, client: OpenAI) -> None: response = client.chat.completions.with_raw_response.create( messages=[ { "content": "string", "role": "developer", } ], model="gpt-4o", stream=True, ) assert response.http_request.headers.get("X-Stainless-Lang") == "python" stream = response.parse() stream.close() @parametrize def test_streaming_response_create_overload_2(self, client: OpenAI) -> None: with client.chat.completions.with_streaming_response.create( messages=[ { "content": "string", "role": "developer", } ], model="gpt-4o", stream=True, ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" stream = response.parse() stream.close() assert cast(Any, response.is_closed) is True @parametrize def test_method_retrieve(self, client: OpenAI) -> None: completion = client.chat.completions.retrieve( "completion_id", ) assert_matches_type(ChatCompletion, completion, path=["response"]) @parametrize def test_raw_response_retrieve(self, client: OpenAI) -> None: response = client.chat.completions.with_raw_response.retrieve( "completion_id", ) assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" completion = response.parse() assert_matches_type(ChatCompletion, completion, path=["response"]) @parametrize def test_streaming_response_retrieve(self, client: OpenAI) -> None: with client.chat.completions.with_streaming_response.retrieve( "completion_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" completion = response.parse() assert_matches_type(ChatCompletion, completion, path=["response"]) assert cast(Any, response.is_closed) is True @parametrize def test_path_params_retrieve(self, client: OpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `completion_id` but received ''"): client.chat.completions.with_raw_response.retrieve( "", ) @parametrize def test_method_update(self, client: OpenAI) -> None: completion = client.chat.completions.update( completion_id="completion_id", metadata={"foo": "string"}, ) assert_matches_type(ChatCompletion, completion, path=["response"]) @parametrize def test_raw_response_update(self, client: OpenAI) -> None: response = client.chat.completions.with_raw_response.update( completion_id="completion_id", metadata={"foo": "string"}, ) assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" completion = response.parse() assert_matches_type(ChatCompletion, completion, path=["response"]) @parametrize def test_streaming_response_update(self, client: OpenAI) -> None: with client.chat.completions.with_streaming_response.update( completion_id="completion_id", metadata={"foo": "string"}, ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" completion = response.parse() assert_matches_type(ChatCompletion, completion, path=["response"]) assert cast(Any, response.is_closed) is True @parametrize def test_path_params_update(self, client: OpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `completion_id` but received ''"): client.chat.completions.with_raw_response.update( completion_id="", metadata={"foo": "string"}, ) @parametrize def test_method_list(self, client: OpenAI) -> None: completion = client.chat.completions.list() assert_matches_type(SyncCursorPage[ChatCompletion], completion, path=["response"]) @parametrize def test_method_list_with_all_params(self, client: OpenAI) -> None: completion = client.chat.completions.list( after="after", limit=0, metadata={"foo": "string"}, model="model", order="asc", ) assert_matches_type(SyncCursorPage[ChatCompletion], completion, path=["response"]) @parametrize def test_raw_response_list(self, client: OpenAI) -> None: response = client.chat.completions.with_raw_response.list() assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" completion = response.parse() assert_matches_type(SyncCursorPage[ChatCompletion], completion, path=["response"]) @parametrize def test_streaming_response_list(self, client: OpenAI) -> None: with client.chat.completions.with_streaming_response.list() as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" completion = response.parse() assert_matches_type(SyncCursorPage[ChatCompletion], completion, path=["response"]) assert cast(Any, response.is_closed) is True @parametrize def test_method_delete(self, client: OpenAI) -> None: completion = client.chat.completions.delete( "completion_id", ) assert_matches_type(ChatCompletionDeleted, completion, path=["response"]) @parametrize def test_raw_response_delete(self, client: OpenAI) -> None: response = client.chat.completions.with_raw_response.delete( "completion_id", ) assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" completion = response.parse() assert_matches_type(ChatCompletionDeleted, completion, path=["response"]) @parametrize def test_streaming_response_delete(self, client: OpenAI) -> None: with client.chat.completions.with_streaming_response.delete( "completion_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" completion = response.parse() assert_matches_type(ChatCompletionDeleted, completion, path=["response"]) assert cast(Any, response.is_closed) is True @parametrize def test_path_params_delete(self, client: OpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `completion_id` but received ''"): client.chat.completions.with_raw_response.delete( "", ) @parametrize def test_method_create_disallows_pydantic(self, client: OpenAI) -> None: class MyModel(pydantic.BaseModel): a: str with pytest.raises(TypeError, match=r"You tried to pass a `BaseModel` class"): client.chat.completions.create( messages=[ { "content": "string", "role": "system", } ], model="gpt-4o", response_format=cast(Any, MyModel), )
TestCompletions
python
pallets__jinja
src/jinja2/runtime.py
{ "start": 12539, "end": 18638 }
class ____: """A wrapper iterable for dynamic ``for`` loops, with information about the loop and iteration. """ #: Current iteration of the loop, starting at 0. index0 = -1 _length: int | None = None _after: t.Any = missing _current: t.Any = missing _before: t.Any = missing _last_changed_value: t.Any = missing def __init__( self, iterable: t.Iterable[V], undefined: type["Undefined"], recurse: t.Optional["LoopRenderFunc"] = None, depth0: int = 0, ) -> None: """ :param iterable: Iterable to wrap. :param undefined: :class:`Undefined` class to use for next and previous items. :param recurse: The function to render the loop body when the loop is marked recursive. :param depth0: Incremented when looping recursively. """ self._iterable = iterable self._iterator = self._to_iterator(iterable) self._undefined = undefined self._recurse = recurse #: How many levels deep a recursive loop currently is, starting at 0. self.depth0 = depth0 @staticmethod def _to_iterator(iterable: t.Iterable[V]) -> t.Iterator[V]: return iter(iterable) @property def length(self) -> int: """Length of the iterable. If the iterable is a generator or otherwise does not have a size, it is eagerly evaluated to get a size. """ if self._length is not None: return self._length try: self._length = len(self._iterable) # type: ignore except TypeError: iterable = list(self._iterator) self._iterator = self._to_iterator(iterable) self._length = len(iterable) + self.index + (self._after is not missing) return self._length def __len__(self) -> int: return self.length @property def depth(self) -> int: """How many levels deep a recursive loop currently is, starting at 1.""" return self.depth0 + 1 @property def index(self) -> int: """Current iteration of the loop, starting at 1.""" return self.index0 + 1 @property def revindex0(self) -> int: """Number of iterations from the end of the loop, ending at 0. Requires calculating :attr:`length`. """ return self.length - self.index @property def revindex(self) -> int: """Number of iterations from the end of the loop, ending at 1. Requires calculating :attr:`length`. """ return self.length - self.index0 @property def first(self) -> bool: """Whether this is the first iteration of the loop.""" return self.index0 == 0 def _peek_next(self) -> t.Any: """Return the next element in the iterable, or :data:`missing` if the iterable is exhausted. Only peeks one item ahead, caching the result in :attr:`_last` for use in subsequent checks. The cache is reset when :meth:`__next__` is called. """ if self._after is not missing: return self._after self._after = next(self._iterator, missing) return self._after @property def last(self) -> bool: """Whether this is the last iteration of the loop. Causes the iterable to advance early. See :func:`itertools.groupby` for issues this can cause. The :func:`groupby` filter avoids that issue. """ return self._peek_next() is missing @property def previtem(self) -> t.Union[t.Any, "Undefined"]: """The item in the previous iteration. Undefined during the first iteration. """ if self.first: return self._undefined("there is no previous item") return self._before @property def nextitem(self) -> t.Union[t.Any, "Undefined"]: """The item in the next iteration. Undefined during the last iteration. Causes the iterable to advance early. See :func:`itertools.groupby` for issues this can cause. The :func:`jinja-filters.groupby` filter avoids that issue. """ rv = self._peek_next() if rv is missing: return self._undefined("there is no next item") return rv def cycle(self, *args: V) -> V: """Return a value from the given args, cycling through based on the current :attr:`index0`. :param args: One or more values to cycle through. """ if not args: raise TypeError("no items for cycling given") return args[self.index0 % len(args)] def changed(self, *value: t.Any) -> bool: """Return ``True`` if previously called with a different value (including when called for the first time). :param value: One or more values to compare to the last call. """ if self._last_changed_value != value: self._last_changed_value = value return True return False def __iter__(self) -> "LoopContext": return self def __next__(self) -> tuple[t.Any, "LoopContext"]: if self._after is not missing: rv = self._after self._after = missing else: rv = next(self._iterator) self.index0 += 1 self._before = self._current self._current = rv return rv, self @internalcode def __call__(self, iterable: t.Iterable[V]) -> str: """When iterating over nested data, render the body of the loop recursively with the given inner iterable data. The loop must have the ``recursive`` marker for this to work. """ if self._recurse is None: raise TypeError( "The loop must have the 'recursive' marker to be called recursively." ) return self._recurse(iterable, self._recurse, depth=self.depth) def __repr__(self) -> str: return f"<{type(self).__name__} {self.index}/{self.length}>"
LoopContext
python
un33k__django-uuslug
uuslug/tests/tests.py
{ "start": 9129, "end": 10029 }
class ____(TestCase): """Tests for Slug - Max length less than field length""" def test_manager(self): name = "john" * 51 with self.assertNumQueries(2): obj = CoolSlug.objects.create(name=name) self.assertEqual(obj.slug, name[:200]) with self.assertNumQueries(3): obj = CoolSlug.objects.create(name=name) self.assertEqual(obj.slug, name[:198] + "-1") def test_max_length_greater_than_field_slug(self): name = 'jaja---lol-méméméoo--a-méméméoo' obj = AutoTruncatedSlug.objects.create(name=name) # 10 is field max_length, 20 is uuslug function max_length self.assertEqual(obj.slug, "jaja-lol-m") # 10 is field max_length, 20 is uuslug function max_length obj = AutoTruncatedSlug.objects.create(name=name) self.assertEqual(obj.slug, "jaja-lol-1")
SlugMaxLengthTestCase
python
wandb__wandb
wandb/vendor/pygments/lexers/templates.py
{ "start": 48567, "end": 50291 }
class ____(RegexLexer): """ Coldfusion statements """ name = 'cfstatement' aliases = ['cfs'] filenames = [] mimetypes = [] flags = re.IGNORECASE tokens = { 'root': [ (r'//.*?\n', Comment.Single), (r'/\*(?:.|\n)*?\*/', Comment.Multiline), (r'\+\+|--', Operator), (r'[-+*/^&=!]', Operator), (r'<=|>=|<|>|==', Operator), (r'mod\b', Operator), (r'(eq|lt|gt|lte|gte|not|is|and|or)\b', Operator), (r'\|\||&&', Operator), (r'\?', Operator), (r'"', String.Double, 'string'), # There is a special rule for allowing html in single quoted # strings, evidently. (r"'.*?'", String.Single), (r'\d+', Number), (r'(if|else|len|var|xml|default|break|switch|component|property|function|do|' r'try|catch|in|continue|for|return|while|required|any|array|binary|boolean|' r'component|date|guid|numeric|query|string|struct|uuid|case)\b', Keyword), (r'(true|false|null)\b', Keyword.Constant), (r'(application|session|client|cookie|super|this|variables|arguments)\b', Name.Constant), (r'([a-z_$][\w.]*)(\s*)(\()', bygroups(Name.Function, Text, Punctuation)), (r'[a-z_$][\w.]*', Name.Variable), (r'[()\[\]{};:,.\\]', Punctuation), (r'\s+', Text), ], 'string': [ (r'""', String.Double), (r'#.+?#', String.Interp), (r'[^"#]+', String.Double), (r'#', String.Double), (r'"', String.Double, '#pop'), ], }
ColdfusionLexer
python
coleifer__peewee
peewee.py
{ "start": 33476, "end": 37943 }
class ____(Node): _converter = None @Node.copy def converter(self, converter=None): self._converter = converter def alias(self, alias): if alias: return Alias(self, alias) return self def unalias(self): return self def bind_to(self, dest): return BindTo(self, dest) def cast(self, as_type): return Cast(self, as_type) def asc(self, collation=None, nulls=None): return Asc(self, collation=collation, nulls=nulls) __pos__ = asc def desc(self, collation=None, nulls=None): return Desc(self, collation=collation, nulls=nulls) __neg__ = desc def __invert__(self): return Negated(self) def _e(op, inv=False): """ Lightweight factory which returns a method that builds an Expression consisting of the left-hand and right-hand operands, using `op`. """ def inner(self, rhs): if inv: return Expression(rhs, op, self) return Expression(self, op, rhs) return inner __and__ = _e(OP.AND) __or__ = _e(OP.OR) __add__ = _e(OP.ADD) __sub__ = _e(OP.SUB) __mul__ = _e(OP.MUL) __div__ = __truediv__ = _e(OP.DIV) __xor__ = _e(OP.XOR) __radd__ = _e(OP.ADD, inv=True) __rsub__ = _e(OP.SUB, inv=True) __rmul__ = _e(OP.MUL, inv=True) __rdiv__ = __rtruediv__ = _e(OP.DIV, inv=True) __rand__ = _e(OP.AND, inv=True) __ror__ = _e(OP.OR, inv=True) __rxor__ = _e(OP.XOR, inv=True) def __eq__(self, rhs): op = OP.IS if rhs is None else OP.EQ return Expression(self, op, rhs) def __ne__(self, rhs): op = OP.IS_NOT if rhs is None else OP.NE return Expression(self, op, rhs) __lt__ = _e(OP.LT) __le__ = _e(OP.LTE) __gt__ = _e(OP.GT) __ge__ = _e(OP.GTE) __lshift__ = _e(OP.IN) __rshift__ = _e(OP.IS) __mod__ = _e(OP.LIKE) __pow__ = _e(OP.ILIKE) like = _e(OP.LIKE) ilike = _e(OP.ILIKE) bin_and = _e(OP.BIN_AND) bin_or = _e(OP.BIN_OR) in_ = _e(OP.IN) not_in = _e(OP.NOT_IN) regexp = _e(OP.REGEXP) iregexp = _e(OP.IREGEXP) # Special expressions. def is_null(self, is_null=True): op = OP.IS if is_null else OP.IS_NOT return Expression(self, op, None) def _escape_like_expr(self, s, template): if s.find('_') >= 0 or s.find('%') >= 0 or s.find('\\') >= 0: s = s.replace('\\', '\\\\').replace('_', '\\_').replace('%', '\\%') # Pass the expression and escape string as unconverted values, to # avoid (e.g.) a Json field converter turning the escaped LIKE # pattern into a Json-quoted string. return NodeList(( Value(template % s, converter=False), SQL('ESCAPE'), Value('\\', converter=False))) return template % s def contains(self, rhs): if isinstance(rhs, Node): rhs = Expression('%', OP.CONCAT, Expression(rhs, OP.CONCAT, '%')) else: rhs = self._escape_like_expr(rhs, '%%%s%%') return Expression(self, OP.ILIKE, rhs) def startswith(self, rhs): if isinstance(rhs, Node): rhs = Expression(rhs, OP.CONCAT, '%') else: rhs = self._escape_like_expr(rhs, '%s%%') return Expression(self, OP.ILIKE, rhs) def endswith(self, rhs): if isinstance(rhs, Node): rhs = Expression('%', OP.CONCAT, rhs) else: rhs = self._escape_like_expr(rhs, '%%%s') return Expression(self, OP.ILIKE, rhs) def between(self, lo, hi): return Expression(self, OP.BETWEEN, NodeList((lo, SQL('AND'), hi))) def concat(self, rhs): return StringExpression(self, OP.CONCAT, rhs) def __getitem__(self, item): if isinstance(item, slice): if item.start is None or item.stop is None: raise ValueError('BETWEEN range must have both a start- and ' 'end-point.') return self.between(item.start, item.stop) return self == item __iter__ = None # Prevent infinite loop. def distinct(self): return NodeList((SQL('DISTINCT'), self)) def collate(self, collation): return NodeList((self, SQL('COLLATE %s' % collation))) def get_sort_key(self, ctx): return ()
ColumnBase
python
python-openxml__python-docx
tests/oxml/test__init__.py
{ "start": 1830, "end": 3214 }
class ____: def it_accepts_bytes_and_assumes_utf8_encoding(self, xml_bytes): parse_xml(xml_bytes) def it_accepts_unicode_providing_there_is_no_encoding_declaration(self): non_enc_decl = '<?xml version="1.0" standalone="yes"?>' enc_decl = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' xml_body = "<foo><bar>føøbår</bar></foo>" # unicode body by itself doesn't raise parse_xml(xml_body) # adding XML decl without encoding attr doesn't raise either xml_text = "%s\n%s" % (non_enc_decl, xml_body) parse_xml(xml_text) # but adding encoding in the declaration raises ValueError xml_text = "%s\n%s" % (enc_decl, xml_body) with pytest.raises(ValueError, match="Unicode strings with encoding declara"): parse_xml(xml_text) def it_uses_registered_element_classes(self, xml_bytes): register_element_cls("a:foo", CustElmCls) element = parse_xml(xml_bytes) assert isinstance(element, CustElmCls) # fixture components --------------------------------------------- @pytest.fixture def xml_bytes(self): return ( '<a:foo xmlns:a="http://schemas.openxmlformats.org/drawingml/200' '6/main">\n' " <a:bar>foøbår</a:bar>\n" "</a:foo>\n" ).encode("utf-8")
DescribeParseXml
python
google__jax
tests/array_extensibility_test.py
{ "start": 18332, "end": 21033 }
class ____(jtu.JaxTestCase): @parameterized.named_parameters( {'testcase_name': api.name(), 'api': api} for api in NUMPY_APIS) def test_numpy_api_supports_jax_array(self, api): if api.skip_on_devices and jtu.test_device_matches(api.skip_on_devices): self.skipTest(f'{api.name()} not supported on {api.skip_on_devices}') fun = api.fun args = api.make_args(self.rng()) wrapped_args = jax.tree.map(JaxArrayWrapper, args) kwargs = api.kwargs expected = fun(*args, **kwargs) wrapped = fun(*wrapped_args, **kwargs) self.assertAllClose(wrapped, expected, atol=0, rtol=0) @jtu.sample_product( api=['array', 'asarray'], test_class=[ JaxArrayWrapper, NumpyArrayWrapper, JaxArrayWrapperWithErroringNumpyArray, ], ) def test_array_creation(self, api, test_class): """Test pytrees with __jax_array__ and/or __array__ methods.""" fun = getattr(jnp, api) x = np.arange(5, dtype='float32') expected = fun(x) actual = fun(test_class(x)) self.assertIsInstance(actual, jax.Array) self.assertAllClose(actual, expected, atol=0, rtol=0) @parameterized.named_parameters( {'testcase_name': func.__name__, 'func': func} for func in [jnp.zeros_like, jnp.ones_like, jnp.empty_like, jnp.full_like] ) def test_array_creation_from_duck_typed_array(self, func): # Ensure that jnp.*_like prefers shape/dtype over __jax_array__ when # both methods are available. if func is jnp.full_like: func = functools.partial(func, fill_value=2.0) obj = DuckTypedArrayWithErroringJaxArray() # The test relies on this failing with self.assertRaises(ValueError): jnp.asarray(obj) result = func(obj) self.assertIsInstance(result, jax.Array) self.assertEqual(result.shape, obj.shape) self.assertEqual(result.dtype, obj.dtype) @parameterized.named_parameters( {"testcase_name": "subscript-form", "args": ("jk,k->j", Float[5, 3], Float[3])}, {"testcase_name": "index-form", "args": (Float[5, 3], (0, 1), Float[3], (1,), (0,))}, ) def test_einsum(self, args): rng = jtu.rand_default(self.rng()) def make_arg(arg): if isinstance(arg, jax.ShapeDtypeStruct): return rng(arg.shape, arg.dtype) return arg args = jax.tree.map(make_arg, args) def wrap_array(arg): if isinstance(arg, (jax.Array, np.ndarray)): return JaxArrayWrapper(arg) return arg wrapped_args = jax.tree.map(wrap_array, args) expected = jnp.einsum(*args) actual = jnp.einsum(*wrapped_args) self.assertAllClose(actual, expected, atol=0, rtol=0) @jtu.with_config(jax_disable_jit=True)
JaxArrayTests
python
viewflow__viewflow
tests/test_middleware.py
{ "start": 374, "end": 852 }
class ____(AppMenuMixin, Viewset): index_path = path( "", TemplateView.as_view(template_name="viewflow/base.html"), name="index" ) nested_path = route("nested/", NestedViewset()) site = Site( title="Test site", viewsets=[ Application( app_name="test", viewsets=[ CityViewset(), ], ) ], ) urlpatterns = [path("", site.urls)] @override_settings(ROOT_URLCONF=__name__)
CityViewset
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py
{ "start": 32120, "end": 32893 }
class ____(BaseModel): type: Literal["PageIncrement"] page_size: Optional[Union[int, str]] = Field( None, description="The number of records to include in each pages.", examples=[100, "100", "{{ config['page_size'] }}"], title="Page Size", ) start_from_page: Optional[int] = Field( 0, description="Index of the first page to request.", examples=[0, 1], title="Start From Page", ) inject_on_first_request: Optional[bool] = Field( False, description="Using the `page number` with value defined by `start_from_page` during the first request", title="Inject Page Number", ) parameters: Optional[Dict[str, Any]] = Field(None, alias="$parameters")
PageIncrement
python
pytorch__pytorch
torch/optim/nadam.py
{ "start": 586, "end": 26761 }
class ____(Optimizer): # noqa: D101 def __init__( self, params: ParamsT, lr: Union[float, Tensor] = 2e-3, betas: tuple[float, float] = (0.9, 0.999), eps: float = 1e-8, weight_decay: float = 0, momentum_decay: float = 4e-3, decoupled_weight_decay: bool = False, *, foreach: Optional[bool] = None, maximize: bool = False, capturable: bool = False, differentiable: bool = False, ) -> None: # noqa: D107 if isinstance(lr, Tensor) and lr.numel() != 1: raise ValueError("Tensor lr must be 1-element") if not 0.0 <= lr: raise ValueError(f"Invalid learning rate: {lr}") if not 0.0 <= eps: raise ValueError(f"Invalid epsilon value: {eps}") if not 0.0 <= betas[0] < 1.0: raise ValueError(f"Invalid beta parameter at index 0: {betas[0]}") if not 0.0 <= betas[1] < 1.0: raise ValueError(f"Invalid beta parameter at index 1: {betas[1]}") if not 0.0 <= weight_decay: raise ValueError(f"Invalid weight_decay value: {weight_decay}") if not 0.0 <= momentum_decay: raise ValueError(f"Invalid momentum_decay value: {momentum_decay}") defaults = { "lr": lr, "betas": betas, "eps": eps, "weight_decay": weight_decay, "momentum_decay": momentum_decay, "decoupled_weight_decay": decoupled_weight_decay, "maximize": maximize, "foreach": foreach, "capturable": capturable, "differentiable": differentiable, } super().__init__(params, defaults) def __setstate__(self, state): # noqa: D105 super().__setstate__(state) for group in self.param_groups: group.setdefault("maximize", False) group.setdefault("foreach", None) group.setdefault("capturable", False) group.setdefault("differentiable", False) group.setdefault("decoupled_weight_decay", False) for p in group["params"]: p_state = self.state.get(p, []) if len(p_state) != 0: if not torch.is_tensor(p_state["step"]): step_val = float(p_state["step"]) p_state["step"] = ( torch.tensor( step_val, dtype=_get_scalar_dtype(), device=p.device ) if group["capturable"] else torch.tensor(step_val, dtype=_get_scalar_dtype()) ) if not torch.is_tensor(p_state["mu_product"]): mu_prod_val = p_state["mu_product"] p_state["mu_product"] = ( torch.tensor( mu_prod_val, dtype=_get_scalar_dtype(), device=p.device ) if group["capturable"] else torch.tensor(mu_prod_val, dtype=_get_scalar_dtype()) ) def _init_group( self, group, params_with_grad, grads, exp_avgs, exp_avg_sqs, mu_products, state_steps, ): has_complex = False for p in group["params"]: if p.grad is not None: has_complex |= torch.is_complex(p) params_with_grad.append(p) if p.grad.is_sparse: raise RuntimeError("NAdam does not support sparse gradients") grads.append(p.grad) state = self.state[p] # Lazy state initialization if len(state) == 0: # note(crcrpar): [special device hosting for step] # Deliberately host `step` and `mu_product` on CPU if capturable is False. # This is because kernel launches are costly on CUDA and XLA. state["step"] = ( torch.zeros((), dtype=_get_scalar_dtype(), device=p.device) if group["capturable"] else torch.tensor(0.0, dtype=_get_scalar_dtype()) ) state["mu_product"] = ( torch.ones((), dtype=_get_scalar_dtype(), device=p.device) if group["capturable"] else torch.tensor(1.0, dtype=_get_scalar_dtype()) ) # Exponential moving average of gradient values state["exp_avg"] = torch.zeros_like( p, memory_format=torch.preserve_format ) # Exponential moving average of squared gradient values state["exp_avg_sq"] = torch.zeros_like( p, memory_format=torch.preserve_format ) exp_avgs.append(state["exp_avg"]) exp_avg_sqs.append(state["exp_avg_sq"]) mu_products.append(state["mu_product"]) state_steps.append(state["step"]) return has_complex @_use_grad_for_differentiable def step(self, closure=None): """Perform a single optimization step. Args: closure (Callable, optional): A closure that reevaluates the model and returns the loss. """ self._cuda_graph_capture_health_check() loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: params_with_grad: list[Tensor] = [] grads: list[Tensor] = [] exp_avgs: list[Tensor] = [] exp_avg_sqs: list[Tensor] = [] mu_products: list[Tensor] = [] state_steps: list[Tensor] = [] beta1, beta2 = cast(tuple[float, float], group["betas"]) has_complex = self._init_group( group, params_with_grad, grads, exp_avgs, exp_avg_sqs, mu_products, state_steps, ) nadam( params_with_grad, grads, exp_avgs, exp_avg_sqs, mu_products, state_steps, beta1=beta1, beta2=beta2, lr=group["lr"], weight_decay=group["weight_decay"], momentum_decay=group["momentum_decay"], eps=group["eps"], maximize=group["maximize"], decoupled_weight_decay=group["decoupled_weight_decay"], foreach=group["foreach"], capturable=group["capturable"], differentiable=group["differentiable"], has_complex=has_complex, ) return loss NAdam.__doc__ = ( r"""Implements NAdam algorithm. .. math:: \begin{aligned} &\rule{110mm}{0.4pt} \\ &\textbf{input} : \gamma_t \text{ (lr)}, \: \beta_1,\beta_2 \text{ (betas)}, \: \theta_0 \text{ (params)}, \: f(\theta) \text{ (objective)} \\ &\hspace{13mm} \: \lambda \text{ (weight decay)}, \:\psi \text{ (momentum decay)} \\ &\hspace{13mm} \: \textit{decoupled\_weight\_decay}, \:\textit{maximize} \\ &\textbf{initialize} : m_0 \leftarrow 0 \text{ ( first moment)}, v_0 \leftarrow 0 \text{ ( second moment)} \\[-1.ex] &\rule{110mm}{0.4pt} \\ &\textbf{for} \: t=1 \: \textbf{to} \: \ldots \: \textbf{do} \\ &\hspace{5mm}\textbf{if} \: \textit{maximize}: \\ &\hspace{10mm}g_t \leftarrow -\nabla_{\theta} f_t (\theta_{t-1}) \\ &\hspace{5mm}\textbf{else} \\ &\hspace{10mm}g_t \leftarrow \nabla_{\theta} f_t (\theta_{t-1}) \\ &\hspace{5mm} \theta_t \leftarrow \theta_{t-1} \\ &\hspace{5mm} \textbf{if} \: \lambda \neq 0 \\ &\hspace{10mm}\textbf{if} \: \textit{decoupled\_weight\_decay} \\ &\hspace{15mm} \theta_t \leftarrow \theta_{t-1} - \gamma \lambda \theta_{t-1} \\ &\hspace{10mm}\textbf{else} \\ &\hspace{15mm} g_t \leftarrow g_t + \lambda \theta_{t-1} \\ &\hspace{5mm} \mu_t \leftarrow \beta_1 \big(1 - \frac{1}{2} 0.96^{t \psi} \big) \\ &\hspace{5mm} \mu_{t+1} \leftarrow \beta_1 \big(1 - \frac{1}{2} 0.96^{(t+1)\psi}\big)\\ &\hspace{5mm}m_t \leftarrow \beta_1 m_{t-1} + (1 - \beta_1) g_t \\ &\hspace{5mm}v_t \leftarrow \beta_2 v_{t-1} + (1-\beta_2) g^2_t \\ &\hspace{5mm}\widehat{m_t} \leftarrow \mu_{t+1} m_t/(1-\prod_{i=1}^{t+1}\mu_i)\\[-1.ex] & \hspace{11mm} + (1-\mu_t) g_t /(1-\prod_{i=1}^{t} \mu_{i}) \\ &\hspace{5mm}\widehat{v_t} \leftarrow v_t/\big(1-\beta_2^t \big) \\ &\hspace{5mm}\theta_t \leftarrow \theta_t - \gamma \widehat{m_t}/ \big(\sqrt{\widehat{v_t}} + \epsilon \big) \\ &\rule{110mm}{0.4pt} \\[-1.ex] &\bf{return} \: \theta_t \\[-1.ex] &\rule{110mm}{0.4pt} \\[-1.ex] \end{aligned} For further details regarding the algorithm we refer to `Incorporating Nesterov Momentum into Adam`_. """ + rf""" Args: {_params_doc} lr (float, Tensor, optional): learning rate (default: 2e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) momentum_decay (float, optional): momentum momentum_decay (default: 4e-3) decoupled_weight_decay (bool, optional): whether to decouple the weight decay as in AdamW to obtain NAdamW. If True, the algorithm does not accumulate weight decay in the momentum nor variance. (default: False) {_foreach_doc} {_maximize_doc} {_capturable_doc} {_differentiable_doc} .. _Incorporating Nesterov Momentum into Adam: https://openreview.net/forum?id=OM0jvwB8jIp57ZJjtNEZ .. _Decoupled Weight Decay Regularization: https://arxiv.org/abs/1711.05101 """ ) def _single_tensor_nadam( params: list[Tensor], grads: list[Tensor], exp_avgs: list[Tensor], exp_avg_sqs: list[Tensor], mu_products: list[Tensor], state_steps: list[Tensor], *, beta1: float, beta2: float, lr: float, weight_decay: float, momentum_decay: float, eps: float, decoupled_weight_decay: bool, maximize: bool, capturable: bool, differentiable: bool, has_complex: bool, ) -> None: if not torch.jit.is_scripting(): lr = _to_scalar(lr) for i, param in enumerate(params): grad = grads[i] if not maximize else -grads[i] exp_avg = exp_avgs[i] exp_avg_sq = exp_avg_sqs[i] mu_product = mu_products[i] step_t = state_steps[i] if torch.is_complex(param): param = torch.view_as_real(param) grad = torch.view_as_real(grad) exp_avg = torch.view_as_real(exp_avg) exp_avg_sq = torch.view_as_real(exp_avg_sq) # If compiling, the compiler will handle cudagraph checks, see note [torch.compile x capturable] if not torch.compiler.is_compiling() and capturable: capturable_supported_devices = _get_capturable_supported_devices() if not ( param.device.type == mu_product.device.type == step_t.device.type and param.device.type in capturable_supported_devices ): raise AssertionError( f"If capturable=True, params, mu_products and state_steps must be " f"on supported devices: {capturable_supported_devices}." ) # update step step_t += 1 if capturable: step = step_t else: step = _get_value(step_t) bias_correction2 = 1 - beta2**step if weight_decay != 0: if decoupled_weight_decay: # Perform stepweight decay param.mul_(1 - lr * weight_decay) else: grad = grad.add(param, alpha=weight_decay) # calculate the momentum cache \mu^{t} and \mu^{t+1} mu = beta1 * (1.0 - 0.5 * (0.96 ** (step * momentum_decay))) mu_next = beta1 * (1.0 - 0.5 * (0.96 ** ((step + 1) * momentum_decay))) # update mu_product mu_product *= mu # decay the first and second moment running average coefficient exp_avg.lerp_(grad, 1 - beta1) exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2) denom = exp_avg_sq.div(bias_correction2).sqrt() if differentiable or capturable: denom = denom.add(eps) # Make autograd track the operations # by updating the grad and exp_avg directly and not using the # scalar "value" argument of addcdiv. mu_product_next = mu_product * mu_next grad = grad * (-lr * (1.0 - mu) / (1.0 - mu_product)) exp_avg = exp_avg * (-lr * mu_next / (1.0 - mu_product_next)) param.addcdiv_(grad, denom) param.addcdiv_(exp_avg, denom) else: mu_product_next = _get_value(mu_product) * mu_next denom.add_(eps) param.addcdiv_( grad, denom, value=(-lr * (1.0 - mu) / (1.0 - _get_value(mu_product))) ) param.addcdiv_( exp_avg, denom, value=cast(float, (-lr * mu_next) / (1.0 - mu_product_next)), ) def _multi_tensor_nadam( params: list[Tensor], grads: list[Tensor], exp_avgs: list[Tensor], exp_avg_sqs: list[Tensor], mu_products: list[Tensor], state_steps: list[Tensor], *, beta1: float, beta2: float, lr: float, weight_decay: float, momentum_decay: float, eps: float, decoupled_weight_decay: bool, maximize: bool, capturable: bool, differentiable: bool, has_complex: bool, ) -> None: if len(params) == 0: return if differentiable: raise AssertionError("_foreach ops don't support autograd") # If compiling, the compiler will handle cudagraph checks, see note [torch.compile x capturable] if not torch.compiler.is_compiling() and capturable: capturable_supported_devices = _get_capturable_supported_devices( supports_xla=False ) if not all( p.device.type == mp.device.type == step.device.type and p.device.type in capturable_supported_devices for p, mp, step in zip(params, mu_products, state_steps, strict=True) ): raise AssertionError( "If capturable=True, " "params, mu_products, and state_steps must be on supported devices: " f"{capturable_supported_devices}." ) lr = _to_scalar(lr) grouped_tensors = Optimizer._group_tensors_by_device_and_dtype( [params, grads, exp_avgs, exp_avg_sqs, mu_products, state_steps] # type: ignore[list-item] ) for ( grouped_params_, grouped_grads_, grouped_exp_avgs_, grouped_exp_avg_sqs_, grouped_mu_products_, grouped_state_steps_, ), _ in grouped_tensors.values(): grouped_params = cast(list[Tensor], grouped_params_) grouped_grads = cast(list[Tensor], grouped_grads_) grouped_exp_avgs = cast(list[Tensor], grouped_exp_avgs_) grouped_exp_avg_sqs = cast(list[Tensor], grouped_exp_avg_sqs_) grouped_mu_products = cast(list[Tensor], grouped_mu_products_) grouped_state_steps = cast(list[Tensor], grouped_state_steps_) # handle complex if has_complex: _view_as_real( grouped_params, grouped_grads, grouped_exp_avgs, grouped_exp_avg_sqs ) if maximize: grouped_grads = torch._foreach_neg(grouped_grads) # type: ignore[assignment] # Update steps # If steps are on CPU, foreach will fall back to the slow path, which is a for-loop calling t.add(1) over # and over. 1 will then be wrapped into a Tensor over and over again, which is slower than if we just # wrapped it once now. The alpha is required to assure we go to the right overload. if not torch.compiler.is_compiling() and grouped_state_steps[0].is_cpu: torch._foreach_add_( grouped_state_steps, torch.tensor(1.0, device="cpu"), alpha=1.0 ) else: torch._foreach_add_(grouped_state_steps, 1) if weight_decay != 0: if decoupled_weight_decay: # Perform stepweight decay torch._foreach_mul_(grouped_params, 1 - lr * weight_decay) else: # Reuse the intermediate memory (grouped_grads) already allocated for maximize if maximize: torch._foreach_add_( grouped_grads, grouped_params, alpha=weight_decay ) else: grouped_grads = torch._foreach_add( # type: ignore[assignment] grouped_grads, grouped_params, alpha=weight_decay ) # Decay the first and second moment running average coefficient torch._foreach_lerp_(grouped_exp_avgs, grouped_grads, 1 - beta1) torch._foreach_mul_(grouped_exp_avg_sqs, beta2) torch._foreach_addcmul_( grouped_exp_avg_sqs, grouped_grads, grouped_grads, 1 - beta2 ) exp_avg_sq_sqrt = torch._foreach_sqrt(grouped_exp_avg_sqs) bias_correction_sqrt: Union[tuple[Tensor, ...], list[Tensor]] mus: Union[tuple[Tensor, ...], list[Tensor]] mu_nexts: Union[tuple[Tensor, ...], list[Tensor]] if capturable: # mus will be beta1 * (1 - 0.5 * 0.96 ** (step * momentum_decay)) exponent = torch._foreach_mul(grouped_state_steps, momentum_decay) mus = torch._foreach_pow(0.96, exponent) torch._foreach_mul_(mus, -0.5) torch._foreach_add_(mus, 1.0) torch._foreach_mul_(mus, beta1) # mu_nexts will be beta1 * (1 - 0.5 * 0.96 ** ((step + 1) * momentum_decay)) torch._foreach_add_(exponent, momentum_decay) mu_nexts = torch._foreach_pow(0.96, exponent) torch._foreach_mul_(mu_nexts, -0.5) torch._foreach_add_(mu_nexts, 1.0) torch._foreach_mul_(mu_nexts, beta1) # save peak memory as we don't need exponent anymore del exponent bias_correction_sqrt = torch._foreach_pow(beta2, grouped_state_steps) # foreach_sub doesn't allow a scalar as the first arg torch._foreach_sub_(bias_correction_sqrt, 1.0) torch._foreach_neg_(bias_correction_sqrt) torch._foreach_sqrt_(bias_correction_sqrt) else: bias_correction_sqrt = [ (1 - beta2 ** _get_value(step)) ** 0.5 for step in grouped_state_steps ] mus = [ beta1 * (1.0 - 0.5 * (0.96 ** (_get_value(step) * momentum_decay))) for step in grouped_state_steps ] mu_nexts = [ beta1 * (1.0 - 0.5 * (0.96 ** ((_get_value(step) + 1) * momentum_decay))) for step in grouped_state_steps ] # update mu_products torch._foreach_mul_(grouped_mu_products, mus) torch._foreach_div_(exp_avg_sq_sqrt, bias_correction_sqrt) torch._foreach_add_(exp_avg_sq_sqrt, eps) # explicitly delete bias_correction refs to save memory del bias_correction_sqrt if capturable: # Build up the step_size multiplier for grad, reusing mus' memory torch._foreach_sub_(mus, 1.0) torch._foreach_mul_(mus, lr) # foreach_sub doesn't allow a scalar as the first arg denom = torch._foreach_sub(grouped_mu_products, 1.0) torch._foreach_neg_(denom) torch._foreach_div_(mus, denom) # - lr * (1 - mu) / (1 - mu_product) step_size_grads = mus # explicitly delete denom to save memory del denom # Build up the step_size multiplier for exp_avg, reusing mu_nexts' memory denom = torch._foreach_mul(grouped_mu_products, mu_nexts) torch._foreach_mul_(mu_nexts, lr) # foreach_sub doesn't allow a scalar as the first arg, but it's okay because # we need a negative here anyway torch._foreach_sub_(denom, 1.0) torch._foreach_div_(mu_nexts, denom) # - lr * mu_next / (1 - mu_product * mu_next) step_size_expavg = mu_nexts # explicitly delete denom to save memory del denom # we cannot inplace into step_size_grads cuz it is a list of ScalarTensors # and mul'ing with grouped_grads will result in a list of bigger Tensors numerator = torch._foreach_mul(step_size_grads, grouped_grads) torch._foreach_addcmul_(numerator, step_size_expavg, grouped_exp_avgs) # finally, update params torch._foreach_addcdiv_(grouped_params, numerator, exp_avg_sq_sqrt) else: step_size_grads = _stack_if_compiling( [ (_get_value(lr) * (1.0 - mu) / (1.0 - _get_value(mu_product))) * -1 for mu_product, mu in zip(grouped_mu_products, mus, strict=True) ] ) step_size_expavg = _stack_if_compiling( [ ( _get_value(lr) * mu_next / (1.0 - _get_value(mu_product) * mu_next) ) * -1 for mu_product, mu_next in zip( grouped_mu_products, mu_nexts, strict=True ) ] ) torch._foreach_addcdiv_( grouped_params, grouped_grads, exp_avg_sq_sqrt, step_size_grads, # type: ignore[arg-type] ) torch._foreach_addcdiv_( grouped_params, grouped_exp_avgs, exp_avg_sq_sqrt, step_size_expavg, # type: ignore[arg-type] ) @_disable_dynamo_if_unsupported(single_tensor_fn=_single_tensor_nadam) def nadam( params: list[Tensor], grads: list[Tensor], exp_avgs: list[Tensor], exp_avg_sqs: list[Tensor], mu_products: list[Tensor], state_steps: list[Tensor], # kwonly args with defaults are not supported by functions compiled with torchscript issue #70627 # setting this as kwarg for now as functional API is compiled by torch/distributed/optim decoupled_weight_decay: bool = False, foreach: Optional[bool] = None, capturable: bool = False, differentiable: bool = False, has_complex: bool = False, maximize: bool = False, *, beta1: float, beta2: float, lr: float, weight_decay: float, momentum_decay: float, eps: float, ) -> None: r"""Functional API that performs NAdam algorithm computation. See :class:`~torch.optim.NAdam` for details. """ if not all(isinstance(t, torch.Tensor) for t in state_steps): raise RuntimeError( "API has changed, `state_steps` argument must contain a list of singleton tensors" ) if not all(isinstance(t, torch.Tensor) for t in mu_products): raise RuntimeError( "API has changed, `mu_products` argument must contain a list of singleton tensors" ) if foreach is None: _, foreach = _default_to_fused_or_foreach( params, differentiable, use_fused=False ) if foreach and torch.jit.is_scripting(): raise RuntimeError("torch.jit.script not supported with foreach optimizers") if foreach and not torch.jit.is_scripting(): func = _multi_tensor_nadam else: func = _single_tensor_nadam func( params, grads, exp_avgs, exp_avg_sqs, mu_products, state_steps, beta1=beta1, beta2=beta2, lr=lr, weight_decay=weight_decay, momentum_decay=momentum_decay, maximize=maximize, decoupled_weight_decay=decoupled_weight_decay, eps=eps, capturable=capturable, differentiable=differentiable, has_complex=has_complex, )
NAdam
python
huggingface__transformers
src/transformers/models/afmoe/modeling_afmoe.py
{ "start": 2118, "end": 5155 }
class ____(nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer` def __init__(self, config: AfmoeConfig, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings self.config = config self.rope_type = self.config.rope_parameters["rope_type"] rope_init_fn: Callable = self.compute_default_rope_parameters if self.rope_type != "default": rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] inv_freq, self.attention_scaling = rope_init_fn(self.config, device) self.register_buffer("inv_freq", inv_freq, persistent=False) self.original_inv_freq = inv_freq @staticmethod def compute_default_rope_parameters( config: Optional[AfmoeConfig] = None, device: Optional["torch.device"] = None, seq_len: Optional[int] = None, ) -> tuple["torch.Tensor", float]: """ Computes the inverse frequencies according to the original RoPE implementation Args: config ([`~transformers.PreTrainedConfig`]): The model configuration. device (`torch.device`): The device to use for initialization of the inverse frequencies. seq_len (`int`, *optional*): The current sequence length. Unused for this type of RoPE. Returns: Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). """ base = config.rope_parameters["rope_theta"] dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads attention_factor = 1.0 # Unused in this type of RoPE # Compute the inverse frequencies inv_freq = 1.0 / ( base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim) ) return inv_freq, attention_factor @torch.no_grad() @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device) position_ids_expanded = position_ids[:, None, :].float() device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with torch.autocast(device_type=device_type, enabled=False): # Force float32 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2) emb = torch.cat((freqs, freqs), dim=-1) cos = emb.cos() * self.attention_scaling sin = emb.sin() * self.attention_scaling return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) @use_kernel_forward_from_hub("RMSNorm")
AfmoeRotaryEmbedding
python
getsentry__sentry
src/sentry/tagstore/types.py
{ "start": 3605, "end": 3783 }
class ____(TypedDict, total=False): uniqueValues: int | None totalValues: int | None topValues: list[TagValueSerializerResponse] | None
TagKeySerializerResponseOptional
python
streamlit__streamlit
lib/streamlit/runtime/caching/cached_message_replay.py
{ "start": 3860, "end": 10691 }
class ____(threading.local): """A utility for storing messages generated by `st` commands called inside a cached function. Data is stored in a thread-local object, so it's safe to use an instance of this class across multiple threads. """ def __init__(self, cache_type: CacheType) -> None: self._cached_message_stack: list[list[MsgData]] = [] self._seen_dg_stack: list[set[str]] = [] self._most_recent_messages: list[MsgData] = [] self._media_data: list[MediaMsgData] = [] self._cache_type = cache_type def __repr__(self) -> str: return util.repr_(self) @contextlib.contextmanager def calling_cached_function(self, func: Callable[..., Any]) -> Iterator[None]: # noqa: ARG002 """Context manager that should wrap the invocation of a cached function. It allows us to track any `st.foo` messages that are generated from inside the function for playback during cache retrieval. """ self._cached_message_stack.append([]) self._seen_dg_stack.append(set()) nested_call = False if in_cached_function.get(): nested_call = True # If we're in a cached function. To disallow usage of widget-like element, # we need to set the in_cached_function to true for this cached function run # to prevent widget usage (triggers a warning). in_cached_function.set(True) try: yield finally: self._most_recent_messages = self._cached_message_stack.pop() self._seen_dg_stack.pop() if not nested_call: # Reset the in_cached_function flag. But only if this # is not nested inside a cached function that disallows widget usage. in_cached_function.set(False) def save_element_message( self, delta_type: str, element_proto: Message, invoked_dg_id: str, used_dg_id: str, returned_dg_id: str, layout_config: LayoutConfig | None = None, ) -> None: """Record the element protobuf as having been produced during any currently executing cached functions, so they can be replayed any time the function's execution is skipped because they're in the cache. """ if not runtime.exists() or not in_cached_function.get(): return if len(self._cached_message_stack) >= 1: id_to_save = self.select_dg_to_save(invoked_dg_id, used_dg_id) media_data = self._media_data element_msg_data = ElementMsgData( delta_type, element_proto, id_to_save, returned_dg_id, media_data, layout_config, ) for msgs in self._cached_message_stack: msgs.append(element_msg_data) # Reset instance state, now that it has been used for the # associated element. self._media_data = [] for s in self._seen_dg_stack: s.add(returned_dg_id) def save_block_message( self, block_proto: Block, invoked_dg_id: str, used_dg_id: str, returned_dg_id: str, ) -> None: if not in_cached_function.get(): return id_to_save = self.select_dg_to_save(invoked_dg_id, used_dg_id) for msgs in self._cached_message_stack: msgs.append(BlockMsgData(block_proto, id_to_save, returned_dg_id)) for s in self._seen_dg_stack: s.add(returned_dg_id) def select_dg_to_save(self, invoked_id: str, acting_on_id: str) -> str: """Select the id of the DG that this message should be invoked on during message replay. See Note [DeltaGenerator method invocation] invoked_id is the DG the st function was called on, usually `st._main`. acting_on_id is the DG the st function ultimately runs on, which may be different if the invoked DG delegated to another one because it was in a `with` block. """ if len(self._seen_dg_stack) > 0 and acting_on_id in self._seen_dg_stack[-1]: return acting_on_id return invoked_id def save_media_data( self, media_data: bytes | str, mimetype: str, media_id: str ) -> None: if not in_cached_function.get(): return self._media_data.append(MediaMsgData(media_data, mimetype, media_id)) P = ParamSpec("P") def replay_cached_messages( result: CachedResult[R], cache_type: CacheType, cached_func: Callable[P, R] ) -> None: """Replay the st element function calls that happened when executing a cache-decorated function. When a cache function is executed, we record the element and block messages produced, and use those to reproduce the DeltaGenerator calls, so the elements will appear in the web app even when execution of the function is skipped because the result was cached. To make this work, for each st function call we record an identifier for the DG it was effectively called on (see Note [DeltaGenerator method invocation]). We also record the identifier for each DG returned by an st function call, if it returns one. Then, for each recorded message, we get the current DG instance corresponding to the DG the message was originally called on, and enqueue the message using that, recording any new DGs produced in case a later st function call is on one of them. """ from streamlit.delta_generator import DeltaGenerator # Maps originally recorded dg ids to this script run's version of that dg returned_dgs: dict[str, DeltaGenerator] = { result.main_id: st._main, result.sidebar_id: st.sidebar, } try: for msg in result.messages: if isinstance(msg, ElementMsgData): if msg.media_data is not None: for data in msg.media_data: runtime.get_instance().media_file_mgr.add( data.media, data.mimetype, data.media_id ) dg = returned_dgs[msg.id_of_dg_called_on] maybe_dg = dg._enqueue( msg.delta_type, msg.message, layout_config=msg.layout_config ) if isinstance(maybe_dg, DeltaGenerator): returned_dgs[msg.returned_dgs_id] = maybe_dg elif isinstance(msg, BlockMsgData): dg = returned_dgs[msg.id_of_dg_called_on] new_dg = dg._block(msg.message) returned_dgs[msg.returned_dgs_id] = new_dg except KeyError as ex: raise CacheReplayClosureError(cache_type, cached_func) from ex
CachedMessageReplayContext
python
numba__numba
numba/cuda/cudadrv/nvvm.py
{ "start": 14569, "end": 24107 }
class ____(object): _cache_ = None def __init__(self): if self._cache_ is None: if get_libdevice() is None: raise RuntimeError(MISSING_LIBDEVICE_FILE_MSG) self._cache_ = open_libdevice() self.bc = self._cache_ def get(self): return self.bc cas_nvvm = """ %cas_success = cmpxchg volatile {Ti}* %iptr, {Ti} %old, {Ti} %new monotonic monotonic %cas = extractvalue {{ {Ti}, i1 }} %cas_success, 0 """ # noqa: E501 # Translation of code from CUDA Programming Guide v6.5, section B.12 ir_numba_atomic_binary_template = """ define internal {T} @___numba_atomic_{T}_{FUNC}({T}* %ptr, {T} %val) alwaysinline {{ entry: %iptr = bitcast {T}* %ptr to {Ti}* %old2 = load volatile {Ti}, {Ti}* %iptr br label %attempt attempt: %old = phi {Ti} [ %old2, %entry ], [ %cas, %attempt ] %dold = bitcast {Ti} %old to {T} %dnew = {OP} {T} %dold, %val %new = bitcast {T} %dnew to {Ti} {CAS} %repeat = icmp ne {Ti} %cas, %old br i1 %repeat, label %attempt, label %done done: %result = bitcast {Ti} %old to {T} ret {T} %result }} """ # noqa: E501 ir_numba_atomic_inc_template = """ define internal {T} @___numba_atomic_{Tu}_inc({T}* %iptr, {T} %val) alwaysinline {{ entry: %old2 = load volatile {T}, {T}* %iptr br label %attempt attempt: %old = phi {T} [ %old2, %entry ], [ %cas, %attempt ] %bndchk = icmp ult {T} %old, %val %inc = add {T} %old, 1 %new = select i1 %bndchk, {T} %inc, {T} 0 {CAS} %repeat = icmp ne {T} %cas, %old br i1 %repeat, label %attempt, label %done done: ret {T} %old }} """ # noqa: E501 ir_numba_atomic_dec_template = """ define internal {T} @___numba_atomic_{Tu}_dec({T}* %iptr, {T} %val) alwaysinline {{ entry: %old2 = load volatile {T}, {T}* %iptr br label %attempt attempt: %old = phi {T} [ %old2, %entry ], [ %cas, %attempt ] %dec = add {T} %old, -1 %bndchk = icmp ult {T} %dec, %val %new = select i1 %bndchk, {T} %dec, {T} %val {CAS} %repeat = icmp ne {T} %cas, %old br i1 %repeat, label %attempt, label %done done: ret {T} %old }} """ # noqa: E501 ir_numba_atomic_minmax_template = """ define internal {T} @___numba_atomic_{T}_{NAN}{FUNC}({T}* %ptr, {T} %val) alwaysinline {{ entry: %ptrval = load volatile {T}, {T}* %ptr ; Return early when: ; - For nanmin / nanmax when val is a NaN ; - For min / max when val or ptr is a NaN %early_return = fcmp uno {T} %val, %{PTR_OR_VAL}val br i1 %early_return, label %done, label %lt_check lt_check: %dold = phi {T} [ %ptrval, %entry ], [ %dcas, %attempt ] ; Continue attempts if dold less or greater than val (depending on whether min or max) ; or if dold is NaN (for nanmin / nanmax) %cmp = fcmp {OP} {T} %dold, %val br i1 %cmp, label %attempt, label %done attempt: ; Attempt to swap in the value %old = bitcast {T} %dold to {Ti} %iptr = bitcast {T}* %ptr to {Ti}* %new = bitcast {T} %val to {Ti} {CAS} %dcas = bitcast {Ti} %cas to {T} br label %lt_check done: ret {T} %ptrval }} """ # noqa: E501 def ir_cas(Ti): return cas_nvvm.format(Ti=Ti) def ir_numba_atomic_binary(T, Ti, OP, FUNC): params = dict(T=T, Ti=Ti, OP=OP, FUNC=FUNC, CAS=ir_cas(Ti)) return ir_numba_atomic_binary_template.format(**params) def ir_numba_atomic_minmax(T, Ti, NAN, OP, PTR_OR_VAL, FUNC): params = dict(T=T, Ti=Ti, NAN=NAN, OP=OP, PTR_OR_VAL=PTR_OR_VAL, FUNC=FUNC, CAS=ir_cas(Ti)) return ir_numba_atomic_minmax_template.format(**params) def ir_numba_atomic_inc(T, Tu): return ir_numba_atomic_inc_template.format(T=T, Tu=Tu, CAS=ir_cas(T)) def ir_numba_atomic_dec(T, Tu): return ir_numba_atomic_dec_template.format(T=T, Tu=Tu, CAS=ir_cas(T)) def llvm_replace(llvmir): replacements = [ ('declare double @"___numba_atomic_double_add"(double* %".1", double %".2")', # noqa: E501 ir_numba_atomic_binary(T='double', Ti='i64', OP='fadd', FUNC='add')), ('declare float @"___numba_atomic_float_sub"(float* %".1", float %".2")', # noqa: E501 ir_numba_atomic_binary(T='float', Ti='i32', OP='fsub', FUNC='sub')), ('declare double @"___numba_atomic_double_sub"(double* %".1", double %".2")', # noqa: E501 ir_numba_atomic_binary(T='double', Ti='i64', OP='fsub', FUNC='sub')), ('declare i64 @"___numba_atomic_u64_inc"(i64* %".1", i64 %".2")', ir_numba_atomic_inc(T='i64', Tu='u64')), ('declare i64 @"___numba_atomic_u64_dec"(i64* %".1", i64 %".2")', ir_numba_atomic_dec(T='i64', Tu='u64')), ('declare float @"___numba_atomic_float_max"(float* %".1", float %".2")', # noqa: E501 ir_numba_atomic_minmax(T='float', Ti='i32', NAN='', OP='nnan olt', PTR_OR_VAL='ptr', FUNC='max')), ('declare double @"___numba_atomic_double_max"(double* %".1", double %".2")', # noqa: E501 ir_numba_atomic_minmax(T='double', Ti='i64', NAN='', OP='nnan olt', PTR_OR_VAL='ptr', FUNC='max')), ('declare float @"___numba_atomic_float_min"(float* %".1", float %".2")', # noqa: E501 ir_numba_atomic_minmax(T='float', Ti='i32', NAN='', OP='nnan ogt', PTR_OR_VAL='ptr', FUNC='min')), ('declare double @"___numba_atomic_double_min"(double* %".1", double %".2")', # noqa: E501 ir_numba_atomic_minmax(T='double', Ti='i64', NAN='', OP='nnan ogt', PTR_OR_VAL='ptr', FUNC='min')), ('declare float @"___numba_atomic_float_nanmax"(float* %".1", float %".2")', # noqa: E501 ir_numba_atomic_minmax(T='float', Ti='i32', NAN='nan', OP='ult', PTR_OR_VAL='', FUNC='max')), ('declare double @"___numba_atomic_double_nanmax"(double* %".1", double %".2")', # noqa: E501 ir_numba_atomic_minmax(T='double', Ti='i64', NAN='nan', OP='ult', PTR_OR_VAL='', FUNC='max')), ('declare float @"___numba_atomic_float_nanmin"(float* %".1", float %".2")', # noqa: E501 ir_numba_atomic_minmax(T='float', Ti='i32', NAN='nan', OP='ugt', PTR_OR_VAL='', FUNC='min')), ('declare double @"___numba_atomic_double_nanmin"(double* %".1", double %".2")', # noqa: E501 ir_numba_atomic_minmax(T='double', Ti='i64', NAN='nan', OP='ugt', PTR_OR_VAL='', FUNC='min')), ('immarg', '') ] for decl, fn in replacements: llvmir = llvmir.replace(decl, fn) llvmir = llvm140_to_70_ir(llvmir) return llvmir def compile_ir(llvmir, **opts): if isinstance(llvmir, str): llvmir = [llvmir] if opts.pop('fastmath', False): opts.update({ 'ftz': True, 'fma': True, 'prec_div': False, 'prec_sqrt': False, }) cu = CompilationUnit() libdevice = LibDevice() for mod in llvmir: mod = llvm_replace(mod) cu.add_module(mod.encode('utf8')) cu.lazy_add_module(libdevice.get()) return cu.compile(**opts) re_attributes_def = re.compile(r"^attributes #\d+ = \{ ([\w\s]+)\ }") def llvm140_to_70_ir(ir): """ Convert LLVM 14.0 IR for LLVM 7.0. """ buf = [] for line in ir.splitlines(): if line.startswith('attributes #'): # Remove function attributes unsupported by LLVM 7.0 m = re_attributes_def.match(line) attrs = m.group(1).split() attrs = ' '.join(a for a in attrs if a != 'willreturn') line = line.replace(m.group(1), attrs) buf.append(line) return '\n'.join(buf) def set_cuda_kernel(function): """ Mark a function as a CUDA kernel. Kernels have the following requirements: - Metadata that marks them as a kernel. - Addition to the @llvm.used list, so that they will not be discarded. - The noinline attribute is not permitted, because this causes NVVM to emit a warning, which counts as failing IR verification. Presently it is assumed that there is one kernel per module, which holds for Numba-jitted functions. If this changes in future or this function is to be used externally, this function may need modification to add to the @llvm.used list rather than creating it. """ module = function.module # Add kernel metadata mdstr = ir.MetaDataString(module, "kernel") mdvalue = ir.Constant(ir.IntType(32), 1) md = module.add_metadata((function, mdstr, mdvalue)) nmd = cgutils.get_or_insert_named_metadata(module, 'nvvm.annotations') nmd.add(md) # Create the used list ptrty = ir.IntType(8).as_pointer() usedty = ir.ArrayType(ptrty, 1) fnptr = function.bitcast(ptrty) llvm_used = ir.GlobalVariable(module, usedty, 'llvm.used') llvm_used.linkage = 'appending' llvm_used.section = 'llvm.metadata' llvm_used.initializer = ir.Constant(usedty, [fnptr]) # Remove 'noinline' if it is present. function.attributes.discard('noinline') def add_ir_version(mod): """Add NVVM IR version to module""" # We specify the IR version to match the current NVVM's IR version i32 = ir.IntType(32) ir_versions = [i32(v) for v in NVVM().get_ir_version()] md_ver = mod.add_metadata(ir_versions) mod.add_named_metadata('nvvmir.version', md_ver)
LibDevice
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constructor2.py
{ "start": 381, "end": 473 }
class ____(Animal[_T3, int]): def __init__(self, p1: _T3 | None = None): pass
Bear
python
astropy__astropy
astropy/coordinates/builtin_frames/ecliptic.py
{ "start": 4012, "end": 5195 }
class ____(BaseEclipticFrame): """ Geocentric true ecliptic coordinates. These origin of the coordinates are the geocenter (Earth), with the x axis pointing to the *true* (not mean) equinox at the time specified by the ``equinox`` attribute, and the xy-plane in the plane of the ecliptic for that date. Be aware that the definition of "geocentric" here means that this frame *includes* light deflection from the sun, aberration, etc when transforming to/from e.g. ICRS. The frame attributes are listed under **Other Parameters**. """ equinox = TimeAttribute(default=EQUINOX_J2000, doc="The equinox time") obstime = TimeAttribute( default=DEFAULT_OBSTIME, doc="The reference time (e.g., time of observation)" ) doc_footer_bary = """ Other parameters ---------------- equinox : `~astropy.time.Time`, optional The date to assume for this frame. Determines the location of the x-axis and the location of the Earth and Sun. Defaults to the 'J2000' equinox. """ @format_doc( base_doc, components=doc_components_ecl.format("barycenter"), footer=doc_footer_bary )
GeocentricTrueEcliptic
python
python-attrs__attrs
typing-examples/mypy.py
{ "start": 1488, "end": 2097 }
class ____: x: int | None = attr.ib(converter=attr.converters.optional(int)) ConvCOptional(1) ConvCOptional(None) # XXX: Fails with E: Unsupported converter, only named functions, types and lambdas are currently supported [misc] # See https://github.com/python/mypy/issues/15736 # # @attr.s # class ConvCPipe: # x: str = attr.ib(converter=attr.converters.pipe(int, str)) # # # ConvCPipe(3.4) # ConvCPipe("09") # # # @attr.s # class ConvCDefaultIfNone: # x: int = attr.ib(converter=attr.converters.default_if_none(42)) # # # ConvCDefaultIfNone(1) # ConvCDefaultIfNone(None) @attr.s
ConvCOptional
python
apache__airflow
airflow-core/src/airflow/jobs/triggerer_job_runner.py
{ "start": 10397, "end": 28056 }
class ____(WatchedSubprocess): """ TriggerRunnerSupervisor is responsible for monitoring the subprocess and marshalling DB access. This class (which runs in the main/sync process) is responsible for querying the DB, sending RunTrigger workload messages to the subprocess, and collecting results and updating them in the DB. """ job: Job capacity: int health_check_threshold = conf.getint("triggerer", "triggerer_health_check_threshold") runner: TriggerRunner | None = None stop: bool = False decoder: ClassVar[TypeAdapter[ToTriggerSupervisor]] = TypeAdapter(ToTriggerSupervisor) # Maps trigger IDs that we think are running in the sub process running_triggers: set[int] = attrs.field(factory=set, init=False) logger_cache: dict[int, TriggerLoggingFactory] = attrs.field(factory=dict, init=False) # A list of triggers that we have told the async process to cancel. We keep them here until we receive the # FinishedTriggers message cancelling_triggers: set[int] = attrs.field(factory=set, init=False) # A list of RunTrigger workloads to send to the async process when it next checks in. We can't send it # directly as all comms has to be initiated by the subprocess creating_triggers: deque[workloads.RunTrigger] = attrs.field(factory=deque, init=False) # Outbound queue of events events: deque[tuple[int, events.TriggerEvent]] = attrs.field(factory=deque, init=False) # Outbound queue of failed triggers failed_triggers: deque[tuple[int, list[str] | None]] = attrs.field(factory=deque, init=False) def is_alive(self) -> bool: # Set by `_service_subprocess` in the loop return self._exit_code is None @classmethod def start( # type: ignore[override] cls, *, job: Job, logger=None, **kwargs, ): proc = super().start(id=job.id, job=job, target=cls.run_in_process, logger=logger, **kwargs) msg = messages.StartTriggerer() proc.send_msg(msg, request_id=0) return proc @functools.cached_property def client(self) -> Client: from airflow.sdk.api.client import Client client = Client(base_url=None, token="", dry_run=True, transport=in_process_api_server().transport) # Mypy is wrong -- the setter accepts a string on the property setter! `URLType = URL | str` client.base_url = "http://in-process.invalid./" return client def _handle_request(self, msg: ToTriggerSupervisor, log: FilteringBoundLogger, req_id: int) -> None: from airflow.sdk.api.datamodels._generated import ( ConnectionResponse, TaskStatesResponse, VariableResponse, XComResponse, ) resp: BaseModel | None = None dump_opts = {} if isinstance(msg, messages.TriggerStateChanges): if msg.events: self.events.extend(msg.events) if msg.failures: self.failed_triggers.extend(msg.failures) for id in msg.finished or (): self.running_triggers.discard(id) self.cancelling_triggers.discard(id) # Remove logger from the cache, and since structlog doesn't have an explicit close method, we # only need to remove the last reference to it to close the open FH if factory := self.logger_cache.pop(id, None): factory.upload_to_remote() response = messages.TriggerStateSync( to_create=[], to_cancel=self.cancelling_triggers, ) # Pull out of these dequeues in a thread-safe manner while self.creating_triggers: workload = self.creating_triggers.popleft() response.to_create.append(workload) self.running_triggers.update(m.id for m in response.to_create) resp = response elif isinstance(msg, GetConnection): conn = self.client.connections.get(msg.conn_id) if isinstance(conn, ConnectionResponse): conn_result = ConnectionResult.from_conn_response(conn) resp = conn_result # `by_alias=True` is used to convert the `schema` field to `schema_` in the Connection model dump_opts = {"exclude_unset": True, "by_alias": True} else: resp = conn elif isinstance(msg, DeleteVariable): resp = self.client.variables.delete(msg.key) elif isinstance(msg, GetVariable): var = self.client.variables.get(msg.key) if isinstance(var, VariableResponse): # TODO: call for help to figure out why this is needed if var.value: from airflow.sdk.log import mask_secret mask_secret(var.value, var.key) var_result = VariableResult.from_variable_response(var) resp = var_result dump_opts = {"exclude_unset": True} else: resp = var elif isinstance(msg, PutVariable): self.client.variables.set(msg.key, msg.value, msg.description) elif isinstance(msg, DeleteXCom): self.client.xcoms.delete(msg.dag_id, msg.run_id, msg.task_id, msg.key, msg.map_index) elif isinstance(msg, GetXCom): xcom = self.client.xcoms.get(msg.dag_id, msg.run_id, msg.task_id, msg.key, msg.map_index) if isinstance(xcom, XComResponse): xcom_result = XComResult.from_xcom_response(xcom) resp = xcom_result dump_opts = {"exclude_unset": True} else: resp = xcom elif isinstance(msg, SetXCom): self.client.xcoms.set( msg.dag_id, msg.run_id, msg.task_id, msg.key, msg.value, msg.map_index, msg.mapped_length ) elif isinstance(msg, GetDRCount): dr_count = self.client.dag_runs.get_count( dag_id=msg.dag_id, logical_dates=msg.logical_dates, run_ids=msg.run_ids, states=msg.states, ) resp = dr_count elif isinstance(msg, GetDagRunState): dr_resp = self.client.dag_runs.get_state(msg.dag_id, msg.run_id) resp = DagRunStateResult.from_api_response(dr_resp) elif isinstance(msg, GetTICount): resp = self.client.task_instances.get_count( dag_id=msg.dag_id, map_index=msg.map_index, task_ids=msg.task_ids, task_group_id=msg.task_group_id, logical_dates=msg.logical_dates, run_ids=msg.run_ids, states=msg.states, ) elif isinstance(msg, GetTaskStates): run_id_task_state_map = self.client.task_instances.get_task_states( dag_id=msg.dag_id, map_index=msg.map_index, task_ids=msg.task_ids, task_group_id=msg.task_group_id, logical_dates=msg.logical_dates, run_ids=msg.run_ids, ) if isinstance(run_id_task_state_map, TaskStatesResponse): resp = TaskStatesResult.from_api_response(run_id_task_state_map) else: resp = run_id_task_state_map elif isinstance(msg, UpdateHITLDetail): api_resp = self.client.hitl.update_response( ti_id=msg.ti_id, chosen_options=msg.chosen_options, params_input=msg.params_input, ) resp = HITLDetailResponseResult.from_api_response(response=api_resp) elif isinstance(msg, GetHITLDetailResponse): api_resp = self.client.hitl.get_detail_response(ti_id=msg.ti_id) resp = HITLDetailResponseResult.from_api_response(response=api_resp) elif isinstance(msg, MaskSecret): from airflow.sdk.log import mask_secret mask_secret(msg.value, msg.name) else: raise ValueError(f"Unknown message type {type(msg)}") self.send_msg(resp, request_id=req_id, error=None, **dump_opts) def run(self) -> None: """Run synchronously and handle all database reads/writes.""" while not self.stop: if not self.is_alive(): log.error("Trigger runner process has died! Exiting.") break with DebugTrace.start_span(span_name="triggerer_job_loop", component="TriggererJobRunner"): self.load_triggers() # Wait for up to 1 second for activity self._service_subprocess(1) self.handle_events() self.handle_failed_triggers() self.clean_unused() self.heartbeat() self.emit_metrics() def heartbeat(self): perform_heartbeat(self.job, heartbeat_callback=self.heartbeat_callback, only_if_necessary=True) def heartbeat_callback(self, session: Session | None = None) -> None: Stats.incr("triggerer_heartbeat", 1, 1) @add_debug_span def load_triggers(self): """Query the database for the triggers we're supposed to be running and update the runner.""" Trigger.assign_unassigned(self.job.id, self.capacity, self.health_check_threshold) ids = Trigger.ids_for_triggerer(self.job.id) self.update_triggers(set(ids)) @add_debug_span def handle_events(self): """Dispatch outbound events to the Trigger model which pushes them to the relevant task instances.""" while self.events: # Get the event and its trigger ID trigger_id, event = self.events.popleft() # Tell the model to wake up its tasks Trigger.submit_event(trigger_id=trigger_id, event=event) # Emit stat event Stats.incr("triggers.succeeded") @add_debug_span def clean_unused(self): """Clean out unused or finished triggers.""" Trigger.clean_unused() @add_debug_span def handle_failed_triggers(self): """ Handle "failed" triggers. - ones that errored or exited before they sent an event. Task Instances that depend on them need failing. """ while self.failed_triggers: # Tell the model to fail this trigger's deps trigger_id, saved_exc = self.failed_triggers.popleft() Trigger.submit_failure(trigger_id=trigger_id, exc=saved_exc) # Emit stat event Stats.incr("triggers.failed") def emit_metrics(self): Stats.gauge(f"triggers.running.{self.job.hostname}", len(self.running_triggers)) Stats.gauge("triggers.running", len(self.running_triggers), tags={"hostname": self.job.hostname}) capacity_left = self.capacity - len(self.running_triggers) Stats.gauge(f"triggerer.capacity_left.{self.job.hostname}", capacity_left) Stats.gauge("triggerer.capacity_left", capacity_left, tags={"hostname": self.job.hostname}) span = Trace.get_current_span() span.set_attributes( { "trigger host": self.job.hostname, "triggers running": len(self.running_triggers), "capacity left": capacity_left, } ) def update_triggers(self, requested_trigger_ids: set[int]): """ Request that we update what triggers we're running. Works out the differences - ones to add, and ones to remove - then adds them to the dequeues so the subprocess can actually mutate the running trigger set. """ render_log_fname = log_filename_template_renderer() known_trigger_ids = ( self.running_triggers.union(x[0] for x in self.events) .union(self.cancelling_triggers) .union(trigger[0] for trigger in self.failed_triggers) .union(trigger.id for trigger in self.creating_triggers) ) # Work out the two difference sets new_trigger_ids = requested_trigger_ids - known_trigger_ids cancel_trigger_ids = self.running_triggers - requested_trigger_ids # Bulk-fetch new trigger records new_triggers = Trigger.bulk_fetch(new_trigger_ids) trigger_ids_with_non_task_associations = Trigger.fetch_trigger_ids_with_non_task_associations() to_create: list[workloads.RunTrigger] = [] # Add in new triggers for new_id in new_trigger_ids: # Check it didn't vanish in the meantime if new_id not in new_triggers: log.warning("Trigger disappeared before we could start it", id=new_id) continue new_trigger_orm = new_triggers[new_id] # If the trigger is not associated to a task, an asset, or a callback, this means the TaskInstance # row was updated by either Trigger.submit_event or Trigger.submit_failure # and can happen when a single trigger Job is being run on multiple TriggerRunners # in a High-Availability setup. if new_trigger_orm.task_instance is None and new_id not in trigger_ids_with_non_task_associations: log.info( ( "TaskInstance Trigger is None. It was likely updated by another trigger job. " "Skipping trigger instantiation." ), id=new_id, ) continue workload = workloads.RunTrigger( classpath=new_trigger_orm.classpath, id=new_id, encrypted_kwargs=new_trigger_orm.encrypted_kwargs, ti=None, ) if new_trigger_orm.task_instance: log_path = render_log_fname(ti=new_trigger_orm.task_instance) if not new_trigger_orm.task_instance.dag_version_id: # This is to handle 2 to 3 upgrade where TI.dag_version_id can be none log.warning( "TaskInstance associated with Trigger has no associated Dag Version, skipping the trigger", ti_id=new_trigger_orm.task_instance.id, ) continue ser_ti = workloads.TaskInstance.model_validate( new_trigger_orm.task_instance, from_attributes=True ) # When producing logs from TIs, include the job id producing the logs to disambiguate it. self.logger_cache[new_id] = TriggerLoggingFactory( log_path=f"{log_path}.trigger.{self.job.id}.log", ti=ser_ti, # type: ignore ) workload.ti = ser_ti workload.timeout_after = new_trigger_orm.task_instance.trigger_timeout to_create.append(workload) self.creating_triggers.extend(to_create) if cancel_trigger_ids: # Enqueue orphaned triggers for cancellation self.cancelling_triggers.update(cancel_trigger_ids) def _register_pipe_readers(self, stdout: socket, stderr: socket, requests: socket, logs: socket): super()._register_pipe_readers(stdout, stderr, requests, logs) # We want to handle logging differently here, so un-register the one our parent class created self.selector.unregister(logs) self.selector.register( logs, selectors.EVENT_READ, make_buffered_socket_reader( self._process_log_messages_from_subprocess(), on_close=self._on_socket_closed ), ) def _process_log_messages_from_subprocess(self) -> Generator[None, bytes | bytearray, None]: import msgspec from structlog.stdlib import NAME_TO_LEVEL from airflow.sdk.log import configure_logging configure_logging() fallback_log = structlog.get_logger(logger_name=__name__) from airflow.sdk.log import logging_processors processors = logging_processors(json_output=True) def get_logger(trigger_id: int) -> WrappedLogger: # TODO: Is a separate dict worth it, or should we make `self.running_triggers` a dict? if factory := self.logger_cache.get(trigger_id): return factory(processors) return fallback_log # We need to look at the json, pull out the while True: # Generator receive syntax, values are "sent" in by the `make_buffered_socket_reader` and returned to # the yield. line = yield try: event: dict[str, Any] = msgspec.json.decode(line) except Exception: fallback_log.exception("Malformed json log", line=line) continue if trigger_id := event.pop("trigger_id", None): log = get_logger(trigger_id) else: # Log message about the TriggerRunner itself -- just output it log = fallback_log if exc := event.pop("exception", None): # TODO: convert the dict back to a pretty stack trace event["error_detail"] = exc if lvl_name := NAME_TO_LEVEL.get(event.pop("level")): log.log(lvl_name, event.pop("event", None), **event) @classmethod def run_in_process(cls): TriggerRunner().run()
TriggerRunnerSupervisor
python
sqlalchemy__sqlalchemy
examples/association/basic_association.py
{ "start": 1342, "end": 1764 }
class ____(Base): __tablename__ = "item" item_id: Mapped[int] = mapped_column(primary_key=True) description: Mapped[str] = mapped_column(String(30)) price: Mapped[float] def __init__(self, description: str, price: float) -> None: self.description = description self.price = price def __repr__(self) -> str: return "Item({!r}, {!r})".format(self.description, self.price)
Item
python
PrefectHQ__prefect
src/integrations/prefect-redis/prefect_redis/messaging.py
{ "start": 6391, "end": 9559 }
class ____(_Publisher): def __init__( self, topic: str, cache: _Cache, deduplicate_by: Optional[str] = None, batch_size: Optional[int] = None, publish_every: Optional[timedelta] = None, ): settings = RedisMessagingPublisherSettings() self.stream = topic # Use topic as stream name self.cache = cache self.deduplicate_by = ( deduplicate_by if deduplicate_by is not None else settings.deduplicate_by ) self.batch_size = batch_size if batch_size is not None else settings.batch_size self.publish_every = ( publish_every if publish_every is not None else settings.publish_every ) self._periodic_task: Optional[asyncio.Task[None]] = None async def __aenter__(self) -> Self: self._client = get_async_redis_client() self._batch: list[RedisStreamsMessage] = [] if self.publish_every is not None: interval = self.publish_every.total_seconds() async def _publish_periodically() -> None: while True: await asyncio.sleep(interval) await asyncio.shield(self._publish_current_batch()) self._periodic_task = asyncio.create_task(_publish_periodically()) return self async def __aexit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: if not hasattr(self, "_batch"): raise RuntimeError("Use this publisher as an async context manager") try: if self._periodic_task: self._periodic_task.cancel() await self._publish_current_batch() except Exception: if self.deduplicate_by: await self.cache.forget_duplicates(self.deduplicate_by, self._batch) raise async def publish_data(self, data: bytes, attributes: dict[str, Any]): if not hasattr(self, "_batch"): raise RuntimeError("Use this publisher as an async context manager") self._batch.append(RedisStreamsMessage(data=data, attributes=attributes)) if len(self._batch) >= self.batch_size: await asyncio.shield(self._publish_current_batch()) async def _publish_current_batch(self) -> None: if not self._batch: return if self.deduplicate_by: to_publish = await self.cache.without_duplicates( self.deduplicate_by, self._batch ) else: to_publish = list(self._batch) self._batch.clear() try: for message in to_publish: await self._client.xadd( self.stream, { "data": message.data, "attributes": orjson.dumps(message.attributes), }, ) except Exception: if self.deduplicate_by: await self.cache.forget_duplicates(self.deduplicate_by, to_publish) raise
Publisher
python
apache__airflow
providers/common/sql/tests/unit/common/sql/hooks/test_sql.py
{ "start": 8101, "end": 12375 }
class ____: def setup_method(self, **kwargs): logging.root.disabled = True @pytest.mark.db_test @pytest.mark.parametrize( "empty_statement", [ pytest.param([], id="Empty list"), pytest.param("", id="Empty string"), pytest.param("\n", id="Only EOL"), ], ) def test_no_query(self, empty_statement): dbapi_hook = mock_db_hook(DbApiHook) with pytest.raises(ValueError, match="List of SQL statements is empty"): dbapi_hook.run(sql=empty_statement) @pytest.mark.db_test def test_placeholder_config_from_extra(self): dbapi_hook = mock_db_hook(DbApiHook, conn_params={"extra": {"placeholder": "?"}}) assert dbapi_hook.placeholder == "?" @pytest.mark.db_test def test_placeholder_config_from_extra_when_not_in_default_sql_placeholders(self, caplog): with caplog.at_level(logging.WARNING, logger="airflow.providers.common.sql.hooks.test_sql"): dbapi_hook = mock_db_hook(DbApiHook, conn_params={"extra": {"placeholder": "!"}}) assert dbapi_hook.placeholder == "%s" assert ( "Placeholder '!' defined in Connection 'default_conn_id' is not listed in 'DEFAULT_SQL_PLACEHOLDERS' " f"and got ignored. Falling back to the default placeholder '{DbApiHook._placeholder}'." in caplog.text ) @pytest.mark.db_test def test_placeholder_multiple_times_and_make_sure_connection_is_only_invoked_once(self): dbapi_hook = mock_db_hook(DbApiHook) for _ in range(10): assert dbapi_hook.placeholder == "%s" assert dbapi_hook.connection_invocations == 1 @pytest.mark.db_test def test_escape_column_names(self): dbapi_hook = mock_db_hook(DbApiHook) assert not dbapi_hook.escape_column_names @pytest.mark.db_test def test_dialect_name(self): dbapi_hook = mock_db_hook(DbApiHook) assert dbapi_hook.dialect_name == "default" @pytest.mark.db_test def test_dialect(self): dbapi_hook = mock_db_hook(DbApiHook) assert isinstance(dbapi_hook.dialect, Dialect) @pytest.mark.db_test def test_when_provider_min_airflow_version_is_3_0_or_higher_remove_obsolete_code(self): """ Once this test starts failing due to the fact that the minimum Airflow version is now 3.0.0 or higher for this provider, you should remove the obsolete code in the get_dialects method of the DbApiHook and remove this test. This test was added to make sure to not forget to remove the fallback code for backward compatibility with Airflow 2.8.x which isn't need anymore once this provider depends on Airflow 3.0.0 or higher. """ min_airflow_version = get_provider_min_airflow_version("apache-airflow-providers-common-sql") # Check if the current Airflow version is 3.0.0 or higher if min_airflow_version[0] >= 3: method_source = inspect.getsource(resolve_dialects) raise AirflowProviderDeprecationWarning( f"Check TODO's to remove obsolete code in resolve_dialects method:\n\r\n\r\t\t\t{method_source}" ) @pytest.mark.db_test def test_uri(self): dbapi_hook = mock_db_hook(DbApiHook) assert dbapi_hook.get_uri() == "//login:password@host:1234/schema" @pytest.mark.db_test def test_uri_with_schema(self): dbapi_hook = mock_db_hook(DbApiHook, conn_params={"schema": "other_schema"}) assert dbapi_hook.get_uri() == "//login:password@host:1234/other_schema" @pytest.mark.db_test @pytest.mark.parametrize( ("df_type", "expected_type"), [ ("test_default_df_type", pd.DataFrame), ("pandas", pd.DataFrame), ("polars", pl.DataFrame), ], ) def test_get_df_with_df_type(db, df_type, expected_type): dbapi_hook = mock_db_hook(DbApiHook) if df_type == "test_default_df_type": df = dbapi_hook.get_df("SQL") assert isinstance(df, pd.DataFrame) else: df = dbapi_hook.get_df("SQL", df_type=df_type) assert isinstance(df, expected_type)
TestDbApiHook
python
spyder-ide__spyder
spyder/plugins/editor/widgets/editorstack/helpers.py
{ "start": 4291, "end": 7319 }
class ____(QObject): """File properties.""" todo_results_changed = Signal() sig_save_bookmarks = Signal(str, str) text_changed_at = Signal(str, tuple) edit_goto = Signal(str, int, str) sig_send_to_help = Signal(str, str, bool) sig_filename_changed = Signal(str) sig_show_object_info = Signal(bool) sig_show_completion_object_info = Signal(str, str) def __init__(self, filename, encoding, editor, new, threadmanager): """Initialize the FileInfo.""" QObject.__init__(self) self.threadmanager = threadmanager self._filename = filename self.newly_created = new self.default = False # Default untitled file self.encoding = encoding self.editor = editor self.path = [] self.classes = (filename, None, None) self.todo_results = [] self.lastmodified = QFileInfo(filename).lastModified() self.editor.textChanged.connect(self.text_changed) self.editor.sig_bookmarks_changed.connect(self.bookmarks_changed) self.editor.sig_show_object_info.connect(self.sig_show_object_info) self.editor.sig_show_completion_object_info.connect( self.sig_send_to_help) self.sig_filename_changed.connect(self.editor.sig_filename_changed) @property def filename(self): """Filename property.""" return self._filename @filename.setter def filename(self, value): """Filename setter.""" self._filename = value self.sig_filename_changed.emit(value) def text_changed(self): """Editor's text has changed.""" self.default = False all_cursors = self.editor.all_cursors positions = tuple(cursor.position() for cursor in all_cursors) self.text_changed_at.emit(self.filename, positions) def get_source_code(self): """Return associated editor source code.""" return str(self.editor.toPlainText()) def run_todo_finder(self): """Run TODO finder.""" if self.editor.is_python_or_ipython(): self.threadmanager.add_thread(find_tasks, self.todo_finished, self.get_source_code(), self) def todo_finished(self, results): """Code analysis thread has finished.""" self.set_todo_results(results) self.todo_results_changed.emit() def set_todo_results(self, results): """Set TODO results and update markers in editor.""" self.todo_results = results self.editor.process_todo(results) def cleanup_todo_results(self): """Clean-up TODO finder results.""" self.todo_results = [] def bookmarks_changed(self): """Bookmarks list has changed.""" bookmarks = self.editor.get_bookmarks() if self.editor.bookmarks != bookmarks: self.editor.bookmarks = bookmarks self.sig_save_bookmarks.emit(self.filename, repr(bookmarks))
FileInfo
python
cython__cython
docs/examples/userguide/extension_types/wrapper_class.py
{ "start": 174, "end": 2160 }
class ____: """A wrapper class for a C/C++ data structure""" _ptr: cython.pointer[my_c_struct] ptr_owner: cython.bint def __cinit__(self): self.ptr_owner = False def __dealloc__(self): # De-allocate if not null and flag is set if self._ptr is not cython.NULL and self.ptr_owner is True: free(self._ptr) self._ptr = cython.NULL def __init__(self): # Prevent accidental instantiation from normal Python code # since we cannot pass a struct pointer into a Python constructor. raise TypeError("This class cannot be instantiated directly.") # Extension class properties @property def a(self): return self._ptr.a if self._ptr is not cython.NULL else None @property def b(self): return self._ptr.b if self._ptr is not cython.NULL else None @staticmethod @cython.cfunc def from_ptr(_ptr: cython.pointer[my_c_struct], owner: cython.bint=False) -> WrapperClass: """Factory function to create WrapperClass objects from given my_c_struct pointer. Setting ``owner`` flag to ``True`` causes the extension type to ``free`` the structure pointed to by ``_ptr`` when the wrapper object is deallocated.""" # Fast call to __new__() that bypasses the __init__() constructor. wrapper: WrapperClass = WrapperClass.__new__(WrapperClass) wrapper._ptr = _ptr wrapper.ptr_owner = owner return wrapper @staticmethod @cython.cfunc def new_struct() -> WrapperClass: """Factory function to create WrapperClass objects with newly allocated my_c_struct""" _ptr: cython.pointer[my_c_struct] = cython.cast( cython.pointer[my_c_struct], malloc(cython.sizeof(my_c_struct))) if _ptr is cython.NULL: raise MemoryError _ptr.a = 0 _ptr.b = 0 return WrapperClass.from_ptr(_ptr, owner=True)
WrapperClass
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/torch_entities/components/reward_providers/base_reward_provider.py
{ "start": 278, "end": 2891 }
class ____(ABC): def __init__(self, specs: BehaviorSpec, settings: RewardSignalSettings) -> None: self._policy_specs = specs self._gamma = settings.gamma self._strength = settings.strength self._ignore_done = False @property def gamma(self) -> float: """ The discount factor for the reward signal """ return self._gamma @property def strength(self) -> float: """ The strength multiplier of the reward provider """ return self._strength @property def name(self) -> str: """ The name of the reward provider. Is used for reporting and identification """ class_name = self.__class__.__name__ return class_name.replace("RewardProvider", "") @property def ignore_done(self) -> bool: """ If true, when the agent is done, the rewards of the next episode must be used to calculate the return of the current episode. Is used to mitigate the positive bias in rewards with no natural end. """ return self._ignore_done @abstractmethod def evaluate(self, mini_batch: AgentBuffer) -> np.ndarray: """ Evaluates the reward for the data present in the Dict mini_batch. Use this when evaluating a reward function drawn straight from a Buffer. :param mini_batch: A Dict of numpy arrays (the format used by our Buffer) when drawing from the update buffer. :return: a np.ndarray of rewards generated by the reward provider """ raise NotImplementedError( "The reward provider's evaluate method has not been implemented " ) @abstractmethod def update(self, mini_batch: AgentBuffer) -> Dict[str, np.ndarray]: """ Update the reward for the data present in the Dict mini_batch. Use this when updating a reward function drawn straight from a Buffer. :param mini_batch: A Dict of numpy arrays (the format used by our Buffer) when drawing from the update buffer. :return: A dictionary from string to stats values """ raise NotImplementedError( "The reward provider's update method has not been implemented " ) def get_modules(self) -> Dict[str, torch.nn.Module]: """ Returns a dictionary of string identifiers to the torch.nn.Modules used by the reward providers. This method is used for loading and saving the weights of the reward providers. """ return {}
BaseRewardProvider
python
scrapy__scrapy
tests/test_engine_stop_download_bytes.py
{ "start": 427, "end": 618 }
class ____(CrawlerRun): def bytes_received(self, data, request, spider): super().bytes_received(data, request, spider) raise StopDownload(fail=False)
BytesReceivedCrawlerRun
python
ray-project__ray
python/ray/serve/_private/logging_utils.py
{ "start": 1409, "end": 2623 }
class ____(logging.Filter): """Serve component filter. The filter will add the component name, id, and type to the log record. """ def __init__( self, component_name: str, component_id: str, component_type: Optional[ServeComponentType] = None, ): self.component_name = component_name self.component_id = component_id self.component_type = component_type def filter(self, record: logging.LogRecord) -> bool: """Add component attributes to the log record. Note: the filter doesn't do any filtering, it only adds the component attributes. """ if should_skip_context_filter(record): return True if self.component_type and self.component_type == ServeComponentType.REPLICA: setattr(record, SERVE_LOG_DEPLOYMENT, self.component_name) setattr(record, SERVE_LOG_REPLICA, self.component_id) setattr(record, SERVE_LOG_COMPONENT, self.component_type) else: setattr(record, SERVE_LOG_COMPONENT, self.component_name) setattr(record, SERVE_LOG_COMPONENT_ID, self.component_id) return True
ServeComponentFilter
python
numba__numba
numba/core/datamodel/models.py
{ "start": 44180, "end": 44497 }
class ____(StructModel): """Model for a mutable struct. A reference to the payload """ def __init__(self, dmm, fe_typ): dtype = fe_typ.get_data_type() members = [ ("meminfo", types.MemInfoPointer(dtype)), ] super().__init__(dmm, fe_typ, members)
StructRefModel
python
miyuchina__mistletoe
mistletoe/contrib/md2jira.py
{ "start": 2339, "end": 3547 }
class ____: def __init__(self): self.version = "1.0.2" self.options = {} self.options['output'] = '-' def run(self, optlist, args): for o, i in optlist: if o in ('-h', '--help'): sys.stderr.write(usageString + '\n') sys.stderr.write(helpString + '\n') sys.exit(1) elif o in ('-v', '--version'): sys.stdout.write('%s\n' % self.version) sys.exit(0) elif o in ('-o', '--output'): self.options['output'] = i if len(args) < 1: sys.stderr.write(usageString + '\n') sys.exit(1) with open(args[0], 'r', encoding='utf-8') if len(args) == 1 else sys.stdin as infile: rendered = mistletoe.markdown(infile, JiraRenderer) if self.options['output'] == '-': sys.stdout.write(rendered) else: with open(self.options['output'], 'w', encoding='utf-8') as outfile: outfile.write(rendered) MarkdownToJIRA = MarkdownToJira """ Deprecated name of the `MarkdownToJira` class. """ if __name__ == '__main__': CommandLineParser()
MarkdownToJira
python
google__jax
tests/pallas/pallas_test.py
{ "start": 92751, "end": 92873 }
class ____(PallasCallNamedGridTest): INTERPRET = True @dataclasses.dataclass(frozen=True)
PallasCallNamedGridInterpretTest
python
graphql-python__graphene
graphene/types/interface.py
{ "start": 259, "end": 397 }
class ____(BaseOptions): fields = None # type: Dict[str, Field] interfaces = () # type: Iterable[Type[Interface]]
InterfaceOptions
python
huggingface__transformers
src/transformers/models/vjepa2/modeling_vjepa2.py
{ "start": 42102, "end": 45099 }
class ____(VJEPA2PreTrainedModel): def __init__(self, config: VJEPA2Config): super().__init__(config) self.num_labels = config.num_labels self.vjepa2 = VJEPA2Model(config) # Classifier head self.pooler = VJEPA2AttentivePooler(config) self.classifier = nn.Linear(config.hidden_size, config.num_labels, bias=True) # Initialize weights and apply final processing self.post_init() @can_return_tuple @auto_docstring def forward( self, pixel_values_videos: torch.Tensor, labels: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, ) -> Union[tuple, ImageClassifierOutput]: r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the image classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). Examples: ```python >>> import torch >>> import numpy as np >>> from transformers import AutoVideoProcessor, VJEPA2ForVideoClassification >>> device = "cuda" >>> video_processor = AutoVideoProcessor.from_pretrained("facebook/vjepa2-vitl-fpc16-256-ssv2") >>> model = VJEPA2ForVideoClassification.from_pretrained("facebook/vjepa2-vitl-fpc16-256-ssv2").to(device) >>> video = np.ones((64, 256, 256, 3)) # 64 frames, 256x256 RGB >>> inputs = video_processor(video, return_tensors="pt").to(device) >>> # For inference >>> with torch.no_grad(): ... outputs = model(**inputs) >>> logits = outputs.logits >>> predicted_label = logits.argmax(-1).item() >>> print(model.config.id2label[predicted_label]) >>> # For training >>> labels = torch.ones(1, dtype=torch.long, device=device) >>> loss = model(**inputs, labels=labels).loss ```""" outputs = self.vjepa2( pixel_values_videos=pixel_values_videos, skip_predictor=True, output_attentions=output_attentions, output_hidden_states=output_hidden_states, ) last_hidden_state = outputs.last_hidden_state pooler_output = self.pooler(last_hidden_state) logits = self.classifier(pooler_output) loss = None if labels is not None: loss = self.loss_function(pooled_logits=logits, labels=labels, config=self.config) return ImageClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) __all__ = ["VJEPA2Model", "VJEPA2PreTrainedModel", "VJEPA2ForVideoClassification"]
VJEPA2ForVideoClassification
python
sanic-org__sanic
sanic/cli/arguments.py
{ "start": 4467, "end": 5121 }
class ____(Group): name = "Socket binding" def attach(self): self.container.add_argument( "-H", "--host", dest="host", type=str, help="Host address [default 127.0.0.1]", ) self.container.add_argument( "-p", "--port", dest="port", type=int, help="Port to serve on [default 8000]", ) self.container.add_argument( "-u", "--unix", dest="unix", type=str, default="", help="location of unix socket", )
SocketGroup
python
ray-project__ray
python/ray/tune/tests/test_trial_scheduler_resource_changing.py
{ "start": 6613, "end": 10771 }
class ____(TestUniformResourceAllocation): def testAllocateFreeResources(self): scheduler = ResourceChangingScheduler( resources_allocation_function=DistributeResources(add_bundles=True) ) base_pgf = PlacementGroupFactory([{"CPU": 1, "GPU": 0}]) trial1, trial2, trial3, trial4 = self._prepareTrials(scheduler, base_pgf) self._allocateAndAssertNewResources( trial1, scheduler, PlacementGroupFactory([{"CPU": 1}] * 2) ) self._allocateAndAssertNewResources( trial2, scheduler, PlacementGroupFactory([{"CPU": 1}] * 2) ) trial4.status = Trial.TERMINATED self._allocateAndAssertNewResources( trial1, scheduler, PlacementGroupFactory([{"CPU": 1}] * 3) ) trial3.status = Trial.TERMINATED self._allocateAndAssertNewResources( trial1, scheduler, PlacementGroupFactory([{"CPU": 1}] * 4) ) trial2.status = Trial.TERMINATED self._allocateAndAssertNewResources( trial1, scheduler, PlacementGroupFactory([{"CPU": 1}] * 8) ) def testAllocateFreeResourcesWithIncreaseBy(self): scheduler = ResourceChangingScheduler( resources_allocation_function=DistributeResources( add_bundles=True, increase_by={"CPU": 2, "GPU": 2} ) ) base_pgf = PlacementGroupFactory([{}, {"CPU": 2, "GPU": 2}]) trial1, trial2, trial3, trial4 = self._prepareTrials(scheduler, base_pgf) decision = scheduler.on_trial_result( self.tune_controller, trial1, {"metric": 1, "training_iteration": 4} ) assert decision == TrialScheduler.CONTINUE trial4.status = Trial.TERMINATED self._allocateAndAssertNewResources( trial1, scheduler, PlacementGroupFactory([{}] + [{"CPU": 2, "GPU": 2}] * 2) ) trial3.status = Trial.TERMINATED self._allocateAndAssertNewResources( trial2, scheduler, PlacementGroupFactory([{}] + [{"CPU": 2, "GPU": 2}] * 2) ) trial2.status = Trial.TERMINATED self._allocateAndAssertNewResources( trial1, scheduler, PlacementGroupFactory([{}] + [{"CPU": 2, "GPU": 2}] * 4) ) def testAllocateFreeResourcesWithIncreaseByTimes(self): scheduler = ResourceChangingScheduler( resources_allocation_function=DistributeResources( add_bundles=True, increase_by={"GPU": 2}, increase_by_times=2 ) ) base_pgf = PlacementGroupFactory([{"CPU": 1}, {"GPU": 2}]) trial1, trial2, trial3, trial4 = self._prepareTrials(scheduler, base_pgf) decision = scheduler.on_trial_result( self.tune_controller, trial1, {"metric": 1, "training_iteration": 4} ) assert decision == TrialScheduler.CONTINUE trial4.status = Trial.TERMINATED self._allocateAndAssertNewResources( trial1, scheduler, PlacementGroupFactory([{"CPU": 1}] + [{"GPU": 2}] * 2) ) trial3.status = Trial.TERMINATED self._allocateAndAssertNewResources( trial2, scheduler, PlacementGroupFactory([{"CPU": 1}] + [{"GPU": 2}] * 2) ) trial2.status = Trial.TERMINATED self._allocateAndAssertNewResources( trial1, scheduler, PlacementGroupFactory([{"CPU": 1}] + [{"GPU": 2}] * 3) ) def testDeallocateResources(self): scheduler = ResourceChangingScheduler( resources_allocation_function=DistributeResources( add_bundles=True, increase_by={"GPU": 2} ) ) base_pgf = PlacementGroupFactory([{"CPU": 1}, {"GPU": 2}]) trial1, trial2, trial3, trial4 = self._prepareTrials(scheduler, base_pgf) trial1.placement_group_factory = PlacementGroupFactory( [{"CPU": 1}] + [{"GPU": 2}] * 2 ) trial4.status = Trial.PENDING self._allocateAndAssertNewResources( trial1, scheduler, PlacementGroupFactory([{"CPU": 1}, {"GPU": 2}]) )
TestUniformResourceAllocationAddBundles
python
pytorch__pytorch
torch/utils/benchmark/utils/_stubs.py
{ "start": 120, "end": 497 }
class ____(Protocol): """This is the portion of the `timeit.Timer` API used by benchmark utils.""" def __init__( self, stmt: str, setup: str, timer: Callable[[], float], globals: dict[str, Any], **kwargs: Any, ) -> None: ... def timeit(self, number: int) -> float: ... @runtime_checkable
TimerClass
python
django-extensions__django-extensions
django_extensions/mongodb/fields/json.py
{ "start": 1197, "end": 2130 }
class ____(StringField): """ JSONField is a generic textfield that neatly serializes/unserializes JSON objects seamlessly. Main object must be a dict object. """ def __init__(self, *args, **kwargs): if "default" not in kwargs: kwargs["default"] = "{}" StringField.__init__(self, *args, **kwargs) def to_python(self, value): """Convert our string value to JSON after we load it from the DB""" if not value: return {} elif isinstance(value, str): res = loads(value) assert isinstance(res, dict) return JSONDict(**res) else: return value def get_db_prep_save(self, value): """Convert our JSON object to a string before we save""" if not value: return super().get_db_prep_save("") else: return super().get_db_prep_save(dumps(value))
JSONField
python
optuna__optuna
optuna/cli.py
{ "start": 12274, "end": 12775 }
class ____(_BaseCommand): """Delete a specified study.""" def add_arguments(self, parser: ArgumentParser) -> None: parser.add_argument("--study-name", default=None, help="The name of the study to delete.") def take_action(self, parsed_args: Namespace) -> int: storage = _get_storage(parsed_args.storage, parsed_args.storage_class) study_id = storage.get_study_id_from_name(parsed_args.study_name) storage.delete_study(study_id) return 0
_DeleteStudy
python
tensorflow__tensorflow
tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py
{ "start": 16279, "end": 20906 }
class ____(test.TestCase): def testEmpty(self): inp = np.random.rand(4, 4).astype("f") for k in xrange(4): with self.cached_session(use_gpu=True): a = constant_op.constant(inp, shape=[4, 4], dtype=dtypes.float32) slice_t = a[2, k:k] slice_val = self.evaluate(slice_t) self.assertAllEqual(slice_val, inp[2, k:k]) def testSimple(self): with self.session(use_gpu=True) as _: inp = np.random.rand(4, 4).astype("f") a = constant_op.constant( [float(x) for x in inp.ravel(order="C")], shape=[4, 4], dtype=dtypes.float32, ) slice_t = array_ops.slice(a, [0, 0], [2, 2]) slice2_t = a[:2, :2] slice_val, slice2_val = self.evaluate([slice_t, slice2_t]) self.assertAllEqual(slice_val, inp[:2, :2]) self.assertAllEqual(slice2_val, inp[:2, :2]) self.assertEqual(slice_val.shape, slice_t.get_shape()) self.assertEqual(slice2_val.shape, slice2_t.get_shape()) def testSingleDimension(self): for _ in range(10): with self.cached_session(use_gpu=True): inp = np.random.rand(10).astype("f") a = constant_op.constant(inp, shape=[10], dtype=dtypes.float32) hi = np.random.randint(0, 9) scalar_t = a[hi] scalar_val = self.evaluate(scalar_t) self.assertAllEqual(scalar_val, inp[hi]) if hi > 0: lo = np.random.randint(0, hi) else: lo = 0 slice_t = a[lo:hi] slice_val = self.evaluate(slice_t) self.assertAllEqual(slice_val, inp[lo:hi]) def test3Dimension(self): with self.cached_session(): input_shape = [8, 16, 16, 16, 8] total_input_size = 1 for s in input_shape: total_input_size *= s inputs = [ i * 1.0 / total_input_size for i in range(1, total_input_size + 1) ] a = constant_op.constant(inputs, shape=input_shape, dtype=dtypes.float32) filter_shape = [1, 1, 1, 8, 8] total_filter_size = 1 for s in filter_shape: total_filter_size *= s filters = [ i * 1.0 / total_filter_size for i in range(1, total_filter_size + 1) ] f = constant_op.constant( filters, shape=filter_shape, dtype=dtypes.float32 ) conv_t = nn_ops.conv3d( a, filter=f, strides=[1, 1, 1, 1, 1], padding="VALID" ) slice_t = array_ops.slice(conv_t, [0, 1, 1, 1, 0], [1, 1, 1, 1, 8]) result = self.evaluate(slice_t) expected = [ 0.03028321, 0.03132677, 0.03237033, 0.03341389, 0.03445745, 0.035501, 0.03654456, 0.03758812, ] self.assertAllClose(expected, result.flatten(), rtol=1e-6) def testRandom(self): # Random dims of rank 6 input_shape = np.random.randint(0, 20, size=6) inp = np.random.rand(*input_shape).astype("f") with self.session(use_gpu=True) as _: a = constant_op.constant( [float(x) for x in inp.ravel(order="C")], shape=input_shape, dtype=dtypes.float32, ) indices = [0 if x == 0 else np.random.randint(x) for x in input_shape] sizes = [ np.random.randint(0, input_shape[i] - indices[i] + 1) for i in range(6) ] slice_t = array_ops.slice(a, indices, sizes) slice2_t = a[ indices[0] : indices[0] + sizes[0], indices[1] : indices[1] + sizes[1], indices[2] : indices[2] + sizes[2], indices[3] : indices[3] + sizes[3], indices[4] : indices[4] + sizes[4], indices[5] : indices[5] + sizes[5], ] slice_val, slice2_val = self.evaluate([slice_t, slice2_t]) expected_val = inp[ indices[0] : indices[0] + sizes[0], indices[1] : indices[1] + sizes[1], indices[2] : indices[2] + sizes[2], indices[3] : indices[3] + sizes[3], indices[4] : indices[4] + sizes[4], indices[5] : indices[5] + sizes[5], ] self.assertAllEqual(slice_val, expected_val) self.assertAllEqual(slice2_val, expected_val) self.assertEqual(expected_val.shape, slice_t.get_shape()) self.assertEqual(expected_val.shape, slice2_t.get_shape()) def testPartialShapeInference(self): z = array_ops.zeros((1, 2, 3)) self.assertAllEqual(z.get_shape().as_list(), [1, 2, 3]) m1 = array_ops.slice(z, [0, 0, 0], [-1, -1, -1]) self.assertAllEqual(m1.get_shape().as_list(), [1, 2, 3]) m2 = array_ops.slice(z, [0, 0, 0], [constant_op.constant(1) + 0, 2, -1]) self.assertAllEqual(m2.get_shape().as_list(), [1, 2, 3])
SliceTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-google-drive/source_google_drive/exceptions.py
{ "start": 139, "end": 205 }
class ____(BaseFileBasedSourceError): pass
ErrorFetchingMetadata
python
Textualize__rich
examples/fullscreen.py
{ "start": 1932, "end": 5492 }
class ____: """Display header with clock.""" def __rich__(self) -> Panel: grid = Table.grid(expand=True) grid.add_column(justify="center", ratio=1) grid.add_column(justify="right") grid.add_row( "[b]Rich[/b] Layout application", datetime.now().ctime().replace(":", "[blink]:[/]"), ) return Panel(grid, style="white on blue") def make_syntax() -> Syntax: code = """\ def ratio_resolve(total: int, edges: List[Edge]) -> List[int]: sizes = [(edge.size or None) for edge in edges] # While any edges haven't been calculated while any(size is None for size in sizes): # Get flexible edges and index to map these back on to sizes list flexible_edges = [ (index, edge) for index, (size, edge) in enumerate(zip(sizes, edges)) if size is None ] # Remaining space in total remaining = total - sum(size or 0 for size in sizes) if remaining <= 0: # No room for flexible edges sizes[:] = [(size or 0) for size in sizes] break # Calculate number of characters in a ratio portion portion = remaining / sum((edge.ratio or 1) for _, edge in flexible_edges) # If any edges will be less than their minimum, replace size with the minimum for index, edge in flexible_edges: if portion * edge.ratio <= edge.minimum_size: sizes[index] = edge.minimum_size break else: # Distribute flexible space and compensate for rounding error # Since edge sizes can only be integers we need to add the remainder # to the following line _modf = modf remainder = 0.0 for index, edge in flexible_edges: remainder, size = _modf(portion * edge.ratio + remainder) sizes[index] = int(size) break # Sizes now contains integers only return cast(List[int], sizes) """ syntax = Syntax(code, "python", line_numbers=True) return syntax job_progress = Progress( "{task.description}", SpinnerColumn(), BarColumn(), TextColumn("[progress.percentage]{task.percentage:>3.0f}%"), ) job_progress.add_task("[green]Cooking") job_progress.add_task("[magenta]Baking", total=200) job_progress.add_task("[cyan]Mixing", total=400) total = sum(task.total for task in job_progress.tasks) overall_progress = Progress() overall_task = overall_progress.add_task("All Jobs", total=int(total)) progress_table = Table.grid(expand=True) progress_table.add_row( Panel( overall_progress, title="Overall Progress", border_style="green", padding=(2, 2), ), Panel(job_progress, title="[b]Jobs", border_style="red", padding=(1, 2)), ) layout = make_layout() layout["header"].update(Header()) layout["body"].update(make_sponsor_message()) layout["box2"].update(Panel(make_syntax(), border_style="green")) layout["box1"].update(Panel(layout.tree, border_style="red")) layout["footer"].update(progress_table) from time import sleep from rich.live import Live with Live(layout, refresh_per_second=10, screen=True): while not overall_progress.finished: sleep(0.1) for job in job_progress.tasks: if not job.finished: job_progress.advance(job.id) completed = sum(task.completed for task in job_progress.tasks) overall_progress.update(overall_task, completed=completed)
Header
python
huggingface__transformers
src/transformers/models/flex_olmo/modeling_flex_olmo.py
{ "start": 15333, "end": 16423 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.top_k = config.num_experts_per_tok self.num_experts = config.num_experts self.norm_topk_prob = config.norm_topk_prob self.hidden_dim = config.hidden_size self.weight = nn.Parameter(torch.zeros(self.num_experts, self.hidden_dim)) def forward(self, hidden_states): hidden_states = hidden_states.reshape(-1, self.hidden_dim) router_logits = F.linear(hidden_states, self.weight) # (seq_len, num_experts) router_logits = torch.nn.functional.softmax(router_logits, dtype=torch.float, dim=-1) router_top_value, router_indices = torch.topk(router_logits, self.top_k, dim=-1) # (seq_len, top_k) if self.norm_topk_prob: router_top_value /= router_top_value.sum(dim=-1, keepdim=True) router_top_value = router_top_value.to(router_logits.dtype) router_scores = torch.zeros_like(router_logits).scatter_(1, router_indices, router_top_value) return router_scores, router_indices
FlexOlmoTopKRouter
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/operators/sagemaker.py
{ "start": 87336, "end": 89295 }
class ____(AwsBaseOperator[SageMakerHook]): """ Delete a notebook instance. .. seealso: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:SageMakerDeleteNotebookOperator` :param instance_name: The name of the notebook instance to delete. :param wait_for_completion: Whether or not to wait for the notebook to delete before returning. :param aws_conn_id: The Airflow connection used for AWS credentials. If this is ``None`` or empty then the default boto3 behaviour is used. If running Airflow in a distributed manner and aws_conn_id is None or empty, then default boto3 configuration would be used (and must be maintained on each worker node). :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used. :param verify: Whether or not to verify SSL certificates. See: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html """ template_fields: Sequence[str] = aws_template_fields("instance_name", "wait_for_completion") aws_hook_class = SageMakerHook ui_color = "#ff7300" def __init__( self, instance_name: str, wait_for_completion: bool = True, **kwargs, ): super().__init__(**kwargs) self.instance_name = instance_name self.wait_for_completion = wait_for_completion def execute(self, context): self.log.info("Deleting SageMaker notebook %s....", self.instance_name) self.hook.conn.delete_notebook_instance(NotebookInstanceName=self.instance_name) if self.wait_for_completion: self.log.info("Waiting for SageMaker notebook %s to delete...", self.instance_name) self.hook.conn.get_waiter("notebook_instance_deleted").wait( NotebookInstanceName=self.instance_name )
SageMakerDeleteNotebookOperator
python
getsentry__sentry
src/sentry/tasks/symbolication.py
{ "start": 2620, "end": 13164 }
class ____(Exception): pass def _do_symbolicate_event( task_kind: SymbolicatorTaskKind, cache_key: str, start_time: float | None, event_id: str | None, data: Event | None = None, queue_switches: int = 0, has_attachments: bool = False, symbolicate_platforms: list[SymbolicatorPlatform] | None = None, ) -> None: if data is None: data = processing.event_processing_store.get(cache_key) if data is None: metrics.incr( "events.failed", tags={"reason": "cache", "stage": "symbolicate"}, skip_internal=False ) error_logger.error("symbolicate.failed.empty", extra={"cache_key": cache_key}) return event_id = str(data["event_id"]) project_id = data["project"] has_changed = False set_current_event_project(project_id) def _continue_to_process_event(was_killswitched: bool = False) -> None: # Go through the remaining symbolication platforms # and submit the next one. if not was_killswitched and symbolicate_platforms: next_platform = symbolicate_platforms.pop(0) submit_symbolicate( task_kind=task_kind.with_platform(next_platform), cache_key=cache_key, event_id=event_id, start_time=start_time, has_attachments=has_attachments, symbolicate_platforms=symbolicate_platforms, ) return # else: store.submit_process( from_reprocessing=task_kind.is_reprocessing, cache_key=cache_key, event_id=event_id, start_time=start_time, data_has_changed=has_changed, from_symbolicate=True, has_attachments=has_attachments, ) try: stacktraces = find_stacktraces_in_data(data) symbolication_function = get_symbolication_function_for_platform( task_kind.platform, data, stacktraces ) except AssertionError: symbolication_function = None symbolication_function_name = getattr(symbolication_function, "__name__", "none") if symbolication_function is None or killswitch_matches_context( "store.load-shed-symbolicate-event-projects", { "project_id": project_id, "event_id": event_id, "platform": data.get("platform") or "null", "symbolication_function": symbolication_function_name, }, ): return _continue_to_process_event(True) symbolication_start_time = time() project = Project.objects.get_from_cache(id=project_id) # needed for efficient featureflag checks in getsentry # NOTE: The `organization` is used for constructing the symbol sources. with sentry_sdk.start_span(op="lang.native.symbolicator.organization.get_from_cache"): project.set_cached_field_value( "organization", Organization.objects.get_from_cache(id=project.organization_id) ) def on_symbolicator_request() -> None: duration = time() - symbolication_start_time if duration > settings.SYMBOLICATOR_PROCESS_EVENT_HARD_TIMEOUT: raise SymbolicationTimeout elif duration > settings.SYMBOLICATOR_PROCESS_EVENT_WARN_TIMEOUT: error_logger.warning( "symbolicate.slow", extra={"project_id": project_id, "event_id": event_id}, ) symbolicator = Symbolicator( task_kind=task_kind, on_request=on_symbolicator_request, project=project, event_id=event_id, ) with ( metrics.timer( "tasks.store.symbolicate_event.symbolication", tags={"symbolication_function": symbolication_function_name}, ), sentry_sdk.start_span( op=f"tasks.store.symbolicate_event.{symbolication_function_name}" ) as span, ): try: symbolicated_data = symbolication_function(symbolicator, data) span.set_data("symbolicated_data", bool(symbolicated_data)) if symbolicated_data: data = symbolicated_data has_changed = True except SymbolicationTimeout: metrics.incr( "tasks.store.symbolicate_event.fatal", tags={ "reason": "timeout", "symbolication_function": symbolication_function_name, }, ) error_logger.exception( "symbolicate.failed.infinite_retry", extra={"project_id": project_id, "event_id": event_id}, ) data.setdefault("_metrics", {})["flag.processing.error"] = True data.setdefault("_metrics", {})["flag.processing.fatal"] = True has_changed = True except Exception: metrics.incr( "tasks.store.symbolicate_event.fatal", tags={ "reason": "error", "symbolication_function": symbolication_function_name, }, ) error_logger.exception("tasks.store.symbolicate_event.symbolication") data.setdefault("_metrics", {})["flag.processing.error"] = True data.setdefault("_metrics", {})["flag.processing.fatal"] = True has_changed = True # We cannot persist canonical types in the cache, so we need to # downgrade this. if not isinstance(data, dict): data = dict(data.items()) if has_changed: cache_key = processing.event_processing_store.store(data) return _continue_to_process_event() # ============ Parameterized tasks below ============ # We have different *tasks* and associated *queues* for the following permutations: # - Event Type (JS vs Native) # - Reprocessing (currently not available for JS events) def submit_symbolicate( task_kind: SymbolicatorTaskKind, cache_key: str, event_id: str | None, start_time: float | None, queue_switches: int = 0, has_attachments: bool = False, symbolicate_platforms: list[SymbolicatorPlatform] | None = None, ) -> None: # Because of `mock` usage, we cannot just save a reference to the actual function # into the `TASK_FNS` dict. We actually have to access it at runtime from the global scope # on every invocation. Great stuff! task_fn_name = TASK_FNS.get(task_kind, "symbolicate_event") task_fn = globals()[task_fn_name] # Pass symbolicate_platforms as strings—apparently we're not allowed to pickle # custom classes. symbolicate_platform_names = ( None if symbolicate_platforms is None else [p.name for p in symbolicate_platforms] ) task_fn.delay( cache_key=cache_key, start_time=start_time, event_id=event_id, queue_switches=queue_switches, has_attachments=has_attachments, symbolicate_platforms=symbolicate_platform_names, ) SymbolicationTaskFn = Any # FIXME: it would be nice if `instrumented_task` would be fully typed # Maps from the `SymbolicatorTaskKind` to the name of the specific task function in the global scope. TASK_FNS: dict[SymbolicatorTaskKind, str] = {} def make_task_fn(name: str, queue: str, task_kind: SymbolicatorTaskKind) -> SymbolicationTaskFn: """ Returns a parameterized version of `_do_symbolicate_event` that runs as a task, and can be spawned as one. """ @instrumented_task( name=name, namespace=symbolication_tasks, processing_deadline_duration=settings.SYMBOLICATOR_PROCESS_EVENT_HARD_TIMEOUT + 30, silo_mode=SiloMode.REGION, ) def symbolication_fn( cache_key: str, start_time: float | None = None, event_id: str | None = None, data: Event | None = None, queue_switches: int = 0, has_attachments: bool = False, symbolicate_platforms: list[str] | None = None, **kwargs: Any, ) -> None: """ Handles event symbolication using the external service: symbolicator. :param string cache_key: the cache key for the event data :param int start_time: the timestamp when the event was ingested :param string event_id: the event identifier """ # Turn symbolicate_platforms back into proper enum values symbolicate_platform_values = ( None if symbolicate_platforms is None else [SymbolicatorPlatform(p) for p in symbolicate_platforms] ) return _do_symbolicate_event( task_kind=task_kind, cache_key=cache_key, start_time=start_time, event_id=event_id, data=data, queue_switches=queue_switches, has_attachments=has_attachments, symbolicate_platforms=symbolicate_platform_values, ) fn_name = name.split(".")[-1] setattr(symbolication_fn, "__name__", fn_name) TASK_FNS[task_kind] = fn_name return symbolication_fn # The names of tasks and metrics in this file point to tasks.store instead of tasks.symbolicator # for legacy reasons, namely to prevent tasks from dropping older tasks and needing to # update metrics tooling (e.g. DataDog). All (as of 19/10/2021) of these tasks were moved # out of tasks/store.py, hence the "store" bit of the name. # # New tasks and metrics are welcome to use the correct naming scheme as they are not # burdened by aforementioned legacy concerns. symbolicate_event = make_task_fn( name="sentry.tasks.store.symbolicate_event", queue="events.symbolicate_event", task_kind=SymbolicatorTaskKind(platform=SymbolicatorPlatform.native, is_reprocessing=False), ) symbolicate_js_event = make_task_fn( name="sentry.tasks.symbolicate_js_event", queue="events.symbolicate_js_event", task_kind=SymbolicatorTaskKind(platform=SymbolicatorPlatform.js, is_reprocessing=False), ) symbolicate_jvm_event = make_task_fn( name="sentry.tasks.symbolicate_jvm_event", queue="events.symbolicate_jvm_event", task_kind=SymbolicatorTaskKind(platform=SymbolicatorPlatform.jvm, is_reprocessing=False), ) # Reprocessing variants, only for "native" events: symbolicate_event_from_reprocessing = make_task_fn( name="sentry.tasks.store.symbolicate_event_from_reprocessing", queue="events.reprocessing.symbolicate_event", task_kind=SymbolicatorTaskKind(platform=SymbolicatorPlatform.native, is_reprocessing=True), )
SymbolicationTimeout
python
sympy__sympy
sympy/physics/quantum/tests/test_represent.py
{ "start": 1856, "end": 5177 }
class ____(Operator): def _represent_default_basis(self, **options): return self._represent_AOp(None, **options) def _represent_AOp(self, basis, **options): return Bmat k = AKet('a') b = ABra('a') A = AOp('A') B = BOp('B') _tests = [ # Bra (b, Dagger(Avec)), (Dagger(b), Avec), # Ket (k, Avec), (Dagger(k), Dagger(Avec)), # Operator (A, Amat), (Dagger(A), Dagger(Amat)), # OuterProduct (OuterProduct(k, b), Avec*Avec.H), # TensorProduct (TensorProduct(A, B), matrix_tensor_product(Amat, Bmat)), # Pow (A**2, Amat**2), # Add/Mul (A*B + 2*A, Amat*Bmat + 2*Amat), # Commutator (Commutator(A, B), Amat*Bmat - Bmat*Amat), # AntiCommutator (AntiCommutator(A, B), Amat*Bmat + Bmat*Amat), # InnerProduct (InnerProduct(b, k), (Avec.H*Avec)[0]) ] def test_format_sympy(): for test in _tests: lhs = represent(test[0], basis=A, format='sympy') rhs = to_sympy(test[1]) assert lhs == rhs def test_scalar_sympy(): assert represent(Integer(1)) == Integer(1) assert represent(Float(1.0)) == Float(1.0) assert represent(1.0 + I) == 1.0 + I np = import_module('numpy') def test_format_numpy(): if not np: skip("numpy not installed.") for test in _tests: lhs = represent(test[0], basis=A, format='numpy') rhs = to_numpy(test[1]) if isinstance(lhs, numpy_ndarray): assert (lhs == rhs).all() else: assert lhs == rhs def test_scalar_numpy(): if not np: skip("numpy not installed.") assert represent(Integer(1), format='numpy') == 1 assert represent(Float(1.0), format='numpy') == 1.0 assert represent(1.0 + I, format='numpy') == 1.0 + 1.0j scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']}) def test_format_scipy_sparse(): if not np: skip("numpy not installed.") if not scipy: skip("scipy not installed.") for test in _tests: lhs = represent(test[0], basis=A, format='scipy.sparse') rhs = to_scipy_sparse(test[1]) if isinstance(lhs, scipy_sparse_matrix): assert np.linalg.norm((lhs - rhs).todense()) == 0.0 else: assert lhs == rhs def test_scalar_scipy_sparse(): if not np: skip("numpy not installed.") if not scipy: skip("scipy not installed.") assert represent(Integer(1), format='scipy.sparse') == 1 assert represent(Float(1.0), format='scipy.sparse') == 1.0 assert represent(1.0 + I, format='scipy.sparse') == 1.0 + 1.0j x_ket = XKet('x') x_bra = XBra('x') x_op = XOp('X') def test_innerprod_represent(): assert rep_innerproduct(x_ket) == InnerProduct(XBra("x_1"), x_ket).doit() assert rep_innerproduct(x_bra) == InnerProduct(x_bra, XKet("x_1")).doit() raises(TypeError, lambda: rep_innerproduct(x_op)) def test_operator_represent(): basis_kets = enumerate_states(operators_to_state(x_op), 1, 2) assert rep_expectation( x_op) == qapply(basis_kets[1].dual*x_op*basis_kets[0]) def test_enumerate_states(): test = XKet("foo") assert enumerate_states(test, 1, 1) == [XKet("foo_1")] assert enumerate_states( test, [1, 2, 4]) == [XKet("foo_1"), XKet("foo_2"), XKet("foo_4")]
BOp
python
ray-project__ray
doc/source/serve/doc_code/monitoring/monitoring.py
{ "start": 193, "end": 486 }
class ____: async def __call__(self, request: Request) -> str: logger.info("Hello world!") return "hi" say_hello = SayHello.bind() # __end__ # serve.run(say_hello) # import requests # response = requests.get("http://localhost:8000/") # assert response.text == "hi"
SayHello
python
getsentry__sentry
src/sentry/issues/endpoints/organization_group_search_view_starred_order.py
{ "start": 680, "end": 1085 }
class ____(serializers.Serializer): view_ids = serializers.ListField(child=serializers.IntegerField(), required=True, min_length=0) def validate_view_ids(self, view_ids): if len(view_ids) != len(set(view_ids)): raise serializers.ValidationError("Single view cannot take up multiple positions") return view_ids @region_silo_endpoint
GroupSearchViewStarredOrderSerializer
python
Textualize__textual
src/textual/cache.py
{ "start": 437, "end": 6526 }
class ____(Generic[CacheKey, CacheValue]): """ A dictionary-like container with a maximum size. If an additional item is added when the LRUCache is full, the least recently used key is discarded to make room for the new item. The implementation is similar to functools.lru_cache, which uses a (doubly) linked list to keep track of the most recently used items. Each entry is stored as [PREV, NEXT, KEY, VALUE] where PREV is a reference to the previous entry, and NEXT is a reference to the next value. Note that stdlib's @lru_cache is implemented in C and faster! It's best to use @lru_cache where you are caching things that are fairly quick and called many times. Use LRUCache where you want increased flexibility and you are caching slow operations where the overhead of the cache is a small fraction of the total processing time. """ __slots__ = [ "_maxsize", "_cache", "_full", "_head", "hits", "misses", ] def __init__(self, maxsize: int) -> None: """Initialize a LRUCache. Args: maxsize: Maximum size of the cache, before old items are discarded. """ self._maxsize = maxsize self._cache: Dict[CacheKey, list[object]] = {} self._full = False self._head: list[object] = [] self.hits = 0 self.misses = 0 super().__init__() @property def maxsize(self) -> int: """int: Maximum size of cache, before new values evict old values.""" return self._maxsize @maxsize.setter def maxsize(self, maxsize: int) -> None: self._maxsize = maxsize def __bool__(self) -> bool: return bool(self._cache) def __len__(self) -> int: return len(self._cache) def __repr__(self) -> str: return f"<LRUCache size={len(self)} maxsize={self._maxsize} hits={self.hits} misses={self.misses}>" def grow(self, maxsize: int) -> None: """Grow the maximum size to at least `maxsize` elements. Args: maxsize: New maximum size. """ self.maxsize = max(self.maxsize, maxsize) def clear(self) -> None: """Clear the cache.""" self._cache.clear() self._full = False self._head = [] def keys(self) -> KeysView[CacheKey]: """Get cache keys.""" # Mostly for tests return self._cache.keys() def set(self, key: CacheKey, value: CacheValue) -> None: """Set a value. Args: key: Key. value: Value. """ if self._cache.get(key) is None: head = self._head if not head: # First link references itself self._head[:] = [head, head, key, value] else: # Add a new root to the beginning self._head = [head[0], head, key, value] # Updated references on previous root head[0][1] = self._head # type: ignore[index] head[0] = self._head self._cache[key] = self._head if self._full or len(self._cache) > self._maxsize: # Cache is full, we need to evict the oldest one self._full = True head = self._head last = head[0] last[0][1] = head # type: ignore[index] head[0] = last[0] # type: ignore[index] del self._cache[last[2]] # type: ignore[index] __setitem__ = set if TYPE_CHECKING: @overload def get(self, key: CacheKey) -> CacheValue | None: ... @overload def get( self, key: CacheKey, default: DefaultValue ) -> CacheValue | DefaultValue: ... def get( self, key: CacheKey, default: DefaultValue | None = None ) -> CacheValue | DefaultValue | None: """Get a value from the cache, or return a default if the key is not present. Args: key: Key default: Default to return if key is not present. Returns: Either the value or a default. """ if (link := self._cache.get(key)) is None: self.misses += 1 return default if link is not self._head: # Remove link from list link[0][1] = link[1] # type: ignore[index] link[1][0] = link[0] # type: ignore[index] head = self._head # Move link to head of list link[0] = head[0] link[1] = head self._head = head[0][1] = head[0] = link # type: ignore[index] self.hits += 1 return link[3] # type: ignore[return-value] def __getitem__(self, key: CacheKey) -> CacheValue: link = self._cache.get(key) if (link := self._cache.get(key)) is None: self.misses += 1 raise KeyError(key) if link is not self._head: link[0][1] = link[1] # type: ignore[index] link[1][0] = link[0] # type: ignore[index] head = self._head link[0] = head[0] link[1] = head self._head = head[0][1] = head[0] = link # type: ignore[index] self.hits += 1 return link[3] # type: ignore[return-value] def __contains__(self, key: CacheKey) -> bool: return key in self._cache def discard(self, key: CacheKey) -> None: """Discard item in cache from key. Args: key: Cache key. """ if key not in self._cache: return link = self._cache[key] # Remove link from list link[0][1] = link[1] # type: ignore[index] link[1][0] = link[0] # type: ignore[index] # Remove link from cache if self._head[2] == key: self._head = self._head[1] # type: ignore[assignment] if self._head[2] == key: # type: ignore[index] self._head = [] del self._cache[key] self._full = False
LRUCache
python
kevin1024__vcrpy
tests/unit/test_vcr.py
{ "start": 11250, "end": 12419 }
class ____(VCR().test_case()): def no_decoration(self): assert httplib.HTTPConnection == _HTTPConnection self.test_dynamically_added() assert httplib.HTTPConnection == _HTTPConnection def test_one(self): with force_reset(): self.no_decoration() with force_reset(): self.test_two() assert httplib.HTTPConnection != _HTTPConnection def test_two(self): assert httplib.HTTPConnection != _HTTPConnection def test_dynamically_added(self): assert httplib.HTTPConnection != _HTTPConnection TestVCRClass.test_dynamically_added = test_dynamically_added del test_dynamically_added def test_path_class_as_cassette(): path = Path(__file__).parent.parent.joinpath( "integration/cassettes/test_httpx_test_test_behind_proxy.yml", ) with use_cassette(path): pass def test_use_cassette_generator_return(): ret_val = object() vcr = VCR() @vcr.use_cassette("test") def gen(): return ret_val yield with pytest.raises(StopIteration) as exc_info: next(gen()) assert exc_info.value.value is ret_val
TestVCRClass
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_assorted_poly.py
{ "start": 49455, "end": 52060 }
class ____(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): global base_item_table, item_table global base_item_collection_table, collection_table base_item_table = Table( "base_item", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("child_name", String(255), default=None), ) item_table = Table( "item", metadata, Column( "id", Integer, ForeignKey("base_item.id"), primary_key=True ), Column("dummy", Integer, default=0), ) base_item_collection_table = Table( "base_item_collection", metadata, Column("item_id", Integer, ForeignKey("base_item.id")), Column("collection_id", Integer, ForeignKey("collection.id")), ) collection_table = Table( "collection", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("name", Unicode(255)), ) def test_pjoin_compile(self): """test that remote_side columns in the secondary join table aren't attempted to be matched to the target polymorphic selectable""" class BaseItem: pass class Item(BaseItem): pass class Collection: pass item_join = polymorphic_union( { "BaseItem": base_item_table.select() .where(base_item_table.c.child_name == "BaseItem") .subquery(), "Item": base_item_table.join(item_table), }, None, "item_join", ) self.mapper_registry.map_imperatively( BaseItem, base_item_table, with_polymorphic=("*", item_join), polymorphic_on=base_item_table.c.child_name, polymorphic_identity="BaseItem", properties=dict( collections=relationship( Collection, secondary=base_item_collection_table, backref="items", ) ), ) self.mapper_registry.map_imperatively( Item, item_table, inherits=BaseItem, polymorphic_identity="Item" ) self.mapper_registry.map_imperatively(Collection, collection_table) class_mapper(BaseItem)
ManyToManyPolyTest
python
imageio__imageio
imageio/plugins/spe.py
{ "start": 13810, "end": 32159 }
class ____(PluginV3): def __init__( self, request: Request, check_filesize: bool = True, char_encoding: Optional[str] = None, sdt_meta: Optional[bool] = None, ) -> None: """Instantiate a new SPE file plugin object Parameters ---------- request : Request A request object representing the resource to be operated on. check_filesize : bool If True, compute the number of frames from the filesize, compare it to the frame count in the file header, and raise a warning if the counts don't match. (Certain software may create files with char_encoding : str Deprecated. Exists for backwards compatibility; use ``char_encoding`` of ``metadata`` instead. sdt_meta : bool Deprecated. Exists for backwards compatibility; use ``sdt_control`` of ``metadata`` instead. """ super().__init__(request) if request.mode.io_mode == IOMode.write: raise InitializationError("cannot write SPE files") if char_encoding is not None: warnings.warn( "Passing `char_encoding` to the constructor is deprecated. " "Use `char_encoding` parameter of the `metadata()` method " "instead.", DeprecationWarning, ) self._char_encoding = char_encoding if sdt_meta is not None: warnings.warn( "Passing `sdt_meta` to the constructor is deprecated. " "Use `sdt_control` parameter of the `metadata()` method " "instead.", DeprecationWarning, ) self._sdt_meta = sdt_meta self._file = self.request.get_file() try: # Spec.basic contains no string, no need to worry about character # encoding. info = self._parse_header(Spec.basic, "latin1") self._file_header_ver = info["file_header_ver"] self._dtype = Spec.dtypes[info["datatype"]] self._shape = (info["ydim"], info["xdim"]) self._len = info["NumFrames"] if check_filesize: # Some software writes incorrect `NumFrames` metadata. # To determine the number of frames, check the size of the data # segment -- until the end of the file for SPE<3, until the # xml footer for SPE>=3. if info["file_header_ver"] >= 3: data_end = info["xml_footer_offset"] else: self._file.seek(0, os.SEEK_END) data_end = self._file.tell() line = data_end - Spec.data_start line //= self._shape[0] * self._shape[1] * self._dtype.itemsize if line != self._len: warnings.warn( f"The file header of {self.request.filename} claims there are " f"{self._len} frames, but there are actually {line} frames." ) self._len = min(line, self._len) self._file.seek(Spec.data_start) except Exception: raise InitializationError("SPE plugin cannot read the provided file.") def read(self, *, index: int = ...) -> np.ndarray: """Read a frame or all frames from the file Parameters ---------- index : int Select the index-th frame from the file. If index is `...`, select all frames and stack them along a new axis. Returns ------- A Numpy array of pixel values. """ if index is Ellipsis: read_offset = Spec.data_start count = self._shape[0] * self._shape[1] * self._len out_shape = (self._len, *self._shape) elif index < 0: raise IndexError(f"Index `{index}` is smaller than 0.") elif index >= self._len: raise IndexError( f"Index `{index}` exceeds the number of frames stored in this file (`{self._len}`)." ) else: read_offset = ( Spec.data_start + index * self._shape[0] * self._shape[1] * self._dtype.itemsize ) count = self._shape[0] * self._shape[1] out_shape = self._shape self._file.seek(read_offset) data = np.fromfile(self._file, dtype=self._dtype, count=count) return data.reshape(out_shape) def iter(self) -> Iterator[np.ndarray]: """Iterate over the frames in the file Yields ------ A Numpy array of pixel values. """ return (self.read(index=i) for i in range(self._len)) def metadata( self, index: int = ..., exclude_applied: bool = True, char_encoding: str = "latin1", sdt_control: bool = True, ) -> Dict[str, Any]: """SPE specific metadata. Parameters ---------- index : int Ignored as SPE files only store global metadata. exclude_applied : bool Ignored. Exists for API compatibility. char_encoding : str The encoding to use when parsing strings. sdt_control : bool If `True`, decode special metadata written by the SDT-control software if present. Returns ------- metadata : dict Key-value pairs of metadata. Notes ----- SPE v3 stores metadata as XML, whereas SPE v2 uses a binary format. .. rubric:: Supported SPE v2 Metadata fields ROIs : list of dict Regions of interest used for recording images. Each dict has the "top_left" key containing x and y coordinates of the top left corner, the "bottom_right" key with x and y coordinates of the bottom right corner, and the "bin" key with number of binned pixels in x and y directions. comments : list of str The SPE format allows for 5 comment strings of 80 characters each. controller_version : int Hardware version logic_output : int Definition of output BNC amp_hi_cap_low_noise : int Amp switching mode mode : int Timing mode exp_sec : float Alternative exposure in seconds date : str Date string detector_temp : float Detector temperature detector_type : int CCD / diode array type st_diode : int Trigger diode delay_time : float Used with async mode shutter_control : int Normal, disabled open, or disabled closed absorb_live : bool on / off absorb_mode : int Reference strip or file can_do_virtual_chip : bool True or False whether chip can do virtual chip threshold_min_live : bool on / off threshold_min_val : float Threshold minimum value threshold_max_live : bool on / off threshold_max_val : float Threshold maximum value time_local : str Experiment local time time_utc : str Experiment UTC time adc_offset : int ADC offset adc_rate : int ADC rate adc_type : int ADC type adc_resolution : int ADC resolution adc_bit_adjust : int ADC bit adjust gain : int gain sw_version : str Version of software which created this file spare_4 : bytes Reserved space readout_time : float Experiment readout time type : str Controller type clockspeed_us : float Vertical clock speed in microseconds readout_mode : ["full frame", "frame transfer", "kinetics", ""] Readout mode. Empty string means that this was not set by the Software. window_size : int Window size for Kinetics mode file_header_ver : float File header version chip_size : [int, int] x and y dimensions of the camera chip virt_chip_size : [int, int] Virtual chip x and y dimensions pre_pixels : [int, int] Pre pixels in x and y dimensions post_pixels : [int, int], Post pixels in x and y dimensions geometric : list of {"rotate", "reverse", "flip"} Geometric operations sdt_major_version : int (only for files created by SDT-control) Major version of SDT-control software sdt_minor_version : int (only for files created by SDT-control) Minor version of SDT-control software sdt_controller_name : str (only for files created by SDT-control) Controller name exposure_time : float (only for files created by SDT-control) Exposure time in seconds color_code : str (only for files created by SDT-control) Color channels used detection_channels : int (only for files created by SDT-control) Number of channels background_subtraction : bool (only for files created by SDT-control) Whether background subtraction war turned on em_active : bool (only for files created by SDT-control) Whether EM was turned on em_gain : int (only for files created by SDT-control) EM gain modulation_active : bool (only for files created by SDT-control) Whether laser modulation (“attenuate”) was turned on pixel_size : float (only for files created by SDT-control) Camera pixel size sequence_type : str (only for files created by SDT-control) Type of sequnce (standard, TOCCSL, arbitrary, …) grid : float (only for files created by SDT-control) Sequence time unit (“grid size”) in seconds n_macro : int (only for files created by SDT-control) Number of macro loops delay_macro : float (only for files created by SDT-control) Time between macro loops in seconds n_mini : int (only for files created by SDT-control) Number of mini loops delay_mini : float (only for files created by SDT-control) Time between mini loops in seconds n_micro : int (only for files created by SDT-control) Number of micro loops delay_micro : float (only for files created by SDT-control) Time between micro loops in seconds n_subpics : int (only for files created by SDT-control) Number of sub-pictures delay_shutter : float (only for files created by SDT-control) Camera shutter delay in seconds delay_prebleach : float (only for files created by SDT-control) Pre-bleach delay in seconds bleach_time : float (only for files created by SDT-control) Bleaching time in seconds recovery_time : float (only for files created by SDT-control) Recovery time in seconds comment : str (only for files created by SDT-control) User-entered comment. This replaces the "comments" field. datetime : datetime.datetime (only for files created by SDT-control) Combines the "date" and "time_local" keys. The latter two plus "time_utc" are removed. modulation_script : str (only for files created by SDT-control) Laser modulation script. Replaces the "spare_4" key. bleach_piezo_active : bool (only for files created by SDT-control) Whether piezo for bleaching was enabled """ if self._file_header_ver < 3: if self._char_encoding is not None: char_encoding = self._char_encoding if self._sdt_meta is not None: sdt_control = self._sdt_meta return self._metadata_pre_v3(char_encoding, sdt_control) return self._metadata_post_v3() def _metadata_pre_v3(self, char_encoding: str, sdt_control: bool) -> Dict[str, Any]: """Extract metadata from SPE v2 files Parameters ---------- char_encoding String character encoding sdt_control If `True`, try to decode special metadata written by the SDT-control software. Returns ------- dict mapping metadata names to values. """ m = self._parse_header(Spec.metadata, char_encoding) nr = m.pop("NumROI", None) nr = 1 if nr < 1 else nr m["ROIs"] = roi_array_to_dict(m["ROIs"][:nr]) # chip sizes m["chip_size"] = [m.pop(k, None) for k in ("xDimDet", "yDimDet")] m["virt_chip_size"] = [m.pop(k, None) for k in ("VChipXdim", "VChipYdim")] m["pre_pixels"] = [m.pop(k, None) for k in ("XPrePixels", "YPrePixels")] m["post_pixels"] = [m.pop(k, None) for k in ("XPostPixels", "YPostPixels")] # convert comments from numpy.str_ to str m["comments"] = [str(c) for c in m["comments"]] # geometric operations g = [] f = m.pop("geometric", 0) if f & 1: g.append("rotate") if f & 2: g.append("reverse") if f & 4: g.append("flip") m["geometric"] = g # Make some additional information more human-readable t = m["type"] if 1 <= t <= len(Spec.controllers): m["type"] = Spec.controllers[t - 1] else: m["type"] = None r = m["readout_mode"] if 1 <= r <= len(Spec.readout_modes): m["readout_mode"] = Spec.readout_modes[r - 1] else: m["readout_mode"] = None # bools for k in ( "absorb_live", "can_do_virtual_chip", "threshold_min_live", "threshold_max_live", ): m[k] = bool(m[k]) # Extract SDT-control metadata if desired if sdt_control: SDTControlSpec.extract_metadata(m, char_encoding) return m def _metadata_post_v3(self) -> Dict[str, Any]: """Extract XML metadata from SPE v3 files Returns ------- dict with key `"__xml"`, whose value is the XML metadata """ info = self._parse_header(Spec.basic, "latin1") self._file.seek(info["xml_footer_offset"]) xml = self._file.read() return {"__xml": xml} def properties(self, index: int = ...) -> ImageProperties: """Standardized ndimage metadata. Parameters ---------- index : int If the index is an integer, select the index-th frame and return its properties. If index is an Ellipsis (...), return the properties of all frames in the file stacked along a new batch dimension. Returns ------- properties : ImageProperties A dataclass filled with standardized image metadata. """ if index is Ellipsis: return ImageProperties( shape=(self._len, *self._shape), dtype=self._dtype, n_images=self._len, is_batch=True, ) return ImageProperties(shape=self._shape, dtype=self._dtype, is_batch=False) def _parse_header( self, spec: Mapping[str, Tuple], char_encoding: str ) -> Dict[str, Any]: """Get information from SPE file header Parameters ---------- spec Maps header entry name to its location, data type description and optionally number of entries. See :py:attr:`Spec.basic` and :py:attr:`Spec.metadata`. char_encoding String character encoding Returns ------- Dict mapping header entry name to its value """ ret = {} # Decode each string from the numpy array read by np.fromfile decode = np.vectorize(lambda x: x.decode(char_encoding)) for name, sp in spec.items(): self._file.seek(sp[0]) cnt = 1 if len(sp) < 3 else sp[2] v = np.fromfile(self._file, dtype=sp[1], count=cnt) if v.dtype.kind == "S" and name not in Spec.no_decode: # Silently ignore string decoding failures try: v = decode(v) except Exception: warnings.warn( f'Failed to decode "{name}" metadata ' "string. Check `char_encoding` parameter." ) try: # For convenience, if the array contains only one single # entry, return this entry itself. v = v.item() except ValueError: v = np.squeeze(v) ret[name] = v return ret def roi_array_to_dict(a: np.ndarray) -> List[Dict[str, List[int]]]: """Convert the `ROIs` structured arrays to :py:class:`dict` Parameters ---------- a Structured array containing ROI data Returns ------- One dict per ROI. Keys are "top_left", "bottom_right", and "bin", values are tuples whose first element is the x axis value and the second element is the y axis value. """ dict_list = [] a = a[["startx", "starty", "endx", "endy", "groupx", "groupy"]] for sx, sy, ex, ey, gx, gy in a: roi_dict = { "top_left": [int(sx), int(sy)], "bottom_right": [int(ex), int(ey)], "bin": [int(gx), int(gy)], } dict_list.append(roi_dict) return dict_list
SpePlugin
python
mkdocs__mkdocs
mkdocs/config/config_options.py
{ "start": 5886, "end": 8051 }
class ____(Generic[T], BaseConfigOption[List[T]]): """ Validates a homogeneous list of items. E.g. for `config_options.ListOfItems(config_options.Type(int))` a valid item is `[1, 2, 3]`. """ required: bool | None = None # Only for subclasses to set. def __init__(self, option_type: BaseConfigOption[T], default=None) -> None: super().__init__() self.default = default self.option_type = option_type self.option_type.warnings = self.warnings def __repr__(self) -> str: return f'{type(self).__name__}: {self.option_type}' def pre_validation(self, config: Config, key_name: str): self._config = config self._key_name = key_name def run_validation(self, value: object) -> list[T]: if value is None: if self.required or self.default is None: raise ValidationError("Required configuration not provided.") value = self.default if not isinstance(value, list): raise ValidationError(f'Expected a list of items, but a {type(value)} was given.') if not value: # Optimization for empty list return value fake_config = LegacyConfig(()) try: fake_config.config_file_path = self._config.config_file_path except AttributeError: pass # Emulate a config-like environment for pre_validation and post_validation. parent_key_name = getattr(self, '_key_name', '') fake_keys = [f'{parent_key_name}[{i}]' for i in range(len(value))] fake_config.data = dict(zip(fake_keys, value)) self.option_type.warnings = self.warnings for key_name in fake_config: self.option_type.pre_validation(fake_config, key_name) for key_name in fake_config: # Specifically not running `validate` to avoid the OptionallyRequired effect. fake_config[key_name] = self.option_type.run_validation(fake_config[key_name]) for key_name in fake_config: self.option_type.post_validation(fake_config, key_name) return [fake_config[k] for k in fake_keys]
ListOfItems
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance6.py
{ "start": 328, "end": 1097 }
class ____(ParentA[_T1]): ... def func1(a: ParentA[int], b: ParentA[str] | ParentA[complex]) -> None: if isinstance(a, ChildA1): reveal_type(a, expected_text="ChildA1[int]") if isinstance(b, ChildA1): reveal_type(b, expected_text="ChildA1[str] | ChildA1[complex]") def func2( a: type[ParentA[int]], b: type[ParentA[str]] | type[ParentA[complex]] ) -> None: if issubclass(a, ChildA1): reveal_type(a, expected_text="type[ChildA1[int]]") if issubclass(b, ChildA1): reveal_type(b, expected_text="type[ChildA1[str]] | type[ChildA1[complex]]") def func3(value: Iterable[_T1]) -> Sequence[_T1] | None: if isinstance(value, Sequence): return value _T2 = TypeVar("_T2", bound=float, covariant=True)
ChildA1
python
getsentry__sentry
src/sentry/migrations/0968_delete_dashboardwidgetsnapshot_db_constraint.py
{ "start": 222, "end": 1712 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # of a table. # Here are some things that make sense to mark as post deployment: # - Large data migrations. Typically we want these to be run manually so that they can be # monitored and not block the deploy for a long period of time while they run. # - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to # run this outside deployments so that we don't block them. Note that while adding an index # is a schema change, it's completely safe to run the operation after the code has deployed. # Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment is_post_deployment = False dependencies = [ ("sentry", "0967_large_tables_legacy_json_field"), ] operations = [ migrations.AlterField( model_name="dashboardwidgetsnapshot", name="widget", field=sentry.db.models.fields.foreignkey.FlexibleForeignKey( db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to="sentry.dashboardwidget", ), ), ]
Migration
python
getsentry__sentry
src/sentry/identity/vsts/provider.py
{ "start": 2076, "end": 5327 }
class ____(OAuth2Provider): key = IntegrationProviderSlug.AZURE_DEVOPS.value name = "Azure DevOps" oauth_access_token_url = "https://app.vssps.visualstudio.com/oauth2/token" oauth_authorize_url = "https://app.vssps.visualstudio.com/oauth2/authorize" def get_oauth_client_id(self): return options.get("vsts.client-id") def get_oauth_client_secret(self): return options.get("vsts.client-secret") def get_refresh_token_url(self) -> str: return self.oauth_access_token_url def get_pipeline_views(self) -> list[PipelineView[IdentityPipeline]]: return [ OAuth2LoginView( authorize_url=self.oauth_authorize_url, client_id=self.get_oauth_client_id(), scope=" ".join(self.get_oauth_scopes()), ), VSTSOAuth2CallbackView( access_token_url=self.oauth_access_token_url, client_id=self.get_oauth_client_id(), client_secret=self.get_oauth_client_secret(), ), ] def get_refresh_token_headers(self): return {"Content-Type": "application/x-www-form-urlencoded", "Content-Length": "1654"} def get_refresh_token_params( self, refresh_token: str, identity: Identity | RpcIdentity, **kwargs: Any ) -> dict[str, str | None]: client_secret = options.get("vsts.client-secret") # The token refresh flow does not operate within a pipeline in the same way # that installation does, this means that we have to use the identity.scopes # to determine which client_secret to use. # # If "vso.code" is missing from the identity.scopes, we know that we installed # using the "vsts-limited.client-secret" and therefore should use that to refresh # the token. # TODO(ecosystem): We should not use scopes to determine which client_secret to use assert isinstance( identity, Identity ), "Legacy VSTS identity provider only supports Identity" if "vso.code" not in identity.scopes: client_secret = options.get("vsts-limited.client-secret") oauth_redirect_url = kwargs.get("redirect_url") if oauth_redirect_url is None: raise ValueError("VSTS requires oauth redirect url when refreshing identity") return { "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", "client_assertion": client_secret, "grant_type": "refresh_token", "assertion": refresh_token, "redirect_uri": absolute_uri(oauth_redirect_url), } def build_identity(self, data): data = data["data"] access_token = data.get("access_token") if not access_token: raise PermissionDenied() user = get_user_info(access_token) return { "type": IntegrationProviderSlug.AZURE_DEVOPS.value, "id": user["id"], "email": user["emailAddress"], "email_verified": True, "name": user["displayName"], "scopes": sorted(self.oauth_scopes), "data": self.get_oauth_data(data), }
VSTSIdentityProvider
python
google__python-fire
fire/parser_fuzz_test.py
{ "start": 821, "end": 3041 }
class ____(testutils.BaseTestCase): @settings(max_examples=10000) @given(st.text(min_size=1)) @example('True') @example(r'"test\t\t\a\\a"') @example(r' "test\t\t\a\\a" ') @example('"(1, 2)"') @example('(1, 2)') @example('(1, 2)') @example('(1, 2) ') @example('a,b,c,d') @example('(a,b,c,d)') @example('[a,b,c,d]') @example('{a,b,c,d}') @example('test:(a,b,c,d)') @example('{test:(a,b,c,d)}') @example('{test:a,b,c,d}') @example('{test:a,b:(c,d)}') # Note: Edit distance may be high for dicts. @example('0,') @example('#') @example('A#00000') # Note: '#'' is treated as a comment. @example('\x80') # Note: Causes UnicodeDecodeError. @example(100 * '[' + '0') # Note: Causes MemoryError. @example('\r\r\r\r1\r\r') def testDefaultParseValueFuzz(self, value): try: result = parser.DefaultParseValue(value) except TypeError: # It's OK to get a TypeError if the string has the null character. if '\x00' in value: return raise except MemoryError: if len(value) > 100: # This is not what we're testing. return raise try: uvalue = str(value) uresult = str(result) except UnicodeDecodeError: # This is not what we're testing. return # Check that the parsed value doesn't differ too much from the input. distance = Levenshtein.distance(uresult, uvalue) max_distance = ( 2 + # Quotes or parenthesis can be implicit. sum(c.isspace() for c in value) + value.count('"') + value.count("'") + 3 * (value.count(',') + 1) + # 'a,' can expand to "'a', " 3 * (value.count(':')) + # 'a:' can expand to "'a': " 2 * value.count('\\')) if '#' in value: max_distance += len(value) - value.index('#') if not isinstance(result, str): max_distance += value.count('0') # Leading 0s are stripped. # Note: We don't check distance for dicts since item order can be changed. if '{' not in value: self.assertLessEqual(distance, max_distance, (distance, max_distance, uvalue, uresult)) if __name__ == '__main__': testutils.main()
ParserFuzzTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-braintree/source_braintree/schemas/dispute.py
{ "start": 465, "end": 1106 }
class ____(CatalogModel): amount_disputed: Decimal amount_won: Decimal case_number: str chargeback_protection_level: Optional[str] created_at: datetime currency_iso_code: str evidence: Union[Evidence, List[Evidence]] graphql_id: str id: str kind: str merchant_account_id: str original_dispute_id: Optional[str] paypal_messages: List[PaypalMessage] processor_comments: Optional[str] reason: str reason_code: str reason_description: Optional[str] received_date: date reference_number: Optional[str] reply_by_date: date status: str updated_at: datetime
Dispute
python
kamyu104__LeetCode-Solutions
Python/number-of-people-aware-of-a-secret.py
{ "start": 34, "end": 451 }
class ____(object): def peopleAwareOfSecret(self, n, delay, forget): """ :type n: int :type delay: int :type forget: int :rtype: int """ MOD = 10**9+7 dp = [0]*forget dp[0] = 1 for i in xrange(1, n): dp[i%forget] = ((dp[(i-1)%forget] if i-1 else 0)-dp[i%forget]+dp[(i-delay)%forget]) % MOD return sum(dp)%MOD
Solution
python
spack__spack
lib/spack/spack/vendor/jinja2/bccache.py
{ "start": 6155, "end": 9802 }
class ____(BytecodeCache): """A bytecode cache that stores bytecode on the filesystem. It accepts two arguments: The directory where the cache items are stored and a pattern string that is used to build the filename. If no directory is specified a default cache directory is selected. On Windows the user's temp directory is used, on UNIX systems a directory is created for the user in the system temp directory. The pattern can be used to have multiple separate caches operate on the same directory. The default pattern is ``'__spack.vendor.jinja2_%s.cache'``. ``%s`` is replaced with the cache key. >>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache') This bytecode cache supports clearing of the cache using the clear method. """ def __init__( self, directory: t.Optional[str] = None, pattern: str = "__spack.vendor.jinja2_%s.cache" ) -> None: if directory is None: directory = self._get_default_cache_dir() self.directory = directory self.pattern = pattern def _get_default_cache_dir(self) -> str: def _unsafe_dir() -> "te.NoReturn": raise RuntimeError( "Cannot determine safe temp directory. You " "need to explicitly provide one." ) tmpdir = tempfile.gettempdir() # On windows the temporary directory is used specific unless # explicitly forced otherwise. We can just use that. if os.name == "nt": return tmpdir if not hasattr(os, "getuid"): _unsafe_dir() dirname = f"_spack.vendor.jinja2-cache-{os.getuid()}" actual_dir = os.path.join(tmpdir, dirname) try: os.mkdir(actual_dir, stat.S_IRWXU) except OSError as e: if e.errno != errno.EEXIST: raise try: os.chmod(actual_dir, stat.S_IRWXU) actual_dir_stat = os.lstat(actual_dir) if ( actual_dir_stat.st_uid != os.getuid() or not stat.S_ISDIR(actual_dir_stat.st_mode) or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU ): _unsafe_dir() except OSError as e: if e.errno != errno.EEXIST: raise actual_dir_stat = os.lstat(actual_dir) if ( actual_dir_stat.st_uid != os.getuid() or not stat.S_ISDIR(actual_dir_stat.st_mode) or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU ): _unsafe_dir() return actual_dir def _get_cache_filename(self, bucket: Bucket) -> str: return os.path.join(self.directory, self.pattern % (bucket.key,)) def load_bytecode(self, bucket: Bucket) -> None: filename = self._get_cache_filename(bucket) if os.path.exists(filename): with open(filename, "rb") as f: bucket.load_bytecode(f) def dump_bytecode(self, bucket: Bucket) -> None: with open(self._get_cache_filename(bucket), "wb") as f: bucket.write_bytecode(f) def clear(self) -> None: # imported lazily here because google app-engine doesn't support # write access on the file system and the function does not exist # normally. from os import remove files = fnmatch.filter(os.listdir(self.directory), self.pattern % ("*",)) for filename in files: try: remove(os.path.join(self.directory, filename)) except OSError: pass
FileSystemBytecodeCache
python
getsentry__sentry
src/sentry/api/serializers/models/group_stream.py
{ "start": 6907, "end": 7007 }
class ____(TypedDict, total=False): stats: dict[str, dict[int, list[tuple[int, int]]]]
_MaybeStats
python
getsentry__sentry-python
tests/integrations/mcp/test_mcp.py
{ "start": 2310, "end": 2834 }
class ____: """Mock HTTP request for SSE/StreamableHTTP transport""" def __init__(self, session_id=None, transport="http"): self.headers = {} self.query_params = {} if transport == "sse": # SSE transport uses query parameter if session_id: self.query_params["session_id"] = session_id else: # StreamableHTTP transport uses header if session_id: self.headers["mcp-session-id"] = session_id
MockHTTPRequest
python
python-excel__xlwt
xlwt/antlr.py
{ "start": 3503, "end": 4330 }
class ____(ANTLRException): def __init__(self, *args): ANTLRException.__init__(self, *args) self.fileName = None self.line = -1 self.column = -1 if len(args) >= 2: self.fileName = args[1] if len(args) >= 3: self.line = args[2] if len(args) >= 4: self.column = args[3] def __str__(self): buf = [''] if self.fileName: buf.append(self.fileName + ":") if self.line != -1: if not self.fileName: buf.append("line ") buf.append(str(self.line)) if self.column != -1: buf.append(":" + str(self.column)) buf.append(":") buf.append(" ") return str('').join(buf) __repr__ = __str__
RecognitionException
python
qdrant__qdrant-client
qdrant_client/http/api/service_api.py
{ "start": 1311, "end": 4085 }
class ____: def __init__(self, api_client: "Union[ApiClient, AsyncApiClient]"): self.api_client = api_client def _build_for_healthz( self, ): """ An endpoint for health checking used in Kubernetes. """ headers = {} return self.api_client.request( type_=str, method="GET", url="/healthz", headers=headers if headers else None, ) def _build_for_livez( self, ): """ An endpoint for health checking used in Kubernetes. """ headers = {} return self.api_client.request( type_=str, method="GET", url="/livez", headers=headers if headers else None, ) def _build_for_metrics( self, anonymize: bool = None, ): """ Collect metrics data including app info, collections info, cluster info and statistics """ query_params = {} if anonymize is not None: query_params["anonymize"] = str(anonymize).lower() headers = {} return self.api_client.request( type_=str, method="GET", url="/metrics", headers=headers if headers else None, params=query_params, ) def _build_for_readyz( self, ): """ An endpoint for health checking used in Kubernetes. """ headers = {} return self.api_client.request( type_=str, method="GET", url="/readyz", headers=headers if headers else None, ) def _build_for_root( self, ): """ Returns information about the running Qdrant instance like version and commit id """ headers = {} return self.api_client.request( type_=m.VersionInfo, method="GET", url="/", headers=headers if headers else None, ) def _build_for_telemetry( self, anonymize: bool = None, details_level: int = None, ): """ Collect telemetry data including app info, system info, collections info, cluster info, configs and statistics """ query_params = {} if anonymize is not None: query_params["anonymize"] = str(anonymize).lower() if details_level is not None: query_params["details_level"] = str(details_level) headers = {} return self.api_client.request( type_=m.InlineResponse2001, method="GET", url="/telemetry", headers=headers if headers else None, params=query_params, )
_ServiceApi
python
django__django
django/db/models/functions/math.py
{ "start": 3623, "end": 3724 }
class ____(FixDecimalInputMixin, NumericOutputFieldMixin, Func): function = "MOD" arity = 2
Mod
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 411230, "end": 412319 }
class ____(ExprNode): # Represents a single item in a DictNode # # key ExprNode # value ExprNode subexprs = ['key', 'value'] nogil_check = None # Parent DictNode takes care of it def calculate_constant_result(self): self.constant_result = ( self.key.constant_result, self.value.constant_result) def analyse_types(self, env): self.key = self.key.analyse_types(env) self.value = self.value.analyse_types(env) self.key = self.key.coerce_to_pyobject(env) self.value = self.value.coerce_to_pyobject(env) return self def generate_evaluation_code(self, code): self.key.generate_evaluation_code(code) self.value.generate_evaluation_code(code) def generate_disposal_code(self, code): self.key.generate_disposal_code(code) self.value.generate_disposal_code(code) def free_temps(self, code): self.key.free_temps(code) self.value.free_temps(code) def __iter__(self): return iter([self.key, self.value])
DictItemNode
python
django__django
tests/db_functions/text/test_substr.py
{ "start": 174, "end": 1918 }
class ____(TestCase): def test_basic(self): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.annotate(name_part=Substr("name", 5, 3)) self.assertQuerySetEqual( authors.order_by("name"), [" Sm", "da"], lambda a: a.name_part ) authors = Author.objects.annotate(name_part=Substr("name", 2)) self.assertQuerySetEqual( authors.order_by("name"), ["ohn Smith", "honda"], lambda a: a.name_part ) # If alias is null, set to first 5 lower characters of the name. Author.objects.filter(alias__isnull=True).update( alias=Lower(Substr("name", 1, 5)), ) self.assertQuerySetEqual( authors.order_by("name"), ["smithj", "rhond"], lambda a: a.alias ) def test_start(self): Author.objects.create(name="John Smith", alias="smithj") a = Author.objects.annotate( name_part_1=Substr("name", 1), name_part_2=Substr("name", 2), ).get(alias="smithj") self.assertEqual(a.name_part_1[1:], a.name_part_2) def test_pos_gt_zero(self): with self.assertRaisesMessage(ValueError, "'pos' must be greater than 0"): Author.objects.annotate(raises=Substr("name", 0)) def test_expressions(self): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") substr = Substr(Upper("name"), StrIndex("name", V("h")), 5) authors = Author.objects.annotate(name_part=substr) self.assertQuerySetEqual( authors.order_by("name"), ["HN SM", "HONDA"], lambda a: a.name_part )
SubstrTests
python
tensorflow__tensorflow
tensorflow/python/autograph/core/function_wrappers.py
{ "start": 1209, "end": 4355 }
class ____(object): """Context manager that wraps the body of a converted function. This context manager handles various operations related to the scope of a function: * optional TF name scopes - these name scopes match the name of the function, for easy visualization in tensorBoard; * optional automatic control dependencies - this adds the same mechanism for control dependencies that is used by `@tf.function`; it can be optionally enabled when using `tf.autograph.to_graph`; * tracking of autograph conversion state (whether it's enabled by the user, conversion options; """ def __init__(self, function_name, scope_name, options): self.name = scope_name self.options = options if options.user_requested: self.autograph_ctx = ag_ctx.ControlStatusCtx(ag_ctx.Status.ENABLED, options) self.callopts = options.call_options() use_name_scope = options.uses(converter.Feature.NAME_SCOPES) self.use_name_scope = use_name_scope if use_name_scope: self.name_scope = ops.name_scope(self._sanitize(function_name)) use_auto_deps = self.options.uses(converter.Feature.AUTO_CONTROL_DEPS) self.use_auto_deps = use_auto_deps if use_auto_deps: self.autodeps_scope = auto_control_deps.AutomaticControlDependencies() self._return_value_marked = False def _sanitize(self, name): """See https://www.tensorflow.org/api_docs/python/tf/Graph#name_scope.""" # TensorFlow doesn't like leading underscores at the top level. if name and name.startswith('_'): name = 'fn' + name return name def __enter__(self): if self.options.user_requested: self.autograph_ctx.__enter__() if self.use_name_scope: self.name_scope.__enter__() if self.use_auto_deps: self.autodeps_scope.__enter__() return self def __exit__(self, exc_type, exc_val, exc_tb): if self.options.user_requested: self.autograph_ctx.__exit__(exc_type, exc_val, exc_tb) if self.use_name_scope: self.name_scope.__exit__(exc_type, exc_val, exc_tb) if self.use_auto_deps: self.autodeps_scope.__exit__(exc_type, exc_val, exc_tb) def ret(self, value, did_return): """Marks a value as returned from the function guarded by the scope.""" del did_return if isinstance(value, variables.UndefinedReturnValue): return None if self.use_auto_deps: self._return_value_marked = True if value is None: # We don't create dummy returns, to preserve Python semantics. The user # is responsible for adding a return value to the top-level function. return None def _mark_return_if_tensor(t): if tensor_util.is_tf_type(t): return self.autodeps_scope.mark_as_return(t) return t value = nest.map_structure(_mark_return_if_tensor, value) return value def with_function_scope(thunk, scope_name, options): """Inline version of the FunctionScope context manager.""" with FunctionScope('lambda_', scope_name, options) as scope: return thunk(scope)
FunctionScope
python
dagster-io__dagster
python_modules/dagster/dagster_tests/components_tests/template_vars_tests/test_basic_template_vars.py
{ "start": 237, "end": 2002 }
class ____(dg.Component, dg.Resolvable, dg.Model): value: str @staticmethod @dg.template_var def foo() -> str: return "value_for_foo" @staticmethod @dg.template_var def a_udf() -> Callable: return lambda: "a_udf_value" @staticmethod @dg.template_var def a_udf_with_args() -> Callable: return lambda x: f"a_udf_value_{x}" def build_defs(self, context: ComponentLoadContext) -> dg.Definitions: ... def test_basic_additional_scope_hardcoded_value(): load_context, component = load_context_and_component_for_test( ComponentWithAdditionalScope, {"value": "a_value"} ) assert component.value == "a_value" @pytest.mark.skipif( sys.version_info < (3, 10), reason="staticmethod behavior differs on python 3.9" ) def test_basic_additional_scope_scope_var(): load_context, component = load_context_and_component_for_test( ComponentWithAdditionalScope, {"value": "{{ foo }}"} ) assert component.value == "value_for_foo" @pytest.mark.skipif( sys.version_info < (3, 10), reason="staticmethod behavior differs on python 3.9" ) def test_basic_additional_scope_scope_udf_no_args(): load_context, component = load_context_and_component_for_test( ComponentWithAdditionalScope, {"value": "{{ a_udf() }}"} ) assert component.value == "a_udf_value" @pytest.mark.skipif( sys.version_info < (3, 10), reason="staticmethod behavior differs on python 3.9" ) def test_basic_additional_scope_scope_udf_with_args(): load_context, component = load_context_and_component_for_test( ComponentWithAdditionalScope, {"value": "{{ a_udf_with_args('1') }}"} ) assert component.value == "a_udf_value_1"
ComponentWithAdditionalScope
python
huggingface__transformers
tests/models/siglip/test_modeling_siglip.py
{ "start": 6125, "end": 9442 }
class ____(SiglipModelTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as SIGLIP does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = (SiglipVisionModel,) if is_torch_available() else () test_resize_embeddings = False # MP works but offload doesn't work when the MultiheadAttention is offloaded # TODO: One potential solution would be to add to set preload_module_classes = ["SiglipMultiheadAttentionPoolingHead"] # in the dispatch_model function test_cpu_offload = False test_disk_offload_safetensors = False test_disk_offload_bin = False def setUp(self): self.model_tester = SiglipVisionModelTester(self) self.config_tester = ConfigTester( self, config_class=SiglipVisionConfig, has_text_modality=False, hidden_size=37 ) def test_config(self): self.config_tester.run_common_tests() @unittest.skip(reason="SIGLIP does not use inputs_embeds") def test_inputs_embeds(self): pass def test_model_get_set_embeddings(self): config, _ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) x = model.get_output_embeddings() self.assertTrue(x is None or isinstance(x, nn.Linear)) def test_forward_signature(self): config, _ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) signature = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic arg_names = [*signature.parameters.keys()] expected_arg_names = ["pixel_values"] self.assertListEqual(arg_names[:1], expected_arg_names) def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) @unittest.skip(reason="SiglipVisionModel does not support standalone training") def test_training(self): pass @unittest.skip(reason="SiglipVisionModel does not support standalone training") def test_training_gradient_checkpointing(self): pass @unittest.skip(reason="SiglipVisionModel does not support standalone training") def test_training_gradient_checkpointing_use_reentrant(self): pass @unittest.skip(reason="SiglipVisionModel does not support standalone training") def test_training_gradient_checkpointing_use_reentrant_false(self): pass @slow def test_model_from_pretrained(self): model_name = "google/siglip-base-patch16-224" model = SiglipVisionModel.from_pretrained(model_name) self.assertIsNotNone(model) @parameterized.expand(TEST_EAGER_MATCHES_SDPA_INFERENCE_PARAMETERIZATION) def test_eager_matches_sdpa_inference(self, *args): # adding only flaky decorator here and call the parent test method return getattr(ModelTesterMixin, self._testMethodName)(self)
SiglipVisionModelTest
python
vyperlang__vyper
vyper/semantics/namespace.py
{ "start": 249, "end": 3703 }
class ____(dict): """ Dictionary subclass that represents the namespace of a contract. Attributes ---------- _scopes : List[Set] List of sets containing the key names for each scope """ def __new__(cls, *args, **kwargs): self = super().__new__(cls, *args, **kwargs) self._scopes = [] return self def __init__(self): super().__init__() # NOTE cyclic imports! # TODO: break this cycle by providing an `init_vyper_namespace` in 3rd module from vyper.builtins.functions import get_builtin_functions from vyper.semantics import environment from vyper.semantics.analysis.base import VarInfo from vyper.semantics.types import PRIMITIVE_TYPES self.update(PRIMITIVE_TYPES) self.update(environment.get_constant_vars()) self.update({k: VarInfo(b) for (k, b) in get_builtin_functions().items()}) def __eq__(self, other): return self is other def __setitem__(self, attr, obj): if self._scopes: self.validate_assignment(attr) self._scopes[-1].add(attr) assert isinstance(attr, str), f"not a string: {attr}" super().__setitem__(attr, obj) def __getitem__(self, key): if key not in self: hint = get_levenshtein_error_suggestions(key, self, 0.2) raise UndeclaredDefinition(f"'{key}' has not been declared.", hint=hint) return super().__getitem__(key) def __enter__(self): if not self._scopes: raise CompilerPanic("Context manager must be invoked via namespace.enter_scope()") def __exit__(self, exc_type, exc_value, traceback): if not self._scopes: raise CompilerPanic("Bad use of namespace as a context manager") for key in self._scopes.pop(): del self[key] def enter_scope(self): """ Enter a new scope within the namespace. Called as a context manager, e.g. `with namespace.enter_scope():` All items that are added within the context are removed upon exit. """ # NOTE cyclic imports! from vyper.semantics import environment self._scopes.append(set()) if len(self._scopes) == 1: # add mutable vars (`self`) to the initial scope self.update(environment.get_mutable_vars()) return self def update(self, other): for key, value in other.items(): self.__setitem__(key, value) def clear(self): super().clear() self.__init__() def validate_assignment(self, attr): validate_identifier(attr) if attr in self: prev = super().__getitem__(attr) prev_decl = getattr(prev, "decl_node", None) msg = f"'{attr}' has already been declared" if prev_decl is None: msg += f" as a {prev}" raise NamespaceCollision(msg, prev_decl=prev_decl) def get_namespace(): """ Get the global namespace object. """ global _namespace try: return _namespace except NameError: _namespace = Namespace() return _namespace @contextlib.contextmanager def override_global_namespace(ns): global _namespace tmp = _namespace try: # clobber global namespace _namespace = ns yield finally: # unclobber _namespace = tmp
Namespace
python
Netflix__metaflow
metaflow/exception.py
{ "start": 4137, "end": 4215 }
class ____(MetaflowException): headline = "Data missing"
MetaflowDataMissing
python
pyca__cryptography
src/cryptography/x509/extensions.py
{ "start": 50329, "end": 52239 }
class ____(ExtensionType): oid = ExtensionOID.ISSUER_ALTERNATIVE_NAME def __init__(self, general_names: Iterable[GeneralName]) -> None: self._general_names = GeneralNames(general_names) __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names") @typing.overload def get_values_for_type( self, type: type[DNSName] | type[UniformResourceIdentifier] | type[RFC822Name], ) -> list[str]: ... @typing.overload def get_values_for_type( self, type: type[DirectoryName], ) -> list[Name]: ... @typing.overload def get_values_for_type( self, type: type[RegisteredID], ) -> list[ObjectIdentifier]: ... @typing.overload def get_values_for_type( self, type: type[IPAddress] ) -> list[_IPAddressTypes]: ... @typing.overload def get_values_for_type( self, type: type[OtherName] ) -> list[OtherName]: ... def get_values_for_type( self, type: type[DNSName] | type[DirectoryName] | type[IPAddress] | type[OtherName] | type[RFC822Name] | type[RegisteredID] | type[UniformResourceIdentifier], ) -> ( list[_IPAddressTypes] | list[str] | list[OtherName] | list[Name] | list[ObjectIdentifier] ): return self._general_names.get_values_for_type(type) def __repr__(self) -> str: return f"<IssuerAlternativeName({self._general_names})>" def __eq__(self, other: object) -> bool: if not isinstance(other, IssuerAlternativeName): return NotImplemented return self._general_names == other._general_names def __hash__(self) -> int: return hash(self._general_names) def public_bytes(self) -> bytes: return rust_x509.encode_extension_value(self)
IssuerAlternativeName
python
walkccc__LeetCode
solutions/213. House Robber II/213.py
{ "start": 0, "end": 401 }
class ____: def rob(self, nums: list[int]) -> int: if not nums: return 0 if len(nums) < 2: return nums[0] def rob(l: int, r: int) -> int: dp1 = 0 dp2 = 0 for i in range(l, r + 1): temp = dp1 dp1 = max(dp1, dp2 + nums[i]) dp2 = temp return dp1 return max(rob(0, len(nums) - 2), rob(1, len(nums) - 1))
Solution
python
pyinstaller__pyinstaller
PyInstaller/loader/pyimod02_importers.py
{ "start": 4764, "end": 17392 }
class ____: """ PyInstaller's frozen path entry finder for specific search path. Per-path instances allow us to properly translate the given module name ("fullname") into full PYZ entry name. For example, with search path being `sys._MEIPASS`, the module "mypackage.mod" would translate to "mypackage.mod" in the PYZ archive. However, if search path was `sys._MEIPASS/myotherpackage/_vendored` (for example, if `myotherpacakge` added this path to `sys.path`), then "mypackage.mod" would need to translate to "myotherpackage._vendored.mypackage.mod" in the PYZ archive. """ def __repr__(self): return f"{self.__class__.__name__}({self._path})" @classmethod def path_hook(cls, path): trace(f"PyInstaller: running path finder hook for path: {path!r}") try: finder = cls(path) trace("PyInstaller: hook succeeded") return finder except Exception as e: trace(f"PyInstaller: hook failed: {e}") raise def __init__(self, path): self._path = path # Store original path, as given. self._pyz_archive = pyz_archive # Compute relative path to the top-level application directory. Do not try to resolve the path itself, because # it might contain symbolic links in parts other than the prefix that corresponds to the top-level application # directory. See #8994 for an example (files symlinked from a common directory outside of the top-level # application directory). Instead, try to compute relative path w.r.t. the original and the resolved top-level # application directory. for top_level_path in _TOP_LEVEL_DIRECTORY_PATHS: try: relative_path = os.path.relpath(path, top_level_path) except ValueError: continue # Failed to compute relative path w.r.t. the given top-level directory path. if relative_path.startswith('..'): continue # Relative path points outside of the given top-level directory. break # Successful match; stop here. else: raise ImportError("Failed to determine relative path w.r.t. top-level application directory.") # Ensure that path does not point to a file on filesystem. Strictly speaking, we should be checking that the # given path is a valid directory, but that would need to check both PYZ and filesystem. So for now, limit the # check to catch paths pointing to file, because that breaks `runpy.run_path()`, as per #8767. if os.path.isfile(path): raise ImportError("only directories are supported") if relative_path == '.': self._pyz_entry_prefix = '' else: self._pyz_entry_prefix = '.'.join(relative_path.split(os.path.sep)) def _compute_pyz_entry_name(self, fullname): """ Convert module fullname into PYZ entry name, subject to the prefix implied by this finder's search path. """ tail_module = fullname.rpartition('.')[2] if self._pyz_entry_prefix: return self._pyz_entry_prefix + "." + tail_module else: return tail_module @property def fallback_finder(self): """ Opportunistically create a *fallback finder* using `sys.path_hooks` entries that are located *after* our hook. The main goal of this exercise is to obtain an instance of python's FileFinder, but in theory any other hook that comes after ours is eligible to be a fallback. Having this fallback allows our finder to "cooperate" with python's FileFinder, as if the two were a single finder, which allows us to work around the python's PathFinder permitting only one finder instance per path without subclassing FileFinder. """ if hasattr(self, '_fallback_finder'): return self._fallback_finder # Try to instantiate fallback finder our_hook_found = False self._fallback_finder = None for idx, hook in enumerate(sys.path_hooks): if hook == self.path_hook: our_hook_found = True continue # Our hook if not our_hook_found: continue # Skip hooks before our hook try: self._fallback_finder = hook(self._path) break except ImportError: pass return self._fallback_finder def _find_fallback_spec(self, fullname, target): """ Attempt to find the spec using fallback finder, which is opportunistically created here. Typically, this would be python's FileFinder, which can discover specs for on-filesystem modules, such as extension modules and modules that are collected only as source .py files. Having this fallback allows our finder to "cooperate" with python's FileFinder, as if the two were a single finder, which allows us to work around the python's PathFinder permitting only one finder instance per path without subclassing FileFinder. """ if not hasattr(self, '_fallback_finder'): self._fallback_finder = self._get_fallback_finder() if self._fallback_finder is None: return None return self._fallback_finder.find_spec(fullname, target) #-- Core PEP451 finder functionality, modeled after importlib.abc.PathEntryFinder # https://docs.python.org/3/library/importlib.html#importlib.abc.PathEntryFinder def invalidate_caches(self): """ A method which, when called, should invalidate any internal cache used by the finder. Used by importlib.invalidate_caches() when invalidating the caches of all finders on sys.meta_path. https://docs.python.org/3/library/importlib.html#importlib.abc.MetaPathFinder.invalidate_caches """ # We do not use any caches, but if we have created a fallback finder, propagate the function call. # NOTE: use getattr() with _fallback_finder attribute, in order to avoid unnecessary creation of the # fallback finder in case when it does not exist yet. fallback_finder = getattr(self, '_fallback_finder', None) if fallback_finder is not None: if hasattr(fallback_finder, 'invalidate_caches'): fallback_finder.invalidate_caches() def find_spec(self, fullname, target=None): """ A method for finding a spec for the specified module. The finder will search for the module only within the path entry to which it is assigned. If a spec cannot be found, None is returned. When passed in, target is a module object that the finder may use to make a more educated guess about what spec to return. https://docs.python.org/3/library/importlib.html#importlib.abc.PathEntryFinder.find_spec """ trace(f"{self}: find_spec: called with fullname={fullname!r}, target={fullname!r}") # Convert fullname to PYZ entry name. pyz_entry_name = self._compute_pyz_entry_name(fullname) # Try looking up the entry in the PYZ archive entry_data = self._pyz_archive.toc.get(pyz_entry_name) if entry_data is None: # Entry not found - try using fallback finder (for example, python's own FileFinder) to resolve on-disk # resources, such as extension modules and modules that are collected only as source .py files. trace(f"{self}: find_spec: {fullname!r} not found in PYZ...") if self.fallback_finder is not None: trace(f"{self}: find_spec: attempting resolve using fallback finder {self.fallback_finder!r}.") fallback_spec = self.fallback_finder.find_spec(fullname, target) trace(f"{self}: find_spec: fallback finder returned spec: {fallback_spec!r}.") return fallback_spec else: trace(f"{self}: find_spec: fallback finder is not available.") return None # Entry found typecode = entry_data[0] trace(f"{self}: find_spec: found {fullname!r} in PYZ as {pyz_entry_name!r}, typecode={typecode}") if typecode == pyimod01_archive.PYZ_ITEM_NSPKG: # PEP420 namespace package # We can use regular list for submodule_search_locations; the caller (i.e., python's PathFinder) takes care # of constructing _NamespacePath from it. spec = _frozen_importlib.ModuleSpec(fullname, None) spec.submodule_search_locations = [ # NOTE: since we are using sys._MEIPASS as prefix, we need to construct path from resolved PYZ entry # name (equivalently, we could combine `self._path` and last part of `fullname`). os.path.join(sys._MEIPASS, pyz_entry_name.replace('.', os.path.sep)), ] return spec is_package = typecode == pyimod01_archive.PYZ_ITEM_PKG # Instantiate frozen loader for the module loader = PyiFrozenLoader( name=fullname, pyz_archive=self._pyz_archive, pyz_entry_name=pyz_entry_name, is_package=is_package, ) # Resolve full filename, as if the module/package was located on filesystem. This is done by the loader. origin = loader.path # Construct spec for module, using all collected information. spec = _frozen_importlib.ModuleSpec( fullname, loader, is_package=is_package, origin=origin, ) # Make the import machinery set __file__. # PEP 451 says: "has_location" is true if the module is locatable. In that case the spec's origin is used # as the location and __file__ is set to spec.origin. If additional location information is required # (e.g., zipimport), that information may be stored in spec.loader_state. spec.has_location = True # Set submodule_search_locations for packages. Seems to be required for importlib_resources from 3.2.0; # see issue #5395. if is_package: spec.submodule_search_locations = [os.path.dirname(origin)] return spec # The following methods are part of legacy PEP302 finder interface. They have been deprecated since python 3.4, # and removed in python 3.12. Provide compatibility shims to accommodate code that might still be using them. if sys.version_info[:2] < (3, 12): def find_loader(self, fullname): """ A legacy method for finding a loader for the specified module. Returns a 2-tuple of (loader, portion) where portion is a sequence of file system locations contributing to part of a namespace package. The loader may be None while specifying portion to signify the contribution of the file system locations to a namespace package. An empty list can be used for portion to signify the loader is not part of a namespace package. If loader is None and portion is the empty list then no loader or location for a namespace package were found (i.e. failure to find anything for the module). Deprecated since python 3.4, removed in 3.12. """ # Based on: # https://github.com/python/cpython/blob/v3.11.9/Lib/importlib/_bootstrap_external.py#L1587-L1600 spec = self.find_spec(fullname) if spec is None: return None, [] return spec.loader, spec.submodule_search_locations or [] def find_module(self, fullname): """ A concrete implementation of Finder.find_module() which is equivalent to self.find_loader(fullname)[0]. Deprecated since python 3.4, removed in 3.12. """ # Based on: # https://github.com/python/cpython/blob/v3.11.9/Lib/importlib/_bootstrap_external.py#L1585 # https://github.com/python/cpython/blob/v3.11.9/Lib/importlib/_bootstrap_external.py#L622-L639 # loader, portions = self.find_loader(fullname) return loader # Helper for enforcing module name in PyiFrozenLoader methods. def _check_name(method): def _check_name_wrapper(self, name, *args, **kwargs): if self.name != name: raise ImportError(f'loader for {self.name} cannot handle {name}', name=name) return method(self, name, *args, **kwargs) return _check_name_wrapper
PyiFrozenFinder
python
ray-project__ray
doc/source/serve/doc_code/image_classifier_example.py
{ "start": 407, "end": 1055 }
class ____: def __init__(self, downloader: DeploymentHandle): self.downloader = downloader self.model = pipeline( "image-classification", model="google/vit-base-patch16-224" ) async def classify(self, image_url: str) -> str: image = await self.downloader.remote(image_url) results = self.model(image) return results[0]["label"] async def __call__(self, req: starlette.requests.Request): req = await req.json() return await self.classify(req["image_url"]) app = ImageClassifier.bind(downloader.bind()) # __serve_example_end__ @serve.deployment
ImageClassifier
python
tensorflow__tensorflow
tensorflow/python/framework/combinations.py
{ "start": 1122, "end": 1844 }
class ____(test_combinations.TestCombination): """Run the test in Graph or Eager mode. The optional `mode` parameter controls the test's execution mode. Its accepted values are "graph" or "eager" literals. """ def context_managers(self, kwargs): mode = kwargs.pop("mode", None) if mode is None: return [] elif mode == "eager": return [context.eager_mode()] elif mode == "graph": return [ops.Graph().as_default(), context.graph_mode()] else: raise ValueError( "Argument 'mode' must be either 'eager' or 'graph'. " f"Received: {mode}.") def parameter_modifiers(self): return [test_combinations.OptionalParameter("mode")]
EagerGraphCombination
python
Netflix__metaflow
metaflow/exception.py
{ "start": 2436, "end": 2614 }
class ____(MetaflowException): headline = "External command failed" def __init__(self, msg): super(ExternalCommandFailed, self).__init__(msg)
ExternalCommandFailed
python
pypa__hatch
tests/project/test_utils.py
{ "start": 78, "end": 1303 }
class ____: def test_no_metadata(self): assert parse_inline_script_metadata("") is None def test_too_many_blocks(self, helpers): script = helpers.dedent( """ # /// script # dependencies = ["foo"] # /// # /// script # dependencies = ["foo"] # /// """ ) with pytest.raises(ValueError, match="^Multiple inline metadata blocks found for type: script$"): parse_inline_script_metadata(script) def test_correct(self, helpers): script = helpers.dedent( """ # /// script # embedded-csharp = ''' # /// <summary> # /// text # /// # /// </summary> # public class MyClass { } # ''' # /// """ ) assert parse_inline_script_metadata(script) == { "embedded-csharp": helpers.dedent( """ /// <summary> /// text /// /// </summary> public class MyClass { } """ ), }
TestParseInlineScriptMetadata
python
PrefectHQ__prefect
tests/assets/test_materializing_tasks.py
{ "start": 48, "end": 1370 }
class ____: def test_with_options_assets_parameter_keeps_existing(self): @materialize("storage://original/asset.csv", persist_result=True) def initial_task(): pass task_with_options = initial_task.with_options(persist_result=False) assert task_with_options.assets == [Asset(key="storage://original/asset.csv")] assert not task_with_options.persist_result def test_with_options_assets_takes_precedence_over_existing(self): @materialize("storage://foo/bar/asset.csv", persist_result=False) def initial_task(): pass task_with_options = initial_task.with_options( assets=["storage://foo/baz/asset.csv"] ) assert task_with_options.assets == [Asset(key="storage://foo/baz/asset.csv")] assert not task_with_options.persist_result def test_with_options_assets_allows_both(self): @materialize("storage://foo/bar/asset.csv", persist_result=False) def initial_task(): pass task_with_options = initial_task.with_options( assets=["storage://foo/baz/asset.csv"], persist_result=True ) assert task_with_options.assets == [Asset(key="storage://foo/baz/asset.csv")] assert task_with_options.persist_result
TestMaterializingTask
python
walkccc__LeetCode
solutions/2273. Find Resultant Array After Removing Anagrams/2273.py
{ "start": 0, "end": 456 }
class ____: def removeAnagrams(self, words: list[str]) -> list[str]: ans = [] def isAnagram(a: str, b: str) -> bool: count = collections.Counter(a) count.subtract(collections.Counter(b)) return all(value == 0 for value in count.values()) i = 0 while i < len(words): j = i + 1 while j < len(words) and isAnagram(words[i], words[j]): j += 1 ans.append(words[i]) i = j return ans
Solution
python
django__django
tests/model_forms/models.py
{ "start": 392, "end": 711 }
class ____(models.Model): name = models.CharField(max_length=20) slug = models.SlugField(max_length=20) url = models.CharField("The URL", max_length=40) class Meta: ordering = ("pk",) def __str__(self): return self.name def __repr__(self): return self.__str__()
Category
python
scikit-image__scikit-image
src/skimage/segmentation/morphsnakes.py
{ "start": 297, "end": 14878 }
class ____: def __init__(self, iterable): """Call functions from the iterable each time it is called.""" self.funcs = cycle(iterable) def __call__(self, *args, **kwargs): f = next(self.funcs) return f(*args, **kwargs) # SI and IS operators for 2D and 3D. _P2 = [ np.eye(3), np.array([[0, 1, 0]] * 3), np.flipud(np.eye(3)), np.rot90([[0, 1, 0]] * 3), ] _P3 = [np.zeros((3, 3, 3)) for i in range(9)] _P3[0][:, :, 1] = 1 _P3[1][:, 1, :] = 1 _P3[2][1, :, :] = 1 _P3[3][:, [0, 1, 2], [0, 1, 2]] = 1 _P3[4][:, [0, 1, 2], [2, 1, 0]] = 1 _P3[5][[0, 1, 2], :, [0, 1, 2]] = 1 _P3[6][[0, 1, 2], :, [2, 1, 0]] = 1 _P3[7][[0, 1, 2], [0, 1, 2], :] = 1 _P3[8][[0, 1, 2], [2, 1, 0], :] = 1 def sup_inf(u): """SI operator.""" if np.ndim(u) == 2: P = _P2 elif np.ndim(u) == 3: P = _P3 else: raise ValueError("u has an invalid number of dimensions " "(should be 2 or 3)") erosions = [] for P_i in P: erosions.append(ndi.binary_erosion(u, P_i).astype(np.int8)) return np.stack(erosions, axis=0).max(0) def inf_sup(u): """IS operator.""" if np.ndim(u) == 2: P = _P2 elif np.ndim(u) == 3: P = _P3 else: raise ValueError("u has an invalid number of dimensions " "(should be 2 or 3)") dilations = [] for P_i in P: dilations.append(ndi.binary_dilation(u, P_i).astype(np.int8)) return np.stack(dilations, axis=0).min(0) _curvop = _fcycle( [lambda u: sup_inf(inf_sup(u)), lambda u: inf_sup(sup_inf(u))] # SIoIS ) # ISoSI def _check_input(image, init_level_set): """Check that shapes of `image` and `init_level_set` match.""" check_nD(image, [2, 3]) if len(image.shape) != len(init_level_set.shape): raise ValueError( "The dimensions of the initial level set do not " "match the dimensions of the image." ) def _init_level_set(init_level_set, image_shape): """Auxiliary function for initializing level sets with a string. If `init_level_set` is not a string, it is returned as is. """ if isinstance(init_level_set, str): if init_level_set == 'checkerboard': res = checkerboard_level_set(image_shape) elif init_level_set == 'disk': res = disk_level_set(image_shape) else: raise ValueError("`init_level_set` not in " "['checkerboard', 'disk']") else: res = init_level_set return res def disk_level_set(image_shape, *, center=None, radius=None): """Create a disk level set with binary values. Parameters ---------- image_shape : tuple of positive integers Shape of the image center : tuple of positive integers, optional Coordinates of the center of the disk given in (row, column). If not given, it defaults to the center of the image. radius : float, optional Radius of the disk. If not given, it is set to the 75% of the smallest image dimension. Returns ------- out : array with shape `image_shape` Binary level set of the disk with the given `radius` and `center`. See Also -------- checkerboard_level_set """ if center is None: center = tuple(i // 2 for i in image_shape) if radius is None: radius = min(image_shape) * 3.0 / 8.0 grid = np.mgrid[[slice(i) for i in image_shape]] grid = (grid.T - center).T phi = radius - np.sqrt(np.sum((grid) ** 2, 0)) res = np.int8(phi > 0) return res def checkerboard_level_set(image_shape, square_size=5): """Create a checkerboard level set with binary values. Parameters ---------- image_shape : tuple of positive integers Shape of the image. square_size : int, optional Size of the squares of the checkerboard. It defaults to 5. Returns ------- out : array with shape `image_shape` Binary level set of the checkerboard. See Also -------- disk_level_set """ grid = np.mgrid[[slice(i) for i in image_shape]] grid = grid // square_size # Alternate 0/1 for even/odd numbers. grid = grid & 1 checkerboard = np.bitwise_xor.reduce(grid, axis=0) res = np.int8(checkerboard) return res def inverse_gaussian_gradient(image, alpha=100.0, sigma=5.0): """Inverse of gradient magnitude. Compute the magnitude of the gradients in the image and then inverts the result in the range [0, 1]. Flat areas are assigned values close to 1, while areas close to borders are assigned values close to 0. This function or a similar one defined by the user should be applied over the image as a preprocessing step before calling `morphological_geodesic_active_contour`. Parameters ---------- image : (M, N) or (L, M, N) array Grayscale image or volume. alpha : float, optional Controls the steepness of the inversion. A larger value will make the transition between the flat areas and border areas steeper in the resulting array. sigma : float, optional Standard deviation of the Gaussian filter applied over the image. Returns ------- gimage : (M, N) or (L, M, N) array Preprocessed image (or volume) suitable for `morphological_geodesic_active_contour`. """ gradnorm = ndi.gaussian_gradient_magnitude(image, sigma, mode='nearest') return 1.0 / np.sqrt(1.0 + alpha * gradnorm) def morphological_chan_vese( image, num_iter, init_level_set='checkerboard', smoothing=1, lambda1=1, lambda2=1, iter_callback=lambda x: None, ): """Morphological Active Contours without Edges (MorphACWE) Active contours without edges implemented with morphological operators. It can be used to segment objects in images and volumes without well defined borders. It is required that the inside of the object looks different on average than the outside (i.e., the inner area of the object should be darker or lighter than the outer area on average). Parameters ---------- image : (M, N) or (L, M, N) array Grayscale image or volume to be segmented. num_iter : uint Number of num_iter to run init_level_set : str, (M, N) array, or (L, M, N) array Initial level set. If an array is given, it will be binarized and used as the initial level set. If a string is given, it defines the method to generate a reasonable initial level set with the shape of the `image`. Accepted values are 'checkerboard' and 'disk'. See the documentation of `checkerboard_level_set` and `disk_level_set` respectively for details about how these level sets are created. smoothing : uint, optional Number of times the smoothing operator is applied per iteration. Reasonable values are around 1-4. Larger values lead to smoother segmentations. lambda1 : float, optional Weight parameter for the outer region. If `lambda1` is larger than `lambda2`, the outer region will contain a larger range of values than the inner region. lambda2 : float, optional Weight parameter for the inner region. If `lambda2` is larger than `lambda1`, the inner region will contain a larger range of values than the outer region. iter_callback : function, optional If given, this function is called once per iteration with the current level set as the only argument. This is useful for debugging or for plotting intermediate results during the evolution. Returns ------- out : (M, N) or (L, M, N) array Final segmentation (i.e., the final level set) See Also -------- disk_level_set, checkerboard_level_set Notes ----- This is a version of the Chan-Vese algorithm that uses morphological operators instead of solving a partial differential equation (PDE) for the evolution of the contour. The set of morphological operators used in this algorithm are proved to be infinitesimally equivalent to the Chan-Vese PDE (see [1]_). However, morphological operators are do not suffer from the numerical stability issues typically found in PDEs (it is not necessary to find the right time step for the evolution), and are computationally faster. The algorithm and its theoretical derivation are described in [1]_. References ---------- .. [1] A Morphological Approach to Curvature-based Evolution of Curves and Surfaces, Pablo Márquez-Neila, Luis Baumela, Luis Álvarez. In IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), 2014, :DOI:`10.1109/TPAMI.2013.106` """ init_level_set = _init_level_set(init_level_set, image.shape) _check_input(image, init_level_set) u = np.int8(init_level_set > 0) iter_callback(u) for _ in range(num_iter): # inside = u > 0 # outside = u <= 0 c0 = (image * (1 - u)).sum() / float((1 - u).sum() + 1e-8) c1 = (image * u).sum() / float(u.sum() + 1e-8) # Image attachment du = np.gradient(u) abs_du = np.abs(du).sum(0) aux = abs_du * (lambda1 * (image - c1) ** 2 - lambda2 * (image - c0) ** 2) u[aux < 0] = 1 u[aux > 0] = 0 # Smoothing for _ in range(smoothing): u = _curvop(u) iter_callback(u) return u def morphological_geodesic_active_contour( gimage, num_iter, init_level_set='disk', smoothing=1, threshold='auto', balloon=0, iter_callback=lambda x: None, ): """Morphological Geodesic Active Contours (MorphGAC). Geodesic active contours implemented with morphological operators. It can be used to segment objects with visible but noisy, cluttered, broken borders. Parameters ---------- gimage : (M, N) or (L, M, N) array Preprocessed image or volume to be segmented. This is very rarely the original image. Instead, this is usually a preprocessed version of the original image that enhances and highlights the borders (or other structures) of the object to segment. :func:`morphological_geodesic_active_contour` will try to stop the contour evolution in areas where `gimage` is small. See :func:`inverse_gaussian_gradient` as an example function to perform this preprocessing. Note that the quality of :func:`morphological_geodesic_active_contour` might greatly depend on this preprocessing. num_iter : uint Number of num_iter to run. init_level_set : str, (M, N) array, or (L, M, N) array Initial level set. If an array is given, it will be binarized and used as the initial level set. If a string is given, it defines the method to generate a reasonable initial level set with the shape of the `image`. Accepted values are 'checkerboard' and 'disk'. See the documentation of `checkerboard_level_set` and `disk_level_set` respectively for details about how these level sets are created. smoothing : uint, optional Number of times the smoothing operator is applied per iteration. Reasonable values are around 1-4. Larger values lead to smoother segmentations. threshold : float, optional Areas of the image with a value smaller than this threshold will be considered borders. The evolution of the contour will stop in these areas. balloon : float, optional Balloon force to guide the contour in non-informative areas of the image, i.e., areas where the gradient of the image is too small to push the contour towards a border. A negative value will shrink the contour, while a positive value will expand the contour in these areas. Setting this to zero will disable the balloon force. iter_callback : function, optional If given, this function is called once per iteration with the current level set as the only argument. This is useful for debugging or for plotting intermediate results during the evolution. Returns ------- out : (M, N) or (L, M, N) array Final segmentation (i.e., the final level set) See Also -------- inverse_gaussian_gradient, disk_level_set, checkerboard_level_set Notes ----- This is a version of the Geodesic Active Contours (GAC) algorithm that uses morphological operators instead of solving partial differential equations (PDEs) for the evolution of the contour. The set of morphological operators used in this algorithm are proved to be infinitesimally equivalent to the GAC PDEs (see [1]_). However, morphological operators are do not suffer from the numerical stability issues typically found in PDEs (e.g., it is not necessary to find the right time step for the evolution), and are computationally faster. The algorithm and its theoretical derivation are described in [1]_. References ---------- .. [1] A Morphological Approach to Curvature-based Evolution of Curves and Surfaces, Pablo Márquez-Neila, Luis Baumela, Luis Álvarez. In IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), 2014, :DOI:`10.1109/TPAMI.2013.106` """ image = gimage init_level_set = _init_level_set(init_level_set, image.shape) _check_input(image, init_level_set) if threshold == 'auto': threshold = np.percentile(image, 40) structure = np.ones((3,) * len(image.shape), dtype=np.int8) dimage = np.gradient(image) # threshold_mask = image > threshold if balloon != 0: threshold_mask_balloon = image > threshold / np.abs(balloon) u = np.int8(init_level_set > 0) iter_callback(u) for _ in range(num_iter): # Balloon if balloon > 0: aux = ndi.binary_dilation(u, structure) elif balloon < 0: aux = ndi.binary_erosion(u, structure) if balloon != 0: u[threshold_mask_balloon] = aux[threshold_mask_balloon] # Image attachment aux = np.zeros_like(image) du = np.gradient(u) for el1, el2 in zip(dimage, du): aux += el1 * el2 u[aux > 0] = 1 u[aux < 0] = 0 # Smoothing for _ in range(smoothing): u = _curvop(u) iter_callback(u) return u
_fcycle