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
pandas-dev__pandas
asv_bench/benchmarks/dtypes.py
{ "start": 481, "end": 645 }
class ____: params = _dtypes + [dt.name for dt in _dtypes] param_names = ["dtype"] def time_pandas_dtype(self, dtype): pandas_dtype(dtype)
Dtypes
python
dagster-io__dagster
python_modules/libraries/dagster-census/dagster_census/components/census_component.py
{ "start": 989, "end": 1196 }
class ____(dg.Resolvable, dg.Model): by_name: Annotated[ Sequence[str], pydantic.Field(..., description="A list of sync names to include in the collection."), ]
CensusSyncSelectorByName
python
django__django
tests/responses/tests.py
{ "start": 1821, "end": 6455 }
class ____(SimpleTestCase): def test_status_code(self): resp = HttpResponse(status=503) self.assertEqual(resp.status_code, 503) self.assertEqual(resp.reason_phrase, "Service Unavailable") def test_change_status_code(self): resp = HttpResponse() resp.status_code = 503 self.assertEqual(resp.status_code, 503) self.assertEqual(resp.reason_phrase, "Service Unavailable") def test_valid_status_code_string(self): resp = HttpResponse(status="100") self.assertEqual(resp.status_code, 100) resp = HttpResponse(status="404") self.assertEqual(resp.status_code, 404) resp = HttpResponse(status="599") self.assertEqual(resp.status_code, 599) def test_invalid_status_code(self): must_be_integer = "HTTP status code must be an integer." must_be_integer_in_range = ( "HTTP status code must be an integer from 100 to 599." ) with self.assertRaisesMessage(TypeError, must_be_integer): HttpResponse(status=object()) with self.assertRaisesMessage(TypeError, must_be_integer): HttpResponse(status="J'attendrai") with self.assertRaisesMessage(ValueError, must_be_integer_in_range): HttpResponse(status=99) with self.assertRaisesMessage(ValueError, must_be_integer_in_range): HttpResponse(status=600) def test_reason_phrase(self): reason = "I'm an anarchist coffee pot on crack." resp = HttpResponse(status=419, reason=reason) self.assertEqual(resp.status_code, 419) self.assertEqual(resp.reason_phrase, reason) def test_charset_detection(self): """HttpResponse should parse charset from content_type.""" response = HttpResponse("ok") self.assertEqual(response.charset, settings.DEFAULT_CHARSET) response = HttpResponse(charset=ISO88591) self.assertEqual(response.charset, ISO88591) self.assertEqual( response.headers["Content-Type"], "text/html; charset=%s" % ISO88591 ) response = HttpResponse( content_type="text/plain; charset=%s" % UTF8, charset=ISO88591 ) self.assertEqual(response.charset, ISO88591) response = HttpResponse(content_type="text/plain; charset=%s" % ISO88591) self.assertEqual(response.charset, ISO88591) response = HttpResponse(content_type='text/plain; charset="%s"' % ISO88591) self.assertEqual(response.charset, ISO88591) response = HttpResponse(content_type="text/plain; charset=") self.assertEqual(response.charset, settings.DEFAULT_CHARSET) response = HttpResponse(content_type="text/plain") self.assertEqual(response.charset, settings.DEFAULT_CHARSET) def test_response_content_charset(self): """HttpResponse should encode based on charset.""" content = "Café :)" utf8_content = content.encode(UTF8) iso_content = content.encode(ISO88591) response = HttpResponse(utf8_content) self.assertContains(response, utf8_content) response = HttpResponse( iso_content, content_type="text/plain; charset=%s" % ISO88591 ) self.assertContains(response, iso_content) response = HttpResponse(iso_content) self.assertContains(response, iso_content) response = HttpResponse(iso_content, content_type="text/plain") self.assertContains(response, iso_content) def test_repr(self): response = HttpResponse(content="Café :)".encode(UTF8), status=201) expected = '<HttpResponse status_code=201, "text/html; charset=utf-8">' self.assertEqual(repr(response), expected) def test_repr_no_content_type(self): response = HttpResponse(status=204) del response.headers["Content-Type"] self.assertEqual(repr(response), "<HttpResponse status_code=204>") def test_wrap_textiowrapper(self): content = "Café :)" r = HttpResponse() with io.TextIOWrapper(r, UTF8) as buf: buf.write(content) self.assertEqual(r.content, content.encode(UTF8)) def test_generator_cache(self): generator = (str(i) for i in range(10)) response = HttpResponse(content=generator) self.assertEqual(response.content, b"0123456789") with self.assertRaises(StopIteration): next(generator) cache.set("my-response-key", response) response = cache.get("my-response-key") self.assertEqual(response.content, b"0123456789")
HttpResponseTests
python
python-excel__xlwt
xlwt/BIFFRecords.py
{ "start": 8131, "end": 8917 }
class ____(BiffRecord): """ This record is part of the file protection. It contains the name of the user that has saved the file. The user name is always stored as an equal-sized string. All unused characters after the name are filled with space characters. It is not required to write the mentioned string length. Every other length will be accepted too. """ _REC_ID = 0x005C def __init__(self, owner): uowner = owner[0:0x30] uowner_len = len(uowner) if isinstance(uowner, six.text_type): uowner = uowner.encode('ascii') # probably not ascii, but play it safe until we know more self._rec_data = pack('%ds%ds' % (uowner_len, 0x70 - uowner_len), uowner, b' '*(0x70 - uowner_len))
WriteAccessRecord
python
pytorch__pytorch
torch/testing/_comparison.py
{ "start": 12835, "end": 15922 }
class ____(abc.ABC): """ABC for all comparison pairs to be used in conjunction with :func:`assert_equal`. Each subclass needs to overwrite :meth:`Pair.compare` that performs the actual comparison. Each pair receives **all** options, so select the ones applicable for the subclass and forward the rest to the super class. Raising an :class:`UnsupportedInputs` during constructions indicates that the pair is not able to handle the inputs and the next pair type will be tried. All other errors should be raised as :class:`ErrorMeta`. After the instantiation, :meth:`Pair._make_error_meta` can be used to automatically handle overwriting the message with a user supplied one and id handling. """ def __init__( self, actual: Any, expected: Any, *, id: tuple[Any, ...] = (), **unknown_parameters: Any, ) -> None: self.actual = actual self.expected = expected self.id = id self._unknown_parameters = unknown_parameters @staticmethod def _inputs_not_supported() -> NoReturn: raise UnsupportedInputs @staticmethod def _check_inputs_isinstance(*inputs: Any, cls: Union[type, tuple[type, ...]]): """Checks if all inputs are instances of a given class and raise :class:`UnsupportedInputs` otherwise.""" if not all(isinstance(input, cls) for input in inputs): Pair._inputs_not_supported() def _fail( self, type: type[Exception], msg: str, *, id: tuple[Any, ...] = () ) -> NoReturn: """Raises an :class:`ErrorMeta` from a given exception type and message and the stored id. .. warning:: If you use this before the ``super().__init__(...)`` call in the constructor, you have to pass the ``id`` explicitly. """ raise ErrorMeta(type, msg, id=self.id if not id and hasattr(self, "id") else id) @abc.abstractmethod def compare(self) -> None: """Compares the inputs and raises an :class`ErrorMeta` in case they mismatch.""" def extra_repr(self) -> Sequence[Union[str, tuple[str, Any]]]: """Returns extra information that will be included in the representation. Should be overwritten by all subclasses that use additional options. The representation of the object will only be surfaced in case we encounter an unexpected error and thus should help debug the issue. Can be a sequence of key-value-pairs or attribute names. """ return [] def __repr__(self) -> str: head = f"{type(self).__name__}(" tail = ")" body = [ f" {name}={value!s}," for name, value in [ ("id", self.id), ("actual", self.actual), ("expected", self.expected), *[ (extra, getattr(self, extra)) if isinstance(extra, str) else extra for extra in self.extra_repr() ], ] ] return "\n".join((head, *body, *tail))
Pair
python
tensorflow__tensorflow
tensorflow/python/data/experimental/ops/from_list.py
{ "start": 1027, "end": 4876 }
class ____(dataset_ops.DatasetSource): """A `Dataset` of elements from a list.""" def __init__(self, elements, name=None): if not elements: raise ValueError( "Invalid `elements`. `elements` should not be empty. If you want an" " empty dataset, use `tf.data.Dataset.range(0)`." ) if not isinstance(elements, list): raise ValueError("Invalid `elements`. `elements` must be a list.") elements = [structure.normalize_element(element) for element in elements] type_specs = [ structure.type_spec_from_value(element) for element in elements ] # Check that elements have same nested structure. num_elements = len(elements) for i in range(1, num_elements): nest.assert_same_structure(type_specs[0], type_specs[i]) # Infer elements' supershape. flattened_type_specs = [nest.flatten(type_spec) for type_spec in type_specs] num_tensors_per_element = len(flattened_type_specs[0]) flattened_structure = [None] * num_tensors_per_element for i in range(num_tensors_per_element): flattened_structure[i] = flattened_type_specs[0][i] for j in range(1, num_elements): flattened_structure[i] = flattened_structure[ i].most_specific_common_supertype([flattened_type_specs[j][i]]) if not isinstance(type_specs[0], dataset_ops.DatasetSpec): self._tensors = list( itertools.chain.from_iterable( [nest.flatten(element) for element in elements])) else: self._tensors = [x._variant_tensor for x in elements] self._structure = nest.pack_sequence_as(type_specs[0], flattened_structure) self._name = name variant_tensor = gen_experimental_dataset_ops.list_dataset( self._tensors, output_types=self._flat_types, output_shapes=self._flat_shapes, metadata=self._metadata.SerializeToString()) super(_ListDataset, self).__init__(variant_tensor) @property def element_spec(self): return self._structure @tf_export("data.experimental.from_list") def from_list(elements, name=None): """Creates a `Dataset` comprising the given list of elements. The returned dataset will produce the items in the list one by one. The functionality is identical to `Dataset.from_tensor_slices` when elements are scalars, but different when elements have structure. Consider the following example. >>> dataset = tf.data.experimental.from_list([(1, 'a'), (2, 'b'), (3, 'c')]) >>> [(n.item(), s) for n, s in dataset.as_numpy_iterator()] [(1, b'a'), (2, b'b'), (3, b'c')] To get the same output with `from_tensor_slices`, the data needs to be reorganized: >>> dataset = tf.data.Dataset.from_tensor_slices(([1, 2, 3], ['a', 'b', 'c'])) >>> [(n.item(), s) for n, s in dataset.as_numpy_iterator()] [(1, b'a'), (2, b'b'), (3, b'c')] Unlike `from_tensor_slices`, `from_list` supports non-rectangular input: >>> dataset = tf.data.experimental.from_list([[1], [2, 3]]) >>> list(dataset.as_numpy_iterator()) [array([1], dtype=int32), array([2, 3], dtype=int32)] Achieving the same with `from_tensor_slices` requires the use of ragged tensors. `from_list` can be more performant than `from_tensor_slices` in some cases, since it avoids the need for data slicing each epoch. However, it can also be less performant, because data is stored as many small tensors rather than a few large tensors as in `from_tensor_slices`. The general guidance is to prefer `from_list` from a performance perspective when the number of elements is small (less than 1000). Args: elements: A list of elements whose components have the same nested structure. name: (Optional.) A name for the tf.data operation. Returns: Dataset: A `Dataset` of the `elements`. """ return _ListDataset(elements, name)
_ListDataset
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_index.py
{ "start": 381, "end": 467 }
class ____: def __index__(self): return "ruff" # [invalid-index-return]
Str
python
numpy__numpy
numpy/distutils/fcompiler/intel.py
{ "start": 575, "end": 996 }
class ____(FCompiler): def update_executables(self): f = dummy_fortran_file() self.executables['version_cmd'] = ['<F77>', '-FI', '-V', '-c', f + '.f', '-o', f + '.o'] def runtime_library_dir_option(self, dir): # TODO: could use -Xlinker here, if it's supported assert "," not in dir return '-Wl,-rpath=%s' % dir
BaseIntelFCompiler
python
plotly__plotly.py
plotly/graph_objs/histogram/hoverlabel/_font.py
{ "start": 233, "end": 17153 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "histogram.hoverlabel" _path_str = "histogram.hoverlabel.font" _valid_props = { "color", "colorsrc", "family", "familysrc", "lineposition", "linepositionsrc", "shadow", "shadowsrc", "size", "sizesrc", "style", "stylesrc", "textcase", "textcasesrc", "variant", "variantsrc", "weight", "weightsrc", } @property def color(self): """ The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list - A list or array of any of the above Returns ------- str|numpy.ndarray """ return self["color"] @color.setter def color(self, val): self["color"] = val @property def colorsrc(self): """ Sets the source reference on Chart Studio Cloud for `color`. The 'colorsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["colorsrc"] @colorsrc.setter def colorsrc(self, val): self["colorsrc"] = val @property def family(self): """ HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. The 'family' property is a string and must be specified as: - A non-empty string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["family"] @family.setter def family(self, val): self["family"] = val @property def familysrc(self): """ Sets the source reference on Chart Studio Cloud for `family`. The 'familysrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["familysrc"] @familysrc.setter def familysrc(self, val): self["familysrc"] = val @property def lineposition(self): """ Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. The 'lineposition' property is a flaglist and may be specified as a string containing: - Any combination of ['under', 'over', 'through'] joined with '+' characters (e.g. 'under+over') OR exactly one of ['none'] (e.g. 'none') - A list or array of the above Returns ------- Any|numpy.ndarray """ return self["lineposition"] @lineposition.setter def lineposition(self, val): self["lineposition"] = val @property def linepositionsrc(self): """ Sets the source reference on Chart Studio Cloud for `lineposition`. The 'linepositionsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["linepositionsrc"] @linepositionsrc.setter def linepositionsrc(self, val): self["linepositionsrc"] = val @property def shadow(self): """ Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow for additional options. The 'shadow' property is a string and must be specified as: - A string - A number that will be converted to a string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["shadow"] @shadow.setter def shadow(self, val): self["shadow"] = val @property def shadowsrc(self): """ Sets the source reference on Chart Studio Cloud for `shadow`. The 'shadowsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["shadowsrc"] @shadowsrc.setter def shadowsrc(self, val): self["shadowsrc"] = val @property def size(self): """ The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|float|numpy.ndarray """ return self["size"] @size.setter def size(self, val): self["size"] = val @property def sizesrc(self): """ Sets the source reference on Chart Studio Cloud for `size`. The 'sizesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["sizesrc"] @sizesrc.setter def sizesrc(self, val): self["sizesrc"] = val @property def style(self): """ Sets whether a font should be styled with a normal or italic face from its family. The 'style' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'italic'] - A tuple, list, or one-dimensional numpy array of the above Returns ------- Any|numpy.ndarray """ return self["style"] @style.setter def style(self, val): self["style"] = val @property def stylesrc(self): """ Sets the source reference on Chart Studio Cloud for `style`. The 'stylesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["stylesrc"] @stylesrc.setter def stylesrc(self, val): self["stylesrc"] = val @property def textcase(self): """ Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. The 'textcase' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'word caps', 'upper', 'lower'] - A tuple, list, or one-dimensional numpy array of the above Returns ------- Any|numpy.ndarray """ return self["textcase"] @textcase.setter def textcase(self, val): self["textcase"] = val @property def textcasesrc(self): """ Sets the source reference on Chart Studio Cloud for `textcase`. The 'textcasesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["textcasesrc"] @textcasesrc.setter def textcasesrc(self, val): self["textcasesrc"] = val @property def variant(self): """ Sets the variant of the font. The 'variant' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'small-caps', 'all-small-caps', 'all-petite-caps', 'petite-caps', 'unicase'] - A tuple, list, or one-dimensional numpy array of the above Returns ------- Any|numpy.ndarray """ return self["variant"] @variant.setter def variant(self, val): self["variant"] = val @property def variantsrc(self): """ Sets the source reference on Chart Studio Cloud for `variant`. The 'variantsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["variantsrc"] @variantsrc.setter def variantsrc(self, val): self["variantsrc"] = val @property def weight(self): """ Sets the weight (or boldness) of the font. The 'weight' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [1, 1000] OR exactly one of ['normal', 'bold'] (e.g. 'bold') - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|numpy.ndarray """ return self["weight"] @weight.setter def weight(self, val): self["weight"] = val @property def weightsrc(self): """ Sets the source reference on Chart Studio Cloud for `weight`. The 'weightsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["weightsrc"] @weightsrc.setter def weightsrc(self, val): self["weightsrc"] = val @property def _prop_descriptions(self): return """\ color colorsrc Sets the source reference on Chart Studio Cloud for `color`. family HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. familysrc Sets the source reference on Chart Studio Cloud for `family`. lineposition Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. linepositionsrc Sets the source reference on Chart Studio Cloud for `lineposition`. shadow Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en- US/docs/Web/CSS/text-shadow for additional options. shadowsrc Sets the source reference on Chart Studio Cloud for `shadow`. size sizesrc Sets the source reference on Chart Studio Cloud for `size`. style Sets whether a font should be styled with a normal or italic face from its family. stylesrc Sets the source reference on Chart Studio Cloud for `style`. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. textcasesrc Sets the source reference on Chart Studio Cloud for `textcase`. variant Sets the variant of the font. variantsrc Sets the source reference on Chart Studio Cloud for `variant`. weight Sets the weight (or boldness) of the font. weightsrc Sets the source reference on Chart Studio Cloud for `weight`. """ def __init__( self, arg=None, color=None, colorsrc=None, family=None, familysrc=None, lineposition=None, linepositionsrc=None, shadow=None, shadowsrc=None, size=None, sizesrc=None, style=None, stylesrc=None, textcase=None, textcasesrc=None, variant=None, variantsrc=None, weight=None, weightsrc=None, **kwargs, ): """ Construct a new Font object Sets the font used in hover labels. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.histogram.hoverlabel.Font` color colorsrc Sets the source reference on Chart Studio Cloud for `color`. family HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. familysrc Sets the source reference on Chart Studio Cloud for `family`. lineposition Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. linepositionsrc Sets the source reference on Chart Studio Cloud for `lineposition`. shadow Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en- US/docs/Web/CSS/text-shadow for additional options. shadowsrc Sets the source reference on Chart Studio Cloud for `shadow`. size sizesrc Sets the source reference on Chart Studio Cloud for `size`. style Sets whether a font should be styled with a normal or italic face from its family. stylesrc Sets the source reference on Chart Studio Cloud for `style`. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. textcasesrc Sets the source reference on Chart Studio Cloud for `textcase`. variant Sets the variant of the font. variantsrc Sets the source reference on Chart Studio Cloud for `variant`. weight Sets the weight (or boldness) of the font. weightsrc Sets the source reference on Chart Studio Cloud for `weight`. Returns ------- Font """ super().__init__("font") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.histogram.hoverlabel.Font constructor must be a dict or an instance of :class:`plotly.graph_objs.histogram.hoverlabel.Font`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("color", arg, color) self._set_property("colorsrc", arg, colorsrc) self._set_property("family", arg, family) self._set_property("familysrc", arg, familysrc) self._set_property("lineposition", arg, lineposition) self._set_property("linepositionsrc", arg, linepositionsrc) self._set_property("shadow", arg, shadow) self._set_property("shadowsrc", arg, shadowsrc) self._set_property("size", arg, size) self._set_property("sizesrc", arg, sizesrc) self._set_property("style", arg, style) self._set_property("stylesrc", arg, stylesrc) self._set_property("textcase", arg, textcase) self._set_property("textcasesrc", arg, textcasesrc) self._set_property("variant", arg, variant) self._set_property("variantsrc", arg, variantsrc) self._set_property("weight", arg, weight) self._set_property("weightsrc", arg, weightsrc) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Font
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI036.py
{ "start": 570, "end": 846 }
class ____: def __exit__(self, __typ: typing.Type[BaseException] | None, exc: BaseException | None, *args: object) -> None: ... async def __aexit__(self, typ: typing_extensions.Type[BaseException] | None, __exc: BaseException | None, *args: object) -> None: ...
GoodThree
python
ray-project__ray
rllib/policy/policy.py
{ "start": 2024, "end": 5860 }
class ____: """A policy spec used in the "config.multiagent.policies" specification dict. As values (keys are the policy IDs (str)). E.g.: config: multiagent: policies: { "pol1": PolicySpec(None, Box, Discrete(2), {"lr": 0.0001}), "pol2": PolicySpec(config={"lr": 0.001}), } """ def __init__( self, policy_class=None, observation_space=None, action_space=None, config=None ): # If None, use the Algorithm's default policy class stored under # `Algorithm._policy_class`. self.policy_class = policy_class # If None, use the env's observation space. If None and there is no Env # (e.g. offline RL), an error is thrown. self.observation_space = observation_space # If None, use the env's action space. If None and there is no Env # (e.g. offline RL), an error is thrown. self.action_space = action_space # Overrides defined keys in the main Algorithm config. # If None, use {}. self.config = config def __eq__(self, other: "PolicySpec"): return ( self.policy_class == other.policy_class and self.observation_space == other.observation_space and self.action_space == other.action_space and self.config == other.config ) def get_state(self) -> Dict[str, Any]: """Returns the state of a `PolicyDict` as a dict.""" return ( self.policy_class, self.observation_space, self.action_space, self.config, ) @classmethod def from_state(cls, state: Dict[str, Any]) -> "PolicySpec": """Builds a `PolicySpec` from a state.""" policy_spec = PolicySpec() policy_spec.__dict__.update(state) return policy_spec def serialize(self) -> Dict: from ray.rllib.algorithms.registry import get_policy_class_name # Try to figure out a durable name for this policy. cls = get_policy_class_name(self.policy_class) if cls is None: logger.warning( f"Can not figure out a durable policy name for {self.policy_class}. " f"You are probably trying to checkpoint a custom policy. " f"Raw policy class may cause problems when the checkpoint needs to " "be loaded in the future. To fix this, make sure you add your " "custom policy in rllib.algorithms.registry.POLICIES." ) cls = self.policy_class return { "policy_class": cls, "observation_space": space_to_dict(self.observation_space), "action_space": space_to_dict(self.action_space), # TODO(jungong) : try making the config dict durable by maybe # getting rid of all the fields that are not JSON serializable. "config": self.config, } @classmethod def deserialize(cls, spec: Dict) -> "PolicySpec": if isinstance(spec["policy_class"], str): # Try to recover the actual policy class from durable name. from ray.rllib.algorithms.registry import get_policy_class policy_class = get_policy_class(spec["policy_class"]) elif isinstance(spec["policy_class"], type): # Policy spec is already a class type. Simply use it. policy_class = spec["policy_class"] else: raise AttributeError(f"Unknown policy class spec {spec['policy_class']}") return cls( policy_class=policy_class, observation_space=space_from_dict(spec["observation_space"]), action_space=space_from_dict(spec["action_space"]), config=spec["config"], ) @OldAPIStack
PolicySpec
python
getsentry__sentry
src/sentry/releases/endpoints/project_release_files.py
{ "start": 2014, "end": 6907 }
class ____(BaseEndpointMixin): def get_releasefiles(self, request: Request, release, organization_id): query = request.GET.getlist("query") checksums = request.GET.getlist("checksum") data_sources: list[QuerySet[ReleaseFile] | ArtifactSource] = [] # Exclude files which are also present in archive: file_list = ReleaseFile.public_objects.filter(release_id=release.id).exclude( artifact_count=0 ) file_list = file_list.select_related("file").order_by("name") if query: condition = Q(name__icontains=query[0]) for name in query[1:]: condition |= Q(name__icontains=name) file_list = file_list.filter(condition) if checksums: condition = Q(file__checksum__in=checksums) file_list = file_list.filter(condition) data_sources.append(file_list.order_by("name")) # Get contents of release archive as well: dists = Distribution.objects.filter(organization_id=organization_id, release=release) for dist in list(dists) + [None]: try: # Only Read from artifact index if it has a positive artifact count artifact_index = read_artifact_index(release, dist, artifact_count__gt=0) except Exception: logger.exception("Failed to read artifact index") artifact_index = None if artifact_index is not None: files = artifact_index.get("files", {}) source = ArtifactSource(dist, files, query, checksums) data_sources.append(source) def on_results(release_files: list[ReleaseFile]): # this should filter out all the "pseudo-ReleaseFile"s maybe_renew_releasefiles([rf for rf in release_files if rf.id]) return serialize(load_dist(release_files), request.user) # NOTE: Returned release files are ordered by name within their block, # (i.e. per index file), but not overall return self.paginate( request=request, sources=data_sources, paginator_cls=ChainPaginator, max_offset=MAX_RELEASE_FILES_OFFSET, on_results=on_results, ) @staticmethod def post_releasefile(request, release, logger): if "file" not in request.data: return Response({"detail": "Missing uploaded file"}, status=400) fileobj = request.data["file"] full_name = request.data.get("name", fileobj.name) if not full_name or full_name == "file": return Response({"detail": "File name must be specified"}, status=400) name = full_name.rsplit("/", 1)[-1] if _filename_re.search(name): return Response( {"detail": "File name must not contain special whitespace characters"}, status=400 ) headers = {"Content-Type": fileobj.content_type} for headerval in request.data.getlist("header") or (): try: k, v = headerval.split(":", 1) except ValueError: return Response({"detail": "header value was not formatted correctly"}, status=400) else: if _filename_re.search(v): return Response( {"detail": "header value must not contain special whitespace characters"}, status=400, ) headers[k] = v.strip() dist_name = request.data.get("dist") dist = None if dist_name: dist = release.add_dist(dist_name) # Quickly check for the presence of this file before continuing with # the costly file upload process. if ReleaseFile.objects.filter( organization_id=release.organization_id, release_id=release.id, name=full_name, dist_id=dist.id if dist else dist, ).exists(): return Response({"detail": ERR_FILE_EXISTS}, status=409) file = File.objects.create(name=name, type="release.file", headers=headers) file.putfile(fileobj, logger=logger) metrics.incr("sourcemaps.upload.single_release_file") try: with atomic_transaction(using=router.db_for_write(ReleaseFile)): releasefile = ReleaseFile.objects.create( organization_id=release.organization_id, release_id=release.id, file=file, name=full_name, dist_id=dist.id if dist else dist, ) except IntegrityError: file.delete() return Response({"detail": ERR_FILE_EXISTS}, status=409) return Response(serialize(releasefile, request.user), status=201)
ReleaseFilesMixin
python
Textualize__textual
tests/option_list/test_option_list_movement.py
{ "start": 6019, "end": 7187 }
class ____(App[None]): def compose(self) -> ComposeResult: self.highlighted = [] yield OptionList( Option("0", disabled=True), Option("1"), Option("2", disabled=True), Option("3", disabled=True), Option("4"), Option("5"), Option("6", disabled=True), Option("7"), Option("8", disabled=True), ) def _on_option_list_option_highlighted( self, message: OptionList.OptionHighlighted ) -> None: self.highlighted.append(str(message.option.prompt)) async def test_keyboard_navigation_with_disabled_options() -> None: """Regression test for https://github.com/Textualize/textual/issues/3881.""" app = OptionListDisabledOptionsApp() async with app.run_test() as pilot: for _ in range(5): await pilot.press("down") for _ in range(5): await pilot.press("up") assert app.highlighted == [ "1", "4", "5", "7", "1", "4", "1", "7", "5", "4", "1", ]
OptionListDisabledOptionsApp
python
pandas-dev__pandas
pandas/tests/indexes/test_base.py
{ "start": 54284, "end": 61114 }
class ____: @pytest.mark.parametrize( "data, names, expected", [ ([[1, 2, 4]], None, Index([1, 2, 4])), ([[1, 2, 4]], ["name"], Index([1, 2, 4], name="name")), ([[1, 2, 3]], None, RangeIndex(1, 4)), ([[1, 2, 3]], ["name"], RangeIndex(1, 4, name="name")), ( [["a", "a"], ["c", "d"]], None, MultiIndex([["a"], ["c", "d"]], [[0, 0], [0, 1]]), ), ( [["a", "a"], ["c", "d"]], ["L1", "L2"], MultiIndex([["a"], ["c", "d"]], [[0, 0], [0, 1]], names=["L1", "L2"]), ), ], ) def test_ensure_index_from_sequences(self, data, names, expected): result = ensure_index_from_sequences(data, names) tm.assert_index_equal(result, expected, exact=True) def test_ensure_index_mixed_closed_intervals(self): # GH27172 intervals = [ pd.Interval(0, 1, closed="left"), pd.Interval(1, 2, closed="right"), pd.Interval(2, 3, closed="neither"), pd.Interval(3, 4, closed="both"), ] result = ensure_index(intervals) expected = Index(intervals, dtype=object) tm.assert_index_equal(result, expected) def test_ensure_index_uint64(self): # with both 0 and a large-uint64, np.array will infer to float64 # https://github.com/numpy/numpy/issues/19146 # but a more accurate choice would be uint64 values = [0, np.iinfo(np.uint64).max] result = ensure_index(values) assert list(result) == values expected = Index(values, dtype="uint64") tm.assert_index_equal(result, expected) def test_get_combined_index(self): result = _get_combined_index([]) expected = RangeIndex(0) tm.assert_index_equal(result, expected) @pytest.mark.parametrize( "opname", [ "eq", "ne", "le", "lt", "ge", "gt", "add", "radd", "sub", "rsub", "mul", "rmul", "truediv", "rtruediv", "floordiv", "rfloordiv", "pow", "rpow", "mod", "divmod", ], ) def test_generated_op_names(opname, index): opname = f"__{opname}__" method = getattr(index, opname) assert method.__name__ == opname @pytest.mark.parametrize( "klass", [ partial(CategoricalIndex, data=[1]), partial(DatetimeIndex, data=["2020-01-01"]), partial(PeriodIndex, data=["2020-01-01"]), partial(TimedeltaIndex, data=["1 day"]), partial(RangeIndex, start=range(1)), partial(IntervalIndex, data=[pd.Interval(0, 1)]), partial(Index, data=["a"], dtype=object), partial(MultiIndex, levels=[1], codes=[0]), ], ) def test_index_subclass_constructor_wrong_kwargs(klass): # GH #19348 with pytest.raises(TypeError, match="unexpected keyword argument"): klass(foo="bar") def test_deprecated_fastpath(): msg = "[Uu]nexpected keyword argument" with pytest.raises(TypeError, match=msg): Index(np.array(["a", "b"], dtype=object), name="test", fastpath=True) with pytest.raises(TypeError, match=msg): Index(np.array([1, 2, 3], dtype="int64"), name="test", fastpath=True) with pytest.raises(TypeError, match=msg): RangeIndex(0, 5, 2, name="test", fastpath=True) with pytest.raises(TypeError, match=msg): CategoricalIndex(["a", "b", "c"], name="test", fastpath=True) def test_shape_of_invalid_index(): # Pre-2.0, it was possible to create "invalid" index objects backed by # a multi-dimensional array (see https://github.com/pandas-dev/pandas/issues/27125 # about this). However, as long as this is not solved in general,this test ensures # that the returned shape is consistent with this underlying array for # compat with matplotlib (see https://github.com/pandas-dev/pandas/issues/27775) idx = Index([0, 1, 2, 3]) with pytest.raises(ValueError, match="Multi-dimensional indexing"): # GH#30588 multi-dimensional indexing deprecated idx[:, None] @pytest.mark.parametrize("dtype", [None, np.int64, np.uint64, np.float64]) def test_validate_1d_input(dtype): # GH#27125 check that we do not have >1-dimensional input msg = "Index data must be 1-dimensional" arr = np.arange(8).reshape(2, 2, 2) with pytest.raises(ValueError, match=msg): Index(arr, dtype=dtype) df = DataFrame(arr.reshape(4, 2)) with pytest.raises(ValueError, match=msg): Index(df, dtype=dtype) # GH#13601 trying to assign a multi-dimensional array to an index is not allowed ser = Series(0, range(4)) with pytest.raises(ValueError, match=msg): ser.index = np.array([[2, 3]] * 4, dtype=dtype) @pytest.mark.parametrize( "klass, extra_kwargs", [ [Index, {}], *[[lambda x: Index(x, dtype=dtyp), {}] for dtyp in tm.ALL_REAL_NUMPY_DTYPES], [DatetimeIndex, {}], [TimedeltaIndex, {}], [PeriodIndex, {"freq": "Y"}], ], ) def test_construct_from_memoryview(klass, extra_kwargs): # GH 13120 result = klass(memoryview(np.arange(2000, 2005)), **extra_kwargs) expected = klass(list(range(2000, 2005)), **extra_kwargs) tm.assert_index_equal(result, expected, exact=True) @pytest.mark.parametrize("op", [operator.lt, operator.gt]) def test_nan_comparison_same_object(op): # GH#47105 idx = Index([np.nan]) expected = np.array([False]) result = op(idx, idx) tm.assert_numpy_array_equal(result, expected) result = op(idx, idx.copy()) tm.assert_numpy_array_equal(result, expected) @td.skip_if_no("pyarrow") def test_is_monotonic_pyarrow_list_type(): # GH 57333 import pyarrow as pa idx = Index([[1], [2, 3]], dtype=pd.ArrowDtype(pa.list_(pa.int64()))) assert not idx.is_monotonic_increasing assert not idx.is_monotonic_decreasing def test_index_equals_different_string_dtype(string_dtype_no_object): # GH 61099 idx_obj = Index(["a", "b", "c"]) idx_str = Index(["a", "b", "c"], dtype=string_dtype_no_object) assert idx_obj.equals(idx_str) assert idx_str.equals(idx_obj) def test_index_comparison_different_string_dtype(string_dtype_no_object): # GH 61099 idx = Index(["a", "b", "c"]) s_obj = Series([1, 2, 3], index=idx) s_str = Series([4, 5, 6], index=idx.astype(string_dtype_no_object)) expected = Series([True, True, True], index=["a", "b", "c"]) result = s_obj < s_str assert_series_equal(result, expected) result = s_str > s_obj expected.index = idx.astype(string_dtype_no_object) assert_series_equal(result, expected)
TestIndexUtils
python
matplotlib__matplotlib
galleries/examples/misc/custom_projection.py
{ "start": 13313, "end": 16204 }
class ____(GeoAxes): """ A custom class for the Aitoff-Hammer projection, an equal-area map projection. https://en.wikipedia.org/wiki/Hammer_projection """ # The projection must specify a name. This will be used by the # user to select the projection, # i.e. ``subplot(projection='custom_hammer')``. name = 'custom_hammer' class HammerTransform(Transform): """The base Hammer transform.""" input_dims = output_dims = 2 def __init__(self, resolution): """ Create a new Hammer transform. Resolution is the number of steps to interpolate between each input line segment to approximate its path in curved Hammer space. """ Transform.__init__(self) self._resolution = resolution def transform_non_affine(self, ll): longitude, latitude = ll.T # Pre-compute some values half_long = longitude / 2 cos_latitude = np.cos(latitude) sqrt2 = np.sqrt(2) alpha = np.sqrt(1 + cos_latitude * np.cos(half_long)) x = (2 * sqrt2) * (cos_latitude * np.sin(half_long)) / alpha y = (sqrt2 * np.sin(latitude)) / alpha return np.column_stack([x, y]) def transform_path_non_affine(self, path): # vertices = path.vertices ipath = path.interpolated(self._resolution) return Path(self.transform(ipath.vertices), ipath.codes) def inverted(self): return HammerAxes.InvertedHammerTransform(self._resolution) class InvertedHammerTransform(Transform): input_dims = output_dims = 2 def __init__(self, resolution): Transform.__init__(self) self._resolution = resolution def transform_non_affine(self, xy): x, y = xy.T z = np.sqrt(1 - (x / 4) ** 2 - (y / 2) ** 2) longitude = 2 * np.arctan((z * x) / (2 * (2 * z ** 2 - 1))) latitude = np.arcsin(y*z) return np.column_stack([longitude, latitude]) def inverted(self): return HammerAxes.HammerTransform(self._resolution) def __init__(self, *args, **kwargs): self._longitude_cap = np.pi / 2.0 super().__init__(*args, **kwargs) self.set_aspect(0.5, adjustable='box', anchor='C') self.clear() def _get_core_transform(self, resolution): return self.HammerTransform(resolution) # Now register the projection with Matplotlib so the user can select it. register_projection(HammerAxes) if __name__ == '__main__': import matplotlib.pyplot as plt # Now make a simple example using the custom projection. fig, ax = plt.subplots(subplot_kw={'projection': 'custom_hammer'}) ax.plot([-1, 1, 1], [-1, -1, 1], "o-") ax.grid() plt.show()
HammerAxes
python
catalyst-team__catalyst
catalyst/metrics/_segmentation.py
{ "start": 9002, "end": 13515 }
class ____(RegionBasedMetric): """ IoU Metric, iou score = intersection / union = tp / (tp + fp + fn). Args: class_dim: indicates class dimension (K) for ``outputs`` and ``targets`` tensors (default = 1) weights: class weights class_names: class names threshold: threshold for outputs binarization eps: epsilon to avoid zero division compute_on_call: Computes and returns metric value during metric call. Used for per-batch logging. default: True compute_per_class_metrics: boolean flag to compute per-class metrics (default: SETTINGS.compute_per_class_metrics or False). prefix: metric prefix suffix: metric suffix Examples: .. code-block:: python import torch from catalyst import metrics outputs = torch.tensor([[[[0.8, 0.1, 0], [0, 0.4, 0.3], [0, 0, 1]]]]) targets = torch.tensor([[[[1.0, 0, 0], [0, 1, 0], [1, 1, 0]]]]) metric = metrics.IOUMetric() metric.reset() metric.compute() # per_class, micro, macro, weighted # ([tensor(0.2222)], tensor(0.2222), tensor(0.2222), None) metric.update_key_value(outputs, targets) metric.compute_key_value() # { # 'iou': tensor(0.2222), # 'iou/_macro': tensor(0.2222), # 'iou/_micro': tensor(0.2222), # 'iou/class_00': tensor(0.2222), # } .. code-block:: python import os import torch from torch import nn from torch.utils.data import DataLoader from catalyst import dl from catalyst.contrib import IoULoss, MNIST model = nn.Sequential( nn.Conv2d(1, 1, 3, 1, 1), nn.ReLU(), nn.Conv2d(1, 1, 3, 1, 1), nn.Sigmoid(), ) criterion = IoULoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.02) loaders = { "train": DataLoader( MNIST(os.getcwd(), train=True), batch_size=32 ), "valid": DataLoader( MNIST(os.getcwd(), train=False), batch_size=32 ), } class CustomRunner(dl.SupervisedRunner): def handle_batch(self, batch): x = batch[self._input_key] x_noise = (x + torch.rand_like(x)).clamp_(0, 1) x_ = self.model(x_noise) self.batch = { self._input_key: x, self._output_key: x_, self._target_key: x } runner = CustomRunner( input_key="features", output_key="scores", target_key="targets", loss_key="loss" ) # model training runner.train( model=model, criterion=criterion, optimizer=optimizer, loaders=loaders, num_epochs=1, callbacks=[ dl.IOUCallback(input_key="scores", target_key="targets"), dl.DiceCallback(input_key="scores", target_key="targets"), dl.TrevskyCallback(input_key="scores", target_key="targets", alpha=0.2), ], logdir="./logdir", valid_loader="valid", valid_metric="loss", minimize_valid_metric=True, verbose=True, ) .. note:: Please follow the `minimal examples`_ sections for more use cases. .. _`minimal examples`: https://github.com/catalyst-team/catalyst#minimal-examples # noqa: E501, W505 """ def __init__( self, class_dim: int = 1, weights: Optional[List[float]] = None, class_names: Optional[List[str]] = None, threshold: Optional[float] = None, eps: float = 1e-7, compute_on_call: bool = True, compute_per_class_metrics: bool = SETTINGS.compute_per_class_metrics, prefix: Optional[str] = None, suffix: Optional[str] = None, ): """Init.""" metric_fn = partial(_iou, eps=eps) super().__init__( metric_fn=metric_fn, metric_name="iou", compute_on_call=compute_on_call, compute_per_class_metrics=compute_per_class_metrics, prefix=prefix, suffix=suffix, class_dim=class_dim, weights=weights, class_names=class_names, threshold=threshold, )
IOUMetric
python
great-expectations__great_expectations
tests/datasource/fluent/test_snowflake_datasource.py
{ "start": 8452, "end": 39765 }
class ____: @pytest.mark.parametrize( "value", [ "orgname.account_name", "orgname-account_name", "abc12345.us-east-1.aws", "xy12345.us-gov-west-1.aws", "xy12345.europe-west4.gcp", "xy12345.central-us.azure", ], ) def test_str_and_repr_methods(self, value: str): account_identifier: AccountIdentifier = pydantic.parse_obj_as(AccountIdentifier, value) assert str(account_identifier) == value assert repr(account_identifier) == f"AccountIdentifier({value!r})" @pytest.mark.parametrize("account_name", ["account_name", "account-name"]) def test_fmt1_parse(self, account_name: str): orgname = "orgname" value = f"{orgname}-{account_name}" print(f"{value=}") account_identifier = pydantic.parse_obj_as(AccountIdentifier, value) assert account_identifier.match assert account_identifier.account_name == account_name assert account_identifier.orgname == orgname assert account_identifier.as_tuple() == (orgname, account_name) @pytest.mark.parametrize( "value", [ "abc12345.us-east-1.aws", "xy12345.us-gov-west-1.aws", "xy12345.europe-west4.gcp", "xy12345.central-us.azure", ], ) def test_fmt2_parse(self, value: str): """ The cloud portion is technically optional if the the provider is AWS, but expecting greatly simplifies our parsing logic. """ print(f"{value=}") locator, _, _remainder = value.partition(".") cloud_region_id, _, cloud_service = _remainder.partition(".") account_identifier = pydantic.parse_obj_as(AccountIdentifier, value) assert account_identifier.match assert account_identifier.account_locator == locator assert account_identifier.region == (cloud_region_id or None) assert account_identifier.cloud == (cloud_service or None) assert account_identifier.as_tuple() == ( locator, cloud_region_id, cloud_service, ) @pytest.mark.parametrize( "value", [ "foobar", "orgname.account-name", "orgname.account_name", "my_account.us-east-1", "xy12345.us-gov-west-1.aws.", "xy12345.europe-west4.gcp.bar", "xy12345.us-east-1.nope", "xy12345.", "xy12345.central-us.bazar", "xy12345_us-gov-west-1_aws", "xy12345_europe-west4_gcp", "xy12345_central-us_azure", ], ) def test_invalid_formats(self, value: str): """ Test that an invalid format that does not match but can still be stringified as the original value. """ print(f"{value=}") account_identifier = pydantic.parse_obj_as(AccountIdentifier, value) assert not account_identifier.match assert str(account_identifier) == value @pytest.mark.unit def test_snowflake_dsn(): dsn = pydantic.parse_obj_as( SnowflakeDsn, "snowflake://my_user:password@my_account/my_db/my_schema?role=my_role&warehouse=my_wh", ) assert dsn.user == "my_user" assert dsn.password == "password" assert dsn.account_identifier == "my_account" assert dsn.database == "my_db" assert dsn.schema_ == "my_schema" assert dsn.role == "my_role" assert dsn.warehouse == "my_wh" @pytest.mark.snowflake # TODO: make this a unit test @pytest.mark.parametrize( "config_kwargs", [ *VALID_DS_CONFIG_PARAMS, param( { "user": "my_user", "password": "password", "account": "my_account", "schema": "s_public", "database": "d_public", "role": "my_role", "warehouse": "my_wh", }, id="old config format - top level keys", ), ], ) def test_valid_config( empty_file_context: AbstractDataContext, seed_env_vars: None, config_kwargs: dict, param_id: str, ): my_sf_ds_1 = SnowflakeDatasource(name=f"my_sf {param_id}", **config_kwargs) assert my_sf_ds_1 my_sf_ds_1._data_context = empty_file_context # attach to enable config substitution sql_engine = my_sf_ds_1.get_engine() assert isinstance(sql_engine, sa.engine.Engine) exec_engine = my_sf_ds_1.get_execution_engine() assert isinstance(exec_engine, SqlAlchemyExecutionEngine) @pytest.mark.unit @pytest.mark.parametrize( ["connection_string", "expected_errors"], [ pytest.param( "${MY_CONFIG_VAR}", [ { "loc": ("connection_string", "__root__"), "msg": "Only password, user may use config substitution;" " 'domain' substitution not allowed", "type": "value_error", }, { "loc": ("__root__",), "msg": "Must provide either a connection string or a combination of account, " "user, password, database, schema, warehouse, role as keyword args or " "a combination of account, user, database, schema, warehouse, role, " "private_key as keyword args.", "type": "value_error", }, ], id="illegal config substitution - full connection string", ), pytest.param( "snowflake://my_user:password@${MY_CONFIG_VAR}/db/schema", [ { "loc": ("connection_string", "__root__"), "msg": "Only password, user may use config substitution;" " 'domain' substitution not allowed", "type": "value_error", }, { "loc": ("__root__",), "msg": "Must provide either a connection string or a combination of account, " "user, password, database, schema, warehouse, role as keyword args or " "a combination of account, user, database, schema, warehouse, role, " "private_key as keyword args.", "type": "value_error", }, ], id="illegal config substitution - account (domain)", ), pytest.param( "snowflake://my_user:password@account/${MY_CONFIG_VAR}/schema", [ { "loc": ("connection_string", "__root__"), "msg": "Only password, user may use config substitution;" " 'path' substitution not allowed", "type": "value_error", }, { "loc": ("__root__",), "msg": "Must provide either a connection string or a combination of account, " "user, password, database, schema, warehouse, role as keyword args or " "a combination of account, user, database, schema, warehouse, role, " "private_key as keyword args.", "type": "value_error", }, ], id="illegal config substitution - database (path)", ), pytest.param( "snowflake://my_user:password@account/db/${MY_CONFIG_VAR}", [ { "loc": ("connection_string", "__root__"), "msg": "Only password, user may use config substitution;" " 'path' substitution not allowed", "type": "value_error", }, { "loc": ("__root__",), "msg": "Must provide either a connection string or a combination of account, " "user, password, database, schema, warehouse, role as keyword args or " "a combination of account, user, database, schema, warehouse, role, " "private_key as keyword args.", "type": "value_error", }, ], id="illegal config substitution - schema (path)", ), pytest.param( "snowflake://my_user:password@my_account", [ { "loc": ("connection_string",), "msg": "value is not a valid dict", "type": "type_error.dict", }, { "loc": ("connection_string",), "msg": "value is not a valid dict", "type": "type_error.dict", }, { "loc": ("connection_string",), "msg": "ConfigStr - contains no config template strings in the format " "'${MY_CONFIG_VAR}' or '$MY_CONFIG_VAR'", "type": "value_error", }, { "loc": ("connection_string",), "msg": "URL path missing database/schema", "type": "value_error.url.path", }, { "loc": ("__root__",), "msg": "Must provide either a connection string or a combination of account, " "user, password, database, schema, warehouse, role as keyword args or " "a combination of account, user, database, schema, warehouse, role, " "private_key as keyword args.", "type": "value_error", }, ], id="missing path", ), pytest.param( "snowflake://my_user:password@my_account//", [ { "loc": ("connection_string",), "msg": "value is not a valid dict", "type": "type_error.dict", }, { "loc": ("connection_string",), "msg": "value is not a valid dict", "type": "type_error.dict", }, { "loc": ("connection_string",), "msg": "ConfigStr - contains no config template strings in the format " "'${MY_CONFIG_VAR}' or '$MY_CONFIG_VAR'", "type": "value_error", }, { "ctx": {"msg": "missing database"}, "loc": ("connection_string",), "msg": "URL path missing database/schema", "type": "value_error.url.path", }, { "loc": ("__root__",), "msg": "Must provide either a connection string or a combination of account, " "user, password, database, schema, warehouse, role as keyword args or " "a combination of account, user, database, schema, warehouse, role, " "private_key as keyword args.", "type": "value_error", }, ], id="missing database + schema", ), pytest.param( "snowflake://my_user:password@my_account/my_db", [ { "loc": ("connection_string",), "msg": "value is not a valid dict", "type": "type_error.dict", }, { "loc": ("connection_string",), "msg": "value is not a valid dict", "type": "type_error.dict", }, { "loc": ("connection_string",), "msg": "ConfigStr - contains no config template strings in the format " "'${MY_CONFIG_VAR}' or '$MY_CONFIG_VAR'", "type": "value_error", }, { "loc": ("connection_string",), "msg": "URL path missing database/schema", "type": "value_error.url.path", }, { "loc": ("__root__",), "msg": "Must provide either a connection string or a combination of account, " "user, password, database, schema, warehouse, role as keyword args or " "a combination of account, user, database, schema, warehouse, role, " "private_key as keyword args.", "type": "value_error", }, ], id="missing schema", ), pytest.param( "snowflake://my_user:password@my_account/my_db/", [ { "loc": ("connection_string",), "msg": "value is not a valid dict", "type": "type_error.dict", }, { "loc": ("connection_string",), "msg": "value is not a valid dict", "type": "type_error.dict", }, { "loc": ("connection_string",), "msg": "ConfigStr - contains no config template strings in the format " "'${MY_CONFIG_VAR}' or '$MY_CONFIG_VAR'", "type": "value_error", }, { "ctx": {"msg": "missing schema"}, "loc": ("connection_string",), "msg": "URL path missing database/schema", "type": "value_error.url.path", }, { "loc": ("__root__",), "msg": "Must provide either a connection string or a combination of account, " "user, password, database, schema, warehouse, role as keyword args or " "a combination of account, user, database, schema, warehouse, role, " "private_key as keyword args.", "type": "value_error", }, ], id="missing schema 2", ), pytest.param( "snowflake://my_user:password@my_account//my_schema", [ { "loc": ("connection_string",), "msg": "value is not a valid dict", "type": "type_error.dict", }, { "loc": ("connection_string",), "msg": "value is not a valid dict", "type": "type_error.dict", }, { "loc": ("connection_string",), "msg": "ConfigStr - contains no config template strings in the format " "'${MY_CONFIG_VAR}' or '$MY_CONFIG_VAR'", "type": "value_error", }, { "ctx": {"msg": "missing database"}, "loc": ("connection_string",), "msg": "URL path missing database/schema", "type": "value_error.url.path", }, { "loc": ("__root__",), "msg": "Must provide either a connection string or a combination of account, " "user, password, database, schema, warehouse, role as keyword args or " "a combination of account, user, database, schema, warehouse, role, " "private_key as keyword args.", "type": "value_error", }, ], id="missing database", ), ], ) def test_missing_required_params( connection_string: str, expected_errors: list[dict], # TODO: use pydantic error dict ): with pytest.raises(pydantic.ValidationError) as exc_info: ds = SnowflakeDatasource( name="my_sf_ds", connection_string=connection_string, ) print(f"{ds!r}") print(f"\n\tErrors:\n{pf(exc_info.value.errors())}") assert exc_info.value.errors() == expected_errors @pytest.mark.unit @pytest.mark.parametrize( "connection_string, expected_errors", [ pytest.param( "user_login_name:password@account_identifier/db/schema?role=my_role&warehouse=my_wh", [ { "loc": ("connection_string",), "msg": "value is not a valid dict", "type": "type_error.dict", }, { "loc": ("connection_string",), "msg": "value is not a valid dict", "type": "type_error.dict", }, { "loc": ("connection_string",), "msg": "ConfigStr - contains no config template strings in the format" " '${MY_CONFIG_VAR}' or '$MY_CONFIG_VAR'", "type": "value_error", }, { "loc": ("connection_string",), "msg": "invalid or missing URL scheme", "type": "value_error.url.scheme", }, { "loc": ("__root__",), "msg": "Must provide either a connection string or a combination of account, " "user, password, database, schema, warehouse, role as keyword args or " "a combination of account, user, database, schema, warehouse, role, " "private_key as keyword args.", "type": "value_error", }, ], id="missing scheme", ), pytest.param( "snowflake://user_login_name@account_identifier/db/schema?role=my_role&warehouse=my_wh", [ { "loc": ("connection_string",), "msg": "value is not a valid dict", "type": "type_error.dict", }, { "loc": ("connection_string",), "msg": "value is not a valid dict", "type": "type_error.dict", }, { "loc": ("connection_string",), "msg": "ConfigStr - contains no config template strings in the format" " '${MY_CONFIG_VAR}' or '$MY_CONFIG_VAR'", "type": "value_error", }, { "loc": ("connection_string",), "msg": "URL password invalid", "type": "value_error.url.password", }, { "loc": ("__root__",), "msg": "Must provide either a connection string or a combination of account, " "user, password, database, schema, warehouse, role as keyword args or " "a combination of account, user, database, schema, warehouse, role, " "private_key as keyword args.", "type": "value_error", }, ], id="bad password", ), pytest.param( "snowflake://user_login_name:password@/db/schema?role=my_role&warehouse=my_wh", [ { "loc": ("connection_string",), "msg": "value is not a valid dict", "type": "type_error.dict", }, { "loc": ("connection_string",), "msg": "value is not a valid dict", "type": "type_error.dict", }, { "loc": ("connection_string",), "msg": "ConfigStr - contains no config template strings in the format" " '${MY_CONFIG_VAR}' or '$MY_CONFIG_VAR'", "type": "value_error", }, { "loc": ("connection_string",), "msg": "URL domain invalid", "type": "value_error.url.domain", }, { "loc": ("__root__",), "msg": "Must provide either a connection string or a combination of account, " "user, password, database, schema, warehouse, role as keyword args or " "a combination of account, user, database, schema, warehouse, role, " "private_key as keyword args.", "type": "value_error", }, ], id="bad domain", ), pytest.param( "snowflake://user_login_name:password@account_identifier/db/schema?warehouse=my_wh", [ { "ctx": {"msg": "missing role"}, "loc": ("connection_string",), "msg": "URL query param missing", "type": "value_error.url.query", }, { "loc": ("__root__",), "msg": "Must provide either a connection string or a combination of account, " "user, password, database, schema, warehouse, role as keyword args or " "a combination of account, user, database, schema, warehouse, role, " "private_key as keyword args.", "type": "value_error", }, ], id="missing role", ), pytest.param( "snowflake://user_login_name:password@account_identifier/db/schema?role=my_role", [ { "ctx": {"msg": "missing warehouse"}, "loc": ("connection_string",), "msg": "URL query param missing", "type": "value_error.url.query", }, { "loc": ("__root__",), "msg": "Must provide either a connection string or a combination of account, " "user, password, database, schema, warehouse, role as keyword args or " "a combination of account, user, database, schema, warehouse, role, " "private_key as keyword args.", "type": "value_error", }, ], id="missing warehouse", ), ], ) def test_invalid_connection_string_raises_dsn_error( connection_string: str, expected_errors: list[dict] ): with pytest.raises(pydantic.ValidationError) as exc_info: _ = SnowflakeDatasource(name="my_snowflake", connection_string=connection_string) assert expected_errors == exc_info.value.errors() @pytest.mark.unit def test_connection_updating_templated_connection_string(): # Create datasource with templated connection string conn_str = "snowflake://user:${MY_PASSWORD}@account/db/schema?warehouse=wh&role=role" datasource = SnowflakeDatasource( name="my_snowflake", connection_string=conn_str, ) # Verify initial connection_string is ConfigUri assert isinstance(datasource.connection_string, ConfigUri) assert datasource.connection_string.template_str == conn_str # Assign a new templated connection string directly new_conn_str = "snowflake://newuser:${NEW_PASSWORD}@newaccount/newdb/newschema?warehouse=newwh&role=newrole" datasource.connection_string = new_conn_str # Verify it's still a ConfigUri after assignment (not a plain str) assert isinstance(datasource.connection_string, ConfigUri), ( f"Expected ConfigUri, got {type(datasource.connection_string)}. " "This indicates validate_assignment is not enabled." ) assert datasource.connection_string.template_str == new_conn_str @pytest.mark.parametrize( "private_key", [ pytest.param("${MY_PRIVATE_KEY}", id="Env Variable"), pytest.param("$MY_PRIVATE_KEY", id="Config Variable"), ], ) @pytest.mark.unit def test_creating_datasource_with_templated_private_key(private_key): connection_args = { "user": "my_user", "private_key": private_key, "account": "my_account", "schema": "S_PUBLIC", "database": "D_PUBLIC", "role": "my_role", "warehouse": "my_wh", } datasource = SnowflakeDatasource(name="my_snowflake", **connection_args) assert isinstance(datasource.private_key, ConfigStr) @pytest.mark.parametrize( "private_key", [ pytest.param("${MY_PRIVATE_KEY}", id="Env Variable"), pytest.param("$MY_PRIVATE_KEY", id="Config Variable"), ], ) @pytest.mark.unit def test_updating_datasource_with_templated_private_key(private_key): datasource = SnowflakeDatasource(name="my_snowflake", **KEY_PAIR_CONNECTION_ARGS) # Verify initial connection_string assert datasource.private_key != private_key datasource.connection_string.private_key = private_key assert isinstance(datasource.private_key, ConfigStr) # TODO: Cleanup how we install test dependencies and remove this skipif @pytest.mark.skipif(True if not snowflake else False, reason="snowflake is not installed") @pytest.mark.unit def test_get_execution_engine_succeeds(): connection_string = ( "snowflake://my_user:password@my_account/my_db/my_schema?role=my_role&warehouse=my_wh" ) datasource = SnowflakeDatasource(name="my_snowflake", connection_string=connection_string) # testing that this doesn't raise an exception datasource.get_execution_engine() @pytest.mark.snowflake @pytest.mark.parametrize( ["config", "expected_called_with"], [ param( { "name": "std connection_str", "connection_string": "snowflake://user:password@account/db/SCHEMA?warehouse=wh&role=role", }, {"url": ANY}, id="std connection_string str", ), param( { "name": "std connection_details", "connection_string": { "user": "user", "password": "password", "account": "account", "database": "db", "schema": "schema", "warehouse": "wh", "role": "role", }, }, { "url": "snowflake://user:password@account/db/schema?application=great_expectations_core&role=role&warehouse=wh", }, id="std connection_string dict", ), param( { "name": "conn str with connect_args", "connection_string": "snowflake://user:password@account/db/schema?warehouse=wh&role=role", "kwargs": {"connect_args": {"private_key": b"my_key"}}, }, { "connect_args": {"private_key": b"my_key"}, "url": ANY, }, id="connection_string str with connect_args", ), param( { "name": "conn details with connect_args", "connection_string": { "user": "user", "password": "password", "account": "account", "database": "db", "schema": "schema", "warehouse": "wh", "role": "role", }, "kwargs": {"connect_args": {"private_key": b"my_key"}}, }, { "connect_args": {"private_key": b"my_key"}, "url": "snowflake://user:password@account/db/schema?application=great_expectations_core&role=role&warehouse=wh", }, id="connection_string dict with connect_args", ), param( { "name": "conn details with connect_args", "connection_string": { "user": "user", "private_key": "my_key", "account": "account", "database": "db", "schema": "schema", "warehouse": "wh", "role": "role", }, }, { "url": "snowflake://user:@account/db/schema?application=great_expectations_core&private_key=my_key&role=role&warehouse=wh", }, id="key pair connection string", ), ], ) def test_create_engine_is_called_with_expected_kwargs( mocker: MockerFixture, sf_test_connection_noop: None, ephemeral_context_with_defaults: AbstractDataContext, config: dict, expected_called_with: dict, ): create_engine_spy = mocker.spy(sa, "create_engine") # Check if this config has private_key in connect_args (deprecated pattern) has_deprecated_pattern = ( isinstance(config.get("kwargs"), dict) and isinstance(config.get("kwargs", {}).get("connect_args"), dict) and "private_key" in config.get("kwargs", {}).get("connect_args", {}) ) if has_deprecated_pattern: with pytest.warns(DeprecationWarning, match="private_key.*deprecated"): datasource = ephemeral_context_with_defaults.data_sources.add_snowflake(**config) else: datasource = ephemeral_context_with_defaults.data_sources.add_snowflake(**config) print(datasource) engine = datasource.get_engine() print(engine) create_engine_spy.assert_called_once_with(**expected_called_with) @pytest.mark.snowflake @pytest.mark.parametrize( ("password", "encoded_password"), [ pytest.param("abc", "abc", id="no need to encode"), pytest.param("a@b", "a%40b", id="encode it"), ], ) def test_test_connection_encoding( mocker: MockerFixture, ephemeral_context_with_defaults: AbstractDataContext, password: str, encoded_password: str, ): account = "account" user = "foo" role = "role" warehouse = "warehouse" db = "db" schema = "schema" create_engine_spy = mocker.patch.object(sa, "create_engine") datasource = ephemeral_context_with_defaults.data_sources.add_snowflake( name="foo", account=account, user=user, password=password, database=db, schema=schema, role=role, warehouse=warehouse, ) datasource.get_engine() create_engine_spy.assert_called_with( url=SnowflakeURL( account=account, user=user, password=encoded_password, database=db, schema=schema, role=role, warehouse=warehouse, application="great_expectations_core", ) ) @pytest.mark.unit @pytest.mark.parametrize("ds_config", VALID_DS_CONFIG_PARAMS)
TestAccountIdentifier
python
fsspec__filesystem_spec
fsspec/implementations/asyn_wrapper.py
{ "start": 876, "end": 3679 }
class ____(AsyncFileSystem): """ A wrapper class to convert a synchronous filesystem into an asynchronous one. This class takes an existing synchronous filesystem implementation and wraps all its methods to provide an asynchronous interface. Parameters ---------- sync_fs : AbstractFileSystem The synchronous filesystem instance to wrap. """ protocol = "asyncwrapper", "async_wrapper" cachable = False def __init__( self, fs=None, asynchronous=None, target_protocol=None, target_options=None, semaphore=None, max_concurrent_tasks=None, **kwargs, ): if asynchronous is None: asynchronous = running_async() super().__init__(asynchronous=asynchronous, **kwargs) if fs is not None: self.sync_fs = fs else: self.sync_fs = fsspec.filesystem(target_protocol, **target_options) self.protocol = self.sync_fs.protocol self.semaphore = semaphore self._wrap_all_sync_methods() @property def fsid(self): return f"async_{self.sync_fs.fsid}" def _wrap_all_sync_methods(self): """ Wrap all synchronous methods of the underlying filesystem with asynchronous versions. """ excluded_methods = {"open"} for method_name in dir(self.sync_fs): if method_name.startswith("_") or method_name in excluded_methods: continue attr = inspect.getattr_static(self.sync_fs, method_name) if isinstance(attr, property): continue method = getattr(self.sync_fs, method_name) if callable(method) and not inspect.iscoroutinefunction(method): async_method = async_wrapper(method, obj=self, semaphore=self.semaphore) setattr(self, f"_{method_name}", async_method) @classmethod def wrap_class(cls, sync_fs_class): """ Create a new class that can be used to instantiate an AsyncFileSystemWrapper with lazy instantiation of the underlying synchronous filesystem. Parameters ---------- sync_fs_class : type The class of the synchronous filesystem to wrap. Returns ------- type A new class that wraps the provided synchronous filesystem class. """ class GeneratedAsyncFileSystemWrapper(cls): def __init__(self, *args, **kwargs): sync_fs = sync_fs_class(*args, **kwargs) super().__init__(sync_fs) GeneratedAsyncFileSystemWrapper.__name__ = ( f"Async{sync_fs_class.__name__}Wrapper" ) return GeneratedAsyncFileSystemWrapper
AsyncFileSystemWrapper
python
django__django
tests/gis_tests/geoapp/tests.py
{ "start": 25480, "end": 31691 }
class ____(TestCase): # TODO: GeoQuerySet is removed, organize these test better. fixtures = ["initial"] @skipUnlessDBFeature("supports_extent_aggr") def test_extent(self): """ Testing the `Extent` aggregate. """ # Reference query: # SELECT ST_extent(point) # FROM geoapp_city # WHERE (name='Houston' or name='Dallas');` # => BOX(-96.8016128540039 29.7633724212646,-95.3631439208984 # 32.7820587158203) expected = ( -96.8016128540039, 29.7633724212646, -95.3631439208984, 32.782058715820, ) qs = City.objects.filter(name__in=("Houston", "Dallas")) extent = qs.aggregate(Extent("point"))["point__extent"] for val, exp in zip(extent, expected): self.assertAlmostEqual(exp, val, 4) self.assertIsNone( City.objects.filter(name=("Smalltown")).aggregate(Extent("point"))[ "point__extent" ] ) @skipUnlessDBFeature("supports_extent_aggr") def test_extent_with_limit(self): """ Testing if extent supports limit. """ extent1 = City.objects.aggregate(Extent("point"))["point__extent"] extent2 = City.objects.all()[:3].aggregate(Extent("point"))["point__extent"] self.assertNotEqual(extent1, extent2) def test_make_line(self): """ Testing the `MakeLine` aggregate. """ if not connection.features.supports_make_line_aggr: with self.assertRaises(NotSupportedError): City.objects.aggregate(MakeLine("point")) return # MakeLine on an inappropriate field returns simply None self.assertIsNone(State.objects.aggregate(MakeLine("poly"))["poly__makeline"]) # Reference query: # SELECT AsText(ST_MakeLine(geoapp_city.point)) FROM geoapp_city; line = City.objects.aggregate(MakeLine("point"))["point__makeline"] ref_points = City.objects.values_list("point", flat=True) self.assertIsInstance(line, LineString) self.assertEqual(len(line), ref_points.count()) # Compare pairs of manually sorted points, as the default ordering is # flaky. for point, ref_city in zip(sorted(line), sorted(ref_points)): point_x, point_y = point self.assertAlmostEqual(point_x, ref_city.x, 5) self.assertAlmostEqual(point_y, ref_city.y, 5) @skipUnlessDBFeature("supports_union_aggr") def test_unionagg(self): """ Testing the `Union` aggregate. """ tx = Country.objects.get(name="Texas").mpoly # Houston, Dallas -- Ordering may differ depending on backend or GEOS # version. union = GEOSGeometry("MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)") qs = City.objects.filter(point__within=tx) with self.assertRaises(ValueError): qs.aggregate(Union("name")) # Using `field_name` keyword argument in one query and specifying an # order in the other (which should not be used because this is # an aggregate method on a spatial column) u1 = qs.aggregate(Union("point"))["point__union"] u2 = qs.order_by("name").aggregate(Union("point"))["point__union"] self.assertTrue(union.equals(u1)) self.assertTrue(union.equals(u2)) qs = City.objects.filter(name="NotACity") self.assertIsNone(qs.aggregate(Union("point"))["point__union"]) @skipUnlessDBFeature("supports_union_aggr") def test_geoagg_subquery(self): tx = Country.objects.get(name="Texas") union = GEOSGeometry("MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)") # Use distinct() to force the usage of a subquery for aggregation. with CaptureQueriesContext(connection) as ctx: self.assertIs( union.equals( City.objects.filter(point__within=tx.mpoly) .distinct() .aggregate( Union("point"), )["point__union"], ), True, ) self.assertIn("subquery", ctx.captured_queries[0]["sql"]) @skipUnlessDBFeature("supports_tolerance_parameter") def test_unionagg_tolerance(self): City.objects.create( point=fromstr("POINT(-96.467222 32.751389)", srid=4326), name="Forney", ) tx = Country.objects.get(name="Texas").mpoly # Tolerance is greater than distance between Forney and Dallas, that's # why Dallas is ignored. forney_houston = GEOSGeometry( "MULTIPOINT(-95.363151 29.763374, -96.467222 32.751389)", srid=4326, ) self.assertIs( forney_houston.equals_exact( City.objects.filter(point__within=tx).aggregate( Union("point", tolerance=32000), )["point__union"], tolerance=10e-6, ), True, ) @skipUnlessDBFeature("supports_tolerance_parameter") def test_unionagg_tolerance_escaping(self): tx = Country.objects.get(name="Texas").mpoly with self.assertRaises(DatabaseError): City.objects.filter(point__within=tx).aggregate( Union("point", tolerance="0.05))), (((1"), ) def test_within_subquery(self): """ Using a queryset inside a geo lookup is working (using a subquery) (#14483). """ tex_cities = City.objects.filter( point__within=Country.objects.filter(name="Texas").values("mpoly") ).order_by("name") self.assertEqual( list(tex_cities.values_list("name", flat=True)), ["Dallas", "Houston"] ) def test_non_concrete_field(self): NonConcreteModel.objects.create(point=Point(0, 0), name="name") list(NonConcreteModel.objects.all()) def test_values_srid(self): for c, v in zip(City.objects.all(), City.objects.values()): self.assertEqual(c.point.srid, v["point"].srid)
GeoQuerySetTest
python
h5py__h5py
h5py/_hl/base.py
{ "start": 15415, "end": 15711 }
class ____: def __init__(self, func): self.__doc__ = getattr(func, "__doc__") self.func = func def __get__(self, obj, cls): if obj is None: return self value = obj.__dict__[self.func.__name__] = self.func(obj) return value
cached_property
python
pyca__cryptography
src/cryptography/hazmat/primitives/hashes.py
{ "start": 2263, "end": 2378 }
class ____(HashAlgorithm): # noqa: N801 name = "sha512-224" digest_size = 28 block_size = 128
SHA512_224
python
walkccc__LeetCode
solutions/3429. Paint House IV/3429.py
{ "start": 0, "end": 828 }
class ____: def minCost(self, n: int, costs: list[list[int]]) -> int: INVALID_COLOR = 3 def getValidColors(prevColor: int) -> list[int]: return [color for color in range(3) if color != prevColor] @functools.lru_cache(None) def minCost(i: int, prevLeftColor: int, prevRightColor: int) -> int: if i == len(costs) // 2: return 0 res = math.inf for leftColor in getValidColors(prevLeftColor): for rightColor in getValidColors(prevRightColor): if leftColor == rightColor: continue leftCost = costs[i][leftColor] rightCost = costs[-1 - i][rightColor] res = min(res, leftCost + rightCost + minCost(i + 1, leftColor, rightColor)) return res return minCost(0, INVALID_COLOR, INVALID_COLOR)
Solution
python
great-expectations__great_expectations
docs/sphinx_api_docs_source/include_exclude_definition.py
{ "start": 139, "end": 1205 }
class ____: """Include or exclude directive for a class, function or method. Name and/or relative filepath of class, function or method definition to exclude or include. Args: reason: Reason for include or exclude. name: name of class, method or function. filepath: Relative to repo_root. E.g. great_expectations/core/expectation_suite.py Required if providing `name`. """ reason: str name: Optional[str] = None filepath: Optional[pathlib.Path] = None def __post_init__(self): if self.name and not self.filepath: raise ValueError("You must provide a filepath if also providing a name.") # noqa: TRY003 if not self.name and not self.filepath: raise ValueError( # noqa: TRY003 "You must provide at least a filepath or filepath and name." ) if self.filepath and not self.filepath.exists(): raise FileNotFoundError(f"File {self.filepath} does not exist.") # noqa: TRY003
IncludeExcludeDefinition
python
OmkarPathak__pygorithm
tests/test_data_structure.py
{ "start": 5133, "end": 5944 }
class ____(unittest.TestCase): def test_binary_search_tree(self): root = tree.BinarySearchTree() root.insert(10) root.insert(12) root.insert(5) root.insert(4) root.insert(20) root.insert(8) root.insert(7) root.insert(15) root.insert(13) inorder = root.inorder() preorder = root.preorder() postorder = root.postorder() expectedResult = [4, 5, 7, 8, 10, 12, 13, 15, 20] self.assertEqual(inorder, expectedResult) expectedResult = [10, 5, 4, 8, 7, 12, 20, 15, 13] self.assertEqual(preorder, expectedResult) expectedResult = [4, 7, 8, 5, 13, 15, 20, 12, 10] self.assertEqual(postorder, expectedResult) self.assertTrue(root.find(8))
TestBinarySearchTree
python
wandb__wandb
wandb/sdk/launch/registry/google_artifact_registry.py
{ "start": 1050, "end": 8510 }
class ____(AbstractRegistry): """Google Artifact Registry helper for interacting with the registry. This helper should be constructed from either a uri or a repository, project, and optional image-name. If constructed from a uri, the uri must be of the form REGION-docker.pkg.dev/PROJECT/REPOSITORY/[IMAGE_NAME], with an optional https:// preceding. """ def __init__( self, uri: Optional[str] = None, repository: Optional[str] = None, image_name: Optional[str] = None, project: Optional[str] = None, region: Optional[str] = None, ) -> None: """Initialize the Google Artifact Registry. Either uri or repository and image_name must be provided. Project and region are optional, and will be inferred from the uri if provided, or from the default credentials if not. Arguments: uri (optional): The uri of the repository. repository (optional): The repository name. image_name (optional): The image name. project (optional): The GCP project name. region (optional): The GCP region name. Raises: LaunchError: If verify is True and the container registry or its environment have not been properly configured. Or if the environment is not an instance of GcpEnvironment. """ _logger.info( f"Initializing Google Artifact Registry with repository {repository} " f"and image name {image_name}" ) if uri is not None: self.uri = uri # Raise an error if any other kwargs were provided in addition to uri. if any([repository, image_name, project, region]): raise LaunchError( "The Google Artifact Registry must be specified with either " "the uri key or the repository, image-name, project and region " "keys, but not both." ) match = GCP_ARTIFACT_REGISTRY_URI_REGEX.match(self.uri) if not match: raise LaunchError( f"The Google Artifact Registry uri {self.uri} is invalid. " "Please provide a uri of the form " "REGION-docker.pkg.dev/PROJECT/REPOSITORY/IMAGE_NAME." ) self.project = match.group("project") self.region = match.group("region") self.repository = match.group("repository") self.image_name = match.group("image_name") else: if any(x is None for x in (repository, region, image_name)): raise LaunchError( "The Google Artifact Registry must be specified with either " "the uri key or the repository, image-name, project and region " "keys." ) self.project = project self.region = region self.repository = repository self.image_name = image_name self.uri = f"{self.region}-docker.pkg.dev/{self.project}/{self.repository}/{self.image_name}" _missing_kwarg_msg = ( "The Google Artifact Registry is missing the {} kwarg. " "Please specify it by name or as part of the uri argument." ) if not self.region: raise LaunchError(_missing_kwarg_msg.format("region")) if not self.repository: raise LaunchError(_missing_kwarg_msg.format("repository")) if not self.image_name: raise LaunchError(_missing_kwarg_msg.format("image-name")) # Try to load default project from the default credentials. self.credentials, project = google.auth.default() self.project = self.project or project self.credentials.refresh(google.auth.transport.requests.Request()) @classmethod def from_config( cls, config: dict, ) -> "GoogleArtifactRegistry": """Create a Google Artifact Registry from a config. Arguments: config: A dictionary containing the following keys: repository: The repository name. image-name: The image name. environment: A GcpEnvironment configured for access to this registry. Returns: A GoogleArtifactRegistry. """ # TODO: Replace this with pydantic. acceptable_keys = { "uri", "type", "repository", "image-name", "region", "project", } unacceptable_keys = set(config.keys()) - acceptable_keys if unacceptable_keys: raise LaunchError( f"The Google Artifact Registry config contains unacceptable keys: " f"{unacceptable_keys}. Please remove these keys. The acceptable " f"keys are: {acceptable_keys}." ) return cls( uri=config.get("uri"), repository=config.get("repository"), image_name=config.get("image-name"), project=config.get("project"), region=config.get("region"), ) async def get_username_password(self) -> Tuple[str, str]: """Get the username and password for the registry. Returns: A tuple of the username and password. """ if not self.credentials.token: self.credentials.refresh(google.auth.transport.requests.Request()) return "oauth2accesstoken", self.credentials.token async def get_repo_uri(self) -> str: """Get the URI for the given repository. Arguments: repo_name: The repository name. Returns: The repository URI. """ return ( f"{self.region}-docker.pkg.dev/" f"{self.project}/{self.repository}/{self.image_name}" ) async def check_image_exists(self, image_uri: str) -> bool: """Check if the image exists. Arguments: image_uri: The image URI. Returns: True if the image exists, False otherwise. """ _logger.info(f"Checking if image {image_uri} exists") repo_uri, tag = image_uri.split(":") self_repo_uri = await self.get_repo_uri() if repo_uri != self_repo_uri: raise LaunchError( f"The image {image_uri} does not match to the image uri " f"repository {self.uri}." ) parent = f"projects/{self.project}/locations/{self.region}/repositories/{self.repository}" artifact_registry_client = event_loop_thread_exec( google.cloud.artifactregistry.ArtifactRegistryClient ) client = await artifact_registry_client(credentials=self.credentials) list_images = event_loop_thread_exec(client.list_docker_images) try: for image in await list_images(request={"parent": parent}): if tag in image.tags: return True except google.api_core.exceptions.NotFound as e: # type: ignore[attr-defined] raise LaunchError( f"The Google Artifact Registry repository {self.repository} " f"does not exist. Please create it or modify your registry configuration." ) from e return False
GoogleArtifactRegistry
python
python-markdown__markdown
markdown/extensions/legacy_attrs.py
{ "start": 1662, "end": 2497 }
class ____(Treeprocessor): def run(self, doc: etree.Element) -> None: """Find and set values of attributes ({@key=value}). """ for el in doc.iter(): alt = el.get('alt', None) if alt is not None: el.set('alt', self.handleAttributes(el, alt)) if el.text and isString(el.text): el.text = self.handleAttributes(el, el.text) if el.tail and isString(el.tail): el.tail = self.handleAttributes(el, el.tail) def handleAttributes(self, el: etree.Element, txt: str) -> str: """ Set attributes and return text without definitions. """ def attributeCallback(match: re.Match[str]): el.set(match.group(1), match.group(2).replace('\n', ' ')) return ATTR_RE.sub(attributeCallback, txt)
LegacyAttrs
python
python-pillow__Pillow
src/PIL/ImageDraw2.py
{ "start": 925, "end": 1081 }
class ____: """Stores a fill color""" def __init__(self, color: str, opacity: int = 255) -> None: self.color = ImageColor.getrgb(color)
Brush
python
getsentry__sentry
tests/sentry/middleware/test_proxy.py
{ "start": 471, "end": 1487 }
class ____(TestCase): middleware = cached_property(SetRemoteAddrFromForwardedFor) def test_ipv4(self) -> None: request = HttpRequest() request.META["HTTP_X_FORWARDED_FOR"] = "8.8.8.8:80,8.8.4.4" self.middleware.process_request(request) assert request.META["REMOTE_ADDR"] == "8.8.8.8" def test_ipv4_whitespace(self) -> None: request = HttpRequest() request.META["HTTP_X_FORWARDED_FOR"] = "8.8.8.8:80 " self.middleware.process_request(request) assert request.META["REMOTE_ADDR"] == "8.8.8.8" def test_ipv6(self) -> None: request = HttpRequest() request.META["HTTP_X_FORWARDED_FOR"] = "2001:4860:4860::8888,2001:4860:4860::8844" self.middleware.process_request(request) assert request.META["REMOTE_ADDR"] == "2001:4860:4860::8888" test_region = Region( "us", 1, "https://test", RegionCategory.MULTI_TENANT, ) @control_silo_test(regions=[test_region])
SetRemoteAddrFromForwardedForTestCase
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_gen_ai.py
{ "start": 6890, "end": 7819 }
class ____: @mock.patch(GEN_AI_PATH.format("GenAIGenerativeModelHook")) def test_execute(self, mock_hook): op = GenAICreateCachedContentOperator( task_id=TASK_ID, project_id=GCP_PROJECT, location=GCP_LOCATION, model=GEMINI_MODEL, cached_content_config=CACHED_CONTENT_CONFIG, gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) op.execute(context={"ti": mock.MagicMock()}) mock_hook.assert_called_once_with( gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) mock_hook.return_value.create_cached_content.assert_called_once_with( project_id=GCP_PROJECT, location=GCP_LOCATION, model=GEMINI_MODEL, cached_content_config=CACHED_CONTENT_CONFIG, )
TestGenAICreateCachedContentOperator
python
pytorch__pytorch
torch/_inductor/codecache.py
{ "start": 8353, "end": 12086 }
class ____(CacheBase): def lookup( self, choices: list[ChoiceCaller], op: str, inputs: str, benchmark: Callable[[Any], dict[ChoiceCaller, float]] | None, hint_override: int | None = None, ) -> dict[ChoiceCaller, float]: """ Check to see if we have benchmarked the given choice callers. For each choice caller: 1. Check local_cache[op][inputs][choice][precision], return benchmark if cached. 2. If benchmark is not None: a. `max_autotune_gemm=True`: benchmark the choice, update local_cache[op][inputs][choice], and return the benchmark. b. `max_autotune_gemm=False`: don't benchmark the choice, return nothing. """ precision = torch.get_float32_matmul_precision() cache_key = f"{inputs}_{hint_override}" if hint_override is not None else inputs timings = {} def check_cache(cache: dict[str, Any]) -> bool: """Check if `cache` contains data for all the choices""" hit = True for choice in choices: choice_hash = choice.hash_key() if choice_hash in cache.get(op, {}).get(cache_key, {}).get( precision, {} ): # cache hit timings[choice] = cache[op][cache_key][precision][choice_hash] else: # cache miss hit = False break return hit local_cache = self.get_local_cache() if config.autotune_local_cache else {} if (not check_cache(local_cache)) and (benchmark is not None): # re-benchmark everything to try to get consistent numbers from the same machine timings = benchmark(choices) assert all(choice in timings for choice in choices) local_cache.setdefault(op, {}) local_cache[op].setdefault(cache_key, {}).setdefault(precision, {}) for choice, timing in timings.items(): local_cache[op][cache_key][precision][choice.hash_key()] = timing self.update_local_cache(local_cache) return timings def get_lock_dir() -> str: lock_dir = os.path.join(cache_dir(), "locks") if not os.path.exists(lock_dir): os.makedirs(lock_dir, exist_ok=True) return lock_dir def sha256_hash(data: bytes) -> str: # [:51] to strip off the "Q====" suffix common to every hash value. return base64.b32encode(hashlib.sha256(data).digest())[:51].decode("utf-8").lower() def code_hash(code: str | bytes, extra: str | bytes = "") -> str: hashing_str = code if isinstance(code, bytes) else code.encode("utf-8") if extra: extra_b = extra if isinstance(extra, bytes) else extra.encode("utf-8") hashing_str = hashing_str + b"||" + extra_b return "c" + sha256_hash(hashing_str) def get_path( basename: str, extension: str, specified_dir: str = "" ) -> tuple[str, str, str]: if specified_dir: if os.path.isabs(specified_dir): subdir = specified_dir else: subdir = os.path.join(cache_dir(), specified_dir) else: subdir = os.path.join(cache_dir(), basename[1:3]) path = os.path.join(subdir, f"{basename}.{extension}") return basename, subdir, path def get_hash(content: str | bytes, extra: str = "", hash_type: str = "code") -> str: if hash_type in {"amdgcn", "code", "ptx", "spv"}: return code_hash(content, extra) if hash_type in {"cubin", "hsaco", "spv"}: return code_hash(repr(content)) raise AssertionError(f"Unknown hash type {hash_type}")
PersistentCache
python
PyCQA__pylint
tests/functional/i/iterable_context.py
{ "start": 2880, "end": 3239 }
class ____: def __init__(self): self._lineparser = None self._init_lineparser() # error should not be emitted here for line in self._lineparser: print(line) def _init_lineparser(self): raise NotImplementedError # class is not named as abstract # but still is deduceably abstract
AbstractUrlMarkManager
python
django__django
tests/delete/models.py
{ "start": 6653, "end": 6732 }
class ____(models.Model): restrict = models.ForeignKey(R, models.RESTRICT)
B3
python
PrefectHQ__prefect
src/integrations/prefect-aws/tests/observers/test_ecs_observer.py
{ "start": 2445, "end": 4570 }
class ____: def test_is_match_with_no_filter_statuses(self): filter = LastStatusFilter() assert filter.is_match("RUNNING") assert filter.is_match("STOPPED") assert filter.is_match("PENDING") def test_is_match_with_single_status(self): filter = LastStatusFilter("RUNNING") assert filter.is_match("RUNNING") assert not filter.is_match("STOPPED") assert not filter.is_match("PENDING") def test_is_match_with_multiple_statuses(self): filter = LastStatusFilter("RUNNING", "STOPPED") assert filter.is_match("RUNNING") assert filter.is_match("STOPPED") assert not filter.is_match("PENDING") assert not filter.is_match("PROVISIONING") def test_is_match_with_all_valid_statuses(self): filter = LastStatusFilter( "PROVISIONING", "PENDING", "ACTIVATING", "RUNNING", "DEACTIVATING", "STOPPING", "DEPROVISIONING", "STOPPED", "DELETED", ) assert filter.is_match("PROVISIONING") assert filter.is_match("PENDING") assert filter.is_match("ACTIVATING") assert filter.is_match("RUNNING") assert filter.is_match("DEACTIVATING") assert filter.is_match("STOPPING") assert filter.is_match("DEPROVISIONING") assert filter.is_match("STOPPED") assert filter.is_match("DELETED") def test_is_match_with_final_states(self): filter = LastStatusFilter("STOPPED", "DELETED") assert filter.is_match("STOPPED") assert filter.is_match("DELETED") assert not filter.is_match("RUNNING") assert not filter.is_match("PENDING") def test_is_match_with_intermediate_states(self): filter = LastStatusFilter("PROVISIONING", "PENDING", "ACTIVATING") assert filter.is_match("PROVISIONING") assert filter.is_match("PENDING") assert filter.is_match("ACTIVATING") assert not filter.is_match("RUNNING") assert not filter.is_match("STOPPED")
TestLastStatusFilter
python
dagster-io__dagster
python_modules/libraries/dagster-azure/dagster_azure_tests/blob_tests/test_compute_log_manager.py
{ "start": 9845, "end": 17099 }
class ____(TestComputeLogManager): __test__ = True @pytest.fixture(name="compute_log_manager") def compute_log_manager( self, blob_client, storage_account, container, credential, ): with ( mock.patch( "dagster_azure.blob.compute_log_manager.generate_blob_sas" ) as generate_blob_sas, mock.patch( "dagster_azure.blob.compute_log_manager.create_blob_client" ) as create_blob_client, tempfile.TemporaryDirectory() as temp_dir, ): generate_blob_sas.return_value = "fake-url" create_blob_client.return_value = blob_client yield AzureBlobComputeLogManager( storage_account=storage_account, container=container, prefix="my_prefix", local_dir=temp_dir, secret_credential=credential, ) # for streaming tests @pytest.fixture(name="write_manager") def write_manager( self, blob_client, storage_account, container, credential, ): with ( mock.patch( "dagster_azure.blob.compute_log_manager.generate_blob_sas" ) as generate_blob_sas, mock.patch( "dagster_azure.blob.compute_log_manager.create_blob_client" ) as create_blob_client, tempfile.TemporaryDirectory() as temp_dir, ): generate_blob_sas.return_value = "fake-url" create_blob_client.return_value = blob_client yield AzureBlobComputeLogManager( storage_account=storage_account, container=container, prefix="my_prefix", local_dir=temp_dir, secret_credential=credential, upload_interval=1, ) @pytest.fixture(name="read_manager") def read_manager(self, compute_log_manager): yield compute_log_manager @mock.patch("dagster_azure.blob.compute_log_manager.DefaultAzureCredential") @mock.patch("dagster_azure.blob.compute_log_manager.generate_blob_sas") @mock.patch("dagster_azure.blob.compute_log_manager.create_blob_client") def test_compute_log_manager_default_azure_credential( mock_create_blob_client, mock_generate_blob_sas, MockDefaultAzureCredential, storage_account, container, ): mock_generate_blob_sas.return_value = "fake-url" fake_client = FakeBlobServiceClient(storage_account) mock_create_blob_client.return_value = fake_client @graph def simple(): @op def easy(context): context.log.info("easy") print(HELLO_WORLD) # noqa: T201 return "easy" easy() with tempfile.TemporaryDirectory() as temp_dir: with environ({"DAGSTER_HOME": temp_dir}): run_store = SqliteRunStorage.from_local(temp_dir) event_store = SqliteEventLogStorage(temp_dir) manager = AzureBlobComputeLogManager( storage_account=storage_account, container=container, prefix="my_prefix", local_dir=temp_dir, default_azure_credential={"exclude_environment_credentials": True}, ) instance = DagsterInstance( instance_type=InstanceType.PERSISTENT, local_artifact_storage=LocalArtifactStorage(temp_dir), run_storage=run_store, event_storage=event_store, compute_log_manager=manager, run_coordinator=DefaultRunCoordinator(), run_launcher=SyncInMemoryRunLauncher(), ref=InstanceRef.from_dir(temp_dir), settings={"telemetry": {"enabled": False}}, ) result = simple.execute_in_process(instance=instance) capture_events = [ event for event in result.all_events if event.event_type == DagsterEventType.LOGS_CAPTURED ] assert len(capture_events) == 1 MockDefaultAzureCredential.assert_called_once_with(exclude_environment_credentials=True) event = capture_events[0] file_key = event.logs_captured_data.file_key log_key = manager.build_log_key_for_run(result.run_id, file_key) # Capture API log_data = manager.get_log_data(log_key) stdout = log_data.stdout.decode("utf-8") # pyright: ignore[reportOptionalMemberAccess] assert stdout == HELLO_WORLD + SEPARATOR stderr = log_data.stderr.decode("utf-8") # pyright: ignore[reportOptionalMemberAccess] for expected in EXPECTED_LOGS: assert expected in stderr # Check ADLS2 directly adls2_object = fake_client.get_blob_client( container=container, blob=f"my_prefix/storage/{result.run_id}/compute_logs/{file_key}.err", ) adls2_stderr = adls2_object.download_blob().readall().decode("utf-8") for expected in EXPECTED_LOGS: assert expected in adls2_stderr # Check download behavior by deleting locally cached logs compute_logs_dir = os.path.join(temp_dir, result.run_id, "compute_logs") for filename in os.listdir(compute_logs_dir): os.unlink(os.path.join(compute_logs_dir, filename)) # Capture API log_data = manager.get_log_data(log_key) stdout = log_data.stdout.decode("utf-8") # pyright: ignore[reportOptionalMemberAccess] assert stdout == HELLO_WORLD + SEPARATOR stderr = log_data.stderr.decode("utf-8") # pyright: ignore[reportOptionalMemberAccess] for expected in EXPECTED_LOGS: assert expected in stderr def test_compute_log_manager_from_config_default_azure_credential(storage_account, container): prefix = "foobar" dagster_yaml = f""" compute_logs: module: dagster_azure.blob.compute_log_manager class: AzureBlobComputeLogManager config: storage_account: "{storage_account}" container: {container} local_dir: "/tmp/cool" prefix: "{prefix}" default_azure_credential: exclude_environment_credentials: true """ with tempfile.TemporaryDirectory() as tempdir: with open(os.path.join(tempdir, "dagster.yaml"), "wb") as f: f.write(dagster_yaml.encode("utf-8")) instance = DagsterInstance.from_config(tempdir) assert instance.compute_log_manager._storage_account == storage_account # noqa: SLF001 # pyright: ignore[reportAttributeAccessIssue] assert instance.compute_log_manager._container == container # noqa: SLF001 # pyright: ignore[reportAttributeAccessIssue] assert instance.compute_log_manager._blob_prefix == prefix # noqa: SLF001 # pyright: ignore[reportAttributeAccessIssue] assert instance.compute_log_manager._default_azure_credential == { # noqa: SLF001 # pyright: ignore[reportAttributeAccessIssue] "exclude_environment_credentials": True }
TestAzureComputeLogManager
python
kamyu104__LeetCode-Solutions
Python/diet-plan-performance.py
{ "start": 48, "end": 564 }
class ____(object): def dietPlanPerformance(self, calories, k, lower, upper): """ :type calories: List[int] :type k: int :type lower: int :type upper: int :rtype: int """ total = sum(itertools.islice(calories, 0, k)) result = int(total > upper)-int(total < lower) for i in xrange(k, len(calories)): total += calories[i]-calories[i-k] result += int(total > upper)-int(total < lower) return result
Solution
python
docker__docker-py
tests/integration/models_nodes_test.py
{ "start": 92, "end": 1148 }
class ____(unittest.TestCase): def setUp(self): helpers.force_leave_swarm(docker.from_env(version=TEST_API_VERSION)) def tearDown(self): helpers.force_leave_swarm(docker.from_env(version=TEST_API_VERSION)) def test_list_get_update(self): client = docker.from_env(version=TEST_API_VERSION) client.swarm.init('127.0.0.1', listen_addr=helpers.swarm_listen_addr()) nodes = client.nodes.list() assert len(nodes) == 1 assert nodes[0].attrs['Spec']['Role'] == 'manager' node = client.nodes.get(nodes[0].id) assert node.id == nodes[0].id assert node.attrs['Spec']['Role'] == 'manager' assert node.version > 0 node = client.nodes.list()[0] assert not node.attrs['Spec'].get('Labels') node.update({ 'Availability': 'active', 'Name': 'node-name', 'Role': 'manager', 'Labels': {'foo': 'bar'} }) node.reload() assert node.attrs['Spec']['Labels'] == {'foo': 'bar'}
NodesTest
python
plotly__plotly.py
plotly/graph_objs/scatterpolargl/_stream.py
{ "start": 233, "end": 3546 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scatterpolargl" _path_str = "scatterpolargl.stream" _valid_props = {"maxpoints", "token"} @property def maxpoints(self): """ Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. The 'maxpoints' property is a number and may be specified as: - An int or float in the interval [0, 10000] Returns ------- int|float """ return self["maxpoints"] @maxpoints.setter def maxpoints(self, val): self["maxpoints"] = val @property def token(self): """ The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details. The 'token' property is a string and must be specified as: - A non-empty string Returns ------- str """ return self["token"] @token.setter def token(self, val): self["token"] = val @property def _prop_descriptions(self): return """\ maxpoints Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. token The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details. """ def __init__(self, arg=None, maxpoints=None, token=None, **kwargs): """ Construct a new Stream object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scatterpolargl.Stream` maxpoints Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. token The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details. Returns ------- Stream """ super().__init__("stream") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.scatterpolargl.Stream constructor must be a dict or an instance of :class:`plotly.graph_objs.scatterpolargl.Stream`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("maxpoints", arg, maxpoints) self._set_property("token", arg, token) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Stream
python
openai__openai-python
src/openai/types/beta/realtime/rate_limits_updated_event.py
{ "start": 670, "end": 949 }
class ____(BaseModel): event_id: str """The unique ID of the server event.""" rate_limits: List[RateLimit] """List of rate limit information.""" type: Literal["rate_limits.updated"] """The event type, must be `rate_limits.updated`."""
RateLimitsUpdatedEvent
python
getsentry__sentry
src/sentry/snuba/outcomes.py
{ "start": 1791, "end": 2252 }
class ____(ABC): @abstractmethod def get_snuba_columns(self, raw_groupby: Sequence[str] | None = None) -> list[str]: raise NotImplementedError() @abstractmethod def extract_from_row( self, row: Mapping[str, Any] | None, group: Mapping[str, Any] | None = None ) -> int: raise NotImplementedError() @abstractmethod def select_params(self, dataset: Dataset) -> Function: raise NotImplementedError()
Field
python
wandb__wandb
wandb/vendor/watchdog_0_9_0/wandb_watchdog/events.py
{ "start": 13008, "end": 15604 }
class ____(FileSystemEventHandler): """ Matches given regexes with file paths associated with occurring events. """ def __init__(self, regexes=[r".*"], ignore_regexes=[], ignore_directories=False, case_sensitive=False): super(RegexMatchingEventHandler, self).__init__() if case_sensitive: self._regexes = [re.compile(r) for r in regexes] self._ignore_regexes = [re.compile(r) for r in ignore_regexes] else: self._regexes = [re.compile(r, re.I) for r in regexes] self._ignore_regexes = [re.compile(r, re.I) for r in ignore_regexes] self._ignore_directories = ignore_directories self._case_sensitive = case_sensitive @property def regexes(self): """ (Read-only) Regexes to allow matching event paths. """ return self._regexes @property def ignore_regexes(self): """ (Read-only) Regexes to ignore matching event paths. """ return self._ignore_regexes @property def ignore_directories(self): """ (Read-only) ``True`` if directories should be ignored; ``False`` otherwise. """ return self._ignore_directories @property def case_sensitive(self): """ (Read-only) ``True`` if path names should be matched sensitive to case; ``False`` otherwise. """ return self._case_sensitive def dispatch(self, event): """Dispatches events to the appropriate methods. :param event: The event object representing the file system event. :type event: :class:`FileSystemEvent` """ if self.ignore_directories and event.is_directory: return paths = [] if has_attribute(event, 'dest_path'): paths.append(unicode_paths.decode(event.dest_path)) if event.src_path: paths.append(unicode_paths.decode(event.src_path)) if any(r.match(p) for r in self.ignore_regexes for p in paths): return if any(r.match(p) for r in self.regexes for p in paths): self.on_any_event(event) _method_map = { EVENT_TYPE_MODIFIED: self.on_modified, EVENT_TYPE_MOVED: self.on_moved, EVENT_TYPE_CREATED: self.on_created, EVENT_TYPE_DELETED: self.on_deleted, } event_type = event.event_type _method_map[event_type](event)
RegexMatchingEventHandler
python
doocs__leetcode
solution/0600-0699/0663.Equal Tree Partition/Solution.py
{ "start": 192, "end": 598 }
class ____: def checkEqualTree(self, root: TreeNode) -> bool: def sum(root): if root is None: return 0 l, r = sum(root.left), sum(root.right) seen.append(l + r + root.val) return seen[-1] seen = [] s = sum(root) if s % 2 == 1: return False seen.pop() return s // 2 in seen
Solution
python
pydata__xarray
xarray/core/indexes.py
{ "start": 22711, "end": 36641 }
class ____(Index): """Wrap a pandas.Index as an xarray compatible index.""" index: pd.Index dim: Hashable coord_dtype: Any __slots__ = ("coord_dtype", "dim", "index") def __init__( self, array: Any, dim: Hashable, coord_dtype: Any = None, *, fastpath: bool = False, ): if fastpath: index = array else: index = safe_cast_to_index(array) if index.name is None: # make a shallow copy: cheap and because the index name may be updated # here or in other constructors (cannot use pd.Index.rename as this # constructor is also called from PandasMultiIndex) index = index.copy() index.name = dim self.index = index self.dim = dim if coord_dtype is None: if is_allowed_extension_array_dtype(index.dtype): cast(pd.api.extensions.ExtensionDtype, index.dtype) coord_dtype = index.dtype else: coord_dtype = get_valid_numpy_dtype(index) self.coord_dtype = coord_dtype def _replace(self, index, dim=None, coord_dtype=None): if dim is None: dim = self.dim if coord_dtype is None: coord_dtype = self.coord_dtype return type(self)(index, dim, coord_dtype, fastpath=True) @classmethod def from_variables( cls, variables: Mapping[Any, Variable], *, options: Mapping[str, Any], ) -> PandasIndex: if len(variables) != 1: raise ValueError( f"PandasIndex only accepts one variable, found {len(variables)} variables" ) name, var = next(iter(variables.items())) if var.ndim == 0: raise ValueError( f"cannot set a PandasIndex from the scalar variable {name!r}, " "only 1-dimensional variables are supported. " f"Note: you might want to use `obj.expand_dims({name!r})` to create a " f"new dimension and turn {name!r} as an indexed dimension coordinate." ) elif var.ndim != 1: raise ValueError( "PandasIndex only accepts a 1-dimensional variable, " f"variable {name!r} has {var.ndim} dimensions" ) dim = var.dims[0] # TODO: (benbovy - explicit indexes): add __index__ to ExplicitlyIndexesNDArrayMixin? # this could be eventually used by Variable.to_index() and would remove the need to perform # the checks below. # preserve wrapped pd.Index (if any) # accessing `.data` can load data from disk, so we only access if needed data = var._data if isinstance(var._data, PandasIndexingAdapter) else var.data # type: ignore[redundant-expr] # multi-index level variable: get level index if isinstance(var._data, PandasMultiIndexingAdapter): level = var._data.level if level is not None: data = var._data.array.get_level_values(level) obj = cls(data, dim, coord_dtype=var.dtype) assert not isinstance(obj.index, pd.MultiIndex) # Rename safely # make a shallow copy: cheap and because the index name may be updated # here or in other constructors (cannot use pd.Index.rename as this # constructor is also called from PandasMultiIndex) obj.index = obj.index.copy() obj.index.name = name return obj @staticmethod def _concat_indexes(indexes, dim, positions=None) -> pd.Index: new_pd_index: pd.Index if not indexes: new_pd_index = pd.Index([]) else: if not all(idx.dim == dim for idx in indexes): dims = ",".join({f"{idx.dim!r}" for idx in indexes}) raise ValueError( f"Cannot concatenate along dimension {dim!r} indexes with " f"dimensions: {dims}" ) pd_indexes = [idx.index for idx in indexes] new_pd_index = pd_indexes[0].append(pd_indexes[1:]) if positions is not None: indices = nputils.inverse_permutation(np.concatenate(positions)) new_pd_index = new_pd_index.take(indices) return new_pd_index @classmethod def concat( cls, indexes: Sequence[Self], dim: Hashable, positions: Iterable[Iterable[int]] | None = None, ) -> Self: new_pd_index = cls._concat_indexes(indexes, dim, positions) if not indexes: coord_dtype = None else: indexes_coord_dtypes = {idx.coord_dtype for idx in indexes} if len(indexes_coord_dtypes) == 1: coord_dtype = next(iter(indexes_coord_dtypes)) else: coord_dtype = np.result_type(*indexes_coord_dtypes) return cls(new_pd_index, dim=dim, coord_dtype=coord_dtype) def create_variables( self, variables: Mapping[Any, Variable] | None = None ) -> IndexVars: from xarray.core.variable import IndexVariable name = self.index.name attrs: Mapping[Hashable, Any] | None encoding: Mapping[Hashable, Any] | None if variables is not None and name in variables: var = variables[name] attrs = var.attrs encoding = var.encoding else: attrs = None encoding = None data = PandasIndexingAdapter(self.index, dtype=self.coord_dtype) var = IndexVariable(self.dim, data, attrs=attrs, encoding=encoding) return {name: var} def to_pandas_index(self) -> pd.Index: return self.index def isel( self, indexers: Mapping[Any, int | slice | np.ndarray | Variable] ) -> PandasIndex | None: from xarray.core.variable import Variable indxr = indexers[self.dim] if isinstance(indxr, Variable): if indxr.dims != (self.dim,): # can't preserve a index if result has new dimensions return None else: indxr = indxr.data if not isinstance(indxr, slice) and is_scalar(indxr): # scalar indexer: drop index return None return self._replace(self.index[indxr]) # type: ignore[index,unused-ignore] def sel( self, labels: dict[Any, Any], method=None, tolerance=None ) -> IndexSelResult: from xarray.core.dataarray import DataArray from xarray.core.variable import Variable if method is not None and not isinstance(method, str): raise TypeError("``method`` must be a string") assert len(labels) == 1 coord_name, label = next(iter(labels.items())) if isinstance(label, slice): indexer = _query_slice(self.index, label, coord_name, method, tolerance) elif is_dict_like(label): raise ValueError( "cannot use a dict-like object for selection on " "a dimension that does not have a MultiIndex" ) else: label_array = normalize_label(label, dtype=self.coord_dtype) if label_array.ndim == 0: label_value = as_scalar(label_array) if isinstance(self.index, pd.CategoricalIndex): if method is not None: raise ValueError( "'method' is not supported when indexing using a CategoricalIndex." ) if tolerance is not None: raise ValueError( "'tolerance' is not supported when indexing using a CategoricalIndex." ) indexer = self.index.get_loc(label_value) elif method is not None: indexer = get_indexer_nd(self.index, label_array, method, tolerance) if np.any(indexer < 0): raise KeyError(f"not all values found in index {coord_name!r}") else: try: indexer = self.index.get_loc(label_value) except KeyError as e: raise KeyError( f"not all values found in index {coord_name!r}. " "Try setting the `method` keyword argument (example: method='nearest')." ) from e elif label_array.dtype.kind == "b": indexer = label_array else: indexer = get_indexer_nd(self.index, label_array, method, tolerance) if np.any(indexer < 0): raise KeyError(f"not all values found in index {coord_name!r}") # attach dimension names and/or coordinates to positional indexer if isinstance(label, Variable): indexer = Variable(label.dims, indexer) elif isinstance(label, DataArray): indexer = DataArray(indexer, coords=label._coords, dims=label.dims) return IndexSelResult({self.dim: indexer}) def equals(self, other: Index, *, exclude: frozenset[Hashable] | None = None): if not isinstance(other, PandasIndex): return False return self.index.equals(other.index) and self.dim == other.dim def join( self, other: Self, how: str = "inner", ) -> Self: if how == "outer": index = self.index.union(other.index) else: # how = "inner" index = self.index.intersection(other.index) coord_dtype = np.result_type(self.coord_dtype, other.coord_dtype) return type(self)(index, self.dim, coord_dtype=coord_dtype) def reindex_like( self, other: Self, method=None, tolerance=None ) -> dict[Hashable, Any]: if not self.index.is_unique: raise ValueError( f"cannot reindex or align along dimension {self.dim!r} because the " "(pandas) index has duplicate values" ) return {self.dim: get_indexer_nd(self.index, other.index, method, tolerance)} def roll(self, shifts: Mapping[Any, int]) -> PandasIndex: shift = shifts[self.dim] % self.index.shape[0] if shift != 0: new_pd_idx = self.index[-shift:].append(self.index[:-shift]) else: new_pd_idx = self.index[:] return self._replace(new_pd_idx) def rename(self, name_dict, dims_dict): if self.index.name not in name_dict and self.dim not in dims_dict: return self new_name = name_dict.get(self.index.name, self.index.name) index = self.index.rename(new_name) new_dim = dims_dict.get(self.dim, self.dim) return self._replace(index, dim=new_dim) def _copy( self: T_PandasIndex, deep: bool = True, memo: dict[int, Any] | None = None ) -> T_PandasIndex: if deep: # pandas is not using the memo index = self.index.copy(deep=True) else: # index will be copied in constructor index = self.index return self._replace(index) def __getitem__(self, indexer: Any): return self._replace(self.index[indexer]) def __repr__(self): return f"PandasIndex({self.index!r})" def _check_dim_compat(variables: Mapping[Any, Variable], all_dims: str = "equal"): """Check that all multi-index variable candidates are 1-dimensional and either share the same (single) dimension or each have a different dimension. """ if any(var.ndim != 1 for var in variables.values()): raise ValueError("PandasMultiIndex only accepts 1-dimensional variables") dims = {var.dims for var in variables.values()} if all_dims == "equal" and len(dims) > 1: raise ValueError( "unmatched dimensions for multi-index variables " + ", ".join([f"{k!r} {v.dims}" for k, v in variables.items()]) ) if all_dims == "different" and len(dims) < len(variables): raise ValueError( "conflicting dimensions for multi-index product variables " + ", ".join([f"{k!r} {v.dims}" for k, v in variables.items()]) ) T_PDIndex = TypeVar("T_PDIndex", bound=pd.Index) def remove_unused_levels_categories(index: T_PDIndex) -> T_PDIndex: """ Remove unused levels from MultiIndex and unused categories from CategoricalIndex """ if isinstance(index, pd.MultiIndex): new_index = cast(pd.MultiIndex, index.remove_unused_levels()) # if it contains CategoricalIndex, we need to remove unused categories # manually. See https://github.com/pandas-dev/pandas/issues/30846 if any(isinstance(lev, pd.CategoricalIndex) for lev in new_index.levels): levels = [] for i, level in enumerate(new_index.levels): if isinstance(level, pd.CategoricalIndex): level = level[new_index.codes[i]].remove_unused_categories() else: level = level[new_index.codes[i]] levels.append(level) # TODO: calling from_array() reorders MultiIndex levels. It would # be best to avoid this, if possible, e.g., by using # MultiIndex.remove_unused_levels() (which does not reorder) on the # part of the MultiIndex that is not categorical, or by fixing this # upstream in pandas. new_index = pd.MultiIndex.from_arrays(levels, names=new_index.names) return cast(T_PDIndex, new_index) if isinstance(index, pd.CategoricalIndex): return index.remove_unused_categories() # type: ignore[attr-defined] return index
PandasIndex
python
kamyu104__LeetCode-Solutions
Python/minimum-cost-to-change-the-final-value-of-expression.py
{ "start": 1302, "end": 2414 }
class ____(object): def minOperationsToFlip(self, expression): """ :type expression: str :rtype: int """ stk = [[None]*3] for c in expression: if c == '(': stk.append([None]*3) elif c in {')', '0', '1'}: if c == ')': dp0, dp1, _ = stk.pop() else: dp0, dp1 = int(c != '0'), int(c != '1') if stk[-1][2] == '&': stk[-1] = [min(stk[-1][0], dp0), min(stk[-1][1]+dp1, min(stk[-1][1], dp1)+1), None] elif stk[-1][2] == '|': stk[-1] = [min(stk[-1][0]+dp0, min(stk[-1][0], dp0)+1), min(stk[-1][1], dp1), None] else: # operand stk[-1] = [dp0, dp1, None] else: stk[-1][2] = c return max(stk[0][0], stk[0][1])
Solution2
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 9308, "end": 10055 }
class ____(sgqlc.types.Enum): """The possible ecosystems of a dependency graph package. Enumeration Choices: * `ACTIONS`: GitHub Actions * `COMPOSER`: PHP packages hosted at packagist.org * `GO`: Go modules * `MAVEN`: Java artifacts hosted at the Maven central repository * `NPM`: JavaScript packages hosted at npmjs.com * `NUGET`: .NET packages hosted at the NuGet Gallery * `PIP`: Python packages hosted at PyPI.org * `PUB`: Dart packages hosted at pub.dev * `RUBYGEMS`: Ruby gems hosted at RubyGems.org * `RUST`: Rust crates """ __schema__ = github_schema __choices__ = ("ACTIONS", "COMPOSER", "GO", "MAVEN", "NPM", "NUGET", "PIP", "PUB", "RUBYGEMS", "RUST")
DependencyGraphEcosystem
python
astropy__astropy
astropy/coordinates/builtin_frames/cirs.py
{ "start": 978, "end": 1550 }
class ____(BaseRADecFrame): """ A coordinate or frame in the Celestial Intermediate Reference System (CIRS). The frame attributes are listed under **Other Parameters**. """ obstime = TimeAttribute( default=DEFAULT_OBSTIME, doc="The reference time (e.g., time of observation" ) location = EarthLocationAttribute( default=EARTH_CENTER, doc="The location on Earth of the observer" ) # The "self-transform" is defined in icrs_cirs_transformations.py, because in # the current implementation it goes through ICRS (like GCRS)
CIRS
python
tensorflow__tensorflow
tensorflow/python/training/proximal_adagrad.py
{ "start": 1074, "end": 5649 }
class ____(optimizer.Optimizer): # pylint: disable=line-too-long """Optimizer that implements the Proximal Adagrad algorithm. References: Adaptive Subgradient Methods for Online Learning and Stochastic Optimization: [Duchi et al., 2011](http://jmlr.org/papers/v12/duchi11a.html) ([pdf](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf)) Efficient Learning using Forward-Backward Splitting: [Duchi et al., 2009](http://papers.nips.cc/paper/3793-efficient-learning-using-forward-backward-splitting) ([pdf](http://papers.nips.cc/paper/3793-efficient-learning-using-forward-backward-splitting.pdf)) """ def __init__(self, learning_rate, initial_accumulator_value=0.1, l1_regularization_strength=0.0, l2_regularization_strength=0.0, use_locking=False, name="ProximalAdagrad"): """Construct a new ProximalAdagrad optimizer. Args: learning_rate: A `Tensor` or a floating point value. The learning rate. initial_accumulator_value: A floating point value. Starting value for the accumulators, must be positive. l1_regularization_strength: A float value, must be greater than or equal to zero. l2_regularization_strength: A float value, must be greater than or equal to zero. use_locking: If `True` use locks for update operations. name: Optional name prefix for the operations created when applying gradients. Defaults to "Adagrad". Raises: ValueError: If the `initial_accumulator_value` is invalid. """ if initial_accumulator_value <= 0.0: raise ValueError("initial_accumulator_value must be positive: %s" % initial_accumulator_value) super(ProximalAdagradOptimizer, self).__init__(use_locking, name) self._learning_rate = learning_rate self._initial_accumulator_value = initial_accumulator_value self._l1_regularization_strength = l1_regularization_strength self._l2_regularization_strength = l2_regularization_strength # Created in Initialize. self._l1_regularization_strength_tensor = None self._l2_regularization_strength_tensor = None self._learning_rate_tensor = None def _create_slots(self, var_list): for v in var_list: with ops.colocate_with(v): val = constant_op.constant(self._initial_accumulator_value, shape=v.get_shape(), dtype=v.dtype.base_dtype) self._get_or_make_slot(v, val, "accumulator", self._name) def _prepare(self): self._learning_rate_tensor = ops.convert_to_tensor(self._learning_rate, name="learning_rate") self._l1_regularization_strength_tensor = ops.convert_to_tensor( self._l1_regularization_strength, name="l1_regularization_strength") self._l2_regularization_strength_tensor = ops.convert_to_tensor( self._l2_regularization_strength, name="l2_regularization_strength") def _apply_dense(self, grad, var): acc = self.get_slot(var, "accumulator") return gen_training_ops.apply_proximal_adagrad( var, acc, self._learning_rate_tensor, self._l1_regularization_strength_tensor, self._l2_regularization_strength_tensor, grad, use_locking=self._use_locking) def _resource_apply_dense(self, grad, var): acc = self.get_slot(var, "accumulator") return gen_training_ops.resource_apply_proximal_adagrad( var.handle, acc.handle, self._learning_rate_tensor, self._l1_regularization_strength_tensor, self._l2_regularization_strength_tensor, grad, use_locking=self._use_locking) def _apply_sparse(self, grad, var): acc = self.get_slot(var, "accumulator") return gen_training_ops.sparse_apply_proximal_adagrad( var, acc, self._learning_rate_tensor, self._l1_regularization_strength_tensor, self._l2_regularization_strength_tensor, grad.values, grad.indices, use_locking=self._use_locking) def _resource_apply_sparse(self, grad, var, indices): acc = self.get_slot(var, "accumulator") return gen_training_ops.resource_sparse_apply_proximal_adagrad( var.handle, acc.handle, math_ops.cast(self._learning_rate_tensor, grad.dtype), math_ops.cast(self._l1_regularization_strength_tensor, grad.dtype), math_ops.cast(self._l2_regularization_strength_tensor, grad.dtype), grad, indices, use_locking=self._use_locking)
ProximalAdagradOptimizer
python
django__django
tests/null_fk/models.py
{ "start": 468, "end": 655 }
class ____(models.Model): forum = models.ForeignKey(Forum, models.SET_NULL, null=True) title = models.CharField(max_length=32) def __str__(self): return self.title
Post
python
lazyprogrammer__machine_learning_examples
rnn_class/srn_language_tf.py
{ "start": 530, "end": 7826 }
class ____: def __init__(self, D, M, V, f, session): self.D = D # dimensionality of word embedding self.M = M # hidden layer size self.V = V # vocabulary size self.f = f self.session = session def set_session(self, session): self.session = session def build(self, We, Wx, Wh, bh, h0, Wo, bo): # make them tf Variables self.We = tf.Variable(We) self.Wx = tf.Variable(Wx) self.Wh = tf.Variable(Wh) self.bh = tf.Variable(bh) self.h0 = tf.Variable(h0) self.Wo = tf.Variable(Wo) self.bo = tf.Variable(bo) self.params = [self.We, self.Wx, self.Wh, self.bh, self.h0, self.Wo, self.bo] # for easy access V = self.V D = self.D M = self.M # placeholders self.tfX = tf.placeholder(tf.int32, shape=(None,), name='X') self.tfY = tf.placeholder(tf.int32, shape=(None,), name='Y') # convert word indexes to word vectors # this would be equivalent to doing # We[tfX] in Numpy / Theano # or: # X_one_hot = one_hot_encode(X) # X_one_hot.dot(We) XW = tf.nn.embedding_lookup(We, self.tfX) # multiply it by input->hidden so we don't have to do # it inside recurrence XW_Wx = tf.matmul(XW, self.Wx) def recurrence(h_t1, XW_Wx_t): # returns h(t), y(t) h_t1 = tf.reshape(h_t1, (1, M)) h_t = self.f(XW_Wx_t + tf.matmul(h_t1, self.Wh) + self.bh) h_t = tf.reshape(h_t, (M,)) return h_t h = tf.scan( fn=recurrence, elems=XW_Wx, initializer=self.h0, ) # output logits = tf.matmul(h, self.Wo) + self.bo prediction = tf.argmax(logits, 1) self.output_probs = tf.nn.softmax(logits) nce_weights = tf.transpose(self.Wo, [1,0]) # needs to be VxD, not DxV nce_biases = self.bo h = tf.reshape(h, (-1, M)) labels = tf.reshape(self.tfY, (-1, 1)) self.cost = tf.reduce_mean( tf.nn.sampled_softmax_loss( weights=nce_weights, biases=nce_biases, labels=labels, inputs=h, num_sampled=50, # number of negative samples num_classes=V ) ) self.predict_op = prediction self.train_op = tf.train.AdamOptimizer(1e-2).minimize(self.cost) # self.train_op = tf.train.MomentumOptimizer(1e-3, 0.9).minimize(self.cost) # init all variables init = tf.global_variables_initializer() self.session.run(init) def fit(self, X, epochs=500, show_fig=False): N = len(X) D = self.D M = self.M V = self.V # initial weights We = init_weight(V, D).astype(np.float32) Wx = init_weight(D, M).astype(np.float32) Wh = init_weight(M, M).astype(np.float32) bh = np.zeros(M).astype(np.float32) h0 = np.zeros(M).astype(np.float32) Wo = init_weight(M, V).astype(np.float32) bo = np.zeros(V).astype(np.float32) # build tensorflow functions self.build(We, Wx, Wh, bh, h0, Wo, bo) # sentence input: # [START, w1, w2, ..., wn] # sentence target: # [w1, w2, w3, ..., END] costs = [] n_total = sum((len(sentence)+1) for sentence in X) for i in range(epochs): X = shuffle(X) n_correct = 0 cost = 0 for j in range(N): # problem! many words --> END token are overrepresented # result: generated lines will be very short # we will try to fix in a later iteration # BAD! magic numbers 0 and 1... input_sequence = [0] + X[j] output_sequence = X[j] + [1] # we set 0 to start and 1 to end _, c, p = self.session.run( (self.train_op, self.cost, self.predict_op), feed_dict={self.tfX: input_sequence, self.tfY: output_sequence} ) # print "p:", p cost += c # print "j:", j, "c:", c/len(X[j]+1) for pj, xj in zip(p, output_sequence): if pj == xj: n_correct += 1 print("i:", i, "cost:", cost, "correct rate:", (float(n_correct)/n_total)) costs.append(cost) if show_fig: plt.plot(costs) plt.show() def predict(self, prev_words): # don't use argmax, so that we can sample # from this probability distribution return self.session.run( self.output_probs, feed_dict={self.tfX: prev_words} ) def save(self, filename): actual_params = self.session.run(self.params) np.savez(filename, *[p for p in actual_params]) @staticmethod def load(filename, activation, session): # TODO: would prefer to save activation to file too npz = np.load(filename) We = npz['arr_0'] Wx = npz['arr_1'] Wh = npz['arr_2'] bh = npz['arr_3'] h0 = npz['arr_4'] Wo = npz['arr_5'] bo = npz['arr_6'] V, D = We.shape _, M = Wx.shape rnn = SimpleRNN(D, M, V, activation, session) rnn.build(We, Wx, Wh, bh, h0, Wo, bo) return rnn def generate(self, pi, word2idx): # convert word2idx -> idx2word idx2word = {v:k for k,v in iteritems(word2idx)} V = len(pi) # generate 4 lines at a time n_lines = 0 # why? because using the START symbol will always yield the same first word! X = [ np.random.choice(V, p=pi) ] print(idx2word[X[0]], end=" ") while n_lines < 4: probs = self.predict(X)[-1] word_idx = np.random.choice(V, p=probs) X.append(word_idx) if word_idx > 1: # it's a real word, not start/end token word = idx2word[word_idx] print(word, end=" ") elif word_idx == 1: # end token n_lines += 1 print('') if n_lines < 4: X = [ np.random.choice(V, p=pi) ] # reset to start of line print(idx2word[X[0]], end=" ") def train_poetry(session, dims, savefile): sentences, word2idx = get_robert_frost() rnn = SimpleRNN(dims, dims, len(word2idx), tf.nn.relu, session) rnn.fit(sentences, epochs=17, show_fig=True) rnn.save(savefile) def generate_poetry(session, savefile): sentences, word2idx = get_robert_frost() rnn = SimpleRNN.load(savefile, tf.nn.relu, session) # determine initial state distribution for starting sentences V = len(word2idx) pi = np.zeros(V) for sentence in sentences: pi[sentence[0]] += 1 pi /= pi.sum() rnn.generate(pi, word2idx) if __name__ == '__main__': dims = 50 savefile = 'RNN_D50_M50_tf.npz' session = tf.InteractiveSession() train_poetry(session, dims, savefile) generate_poetry(session, savefile)
SimpleRNN
python
matplotlib__matplotlib
lib/matplotlib/offsetbox.py
{ "start": 16418, "end": 19321 }
class ____(OffsetBox): """ A container to add a padding around an `.Artist`. The `.PaddedBox` contains a `.FancyBboxPatch` that is used to visualize it when rendering. .. code-block:: none +----------------------------+ | | | | | | | <--pad--> Artist | | ^ | | pad | | v | +----------------------------+ Attributes ---------- pad : float The padding in points. patch : `.FancyBboxPatch` When *draw_frame* is True, this `.FancyBboxPatch` is made visible and creates a border around the box. """ def __init__(self, child, pad=0., *, draw_frame=False, patch_attrs=None): """ Parameters ---------- child : `~matplotlib.artist.Artist` The contained `.Artist`. pad : float, default: 0.0 The padding in points. This will be scaled with the renderer dpi. In contrast, *width* and *height* are in *pixels* and thus not scaled. draw_frame : bool Whether to draw the contained `.FancyBboxPatch`. patch_attrs : dict or None Additional parameters passed to the contained `.FancyBboxPatch`. """ super().__init__() self.pad = pad self._children = [child] self.patch = FancyBboxPatch( xy=(0.0, 0.0), width=1., height=1., facecolor='w', edgecolor='k', mutation_scale=1, # self.prop.get_size_in_points(), snap=True, visible=draw_frame, boxstyle="square,pad=0", ) if patch_attrs is not None: self.patch.update(patch_attrs) def _get_bbox_and_child_offsets(self, renderer): # docstring inherited. pad = self.pad * renderer.points_to_pixels(1.) return (self._children[0].get_bbox(renderer).padded(pad), [(0, 0)]) def draw(self, renderer): # docstring inherited bbox, offsets = self._get_bbox_and_child_offsets(renderer) px, py = self.get_offset(bbox, renderer) for c, (ox, oy) in zip(self.get_visible_children(), offsets): c.set_offset((px + ox, py + oy)) self.draw_frame(renderer) for c in self.get_visible_children(): c.draw(renderer) self.stale = False def update_frame(self, bbox, fontsize=None): self.patch.set_bounds(bbox.bounds) if fontsize: self.patch.set_mutation_scale(fontsize) self.stale = True def draw_frame(self, renderer): # update the location and size of the legend self.update_frame(self.get_window_extent(renderer)) self.patch.draw(renderer)
PaddedBox
python
tensorflow__tensorflow
tensorflow/python/ops/image_ops_test.py
{ "start": 160292, "end": 164916 }
class ____(test_util.TensorFlowTestCase): def _ResizeImageWithPad(self, x, target_height, target_width, use_tensor_inputs): if use_tensor_inputs: target_height = ops.convert_to_tensor(target_height) target_width = ops.convert_to_tensor(target_width) x_tensor = ops.convert_to_tensor(x) else: x_tensor = x with self.cached_session(): return self.evaluate( image_ops.resize_image_with_pad_v2(x_tensor, target_height, target_width)) def _assertReturns(self, x, x_shape, y, y_shape, use_tensor_inputs_options=None): use_tensor_inputs_options = use_tensor_inputs_options or [False, True] target_height, target_width, _ = y_shape x = np.array(x).reshape(x_shape) y = np.array(y).reshape(y_shape) for use_tensor_inputs in use_tensor_inputs_options: y_tf = self._ResizeImageWithPad(x, target_height, target_width, use_tensor_inputs) self.assertAllClose(y, y_tf) def _assertRaises(self, x, x_shape, target_height, target_width, err_msg, use_tensor_inputs_options=None): use_tensor_inputs_options = use_tensor_inputs_options or [False, True] x = np.array(x).reshape(x_shape) for use_tensor_inputs in use_tensor_inputs_options: with self.assertRaisesRegex( (ValueError, errors.InvalidArgumentError), err_msg): self._ResizeImageWithPad(x, target_height, target_width, use_tensor_inputs) def _assertShapeInference(self, pre_shape, height, width, post_shape): image = array_ops.placeholder(dtypes.float32, shape=pre_shape) y = image_ops.resize_image_with_pad_v1(image, height, width) self.assertEqual(y.get_shape().as_list(), post_shape) def testShapeInference(self): # Shape function requires placeholders and a graph. with ops.Graph().as_default(): # Test with 3-D tensors. self._assertShapeInference([55, 66, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([50, 60, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, 66, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, 60, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([55, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([50, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([55, 66, None], 55, 66, [55, 66, None]) self._assertShapeInference([50, 60, None], 55, 66, [55, 66, None]) self._assertShapeInference([None, None, None], 55, 66, [55, 66, None]) self._assertShapeInference(None, 55, 66, [55, 66, None]) # Test with 4-D tensors. self._assertShapeInference([5, 55, 66, 3], 55, 66, [5, 55, 66, 3]) self._assertShapeInference([5, 50, 60, 3], 55, 66, [5, 55, 66, 3]) self._assertShapeInference([5, None, 66, 3], 55, 66, [5, 55, 66, 3]) self._assertShapeInference([5, None, 60, 3], 55, 66, [5, 55, 66, 3]) self._assertShapeInference([5, 55, None, 3], 55, 66, [5, 55, 66, 3]) self._assertShapeInference([5, 50, None, 3], 55, 66, [5, 55, 66, 3]) self._assertShapeInference([5, None, None, 3], 55, 66, [5, 55, 66, 3]) self._assertShapeInference([5, 55, 66, None], 55, 66, [5, 55, 66, None]) self._assertShapeInference([5, 50, 60, None], 55, 66, [5, 55, 66, None]) self._assertShapeInference([5, None, None, None], 55, 66, [5, 55, 66, None]) self._assertShapeInference([None, None, None, None], 55, 66, [None, 55, 66, None]) def testNoOp(self): x_shape = [10, 10, 10] x = np.random.uniform(size=x_shape) self._assertReturns(x, x_shape, x, x_shape) def testPad(self): # Reduce vertical dimension x = [1, 2, 3, 4, 5, 6, 7, 8] x_shape = [2, 4, 1] y = [0, 3.5, 5.5, 0] y_shape = [1, 4, 1] self._assertReturns(x, x_shape, y, y_shape) # Reduce horizontal dimension x = [1, 2, 3, 4, 5, 6, 7, 8] x_shape = [2, 4, 1] y = [3.5, 5.5, 0, 0] y_shape = [2, 2, 1] self._assertReturns(x, x_shape, y, y_shape) x = [1, 2, 3, 4, 5, 6, 7, 8] x_shape = [2, 4, 1] y = [3.5, 5.5] y_shape = [1, 2, 1] self._assertReturns(x, x_shape, y, y_shape)
ResizeImageWithPadV2Test
python
google__python-fire
fire/docstrings.py
{ "start": 3179, "end": 25023 }
class ____(enum.Enum): GOOGLE = 0 NUMPY = 1 RST = 2 SECTION_TITLES = { Sections.ARGS: ('argument', 'arg', 'parameter', 'param', 'key'), Sections.RETURNS: ('return',), Sections.YIELDS: ('yield',), Sections.RAISES: ('raise', 'except', 'exception', 'throw', 'error', 'warn'), Sections.TYPE: ('type',), # rst-only } def parse(docstring): """Returns DocstringInfo about the given docstring. This parser aims to parse Google, numpy, and rst formatted docstrings. These are the three most common docstring styles at the time of this writing. This parser aims to be permissive, working even when the docstring deviates from the strict recommendations of these styles. This parser does not aim to fully extract all structured information from a docstring, since there are simply too many ways to structure information in a docstring. Sometimes content will remain as unstructured text and simply gets included in the description. The Google docstring style guide is available at: https://github.com/google/styleguide/blob/gh-pages/pyguide.md The numpy docstring style guide is available at: https://numpydoc.readthedocs.io/en/latest/format.html Information about the rST docstring format is available at: https://www.python.org/dev/peps/pep-0287/ The full set of directives such as param and type for rST docstrings are at: http://www.sphinx-doc.org/en/master/usage/restructuredtext/domains.html Note: This function does not claim to handle all docstrings well. A list of limitations is available at the top of the file. It does aim to run without crashing in O(n) time on all strings on length n. If you find a string that causes this to crash or run unacceptably slowly, please consider submitting a pull request. Args: docstring: The docstring to parse. Returns: A DocstringInfo containing information about the docstring. """ if docstring is None: return DocstringInfo() lines = docstring.strip().split('\n') lines_len = len(lines) state = Namespace() # TODO(dbieber): Switch to an explicit class. # Variables in state include: state.section.title = None state.section.indentation = None state.section.line1_indentation = None state.section.format = None state.summary.permitted = True state.summary.lines = [] state.description.lines = [] state.args = [] state.kwargs = [] state.current_arg = None state.returns.lines = [] state.yields.lines = [] state.raises.lines = [] for index, line in enumerate(lines): has_next = index + 1 < lines_len previous_line = lines[index - 1] if index > 0 else None next_line = lines[index + 1] if has_next else None line_info = _create_line_info(line, next_line, previous_line) _consume_line(line_info, state) summary = ' '.join(state.summary.lines) if state.summary.lines else None state.description.lines = _strip_blank_lines(state.description.lines) description = textwrap.dedent('\n'.join(state.description.lines)) if not description: description = None returns = _join_lines(state.returns.lines) yields = _join_lines(state.yields.lines) raises = _join_lines(state.raises.lines) args = [ArgInfo( name=arg.name, type=_cast_to_known_type(_join_lines(arg.type.lines)), description=_join_lines(arg.description.lines)) for arg in state.args] args.extend([KwargInfo( name=arg.name, type=_cast_to_known_type(_join_lines(arg.type.lines)), description=_join_lines(arg.description.lines)) for arg in state.kwargs]) return DocstringInfo( summary=summary, description=description, args=args or None, returns=returns, raises=raises, yields=yields, ) def _strip_blank_lines(lines): """Removes lines containing only blank characters before and after the text. Args: lines: A list of lines. Returns: A list of lines without trailing or leading blank lines. """ # Find the first non-blank line. start = 0 num_lines = len(lines) while lines and start < num_lines and _is_blank(lines[start]): start += 1 lines = lines[start:] # Remove trailing blank lines. while lines and _is_blank(lines[-1]): lines.pop() return lines def _is_blank(line): return not line or line.isspace() def _join_lines(lines): """Joins lines with the appropriate connective whitespace. This puts a single space between consecutive lines, unless there's a blank line, in which case a full blank line is included. Args: lines: A list of lines to join. Returns: A string, the lines joined together. """ # TODO(dbieber): Add parameters for variations in whitespace handling. if not lines: return None started = False group_texts = [] # Full text of each section. group_lines = [] # Lines within the current section. for line in lines: stripped_line = line.strip() if stripped_line: started = True group_lines.append(stripped_line) else: if started: group_text = ' '.join(group_lines) group_texts.append(group_text) group_lines = [] if group_lines: # Process the final group. group_text = ' '.join(group_lines) group_texts.append(group_text) return '\n\n'.join(group_texts) def _get_or_create_arg_by_name(state, name, is_kwarg=False): """Gets or creates a new Arg. These Arg objects (Namespaces) are turned into the ArgInfo namedtuples returned by parse. Each Arg object is used to collect the name, type, and description of a single argument to the docstring's function. Args: state: The state of the parser. name: The name of the arg to create. is_kwarg: A boolean representing whether the argument is a keyword arg. Returns: The new Arg. """ for arg in state.args + state.kwargs: if arg.name == name: return arg arg = Namespace() # TODO(dbieber): Switch to an explicit class. arg.name = name arg.type.lines = [] arg.description.lines = [] if is_kwarg: state.kwargs.append(arg) else: state.args.append(arg) return arg def _is_arg_name(name): """Returns whether name is a valid arg name. This is used to prevent multiple words (plaintext) from being misinterpreted as an argument name. Any line that doesn't match the pattern for a valid argument is treated as not being an argument. Args: name: The name of the potential arg. Returns: True if name looks like an arg name, False otherwise. """ name = name.strip() # arg_pattern is a letter or underscore followed by # zero or more letters, numbers, or underscores. arg_pattern = r'^[a-zA-Z_]\w*$' re.match(arg_pattern, name) return re.match(arg_pattern, name) is not None def _as_arg_name_and_type(text): """Returns text as a name and type, if text looks like an arg name and type. Example: _as_arg_name_and_type("foo (int)") == "foo", "int" Args: text: The text, which may or may not be an arg name and type. Returns: The arg name and type, if text looks like an arg name and type. None otherwise. """ tokens = text.split() if len(tokens) < 2: return None if _is_arg_name(tokens[0]): type_token = ' '.join(tokens[1:]) type_token = type_token.lstrip('{([').rstrip('])}') return tokens[0], type_token else: return None def _as_arg_names(names_str): """Converts names_str to a list of arg names. Example: _as_arg_names("a, b, c") == ["a", "b", "c"] Args: names_str: A string with multiple space or comma separated arg names. Returns: A list of arg names, or None if names_str doesn't look like a list of arg names. """ names = re.split(',| ', names_str) names = [name.strip() for name in names if name.strip()] for name in names: if not _is_arg_name(name): return None if not names: return None return names def _cast_to_known_type(name): """Canonicalizes a string representing a type if possible. # TODO(dbieber): Support additional canonicalization, such as string/str, and # boolean/bool. Example: _cast_to_known_type("str.") == "str" Args: name: A string representing a type, or None. Returns: A canonicalized version of the type string. """ if name is None: return None return name.rstrip('.') def _consume_google_args_line(line_info, state): """Consume a single line from a Google args section.""" split_line = line_info.remaining.split(':', 1) if len(split_line) > 1: first, second = split_line # first is either the "arg" or "arg (type)" if _is_arg_name(first.strip()): arg = _get_or_create_arg_by_name(state, first.strip()) arg.description.lines.append(second.strip()) state.current_arg = arg else: arg_name_and_type = _as_arg_name_and_type(first) if arg_name_and_type: arg_name, type_str = arg_name_and_type arg = _get_or_create_arg_by_name(state, arg_name) arg.type.lines.append(type_str) arg.description.lines.append(second.strip()) state.current_arg = arg else: if state.current_arg: state.current_arg.description.lines.append(split_line[0]) else: if state.current_arg: state.current_arg.description.lines.append(split_line[0]) def _consume_line(line_info, state): """Consumes one line of text, updating the state accordingly. When _consume_line is called, part of the line may already have been processed for header information. Args: line_info: Information about the current and next line of the docstring. state: The state of the docstring parser. """ _update_section_state(line_info, state) if state.section.title is None: if state.summary.permitted: if line_info.remaining: state.summary.lines.append(line_info.remaining) elif state.summary.lines: state.summary.permitted = False else: # We're past the end of the summary. # Additions now contribute to the description. state.description.lines.append(line_info.remaining_raw) else: state.summary.permitted = False if state.section.new and state.section.format == Formats.RST: # The current line starts with an RST directive, e.g. ":param arg:". directive = _get_directive(line_info) directive_tokens = directive.split() if state.section.title == Sections.ARGS: name = directive_tokens[-1] arg = _get_or_create_arg_by_name( state, name, is_kwarg=directive_tokens[0] == 'key' ) if len(directive_tokens) == 3: # A param directive of the form ":param type arg:". arg.type.lines.append(directive_tokens[1]) state.current_arg = arg elif state.section.title == Sections.TYPE: name = directive_tokens[-1] arg = _get_or_create_arg_by_name(state, name) state.current_arg = arg if (state.section.format == Formats.NUMPY and _line_is_hyphens(line_info.remaining)): # Skip this all-hyphens line, which is part of the numpy section header. return if state.section.title == Sections.ARGS: if state.section.format == Formats.GOOGLE: _consume_google_args_line(line_info, state) elif state.section.format == Formats.RST: state.current_arg.description.lines.append(line_info.remaining.strip()) elif state.section.format == Formats.NUMPY: line_stripped = line_info.remaining.strip() if _is_arg_name(line_stripped): # Token on its own line can either be the last word of the description # of the previous arg, or a new arg. TODO: Whitespace can distinguish. arg = _get_or_create_arg_by_name(state, line_stripped) state.current_arg = arg elif _line_is_numpy_parameter_type(line_info): possible_args, type_data = line_stripped.split(':', 1) arg_names = _as_arg_names(possible_args) # re.split(' |,', s) if arg_names: for arg_name in arg_names: arg = _get_or_create_arg_by_name(state, arg_name) arg.type.lines.append(type_data) state.current_arg = arg # TODO(dbieber): Multiple current args. else: # Just an ordinary line. if state.current_arg: state.current_arg.description.lines.append( line_info.remaining.strip()) else: # TODO(dbieber): If not a blank line, add it to the description. pass else: # Just an ordinary line. if state.current_arg: state.current_arg.description.lines.append( line_info.remaining.strip()) else: # TODO(dbieber): If not a blank line, add it to the description. pass elif state.section.title == Sections.RETURNS: state.returns.lines.append(line_info.remaining.strip()) elif state.section.title == Sections.YIELDS: state.yields.lines.append(line_info.remaining.strip()) elif state.section.title == Sections.RAISES: state.raises.lines.append(line_info.remaining.strip()) elif state.section.title == Sections.TYPE: if state.section.format == Formats.RST: assert state.current_arg is not None state.current_arg.type.lines.append(line_info.remaining.strip()) else: pass def _create_line_info(line, next_line, previous_line): """Returns information about the current line and surrounding lines.""" line_info = Namespace() # TODO(dbieber): Switch to an explicit class. line_info.line = line line_info.stripped = line.strip() line_info.remaining_raw = line_info.line line_info.remaining = line_info.stripped line_info.indentation = len(line) - len(line.lstrip()) # TODO(dbieber): If next_line is blank, use the next non-blank line. line_info.next.line = next_line next_line_exists = next_line is not None line_info.next.stripped = next_line.strip() if next_line_exists else None line_info.next.indentation = ( len(next_line) - len(next_line.lstrip()) if next_line_exists else None) line_info.previous.line = previous_line previous_line_exists = previous_line is not None line_info.previous.indentation = ( len(previous_line) - len(previous_line.lstrip()) if previous_line_exists else None) # Note: This counts all whitespace equally. return line_info def _update_section_state(line_info, state): """Uses line_info to determine the current section of the docstring. Updates state and line_info.remaining. Args: line_info: Information about the current line. state: The state of the parser. """ section_updated = False google_section_permitted = _google_section_permitted(line_info, state) google_section = google_section_permitted and _google_section(line_info) if google_section: state.section.format = Formats.GOOGLE state.section.title = google_section line_info.remaining = _get_after_google_header(line_info) line_info.remaining_raw = line_info.remaining section_updated = True rst_section = _rst_section(line_info) if rst_section: state.section.format = Formats.RST state.section.title = rst_section line_info.remaining = _get_after_directive(line_info) line_info.remaining_raw = line_info.remaining section_updated = True numpy_section = _numpy_section(line_info) if numpy_section: state.section.format = Formats.NUMPY state.section.title = numpy_section line_info.remaining = '' line_info.remaining_raw = line_info.remaining section_updated = True if section_updated: state.section.new = True state.section.indentation = line_info.indentation state.section.line1_indentation = line_info.next.indentation else: state.section.new = False def _google_section_permitted(line_info, state): """Returns whether a new google section is permitted to start here. Q: Why might a new Google section not be allowed? A: If we're in the middle of a Google "Args" section, then lines that start "param:" will usually be a new arg, rather than a new section. We use whitespace to determine when the Args section has actually ended. A Google section ends when either: - A new google section begins at either - indentation less than indentation of line 1 of the previous section - or <= indentation of the previous section - Or the docstring terminates. Args: line_info: Information about the current line. state: The state of the parser. Returns: True or False, indicating whether a new Google section is permitted at the current line. """ if state.section.indentation is None: # We're not in a section yet. return True return (line_info.indentation <= state.section.indentation or line_info.indentation < state.section.line1_indentation) def _matches_section_title(title, section_title): """Returns whether title is a match for a specific section_title. Example: _matches_section_title('Yields', 'yield') == True Args: title: The title to check for matching. section_title: A specific known section title to check against. """ title = title.lower() section_title = section_title.lower() return section_title in (title, title[:-1]) # Supports plurals / some typos. def _matches_section(title, section): """Returns whether title is a match any known title for a specific section. Example: _matches_section_title('Yields', Sections.YIELDS) == True _matches_section_title('param', Sections.Args) == True Args: title: The title to check for matching. section: A specific section to check all possible titles for. Returns: True or False, indicating whether title is a match for the specified section. """ for section_title in SECTION_TITLES[section]: if _matches_section_title(title, section_title): return True return False def _section_from_possible_title(possible_title): """Returns a section matched by the possible title, or None if none match. Args: possible_title: A string that may be the title of a new section. Returns: A Section type if one matches, or None if no section type matches. """ for section in SECTION_TITLES: if _matches_section(possible_title, section): return section return None def _google_section(line_info): """Checks whether the current line is the start of a new Google-style section. This docstring is a Google-style docstring. Google-style sections look like this: Section Name: section body goes here Args: line_info: Information about the current line. Returns: A Section type if one matches, or None if no section type matches. """ colon_index = line_info.remaining.find(':') possible_title = line_info.remaining[:colon_index] return _section_from_possible_title(possible_title) def _get_after_google_header(line_info): """Gets the remainder of the line, after a Google header.""" colon_index = line_info.remaining.find(':') return line_info.remaining[colon_index + 1:] def _get_directive(line_info): """Gets a directive from the start of the line. If the line is ":param str foo: Description of foo", then _get_directive(line_info) returns "param str foo". Args: line_info: Information about the current line. Returns: The contents of a directive, or None if the line doesn't start with a directive. """ if line_info.stripped.startswith(':'): return line_info.stripped.split(':', 2)[1] else: return None def _get_after_directive(line_info): """Gets the remainder of the line, after a directive.""" sections = line_info.stripped.split(':', 2) if len(sections) > 2: return sections[-1] else: return '' def _rst_section(line_info): """Checks whether the current line is the start of a new RST-style section. RST uses directives to specify information. An RST directive, which we refer to as a section here, are surrounded with colons. For example, :param name:. Args: line_info: Information about the current line. Returns: A Section type if one matches, or None if no section type matches. """ directive = _get_directive(line_info) if directive: possible_title = directive.split()[0] return _section_from_possible_title(possible_title) else: return None def _line_is_hyphens(line): """Returns whether the line is entirely hyphens (and not blank).""" return line and not line.strip('-') def _numpy_section(line_info): """Checks whether the current line is the start of a new numpy-style section. Numpy style sections are followed by a full line of hyphens, for example: Section Name ------------ Section body goes here. Args: line_info: Information about the current line. Returns: A Section type if one matches, or None if no section type matches. """ next_line_is_hyphens = _line_is_hyphens(line_info.next.stripped) if next_line_is_hyphens: possible_title = line_info.remaining return _section_from_possible_title(possible_title) else: return None def _line_is_numpy_parameter_type(line_info): """Returns whether the line contains a numpy style parameter type definition. We look for a line of the form: x : type And we have to exclude false positives on argument descriptions containing a colon by checking the indentation of the line above. Args: line_info: Information about the current line. Returns: True if the line is a numpy parameter type definition, False otherwise. """ line_stripped = line_info.remaining.strip() if ':' in line_stripped: previous_indent = line_info.previous.indentation current_indent = line_info.indentation if ':' in line_info.previous.line and current_indent > previous_indent: # The parameter type was the previous line; this is the description. return False else: return True return False
Formats
python
allegroai__clearml
clearml/backend_api/services/v2_23/events.py
{ "start": 113843, "end": 117343 }
class ____(Response): """ Response of events.get_task_events endpoint. :param events: Events list :type events: Sequence[dict] :param returned: Number of results returned :type returned: int :param total: Total number of results available for this query. In case there are more than 10000 results it is set to 10000 :type total: float :param scroll_id: Scroll ID for getting more results :type scroll_id: str """ _service = "events" _action = "get_task_events" _version = "2.23" _schema = { "definitions": {}, "properties": { "events": { "description": "Events list", "items": {"type": "object"}, "type": ["array", "null"], }, "returned": { "description": "Number of results returned", "type": ["integer", "null"], }, "scroll_id": { "description": "Scroll ID for getting more results", "type": ["string", "null"], }, "total": { "description": "Total number of results available for this query. In case there are more than 10000 results it is set to 10000", "type": ["number", "null"], }, }, "type": "object", } def __init__( self, events: Optional[List[dict]] = None, returned: Optional[int] = None, total: Optional[float] = None, scroll_id: Optional[str] = None, **kwargs: Any ) -> None: super(GetTaskEventsResponse, self).__init__(**kwargs) self.events = events self.returned = returned self.total = total self.scroll_id = scroll_id @schema_property("events") def events(self) -> Optional[List[dict]]: return self._property_events @events.setter def events(self, value: Optional[List[dict]]) -> None: if value is None: self._property_events = None return self.assert_isinstance(value, "events", (list, tuple)) self.assert_isinstance(value, "events", (dict,), is_array=True) self._property_events = value @schema_property("returned") def returned(self) -> Optional[int]: return self._property_returned @returned.setter def returned(self, value: Optional[int]) -> None: if value is None: self._property_returned = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "returned", six.integer_types) self._property_returned = value @schema_property("total") def total(self) -> Optional[float]: return self._property_total @total.setter def total(self, value: Optional[float]) -> None: if value is None: self._property_total = None return self.assert_isinstance(value, "total", six.integer_types + (float,)) self._property_total = value @schema_property("scroll_id") def scroll_id(self) -> Optional[str]: return self._property_scroll_id @scroll_id.setter def scroll_id(self, value: Optional[str]) -> None: if value is None: self._property_scroll_id = None return self.assert_isinstance(value, "scroll_id", six.string_types) self._property_scroll_id = value
GetTaskEventsResponse
python
astropy__astropy
astropy/nddata/mixins/ndslicing.py
{ "start": 340, "end": 4478 }
class ____: """Mixin to provide slicing on objects using the `NDData` interface. The ``data``, ``mask``, ``uncertainty`` and ``wcs`` will be sliced, if set and sliceable. The ``unit`` and ``meta`` will be untouched. The return will be a reference and not a copy, if possible. Examples -------- Using this Mixin with `~astropy.nddata.NDData`: >>> from astropy.nddata import NDData, NDSlicingMixin >>> class NDDataSliceable(NDSlicingMixin, NDData): ... pass Slicing an instance containing data:: >>> nd = NDDataSliceable([1,2,3,4,5]) >>> nd[1:3] NDDataSliceable([2, 3]) Also the other attributes are sliced for example the ``mask``:: >>> import numpy as np >>> mask = np.array([True, False, True, True, False]) >>> nd2 = NDDataSliceable(nd, mask=mask) >>> nd2slc = nd2[1:3] >>> nd2slc[nd2slc.mask] NDDataSliceable([—]) Be aware that changing values of the sliced instance will change the values of the original:: >>> nd3 = nd2[1:3] >>> nd3.data[0] = 100 >>> nd2 NDDataSliceable([———, 100, ———, ———, 5]) See Also -------- NDDataRef NDDataArray """ def __getitem__(self, item): # Abort slicing if the data is a single scalar. if self.data.shape == (): raise TypeError("scalars cannot be sliced.") # Let the other methods handle slicing. kwargs = self._slice(item) return self.__class__(**kwargs) def _slice(self, item): """Collects the sliced attributes and passes them back as `dict`. It passes uncertainty, mask and wcs to their appropriate ``_slice_*`` method, while ``meta`` and ``unit`` are simply taken from the original. The data is assumed to be sliceable and is sliced directly. When possible the return should *not* be a copy of the data but a reference. Parameters ---------- item : slice The slice passed to ``__getitem__``. Returns ------- dict : Containing all the attributes after slicing - ready to use them to create ``self.__class__.__init__(**kwargs)`` in ``__getitem__``. """ kwargs = {} kwargs["data"] = self.data[item] # Try to slice some attributes kwargs["uncertainty"] = self._slice_uncertainty(item) kwargs["mask"] = self._slice_mask(item) kwargs["wcs"] = self._slice_wcs(item) # Attributes which are copied and not intended to be sliced kwargs["unit"] = self.unit kwargs["meta"] = self.meta return kwargs def _slice_uncertainty(self, item): if self.uncertainty is None: return None try: return self.uncertainty[item] except (TypeError, KeyError): # Catching TypeError in case the object has no __getitem__ method. # Catching KeyError for Python 3.12. # But let IndexError raise. log.info("uncertainty cannot be sliced.") return self.uncertainty def _slice_mask(self, item): if self.mask is None: return None try: return self.mask[item] except (TypeError, KeyError): log.info("mask cannot be sliced.") return self.mask def _slice_wcs(self, item): if self.wcs is None: return None try: llwcs = SlicedLowLevelWCS(self.wcs.low_level_wcs, item) return HighLevelWCSWrapper(llwcs) except Exception as err: self._handle_wcs_slicing_error(err, item) # Implement this in a method to allow subclasses to customise the error. def _handle_wcs_slicing_error(self, err, item): raise ValueError( f"Slicing the WCS object with the slice '{item}' " "failed, if you want to slice the NDData object without the WCS, you " "can remove by setting `NDData.wcs = None` and then retry." ) from err
NDSlicingMixin
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 14261, "end": 14436 }
class ____(models.Model): """A series of works, like a trilogy of books.""" name = models.CharField(max_length=100) author = models.CharField(max_length=100)
Series
python
pypa__warehouse
tests/unit/utils/test_wsgi.py
{ "start": 6173, "end": 8283 }
class ____: def test_removes_header(self): response = pretend.stub() app = pretend.call_recorder(lambda e, s: response) environ = {"HTTP_X_VHM_ROOT": "/foo/bar"} start_response = pretend.stub() resp = wsgi.VhmRootRemover(app)(environ, start_response) assert resp is response assert app.calls == [pretend.call({}, start_response)] def test_passes_through_headers(self): response = pretend.stub() app = pretend.call_recorder(lambda e, s: response) environ = {"HTTP_X_FOOBAR": "wat"} start_response = pretend.stub() resp = wsgi.VhmRootRemover(app)(environ, start_response) assert resp is response assert app.calls == [pretend.call({"HTTP_X_FOOBAR": "wat"}, start_response)] def test_ip_address_exists(db_request): ip_address = DBIpAddressFactory(ip_address="192.0.2.69") db_request.environ["REMOTE_ADDR"] = "192.0.2.69" db_request.remote_addr = "192.0.2.69" assert wsgi._ip_address(db_request) == ip_address def test_ip_address_created(db_request): with pytest.raises(NoResultFound): db_request.db.query(IpAddress).filter_by( ip_address=type_coerce("192.0.2.69", INET) ).one() db_request.environ["GEOIP_CITY"] = "Anytown, ST" db_request.remote_addr = "192.0.2.69" db_request.remote_addr_hashed = "deadbeef" wsgi._ip_address(db_request) ip_address = ( db_request.db.query(IpAddress) .filter_by(ip_address=type_coerce("192.0.2.69", INET)) .one() ) assert str(ip_address.ip_address) == "192.0.2.69" assert ip_address.hashed_ip_address == "deadbeef" assert ip_address.geoip_info == {"city": "Anytown, ST"} def test_remote_addr_hashed(): environ = {"REMOTE_ADDR_HASHED": REMOTE_ADDR_HASHED} request = pretend.stub(environ=environ) assert wsgi._remote_addr_hashed(request) == REMOTE_ADDR_HASHED def test_remote_addr_hashed_missing(): environ = {} request = pretend.stub(environ=environ) assert wsgi._remote_addr_hashed(request) == ""
TestVhmRootRemover
python
google__jax
tests/pallas/tpu_sparsecore_pallas_test.py
{ "start": 57088, "end": 57168 }
class ____(TCTilingMixin, VectorSubcoreTest): pass
VectorSubcoreTestWithTCTiling
python
tornadoweb__tornado
tornado/test/httpserver_test.py
{ "start": 1847, "end": 2158 }
class ____(AsyncHTTPTestCase): Handler = None def get_app(self): return Application([("/", self.__class__.Handler)]) def fetch_json(self, *args, **kwargs): response = self.fetch(*args, **kwargs) response.rethrow() return json_decode(response.body)
HandlerBaseTestCase
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/fftw/package.py
{ "start": 216, "end": 719 }
class ____(Package): """Used to test that a few problematic concretization cases with the old concretizer have been solved by the new ones. """ homepage = "http://www.example.com" url = "http://www.example.com/fftw-1.0.tar.gz" version("2.0", md5="abcdef1234567890abcdef1234567890") version("1.0", md5="1234567890abcdef1234567890abcdef") variant("mpi", default=False, description="Enable MPI") depends_on("c", type="build") depends_on("mpi", when="+mpi")
Fftw
python
weaviate__weaviate-python-client
weaviate/collections/classes/config.py
{ "start": 10687, "end": 11013 }
class ____(_GenerativeProvider): generative: Union[GenerativeSearches, _EnumLikeStr] = Field( default=GenerativeSearches.DATABRICKS, frozen=True, exclude=True ) endpoint: str maxTokens: Optional[int] temperature: Optional[float] topK: Optional[int] topP: Optional[float]
_GenerativeDatabricks
python
instagram__MonkeyType
tests/test_typing.py
{ "start": 24855, "end": 24945 }
class ____: """A name conflict that is not generic.""" pass T = TypeVar("T")
Tuple
python
ray-project__ray
python/ray/experimental/raysort/tracing_utils.py
{ "start": 1950, "end": 3456 }
class ____: def __init__( self, gauges: List[str], histograms: List[Tuple[str, List[int]]], ): self.counts = {m: 0 for m in gauges} self.gauges = {m: Gauge(m) for m in gauges} self.reset_gauges() self.histograms = {m: Histogram(m, boundaries=b) for m, b in histograms} logging_utils.init() def reset_gauges(self): for g in self.gauges.values(): g.set(0) def inc(self, metric_name, value=1, echo=False): gauge = self.gauges.get(metric_name) if gauge is None: logging.warning(f"No such Gauge: {metric_name}") return self.counts[metric_name] += value gauge.set(self.counts[metric_name]) if echo: logging.info(f"{metric_name} {self.counts[metric_name]}") def dec(self, metric_name, value=1, echo=False): return self.inc(metric_name, -value, echo) def observe(self, metric_name, value, echo=False): histogram = self.histograms.get(metric_name) if histogram is None: logging.warning(f"No such Histogram: {metric_name}") return histogram.observe(value) if echo: logging.info(f"{metric_name} {value}") def export_timeline(): timestr = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") filename = f"/tmp/ray-timeline-{timestr}.json" ray.timeline(filename=filename) logging.info(f"Exported Ray timeline to {filename}")
ProgressTracker
python
kamyu104__LeetCode-Solutions
Python/maximum-total-importance-of-roads.py
{ "start": 1139, "end": 1492 }
class ____(object): def maximumImportance(self, n, roads): """ :type n: int :type roads: List[List[int]] :rtype: int """ degree = [0]*n for a, b in roads: degree[a] += 1 degree[b] += 1 degree.sort() return sum(i*x for i, x in enumerate(degree, 1))
Solution2
python
kamyu104__LeetCode-Solutions
Python/number-of-people-that-can-be-seen-in-a-grid.py
{ "start": 76, "end": 1025 }
class ____(object): def seePeople(self, heights): """ :type heights: List[List[int]] :rtype: List[List[int]] """ def count(h, stk): cnt = 0 while stk and stk[-1] < h: stk.pop() cnt += 1 if stk: cnt += 1 if not stk or stk[-1] != h: stk.append(h) return cnt result = [[0]*len(heights[0]) for _ in xrange(len(heights))] for i in xrange(len(heights)): stk = [] for j in reversed(xrange(len(heights[0]))): result[i][j] += count(heights[i][j], stk) for j in xrange(len(heights[0])): stk = [] for i in reversed(xrange(len(heights))): result[i][j] += count(heights[i][j], stk) return result # Time: O(m * n) # Space: O(m + n) # mono stack
Solution
python
django__django
tests/test_runner/runner.py
{ "start": 48, "end": 862 }
class ____(DiscoverRunner): def __init__( self, verbosity=1, interactive=True, failfast=True, option_a=None, option_b=None, option_c=None, **kwargs, ): super().__init__( verbosity=verbosity, interactive=interactive, failfast=failfast ) self.option_a = option_a self.option_b = option_b self.option_c = option_c @classmethod def add_arguments(cls, parser): parser.add_argument("--option_a", "-a", default="1") parser.add_argument("--option_b", "-b", default="2") parser.add_argument("--option_c", "-c", default="3") def run_tests(self, test_labels, **kwargs): print("%s:%s:%s" % (self.option_a, self.option_b, self.option_c))
CustomOptionsTestRunner
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/exc.py
{ "start": 24183, "end": 24279 }
class ____(DBAPIError): """Wraps a DB-API InterfaceError.""" code = "rvf5"
InterfaceError
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/solver14.py
{ "start": 1052, "end": 1478 }
class ____(Protocol): def __lt__(self, __other: Any) -> bool: ... SupportsLessThanT = TypeVar("SupportsLessThanT", bound=SupportsLessThan) def max2(__arg1: SupportsLessThanT, __arg2: SupportsLessThanT) -> SupportsLessThanT: ... def min2(__arg1: SupportsLessThanT, __arg2: SupportsLessThanT) -> SupportsLessThanT: ... def func1(): x = max2(1, min2(1, 4.5)) reveal_type(x, expected_text="float")
SupportsLessThan
python
kamyu104__LeetCode-Solutions
Python/patching-array.py
{ "start": 662, "end": 1333 }
class ____(object): def minPatches(self, nums, n): """ :type nums: List[int] :type n: int :rtype: int """ result = reachable = 0 for x in nums: while not reachable >= x-1: result += 1 reachable += reachable+1 if reachable >= n: return result reachable += x if reachable >= n: return result while not reachable >= n: result += 1 reachable += reachable+1 return result # Time: O(s + logn), s is the number of elements in the array # Space: O(1)
Solution2
python
google__pytype
pytype/tests/test_tracebacks2.py
{ "start": 95, "end": 453 }
class ____(test_base.BaseTest): """Tests for tracebacks in error messages.""" def test_build_class(self): errors = self.CheckWithErrors(""" class Foo: def f(self, x: Bar): # name-error[e] pass """) self.assertErrorRegexes(errors, {"e": r"Bar.*not defined$"}) if __name__ == "__main__": test_base.main()
TracebackTest
python
ray-project__ray
python/ray/serve/tests/unit/test_schema.py
{ "start": 6048, "end": 13770 }
class ____: def get_minimal_deployment_schema(self): # Generate a DeploymentSchema with the fewest possible attributes set return {"name": "deep"} def test_valid_deployment_schema(self): # Ensure a valid DeploymentSchema can be generated deployment_schema = { "name": "shallow", "num_replicas": 2, "route_prefix": "/shallow", "max_queued_requests": 12, "user_config": {"threshold": 0.2, "pattern": "rainbow"}, "autoscaling_config": None, "graceful_shutdown_wait_loop_s": 17, "graceful_shutdown_timeout_s": 49, "health_check_period_s": 11, "health_check_timeout_s": 11, "max_ongoing_requests": 32, "ray_actor_options": { "runtime_env": { "working_dir": TEST_MODULE_PINNED_URI, "py_modules": [TEST_DEPLOY_GROUP_PINNED_URI], }, "num_cpus": 3, "num_gpus": 4.2, "memory": 5, "resources": {"custom_asic": 8}, "accelerator_type": NVIDIA_TESLA_P4, }, } DeploymentSchema.parse_obj(deployment_schema) def test_gt_zero_deployment_schema(self): # Ensure ValidationError is raised when any fields that must be greater # than zero is set to zero. deployment_schema = self.get_minimal_deployment_schema() gt_zero_fields = [ "num_replicas", "max_ongoing_requests", "health_check_period_s", "health_check_timeout_s", ] for field in gt_zero_fields: deployment_schema[field] = 0 with pytest.raises(ValidationError): DeploymentSchema.parse_obj(deployment_schema) deployment_schema[field] = None def test_ge_zero_deployment_schema(self): # Ensure ValidationError is raised when any fields that must be greater # than or equal to zero is set to -1. deployment_schema = self.get_minimal_deployment_schema() ge_zero_fields = [ "graceful_shutdown_wait_loop_s", "graceful_shutdown_timeout_s", ] for field in ge_zero_fields: deployment_schema[field] = -1 with pytest.raises(ValidationError): DeploymentSchema.parse_obj(deployment_schema) deployment_schema[field] = None def test_validate_max_queued_requests(self): # Ensure ValidationError is raised when max_queued_requests is not -1 or > 1. deployment_schema = self.get_minimal_deployment_schema() deployment_schema["max_queued_requests"] = -1 DeploymentSchema.parse_obj(deployment_schema) deployment_schema["max_queued_requests"] = 1 DeploymentSchema.parse_obj(deployment_schema) deployment_schema["max_queued_requests"] = 100 DeploymentSchema.parse_obj(deployment_schema) deployment_schema["max_queued_requests"] = "hi" with pytest.raises(ValidationError): DeploymentSchema.parse_obj(deployment_schema) deployment_schema["max_queued_requests"] = 1.5 with pytest.raises(ValidationError): DeploymentSchema.parse_obj(deployment_schema) deployment_schema["max_queued_requests"] = 0 with pytest.raises(ValidationError): DeploymentSchema.parse_obj(deployment_schema) deployment_schema["max_queued_requests"] = -2 with pytest.raises(ValidationError): DeploymentSchema.parse_obj(deployment_schema) deployment_schema["max_queued_requests"] = -100 with pytest.raises(ValidationError): DeploymentSchema.parse_obj(deployment_schema) def test_mutually_exclusive_num_replicas_and_autoscaling_config(self): # num_replicas and autoscaling_config cannot be set at the same time deployment_schema = self.get_minimal_deployment_schema() deployment_schema["num_replicas"] = 5 deployment_schema["autoscaling_config"] = None DeploymentSchema.parse_obj(deployment_schema) deployment_schema["num_replicas"] = None deployment_schema["autoscaling_config"] = AutoscalingConfig().dict() DeploymentSchema.parse_obj(deployment_schema) deployment_schema["num_replicas"] = 5 deployment_schema["autoscaling_config"] = AutoscalingConfig().dict() with pytest.raises(ValueError): DeploymentSchema.parse_obj(deployment_schema) def test_mutually_exclusive_max_replicas_per_node_and_placement_group_bundles(self): # max_replicas_per_node and placement_group_bundles # cannot be set at the same time deployment_schema = self.get_minimal_deployment_schema() deployment_schema["max_replicas_per_node"] = 5 deployment_schema.pop("placement_group_bundles", None) DeploymentSchema.parse_obj(deployment_schema) deployment_schema.pop("max_replicas_per_node", None) deployment_schema["placement_group_bundles"] = [{"GPU": 1}, {"GPU": 1}] DeploymentSchema.parse_obj(deployment_schema) deployment_schema["max_replicas_per_node"] = 5 deployment_schema["placement_group_bundles"] = [{"GPU": 1}, {"GPU": 1}] with pytest.raises( ValueError, match=( "Setting max_replicas_per_node is not allowed when " "placement_group_bundles is provided." ), ): DeploymentSchema.parse_obj(deployment_schema) def test_num_replicas_auto(self): deployment_schema = self.get_minimal_deployment_schema() deployment_schema["num_replicas"] = "auto" deployment_schema["autoscaling_config"] = None DeploymentSchema.parse_obj(deployment_schema) deployment_schema["num_replicas"] = "auto" deployment_schema["autoscaling_config"] = {"max_replicas": 99} DeploymentSchema.parse_obj(deployment_schema) deployment_schema["num_replicas"] = "random_str" deployment_schema["autoscaling_config"] = None with pytest.raises(ValueError): DeploymentSchema.parse_obj(deployment_schema) def test_extra_fields_invalid_deployment_schema(self): # Undefined fields should be forbidden in the schema deployment_schema = self.get_minimal_deployment_schema() # Schema should be createable with valid fields DeploymentSchema.parse_obj(deployment_schema) # Schema should NOT raise error when extra field is included deployment_schema["extra_field"] = None DeploymentSchema.parse_obj(deployment_schema) def test_user_config_nullable(self): deployment_options = {"name": "test", "user_config": None} DeploymentSchema.parse_obj(deployment_options) def test_autoscaling_config_nullable(self): deployment_options = { "name": "test", "autoscaling_config": None, "num_replicas": 5, } DeploymentSchema.parse_obj(deployment_options) def test_route_prefix_nullable(self): deployment_options = {"name": "test", "route_prefix": None} DeploymentSchema.parse_obj(deployment_options) def test_num_replicas_nullable(self): deployment_options = { "name": "test", "num_replicas": None, "autoscaling_config": { "min_replicas": 1, "max_replicas": 5, "target_ongoing_requests": 5, }, } DeploymentSchema.parse_obj(deployment_options)
TestDeploymentSchema
python
huggingface__transformers
src/transformers/models/qwen2_vl/modeling_qwen2_vl.py
{ "start": 40685, "end": 58695 }
class ____(Qwen2VLPreTrainedModel): base_model_prefix = "model" _checkpoint_conversion_mapping = {"^model": "language_model"} # Reference: fix gemma3 grad acc #37208 accepts_loss_kwargs = False def __init__(self, config: Qwen2VLConfig): super().__init__(config) self.visual = Qwen2VisionTransformerPretrainedModel._from_config(config.vision_config) self.language_model = Qwen2VLTextModel._from_config(config.text_config) self.rope_deltas = None # cache rope_deltas here # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.language_model.get_input_embeddings() def set_input_embeddings(self, value): self.language_model.set_input_embeddings(value) def get_rope_index( self, input_ids: Optional[torch.LongTensor] = None, image_grid_thw: Optional[torch.LongTensor] = None, video_grid_thw: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, ) -> tuple[torch.Tensor, torch.Tensor]: """ Calculate the 3D rope index based on image and video's temporal, height and width in LLM. Explanation: Each embedding sequence contains vision embedding and text embedding or just contains text embedding. For pure text embedding sequence, the rotary position embedding has no difference with modern LLMs. Examples: input_ids: [T T T T T], here T is for text. temporal position_ids: [0, 1, 2, 3, 4] height position_ids: [0, 1, 2, 3, 4] width position_ids: [0, 1, 2, 3, 4] For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part and 1D rotary position embedding for text part. Examples: Assume we have a video input with 3 temporal patches, 2 height patches and 2 width patches. input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision. vision temporal position_ids: [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2] vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1] vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] text temporal position_ids: [3, 4, 5, 6, 7] text height position_ids: [3, 4, 5, 6, 7] text width position_ids: [3, 4, 5, 6, 7] Here we calculate the text start position_ids as the max vision position_ids plus 1. Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*): The temporal, height and width of feature shape of each image in LLM. video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*): The temporal, height and width of feature shape of each video in LLM. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. Returns: position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`) mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`) """ spatial_merge_size = self.config.vision_config.spatial_merge_size image_token_id = self.config.image_token_id video_token_id = self.config.video_token_id vision_start_token_id = self.config.vision_start_token_id mrope_position_deltas = [] if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None): total_input_ids = input_ids if attention_mask is None: attention_mask = torch.ones_like(total_input_ids) position_ids = torch.ones( 3, input_ids.shape[0], input_ids.shape[1], dtype=input_ids.dtype, device=input_ids.device ) image_index, video_index = 0, 0 for i, input_ids in enumerate(total_input_ids): input_ids = input_ids[attention_mask[i].to(input_ids.device) == 1] image_nums, video_nums = 0, 0 vision_start_indices = torch.argwhere(input_ids == vision_start_token_id).squeeze(1) vision_tokens = input_ids[vision_start_indices + 1] image_nums = (vision_tokens == image_token_id).sum() video_nums = (vision_tokens == video_token_id).sum() input_tokens = input_ids.tolist() llm_pos_ids_list: list = [] st = 0 remain_images, remain_videos = image_nums, video_nums for _ in range(image_nums + video_nums): if image_token_id in input_tokens and remain_images > 0: ed_image = input_tokens.index(image_token_id, st) else: ed_image = len(input_tokens) + 1 if video_token_id in input_tokens and remain_videos > 0: ed_video = input_tokens.index(video_token_id, st) else: ed_video = len(input_tokens) + 1 if ed_image < ed_video: t, h, w = ( image_grid_thw[image_index][0], image_grid_thw[image_index][1], image_grid_thw[image_index][2], ) image_index += 1 remain_images -= 1 ed = ed_image else: t, h, w = ( video_grid_thw[video_index][0], video_grid_thw[video_index][1], video_grid_thw[video_index][2], ) video_index += 1 remain_videos -= 1 ed = ed_video llm_grid_t, llm_grid_h, llm_grid_w = ( t.item(), h.item() // spatial_merge_size, w.item() // spatial_merge_size, ) text_len = ed - st st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) t_index = torch.arange(llm_grid_t).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w).flatten() h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten() w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten() llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx) st = ed + llm_grid_t * llm_grid_h * llm_grid_w if st < len(input_tokens): st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 text_len = len(input_tokens) - st llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1) position_ids[..., i, attention_mask[i] == 1] = llm_positions.to(position_ids.device) mrope_position_deltas.append(llm_positions.max() + 1 - len(total_input_ids[i])) mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1) return position_ids, mrope_position_deltas else: if attention_mask is not None: position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) position_ids = position_ids.unsqueeze(0).expand(3, -1, -1).to(attention_mask.device) max_position_ids = position_ids.max(0, keepdim=False)[0].max(-1, keepdim=True)[0] mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1] else: position_ids = ( torch.arange(input_ids.shape[1], device=input_ids.device) .view(1, 1, -1) .expand(3, input_ids.shape[0], -1) ) mrope_position_deltas = torch.zeros( [input_ids.shape[0], 1], device=input_ids.device, dtype=input_ids.dtype, ) return position_ids, mrope_position_deltas def get_video_features( self, pixel_values_videos: torch.FloatTensor, video_grid_thw: Optional[torch.LongTensor] = None ): """ Encodes videos into continuous embeddings that can be forwarded to the language model. Args: pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`): The tensors corresponding to the input videos. video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*): The temporal, height and width of feature shape of each video in LLM. """ pixel_values_videos = pixel_values_videos.type(self.visual.dtype) video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw) split_sizes = (video_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist() video_embeds = torch.split(video_embeds, split_sizes) return video_embeds def get_image_features(self, pixel_values: torch.FloatTensor, image_grid_thw: Optional[torch.LongTensor] = None): """ Encodes images into continuous embeddings that can be forwarded to the language model. Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`): The tensors corresponding to the input images. image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*): The temporal, height and width of feature shape of each image in LLM. """ pixel_values = pixel_values.type(self.visual.dtype) image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw) split_sizes = (image_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist() image_embeds = torch.split(image_embeds, split_sizes) return image_embeds def get_placeholder_mask( self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: Optional[torch.FloatTensor] = None, video_features: Optional[torch.FloatTensor] = None, ): """ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is equal to the length of multimodal features. If the lengths are different, an error is raised. """ if input_ids is None: special_image_mask = inputs_embeds == self.get_input_embeddings()( torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device) ) special_image_mask = special_image_mask.all(-1) special_video_mask = inputs_embeds == self.get_input_embeddings()( torch.tensor(self.config.video_token_id, dtype=torch.long, device=inputs_embeds.device) ) special_video_mask = special_video_mask.all(-1) else: special_image_mask = input_ids == self.config.image_token_id special_video_mask = input_ids == self.config.video_token_id n_image_tokens = special_image_mask.sum() special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device) if image_features is not None and inputs_embeds[special_image_mask].numel() != image_features.numel(): raise ValueError( f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {image_features.shape[0]}" ) n_video_tokens = special_video_mask.sum() special_video_mask = special_video_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device) if video_features is not None and inputs_embeds[special_video_mask].numel() != video_features.numel(): raise ValueError( f"Videos features and video tokens do not match: tokens: {n_video_tokens}, features {video_features.shape[0]}" ) return special_image_mask, special_video_mask @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, pixel_values: Optional[torch.Tensor] = None, pixel_values_videos: Optional[torch.FloatTensor] = None, image_grid_thw: Optional[torch.LongTensor] = None, video_grid_thw: Optional[torch.LongTensor] = None, rope_deltas: Optional[torch.LongTensor] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple, Qwen2VLModelOutputWithPast]: r""" image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*): The temporal, height and width of feature shape of each image in LLM. video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*): The temporal, height and width of feature shape of each video in LLM. rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*): The rope index difference between sequence length and multimodal rope. """ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict if inputs_embeds is None: inputs_embeds = self.get_input_embeddings()(input_ids) if pixel_values is not None: image_embeds = self.get_image_features(pixel_values, image_grid_thw) image_embeds = torch.cat(image_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype) image_mask, _ = self.get_placeholder_mask( input_ids, inputs_embeds=inputs_embeds, image_features=image_embeds ) inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds) if pixel_values_videos is not None: video_embeds = self.get_video_features(pixel_values_videos, video_grid_thw) video_embeds = torch.cat(video_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype) _, video_mask = self.get_placeholder_mask( input_ids, inputs_embeds=inputs_embeds, video_features=video_embeds ) inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds) if position_ids is None: if self.rope_deltas is None or cache_position is None or cache_position[0] == 0: position_ids, rope_deltas = self.get_rope_index( input_ids, image_grid_thw, video_grid_thw, attention_mask ) self.rope_deltas = rope_deltas # then use the prev pre-calculated rope-deltas to get the correct position ids else: batch_size, seq_length, _ = inputs_embeds.shape position_ids = torch.arange(seq_length, device=inputs_embeds.device) position_ids = position_ids.view(1, 1, -1).expand(3, batch_size, -1) if cache_position is not None: delta = (cache_position[0] + self.rope_deltas).to(inputs_embeds.device) else: delta = torch.zeros((batch_size, seq_length), device=inputs_embeds.device) delta = delta.repeat_interleave(batch_size // delta.shape[0], dim=0) position_ids = position_ids + delta.to(position_ids.device) outputs = self.language_model( input_ids=None, position_ids=position_ids, attention_mask=attention_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=True, cache_position=cache_position, **kwargs, ) output = Qwen2VLModelOutputWithPast( last_hidden_state=outputs.last_hidden_state, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, rope_deltas=self.rope_deltas, ) return output if return_dict else output.to_tuple()
Qwen2VLModel
python
pandas-dev__pandas
pandas/core/arrays/arrow/accessors.py
{ "start": 1438, "end": 6551 }
class ____(ArrowAccessor): """ Accessor object for list data properties of the Series values. Parameters ---------- data : Series Series containing Arrow list data. """ def __init__(self, data=None) -> None: super().__init__( data, validation_msg="Can only use the '.list' accessor with " "'list[pyarrow]' dtype, not {dtype}.", ) def _is_valid_pyarrow_dtype(self, pyarrow_dtype) -> bool: return ( pa.types.is_list(pyarrow_dtype) or pa.types.is_fixed_size_list(pyarrow_dtype) or pa.types.is_large_list(pyarrow_dtype) ) def len(self) -> Series: """ Return the length of each list in the Series. Returns ------- pandas.Series The length of each list. See Also -------- str.len : Python built-in function returning the length of an object. Series.size : Returns the length of the Series. StringMethods.len : Compute the length of each element in the Series/Index. Examples -------- >>> import pyarrow as pa >>> s = pd.Series( ... [ ... [1, 2, 3], ... [3], ... ], ... dtype=pd.ArrowDtype(pa.list_(pa.int64())), ... ) >>> s.list.len() 0 3 1 1 dtype: int32[pyarrow] """ from pandas import Series value_lengths = pc.list_value_length(self._pa_array) return Series( value_lengths, dtype=ArrowDtype(value_lengths.type), index=self._data.index, name=self._data.name, ) def __getitem__(self, key: int | slice) -> Series: """ Index or slice lists in the Series. Parameters ---------- key : int | slice Index or slice of indices to access from each list. Returns ------- pandas.Series The list at requested index. See Also -------- ListAccessor.flatten : Flatten list values. Examples -------- >>> import pyarrow as pa >>> s = pd.Series( ... [ ... [1, 2, 3], ... [3], ... ], ... dtype=pd.ArrowDtype(pa.list_(pa.int64())), ... ) >>> s.list[0] 0 1 1 3 dtype: int64[pyarrow] """ from pandas import Series if isinstance(key, int): # TODO: Support negative key but pyarrow does not allow # element index to be an array. # if key < 0: # key = pc.add(key, pc.list_value_length(self._pa_array)) element = pc.list_element(self._pa_array, key) return Series( element, dtype=ArrowDtype(element.type), index=self._data.index, name=self._data.name, ) elif isinstance(key, slice): # TODO: Support negative start/stop/step, ideally this would be added # upstream in pyarrow. start, stop, step = key.start, key.stop, key.step if start is None: # TODO: When adding negative step support # this should be setto last element of array # when step is negative. start = 0 if step is None: step = 1 sliced = pc.list_slice(self._pa_array, start, stop, step) return Series( sliced, dtype=ArrowDtype(sliced.type), index=self._data.index, name=self._data.name, ) else: raise ValueError(f"key must be an int or slice, got {type(key).__name__}") def __iter__(self) -> Iterator: raise TypeError(f"'{type(self).__name__}' object is not iterable") def flatten(self) -> Series: """ Flatten list values. Returns ------- pandas.Series The data from all lists in the series flattened. See Also -------- ListAccessor.__getitem__ : Index or slice values in the Series. Examples -------- >>> import pyarrow as pa >>> s = pd.Series( ... [ ... [1, 2, 3], ... [3], ... ], ... dtype=pd.ArrowDtype(pa.list_(pa.int64())), ... ) >>> s.list.flatten() 0 1 0 2 0 3 1 3 dtype: int64[pyarrow] """ from pandas import Series counts = pa.compute.list_value_length(self._pa_array) flattened = pa.compute.list_flatten(self._pa_array) index = self._data.index.repeat(counts.fill_null(pa.scalar(0, counts.type))) return Series( flattened, dtype=ArrowDtype(flattened.type), index=index, name=self._data.name, )
ListAccessor
python
astropy__astropy
astropy/units/tests/test_quantity_non_ufuncs.py
{ "start": 63940, "end": 64471 }
class ____(InvariantUnitTestSetup): def test_sort(self): self.check(np.sort) def test_sort_axis(self): self.check(np.sort, axis=0) @pytest.mark.skipif(not NUMPY_LT_2_0, reason="np.msort was removed in numpy 2.0") def test_msort(self): with pytest.warns(DeprecationWarning, match="^msort is deprecated"): self.check(np.msort) def test_sort_complex(self): self.check(np.sort_complex) def test_partition(self): self.check(np.partition, 2)
TestSortFunctions
python
django__django
tests/basic/models.py
{ "start": 303, "end": 427 }
class ____(models.Model): article = models.OneToOneField(Article, models.CASCADE, related_name="featured")
FeaturedArticle
python
skorch-dev__skorch
skorch/history.py
{ "start": 3511, "end": 9587 }
class ____(list): """History contains the information about the training history of a :class:`.NeuralNet`, facilitating some of the more common tasks that are occur during training. When you want to log certain information during training (say, a particular score or the norm of the gradients), you should write them to the net's history object. It is basically a list of dicts for each epoch, that, again, contains a list of dicts for each batch. For convenience, it has enhanced slicing notation and some methods to write new items. To access items from history, you may pass a tuple of up to four items: 1. Slices along the epochs. 2. Selects columns from history epochs, may be a single one or a tuple of column names. 3. Slices along the batches. 4. Selects columns from history batchs, may be a single one or a tuple of column names. You may use a combination of the four items. If you select columns that are not present in all epochs/batches, only those epochs/batches are chosen that contain said columns. If this set is empty, a ``KeyError`` is raised. Examples -------- >>> # ACCESSING ITEMS >>> # history of a fitted neural net >>> history = net.history >>> # get current epoch, a dict >>> history[-1] >>> # get train losses from all epochs, a list of floats >>> history[:, 'train_loss'] >>> # get train and valid losses from all epochs, a list of tuples >>> history[:, ('train_loss', 'valid_loss')] >>> # get current batches, a list of dicts >>> history[-1, 'batches'] >>> # get latest batch, a dict >>> history[-1, 'batches', -1] >>> # get train losses from current batch, a list of floats >>> history[-1, 'batches', :, 'train_loss'] >>> # get train and valid losses from current batch, a list of tuples >>> history[-1, 'batches', :, ('train_loss', 'valid_loss')] >>> # WRITING ITEMS >>> # add new epoch row >>> history.new_epoch() >>> # add an entry to current epoch >>> history.record('my-score', 123) >>> # add a batch row to the current epoch >>> history.new_batch() >>> # add an entry to the current batch >>> history.record_batch('my-batch-score', 456) >>> # overwrite entry of current batch >>> history.record_batch('my-batch-score', 789) """ def new_epoch(self): """Register a new epoch row.""" self.append({'batches': []}) def new_batch(self): """Register a new batch row for the current epoch.""" # pylint: disable=invalid-sequence-index self[-1]['batches'].append({}) def record(self, attr, value): """Add a new value to the given column for the current epoch. """ msg = "Call new_epoch before recording for the first time." if not self: raise ValueError(msg) self[-1][attr] = value def record_batch(self, attr, value): """Add a new value to the given column for the current batch. """ # pylint: disable=invalid-sequence-index self[-1]['batches'][-1][attr] = value def to_list(self): """Return history object as a list.""" return list(self) @classmethod def from_file(cls, f): """Load the history of a ``NeuralNet`` from a json file. Parameters ---------- f : file-like object or str """ with open_file_like(f, 'r') as fp: return cls(json.load(fp)) def to_file(self, f): """Saves the history as a json file. In order to use this feature, the history must only contain JSON encodable Python data structures. Numpy and PyTorch types should not be in the history. Parameters ---------- f : file-like object or str """ with open_file_like(f, 'w') as fp: json.dump(self.to_list(), fp) def __getitem__(self, i): # This implementation resolves indexing backwards, # i.e. starting from the batches, then progressing to the # epochs. if isinstance(i, (int, slice)): i = (i,) # i_e: index epoch, k_e: key epoch # i_b: index batch, k_b: key batch i_e, k_e, i_b, k_b = _unpack_index(i) keyerror_msg = "Key {!r} was not found in history." if i_b is not None and k_e != 'batches': raise KeyError("History indexing beyond the 2nd level is " "only possible if key 'batches' is used, " "found key {!r}.".format(k_e)) items = self.to_list() # extract the epochs # handles: history[i_e] if i_e is not None: items = items[i_e] if isinstance(i_e, int): items = [items] # extract indices of batches # handles: history[..., k_e, i_b] if i_b is not None: items = [row[k_e][i_b] for row in items] # extract keys of epochs or batches # handles: history[..., k_e] # handles: history[..., ..., ..., k_b] if k_e is not None and (i_b is None or k_b is not None): key = k_e if k_b is None else k_b if items: extract = _get_getitem_method(items[0], key) items = [extract(item, key) for item in items] # filter out epochs with missing keys items = list(filter(_not_none, items)) if not items and not (k_e == 'batches' and i_b is None): # none of the epochs matched raise KeyError(keyerror_msg.format(key)) if ( isinstance(i_b, slice) and k_b is not None and not any(batches for batches in items) ): # none of the batches matched raise KeyError(keyerror_msg.format(key)) if isinstance(i_e, int): items, = items return items
History
python
pytorch__pytorch
torch/testing/_internal/common_quantization.py
{ "start": 83802, "end": 84135 }
class ____(nn.Module): def __init__(self) -> None: super().__init__() self.conv = FunctionalConv2d() def forward(self, x): x = self.conv(x) x = F.relu(x) return x def get_example_inputs(self) -> tuple[Any, ...]: return self.conv.get_example_inputs()
FunctionalConvReluModel
python
xlwings__xlwings
xlwings/main.py
{ "start": 2594, "end": 4271 }
class ____: def __init__(self): self.active = None self.engines = [] self.engines_by_name = {} def add(self, engine): self.engines.append(engine) self.engines_by_name[engine.name] = engine @property def count(self): return len(self) def __call__(self, name_or_index): if isinstance(name_or_index, numbers.Number): return self.engines[name_or_index - 1] else: return self.engines_by_name[name_or_index] def __getitem__(self, name_or_index): if isinstance(name_or_index, numbers.Number): return self.engines[name_or_index] else: try: return self.engines_by_name[name_or_index] except KeyError: engine_to_product_name = { "remote": "xlwings Server", "calamine": "xlwings Reader", } if not xlwings.__pro__ and name_or_index != "excel": raise LicenseError( f"{engine_to_product_name.get(name_or_index, name_or_index)} " "requires a license key. Install one by running 'xlwings " "license update -k your-key-here' or by setting the " "XLWINGS_LICENSE_KEY environment variable." ) else: raise def __len__(self): return len(self.engines) def __iter__(self): for engine in self.engines: yield engine def __repr__(self): return "{}({})".format(self.__class__.__name__, repr(list(self)))
Engines
python
kamyu104__LeetCode-Solutions
Python/cells-with-odd-values-in-a-matrix.py
{ "start": 509, "end": 897 }
class ____(object): def oddCells(self, n, m, indices): """ :type n: int :type m: int :type indices: List[List[int]] :rtype: int """ fn = lambda x: sum(count&1 for count in collections.Counter(x).itervalues()) row_sum, col_sum = map(fn, itertools.izip(*indices)) return row_sum*m+col_sum*n-2*row_sum*col_sum
Solution2
python
ray-project__ray
doc/source/ray-core/doc_code/direct_transport_gloo.py
{ "start": 81, "end": 229 }
class ____: def random_tensor(self): return torch.randn(1000, 1000) # __normal_example_end__ # __gloo_example_start__ @ray.remote
MyActor
python
fastapi__sqlmodel
docs_src/tutorial/fastapi/multiple_models/tutorial001_py310.py
{ "start": 303, "end": 395 }
class ____(SQLModel): name: str secret_name: str age: int | None = None
HeroCreate
python
pytorch__pytorch
test/test_nn.py
{ "start": 352457, "end": 354094 }
class ____(TestCase): @set_default_dtype(torch.double) @given(X=hu.tensor(shapes=((5, 3, 5, 5),), dtype=np.double), running_mean=hu.tensor(shapes=(6,), dtype=np.double), running_var=hu.tensor(shapes=(6,), dtype=np.double)) def test_fuse_module_eval_numerics(self, X, running_mean, running_var): inputs, _ = X iC, oC = inputs.shape[1], len(running_mean[0]) inputs = torch.from_numpy(inputs) kernel_size = (3, 3) conv_ref = torch.nn.Conv2d(iC, oC, bias=True, kernel_size=kernel_size) bn_ref = torch.nn.BatchNorm2d(oC) bn_ref.running_mean = torch.from_numpy(running_mean[0]) bn_ref.running_var = torch.from_numpy(running_var[0]) conv_ref.eval() bn_ref.eval() Y_ref = bn_ref(conv_ref(inputs)) conv_bn_fused = torch.nn.utils.fusion.fuse_conv_bn_eval(conv_ref, bn_ref) Y_hat = conv_bn_fused(inputs) self.assertEqual(Y_ref, Y_hat, msg="Conv+BN fusion results are off") na_bn_ref = torch.nn.BatchNorm2d(oC, affine=False) na_bn_ref.running_mean = torch.from_numpy(running_mean[0]) na_bn_ref.running_var = torch.from_numpy(running_var[0]) na_bn_ref.eval() Y_ref = na_bn_ref(conv_ref(inputs)) conv_na_bn_fused = torch.nn.utils.fusion.fuse_conv_bn_eval(conv_ref, na_bn_ref) Y_hat = conv_na_bn_fused(inputs) self.assertEqual(Y_ref, Y_hat, msg="Conv+BN(non-affine) fusion results are off")
TestFusionEval
python
getsentry__sentry
tests/sentry/digests/test_notifications.py
{ "start": 668, "end": 1965 }
class ____(TestCase): notification_uuid = str(uuid.uuid4()) @cached_property def project(self) -> Project: return self.create_project(fire_project_created=True) @cached_property def rule(self) -> Rule: return self.event.project.rule_set.all()[0] @cached_property def record(self) -> Record: return event_to_record(self.event, (self.rule,), self.notification_uuid) @property def group_mapping(self) -> dict[int, Group]: return {self.event.group.id: self.event.group} @property def rule_mapping(self) -> dict[int, Rule]: return {self.rule.id: self.rule} def test_success(self) -> None: (record,) = _bind_records([self.record], self.group_mapping, self.rule_mapping) assert record == self.record.with_rules([self.rule]) def test_without_group(self) -> None: # If the record can't be associated with a group, it should be dropped assert not _bind_records([self.record], {}, self.rule_mapping) def test_filters_invalid_rules(self) -> None: # If the record can't be associated with a rule, the rule should be dropped (record,) = _bind_records([self.record], self.group_mapping, {}) assert record == self.record.with_rules([])
BindRecordsTestCase
python
numba__numba
numba/cuda/models.py
{ "start": 844, "end": 1328 }
class ____(models.PrimitiveModel): def __init__(self, dmm, fe_type): if fe_type == types.float16: be_type = ir.IntType(16) elif fe_type == types.float32: be_type = ir.FloatType() elif fe_type == types.float64: be_type = ir.DoubleType() else: raise NotImplementedError(fe_type) super(FloatModel, self).__init__(dmm, fe_type, be_type) register_model(CUDADispatcher)(models.OpaqueModel)
FloatModel
python
redis__redis-py
tests/test_pubsub.py
{ "start": 29656, "end": 33230 }
class ____: @pytest.mark.onlynoncluster @skip_if_server_version_lt("2.8.0") def test_pubsub_channels(self, r): p = r.pubsub() p.subscribe("foo", "bar", "baz", "quux") for i in range(4): assert wait_for_message(p)["type"] == "subscribe" expected = [b"bar", b"baz", b"foo", b"quux"] assert all([channel in r.pubsub_channels() for channel in expected]) @pytest.mark.onlynoncluster @skip_if_server_version_lt("7.0.0") def test_pubsub_shardchannels(self, r): p = r.pubsub() p.ssubscribe("foo", "bar", "baz", "quux") for i in range(4): assert wait_for_message(p)["type"] == "ssubscribe" expected = [b"bar", b"baz", b"foo", b"quux"] assert all([channel in r.pubsub_shardchannels() for channel in expected]) @pytest.mark.onlycluster @skip_if_server_version_lt("7.0.0") def test_pubsub_shardchannels_cluster(self, r): channels = { b"foo": r.get_node_from_key("foo"), b"bar": r.get_node_from_key("bar"), b"baz": r.get_node_from_key("baz"), b"quux": r.get_node_from_key("quux"), } p = r.pubsub() p.ssubscribe("foo", "bar", "baz", "quux") for node in channels.values(): assert wait_for_message(p, node=node)["type"] == "ssubscribe" for channel, node in channels.items(): assert channel in r.pubsub_shardchannels(target_nodes=node) assert all( [ channel in r.pubsub_shardchannels(target_nodes="all") for channel in channels.keys() ] ) @pytest.mark.onlynoncluster @skip_if_server_version_lt("2.8.0") def test_pubsub_numsub(self, r): p1 = r.pubsub() p1.subscribe("foo", "bar", "baz") for i in range(3): assert wait_for_message(p1)["type"] == "subscribe" p2 = r.pubsub() p2.subscribe("bar", "baz") for i in range(2): assert wait_for_message(p2)["type"] == "subscribe" p3 = r.pubsub() p3.subscribe("baz") assert wait_for_message(p3)["type"] == "subscribe" channels = [(b"foo", 1), (b"bar", 2), (b"baz", 3)] assert r.pubsub_numsub("foo", "bar", "baz") == channels @skip_if_server_version_lt("2.8.0") def test_pubsub_numpat(self, r): p = r.pubsub() p.psubscribe("*oo", "*ar", "b*z") for i in range(3): assert wait_for_message(p)["type"] == "psubscribe" assert r.pubsub_numpat() == 3 @pytest.mark.onlycluster @skip_if_server_version_lt("7.0.0") def test_pubsub_shardnumsub(self, r): channels = { b"foo": r.get_node_from_key("foo"), b"bar": r.get_node_from_key("bar"), b"baz": r.get_node_from_key("baz"), } p1 = r.pubsub() p1.ssubscribe(*channels.keys()) for node in channels.values(): assert wait_for_message(p1, node=node)["type"] == "ssubscribe" p2 = r.pubsub() p2.ssubscribe("bar", "baz") for i in range(2): assert ( wait_for_message(p2, func=p2.get_sharded_message)["type"] == "ssubscribe" ) p3 = r.pubsub() p3.ssubscribe("baz") assert wait_for_message(p3, node=channels[b"baz"])["type"] == "ssubscribe" channels = [(b"foo", 1), (b"bar", 2), (b"baz", 3)] assert r.pubsub_shardnumsub("foo", "bar", "baz", target_nodes="all") == channels
TestPubSubSubcommands
python
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/pygments/lexers/python.py
{ "start": 816, "end": 18271 }
class ____(RegexLexer): """ For Python source code (version 3.x). .. versionchanged:: 2.5 This is now the default ``PythonLexer``. It is still available as the alias ``Python3Lexer``. """ name = 'Python' url = 'https://www.python.org' aliases = ['python', 'py', 'sage', 'python3', 'py3', 'bazel', 'starlark'] filenames = [ '*.py', '*.pyw', # Type stubs '*.pyi', # Jython '*.jy', # Sage '*.sage', # SCons '*.sc', 'SConstruct', 'SConscript', # Skylark/Starlark (used by Bazel, Buck, and Pants) '*.bzl', 'BUCK', 'BUILD', 'BUILD.bazel', 'WORKSPACE', # Twisted Application infrastructure '*.tac', ] mimetypes = ['text/x-python', 'application/x-python', 'text/x-python3', 'application/x-python3'] version_added = '0.10' uni_name = f"[{uni.xid_start}][{uni.xid_continue}]*" def innerstring_rules(ttype): return [ # the old style '%s' % (...) string formatting (still valid in Py3) (r'%(\(\w+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?' '[hlL]?[E-GXc-giorsaux%]', String.Interpol), # the new style '{}'.format(...) string formatting (r'\{' r'((\w+)((\.\w+)|(\[[^\]]+\]))*)?' # field name r'(\![sra])?' # conversion r'(\:(.?[<>=\^])?[-+ ]?#?0?(\d+)?,?(\.\d+)?[E-GXb-gnosx%]?)?' r'\}', String.Interpol), # backslashes, quotes and formatting signs must be parsed one at a time (r'[^\\\'"%{\n]+', ttype), (r'[\'"\\]', ttype), # unhandled string formatting sign (r'%|(\{{1,2})', ttype) # newlines are an error (use "nl" state) ] def fstring_rules(ttype): return [ # Assuming that a '}' is the closing brace after format specifier. # Sadly, this means that we won't detect syntax error. But it's # more important to parse correct syntax correctly, than to # highlight invalid syntax. (r'\}', String.Interpol), (r'\{', String.Interpol, 'expr-inside-fstring'), # backslashes, quotes and formatting signs must be parsed one at a time (r'[^\\\'"{}\n]+', ttype), (r'[\'"\\]', ttype), # newlines are an error (use "nl" state) ] tokens = { 'root': [ (r'\n', Whitespace), (r'^(\s*)([rRuUbB]{,2})("""(?:.|\n)*?""")', bygroups(Whitespace, String.Affix, String.Doc)), (r"^(\s*)([rRuUbB]{,2})('''(?:.|\n)*?''')", bygroups(Whitespace, String.Affix, String.Doc)), (r'\A#!.+$', Comment.Hashbang), (r'#.*$', Comment.Single), (r'\\\n', Text), (r'\\', Text), include('keywords'), include('soft-keywords'), (r'(def)((?:\s|\\\s)+)', bygroups(Keyword, Text), 'funcname'), (r'(class)((?:\s|\\\s)+)', bygroups(Keyword, Text), 'classname'), (r'(from)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Text), 'fromimport'), (r'(import)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Text), 'import'), include('expr'), ], 'expr': [ # raw f-strings ('(?i)(rf|fr)(""")', bygroups(String.Affix, String.Double), combined('rfstringescape', 'tdqf')), ("(?i)(rf|fr)(''')", bygroups(String.Affix, String.Single), combined('rfstringescape', 'tsqf')), ('(?i)(rf|fr)(")', bygroups(String.Affix, String.Double), combined('rfstringescape', 'dqf')), ("(?i)(rf|fr)(')", bygroups(String.Affix, String.Single), combined('rfstringescape', 'sqf')), # non-raw f-strings ('([fF])(""")', bygroups(String.Affix, String.Double), combined('fstringescape', 'tdqf')), ("([fF])(''')", bygroups(String.Affix, String.Single), combined('fstringescape', 'tsqf')), ('([fF])(")', bygroups(String.Affix, String.Double), combined('fstringescape', 'dqf')), ("([fF])(')", bygroups(String.Affix, String.Single), combined('fstringescape', 'sqf')), # raw bytes and strings ('(?i)(rb|br|r)(""")', bygroups(String.Affix, String.Double), 'tdqs'), ("(?i)(rb|br|r)(''')", bygroups(String.Affix, String.Single), 'tsqs'), ('(?i)(rb|br|r)(")', bygroups(String.Affix, String.Double), 'dqs'), ("(?i)(rb|br|r)(')", bygroups(String.Affix, String.Single), 'sqs'), # non-raw strings ('([uU]?)(""")', bygroups(String.Affix, String.Double), combined('stringescape', 'tdqs')), ("([uU]?)(''')", bygroups(String.Affix, String.Single), combined('stringescape', 'tsqs')), ('([uU]?)(")', bygroups(String.Affix, String.Double), combined('stringescape', 'dqs')), ("([uU]?)(')", bygroups(String.Affix, String.Single), combined('stringescape', 'sqs')), # non-raw bytes ('([bB])(""")', bygroups(String.Affix, String.Double), combined('bytesescape', 'tdqs')), ("([bB])(''')", bygroups(String.Affix, String.Single), combined('bytesescape', 'tsqs')), ('([bB])(")', bygroups(String.Affix, String.Double), combined('bytesescape', 'dqs')), ("([bB])(')", bygroups(String.Affix, String.Single), combined('bytesescape', 'sqs')), (r'[^\S\n]+', Text), include('numbers'), (r'!=|==|<<|>>|:=|[-~+/*%=<>&^|.]', Operator), (r'[]{}:(),;[]', Punctuation), (r'(in|is|and|or|not)\b', Operator.Word), include('expr-keywords'), include('builtins'), include('magicfuncs'), include('magicvars'), include('name'), ], 'expr-inside-fstring': [ (r'[{([]', Punctuation, 'expr-inside-fstring-inner'), # without format specifier (r'(=\s*)?' # debug (https://bugs.python.org/issue36817) r'(\![sraf])?' # conversion r'\}', String.Interpol, '#pop'), # with format specifier # we'll catch the remaining '}' in the outer scope (r'(=\s*)?' # debug (https://bugs.python.org/issue36817) r'(\![sraf])?' # conversion r':', String.Interpol, '#pop'), (r'\s+', Whitespace), # allow new lines include('expr'), ], 'expr-inside-fstring-inner': [ (r'[{([]', Punctuation, 'expr-inside-fstring-inner'), (r'[])}]', Punctuation, '#pop'), (r'\s+', Whitespace), # allow new lines include('expr'), ], 'expr-keywords': [ # Based on https://docs.python.org/3/reference/expressions.html (words(( 'async for', 'await', 'else', 'for', 'if', 'lambda', 'yield', 'yield from'), suffix=r'\b'), Keyword), (words(('True', 'False', 'None'), suffix=r'\b'), Keyword.Constant), ], 'keywords': [ (words(( 'assert', 'async', 'await', 'break', 'continue', 'del', 'elif', 'else', 'except', 'finally', 'for', 'global', 'if', 'lambda', 'pass', 'raise', 'nonlocal', 'return', 'try', 'while', 'yield', 'yield from', 'as', 'with'), suffix=r'\b'), Keyword), (words(('True', 'False', 'None'), suffix=r'\b'), Keyword.Constant), ], 'soft-keywords': [ # `match`, `case` and `_` soft keywords (r'(^[ \t]*)' # at beginning of line + possible indentation r'(match|case)\b' # a possible keyword r'(?![ \t]*(?:' # not followed by... r'[:,;=^&|@~)\]}]|(?:' + # characters and keywords that mean this isn't # pattern matching (but None/True/False is ok) r'|'.join(k for k in keyword.kwlist if k[0].islower()) + r')\b))', bygroups(Text, Keyword), 'soft-keywords-inner'), ], 'soft-keywords-inner': [ # optional `_` keyword (r'(\s+)([^\n_]*)(_\b)', bygroups(Whitespace, using(this), Keyword)), default('#pop') ], 'builtins': [ (words(( '__import__', 'abs', 'aiter', 'all', 'any', 'bin', 'bool', 'bytearray', 'breakpoint', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip'), prefix=r'(?<!\.)', suffix=r'\b'), Name.Builtin), (r'(?<!\.)(self|Ellipsis|NotImplemented|cls)\b', Name.Builtin.Pseudo), (words(( 'ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'VMSError', 'Warning', 'WindowsError', 'ZeroDivisionError', # new builtin exceptions from PEP 3151 'BlockingIOError', 'ChildProcessError', 'ConnectionError', 'BrokenPipeError', 'ConnectionAbortedError', 'ConnectionRefusedError', 'ConnectionResetError', 'FileExistsError', 'FileNotFoundError', 'InterruptedError', 'IsADirectoryError', 'NotADirectoryError', 'PermissionError', 'ProcessLookupError', 'TimeoutError', # others new in Python 3 'StopAsyncIteration', 'ModuleNotFoundError', 'RecursionError', 'EncodingWarning'), prefix=r'(?<!\.)', suffix=r'\b'), Name.Exception), ], 'magicfuncs': [ (words(( '__abs__', '__add__', '__aenter__', '__aexit__', '__aiter__', '__and__', '__anext__', '__await__', '__bool__', '__bytes__', '__call__', '__complex__', '__contains__', '__del__', '__delattr__', '__delete__', '__delitem__', '__dir__', '__divmod__', '__enter__', '__eq__', '__exit__', '__float__', '__floordiv__', '__format__', '__ge__', '__get__', '__getattr__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__iand__', '__ifloordiv__', '__ilshift__', '__imatmul__', '__imod__', '__imul__', '__index__', '__init__', '__instancecheck__', '__int__', '__invert__', '__ior__', '__ipow__', '__irshift__', '__isub__', '__iter__', '__itruediv__', '__ixor__', '__le__', '__len__', '__length_hint__', '__lshift__', '__lt__', '__matmul__', '__missing__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__next__', '__or__', '__pos__', '__pow__', '__prepare__', '__radd__', '__rand__', '__rdivmod__', '__repr__', '__reversed__', '__rfloordiv__', '__rlshift__', '__rmatmul__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__set__', '__setattr__', '__setitem__', '__str__', '__sub__', '__subclasscheck__', '__truediv__', '__xor__'), suffix=r'\b'), Name.Function.Magic), ], 'magicvars': [ (words(( '__annotations__', '__bases__', '__class__', '__closure__', '__code__', '__defaults__', '__dict__', '__doc__', '__file__', '__func__', '__globals__', '__kwdefaults__', '__module__', '__mro__', '__name__', '__objclass__', '__qualname__', '__self__', '__slots__', '__weakref__'), suffix=r'\b'), Name.Variable.Magic), ], 'numbers': [ (r'(\d(?:_?\d)*\.(?:\d(?:_?\d)*)?|(?:\d(?:_?\d)*)?\.\d(?:_?\d)*)' r'([eE][+-]?\d(?:_?\d)*)?', Number.Float), (r'\d(?:_?\d)*[eE][+-]?\d(?:_?\d)*j?', Number.Float), (r'0[oO](?:_?[0-7])+', Number.Oct), (r'0[bB](?:_?[01])+', Number.Bin), (r'0[xX](?:_?[a-fA-F0-9])+', Number.Hex), (r'\d(?:_?\d)*', Number.Integer), ], 'name': [ (r'@' + uni_name, Name.Decorator), (r'@', Operator), # new matrix multiplication operator (uni_name, Name), ], 'funcname': [ include('magicfuncs'), (uni_name, Name.Function, '#pop'), default('#pop'), ], 'classname': [ (uni_name, Name.Class, '#pop'), ], 'import': [ (r'(\s+)(as)(\s+)', bygroups(Text, Keyword, Text)), (r'\.', Name.Namespace), (uni_name, Name.Namespace), (r'(\s*)(,)(\s*)', bygroups(Text, Operator, Text)), default('#pop') # all else: go back ], 'fromimport': [ (r'(\s+)(import)\b', bygroups(Text, Keyword.Namespace), '#pop'), (r'\.', Name.Namespace), # if None occurs here, it's "raise x from None", since None can # never be a module name (r'None\b', Keyword.Constant, '#pop'), (uni_name, Name.Namespace), default('#pop'), ], 'rfstringescape': [ (r'\{\{', String.Escape), (r'\}\}', String.Escape), ], 'fstringescape': [ include('rfstringescape'), include('stringescape'), ], 'bytesescape': [ (r'\\([\\abfnrtv"\']|\n|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape) ], 'stringescape': [ (r'\\(N\{.*?\}|u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8})', String.Escape), include('bytesescape') ], 'fstrings-single': fstring_rules(String.Single), 'fstrings-double': fstring_rules(String.Double), 'strings-single': innerstring_rules(String.Single), 'strings-double': innerstring_rules(String.Double), 'dqf': [ (r'"', String.Double, '#pop'), (r'\\\\|\\"|\\\n', String.Escape), # included here for raw strings include('fstrings-double') ], 'sqf': [ (r"'", String.Single, '#pop'), (r"\\\\|\\'|\\\n", String.Escape), # included here for raw strings include('fstrings-single') ], 'dqs': [ (r'"', String.Double, '#pop'), (r'\\\\|\\"|\\\n', String.Escape), # included here for raw strings include('strings-double') ], 'sqs': [ (r"'", String.Single, '#pop'), (r"\\\\|\\'|\\\n", String.Escape), # included here for raw strings include('strings-single') ], 'tdqf': [ (r'"""', String.Double, '#pop'), include('fstrings-double'), (r'\n', String.Double) ], 'tsqf': [ (r"'''", String.Single, '#pop'), include('fstrings-single'), (r'\n', String.Single) ], 'tdqs': [ (r'"""', String.Double, '#pop'), include('strings-double'), (r'\n', String.Double) ], 'tsqs': [ (r"'''", String.Single, '#pop'), include('strings-single'), (r'\n', String.Single) ], } def analyse_text(text): return shebang_matches(text, r'pythonw?(3(\.\d)?)?') or \ 'import ' in text[:1000] Python3Lexer = PythonLexer
PythonLexer
python
catalyst-team__catalyst
catalyst/contrib/layers/common.py
{ "start": 488, "end": 801 }
class ____(nn.Module): """@TODO: Docs. Contribution is welcome.""" def __init__(self, lambda_fn): """@TODO: Docs. Contribution is welcome.""" super().__init__() self.lambda_fn = lambda_fn def forward(self, x): """Forward call.""" return self.lambda_fn(x)
Lambda
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 233519, "end": 234463 }
class ____(Operation): def call(self, x1, x2): return backend.numpy.floor_divide(x1, x2) def compute_output_spec(self, x1, x2): x1_shape = getattr(x1, "shape", []) x2_shape = getattr(x2, "shape", []) output_shape = broadcast_shapes(x1_shape, x2_shape) output_dtype = dtypes.result_type( getattr(x1, "dtype", type(x1)), getattr(x2, "dtype", type(x2)), ) return KerasTensor(output_shape, dtype=output_dtype) @keras_export(["keras.ops.floor_divide", "keras.ops.numpy.floor_divide"]) def floor_divide(x1, x2): """Returns the largest integer smaller or equal to the division of inputs. Args: x1: Numerator. x2: Denominator. Returns: Output tensor, `y = floor(x1/x2)` """ if any_symbolic_tensors((x1, x2)): return FloorDivide().symbolic_call(x1, x2) return backend.numpy.floor_divide(x1, x2)
FloorDivide
python
mlflow__mlflow
mlflow/gateway/config.py
{ "start": 10503, "end": 10574 }
class ____(ConfigModel): limits: list[Limit] | None = []
LimitsConfig
python
xlwings__xlwings
xlwings/constants.py
{ "start": 62432, "end": 62918 }
class ____: xlFilterAllDatesInPeriodDay = 2 # from enum XlFilterAllDatesInPeriod xlFilterAllDatesInPeriodHour = 3 # from enum XlFilterAllDatesInPeriod xlFilterAllDatesInPeriodMinute = 4 # from enum XlFilterAllDatesInPeriod xlFilterAllDatesInPeriodMonth = 1 # from enum XlFilterAllDatesInPeriod xlFilterAllDatesInPeriodSecond = 5 # from enum XlFilterAllDatesInPeriod xlFilterAllDatesInPeriodYear = 0 # from enum XlFilterAllDatesInPeriod
FilterAllDatesInPeriod
python
pallets__werkzeug
src/werkzeug/sansio/multipart.py
{ "start": 10371, "end": 11963 }
class ____: def __init__(self, boundary: bytes) -> None: self.boundary = boundary self.state = State.PREAMBLE def send_event(self, event: Event) -> bytes: if isinstance(event, Preamble) and self.state == State.PREAMBLE: self.state = State.PART return event.data elif isinstance(event, (Field, File)) and self.state in { State.PREAMBLE, State.PART, State.DATA, }: data = b"\r\n--" + self.boundary + b"\r\n" data += b'Content-Disposition: form-data; name="%s"' % event.name.encode() if isinstance(event, File): data += b'; filename="%s"' % event.filename.encode() data += b"\r\n" for name, value in t.cast(Field, event).headers: if name.lower() != "content-disposition": data += f"{name}: {value}\r\n".encode() self.state = State.DATA_START return data elif isinstance(event, Data) and self.state == State.DATA_START: self.state = State.DATA if len(event.data) > 0: return b"\r\n" + event.data else: return event.data elif isinstance(event, Data) and self.state == State.DATA: return event.data elif isinstance(event, Epilogue): self.state = State.COMPLETE return b"\r\n--" + self.boundary + b"--\r\n" + event.data else: raise ValueError(f"Cannot generate {event} in state: {self.state}")
MultipartEncoder
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/auto_materialize_policy.py
{ "start": 2258, "end": 14363 }
class ____( NamedTuple( "_AutoMaterializePolicy", [ ("rules", frozenset["AutoMaterializeRule"]), ("max_materializations_per_minute", Optional[int]), ("asset_condition", Optional["AutomationCondition"]), ], ) ): """An AutoMaterializePolicy specifies how Dagster should attempt to keep an asset up-to-date. Each policy consists of a set of AutoMaterializeRules, which are used to determine whether an asset or a partition of an asset should or should not be auto-materialized. The most common policy is `AutoMaterializePolicy.eager()`, which consists of the following rules: - `AutoMaterializeRule.materialize_on_missing()` Materialize an asset or a partition if it has never been materialized. - `AutoMaterializeRule.materialize_on_parent_updated()` Materialize an asset or a partition if one of its parents have been updated more recently than it has. - `AutoMaterializeRule.materialize_on_required_for_freshness()` Materialize an asset or a partition if it is required to satisfy a freshness policy. - `AutoMaterializeRule.skip_on_parent_outdated()` Skip materializing an asset or partition if any of its parents have ancestors that have been materialized more recently. - `AutoMaterializeRule.skip_on_parent_missing()` Skip materializing an asset or a partition if any parent has never been materialized or observed. Policies can be customized by adding or removing rules. For example, if you'd like to allow an asset to be materialized even if some of its parent partitions are missing: .. code-block:: python from dagster import AutoMaterializePolicy, AutoMaterializeRule my_policy = AutoMaterializePolicy.eager().without_rules( AutoMaterializeRule.skip_on_parent_missing(), ) If you'd like an asset to wait for all of its parents to be updated before materializing: .. code-block:: python from dagster import AutoMaterializePolicy, AutoMaterializeRule my_policy = AutoMaterializePolicy.eager().with_rules( AutoMaterializeRule.skip_on_all_parents_not_updated(), ) Lastly, the `max_materializations_per_minute` parameter, which is set to 1 by default, rate-limits the number of auto-materializations that can occur for a particular asset within a short time interval. This mainly matters for partitioned assets. Its purpose is to provide a safeguard against "surprise backfills", where user-error causes auto-materialize to be accidentally triggered for large numbers of partitions at once. **Warning:** Constructing an AutoMaterializePolicy directly is not recommended as the API is subject to change. AutoMaterializePolicy.eager() and AutoMaterializePolicy.lazy() are the recommended API. """ def __new__( cls, rules: AbstractSet["AutoMaterializeRule"], max_materializations_per_minute: Optional[int] = 1, asset_condition: Optional["AutomationCondition"] = None, ): from dagster._core.definitions.auto_materialize_rule import AutoMaterializeRule check.invariant( max_materializations_per_minute is None or max_materializations_per_minute > 0, "max_materializations_per_minute must be positive. To disable rate-limiting, set it" " to None. To disable auto materializing, remove the policy.", ) check.param_invariant( bool(rules) ^ bool(asset_condition), "asset_condition", "Must specify exactly one of `rules` or `asset_condition`.", ) if asset_condition is not None: check.param_invariant( max_materializations_per_minute is None, "max_materializations_per_minute", "`max_materializations_per_minute` is not supported when using `asset_condition`.", ) return super().__new__( cls, rules=frozenset(check.set_param(rules, "rules", of_type=AutoMaterializeRule)), max_materializations_per_minute=max_materializations_per_minute, asset_condition=asset_condition, ) @property def materialize_rules(self) -> AbstractSet["AutoMaterializeRule"]: from dagster._core.definitions.auto_materialize_rule_evaluation import ( AutoMaterializeDecisionType, ) return { rule for rule in self.rules if rule.decision_type == AutoMaterializeDecisionType.MATERIALIZE } @property def skip_rules(self) -> AbstractSet["AutoMaterializeRule"]: from dagster._core.definitions.auto_materialize_rule_evaluation import ( AutoMaterializeDecisionType, ) return { rule for rule in self.rules if rule.decision_type == AutoMaterializeDecisionType.SKIP } @staticmethod def from_automation_condition( automation_condition: "AutomationCondition", ) -> "AutoMaterializePolicy": """Constructs an AutoMaterializePolicy which will materialize an asset partition whenever the provided automation_condition evaluates to True. Args: automation_condition (AutomationCondition): The condition which determines whether an asset partition should be materialized. """ return AutoMaterializePolicy( rules=set(), max_materializations_per_minute=None, asset_condition=automation_condition ) @public @staticmethod @deprecated( breaking_version="1.10.0", additional_warn_text="Use `AutomationCondition.eager()` instead.", ) def eager(max_materializations_per_minute: Optional[int] = 1) -> "AutoMaterializePolicy": """Constructs an eager AutoMaterializePolicy. Args: max_materializations_per_minute (Optional[int]): The maximum number of auto-materializations for this asset that may be initiated per minute. If this limit is exceeded, the partitions which would have been materialized will be discarded, and will require manual materialization in order to be updated. Defaults to 1. """ from dagster._core.definitions.auto_materialize_rule import AutoMaterializeRule return AutoMaterializePolicy( rules={ AutoMaterializeRule.materialize_on_missing(), AutoMaterializeRule.materialize_on_parent_updated(), AutoMaterializeRule.materialize_on_required_for_freshness(), AutoMaterializeRule.skip_on_parent_outdated(), AutoMaterializeRule.skip_on_parent_missing(), AutoMaterializeRule.skip_on_required_but_nonexistent_parents(), AutoMaterializeRule.skip_on_backfill_in_progress(), }, max_materializations_per_minute=check.opt_int_param( max_materializations_per_minute, "max_materializations_per_minute" ), ) @public @staticmethod @deprecated( breaking_version="1.10.0", additional_warn_text="Use `AutomationCondition.any_downstream_conditions()` instead.", ) def lazy(max_materializations_per_minute: Optional[int] = 1) -> "AutoMaterializePolicy": """(Deprecated) Constructs a lazy AutoMaterializePolicy. Args: max_materializations_per_minute (Optional[int]): The maximum number of auto-materializations for this asset that may be initiated per minute. If this limit is exceeded, the partitions which would have been materialized will be discarded, and will require manual materialization in order to be updated. Defaults to 1. """ from dagster._core.definitions.auto_materialize_rule import AutoMaterializeRule return AutoMaterializePolicy( rules={ AutoMaterializeRule.materialize_on_required_for_freshness(), AutoMaterializeRule.skip_on_parent_outdated(), AutoMaterializeRule.skip_on_parent_missing(), AutoMaterializeRule.skip_on_required_but_nonexistent_parents(), AutoMaterializeRule.skip_on_backfill_in_progress(), }, max_materializations_per_minute=check.opt_int_param( max_materializations_per_minute, "max_materializations_per_minute" ), ) @public def without_rules(self, *rules_to_remove: "AutoMaterializeRule") -> "AutoMaterializePolicy": """Constructs a copy of this policy with the specified rules removed. Raises an error if any of the arguments are not rules in this policy. """ non_matching_rules = set(rules_to_remove).difference(self.rules) check.param_invariant( not non_matching_rules, "rules_to_remove", f"Rules {[rule for rule in rules_to_remove if rule in non_matching_rules]} do not" " exist in this policy.", ) return self._replace( rules=self.rules.difference(set(rules_to_remove)), ) @public def with_rules(self, *rules_to_add: "AutoMaterializeRule") -> "AutoMaterializePolicy": """Constructs a copy of this policy with the specified rules added. If an instance of a provided rule with the same type exists on this policy, it will be replaced. """ new_rule_types = {type(rule) for rule in rules_to_add} return self._replace( rules=set(rules_to_add).union( {rule for rule in self.rules if type(rule) not in new_rule_types} ) ) @property def policy_type(self) -> AutoMaterializePolicyType: from dagster._core.definitions.auto_materialize_rule import AutoMaterializeRule if AutoMaterializeRule.materialize_on_parent_updated() in self.rules: return AutoMaterializePolicyType.EAGER return AutoMaterializePolicyType.LAZY @property def rule_snapshots(self) -> Sequence["AutoMaterializeRuleSnapshot"]: return [rule.to_snapshot() for rule in self.rules] def to_automation_condition(self) -> "AutomationCondition": """Converts a set of materialize / skip rules into a single binary expression.""" from dagster._core.definitions.auto_materialize_rule_impls import ( DiscardOnMaxMaterializationsExceededRule, ) from dagster._core.definitions.declarative_automation.operators import ( AndAutomationCondition, NotAutomationCondition, OrAutomationCondition, ) if self.asset_condition is not None: return self.asset_condition materialize_condition = OrAutomationCondition( operands=[ rule.to_asset_condition() for rule in sorted(self.materialize_rules, key=lambda rule: rule.description) ] ) skip_condition = OrAutomationCondition( operands=[ rule.to_asset_condition() for rule in sorted(self.skip_rules, key=lambda rule: rule.description) ] ) children = [ materialize_condition, NotAutomationCondition(operand=skip_condition), ] if self.max_materializations_per_minute: discard_condition = DiscardOnMaxMaterializationsExceededRule( self.max_materializations_per_minute ).to_asset_condition() children.append(NotAutomationCondition(operand=discard_condition)) # results in an expression of the form (m1 | m2 | ... | mn) & ~(s1 | s2 | ... | sn) & ~d return AndAutomationCondition(operands=children) def __eq__(self, other) -> bool: return ( super().__eq__(other) or self.to_automation_condition() == other.to_automation_condition() )
AutoMaterializePolicy
python
walkccc__LeetCode
solutions/3231. Minimum Number of Increasing Subsequence to Be Removed/3231.py
{ "start": 0, "end": 444 }
class ____: def minOperations(self, nums: list[int]) -> int: return self._lengthOfLIS(nums[::-1]) def _lengthOfLIS(self, nums: list[int]) -> int: # tails[i] := the minimum tail of all the increasing subsequences having # length i + 1 tails = [] for num in nums: if not tails or num >= tails[-1]: tails.append(num) else: tails[bisect.bisect_right(tails, num)] = num return len(tails)
Solution
python
apache__airflow
airflow-ctl/src/airflowctl/api/operations.py
{ "start": 6593, "end": 10971 }
class ____(BaseOperations): """Assets operations.""" def get(self, asset_id: str) -> AssetResponse | ServerResponseError: """Get an asset from the API server.""" try: self.response = self.client.get(f"assets/{asset_id}") return AssetResponse.model_validate_json(self.response.content) except ServerResponseError as e: raise e def get_by_alias(self, alias: str) -> AssetAliasResponse | ServerResponseError: """Get an asset by alias from the API server.""" try: self.response = self.client.get(f"assets/aliases/{alias}") return AssetAliasResponse.model_validate_json(self.response.content) except ServerResponseError as e: raise e def list(self) -> AssetCollectionResponse | ServerResponseError: """List all assets from the API server.""" return super().execute_list(path="assets", data_model=AssetCollectionResponse) def list_by_alias(self) -> AssetAliasCollectionResponse | ServerResponseError: """List all assets by alias from the API server.""" return super().execute_list(path="/assets/aliases", data_model=AssetAliasCollectionResponse) def create_event( self, asset_event_body: CreateAssetEventsBody ) -> AssetEventResponse | ServerResponseError: """Create an asset event.""" try: # Ensure extra is initialised before sent to API if asset_event_body.extra is None: asset_event_body.extra = {} self.response = self.client.post("assets/events", json=asset_event_body.model_dump(mode="json")) return AssetEventResponse.model_validate_json(self.response.content) except ServerResponseError as e: raise e def materialize(self, asset_id: str) -> DAGRunResponse | ServerResponseError: """Materialize an asset.""" try: self.response = self.client.post(f"assets/{asset_id}/materialize") return DAGRunResponse.model_validate_json(self.response.content) except ServerResponseError as e: raise e def get_queued_events(self, asset_id: str) -> QueuedEventCollectionResponse | ServerResponseError: """Get queued events for an asset.""" try: self.response = self.client.get(f"assets/{asset_id}/queuedEvents") return QueuedEventCollectionResponse.model_validate_json(self.response.content) except ServerResponseError as e: raise e def get_dag_queued_events( self, dag_id: str, before: str ) -> QueuedEventCollectionResponse | ServerResponseError: """Get queued events for a dag.""" try: self.response = self.client.get(f"dags/{dag_id}/assets/queuedEvents", params={"before": before}) return QueuedEventCollectionResponse.model_validate_json(self.response.content) except ServerResponseError as e: raise e def get_dag_queued_event(self, dag_id: str, asset_id: str) -> QueuedEventResponse | ServerResponseError: """Get a queued event for a dag.""" try: self.response = self.client.get(f"dags/{dag_id}/assets/{asset_id}/queuedEvents") return QueuedEventResponse.model_validate_json(self.response.content) except ServerResponseError as e: raise e def delete_queued_events(self, asset_id: str) -> str | ServerResponseError: """Delete a queued event for an asset.""" try: self.client.delete(f"assets/{asset_id}/queuedEvents/") return asset_id except ServerResponseError as e: raise e def delete_dag_queued_events(self, dag_id: str, before: str) -> str | ServerResponseError: """Delete a queued event for a dag.""" try: self.client.delete(f"assets/dags/{dag_id}/queuedEvents", params={"before": before}) return dag_id except ServerResponseError as e: raise e def delete_queued_event(self, dag_id: str, asset_id: str) -> str | ServerResponseError: """Delete a queued event for a dag.""" try: self.client.delete(f"assets/dags/{dag_id}/assets/{asset_id}/queuedEvents/") return asset_id except ServerResponseError as e: raise e
AssetsOperations
python
ray-project__ray
rllib/utils/tf_utils.py
{ "start": 28787, "end": 36914 }
class ____: """A class used to set and get weights for Tensorflow networks. Attributes: sess (tf.Session): The tensorflow session used to run assignment. variables (Dict[str, tf.Variable]): Extracted variables from the loss or additional variables that are passed in. placeholders (Dict[str, tf.placeholders]): Placeholders for weights. assignment_nodes (Dict[str, tf.Tensor]): Nodes that assign weights. """ def __init__(self, output, sess=None, input_variables=None): """Creates TensorFlowVariables containing extracted variables. The variables are extracted by performing a BFS search on the dependency graph with loss as the root node. After the tree is traversed and those variables are collected, we append input_variables to the collected variables. For each variable in the list, the variable has a placeholder and assignment operation created for it. Args: output (tf.Operation, List[tf.Operation]): The tensorflow operation to extract all variables from. sess (Optional[tf.Session]): Optional tf.Session used for running the get and set methods in tf graph mode. Use None for tf eager. input_variables (List[tf.Variables]): Variables to include in the list. """ self.sess = sess output = force_list(output) queue = deque(output) variable_names = [] explored_inputs = set(output) # We do a BFS on the dependency graph of the input function to find # the variables. while len(queue) != 0: tf_obj = queue.popleft() if tf_obj is None: continue # The object put into the queue is not necessarily an operation, # so we want the op attribute to get the operation underlying the # object. Only operations contain the inputs that we can explore. if hasattr(tf_obj, "op"): tf_obj = tf_obj.op for input_op in tf_obj.inputs: if input_op not in explored_inputs: queue.append(input_op) explored_inputs.add(input_op) # Tensorflow control inputs can be circular, so we keep track of # explored operations. for control in tf_obj.control_inputs: if control not in explored_inputs: queue.append(control) explored_inputs.add(control) if "Variable" in tf_obj.node_def.op or "VarHandle" in tf_obj.node_def.op: variable_names.append(tf_obj.node_def.name) self.variables = OrderedDict() variable_list = [ v for v in tf1.global_variables() if v.op.node_def.name in variable_names ] if input_variables is not None: variable_list += input_variables if not tf1.executing_eagerly(): for v in variable_list: self.variables[v.op.node_def.name] = v self.placeholders = {} self.assignment_nodes = {} # Create new placeholders to put in custom weights. for k, var in self.variables.items(): self.placeholders[k] = tf1.placeholder( var.value().dtype, var.get_shape().as_list(), name="Placeholder_" + k, ) self.assignment_nodes[k] = var.assign(self.placeholders[k]) else: for v in variable_list: self.variables[v.name] = v def get_flat_size(self): """Returns the total length of all of the flattened variables. Returns: The length of all flattened variables concatenated. """ return sum(np.prod(v.get_shape().as_list()) for v in self.variables.values()) def get_flat(self): """Gets the weights and returns them as a flat array. Returns: 1D Array containing the flattened weights. """ # Eager mode. if not self.sess: return np.concatenate( [v.numpy().flatten() for v in self.variables.values()] ) # Graph mode. return np.concatenate( [v.eval(session=self.sess).flatten() for v in self.variables.values()] ) def set_flat(self, new_weights): """Sets the weights to new_weights, converting from a flat array. Note: You can only set all weights in the network using this function, i.e., the length of the array must match get_flat_size. Args: new_weights (np.ndarray): Flat array containing weights. """ shapes = [v.get_shape().as_list() for v in self.variables.values()] arrays = _unflatten(new_weights, shapes) if not self.sess: for v, a in zip(self.variables.values(), arrays): v.assign(a) else: placeholders = [self.placeholders[k] for k, v in self.variables.items()] self.sess.run( list(self.assignment_nodes.values()), feed_dict=dict(zip(placeholders, arrays)), ) def get_weights(self): """Returns a dictionary containing the weights of the network. Returns: Dictionary mapping variable names to their weights. """ # Eager mode. if not self.sess: return self.variables # Graph mode. return self.sess.run(self.variables) def set_weights(self, new_weights: dict): """Sets the weights to new_weights. Note: Can set subsets of variables as well, by only passing in the variables you want to be set. Args: new_weights: Dictionary mapping variable names to their weights. """ if self.sess is None: for name, var in self.variables.items(): var.assign(new_weights[name]) else: assign_list, feed_dict = self._assign_weights(new_weights) self.sess.run(assign_list, feed_dict=feed_dict) def _assign_weights(self, weights): """Sets weigths using exact or closest assignable variable name Args: weights: Dictionary mapping variable names to their weights. Returns: Tuple[List, Dict]: assigned variables list, dict of placeholders and weights """ assigned = [] feed_dict = {} assignable = set(self.assignment_nodes.keys()) def nb_common_elem(l1, l2): return len([e for e in l1 if e in l2]) def assign(name, value): feed_dict[self.placeholders[name]] = value assigned.append(name) assignable.remove(name) for name, value in weights.items(): if name in assignable: assign(name, value) else: common = { var: nb_common_elem(name.split("/"), var.split("/")) for var in assignable } select = [ close_var for close_var, cn in sorted(common.items(), key=lambda i: -i[1]) if cn > 0 and value.shape == self.assignment_nodes[close_var].shape ] if select: assign(select[0], value) assert assigned, ( "No variables in the input matched those in the network. " "Possible cause: Two networks were defined in the same " "TensorFlow graph. To fix this, place each network " "definition in its own tf.Graph." ) assert len(assigned) == len(weights), ( "All weights couldn't be assigned because no variable " "had an exact/close name or had same shape" ) return [self.assignment_nodes[v] for v in assigned], feed_dict
TensorFlowVariables
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/pipeline_job.py
{ "start": 20540, "end": 23540 }
class ____(GoogleCloudBaseOperator): """ Delete a Pipeline job. :param project_id: Required. The ID of the Google Cloud project that the service belongs to. :param region: Required. The ID of the Google Cloud region that the service belongs to. :param pipeline_job_id: Required. The ID of the PipelineJob resource to be deleted. :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 = [ "region", "project_id", "pipeline_job_id", "impersonation_chain", ] def __init__( self, *, project_id: str, region: str, pipeline_job_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.pipeline_job_id = pipeline_job_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 = PipelineJobHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain, ) try: self.log.info("Deleting Pipeline job: %s", self.pipeline_job_id) operation = hook.delete_pipeline_job( region=self.region, project_id=self.project_id, pipeline_job_id=self.pipeline_job_id, retry=self.retry, timeout=self.timeout, metadata=self.metadata, ) hook.wait_for_operation(timeout=self.timeout, operation=operation) self.log.info("Pipeline job was deleted.") except NotFound: self.log.info("The Pipeline Job ID %s does not exist.", self.pipeline_job_id)
DeletePipelineJobOperator
python
joblib__joblib
joblib/hashing.py
{ "start": 5761, "end": 10694 }
class ____(Hasher): """Special case the hasher for when numpy is loaded.""" def __init__(self, hash_name="md5", coerce_mmap=False): """ Parameters ---------- hash_name: string The hash algorithm to be used coerce_mmap: boolean Make no difference between np.memmap and np.ndarray objects. """ self.coerce_mmap = coerce_mmap Hasher.__init__(self, hash_name=hash_name) # delayed import of numpy, to avoid tight coupling import numpy as np self.np = np if hasattr(np, "getbuffer"): self._getbuffer = np.getbuffer else: self._getbuffer = memoryview def save(self, obj): """Subclass the save method, to hash ndarray subclass, rather than pickling them. Off course, this is a total abuse of the Pickler class. """ if isinstance(obj, self.np.ndarray) and not obj.dtype.hasobject: # Compute a hash of the object # The update function of the hash requires a c_contiguous buffer. if obj.shape == (): # 0d arrays need to be flattened because viewing them as bytes # raises a ValueError exception. obj_c_contiguous = obj.flatten() elif obj.flags.c_contiguous: obj_c_contiguous = obj elif obj.flags.f_contiguous: obj_c_contiguous = obj.T else: # Cater for non-single-segment arrays: this creates a # copy, and thus alleviates this issue. # XXX: There might be a more efficient way of doing this obj_c_contiguous = obj.flatten() # memoryview is not supported for some dtypes, e.g. datetime64, see # https://github.com/numpy/numpy/issues/4983. The # workaround is to view the array as bytes before # taking the memoryview. self._hash.update(self._getbuffer(obj_c_contiguous.view(self.np.uint8))) # We store the class, to be able to distinguish between # Objects with the same binary content, but different # classes. if self.coerce_mmap and isinstance(obj, self.np.memmap): # We don't make the difference between memmap and # normal ndarrays, to be able to reload previously # computed results with memmap. klass = self.np.ndarray else: klass = obj.__class__ # We also return the dtype and the shape, to distinguish # different views on the same data with different dtypes. # The object will be pickled by the pickler hashed at the end. obj = (klass, ("HASHED", obj.dtype, obj.shape, obj.strides)) elif isinstance(obj, self.np.dtype): # numpy.dtype consistent hashing is tricky to get right. This comes # from the fact that atomic np.dtype objects are interned: # ``np.dtype('f4') is np.dtype('f4')``. The situation is # complicated by the fact that this interning does not resist a # simple pickle.load/dump roundtrip: # ``pickle.loads(pickle.dumps(np.dtype('f4'))) is not # np.dtype('f4') Because pickle relies on memoization during # pickling, it is easy to # produce different hashes for seemingly identical objects, such as # ``[np.dtype('f4'), np.dtype('f4')]`` # and ``[np.dtype('f4'), pickle.loads(pickle.dumps('f4'))]``. # To prevent memoization from interfering with hashing, we isolate # the serialization (and thus the pickle memoization) of each dtype # using each time a different ``pickle.dumps`` call unrelated to # the current Hasher instance. self._hash.update("_HASHED_DTYPE".encode("utf-8")) self._hash.update(pickle.dumps(obj)) return Hasher.save(self, obj) def hash(obj, hash_name="md5", coerce_mmap=False): """Quick calculation of a hash to identify uniquely Python objects containing numpy arrays. Parameters ---------- hash_name: 'md5' or 'sha1' Hashing algorithm used. sha1 is supposedly safer, but md5 is faster. coerce_mmap: boolean Make no difference between np.memmap and np.ndarray """ valid_hash_names = ("md5", "sha1") if hash_name not in valid_hash_names: raise ValueError( "Valid options for 'hash_name' are {}. Got hash_name={!r} instead.".format( valid_hash_names, hash_name ) ) if "numpy" in sys.modules: hasher = NumpyHasher(hash_name=hash_name, coerce_mmap=coerce_mmap) else: hasher = Hasher(hash_name=hash_name) return hasher.hash(obj)
NumpyHasher
python
python__mypy
mypy/dmypy/client.py
{ "start": 788, "end": 8774 }
class ____(argparse.RawDescriptionHelpFormatter): def __init__(self, prog: str, **kwargs: Any) -> None: super().__init__(prog=prog, max_help_position=30, **kwargs) parser = argparse.ArgumentParser( prog="dmypy", description="Client for mypy daemon mode", fromfile_prefix_chars="@" ) parser.set_defaults(action=None) parser.add_argument( "--status-file", default=DEFAULT_STATUS_FILE, help="status file to retrieve daemon details" ) parser.add_argument( "-V", "--version", action="version", version="%(prog)s " + __version__, help="Show program's version number and exit", ) subparsers = parser.add_subparsers() start_parser = p = subparsers.add_parser("start", help="Start daemon") p.add_argument("--log-file", metavar="FILE", type=str, help="Direct daemon stdout/stderr to FILE") p.add_argument( "--timeout", metavar="TIMEOUT", type=int, help="Server shutdown timeout (in seconds)" ) p.add_argument( "flags", metavar="FLAG", nargs="*", type=str, help="Regular mypy flags (precede with --)" ) restart_parser = p = subparsers.add_parser( "restart", help="Restart daemon (stop or kill followed by start)" ) p.add_argument("--log-file", metavar="FILE", type=str, help="Direct daemon stdout/stderr to FILE") p.add_argument( "--timeout", metavar="TIMEOUT", type=int, help="Server shutdown timeout (in seconds)" ) p.add_argument( "flags", metavar="FLAG", nargs="*", type=str, help="Regular mypy flags (precede with --)" ) status_parser = p = subparsers.add_parser("status", help="Show daemon status") p.add_argument("-v", "--verbose", action="store_true", help="Print detailed status") p.add_argument("--fswatcher-dump-file", help="Collect information about the current file state") stop_parser = p = subparsers.add_parser("stop", help="Stop daemon (asks it politely to go away)") kill_parser = p = subparsers.add_parser("kill", help="Kill daemon (kills the process)") check_parser = p = subparsers.add_parser( "check", formatter_class=AugmentedHelpFormatter, help="Check some files (requires daemon)" ) p.add_argument("-v", "--verbose", action="store_true", help="Print detailed status") p.add_argument("-q", "--quiet", action="store_true", help=argparse.SUPPRESS) # Deprecated p.add_argument("--junit-xml", help="Write junit.xml to the given file") p.add_argument("--perf-stats-file", help="write performance information to the given file") p.add_argument("files", metavar="FILE", nargs="+", help="File (or directory) to check") p.add_argument( "--export-types", action="store_true", help="Store types of all expressions in a shared location (useful for inspections)", ) run_parser = p = subparsers.add_parser( "run", formatter_class=AugmentedHelpFormatter, help="Check some files, [re]starting daemon if necessary", ) p.add_argument("-v", "--verbose", action="store_true", help="Print detailed status") p.add_argument("--junit-xml", help="Write junit.xml to the given file") p.add_argument("--perf-stats-file", help="write performance information to the given file") p.add_argument( "--timeout", metavar="TIMEOUT", type=int, help="Server shutdown timeout (in seconds)" ) p.add_argument("--log-file", metavar="FILE", type=str, help="Direct daemon stdout/stderr to FILE") p.add_argument( "--export-types", action="store_true", help="Store types of all expressions in a shared location (useful for inspections)", ) p.add_argument( "flags", metavar="ARG", nargs="*", type=str, help="Regular mypy flags and files (precede with --)", ) recheck_parser = p = subparsers.add_parser( "recheck", formatter_class=AugmentedHelpFormatter, help="Re-check the previous list of files, with optional modifications (requires daemon)", ) p.add_argument("-v", "--verbose", action="store_true", help="Print detailed status") p.add_argument("-q", "--quiet", action="store_true", help=argparse.SUPPRESS) # Deprecated p.add_argument("--junit-xml", help="Write junit.xml to the given file") p.add_argument("--perf-stats-file", help="write performance information to the given file") p.add_argument( "--export-types", action="store_true", help="Store types of all expressions in a shared location (useful for inspections)", ) p.add_argument( "--update", metavar="FILE", nargs="*", help="Files in the run to add or check again (default: all from previous run)", ) p.add_argument("--remove", metavar="FILE", nargs="*", help="Files to remove from the run") suggest_parser = p = subparsers.add_parser( "suggest", help="Suggest a signature or show call sites for a specific function" ) p.add_argument( "function", metavar="FUNCTION", type=str, help="Function specified as '[package.]module.[class.]function'", ) p.add_argument( "--json", action="store_true", help="Produce json that pyannotate can use to apply a suggestion", ) p.add_argument( "--no-errors", action="store_true", help="Only produce suggestions that cause no errors" ) p.add_argument( "--no-any", action="store_true", help="Only produce suggestions that don't contain Any" ) p.add_argument( "--flex-any", type=float, help="Allow anys in types if they go above a certain score (scores are from 0-1)", ) p.add_argument( "--callsites", action="store_true", help="Find callsites instead of suggesting a type" ) p.add_argument( "--use-fixme", metavar="NAME", type=str, help="A dummy name to use instead of Any for types that can't be inferred", ) p.add_argument( "--max-guesses", type=int, help="Set the maximum number of types to try for a function (default 64)", ) inspect_parser = p = subparsers.add_parser( "inspect", help="Locate and statically inspect expression(s)" ) p.add_argument( "location", metavar="LOCATION", type=str, help="Location specified as path/to/file.py:line:column[:end_line:end_column]." " If position is given (i.e. only line and column), this will return all" " enclosing expressions", ) p.add_argument( "--show", metavar="INSPECTION", type=str, default="type", choices=["type", "attrs", "definition"], help="What kind of inspection to run", ) p.add_argument( "--verbose", "-v", action="count", default=0, help="Increase verbosity of the type string representation (can be repeated)", ) p.add_argument( "--limit", metavar="NUM", type=int, default=0, help="Return at most NUM innermost expressions (if position is given); 0 means no limit", ) p.add_argument( "--include-span", action="store_true", help="Prepend each inspection result with the span of corresponding expression" ' (e.g. 1:2:3:4:"int")', ) p.add_argument( "--include-kind", action="store_true", help="Prepend each inspection result with the kind of corresponding expression" ' (e.g. NameExpr:"int")', ) p.add_argument( "--include-object-attrs", action="store_true", help='Include attributes of "object" in "attrs" inspection', ) p.add_argument( "--union-attrs", action="store_true", help="Include attributes valid for some of possible expression types" " (by default an intersection is returned)", ) p.add_argument( "--force-reload", action="store_true", help="Re-parse and re-type-check file before inspection (may be slow)", ) hang_parser = p = subparsers.add_parser("hang", help="Hang for 100 seconds") daemon_parser = p = subparsers.add_parser("daemon", help="Run daemon in foreground") p.add_argument( "--timeout", metavar="TIMEOUT", type=int, help="Server shutdown timeout (in seconds)" ) p.add_argument("--log-file", metavar="FILE", type=str, help="Direct daemon stdout/stderr to FILE") p.add_argument( "flags", metavar="FLAG", nargs="*", type=str, help="Regular mypy flags (precede with --)" ) p.add_argument("--options-data", help=argparse.SUPPRESS) help_parser = p = subparsers.add_parser("help") del p
AugmentedHelpFormatter
python
RaRe-Technologies__gensim
gensim/topic_coherence/text_analysis.py
{ "start": 21721, "end": 24317 }
class ____(UsesDictionary): """Accumulate context vectors for words using word vector embeddings. Attributes ---------- model: Word2Vec (:class:`~gensim.models.keyedvectors.KeyedVectors`) If None, a new Word2Vec model is trained on the given text corpus. Otherwise, it should be a pre-trained Word2Vec context vectors. model_kwargs: if model is None, these keyword arguments will be passed through to the Word2Vec constructor. """ def __init__(self, relevant_ids, dictionary, model=None, **model_kwargs): super(WordVectorsAccumulator, self).__init__(relevant_ids, dictionary) self.model = model self.model_kwargs = model_kwargs def not_in_vocab(self, words): uniq_words = set(utils.flatten(words)) return set(word for word in uniq_words if word not in self.model) def get_occurrences(self, word): """Return number of docs the word occurs in, once `accumulate` has been called.""" try: self.token2id[word] # is this a token or an id? except KeyError: word = self.dictionary.id2token[word] return self.model.get_vecattr(word, 'count') def get_co_occurrences(self, word1, word2): """Return number of docs the words co-occur in, once `accumulate` has been called.""" raise NotImplementedError("Word2Vec model does not support co-occurrence counting") def accumulate(self, texts, window_size): if self.model is not None: logger.debug("model is already trained; no accumulation necessary") return self kwargs = self.model_kwargs.copy() if window_size is not None: kwargs['window'] = window_size kwargs['min_count'] = kwargs.get('min_count', 1) kwargs['sg'] = kwargs.get('sg', 1) kwargs['hs'] = kwargs.get('hw', 0) self.model = Word2Vec(**kwargs) self.model.build_vocab(texts) self.model.train(texts, total_examples=self.model.corpus_count, epochs=self.model.epochs) self.model = self.model.wv # retain KeyedVectors return self def ids_similarity(self, ids1, ids2): words1 = self._words_with_embeddings(ids1) words2 = self._words_with_embeddings(ids2) return self.model.n_similarity(words1, words2) def _words_with_embeddings(self, ids): if not hasattr(ids, '__iter__'): ids = [ids] words = [self.dictionary.id2token[word_id] for word_id in ids] return [word for word in words if word in self.model]
WordVectorsAccumulator
python
huggingface__transformers
src/transformers/models/dac/modeling_dac.py
{ "start": 7752, "end": 9109 }
class ____(nn.Module): """ A residual unit composed of Snake1d and weight-normalized Conv1d layers with dilations. """ def __init__(self, dimension: int = 16, dilation: int = 1): super().__init__() pad = ((7 - 1) * dilation) // 2 self.snake1 = Snake1d(dimension) self.conv1 = nn.Conv1d(dimension, dimension, kernel_size=7, dilation=dilation, padding=pad) self.snake2 = Snake1d(dimension) self.conv2 = nn.Conv1d(dimension, dimension, kernel_size=1) def forward(self, hidden_state): """ Forward pass through the residual unit. Args: hidden_state (`torch.Tensor` of shape `(batch_size, channels, time_steps)`): Input tensor . Returns: output_tensor (`torch.Tensor` of shape `(batch_size, channels, time_steps)`): Input tensor after passing through the residual unit. """ output_tensor = hidden_state output_tensor = self.conv1(self.snake1(output_tensor)) output_tensor = self.conv2(self.snake2(output_tensor)) padding = (hidden_state.shape[-1] - output_tensor.shape[-1]) // 2 if padding > 0: hidden_state = hidden_state[..., padding:-padding] output_tensor = hidden_state + output_tensor return output_tensor
DacResidualUnit
python
jina-ai__jina
tests/integration/concurrent_clients/test_multithread_client.py
{ "start": 178, "end": 1562 }
class ____(Executor): @requests def foo(self, docs, **kwargs): for doc in docs: doc.text = 'I am coming from MyExecutor' def flow_run(flow, stop_event): with flow: flow.block(stop_event) def client_post(doc, port, client): result = client.post(on='/', inputs=doc)[0] print(f'doc.id {doc.id} vs result.id {result.id}') return result def test_multithread_client(capsys): port = random_port() stop_event = threading.Event() flow = Flow(port=port).add(uses=MyExecutor) t = threading.Thread(target=flow_run, args=(flow, stop_event)) c = Client(port=port) try: with capsys.disabled(): t.start() time.sleep(5) with ThreadPoolExecutor(max_workers=50) as pool: tasks = [] for i in range(1000): doc = Document(id=f'{i}', text='hello world') task = pool.submit(client_post, doc, port, c) tasks.append(task) for i, task in enumerate(tasks): result = task.result() assert result.id == f'{i}' assert result.text == 'I am coming from MyExecutor' with capsys.disabled(): stdout, stderr = capsys.readouterr() assert 'BlockingIOError' not in stderr finally: stop_event.set() t.join()
MyExecutor
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/links/managed_kafka.py
{ "start": 1451, "end": 1670 }
class ____(BaseGoogleLink): """Helper class for constructing Apache Kafka Cluster link.""" name = "Apache Kafka Cluster" key = "cluster_conf" format_str = MANAGED_KAFKA_CLUSTER_LINK
ApacheKafkaClusterLink