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
jazzband__django-polymorphic
src/polymorphic/tests/models.py
{ "start": 9642, "end": 9877 }
class ____(ShowFieldType, PolymorphicModel): ctype = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True, editable=False) # class with a parent_link to superclass, and a related_name back to subclass
RelatedNameClash
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/internal/constants_ast.py
{ "start": 3754, "end": 9989 }
class ____(NodeVisitor): CONSTANTS_LIMIT: int = 1024 def __init__(self, *, limit: bool): super().__init__() self.constants = Constants() self.limit = limit def _add_constant(self, value: object) -> None: if self.limit and len(self.constants) >= self.CONSTANTS_LIMIT: raise TooManyConstants if isinstance(value, str) and ( value.isspace() or value == "" # long strings are unlikely to be useful. or len(value) > 20 ): return if isinstance(value, bytes) and ( value == b"" # long bytes seem plausibly more likely to be useful than long strings # (e.g. AES-256 has a 32 byte key), but we still want to cap at some # point to avoid performance issues. or len(value) > 50 ): return if isinstance(value, bool): return if isinstance(value, float) and math.isinf(value): # we already upweight inf. return if isinstance(value, int) and -100 < value < 100: # we already upweight small integers. return if isinstance(value, (int, float, bytes, str)): self.constants.add(value) return # I don't kow what case could go here, but am also not confident there # isn't one. return # pragma: no cover def visit_UnaryOp(self, node: UnaryOp) -> None: # `a = -1` is actually a combination of a USub and the constant 1. if ( isinstance(node.op, USub) and isinstance(node.operand, Constant) and isinstance(node.operand.value, (int, float)) and not isinstance(node.operand.value, bool) ): self._add_constant(-node.operand.value) # don't recurse on this node to avoid adding the positive variant return self.generic_visit(node) def visit_Expr(self, node: Expr) -> None: if isinstance(node.value, Constant) and isinstance(node.value.value, str): return self.generic_visit(node) def visit_JoinedStr(self, node): # dont recurse on JoinedStr, i.e. f strings. Constants that appear *only* # in f strings are unlikely to be helpful. return def visit_Constant(self, node): self._add_constant(node.value) self.generic_visit(node) def _constants_from_source(source: str | bytes, *, limit: bool) -> Constants: tree = ast.parse(source) visitor = ConstantVisitor(limit=limit) try: visitor.visit(tree) except TooManyConstants: # in the case of an incomplete collection, return nothing, to avoid # muddying caches etc. return Constants() return visitor.constants def _constants_file_str(constants: Constants) -> str: return str(sorted(constants, key=lambda v: (str(type(v)), v))) @lru_cache(4096) def constants_from_module(module: ModuleType, *, limit: bool = True) -> Constants: try: module_file = inspect.getsourcefile(module) # use type: ignore because we know this might error source_bytes = Path(module_file).read_bytes() # type: ignore except Exception: return Constants() if limit and len(source_bytes) > 512 * 1024: # Skip files over 512kb. For reference, the largest source file # in Hypothesis is strategies/_internal/core.py at 107kb at time # of writing. return Constants() source_hash = hashlib.sha1(source_bytes).hexdigest()[:16] # separate cache files for each limit param. see discussion in pull/4398 cache_p = storage_directory("constants") / ( source_hash + ("" if limit else "_nolimit") ) try: return _constants_from_source(cache_p.read_bytes(), limit=limit) except Exception: # if the cached location doesn't exist, or it does exist but there was # a problem reading it, fall back to standard computation of the constants pass try: constants = _constants_from_source(source_bytes, limit=limit) except Exception: # A bunch of things can go wrong here. # * ast.parse may fail on the source code # * NodeVisitor may hit a RecursionError (see many related issues on # e.g. libcst https://github.com/Instagram/LibCST/issues?q=recursion), # or a MemoryError (`"[1, " * 200 + "]" * 200`) return Constants() try: cache_p.parent.mkdir(parents=True, exist_ok=True) cache_p.write_text( f"# file: {module_file}\n# hypothesis_version: {hypothesis.__version__}\n\n" # somewhat arbitrary sort order. The cache file doesn't *have* to be # stable... but it is aesthetically pleasing, and means we could rely # on it in the future! + _constants_file_str(constants), encoding="utf-8", ) except Exception: # pragma: no cover pass return constants @lru_cache(4096) def is_local_module_file(path: str) -> bool: from hypothesis.internal.scrutineer import ModuleLocation return ( # Skip expensive path lookup for stdlib modules. # This will cause false negatives if a user names their module the # same as a stdlib module. path not in sys.stdlib_module_names # A path containing site-packages is extremely likely to be # ModuleLocation.SITE_PACKAGES. Skip the expensive path lookup here. and "/site-packages/" not in path and ModuleLocation.from_path(path) is ModuleLocation.LOCAL # normally, hypothesis is a third-party library and is not returned # by local_modules. However, if it is installed as an editable package # with pip install -e, then we will pick up on it. Just hardcode an # ignore here. and not is_hypothesis_file(path) # avoid collecting constants from test files and not ( "test" in (p := Path(path)).parts or "tests" in p.parts or p.stem.startswith("test_") or p.stem.endswith("_test") ) )
ConstantVisitor
python
PyCQA__pylint
tests/functional/b/bugfix_local_scope_metaclass_1177.py
{ "start": 165, "end": 487 }
class ____(metaclass=Meta): pass def func_scope(): class Meta2(type): pass class Class2(metaclass=Meta2): pass return Class2 def func_scope_with_metaclass_from_call(): def get_type(): return type class Class2(metaclass=get_type()): pass return Class2
Class
python
plotly__plotly.py
plotly/graph_objs/layout/legend/_font.py
{ "start": 235, "end": 9882 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout.legend" _path_str = "layout.legend.font" _valid_props = { "color", "family", "lineposition", "shadow", "size", "style", "textcase", "variant", "weight", } @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 Returns ------- str """ return self["color"] @color.setter def color(self, val): self["color"] = 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 Returns ------- str """ return self["family"] @family.setter def family(self, val): self["family"] = 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') Returns ------- Any """ return self["lineposition"] @lineposition.setter def lineposition(self, val): self["lineposition"] = 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 Returns ------- str """ return self["shadow"] @shadow.setter def shadow(self, val): self["shadow"] = 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] Returns ------- int|float """ return self["size"] @size.setter def size(self, val): self["size"] = 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'] Returns ------- Any """ return self["style"] @style.setter def style(self, val): self["style"] = 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'] Returns ------- Any """ return self["textcase"] @textcase.setter def textcase(self, val): self["textcase"] = 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'] Returns ------- Any """ return self["variant"] @variant.setter def variant(self, val): self["variant"] = 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') Returns ------- int """ return self["weight"] @weight.setter def weight(self, val): self["weight"] = val @property def _prop_descriptions(self): return """\ 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. 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. 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. size style Sets whether a font should be styled with a normal or italic face from its family. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. variant Sets the variant of the font. weight Sets the weight (or boldness) of the font. """ def __init__( self, arg=None, color=None, family=None, lineposition=None, shadow=None, size=None, style=None, textcase=None, variant=None, weight=None, **kwargs, ): """ Construct a new Font object Sets the font used to text the legend items. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.layout.legend.Font` 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. 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. 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. size style Sets whether a font should be styled with a normal or italic face from its family. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. variant Sets the variant of the font. weight Sets the weight (or boldness) of the font. 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.layout.legend.Font constructor must be a dict or an instance of :class:`plotly.graph_objs.layout.legend.Font`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("color", arg, color) self._set_property("family", arg, family) self._set_property("lineposition", arg, lineposition) self._set_property("shadow", arg, shadow) self._set_property("size", arg, size) self._set_property("style", arg, style) self._set_property("textcase", arg, textcase) self._set_property("variant", arg, variant) self._set_property("weight", arg, weight) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Font
python
pypa__pip
src/pip/_internal/commands/cache.py
{ "start": 426, "end": 8230 }
class ____(Command): """ Inspect and manage pip's wheel cache. Subcommands: - dir: Show the cache directory. - info: Show information about the cache. - list: List filenames of packages stored in the cache. - remove: Remove one or more package from the cache. - purge: Remove all items from the cache. ``<pattern>`` can be a glob expression or a package name. """ ignore_require_venv = True usage = """ %prog dir %prog info %prog list [<pattern>] [--format=[human, abspath]] %prog remove <pattern> %prog purge """ def add_options(self) -> None: self.cmd_opts.add_option( "--format", action="store", dest="list_format", default="human", choices=("human", "abspath"), help="Select the output format among: human (default) or abspath", ) self.parser.insert_option_group(0, self.cmd_opts) def handler_map(self) -> dict[str, Callable[[Values, list[str]], None]]: return { "dir": self.get_cache_dir, "info": self.get_cache_info, "list": self.list_cache_items, "remove": self.remove_cache_items, "purge": self.purge_cache, } def run(self, options: Values, args: list[str]) -> int: handler_map = self.handler_map() if not options.cache_dir: logger.error("pip cache commands can not function since cache is disabled.") return ERROR # Determine action if not args or args[0] not in handler_map: logger.error( "Need an action (%s) to perform.", ", ".join(sorted(handler_map)), ) return ERROR action = args[0] # Error handling happens here, not in the action-handlers. try: handler_map[action](options, args[1:]) except PipError as e: logger.error(e.args[0]) return ERROR return SUCCESS def get_cache_dir(self, options: Values, args: list[str]) -> None: if args: raise CommandError("Too many arguments") logger.info(options.cache_dir) def get_cache_info(self, options: Values, args: list[str]) -> None: if args: raise CommandError("Too many arguments") num_http_files = len(self._find_http_files(options)) num_packages = len(self._find_wheels(options, "*")) http_cache_location = self._cache_dir(options, "http-v2") old_http_cache_location = self._cache_dir(options, "http") wheels_cache_location = self._cache_dir(options, "wheels") http_cache_size = filesystem.format_size( filesystem.directory_size(http_cache_location) + filesystem.directory_size(old_http_cache_location) ) wheels_cache_size = filesystem.format_directory_size(wheels_cache_location) message = ( textwrap.dedent( """ Package index page cache location (pip v23.3+): {http_cache_location} Package index page cache location (older pips): {old_http_cache_location} Package index page cache size: {http_cache_size} Number of HTTP files: {num_http_files} Locally built wheels location: {wheels_cache_location} Locally built wheels size: {wheels_cache_size} Number of locally built wheels: {package_count} """ # noqa: E501 ) .format( http_cache_location=http_cache_location, old_http_cache_location=old_http_cache_location, http_cache_size=http_cache_size, num_http_files=num_http_files, wheels_cache_location=wheels_cache_location, package_count=num_packages, wheels_cache_size=wheels_cache_size, ) .strip() ) logger.info(message) def list_cache_items(self, options: Values, args: list[str]) -> None: if len(args) > 1: raise CommandError("Too many arguments") if args: pattern = args[0] else: pattern = "*" files = self._find_wheels(options, pattern) if options.list_format == "human": self.format_for_human(files) else: self.format_for_abspath(files) def format_for_human(self, files: list[str]) -> None: if not files: logger.info("No locally built wheels cached.") return results = [] for filename in files: wheel = os.path.basename(filename) size = filesystem.format_file_size(filename) results.append(f" - {wheel} ({size})") logger.info("Cache contents:\n") logger.info("\n".join(sorted(results))) def format_for_abspath(self, files: list[str]) -> None: if files: logger.info("\n".join(sorted(files))) def remove_cache_items(self, options: Values, args: list[str]) -> None: if len(args) > 1: raise CommandError("Too many arguments") if not args: raise CommandError("Please provide a pattern") files = self._find_wheels(options, args[0]) no_matching_msg = "No matching packages" if args[0] == "*": # Only fetch http files if no specific pattern given files += self._find_http_files(options) else: # Add the pattern to the log message no_matching_msg += f' for pattern "{args[0]}"' if not files: logger.warning(no_matching_msg) bytes_removed = 0 for filename in files: bytes_removed += os.stat(filename).st_size os.unlink(filename) logger.verbose("Removed %s", filename) logger.info("Files removed: %s (%s)", len(files), format_size(bytes_removed)) def purge_cache(self, options: Values, args: list[str]) -> None: if args: raise CommandError("Too many arguments") return self.remove_cache_items(options, ["*"]) def _cache_dir(self, options: Values, subdir: str) -> str: return os.path.join(options.cache_dir, subdir) def _find_http_files(self, options: Values) -> list[str]: old_http_dir = self._cache_dir(options, "http") new_http_dir = self._cache_dir(options, "http-v2") return filesystem.find_files(old_http_dir, "*") + filesystem.find_files( new_http_dir, "*" ) def _find_wheels(self, options: Values, pattern: str) -> list[str]: wheel_dir = self._cache_dir(options, "wheels") # The wheel filename format, as specified in PEP 427, is: # {distribution}-{version}(-{build})?-{python}-{abi}-{platform}.whl # # Additionally, non-alphanumeric values in the distribution are # normalized to underscores (_), meaning hyphens can never occur # before `-{version}`. # # Given that information: # - If the pattern we're given contains a hyphen (-), the user is # providing at least the version. Thus, we can just append `*.whl` # to match the rest of it. # - If the pattern we're given doesn't contain a hyphen (-), the # user is only providing the name. Thus, we append `-*.whl` to # match the hyphen before the version, followed by anything else. # # PEP 427: https://www.python.org/dev/peps/pep-0427/ pattern = pattern + ("*.whl" if "-" in pattern else "-*.whl") return filesystem.find_files(wheel_dir, pattern)
CacheCommand
python
getsentry__sentry
src/sentry/api/exceptions.py
{ "start": 1762, "end": 2508 }
class ____(SentryAPIException): status_code = status.HTTP_401_UNAUTHORIZED code = "sso-required" message = "Must login via SSO" def __init__( self, organization: Organization | RpcOrganization, request: HttpRequest, after_login_redirect=None, ): login_url = reverse("sentry-auth-organization", args=[organization.slug]) if is_using_customer_domain(request): login_url = organization.absolute_url(path=login_url) if after_login_redirect: query_params = {REDIRECT_FIELD_NAME: after_login_redirect} login_url = construct_link_with_query(path=login_url, query_params=query_params) super().__init__(loginUrl=login_url)
SsoRequired
python
sympy__sympy
sympy/polys/polytools.py
{ "start": 3873, "end": 124933 }
class ____(Basic): """ Generic class for representing and operating on polynomial expressions. See :ref:`polys-docs` for general documentation. Poly is a subclass of Basic rather than Expr but instances can be converted to Expr with the :py:meth:`~.Poly.as_expr` method. .. deprecated:: 1.6 Combining Poly with non-Poly objects in binary operations is deprecated. Explicitly convert both objects to either Poly or Expr first. See :ref:`deprecated-poly-nonpoly-binary-operations`. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y Create a univariate polynomial: >>> Poly(x*(x**2 + x - 1)**2) Poly(x**5 + 2*x**4 - x**3 - 2*x**2 + x, x, domain='ZZ') Create a univariate polynomial with specific domain: >>> from sympy import sqrt >>> Poly(x**2 + 2*x + sqrt(3), domain='R') Poly(1.0*x**2 + 2.0*x + 1.73205080756888, x, domain='RR') Create a multivariate polynomial: >>> Poly(y*x**2 + x*y + 1) Poly(x**2*y + x*y + 1, x, y, domain='ZZ') Create a univariate polynomial, where y is a constant: >>> Poly(y*x**2 + x*y + 1,x) Poly(y*x**2 + y*x + 1, x, domain='ZZ[y]') You can evaluate the above polynomial as a function of y: >>> Poly(y*x**2 + x*y + 1,x).eval(2) 6*y + 1 See Also ======== sympy.core.expr.Expr """ __slots__ = ('rep', 'gens') is_commutative = True is_Poly = True _op_priority = 10.001 rep: DMP gens: tuple[Expr, ...] def __new__(cls, rep, *gens, **args) -> Self: """Create a new polynomial instance out of something useful. """ opt = options.build_options(gens, args) if 'order' in opt: raise NotImplementedError("'order' keyword is not implemented yet") if isinstance(rep, (DMP, DMF, ANP, DomainElement)): return cls._from_domain_element(rep, opt) elif iterable(rep, exclude=str): if isinstance(rep, dict): return cls._from_dict(rep, opt) else: return cls._from_list(list(rep), opt) else: rep = sympify(rep, evaluate=type(rep) is not str) # type: ignore if rep.is_Poly: return cls._from_poly(rep, opt) else: return cls._from_expr(rep, opt) # Poly does not pass its args to Basic.__new__ to be stored in _args so we # have to emulate them here with an args property that derives from rep # and gens which are instance attributes. This also means we need to # define _hashable_content. The _hashable_content is rep and gens but args # uses expr instead of rep (expr is the Basic version of rep). Passing # expr in args means that Basic methods like subs should work. Using rep # otherwise means that Poly can remain more efficient than Basic by # avoiding creating a Basic instance just to be hashable. @classmethod def new(cls, rep, *gens): """Construct :class:`Poly` instance from raw representation. """ if not isinstance(rep, DMP): raise PolynomialError( "invalid polynomial representation: %s" % rep) elif rep.lev != len(gens) - 1: raise PolynomialError("invalid arguments: %s, %s" % (rep, gens)) obj = Basic.__new__(cls) obj.rep = rep obj.gens = gens return obj @property def expr(self): return basic_from_dict(self.rep.to_sympy_dict(), *self.gens) @property def args(self): return (self.expr,) + self.gens def _hashable_content(self): return (self.rep,) + self.gens @classmethod def from_dict(cls, rep: dict[tuple[int, ...], Any] | dict[int, Any], *gens, **args): """Construct a polynomial from a ``dict``. """ opt = options.build_options(gens, args) return cls._from_dict(rep, opt) @classmethod def from_list(cls, rep, *gens, **args): """Construct a polynomial from a ``list``. """ opt = options.build_options(gens, args) return cls._from_list(rep, opt) @classmethod def from_poly(cls, rep, *gens, **args): """Construct a polynomial from a polynomial. """ opt = options.build_options(gens, args) return cls._from_poly(rep, opt) @classmethod def from_expr(cls, rep, *gens, **args): """Construct a polynomial from an expression. """ opt = options.build_options(gens, args) return cls._from_expr(rep, opt) @classmethod def _from_dict(cls, rep: dict[tuple[int, ...], Any] | dict[int, Any], opt): """Construct a polynomial from a ``dict``. """ gens = opt.gens if not gens: raise GeneratorsNeeded( "Cannot initialize from 'dict' without generators") level = len(gens) - 1 domain = opt.domain if domain is None: domain, rep_d = construct_domain(rep, opt=opt) else: convert = domain.convert rep_d = {monom: convert(coeff) for monom, coeff in rep.items()} # rep_d could be dict[tuple[int, ...], Er] or dict[int, Er] n = None for n in rep_d: # type: ignore break if isinstance(n, int): raw_dict = cast(dict[int, Any], rep_d) return cls.new(DMP.from_raw_dict(raw_dict, domain), *gens) else: multi_dict = cast(dict[tuple[int, ...], Any], rep_d) return cls.new(DMP.from_dict(multi_dict, level, domain), *gens) @classmethod def _from_list(cls, rep, opt): """Construct a polynomial from a ``list``. """ gens = opt.gens if not gens: raise GeneratorsNeeded( "Cannot initialize from 'list' without generators") elif len(gens) != 1: raise MultivariatePolynomialError( "'list' representation not supported") level = len(gens) - 1 domain = opt.domain if domain is None: domain, rep = construct_domain(rep, opt=opt) else: rep = list(map(domain.convert, rep)) return cls.new(DMP.from_list(rep, level, domain), *gens) @classmethod def _from_poly(cls, rep, opt): """Construct a polynomial from a polynomial. """ if cls != rep.__class__: rep = cls.new(rep.rep, *rep.gens) gens = opt.gens field = opt.field domain = opt.domain if gens and rep.gens != gens: if set(rep.gens) != set(gens): return cls._from_expr(rep.as_expr(), opt) else: rep = rep.reorder(*gens) if 'domain' in opt and domain: rep = rep.set_domain(domain) elif field is True: rep = rep.to_field() return rep @classmethod def _from_expr(cls, rep, opt): """Construct a polynomial from an expression. """ rep, opt = _dict_from_expr(rep, opt) return cls._from_dict(rep, opt) @classmethod def _from_domain_element(cls, rep, opt): gens = opt.gens domain = opt.domain level = len(gens) - 1 rep = [domain.convert(rep)] return cls.new(DMP.from_list(rep, level, domain), *gens) def __hash__(self): return super().__hash__() @property def free_symbols(self): """ Free symbols of a polynomial expression. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> Poly(x**2 + 1).free_symbols {x} >>> Poly(x**2 + y).free_symbols {x, y} >>> Poly(x**2 + y, x).free_symbols {x, y} >>> Poly(x**2 + y, x, z).free_symbols {x, y} """ symbols = set() gens = self.gens for i in range(len(gens)): for monom in self.monoms(): if monom[i]: symbols |= gens[i].free_symbols break return symbols | self.free_symbols_in_domain @property def free_symbols_in_domain(self): """ Free symbols of the domain of ``self``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 1).free_symbols_in_domain set() >>> Poly(x**2 + y).free_symbols_in_domain set() >>> Poly(x**2 + y, x).free_symbols_in_domain {y} """ domain, symbols = self.rep.dom, set() if domain.is_Composite: for gen in domain.symbols: symbols |= gen.free_symbols elif domain.is_EX: for coeff in self.coeffs(): symbols |= coeff.free_symbols return symbols @property def gen(self): """ Return the principal generator. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).gen x """ return self.gens[0] @property def domain(self): """Get the ground domain of a :py:class:`~.Poly` Returns ======= :py:class:`~.Domain`: Ground domain of the :py:class:`~.Poly`. Examples ======== >>> from sympy import Poly, Symbol >>> x = Symbol('x') >>> p = Poly(x**2 + x) >>> p Poly(x**2 + x, x, domain='ZZ') >>> p.domain ZZ """ return self.get_domain() @property def zero(self): """Return zero polynomial with ``self``'s properties. """ return self.new(self.rep.zero(self.rep.lev, self.rep.dom), *self.gens) @property def one(self): """Return one polynomial with ``self``'s properties. """ return self.new(self.rep.one(self.rep.lev, self.rep.dom), *self.gens) def unify(f, g: Poly | Expr | complex) -> tuple[Poly, Poly]: """ Make ``f`` and ``g`` belong to the same domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f, g = Poly(x/2 + 1), Poly(2*x + 1) >>> f Poly(1/2*x + 1, x, domain='QQ') >>> g Poly(2*x + 1, x, domain='ZZ') >>> F, G = f.unify(g) >>> F Poly(1/2*x + 1, x, domain='QQ') >>> G Poly(2*x + 1, x, domain='QQ') """ _, per, F, G = f._unify(g) return per(F), per(G) def _unify(f, g: Poly | Expr | complex) -> tuple[Domain, Callable[[DMP], Poly], DMP, DMP]: gs = cast('Poly | Expr', sympify(g)) if not isinstance(gs, Poly): try: g_coeff = f.rep.dom.from_sympy(gs) except CoercionFailed: raise UnificationFailed("Cannot unify %s with %s" % (f, gs)) else: return f.rep.dom, f.per, f.rep, f.rep.ground_new(g_coeff) if isinstance(f.rep, DMP) and isinstance(gs.rep, DMP): gens = _unify_gens(f.gens, gs.gens) dom, lev = f.rep.dom.unify(gs.rep.dom, gens), len(gens) - 1 if f.gens != gens: f_monoms, f_coeffs = _dict_reorder( f.rep.to_dict(), f.gens, gens) if f.rep.dom != dom: f_coeffs = [dom.convert(c, f.rep.dom) for c in f_coeffs] F = DMP.from_dict(dict(list(zip(f_monoms, f_coeffs))), lev, dom) else: F = f.rep.convert(dom) if gs.gens != gens: g_monoms, g_coeffs = _dict_reorder( gs.rep.to_dict(), gs.gens, gens) if gs.rep.dom != dom: g_coeffs = [dom.convert(c, gs.rep.dom) for c in g_coeffs] G = DMP.from_dict(dict(list(zip(g_monoms, g_coeffs))), lev, dom) else: G = gs.rep.convert(dom) else: raise UnificationFailed("Cannot unify %s with %s" % (f, gs)) cls = f.__class__ def per(rep, dom=dom, gens=gens, remove=None): if remove is not None: gens = gens[:remove] + gens[remove + 1:] if not gens: return dom.to_sympy(rep) return cls.new(rep, *gens) return dom, per, F, G @overload def per( f, rep: DMP, gens: tuple[Expr, ...] | None = None, *, remove: int ) -> Poly | Expr: ... @overload def per( f, rep: DMP, gens: tuple[Expr, ...] | None = None, remove: None = None ) -> Poly: ... def per( f, rep: DMP, gens: tuple[Expr, ...] | None = None, remove: int | None = None ) -> Poly | Expr: """ Create a Poly out of the given representation. Examples ======== >>> from sympy import Poly, ZZ >>> from sympy.abc import x, y >>> from sympy.polys.polyclasses import DMP >>> a = Poly(x**2 + 1) >>> a.per(DMP([ZZ(1), ZZ(1)], ZZ), gens=[y]) Poly(y + 1, y, domain='ZZ') """ if gens is None: gens = f.gens if remove is not None: gens = gens[:remove] + gens[remove + 1:] if not gens: return f.rep.dom.to_sympy(rep) return f.__class__.new(rep, *gens) def set_domain(f, domain): """Set the ground domain of ``f``. """ opt = options.build_options(f.gens, {'domain': domain}) return f.per(f.rep.convert(opt.domain)) def get_domain(f): """Get the ground domain of ``f``. """ return f.rep.dom def set_modulus(f, modulus): """ Set the modulus of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(5*x**2 + 2*x - 1, x).set_modulus(2) Poly(x**2 + 1, x, modulus=2) """ modulus = options.Modulus.preprocess(modulus) return f.set_domain(FF(modulus)) def get_modulus(f): """ Get the modulus of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, modulus=2).get_modulus() 2 """ domain = f.get_domain() if domain.is_FiniteField: return Integer(domain.characteristic()) else: raise PolynomialError("not a polynomial over a Galois field") def _eval_subs(f, old, new): """Internal implementation of :func:`subs`. """ if old in f.gens: if new.is_number: return f.eval(old, new) else: try: return f.replace(old, new) except PolynomialError: pass return f.as_expr().subs(old, new) def exclude(f): """ Remove unnecessary generators from ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import a, b, c, d, x >>> Poly(a + x, a, b, c, d, x).exclude() Poly(a + x, a, x, domain='ZZ') """ J, new = f.rep.exclude() gens = [gen for j, gen in enumerate(f.gens) if j not in J] return f.per(new, gens=gens) def replace(f, x, y=None, **_ignore): # XXX this does not match Basic's signature """ Replace ``x`` with ``y`` in generators list. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 1, x).replace(x, y) Poly(y**2 + 1, y, domain='ZZ') """ if y is None: if f.is_univariate: x, y = f.gen, x else: raise PolynomialError( "syntax supported only in univariate case") if x == y or x not in f.gens: return f if x in f.gens and y not in f.gens: dom = f.get_domain() if not dom.is_Composite or y not in dom.symbols: gens = list(f.gens) gens[gens.index(x)] = y return f.per(f.rep, gens=gens) raise PolynomialError("Cannot replace %s with %s in %s" % (x, y, f)) def match(f, *args, **kwargs): """Match expression from Poly. See Basic.match()""" return f.as_expr().match(*args, **kwargs) def reorder(f, *gens, **args): """ Efficiently apply new order of generators. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + x*y**2, x, y).reorder(y, x) Poly(y**2*x + x**2, y, x, domain='ZZ') """ opt = options.Options((), args) if not gens: gens = _sort_gens(f.gens, opt=opt) elif set(f.gens) != set(gens): raise PolynomialError( "generators list can differ only up to order of elements") rep = dict(list(zip(*_dict_reorder(f.rep.to_dict(), f.gens, gens)))) return f.per(DMP.from_dict(rep, len(gens) - 1, f.rep.dom), gens=gens) def ltrim(f, gen): """ Remove dummy generators from ``f`` that are to the left of specified ``gen`` in the generators as ordered. When ``gen`` is an integer, it refers to the generator located at that position within the tuple of generators of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> Poly(y**2 + y*z**2, x, y, z).ltrim(y) Poly(y**2 + y*z**2, y, z, domain='ZZ') >>> Poly(z, x, y, z).ltrim(-1) Poly(z, z, domain='ZZ') """ rep = f.as_dict(native=True) j = f._gen_to_level(gen) terms = {} for monom, coeff in rep.items(): if any(monom[:j]): # some generator is used in the portion to be trimmed raise PolynomialError("Cannot left trim %s" % f) terms[monom[j:]] = coeff gens = f.gens[j:] return f.new(DMP.from_dict(terms, len(gens) - 1, f.rep.dom), *gens) def has_only_gens(f, *gens): """ Return ``True`` if ``Poly(f, *gens)`` retains ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> Poly(x*y + 1, x, y, z).has_only_gens(x, y) True >>> Poly(x*y + z, x, y, z).has_only_gens(x, y) False """ indices = set() for gen in gens: try: index = f.gens.index(gen) except ValueError: raise GeneratorsError( "%s doesn't have %s as generator" % (f, gen)) else: indices.add(index) for monom in f.monoms(): for i, elt in enumerate(monom): if i not in indices and elt: return False return True def to_ring(f): """ Make the ground domain a ring. Examples ======== >>> from sympy import Poly, QQ >>> from sympy.abc import x >>> Poly(x**2 + 1, domain=QQ).to_ring() Poly(x**2 + 1, x, domain='ZZ') """ if hasattr(f.rep, 'to_ring'): result = f.rep.to_ring() else: # pragma: no cover raise OperationNotSupported(f, 'to_ring') return f.per(result) def to_field(f): """ Make the ground domain a field. Examples ======== >>> from sympy import Poly, ZZ >>> from sympy.abc import x >>> Poly(x**2 + 1, x, domain=ZZ).to_field() Poly(x**2 + 1, x, domain='QQ') """ if hasattr(f.rep, 'to_field'): result = f.rep.to_field() else: # pragma: no cover raise OperationNotSupported(f, 'to_field') return f.per(result) def to_exact(f): """ Make the ground domain exact. Examples ======== >>> from sympy import Poly, RR >>> from sympy.abc import x >>> Poly(x**2 + 1.0, x, domain=RR).to_exact() Poly(x**2 + 1, x, domain='QQ') """ if hasattr(f.rep, 'to_exact'): result = f.rep.to_exact() else: # pragma: no cover raise OperationNotSupported(f, 'to_exact') return f.per(result) def retract(f, field=None): """ Recalculate the ground domain of a polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = Poly(x**2 + 1, x, domain='QQ[y]') >>> f Poly(x**2 + 1, x, domain='QQ[y]') >>> f.retract() Poly(x**2 + 1, x, domain='ZZ') >>> f.retract(field=True) Poly(x**2 + 1, x, domain='QQ') """ dom, rep = construct_domain(f.as_dict(zero=True), field=field, composite=f.domain.is_Composite or None) return f.from_dict(rep, f.gens, domain=dom) def slice(f, x, m, n=None): """Take a continuous subsequence of terms of ``f``. """ if n is None: j, m, n = 0, x, m else: j = f._gen_to_level(x) m, n = int(m), int(n) if hasattr(f.rep, 'slice'): result = f.rep.slice(m, n, j) else: # pragma: no cover raise OperationNotSupported(f, 'slice') return f.per(result) def coeffs(f, order=None): """ Returns all non-zero coefficients from ``f`` in lex order. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x + 3, x).coeffs() [1, 2, 3] See Also ======== all_coeffs coeff_monomial nth """ return [f.rep.dom.to_sympy(c) for c in f.rep.coeffs(order=order)] def monoms(f, order=None): """ Returns all non-zero monomials from ``f`` in lex order. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x*y**2 + x*y + 3*y, x, y).monoms() [(2, 0), (1, 2), (1, 1), (0, 1)] See Also ======== all_monoms """ return f.rep.monoms(order=order) def terms(f, order=None): """ Returns all non-zero terms from ``f`` in lex order. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x*y**2 + x*y + 3*y, x, y).terms() [((2, 0), 1), ((1, 2), 2), ((1, 1), 1), ((0, 1), 3)] See Also ======== all_terms """ return [(m, f.rep.dom.to_sympy(c)) for m, c in f.rep.terms(order=order)] def all_coeffs(f): """ Returns all coefficients from a univariate polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x - 1, x).all_coeffs() [1, 0, 2, -1] """ return [f.rep.dom.to_sympy(c) for c in f.rep.all_coeffs()] def all_monoms(f): """ Returns all monomials from a univariate polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x - 1, x).all_monoms() [(3,), (2,), (1,), (0,)] See Also ======== all_terms """ return f.rep.all_monoms() def all_terms(f): """ Returns all terms from a univariate polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x - 1, x).all_terms() [((3,), 1), ((2,), 0), ((1,), 2), ((0,), -1)] """ return [(m, f.rep.dom.to_sympy(c)) for m, c in f.rep.all_terms()] def termwise(f, func, *gens, **args): """ Apply a function to all terms of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> def func(k, coeff): ... k = k[0] ... return coeff//10**(2-k) >>> Poly(x**2 + 20*x + 400).termwise(func) Poly(x**2 + 2*x + 4, x, domain='ZZ') """ terms = {} for monom, coeff in f.terms(): result = func(monom, coeff) if isinstance(result, tuple): monom, coeff = result else: coeff = result if coeff: if monom not in terms: terms[monom] = coeff else: raise PolynomialError( "%s monomial was generated twice" % monom) return f.from_dict(terms, *(gens or f.gens), **args) def length(f): """ Returns the number of non-zero terms in ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 2*x - 1).length() 3 """ return len(f.as_dict()) def as_dict(f, native=False, zero=False): """ Switch to a ``dict`` representation. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x*y**2 - y, x, y).as_dict() {(0, 1): -1, (1, 2): 2, (2, 0): 1} """ if native: return f.rep.to_dict(zero=zero) else: return f.rep.to_sympy_dict(zero=zero) def as_list(f, native=False): """Switch to a ``list`` representation. """ if native: return f.rep.to_list() else: return f.rep.to_sympy_list() def as_expr(f, *gens): """ Convert a Poly instance to an Expr instance. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2 + 2*x*y**2 - y, x, y) >>> f.as_expr() x**2 + 2*x*y**2 - y >>> f.as_expr({x: 5}) 10*y**2 - y + 25 >>> f.as_expr(5, 6) 379 """ if not gens: return f.expr if len(gens) == 1 and isinstance(gens[0], dict): mapping = gens[0] gens = list(f.gens) for gen, value in mapping.items(): try: index = gens.index(gen) except ValueError: raise GeneratorsError( "%s doesn't have %s as generator" % (f, gen)) else: gens[index] = value return basic_from_dict(f.rep.to_sympy_dict(), *gens) def as_poly(self, *gens, **args): """Converts ``self`` to a polynomial or returns ``None``. >>> from sympy import sin >>> from sympy.abc import x, y >>> print((x**2 + x*y).as_poly()) Poly(x**2 + x*y, x, y, domain='ZZ') >>> print((x**2 + x*y).as_poly(x, y)) Poly(x**2 + x*y, x, y, domain='ZZ') >>> print((x**2 + sin(y)).as_poly(x, y)) None """ try: poly = Poly(self, *gens, **args) if not poly.is_Poly: return None else: return poly except PolynomialError: return None def lift(f): """ Convert algebraic coefficients to rationals. Examples ======== >>> from sympy import Poly, I >>> from sympy.abc import x >>> Poly(x**2 + I*x + 1, x, extension=I).lift() Poly(x**4 + 3*x**2 + 1, x, domain='QQ') """ if hasattr(f.rep, 'lift'): result = f.rep.lift() else: # pragma: no cover raise OperationNotSupported(f, 'lift') return f.per(result) def deflate(f): """ Reduce degree of ``f`` by mapping ``x_i**m`` to ``y_i``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**6*y**2 + x**3 + 1, x, y).deflate() ((3, 2), Poly(x**2*y + x + 1, x, y, domain='ZZ')) """ if hasattr(f.rep, 'deflate'): J, result = f.rep.deflate() else: # pragma: no cover raise OperationNotSupported(f, 'deflate') return J, f.per(result) def inject(f, front=False): """ Inject ground domain generators into ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2*y + x*y**3 + x*y + 1, x) >>> f.inject() Poly(x**2*y + x*y**3 + x*y + 1, x, y, domain='ZZ') >>> f.inject(front=True) Poly(y**3*x + y*x**2 + y*x + 1, y, x, domain='ZZ') """ dom = f.rep.dom if dom.is_Numerical: return f elif not dom.is_Poly: raise DomainError("Cannot inject generators over %s" % dom) if hasattr(f.rep, 'inject'): result = f.rep.inject(front=front) else: # pragma: no cover raise OperationNotSupported(f, 'inject') if front: gens = dom.symbols + f.gens else: gens = f.gens + dom.symbols return f.new(result, *gens) def eject(f, *gens): """ Eject selected generators into the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2*y + x*y**3 + x*y + 1, x, y) >>> f.eject(x) Poly(x*y**3 + (x**2 + x)*y + 1, y, domain='ZZ[x]') >>> f.eject(y) Poly(y*x**2 + (y**3 + y)*x + 1, x, domain='ZZ[y]') """ dom = f.rep.dom if not dom.is_Numerical: raise DomainError("Cannot eject generators over %s" % dom) k = len(gens) if f.gens[:k] == gens: _gens, front = f.gens[k:], True elif f.gens[-k:] == gens: _gens, front = f.gens[:-k], False else: raise NotImplementedError( "can only eject front or back generators") dom = dom.inject(*gens) if hasattr(f.rep, 'eject'): result = f.rep.eject(dom, front=front) else: # pragma: no cover raise OperationNotSupported(f, 'eject') return f.new(result, *_gens) def terms_gcd(f): """ Remove GCD of terms from the polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**6*y**2 + x**3*y, x, y).terms_gcd() ((3, 1), Poly(x**3*y + 1, x, y, domain='ZZ')) """ if hasattr(f.rep, 'terms_gcd'): J, result = f.rep.terms_gcd() else: # pragma: no cover raise OperationNotSupported(f, 'terms_gcd') return J, f.per(result) def add_ground(f, coeff): """ Add an element of the ground domain to ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x + 1).add_ground(2) Poly(x + 3, x, domain='ZZ') """ if hasattr(f.rep, 'add_ground'): result = f.rep.add_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'add_ground') return f.per(result) def sub_ground(f, coeff): """ Subtract an element of the ground domain from ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x + 1).sub_ground(2) Poly(x - 1, x, domain='ZZ') """ if hasattr(f.rep, 'sub_ground'): result = f.rep.sub_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'sub_ground') return f.per(result) def mul_ground(f, coeff): """ Multiply ``f`` by a an element of the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x + 1).mul_ground(2) Poly(2*x + 2, x, domain='ZZ') """ if hasattr(f.rep, 'mul_ground'): result = f.rep.mul_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'mul_ground') return f.per(result) def quo_ground(f, coeff): """ Quotient of ``f`` by a an element of the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x + 4).quo_ground(2) Poly(x + 2, x, domain='ZZ') >>> Poly(2*x + 3).quo_ground(2) Poly(x + 1, x, domain='ZZ') """ if hasattr(f.rep, 'quo_ground'): result = f.rep.quo_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'quo_ground') return f.per(result) def exquo_ground(f, coeff): """ Exact quotient of ``f`` by a an element of the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x + 4).exquo_ground(2) Poly(x + 2, x, domain='ZZ') >>> Poly(2*x + 3).exquo_ground(2) Traceback (most recent call last): ... ExactQuotientFailed: 2 does not divide 3 in ZZ """ if hasattr(f.rep, 'exquo_ground'): result = f.rep.exquo_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'exquo_ground') return f.per(result) def abs(f): """ Make all coefficients in ``f`` positive. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).abs() Poly(x**2 + 1, x, domain='ZZ') """ if hasattr(f.rep, 'abs'): result = f.rep.abs() else: # pragma: no cover raise OperationNotSupported(f, 'abs') return f.per(result) def neg(f): """ Negate all coefficients in ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).neg() Poly(-x**2 + 1, x, domain='ZZ') >>> -Poly(x**2 - 1, x) Poly(-x**2 + 1, x, domain='ZZ') """ if hasattr(f.rep, 'neg'): result = f.rep.neg() else: # pragma: no cover raise OperationNotSupported(f, 'neg') return f.per(result) def add(f, g): """ Add two polynomials ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).add(Poly(x - 2, x)) Poly(x**2 + x - 1, x, domain='ZZ') >>> Poly(x**2 + 1, x) + Poly(x - 2, x) Poly(x**2 + x - 1, x, domain='ZZ') """ g = sympify(g) if not g.is_Poly: return f.add_ground(g) _, per, F, G = f._unify(g) if hasattr(f.rep, 'add'): result = F.add(G) else: # pragma: no cover raise OperationNotSupported(f, 'add') return per(result) def sub(f, g): """ Subtract two polynomials ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).sub(Poly(x - 2, x)) Poly(x**2 - x + 3, x, domain='ZZ') >>> Poly(x**2 + 1, x) - Poly(x - 2, x) Poly(x**2 - x + 3, x, domain='ZZ') """ g = sympify(g) if not g.is_Poly: return f.sub_ground(g) _, per, F, G = f._unify(g) if hasattr(f.rep, 'sub'): result = F.sub(G) else: # pragma: no cover raise OperationNotSupported(f, 'sub') return per(result) def mul(f, g): """ Multiply two polynomials ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).mul(Poly(x - 2, x)) Poly(x**3 - 2*x**2 + x - 2, x, domain='ZZ') >>> Poly(x**2 + 1, x)*Poly(x - 2, x) Poly(x**3 - 2*x**2 + x - 2, x, domain='ZZ') """ g = sympify(g) if not g.is_Poly: return f.mul_ground(g) _, per, F, G = f._unify(g) if hasattr(f.rep, 'mul'): result = F.mul(G) else: # pragma: no cover raise OperationNotSupported(f, 'mul') return per(result) def sqr(f): """ Square a polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x - 2, x).sqr() Poly(x**2 - 4*x + 4, x, domain='ZZ') >>> Poly(x - 2, x)**2 Poly(x**2 - 4*x + 4, x, domain='ZZ') """ if hasattr(f.rep, 'sqr'): result = f.rep.sqr() else: # pragma: no cover raise OperationNotSupported(f, 'sqr') return f.per(result) def pow(f, n): """ Raise ``f`` to a non-negative power ``n``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x - 2, x).pow(3) Poly(x**3 - 6*x**2 + 12*x - 8, x, domain='ZZ') >>> Poly(x - 2, x)**3 Poly(x**3 - 6*x**2 + 12*x - 8, x, domain='ZZ') """ n = int(n) if hasattr(f.rep, 'pow'): result = f.rep.pow(n) else: # pragma: no cover raise OperationNotSupported(f, 'pow') return f.per(result) def pdiv(f, g): """ Polynomial pseudo-division of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).pdiv(Poly(2*x - 4, x)) (Poly(2*x + 4, x, domain='ZZ'), Poly(20, x, domain='ZZ')) """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'pdiv'): q, r = F.pdiv(G) else: # pragma: no cover raise OperationNotSupported(f, 'pdiv') return per(q), per(r) def prem(f, g): """ Polynomial pseudo-remainder of ``f`` by ``g``. Caveat: The function prem(f, g, x) can be safely used to compute in Z[x] _only_ subresultant polynomial remainder sequences (prs's). To safely compute Euclidean and Sturmian prs's in Z[x] employ anyone of the corresponding functions found in the module sympy.polys.subresultants_qq_zz. The functions in the module with suffix _pg compute prs's in Z[x] employing rem(f, g, x), whereas the functions with suffix _amv compute prs's in Z[x] employing rem_z(f, g, x). The function rem_z(f, g, x) differs from prem(f, g, x) in that to compute the remainder polynomials in Z[x] it premultiplies the divident times the absolute value of the leading coefficient of the divisor raised to the power degree(f, x) - degree(g, x) + 1. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).prem(Poly(2*x - 4, x)) Poly(20, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'prem'): result = F.prem(G) else: # pragma: no cover raise OperationNotSupported(f, 'prem') return per(result) def pquo(f, g): """ Polynomial pseudo-quotient of ``f`` by ``g``. See the Caveat note in the function prem(f, g). Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).pquo(Poly(2*x - 4, x)) Poly(2*x + 4, x, domain='ZZ') >>> Poly(x**2 - 1, x).pquo(Poly(2*x - 2, x)) Poly(2*x + 2, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'pquo'): result = F.pquo(G) else: # pragma: no cover raise OperationNotSupported(f, 'pquo') return per(result) def pexquo(f, g): """ Polynomial exact pseudo-quotient of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).pexquo(Poly(2*x - 2, x)) Poly(2*x + 2, x, domain='ZZ') >>> Poly(x**2 + 1, x).pexquo(Poly(2*x - 4, x)) Traceback (most recent call last): ... ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'pexquo'): try: result = F.pexquo(G) except ExactQuotientFailed as exc: raise exc.new(f.as_expr(), g.as_expr()) else: # pragma: no cover raise OperationNotSupported(f, 'pexquo') return per(result) def div(f, g, auto=True): """ Polynomial division with remainder of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).div(Poly(2*x - 4, x)) (Poly(1/2*x + 1, x, domain='QQ'), Poly(5, x, domain='QQ')) >>> Poly(x**2 + 1, x).div(Poly(2*x - 4, x), auto=False) (Poly(0, x, domain='ZZ'), Poly(x**2 + 1, x, domain='ZZ')) """ dom, per, F, G = f._unify(g) retract = False if auto and dom.is_Ring and not dom.is_Field: F, G = F.to_field(), G.to_field() retract = True if hasattr(f.rep, 'div'): q, r = F.div(G) else: # pragma: no cover raise OperationNotSupported(f, 'div') if retract: try: Q, R = q.to_ring(), r.to_ring() except CoercionFailed: pass else: q, r = Q, R return per(q), per(r) def rem(f, g, auto=True): """ Computes the polynomial remainder of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).rem(Poly(2*x - 4, x)) Poly(5, x, domain='ZZ') >>> Poly(x**2 + 1, x).rem(Poly(2*x - 4, x), auto=False) Poly(x**2 + 1, x, domain='ZZ') """ dom, per, F, G = f._unify(g) retract = False if auto and dom.is_Ring and not dom.is_Field: F, G = F.to_field(), G.to_field() retract = True if hasattr(f.rep, 'rem'): r = F.rem(G) else: # pragma: no cover raise OperationNotSupported(f, 'rem') if retract: try: r = r.to_ring() except CoercionFailed: pass return per(r) def quo(f, g, auto=True): """ Computes polynomial quotient of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).quo(Poly(2*x - 4, x)) Poly(1/2*x + 1, x, domain='QQ') >>> Poly(x**2 - 1, x).quo(Poly(x - 1, x)) Poly(x + 1, x, domain='ZZ') """ dom, per, F, G = f._unify(g) retract = False if auto and dom.is_Ring and not dom.is_Field: F, G = F.to_field(), G.to_field() retract = True if hasattr(f.rep, 'quo'): q = F.quo(G) else: # pragma: no cover raise OperationNotSupported(f, 'quo') if retract: try: q = q.to_ring() except CoercionFailed: pass return per(q) def exquo(f, g, auto=True): """ Computes polynomial exact quotient of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).exquo(Poly(x - 1, x)) Poly(x + 1, x, domain='ZZ') >>> Poly(x**2 + 1, x).exquo(Poly(2*x - 4, x)) Traceback (most recent call last): ... ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 """ dom, per, F, G = f._unify(g) retract = False if auto and dom.is_Ring and not dom.is_Field: F, G = F.to_field(), G.to_field() retract = True if hasattr(f.rep, 'exquo'): try: q = F.exquo(G) except ExactQuotientFailed as exc: raise exc.new(f.as_expr(), g.as_expr()) else: # pragma: no cover raise OperationNotSupported(f, 'exquo') if retract: try: q = q.to_ring() except CoercionFailed: pass return per(q) def _gen_to_level(f, gen): """Returns level associated with the given generator. """ if isinstance(gen, int): length = len(f.gens) if -length <= gen < length: if gen < 0: return length + gen else: return gen else: raise PolynomialError("-%s <= gen < %s expected, got %s" % (length, length, gen)) else: try: return f.gens.index(sympify(gen)) except ValueError: raise PolynomialError( "a valid generator expected, got %s" % gen) def degree(f, gen: int = 0) -> int | NegativeInfinity: """ Returns degree of ``f`` in ``x_j``. The degree of 0 is negative infinity. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + y*x + 1, x, y).degree() 2 >>> Poly(x**2 + y*x + y, x, y).degree(y) 1 >>> Poly(0, x).degree() -oo """ j = f._gen_to_level(gen) if hasattr(f.rep, 'degree'): d = f.rep.degree(j) if d < 0: return S.NegativeInfinity return d else: # pragma: no cover raise OperationNotSupported(f, 'degree') def degree_list(f) -> tuple[int | NegativeInfinity, ...]: """ Returns a list of degrees of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + y*x + 1, x, y).degree_list() (2, 1) """ if hasattr(f.rep, 'degree_list'): degrees = f.rep.degree_list() return tuple(d if d >= 0 else S.NegativeInfinity for d in degrees) else: # pragma: no cover raise OperationNotSupported(f, 'degree_list') def total_degree(f) -> int | NegativeInfinity: """ Returns the total degree of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + y*x + 1, x, y).total_degree() 2 >>> Poly(x + y**5, x, y).total_degree() 5 """ if hasattr(f.rep, 'total_degree'): d = f.rep.total_degree() return d if d >= 0 else S.NegativeInfinity else: # pragma: no cover raise OperationNotSupported(f, 'total_degree') def homogenize(f, s): """ Returns the homogeneous polynomial of ``f``. A homogeneous polynomial is a polynomial whose all monomials with non-zero coefficients have the same total degree. If you only want to check if a polynomial is homogeneous, then use :func:`Poly.is_homogeneous`. If you want not only to check if a polynomial is homogeneous but also compute its homogeneous order, then use :func:`Poly.homogeneous_order`. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> f = Poly(x**5 + 2*x**2*y**2 + 9*x*y**3) >>> f.homogenize(z) Poly(x**5 + 2*x**2*y**2*z + 9*x*y**3*z, x, y, z, domain='ZZ') """ if not isinstance(s, Symbol): raise TypeError("``Symbol`` expected, got %s" % type(s)) if s in f.gens: i = f.gens.index(s) gens = f.gens else: i = len(f.gens) gens = f.gens + (s,) if hasattr(f.rep, 'homogenize'): return f.per(f.rep.homogenize(i), gens=gens) raise OperationNotSupported(f, 'homogeneous_order') def homogeneous_order(f): """ Returns the homogeneous order of ``f``. A homogeneous polynomial is a polynomial whose all monomials with non-zero coefficients have the same total degree. This degree is the homogeneous order of ``f``. If you only want to check if a polynomial is homogeneous, then use :func:`Poly.is_homogeneous`. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**5 + 2*x**3*y**2 + 9*x*y**4) >>> f.homogeneous_order() 5 """ if hasattr(f.rep, 'homogeneous_order'): return f.rep.homogeneous_order() else: # pragma: no cover raise OperationNotSupported(f, 'homogeneous_order') def LC(f, order=None): """ Returns the leading coefficient of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(4*x**3 + 2*x**2 + 3*x, x).LC() 4 """ if order is not None: return f.coeffs(order)[0] if hasattr(f.rep, 'LC'): result = f.rep.LC() else: # pragma: no cover raise OperationNotSupported(f, 'LC') return f.rep.dom.to_sympy(result) def TC(f): """ Returns the trailing coefficient of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x**2 + 3*x, x).TC() 0 """ if hasattr(f.rep, 'TC'): result = f.rep.TC() else: # pragma: no cover raise OperationNotSupported(f, 'TC') return f.rep.dom.to_sympy(result) def EC(f, order=None): """ Returns the last non-zero coefficient of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x**2 + 3*x, x).EC() 3 """ if hasattr(f.rep, 'coeffs'): return f.coeffs(order)[-1] else: # pragma: no cover raise OperationNotSupported(f, 'EC') def coeff_monomial(f, monom): """ Returns the coefficient of ``monom`` in ``f`` if there, else None. Examples ======== >>> from sympy import Poly, exp >>> from sympy.abc import x, y >>> p = Poly(24*x*y*exp(8) + 23*x, x, y) >>> p.coeff_monomial(x) 23 >>> p.coeff_monomial(y) 0 >>> p.coeff_monomial(x*y) 24*exp(8) Note that ``Expr.coeff()`` behaves differently, collecting terms if possible; the Poly must be converted to an Expr to use that method, however: >>> p.as_expr().coeff(x) 24*y*exp(8) + 23 >>> p.as_expr().coeff(y) 24*x*exp(8) >>> p.as_expr().coeff(x*y) 24*exp(8) See Also ======== nth: more efficient query using exponents of the monomial's generators """ return f.nth(*Monomial(monom, f.gens).exponents) def nth(f, *N): """ Returns the ``n``-th coefficient of ``f`` where ``N`` are the exponents of the generators in the term of interest. Examples ======== >>> from sympy import Poly, sqrt >>> from sympy.abc import x, y >>> Poly(x**3 + 2*x**2 + 3*x, x).nth(2) 2 >>> Poly(x**3 + 2*x*y**2 + y**2, x, y).nth(1, 2) 2 >>> Poly(4*sqrt(x)*y) Poly(4*y*(sqrt(x)), y, sqrt(x), domain='ZZ') >>> _.nth(1, 1) 4 See Also ======== coeff_monomial """ if hasattr(f.rep, 'nth'): if len(N) != len(f.gens): raise ValueError('exponent of each generator must be specified') result = f.rep.nth(*list(map(int, N))) else: # pragma: no cover raise OperationNotSupported(f, 'nth') return f.rep.dom.to_sympy(result) def coeff(f, x, n=1, right=False): # the semantics of coeff_monomial and Expr.coeff are different; # if someone is working with a Poly, they should be aware of the # differences and chose the method best suited for the query. # Alternatively, a pure-polys method could be written here but # at this time the ``right`` keyword would be ignored because Poly # doesn't work with non-commutatives. raise NotImplementedError( 'Either convert to Expr with `as_expr` method ' 'to use Expr\'s coeff method or else use the ' '`coeff_monomial` method of Polys.') def LM(f, order=None): """ Returns the leading monomial of ``f``. The Leading monomial signifies the monomial having the highest power of the principal generator in the expression f. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).LM() x**2*y**0 """ return Monomial(f.monoms(order)[0], f.gens) def EM(f, order=None): """ Returns the last non-zero monomial of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).EM() x**0*y**1 """ return Monomial(f.monoms(order)[-1], f.gens) def LT(f, order=None): """ Returns the leading term of ``f``. The Leading term signifies the term having the highest power of the principal generator in the expression f along with its coefficient. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).LT() (x**2*y**0, 4) """ monom, coeff = f.terms(order)[0] return Monomial(monom, f.gens), coeff def ET(f, order=None): """ Returns the last non-zero term of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).ET() (x**0*y**1, 3) """ monom, coeff = f.terms(order)[-1] return Monomial(monom, f.gens), coeff def max_norm(f): """ Returns maximum norm of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(-x**2 + 2*x - 3, x).max_norm() 3 """ if hasattr(f.rep, 'max_norm'): result = f.rep.max_norm() else: # pragma: no cover raise OperationNotSupported(f, 'max_norm') return f.rep.dom.to_sympy(result) def l1_norm(f): """ Returns l1 norm of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(-x**2 + 2*x - 3, x).l1_norm() 6 """ if hasattr(f.rep, 'l1_norm'): result = f.rep.l1_norm() else: # pragma: no cover raise OperationNotSupported(f, 'l1_norm') return f.rep.dom.to_sympy(result) def clear_denoms(self, convert=False): """ Clear denominators, but keep the ground domain. Examples ======== >>> from sympy import Poly, S, QQ >>> from sympy.abc import x >>> f = Poly(x/2 + S(1)/3, x, domain=QQ) >>> f.clear_denoms() (6, Poly(3*x + 2, x, domain='QQ')) >>> f.clear_denoms(convert=True) (6, Poly(3*x + 2, x, domain='ZZ')) """ f = self if not f.rep.dom.is_Field: return S.One, f dom = f.get_domain() if dom.has_assoc_Ring: dom = f.rep.dom.get_ring() if hasattr(f.rep, 'clear_denoms'): coeff, result = f.rep.clear_denoms() else: # pragma: no cover raise OperationNotSupported(f, 'clear_denoms') coeff, f = dom.to_sympy(coeff), f.per(result) if not convert or not dom.has_assoc_Ring: return coeff, f else: return coeff, f.to_ring() def rat_clear_denoms(self, g): """ Clear denominators in a rational function ``f/g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2/y + 1, x) >>> g = Poly(x**3 + y, x) >>> p, q = f.rat_clear_denoms(g) >>> p Poly(x**2 + y, x, domain='ZZ[y]') >>> q Poly(y*x**3 + y**2, x, domain='ZZ[y]') """ f = self dom, per, f, g = f._unify(g) f = per(f) g = per(g) if not (dom.is_Field and dom.has_assoc_Ring): return f, g a, f = f.clear_denoms(convert=True) b, g = g.clear_denoms(convert=True) f = f.mul_ground(b) g = g.mul_ground(a) return f, g def integrate(self, *specs, **args): """ Computes indefinite integral of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x + 1, x).integrate() Poly(1/3*x**3 + x**2 + x, x, domain='QQ') >>> Poly(x*y**2 + x, x, y).integrate((0, 1), (1, 0)) Poly(1/2*x**2*y**2 + 1/2*x**2, x, y, domain='QQ') """ f = self if args.get('auto', True) and f.rep.dom.is_Ring: f = f.to_field() if hasattr(f.rep, 'integrate'): if not specs: return f.per(f.rep.integrate(m=1)) rep = f.rep for spec in specs: if isinstance(spec, tuple): gen, m = spec else: gen, m = spec, 1 rep = rep.integrate(int(m), f._gen_to_level(gen)) return f.per(rep) else: # pragma: no cover raise OperationNotSupported(f, 'integrate') def diff(f, *specs, **kwargs): """ Computes partial derivative of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x + 1, x).diff() Poly(2*x + 2, x, domain='ZZ') >>> Poly(x*y**2 + x, x, y).diff((0, 0), (1, 1)) Poly(2*x*y, x, y, domain='ZZ') """ if not kwargs.get('evaluate', True): return Derivative(f, *specs, **kwargs) if hasattr(f.rep, 'diff'): if not specs: return f.per(f.rep.diff(m=1)) rep = f.rep for spec in specs: if isinstance(spec, tuple): gen, m = spec else: gen, m = spec, 1 rep = rep.diff(int(m), f._gen_to_level(gen)) return f.per(rep) else: # pragma: no cover raise OperationNotSupported(f, 'diff') _eval_derivative = diff def eval(self, x, a=None, auto=True): """ Evaluate ``f`` at ``a`` in the given variable. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> Poly(x**2 + 2*x + 3, x).eval(2) 11 >>> Poly(2*x*y + 3*x + y + 2, x, y).eval(x, 2) Poly(5*y + 8, y, domain='ZZ') >>> f = Poly(2*x*y + 3*x + y + 2*z, x, y, z) >>> f.eval({x: 2}) Poly(5*y + 2*z + 6, y, z, domain='ZZ') >>> f.eval({x: 2, y: 5}) Poly(2*z + 31, z, domain='ZZ') >>> f.eval({x: 2, y: 5, z: 7}) 45 >>> f.eval((2, 5)) Poly(2*z + 31, z, domain='ZZ') >>> f(2, 5) Poly(2*z + 31, z, domain='ZZ') """ f = self if a is None: if isinstance(x, dict): mapping = x for gen, value in mapping.items(): f = f.eval(gen, value) return f elif isinstance(x, (tuple, list)): values = x if len(values) > len(f.gens): raise ValueError("too many values provided") for gen, value in zip(f.gens, values): f = f.eval(gen, value) return f else: j, a = 0, x else: j = f._gen_to_level(x) if not hasattr(f.rep, 'eval'): # pragma: no cover raise OperationNotSupported(f, 'eval') try: result = f.rep.eval(a, j) except CoercionFailed: if not auto: raise DomainError("Cannot evaluate at %s in %s" % (a, f.rep.dom)) else: a_domain, [a] = construct_domain([a]) new_domain = f.get_domain().unify_with_symbols(a_domain, f.gens) f = f.set_domain(new_domain) a = new_domain.convert(a, a_domain) result = f.rep.eval(a, j) return f.per(result, remove=j) def __call__(f, *values): """ Evaluate ``f`` at the give values. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> f = Poly(2*x*y + 3*x + y + 2*z, x, y, z) >>> f(2) Poly(5*y + 2*z + 6, y, z, domain='ZZ') >>> f(2, 5) Poly(2*z + 31, z, domain='ZZ') >>> f(2, 5, 7) 45 """ return f.eval(values) def half_gcdex(f, g, auto=True): """ Half extended Euclidean algorithm of ``f`` and ``g``. Returns ``(s, h)`` such that ``h = gcd(f, g)`` and ``s*f = h (mod g)``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15 >>> g = x**3 + x**2 - 4*x - 4 >>> Poly(f).half_gcdex(Poly(g)) (Poly(-1/5*x + 3/5, x, domain='QQ'), Poly(x + 1, x, domain='QQ')) """ dom, per, F, G = f._unify(g) if auto and dom.is_Ring: F, G = F.to_field(), G.to_field() if hasattr(f.rep, 'half_gcdex'): s, h = F.half_gcdex(G) else: # pragma: no cover raise OperationNotSupported(f, 'half_gcdex') return per(s), per(h) def gcdex(f, g, auto=True): """ Extended Euclidean algorithm of ``f`` and ``g``. Returns ``(s, t, h)`` such that ``h = gcd(f, g)`` and ``s*f + t*g = h``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15 >>> g = x**3 + x**2 - 4*x - 4 >>> Poly(f).gcdex(Poly(g)) (Poly(-1/5*x + 3/5, x, domain='QQ'), Poly(1/5*x**2 - 6/5*x + 2, x, domain='QQ'), Poly(x + 1, x, domain='QQ')) """ dom, per, F, G = f._unify(g) if auto and dom.is_Ring: F, G = F.to_field(), G.to_field() if hasattr(f.rep, 'gcdex'): s, t, h = F.gcdex(G) else: # pragma: no cover raise OperationNotSupported(f, 'gcdex') return per(s), per(t), per(h) def invert(f, g, auto=True): """ Invert ``f`` modulo ``g`` when possible. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).invert(Poly(2*x - 1, x)) Poly(-4/3, x, domain='QQ') >>> Poly(x**2 - 1, x).invert(Poly(x - 1, x)) Traceback (most recent call last): ... NotInvertible: zero divisor """ dom, per, F, G = f._unify(g) if auto and dom.is_Ring: F, G = F.to_field(), G.to_field() if hasattr(f.rep, 'invert'): result = F.invert(G) else: # pragma: no cover raise OperationNotSupported(f, 'invert') return per(result) def revert(f, n): """ Compute ``f**(-1)`` mod ``x**n``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(1, x).revert(2) Poly(1, x, domain='ZZ') >>> Poly(1 + x, x).revert(1) Poly(1, x, domain='ZZ') >>> Poly(x**2 - 2, x).revert(2) Traceback (most recent call last): ... NotReversible: only units are reversible in a ring >>> Poly(1/x, x).revert(1) Traceback (most recent call last): ... PolynomialError: 1/x contains an element of the generators set """ if hasattr(f.rep, 'revert'): result = f.rep.revert(int(n)) else: # pragma: no cover raise OperationNotSupported(f, 'revert') return f.per(result) def subresultants(f, g): """ Computes the subresultant PRS of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).subresultants(Poly(x**2 - 1, x)) [Poly(x**2 + 1, x, domain='ZZ'), Poly(x**2 - 1, x, domain='ZZ'), Poly(-2, x, domain='ZZ')] """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'subresultants'): result = F.subresultants(G) else: # pragma: no cover raise OperationNotSupported(f, 'subresultants') return list(map(per, result)) def resultant(f, g, includePRS=False): """ Computes the resultant of ``f`` and ``g`` via PRS. If includePRS=True, it includes the subresultant PRS in the result. Because the PRS is used to calculate the resultant, this is more efficient than calling :func:`subresultants` separately. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = Poly(x**2 + 1, x) >>> f.resultant(Poly(x**2 - 1, x)) 4 >>> f.resultant(Poly(x**2 - 1, x), includePRS=True) (4, [Poly(x**2 + 1, x, domain='ZZ'), Poly(x**2 - 1, x, domain='ZZ'), Poly(-2, x, domain='ZZ')]) """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'resultant'): if includePRS: result, R = F.resultant(G, includePRS=includePRS) else: result = F.resultant(G) else: # pragma: no cover raise OperationNotSupported(f, 'resultant') if includePRS: return (per(result, remove=0), list(map(per, R))) return per(result, remove=0) def discriminant(f): """ Computes the discriminant of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 2*x + 3, x).discriminant() -8 """ if hasattr(f.rep, 'discriminant'): result = f.rep.discriminant() else: # pragma: no cover raise OperationNotSupported(f, 'discriminant') return f.per(result, remove=0) def dispersionset(f, g=None): r"""Compute the *dispersion set* of two polynomials. For two polynomials `f(x)` and `g(x)` with `\deg f > 0` and `\deg g > 0` the dispersion set `\operatorname{J}(f, g)` is defined as: .. math:: \operatorname{J}(f, g) & := \{a \in \mathbb{N}_0 | \gcd(f(x), g(x+a)) \neq 1\} \\ & = \{a \in \mathbb{N}_0 | \deg \gcd(f(x), g(x+a)) \geq 1\} For a single polynomial one defines `\operatorname{J}(f) := \operatorname{J}(f, f)`. Examples ======== >>> from sympy import poly >>> from sympy.polys.dispersion import dispersion, dispersionset >>> from sympy.abc import x Dispersion set and dispersion of a simple polynomial: >>> fp = poly((x - 3)*(x + 3), x) >>> sorted(dispersionset(fp)) [0, 6] >>> dispersion(fp) 6 Note that the definition of the dispersion is not symmetric: >>> fp = poly(x**4 - 3*x**2 + 1, x) >>> gp = fp.shift(-3) >>> sorted(dispersionset(fp, gp)) [2, 3, 4] >>> dispersion(fp, gp) 4 >>> sorted(dispersionset(gp, fp)) [] >>> dispersion(gp, fp) -oo Computing the dispersion also works over field extensions: >>> from sympy import sqrt >>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ<sqrt(5)>') >>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ<sqrt(5)>') >>> sorted(dispersionset(fp, gp)) [2] >>> sorted(dispersionset(gp, fp)) [1, 4] We can even perform the computations for polynomials having symbolic coefficients: >>> from sympy.abc import a >>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x) >>> sorted(dispersionset(fp)) [0, 1] See Also ======== dispersion References ========== 1. [ManWright94]_ 2. [Koepf98]_ 3. [Abramov71]_ 4. [Man93]_ """ from sympy.polys.dispersion import dispersionset return dispersionset(f, g) def dispersion(f, g=None): r"""Compute the *dispersion* of polynomials. For two polynomials `f(x)` and `g(x)` with `\deg f > 0` and `\deg g > 0` the dispersion `\operatorname{dis}(f, g)` is defined as: .. math:: \operatorname{dis}(f, g) & := \max\{ J(f,g) \cup \{0\} \} \\ & = \max\{ \{a \in \mathbb{N} | \gcd(f(x), g(x+a)) \neq 1\} \cup \{0\} \} and for a single polynomial `\operatorname{dis}(f) := \operatorname{dis}(f, f)`. Examples ======== >>> from sympy import poly >>> from sympy.polys.dispersion import dispersion, dispersionset >>> from sympy.abc import x Dispersion set and dispersion of a simple polynomial: >>> fp = poly((x - 3)*(x + 3), x) >>> sorted(dispersionset(fp)) [0, 6] >>> dispersion(fp) 6 Note that the definition of the dispersion is not symmetric: >>> fp = poly(x**4 - 3*x**2 + 1, x) >>> gp = fp.shift(-3) >>> sorted(dispersionset(fp, gp)) [2, 3, 4] >>> dispersion(fp, gp) 4 >>> sorted(dispersionset(gp, fp)) [] >>> dispersion(gp, fp) -oo Computing the dispersion also works over field extensions: >>> from sympy import sqrt >>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ<sqrt(5)>') >>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ<sqrt(5)>') >>> sorted(dispersionset(fp, gp)) [2] >>> sorted(dispersionset(gp, fp)) [1, 4] We can even perform the computations for polynomials having symbolic coefficients: >>> from sympy.abc import a >>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x) >>> sorted(dispersionset(fp)) [0, 1] See Also ======== dispersionset References ========== 1. [ManWright94]_ 2. [Koepf98]_ 3. [Abramov71]_ 4. [Man93]_ """ from sympy.polys.dispersion import dispersion return dispersion(f, g) def cofactors(f, g): """ Returns the GCD of ``f`` and ``g`` and their cofactors. Returns polynomials ``(h, cff, cfg)`` such that ``h = gcd(f, g)``, and ``cff = quo(f, h)`` and ``cfg = quo(g, h)`` are, so called, cofactors of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).cofactors(Poly(x**2 - 3*x + 2, x)) (Poly(x - 1, x, domain='ZZ'), Poly(x + 1, x, domain='ZZ'), Poly(x - 2, x, domain='ZZ')) """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'cofactors'): h, cff, cfg = F.cofactors(G) else: # pragma: no cover raise OperationNotSupported(f, 'cofactors') return per(h), per(cff), per(cfg) def gcd(f, g): """ Returns the polynomial GCD of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).gcd(Poly(x**2 - 3*x + 2, x)) Poly(x - 1, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'gcd'): result = F.gcd(G) else: # pragma: no cover raise OperationNotSupported(f, 'gcd') return per(result) def lcm(f, g): """ Returns polynomial LCM of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).lcm(Poly(x**2 - 3*x + 2, x)) Poly(x**3 - 2*x**2 - x + 2, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'lcm'): result = F.lcm(G) else: # pragma: no cover raise OperationNotSupported(f, 'lcm') return per(result) def trunc(f, p): """ Reduce ``f`` modulo a constant ``p``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**3 + 3*x**2 + 5*x + 7, x).trunc(3) Poly(-x**3 - x + 1, x, domain='ZZ') """ p = f.rep.dom.convert(p) if hasattr(f.rep, 'trunc'): result = f.rep.trunc(p) else: # pragma: no cover raise OperationNotSupported(f, 'trunc') return f.per(result) def monic(self, auto=True): """ Divides all coefficients by ``LC(f)``. Examples ======== >>> from sympy import Poly, ZZ >>> from sympy.abc import x >>> Poly(3*x**2 + 6*x + 9, x, domain=ZZ).monic() Poly(x**2 + 2*x + 3, x, domain='QQ') >>> Poly(3*x**2 + 4*x + 2, x, domain=ZZ).monic() Poly(x**2 + 4/3*x + 2/3, x, domain='QQ') """ f = self if auto and f.rep.dom.is_Ring: f = f.to_field() if hasattr(f.rep, 'monic'): result = f.rep.monic() else: # pragma: no cover raise OperationNotSupported(f, 'monic') return f.per(result) def content(f): """ Returns the GCD of polynomial coefficients. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(6*x**2 + 8*x + 12, x).content() 2 """ if hasattr(f.rep, 'content'): result = f.rep.content() else: # pragma: no cover raise OperationNotSupported(f, 'content') return f.rep.dom.to_sympy(result) def primitive(f): """ Returns the content and a primitive form of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**2 + 8*x + 12, x).primitive() (2, Poly(x**2 + 4*x + 6, x, domain='ZZ')) """ if hasattr(f.rep, 'primitive'): cont, result = f.rep.primitive() else: # pragma: no cover raise OperationNotSupported(f, 'primitive') return f.rep.dom.to_sympy(cont), f.per(result) def compose(f, g): """ Computes the functional composition of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + x, x).compose(Poly(x - 1, x)) Poly(x**2 - x, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'compose'): result = F.compose(G) else: # pragma: no cover raise OperationNotSupported(f, 'compose') return per(result) def decompose(f): """ Computes a functional decomposition of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**4 + 2*x**3 - x - 1, x, domain='ZZ').decompose() [Poly(x**2 - x - 1, x, domain='ZZ'), Poly(x**2 + x, x, domain='ZZ')] """ if hasattr(f.rep, 'decompose'): result = f.rep.decompose() else: # pragma: no cover raise OperationNotSupported(f, 'decompose') return list(map(f.per, result)) def shift(f, a): """ Efficiently compute Taylor shift ``f(x + a)``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 2*x + 1, x).shift(2) Poly(x**2 + 2*x + 1, x, domain='ZZ') See Also ======== shift_list: Analogous method for multivariate polynomials. """ return f.per(f.rep.shift(a)) def shift_list(f, a): """ Efficiently compute Taylor shift ``f(X + A)``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x*y, [x,y]).shift_list([1, 2]) == Poly((x+1)*(y+2), [x,y]) True See Also ======== shift: Analogous method for univariate polynomials. """ return f.per(f.rep.shift_list(a)) def transform(f, p, q): """ Efficiently evaluate the functional transformation ``q**n * f(p/q)``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1, x), Poly(x - 1, x)) Poly(4, x, domain='ZZ') """ P, Q = p.unify(q) F, P = f.unify(P) F, Q = F.unify(Q) if hasattr(F.rep, 'transform'): result = F.rep.transform(P.rep, Q.rep) else: # pragma: no cover raise OperationNotSupported(F, 'transform') return F.per(result) def sturm(self, auto=True): """ Computes the Sturm sequence of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 - 2*x**2 + x - 3, x).sturm() [Poly(x**3 - 2*x**2 + x - 3, x, domain='QQ'), Poly(3*x**2 - 4*x + 1, x, domain='QQ'), Poly(2/9*x + 25/9, x, domain='QQ'), Poly(-2079/4, x, domain='QQ')] """ f = self if auto and f.rep.dom.is_Ring: f = f.to_field() if hasattr(f.rep, 'sturm'): result = f.rep.sturm() else: # pragma: no cover raise OperationNotSupported(f, 'sturm') return list(map(f.per, result)) def gff_list(f): """ Computes greatest factorial factorization of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = x**5 + 2*x**4 - x**3 - 2*x**2 >>> Poly(f).gff_list() [(Poly(x, x, domain='ZZ'), 1), (Poly(x + 2, x, domain='ZZ'), 4)] """ if hasattr(f.rep, 'gff_list'): result = f.rep.gff_list() else: # pragma: no cover raise OperationNotSupported(f, 'gff_list') return [(f.per(g), k) for g, k in result] def norm(f): """ Computes the product, ``Norm(f)``, of the conjugates of a polynomial ``f`` defined over a number field ``K``. Examples ======== >>> from sympy import Poly, sqrt >>> from sympy.abc import x >>> a, b = sqrt(2), sqrt(3) A polynomial over a quadratic extension. Two conjugates x - a and x + a. >>> f = Poly(x - a, x, extension=a) >>> f.norm() Poly(x**2 - 2, x, domain='QQ') A polynomial over a quartic extension. Four conjugates x - a, x - a, x + a and x + a. >>> f = Poly(x - a, x, extension=(a, b)) >>> f.norm() Poly(x**4 - 4*x**2 + 4, x, domain='QQ') """ if hasattr(f.rep, 'norm'): r = f.rep.norm() else: # pragma: no cover raise OperationNotSupported(f, 'norm') return f.per(r) def sqf_norm(f): """ Computes square-free norm of ``f``. Returns ``s``, ``f``, ``r``, such that ``g(x) = f(x-sa)`` and ``r(x) = Norm(g(x))`` is a square-free polynomial over ``K``, where ``a`` is the algebraic extension of the ground domain. Examples ======== >>> from sympy import Poly, sqrt >>> from sympy.abc import x >>> s, f, r = Poly(x**2 + 1, x, extension=[sqrt(3)]).sqf_norm() >>> s [1] >>> f Poly(x**2 - 2*sqrt(3)*x + 4, x, domain='QQ<sqrt(3)>') >>> r Poly(x**4 - 4*x**2 + 16, x, domain='QQ') """ if hasattr(f.rep, 'sqf_norm'): s, g, r = f.rep.sqf_norm() else: # pragma: no cover raise OperationNotSupported(f, 'sqf_norm') return s, f.per(g), f.per(r) def sqf_part(f): """ Computes square-free part of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 - 3*x - 2, x).sqf_part() Poly(x**2 - x - 2, x, domain='ZZ') """ if hasattr(f.rep, 'sqf_part'): result = f.rep.sqf_part() else: # pragma: no cover raise OperationNotSupported(f, 'sqf_part') return f.per(result) def sqf_list(f, all=False): """ Returns a list of square-free factors of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = 2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16 >>> Poly(f).sqf_list() (2, [(Poly(x + 1, x, domain='ZZ'), 2), (Poly(x + 2, x, domain='ZZ'), 3)]) >>> Poly(f).sqf_list(all=True) (2, [(Poly(1, x, domain='ZZ'), 1), (Poly(x + 1, x, domain='ZZ'), 2), (Poly(x + 2, x, domain='ZZ'), 3)]) """ if hasattr(f.rep, 'sqf_list'): coeff, factors = f.rep.sqf_list(all) else: # pragma: no cover raise OperationNotSupported(f, 'sqf_list') return f.rep.dom.to_sympy(coeff), [(f.per(g), k) for g, k in factors] def sqf_list_include(f, all=False): """ Returns a list of square-free factors of ``f``. Examples ======== >>> from sympy import Poly, expand >>> from sympy.abc import x >>> f = expand(2*(x + 1)**3*x**4) >>> f 2*x**7 + 6*x**6 + 6*x**5 + 2*x**4 >>> Poly(f).sqf_list_include() [(Poly(2, x, domain='ZZ'), 1), (Poly(x + 1, x, domain='ZZ'), 3), (Poly(x, x, domain='ZZ'), 4)] >>> Poly(f).sqf_list_include(all=True) [(Poly(2, x, domain='ZZ'), 1), (Poly(1, x, domain='ZZ'), 2), (Poly(x + 1, x, domain='ZZ'), 3), (Poly(x, x, domain='ZZ'), 4)] """ if hasattr(f.rep, 'sqf_list_include'): factors = f.rep.sqf_list_include(all) else: # pragma: no cover raise OperationNotSupported(f, 'sqf_list_include') return [(f.per(g), k) for g, k in factors] def factor_list(f) -> tuple[Expr, list[tuple[Poly, int]]]: """ Returns a list of irreducible factors of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = 2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y >>> Poly(f).factor_list() (2, [(Poly(x + y, x, y, domain='ZZ'), 1), (Poly(x**2 + 1, x, y, domain='ZZ'), 2)]) """ if hasattr(f.rep, 'factor_list'): try: coeff, factors = f.rep.factor_list() except DomainError: if f.degree() == 0: return f.as_expr(), [] else: return S.One, [(f, 1)] else: # pragma: no cover raise OperationNotSupported(f, 'factor_list') return f.rep.dom.to_sympy(coeff), [(f.per(g), k) for g, k in factors] def factor_list_include(f): """ Returns a list of irreducible factors of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = 2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y >>> Poly(f).factor_list_include() [(Poly(2*x + 2*y, x, y, domain='ZZ'), 1), (Poly(x**2 + 1, x, y, domain='ZZ'), 2)] """ if hasattr(f.rep, 'factor_list_include'): try: factors = f.rep.factor_list_include() except DomainError: return [(f, 1)] else: # pragma: no cover raise OperationNotSupported(f, 'factor_list_include') return [(f.per(g), k) for g, k in factors] def intervals(f, all=False, eps=None, inf=None, sup=None, fast=False, sqf=False): """ Compute isolating intervals for roots of ``f``. For real roots the Vincent-Akritas-Strzebonski (VAS) continued fractions method is used. References ========== .. [#] Alkiviadis G. Akritas and Adam W. Strzebonski: A Comparative Study of Two Real Root Isolation Methods . Nonlinear Analysis: Modelling and Control, Vol. 10, No. 4, 297-304, 2005. .. [#] Alkiviadis G. Akritas, Adam W. Strzebonski and Panagiotis S. Vigklas: Improving the Performance of the Continued Fractions Method Using new Bounds of Positive Roots. Nonlinear Analysis: Modelling and Control, Vol. 13, No. 3, 265-279, 2008. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 3, x).intervals() [((-2, -1), 1), ((1, 2), 1)] >>> Poly(x**2 - 3, x).intervals(eps=1e-2) [((-26/15, -19/11), 1), ((19/11, 26/15), 1)] """ if eps is not None: eps = QQ.convert(eps) if eps <= 0: raise ValueError("'eps' must be a positive rational") if inf is not None: inf = QQ.convert(inf) if sup is not None: sup = QQ.convert(sup) if hasattr(f.rep, 'intervals'): result = f.rep.intervals( all=all, eps=eps, inf=inf, sup=sup, fast=fast, sqf=sqf) else: # pragma: no cover raise OperationNotSupported(f, 'intervals') if sqf: def _real(interval): s, t = interval return (QQ.to_sympy(s), QQ.to_sympy(t)) if not all: return list(map(_real, result)) def _complex(rectangle): (u, v), (s, t) = rectangle return (QQ.to_sympy(u) + I*QQ.to_sympy(v), QQ.to_sympy(s) + I*QQ.to_sympy(t)) real_part, complex_part = result return list(map(_real, real_part)), list(map(_complex, complex_part)) else: def _real(interval): (s, t), k = interval return ((QQ.to_sympy(s), QQ.to_sympy(t)), k) if not all: return list(map(_real, result)) def _complex(rectangle): ((u, v), (s, t)), k = rectangle return ((QQ.to_sympy(u) + I*QQ.to_sympy(v), QQ.to_sympy(s) + I*QQ.to_sympy(t)), k) real_part, complex_part = result return list(map(_real, real_part)), list(map(_complex, complex_part)) def refine_root(f, s, t, eps=None, steps=None, fast=False, check_sqf=False): """ Refine an isolating interval of a root to the given precision. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 3, x).refine_root(1, 2, eps=1e-2) (19/11, 26/15) """ if check_sqf and not f.is_sqf: raise PolynomialError("only square-free polynomials supported") s, t = QQ.convert(s), QQ.convert(t) if eps is not None: eps = QQ.convert(eps) if eps <= 0: raise ValueError("'eps' must be a positive rational") if steps is not None: steps = int(steps) elif eps is None: steps = 1 if hasattr(f.rep, 'refine_root'): S, T = f.rep.refine_root(s, t, eps=eps, steps=steps, fast=fast) else: # pragma: no cover raise OperationNotSupported(f, 'refine_root') return QQ.to_sympy(S), QQ.to_sympy(T) def count_roots(f, inf=None, sup=None): """ Return the number of roots of ``f`` in ``[inf, sup]`` interval. Examples ======== >>> from sympy import Poly, I >>> from sympy.abc import x >>> Poly(x**4 - 4, x).count_roots(-3, 3) 2 >>> Poly(x**4 - 4, x).count_roots(0, 1 + 3*I) 1 """ inf_real, sup_real = True, True if inf is not None: inf = sympify(inf) if inf is S.NegativeInfinity: inf = None else: re, im = inf.as_real_imag() if not im: inf = QQ.convert(inf) else: inf, inf_real = list(map(QQ.convert, (re, im))), False if sup is not None: sup = sympify(sup) if sup is S.Infinity: sup = None else: re, im = sup.as_real_imag() if not im: sup = QQ.convert(sup) else: sup, sup_real = list(map(QQ.convert, (re, im))), False if inf_real and sup_real: if hasattr(f.rep, 'count_real_roots'): count = f.rep.count_real_roots(inf=inf, sup=sup) else: # pragma: no cover raise OperationNotSupported(f, 'count_real_roots') else: if inf_real and inf is not None: inf = (inf, QQ.zero) if sup_real and sup is not None: sup = (sup, QQ.zero) if hasattr(f.rep, 'count_complex_roots'): count = f.rep.count_complex_roots(inf=inf, sup=sup) else: # pragma: no cover raise OperationNotSupported(f, 'count_complex_roots') return Integer(count) def root(f, index, radicals=True): """ Get an indexed root of a polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = Poly(2*x**3 - 7*x**2 + 4*x + 4) >>> f.root(0) -1/2 >>> f.root(1) 2 >>> f.root(2) 2 >>> f.root(3) Traceback (most recent call last): ... IndexError: root index out of [-3, 2] range, got 3 >>> Poly(x**5 + x + 1).root(0) CRootOf(x**3 - x**2 + 1, 0) """ return sympy.polys.rootoftools.rootof(f, index, radicals=radicals) def real_roots(f, multiple=True, radicals=True): """ Return a list of real roots with multiplicities. See :func:`real_roots` for more explanation. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**3 - 7*x**2 + 4*x + 4).real_roots() [-1/2, 2, 2] >>> Poly(x**3 + x + 1).real_roots() [CRootOf(x**3 + x + 1, 0)] """ reals = sympy.polys.rootoftools.CRootOf.real_roots(f, radicals=radicals) if multiple: return reals else: return group(reals, multiple=False) def all_roots(f, multiple=True, radicals=True): """ Return a list of real and complex roots with multiplicities. See :func:`all_roots` for more explanation. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**3 - 7*x**2 + 4*x + 4).all_roots() [-1/2, 2, 2] >>> Poly(x**3 + x + 1).all_roots() [CRootOf(x**3 + x + 1, 0), CRootOf(x**3 + x + 1, 1), CRootOf(x**3 + x + 1, 2)] """ roots = sympy.polys.rootoftools.CRootOf.all_roots(f, radicals=radicals) if multiple: return roots else: return group(roots, multiple=False) def nroots(f, n=15, maxsteps=50, cleanup=True): """ Compute numerical approximations of roots of ``f``. Parameters ========== n ... the number of digits to calculate maxsteps ... the maximum number of iterations to do If the accuracy `n` cannot be reached in `maxsteps`, it will raise an exception. You need to rerun with higher maxsteps. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 3).nroots(n=15) [-1.73205080756888, 1.73205080756888] >>> Poly(x**2 - 3).nroots(n=30) [-1.73205080756887729352744634151, 1.73205080756887729352744634151] """ if f.is_multivariate: raise MultivariatePolynomialError( "Cannot compute numerical roots of %s" % f) if f.degree() <= 0: return [] # For integer and rational coefficients, convert them to integers only # (for accuracy). Otherwise just try to convert the coefficients to # mpmath.mpc and raise an exception if the conversion fails. if f.rep.dom is ZZ: coeffs = [int(coeff) for coeff in f.all_coeffs()] elif f.rep.dom is QQ: denoms = [coeff.q for coeff in f.all_coeffs()] fac = ilcm(*denoms) coeffs = [int(coeff*fac) for coeff in f.all_coeffs()] else: coeffs = [coeff.evalf(n=n).as_real_imag() for coeff in f.all_coeffs()] with mpmath.workdps(n): try: coeffs = [mpmath.mpc(*coeff) for coeff in coeffs] except TypeError: raise DomainError("Numerical domain expected, got %s" % \ f.rep.dom) dps = mpmath.mp.dps mpmath.mp.dps = n from sympy.functions.elementary.complexes import sign try: # We need to add extra precision to guard against losing accuracy. # 10 times the degree of the polynomial seems to work well. roots = mpmath.polyroots(coeffs, maxsteps=maxsteps, cleanup=cleanup, error=False, extraprec=f.degree()*10) # Mpmath puts real roots first, then complex ones (as does all_roots) # so we make sure this convention holds here, too. roots = list(map(sympify, sorted(roots, key=lambda r: (1 if r.imag else 0, r.real, abs(r.imag), sign(r.imag))))) except NoConvergence: try: # If roots did not converge try again with more extra precision. roots = mpmath.polyroots(coeffs, maxsteps=maxsteps, cleanup=cleanup, error=False, extraprec=f.degree()*15) roots = list(map(sympify, sorted(roots, key=lambda r: (1 if r.imag else 0, r.real, abs(r.imag), sign(r.imag))))) except NoConvergence: raise NoConvergence( 'convergence to root failed; try n < %s or maxsteps > %s' % ( n, maxsteps)) finally: mpmath.mp.dps = dps return roots def ground_roots(f): """ Compute roots of ``f`` by factorization in the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**6 - 4*x**4 + 4*x**3 - x**2).ground_roots() {0: 2, 1: 2} """ if f.is_multivariate: raise MultivariatePolynomialError( "Cannot compute ground roots of %s" % f) roots = {} for factor, k in f.factor_list()[1]: if factor.is_linear: a, b = factor.all_coeffs() roots[-b/a] = k return roots def nth_power_roots_poly(f, n): """ Construct a polynomial with n-th powers of roots of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = Poly(x**4 - x**2 + 1) >>> f.nth_power_roots_poly(2) Poly(x**4 - 2*x**3 + 3*x**2 - 2*x + 1, x, domain='ZZ') >>> f.nth_power_roots_poly(3) Poly(x**4 + 2*x**2 + 1, x, domain='ZZ') >>> f.nth_power_roots_poly(4) Poly(x**4 + 2*x**3 + 3*x**2 + 2*x + 1, x, domain='ZZ') >>> f.nth_power_roots_poly(12) Poly(x**4 - 4*x**3 + 6*x**2 - 4*x + 1, x, domain='ZZ') """ if f.is_multivariate: raise MultivariatePolynomialError( "must be a univariate polynomial") N = sympify(n) if N.is_Integer and N >= 1: n = int(N) else: raise ValueError("'n' must an integer and n >= 1, got %s" % n) x = f.gen t = Dummy('t') r = f.resultant(f.__class__.from_expr(x**n - t, x, t)) return r.replace(t, x) def which_real_roots(f, candidates): """ Find roots of a square-free polynomial ``f`` from ``candidates``. Explanation =========== If ``f`` is a square-free polynomial and ``candidates`` is a superset of the roots of ``f``, then ``f.which_real_roots(candidates)`` returns a list containing exactly the set of roots of ``f``. The domain must be :ref:`ZZ`, :ref:`QQ`, or :ref:`QQ(a)` and``f`` must be univariate and square-free. The list ``candidates`` must be a superset of the real roots of ``f`` and ``f.which_real_roots(candidates)`` returns the set of real roots of ``f``. The output preserves the order of the order of ``candidates``. Examples ======== >>> from sympy import Poly, sqrt >>> from sympy.abc import x >>> f = Poly(x**4 - 1) >>> f.which_real_roots([-1, 1, 0, -2, 2]) [-1, 1] >>> f.which_real_roots([-1, 1, 1, 1, 1]) [-1, 1] This method is useful as lifting to rational coefficients produced extraneous roots, which we can filter out with this method. >>> f = Poly(sqrt(2)*x**3 + x**2 - 1, x, extension=True) >>> f.lift() Poly(-2*x**6 + x**4 - 2*x**2 + 1, x, domain='QQ') >>> f.lift().real_roots() [-sqrt(2)/2, sqrt(2)/2] >>> f.which_real_roots(f.lift().real_roots()) [sqrt(2)/2] This procedure is already done internally when calling `.real_roots()` on a polynomial with algebraic coefficients. >>> f.real_roots() [sqrt(2)/2] See Also ======== same_root which_all_roots """ if f.is_multivariate: raise MultivariatePolynomialError( "Must be a univariate polynomial") dom = f.get_domain() if not (dom.is_ZZ or dom.is_QQ or dom.is_AlgebraicField): raise NotImplementedError( "root counting not supported over %s" % dom) return f._which_roots(candidates, f.count_roots()) def which_all_roots(f, candidates): """ Find roots of a square-free polynomial ``f`` from ``candidates``. Explanation =========== If ``f`` is a square-free polynomial and ``candidates`` is a superset of the roots of ``f``, then ``f.which_all_roots(candidates)`` returns a list containing exactly the set of roots of ``f``. The polynomial``f`` must be univariate and square-free. The list ``candidates`` must be a superset of the complex roots of ``f`` and ``f.which_all_roots(candidates)`` returns exactly the set of all complex roots of ``f``. The output preserves the order of the order of ``candidates``. Examples ======== >>> from sympy import Poly, I >>> from sympy.abc import x >>> f = Poly(x**4 - 1) >>> f.which_all_roots([-1, 1, -I, I, 0]) [-1, 1, -I, I] >>> f.which_all_roots([-1, 1, -I, I, I, I]) [-1, 1, -I, I] This method is useful as lifting to rational coefficients produced extraneous roots, which we can filter out with this method. >>> f = Poly(x**2 + I*x - 1, x, extension=True) >>> f.lift() Poly(x**4 - x**2 + 1, x, domain='ZZ') >>> f.lift().all_roots() [CRootOf(x**4 - x**2 + 1, 0), CRootOf(x**4 - x**2 + 1, 1), CRootOf(x**4 - x**2 + 1, 2), CRootOf(x**4 - x**2 + 1, 3)] >>> f.which_all_roots(f.lift().all_roots()) [CRootOf(x**4 - x**2 + 1, 0), CRootOf(x**4 - x**2 + 1, 2)] This procedure is already done internally when calling `.all_roots()` on a polynomial with algebraic coefficients, or polynomials with Gaussian domains. >>> f.all_roots() [CRootOf(x**4 - x**2 + 1, 0), CRootOf(x**4 - x**2 + 1, 2)] See Also ======== same_root which_real_roots """ if f.is_multivariate: raise MultivariatePolynomialError( "Must be a univariate polynomial") return f._which_roots(candidates, f.degree()) def _which_roots(f, candidates, num_roots): prec = 10 # using Counter bc its like an ordered set root_counts = Counter(candidates) while len(root_counts) > num_roots: for r in list(root_counts.keys()): # If f(r) != 0 then f(r).evalf() gives a float/complex with precision. f_r = f(r).evalf(prec, maxn=2*prec) if abs(f_r)._prec >= 2: root_counts.pop(r) prec *= 2 return list(root_counts.keys()) def same_root(f, a, b): """ Decide whether two roots of this polynomial are equal. Examples ======== >>> from sympy import Poly, cyclotomic_poly, exp, I, pi >>> f = Poly(cyclotomic_poly(5)) >>> r0 = exp(2*I*pi/5) >>> indices = [i for i, r in enumerate(f.all_roots()) if f.same_root(r, r0)] >>> print(indices) [3] Raises ====== DomainError If the domain of the polynomial is not :ref:`ZZ`, :ref:`QQ`, :ref:`RR`, or :ref:`CC`. MultivariatePolynomialError If the polynomial is not univariate. PolynomialError If the polynomial is of degree < 2. See Also ======== which_real_roots which_all_roots """ if f.is_multivariate: raise MultivariatePolynomialError( "Must be a univariate polynomial") dom_delta_sq = f.rep.mignotte_sep_bound_squared() delta_sq = f.domain.get_field().to_sympy(dom_delta_sq) # We have delta_sq = delta**2, where delta is a lower bound on the # minimum separation between any two roots of this polynomial. # Let eps = delta/3, and define eps_sq = eps**2 = delta**2/9. eps_sq = delta_sq / 9 r, _, _, _ = evalf(1/eps_sq, 1, {}) n = fastlog(r) # Then 2^n > 1/eps**2. m = (n // 2) + (n % 2) # Then 2^(-m) < eps. ev = lambda x: quad_to_mpmath(_evalf_with_bounded_error(x, m=m)) # Then for any complex numbers a, b we will have # |a - ev(a)| < eps and |b - ev(b)| < eps. # So if |ev(a) - ev(b)|**2 < eps**2, then # |ev(a) - ev(b)| < eps, hence |a - b| < 3*eps = delta. A, B = ev(a), ev(b) return (A.real - B.real)**2 + (A.imag - B.imag)**2 < eps_sq def cancel(f, g, include=False): """ Cancel common factors in a rational function ``f/g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**2 - 2, x).cancel(Poly(x**2 - 2*x + 1, x)) (1, Poly(2*x + 2, x, domain='ZZ'), Poly(x - 1, x, domain='ZZ')) >>> Poly(2*x**2 - 2, x).cancel(Poly(x**2 - 2*x + 1, x), include=True) (Poly(2*x + 2, x, domain='ZZ'), Poly(x - 1, x, domain='ZZ')) """ dom, per, F, G = f._unify(g) if hasattr(F, 'cancel'): result = F.cancel(G, include=include) else: # pragma: no cover raise OperationNotSupported(f, 'cancel') if not include: if dom.has_assoc_Ring: dom = dom.get_ring() cp, cq, p, q = result cp = dom.to_sympy(cp) cq = dom.to_sympy(cq) return cp/cq, per(p), per(q) else: return tuple(map(per, result)) def make_monic_over_integers_by_scaling_roots(f): """ Turn any univariate polynomial over :ref:`QQ` or :ref:`ZZ` into a monic polynomial over :ref:`ZZ`, by scaling the roots as necessary. Explanation =========== This operation can be performed whether or not *f* is irreducible; when it is, this can be understood as determining an algebraic integer generating the same field as a root of *f*. Examples ======== >>> from sympy import Poly, S >>> from sympy.abc import x >>> f = Poly(x**2/2 + S(1)/4 * x + S(1)/8, x, domain='QQ') >>> f.make_monic_over_integers_by_scaling_roots() (Poly(x**2 + 2*x + 4, x, domain='ZZ'), 4) Returns ======= Pair ``(g, c)`` g is the polynomial c is the integer by which the roots had to be scaled """ if not f.is_univariate or f.domain not in [ZZ, QQ]: raise ValueError('Polynomial must be univariate over ZZ or QQ.') if f.is_monic and f.domain == ZZ: return f, ZZ.one else: fm = f.monic() c, _ = fm.clear_denoms() return fm.transform(Poly(fm.gen), c).to_ring(), c def galois_group(f, by_name=False, max_tries=30, randomize=False): """ Compute the Galois group of this polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = Poly(x**4 - 2) >>> G, _ = f.galois_group(by_name=True) >>> print(G) S4TransitiveSubgroups.D4 See Also ======== sympy.polys.numberfields.galoisgroups.galois_group """ from sympy.polys.numberfields.galoisgroups import ( _galois_group_degree_3, _galois_group_degree_4_lookup, _galois_group_degree_5_lookup_ext_factor, _galois_group_degree_6_lookup, ) if (not f.is_univariate or not f.is_irreducible or f.domain not in [ZZ, QQ] ): raise ValueError('Polynomial must be irreducible and univariate over ZZ or QQ.') gg = { 3: _galois_group_degree_3, 4: _galois_group_degree_4_lookup, 5: _galois_group_degree_5_lookup_ext_factor, 6: _galois_group_degree_6_lookup, } max_supported = max(gg.keys()) n = f.degree() if n > max_supported: raise ValueError(f"Only polynomials up to degree {max_supported} are supported.") elif n < 1: raise ValueError("Constant polynomial has no Galois group.") elif n == 1: from sympy.combinatorics.galois import S1TransitiveSubgroups name, alt = S1TransitiveSubgroups.S1, True elif n == 2: from sympy.combinatorics.galois import S2TransitiveSubgroups name, alt = S2TransitiveSubgroups.S2, False else: g, _ = f.make_monic_over_integers_by_scaling_roots() name, alt = gg[n](g, max_tries=max_tries, randomize=randomize) G = name if by_name else name.get_perm_group() return G, alt def hurwitz_conditions(f): """ Compute the conditions that ensure ``f`` is a Hurwitz polynomial of full degree. Explanation =========== Returns expressions ``[e1, e2, ...]`` such that the leading coefficient is nonzero and all roots of the polynomial have strictly negative real part if and only if ``ei > 0`` for all ``i``. Note ==== If you need a fast computation of the conditions, consider using the domain ``EXRAW``. Conditions may be less simplified, but the computation will be a lot faster. Examples ======== >>> from sympy import symbols, Poly, reduce_inequalities >>> x, k = symbols("x k") >>> p3 = Poly(x**3 + x**2 + 2*k*x + 1 - k, x) >>> conditions = p3.hurwitz_conditions() >>> conditions [1, 3*k - 1, 1 - k] >>> reduce_inequalities([c > 0 for c in conditions]) (1/3 < k) & (k < 1) References ========== .. [1] G. Meinsma: Elementary proof of the Routh-Hurwitz test. Systems & Control Letters, Volume 25, Issue 4, 1995, Pages 237-242, https://courses.washington.edu/mengr471/resources/Routh_Hurwitz_Proof.pdf """ conds = f.rep.hurwitz_conditions() return [f.domain.to_sympy(cond) for cond in conds] def schur_conditions(f): """ Compute the conditions that ensure ``f`` is a Schur stable polynomial. Explanation =========== Returns expressions ``[e1, e2, ...]`` such that all roots of the polynomial lie inside the unit circle if and only if ``ei > 0`` for all ``i``. Note ==== If you need a fast computation of the conditions, consider using the domain ``EXRAW``. Conditions may be less simplified and there could be some precision issues, but the computation will be a lot faster. Examples ======== >>> from sympy import symbols, Poly, reduce_inequalities >>> x, k = symbols("x k") >>> p3 = Poly(x**3 + x**2 + 2*k*x + 1 - k, x) >>> conditions = p3.schur_conditions() >>> conditions [-15*k**2 + 20*k - 5, -8*k**2 - 8*k + 8, 3*k**2 + 8*k - 3] >>> reduce_inequalities([c > 0 for c in conditions]) (1/3 < k) & (k < -1/2 + sqrt(5)/2) References ========== .. [1] https://faculty.washington.edu/chx/teaching/me547/2_1_stability.pdf#:~:text=2.6%20Routh,plane%20Real """ conds = f.rep.schur_conditions() return [f.domain.to_sympy(cond) for cond in conds] @property def is_zero(f): """ Returns ``True`` if ``f`` is a zero polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(0, x).is_zero True >>> Poly(1, x).is_zero False """ return f.rep.is_zero @property def is_one(f): """ Returns ``True`` if ``f`` is a unit polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(0, x).is_one False >>> Poly(1, x).is_one True """ return f.rep.is_one @property def is_sqf(f): """ Returns ``True`` if ``f`` is a square-free polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 2*x + 1, x).is_sqf False >>> Poly(x**2 - 1, x).is_sqf True """ return f.rep.is_sqf @property def is_monic(f): """ Returns ``True`` if the leading coefficient of ``f`` is one. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x + 2, x).is_monic True >>> Poly(2*x + 2, x).is_monic False """ return f.rep.is_monic @property def is_primitive(f): """ Returns ``True`` if GCD of the coefficients of ``f`` is one. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**2 + 6*x + 12, x).is_primitive False >>> Poly(x**2 + 3*x + 6, x).is_primitive True """ return f.rep.is_primitive @property def is_ground(f): """ Returns ``True`` if ``f`` is an element of the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x, x).is_ground False >>> Poly(2, x).is_ground True >>> Poly(y, x).is_ground True """ return f.rep.is_ground @property def is_linear(f): """ Returns ``True`` if ``f`` is linear in all its variables. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x + y + 2, x, y).is_linear True >>> Poly(x*y + 2, x, y).is_linear False """ return f.rep.is_linear @property def is_quadratic(f): """ Returns ``True`` if ``f`` is quadratic in all its variables. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x*y + 2, x, y).is_quadratic True >>> Poly(x*y**2 + 2, x, y).is_quadratic False """ return f.rep.is_quadratic @property def is_monomial(f): """ Returns ``True`` if ``f`` is zero or has only one term. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(3*x**2, x).is_monomial True >>> Poly(3*x**2 + 1, x).is_monomial False """ return f.rep.is_monomial @property def is_homogeneous(f): """ Returns ``True`` if ``f`` is a homogeneous polynomial. A homogeneous polynomial is a polynomial whose all monomials with non-zero coefficients have the same total degree. If you want not only to check if a polynomial is homogeneous but also compute its homogeneous order, then use :func:`Poly.homogeneous_order`. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + x*y, x, y).is_homogeneous True >>> Poly(x**3 + x*y, x, y).is_homogeneous False """ return f.rep.is_homogeneous @property def is_irreducible(f): """ Returns ``True`` if ``f`` has no factors over its domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + x + 1, x, modulus=2).is_irreducible True >>> Poly(x**2 + 1, x, modulus=2).is_irreducible False """ return f.rep.is_irreducible @property def is_univariate(f): """ Returns ``True`` if ``f`` is a univariate polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + x + 1, x).is_univariate True >>> Poly(x*y**2 + x*y + 1, x, y).is_univariate False >>> Poly(x*y**2 + x*y + 1, x).is_univariate True >>> Poly(x**2 + x + 1, x, y).is_univariate False """ return len(f.gens) == 1 @property def is_multivariate(f): """ Returns ``True`` if ``f`` is a multivariate polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + x + 1, x).is_multivariate False >>> Poly(x*y**2 + x*y + 1, x, y).is_multivariate True >>> Poly(x*y**2 + x*y + 1, x).is_multivariate False >>> Poly(x**2 + x + 1, x, y).is_multivariate True """ return len(f.gens) != 1 @property def is_cyclotomic(f): """ Returns ``True`` if ``f`` is a cyclotomic polnomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1 >>> Poly(f).is_cyclotomic False >>> g = x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1 >>> Poly(g).is_cyclotomic True """ return f.rep.is_cyclotomic def __abs__(f): return f.abs() def __neg__(f): return f.neg() @_polifyit def __add__(f, g): return f.add(g) @_polifyit def __radd__(f, g): return g.add(f) @_polifyit def __sub__(f, g): return f.sub(g) @_polifyit def __rsub__(f, g): return g.sub(f) @_polifyit def __mul__(f, g): return f.mul(g) @_polifyit def __rmul__(f, g): return g.mul(f) @_sympifyit('n', NotImplemented) def __pow__(f, n): if n.is_Integer and n >= 0: return f.pow(n) else: return NotImplemented @_polifyit def __divmod__(f, g): return f.div(g) @_polifyit def __rdivmod__(f, g): return g.div(f) @_polifyit def __mod__(f, g): return f.rem(g) @_polifyit def __rmod__(f, g): return g.rem(f) @_polifyit def __floordiv__(f, g): return f.quo(g) @_polifyit def __rfloordiv__(f, g): return g.quo(f) @_sympifyit('g', NotImplemented) def __truediv__(f, g): return f.as_expr()/g.as_expr() @_sympifyit('g', NotImplemented) def __rtruediv__(f, g): return g.as_expr()/f.as_expr() @_sympifyit('other', NotImplemented) def __eq__(self, other): f, g = self, other if not g.is_Poly: try: g = f.__class__(g, f.gens, domain=f.get_domain()) except (PolynomialError, DomainError, CoercionFailed): return False if f.gens != g.gens: return False if f.rep.dom != g.rep.dom: return False return f.rep == g.rep @_sympifyit('g', NotImplemented) def __ne__(f, g): return not f == g def __bool__(f): return not f.is_zero def eq(f, g, strict=False): if not strict: return f == g else: return f._strict_eq(sympify(g)) def ne(f, g, strict=False): return not f.eq(g, strict=strict) def _strict_eq(f, g): return isinstance(g, f.__class__) and f.gens == g.gens and f.rep.eq(g.rep, strict=True) @public
Poly
python
ray-project__ray
python/ray/_private/worker.py
{ "start": 10846, "end": 12224 }
class ____(HasOptions, Generic[R, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9]): def __init__( self, function: Callable[[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9], R] ) -> None: pass def remote( self, __arg0: "Union[T0, ObjectRef[T0]]", __arg1: "Union[T1, ObjectRef[T1]]", __arg2: "Union[T2, ObjectRef[T2]]", __arg3: "Union[T3, ObjectRef[T3]]", __arg4: "Union[T4, ObjectRef[T4]]", __arg5: "Union[T5, ObjectRef[T5]]", __arg6: "Union[T6, ObjectRef[T6]]", __arg7: "Union[T7, ObjectRef[T7]]", __arg8: "Union[T8, ObjectRef[T8]]", __arg9: "Union[T9, ObjectRef[T9]]", ) -> "ObjectRef[R]": ... def bind( self, __arg0: "Union[T0, DAGNode[T0]]", __arg1: "Union[T1, DAGNode[T1]]", __arg2: "Union[T2, DAGNode[T2]]", __arg3: "Union[T3, DAGNode[T3]]", __arg4: "Union[T4, DAGNode[T4]]", __arg5: "Union[T5, DAGNode[T5]]", __arg6: "Union[T6, DAGNode[T6]]", __arg7: "Union[T7, DAGNode[T7]]", __arg8: "Union[T8, DAGNode[T8]]", __arg9: "Union[T9, DAGNode[T9]]", ) -> "DAGNode[R]": ... # Visible for testing. def _unhandled_error_handler(e: Exception): logger.error( f"Unhandled error (suppress with 'RAY_IGNORE_UNHANDLED_ERRORS=1'): {e}" )
RemoteFunction9
python
jazzband__django-model-utils
tests/test_managers/test_inheritance_manager.py
{ "start": 8431, "end": 21185 }
class ____(TestCase): def setUp(self) -> None: self.parent1 = InheritanceManagerTestParent.objects.create() self.child1 = InheritanceManagerTestChild1.objects.create() self.child2 = InheritanceManagerTestChild2.objects.create() self.grandchild1 = InheritanceManagerTestGrandChild1.objects.create() self.grandchild1_2 = InheritanceManagerTestGrandChild1_2.objects.create() def test_select_subclass_by_child_model(self) -> None: """ Confirm that passing a child model works the same as passing the select_related manually """ objs = InheritanceManagerTestParent.objects.select_subclasses( "inheritancemanagertestchild1").order_by('pk') objsmodels = InheritanceManagerTestParent.objects.select_subclasses( InheritanceManagerTestChild1).order_by('pk') self.assertEqual(objs.subclasses, objsmodels.subclasses) self.assertEqual(list(objs), list(objsmodels)) def test_select_subclass_by_grandchild_model(self) -> None: """ Confirm that passing a grandchild model works the same as passing the select_related manually """ objs = InheritanceManagerTestParent.objects.select_subclasses( "inheritancemanagertestchild1__inheritancemanagertestgrandchild1") \ .order_by('pk') objsmodels = InheritanceManagerTestParent.objects.select_subclasses( InheritanceManagerTestGrandChild1).order_by('pk') self.assertEqual(objs.subclasses, objsmodels.subclasses) self.assertEqual(list(objs), list(objsmodels)) def test_selecting_all_subclasses_specifically_grandchildren(self) -> None: """ A bare select_subclasses() should achieve the same results as doing select_subclasses and specifying all possible subclasses. This test checks grandchildren, so only works on 1.6>= """ objs = InheritanceManagerTestParent.objects.select_subclasses().order_by('pk') objsmodels = InheritanceManagerTestParent.objects.select_subclasses( InheritanceManagerTestChild1, InheritanceManagerTestChild2, InheritanceManagerTestChild3, InheritanceManagerTestChild3_1, InheritanceManagerTestChild4, InheritanceManagerTestGrandChild1, InheritanceManagerTestGrandChild1_2).order_by('pk') self.assertEqual(set(objs.subclasses), set(objsmodels.subclasses)) self.assertEqual(list(objs), list(objsmodels)) def test_selecting_all_subclasses_specifically_children(self) -> None: """ A bare select_subclasses() should achieve the same results as doing select_subclasses and specifying all possible subclasses. Note: This is sort of the same test as `test_selecting_all_subclasses_specifically_grandchildren` but it specifically switches what models are used because that happens behind the scenes in a bare select_subclasses(), so we need to emulate it. """ objs = InheritanceManagerTestParent.objects.select_subclasses().order_by('pk') models = (InheritanceManagerTestChild1, InheritanceManagerTestChild2, InheritanceManagerTestChild3, InheritanceManagerTestChild3_1, InheritanceManagerTestChild4, InheritanceManagerTestGrandChild1, InheritanceManagerTestGrandChild1_2) objsmodels = InheritanceManagerTestParent.objects.select_subclasses( *models).order_by('pk') # order shouldn't matter, I don't think, as long as the resulting # queryset (when cast to a list) is the same. self.assertEqual(set(objs.subclasses), set(objsmodels.subclasses)) self.assertEqual(list(objs), list(objsmodels)) def test_select_subclass_just_self(self) -> None: """ Passing in the same model as the manager/queryset is bound against (ie: the root parent) should have no effect on the result set. """ objsmodels = InheritanceManagerTestParent.objects.select_subclasses( InheritanceManagerTestParent).order_by('pk') self.assertEqual([], objsmodels.subclasses) self.assertEqual(list(objsmodels), [ InheritanceManagerTestParent(pk=self.parent1.pk), InheritanceManagerTestParent(pk=self.child1.pk), InheritanceManagerTestParent(pk=self.child2.pk), InheritanceManagerTestParent(pk=self.grandchild1.pk), InheritanceManagerTestParent(pk=self.grandchild1_2.pk), ]) def test_select_subclass_invalid_related_model(self) -> None: """ Confirming that giving a stupid model doesn't work. """ regex = '^.+? is not a subclass of .+$' with self.assertRaisesRegex(ValueError, regex): InheritanceManagerTestParent.objects.select_subclasses( TimeFrame).order_by('pk') def test_mixing_strings_and_classes_with_grandchildren(self) -> None: """ Given arguments consisting of both strings and model classes, ensure the right resolutions take place, accounting for the extra depth (grandchildren etc) 1.6> allows. """ objs = InheritanceManagerTestParent.objects.select_subclasses( "inheritancemanagertestchild2", InheritanceManagerTestGrandChild1_2).order_by('pk') expecting = ['inheritancemanagertestchild1__inheritancemanagertestgrandchild1_2', 'inheritancemanagertestchild2'] self.assertEqual(set(objs.subclasses), set(expecting)) expecting2 = [ InheritanceManagerTestParent(pk=self.parent1.pk), InheritanceManagerTestParent(pk=self.child1.pk), InheritanceManagerTestChild2(pk=self.child2.pk), InheritanceManagerTestParent(pk=self.grandchild1.pk), InheritanceManagerTestGrandChild1_2(pk=self.grandchild1_2.pk), ] self.assertEqual(list(objs), expecting2) def test_mixing_strings_and_classes_with_children(self) -> None: """ Given arguments consisting of both strings and model classes, ensure the right resolutions take place, walking down as far as children. """ objs = InheritanceManagerTestParent.objects.select_subclasses( "inheritancemanagertestchild2", InheritanceManagerTestChild1).order_by('pk') expecting = ['inheritancemanagertestchild1', 'inheritancemanagertestchild2'] self.assertEqual(set(objs.subclasses), set(expecting)) expecting2 = [ InheritanceManagerTestParent(pk=self.parent1.pk), InheritanceManagerTestChild1(pk=self.child1.pk), InheritanceManagerTestChild2(pk=self.child2.pk), InheritanceManagerTestChild1(pk=self.grandchild1.pk), InheritanceManagerTestChild1(pk=self.grandchild1_2.pk), ] self.assertEqual(list(objs), expecting2) def test_duplications(self) -> None: """ Check that even if the same thing is provided as a string and a model that the right results are retrieved. """ # mixing strings and models which evaluate to the same thing is fine. objs = InheritanceManagerTestParent.objects.select_subclasses( "inheritancemanagertestchild2", InheritanceManagerTestChild2).order_by('pk') self.assertEqual(list(objs), [ InheritanceManagerTestParent(pk=self.parent1.pk), InheritanceManagerTestParent(pk=self.child1.pk), InheritanceManagerTestChild2(pk=self.child2.pk), InheritanceManagerTestParent(pk=self.grandchild1.pk), InheritanceManagerTestParent(pk=self.grandchild1_2.pk), ]) def test_child_doesnt_accidentally_get_parent(self) -> None: """ Given a Child model which also has an InheritanceManager, none of the returned objects should be Parent objects. """ objs = InheritanceManagerTestChild1.objects.select_subclasses( InheritanceManagerTestGrandChild1).order_by('pk') self.assertEqual([ InheritanceManagerTestChild1(pk=self.child1.pk), InheritanceManagerTestGrandChild1(pk=self.grandchild1.pk), InheritanceManagerTestChild1(pk=self.grandchild1_2.pk), ], list(objs)) def test_manually_specifying_parent_fk_only_specific_child(self) -> None: """ given a Model which inherits from another Model, but also declares the OneToOne link manually using `related_name` and `parent_link`, ensure that the relation names and subclasses are obtained correctly. """ child3 = InheritanceManagerTestChild3.objects.create() results = InheritanceManagerTestParent.objects.all().select_subclasses( InheritanceManagerTestChild3).order_by('pk') expected_objs = [ InheritanceManagerTestParent(pk=self.parent1.pk), InheritanceManagerTestParent(pk=self.child1.pk), InheritanceManagerTestParent(pk=self.child2.pk), InheritanceManagerTestParent(pk=self.grandchild1.pk), InheritanceManagerTestParent(pk=self.grandchild1_2.pk), child3 ] self.assertEqual(list(results), expected_objs) expected_related_names = ['manual_onetoone'] self.assertEqual(set(results.subclasses), set(expected_related_names)) def test_extras_descend(self) -> None: """ Ensure that extra(select=) values are copied onto sub-classes. """ results = InheritanceManagerTestParent.objects.select_subclasses().extra( select={'foo': 'id + 1'} ) self.assertTrue(all(result.foo == (result.id + 1) for result in results)) def test_limit_to_specific_subclass(self) -> None: child3 = InheritanceManagerTestChild3.objects.create() results = InheritanceManagerTestParent.objects.instance_of(InheritanceManagerTestChild3) self.assertEqual([child3], list(results)) def test_limit_to_specific_subclass_with_custom_db_column(self) -> None: item = InheritanceManagerTestChild3_1.objects.create() results = InheritanceManagerTestParent.objects.instance_of(InheritanceManagerTestChild3_1) self.assertEqual([item], list(results)) def test_limit_to_specific_grandchild_class(self) -> None: grandchild1 = InheritanceManagerTestGrandChild1.objects.get() results = InheritanceManagerTestParent.objects.instance_of(InheritanceManagerTestGrandChild1) self.assertEqual([grandchild1], list(results)) def test_limit_to_child_fetches_grandchildren_as_child_class(self) -> None: # Not sure if this is the desired behaviour...? children = InheritanceManagerTestChild1.objects.all() results = InheritanceManagerTestParent.objects.instance_of(InheritanceManagerTestChild1) self.assertEqual(set(children), set(results)) def test_can_fetch_limited_class_grandchildren(self) -> None: # Not sure if this is the desired behaviour...? children = InheritanceManagerTestChild1.objects.select_subclasses() results = InheritanceManagerTestParent.objects.instance_of(InheritanceManagerTestChild1).select_subclasses() self.assertEqual(set(children), set(results)) def test_selecting_multiple_instance_classes(self) -> None: child3 = InheritanceManagerTestChild3.objects.create() children1 = InheritanceManagerTestChild1.objects.all() results = InheritanceManagerTestParent.objects.instance_of(InheritanceManagerTestChild3, InheritanceManagerTestChild1) self.assertEqual(set([child3] + list(children1)), set(results)) def test_selecting_multiple_instance_classes_including_grandchildren(self) -> None: child3 = InheritanceManagerTestChild3.objects.create() grandchild1 = InheritanceManagerTestGrandChild1.objects.get() results = InheritanceManagerTestParent.objects.instance_of(InheritanceManagerTestChild3, InheritanceManagerTestGrandChild1).select_subclasses() self.assertEqual({child3, grandchild1}, set(results)) def test_select_subclasses_interaction_with_instance_of(self) -> None: child3 = InheritanceManagerTestChild3.objects.create() results = InheritanceManagerTestParent.objects.select_subclasses(InheritanceManagerTestChild1).instance_of(InheritanceManagerTestChild3) self.assertEqual({child3}, set(results))
InheritanceManagerUsingModelsTests
python
pypa__setuptools
setuptools/config/pyprojecttoml.py
{ "start": 6368, "end": 15982 }
class ____: def __init__( self, config: dict, root_dir: StrPath | None = None, ignore_option_errors: bool = False, dist: Distribution | None = None, ) -> None: self.config = config self.root_dir = root_dir or os.getcwd() self.project_cfg = config.get("project", {}) self.dynamic = self.project_cfg.get("dynamic", []) self.setuptools_cfg = config.get("tool", {}).get("setuptools", {}) self.dynamic_cfg = self.setuptools_cfg.get("dynamic", {}) self.ignore_option_errors = ignore_option_errors self._dist = dist self._referenced_files = set[str]() def _ensure_dist(self) -> Distribution: from setuptools.dist import Distribution attrs = {"src_root": self.root_dir, "name": self.project_cfg.get("name", None)} return self._dist or Distribution(attrs) def _process_field(self, container: dict, field: str, fn: Callable): if field in container: with _ignore_errors(self.ignore_option_errors): container[field] = fn(container[field]) def _canonic_package_data(self, field="package-data"): package_data = self.setuptools_cfg.get(field, {}) return _expand.canonic_package_data(package_data) def expand(self): self._expand_packages() self._canonic_package_data() self._canonic_package_data("exclude-package-data") # A distribution object is required for discovering the correct package_dir dist = self._ensure_dist() ctx = _EnsurePackagesDiscovered(dist, self.project_cfg, self.setuptools_cfg) with ctx as ensure_discovered: package_dir = ensure_discovered.package_dir self._expand_data_files() self._expand_cmdclass(package_dir) self._expand_all_dynamic(dist, package_dir) dist._referenced_files.update(self._referenced_files) return self.config def _expand_packages(self): packages = self.setuptools_cfg.get("packages") if packages is None or isinstance(packages, (list, tuple)): return find = packages.get("find") if isinstance(find, dict): find["root_dir"] = self.root_dir find["fill_package_dir"] = self.setuptools_cfg.setdefault("package-dir", {}) with _ignore_errors(self.ignore_option_errors): self.setuptools_cfg["packages"] = _expand.find_packages(**find) def _expand_data_files(self): data_files = partial(_expand.canonic_data_files, root_dir=self.root_dir) self._process_field(self.setuptools_cfg, "data-files", data_files) def _expand_cmdclass(self, package_dir: Mapping[str, str]): root_dir = self.root_dir cmdclass = partial(_expand.cmdclass, package_dir=package_dir, root_dir=root_dir) self._process_field(self.setuptools_cfg, "cmdclass", cmdclass) def _expand_all_dynamic(self, dist: Distribution, package_dir: Mapping[str, str]): special = ( # need special handling "version", "readme", "entry-points", "scripts", "gui-scripts", "classifiers", "dependencies", "optional-dependencies", ) # `_obtain` functions are assumed to raise appropriate exceptions/warnings. obtained_dynamic = { field: self._obtain(dist, field, package_dir) for field in self.dynamic if field not in special } obtained_dynamic.update( self._obtain_entry_points(dist, package_dir) or {}, version=self._obtain_version(dist, package_dir), readme=self._obtain_readme(dist), classifiers=self._obtain_classifiers(dist), dependencies=self._obtain_dependencies(dist), optional_dependencies=self._obtain_optional_dependencies(dist), ) # `None` indicates there is nothing in `tool.setuptools.dynamic` but the value # might have already been set by setup.py/extensions, so avoid overwriting. updates = {k: v for k, v in obtained_dynamic.items() if v is not None} self.project_cfg.update(updates) def _ensure_previously_set(self, dist: Distribution, field: str): previous = _PREVIOUSLY_DEFINED[field](dist) if previous is None and not self.ignore_option_errors: msg = ( f"No configuration found for dynamic {field!r}.\n" "Some dynamic fields need to be specified via `tool.setuptools.dynamic`" "\nothers must be specified via the equivalent attribute in `setup.py`." ) raise InvalidConfigError(msg) def _expand_directive( self, specifier: str, directive, package_dir: Mapping[str, str] ): from more_itertools import always_iterable with _ignore_errors(self.ignore_option_errors): root_dir = self.root_dir if "file" in directive: self._referenced_files.update(always_iterable(directive["file"])) return _expand.read_files(directive["file"], root_dir) if "attr" in directive: return _expand.read_attr(directive["attr"], package_dir, root_dir) raise ValueError(f"invalid `{specifier}`: {directive!r}") return None def _obtain(self, dist: Distribution, field: str, package_dir: Mapping[str, str]): if field in self.dynamic_cfg: return self._expand_directive( f"tool.setuptools.dynamic.{field}", self.dynamic_cfg[field], package_dir, ) self._ensure_previously_set(dist, field) return None def _obtain_version(self, dist: Distribution, package_dir: Mapping[str, str]): # Since plugins can set version, let's silently skip if it cannot be obtained if "version" in self.dynamic and "version" in self.dynamic_cfg: return _expand.version( # We already do an early check for the presence of "version" self._obtain(dist, "version", package_dir) # pyright: ignore[reportArgumentType] ) return None def _obtain_readme(self, dist: Distribution) -> dict[str, str] | None: if "readme" not in self.dynamic: return None dynamic_cfg = self.dynamic_cfg if "readme" in dynamic_cfg: return { # We already do an early check for the presence of "readme" "text": self._obtain(dist, "readme", {}), "content-type": dynamic_cfg["readme"].get("content-type", "text/x-rst"), } # pyright: ignore[reportReturnType] self._ensure_previously_set(dist, "readme") return None def _obtain_entry_points( self, dist: Distribution, package_dir: Mapping[str, str] ) -> dict[str, dict[str, Any]] | None: fields = ("entry-points", "scripts", "gui-scripts") if not any(field in self.dynamic for field in fields): return None text = self._obtain(dist, "entry-points", package_dir) if text is None: return None groups = _expand.entry_points(text) # Any is str | dict[str, str], but causes variance issues expanded: dict[str, dict[str, Any]] = {"entry-points": groups} def _set_scripts(field: str, group: str): if group in groups: value = groups.pop(group) if field not in self.dynamic: raise InvalidConfigError(_MissingDynamic.details(field, value)) expanded[field] = value _set_scripts("scripts", "console_scripts") _set_scripts("gui-scripts", "gui_scripts") return expanded def _obtain_classifiers(self, dist: Distribution): if "classifiers" in self.dynamic: value = self._obtain(dist, "classifiers", {}) if value: return value.splitlines() return None def _obtain_dependencies(self, dist: Distribution): if "dependencies" in self.dynamic: value = self._obtain(dist, "dependencies", {}) if value: return _parse_requirements_list(value) return None def _obtain_optional_dependencies(self, dist: Distribution): if "optional-dependencies" not in self.dynamic: return None if "optional-dependencies" in self.dynamic_cfg: optional_dependencies_map = self.dynamic_cfg["optional-dependencies"] assert isinstance(optional_dependencies_map, dict) return { group: _parse_requirements_list( self._expand_directive( f"tool.setuptools.dynamic.optional-dependencies.{group}", directive, {}, ) ) for group, directive in optional_dependencies_map.items() } self._ensure_previously_set(dist, "optional-dependencies") return None def _parse_requirements_list(value): return [ line for line in value.splitlines() if line.strip() and not line.strip().startswith("#") ] @contextmanager def _ignore_errors(ignore_option_errors: bool): if not ignore_option_errors: yield return try: yield except Exception as ex: _logger.debug(f"ignored error: {ex.__class__.__name__} - {ex}")
_ConfigExpander
python
numba__numba
numba/core/typeinfer.py
{ "start": 6393, "end": 7141 }
class ____(object): def __init__(self, dst, src, loc): self.dst = dst self.src = src self.loc = loc def __call__(self, typeinfer): with new_error_context("typing of argument at {loc}", loc=self.loc): typevars = typeinfer.typevars src = typevars[self.src] if not src.defined: return ty = src.getone() if isinstance(ty, types.Omitted): ty = typeinfer.context.resolve_value_type_prefer_literal( ty.value, ) if not ty.is_precise(): raise TypingError('non-precise type {}'.format(ty)) typeinfer.add_type(self.dst, ty, loc=self.loc)
ArgConstraint
python
astropy__astropy
astropy/nddata/compat.py
{ "start": 570, "end": 10254 }
class ____(NDArithmeticMixin, NDSlicingMixin, NDIOMixin, NDData): """ An ``NDData`` object with arithmetic. This class is functionally equivalent to ``NDData`` in astropy versions prior to 1.0. The key distinction from raw numpy arrays is the presence of additional metadata such as uncertainties, a mask, units, flags, and/or a coordinate system. See also: https://docs.astropy.org/en/stable/nddata/ Parameters ---------- data : ndarray or `NDData` The actual data contained in this `NDData` object. Not that this will always be copies by *reference* , so you should make copy the ``data`` before passing it in if that's the desired behavior. uncertainty : `~astropy.nddata.NDUncertainty`, optional Uncertainties on the data. mask : array-like, optional Mask for the data, given as a boolean Numpy array or any object that can be converted to a boolean Numpy array with a shape matching that of the data. The values must be ``False`` where the data is *valid* and ``True`` when it is not (like Numpy masked arrays). If ``data`` is a numpy masked array, providing ``mask`` here will causes the mask from the masked array to be ignored. flags : array-like or `~astropy.nddata.FlagCollection`, optional Flags giving information about each pixel. These can be specified either as a Numpy array of any type (or an object which can be converted to a Numpy array) with a shape matching that of the data, or as a `~astropy.nddata.FlagCollection` instance which has a shape matching that of the data. wcs : None, optional WCS-object containing the world coordinate system for the data. .. warning:: This is not yet defined because the discussion of how best to represent this class's WCS system generically is still under consideration. For now just leave it as None meta : `dict`-like object, optional Metadata for this object. "Metadata" here means all information that is included with this object but not part of any other attribute of this particular object. e.g., creation date, unique identifier, simulation parameters, exposure time, telescope name, etc. unit : `~astropy.units.UnitBase` instance or str, optional The units of the data. Raises ------ ValueError : If the `uncertainty` or `mask` inputs cannot be broadcast (e.g., match shape) onto ``data``. """ def __init__(self, data, *args, flags=None, **kwargs): # Initialize with the parent... super().__init__(data, *args, **kwargs) # ...then reset uncertainty to force it to go through the # setter logic below. In base NDData all that is done is to # set self._uncertainty to whatever uncertainty is passed in. self.uncertainty = self._uncertainty # Same thing for mask. self.mask = self._mask # Initial flags because it is no longer handled in NDData # or NDDataBase. if isinstance(data, NDDataArray): if flags is None: flags = data.flags else: log.info( "Overwriting NDDataArrays's current flags with specified flags" ) self.flags = flags # Implement uncertainty as NDUncertainty to support propagation of # uncertainties in arithmetic operations @property def uncertainty(self): return self._uncertainty @uncertainty.setter def uncertainty(self, value): if value is not None: if isinstance(value, NDUncertainty): class_name = self.__class__.__name__ if not self.unit and value._unit: # Raise an error if uncertainty has unit and data does not raise ValueError( "Cannot assign an uncertainty with unit " f"to {class_name} without " "a unit" ) self._uncertainty = value self._uncertainty.parent_nddata = self else: raise TypeError( "Uncertainty must be an instance of a NDUncertainty object" ) else: self._uncertainty = value # Override unit so that we can add a setter. @property def unit(self): return self._unit @unit.setter def unit(self, value): from . import conf try: if self._unit is not None and conf.warn_setting_unit_directly: log.info( "Setting the unit directly changes the unit without " "updating the data or uncertainty. Use the " ".convert_unit_to() method to change the unit and " "scale values appropriately." ) except AttributeError: # raised if self._unit has not been set yet, in which case the # warning is irrelevant pass if value is None: self._unit = None else: self._unit = Unit(value) # Implement mask in a way that converts nicely to a numpy masked array @property def mask(self): if self._mask is np.ma.nomask: return None else: return self._mask @mask.setter def mask(self, value): # Check that value is not either type of null mask. if (value is not None) and (value is not np.ma.nomask): mask = np.asarray(value, dtype=np.bool_) if mask.shape != self.data.shape: raise ValueError( f"dimensions of mask {mask.shape} and data {self.data.shape} do not match" ) else: self._mask = mask else: # internal representation should be one numpy understands self._mask = np.ma.nomask @property def shape(self): """ shape tuple of this object's data. """ return self.data.shape @property def size(self): """ integer size of this object's data. """ return self.data.size @property def dtype(self): """ `numpy.dtype` of this object's data. """ return self.data.dtype @property def ndim(self): """ integer dimensions of this object's data. """ return self.data.ndim @property def flags(self): return self._flags @flags.setter def flags(self, value): if value is not None: if isinstance(value, FlagCollection): if value.shape != self.shape: raise ValueError("dimensions of FlagCollection does not match data") else: self._flags = value else: flags = np.asarray(value) if flags.shape != self.shape: raise ValueError("dimensions of flags do not match data") else: self._flags = flags else: self._flags = value def __array__(self, dtype=None, copy=COPY_IF_NEEDED): """ This allows code that requests a Numpy array to use an NDData object as a Numpy array. """ if self.mask is not None: return np.ma.masked_array( self.data, self.mask, dtype=dtype, copy=copy, ) else: return np.array(self.data, dtype=dtype, copy=copy) def __array_wrap__(self, array, context=None, return_scalar=False): """ This ensures that a masked array is returned if self is masked. """ if self.mask is not None: return np.ma.masked_array(array, self.mask) else: return array def convert_unit_to(self, unit, equivalencies=[]): """ Returns a new `NDData` object whose values have been converted to a new unit. Parameters ---------- unit : `astropy.units.UnitBase` instance or str The unit to convert to. equivalencies : list of tuple A list of equivalence pairs to try if the units are not directly convertible. See :ref:`astropy:unit_equivalencies`. Returns ------- result : `~astropy.nddata.NDData` The resulting dataset Raises ------ `~astropy.units.UnitsError` If units are inconsistent. """ if self.unit is None: raise ValueError("No unit specified on source data") data = self.unit.to(unit, self.data, equivalencies=equivalencies) if self.uncertainty is not None: uncertainty_values = self.unit.to( unit, self.uncertainty.array, equivalencies=equivalencies ) # should work for any uncertainty class uncertainty = self.uncertainty.__class__(uncertainty_values) else: uncertainty = None if self.mask is not None: new_mask = self.mask.copy() else: new_mask = None # Call __class__ in case we are dealing with an inherited type return self.__class__( data, uncertainty=uncertainty, mask=new_mask, wcs=self.wcs, meta=self.meta, unit=unit, )
NDDataArray
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_set.py
{ "start": 1823, "end": 1935 }
class ____: def __hash__(self): return 1 def __eq__(self, other): raise RuntimeError
BadCmp
python
sqlalchemy__sqlalchemy
test/sql/test_type_expressions.py
{ "start": 12143, "end": 13181 }
class ____(_ExprFixture, fixtures.TestBase, AssertsCompiledSQL): __dialect__ = "default" def test_select_from_select(self): table = self._fixture() self.assert_compile( table.select().subquery().select(), "SELECT anon_1.x, lower(anon_1.y) AS y FROM " "(SELECT test_table.x " "AS x, test_table.y AS y FROM test_table) AS anon_1", ) def test_select_from_aliased_join(self): table = self._fixture() s1 = table.select().alias() s2 = table.select().alias() j = s1.join(s2, s1.c.x == s2.c.x) s3 = j.select() self.assert_compile( s3, "SELECT anon_1.x, lower(anon_1.y) AS y, anon_2.x AS x_1, " "lower(anon_2.y) AS y_1 " "FROM (SELECT test_table.x AS x, test_table.y AS y " "FROM test_table) AS anon_1 JOIN (SELECT " "test_table.x AS x, test_table.y AS y " "FROM test_table) AS anon_2 ON anon_1.x = anon_2.x", )
DerivedTest
python
getsentry__sentry
src/sentry/grouping/enhancer/matchers.py
{ "start": 10973, "end": 11403 }
class ____(FrameMatch): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._flags = set(self._encoded_pattern.split(b",")) def _positive_frame_match( self, match_frame: MatchFrame, exception_data: dict[str, Any], cache: ReturnValueCache ) -> bool: if b"all" in self._flags: return True return match_frame["family"] in self._flags
FamilyMatch
python
urllib3__urllib3
dummyserver/socketserver.py
{ "start": 2583, "end": 5546 }
class ____(threading.Thread): """ :param socket_handler: Callable which receives a socket argument for one request. :param ready_event: Event which gets set when the socket handler is ready to receive requests. """ USE_IPV6 = HAS_IPV6_AND_DNS def __init__( self, socket_handler: typing.Callable[[socket.socket], None], host: str = "localhost", ready_event: threading.Event | None = None, quit_event: threading.Event | None = None, ) -> None: super().__init__() self.daemon = True self.socket_handler = socket_handler self.host = host self.ready_event = ready_event self.quit_event = quit_event def _start_server(self) -> None: if self.USE_IPV6: sock = socket.socket(socket.AF_INET6) else: warnings.warn("No IPv6 support. Falling back to IPv4.", NoIPv6Warning) sock = socket.socket(socket.AF_INET) if sys.platform != "win32": sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) with sock: sock.bind((self.host, 0)) self.port = sock.getsockname()[1] # Once listen() returns, the server socket is ready sock.listen(1) if self.ready_event: self.ready_event.set() self.socket_handler(sock) def run(self) -> None: self._start_server() def ssl_options_to_context( # type: ignore[no-untyped-def] keyfile=None, certfile=None, server_side=None, cert_reqs=None, ssl_version: str | int | None = None, ca_certs=None, do_handshake_on_connect=None, suppress_ragged_eofs=None, ciphers=None, alpn_protocols=None, ) -> ssl.SSLContext: """Return an equivalent SSLContext based on ssl.wrap_socket args.""" ssl_version = resolve_ssl_version(ssl_version) cert_none = resolve_cert_reqs("CERT_NONE") if cert_reqs is None: cert_reqs = cert_none else: cert_reqs = resolve_cert_reqs(cert_reqs) ctx = ssl.SSLContext(ssl_version) ctx.load_cert_chain(certfile, keyfile) ctx.verify_mode = cert_reqs if ctx.verify_mode != cert_none: ctx.load_verify_locations(cafile=ca_certs) if alpn_protocols: ctx.set_alpn_protocols(alpn_protocols) return ctx def get_unreachable_address() -> tuple[str, int]: # reserved as per rfc2606 return ("something.invalid", 54321) def encrypt_key_pem(private_key_pem: trustme.Blob, password: bytes) -> trustme.Blob: private_key = serialization.load_pem_private_key( private_key_pem.bytes(), password=None, backend=default_backend() ) encrypted_key = private_key.private_bytes( serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL, serialization.BestAvailableEncryption(password), ) return trustme.Blob(encrypted_key)
SocketServerThread
python
viewflow__viewflow
viewflow/workflow/nodes/view.py
{ "start": 285, "end": 4072 }
class ____(mixins.NextNodeActivationMixin, Activation): """View node activation.""" @classmethod def create(cls, flow_task, prev_activation, token, data=None, seed=None): """Instantiate and persist new flow task.""" flow_class = flow_task.flow_class task = flow_class.task_class( process=prev_activation.process, flow_task=flow_task, token=token, ) task.data = data if data is not None else {} task.seed = seed activation = cls(task) # Try to assign permission owner_permission = flow_task.calc_owner_permission(activation) if owner_permission: task.owner_permission = owner_permission task.owner_permission_obj = flow_task.calc_owner_permission_obj(activation) # Try to assign owner owner = flow_task.calc_owner(activation) if owner: task.owner = owner task.status = STATUS.ASSIGNED task.save() task.previous.add(prev_activation.task) if flow_task._on_create is not None: flow_task._on_create(activation) return activation @Activation.status.transition( source=STATUS.NEW, target=STATUS.ASSIGNED, permission=lambda activation, user: activation.flow_task.can_assign( user, activation.task ), ) def assign(self, user): """Assign user to the task.""" self.task.owner = user self.task.save() @Activation.status.transition( source=STATUS.ASSIGNED, target=STATUS.NEW, permission=lambda activation, user: activation.flow_task.can_unassign( user, activation.task ), ) def unassign(self): """Remove user from the task assignment.""" self.task.owner = None self.task.save() @Activation.status.transition( source=STATUS.ASSIGNED, permission=lambda activation, user: activation.flow_task.can_unassign( user, activation.task ), ) def reassign(self, user=None): """Reassign to another user.""" if user: self.task.owner = user self.task.save() @Activation.status.super() def activate(self): """Do nothing on sync call""" @Activation.status.transition( label="Execute", source=STATUS.ASSIGNED, target=STATUS.STARTED, permission=lambda activation, user: activation.flow_task.can_execute( user, activation.task ), ) def start(self, request): # TODO request.GET['started'] task_started.send(sender=self.flow_class, process=self.process, task=self.task) self.task.started = now() @Activation.status.transition(source=STATUS.STARTED, target=STATUS.DONE) def complete(self): """Complete task and create next.""" super().complete.original() @Activation.status.transition( source=STATUS.STARTED, permission=lambda activation, user: activation.flow_task.can_execute( user, activation.task ), ) def execute(self): self.complete() self.activate_next() @Activation.status.transition( source=[STATUS.NEW, STATUS.ASSIGNED], target=STATUS.CANCELED, permission=has_manage_permission, ) def cancel(self): self.task.finished = now() self.task.save() @Activation.status.super() def undo(self): # undo if self.flow_task._undo_func is not None: self.flow_task._undo_func(self) super().undo.original() def get_success_url(self, request): return request.resolver_match.flow_viewset.get_success_url(request)
ViewActivation
python
encode__django-rest-framework
tests/test_permissions.py
{ "start": 11204, "end": 11331 }
class ____(models.Model): text = models.CharField(max_length=100) class Meta: app_label = 'tests'
BasicPermModel
python
pytorch__pytorch
torch/testing/_internal/distributed/nn/api/remote_module_test.py
{ "start": 2382, "end": 2675 }
class ____(nn.Module): def __init__(self, first_arg, first_kwarg=-1): super().__init__() self.param1 = _PARAM_VAL def forward( self, tensor: Tensor, number: int, word: str = "default" ) -> tuple[str, int, Tensor]: return word, number, tensor
MyModule
python
doocs__leetcode
solution/3700-3799/3750.Minimum Number of Flips to Reverse Binary String/Solution.py
{ "start": 0, "end": 169 }
class ____: def minimumFlips(self, n: int) -> int: s = bin(n)[2:] m = len(s) return sum(s[i] != s[m - i - 1] for i in range(m // 2)) * 2
Solution
python
django-guardian__django-guardian
guardian/testapp/tests/test_conf.py
{ "start": 220, "end": 883 }
class ____(TestCase): def test_check_configuration(self): with mock.patch("guardian.conf.settings.RENDER_403", True): with mock.patch("guardian.conf.settings.RAISE_403", True): self.assertRaises(ImproperlyConfigured, guardian_settings.check_configuration) def test_get_content_type(self): with mock.patch( "guardian.conf.settings.GET_CONTENT_TYPE", "guardian.testapp.tests.test_conf.get_test_content_type" ): self.assertEqual(get_content_type(None), "x") def get_test_content_type(obj): """Used in TestConfiguration.test_get_content_type().""" return "x"
TestConfiguration
python
pyparsing__pyparsing
examples/booleansearchparser.py
{ "start": 4357, "end": 10746 }
class ____: def __init__(self, only_parse=False): self._methods = { "and": self.evaluateAnd, "or": self.evaluateOr, "not": self.evaluateNot, "parenthesis": self.evaluateParenthesis, "quotes": self.evaluateQuotes, "word": self.evaluateWord, "wordwildcardprefix": self.evaluateWordWildcardPrefix, "wordwildcardsufix": self.evaluateWordWildcardSufix, } self._parser = self.parser() self.text = "" self.words = [] def parser(self): """ This function returns a parser. The grammar should be like most full text search engines (Google, Tsearch, Lucene). Grammar: - a query consists of alphanumeric words, with an optional '*' wildcard at the end or the beginning of a word - a sequence of words between quotes is a literal string - words can be used together by using operators ('and' or 'or') - words with operators can be grouped with parenthesis - a word or group of words can be preceded by a 'not' operator - the 'and' operator precedes an 'or' operator - if an operator is missing, use an 'and' operator """ operatorOr = Forward() alphabet = alphanums # support for non-western alphabets for lo, hi in alphabet_ranges: alphabet += "".join(chr(c) for c in range(lo, hi + 1) if not chr(c).isspace()) operatorWord = Group(Word(alphabet + "*")).set_results_name("word*") operatorQuotesContent = Forward() operatorQuotesContent << ((operatorWord + operatorQuotesContent) | operatorWord) operatorQuotes = ( Group(Suppress('"') + operatorQuotesContent + Suppress('"')).set_results_name( "quotes" ) | operatorWord ) operatorParenthesis = ( Group(Suppress("(") + operatorOr + Suppress(")")).set_results_name( "parenthesis" ) | operatorQuotes ) operatorNot = Forward() operatorNot << ( Group(Suppress(CaselessKeyword("not")) + operatorNot).set_results_name( "not" ) | operatorParenthesis ) operatorAnd = Forward() operatorAnd << ( Group( operatorNot + Suppress(CaselessKeyword("and")) + operatorAnd ).set_results_name("and") | Group( operatorNot + OneOrMore(~one_of("and or") + operatorAnd) ).set_results_name("and") | operatorNot ) operatorOr << ( Group( operatorAnd + Suppress(CaselessKeyword("or")) + operatorOr ).set_results_name("or") | operatorAnd ) return operatorOr.parse_string def evaluateAnd(self, argument): return all(self.evaluate(arg) for arg in argument) def evaluateOr(self, argument): return any(self.evaluate(arg) for arg in argument) def evaluateNot(self, argument): return self.GetNot(self.evaluate(argument[0])) def evaluateParenthesis(self, argument): return self.evaluate(argument[0]) def evaluateQuotes(self, argument): """Evaluate quoted strings First is does an 'and' on the individual search terms, then it asks the function GetQuoted to only return the subset of ID's that contain the literal string. """ # r = set() r = False search_terms = [] for item in argument: search_terms.append(item[0]) r = r and self.evaluate(item) return self.GetQuotes(" ".join(search_terms), r) def evaluateWord(self, argument): wildcard_count = argument[0].count("*") if wildcard_count > 0: if wildcard_count == 1 and argument[0].startswith("*"): return self.GetWordWildcard(argument[0][1:], method="endswith") if wildcard_count == 1 and argument[0].endswith("*"): return self.GetWordWildcard(argument[0][:-1], method="startswith") else: _regex = argument[0].replace("*", ".+") matched = False for w in self.words: matched = bool(re.search(_regex, w)) if matched: break return matched return self.GetWord(argument[0]) def evaluateWordWildcardPrefix(self, argument): return self.GetWordWildcard(argument[0], method="endswith") def evaluateWordWildcardSufix(self, argument): return self.GetWordWildcard(argument[0], method="startswith") def evaluate(self, argument): return self._methods[argument.get_name()](argument) def Parse(self, query): return self.evaluate(self._parser(query)[0]) def GetWord(self, word): return word in self.words def GetWordWildcard(self, word, method="startswith"): matched = False for w in self.words: matched = getattr(w, method)(word) if matched: break return matched """ def GetKeyword(self, name, value): return set() def GetBetween(self, min, max): print (min,max) return set() """ def GetQuotes(self, search_string, tmp_result): return search_string in self.text def GetNot(self, not_set): return not not_set def _split_words(self, text): words = [] """ >>> import string >>> string.punctuation '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' """ # it will keep @, # and # usernames and hashtags can contain dots, so a double check is done r = re.compile(r"[\s{}]+".format(re.escape("!\"$%&'()*+,-/:;<=>?[\\]^`{|}~"))) _words = r.split(text) for _w in _words: if "." in _w and not _w.startswith("#") and not _w.startswith("@"): for __w in _w.split("."): words.append(__w) continue words.append(_w) return words def match(self, text, expr): self.text = text self.words = self._split_words(text) return self.Parse(expr)
BooleanSearchParser
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/methodOverride3.py
{ "start": 1890, "end": 1999 }
class ____(G1[[int, int], str]): def f(self, a: int, b: int, /) -> str: ... def g(self) -> str: ...
G4
python
dagster-io__dagster
python_modules/dagster/dagster_tests/components_tests/resolution_tests/test_resolved.py
{ "start": 11832, "end": 14458 }
class ____: name: str ResolvedFoo: TypeAlias = Annotated[Foo, dg.Resolver(lambda _, v: Foo(name=v), model_field_type=str)] def test_containers(): class Target(dg.Resolvable, dg.Model): li: list[ResolvedFoo] t: tuple[ResolvedFoo, ...] s: Sequence[ResolvedFoo] mli: Optional[list[ResolvedFoo]] uli: Union[list[ResolvedFoo], str] t = Target.resolve_from_yaml(""" li: - a - b t: - c - d s: - e - f mli: - g - h uli: - g - h """) # ensure we don't end up with a container type mismatch from resolution assert isinstance(t.li, list) assert isinstance(t.t, tuple) assert isinstance(t.s, Sequence) # or nested resolution assert isinstance(t.mli, list) assert isinstance(t.uli, list) def test_non_resolvable_resolver(): class Plain(dg.Model): num: Annotated[int, Field(description="cool")] class Target(dg.Model, dg.Resolvable): plain: Plain # ensure annotations on plain models are fine assert Target.model() class Mistake(dg.Model): num: Annotated[int, dg.Resolver(lambda _, v: v + 2)] class Bad(dg.Model, dg.Resolvable): mistake: Mistake # but if Resolver is used on a class that does not subclass Resolvable, we throw with pytest.raises(ResolutionException, match="Subclass Resolvable"): Bad.model() def test_enums(): class Thing(Enum): FOO = "FOO" BAR = "BAR" class Direct(dg.Resolvable, dg.Model): thing: Thing assert Direct.resolve_from_dict({"thing": "FOO"}) class Wrapper(dg.Model): thing: Thing class Indirect(dg.Resolvable, dg.Model): wrapper: Wrapper assert Indirect.resolve_from_dict({"wrapper": {"thing": "BAR"}}) def test_dicts(): class Inner(dg.Resolvable, dg.Model): name: str value: Optional[dg.ResolvedAssetSpec] class HasDict(dg.Resolvable, dg.Model): thing: dict[str, Inner] other_thing: dict[str, Inner] assert HasDict.resolve_from_dict( { "thing": {"a": {"name": "a", "value": {"key": "a"}}}, "other_thing": {"b": {"name": "b", "value": {"key": "b"}}}, } ) == HasDict( thing={"a": Inner(name="a", value=dg.AssetSpec("a"))}, other_thing={"b": Inner(name="b", value=dg.AssetSpec("b"))}, ) class BadHasDict(dg.Resolvable, dg.Model): thing: dict[int, Inner] with pytest.raises(ResolutionException, match="dict key type must be str"): BadHasDict.resolve_from_dict({"thing": {"a": {"name": "a", "value": {"key": "a"}}}})
Foo
python
matplotlib__matplotlib
lib/matplotlib/colors.py
{ "start": 86476, "end": 93588 }
class ____(Norm): """ A class which, when called, maps values within the interval ``[vmin, vmax]`` linearly to the interval ``[0.0, 1.0]``. The mapping of values outside ``[vmin, vmax]`` depends on *clip*. Examples -------- :: x = [-2, -1, 0, 1, 2] norm = mpl.colors.Normalize(vmin=-1, vmax=1, clip=False) norm(x) # [-0.5, 0., 0.5, 1., 1.5] norm = mpl.colors.Normalize(vmin=-1, vmax=1, clip=True) norm(x) # [0., 0., 0.5, 1., 1.] See Also -------- :ref:`colormapnorms` """ def __init__(self, vmin=None, vmax=None, clip=False): """ Parameters ---------- vmin, vmax : float or None Values within the range ``[vmin, vmax]`` from the input data will be linearly mapped to ``[0, 1]``. If either *vmin* or *vmax* is not provided, they default to the minimum and maximum values of the input, respectively. clip : bool, default: False Determines the behavior for mapping values outside the range ``[vmin, vmax]``. If clipping is off, values outside the range ``[vmin, vmax]`` are also transformed, resulting in values outside ``[0, 1]``. This behavior is usually desirable, as colormaps can mark these *under* and *over* values with specific colors. If clipping is on, values below *vmin* are mapped to 0 and values above *vmax* are mapped to 1. Such values become indistinguishable from regular boundary values, which may cause misinterpretation of the data. Notes ----- If ``vmin == vmax``, input data will be mapped to 0. """ super().__init__() self._vmin = _sanitize_extrema(vmin) self._vmax = _sanitize_extrema(vmax) self._clip = clip self._scale = None @property def vmin(self): # docstring inherited return self._vmin @vmin.setter def vmin(self, value): value = _sanitize_extrema(value) if value != self._vmin: self._vmin = value self._changed() @property def vmax(self): # docstring inherited return self._vmax @vmax.setter def vmax(self, value): value = _sanitize_extrema(value) if value != self._vmax: self._vmax = value self._changed() @property def clip(self): # docstring inherited return self._clip @clip.setter def clip(self, value): if value != self._clip: self._clip = value self._changed() @staticmethod def process_value(value): """ Homogenize the input *value* for easy and efficient normalization. *value* can be a scalar or sequence. Parameters ---------- value Data to normalize. Returns ------- result : masked array Masked array with the same shape as *value*. is_scalar : bool Whether *value* is a scalar. Notes ----- Float dtypes are preserved; integer types with two bytes or smaller are converted to np.float32, and larger types are converted to np.float64. Preserving float32 when possible, and using in-place operations, greatly improves speed for large arrays. """ is_scalar = not np.iterable(value) if is_scalar: value = [value] dtype = np.min_scalar_type(value) if np.issubdtype(dtype, np.integer) or dtype.type is np.bool_: # bool_/int8/int16 -> float32; int32/int64 -> float64 dtype = np.promote_types(dtype, np.float32) # ensure data passed in as an ndarray subclass are interpreted as # an ndarray. See issue #6622. mask = np.ma.getmask(value) data = np.asarray(value) result = np.ma.array(data, mask=mask, dtype=dtype, copy=True) return result, is_scalar def __call__(self, value, clip=None): # docstring inherited if clip is None: clip = self.clip result, is_scalar = self.process_value(value) if self.vmin is None or self.vmax is None: self.autoscale_None(result) # Convert at least to float, without losing precision. (vmin,), _ = self.process_value(self.vmin) (vmax,), _ = self.process_value(self.vmax) if vmin == vmax: result.fill(0) # Or should it be all masked? Or 0.5? elif vmin > vmax: raise ValueError("minvalue must be less than or equal to maxvalue") else: if clip: mask = np.ma.getmask(result) result = np.ma.array(np.clip(result.filled(vmax), vmin, vmax), mask=mask) # ma division is very slow; we can take a shortcut resdat = result.data resdat -= vmin resdat /= (vmax - vmin) result = np.ma.array(resdat, mask=result.mask, copy=False) if is_scalar: result = result[0] return result def inverse(self, value): """ Maps the normalized value (i.e., index in the colormap) back to image data value. Parameters ---------- value Normalized value. """ if not self.scaled(): raise ValueError("Not invertible until both vmin and vmax are set") (vmin,), _ = self.process_value(self.vmin) (vmax,), _ = self.process_value(self.vmax) if np.iterable(value): val = np.ma.asarray(value) return vmin + val * (vmax - vmin) else: return vmin + value * (vmax - vmin) def autoscale(self, A): # docstring inherited with self.callbacks.blocked(): # Pause callbacks while we are updating so we only get # a single update signal at the end self.vmin = self.vmax = None self.autoscale_None(A) self._changed() def autoscale_None(self, A): # docstring inherited A = np.asanyarray(A) if isinstance(A, np.ma.MaskedArray): # we need to make the distinction between an array, False, np.bool_(False) if A.mask is False or not A.mask.shape: A = A.data if self.vmin is None and A.size: self.vmin = A.min() if self.vmax is None and A.size: self.vmax = A.max() def scaled(self): # docstring inherited return self.vmin is not None and self.vmax is not None @property def n_components(self): """ The number of distinct components supported (1). This is the number of elements of the parameter to ``__call__`` and of *vmin*, *vmax*. This class support only a single component, as opposed to `MultiNorm` which supports multiple components. """ return 1
Normalize
python
tensorflow__tensorflow
tensorflow/python/ops/weak_tensor_math_ops_test.py
{ "start": 12766, "end": 14205 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): @test_util.run_all_in_graph_and_eager_modes def testEqualityNone(self): x = _get_weak_tensor([1.0, 2.0, 0.0, 4.0], dtype=dtypes.float32) self.assertNotEqual(x, None) self.assertNotEqual(None, x) self.assertFalse(math_ops.tensor_equals(x, None)) self.assertTrue(math_ops.tensor_not_equals(x, None)) @parameterized.named_parameters( (f"-is_equals={is_equals}-float_literal_type={type(float_literal)}" # pylint: disable=g-complex-comprehension f"-float_literal={float_literal}", is_equals, float_literal) for float_literal in [4.6, np.float32(4.6), 4.4, np.float32(4.4)] for is_equals in [True, False]) def testEqualityNoDowncast(self, is_equals, float_literal): if (tf2.enabled() and isinstance(float_literal, np.float32) or not tf2.enabled() and isinstance(float_literal, float)): # TODO(b/199262800): Remove this skip self.skipTest("There is a bug in type promotion.") if is_equals: op = math_ops.tensor_equals else: op = math_ops.tensor_not_equals x = _get_weak_tensor(4) try: result = op(x, float_literal) if isinstance(result, tensor.Tensor): result = self.evaluate(result) except TypeError: # Throwing a TypeError is OK return self.assertEqual(result, not is_equals) @test_util.run_all_in_graph_and_eager_modes
EqualityTest
python
PrefectHQ__prefect
src/integrations/prefect-azure/prefect_azure/credentials.py
{ "start": 14275, "end": 17784 }
class ____(Block): """ Block used to manage authentication with AzureML. Azure authentication is handled via the `azure` module. Args: tenant_id: The active directory tenant that the service identity belongs to. service_principal_id: The service principal ID. service_principal_password: The service principal password/key. subscription_id: The Azure subscription ID containing the workspace. resource_group: The resource group containing the workspace. workspace_name: The existing workspace name. Example: Load stored AzureML credentials: ```python from prefect_azure import AzureMlCredentials azure_ml_credentials_block = AzureMlCredentials.load("BLOCK_NAME") ``` """ _block_type_name = "AzureML Credentials" _logo_url = "https://cdn.sanity.io/images/3ugk85nk/production/54e3fa7e00197a4fbd1d82ed62494cb58d08c96a-250x250.png" # noqa _documentation_url = "https://docs.prefect.io/integrations/prefect-azure" # noqa tenant_id: str = Field( default=..., description="The active directory tenant that the service identity belongs to.", ) service_principal_id: str = Field( default=..., description="The service principal ID." ) service_principal_password: SecretStr = Field( default=..., description="The service principal password/key." ) subscription_id: str = Field( default=..., description="The Azure subscription ID containing the workspace, in format: '00000000-0000-0000-0000-000000000000'.", # noqa ) resource_group: str = Field( default=..., description="The resource group containing the workspace." ) workspace_name: str = Field(default=..., description="The existing workspace name.") @_raise_help_msg("ml_datastore") def get_workspace(self) -> "Workspace": """ Returns an authenticated base Workspace that can be used in Azure's Datasets and Datastores. Example: Create an authorized workspace ```python import os from prefect import flow from prefect_azure import AzureMlCredentials @flow def example_get_workspace_flow(): azure_credentials = AzureMlCredentials( tenant_id="tenant_id", service_principal_id="service_principal_id", service_principal_password="service_principal_password", subscription_id="subscription_id", resource_group="resource_group", workspace_name="workspace_name" ) workspace_client = azure_credentials.get_workspace() return workspace_client example_get_workspace_flow() ``` """ service_principal_password = self.service_principal_password.get_secret_value() service_principal_authentication = ServicePrincipalAuthentication( tenant_id=self.tenant_id, service_principal_id=self.service_principal_id, service_principal_password=service_principal_password, ) workspace = Workspace( subscription_id=self.subscription_id, resource_group=self.resource_group, workspace_name=self.workspace_name, auth=service_principal_authentication, ) return workspace
AzureMlCredentials
python
altair-viz__altair
sphinxext/altairgallery.py
{ "start": 7223, "end": 11596 }
class ____(Directive): has_content = False option_spec = { "size": int, "names": str, "indices": _indices, "shuffle": flag, "seed": int, "titles": bool, "width": str, } def run(self) -> list[Node]: size = self.options.get("size", 15) names = [name.strip() for name in self.options.get("names", "").split(",")] indices = self.options.get("indices", []) shuffle = "shuffle" in self.options seed = self.options.get("seed", 42) titles = self.options.get("titles", False) width = self.options.get("width", None) env = self.state.document.settings.env app = env.app gallery_dir = app.builder.config.altair_gallery_dir examples = populate_examples() if names: if len(names) < size: msg = ( "altair-minigallery: if names are specified, " "the list must be at least as long as size." ) raise ValueError(msg) mapping = {example["name"]: example for example in examples} examples = [mapping[name] for name in names] else: if indices: examples = [examples[i] for i in indices] if shuffle: random.seed(seed) random.shuffle(examples) if size: examples = examples[:size] include = MINIGALLERY_TEMPLATE.render( image_dir="/_static", gallery_dir=gallery_dir, examples=examples, titles=titles, width=width, ) # parse and return documentation result = StringList() for line in include.split("\n"): result.append(line, "<altair-minigallery>") node = nodes.paragraph() node.document = self.state.document nested_parse_with_titles(self.state, result, node) return node.children def main(app) -> None: src_dir = Path(app.builder.srcdir) target_dir: Path = src_dir / Path(app.builder.config.altair_gallery_dir) image_dir: Path = src_dir / "_images" gallery_ref = app.builder.config.altair_gallery_ref gallery_title = app.builder.config.altair_gallery_title examples = populate_examples(gallery_ref=gallery_ref, code_below=True, strict=False) target_dir.mkdir(parents=True, exist_ok=True) image_dir.mkdir(exist_ok=True) examples = sorted(examples, key=itemgetter("title")) examples_toc = collections.OrderedDict( { "Simple Charts": [], "Bar Charts": [], "Line Charts": [], "Area Charts": [], "Circular Plots": [], "Scatter Plots": [], "Uncertainties And Trends": [], "Distributions": [], "Tables": [], "Maps": [], "Interactive Charts": [], "Advanced Calculations": [], "Case Studies": [], } ) for d in examples: examples_toc[d["category"]].append(d) encoding = "utf-8" # Write the gallery index file fp = target_dir / "index.rst" fp.write_text( GALLERY_TEMPLATE.render( title=gallery_title, examples=examples_toc.items(), image_dir="/_static", gallery_ref=gallery_ref, ), encoding=encoding, ) # save the images to file save_example_pngs(examples, image_dir) # Write the individual example files for prev_ex, example, next_ex in prev_this_next(examples): if prev_ex: example["prev_ref"] = "gallery_{name}".format(**prev_ex) if next_ex: example["next_ref"] = "gallery_{name}".format(**next_ex) fp = target_dir / "".join((example["name"], ".rst")) fp.write_text(EXAMPLE_TEMPLATE.render(example), encoding=encoding) def setup(app) -> None: app.connect("builder-inited", main) app.add_css_file("altair-gallery.css") app.add_config_value("altair_gallery_dir", "gallery", "env") app.add_config_value("altair_gallery_ref", "example-gallery", "env") app.add_config_value("altair_gallery_title", "Example Gallery", "env") app.add_directive_to_domain("py", "altair-minigallery", AltairMiniGalleryDirective)
AltairMiniGalleryDirective
python
pytorch__pytorch
torchgen/api/types/types_base.py
{ "start": 3520, "end": 3884 }
class ____(CType): elem: CType size: int def cpp_type(self, *, strip_ref: bool = False) -> str: # Do not pass `strip_ref` recursively. return f"::std::array<{self.elem.cpp_type()},{self.size}>" def remove_const_ref(self) -> CType: return ArrayCType(self.elem.remove_const_ref(), self.size) @dataclass(frozen=True)
ArrayCType
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/functions.py
{ "start": 60800, "end": 62094 }
class ____(ReturnTypeFromArgs[Sequence[_T]]): """Support for the ARRAY_AGG function. The ``func.array_agg(expr)`` construct returns an expression of type :class:`_types.ARRAY`. e.g.:: stmt = select(func.array_agg(table.c.values)[2:5]) .. seealso:: :func:`_postgresql.array_agg` - PostgreSQL-specific version that returns :class:`_postgresql.ARRAY`, which has PG-specific operators added. """ inherit_cache = True def __init__( self, *args: _ColumnExpressionArgument[Any], **kwargs: Any ) -> None: fn_args: Sequence[ColumnElement[Any]] = [ coercions.expect( roles.ExpressionElementRole, c, apply_propagate_attrs=self ) for c in args ] default_array_type = kwargs.pop("_default_array_type", sqltypes.ARRAY) if "type_" not in kwargs: type_from_args = _type_from_args(fn_args) if isinstance(type_from_args, sqltypes.ARRAY): kwargs["type_"] = type_from_args else: kwargs["type_"] = default_array_type( type_from_args, dimensions=1 ) kwargs["_parsed_args"] = fn_args super().__init__(*fn_args, **kwargs)
array_agg
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/pad_op_test.py
{ "start": 1137, "end": 18405 }
class ____(test.TestCase): def setUp(self): super().setUp() # Create mapping between TensorFlow quantized types and numpy types. self._quint8 = np.dtype([("quint8", np.uint8)]) self._qint8 = np.dtype([("qint8", np.int8)]) self._qint32 = np.dtype([("qint32", np.int32)]) def _npPad(self, inp, paddings, mode, constant_values=0): mode = mode.lower() if mode == "constant": return np.pad(inp, paddings, mode=mode, constant_values=constant_values) else: return np.pad(inp, paddings, mode=mode) def testNpPad(self): self.assertAllEqual( np.array([[0, 0, 0, 0, 0, 0], [0, 3, 3, 0, 0, 0], [0, 4, 4, 0, 0, 0], [0, 5, 5, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]), self._npPad( np.array([[3, 3], [4, 4], [5, 5]]), [[1, 2], [1, 3]], mode="constant")) self.assertAllEqual( np.array([[1, 1, 1, 1, 1, 1], [1, 3, 3, 1, 1, 1], [1, 4, 4, 1, 1, 1], [1, 5, 5, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]]), self._npPad( np.array([[3, 3], [4, 4], [5, 5]]), [[1, 2], [1, 3]], mode="constant", constant_values=1)) self.assertAllEqual( np.array([[4, 3, 4, 9, 4, 3], [1, 0, 1, 2, 1, 0], [4, 3, 4, 9, 4, 3], [1, 0, 1, 2, 1, 0]]), self._npPad( np.array([[0, 1, 2], [3, 4, 9]]), [[1, 1], [1, 2]], mode="reflect")) self.assertAllEqual( np.array([[0, 0, 1, 2, 2, 1], [0, 0, 1, 2, 2, 1], [3, 3, 4, 9, 9, 4], [3, 3, 4, 9, 9, 4]]), self._npPad( np.array([[0, 1, 2], [3, 4, 9]]), [[1, 1], [1, 2]], mode="symmetric")) def _testPad(self, np_inputs, paddings, mode, constant_values): np_val = self._npPad(np_inputs, paddings, mode=mode, constant_values=constant_values) for use_gpu in [True, False]: with test_util.device(use_gpu=use_gpu): tf_val = array_ops.pad(np_inputs, paddings, mode=mode, constant_values=constant_values) out = self.evaluate(tf_val) if np_inputs.dtype in [self._qint8, self._quint8, self._qint32]: # Cast quantized types back to their numpy equivalents. np_val = np_val.astype(np_inputs.dtype[0]) self.assertAllEqual(np_val, out) self.assertShapeEqual(np_val, tf_val) def _testGradient(self, x, a, mode, constant_values, paddings_dtype=dtypes.int32): def pad(x): return array_ops.pad( x, ops.convert_to_tensor(a, paddings_dtype), mode=mode, constant_values=constant_values) with self.cached_session(): jacob_t, jacob_n = gradient_checker_v2.compute_gradient(pad, [x]) if x.dtype == dtypes.bfloat16.as_numpy_dtype: # Compare bf16 analytical gradients to fp32 numerical gradients. x_fp32 = constant_op.constant(x, shape=x.shape, dtype=dtypes.float32) _, jacob_n = gradient_checker_v2.compute_gradient(pad, [x_fp32]) tol = 1e-3 if x.dtype == np.float16 else 4e-5 self.assertAllClose(jacob_t, jacob_n, rtol=tol, atol=tol) def _testAll(self, np_inputs, paddings, constant_values): for mode in ("CONSTANT", "REFLECT", "SYMMETRIC", "reflect", "symmetric", "constant"): # Zero-sized input is not allowed for REFLECT mode, but we still want # zero-sized input test cases for the other modes. if not np_inputs.size and mode.upper() == "REFLECT": continue # Empty tensor is not allowed for MirrorPad. if 0 in np_inputs.shape and mode.upper() in ["REFLECT", "SYMMETRIC"]: continue self._testPad( np_inputs, paddings, mode=mode, constant_values=constant_values) if np_inputs.dtype in [ np.float32, np.float16, dtypes.bfloat16.as_numpy_dtype ]: self._testGradient( np_inputs, paddings, mode=mode, constant_values=constant_values) def testInputDims(self): with test_util.use_gpu(): with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError), "Shape must be rank 1 but is rank 6|" "paddings must be the rank of inputs"): array_ops.pad(array_ops.reshape( [1, 2], shape=[1, 2, 1, 1, 1, 1]), array_ops.reshape( [1, 2], shape=[1, 2])) def testPaddingsDim(self): with test_util.use_gpu(): with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError), "Shape must be rank 2 but is rank 1|" "paddings must be a matrix with 2 columns"): array_ops.pad(array_ops.reshape( [1, 2], shape=[1, 2]), array_ops.reshape( [1, 2], shape=[2])) def testPaddingsDim2(self): with test_util.use_gpu(): with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError), "Dimension must be 2 but is 1|" "paddings must be a matrix with 2 columns"): array_ops.pad(array_ops.reshape( [1, 2], shape=[1, 2]), array_ops.reshape( [1, 2], shape=[2, 1])) def testPaddingsDim3(self): with test_util.use_gpu(): with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError), "Shape must be rank 1 but is rank 2|" "paddings must be the rank of inputs"): array_ops.pad(array_ops.reshape( [1, 2], shape=[1, 2]), array_ops.reshape( [1, 2], shape=[1, 2])) def testPaddingsDim4(self): with test_util.use_gpu(): with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError), "Shape must be rank 3 but is rank 2|" "paddings must be the rank of inputs"): array_ops.pad(array_ops.reshape( [1, 2], shape=[1, 2]), array_ops.reshape( [1, 2, 3, 4, 5, 6], shape=[3, 2])) def testPaddingsNonNegative(self): with test_util.use_gpu(): with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError), "must be non-negative"): array_ops.pad(constant_op.constant( [1], shape=[1]), constant_op.constant( [-1, 0], shape=[1, 2])) def testPaddingsNonNegative2(self): with test_util.use_gpu(): with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError), "must be non-negative"): array_ops.pad(constant_op.constant( [1], shape=[1]), constant_op.constant( [-1, 0], shape=[1, 2])) def testPaddingsMaximum(self): with test_util.use_gpu(): with self.assertRaises(Exception): array_ops.pad(constant_op.constant( [1], shape=[2]), constant_op.constant( [2, 0], shape=[1, 2]), mode="REFLECT").eval() with self.assertRaises(Exception): array_ops.pad(constant_op.constant( [1], shape=[2]), constant_op.constant( [0, 3], shape=[1, 2]), mode="SYMMETRIC").eval() def testInvalid(self): with self.cached_session(): x = [[1, 2, 3], [4, 5, 6]] with self.assertRaisesRegex( ValueError, "Value of argument `mode` expected to be .* Received `mode` = WEIRD"): self.evaluate(array_ops.pad(x, [[1, 0], [2, 1]], mode="weird")) def testPaddingTypes(self): paddings = [[1, 0], [2, 0]] inputs = np.random.rand(2, 5).astype(np.float32) for mode in ("CONSTANT", "REFLECT", "SYMMETRIC", "reflect", "symmetric", "constant"): for paddings_dtype in [dtypes.int32, dtypes.int64]: np_val = self._npPad(inputs, paddings, mode=mode, constant_values=0) with test_util.use_gpu(): tf_val = array_ops.pad( inputs, constant_op.constant(paddings, paddings_dtype), mode=mode, constant_values=0) out = self.evaluate(tf_val) self.assertAllEqual(np_val, out) self.assertShapeEqual(np_val, tf_val) if mode.upper() != "REFLECT": with ops.Graph().as_default(): self._testGradient( inputs, paddings, mode=mode, constant_values=0, paddings_dtype=paddings_dtype) def testQuantizedTypes(self): for t in [self._qint8, self._quint8, self._qint32]: self._testAll( np.random.randint(-100, 100, (4, 4, 3)).astype(t), [[1, 0], [2, 3], [0, 2]], 0) self._testAll( np.random.randint(-100, 100, (4, 2, 1, 3)).astype(t), [[0, 0], [0, 0], [0, 0], [0, 0]], np.array(123).astype(t)) def testIntTypes(self): # TODO(touts): Figure out why the padding tests do not work on GPU # for int types and rank > 2. for t in [np.int8, np.uint8, np.int32, np.int64]: self._testAll( np.random.randint(-100, 100, (4, 4, 3)).astype(t), [[1, 0], [2, 3], [0, 2]], 0) self._testAll( np.random.randint(-100, 100, (4, 2, 1, 3)).astype(t), [[0, 0], [0, 0], [0, 0], [0, 0]], -123) def testFloatTypes(self): for t in [ np.float16, np.float32, np.float64, dtypes.bfloat16.as_numpy_dtype ]: self._testAll(np.random.rand(2, 5).astype(t), [[1, 0], [2, 0]], 0.0) self._testAll( np.random.rand(2, 3, 4).astype(t), [[0, 0], [0, 0], [0, 0]], -12.34) self._testAll( np.random.rand(1, 3, 4).astype(t), [[0, 0], [1, 1], [2, 2]], 1.41) def testEmptyTensor(self): for t in [ np.float16, np.float32, np.float64, dtypes.bfloat16.as_numpy_dtype ]: self._testAll(np.random.rand(0, 3, 4).astype(t), [[0, 0], [2, 1], [2, 3]], 0.0) def testComplexTypes(self): for t in [np.complex64, np.complex128]: x = np.random.rand(2, 5).astype(t) self._testAll(x + 1j * x, [[1, 0], [2, 0]], 1234.0 - 1234.0j) x = np.random.rand(3, 2, 1, 1).astype(t) self._testAll(x + 1j * x, [[0, 0], [0, 0], [0, 0], [0, 0]], 0 + 0j) def testString(self): # Numpy does not support padding strings so we compare padding manually. x = ops.convert_to_tensor([["Hello", "World"], ["Goodnight", "Moon"]]) constant = array_ops.pad(x, [[1, 0], [0, 1]], mode="CONSTANT", constant_values="PAD") reflect = array_ops.pad(x, [[1, 0], [0, 1]], mode="REFLECT", constant_values="PAD") symmetric = array_ops.pad(x, [[1, 0], [0, 1]], mode="SYMMETRIC", constant_values="PAD") with test_util.use_gpu(): self.assertAllEqual( [[b"PAD", b"PAD", b"PAD"], [b"Hello", b"World", b"PAD"], [b"Goodnight", b"Moon", b"PAD"]], self.evaluate(constant)) self.assertAllEqual([[b"Goodnight", b"Moon", b"Goodnight"], [b"Hello", b"World", b"Hello"], [b"Goodnight", b"Moon", b"Goodnight"]], self.evaluate(reflect)) self.assertAllEqual( [[b"Hello", b"World", b"World"], [b"Hello", b"World", b"World"], [b"Goodnight", b"Moon", b"Moon"]], self.evaluate(symmetric)) def testShapeFunctionEdgeCases(self): # Shape function requires placeholders and a graph with ops.Graph().as_default(): # Unknown paddings shape. inp = constant_op.constant(0.0, shape=[4, 4, 4, 4]) padded = array_ops.pad(inp, array_ops.placeholder(dtypes.int32)) self.assertEqual([None, None, None, None], padded.get_shape().as_list()) # Unknown input shape. inp = array_ops.placeholder(dtypes.float32) padded = array_ops.pad(inp, [[2, 2], [2, 2]]) self.assertEqual([None, None], padded.get_shape().as_list()) # Unknown input and paddings shape. inp = array_ops.placeholder(dtypes.float32) padded = array_ops.pad(inp, array_ops.placeholder(dtypes.int32)) self.assertAllEqual(None, padded.get_shape().ndims) def testPartialShapeInformation(self): # Partial shapes requires placeholders and a graph with ops.Graph().as_default(): unknown = array_ops.placeholder(dtypes.int32) # Known input shape, partial unknown padding (one dimension). inp = constant_op.constant(0.0, shape=[4, 4]) padded = array_ops.pad(inp, [[1, 2], unknown]) self.assertEqual([7, None], padded.get_shape().as_list()) # Known input shape, partial unknown padding (begin). inp = constant_op.constant(0.0, shape=[4, 4]) padded = array_ops.pad(inp, [[unknown, 0], [1, 2]]) self.assertEqual([None, 7], padded.get_shape().as_list()) # Known input shape, partial unknown padding (end). inp = constant_op.constant(0.0, shape=[4, 4]) padded = array_ops.pad(inp, [[1, 2], [0, unknown]]) self.assertEqual([7, None], padded.get_shape().as_list()) # Unknown input shape, partial unknown padding (one dimension). padded = array_ops.pad(unknown, [[1, 2], unknown]) self.assertEqual([None, None], padded.get_shape().as_list()) # Unknown input shape (rank known), partial unknown padding (one dim). rank_known = array_ops.placeholder(dtypes.int32) rank_known.set_shape([None, None]) padded = array_ops.pad(rank_known, [[1, 2], unknown]) self.assertEqual([None, None], padded.get_shape().as_list()) # Known input shape, partial unknown padding (begin), with constant begin. inp = constant_op.constant(0.0, shape=[4, 4]) padded = array_ops.pad( inp, [[constant_op.constant(1, shape=[]), 2], [0, unknown]]) self.assertEqual([7, None], padded.get_shape().as_list()) # Known input shape, partial unknown padding (begin), with constant dim. inp = constant_op.constant(0.0, shape=[4, 4]) padded = array_ops.pad(inp, [constant_op.constant(1, shape=[2]), [0, unknown]]) self.assertEqual([6, None], padded.get_shape().as_list()) # Zero padding on a known dimension. inp = array_ops.placeholder(dtypes.int32, [None, None, 20]) padded = array_ops.pad(inp, [[0, 0], [0, unknown], [0, 0]]) self.assertEqual([None, None, 20], padded.get_shape().as_list()) def testScalars(self): paddings = np.zeros((0, 2), dtype=np.int32) inp = np.asarray(7) with test_util.use_gpu(): tf_val = array_ops.pad(inp, paddings) out = self.evaluate(tf_val) self.assertAllEqual(inp, out) self.assertShapeEqual(inp, tf_val) def testPadTypes(self): for dtype in [dtypes.int32, dtypes.int64]: paddings = np.zeros((0, 2)) inp = np.asarray(7) with self.cached_session(): tf_val = array_ops.pad(inp, constant_op.constant(paddings, dtype=dtype)) out = self.evaluate(tf_val) self.assertAllEqual(inp, out) self.assertShapeEqual(inp, tf_val) def testCollapseAdjacentNonPaddedDimensions(self): # pyformat: disable paddings_values = [[[0, 0], [0, 0], [0, 0], [0, 1]], [[0, 0], [2, 3], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0]]] # pyformat: enable for paddings_value in paddings_values: for dtype in [dtypes.float32, dtypes.int32]: inp = constant_op.constant(1, shape=[8, 28, 28, 3], dtype=dtype) paddings = constant_op.constant(paddings_value, dtype=dtypes.int32) padded = array_ops.pad(inp, paddings) middle = array_ops.slice(padded, [row[0] for row in paddings_value], [dim.value for dim in inp.shape.dims]) left = array_ops.slice(padded, [0, 0, 0, 0], [row[0] for row in paddings_value]) right = array_ops.slice( padded, [paddings_value[i][0] + inp.shape.dims[i].value for i in range(4)], [-1, -1, -1, -1]) with self.cached_session(): self.assertAllEqual(inp, self.evaluate(middle)) self.assertAllEqual( np.zeros([row[0] for row in paddings_value]), self.evaluate(left)) self.assertAllEqual( np.zeros([row[1] for row in paddings_value]), self.evaluate(right)) if __name__ == "__main__": test.main()
PadOpTest
python
xlwings__xlwings
xlwings/constants.py
{ "start": 96754, "end": 96908 }
class ____: xlFreeFloating = 3 # from enum XlPlacement xlMove = 2 # from enum XlPlacement xlMoveAndSize = 1 # from enum XlPlacement
Placement
python
airbytehq__airbyte
airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/api.py
{ "start": 521, "end": 697 }
class ____(Exception): """General class for all API errors""" backoff_policy = retry_pattern(backoff.expo, FacebookRequestError, max_tries=5, factor=5)
FacebookAPIException
python
wireservice__csvkit
tests/test_utilities/test_csvjoin.py
{ "start": 193, "end": 4934 }
class ____(CSVKitTestCase, EmptyFileTests): Utility = CSVJoin default_args = ['examples/dummy.csv', '-'] def test_launch_new_instance(self): with patch.object(sys, 'argv', [self.Utility.__name__.lower(), 'examples/join_a.csv', 'examples/join_b.csv']): launch_new_instance() def test_options(self): for args, message in ( ( ['-c' '1,2'], 'The number of join column names must match the number of files, ' 'or be a single column name that exists in all files.', ), (['-c', '1', '--left', '--right'], 'It is not valid to specify both a left and a right join.'), ): with self.subTest(args=args): self.assertError(launch_new_instance, args, message) def test_join_options(self): for option in ('--left', '--right', '--outer'): with self.subTest(option=option): self.assertError( launch_new_instance, [option], 'You must provide join column names when performing an outer join.', ) @unittest.skipIf(os.name != 'nt', 'Windows only') def test_glob(self): self.assertRows(['--no-inference', '-c', 'a', 'examples/dummy?.csv'], [ ['a', 'b', 'c', 'b2', 'c2'], ['1', '2', '3', '2', '3'], ['1', '2', '3', '4', '5'], ]) def test_sequential(self): output = self.get_output_as_io(['examples/join_a.csv', 'examples/join_b.csv']) self.assertEqual(len(output.readlines()), 4) def test_inner(self): output = self.get_output_as_io(['-c', 'a', 'examples/join_a.csv', 'examples/join_b.csv']) self.assertEqual(len(output.readlines()), 3) def test_left(self): output = self.get_output_as_io(['-c', 'a', '--left', 'examples/join_a.csv', 'examples/join_b.csv']) self.assertEqual(len(output.readlines()), 5) def test_right(self): output = self.get_output_as_io(['-c', 'a', '--right', 'examples/join_a.csv', 'examples/join_b.csv']) self.assertEqual(len(output.readlines()), 4) def test_right_indices(self): output = self.get_output_as_io(['-c', '1,4', '--right', 'examples/join_a.csv', 'examples/blanks.csv']) self.assertEqual(len(output.readlines()), 2) def test_outer(self): output = self.get_output_as_io(['-c', 'a', '--outer', 'examples/join_a.csv', 'examples/join_b.csv']) self.assertEqual(len(output.readlines()), 6) def test_left_short_columns(self): output = self.get_output_as_io(['-c', 'a', 'examples/join_a_short.csv', 'examples/join_b.csv']) with open('examples/join_short.csv') as f: self.assertEqual(output.readlines(), f.readlines()) def test_single(self): self.assertRows(['examples/dummy.csv', '--no-inference'], [ ['a', 'b', 'c'], ['1', '2', '3'], ]) def test_no_blanks(self): self.assertRows(['examples/blanks.csv', 'examples/blanks.csv'], [ ['a', 'b', 'c', 'd', 'e', 'f', 'a2', 'b2', 'c2', 'd2', 'e2', 'f2'], ['', '', '', '', '', '', '', '', '', '', '', ''], ]) def test_blanks(self): self.assertRows(['--blanks', 'examples/blanks.csv', 'examples/blanks.csv'], [ ['a', 'b', 'c', 'd', 'e', 'f', 'a2', 'b2', 'c2', 'd2', 'e2', 'f2'], ['', 'NA', 'N/A', 'NONE', 'NULL', '.', '', 'NA', 'N/A', 'NONE', 'NULL', '.'], ]) def test_no_header_row(self): output = self.get_output_as_io( ['-c', '1', '--no-header-row', 'examples/join_a.csv', 'examples/join_no_header_row.csv']) self.assertEqual(len(output.readlines()), 3) def test_no_inference(self): self.assertRows(['--no-inference', 'examples/join_a.csv', 'examples/join_short.csv'], [ ['a', 'b', 'c', 'a2', 'b2', 'c2', 'b2_2', 'c2_2'], ['1', 'b', 'c', '1', 'b', '', 'b', 'c'], ['2', 'b', 'c', '1', 'b', '', 'b', 'c'], ['3', 'b', 'c', '', '', '', '', ''], ]) def test_sniff_limit_no_limit(self): self.assertRows(['examples/join_a.csv', 'examples/sniff_limit.csv'], [ ['a', 'b', 'c', 'a2', 'b2', 'c2'], ['1', 'b', 'c', 'True', '2', '3'], ['2', 'b', 'c', '', '', ''], ['3', 'b', 'c', '', '', ''], ]) def test_sniff_limit_zero_limit(self): self.assertRows(['--snifflimit', '0', 'examples/join_a.csv', 'examples/sniff_limit.csv'], [ ['a', 'b', 'c', 'a;b;c'], ['1', 'b', 'c', '1;2;3'], ['2', 'b', 'c', ''], ['3', 'b', 'c', ''], ])
TestCSVJoin
python
sqlalchemy__sqlalchemy
test/orm/test_utils.py
{ "start": 20366, "end": 32989 }
class ____(_fixtures.FixtureTest): run_setup_mappers = "once" run_inserts = None run_deletes = None @classmethod def setup_mappers(cls): cls._setup_stock_mapping() def test_root_registry(self): umapper = inspect(self.classes.User) is_(RootRegistry()[umapper], umapper._path_registry) eq_(RootRegistry()[umapper], PathRegistry.coerce((umapper,))) def test_expand(self): umapper = inspect(self.classes.User) amapper = inspect(self.classes.Address) path = PathRegistry.coerce((umapper,)) eq_( path[umapper.attrs.addresses][amapper][ amapper.attrs.email_address ], PathRegistry.coerce( ( umapper, umapper.attrs.addresses, amapper, amapper.attrs.email_address, ) ), ) def test_entity_boolean(self): umapper = inspect(self.classes.User) path = PathRegistry.coerce((umapper,)) is_(bool(path), True) def test_key_boolean(self): umapper = inspect(self.classes.User) path = PathRegistry.coerce((umapper, umapper.attrs.addresses)) is_(bool(path), True) def test_aliased_class(self): User = self.classes.User ua = aliased(User) ua_insp = inspect(ua) path = PathRegistry.coerce((ua_insp, ua_insp.mapper.attrs.addresses)) assert path.parent.is_aliased_class def test_indexed_entity(self): umapper = inspect(self.classes.User) amapper = inspect(self.classes.Address) path = PathRegistry.coerce( ( umapper, umapper.attrs.addresses, amapper, amapper.attrs.email_address, ) ) is_(path[0], umapper) is_(path[2], amapper) def test_indexed_key_token(self): umapper = inspect(self.classes.User) amapper = inspect(self.classes.Address) path = PathRegistry.coerce( ( umapper, umapper.attrs.addresses, amapper, PathToken.intern(":*"), ) ) is_true(path.is_token) eq_(path[1], umapper.attrs.addresses) eq_(path[3], ":*") with expect_raises(IndexError): path[amapper] def test_slice_token(self): umapper = inspect(self.classes.User) amapper = inspect(self.classes.Address) path = PathRegistry.coerce( ( umapper, umapper.attrs.addresses, amapper, PathToken.intern(":*"), ) ) is_true(path.is_token) eq_(path[1:3], (umapper.attrs.addresses, amapper)) def test_indexed_key(self): umapper = inspect(self.classes.User) amapper = inspect(self.classes.Address) path = PathRegistry.coerce( ( umapper, umapper.attrs.addresses, amapper, amapper.attrs.email_address, ) ) eq_(path[1], umapper.attrs.addresses) eq_(path[3], amapper.attrs.email_address) def test_slice(self): umapper = inspect(self.classes.User) amapper = inspect(self.classes.Address) path = PathRegistry.coerce( ( umapper, umapper.attrs.addresses, amapper, amapper.attrs.email_address, ) ) eq_(path[1:3], (umapper.attrs.addresses, amapper)) def test_addition(self): umapper = inspect(self.classes.User) amapper = inspect(self.classes.Address) p1 = PathRegistry.coerce((umapper, umapper.attrs.addresses)) p2 = PathRegistry.coerce((amapper, amapper.attrs.email_address)) eq_( p1 + p2, PathRegistry.coerce( ( umapper, umapper.attrs.addresses, amapper, amapper.attrs.email_address, ) ), ) def test_length(self): umapper = inspect(self.classes.User) amapper = inspect(self.classes.Address) pneg1 = PathRegistry.coerce(()) p0 = PathRegistry.coerce((umapper,)) p1 = PathRegistry.coerce((umapper, umapper.attrs.addresses)) p2 = PathRegistry.coerce((umapper, umapper.attrs.addresses, amapper)) p3 = PathRegistry.coerce( ( umapper, umapper.attrs.addresses, amapper, amapper.attrs.email_address, ) ) eq_(len(pneg1), 0) eq_(len(p0), 1) eq_(len(p1), 2) eq_(len(p2), 3) eq_(len(p3), 4) eq_(pneg1.length, 0) eq_(p0.length, 1) eq_(p1.length, 2) eq_(p2.length, 3) eq_(p3.length, 4) def test_eq(self): umapper = inspect(self.classes.User) amapper = inspect(self.classes.Address) u_alias = inspect(aliased(self.classes.User)) p1 = PathRegistry.coerce((umapper, umapper.attrs.addresses)) p2 = PathRegistry.coerce((umapper, umapper.attrs.addresses)) p3 = PathRegistry.coerce((umapper, umapper.attrs.name)) p4 = PathRegistry.coerce((u_alias, umapper.attrs.addresses)) p5 = PathRegistry.coerce((umapper, umapper.attrs.addresses, amapper)) p6 = PathRegistry.coerce( (amapper, amapper.attrs.user, umapper, umapper.attrs.addresses) ) p7 = PathRegistry.coerce( ( amapper, amapper.attrs.user, umapper, umapper.attrs.addresses, amapper, amapper.attrs.email_address, ) ) is_(p1 == p2, True) is_(p1 == p3, False) is_(p1 == p4, False) is_(p1 == p5, False) is_(p6 == p7, False) is_(p6 == p7.parent.parent, True) is_(p1 != p2, False) is_(p1 != p3, True) is_(p1 != p4, True) is_(p1 != p5, True) def test_eq_non_path(self): umapper = inspect(self.classes.User) amapper = inspect(self.classes.Address) u_alias = inspect(aliased(self.classes.User)) p1 = PathRegistry.coerce((umapper,)) p2 = PathRegistry.coerce((umapper, umapper.attrs.addresses)) p3 = PathRegistry.coerce((u_alias, umapper.attrs.addresses)) p4 = PathRegistry.coerce((u_alias, umapper.attrs.addresses, amapper)) p5 = PathRegistry.coerce((u_alias,)).token(":*") non_object = 54.1432 for obj in [p1, p2, p3, p4, p5]: with expect_warnings( "Comparison of PathRegistry to " "<.* 'float'> is not supported" ): is_(obj == non_object, False) with expect_warnings( "Comparison of PathRegistry to " "<.* 'float'> is not supported" ): is_(obj != non_object, True) def test_contains_mapper(self): umapper = inspect(self.classes.User) amapper = inspect(self.classes.Address) p1 = PathRegistry.coerce((umapper, umapper.attrs.addresses)) assert p1.contains_mapper(umapper) assert not p1.contains_mapper(amapper) def test_path(self): umapper = inspect(self.classes.User) amapper = inspect(self.classes.Address) p1 = PathRegistry.coerce((umapper, umapper.attrs.addresses)) p2 = PathRegistry.coerce((umapper, umapper.attrs.addresses, amapper)) p3 = PathRegistry.coerce((amapper, amapper.attrs.email_address)) eq_(p1.path, (umapper, umapper.attrs.addresses)) eq_(p2.path, (umapper, umapper.attrs.addresses, amapper)) eq_(p3.path, (amapper, amapper.attrs.email_address)) def test_registry_set(self): reg = {} umapper = inspect(self.classes.User) amapper = inspect(self.classes.Address) p1 = PathRegistry.coerce((umapper, umapper.attrs.addresses)) p2 = PathRegistry.coerce((umapper, umapper.attrs.addresses, amapper)) p3 = PathRegistry.coerce((amapper, amapper.attrs.email_address)) p1.set(reg, "p1key", "p1value") p2.set(reg, "p2key", "p2value") p3.set(reg, "p3key", "p3value") eq_( reg, { ("p1key", p1.path): "p1value", ("p2key", p2.path): "p2value", ("p3key", p3.path): "p3value", }, ) def test_registry_get(self): reg = {} umapper = inspect(self.classes.User) amapper = inspect(self.classes.Address) p1 = PathRegistry.coerce((umapper, umapper.attrs.addresses)) p2 = PathRegistry.coerce((umapper, umapper.attrs.addresses, amapper)) p3 = PathRegistry.coerce((amapper, amapper.attrs.email_address)) reg.update( { ("p1key", p1.path): "p1value", ("p2key", p2.path): "p2value", ("p3key", p3.path): "p3value", } ) eq_(p1.get(reg, "p1key"), "p1value") eq_(p2.get(reg, "p2key"), "p2value") eq_(p2.get(reg, "p1key"), None) eq_(p3.get(reg, "p3key"), "p3value") eq_(p3.get(reg, "p1key"), None) def test_registry_contains(self): reg = {} umapper = inspect(self.classes.User) amapper = inspect(self.classes.Address) p1 = PathRegistry.coerce((umapper, umapper.attrs.addresses)) p2 = PathRegistry.coerce((umapper, umapper.attrs.addresses, amapper)) p3 = PathRegistry.coerce((amapper, amapper.attrs.email_address)) reg.update( { ("p1key", p1.path): "p1value", ("p2key", p2.path): "p2value", ("p3key", p3.path): "p3value", } ) assert p1.contains(reg, "p1key") assert not p1.contains(reg, "p2key") assert p3.contains(reg, "p3key") assert not p2.contains(reg, "fake") def test_registry_setdefault(self): reg = {} umapper = inspect(self.classes.User) amapper = inspect(self.classes.Address) p1 = PathRegistry.coerce((umapper, umapper.attrs.addresses)) p2 = PathRegistry.coerce((umapper, umapper.attrs.addresses, amapper)) reg.update({("p1key", p1.path): "p1value"}) p1.setdefault(reg, "p1key", "p1newvalue_a") p1.setdefault(reg, "p1key_new", "p1newvalue_b") p2.setdefault(reg, "p2key", "p2newvalue") eq_( reg, { ("p1key", p1.path): "p1value", ("p1key_new", p1.path): "p1newvalue_b", ("p2key", p2.path): "p2newvalue", }, ) def test_serialize(self): User = self.classes.User Address = self.classes.Address umapper = inspect(self.classes.User) amapper = inspect(self.classes.Address) p1 = PathRegistry.coerce( ( umapper, umapper.attrs.addresses, amapper, amapper.attrs.email_address, ) ) p2 = PathRegistry.coerce((umapper, umapper.attrs.addresses, amapper)) p3 = PathRegistry.coerce((umapper, umapper.attrs.addresses)) eq_(p1.serialize(), [(User, "addresses"), (Address, "email_address")]) eq_(p2.serialize(), [(User, "addresses"), (Address, None)]) eq_(p3.serialize(), [(User, "addresses")]) def test_deseralize(self): User = self.classes.User Address = self.classes.Address umapper = inspect(self.classes.User) amapper = inspect(self.classes.Address) p1 = PathRegistry.coerce( ( umapper, umapper.attrs.addresses, amapper, amapper.attrs.email_address, ) ) p2 = PathRegistry.coerce((umapper, umapper.attrs.addresses, amapper)) p3 = PathRegistry.coerce((umapper, umapper.attrs.addresses)) eq_( PathRegistry.deserialize( [(User, "addresses"), (Address, "email_address")] ), p1, ) eq_( PathRegistry.deserialize([(User, "addresses"), (Address, None)]), p2, ) eq_(PathRegistry.deserialize([(User, "addresses")]), p3)
PathRegistryTest
python
pytorch__pytorch
torch/distributed/checkpoint/filesystem.py
{ "start": 1810, "end": 2105 }
class ____: """This is the per entry storage info.""" relative_path: str offset: int length: int transform_descriptors: Optional[Sequence[str]] = None def __getstate__(self): return {k: v for k, v in self.__dict__.items() if v is not None} @dataclass
_StorageInfo
python
tensorflow__tensorflow
tensorflow/dtensor/python/d_checkpoint.py
{ "start": 18742, "end": 20712 }
class ____(util.Checkpoint): """Manages saving/restoring trackable values to disk, for DTensor.""" def __init__(self, mesh: layout.Mesh, root=None, **kwargs): super(DTensorCheckpoint, self).__init__(root=root, **kwargs) self._mesh = mesh saver_root = self attached_dependencies = None self._save_counter = None # Created lazily for restore-on-create. self._save_assign_op = None if root: util._assert_trackable(root, "root") saver_root = root attached_dependencies = [] # All keyword arguments (including root itself) are set as children # of root. kwargs["root"] = root root._maybe_initialize_trackable() self._save_counter = data_structures.NoDependency( root._lookup_dependency("save_counter")) self._root = data_structures.NoDependency(root) for k, v in sorted(kwargs.items(), key=lambda item: item[0]): setattr(self, k, v) # Call getattr instead of directly using v because setattr converts # v to a Trackable data structure when v is a list/dict/tuple. converted_v = getattr(self, k) util._assert_trackable(converted_v, k) if root: # Make sure that root doesn't already have dependencies with these names attached_dependencies = attached_dependencies or [] child = root._lookup_dependency(k) if child is None: attached_dependencies.append(base.TrackableReference(k, converted_v)) elif child != converted_v: raise ValueError( "Cannot create a Checkpoint with keyword argument {name} if " "root.{name} already exists.".format(name=k)) # DTensor Change: # Override the parents saver with DTrackableSaver with _SingleDeviceSaver. self._saver = DTrackableSaver( mesh, graph_view_lib.ObjectGraphView( weakref.ref(saver_root), attached_dependencies=attached_dependencies))
DTensorCheckpoint
python
openai__openai-python
src/openai/types/vector_stores/vector_store_file_batch.py
{ "start": 211, "end": 606 }
class ____(BaseModel): cancelled: int """The number of files that where cancelled.""" completed: int """The number of files that have been processed.""" failed: int """The number of files that have failed to process.""" in_progress: int """The number of files that are currently being processed.""" total: int """The total number of files."""
FileCounts
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 52955, "end": 53925 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "pull_request_id", "commit_oid", "body", "event", "comments", "threads", "client_mutation_id", ) pull_request_id = sgqlc.types.Field( sgqlc.types.non_null(ID), graphql_name="pullRequestId" ) commit_oid = sgqlc.types.Field(GitObjectID, graphql_name="commitOID") body = sgqlc.types.Field(String, graphql_name="body") event = sgqlc.types.Field(PullRequestReviewEvent, graphql_name="event") comments = sgqlc.types.Field( sgqlc.types.list_of("DraftPullRequestReviewComment"), graphql_name="comments" ) threads = sgqlc.types.Field( sgqlc.types.list_of("DraftPullRequestReviewThread"), graphql_name="threads" ) client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
AddPullRequestReviewInput
python
tensorflow__tensorflow
tensorflow/python/util/function_utils_test.py
{ "start": 7353, "end": 8356 }
class ____(test.TestCase): def testWithSimpleFunction(self): self.assertEqual( 'silly_example_function', function_utils.get_func_name(silly_example_function)) def testWithClassMethod(self): self.assertEqual( 'GetFuncNameTest.testWithClassMethod', function_utils.get_func_name(self.testWithClassMethod)) def testWithCallableClass(self): callable_instance = SillyCallableClass() self.assertRegex( function_utils.get_func_name(callable_instance), '<.*SillyCallableClass.*>') def testWithFunctoolsPartial(self): partial = functools.partial(silly_example_function) self.assertRegex( function_utils.get_func_name(partial), '<.*functools.partial.*>') def testWithLambda(self): anon_fn = lambda x: x self.assertEqual('<lambda>', function_utils.get_func_name(anon_fn)) def testRaisesWithNonCallableObject(self): with self.assertRaises(ValueError): function_utils.get_func_name(None)
GetFuncNameTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/memberAccess18.py
{ "start": 222, "end": 319 }
class ____: def __get__(self, instance: object, owner: Any) -> A: return A()
Descriptor
python
falconry__falcon
tests/test_request_media.py
{ "start": 1071, "end": 1340 }
class ____: async def on_post(self, req, resp, **kwargs): self.captured_req_media = await req.get_media() # NOTE(kgriffs): Ensure that the media object is cached assert self.captured_req_media is await req.get_media()
ResourceCachedMediaAsync
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/ndb/entities/snippets.py
{ "start": 5334, "end": 5571 }
class ____(ndb.Expando): name = ndb.StringProperty() age = ndb.IntegerProperty() def create_expando_model_entity_with_defined_properties(): employee = FlexEmployee(name="Sandy", location="SF") return employee
FlexEmployee
python
Pylons__pyramid
docs/quick_tutorial/json/tutorial/views.py
{ "start": 105, "end": 440 }
class ____: def __init__(self, request): self.request = request @view_config(route_name='home') def home(self): return {'name': 'Home View'} @view_config(route_name='hello') @view_config(route_name='hello_json', renderer='json') def hello(self): return {'name': 'Hello View'}
TutorialViews
python
django__django
django/contrib/sessions/base_session.py
{ "start": 782, "end": 1491 }
class ____(models.Model): session_key = models.CharField(_("session key"), max_length=40, primary_key=True) session_data = models.TextField(_("session data")) expire_date = models.DateTimeField(_("expire date"), db_index=True) objects = BaseSessionManager() class Meta: abstract = True verbose_name = _("session") verbose_name_plural = _("sessions") def __str__(self): return self.session_key @classmethod def get_session_store_class(cls): raise NotImplementedError def get_decoded(self): session_store_class = self.get_session_store_class() return session_store_class().decode(self.session_data)
AbstractBaseSession
python
pydantic__pydantic
tests/mypy/modules/strict_equality.py
{ "start": 33, "end": 191 }
class ____(BaseModel): username: str user = User(username='test') print(user == 'test') print(user.username == int('1')) print(user.username == 'test')
User
python
tensorflow__tensorflow
tensorflow/compiler/mlir/tfr/python/tfr_gen_test.py
{ "start": 6180, "end": 29477 }
class ____(TFRGenTestBase): """MLIR Generation Tests for MLIR TFR Program.""" def test_tfr_loc(self): mlir_code = tfr_gen(sys.modules[__name__], '_tfr_loc', [test_ops]) mlir_code_exp = r""" CHECK-LABEL: tfr.func @tf__test_input_n_op(%x: !tfr.tensor_list) -> (!tfr.tensor) { CHECK-NEXT: %[[n:.*]] = arith.constant 10 : i64 CHECK-SAME loc("tfr_gen_test.py":%{{.*}}:6) CHECK-NEXT: %[[cst:.*]] = arith.constant 0 : index CHECK-SAME loc("tfr_gen_test.py":%[[sum_line:.*]]:10) CHECK-NEXT: %[[elt:.*]] = tfr.get_element %x[%[[cst]]] : (!tfr.tensor_list, index) -> !tfr.tensor CHECK-SAME loc("tfr_gen_test.py":%[[sum_line]]:10) CHECK-NEXT: %[[cst_1:.*]] = arith.constant 1 : i64 CHECK-SAME loc("tfr_gen_test.py":%[[for_line:.*]]:2) CHECK-NEXT: %[[begin:.*]] = arith.index_cast %[[cst_1]] : i64 to index CHECK-SAME loc("tfr_gen_test.py":%[[for_line]]:2) CHECK-NEXT: %[[end:.*]] = arith.index_cast %[[n]] : i64 to index CHECK-SAME loc("tfr_gen_test.py":%[[for_line]]:2) CHECK-NEXT: %[[step:.*]] = arith.constant 1 : index CHECK-SAME loc("tfr_gen_test.py":%[[for_line]]:2) CHECK-NEXT: %[[for_stmt:.*]] = scf.for %[[itr_1:.*]] = %[[begin]] to %[[end]] step %[[step]] CHECK-SAME: iter_args(%[[it_arg:.*]] = %[[elt]]) -> (!tfr.tensor) { CHECK-NEXT: %[[elt_1:.*]] = tfr.get_element %x[%itr_1] : (!tfr.tensor_list, index) -> !tfr.tensor CHECK-SAME loc("tfr_gen_test.py":%[[add_line:.*]]:34) CHECK-NEXT: %[[Add:.*]] = tfr.call @tf__add(%[[it_arg]], %[[elt_1]]) : (!tfr.tensor, !tfr.tensor) -> (!tfr.tensor) CHECK-SAME loc("tfr_gen_test.py":%[[add_line]]:12) CHECK-NEXT: scf.yield %[[Add]] : !tfr.tensor CHECK-SAME loc(unknown) CHECK-NEXT: } CHECK-SAME loc("tfr_gen_test.py":%[[for_line]]:2) CHECK-NEXT: %{{.*}} = arith.constant true CHECK-SAME loc(unknown) CHECK-NEXT: tfr.return %[[for_stmt]] : !tfr.tensor CHECK-SAME loc(unknown) CHECK-NEXT: } CHECK-SAME loc("tfr_gen_test.py":%{{def_line:.*}}:0) """ self._check_code(mlir_code, mlir_code_exp) def test_tfr_tensors(self): mlir_code = tfr_gen(sys.modules[__name__], '_tfr_tensor', [test_ops]) mlir_code_exp = r""" CHECK-LABEL: tfr.func @tf__test_no_op() -> () { CHECK-NEXT: tfr.return CHECK-NEXT: } CHECK-LABEL: tfr.func @tf__test_identity_op(%x: !tfr.tensor) -> (!tfr.tensor) { CHECK-NEXT: constant true CHECK-NEXT: tfr.return %x : !tfr.tensor CHECK-NEXT: } CHECK-LABEL: tfr.func @tf__test_identity_n_op(%x: !tfr.tensor_list) -> (!tfr.tensor_list) { CHECK-NEXT: constant true CHECK-NEXT: tfr.return %x : !tfr.tensor_list CHECK-NEXT: } CHECK-LABEL: tfr.func @tf__test_input_n_op(%x: !tfr.tensor_list) -> (!tfr.tensor) { CHECK-NEXT: constant true CHECK-NEXT: %[[index:.*]] = arith.constant 1 : index CHECK-NEXT: %[[sub:.*]] = tfr.get_element %x[%cst_1] : (!tfr.tensor_list, index) -> !tfr.tensor CHECK-NEXT: tfr.return %[[sub]] : !tfr.tensor CHECK-NEXT: } CHECK-LABEL: tfr.func @tf__test_output_n_op(%x: !tfr.tensor) -> (!tfr.tensor_list) { CHECK-NEXT: constant true CHECK-NEXT: %[[list:.*]] = "tfr.build_list"(%x, %x) : (!tfr.tensor, !tfr.tensor) -> !tfr.tensor_list CHECK-NEXT: tfr.return %[[list]] : !tfr.tensor_list CHECK-NEXT: } CHECK-LABEL: tfr.func @tf__test_two_inputs_op(%x: !tfr.tensor, %y: !tfr.tensor, %pred: i1{tfr.name="pred",tfr.default=false}) -> (!tfr.tensor) { CHECK-NEXT: %[[cst:.*]] = arith.constant 0 : i64 CHECK-NEXT: %[[cst_1:.*]] = arith.constant 2 : i64 CHECK-NEXT: %[[cst_2:.*]] = "tfr.constant_tensor"(%[[cst]]) : (i64) -> !tfr.tensor CHECK-NEXT: %[[Split:.*]] = tfr.call @tf__split(%[[cst_2]], %x, %[[cst_1]]) : (!tfr.tensor, !tfr.tensor, i64) -> (!tfr.tensor_list) CHECK-NEXT: %[[cst_4:.*]] = arith.constant 0 : index CHECK-NEXT: %[[elt:.*]] = tfr.get_element %[[Split]][%idx] : (!tfr.tensor_list, index) -> !tfr.tensor CHECK-NEXT: %[[cst_5:.*]] = arith.constant 1 : index CHECK-NEXT: %[[elt_1:.*]] = tfr.get_element %[[Split]][%idx_1] : (!tfr.tensor_list, index) -> !tfr.tensor CHECK-NEXT: constant true CHECK-NEXT: tfr.return %[[elt]] : !tfr.tensor CHECK-NEXT: } CHECK-LABEL: tfr.func @tf__test_two_outputs_op(%x: !tfr.tensor) -> (!tfr.tensor, !tfr.tensor) { CHECK-NEXT: %[[cst:.*]] = arith.constant 0 : i64 CHECK-NEXT: %[[cst_1:.*]] = arith.constant 2 : i64 CHECK-NEXT: %[[cst_2:.*]] = "tfr.constant_tensor"(%[[cst]]) : (i64) -> !tfr.tensor CHECK-NEXT: %[[Split:.*]] = tfr.call @tf__split(%[[cst_2]], %x, %[[cst_1]]) : (!tfr.tensor, !tfr.tensor, i64) -> (!tfr.tensor_list) CHECK-NEXT: constant true CHECK-NEXT: %[[cst_4:.*]] = arith.constant 0 : index CHECK-NEXT: %[[elt:.*]] = tfr.get_element %[[Split]][%cst_4] : (!tfr.tensor_list, index) -> !tfr.tensor CHECK-NEXT: %[[cst_5:.*]] = arith.constant 1 : index CHECK-NEXT: %[[elt_1:.*]] = tfr.get_element %[[Split]][%cst_5] : (!tfr.tensor_list, index) -> !tfr.tensor CHECK-NEXT: tfr.return %[[elt]], %[[elt_1]] : !tfr.tensor, !tfr.tensor CHECK-NEXT: } CHECK-LABEL: tfr.func @tf__test_num_attrs_op(%x1: i64{tfr.name="x1",tfr.default=-10}, %y1: i64{tfr.name="y1",tfr.default=1}, %x2: f32{tfr.name="x2",tfr.default=0.0}, %y2: f32{tfr.name="y2",tfr.default=-3.0}) -> () { CHECK-NEXT: %[[cst:.*]] = arith.constant 0 : i64 CHECK-NEXT: %[[cst_1:.*]] = arith.constant 2 : i64 CHECK-NEXT: %[[cst_2:.*]] = arith.constant 1 : i64 CHECK-NEXT: %[[zero:.*]] = arith.constant 0 : i64 CHECK-NEXT: %[[cst_3:.*]] = arith.subi %zero, %cst_2 : i64 CHECK-NEXT: %[[list:.*]] = "tfr.build_list"(%[[cst]], %[[cst_1]], %[[cst_3]], %x1) : (i64, i64, i64, i64) -> !tfr.attr CHECK-NEXT: %[[cst_4:.*]] = arith.constant true CHECK-NEXT: %[[cst_5:.*]] = arith.constant false CHECK-NEXT: %[[cst_6:.*]] = "tfr.constant_tensor"(%[[list]]) : (!tfr.attr) -> !tfr.tensor CHECK-NEXT: %[[cst_7:.*]] = "tfr.constant_tensor"(%y1) : (i64) -> !tfr.tensor CHECK-NEXT: %[[cst_8:.*]] = "tfr.constant_tensor"(%[[cst_4]]) : (i1) -> !tfr.tensor CHECK-NEXT: %[[cst_9:.*]] = "tfr.constant_tensor"(%[[cst_5]]) : (i1) -> !tfr.tensor CHECK-NEXT: %[[cst_10:.*]] = arith.constant -1 : i64 CHECK-NEXT: %[[OneHot:.*]] = tfr.call @tf__one_hot(%[[cst_6]], %[[cst_7]], %[[cst_8]], %[[cst_9]], %[[cst_10]]) CHECK-SAME: (!tfr.tensor, !tfr.tensor, !tfr.tensor, !tfr.tensor, i64) -> (!tfr.tensor) CHECK-NEXT: constant true CHECK-NEXT: tfr.return CHECK-NEXT: } """ self._check_code(mlir_code, mlir_code_exp) def test_tfr_control_flow(self): mlir_code = tfr_gen(sys.modules[__name__], '_tfr_control_flow', [test_ops]) mlir_code_exp = r""" CHECK-LABEL: tfr.func @tf__test_two_inputs_op(%x: !tfr.tensor, %y: !tfr.tensor, CHECK-SAME: %pred: i1{tfr.name="pred",tfr.default=false}) -> (!tfr.tensor) { CHECK-NEXT: %[[if:.*]] = scf.if %pred -> (!tfr.tensor) { CHECK-NEXT: arith.constant true CHECK-NEXT: scf.yield %x : !tfr.tensor CHECK-NEXT: } else { CHECK-NEXT: arith.constant true CHECK-NEXT: scf.yield %y : !tfr.tensor CHECK-NEXT: } CHECK-NEXT: tfr.return %if_stmt : !tfr.tensor CHECK-NEXT: } CHECK-LABEL: tfr.func @tf__test_three_inputs_op(%x: !tfr.tensor, %y: !tfr.tensor, %z: !tfr.tensor, CHECK-SAME: %select: !tfr.attr{tfr.name="act",tfr.default="z"}) -> (!tfr.tensor) { CHECK-NEXT: %[[cst:.*]] = tfr.constant "x" -> !tfr.attr CHECK-NEXT: %[[eq:.*]] = tfr.equal %select, %[[cst]] -> i1 CHECK-NEXT: %[[if_stmt:.*]] = scf.if %[[eq]] -> (!tfr.tensor) { CHECK-NEXT: %[[cst_1:.*]] = arith.constant true CHECK-NEXT: scf.yield %x : !tfr.tensor CHECK-NEXT: } else { CHECK-NEXT: %[[cst_2:.*]] = tfr.constant "y" -> !tfr.attr CHECK-NEXT: %[[eq_1:.*]] = tfr.equal %select, %[[cst_2]] -> i1 CHECK-NEXT: %[[if_stmt1:.*]] = scf.if %[[eq_1]] -> (!tfr.tensor) { CHECK-NEXT: %[[cst_3:.*]] = arith.constant true CHECK-NEXT: scf.yield %y : !tfr.tensor CHECK-NEXT: } else { CHECK-NEXT: %[[cst_4:.*]] = arith.constant true CHECK-NEXT: scf.yield %z : !tfr.tensor CHECK-NEXT: } CHECK-NEXT: scf.yield %[[if_stmt1]] : !tfr.tensor CHECK-NEXT: } CHECK-NEXT: tfr.return %[[if_stmt]] : !tfr.tensor CHECK-NEXT: } CHECK-LABEL: tfr.func @tf__test_input_n_op(%x: !tfr.tensor_list) -> (!tfr.tensor) { CHECK-NEXT: %[[n:.*]] = arith.constant 10 : i64 CHECK-NEXT: %[[cst:.*]] = arith.constant 0 : index CHECK-NEXT: %[[elt:.*]] = tfr.get_element %x[%[[cst]]] : (!tfr.tensor_list, index) -> !tfr.tensor CHECK-NEXT: %[[cst_1:.*]] = arith.constant 1 : i64 CHECK-NEXT: %[[begin:.*]] = arith.index_cast %[[cst_1]] : i64 to index CHECK-NEXT: %[[end:.*]] = arith.index_cast %[[n]] : i64 to index CHECK-NEXT: %[[step:.*]] = arith.constant 1 : index CHECK-NEXT: %[[for_stmt:.*]] = scf.for %[[itr_1:.*]] = %[[begin]] to %[[end]] step %[[step]] CHECK-SAME: iter_args(%[[it_arg:.*]] = %[[elt]]) -> (!tfr.tensor) { CHECK-NEXT: %[[elt_1:.*]] = tfr.get_element %x[%itr_1] : (!tfr.tensor_list, index) -> !tfr.tensor CHECK-NEXT: %[[Add:.*]] = tfr.call @tf__add(%[[it_arg]], %[[elt_1]]) : (!tfr.tensor, !tfr.tensor) -> (!tfr.tensor) CHECK-NEXT: scf.yield %[[Add]] : !tfr.tensor CHECK-NEXT: } CHECK-NEXT: %{{.*}} = arith.constant true CHECK-NEXT: tfr.return %[[for_stmt]] : !tfr.tensor CHECK-NEXT: } CHECK-LABEL: tfr.func @tf__test_input_n_op(%ins: !tfr.tensor_list) -> (!tfr.tensor) { CHECK: %[[attr:.*]] = tfr.constant i64 -> !tfr.attr CHECK: %Const = tfr.call @tf__const(%{{.*}}, %[[attr]]) : (!tfr.attr, !tfr.attr) -> (!tfr.tensor) """ self._check_code(mlir_code, mlir_code_exp) def test_tfr_tf_ops(self): mlir_code = tfr_gen(sys.modules[__name__], '_tfr_tf_ops', [test_ops]) mlir_code_exp = r""" CHECK-LABEL: tfr.func @tf__test_complex_tf_op(%lhs: !tfr.tensor, %rhs: !tfr.tensor) -> (!tfr.tensor_list) { CHECK-NEXT: %[[cst:.*]] = arith.constant 1 : i64 CHECK-NEXT: %[[zero:.*]] = arith.constant 0 : i64 CHECK-NEXT: %[[cst_1:.*]] = arith.subi %[[zero]], %cst : i64 CHECK-NEXT: %[[cst_2:.*]] = "tfr.constant_tensor"(%[[cst_1]]) : (i64) -> !tfr.tensor CHECK-NEXT: %[[list:.*]] = "tfr.build_list"(%rhs, %[[cst_2]]) : (!tfr.tensor, !tfr.tensor) -> !tfr.tensor_list CHECK-NEXT: %[[cst_3:.*]] = arith.constant 0 : i64 CHECK-NEXT: %[[cst_4:.*]] = arith.constant 2 : i64 CHECK-NEXT: %[[zero_1:.*]] = arith.constant 0 : i64 CHECK-NEXT: %[[pack:.*]] = tfr.call @tf__pack(%[[list]], %[[zero_1]]) : (!tfr.tensor_list, i64) -> !tfr.tensor CHECK-NEXT: %[[cst_5:.*]] = "tfr.constant_tensor"(%[[cst_3]]) : (i64) -> !tfr.tensor CHECK-NEXT: %[[SplitV:.*]] = tfr.call @tf__split_v(%lhs, %[[pack]], %[[cst_5]], %[[cst_4]]) CHECK-NEXT: %[[idx:.*]] = arith.constant 0 : index CHECK-NEXT: %[[elt:.*]] = tfr.get_element %SplitV[%idx] : (!tfr.tensor_list, index) -> !tfr.tensor CHECK-NEXT: %[[idx_1:.*]] = arith.constant 1 : index CHECK-NEXT: %[[elt_1:.*]] = tfr.get_element %SplitV[%idx_1] : (!tfr.tensor_list, index) -> !tfr.tensor CHECK-NEXT: %[[list_1:.*]] = "tfr.build_list"(%rhs, %rhs) : (!tfr.tensor, !tfr.tensor) -> !tfr.tensor_list CHECK-NEXT: %[[cst_6:.*]] = arith.constant 1 : i64 CHECK-NEXT: %[[cst_7:.*]] = arith.constant 2 : i64 CHECK-NEXT: %[[zero_2:.*]] = arith.constant 0 : i64 CHECK-NEXT: %[[pack_1:.*]] = tfr.call @tf__pack(%[[list_1]], %[[zero_2]]) : (!tfr.tensor_list, i64) -> !tfr.tensor CHECK-NEXT: %[[cst_8:.*]] = "tfr.constant_tensor"(%[[cst_6]]) : (i64) -> !tfr.tensor CHECK-NEXT: %[[SplitV_1:.*]] = tfr.call @tf__split_v(%lhs, %[[pack_1]], %[[cst_8]], %[[cst_7]]) CHECK-NEXT: %[[idx_2:.*]] = arith.constant 0 : index CHECK-NEXT: %[[elt_2:.*]] = tfr.get_element %SplitV_1[%idx_2] : (!tfr.tensor_list, index) -> !tfr.tensor CHECK-NEXT: %[[idx_3:.*]] = arith.constant 1 : index CHECK-NEXT: %[[elt_3:.*]] = tfr.get_element %SplitV_1[%idx_3] : (!tfr.tensor_list, index) -> !tfr.tensor CHECK-NEXT: %[[cst_9:.*]] = arith.constant true CHECK-NEXT: %[[list_2:.*]] = "tfr.build_list"(%[[elt]], %[[elt_3]]) : (!tfr.tensor, !tfr.tensor) -> !tfr.tensor_list CHECK-NEXT: tfr.return %[[list_2]] : !tfr.tensor_list CHECK-NEXT: } CHECK-LABEL: tfr.func @tf__test_identity_op(%x: !tfr.tensor) -> (!tfr.tensor) { CHECK-NEXT: %cst = arith.constant true CHECK-NEXT: %[[Id:.*]] = tfr.call @tf__identity(%x) : (!tfr.tensor) -> (!tfr.tensor) CHECK-NEXT: tfr.return %[[Id]] : !tfr.tensor CHECK-NEXT: } CHECK-LABEL: tfr.func @tf__test_two_inputs_op(%x: !tfr.tensor, %y: !tfr.tensor, CHECK-SAME: %pred: i1{tfr.name="pred",tfr.default=false}) -> (!tfr.tensor) { CHECK-NEXT: %[[if_stmt:.*]] = scf.if %pred -> (!tfr.tensor) { CHECK-NEXT: %cst = arith.constant true CHECK-NEXT: %[[Add:.*]] = tfr.call @tf__add(%x, %y) : (!tfr.tensor, !tfr.tensor) -> (!tfr.tensor) CHECK-NEXT: scf.yield %[[Add]] : !tfr.tensor CHECK-NEXT: } else { CHECK-NEXT: %cst_1 = arith.constant true CHECK-NEXT: %[[cst_2:.*]] = arith.constant 0 : i64 CHECK-NEXT: %[[list:.*]] = "tfr.build_list"(%x, %y) : (!tfr.tensor, !tfr.tensor) -> !tfr.tensor_list CHECK-NEXT: %[[Concat:.*]] = tfr.call @tf__concat(%[[cst_2]], %[[list]]) : (i64, !tfr.tensor_list) -> (!tfr.tensor) CHECK-NEXT: scf.yield %[[Concat]] : !tfr.tensor CHECK-NEXT: } CHECK-NEXT: tfr.return %[[if_stmt]] : !tfr.tensor CHECK-NEXT: } CHECK-LABEL: tfr.func @tf__test_input_n_op(%ins: !tfr.tensor_list) -> (!tfr.tensor) { CHECK-NEXT: %cst = arith.constant true CHECK-NEXT: %[[cst_1:.*]] = arith.constant 0 : index CHECK-NEXT: %[[elt:.*]] = tfr.get_element %ins[%cst_1] : (!tfr.tensor_list, index) -> !tfr.tensor CHECK-NEXT: %[[cst_2:.*]] = arith.constant 1 : index CHECK-NEXT: %[[elt_1:.*]] = tfr.get_element %ins[%cst_2] : (!tfr.tensor_list, index) -> !tfr.tensor CHECK-NEXT: %[[cst_3:.*]] = arith.constant false CHECK-NEXT: %[[call:.*]] = tfr.call @tf__test_two_inputs_op( CHECK-SAME: %[[elt]], %[[elt_1]], %[[cst_3]]) : (!tfr.tensor, !tfr.tensor, i1) -> (!tfr.tensor) CHECK-NEXT: tfr.return %[[call]] : !tfr.tensor CHECK-NEXT: } CHECK-LABEL: tfr.func @tf__add_(!tfr.tensor<T>,!tfr.tensor<T>) -> (!tfr.tensor<T>) attributes {T,f32_,i1_,i32_,i64_} CHECK-LABEL: tfr.func @tf__concat_(!tfr.tensor<i32_>,!tfr.tensor_list<N,T>) -> (!tfr.tensor<T>) attributes {N,T,f32_,i1_,i32_,i64_} CHECK-LABEL: tfr.func @tf__identity_(!tfr.tensor<T>) -> (!tfr.tensor<T>) attributes {T,f32_,i1_,i32_,i64_} CHECK-LABEL: tfr.func @tf__pack_(!tfr.tensor_list<N,T>,i64{tfr.name="axis",tfr.type="int"}) -> (!tfr.tensor<T>) attributes {N,T,axis,f32_,i1_,i32_,i64_} CHECK-LABEL: tfr.func @tf__split_v_(!tfr.tensor<T>,!tfr.tensor<Tlen>,!tfr.tensor<i32_>,i64{tfr.name="num_split",tfr.type="int"}) -> (!tfr.tensor_list<num_split,T>) attributes {T,Tlen,f32_,i1_,i32_,i64_,num_split} CHECK-LABEL: tfr.func @tf__test_complex_tf_op_(!tfr.tensor<T>,!tfr.tensor<Tlen>,i64{tfr.name="N",tfr.type="int"}) -> (!tfr.tensor_list<N,T>) attributes {N,T,Tlen,f32_,i1_,i32_,i64_} CHECK-LABEL: tfr.func @tf__test_identity_op_(!tfr.tensor<T>) -> (!tfr.tensor<T>) attributes {T,f32_,i1_,i32_,i64_} CHECK-LABEL: tfr.func @tf__test_input_n_op_(!tfr.tensor_list<N,T>) -> (!tfr.tensor<T>) attributes {N,T,f32_,i1_,i32_,i64_} CHECK-LABEL: tfr.func @tf__test_two_inputs_op_(!tfr.tensor<T>,!tfr.tensor<T>,i1{tfr.name="pred",tfr.type="bool"}) -> (!tfr.tensor<T>) attributes {T,f32_,i1_,i32_,i64_,pred} CHECK-LABEL: tfr.func @tf__test_two_outputs_op_(!tfr.tensor<T>) -> (!tfr.tensor<T>,!tfr.tensor<T>) attributes {T,f32_,i1_,i32_,i64_} """ self._check_code(mlir_code, mlir_code_exp) def test_tfr_attrs(self): mlir_code = tfr_gen(sys.modules[__name__], '_tfr_attrs', [test_ops]) mlir_code_exp = r""" CHECK-LABEL: tfr.func @tf__test_num_attrs_op( CHECK-SAME: %x: i64{tfr.name="x1",tfr.default=-10}, CHECK-SAME: %y: i64{tfr.name="y1",tfr.default=1}, CHECK-SAME: %x1: f32{tfr.name="x2",tfr.default=0.0}, CHECK-SAME: %y1: f32{tfr.name="y2",tfr.default=-3.0}) -> () { CHECK-NEXT: %{{.*}} = "tfr.build_list"(%x, %y) : (i64, i64) -> !tfr.attr CHECK-NEXT: %{{.*}} = arith.cmpi "eq", %x, %y : i64 CHECK-NEXT: %{{.*}} = arith.cmpi "ult", %x, %y : i64 CHECK-NEXT: %{{.*}} = arith.cmpi "ule", %x, %y : i64 CHECK-NEXT: %{{.*}} = arith.cmpi "ugt", %x, %y : i64 CHECK-NEXT: %{{.*}} = arith.cmpi "uge", %x, %y : i64 CHECK-NEXT: %{{.*}} = arith.cmpi "ne", %x, %y : i64 CHECK-NEXT: %{{.*}} = arith.addi %x, %y : i64 CHECK-NEXT: %[[sub_1:.*]] = arith.subi %x, %y : i64 CHECK-NEXT: %[[add_1:.*]] = arith.addi %[[sub_1]], %x : i64 CHECK-NEXT: %[[cst:.*]] = arith.constant 1 : i64 CHECK-NEXT: %{{.*}} = arith.addi %[[add_1]], %[[cst]] : i64 CHECK-NEXT: %{{.*}} = arith.cmpf "ugt", %x1, %y1 : f32 CHECK-NEXT: %{{.*}} = arith.addf %x1, %y1 : f32 CHECK-NEXT: %{{.*}} = "tfr.build_list"(%x1, %y1) : (f32, f32) -> !tfr.attr CHECK-NEXT: %{{.*}} = arith.constant true CHECK-NEXT: tfr.return CHECK-NEXT: } CHECK-LABEL: tfr.func @tf__test_non_num_attrs_op( CHECK-SAME: %x: !tfr.attr{tfr.name="z"}, CHECK-SAME: %y: !tfr.attr{tfr.name="x",tfr.default="hello"}, CHECK-SAME: %z: !tfr.attr{tfr.name="y",tfr.default=f32}) -> () { CHECK-NEXT: %{{.*}} = tfr.equal %x, %y -> i1 CHECK-NEXT: %[[cst:.*]] = tfr.constant "test" -> !tfr.attr CHECK-NEXT: %{{.*}} = tfr.equal %x, %[[cst]] -> i1 CHECK-NEXT: %{{.*}} = tfr.equal %y, %z -> i1 CHECK-NEXT: %{{.*}} = arith.constant true CHECK-NEXT: tfr.return CHECK-NEXT: } """ self._check_code(mlir_code, mlir_code_exp) def test_tf_tensor_shape(self): mlir_code = tfr_gen(sys.modules[__name__], '_tfr_shapes', [test_ops]) mlir_code_exp = r""" CHECK-LABEL: tfr.func @tf__test_identity_op(%x: !tfr.tensor) -> (!tfr.tensor) { CHECK-NEXT: %[[shape:.*]] = tfr.get_shape %x -> !shape.shape CHECK-NEXT: %[[shape_1:.*]] = tfr.get_shape %x -> !shape.shape CHECK-NEXT: %[[len:.*]] = shape.rank %[[shape_1]] : !shape.shape -> !shape.size CHECK-NEXT: %[[index:.*]] = shape.size_to_index %[[len]] : !shape.size CHECK-NEXT: %[[begin:.*]] = arith.constant 0 : index CHECK-NEXT: %[[step:.*]] = arith.constant 1 : index CHECK-NEXT: scf.for %[[itr_1:.*]] = %[[begin]] to %[[index]] step %[[step]] { CHECK-NEXT: %[[size:.*]] = shape.get_extent %[[shape_1]], %[[itr_1]]: !shape.shape, index -> !shape.size CHECK-NEXT: %[[elt:.*]] = shape.size_to_index %[[size]] : !shape.size CHECK-NEXT: scf.yield CHECK-NEXT: } CHECK-NEXT: %[[cst:.*]] = arith.constant 1 : i64 CHECK-NEXT: %[[len_1:.*]] = shape.rank %shape_1 : !shape.shape -> !shape.size CHECK-NEXT: %[[len_size_1:.*]] = shape.size_to_index %[[len_1]] : !shape.size CHECK-NEXT: %[[cst_1:.*]] = arith.constant 2 : i64 CHECK-NEXT: %[[begin_1:.*]] = arith.index_cast %[[cst]] : i64 to index CHECK-NEXT: %[[step_1:.*]] = arith.index_cast %[[cst_1]] : i64 to index CHECK-NEXT: scf.for %[[itr_3:.*]] = %[[begin_1]] to %[[len_size_1]] step %[[step_1]] CHECK: %[[cst:.*]] = tfr.constant i32 -> !tfr.attr CHECK-NEXT: %[[Shape:.*]] = tfr.call @tf__shape(%x, %[[cst]]) : (!tfr.tensor, !tfr.attr) -> (!tfr.tensor) CHECK-NEXT: %{{.*}} = arith.constant true CHECK-NEXT: tfr.return %x : !tfr.tensor CHECK-NEXT: } """ self._check_code(mlir_code, mlir_code_exp) def test_temp_function(self): mlir_code = tfr_gen(sys.modules[__name__], '_tfr_temp', [test_ops]) mlir_code_exp = r""" CHECK-LABEL: tfr.func @tf__test_identity_n_op(%x: !tfr.tensor_list) -> (!tfr.tensor_list) CHECK-LABEL: tfr.func @tf__test_identity_op(%x: !tfr.tensor) -> (!tfr.tensor) { CHECK-NEXT: %[[list:.*]] = "tfr.build_list"(%x) : (!tfr.tensor) -> !tfr.tensor_list CHECK-NEXT: %[[call:.*]] = tfr.call @tf__test_identity_n_op(%[[list]]) : (!tfr.tensor_list) """ self._check_code(mlir_code, mlir_code_exp) def test_quant_builtins(self): mlir_code = tfr_gen(sys.modules[__name__], '_tfr_quant', [test_ops]) mlir_code_exp = r""" CHECK-LABEL: tfr.func @tf__test_identity_op(%x: !tfr.tensor) -> (!tfr.tensor) { CHECK-NEXT: %[[raw_data:.*]] = tfr.quant_raw_data(%x) : (!tfr.tensor) -> (!tfr.tensor) CHECK-NEXT: %[[qparam:.*]]:2 = tfr.quant_qparam(%x) : (!tfr.tensor) -> (!tfr.tensor, !tfr.tensor) CHECK: %[[list:.*]] = "tfr.build_list"(%[[qparam]]#0, %[[qparam]]#0) : (!tfr.tensor, !tfr.tensor) -> !tfr.tensor_list CHECK: %[[factor:.*]] = tfr.quant_scale_factor(%{{.*}}, %[[list]]) : (f32, !tfr.tensor_list) -> (!tfr.tensor) CHECK: %[[list1:.*]] = "tfr.build_list"(%[[factor]]) : (!tfr.tensor) -> !tfr.tensor_list CHECK: %[[factor1:.*]] = tfr.quant_scale_factor(%{{.*}}, %[[list1]]) : (f32, !tfr.tensor_list) -> (!tfr.tensor) CHECK-NEXT: %[[Sub:.*]] = tfr.call @tf__sub(%[[raw_data]], %[[qparam]]#1) : (!tfr.tensor, !tfr.tensor) -> (!tfr.tensor) CHECK: %[[act_range:.*]]:2 = tfr.quant_act_range(%{{.*}}, %{{.*}}, %{{.*}}) : (!tfr.attr, f32, i64) -> (!tfr.tensor, !tfr.tensor) CHECK: %[[rescale:.*]] = tfr.quant_rescale(%[[Sub]], %[[factor1]], %{{.*}}) : (!tfr.tensor, !tfr.tensor, i64) -> (!tfr.tensor) CHECK: %[[attr:.*]] = tfr.constant i16 -> !tfr.attr CHECK: %[[Cast:.*]] = tfr.call @tf__cast(%[[rescale]], %[[attr]], %{{.*}}) : (!tfr.tensor, !tfr.attr, i1) -> (!tfr.tensor) CHECK: %[[attr_1:.*]] = tfr.constant i8 -> !tfr.attr CHECK: tfr.call @tf__cast(%[[Cast]], %[[attr_1]], %{{.*}}) : (!tfr.tensor, !tfr.attr, i1) -> (!tfr.tensor) CHECK: } CHECK-LABEL: tfr.func @tf__test_identity_n_op(%x: !tfr.tensor_list) -> (!tfr.tensor_list) { CHECK-NEXT: %[[raw_data:.*]] = tfr.quant_raw_data(%x) : (!tfr.tensor_list) -> (!tfr.tensor_list) CHECK: tfr.return %[[raw_data:.*]] : !tfr.tensor_list CHECK: } """ self._check_code(mlir_code, mlir_code_exp) if __name__ == '__main__': test.main()
TFRGenTensorTest
python
tensorflow__tensorflow
third_party/xla/xla/python/status_casters_test.py
{ "start": 792, "end": 1520 }
class ____(absltest.TestCase): def test_status_wrappers(self): self.assertIsNone(status_casters_ext.my_lambda()) self.assertIsNone(status_casters_ext.my_lambda2()) self.assertIsNone(status_casters_ext.MyClass().my_method(1, 2)) self.assertIsNone(status_casters_ext.MyClass().my_method_const(1, 2)) def test_status_or_wrappers(self): self.assertEqual(status_casters_ext.my_lambda_statusor(), 1) self.assertEqual(status_casters_ext.status_or_identity(2), 2) self.assertEqual(status_casters_ext.MyClass().my_method_status_or(1, 2), 3) self.assertEqual( status_casters_ext.MyClass().my_method_status_or_const(1, 2), 3 ) if __name__ == "__main__": absltest.main()
StatusCastersTest
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 27284, "end": 27468 }
class ____(sgqlc.types.Enum): """ See source code for more info. """ __schema__ = graphql_schema __choices__ = ("PENDING", "SUBMITTED")
PullRequestReviewCommentState
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 102635, "end": 103567 }
class ____(str, Enum): """ How to use positive and negative examples to find the results, default is `average_vector`: * `average_vector` - Average positive and negative vectors and create a single query with the formula `query = avg_pos + avg_pos - avg_neg`. Then performs normal search. * `best_score` - Uses custom search objective. Each candidate is compared against all examples, its score is then chosen from the `max(max_pos_score, max_neg_score)`. If the `max_neg_score` is chosen then it is squared and negated, otherwise it is just the `max_pos_score`. * `sum_scores` - Uses custom search objective. Compares against all inputs, sums all the scores. Scores against positive vectors are added, against negatives are subtracted. """ def __str__(self) -> str: return str(self.value) AVERAGE_VECTOR = "average_vector" BEST_SCORE = "best_score" SUM_SCORES = "sum_scores"
RecommendStrategy
python
kamyu104__LeetCode-Solutions
Python/number-of-islands.py
{ "start": 1512, "end": 2546 }
class ____(object): def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] def dfs(grid, i, j): if grid[i][j] == '0': return False grid[i][j] = '0' stk = [(i, j)] while stk: r, c = stk.pop() for dr, dc in directions: nr, nc = r+dr, c+dc if not (0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] == '1'): continue grid[nr][nc] = '0' stk.append((nr, nc)) return True count = 0 for i in xrange(len(grid)): for j in xrange(len(grid[0])): if dfs(grid, i, j): count += 1 return count # Time: O(m * n) # Space: O(m * n) import collections # bfs solution
Solution2
python
matplotlib__matplotlib
lib/matplotlib/__init__.py
{ "start": 10929, "end": 23178 }
class ____(FileNotFoundError): """ Error raised when an executable that Matplotlib optionally depends on can't be found. """ pass @functools.cache def _get_executable_info(name): """ Get the version of some executable that Matplotlib optionally depends on. .. warning:: The list of executables that this function supports is set according to Matplotlib's internal needs, and may change without notice. Parameters ---------- name : str The executable to query. The following values are currently supported: "dvipng", "gs", "inkscape", "magick", "pdftocairo", "pdftops". This list is subject to change without notice. Returns ------- tuple A namedtuple with fields ``executable`` (`str`) and ``version`` (`packaging.Version`, or ``None`` if the version cannot be determined). Raises ------ ExecutableNotFoundError If the executable is not found or older than the oldest version supported by Matplotlib. For debugging purposes, it is also possible to "hide" an executable from Matplotlib by adding it to the :envvar:`_MPLHIDEEXECUTABLES` environment variable (a comma-separated list), which must be set prior to any calls to this function. ValueError If the executable is not one that we know how to query. """ def impl(args, regex, min_ver=None, ignore_exit_code=False): # Execute the subprocess specified by args; capture stdout and stderr. # Search for a regex match in the output; if the match succeeds, the # first group of the match is the version. # Return an _ExecInfo if the executable exists, and has a version of # at least min_ver (if set); else, raise ExecutableNotFoundError. try: output = subprocess.check_output( args, stderr=subprocess.STDOUT, text=True, errors="replace", timeout=30) except subprocess.CalledProcessError as _cpe: if ignore_exit_code: output = _cpe.output else: raise ExecutableNotFoundError(str(_cpe)) from _cpe except subprocess.TimeoutExpired as _te: msg = f"Timed out running {cbook._pformat_subprocess(args)}" raise ExecutableNotFoundError(msg) from _te except OSError as _ose: raise ExecutableNotFoundError(str(_ose)) from _ose match = re.search(regex, output) if match: raw_version = match.group(1) version = parse_version(raw_version) if min_ver is not None and version < parse_version(min_ver): raise ExecutableNotFoundError( f"You have {args[0]} version {version} but the minimum " f"version supported by Matplotlib is {min_ver}") return _ExecInfo(args[0], raw_version, version) else: raise ExecutableNotFoundError( f"Failed to determine the version of {args[0]} from " f"{' '.join(args)}, which output {output}") if name in os.environ.get("_MPLHIDEEXECUTABLES", "").split(","): raise ExecutableNotFoundError(f"{name} was hidden") if name == "dvipng": return impl(["dvipng", "-version"], "(?m)^dvipng(?: .*)? (.+)", "1.6") elif name == "gs": execs = (["gswin32c", "gswin64c", "mgs", "gs"] # "mgs" for miktex. if sys.platform == "win32" else ["gs"]) for e in execs: try: return impl([e, "--version"], "(.*)", "9") except ExecutableNotFoundError: pass message = "Failed to find a Ghostscript installation" raise ExecutableNotFoundError(message) elif name == "inkscape": try: # Try headless option first (needed for Inkscape version < 1.0): return impl(["inkscape", "--without-gui", "-V"], "Inkscape ([^ ]*)") except ExecutableNotFoundError: pass # Suppress exception chaining. # If --without-gui is not accepted, we may be using Inkscape >= 1.0 so # try without it: return impl(["inkscape", "-V"], "Inkscape ([^ ]*)") elif name == "magick": if sys.platform == "win32": # Check the registry to avoid confusing ImageMagick's convert with # Windows's builtin convert.exe. import winreg binpath = "" for flag in [0, winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY]: try: with winreg.OpenKeyEx( winreg.HKEY_LOCAL_MACHINE, r"Software\Imagemagick\Current", 0, winreg.KEY_QUERY_VALUE | flag) as hkey: binpath = winreg.QueryValueEx(hkey, "BinPath")[0] except OSError: pass path = None if binpath: for name in ["convert.exe", "magick.exe"]: candidate = Path(binpath, name) if candidate.exists(): path = str(candidate) break if path is None: raise ExecutableNotFoundError( "Failed to find an ImageMagick installation") else: path = "convert" # Ignore deprecation warning for "convert" on IM>=7.1.1-33. info = impl([path, "--version"], r"(?sm:.*^)Version: ImageMagick (\S*)") if info.raw_version == "7.0.10-34": # https://github.com/ImageMagick/ImageMagick/issues/2720 raise ExecutableNotFoundError( f"You have ImageMagick {info.version}, which is unsupported") return info elif name == "pdftocairo": return impl(["pdftocairo", "-v"], "pdftocairo version (.*)") elif name == "pdftops": info = impl(["pdftops", "-v"], "^pdftops version (.*)", ignore_exit_code=True) if info and not ( 3 <= info.version.major or # poppler version numbers. parse_version("0.9") <= info.version < parse_version("1.0")): raise ExecutableNotFoundError( f"You have pdftops version {info.version} but the minimum " f"version supported by Matplotlib is 3.0") return info else: raise ValueError(f"Unknown executable: {name!r}") def _get_xdg_config_dir(): """ Return the XDG configuration directory, according to the XDG base directory spec: https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html """ return os.environ.get('XDG_CONFIG_HOME') or str(Path.home() / ".config") def _get_xdg_cache_dir(): """ Return the XDG cache directory, according to the XDG base directory spec: https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html """ return os.environ.get('XDG_CACHE_HOME') or str(Path.home() / ".cache") def _get_config_or_cache_dir(xdg_base_getter): configdir = os.environ.get('MPLCONFIGDIR') if configdir: configdir = Path(configdir) elif sys.platform.startswith(('linux', 'freebsd')): # Only call _xdg_base_getter here so that MPLCONFIGDIR is tried first, # as _xdg_base_getter can throw. try: configdir = Path(xdg_base_getter(), "matplotlib") except RuntimeError: # raised if Path.home() is not available pass else: try: configdir = Path.home() / ".matplotlib" except RuntimeError: # raised if Path.home() is not available pass if configdir: # Resolve the path to handle potential issues with inaccessible symlinks. configdir = configdir.resolve() try: configdir.mkdir(parents=True, exist_ok=True) except OSError as exc: _log.warning("mkdir -p failed for path %s: %s", configdir, exc) else: if os.access(str(configdir), os.W_OK) and configdir.is_dir(): return str(configdir) _log.warning("%s is not a writable directory", configdir) issue_msg = "the default path ({configdir})" else: issue_msg = "resolving the home directory" # If the config or cache directory cannot be created or is not a writable # directory, create a temporary one. try: tmpdir = tempfile.mkdtemp(prefix="matplotlib-") except OSError as exc: raise OSError( f"Matplotlib requires access to a writable cache directory, but there " f"was an issue with {issue_msg}, and a temporary " f"directory could not be created; set the MPLCONFIGDIR environment " f"variable to a writable directory") from exc os.environ["MPLCONFIGDIR"] = tmpdir atexit.register(shutil.rmtree, tmpdir) _log.warning( "Matplotlib created a temporary cache directory at %s because there was " "an issue with %s; it is highly recommended to set the " "MPLCONFIGDIR environment variable to a writable directory, in particular to " "speed up the import of Matplotlib and to better support multiprocessing.", tmpdir, issue_msg) return tmpdir @_logged_cached('CONFIGDIR=%s') def get_configdir(): """ Return the string path of the configuration directory. The directory is chosen as follows: 1. If the MPLCONFIGDIR environment variable is supplied, choose that. 2. On Linux, follow the XDG specification and look first in ``$XDG_CONFIG_HOME``, if defined, or ``$HOME/.config``. On other platforms, choose ``$HOME/.matplotlib``. 3. If the chosen directory exists and is writable, use that as the configuration directory. 4. Else, create a temporary directory, and use it as the configuration directory. """ return _get_config_or_cache_dir(_get_xdg_config_dir) @_logged_cached('CACHEDIR=%s') def get_cachedir(): """ Return the string path of the cache directory. The procedure used to find the directory is the same as for `get_configdir`, except using ``$XDG_CACHE_HOME``/``$HOME/.cache`` instead. """ return _get_config_or_cache_dir(_get_xdg_cache_dir) @_logged_cached('matplotlib data path: %s') def get_data_path(): """Return the path to Matplotlib data.""" return str(Path(__file__).with_name("mpl-data")) def matplotlib_fname(): """ Get the location of the config file. The file location is determined in the following order - ``$PWD/matplotlibrc`` - ``$MATPLOTLIBRC`` if it is not a directory - ``$MATPLOTLIBRC/matplotlibrc`` - ``$MPLCONFIGDIR/matplotlibrc`` - On Linux, - ``$XDG_CONFIG_HOME/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME`` is defined) - or ``$HOME/.config/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME`` is not defined) - On other platforms, - ``$HOME/.matplotlib/matplotlibrc`` if ``$HOME`` is defined - Lastly, it looks in ``$MATPLOTLIBDATA/matplotlibrc``, which should always exist. """ def gen_candidates(): # rely on down-stream code to make absolute. This protects us # from having to directly get the current working directory # which can fail if the user has ended up with a cwd that is # non-existent. yield 'matplotlibrc' try: matplotlibrc = os.environ['MATPLOTLIBRC'] except KeyError: pass else: yield matplotlibrc yield os.path.join(matplotlibrc, 'matplotlibrc') yield os.path.join(get_configdir(), 'matplotlibrc') yield os.path.join(get_data_path(), 'matplotlibrc') for fname in gen_candidates(): if os.path.exists(fname) and not os.path.isdir(fname): return fname raise RuntimeError("Could not find matplotlibrc file; your Matplotlib " "install is broken") @_docstring.Substitution( "\n".join(map("- {}".format, sorted(rcsetup._validators, key=str.lower))) )
ExecutableNotFoundError
python
django-haystack__django-haystack
test_haystack/test_loading.py
{ "start": 6960, "end": 7090 }
class ____(indexes.BasicSearchIndex, indexes.Indexable): def get_model(self): return MockModel
BasicMockModelSearchIndex
python
ethereum__web3.py
web3/types.py
{ "start": 11956, "end": 12108 }
class ____(TypedDict, total=False): pending: dict[ChecksumAddress, dict[Nonce, str]] queued: dict[ChecksumAddress, dict[Nonce, str]]
TxPoolInspect
python
keon__algorithms
tests/test_strings.py
{ "start": 4467, "end": 4825 }
class ____(unittest.TestCase): """[summary] Test for the file int_to_roman.py Arguments: unittest {[type]} -- [description] """ def test_int_to_roman(self): self.assertEqual("DCXLIV", int_to_roman(644)) self.assertEqual("I", int_to_roman(1)) self.assertEqual("MMMCMXCIX", int_to_roman(3999))
TestIntToRoman
python
nedbat__coveragepy
tests/test_goldtest.py
{ "start": 1692, "end": 5924 }
class ____(CoverageTest): """Tests of goldtest.py:compare()""" def setUp(self) -> None: super().setUp() self.addCleanup(remove_tree, ACTUAL_DIR) def test_good(self) -> None: self.make_file("out/gettysburg.txt", GOOD_GETTY) compare(gold_path("testing/getty"), "out", scrubs=SCRUBS) self.assert_doesnt_exist(ACTUAL_GETTY_FILE) def test_bad(self) -> None: self.make_file("out/gettysburg.txt", BAD_GETTY) # compare() raises an assertion. msg = rf"Files differ: .*{GOLD_PATH_RX} != {OUT_PATH_RX}" with pytest.raises(AssertionError, match=msg): compare(gold_path("testing/getty"), "out", scrubs=SCRUBS) # Stdout has a description of the diff. The diff shows the scrubbed content. stdout = self.stdout() assert "- Four score" in stdout assert "+ Five score" in stdout assert re_line(rf"^:::: diff '.*{GOLD_PATH_RX}' and '{OUT_PATH_RX}'", stdout) assert re_line(rf"^:::: end diff '.*{GOLD_PATH_RX}' and '{OUT_PATH_RX}'", stdout) assert os_sep( f"Saved actual output to '{ACTUAL_GETTY_FILE}': see tests/gold/README.rst" ) in os_sep(stdout) assert " D/D/D, Gxxx, Pennsylvania" in stdout # The actual file was saved. with open(ACTUAL_GETTY_FILE, encoding="utf-8") as f: saved = f.read() assert saved == BAD_GETTY def test_good_needs_scrubs(self) -> None: # Comparing the "good" result without scrubbing the variable parts will fail. self.make_file("out/gettysburg.txt", GOOD_GETTY) # compare() raises an assertion. msg = rf"Files differ: .*{GOLD_PATH_RX} != {OUT_PATH_RX}" with pytest.raises(AssertionError, match=msg): compare(gold_path("testing/getty"), "out") stdout = self.stdout() assert "- 11/19/1863, Gettysburg, Pennsylvania" in stdout assert "+ 11/19/9999, Gettysburg, Pennsylvania" in stdout def test_actual_extra(self) -> None: self.make_file("out/gettysburg.txt", GOOD_GETTY) self.make_file("out/another.more", "hi") # Extra files in the output are ok with actual_extra=True. compare(gold_path("testing/getty"), "out", scrubs=SCRUBS, actual_extra=True) # But not without it: # (test output is in files like /tmp/pytest-of-user/pytest-0/popen-gw3/t76/out) msg = r"Files in .*[/\\]t\d+[/\\]out only: \['another.more'\]" with pytest.raises(AssertionError, match=msg): compare(gold_path("testing/getty"), "out", scrubs=SCRUBS) self.assert_exists(os.path.join(TESTS_DIR, "actual/testing/getty/another.more")) # But only the files matching the file_pattern are considered. compare(gold_path("testing/getty"), "out", file_pattern="*.txt", scrubs=SCRUBS) def test_xml_good(self) -> None: self.make_file( "out/output.xml", """\ <?xml version="1.0" ?> <the_root c="three" b="222" a="one"> <also z="nine" x="seven" y="888"> Goodie </also> </the_root> """, ) compare(gold_path("testing/xml"), "out", scrubs=SCRUBS) def test_xml_bad(self) -> None: self.make_file( "out/output.xml", """\ <?xml version="1.0" ?> <the_root c="nine" b="2" a="one"> <also z="three" x="seven" y="8"> Goodbye </also> </the_root> """, ) # compare() raises an exception. gold_rx = path_regex(gold_path("testing/xml/output.xml")) out_rx = path_regex("out/output.xml") msg = rf"Files differ: .*{gold_rx} != {out_rx}" with pytest.raises(AssertionError, match=msg): compare(gold_path("testing/xml"), "out", scrubs=SCRUBS) # Stdout has a description of the diff. The diff shows the # canonicalized and scrubbed content. stdout = self.stdout() assert '- <the_root a="one" b="D" c="three">' in stdout assert '+ <the_root a="one" b="D" c="nine">' in stdout
CompareTest
python
ansible__ansible
test/lib/ansible_test/_internal/host_profiles.py
{ "start": 63468, "end": 68222 }
class ____(ControllerHostProfile[PosixRemoteConfig], RemoteProfile[PosixRemoteConfig], DebuggableProfile[PosixRemoteConfig]): """Host profile for a POSIX remote instance.""" def wait(self) -> None: """Wait for the instance to be ready. Executed before delegation for the controller and after delegation for targets.""" self.wait_until_ready() def setup(self) -> None: """Perform out-of-band setup before delegation.""" if self.debugging_enabled: self.enable_debugger_forwarding(self.get_origin_controller_connection().settings) def configure(self) -> None: """Perform in-band configuration. Executed before delegation for the controller and after delegation for targets.""" # a target uses a single python version, but a controller may include additional versions for targets running on the controller python_interpreters = {self.python.version: self.python.path} python_interpreters.update({target.python.version: target.python.path for target in self.targets if isinstance(target, ControllerConfig)}) python_interpreters = {version: python_interpreters[version] for version in sorted_versions(list(python_interpreters.keys()))} core_ci = self.wait_for_instance() pwd = self.wait_until_ready() display.info(f'Remote working directory: {pwd}', verbosity=1) bootstrapper = BootstrapRemote( controller=self.controller, platform=self.config.platform, platform_version=self.config.version, python_interpreters=python_interpreters, ssh_key=core_ci.ssh_key, ) setup_sh = bootstrapper.get_script() shell = setup_sh.splitlines()[0][2:] ssh = self.get_origin_controller_connection() ssh.run([shell], data=setup_sh, capture=False) def get_ssh_connection(self) -> SshConnection: """Return an SSH connection for accessing the host.""" core_ci = self.wait_for_instance() settings = SshConnectionDetail( name=core_ci.name, user=core_ci.connection.username, host=core_ci.connection.hostname, port=core_ci.connection.port, identity_file=core_ci.ssh_key.key, python_interpreter=self.python.path, ) if settings.user == 'root': become: t.Optional[Become] = None elif self.config.become: become = SUPPORTED_BECOME_METHODS[self.config.become]() else: display.warning(f'Defaulting to "sudo" for platform "{self.config.platform}" become support.', unique=True) become = Sudo() return SshConnection(self.args, settings, become) def wait_until_ready(self) -> str: """Wait for instance to respond to SSH, returning the current working directory once connected.""" core_ci = self.wait_for_instance() for dummy in range(1, 90): try: return self.get_working_directory() except SubprocessError as ex: # No "Permission denied" check is performed here. # Unlike containers, with remote instances, user configuration isn't guaranteed to have been completed before SSH connections are attempted. display.warning(str(ex)) time.sleep(10) raise HostConnectionError(f'Timeout waiting for {self.config.name} instance {core_ci.instance_id}.') def get_controller_target_connections(self) -> list[SshConnection]: """Return SSH connection(s) for accessing the host as a target from the controller.""" return [self.get_ssh_connection()] def get_origin_controller_connection(self) -> SshConnection: """Return a connection for accessing the host as a controller from the origin.""" return self.get_ssh_connection() def get_working_directory(self) -> str: """Return the working directory for the host.""" if not self.pwd: ssh = self.get_origin_controller_connection() stdout = ssh.run(['pwd'], capture=True)[0] if self.args.explain: return '/pwd' pwd = stdout.strip().splitlines()[-1] if not pwd.startswith('/'): raise Exception(f'Unexpected current working directory "{pwd}" from "pwd" command output:\n{stdout.strip()}') self.pwd = pwd return self.pwd @property def pwd(self) -> t.Optional[str]: """Return the cached pwd, if any, otherwise None.""" return self.cache.get('pwd') @pwd.setter def pwd(self, value: str) -> None: """Cache the given pwd.""" self.cache['pwd'] = value
PosixRemoteProfile
python
mlflow__mlflow
dev/clint/src/clint/resolver.py
{ "start": 88, "end": 2931 }
class ____: def __init__(self) -> None: self.name_map: dict[str, list[str]] = {} self._scope_stack: list[dict[str, list[str]]] = [] def clear(self) -> None: """Clear all name mappings. Useful when starting to process a new file.""" self.name_map.clear() self._scope_stack.clear() def enter_scope(self) -> None: """Enter a new scope by taking a snapshot of current mappings.""" self._scope_stack.append(self.name_map.copy()) def exit_scope(self) -> None: """Exit current scope by restoring the previous snapshot.""" if self._scope_stack: self.name_map = self._scope_stack.pop() @contextmanager def scope(self) -> Iterator[None]: """Context manager for automatic scope management.""" self.enter_scope() try: yield finally: self.exit_scope() def add_import(self, node: ast.Import) -> None: for alias in node.names: if alias.asname: self.name_map[alias.asname] = alias.name.split(".") else: toplevel = alias.name.split(".", 1)[0] self.name_map[toplevel] = [toplevel] def add_import_from(self, node: ast.ImportFrom) -> None: if node.module is None: return for alias in node.names: name = alias.asname or alias.name module_parts = node.module.split(".") self.name_map[name] = module_parts + [alias.name] def resolve(self, node: ast.expr) -> list[str] | None: """ Resolve a node to its fully qualified name parts. Args: node: AST node to resolve, typically a Call, Name, or Attribute. Returns: List of name parts (e.g., ["threading", "Thread"]) or None if unresolvable """ if isinstance(node, ast.Call): parts = self._extract_call_parts(node.func) elif isinstance(node, ast.Name): parts = [node.id] elif isinstance(node, ast.Attribute): parts = self._extract_call_parts(node) else: return None return self._resolve_parts(parts) if parts else None def _extract_call_parts(self, node: ast.expr) -> list[str]: if isinstance(node, ast.Name): return [node.id] elif isinstance(node, ast.Attribute) and ( base_parts := self._extract_call_parts(node.value) ): return base_parts + [node.attr] return [] def _resolve_parts(self, parts: list[str]) -> list[str] | None: if not parts: return None # Check if the first part is in our name mapping if resolved_base := self.name_map.get(parts[0]): return resolved_base + parts[1:] return None
Resolver
python
tensorflow__tensorflow
tensorflow/python/ops/variables.py
{ "start": 6850, "end": 7406 }
class ____(abc.ABCMeta): """Metaclass to allow construction of tf.Variable to be overridden.""" @traceback_utils.filter_traceback def __call__(cls, *args, **kwargs): if hasattr(cls, "_variable_call") and callable(cls._variable_call): variable_call = cls._variable_call(*args, **kwargs) if variable_call is not None: return variable_call return super(VariableMetaclass, cls).__call__(*args, **kwargs) @tf_export("Variable", v1=[]) # TODO(mdan): This should subclass core.Tensor, and not all its subclasses?
VariableMetaclass
python
giampaolo__psutil
tests/test_connections.py
{ "start": 1522, "end": 2533 }
class ____(PsutilTestCase): def setUp(self): assert this_proc_net_connections(kind='all') == [] def tearDown(self): # Make sure we closed all resources. assert this_proc_net_connections(kind='all') == [] def compare_procsys_connections(self, pid, proc_cons, kind='all'): """Given a process PID and its list of connections compare those against system-wide connections retrieved via psutil.net_connections. """ try: sys_cons = psutil.net_connections(kind=kind) except psutil.AccessDenied: # On MACOS, system-wide connections are retrieved by iterating # over all processes if MACOS: return else: raise # Filter for this proc PID and exlucde PIDs from the tuple. sys_cons = [c[:-1] for c in sys_cons if c.pid == pid] sys_cons.sort() proc_cons.sort() assert proc_cons == sys_cons
ConnectionTestCase
python
dagster-io__dagster
python_modules/libraries/dagster-shared/dagster_shared/serdes/objects/definition_metadata.py
{ "start": 507, "end": 606 }
class ____: name: str cron_schedule: str source: Optional[str] @record
DgScheduleMetadata
python
realpython__materials
python-mutable-immutable/user.py
{ "start": 0, "end": 128 }
class ____: __slots__ = ("name", "job") def __init__(self, name, job): self.name = name self.job = job
User
python
google__jax
docs/autodidax.py
{ "start": 8181, "end": 9143 }
class ____: _trace: Trace __array_priority__ = 1000 @property def aval(self): assert False # must override def full_lower(self): return self # default implementation def __neg__(self): return self.aval._neg(self) def __add__(self, other): return self.aval._add(self, other) def __radd__(self, other): return self.aval._radd(self, other) def __mul__(self, other): return self.aval._mul(self, other) def __rmul__(self, other): return self.aval._rmul(self, other) def __gt__(self, other): return self.aval._gt(self, other) def __lt__(self, other): return self.aval._lt(self, other) def __bool__(self): return self.aval._bool(self) def __nonzero__(self): return self.aval._nonzero(self) def __getattr__(self, name): try: return getattr(self.aval, name) except AttributeError: raise AttributeError(f"{self.__class__.__name__} has no attribute {name}") def swap(f): return lambda x, y: f(y, x) # +
Tracer
python
kamyu104__LeetCode-Solutions
Python/find-the-maximum-divisibility-score.py
{ "start": 47, "end": 300 }
class ____(object): def maxDivScore(self, nums, divisors): """ :type nums: List[int] :type divisors: List[int] :rtype: int """ return max(divisors, key=lambda d: (sum(x%d == 0 for x in nums), -d))
Solution
python
great-expectations__great_expectations
tests/integration/metrics/batch/test_row_count.py
{ "start": 382, "end": 1698 }
class ____: ROW_COUNT = 4 @parameterize_batch_for_data_sources( data_source_configs=PANDAS_DATA_SOURCES, data=DATA_FRAME, ) def test_success_pandas(self, batch_for_datasource) -> None: batch = batch_for_datasource metric = BatchRowCount() metric_result = batch.compute_metrics(metric) assert isinstance(metric_result, BatchRowCountResult) assert metric_result.value == self.ROW_COUNT @parameterize_batch_for_data_sources( data_source_configs=SPARK_DATA_SOURCES, data=DATA_FRAME, ) def test_success_spark(self, batch_for_datasource) -> None: batch = batch_for_datasource metric = BatchRowCount() metric_result = batch.compute_metrics(metric) assert isinstance(metric_result, BatchRowCountResult) assert metric_result.value == self.ROW_COUNT @parameterize_batch_for_data_sources( data_source_configs=SQL_DATA_SOURCES, data=DATA_FRAME, ) def test_success_sql(self, batch_for_datasource) -> None: batch = batch_for_datasource metric = BatchRowCount() metric_result = batch.compute_metrics(metric) assert isinstance(metric_result, BatchRowCountResult) assert metric_result.value == self.ROW_COUNT
TestBatchRowCount
python
weaviate__weaviate-python-client
weaviate/collections/classes/batch.py
{ "start": 12168, "end": 12780 }
class ____: """This class contains the results of a batch operation. Since the individual objects and references within the batch can error for differing reasons, the data is split up within this class for ease use when performing error checking, handling, and data revalidation. Attributes: objs: The results of the batch object operation. refs: The results of the batch reference operation. """ def __init__(self) -> None: self.objs: BatchObjectReturn = BatchObjectReturn() self.refs: BatchReferenceReturn = BatchReferenceReturn() @dataclass
BatchResult
python
ray-project__ray
python/ray/serve/_private/router.py
{ "start": 44418, "end": 47914 }
class ____: def __init__(self, controller_handle: ActorHandle, event_loop: AbstractEventLoop): self.controller_handler = controller_handle self.event_loop = event_loop # We use a WeakSet to store the Routers so that we don't prevent them # from being garbage-collected. self.routers: MutableMapping[ DeploymentID, weakref.WeakSet[AsyncioRouter] ] = defaultdict(weakref.WeakSet) # Creating the LongPollClient implicitly starts it self.long_poll_client = LongPollClient( controller_handle, key_listeners={}, call_in_event_loop=self.event_loop, ) @classmethod @lru_cache(maxsize=None) def get_or_create( cls, controller_handle: ActorHandle, event_loop: AbstractEventLoop ) -> "SharedRouterLongPollClient": shared = cls(controller_handle=controller_handle, event_loop=event_loop) logger.info(f"Started {shared}.") return shared def update_deployment_targets( self, deployment_target_info: DeploymentTargetInfo, deployment_id: DeploymentID, ) -> None: for router in self.routers[deployment_id]: router.update_deployment_targets(deployment_target_info) router.long_poll_client.stop() def update_deployment_config( self, deployment_config: DeploymentConfig, deployment_id: DeploymentID ) -> None: for router in self.routers[deployment_id]: router.update_deployment_config(deployment_config) router.long_poll_client.stop() def register(self, router: AsyncioRouter) -> None: # We need to run the underlying method in the same event loop that runs # the long poll loop, because we need to mutate the mapping of routers, # which are also being iterated over by the key listener callbacks. # If those happened concurrently in different threads, # we could get a `RuntimeError: Set changed size during iteration`. # See https://github.com/ray-project/ray/pull/53613 for more details. self.event_loop.call_soon_threadsafe(self._register, router) def _register(self, router: AsyncioRouter) -> None: self.routers[router.deployment_id].add(router) # Remove the entries for any deployment ids that no longer have any routers. # The WeakSets will automatically lose track of Routers that get GC'd, # but the outer dict will keep the key around, so we need to clean up manually. # Note the list(...) to avoid mutating self.routers while iterating over it. for deployment_id, routers in list(self.routers.items()): if not routers: self.routers.pop(deployment_id) # Register the new listeners on the long poll client. # Some of these listeners may already exist, but it's safe to add them again. key_listeners = { (LongPollNamespace.DEPLOYMENT_TARGETS, deployment_id): partial( self.update_deployment_targets, deployment_id=deployment_id ) for deployment_id in self.routers.keys() } | { (LongPollNamespace.DEPLOYMENT_CONFIG, deployment_id): partial( self.update_deployment_config, deployment_id=deployment_id ) for deployment_id in self.routers.keys() } self.long_poll_client.add_key_listeners(key_listeners)
SharedRouterLongPollClient
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/suite/test_types.py
{ "start": 22512, "end": 22857 }
class ____(_DateFixture, fixtures.TablesTest): __requires__ = ("time",) __backend__ = True datatype = Time data = datetime.time(12, 57, 18) @testing.requires.time_implicit_bound def test_select_direct(self, connection): result = connection.scalar(select(literal(self.data))) eq_(result, self.data)
TimeTest
python
dagster-io__dagster
python_modules/dagster/dagster/_core/errors.py
{ "start": 25014, "end": 25211 }
class ____(DagsterError): """The user has tried to use a command that requires an instance or invoke DagsterInstance.get() without setting DAGSTER_HOME env var. """
DagsterHomeNotSetError
python
google__pytype
pytype/types/base.py
{ "start": 247, "end": 843 }
class ____: """The base class for abstract values. A BaseValue is pytype's internal representation of a python object. """ def to_pytd_type_of_instance(self, *args, **kwargs) -> pytd.Type: """Get the pytd type an instance of us would have.""" raise NotImplementedError() # Pytype wraps values in Variables, which contain bindings of named python # variables or expressions to abstract values. Variables are an internal # implementation detail that no external code should depend on; we define a # Variable type alias here simply to use in type signatures. Variable = Any
BaseValue
python
sqlalchemy__sqlalchemy
test/orm/test_core_compilation.py
{ "start": 95897, "end": 100444 }
class ____( InheritedTest, _poly_fixtures._Polymorphic, AssertsCompiledSQL ): __dialect__ = "default" def test_load_only_on_sub_table(self): Company = self.classes.Company Engineer = self.classes.Engineer e1 = aliased(Engineer, inspect(Engineer).local_table) q = select(Company.name, e1.primary_language).join( Company.employees.of_type(e1) ) self.assert_compile( q, "SELECT companies.name, engineers.primary_language " "FROM companies JOIN engineers " "ON companies.company_id = people.company_id", ) def test_load_only_on_sub_table_aliased(self): Company = self.classes.Company Engineer = self.classes.Engineer e1 = aliased(Engineer, inspect(Engineer).local_table.alias()) q = select(Company.name, e1.primary_language).join( Company.employees.of_type(e1) ) self.assert_compile( q, "SELECT companies.name, engineers_1.primary_language " "FROM companies JOIN engineers AS engineers_1 " "ON companies.company_id = people.company_id", ) def test_cte_recursive_handles_dupe_columns(self): """test #10169""" Engineer = self.classes.Engineer my_cte = select(Engineer).cte(recursive=True) self.assert_compile( select(my_cte), "WITH RECURSIVE anon_1(person_id, person_id_1, company_id, name, " "type, status, " "engineer_name, primary_language) AS (SELECT engineers.person_id " "AS person_id, people.person_id AS person_id_1, people.company_id " "AS company_id, people.name AS name, people.type AS type, " "engineers.status AS status, engineers.engineer_name AS " "engineer_name, engineers.primary_language AS primary_language " "FROM people JOIN engineers ON people.person_id = " "engineers.person_id) SELECT anon_1.person_id, " "anon_1.person_id_1, anon_1.company_id, " "anon_1.name, anon_1.type, anon_1.status, anon_1.engineer_name, " "anon_1.primary_language FROM anon_1", ) @testing.variation("named", [True, False]) @testing.variation("flat", [True, False]) def test_aliased_joined_entities(self, named, flat): Company = self.classes.Company Engineer = self.classes.Engineer if named: e1 = aliased(Engineer, flat=flat, name="myengineer") else: e1 = aliased(Engineer, flat=flat) q = select(Company.name, e1.primary_language).join( Company.employees.of_type(e1) ) if not flat: name = "anon_1" if not named else "myengineer" self.assert_compile( q, "SELECT companies.name, " f"{name}.engineers_primary_language FROM companies " "JOIN (SELECT people.person_id AS people_person_id, " "people.company_id AS people_company_id, " "people.name AS people_name, people.type AS people_type, " "engineers.person_id AS engineers_person_id, " "engineers.status AS engineers_status, " "engineers.engineer_name AS engineers_engineer_name, " "engineers.primary_language AS engineers_primary_language " "FROM people JOIN engineers " "ON people.person_id = engineers.person_id) AS " f"{name} " f"ON companies.company_id = {name}.people_company_id", ) elif named: self.assert_compile( q, "SELECT companies.name, " "myengineer_engineers.primary_language " "FROM companies JOIN (people AS myengineer_people " "JOIN engineers AS myengineer_engineers " "ON myengineer_people.person_id = " "myengineer_engineers.person_id) " "ON companies.company_id = myengineer_people.company_id", ) else: self.assert_compile( q, "SELECT companies.name, engineers_1.primary_language " "FROM companies JOIN (people AS people_1 " "JOIN engineers AS engineers_1 " "ON people_1.person_id = engineers_1.person_id) " "ON companies.company_id = people_1.company_id", )
JoinedInhTest
python
pytorch__pytorch
tools/test/heuristics/test_interface.py
{ "start": 1169, "end": 10909 }
class ____(TestTD): def test_init_none(self) -> None: tests = ["test_a", "test_b"] test_prioritizations = interface.TestPrioritizations(tests, {}) self.assertSetEqual(test_prioritizations._original_tests, set(tests)) self.assertDictEqual( test_prioritizations._test_scores, {TestRun("test_a"): 0.0, TestRun("test_b"): 0.0}, ) def test_init_set_scores_full_files(self) -> None: tests = ["test_a", "test_b"] test_prioritizations = interface.TestPrioritizations( tests, {TestRun("test_a"): 0.5, TestRun("test_b"): 0.25} ) self.assertSetEqual(test_prioritizations._original_tests, set(tests)) self.assertDictEqual( test_prioritizations._test_scores, {TestRun("test_a"): 0.5, TestRun("test_b"): 0.25}, ) def test_init_set_scores_some_full_files(self) -> None: tests = ["test_a", "test_b"] test_prioritizations = interface.TestPrioritizations( tests, {TestRun("test_a"): 0.5} ) self.assertSetEqual(test_prioritizations._original_tests, set(tests)) self.assertDictEqual( test_prioritizations._test_scores, {TestRun("test_a"): 0.5, TestRun("test_b"): 0.0}, ) def test_init_set_scores_classes(self) -> None: tests = ["test_a", "test_b"] test_prioritizations = interface.TestPrioritizations( tests, {TestRun("test_a", included=["TestA"]): 0.5} ) self.assertSetEqual(test_prioritizations._original_tests, set(tests)) self.assertDictEqual( test_prioritizations._test_scores, { TestRun("test_a", included=["TestA"]): 0.5, TestRun("test_a", excluded=["TestA"]): 0.0, TestRun("test_b"): 0.0, }, ) def test_init_set_scores_other_class_naming_convention(self) -> None: tests = ["test_a", "test_b"] test_prioritizations = interface.TestPrioritizations( tests, {TestRun("test_a::TestA"): 0.5} ) self.assertSetEqual(test_prioritizations._original_tests, set(tests)) self.assertDictEqual( test_prioritizations._test_scores, { TestRun("test_a", included=["TestA"]): 0.5, TestRun("test_a", excluded=["TestA"]): 0.0, TestRun("test_b"): 0.0, }, ) def test_set_test_score_full_class(self) -> None: tests = ["test_a", "test_b"] test_prioritizations = interface.TestPrioritizations(tests, {}) test_prioritizations.set_test_score(TestRun("test_a"), 0.5) self.assertSetEqual(test_prioritizations._original_tests, set(tests)) self.assertDictEqual( test_prioritizations._test_scores, {TestRun("test_a"): 0.5, TestRun("test_b"): 0.0}, ) def test_set_test_score_mix(self) -> None: tests = ["test_a", "test_b"] test_prioritizations = interface.TestPrioritizations( tests, {TestRun("test_b"): -0.5} ) test_prioritizations.set_test_score(TestRun("test_a"), 0.1) test_prioritizations.set_test_score(TestRun("test_a::TestA"), 0.2) test_prioritizations.set_test_score(TestRun("test_a::TestB"), 0.3) test_prioritizations.set_test_score(TestRun("test_a", included=["TestC"]), 0.4) self.assertSetEqual(test_prioritizations._original_tests, set(tests)) self.assertDictEqual( test_prioritizations._test_scores, { TestRun("test_a", included=["TestA"]): 0.2, TestRun("test_a", included=["TestB"]): 0.3, TestRun("test_a", included=["TestC"]): 0.4, TestRun("test_a", excluded=["TestA", "TestB", "TestC"]): 0.1, TestRun("test_b"): -0.5, }, ) test_prioritizations.set_test_score( TestRun("test_a", included=["TestA", "TestB"]), 0.5 ) self.assertDictEqual( test_prioritizations._test_scores, { TestRun("test_a", included=["TestA", "TestB"]): 0.5, TestRun("test_a", included=["TestC"]): 0.4, TestRun("test_a", excluded=["TestA", "TestB", "TestC"]): 0.1, TestRun("test_b"): -0.5, }, ) test_prioritizations.set_test_score( TestRun("test_a", excluded=["TestA", "TestB"]), 0.6 ) self.assertDictEqual( test_prioritizations._test_scores, { TestRun("test_a", included=["TestA", "TestB"]): 0.5, TestRun("test_a", excluded=["TestA", "TestB"]): 0.6, TestRun("test_b"): -0.5, }, ) test_prioritizations.set_test_score(TestRun("test_a", included=["TestC"]), 0.7) self.assertDictEqual( test_prioritizations._test_scores, { TestRun("test_a", included=["TestA", "TestB"]): 0.5, TestRun("test_a", excluded=["TestA", "TestB", "TestC"]): 0.6, TestRun("test_a", included=["TestC"]): 0.7, TestRun("test_b"): -0.5, }, ) test_prioritizations.set_test_score(TestRun("test_a", excluded=["TestD"]), 0.8) self.assertDictEqual( test_prioritizations._test_scores, { TestRun("test_a", excluded=["TestD"]): 0.8, TestRun("test_a", included=["TestD"]): 0.6, TestRun("test_b"): -0.5, }, ) self.assertSetEqual(test_prioritizations._original_tests, set(tests)) test_prioritizations.validate() def test_add_test_score_mix(self) -> None: tests = ["test_a", "test_b"] test_prioritizations = interface.TestPrioritizations( tests, {TestRun("test_b"): -0.5} ) test_prioritizations.add_test_score(TestRun("test_a"), 0.1) test_prioritizations.add_test_score(TestRun("test_a::TestA"), 0.2) test_prioritizations.add_test_score(TestRun("test_a::TestB"), 0.3) test_prioritizations.add_test_score(TestRun("test_a", included=["TestC"]), 0.4) self.assertSetEqual(test_prioritizations._original_tests, set(tests)) self.assert_test_scores_almost_equal( test_prioritizations._test_scores, { TestRun("test_a", included=["TestA"]): 0.3, TestRun("test_a", included=["TestB"]): 0.4, TestRun("test_a", included=["TestC"]): 0.5, TestRun("test_a", excluded=["TestA", "TestB", "TestC"]): 0.1, TestRun("test_b"): -0.5, }, ) test_prioritizations.add_test_score( TestRun("test_a", included=["TestA", "TestB"]), 0.5 ) self.assert_test_scores_almost_equal( test_prioritizations._test_scores, { TestRun("test_a", included=["TestA"]): 0.8, TestRun("test_a", included=["TestB"]): 0.9, TestRun("test_a", included=["TestC"]): 0.5, TestRun("test_a", excluded=["TestA", "TestB", "TestC"]): 0.1, TestRun("test_b"): -0.5, }, ) test_prioritizations.add_test_score( TestRun("test_a", excluded=["TestA", "TestB"]), 0.6 ) self.assert_test_scores_almost_equal( test_prioritizations._test_scores, { TestRun("test_a", included=["TestA"]): 0.8, TestRun("test_a", included=["TestB"]): 0.9, TestRun("test_a", included=["TestC"]): 1.1, TestRun("test_a", excluded=["TestA", "TestB", "TestC"]): 0.7, TestRun("test_b"): -0.5, }, ) test_prioritizations.add_test_score(TestRun("test_a", included=["TestC"]), 0.7) self.assert_test_scores_almost_equal( test_prioritizations._test_scores, { TestRun("test_a", included=["TestA"]): 0.8, TestRun("test_a", included=["TestB"]): 0.9, TestRun("test_a", included=["TestC"]): 1.8, TestRun("test_a", excluded=["TestA", "TestB", "TestC"]): 0.7, TestRun("test_b"): -0.5, }, ) test_prioritizations.add_test_score(TestRun("test_a", excluded=["TestD"]), 0.8) self.assert_test_scores_almost_equal( test_prioritizations._test_scores, { TestRun("test_a", included=["TestA"]): 1.6, TestRun("test_a", included=["TestB"]): 1.7, TestRun("test_a", included=["TestC"]): 2.6, TestRun("test_a", included=["TestD"]): 0.7, TestRun("test_a", excluded=["TestA", "TestB", "TestC", "TestD"]): 1.5, TestRun("test_b"): -0.5, }, ) test_prioritizations.add_test_score( TestRun("test_a", excluded=["TestD", "TestC"]), 0.1 ) self.assert_test_scores_almost_equal( test_prioritizations._test_scores, { TestRun("test_a", included=["TestA"]): 1.7, TestRun("test_a", included=["TestB"]): 1.8, TestRun("test_a", included=["TestC"]): 2.6, TestRun("test_a", included=["TestD"]): 0.7, TestRun("test_a", excluded=["TestA", "TestB", "TestC", "TestD"]): 1.6, TestRun("test_b"): -0.5, }, ) self.assertSetEqual(test_prioritizations._original_tests, set(tests)) test_prioritizations.validate()
TestTestPrioritizations
python
celery__celery
celery/utils/dispatch/signal.py
{ "start": 2105, "end": 13857 }
class ____: # pragma: no cover """Create new signal. Keyword Arguments: providing_args (List): A list of the arguments this signal can pass along in a :meth:`send` call. use_caching (bool): Enable receiver cache. name (str): Name of signal, used for debugging purposes. """ #: Holds a dictionary of #: ``{receiverkey (id): weakref(receiver)}`` mappings. receivers = None def __init__(self, providing_args=None, use_caching=False, name=None): self.receivers = [] self.providing_args = set( providing_args if providing_args is not None else []) self.lock = threading.Lock() self.use_caching = use_caching self.name = name # For convenience we create empty caches even if they are not used. # A note about caching: if use_caching is defined, then for each # distinct sender we cache the receivers that sender has in # 'sender_receivers_cache'. The cache is cleaned when .connect() or # .disconnect() is called and populated on .send(). self.sender_receivers_cache = ( weakref.WeakKeyDictionary() if use_caching else {} ) self._dead_receivers = False def _connect_proxy(self, fun, sender, weak, dispatch_uid): return self.connect( fun, sender=sender._get_current_object(), weak=weak, dispatch_uid=dispatch_uid, ) def connect(self, *args, **kwargs): """Connect receiver to sender for signal. Arguments: receiver (Callable): A function or an instance method which is to receive signals. Receivers must be hashable objects. if weak is :const:`True`, then receiver must be weak-referenceable. Receivers must be able to accept keyword arguments. If receivers have a `dispatch_uid` attribute, the receiver will not be added if another receiver already exists with that `dispatch_uid`. sender (Any): The sender to which the receiver should respond. Must either be a Python object, or :const:`None` to receive events from any sender. weak (bool): Whether to use weak references to the receiver. By default, the module will attempt to use weak references to the receiver objects. If this parameter is false, then strong references will be used. dispatch_uid (Hashable): An identifier used to uniquely identify a particular instance of a receiver. This will usually be a string, though it may be anything hashable. retry (bool): If the signal receiver raises an exception (e.g. ConnectionError), the receiver will be retried until it runs successfully. A strong ref to the receiver will be stored and the `weak` option will be ignored. """ def _handle_options(sender=None, weak=True, dispatch_uid=None, retry=False): def _connect_signal(fun): options = {'dispatch_uid': dispatch_uid, 'weak': weak} def _retry_receiver(retry_fun): def _try_receiver_over_time(*args, **kwargs): def on_error(exc, intervals, retries): interval = next(intervals) err_msg = RECEIVER_RETRY_ERROR % \ {'receiver': retry_fun, 'when': humanize_seconds(interval, 'in', ' ')} logger.error(err_msg) return interval return retry_over_time(retry_fun, Exception, args, kwargs, on_error) return _try_receiver_over_time if retry: options['weak'] = False if not dispatch_uid: # if there's no dispatch_uid then we need to set the # dispatch uid to the original func id so we can look # it up later with the original func id options['dispatch_uid'] = _make_id(fun) fun = _retry_receiver(fun) fun._dispatch_uid = options['dispatch_uid'] self._connect_signal(fun, sender, options['weak'], options['dispatch_uid']) return fun return _connect_signal if args and callable(args[0]): return _handle_options(*args[1:], **kwargs)(args[0]) return _handle_options(*args, **kwargs) def _connect_signal(self, receiver, sender, weak, dispatch_uid): assert callable(receiver), 'Signal receivers must be callable' if not fun_accepts_kwargs(receiver): raise ValueError( 'Signal receiver must accept keyword arguments.') if isinstance(sender, PromiseProxy): sender.__then__( self._connect_proxy, receiver, sender, weak, dispatch_uid, ) return receiver lookup_key = _make_lookup_key(receiver, sender, dispatch_uid) if weak: ref, receiver_object = _boundmethod_safe_weakref(receiver) receiver = ref(receiver) weakref.finalize(receiver_object, self._remove_receiver) with self.lock: self._clear_dead_receivers() for r_key, _ in self.receivers: if r_key == lookup_key: break else: self.receivers.append((lookup_key, receiver)) self.sender_receivers_cache.clear() return receiver def disconnect(self, receiver=None, sender=None, weak=None, dispatch_uid=None): """Disconnect receiver from sender for signal. If weak references are used, disconnect needn't be called. The receiver will be removed from dispatch automatically. Arguments: receiver (Callable): The registered receiver to disconnect. May be none if `dispatch_uid` is specified. sender (Any): The registered sender to disconnect. weak (bool): The weakref state to disconnect. dispatch_uid (Hashable): The unique identifier of the receiver to disconnect. """ if weak is not None: warnings.warn( 'Passing `weak` to disconnect has no effect.', CDeprecationWarning, stacklevel=2) lookup_key = _make_lookup_key(receiver, sender, dispatch_uid) disconnected = False with self.lock: self._clear_dead_receivers() for index in range(len(self.receivers)): (r_key, _) = self.receivers[index] if r_key == lookup_key: disconnected = True del self.receivers[index] break self.sender_receivers_cache.clear() return disconnected def has_listeners(self, sender=None): return bool(self._live_receivers(sender)) def send(self, sender, **named): """Send signal from sender to all connected receivers. If any receiver raises an error, the exception is returned as the corresponding response. (This is different from the "send" in Django signals. In Celery "send" and "send_robust" do the same thing.) Arguments: sender (Any): The sender of the signal. Either a specific object or :const:`None`. **named (Any): Named arguments which will be passed to receivers. Returns: List: of tuple pairs: `[(receiver, response), … ]`. """ responses = [] if not self.receivers or \ self.sender_receivers_cache.get(sender) is NO_RECEIVERS: return responses for receiver in self._live_receivers(sender): try: response = receiver(signal=self, sender=sender, **named) except Exception as exc: # pylint: disable=broad-except if not hasattr(exc, '__traceback__'): exc.__traceback__ = sys.exc_info()[2] logger.exception( 'Signal handler %r raised: %r', receiver, exc) responses.append((receiver, exc)) else: responses.append((receiver, response)) return responses send_robust = send # Compat with Django interface. def _clear_dead_receivers(self): # Warning: caller is assumed to hold self.lock if self._dead_receivers: self._dead_receivers = False new_receivers = [] for r in self.receivers: if isinstance(r[1], weakref.ReferenceType) and r[1]() is None: continue new_receivers.append(r) self.receivers = new_receivers def _live_receivers(self, sender): """Filter sequence of receivers to get resolved, live receivers. This checks for weak references and resolves them, then returning only live receivers. """ receivers = None if self.use_caching and not self._dead_receivers: receivers = self.sender_receivers_cache.get(sender) # We could end up here with NO_RECEIVERS even if we do check this # case in .send() prior to calling _Live_receivers() due to # concurrent .send() call. if receivers is NO_RECEIVERS: return [] if receivers is None: with self.lock: self._clear_dead_receivers() senderkey = _make_id(sender) receivers = [] for (receiverkey, r_senderkey), receiver in self.receivers: if r_senderkey == NONE_ID or r_senderkey == senderkey: receivers.append(receiver) if self.use_caching: if not receivers: self.sender_receivers_cache[sender] = NO_RECEIVERS else: # Note: we must cache the weakref versions. self.sender_receivers_cache[sender] = receivers non_weak_receivers = [] for receiver in receivers: if isinstance(receiver, weakref.ReferenceType): # Dereference the weak reference. receiver = receiver() if receiver is not None: non_weak_receivers.append(receiver) else: non_weak_receivers.append(receiver) return non_weak_receivers def _remove_receiver(self, receiver=None): """Remove dead receivers from connections.""" # Mark that the self..receivers first has dead weakrefs. If so, # we will clean those up in connect, disconnect and _live_receivers # while holding self.lock. Note that doing the cleanup here isn't a # good idea, _remove_receiver() will be called as a side effect of # garbage collection, and so the call can happen wh ile we are already # holding self.lock. self._dead_receivers = True def __repr__(self): """``repr(signal)``.""" return f'<{type(self).__name__}: {self.name} providing_args={self.providing_args!r}>' def __str__(self): """``str(signal)``.""" return repr(self)
Signal
python
airbytehq__airbyte
airbyte-integrations/connectors/source-iterable/source_iterable/streams.py
{ "start": 12992, "end": 13121 }
class ____(IterableStream): data_field = "campaigns" def path(self, **kwargs) -> str: return "campaigns"
Campaigns
python
doocs__leetcode
solution/0000-0099/0072.Edit Distance/Solution.py
{ "start": 0, "end": 529 }
class ____: def minDistance(self, word1: str, word2: str) -> int: m, n = len(word1), len(word2) f = [[0] * (n + 1) for _ in range(m + 1)] for j in range(1, n + 1): f[0][j] = j for i, a in enumerate(word1, 1): f[i][0] = i for j, b in enumerate(word2, 1): if a == b: f[i][j] = f[i - 1][j - 1] else: f[i][j] = min(f[i - 1][j], f[i][j - 1], f[i - 1][j - 1]) + 1 return f[m][n]
Solution
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-nvidia-triton/llama_index/llms/nvidia_triton/base.py
{ "start": 2636, "end": 12022 }
class ____(LLM): """ Nvidia Triton LLM. Nvidia's Triton is an inference server that provides API access to hosted LLM models. This connector allows for llama_index to remotely interact with a Triton inference server over GRPC to accelerate inference operations. [Triton Inference Server Github](https://github.com/triton-inference-server/server) Examples: `pip install llama-index-llms-nvidia-triton` ```python from llama_index.llms.nvidia_triton import NvidiaTriton # Ensure a Triton server instance is running and provide the correct URL for your Triton server instance triton_url = "localhost:8001" # Instantiate the NvidiaTriton class triton_client = NvidiaTriton() # Call the complete method with a prompt resp = triton_client.complete("The tallest mountain in North America is ") print(resp) ``` """ server_url: str = Field( default=DEFAULT_SERVER_URL, description="The URL of the Triton inference server to use.", ) model_name: str = Field( default=DEFAULT_MODEL, description="The name of the Triton hosted model this client should use", ) temperature: Optional[float] = Field( default=DEFAULT_TEMPERATURE, description="Temperature to use for sampling" ) top_p: Optional[float] = Field( default=DEFAULT_TOP_P, description="The top-p value to use for sampling" ) top_k: Optional[float] = Field( default=DEFAULT_TOP_K, description="The top k value to use for sampling" ) tokens: Optional[int] = Field( default=DEFAULT_MAX_TOKENS, description="The maximum number of tokens to generate.", ) beam_width: Optional[int] = Field( default=DEFAULT_BEAM_WIDTH, description="Last n number of tokens to penalize" ) repetition_penalty: Optional[float] = Field( default=DEFAULT_REPTITION_PENALTY, description="Last n number of tokens to penalize", ) length_penalty: Optional[float] = Field( default=DEFAULT_LENGTH_PENALTY, description="The penalty to apply repeated tokens", ) max_retries: Optional[int] = Field( default=DEFAULT_MAX_RETRIES, description="Maximum number of attempts to retry Triton client invocation before erroring", ) timeout: Optional[float] = Field( default=DEFAULT_TIMEOUT, description="Maximum time (seconds) allowed for a Triton client call before erroring", ) reuse_client: Optional[bool] = Field( default=DEFAULT_REUSE_CLIENT, description="True for reusing the same client instance between invocations", ) triton_load_model_call: Optional[bool] = Field( default=DEFAULT_TRITON_LOAD_MODEL, description="True if a Triton load model API call should be made before using the client", ) _client: Optional[GrpcTritonClient] = PrivateAttr() def __init__( self, server_url: str = DEFAULT_SERVER_URL, model: str = DEFAULT_MODEL, temperature: float = DEFAULT_TEMPERATURE, top_p: float = DEFAULT_TOP_P, top_k: float = DEFAULT_TOP_K, tokens: Optional[int] = DEFAULT_MAX_TOKENS, beam_width: int = DEFAULT_BEAM_WIDTH, repetition_penalty: float = DEFAULT_REPTITION_PENALTY, length_penalty: float = DEFAULT_LENGTH_PENALTY, max_retries: int = DEFAULT_MAX_RETRIES, timeout: float = DEFAULT_TIMEOUT, reuse_client: bool = DEFAULT_REUSE_CLIENT, triton_load_model_call: bool = DEFAULT_TRITON_LOAD_MODEL, callback_manager: Optional[CallbackManager] = None, additional_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any, ) -> None: additional_kwargs = additional_kwargs or {} super().__init__( server_url=server_url, model=model, temperature=temperature, top_p=top_p, top_k=top_k, tokens=tokens, beam_width=beam_width, repetition_penalty=repetition_penalty, length_penalty=length_penalty, max_retries=max_retries, timeout=timeout, reuse_client=reuse_client, triton_load_model_call=triton_load_model_call, callback_manager=callback_manager, additional_kwargs=additional_kwargs, **kwargs, ) try: self._client = GrpcTritonClient(server_url) except ImportError as err: raise ImportError( "Could not import triton client python package. " "Please install it with `pip install tritonclient`." ) from err @property def _get_model_default_parameters(self) -> Dict[str, Any]: return { "tokens": self.tokens, "top_k": self.top_k, "top_p": self.top_p, "temperature": self.temperature, "repetition_penalty": self.repetition_penalty, "length_penalty": self.length_penalty, "beam_width": self.beam_width, } @property def _invocation_params(self, **kwargs: Any) -> Dict[str, Any]: return {**self._get_model_default_parameters, **kwargs} @property def _identifying_params(self) -> Dict[str, Any]: """Get all the identifying parameters.""" return { "server_url": self.server_url, "model_name": self.model_name, } def _get_client(self) -> Any: """Create or reuse a Triton client connection.""" if not self.reuse_client: return GrpcTritonClient(self.server_url) if self._client is None: self._client = GrpcTritonClient(self.server_url) return self._client @property def metadata(self) -> LLMMetadata: """Gather and return metadata about the user Triton configured LLM model.""" return LLMMetadata( model_name=self.model_name, ) @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: chat_fn = completion_to_chat_decorator(self.complete) return chat_fn(messages, **kwargs) @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: chat_stream_fn = stream_completion_to_chat_decorator(self.stream_complete) return chat_stream_fn(messages, **kwargs) def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: from tritonclient.utils import InferenceServerException client = self._get_client() invocation_params = self._get_model_default_parameters invocation_params.update(kwargs) invocation_params["prompt"] = [[prompt]] model_params = self._identifying_params model_params.update(kwargs) request_id = str(random.randint(1, 9999999)) # nosec if self.triton_load_model_call: client.load_model(model_params["model_name"]) result_queue = client.request_streaming( model_params["model_name"], request_id, **invocation_params ) response = "" for token in result_queue: if isinstance(token, InferenceServerException): client.stop_stream(model_params["model_name"], request_id) raise token response += token return CompletionResponse( text=response, ) def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: from tritonclient.utils import InferenceServerException client = self._get_client() invocation_params = self._get_model_default_parameters invocation_params.update(kwargs) invocation_params["prompt"] = [[prompt]] model_params = self._identifying_params model_params.update(kwargs) request_id = str(random.randint(1, 9999999)) # nosec if self.triton_load_model_call: client.load_model(model_params["model_name"]) result_queue = client.request_streaming( model_params["model_name"], request_id, **invocation_params ) def gen() -> CompletionResponseGen: text = "" for token in result_queue: if isinstance(token, InferenceServerException): client.stop_stream(model_params["model_name"], request_id) raise token text += token yield CompletionResponse(text=text, delta=token) return gen() async def achat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponse: raise NotImplementedError async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: raise NotImplementedError async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: raise NotImplementedError async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: raise NotImplementedError
NvidiaTriton
python
pandas-dev__pandas
asv_bench/benchmarks/hash_functions.py
{ "start": 251, "end": 576 }
class ____: # GH28303 def setup(self): self.df = pd.date_range( start="1/1/2018", end="1/2/2018", periods=10**6 ).to_frame() self.group_index = np.round(self.df.index.astype(int) / 10**9) def time_groupby(self): self.df.groupby(self.group_index).last()
Float64GroupIndex
python
prabhupant__python-ds
data_structures/graphs/bellman_ford.py
{ "start": 1017, "end": 1161 }
class ____: def __init__(self, source, dest, weight): self.source = source self.dest = dest self.weight = weight
Edge
python
gevent__gevent
src/gevent/_config.py
{ "start": 13807, "end": 14847 }
class ____(BoolSettingMixin, Setting): name = 'monitor_thread' environment_key = 'GEVENT_MONITOR_THREAD_ENABLE' default = False desc = """\ Should each hub start a native OS thread to monitor for problems? Such a thread will periodically check to see if the event loop is blocked for longer than `max_blocking_time`, producing output on the hub's exception stream (stderr by default) if it detects this condition. If this setting is true, then this thread will be created the first time the hub is switched to, or you can call :meth:`gevent.hub.Hub.start_periodic_monitoring_thread` at any time to create it (from the same thread that will run the hub). That function will return an instance of :class:`gevent.events.IPeriodicMonitorThread` to which you can add your own monitoring functions. That function also emits an event of :class:`gevent.events.PeriodicMonitorThreadStartedEvent`. .. seealso:: `max_blocking_time` .. versionadded:: 1.3b1 """
MonitorThread
python
spack__spack
lib/spack/spack/config.py
{ "start": 4723, "end": 7340 }
class ____: def __init__(self, name: str) -> None: self.name = name self.writable = False self.sections = syaml.syaml_dict() self.prefer_modify = False #: names of any included scopes self._included_scopes: Optional[List["ConfigScope"]] = None @property def included_scopes(self) -> List["ConfigScope"]: """Memoized list of included scopes, in the order they appear in this scope.""" if self._included_scopes is None: self._included_scopes = [] includes = self.get_section("include") if includes: include_paths = [included_path(data) for data in includes["include"]] included_scopes = chain(*[include.scopes(self) for include in include_paths]) # Do not include duplicate scopes for included_scope in included_scopes: if any([included_scope.name == scope.name for scope in self._included_scopes]): tty.warn(f"Ignoring duplicate included scope: {included_scope.name}") continue if included_scope not in self._included_scopes: self._included_scopes.append(included_scope) return self._included_scopes def override_include(self): """Whether the ``include::`` section of this scope should override lower scopes.""" include = self.sections.get("include") if not include: return False # override if this has an include section and there is an override attribute on # the include key in the dict and it is set to True. return getattr(next(iter(include.keys()), None), "override", False) def transitive_includes(self, _names: Optional[Set[str]] = None) -> Set[str]: """Get name of this scope and names of its transitively included scopes.""" if _names is None: _names = _set() _names.add(self.name) for scope in self.included_scopes: _names |= scope.transitive_includes(_names=_names) return _names def get_section_filename(self, section: str) -> str: raise NotImplementedError def get_section(self, section: str) -> Optional[YamlConfigDict]: raise NotImplementedError def _write_section(self, section: str) -> None: raise NotImplementedError def clear(self) -> None: """Empty cached config information.""" self.sections = syaml.syaml_dict() def __repr__(self) -> str: return f"<ConfigScope: {self.name}>"
ConfigScope
python
plotly__plotly.py
plotly/callbacks.py
{ "start": 4595, "end": 5459 }
class ____: def __init__(self, xrange=None, yrange=None, **_): self._type = "box" self._xrange = xrange self._yrange = yrange def __repr__(self): return """\ BoxSelector(xrange={xrange}, yrange={yrange})""".format(xrange=self.xrange, yrange=self.yrange) @property def type(self): """ The selector's type Returns ------- str """ return self._type @property def xrange(self): """ x-axis range extents of the box selection Returns ------- (float, float) """ return self._xrange @property def yrange(self): """ y-axis range extents of the box selection Returns ------- (float, float) """ return self._yrange
BoxSelector
python
dask__distributed
distributed/utils.py
{ "start": 23055, "end": 34809 }
class ____: __slots__ = ("pdb", "unroll_stack") pdb: bool unroll_stack: int def __init__(self, pdb: bool, unroll_stack: int): self.pdb = pdb self.unroll_stack = unroll_stack def __call__(self, func: Callable[P, T], /) -> Callable[P, T]: self.unroll_stack += 1 if inspect.iscoroutinefunction(func): async def wrapper(*args, **kwargs): with self: return await func(*args, **kwargs) else: def wrapper(*args, **kwargs): with self: return func(*args, **kwargs) return wraps(func)(wrapper) def __enter__(self): return self def __exit__(self, exc_type, exc_value, tb): from distributed.comm import CommClosedError if not exc_type or issubclass(exc_type, (CommClosedError, gen.Return)): return stack = traceback.extract_tb(tb) frame = stack[min(self.unroll_stack, len(stack) - 1)] modname = _getmodulename_with_path(frame.filename) try: logger = logging.getLogger(modname) logger.exception(exc_value) except Exception: # Interpreter teardown pass # pragma: nocover if self.pdb: import pdb # pragma: nocover pdb.set_trace() # pragma: nocover def silence_logging(level, root="distributed"): """ Change all StreamHandlers for the given logger to the given level """ warnings.warn( "silence_logging is deprecated, call silence_logging_cmgr", DeprecationWarning, stacklevel=2, ) if isinstance(level, str): level = getattr(logging, level.upper()) old = None logger = logging.getLogger(root) for handler in logger.handlers: if isinstance(handler, logging.StreamHandler): old = handler.level handler.setLevel(level) return old @contextlib.contextmanager def silence_logging_cmgr( level: str | int, root: str = "distributed" ) -> Generator[None]: """ Temporarily change all StreamHandlers for the given logger to the given level """ if isinstance(level, str): level = getattr(logging, level.upper()) logger = logging.getLogger(root) with contextlib.ExitStack() as stack: for handler in logger.handlers: if isinstance(handler, logging.StreamHandler): old = handler.level if old != level: handler.setLevel(level) stack.callback(handler.setLevel, old) yield @toolz.memoize def ensure_ip(hostname): """Ensure that address is an IP address Examples -------- >>> ensure_ip('localhost') '127.0.0.1' >>> ensure_ip('') # Maps as localhost for binding e.g. 'tcp://:8811' '127.0.0.1' >>> ensure_ip('123.123.123.123') # pass through IP addresses '123.123.123.123' """ if not hostname: hostname = "localhost" # Prefer IPv4 over IPv6, for compatibility families = [socket.AF_INET, socket.AF_INET6] for fam in families: try: results = socket.getaddrinfo( hostname, 1234, fam, socket.SOCK_STREAM # dummy port number ) except socket.gaierror as e: exc = e else: return results[0][4][0] raise exc tblib.pickling_support.install() def get_traceback(): exc_type, exc_value, exc_traceback = sys.exc_info() bad = [ os.path.join("distributed", "worker"), os.path.join("distributed", "scheduler"), os.path.join("tornado", "gen.py"), os.path.join("concurrent", "futures"), os.path.join("dask", "_task_spec"), ] while exc_traceback and any( b in exc_traceback.tb_frame.f_code.co_filename for b in bad ): exc_traceback = exc_traceback.tb_next return exc_traceback def truncate_exception(e, n=10000): """Truncate exception to be about a certain length""" if len(str(e)) > n: try: return type(e)("Long error message", str(e)[:n]) except Exception: return Exception("Long error message", type(e), str(e)[:n]) else: return e def seek_delimiter(file, delimiter, blocksize): """Seek current file to next byte after a delimiter bytestring This seeks the file to the next byte following the delimiter. It does not return anything. Use ``file.tell()`` to see location afterwards. Parameters ---------- file: a file delimiter: bytes a delimiter like ``b'\n'`` or message sentinel blocksize: int Number of bytes to read from the file at once. """ if file.tell() == 0: return last = b"" while True: current = file.read(blocksize) if not current: return full = last + current try: i = full.index(delimiter) file.seek(file.tell() - (len(full) - i) + len(delimiter)) return except ValueError: pass last = full[-len(delimiter) :] def read_block(f, offset, length, delimiter=None): """Read a block of bytes from a file Parameters ---------- f: file File-like object supporting seek, read, tell, etc.. offset: int Byte offset to start read length: int Number of bytes to read delimiter: bytes (optional) Ensure reading starts and stops at delimiter bytestring If using the ``delimiter=`` keyword argument we ensure that the read starts and stops at delimiter boundaries that follow the locations ``offset`` and ``offset + length``. If ``offset`` is zero then we start at zero. The bytestring returned WILL include the terminating delimiter string. Examples -------- >>> from io import BytesIO # doctest: +SKIP >>> f = BytesIO(b'Alice, 100\\nBob, 200\\nCharlie, 300') # doctest: +SKIP >>> read_block(f, 0, 13) # doctest: +SKIP b'Alice, 100\\nBo' >>> read_block(f, 0, 13, delimiter=b'\\n') # doctest: +SKIP b'Alice, 100\\nBob, 200\\n' >>> read_block(f, 10, 10, delimiter=b'\\n') # doctest: +SKIP b'Bob, 200\\nCharlie, 300' """ if delimiter: f.seek(offset) seek_delimiter(f, delimiter, 2**16) start = f.tell() length -= start - offset f.seek(start + length) seek_delimiter(f, delimiter, 2**16) end = f.tell() offset = start length = end - start f.seek(offset) bytes = f.read(length) return bytes def ensure_bytes(s): """Attempt to turn `s` into bytes. Parameters ---------- s : Any The object to be converted. Will correctly handled * str * bytes * objects implementing the buffer protocol (memoryview, ndarray, etc.) Returns ------- b : bytes Raises ------ TypeError When `s` cannot be converted Examples -------- >>> ensure_bytes('123') b'123' >>> ensure_bytes(b'123') b'123' """ warnings.warn( "`distributed.utils.ensure_bytes` is deprecated. " "Please switch to `dask.utils.ensure_bytes`. " "This will be removed in `2022.6.0`.", DeprecationWarning, stacklevel=2, ) return _ensure_bytes(s) def ensure_memoryview(obj: bytes | bytearray | memoryview | PickleBuffer) -> memoryview: """Ensure `obj` is a 1-D contiguous `uint8` `memoryview`""" if not isinstance(obj, memoryview): obj = memoryview(obj) if not obj.nbytes: # Drop `obj` reference to permit freeing underlying data return memoryview(bytearray()) elif not obj.contiguous: # Copy to contiguous form of expected shape & type return memoryview(bytearray(obj)) elif obj.ndim != 1 or obj.format != "B": # Perform zero-copy reshape & cast # Use `PickleBuffer.raw()` as `memoryview.cast()` fails with F-order # xref: https://github.com/python/cpython/issues/91484 return PickleBuffer(obj).raw() else: # Return `memoryview` as it already meets requirements return obj def open_port(host: str = "") -> int: """Return a probably-open port There is a chance that this port will be taken by the operating system soon after returning from this function. """ # http://stackoverflow.com/questions/2838244/get-open-tcp-port-in-python with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((host, 0)) s.listen(1) port = s.getsockname()[1] return port def import_file(path: str) -> list[ModuleType]: """Loads modules for a file (.py, .zip, .egg)""" directory, filename = os.path.split(path) name, ext = os.path.splitext(filename) names_to_import: list[str] = [] tmp_python_path: str | None = None if ext in (".py",): # , '.pyc'): if directory not in sys.path: tmp_python_path = directory names_to_import.append(name) if ext == ".py": # Ensure that no pyc file will be reused cache_file = cache_from_source(path) with contextlib.suppress(OSError): os.remove(cache_file) if ext in (".egg", ".zip", ".pyz"): if path not in sys.path: sys.path.insert(0, path) names = (mod_info.name for mod_info in pkgutil.iter_modules([path])) names_to_import.extend(names) loaded: list[ModuleType] = [] if not names_to_import: logger.warning("Found nothing to import from %s", filename) else: importlib.invalidate_caches() if tmp_python_path is not None: sys.path.insert(0, tmp_python_path) try: for name in names_to_import: logger.info("Reload module %s from %s file", name, ext) loaded.append(importlib.reload(importlib.import_module(name))) finally: if tmp_python_path is not None: sys.path.remove(tmp_python_path) return loaded def asciitable(columns, rows): """Formats an ascii table for given columns and rows. Parameters ---------- columns : list The column names rows : list of tuples The rows in the table. Each tuple must be the same length as ``columns``. """ rows = [tuple(str(i) for i in r) for r in rows] columns = tuple(str(i) for i in columns) widths = tuple(max(max(map(len, x)), len(c)) for x, c in zip(zip(*rows), columns)) row_template = ("|" + (" %%-%ds |" * len(columns))) % widths header = row_template % tuple(columns) bar = "+%s+" % "+".join("-" * (w + 2) for w in widths) data = "\n".join(row_template % r for r in rows) return "\n".join([bar, header, bar, data, bar]) def nbytes(frame, _bytes_like=(bytes, bytearray)): """Number of bytes of a frame or memoryview""" if isinstance(frame, _bytes_like): return len(frame) else: try: return frame.nbytes except AttributeError: return len(frame) def json_load_robust(fn, load=json.load, timeout=None): """Reads a JSON file from disk that may be being written as we read""" deadline = Deadline.after(timeout) while not deadline.expires or deadline.remaining: if os.path.exists(fn): try: with open(fn) as f: cfg = load(f) if cfg: return cfg except (ValueError, KeyError): # race with writing process pass sleep(0.1) else: raise TimeoutError(f"Could not load file after {timeout}s.")
_LogErrors
python
google__jax
jax/experimental/mosaic/gpu/utils.py
{ "start": 38880, "end": 42398 }
class ____: barrier: BarrierRef cluster_mask: ir.Value | None @staticmethod def initialize( barrier_memref: ir.Value, arrival_count: int, dims: Sequence[gpu.Dimension | Sequence[gpu.Dimension]], cluster_shape: tuple[int, int, int], ) -> "CollectiveBarrierRef": i32 = ir.IntegerType.get_signless(32) # With the exception of the current device, each pair of slices along # collective dims is disjoint. Since the current device is overcounted, # we must decrease the arrival count a little. dims_shape = [ cluster_shape[d] if isinstance(d, gpu.Dimension) else math.prod(cluster_shape[dd] for dd in d) for d in dims ] cluster_arrival_count = sum(dims_shape) - len(dims) + 1 if cluster_arrival_count == 1: assert all(s == 1 for s in dims_shape) cluster_mask = None else: cluster_mask = c(0, i32) for d, size in zip(dims, dims_shape): if size == 1: # Only the current device is in this mask, but it will also be # present in one of the non-trivial cluster dims. continue cluster_mask = arith.ori( cluster_mask, cluster_collective_mask(cluster_shape, d) ) barrier = BarrierRef.initialize( barrier_memref, arrival_count=arrival_count * cluster_arrival_count ) return CollectiveBarrierRef(barrier, cluster_mask) def __iter__(self): for b in self.barrier: yield CollectiveBarrierRef(b, self.cluster_mask) def __getitem__(self, offset): return CollectiveBarrierRef(self.barrier[offset], self.cluster_mask) def arrive(self, orders_tensor_core: bool = False): """Arrives on a barrier in all blocks that share at least one of the coordinates along the collective dimensions. Note that unlike in arrive, each warpgroup arrives once. """ if orders_tensor_core: llvm.inline_asm( ir.Type.parse("!llvm.void"), [], "tcgen05.fence::before_thread_sync;", "", has_side_effects=True, ) if self.barrier.num_barriers != 1: raise ValueError("Can only arrive on a single barrier") if self.cluster_mask is None: with single_thread(scope=ThreadSubset.WARPGROUP): self.barrier.arrive() return i32 = ir.IntegerType.get_signless(32) thread_in_warpgroup = arith.remui(thread_idx(), c(WARPGROUP_SIZE, i32)) signaled_block = arith.divui( thread_in_warpgroup, c(WARPGROUP_SIZE // 16, i32) ) is_collective_block = arith.cmpi( arith.CmpIPredicate.ne, arith.andi(self.cluster_mask, arith.shli(c(1, i32), signaled_block)), c(0, i32), ) is_signaling_thread = arith.cmpi( arith.CmpIPredicate.eq, arith.remui(thread_in_warpgroup, c(WARPGROUP_SIZE // 16, i32)), c(0, i32), ) should_arrive = arith.andi(is_collective_block, is_signaling_thread) llvm.inline_asm( ir.Type.parse("!llvm.void"), [should_arrive, self.barrier.get_ptr(), signaled_block], """ { .reg .b32 mapped_addr; @$0 mapa.shared::cluster.u32 mapped_addr, $1, $2; @$0 mbarrier.arrive.shared::cluster.b64 _, [mapped_addr]; }""", "b,r,r", has_side_effects=True, ) def wait(self, *args, **kwargs): self.barrier.wait(*args, **kwargs) def wait_parity(self, *args, **kwargs): self.barrier.wait_parity(*args, **kwargs) @dataclasses.dataclass(frozen=True)
CollectiveBarrierRef
python
getsentry__sentry
tests/sentry/replays/endpoints/test_organization_selector_index.py
{ "start": 260, "end": 10176 }
class ____(APITestCase, ReplaysSnubaTestCase): endpoint = "sentry-api-0-organization-replay-selectors-index" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) self.url = reverse(self.endpoint, args=(self.organization.slug,)) def test_feature_flag_disabled(self) -> None: """Test replays can be disabled.""" response = self.client.get(self.url) assert response.status_code == 404 def test_no_projects(self) -> None: """Test replays must be used with a project(s).""" with self.feature(REPLAYS_FEATURES): response = self.client.get(self.url) assert response.status_code == 200 response_data = response.json() assert "data" in response_data assert response_data["data"] == [] def test_get_replays(self) -> None: """Test replays conform to the interchange format.""" project = self.create_project(teams=[self.team]) replay_id = uuid.uuid4().hex seq1_timestamp = datetime.datetime.now() - datetime.timedelta(seconds=22) seq2_timestamp = datetime.datetime.now() - datetime.timedelta(seconds=5) self.store_replays(mock_replay(seq1_timestamp, project.id, replay_id)) self.store_replays(mock_replay(seq2_timestamp, project.id, replay_id)) self.store_replays( mock_replay_click( seq2_timestamp, project.id, replay_id, node_id=1, tag="div", id="myid", class_=["class1", "class2"], role="button", testid="1", alt="Alt", aria_label="AriaLabel", title="MyTitle", is_dead=1, is_rage=1, text="Hello", component_name="SignUpForm", ) ) self.store_replays( mock_replay_click( seq2_timestamp, project.id, replay_id, node_id=1, tag="div", id="myid", class_=["class1", "class2", ""], role="button", testid="1", alt="Alt", aria_label="AriaLabel", title="MyTitle", is_dead=1, is_rage=0, text="Hello", component_name="SignUpForm", ) ) with self.feature(REPLAYS_FEATURES): response = self.client.get(self.url) assert response.status_code == 200 response_data = response.json() assert "data" in response_data assert len(response_data["data"]) == 1 assert response_data["data"][0]["project_id"] == project.id assert ( response_data["data"][0]["dom_element"] == 'div#myid.class1.class2[role="button"][alt="Alt"][testid="1"][aria="AriaLabel"][title="MyTitle"][component_name="SignUpForm"]' ) assert response_data["data"][0]["count_dead_clicks"] == 2 assert response_data["data"][0]["count_rage_clicks"] == 1 assert response_data["data"][0]["element"]["alt"] == "Alt" assert response_data["data"][0]["element"]["aria_label"] == "AriaLabel" assert response_data["data"][0]["element"]["class"] == ["class1", "class2"] assert response_data["data"][0]["element"]["id"] == "myid" assert response_data["data"][0]["element"]["role"] == "button" assert response_data["data"][0]["element"]["tag"] == "div" assert response_data["data"][0]["element"]["testid"] == "1" assert response_data["data"][0]["element"]["title"] == "MyTitle" assert response_data["data"][0]["element"]["component_name"] == "SignUpForm" def test_get_replays_filter_clicks(self) -> None: """Test replays conform to the interchange format.""" replay_id = uuid.uuid4().hex seq1_timestamp = datetime.datetime.now() - datetime.timedelta(seconds=22) seq2_timestamp = datetime.datetime.now() - datetime.timedelta(seconds=5) self.store_replays(mock_replay(seq1_timestamp, self.project.id, replay_id)) self.store_replays( mock_replay_click( seq2_timestamp, self.project.id, replay_id, node_id=1, tag="div", id="id1", class_=["class1", "class2"], role="button", testid="1", alt="Alt", aria_label="AriaLabel", title="MyTitle", text="Hello", component_name="SignUpForm", is_dead=True, is_rage=False, ) ) self.store_replays( mock_replay_click( seq2_timestamp, self.project.id, replay_id, node_id=1, tag="div", id="id1", class_=["class1", "class2"], role="button", testid="1", alt="Alt", aria_label="AriaLabel", title="MyTitle", text="Hello", component_name="SignUpForm", is_dead=True, is_rage=True, ) ) with self.feature(REPLAYS_FEATURES): queries = ["count_dead_clicks:2", "count_rage_clicks:1"] for query in queries: response = self.client.get(self.url + f"?query={query}") assert response.status_code == 200, query response_data = response.json() assert len(response_data["data"]) == 1, query queries = ["count_dead_clicks:1", "count_rage_clicks:2"] for query in queries: response = self.client.get(self.url + f"?query={query}") assert response.status_code == 200, query response_data = response.json() assert len(response_data["data"]) == 0, query def test_get_click_filter_environment(self) -> None: """Test that clicks can be filtered by environment.""" prod_env = self.create_environment(name="prod", project=self.project) dev_env = self.create_environment(name="dev", project=self.project) staging_env = self.create_environment(name="staging", project=self.project) timestamp = datetime.datetime.now() - datetime.timedelta(hours=1) replay_id_prod = uuid.uuid4().hex replay_id_dev = uuid.uuid4().hex replay_id_staging = uuid.uuid4().hex self.store_replays( mock_replay(timestamp, self.project.id, replay_id_prod, environment=prod_env.name) ) self.store_replays( mock_replay_click( timestamp, self.project.id, replay_id_prod, environment=prod_env.name, node_id=1, tag="div", id="myid", class_=["class1"], is_dead=True, is_rage=False, ) ) self.store_replays( mock_replay(timestamp, self.project.id, replay_id_dev, environment=dev_env.name) ) self.store_replays( mock_replay_click( timestamp, self.project.id, replay_id_dev, environment=dev_env.name, node_id=1, tag="div", id="myid", class_=["class1"], is_dead=True, is_rage=True, ) ) self.store_replays( mock_replay(timestamp, self.project.id, replay_id_staging, environment=staging_env.name) ) self.store_replays( mock_replay_click( timestamp, self.project.id, replay_id_staging, environment=staging_env.name, node_id=1, tag="div", id="myid", class_=["class1"], is_dead=True, is_rage=False, ) ) with self.feature(REPLAYS_FEATURES): # Test single environment response = self.client.get(self.url + f"?environment={prod_env.name}") assert response.status_code == 200 response_data = response.json() assert len(response_data["data"]) == 1 assert response_data["data"][0]["count_dead_clicks"] == 1 assert response_data["data"][0]["count_rage_clicks"] == 0 # Test multiple environments response = self.client.get( self.url + f"?environment={prod_env.name}&environment={dev_env.name}" ) assert response.status_code == 200 response_data = response.json() assert len(response_data["data"]) == 1 assert response_data["data"][0]["count_dead_clicks"] == 2 assert response_data["data"][0]["count_rage_clicks"] == 1 # Test all environments response = self.client.get(self.url) assert response.status_code == 200 response_data = response.json() assert len(response_data["data"]) == 1 assert response_data["data"][0]["count_dead_clicks"] == 3 assert response_data["data"][0]["count_rage_clicks"] == 1 # Test non-existent environment response = self.client.get(self.url + "?environment=nonexistent") assert response.status_code == 404
OrganizationSelectorIndexTest
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/roots/mutation.py
{ "start": 26719, "end": 27109 }
class ____(graphene.Union): """The output from deleting asset history.""" class Meta: types = ( GrapheneAssetNotFoundError, GrapheneUnauthorizedError, GraphenePythonError, GrapheneUnsupportedOperationError, GrapheneAssetWipeSuccess, ) name = "AssetWipeMutationResult"
GrapheneAssetWipeMutationResult
python
langchain-ai__langchain
libs/langchain/langchain_classic/smith/evaluation/runner_utils.py
{ "start": 2250, "end": 2360 }
class ____(Exception): """Raised when the input format is invalid.""" ## Shared Utilities
InputFormatError
python
numpy__numpy
numpy/_core/tests/test_multiarray.py
{ "start": 153364, "end": 153538 }
class ____: def test_array_contains(self): assert_(4.0 in np.arange(16.).reshape(4, 4)) assert_(20.0 not in np.arange(16.).reshape(4, 4))
TestCequenceMethods
python
django__django
tests/model_regress/tests.py
{ "start": 485, "end": 8828 }
class ____(TestCase): def test_model_init_too_many_args(self): msg = "Number of args exceeds number of fields" with self.assertRaisesMessage(IndexError, msg): Worker(1, 2, 3, 4) # The bug is that the following queries would raise: # "TypeError: Related Field has invalid lookup: gte" def test_related_gte_lookup(self): """ Regression test for #10153: foreign key __gte lookups. """ Worker.objects.filter(department__gte=0) def test_related_lte_lookup(self): """ Regression test for #10153: foreign key __lte lookups. """ Worker.objects.filter(department__lte=0) def test_sql_insert_compiler_return_id_attribute(self): """ Regression test for #14019: SQLInsertCompiler.as_sql() failure """ db = router.db_for_write(Party) query = InsertQuery(Party) query.insert_values([Party._meta.fields[0]], [], raw=False) # this line will raise an AttributeError without the accompanying fix query.get_compiler(using=db).as_sql() def test_empty_choice(self): # NOTE: Part of the regression test here is merely parsing the model # declaration. The verbose_name, in particular, did not always work. a = Article.objects.create( headline="Look at me!", pub_date=datetime.datetime.now() ) # An empty choice field should return None for the display name. self.assertIs(a.get_status_display(), None) # Empty strings should be returned as string a = Article.objects.get(pk=a.pk) self.assertEqual(a.misc_data, "") def test_long_textfield(self): # TextFields can hold more than 4000 characters (this was broken in # Oracle). a = Article.objects.create( headline="Really, really big", pub_date=datetime.datetime.now(), article_text="ABCDE" * 1000, ) a = Article.objects.get(pk=a.pk) self.assertEqual(len(a.article_text), 5000) def test_long_unicode_textfield(self): # TextFields can hold more than 4000 bytes also when they are # less than 4000 characters a = Article.objects.create( headline="Really, really big", pub_date=datetime.datetime.now(), article_text="\u05d0\u05d1\u05d2" * 1000, ) a = Article.objects.get(pk=a.pk) self.assertEqual(len(a.article_text), 3000) def test_date_lookup(self): # Regression test for #659 Party.objects.create(when=datetime.datetime(1999, 12, 31)) Party.objects.create(when=datetime.datetime(1998, 12, 31)) Party.objects.create(when=datetime.datetime(1999, 1, 1)) Party.objects.create(when=datetime.datetime(1, 3, 3)) self.assertQuerySetEqual(Party.objects.filter(when__month=2), []) self.assertQuerySetEqual( Party.objects.filter(when__month=1), [datetime.date(1999, 1, 1)], attrgetter("when"), ) self.assertQuerySetEqual( Party.objects.filter(when__month=12), [ datetime.date(1999, 12, 31), datetime.date(1998, 12, 31), ], attrgetter("when"), ordered=False, ) self.assertQuerySetEqual( Party.objects.filter(when__year=1998), [ datetime.date(1998, 12, 31), ], attrgetter("when"), ) # Regression test for #8510 self.assertQuerySetEqual( Party.objects.filter(when__day="31"), [ datetime.date(1999, 12, 31), datetime.date(1998, 12, 31), ], attrgetter("when"), ordered=False, ) self.assertQuerySetEqual( Party.objects.filter(when__month="12"), [ datetime.date(1999, 12, 31), datetime.date(1998, 12, 31), ], attrgetter("when"), ordered=False, ) self.assertQuerySetEqual( Party.objects.filter(when__year="1998"), [ datetime.date(1998, 12, 31), ], attrgetter("when"), ) # Regression test for #18969 self.assertQuerySetEqual( Party.objects.filter(when__year=1), [ datetime.date(1, 3, 3), ], attrgetter("when"), ) self.assertQuerySetEqual( Party.objects.filter(when__year="1"), [ datetime.date(1, 3, 3), ], attrgetter("when"), ) def test_date_filter_null(self): # Date filtering was failing with NULL date values in SQLite # (regression test for #3501, among other things). Party.objects.create(when=datetime.datetime(1999, 1, 1)) Party.objects.create() p = Party.objects.filter(when__month=1)[0] self.assertEqual(p.when, datetime.date(1999, 1, 1)) self.assertQuerySetEqual( Party.objects.filter(pk=p.pk).dates("when", "month"), [1], attrgetter("month"), ) def test_get_next_prev_by_field(self): # get_next_by_FIELD() and get_previous_by_FIELD() don't crash when # microseconds values are stored in the database. Event.objects.create(when=datetime.datetime(2000, 1, 1, 16, 0, 0)) Event.objects.create(when=datetime.datetime(2000, 1, 1, 6, 1, 1)) Event.objects.create(when=datetime.datetime(2000, 1, 1, 13, 1, 1)) e = Event.objects.create(when=datetime.datetime(2000, 1, 1, 12, 0, 20, 24)) self.assertEqual( e.get_next_by_when().when, datetime.datetime(2000, 1, 1, 13, 1, 1) ) self.assertEqual( e.get_previous_by_when().when, datetime.datetime(2000, 1, 1, 6, 1, 1) ) def test_get_next_prev_by_field_unsaved(self): msg = "get_next/get_previous cannot be used on unsaved objects." with self.assertRaisesMessage(ValueError, msg): Event().get_next_by_when() with self.assertRaisesMessage(ValueError, msg): Event().get_previous_by_when() def test_primary_key_foreign_key_types(self): # Check Department and Worker (non-default PK type) d = Department.objects.create(id=10, name="IT") w = Worker.objects.create(department=d, name="Full-time") self.assertEqual(str(w), "Full-time") @skipUnlessDBFeature("supports_timezones") def test_timezones(self): # Saving and updating with timezone-aware datetime Python objects. # Regression test for #10443. # The idea is that all these creations and saving should work without # crashing. It's not rocket science. dt1 = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=get_fixed_timezone(600)) dt2 = datetime.datetime(2008, 8, 31, 17, 20, tzinfo=get_fixed_timezone(600)) obj = Article.objects.create( headline="A headline", pub_date=dt1, article_text="foo" ) obj.pub_date = dt2 obj.save() self.assertEqual( Article.objects.filter(headline="A headline").update(pub_date=dt1), 1 ) def test_chained_fks(self): """ Chained foreign keys with to_field produce incorrect query. """ m1 = Model1.objects.create(pkey=1000) m2 = Model2.objects.create(model1=m1) m3 = Model3.objects.create(model2=m2) # this is the actual test for #18432 m3 = Model3.objects.get(model2=1000) m3.model2 @isolate_apps("model_regress") def test_metaclass_can_access_attribute_dict(self): """ Model metaclasses have access to the class attribute dict in __init__() (#30254). """ class HorseBase(models.base.ModelBase): def __init__(cls, name, bases, attrs): super().__init__(name, bases, attrs) cls.horns = 1 if "magic" in attrs else 0 class Horse(models.Model, metaclass=HorseBase): name = models.CharField(max_length=255) magic = True self.assertEqual(Horse.horns, 1)
ModelTests
python
airbytehq__airbyte
airbyte-integrations/connectors/source-stripe/unit_tests/integration/pagination.py
{ "start": 169, "end": 325 }
class ____(PaginationStrategy): @staticmethod def update(response: Dict[str, Any]) -> None: response["has_more"] = True
StripePaginationStrategy
python
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/rich/syntax.py
{ "start": 7229, "end": 7577 }
class ____(NamedTuple): """ A range to highlight in a Syntax object. `start` and `end` are 2-integers tuples, where the first integer is the line number (starting from 1) and the second integer is the column index (starting from 0). """ style: StyleType start: SyntaxPosition end: SyntaxPosition
_SyntaxHighlightRange
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/string_conversion.py
{ "start": 968, "end": 1399 }
class ____: def __init__(self, value): self.value = value def __str__(self): return self.value def propagate_taint(): eval(f"{A(request.GET['tainted'])}") # noqa: P204 def not_propagate_taint(): eval(f"{A('not tainted')}") # noqa: P204 def multiple_targets_for_single_expression(x: Union[A, StrIsTainted]): # two targets: [A.__str__, StrIsTainted.__str__] eval(f"{x}") # noqa: P204
A
python
kamyu104__LeetCode-Solutions
Python/lexicographically-smallest-generated-string.py
{ "start": 1995, "end": 3850 }
class ____(object): def generateString(self, str1, str2): """ :type str1: str :type str2: str :rtype: str """ # Template: https://cp-algorithms.com/string/z-function.html def z_function(s): # Time: O(n), Space: O(n) z = [0]*len(s) l, r = 0, 0 for i in xrange(1, len(z)): if i <= r: z[i] = min(r-i+1, z[i-l]) while i+z[i] < len(z) and s[z[i]] == s[i+z[i]]: z[i] += 1 if i+z[i]-1 > r: l, r = i, i+z[i]-1 return z n, m = len(str1), len(str2) candidate = ['*']*(n+m-1) z = z_function(str2) prev = -m for i, x in enumerate(str1): if x != 'T': continue diff = i-prev if diff < m: if z[diff] == m-diff: candidate[prev+m:i+m] = str2[m-diff:] else: return "" else: candidate[i:i+m] = str2 prev = i result = list(str2)+['#']+candidate idxs = [] for i in xrange(m+1, len(result)): if result[i] == '*': result[i] = 'a' idxs.append(i) z = z_function(result) dq = collections.deque() i, j = m+1, 0 while i-(m+1) < n: while dq and dq[0] < i: dq.popleft() while j < len(idxs) and idxs[j] <= i+(m-1): dq.append(idxs[j]) j += 1 if str1[i-(m+1)] == 'F' and z[i] == m: if not dq: return "" result[dq[-1]] = 'b' i += m else: i += 1 return "".join(result[m+1:])
Solution2
python
astropy__astropy
astropy/io/votable/exceptions.py
{ "start": 19443, "end": 20075 }
class ____(VOTableSpecWarning): """ A ``DESCRIPTION`` element can only appear once within its parent element. According to the schema, it may only occur once (`1.1 <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__, `1.2 <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC58>`__) However, it is a `proposed extension <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:addesc>`__ to VOTable 1.2. """ message_template = "{} element contains more than one DESCRIPTION element" default_args = ("x",)
W17
python
gevent__gevent
src/gevent/tests/test__semaphore.py
{ "start": 12799, "end": 13756 }
class ____(greentest.TestCase): def test_fair_or_hangs(self): # If the lock isn't fair, this hangs, spinning between # the last two greenlets. # See https://github.com/gevent/gevent/issues/1487 sem = Semaphore() should_quit = [] keep_going1 = FirstG.spawn(acquire_then_spawn, sem, should_quit) keep_going2 = FirstG.spawn(acquire_then_spawn, sem, should_quit) exiting = LastG.spawn(acquire_then_exit, sem, should_quit) with self.assertRaises(gevent.exceptions.LoopExit): gevent.joinall([keep_going1, keep_going2, exiting]) self.assertTrue(exiting.dead, exiting) self.assertTrue(keep_going2.dead, keep_going2) self.assertFalse(keep_going1.dead, keep_going1) sem.release() keep_going1.kill() keep_going2.kill() exiting.kill() gevent.idle() if __name__ == '__main__': greentest.main()
TestSemaphoreFair
python
google__jax
jax/_src/lax/lax.py
{ "start": 72719, "end": 74494 }
class ____(enum.Enum): """Precision enum for lax matrix multiply related functions. The device-dependent `precision` argument to JAX functions generally controls the tradeoff between speed and accuracy for array computations on accelerator backends, (i.e. TPU and GPU). Has no impact on CPU backends. This only has an effect on float32 computations, and does not affect the input/output datatypes. Members are: DEFAULT: Fastest mode, but least accurate. On TPU: performs float32 computations in bfloat16. On GPU: uses tensorfloat32 if available (e.g. on A100 and H100 GPUs), otherwise standard float32 (e.g. on V100 GPUs). Aliases: ``'default'``, ``'fastest'``. HIGH: Slower but more accurate. On TPU: performs float32 computations in 3 bfloat16 passes. On GPU: uses tensorfloat32 where available, otherwise float32. Aliases: ``'high'``.. HIGHEST: Slowest but most accurate. On TPU: performs float32 computations in 6 bfloat16. Aliases: ``'highest'``. On GPU: uses float32. """ DEFAULT = 0 HIGH = 1 HIGHEST = 2 @classmethod def _missing_(cls, value: object) -> Precision | None: return _precision_strings.get(value) def __repr__(self) -> str: return f'{self.__class__.__name__}.{self.name}' def __str__(self) -> str: return self.name _precision_strings['highest'] = Precision.HIGHEST _precision_strings['float32'] = Precision.HIGHEST _precision_strings['high'] = Precision.HIGH _precision_strings['bfloat16_3x'] = Precision.HIGH _precision_strings['tensorfloat32'] = Precision.HIGH _precision_strings['default'] = Precision.DEFAULT _precision_strings['bfloat16'] = Precision.DEFAULT _precision_strings['fastest'] = Precision.DEFAULT _precision_strings[None] = Precision.DEFAULT
Precision
python
mitmproxy__pdoc
test/testdata/misc.py
{ "start": 6587, "end": 6698 }
class ____: class SubClass: pass def __init__(self, x: "SubClass"): print(x)
SubclassRef
python
huggingface__transformers
src/transformers/models/lfm2_vl/modeling_lfm2_vl.py
{ "start": 3273, "end": 3814 }
class ____(PreTrainedModel): config: Lfm2VlConfig base_model_prefix = "model" input_modalities = ("image", "text") supports_gradient_checkpointing = True _skip_keys_device_placement = "past_key_values" _supports_flash_attn = True _supports_sdpa = True _can_compile_fullgraph = False _supports_flex_attn = True _supports_attention_backend = True @dataclass @auto_docstring( custom_intro=""" Base class for Lfm2Vl causal language model (or autoregressive) outputs. """ )
Lfm2VlPreTrainedModel
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_ip_is_not_blacklisted.py
{ "start": 1861, "end": 4482 }
class ____(ColumnMapExpectation): """Expect IP address to not be on blacklists.""" # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "all_valid": [ "142.250.201.206", "213.181.199.17", "13.77.161.179", "140.82.121.4", "204.79.197.200", ], "some_other": [ "68.128.212.240", "213.181.199.17", "13.77.161.179", "140.82.121.4", "204.79.197.200", ], }, "tests": [ { "title": "basic_positive_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "all_valid"}, "out": { "success": True, }, }, { "title": "basic_negative_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "some_other", "mostly": 1}, "out": { "success": False, }, }, ], } ] # This is the id string of the Metric used by this Expectation. # For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above. map_metric = "column_values.ip_is_not_blacklisted" # This is a list of parameter names that can affect whether the Expectation evaluates to True or False success_keys = ("mostly",) # This dictionary contains default values for any parameters that should have default values default_kwarg_values = {} # This object contains metadata for display in the public Gallery library_metadata = { "maturity": "experimental", "tags": [ "hackathon-22", "experimental", "typed-entities", ], # Tags for this Expectation in the Gallery "contributors": [ # Github handles for all contributors to this Expectation. "@szecsip", # Don't forget to add your github handle here! ], "requirements": ["pydnsbl"], } if __name__ == "__main__": ExpectColumnValuesIpIsNotBlacklisted().print_diagnostic_checklist()
ExpectColumnValuesIpIsNotBlacklisted
python
run-llama__llama_index
llama-index-core/llama_index/core/evaluation/context_relevancy.py
{ "start": 2802, "end": 6717 }
class ____(BaseEvaluator): """ Context relevancy evaluator. Evaluates the relevancy of retrieved contexts to a query. This evaluator considers the query string and retrieved contexts. Args: raise_error(Optional[bool]): Whether to raise an error if the response is invalid. Defaults to False. eval_template(Optional[Union[str, BasePromptTemplate]]): The template to use for evaluation. refine_template(Optional[Union[str, BasePromptTemplate]]): The template to use for refinement. """ def __init__( self, llm: Optional[LLM] = None, raise_error: bool = False, eval_template: str | BasePromptTemplate | None = None, refine_template: str | BasePromptTemplate | None = None, score_threshold: float = _DEFAULT_SCORE_THRESHOLD, parser_function: Callable[ [str], Tuple[Optional[float], Optional[str]] ] = _default_parser_function, ) -> None: """Init params.""" from llama_index.core import Settings self._llm = llm or Settings.llm self._raise_error = raise_error self._eval_template: BasePromptTemplate if isinstance(eval_template, str): self._eval_template = PromptTemplate(eval_template) else: self._eval_template = eval_template or DEFAULT_EVAL_TEMPLATE self._refine_template: BasePromptTemplate if isinstance(refine_template, str): self._refine_template = PromptTemplate(refine_template) else: self._refine_template = refine_template or DEFAULT_REFINE_TEMPLATE self.parser_function = parser_function self.score_threshold = score_threshold def _get_prompts(self) -> PromptDictType: """Get prompts.""" return { "eval_template": self._eval_template, "refine_template": self._refine_template, } def _update_prompts(self, prompts: PromptDictType) -> None: """Update prompts.""" if "eval_template" in prompts: self._eval_template = prompts["eval_template"] if "refine_template" in prompts: self._refine_template = prompts["refine_template"] async def aevaluate( self, query: str | None = None, response: str | None = None, contexts: Sequence[str] | None = None, sleep_time_in_seconds: int = 0, **kwargs: Any, ) -> EvaluationResult: """Evaluate whether the contexts is relevant to the query.""" del kwargs # Unused del response # Unused if query is None or contexts is None: raise ValueError("Both query and contexts must be provided") docs = [Document(text=context) for context in contexts] index = SummaryIndex.from_documents(docs) await asyncio.sleep(sleep_time_in_seconds) query_engine = index.as_query_engine( llm=self._llm, text_qa_template=self._eval_template, refine_template=self._refine_template, ) response_obj = await query_engine.aquery(query) raw_response_txt = str(response_obj) score, reasoning = self.parser_function(raw_response_txt) invalid_result, invalid_reason = False, None if score is None and reasoning is None: if self._raise_error: raise ValueError("The response is invalid") invalid_result = True invalid_reason = "Unable to parse the output string." if score: score /= self.score_threshold return EvaluationResult( query=query, contexts=contexts, score=score, feedback=raw_response_txt, invalid_result=invalid_result, invalid_reason=invalid_reason, )
ContextRelevancyEvaluator
python
catalyst-team__catalyst
catalyst/contrib/optimizers/lamb.py
{ "start": 680, "end": 5493 }
class ____(Optimizer): """Implements Lamb algorithm. It has been proposed in `Training BERT in 76 minutes`_. .. _`Training BERT in 76 minutes`: https://arxiv.org/abs/1904.00962 """ def __init__( self, params, lr: Optional[float] = 1e-3, betas: Optional[Tuple[float, float]] = (0.9, 0.999), eps: Optional[float] = 1e-6, weight_decay: Optional[float] = 0.0, adam: Optional[bool] = False, ): """ Args: params: iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): learning rate (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) adam (bool, optional): always use trust ratio = 1, which turns this into Adam. Useful for comparison purposes. Raises: ValueError: if invalid learning rate, epsilon value or betas. """ if not 0.0 <= lr: raise ValueError(f"Invalid learning rate: {lr}") if not 0.0 <= eps: raise ValueError(f"Invalid epsilon value: {eps}") if not 0.0 <= betas[0] < 1.0: raise ValueError(f"Invalid beta parameter at index 0: {betas[0]}") if not 0.0 <= betas[1] < 1.0: raise ValueError(f"Invalid beta parameter at index 1: {betas[1]}") defaults = { "lr": lr, "betas": betas, "eps": eps, "weight_decay": weight_decay, } self.adam = adam super(Lamb, self).__init__(params, defaults) def step(self, closure: Optional[Callable] = None): """Makes optimizer step. Args: closure (callable, optional): A closure that reevaluates the model and returns the loss. Returns: computed loss Raises: RuntimeError: Lamb does not support sparse gradients """ loss = None if closure is not None: loss = closure() for group in self.param_groups: for p in group["params"]: if p.grad is None: continue grad = p.grad.data if grad.is_sparse: raise RuntimeError( "Lamb does not support sparse gradients, " "consider SparseAdam instad." ) state = self.state[p] # State initialization if len(state) == 0: state["step"] = 0 # Exponential moving average of gradient values state["exp_avg"] = torch.zeros_like(p.data) # Exponential moving average of squared gradient values state["exp_avg_sq"] = torch.zeros_like(p.data) exp_avg, exp_avg_sq = state["exp_avg"], state["exp_avg_sq"] beta1, beta2 = group["betas"] state["step"] += 1 # Decay the first and second moment # running average coefficient # m_t exp_avg.mul_(beta1).add_(1 - beta1, grad) # v_t exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad) # Paper v3 does not use debiasing. # bias_correction1 = 1 - beta1 ** state["step"] # bias_correction2 = 1 - beta2 ** state["step"] # Apply bias to lr to avoid broadcast. # * math.sqrt(bias_correction2) / bias_correction1 step_size = group["lr"] weight_norm = p.data.pow(2).sum().sqrt().clamp(0, 10) adam_step = exp_avg / exp_avg_sq.sqrt().add(group["eps"]) if group["weight_decay"] != 0: adam_step.add_(group["weight_decay"], p.data) adam_norm = adam_step.pow(2).sum().sqrt() if weight_norm == 0 or adam_norm == 0: trust_ratio = 1 else: trust_ratio = weight_norm / adam_norm state["weight_norm"] = weight_norm state["adam_norm"] = adam_norm state["trust_ratio"] = trust_ratio if self.adam: trust_ratio = 1 p.data.add_(-step_size * trust_ratio, adam_step) return loss __all__ = ["Lamb"]
Lamb