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
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_chartarea03.py
{ "start": 315, "end": 1735 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_chartarea03.xlsx") def test_create_file(self): """Test XlsxWriter chartarea properties.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "scatter"}) chart.axis_ids = [46210048, 46208512] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) chart.add_series( { "categories": "=Sheet1!$A$1:$A$5", "values": "=Sheet1!$B$1:$B$5", } ) chart.add_series( { "categories": "=Sheet1!$A$1:$A$5", "values": "=Sheet1!$C$1:$C$5", } ) chart.set_chartarea( {"border": {"dash_type": "round_dot"}, "fill": {"color": "#9999FF"}} ) chart.set_plotarea( {"border": {"dash_type": "square_dot"}, "fill": {"color": "#FFC000"}} ) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
pennersr__django-allauth
allauth/account/views.py
{ "start": 8004, "end": 8359 }
class ____(SignupView): template_name = "account/signup_by_passkey." + app_settings.TEMPLATE_EXTENSION def get_form_kwargs(self): ret = super().get_form_kwargs() ret["by_passkey"] = True return ret signup_by_passkey = SignupByPasskeyView.as_view() @method_decorator(login_not_required, name="dispatch")
SignupByPasskeyView
python
yandexdataschool__Practical_RL
week06_policy_based/atari_wrappers.py
{ "start": 417, "end": 1359 }
class ____(Wrapper): """Sets done flag to true when agent dies.""" def __init__(self, env): super().__init__(env) self.lives = 0 self.real_done = True def step(self, action): obs, reward, terminated, truncated, info = self.env.step(action) self.real_done = terminated or truncated info["real_done"] = self.real_done lives = self.env.unwrapped.ale.lives() if 0 < lives < self.lives: terminated = True self.lives = lives return obs, reward, terminated, truncated, info def reset(self, **kwargs): if self.real_done: obs, info = self.env.reset(**kwargs) else: obs, _, terminated, truncated, info = self.env.step(0) if terminated or truncated: obs, info = self.env.reset(**kwargs) self.lives = self.env.unwrapped.ale.lives() return obs, info
EpisodicLife
python
django__django
django/db/migrations/operations/models.py
{ "start": 31349, "end": 31505 }
class ____(Operation): option_name = "indexes" @cached_property def model_name_lower(self): return self.model_name.lower()
IndexOperation
python
networkx__networkx
networkx/utils/heaps.py
{ "start": 3216, "end": 8383 }
class ____(MinHeap): """A pairing heap.""" class _Node(MinHeap._Item): """A node in a pairing heap. A tree in a pairing heap is stored using the left-child, right-sibling representation. """ __slots__ = ("left", "next", "prev", "parent") def __init__(self, key, value): super().__init__(key, value) # The leftmost child. self.left = None # The next sibling. self.next = None # The previous sibling. self.prev = None # The parent. self.parent = None def __init__(self): """Initialize a pairing heap.""" super().__init__() self._root = None def min(self): if self._root is None: raise nx.NetworkXError("heap is empty.") return (self._root.key, self._root.value) def pop(self): if self._root is None: raise nx.NetworkXError("heap is empty.") min_node = self._root self._root = self._merge_children(self._root) del self._dict[min_node.key] return (min_node.key, min_node.value) def get(self, key, default=None): node = self._dict.get(key) return node.value if node is not None else default def insert(self, key, value, allow_increase=False): node = self._dict.get(key) root = self._root if node is not None: if value < node.value: node.value = value if node is not root and value < node.parent.value: self._cut(node) self._root = self._link(root, node) return True elif allow_increase and value > node.value: node.value = value child = self._merge_children(node) # Nonstandard step: Link the merged subtree with the root. See # below for the standard step. if child is not None: self._root = self._link(self._root, child) # Standard step: Perform a decrease followed by a pop as if the # value were the smallest in the heap. Then insert the new # value into the heap. # if node is not root: # self._cut(node) # if child is not None: # root = self._link(root, child) # self._root = self._link(root, node) # else: # self._root = (self._link(node, child) # if child is not None else node) return False else: # Insert a new key. node = self._Node(key, value) self._dict[key] = node self._root = self._link(root, node) if root is not None else node return True def _link(self, root, other): """Link two nodes, making the one with the smaller value the parent of the other. """ if other.value < root.value: root, other = other, root next = root.left other.next = next if next is not None: next.prev = other other.prev = None root.left = other other.parent = root return root def _merge_children(self, root): """Merge the subtrees of the root using the standard two-pass method. The resulting subtree is detached from the root. """ node = root.left root.left = None if node is not None: link = self._link # Pass 1: Merge pairs of consecutive subtrees from left to right. # At the end of the pass, only the prev pointers of the resulting # subtrees have meaningful values. The other pointers will be fixed # in pass 2. prev = None while True: next = node.next if next is None: node.prev = prev break next_next = next.next node = link(node, next) node.prev = prev prev = node if next_next is None: break node = next_next # Pass 2: Successively merge the subtrees produced by pass 1 from # right to left with the rightmost one. prev = node.prev while prev is not None: prev_prev = prev.prev node = link(prev, node) prev = prev_prev # Now node can become the new root. Its has no parent nor siblings. node.prev = None node.next = None node.parent = None return node def _cut(self, node): """Cut a node from its parent.""" prev = node.prev next = node.next if prev is not None: prev.next = next else: node.parent.left = next node.prev = None if next is not None: next.prev = prev node.next = None node.parent = None
PairingHeap
python
google__pytype
pytype_extensions/instrumentation_for_testing.py
{ "start": 1727, "end": 1905 }
class ____(Generic[_T]): def __init__(self, production_type: _T): pass def __call__(self, instrumented_type: Any) -> _T: return instrumented_type
SealAsProductionType
python
getsentry__sentry
src/sentry/preprod/api/validators.py
{ "start": 152, "end": 3007 }
class ____(serializers.Serializer[Any]): """Validator for preprod list builds endpoint parameters.""" app_id = serializers.CharField(required=False, help_text="Filter by app identifier") state = serializers.ChoiceField( choices=PreprodArtifact.ArtifactState.as_choices(), required=False, help_text="Filter by artifact state", ) build_version = serializers.CharField(required=False, help_text="Filter by build version") build_configuration = serializers.CharField( required=False, help_text="Filter by build configuration name" ) platform = serializers.ChoiceField( choices=[("ios", "iOS"), ("android", "Android"), ("macos", "macOS")], required=False, help_text="Filter by platform", ) release_version = serializers.CharField( required=False, help_text="Filter by release version (formats: 'app_id@version+build_number' or 'app_id@version')", ) query = serializers.CharField( max_length=100, required=False, help_text="General search across app name, app ID, build version, and commit SHA", ) per_page = serializers.IntegerField( default=25, min_value=1, max_value=100, required=False, help_text="Number of results per page", ) cursor = serializers.CharField(required=False, help_text="Cursor for pagination") def validate_state(self, value: str | None) -> int | None: """Convert state string to integer enum value.""" if value is None: return None # Get valid integer values and string names choices = PreprodArtifact.ArtifactState.as_choices() valid_int_values = [choice[0] for choice in choices] valid_str_names = [choice[1] for choice in choices] # Try to convert to int (handles numeric strings like "0", "1", etc.) try: state_int = int(value) if state_int in valid_int_values: return state_int except (ValueError, TypeError): pass # Check if it's a valid state name (like "uploading", "uploaded", etc.) try: index = valid_str_names.index(value) return valid_int_values[index] except ValueError: pass raise serializers.ValidationError(f"Invalid state: {value}") def validate_query(self, value: str | None) -> str | None: """Validate search query length.""" if value and len(value.strip()) > 100: raise serializers.ValidationError("Search term too long") return value.strip() if value else value def validate_platform(self, value: str | None) -> str | None: """Normalize platform value.""" if value: return value.lower() return value
PreprodListBuildsValidator
python
scipy__scipy
scipy/_lib/_docscrape.py
{ "start": 2677, "end": 18075 }
class ____(Mapping): """Parses a numpydoc string to an abstract representation Instances define a mapping from section title to structured data. """ sections = { "Signature": "", "Summary": [""], "Extended Summary": [], "Parameters": [], "Attributes": [], "Methods": [], "Returns": [], "Yields": [], "Receives": [], "Other Parameters": [], "Raises": [], "Warns": [], "Warnings": [], "See Also": [], "Notes": [], "References": "", "Examples": "", "index": {}, } def __init__(self, docstring, config=None): orig_docstring = docstring docstring = textwrap.dedent(docstring).split("\n") self._doc = Reader(docstring) self._parsed_data = copy.deepcopy(self.sections) try: self._parse() except ParseError as e: e.docstring = orig_docstring raise def __getitem__(self, key): return self._parsed_data[key] def __setitem__(self, key, val): if key not in self._parsed_data: self._error_location(f"Unknown section {key}", error=False) else: self._parsed_data[key] = val def __iter__(self): return iter(self._parsed_data) def __len__(self): return len(self._parsed_data) def _is_at_section(self): self._doc.seek_next_non_empty_line() if self._doc.eof(): return False l1 = self._doc.peek().strip() # e.g. Parameters if l1.startswith(".. index::"): return True l2 = self._doc.peek(1).strip() # ---------- or ========== if len(l2) >= 3 and (set(l2) in ({"-"}, {"="})) and len(l2) != len(l1): snip = "\n".join(self._doc._str[:2]) + "..." self._error_location( f"potentially wrong underline length... \n{l1} \n{l2} in \n{snip}", error=False, ) return l2.startswith("-" * len(l1)) or l2.startswith("=" * len(l1)) def _strip(self, doc): i = 0 j = 0 for i, line in enumerate(doc): if line.strip(): break for j, line in enumerate(doc[::-1]): if line.strip(): break return doc[i : len(doc) - j] def _read_to_next_section(self): section = self._doc.read_to_next_empty_line() while not self._is_at_section() and not self._doc.eof(): if not self._doc.peek(-1).strip(): # previous line was empty section += [""] section += self._doc.read_to_next_empty_line() return section def _read_sections(self): while not self._doc.eof(): data = self._read_to_next_section() name = data[0].strip() if name.startswith(".."): # index section yield name, data[1:] elif len(data) < 2: yield StopIteration else: yield name, self._strip(data[2:]) def _parse_param_list(self, content, single_element_is_type=False): content = dedent_lines(content) r = Reader(content) params = [] while not r.eof(): header = r.read().strip() if " : " in header: arg_name, arg_type = header.split(" : ", maxsplit=1) else: # NOTE: param line with single element should never have a # a " :" before the description line, so this should probably # warn. if header.endswith(" :"): header = header[:-2] if single_element_is_type: arg_name, arg_type = "", header else: arg_name, arg_type = header, "" desc = r.read_to_next_unindented_line() desc = dedent_lines(desc) desc = strip_blank_lines(desc) params.append(Parameter(arg_name, arg_type, desc)) return params # See also supports the following formats. # # <FUNCNAME> # <FUNCNAME> SPACE* COLON SPACE+ <DESC> SPACE* # <FUNCNAME> ( COMMA SPACE+ <FUNCNAME>)+ (COMMA | PERIOD)? SPACE* # <FUNCNAME> ( COMMA SPACE+ <FUNCNAME>)* SPACE* COLON SPACE+ <DESC> SPACE* # <FUNCNAME> is one of # <PLAIN_FUNCNAME> # COLON <ROLE> COLON BACKTICK <PLAIN_FUNCNAME> BACKTICK # where # <PLAIN_FUNCNAME> is a legal function name, and # <ROLE> is any nonempty sequence of word characters. # Examples: func_f1 :meth:`func_h1` :obj:`~baz.obj_r` :class:`class_j` # <DESC> is a string describing the function. _role = r":(?P<role>(py:)?\w+):" _funcbacktick = r"`(?P<name>(?:~\w+\.)?[a-zA-Z0-9_\.-]+)`" _funcplain = r"(?P<name2>[a-zA-Z0-9_\.-]+)" _funcname = r"(" + _role + _funcbacktick + r"|" + _funcplain + r")" _funcnamenext = _funcname.replace("role", "rolenext") _funcnamenext = _funcnamenext.replace("name", "namenext") _description = r"(?P<description>\s*:(\s+(?P<desc>\S+.*))?)?\s*$" _func_rgx = re.compile(r"^\s*" + _funcname + r"\s*") _line_rgx = re.compile( r"^\s*" + r"(?P<allfuncs>" + _funcname # group for all function names + r"(?P<morefuncs>([,]\s+" + _funcnamenext + r")*)" + r")" + r"(?P<trailing>[,\.])?" # end of "allfuncs" + _description # Some function lists have a trailing comma (or period) '\s*' ) # Empty <DESC> elements are replaced with '..' empty_description = ".." def _parse_see_also(self, content): """ func_name : Descriptive text continued text another_func_name : Descriptive text func_name1, func_name2, :meth:`func_name`, func_name3 """ content = dedent_lines(content) items = [] def parse_item_name(text): """Match ':role:`name`' or 'name'.""" m = self._func_rgx.match(text) if not m: self._error_location(f"Error parsing See Also entry {line!r}") role = m.group("role") name = m.group("name") if role else m.group("name2") return name, role, m.end() rest = [] for line in content: if not line.strip(): continue line_match = self._line_rgx.match(line) description = None if line_match: description = line_match.group("desc") if line_match.group("trailing") and description: self._error_location( "Unexpected comma or period after function list at index %d of " 'line "%s"' % (line_match.end("trailing"), line), error=False, ) if not description and line.startswith(" "): rest.append(line.strip()) elif line_match: funcs = [] text = line_match.group("allfuncs") while True: if not text.strip(): break name, role, match_end = parse_item_name(text) funcs.append((name, role)) text = text[match_end:].strip() if text and text[0] == ",": text = text[1:].strip() rest = list(filter(None, [description])) items.append((funcs, rest)) else: self._error_location(f"Error parsing See Also entry {line!r}") return items def _parse_index(self, section, content): """ .. index:: default :refguide: something, else, and more """ def strip_each_in(lst): return [s.strip() for s in lst] out = {} section = section.split("::") if len(section) > 1: out["default"] = strip_each_in(section[1].split(","))[0] for line in content: line = line.split(":") if len(line) > 2: out[line[1]] = strip_each_in(line[2].split(",")) return out def _parse_summary(self): """Grab signature (if given) and summary""" if self._is_at_section(): return # If several signatures present, take the last one while True: summary = self._doc.read_to_next_empty_line() summary_str = " ".join([s.strip() for s in summary]).strip() compiled = re.compile(r"^([\w., ]+=)?\s*[\w\.]+\(.*\)$") if compiled.match(summary_str): self["Signature"] = summary_str if not self._is_at_section(): continue break if summary is not None: self["Summary"] = summary if not self._is_at_section(): self["Extended Summary"] = self._read_to_next_section() def _parse(self): self._doc.reset() self._parse_summary() sections = list(self._read_sections()) section_names = {section for section, content in sections} has_yields = "Yields" in section_names # We could do more tests, but we are not. Arbitrarily. if not has_yields and "Receives" in section_names: msg = "Docstring contains a Receives section but not Yields." raise ValueError(msg) for section, content in sections: if not section.startswith(".."): section = (s.capitalize() for s in section.split(" ")) section = " ".join(section) if self.get(section): self._error_location( "The section %s appears twice in %s" % (section, "\n".join(self._doc._str)) ) if section in ("Parameters", "Other Parameters", "Attributes", "Methods"): self[section] = self._parse_param_list(content) elif section in ("Returns", "Yields", "Raises", "Warns", "Receives"): self[section] = self._parse_param_list( content, single_element_is_type=True ) elif section.startswith(".. index::"): self["index"] = self._parse_index(section, content) elif section == "See Also": self["See Also"] = self._parse_see_also(content) else: self[section] = content @property def _obj(self): if hasattr(self, "_cls"): return self._cls elif hasattr(self, "_f"): return self._f return None def _error_location(self, msg, error=True): if self._obj is not None: # we know where the docs came from: try: filename = inspect.getsourcefile(self._obj) except TypeError: filename = None # Make UserWarning more descriptive via object introspection. # Skip if introspection fails name = getattr(self._obj, "__name__", None) if name is None: name = getattr(getattr(self._obj, "__class__", None), "__name__", None) if name is not None: msg += f" in the docstring of {name}" msg += f" in {filename}." if filename else "" if error: raise ValueError(msg) else: warn(msg, stacklevel=3) # string conversion routines def _str_header(self, name, symbol="-"): return [name, len(name) * symbol] def _str_indent(self, doc, indent=4): return [" " * indent + line for line in doc] def _str_signature(self): if self["Signature"]: return [self["Signature"].replace("*", r"\*")] + [""] return [""] def _str_summary(self): if self["Summary"]: return self["Summary"] + [""] return [] def _str_extended_summary(self): if self["Extended Summary"]: return self["Extended Summary"] + [""] return [] def _str_param_list(self, name): out = [] if self[name]: out += self._str_header(name) for param in self[name]: parts = [] if param.name: parts.append(param.name) if param.type: parts.append(param.type) out += [" : ".join(parts)] if param.desc and "".join(param.desc).strip(): out += self._str_indent(param.desc) out += [""] return out def _str_section(self, name): out = [] if self[name]: out += self._str_header(name) out += self[name] out += [""] return out def _str_see_also(self, func_role): if not self["See Also"]: return [] out = [] out += self._str_header("See Also") out += [""] last_had_desc = True for funcs, desc in self["See Also"]: assert isinstance(funcs, list) links = [] for func, role in funcs: if role: link = f":{role}:`{func}`" elif func_role: link = f":{func_role}:`{func}`" else: link = f"`{func}`_" links.append(link) link = ", ".join(links) out += [link] if desc: out += self._str_indent([" ".join(desc)]) last_had_desc = True else: last_had_desc = False out += self._str_indent([self.empty_description]) if last_had_desc: out += [""] out += [""] return out def _str_index(self): idx = self["index"] out = [] output_index = False default_index = idx.get("default", "") if default_index: output_index = True out += [f".. index:: {default_index}"] for section, references in idx.items(): if section == "default": continue output_index = True out += [f" :{section}: {', '.join(references)}"] if output_index: return out return "" def __str__(self, func_role=""): out = [] out += self._str_signature() out += self._str_summary() out += self._str_extended_summary() out += self._str_param_list("Parameters") for param_list in ("Attributes", "Methods"): out += self._str_param_list(param_list) for param_list in ( "Returns", "Yields", "Receives", "Other Parameters", "Raises", "Warns", ): out += self._str_param_list(param_list) out += self._str_section("Warnings") out += self._str_see_also(func_role) for s in ("Notes", "References", "Examples"): out += self._str_section(s) out += self._str_index() return "\n".join(out) def dedent_lines(lines): """Deindent a list of lines maximally""" return textwrap.dedent("\n".join(lines)).split("\n")
NumpyDocString
python
sympy__sympy
sympy/physics/mechanics/loads.py
{ "start": 218, "end": 819 }
class ____(ABC, namedtuple('LoadBase', ['location', 'vector'])): """Abstract base class for the various loading types.""" def __add__(self, other): raise TypeError(f"unsupported operand type(s) for +: " f"'{self.__class__.__name__}' and " f"'{other.__class__.__name__}'") def __mul__(self, other): raise TypeError(f"unsupported operand type(s) for *: " f"'{self.__class__.__name__}' and " f"'{other.__class__.__name__}'") __radd__ = __add__ __rmul__ = __mul__
LoadBase
python
Pylons__pyramid
src/pyramid/interfaces.py
{ "start": 24733, "end": 25126 }
class ____(Interface): """A policy for generating URLs to static assets""" def add(config, name, spec, **extra): """Add a new static info registration""" def generate(path, request, **kw): """Generate a URL for the given path""" def add_cache_buster(config, spec, cache_buster): """Add a new cache buster to a particular set of assets"""
IStaticURLInfo
python
pytorch__pytorch
torch/distributed/elastic/events/api.py
{ "start": 1874, "end": 3313 }
class ____: """ Dataclass to represent any rendezvous event. Args: name: Event name. (E.g. Current action being performed) run_id: The run id of the rendezvous message: The message describing the event hostname: Hostname of the node pid: The process id of the node node_state: The state of the node (INIT, RUNNING, SUCCEEDED, FAILED) master_endpoint: The master endpoint for the rendezvous store, if known rank: The rank of the node, if known local_id: The local_id of the node, if defined in dynamic_rendezvous.py error_trace: Error stack trace, if this is an error event. """ name: str run_id: str message: str hostname: str pid: int node_state: NodeState master_endpoint: str = "" rank: int | None = None local_id: int | None = None error_trace: str = "" def __str__(self): return self.serialize() @staticmethod def deserialize(data: Union[str, "RdzvEvent"]) -> "RdzvEvent": if isinstance(data, RdzvEvent): return data if isinstance(data, str): data_dict = json.loads(data) data_dict["node_state"] = NodeState[data_dict["node_state"]] # type: ignore[possibly-undefined] # pyrefly: ignore [unbound-name] return RdzvEvent(**data_dict) def serialize(self) -> str: return json.dumps(asdict(self))
RdzvEvent
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-oci-data-science/tests/test_oci_data_science_client.py
{ "start": 321, "end": 1247 }
class ____: """Unit tests for OCIAuth class.""" def setup_method(self): self.signer_mock = Mock() self.oci_auth = OCIAuth(self.signer_mock) def test_auth_flow(self): """Ensures that the auth_flow signs the request correctly.""" request = httpx.Request("POST", "https://example.com") prepared_request_mock = Mock() prepared_request_mock.headers = {"Authorization": "Signed"} with patch("requests.Request") as mock_requests_request: mock_requests_request.return_value = Mock() mock_requests_request.return_value.prepare.return_value = ( prepared_request_mock ) self.signer_mock.do_request_sign = Mock() list(self.oci_auth.auth_flow(request)) self.signer_mock.do_request_sign.assert_called() assert request.headers.get("Authorization") == "Signed"
TestOCIAuth
python
celery__celery
t/unit/app/test_amqp.py
{ "start": 7193, "end": 7494 }
class ____: def setup_method(self): self.simple_message = self.app.amqp.as_task_v2( uuid(), 'foo', create_sent_event=True, ) self.simple_message_no_sent_event = self.app.amqp.as_task_v2( uuid(), 'foo', create_sent_event=False, )
test_AMQP_Base
python
fsspec__filesystem_spec
fsspec/implementations/reference.py
{ "start": 47349, "end": 48814 }
class ____(AbstractBufferedFile): def __init__( self, fs, path, mode="rb", block_size="default", autocommit=True, cache_type="readahead", cache_options=None, size=None, **kwargs, ): super().__init__( fs, path, mode=mode, block_size=block_size, autocommit=autocommit, size=size, cache_type=cache_type, cache_options=cache_options, **kwargs, ) part_or_url, self.start, self.end = self.fs._cat_common(self.path) protocol, _ = split_protocol(part_or_url) self.src_fs = self.fs.fss[protocol] self.src_path = part_or_url self._f = None @property def f(self): if self._f is None or self._f.closed: self._f = self.src_fs._open( self.src_path, mode=self.mode, block_size=self.blocksize, autocommit=self.autocommit, cache_type="none", **self.kwargs, ) return self._f def close(self): if self._f is not None: self._f.close() return super().close() def _fetch_range(self, start, end): start = start + self.start end = min(end + self.start, self.end) self.f.seek(start) return self.f.read(end - start)
ReferenceFile
python
streamlit__streamlit
lib/streamlit/elements/lib/column_types.py
{ "start": 4323, "end": 4388 }
class ____(TypedDict): type: Literal["image"]
ImageColumnConfig
python
scipy__scipy
benchmarks/benchmarks/sparse.py
{ "start": 1353, "end": 2027 }
class ____(Benchmark): param_names = ['sparse_type', 'format', 'XY', 'op'] params = [ ['spmatrix', 'sparray'], ['csr', 'csc', 'coo', 'dia'], ['AA', 'AB', 'BA', 'BB'], ['__add__', '__sub__', 'multiply', '__mul__'] ] def setup(self, sparse_type, format, XY, op): matrices = dict(A=poisson2d(250, format=format, sparse_type=sparse_type)) matrices['B'] = (matrices['A']**2).asformat(format) x = matrices[XY[0]] self.y = matrices[XY[1]] self.fn = getattr(x, op) self.fn(self.y) # warmup def time_arithmetic(self, sparse_type, format, XY, op): self.fn(self.y)
Arithmetic
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_tp_integration.py
{ "start": 1408, "end": 2412 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.net1 = torch.nn.Linear(5, 8) self.relu = torch.nn.ReLU() self.net2 = torch.nn.Linear(8, 4) self.net3 = torch.nn.Linear(4, 12) def forward(self, x): return self.net3(self.net2(self.relu(self.net1(x)))) @staticmethod def get_sharded_param_names() -> list[str]: return ["net1.weight", "net1.bias", "net2.weight"] @staticmethod def get_non_sharded_param_names() -> list[str]: return ["net3.weight", "net3.bias"] def distribute_rmsnorm(module, device_mesh): def prepare_input_fn(mod, inputs, device_mesh): shard_tensor = DTensor.from_local(inputs[0], device_mesh, [Shard(0)]) return shard_tensor def prepare_output_fn(mod, outputs, device_mesh): return outputs.to_local() return distribute_module( module, device_mesh, input_fn=prepare_input_fn, output_fn=prepare_output_fn )
SimpleModel
python
wandb__wandb
wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/gevent.py
{ "start": 118, "end": 495 }
class ____(object): def __init__(self): self.jobs = [] def wait_until_finished(self): [j.join() for j in self.jobs] # gevent.joinall(self.jobs) def execute(self, fn, *args, **kwargs): promise = Promise() job = gevent.spawn(process, promise, fn, args, kwargs) self.jobs.append(job) return promise
GeventExecutor
python
astropy__astropy
astropy/io/ascii/sextractor.py
{ "start": 295, "end": 4534 }
class ____(core.BaseHeader): """Read the header from a file produced by SExtractor.""" comment = r"^\s*#\s*\S\D.*" # Find lines that don't have "# digit" def get_cols(self, lines): """ Initialize the header Column objects from the table ``lines`` for a SExtractor header. The SExtractor header is specialized so that we just copy the entire BaseHeader get_cols routine and modify as needed. Parameters ---------- lines : list List of table lines """ # This assumes that the columns are listed in order, one per line with a # header comment string of the format: "# 1 ID short description [unit]" # However, some may be missing and must be inferred from skipped column numbers columns = {} # E.g. '# 1 ID identification number' (no units) or '# 2 MAGERR magnitude of error [mag]' # Updated along with issue #4603, for more robust parsing of unit re_name_def = re.compile( r"""^\s* \# \s* # possible whitespace around # (?P<colnumber> [0-9]+)\s+ # number of the column in table (?P<colname> [-\w]+) # name of the column # column description, match any character until... (?:\s+(?P<coldescr> \w .+) # ...until [non-space][space][unit] or [not-right-bracket][end] (?:(?<!(\]))$|(?=(?:(?<=\S)\s+\[.+\]))))? (?:\s*\[(?P<colunit>.+)\])?.* # match units in brackets """, re.VERBOSE, ) dataline = None for line in lines: if not line.startswith("#"): dataline = line # save for later to infer the actual number of columns break # End of header lines match = re_name_def.search(line) if match: colnumber = int(match.group("colnumber")) colname = match.group("colname") coldescr = match.group("coldescr") # If no units are given, colunit = None colunit = match.group("colunit") columns[colnumber] = (colname, coldescr, colunit) # Handle skipped column numbers colnumbers = sorted(columns) # Handle the case where the last column is array-like by append a pseudo column # If there are more data columns than the largest column number # then add a pseudo-column that will be dropped later. This allows # the array column logic below to work in all cases. if dataline is not None: n_data_cols = len(dataline.split()) else: # handles no data, where we have to rely on the last column number n_data_cols = colnumbers[-1] # sextractor column number start at 1. columns[n_data_cols + 1] = (None, None, None) colnumbers.append(n_data_cols + 1) if len(columns) > 1: # only fill in skipped columns when there is genuine column initially previous_column = 0 for n in colnumbers: if n != previous_column + 1: for c in range(previous_column + 1, n): column_name = ( columns[previous_column][0] + f"_{c - previous_column}" ) column_descr = columns[previous_column][1] column_unit = columns[previous_column][2] columns[c] = (column_name, column_descr, column_unit) previous_column = n # Add the columns in order to self.names colnumbers = sorted(columns)[:-1] # drop the pseudo column self.names = [] for n in colnumbers: self.names.append(columns[n][0]) if not self.names: raise core.InconsistentTableError( "No column names found in SExtractor header" ) self.cols = [] for n in colnumbers: col = core.Column(name=columns[n][0]) col.description = columns[n][1] col.unit = columns[n][2] self.cols.append(col)
SExtractorHeader
python
pytorch__pytorch
torch/testing/_internal/common_subclass.py
{ "start": 3161, "end": 4100 }
class ____(WrapperTensor): @classmethod def get_wrapper_properties(cls, t, requires_grad=False): return t, {"requires_grad": requires_grad, "dispatch_sizes_strides_policy": "strides"} def __init__(self, t, requires_grad=False): self.t = t @classmethod def __torch_dispatch__(cls, func, types, args=(), kwargs=None): if not all(issubclass(cls, t) for t in types): return NotImplemented if kwargs is None: kwargs = {} def unwrap(e): return e.t if isinstance(e, WrapperTensorWithCustomStrides) else e def wrap(e): return WrapperTensorWithCustomStrides(e) if isinstance(e, torch.Tensor) else e rs = tree_map(wrap, func(*tree_map(unwrap, args), **tree_map(unwrap, kwargs or {}))) return rs def __repr__(self): return super().__repr__(tensor_contents=f"t={self.t}")
WrapperTensorWithCustomStrides
python
PyCQA__pylint
pylint/typing.py
{ "start": 2576, "end": 3051 }
class ____(TypedDict, total=False): """All allowed keys in the extra options for message definitions.""" scope: str old_names: list[tuple[str, str]] maxversion: tuple[int, int] minversion: tuple[int, int] shared: bool default_enabled: bool MessageDefinitionTuple = ( tuple[str, str, str] | tuple[str, str, str, ExtraMessageOptions] ) DirectoryNamespaceDict = dict[Path, tuple[argparse.Namespace, "DirectoryNamespaceDict"]]
ExtraMessageOptions
python
networkx__networkx
networkx/classes/tests/test_reportviews.py
{ "start": 12757, "end": 13704 }
class ____(TestEdgeDataView): @classmethod def setup_class(cls): cls.G = nx.path_graph(9, create_using=nx.MultiGraph()) cls.eview = nx.reportviews.MultiEdgeView def modify_edge(self, G, e, **kwds): G._adj[e[0]][e[1]][0].update(kwds) def test_repr(self): ev = self.eview(self.G)(data=True) rep = ( "MultiEdgeDataView([(0, 1, {}), (1, 2, {}), " + "(2, 3, {}), (3, 4, {}), " + "(4, 5, {}), (5, 6, {}), " + "(6, 7, {}), (7, 8, {})])" ) assert repr(ev) == rep def test_contains_with_nbunch(self): evr = self.eview(self.G) ev = evr(nbunch=[0, 2]) assert (0, 1) in ev assert (1, 2) in ev assert (2, 3) in ev assert (3, 4) not in ev assert (4, 5) not in ev assert (5, 6) not in ev assert (7, 8) not in ev assert (8, 9) not in ev
TestMultiEdgeDataView
python
doocs__leetcode
solution/3700-3799/3731.Find Missing Elements/Solution.py
{ "start": 0, "end": 201 }
class ____: def findMissingElements(self, nums: List[int]) -> List[int]: mn, mx = min(nums), max(nums) s = set(nums) return [x for x in range(mn + 1, mx) if x not in s]
Solution
python
joke2k__faker
faker/providers/lorem/ja_JP/__init__.py
{ "start": 68, "end": 3547 }
class ____(LoremProvider): """Implement lorem provider for ``ja_JP`` locale.""" word_connector = "" sentence_punctuation = "。" word_list = ( "コミュニティ", "隠す", "葉", "陶器", "錯覚", "バーゲン", "リニア", "コーラス", "仕上げ", "叔父", "移動", "差別する", "極端な", "数字", "テント", "必要", "主人", "電池", "ソース", "野球", "ストレージ", "スキーム", "暖かい", "ささやき", "器官", "トリビュート", "同行", "ジャム", "パン", "索引", "トス", "織る", "パーセント", "拡張", "教授", "バスケット", "創傷", "フレーム", "明らかにする", "フェミニスト", "発生する", "怒り", "ボトル", "狐", "柔らかい", "リフト", "バス", "雪", "画面", "パイオニア", "マリン", "ダイヤモンド", "普通の", "意図", "ヘア", "日曜日", "プラスチック", "衝突", "評議会", "主婦", "保証金", "動物", "参加する", "教会", "コミュニケーション", "憲法", "本質的な", "探査", "呼ぶ", "供給", "スペル", "再現する", "合計", "ダッシュ", "擁する", "知覚", "シェービング", "コンペ", "オークション", "細かい", "ニュース", "癌", "トーン", "チーズ", "反射", "ブランチ", "コピー", "状況", "スマッシュ", "式", "協力", "管理する", "文言", "編組", "ジャーナル", "腐った", "見落とす", "ハードウェア", "ピック", "感謝する", "楽しんで", "人形", "建築", "見出し", "タワー", "ホイール", "省略", "ログ", "助けて", "不自然な", "出演者", "転倒", "運", "障害", "クルー", "追放する", "月", "カレッジ", "緩む", "分割", "欠乏", "通行料金", "電話", "狭い", "中央", "埋め込む", "革新", "ブレーキ", "コーナー", "溝", "脊椎", "ブラケット", "戦略的", "尿", "血まみれの", "尊敬する", "催眠術", "アクセルペダル", "厳しい", "サンプル", "奨励します", "指名", "クール", "クロス", "ヒール", "敵対的な", "近代化する", "部隊", "目的", "保持する", "中世", "デッド", "ノート", "デフォルト", "犯罪者", "キャビン", "副", "改善", "職人", "シュガー", "花嫁", "倫理", "偏差", "販売", "軸", "サラダ", "品質", "風景", "虐待", "立派な", "ベルベット", "ハンマー", "キャビネット", "トレーナー", "リハビリ", "サワー", "連続", "学生", "高い", "賞賛する", "行進", "ダニ", "証言する", "符号", "バナー", "バケツ", "カラム", "装置", "ヒット", "敵", "トースト", "試してみる", "大統領", "屋根裏", "メニュー", "残る", "リンク", "舗装", "インチ", "特徴", "は", "持つ", "持っていました", "あった", "ない", "今", "今日", "持ってる", "午前", "私", "君は", "彼", "彼女", "それ", "自体", "あなた自身", "じぶんの", "鉱山", ) parts_of_speech: Dict[str, tuple] = {}
Provider
python
pytest-dev__pytest-xdist
src/xdist/looponfail.py
{ "start": 8221, "end": 10144 }
class ____: def __init__(self, rootdirlist: Sequence[Path]) -> None: self.rootdirlist = rootdirlist self.statcache: dict[Path, os.stat_result] = {} self.check() # snapshot state def fil(self, p: Path) -> bool: return p.is_file() and not p.name.startswith(".") and p.suffix != ".pyc" def rec(self, p: Path) -> bool: return not p.name.startswith(".") and p.exists() def waitonchange(self, checkinterval: float = 1.0) -> None: while 1: changed = self.check() if changed: return time.sleep(checkinterval) def check(self, removepycfiles: bool = True) -> bool: changed = False newstat: dict[Path, os.stat_result] = {} for rootdir in self.rootdirlist: for path in visit_path(rootdir, filter=self.fil, recurse=self.rec): oldstat = self.statcache.pop(path, None) try: curstat = path.stat() except OSError: if oldstat: changed = True else: newstat[path] = curstat if oldstat is not None: if ( oldstat.st_mtime != curstat.st_mtime or oldstat.st_size != curstat.st_size ): changed = True print("# MODIFIED", path) if removepycfiles and path.suffix == ".py": pycfile = path.with_suffix(".pyc") if pycfile.is_file(): os.unlink(pycfile) else: changed = True if self.statcache: changed = True self.statcache = newstat return changed
StatRecorder
python
plotly__plotly.py
plotly/graph_objs/scattermapbox/selected/_marker.py
{ "start": 233, "end": 3615 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scattermapbox.selected" _path_str = "scattermapbox.selected.marker" _valid_props = {"color", "opacity", "size"} @property def color(self): """ Sets the marker color of selected points. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["color"] @color.setter def color(self, val): self["color"] = val @property def opacity(self): """ Sets the marker opacity of selected points. The 'opacity' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float """ return self["opacity"] @opacity.setter def opacity(self, val): self["opacity"] = val @property def size(self): """ Sets the marker size of selected points. The 'size' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["size"] @size.setter def size(self, val): self["size"] = val @property def _prop_descriptions(self): return """\ color Sets the marker color of selected points. opacity Sets the marker opacity of selected points. size Sets the marker size of selected points. """ def __init__(self, arg=None, color=None, opacity=None, size=None, **kwargs): """ Construct a new Marker object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scattermapbox. selected.Marker` color Sets the marker color of selected points. opacity Sets the marker opacity of selected points. size Sets the marker size of selected points. Returns ------- Marker """ super().__init__("marker") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.scattermapbox.selected.Marker constructor must be a dict or an instance of :class:`plotly.graph_objs.scattermapbox.selected.Marker`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("color", arg, color) self._set_property("opacity", arg, opacity) self._set_property("size", arg, size) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Marker
python
spyder-ide__spyder
spyder/plugins/mainmenu/api.py
{ "start": 4119, "end": 4311 }
class ____(SpyderMenu): """ Spyder main window application menu. This class provides application menus with some predefined functionality. """ APP_MENU = True
ApplicationMenu
python
huggingface__transformers
src/transformers/models/ovis2/modular_ovis2.py
{ "start": 2893, "end": 3584 }
class ____(SiglipEncoder): def __init__(self, config: Ovis2VisionConfig): super().__init__(config) self.layers = nn.ModuleList([Ovis2VisionEncoderLayer(config) for _ in range(config.num_hidden_layers)]) @can_return_tuple @auto_docstring def forward( self, inputs_embeds, attention_mask: Optional[torch.Tensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> BaseModelOutput: hidden_states = inputs_embeds for encoder_layer in self.layers: hidden_states = encoder_layer(hidden_states, attention_mask, **kwargs) return BaseModelOutput(last_hidden_state=hidden_states)
Ovis2VisionEncoder
python
mlflow__mlflow
mlflow/server/graphql/autogenerated_graphql_schema.py
{ "start": 8055, "end": 8243 }
class ____(graphene.InputObjectType): run_id = graphene.String() run_uuid = graphene.String() path = graphene.String() page_token = graphene.String()
MlflowListArtifactsInput
python
protocolbuffers__protobuf
python/google/protobuf/descriptor.py
{ "start": 17951, "end": 28758 }
class ____(DescriptorBase): """Descriptor for a single field in a .proto file. Attributes: name (str): Name of this field, exactly as it appears in .proto. full_name (str): Name of this field, including containing scope. This is particularly relevant for extensions. index (int): Dense, 0-indexed index giving the order that this field textually appears within its message in the .proto file. number (int): Tag number declared for this field in the .proto file. type (int): (One of the TYPE_* constants below) Declared type. cpp_type (int): (One of the CPPTYPE_* constants below) C++ type used to represent this field. label (int): (One of the LABEL_* constants below) Tells whether this field is optional, required, or repeated. has_default_value (bool): True if this field has a default value defined, otherwise false. default_value (Varies): Default value of this field. Only meaningful for non-repeated scalar fields. Repeated fields should always set this to [], and non-repeated composite fields should always set this to None. containing_type (Descriptor): Descriptor of the protocol message type that contains this field. Set by the Descriptor constructor if we're passed into one. Somewhat confusingly, for extension fields, this is the descriptor of the EXTENDED message, not the descriptor of the message containing this field. (See is_extension and extension_scope below). message_type (Descriptor): If a composite field, a descriptor of the message type contained in this field. Otherwise, this is None. enum_type (EnumDescriptor): If this field contains an enum, a descriptor of that enum. Otherwise, this is None. is_extension: True iff this describes an extension field. extension_scope (Descriptor): Only meaningful if is_extension is True. Gives the message that immediately contains this extension field. Will be None iff we're a top-level (file-level) extension field. options (descriptor_pb2.FieldOptions): Protocol message field options or None to use default field options. containing_oneof (OneofDescriptor): If the field is a member of a oneof union, contains its descriptor. Otherwise, None. file (FileDescriptor): Reference to file descriptor. """ # Must be consistent with C++ FieldDescriptor::Type enum in # descriptor.h. # # TODO: Find a way to eliminate this repetition. TYPE_DOUBLE = 1 TYPE_FLOAT = 2 TYPE_INT64 = 3 TYPE_UINT64 = 4 TYPE_INT32 = 5 TYPE_FIXED64 = 6 TYPE_FIXED32 = 7 TYPE_BOOL = 8 TYPE_STRING = 9 TYPE_GROUP = 10 TYPE_MESSAGE = 11 TYPE_BYTES = 12 TYPE_UINT32 = 13 TYPE_ENUM = 14 TYPE_SFIXED32 = 15 TYPE_SFIXED64 = 16 TYPE_SINT32 = 17 TYPE_SINT64 = 18 MAX_TYPE = 18 # Must be consistent with C++ FieldDescriptor::CppType enum in # descriptor.h. # # TODO: Find a way to eliminate this repetition. CPPTYPE_INT32 = 1 CPPTYPE_INT64 = 2 CPPTYPE_UINT32 = 3 CPPTYPE_UINT64 = 4 CPPTYPE_DOUBLE = 5 CPPTYPE_FLOAT = 6 CPPTYPE_BOOL = 7 CPPTYPE_ENUM = 8 CPPTYPE_STRING = 9 CPPTYPE_MESSAGE = 10 MAX_CPPTYPE = 10 _PYTHON_TO_CPP_PROTO_TYPE_MAP = { TYPE_DOUBLE: CPPTYPE_DOUBLE, TYPE_FLOAT: CPPTYPE_FLOAT, TYPE_ENUM: CPPTYPE_ENUM, TYPE_INT64: CPPTYPE_INT64, TYPE_SINT64: CPPTYPE_INT64, TYPE_SFIXED64: CPPTYPE_INT64, TYPE_UINT64: CPPTYPE_UINT64, TYPE_FIXED64: CPPTYPE_UINT64, TYPE_INT32: CPPTYPE_INT32, TYPE_SFIXED32: CPPTYPE_INT32, TYPE_SINT32: CPPTYPE_INT32, TYPE_UINT32: CPPTYPE_UINT32, TYPE_FIXED32: CPPTYPE_UINT32, TYPE_BYTES: CPPTYPE_STRING, TYPE_STRING: CPPTYPE_STRING, TYPE_BOOL: CPPTYPE_BOOL, TYPE_MESSAGE: CPPTYPE_MESSAGE, TYPE_GROUP: CPPTYPE_MESSAGE, } # Must be consistent with C++ FieldDescriptor::Label enum in # descriptor.h. # # TODO: Find a way to eliminate this repetition. LABEL_OPTIONAL = 1 LABEL_REQUIRED = 2 LABEL_REPEATED = 3 MAX_LABEL = 3 # Must be consistent with C++ constants kMaxNumber, kFirstReservedNumber, # and kLastReservedNumber in descriptor.h MAX_FIELD_NUMBER = (1 << 29) - 1 FIRST_RESERVED_FIELD_NUMBER = 19000 LAST_RESERVED_FIELD_NUMBER = 19999 if _USE_C_DESCRIPTORS: _C_DESCRIPTOR_CLASS = _message.FieldDescriptor def __new__( cls, name, full_name, index, number, type, cpp_type, label, default_value, message_type, enum_type, containing_type, is_extension, extension_scope, options=None, serialized_options=None, has_default_value=True, containing_oneof=None, json_name=None, file=None, create_key=None, ): # pylint: disable=redefined-builtin _message.Message._CheckCalledFromGeneratedFile() if is_extension: return _message.default_pool.FindExtensionByName(full_name) else: return _message.default_pool.FindFieldByName(full_name) def __init__( self, name, full_name, index, number, type, cpp_type, label, default_value, message_type, enum_type, containing_type, is_extension, extension_scope, options=None, serialized_options=None, has_default_value=True, containing_oneof=None, json_name=None, file=None, create_key=None, ): # pylint: disable=redefined-builtin """The arguments are as described in the description of FieldDescriptor attributes above. Note that containing_type may be None, and may be set later if necessary (to deal with circular references between message types, for example). Likewise for extension_scope. """ if create_key is not _internal_create_key: _Deprecated('create function FieldDescriptor()') super(FieldDescriptor, self).__init__( file, options, serialized_options, 'FieldOptions' ) self.name = name self.full_name = full_name self._camelcase_name = None if json_name is None: self.json_name = _ToJsonName(name) else: self.json_name = json_name self.index = index self.number = number self._type = type self.cpp_type = cpp_type self._label = label self.has_default_value = has_default_value self.default_value = default_value self.containing_type = containing_type self.message_type = message_type self.enum_type = enum_type self.is_extension = is_extension self.extension_scope = extension_scope self.containing_oneof = containing_oneof if api_implementation.Type() == 'python': self._cdescriptor = None else: if is_extension: self._cdescriptor = _message.default_pool.FindExtensionByName(full_name) else: self._cdescriptor = _message.default_pool.FindFieldByName(full_name) @property def _parent(self): if self.containing_oneof: return self.containing_oneof if self.is_extension: return self.extension_scope or self.file return self.containing_type def _InferLegacyFeatures(self, edition, options, features): # pylint: disable=g-import-not-at-top from google.protobuf import descriptor_pb2 if edition >= descriptor_pb2.Edition.EDITION_2023: return if self._label == FieldDescriptor.LABEL_REQUIRED: features.field_presence = ( descriptor_pb2.FeatureSet.FieldPresence.LEGACY_REQUIRED ) if self._type == FieldDescriptor.TYPE_GROUP: features.message_encoding = ( descriptor_pb2.FeatureSet.MessageEncoding.DELIMITED ) if options.HasField('packed'): features.repeated_field_encoding = ( descriptor_pb2.FeatureSet.RepeatedFieldEncoding.PACKED if options.packed else descriptor_pb2.FeatureSet.RepeatedFieldEncoding.EXPANDED ) @property def type(self): if ( self._GetFeatures().message_encoding == _FEATURESET_MESSAGE_ENCODING_DELIMITED and self.message_type and not self.message_type.GetOptions().map_entry and not self.containing_type.GetOptions().map_entry ): return FieldDescriptor.TYPE_GROUP return self._type @type.setter def type(self, val): self._type = val @property def is_required(self): """Returns if the field is required.""" return ( self._GetFeatures().field_presence == _FEATURESET_FIELD_PRESENCE_LEGACY_REQUIRED ) @property def is_repeated(self): """Returns if the field is repeated.""" return self._label == FieldDescriptor.LABEL_REPEATED @property def camelcase_name(self): """Camelcase name of this field. Returns: str: the name in CamelCase. """ if self._camelcase_name is None: self._camelcase_name = _ToCamelCase(self.name) return self._camelcase_name @property def has_presence(self): """Whether the field distinguishes between unpopulated and default values. Raises: RuntimeError: singular field that is not linked with message nor file. """ if self.is_repeated: return False if ( self.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE or self.is_extension or self.containing_oneof ): return True return ( self._GetFeatures().field_presence != _FEATURESET_FIELD_PRESENCE_IMPLICIT ) @property def is_packed(self): """Returns if the field is packed.""" if not self.is_repeated: return False field_type = self.type if ( field_type == FieldDescriptor.TYPE_STRING or field_type == FieldDescriptor.TYPE_GROUP or field_type == FieldDescriptor.TYPE_MESSAGE or field_type == FieldDescriptor.TYPE_BYTES ): return False return ( self._GetFeatures().repeated_field_encoding == _FEATURESET_REPEATED_FIELD_ENCODING_PACKED ) @staticmethod def ProtoTypeToCppProtoType(proto_type): """Converts from a Python proto type to a C++ Proto Type. The Python ProtocolBuffer classes specify both the 'Python' datatype and the 'C++' datatype - and they're not the same. This helper method should translate from one to another. Args: proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*) Returns: int: descriptor.FieldDescriptor.CPPTYPE_*, the C++ type. Raises: TypeTransformationError: when the Python proto type isn't known. """ try: return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type] except KeyError: raise TypeTransformationError('Unknown proto_type: %s' % proto_type)
FieldDescriptor
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 25325, "end": 25940 }
class ____(MixinSequenceOfValues): """ Facet labels along the horizontal axis Parameters ---------- theme_element : element_text """ _omit = ["margin", "ha", "va"] def apply_figure(self, figure: Figure, targets: ThemeTargets): super().apply_figure(figure, targets) if texts := targets.strip_text_x: self.set(texts) def blank_figure(self, figure: Figure, targets: ThemeTargets): super().blank_figure(figure, targets) if texts := targets.strip_text_x: for text in texts: text.set_visible(False)
strip_text_x
python
docker__docker-py
tests/integration/api_container_test.py
{ "start": 28157, "end": 28729 }
class ____(BaseAPIIntegrationTest): def test_rename_container(self): version = self.client.version()['Version'] name = 'hong_meiling' res = self.client.create_container(TEST_IMG, 'true') assert 'Id' in res self.tmp_containers.append(res['Id']) self.client.rename(res, name) inspect = self.client.inspect_container(res['Id']) assert 'Name' in inspect if version == '1.5.0': assert name == inspect['Name'] else: assert f'/{name}' == inspect['Name']
RenameContainerTest
python
PyCQA__pylint
tests/functional/g/generic_alias/generic_alias_side_effects.py
{ "start": 291, "end": 1628 }
class ____(Generic[TYPE]): """ Simple class with slots """ __slots__ = ['value'] def __init__(self, value): self.value = value # tests/functional/d/dangerous_default_value_py30.py def function4(value=set()): # [dangerous-default-value] """set is mutable and dangerous.""" return value def function5(value=frozenset()): """frozenset is immutable and safe.""" return value def function7(value=dict()): # [dangerous-default-value] """dict is mutable and dangerous.""" return value def function8(value=list()): # [dangerous-default-value] """list is mutable and dangerous.""" return value def function17(value=collections.deque()): # [dangerous-default-value] """mutable, dangerous""" return value def function18(value=collections.ChainMap()): # [dangerous-default-value] """mutable, dangerous""" return value def function19(value=collections.Counter()): # [dangerous-default-value] """mutable, dangerous""" return value def function20(value=collections.OrderedDict()): # [dangerous-default-value] """mutable, dangerous""" return value def function21(value=collections.defaultdict()): # [dangerous-default-value] """mutable, dangerous""" return value # tests/functional/p/protocol_classes.py (min py38) T2 = typing.TypeVar("T2")
Cls
python
openai__gym
gym/wrappers/pixel_observation.py
{ "start": 263, "end": 8049 }
class ____(gym.ObservationWrapper): """Augment observations by pixel values. Observations of this wrapper will be dictionaries of images. You can also choose to add the observation of the base environment to this dictionary. In that case, if the base environment has an observation space of type :class:`Dict`, the dictionary of rendered images will be updated with the base environment's observation. If, however, the observation space is of type :class:`Box`, the base environment's observation (which will be an element of the :class:`Box` space) will be added to the dictionary under the key "state". Example: >>> import gym >>> env = PixelObservationWrapper(gym.make('CarRacing-v1', render_mode="rgb_array")) >>> obs = env.reset() >>> obs.keys() odict_keys(['pixels']) >>> obs['pixels'].shape (400, 600, 3) >>> env = PixelObservationWrapper(gym.make('CarRacing-v1', render_mode="rgb_array"), pixels_only=False) >>> obs = env.reset() >>> obs.keys() odict_keys(['state', 'pixels']) >>> obs['state'].shape (96, 96, 3) >>> obs['pixels'].shape (400, 600, 3) >>> env = PixelObservationWrapper(gym.make('CarRacing-v1', render_mode="rgb_array"), pixel_keys=('obs',)) >>> obs = env.reset() >>> obs.keys() odict_keys(['obs']) >>> obs['obs'].shape (400, 600, 3) """ def __init__( self, env: gym.Env, pixels_only: bool = True, render_kwargs: Optional[Dict[str, Dict[str, Any]]] = None, pixel_keys: Tuple[str, ...] = ("pixels",), ): """Initializes a new pixel Wrapper. Args: env: The environment to wrap. pixels_only (bool): If ``True`` (default), the original observation returned by the wrapped environment will be discarded, and a dictionary observation will only include pixels. If ``False``, the observation dictionary will contain both the original observations and the pixel observations. render_kwargs (dict): Optional dictionary containing that maps elements of ``pixel_keys``to keyword arguments passed to the :meth:`self.render` method. pixel_keys: Optional custom string specifying the pixel observation's key in the ``OrderedDict`` of observations. Defaults to ``(pixels,)``. Raises: AssertionError: If any of the keys in ``render_kwargs``do not show up in ``pixel_keys``. ValueError: If ``env``'s observation space is not compatible with the wrapper. Supported formats are a single array, or a dict of arrays. ValueError: If ``env``'s observation already contains any of the specified ``pixel_keys``. TypeError: When an unexpected pixel type is used """ super().__init__(env) # Avoid side-effects that occur when render_kwargs is manipulated render_kwargs = copy.deepcopy(render_kwargs) self.render_history = [] if render_kwargs is None: render_kwargs = {} for key in render_kwargs: assert key in pixel_keys, ( "The argument render_kwargs should map elements of " "pixel_keys to dictionaries of keyword arguments. " f"Found key '{key}' in render_kwargs but not in pixel_keys." ) default_render_kwargs = {} if not env.render_mode: raise AttributeError( "env.render_mode must be specified to use PixelObservationWrapper:" "`gym.make(env_name, render_mode='rgb_array')`." ) for key in pixel_keys: render_kwargs.setdefault(key, default_render_kwargs) wrapped_observation_space = env.observation_space if isinstance(wrapped_observation_space, spaces.Box): self._observation_is_dict = False invalid_keys = {STATE_KEY} elif isinstance(wrapped_observation_space, (spaces.Dict, MutableMapping)): self._observation_is_dict = True invalid_keys = set(wrapped_observation_space.spaces.keys()) else: raise ValueError("Unsupported observation space structure.") if not pixels_only: # Make sure that now keys in the `pixel_keys` overlap with # `observation_keys` overlapping_keys = set(pixel_keys) & set(invalid_keys) if overlapping_keys: raise ValueError( f"Duplicate or reserved pixel keys {overlapping_keys!r}." ) if pixels_only: self.observation_space = spaces.Dict() elif self._observation_is_dict: self.observation_space = copy.deepcopy(wrapped_observation_space) else: self.observation_space = spaces.Dict({STATE_KEY: wrapped_observation_space}) # Extend observation space with pixels. self.env.reset() pixels_spaces = {} for pixel_key in pixel_keys: pixels = self._render(**render_kwargs[pixel_key]) pixels: np.ndarray = pixels[-1] if isinstance(pixels, List) else pixels if not hasattr(pixels, "dtype") or not hasattr(pixels, "shape"): raise TypeError( f"Render method returns a {pixels.__class__.__name__}, but an array with dtype and shape is expected." "Be sure to specify the correct render_mode." ) if np.issubdtype(pixels.dtype, np.integer): low, high = (0, 255) elif np.issubdtype(pixels.dtype, np.float): low, high = (-float("inf"), float("inf")) else: raise TypeError(pixels.dtype) pixels_space = spaces.Box( shape=pixels.shape, low=low, high=high, dtype=pixels.dtype ) pixels_spaces[pixel_key] = pixels_space self.observation_space.spaces.update(pixels_spaces) self._pixels_only = pixels_only self._render_kwargs = render_kwargs self._pixel_keys = pixel_keys def observation(self, observation): """Updates the observations with the pixel observations. Args: observation: The observation to add pixel observations for Returns: The updated pixel observations """ pixel_observation = self._add_pixel_observation(observation) return pixel_observation def _add_pixel_observation(self, wrapped_observation): if self._pixels_only: observation = collections.OrderedDict() elif self._observation_is_dict: observation = type(wrapped_observation)(wrapped_observation) else: observation = collections.OrderedDict() observation[STATE_KEY] = wrapped_observation pixel_observations = { pixel_key: self._render(**self._render_kwargs[pixel_key]) for pixel_key in self._pixel_keys } observation.update(pixel_observations) return observation def render(self, *args, **kwargs): """Renders the environment.""" render = self.env.render(*args, **kwargs) if isinstance(render, list): render = self.render_history + render self.render_history = [] return render def _render(self, *args, **kwargs): render = self.env.render(*args, **kwargs) if isinstance(render, list): self.render_history += render return render
PixelObservationWrapper
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/triggers/cloud_run.py
{ "start": 1245, "end": 1393 }
class ____(Enum): """Enum to represent the status of a job run.""" SUCCESS = "Success" FAIL = "Fail" TIMEOUT = "Timeout"
RunJobStatus
python
bokeh__bokeh
src/bokeh/models/tools.py
{ "start": 30506, "end": 31097 }
class ____(PlotActionTool): ''' *toolbar icon*: |reset_icon| The reset tool is an action. When activated in the toolbar, the tool resets the data bounds of the plot to their values when the plot was initially created. .. |reset_icon| image:: /_images/icons/reset.svg :height: 24px :alt: Icon of two arrows on a circular arc forming a circle representing the reset tool in the toolbar. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs)
ResetTool
python
tensorflow__tensorflow
tensorflow/python/saved_model/keras_injection_test.py
{ "start": 936, "end": 1434 }
class ____(tf.test.TestCase): def test_keras_optimizer_injected(self): save_path = test.test_src_dir_path( 'cc/saved_model/testdata/OptimizerSlotVariableModule') _ = tf.saved_model.load(save_path) # Make sure keras optimizers are registed without accessing keras code # when loading a model with optimizers self.assertIn( 'optimizer', tf.__internal__.saved_model.load.registered_identifiers() ) if __name__ == '__main__': tf.test.main()
KerasInjectionTest
python
pytest-dev__pytest
src/_pytest/fixtures.py
{ "start": 47196, "end": 48789 }
class ____: scope: _ScopeName | Callable[[str, Config], _ScopeName] params: tuple[object, ...] | None autouse: bool = False ids: tuple[object | None, ...] | Callable[[Any], object | None] | None = None name: str | None = None _ispytest: dataclasses.InitVar[bool] = False def __post_init__(self, _ispytest: bool) -> None: check_ispytest(_ispytest) def __call__(self, function: FixtureFunction) -> FixtureFunctionDefinition: if inspect.isclass(function): raise ValueError("class fixtures not supported (maybe in the future)") if isinstance(function, FixtureFunctionDefinition): raise ValueError( f"@pytest.fixture is being applied more than once to the same function {function.__name__!r}" ) if hasattr(function, "pytestmark"): fail( "Marks cannot be applied to fixtures.\n" "See docs: https://docs.pytest.org/en/stable/deprecations.html#applying-a-mark-to-a-fixture-function" ) fixture_definition = FixtureFunctionDefinition( function=function, fixture_function_marker=self, _ispytest=True ) name = self.name or function.__name__ if name == "request": location = getlocation(function) fail( f"'request' is a reserved word for fixtures, use another name:\n {location}", pytrace=False, ) return fixture_definition # TODO: paramspec/return type annotation tracking and storing
FixtureFunctionMarker
python
boto__boto3
boto3/dynamodb/conditions.py
{ "start": 5771, "end": 5888 }
class ____(ConditionBase): expression_operator = 'contains' expression_format = '{operator}({0}, {1})'
Contains
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 695103, "end": 695561 }
class ____(sgqlc.types.Type): """Autogenerated return type of MergeBranch""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "merge_commit") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation.""" merge_commit = sgqlc.types.Field("Commit", graphql_name="mergeCommit") """The resulting merge Commit."""
MergeBranchPayload
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_C.py
{ "start": 15535, "end": 17137 }
class ____(Benchmark): r""" Csendes objective function. This class defines the Csendes [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Csendes}}(x) = \sum_{i=1}^n x_i^6 \left[ 2 + \sin \left( \frac{1}{x_i} \right ) \right] Here, :math:`n` represents the number of dimensions and :math:`x_i \in [-1, 1]` for :math:`i = 1, ..., N`. *Global optimum*: :math:`f(x) = 0.0` for :math:`x_i = 0` for :math:`i = 1, ..., N` .. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions For Global Optimization Problems Int. Journal of Mathematical Modelling and Numerical Optimisation, 2013, 4, 150-194. """ change_dimensionality = True def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-1.0] * self.N, [1.0] * self.N)) self.global_optimum = [[0 for _ in range(self.N)]] self.fglob = np.nan def fun(self, x, *args): self.nfev += 1 try: return sum((x ** 6.0) * (2.0 + sin(1.0 / x))) except ZeroDivisionError: return np.nan except FloatingPointError: return np.nan def success(self, x): """Is a candidate solution at the global minimum""" val = self.fun(asarray(x)) if isnan(val): return True try: assert_almost_equal(val, 0., 4) return True except AssertionError: return False return False
Csendes
python
google__pytype
pytype/tests/test_typing_self.py
{ "start": 155, "end": 7679 }
class ____(test_base.BaseTest): """Tests for typing.Self.""" def test_instance_method_return(self): self.Check(""" from typing_extensions import Self class A: def f(self) -> Self: return self class B(A): pass assert_type(A().f(), A) assert_type(B().f(), B) """) def test_parameterized_return(self): self.Check(""" from typing import List from typing_extensions import Self class A: def f(self) -> List[Self]: return [self] class B(A): pass assert_type(A().f(), "list[A]") assert_type(B().f(), "list[B]") """) def test_parameter(self): errors = self.CheckWithErrors(""" from typing_extensions import Self class A: def f(self, other: Self) -> bool: return False class B(A): pass B().f(B()) # ok B().f(0) # wrong-arg-types[e] """) self.assertErrorSequences(errors, {"e": ["Expected", "B", "Actual", "int"]}) def test_nested_class(self): self.Check(""" from typing_extensions import Self class A: class B: def f(self) -> Self: return self class C(A.B): pass assert_type(A.B().f(), A.B) assert_type(C().f(), C) """) @test_utils.skipBeforePy((3, 11), "typing.Self is new in 3.11") def test_import_from_typing(self): self.Check(""" from typing import Self class A: def f(self) -> Self: return self class B(A): pass assert_type(A().f(), A) assert_type(B().f(), B) """) def test_classmethod(self): self.Check(""" from typing_extensions import Self class A: @classmethod def build(cls) -> Self: return cls() class B(A): pass assert_type(A.build(), A) assert_type(B.build(), B) """) def test_new(self): self.Check(""" from typing_extensions import Self class A: def __new__(cls) -> Self: return super().__new__(cls) class B(A): pass assert_type(A(), A) assert_type(B(), B) """) def test_generic_class(self): self.Check(""" from typing import Generic, TypeVar from typing_extensions import Self T = TypeVar('T') class A(Generic[T]): def copy(self) -> Self: return self class B(A[T]): pass assert_type(A[int]().copy(), A[int]) assert_type(B[str]().copy(), B[str]) """) def test_protocol(self): # From https://peps.python.org/pep-0673/#use-in-protocols: # If a protocol uses `Self` in methods or attribute annotations, then a # class `Foo` is considered compatible with the protocol if its # corresponding methods and attribute annotations use either `Self` or # `Foo` or any of `Foo`'s subclasses. self.CheckWithErrors(""" from typing import Protocol, TypeVar from typing_extensions import Self T = TypeVar('T') class MyProtocol(Protocol[T]): def f(self) -> Self: return self class Ok1: def f(self) -> MyProtocol: return self class Ok2: def f(self) -> 'Ok2': return self class Ok3: def f(self) -> Self: return self class Bad: def f(self) -> int: return 0 def f(x: MyProtocol[str]): pass f(Ok1()) f(Ok2()) f(Ok3()) f(Bad()) # wrong-arg-types """) def test_protocol_classmethod(self): self.CheckWithErrors(""" from typing import Protocol, TypeVar from typing_extensions import Self T = TypeVar('T') class MyProtocol(Protocol[T]): @classmethod def build(cls) -> Self: return cls() class Ok: @classmethod def build(cls) -> 'Ok': return cls() class Bad: @classmethod def build(cls) -> int: return 0 def f(x: MyProtocol[str]): pass f(Ok()) f(Bad()) # wrong-arg-types """) def test_signature_mismatch(self): self.CheckWithErrors(""" from typing_extensions import Self class Foo: def f(self) -> Self: return self class Ok(Foo): def f(self) -> 'Ok': return self class Bad(Foo): def f(self) -> int: # signature-mismatch return 0 """) def test_class_attribute(self): self.Check(""" from typing_extensions import Self class Foo: x: Self class Bar(Foo): pass assert_type(Foo.x, Foo) assert_type(Foo().x, Foo) assert_type(Bar.x, Bar) assert_type(Bar().x, Bar) """) def test_instance_attribute(self): self.Check(""" from typing_extensions import Self class Foo: def __init__(self, x: Self): self.x = x self.y: Self = __any_object__ class Bar(Foo): pass assert_type(Foo(__any_object__).x, Foo) assert_type(Foo(__any_object__).y, Foo) assert_type(Bar(__any_object__).x, Bar) assert_type(Bar(__any_object__).y, Bar) """) def test_cast(self): self.Check(""" from typing import cast from typing_extensions import Self class Foo: def f(self): return cast(Self, __any_object__) class Bar(Foo): pass assert_type(Foo().f(), Foo) assert_type(Bar().f(), Bar) """) def test_generic_attribute(self): self.Check(""" from typing import Generic, TypeVar from typing_extensions import Self T = TypeVar('T') class C(Generic[T]): x: Self class D(C[T]): pass assert_type(C[int].x, C[int]) assert_type(C[int]().x, C[int]) assert_type(D[str].x, D[str]) assert_type(D[str]().x, D[str]) """) def test_attribute_mismatch(self): self.CheckWithErrors(""" from typing import Protocol from typing_extensions import Self class C(Protocol): x: Self class Ok: x: 'Ok' class Bad: x: int def f(c: C): pass f(Ok()) f(Bad()) # wrong-arg-types """) def test_method_with_callable_annotated_decorator(self): self.Check(""" from typing import Callable from typing_extensions import Self def decorate(f) -> Callable[['C'], 'C']: return f class C: @decorate def f(self) -> Self: return self """) def test_method_with_identity_annotated_decorator(self): self.Check(""" from typing import Callable, TypeVar from typing_extensions import Self T = TypeVar('T', bound='C') def decorate(f) -> Callable[[T], T]: return f class C: @decorate def f(self) -> Self: return self """) def test_signature_compatibility(self): self.Check(""" from typing_extensions import Self class Parent: def add(self, other: Self) -> Self: return self class Child(Parent): def add(self, other: Self) -> Self: return self """) def test_overload(self): self.Check(""" from typing import overload from typing_extensions import Self class C: @overload def f(self, other: Self) -> Self: ... def f(self, other): return other class D(C): pass assert_type(D().f(__any_object__), D) """)
SelfTest
python
sqlalchemy__sqlalchemy
test/ext/test_extendedattr.py
{ "start": 1683, "end": 2441 }
class ____(instrumentation.InstrumentationManager): def instrument_attribute(self, class_, key, attr): pass def install_descriptor(self, class_, key, attr): pass def uninstall_descriptor(self, class_, key): pass def instrument_collection_class(self, class_, key, collection_class): return MyListLike def get_instance_dict(self, class_, instance): return instance._goofy_dict def initialize_instance_dict(self, class_, instance): instance.__dict__["_goofy_dict"] = {} def install_state(self, class_, instance, state): instance.__dict__["_my_state"] = state def state_getter(self, class_): return lambda instance: instance.__dict__["_my_state"]
MyTypesManager
python
pytorch__pytorch
torch/_inductor/template_heuristics/triton.py
{ "start": 77939, "end": 78366 }
class ____( BlackwellTMATemplateConfigMixin, CUDAConfigHeuristic ): """Blackwell Persistent TMA template""" def __init__(self) -> None: super().__init__() self.mm_configs = self.blackwell_persistent_mm_configs @register_template_heuristic( persistent_tma_mm_template.uid, "cuda", register=torch.version.hip is None, op_name="addmm", )
CUDABlackwellPersistentTMATemplateConfigHeuristic
python
doocs__leetcode
solution/2600-2699/2613.Beautiful Pairs/Solution.py
{ "start": 0, "end": 1516 }
class ____: def beautifulPair(self, nums1: List[int], nums2: List[int]) -> List[int]: def dist(x1: int, y1: int, x2: int, y2: int) -> int: return abs(x1 - x2) + abs(y1 - y2) def dfs(l: int, r: int): if l >= r: return inf, -1, -1 m = (l + r) >> 1 x = points[m][0] d1, pi1, pj1 = dfs(l, m) d2, pi2, pj2 = dfs(m + 1, r) if d1 > d2 or (d1 == d2 and (pi1 > pi2 or (pi1 == pi2 and pj1 > pj2))): d1, pi1, pj1 = d2, pi2, pj2 t = [p for p in points[l : r + 1] if abs(p[0] - x) <= d1] t.sort(key=lambda x: x[1]) for i in range(len(t)): for j in range(i + 1, len(t)): if t[j][1] - t[i][1] > d1: break pi, pj = sorted([t[i][2], t[j][2]]) d = dist(t[i][0], t[i][1], t[j][0], t[j][1]) if d < d1 or (d == d1 and (pi < pi1 or (pi == pi1 and pj < pj1))): d1, pi1, pj1 = d, pi, pj return d1, pi1, pj1 pl = defaultdict(list) for i, (x, y) in enumerate(zip(nums1, nums2)): pl[(x, y)].append(i) points = [] for i, (x, y) in enumerate(zip(nums1, nums2)): if len(pl[(x, y)]) > 1: return [i, pl[(x, y)][1]] points.append((x, y, i)) points.sort() _, pi, pj = dfs(0, len(points) - 1) return [pi, pj]
Solution
python
pallets__click
src/click/_utils.py
{ "start": 69, "end": 943 }
class ____(enum.Enum): """Enum used to define sentinel values. .. seealso:: `PEP 661 - Sentinel Values <https://peps.python.org/pep-0661/>`_. """ UNSET = object() FLAG_NEEDS_VALUE = object() def __repr__(self) -> str: return f"{self.__class__.__name__}.{self.name}" UNSET = Sentinel.UNSET """Sentinel used to indicate that a value is not set.""" FLAG_NEEDS_VALUE = Sentinel.FLAG_NEEDS_VALUE """Sentinel used to indicate an option was passed as a flag without a value but is not a flag option. ``Option.consume_value`` uses this to prompt or use the ``flag_value``. """ T_UNSET = t.Literal[UNSET] # type: ignore[valid-type] """Type hint for the :data:`UNSET` sentinel value.""" T_FLAG_NEEDS_VALUE = t.Literal[FLAG_NEEDS_VALUE] # type: ignore[valid-type] """Type hint for the :data:`FLAG_NEEDS_VALUE` sentinel value."""
Sentinel
python
pennersr__django-allauth
allauth/headless/account/views.py
{ "start": 4821, "end": 7234 }
class ____(APIView): input_class = VerifyEmailInput def handle(self, request, *args, **kwargs): self.stage = LoginStageController.enter(request, EmailVerificationStage.key) if ( not self.stage and account_settings.EMAIL_VERIFICATION_BY_CODE_ENABLED and not request.user.is_authenticated ): return ConflictResponse(request) self.process = None if account_settings.EMAIL_VERIFICATION_BY_CODE_ENABLED: self.process = ( flows.email_verification_by_code.EmailVerificationProcess.resume( request ) ) if not self.process: return ConflictResponse(request) return super().handle(request, *args, **kwargs) def get_input_kwargs(self): return {"process": self.process} def handle_invalid_input(self, input: VerifyEmailInput): if self.process: self.process.record_invalid_attempt() return super().handle_invalid_input(input) def get(self, request, *args, **kwargs): key = request.headers.get("x-email-verification-key", "") input = self.input_class({"key": key}, process=self.process) if not input.is_valid(): if self.process: self.process.record_invalid_attempt() return ErrorResponse(request, input=input) if self.process: email_address = self.process.email_address else: email_address = input.verification.email_address return response.VerifyEmailResponse(request, email_address, stage=self.stage) def post(self, request, *args, **kwargs): if self.process: email_address = self.process.finish() else: email_address = self.input.verification.confirm(request) if not email_address: # Should not happen, VerifyInputInput should have verified all # preconditions. return APIResponse(request, status=HTTPStatus.INTERNAL_SERVER_ERROR) response = None if self.stage: # Verifying email as part of login/signup flow may imply the user is # to be logged in... response = email_verification.login_on_verification(request, email_address) return AuthenticationResponse.from_response(request, response)
VerifyEmailView
python
pytorch__pytorch
torch/cuda/__init__.py
{ "start": 57430, "end": 57644 }
class ____(_CudaLegacyStorage): @classproperty def dtype(self): _warn_typed_storage_removal() return self._dtype @classproperty def _dtype(self): return torch.bool
BoolStorage
python
django__django
django/contrib/admin/templatetags/base.py
{ "start": 100, "end": 1465 }
class ____(InclusionNode): """ Template tag that allows its template to be overridden per model, per app, or globally. """ def __init__(self, parser, token, func, template_name, takes_context=True): self.template_name = template_name params, varargs, varkw, defaults, kwonly, kwonly_defaults, _ = getfullargspec( func ) bits = token.split_contents() args, kwargs = parse_bits( parser, bits[1:], params, varargs, varkw, defaults, kwonly, kwonly_defaults, takes_context, bits[0], ) super().__init__(func, takes_context, args, kwargs, filename=None) def render(self, context): opts = context["opts"] app_label = opts.app_label.lower() object_name = opts.model_name # Load template for this render call. (Setting self.filename isn't # thread-safe.) context.render_context[self] = context.template.engine.select_template( [ "admin/%s/%s/%s" % (app_label, object_name, self.template_name), "admin/%s/%s" % (app_label, self.template_name), "admin/%s" % self.template_name, ] ) return super().render(context)
InclusionAdminNode
python
dagster-io__dagster
python_modules/libraries/dagster-shared/dagster_shared/serdes/objects/package_entry.py
{ "start": 634, "end": 1742 }
class ____: namespace: str name: str @property def package(self) -> str: return self.namespace.split(".")[0] def to_typename(self) -> str: return f"{self.namespace}.{self.name}" @staticmethod def is_valid_typename(typename: str) -> bool: """Check if the typename is valid.""" try: EnvRegistryKey.from_typename(typename) return True except ValueError: return False @staticmethod def from_typename(typename: str) -> "EnvRegistryKey": parts = typename.split(".") for part in parts: if not part.isidentifier(): raise ValueError(_generate_invalid_component_typename_error_message(typename)) if len(parts) < 2: raise ValueError(_generate_invalid_component_typename_error_message(typename)) namespace, _, name = typename.rpartition(".") return EnvRegistryKey(name=name, namespace=namespace) ########### # TYPE DATA ########### EnvRegistryObjectFeature: TypeAlias = Literal["component", "scaffold-target"]
EnvRegistryKey
python
pytorch__pytorch
test/distributed/_composable/fsdp/test_fully_shard_init.py
{ "start": 21083, "end": 26773 }
class ____(FSDPTestMultiThread): @property def world_size(self) -> int: return 2 @skip_if_lt_x_gpu(1) def test_fully_shard_is_root(self): """ Tests that ``_is_root`` is set correctly after lazy initialization. FSDP(model( 0: MLP(FSDP(in_proj), FSDP(out_proj)), 1: MLP(in_proj, out_proj), )) """ model = nn.Sequential(MLP(8), MLP(8)) fully_shard(model[0].in_proj) fully_shard(model[0].out_proj) fully_shard(model) # root gets `model[1]` root_state = fully_shard.state(model) root_state._lazy_init() model0_in_proj_state = fully_shard.state(model[0].in_proj) model0_out_proj_state = fully_shard.state(model[0].out_proj) self.assertTrue(root_state._is_root) self.assertFalse(model0_in_proj_state._is_root) self.assertFalse(model0_out_proj_state._is_root) all_states = root_state._state_ctx.all_states self.assertEqual(len(all_states), 3) self.assertEqual( all_states, [root_state, model0_in_proj_state, model0_out_proj_state] ) @skip_if_lt_x_gpu(1) def test_fully_shard_module_and_param_fqns(self): """ Tests that the module and parameter FQNs are computed correctly after lazy initialization. FSDP(model( 0: MLP(FSDP(in_proj), FSDP(out_proj)), 1: MLP(in_proj, out_proj), )) """ model = nn.Sequential(MLP(8), MLP(8)) fully_shard(model[0].in_proj) fully_shard(model[0].out_proj) fully_shard(model) # root gets `model[1]` root_state = fully_shard.state(model) root_state._lazy_init() root_param_group = root_state._fsdp_param_group self.assertIsNotNone(root_param_group) self.assertEqual(root_param_group._module_fqn, "") root_param_fqns = { fsdp_param._param_fqn for fsdp_param in root_param_group.fsdp_params } self.assertEqual( root_param_fqns, { "1.in_proj.weight", "1.in_proj.bias", "1.out_proj.weight", "1.out_proj.bias", }, ) model0_in_proj_state = fully_shard.state(model[0].in_proj) model0_in_proj_param_group = model0_in_proj_state._fsdp_param_group self.assertIsNotNone(model0_in_proj_param_group) self.assertEqual(model0_in_proj_param_group._module_fqn, "0.in_proj") model0_in_proj_param_fqns = { fsdp_param._param_fqn for fsdp_param in model0_in_proj_param_group.fsdp_params } self.assertEqual( model0_in_proj_param_fqns, {"0.in_proj.weight", "0.in_proj.bias"} ) model0_out_proj_state = fully_shard.state(model[0].out_proj) model0_out_proj_param_group = model0_out_proj_state._fsdp_param_group self.assertIsNotNone(model0_out_proj_param_group) self.assertEqual(model0_out_proj_param_group._module_fqn, "0.out_proj") model0_out_proj_param_fqns = { fsdp_param._param_fqn for fsdp_param in model0_out_proj_param_group.fsdp_params } self.assertEqual( model0_out_proj_param_fqns, {"0.out_proj.weight", "0.out_proj.bias"} ) @skip_if_lt_x_gpu(1) def test_fully_shard_double_lazy_init(self): model = nn.Sequential(MLP(8), MLP(8)) fully_shard(model[0].in_proj) fully_shard(model[0].out_proj) fully_shard(model) root_state = fully_shard.state(model) model0_in_proj_state = fully_shard.state(model[0].in_proj) model0_in_proj_state._lazy_init() regex = ( "FSDP state has already been lazily initialized for 0.in_proj\n" "FSDP requires running forward through the root module first" ) with self.assertRaisesRegex(RuntimeError, regex): root_state._lazy_init() @skip_if_lt_x_gpu(1) def test_fully_shard_multi_module_root(self): model = nn.Sequential(MLP(8), MLP(8)) fully_shard([model[0], model[1]]) root_state = fully_shard.state(model[0]) regex = "FSDP requires a single root module but got " with self.assertRaisesRegex(RuntimeError, regex): root_state._lazy_init() @skip_if_lt_x_gpu(1) def test_reset_sharded_param_in_lazy_init(self): class MyModel(nn.Module): def __init__(self): super().__init__() self.layer1 = nn.Linear(3, 3, bias=False) self.layer2 = nn.Linear(3, 3, bias=False) self.weight_norm = nn.Parameter(torch.empty(3)) def init_weight_norm(self): with torch.no_grad(): weight_norm = torch.linalg.norm( self.layer1.weight, dim=1 ) + torch.linalg.norm(self.layer2.weight, dim=1) model.weight_norm = nn.Parameter(weight_norm) def forward(self, inp: torch.Tensor) -> torch.Tensor: out = self.layer1(inp) out = self.layer2(out) return out.sum() + self.weight_norm.sum() with torch.device("meta"): model = MyModel() fully_shard(model.layer1) fully_shard(model.layer2) fully_shard(model) model.layer1.to_empty(device=device_type.type) model.layer2.to_empty(device=device_type.type) model.init_weight_norm() inp = torch.randn(3, 3, device=device_type.type) loss = model(inp).sum() loss.backward()
TestFullyShardLazyInit
python
ipython__ipython
tests/fake_llm.py
{ "start": 344, "end": 2536 }
class ____(BaseProvider, FakeListLLM): # type: ignore[misc, valid-type] id = "my_provider" name = "My Provider" model_id_key = "model" models = ["model_a"] def __init__(self, **kwargs): kwargs["responses"] = ["This fake response will not be used for completion"] kwargs["model_id"] = "model_a" super().__init__(**kwargs) async def generate_inline_completions(self, request): raise ValueError("IPython only supports streaming models.") async def stream_inline_completions(self, request): from jupyter_ai.completions.models import ( InlineCompletionList, InlineCompletionReply, ) assert request.number > 0 token = f"t{request.number}s0" last_line = request.prefix.splitlines()[-1] if not FIBONACCI.startswith(last_line): return yield InlineCompletionReply( list=InlineCompletionList( items=[ {"insertText": "", "isIncomplete": True, "token": token}, ] ), reply_to=request.number, ) async for reply in self._stream( FIBONACCI[len(last_line) :], request.number, token, ): yield reply async def _stream(self, sentence, request_number, token, start_with=""): from jupyter_ai.completions.models import InlineCompletionStreamChunk suggestion = start_with for fragment in sentence.split(" "): await asyncio.sleep(0.05) if suggestion: suggestion += " " suggestion += fragment yield InlineCompletionStreamChunk( type="stream", response={"insertText": suggestion, "token": token}, reply_to=request_number, done=False, ) # finally, send a message confirming that we are done yield InlineCompletionStreamChunk( type="stream", response={"insertText": suggestion, "token": token}, reply_to=request_number, done=True, )
FibonacciCompletionProvider
python
scipy__scipy
scipy/ndimage/tests/test_filters.py
{ "start": 4714, "end": 111097 }
class ____: def _validate_complex(self, xp, array, kernel, type2, mode='reflect', cval=0, check_warnings=True): # utility for validating complex-valued correlations real_dtype = xp.real(xp.asarray([], dtype=type2)).dtype expected = _complex_correlate( xp, array, kernel, real_dtype, convolve=False, mode=mode, cval=cval ) if array.ndim == 1: correlate = functools.partial(ndimage.correlate1d, axis=-1, mode=mode, cval=cval) convolve = functools.partial(ndimage.convolve1d, axis=-1, mode=mode, cval=cval) else: correlate = functools.partial(ndimage.correlate, mode=mode, cval=cval) convolve = functools.partial(ndimage.convolve, mode=mode, cval=cval) # test correlate output dtype output = correlate(array, kernel, output=type2) assert_array_almost_equal(expected, output) assert output.dtype.type == type2 # test correlate with pre-allocated output output = xp.zeros_like(array, dtype=type2) correlate(array, kernel, output=output) assert_array_almost_equal(expected, output) # test convolve output dtype output = convolve(array, kernel, output=type2) expected = _complex_correlate( xp, array, kernel, real_dtype, convolve=True, mode=mode, cval=cval, ) assert_array_almost_equal(expected, output) assert output.dtype.type == type2 # convolve with pre-allocated output convolve(array, kernel, output=output) assert_array_almost_equal(expected, output) assert output.dtype.type == type2 if check_warnings: # warns if the output is not a complex dtype with pytest.warns(UserWarning, match="promoting specified output dtype to " "complex"): correlate(array, kernel, output=real_dtype) with pytest.warns(UserWarning, match="promoting specified output dtype to " "complex"): convolve(array, kernel, output=real_dtype) # raises if output array is provided, but is not complex-valued output_real = xp.zeros_like(array, dtype=real_dtype) with assert_raises(RuntimeError): correlate(array, kernel, output=output_real) with assert_raises(RuntimeError): convolve(array, kernel, output=output_real) def test_correlate01(self, xp): array = xp.asarray([1, 2]) weights = xp.asarray([2]) expected = xp.asarray([2, 4]) output = ndimage.correlate(array, weights) assert_array_almost_equal(output, expected) output = ndimage.convolve(array, weights) assert_array_almost_equal(output, expected) output = ndimage.correlate1d(array, weights) assert_array_almost_equal(output, expected) output = ndimage.convolve1d(array, weights) assert_array_almost_equal(output, expected) @xfail_xp_backends('cupy', reason="Differs by a factor of two?") @uses_output_array def test_correlate01_overlap(self, xp): array = xp.reshape(xp.arange(256), (16, 16)) weights = xp.asarray([2]) expected = 2 * array ndimage.correlate1d(array, weights, output=array) assert_array_almost_equal(array, expected) def test_correlate02(self, xp): array = xp.asarray([1, 2, 3]) kernel = xp.asarray([1]) output = ndimage.correlate(array, kernel) assert_array_almost_equal(array, output) output = ndimage.convolve(array, kernel) assert_array_almost_equal(array, output) output = ndimage.correlate1d(array, kernel) assert_array_almost_equal(array, output) output = ndimage.convolve1d(array, kernel) assert_array_almost_equal(array, output) def test_correlate03(self, xp): array = xp.asarray([1]) weights = xp.asarray([1, 1]) expected = xp.asarray([2]) output = ndimage.correlate(array, weights) assert_array_almost_equal(output, expected) output = ndimage.convolve(array, weights) assert_array_almost_equal(output, expected) output = ndimage.correlate1d(array, weights) assert_array_almost_equal(output, expected) output = ndimage.convolve1d(array, weights) assert_array_almost_equal(output, expected) def test_correlate04(self, xp): array = xp.asarray([1, 2]) tcor = xp.asarray([2, 3]) tcov = xp.asarray([3, 4]) weights = xp.asarray([1, 1]) output = ndimage.correlate(array, weights) assert_array_almost_equal(output, tcor) output = ndimage.convolve(array, weights) assert_array_almost_equal(output, tcov) output = ndimage.correlate1d(array, weights) assert_array_almost_equal(output, tcor) output = ndimage.convolve1d(array, weights) assert_array_almost_equal(output, tcov) def test_correlate05(self, xp): array = xp.asarray([1, 2, 3]) tcor = xp.asarray([2, 3, 5]) tcov = xp.asarray([3, 5, 6]) kernel = xp.asarray([1, 1]) output = ndimage.correlate(array, kernel) assert_array_almost_equal(tcor, output) output = ndimage.convolve(array, kernel) assert_array_almost_equal(tcov, output) output = ndimage.correlate1d(array, kernel) assert_array_almost_equal(tcor, output) output = ndimage.convolve1d(array, kernel) assert_array_almost_equal(tcov, output) def test_correlate06(self, xp): array = xp.asarray([1, 2, 3]) tcor = xp.asarray([9, 14, 17]) tcov = xp.asarray([7, 10, 15]) weights = xp.asarray([1, 2, 3]) output = ndimage.correlate(array, weights) assert_array_almost_equal(output, tcor) output = ndimage.convolve(array, weights) assert_array_almost_equal(output, tcov) output = ndimage.correlate1d(array, weights) assert_array_almost_equal(output, tcor) output = ndimage.convolve1d(array, weights) assert_array_almost_equal(output, tcov) def test_correlate07(self, xp): array = xp.asarray([1, 2, 3]) expected = xp.asarray([5, 8, 11]) weights = xp.asarray([1, 2, 1]) output = ndimage.correlate(array, weights) assert_array_almost_equal(output, expected) output = ndimage.convolve(array, weights) assert_array_almost_equal(output, expected) output = ndimage.correlate1d(array, weights) assert_array_almost_equal(output, expected) output = ndimage.convolve1d(array, weights) assert_array_almost_equal(output, expected) def test_correlate08(self, xp): array = xp.asarray([1, 2, 3]) tcor = xp.asarray([1, 2, 5]) tcov = xp.asarray([3, 6, 7]) weights = xp.asarray([1, 2, -1]) output = ndimage.correlate(array, weights) assert_array_almost_equal(output, tcor) output = ndimage.convolve(array, weights) assert_array_almost_equal(output, tcov) output = ndimage.correlate1d(array, weights) assert_array_almost_equal(output, tcor) output = ndimage.convolve1d(array, weights) assert_array_almost_equal(output, tcov) def test_correlate09(self, xp): array = xp.asarray([]) kernel = xp.asarray([1, 1]) output = ndimage.correlate(array, kernel) assert_array_almost_equal(array, output) output = ndimage.convolve(array, kernel) assert_array_almost_equal(array, output) output = ndimage.correlate1d(array, kernel) assert_array_almost_equal(array, output) output = ndimage.convolve1d(array, kernel) assert_array_almost_equal(array, output) def test_correlate10(self, xp): array = xp.asarray([[]]) kernel = xp.asarray([[1, 1]]) output = ndimage.correlate(array, kernel) assert_array_almost_equal(array, output) output = ndimage.convolve(array, kernel) assert_array_almost_equal(array, output) def test_correlate11(self, xp): array = xp.asarray([[1, 2, 3], [4, 5, 6]]) kernel = xp.asarray([[1, 1], [1, 1]]) output = ndimage.correlate(array, kernel) assert_array_almost_equal(xp.asarray([[4, 6, 10], [10, 12, 16]]), output) output = ndimage.convolve(array, kernel) assert_array_almost_equal(xp.asarray([[12, 16, 18], [18, 22, 24]]), output) def test_correlate12(self, xp): array = xp.asarray([[1, 2, 3], [4, 5, 6]]) kernel = xp.asarray([[1, 0], [0, 1]]) output = ndimage.correlate(array, kernel) assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output) output = ndimage.convolve(array, kernel) assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output) @uses_output_dtype @pytest.mark.parametrize('dtype_array', types) @pytest.mark.parametrize('dtype_kernel', types) def test_correlate13(self, dtype_array, dtype_kernel, xp): dtype_array = getattr(xp, dtype_array) dtype_kernel = getattr(xp, dtype_kernel) kernel = xp.asarray([[1, 0], [0, 1]]) array = xp.asarray([[1, 2, 3], [4, 5, 6]], dtype=dtype_array) output = ndimage.correlate(array, kernel, output=dtype_kernel) assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output) assert output.dtype.type == dtype_kernel output = ndimage.convolve(array, kernel, output=dtype_kernel) assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output) assert output.dtype.type == dtype_kernel @uses_output_array @pytest.mark.parametrize('dtype_array', types) @pytest.mark.parametrize('dtype_output', types) def test_correlate14(self, dtype_array, dtype_output, xp): dtype_array = getattr(xp, dtype_array) dtype_output = getattr(xp, dtype_output) kernel = xp.asarray([[1, 0], [0, 1]]) array = xp.asarray([[1, 2, 3], [4, 5, 6]], dtype=dtype_array) output = xp.zeros(array.shape, dtype=dtype_output) ndimage.correlate(array, kernel, output=output) assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output) assert output.dtype == dtype_output ndimage.convolve(array, kernel, output=output) assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output) assert output.dtype == dtype_output @uses_output_dtype @pytest.mark.parametrize('dtype_array', types) def test_correlate15(self, dtype_array, xp): dtype_array = getattr(xp, dtype_array) kernel = xp.asarray([[1, 0], [0, 1]]) array = xp.asarray([[1, 2, 3], [4, 5, 6]], dtype=dtype_array) output = ndimage.correlate(array, kernel, output=xp.float32) assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output) assert output.dtype.type == xp.float32 output = ndimage.convolve(array, kernel, output=xp.float32) assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output) assert output.dtype.type == xp.float32 @uses_output_dtype @pytest.mark.parametrize('dtype_array', types) def test_correlate16(self, dtype_array, xp): dtype_array = getattr(xp, dtype_array) kernel = xp.asarray([[0.5, 0], [0, 0.5]]) array = xp.asarray([[1, 2, 3], [4, 5, 6]], dtype=dtype_array) output = ndimage.correlate(array, kernel, output=xp.float32) assert_array_almost_equal(xp.asarray([[1, 1.5, 2.5], [2.5, 3, 4]]), output) assert output.dtype.type == xp.float32 output = ndimage.convolve(array, kernel, output=xp.float32) assert_array_almost_equal(xp.asarray([[3, 4, 4.5], [4.5, 5.5, 6]]), output) assert output.dtype.type == xp.float32 def test_correlate17(self, xp): array = xp.asarray([1, 2, 3]) tcor = xp.asarray([3, 5, 6]) tcov = xp.asarray([2, 3, 5]) kernel = xp.asarray([1, 1]) output = ndimage.correlate(array, kernel, origin=-1) assert_array_almost_equal(tcor, output) output = ndimage.convolve(array, kernel, origin=-1) assert_array_almost_equal(tcov, output) output = ndimage.correlate1d(array, kernel, origin=-1) assert_array_almost_equal(tcor, output) output = ndimage.convolve1d(array, kernel, origin=-1) assert_array_almost_equal(tcov, output) @uses_output_dtype @pytest.mark.parametrize('dtype_array', types) def test_correlate18(self, dtype_array, xp): dtype_array = getattr(xp, dtype_array) kernel = xp.asarray([[1, 0], [0, 1]]) array = xp.asarray([[1, 2, 3], [4, 5, 6]], dtype=dtype_array) output = ndimage.correlate(array, kernel, output=xp.float32, mode='nearest', origin=-1) assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output) assert output.dtype.type == xp.float32 output = ndimage.convolve(array, kernel, output=xp.float32, mode='nearest', origin=-1) assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output) assert output.dtype.type == xp.float32 def test_correlate_mode_sequence(self, xp): kernel = xp.ones((2, 2)) array = xp.ones((3, 3), dtype=xp.float64) with assert_raises(RuntimeError): ndimage.correlate(array, kernel, mode=['nearest', 'reflect']) with assert_raises(RuntimeError): ndimage.convolve(array, kernel, mode=['nearest', 'reflect']) @uses_output_dtype @pytest.mark.parametrize('dtype_array', types) def test_correlate19(self, dtype_array, xp): dtype_array = getattr(xp, dtype_array) kernel = xp.asarray([[1, 0], [0, 1]]) array = xp.asarray([[1, 2, 3], [4, 5, 6]], dtype=dtype_array) output = ndimage.correlate(array, kernel, output=xp.float32, mode='nearest', origin=[-1, 0]) assert_array_almost_equal(xp.asarray([[5, 6, 8], [8, 9, 11]]), output) assert output.dtype.type == xp.float32 output = ndimage.convolve(array, kernel, output=xp.float32, mode='nearest', origin=[-1, 0]) assert_array_almost_equal(xp.asarray([[3, 5, 6], [6, 8, 9]]), output) assert output.dtype.type == xp.float32 @uses_output_array @pytest.mark.parametrize('dtype_array', types) @pytest.mark.parametrize('dtype_output', types) def test_correlate20(self, dtype_array, dtype_output, xp): dtype_array = getattr(xp, dtype_array) dtype_output = getattr(xp, dtype_output) weights = xp.asarray([1, 2, 1]) expected = xp.asarray([[5, 10, 15], [7, 14, 21]]) array = xp.asarray([[1, 2, 3], [2, 4, 6]], dtype=dtype_array) output = xp.zeros((2, 3), dtype=dtype_output) ndimage.correlate1d(array, weights, axis=0, output=output) assert_array_almost_equal(output, expected) ndimage.convolve1d(array, weights, axis=0, output=output) assert_array_almost_equal(output, expected) def test_correlate21(self, xp): array = xp.asarray([[1, 2, 3], [2, 4, 6]]) expected = xp.asarray([[5, 10, 15], [7, 14, 21]]) weights = xp.asarray([1, 2, 1]) output = ndimage.correlate1d(array, weights, axis=0) assert_array_almost_equal(output, expected) output = ndimage.convolve1d(array, weights, axis=0) assert_array_almost_equal(output, expected) @uses_output_array @pytest.mark.parametrize('dtype_array', types) @pytest.mark.parametrize('dtype_output', types) def test_correlate22(self, dtype_array, dtype_output, xp): dtype_array = getattr(xp, dtype_array) dtype_output = getattr(xp, dtype_output) weights = xp.asarray([1, 2, 1]) expected = xp.asarray([[6, 12, 18], [6, 12, 18]]) array = xp.asarray([[1, 2, 3], [2, 4, 6]], dtype=dtype_array) output = xp.zeros((2, 3), dtype=dtype_output) ndimage.correlate1d(array, weights, axis=0, mode='wrap', output=output) assert_array_almost_equal(output, expected) ndimage.convolve1d(array, weights, axis=0, mode='wrap', output=output) assert_array_almost_equal(output, expected) @uses_output_array @pytest.mark.parametrize('dtype_array', types) @pytest.mark.parametrize('dtype_output', types) def test_correlate23(self, dtype_array, dtype_output, xp): dtype_array = getattr(xp, dtype_array) dtype_output = getattr(xp, dtype_output) weights = xp.asarray([1, 2, 1]) expected = xp.asarray([[5, 10, 15], [7, 14, 21]]) array = xp.asarray([[1, 2, 3], [2, 4, 6]], dtype=dtype_array) output = xp.zeros((2, 3), dtype=dtype_output) ndimage.correlate1d(array, weights, axis=0, mode='nearest', output=output) assert_array_almost_equal(output, expected) ndimage.convolve1d(array, weights, axis=0, mode='nearest', output=output) assert_array_almost_equal(output, expected) @uses_output_array @pytest.mark.parametrize('dtype_array', types) @pytest.mark.parametrize('dtype_output', types) def test_correlate24(self, dtype_array, dtype_output, xp): dtype_array = getattr(xp, dtype_array) dtype_output = getattr(xp, dtype_output) weights = xp.asarray([1, 2, 1]) tcor = xp.asarray([[7, 14, 21], [8, 16, 24]]) tcov = xp.asarray([[4, 8, 12], [5, 10, 15]]) array = xp.asarray([[1, 2, 3], [2, 4, 6]], dtype=dtype_array) output = xp.zeros((2, 3), dtype=dtype_output) ndimage.correlate1d(array, weights, axis=0, mode='nearest', output=output, origin=-1) assert_array_almost_equal(output, tcor) ndimage.convolve1d(array, weights, axis=0, mode='nearest', output=output, origin=-1) assert_array_almost_equal(output, tcov) @uses_output_array @pytest.mark.parametrize('dtype_array', types) @pytest.mark.parametrize('dtype_output', types) def test_correlate25(self, dtype_array, dtype_output, xp): dtype_array = getattr(xp, dtype_array) dtype_output = getattr(xp, dtype_output) weights = xp.asarray([1, 2, 1]) tcor = xp.asarray([[4, 8, 12], [5, 10, 15]]) tcov = xp.asarray([[7, 14, 21], [8, 16, 24]]) array = xp.asarray([[1, 2, 3], [2, 4, 6]], dtype=dtype_array) output = xp.zeros((2, 3), dtype=dtype_output) ndimage.correlate1d(array, weights, axis=0, mode='nearest', output=output, origin=1) assert_array_almost_equal(output, tcor) ndimage.convolve1d(array, weights, axis=0, mode='nearest', output=output, origin=1) assert_array_almost_equal(output, tcov) def test_correlate26(self, xp): # test fix for gh-11661 (mirror extension of a length 1 signal) y = ndimage.convolve1d(xp.ones(1), xp.ones(5), mode='mirror') xp_assert_equal(y, xp.asarray([5.])) y = ndimage.correlate1d(xp.ones(1), xp.ones(5), mode='mirror') xp_assert_equal(y, xp.asarray([5.])) @uses_output_dtype @pytest.mark.parametrize('dtype_kernel', complex_types) @pytest.mark.parametrize('dtype_input', types) @pytest.mark.parametrize('dtype_output', complex_types) def test_correlate_complex_kernel(self, dtype_input, dtype_kernel, dtype_output, xp, num_parallel_threads): dtype_input = getattr(xp, dtype_input) dtype_kernel = getattr(xp, dtype_kernel) dtype_output = getattr(xp, dtype_output) kernel = xp.asarray([[1, 0], [0, 1 + 1j]], dtype=dtype_kernel) array = xp.asarray([[1, 2, 3], [4, 5, 6]], dtype=dtype_input) self._validate_complex(xp, array, kernel, dtype_output, check_warnings=num_parallel_threads == 1) @uses_output_dtype @pytest.mark.parametrize('dtype_kernel', complex_types) @pytest.mark.parametrize('dtype_input', types) @pytest.mark.parametrize('dtype_output', complex_types) @pytest.mark.parametrize('mode', ['grid-constant', 'constant']) def test_correlate_complex_kernel_cval(self, dtype_input, dtype_kernel, dtype_output, mode, xp, num_parallel_threads): dtype_input = getattr(xp, dtype_input) dtype_kernel = getattr(xp, dtype_kernel) dtype_output = getattr(xp, dtype_output) if is_cupy(xp) and mode == 'grid-constant': pytest.xfail('cupy/cupy#8404') # test use of non-zero cval with complex inputs # also verifies that mode 'grid-constant' does not segfault kernel = xp.asarray([[1, 0], [0, 1 + 1j]], dtype=dtype_kernel) array = xp.asarray([[1, 2, 3], [4, 5, 6]], dtype=dtype_input) self._validate_complex(xp, array, kernel, dtype_output, mode=mode, cval=5.0, check_warnings=num_parallel_threads == 1) @xfail_xp_backends('cupy', reason="cupy/cupy#8405") @pytest.mark.parametrize('dtype_kernel', complex_types) @pytest.mark.parametrize('dtype_input', types) def test_correlate_complex_kernel_invalid_cval(self, dtype_input, dtype_kernel, xp): dtype_input = getattr(xp, dtype_input) dtype_kernel = getattr(xp, dtype_kernel) # cannot give complex cval with a real image kernel = xp.asarray([[1, 0], [0, 1 + 1j]], dtype=dtype_kernel) array = xp.asarray([[1, 2, 3], [4, 5, 6]], dtype=dtype_input) for func in [ndimage.convolve, ndimage.correlate, ndimage.convolve1d, ndimage.correlate1d]: with pytest.raises((ValueError, TypeError)): func(array, kernel, mode='constant', cval=5.0 + 1.0j, output=xp.complex64) @uses_output_dtype @pytest.mark.parametrize('dtype_kernel', complex_types) @pytest.mark.parametrize('dtype_input', types) @pytest.mark.parametrize('dtype_output', complex_types) def test_correlate1d_complex_kernel(self, dtype_input, dtype_kernel, dtype_output, xp, num_parallel_threads): dtype_input = getattr(xp, dtype_input) dtype_kernel = getattr(xp, dtype_kernel) dtype_output = getattr(xp, dtype_output) kernel = xp.asarray([1, 1 + 1j], dtype=dtype_kernel) array = xp.asarray([1, 2, 3, 4, 5, 6], dtype=dtype_input) self._validate_complex(xp, array, kernel, dtype_output, check_warnings=num_parallel_threads == 1) @uses_output_dtype @pytest.mark.parametrize('dtype_kernel', complex_types) @pytest.mark.parametrize('dtype_input', types) @pytest.mark.parametrize('dtype_output', complex_types) def test_correlate1d_complex_kernel_cval(self, dtype_input, dtype_kernel, dtype_output, xp, num_parallel_threads): dtype_input = getattr(xp, dtype_input) dtype_kernel = getattr(xp, dtype_kernel) dtype_output = getattr(xp, dtype_output) kernel = xp.asarray([1, 1 + 1j], dtype=dtype_kernel) array = xp.asarray([1, 2, 3, 4, 5, 6], dtype=dtype_input) self._validate_complex(xp, array, kernel, dtype_output, mode='constant', cval=5.0, check_warnings=num_parallel_threads == 1) @uses_output_dtype @pytest.mark.parametrize('dtype_kernel', types) @pytest.mark.parametrize('dtype_input', complex_types) @pytest.mark.parametrize('dtype_output', complex_types) def test_correlate_complex_input(self, dtype_input, dtype_kernel, dtype_output, xp, num_parallel_threads): dtype_input = getattr(xp, dtype_input) dtype_kernel = getattr(xp, dtype_kernel) dtype_output = getattr(xp, dtype_output) kernel = xp.asarray([[1, 0], [0, 1]], dtype=dtype_kernel) array = xp.asarray([[1, 2j, 3], [1 + 4j, 5, 6j]], dtype=dtype_input) self._validate_complex(xp, array, kernel, dtype_output, check_warnings=num_parallel_threads == 1) @uses_output_dtype @pytest.mark.parametrize('dtype_kernel', types) @pytest.mark.parametrize('dtype_input', complex_types) @pytest.mark.parametrize('dtype_output', complex_types) def test_correlate1d_complex_input(self, dtype_input, dtype_kernel, dtype_output, xp, num_parallel_threads): dtype_input = getattr(xp, dtype_input) dtype_kernel = getattr(xp, dtype_kernel) dtype_output = getattr(xp, dtype_output) kernel = xp.asarray([1, 0, 1], dtype=dtype_kernel) array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype_input) self._validate_complex(xp, array, kernel, dtype_output, check_warnings=num_parallel_threads == 1) @uses_output_dtype @xfail_xp_backends("cupy", reason="cupy/cupy#8405") @pytest.mark.parametrize('dtype_kernel', types) @pytest.mark.parametrize('dtype_input', complex_types) @pytest.mark.parametrize('dtype_output', complex_types) def test_correlate1d_complex_input_cval(self, dtype_input, dtype_kernel, dtype_output, xp, num_parallel_threads): dtype_input = getattr(xp, dtype_input) dtype_kernel = getattr(xp, dtype_kernel) dtype_output = getattr(xp, dtype_output) kernel = xp.asarray([1, 0, 1], dtype=dtype_kernel) array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype_input) self._validate_complex(xp, array, kernel, dtype_output, mode='constant', cval=5 - 3j, check_warnings=num_parallel_threads == 1) @uses_output_dtype @xfail_xp_backends("cupy", reason="unhashable type: 'ndarray'") @pytest.mark.parametrize('dtype', complex_types) @pytest.mark.parametrize('dtype_output', complex_types) def test_correlate_complex_input_and_kernel(self, dtype, dtype_output, xp, num_parallel_threads): dtype = getattr(xp, dtype) dtype_output = getattr(xp, dtype_output) kernel = xp.asarray([[1, 0], [0, 1 + 1j]], dtype=dtype) array = xp.asarray([[1, 2j, 3], [1 + 4j, 5, 6j]], dtype=dtype) self._validate_complex(xp, array, kernel, dtype_output, check_warnings=num_parallel_threads == 1) @uses_output_dtype @xfail_xp_backends("cupy", reason="cupy/cupy#8405") @pytest.mark.parametrize('dtype', complex_types) @pytest.mark.parametrize('dtype_output', complex_types) def test_correlate_complex_input_and_kernel_cval(self, dtype, dtype_output, xp, num_parallel_threads): dtype = getattr(xp, dtype) dtype_output = getattr(xp, dtype_output) kernel = xp.asarray([[1, 0], [0, 1 + 1j]], dtype=dtype) array = xp.asarray([[1, 2, 3], [4, 5, 6]], dtype=dtype) self._validate_complex(xp, array, kernel, dtype_output, mode='constant', cval=5.0 + 2.0j, check_warnings=num_parallel_threads == 1) @uses_output_dtype @xfail_xp_backends("cupy", reason="unhashable type: 'ndarray'") @pytest.mark.parametrize('dtype', complex_types) @pytest.mark.parametrize('dtype_output', complex_types) def test_correlate1d_complex_input_and_kernel(self, dtype, dtype_output, xp, num_parallel_threads): dtype = getattr(xp, dtype) dtype_output = getattr(xp, dtype_output) kernel = xp.asarray([1, 1 + 1j], dtype=dtype) array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype) self._validate_complex(xp, array, kernel, dtype_output, check_warnings=num_parallel_threads == 1) @uses_output_dtype @xfail_xp_backends("cupy", reason="cupy/cupy#8405") @pytest.mark.parametrize('dtype', complex_types) @pytest.mark.parametrize('dtype_output', complex_types) def test_correlate1d_complex_input_and_kernel_cval(self, dtype, dtype_output, xp, num_parallel_threads): dtype = getattr(xp, dtype) dtype_output = getattr(xp, dtype_output) kernel = xp.asarray([1, 1 + 1j], dtype=dtype) array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype) self._validate_complex(xp, array, kernel, dtype_output, mode='constant', cval=5.0 + 2.0j, check_warnings=num_parallel_threads == 1) def test_gauss01(self, xp): input = xp.asarray([[1, 2, 3], [2, 4, 6]], dtype=xp.float32) output = ndimage.gaussian_filter(input, 0) assert_array_almost_equal(output, input) def test_gauss02(self, xp): input = xp.asarray([[1, 2, 3], [2, 4, 6]], dtype=xp.float32) output = ndimage.gaussian_filter(input, 1.0) assert input.dtype == output.dtype assert input.shape == output.shape @xfail_xp_backends("cupy", reason="cupy/cupy#8403") def test_gauss03(self, xp): # single precision data input = xp.arange(100 * 100, dtype=xp.float32) input = xp.reshape(input, (100, 100)) output = ndimage.gaussian_filter(input, [1.0, 1.0]) assert input.dtype == output.dtype assert input.shape == output.shape # input.sum() is 49995000.0. With single precision floats, we can't # expect more than 8 digits of accuracy, so use decimal=0 in this test. o_sum = xp.sum(output, dtype=xp.float64) i_sum = xp.sum(input, dtype=xp.float64) assert_almost_equal(o_sum, i_sum, decimal=0) assert sumsq(input, output) > 1.0 @uses_output_dtype def test_gauss04(self, xp): input = xp.arange(100 * 100, dtype=xp.float32) input = xp.reshape(input, (100, 100)) otype = xp.float64 output = ndimage.gaussian_filter(input, [1.0, 1.0], output=otype) assert output.dtype.type == xp.float64 assert input.shape == output.shape assert sumsq(input, output) > 1.0 @uses_output_dtype def test_gauss05(self, xp): input = xp.arange(100 * 100, dtype=xp.float32) input = xp.reshape(input, (100, 100)) otype = xp.float64 output = ndimage.gaussian_filter(input, [1.0, 1.0], order=1, output=otype) assert output.dtype.type == xp.float64 assert input.shape == output.shape assert sumsq(input, output) > 1.0 @uses_output_dtype def test_gauss06(self, xp): input = xp.arange(100 * 100, dtype=xp.float32) input = xp.reshape(input, (100, 100)) otype = xp.float64 output1 = ndimage.gaussian_filter(input, [1.0, 1.0], output=otype) output2 = ndimage.gaussian_filter(input, 1.0, output=otype) assert_array_almost_equal(output1, output2) @uses_output_array def test_gauss_memory_overlap(self, xp): input = xp.arange(100 * 100, dtype=xp.float32) input = xp.reshape(input, (100, 100)) output1 = ndimage.gaussian_filter(input, 1.0) ndimage.gaussian_filter(input, 1.0, output=input) assert_array_almost_equal(output1, input) @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339") @pytest.mark.parametrize(('filter_func', 'extra_args', 'size0', 'size'), [(ndimage.gaussian_filter, (), 0, 1.0), (ndimage.uniform_filter, (), 1, 3), (ndimage.minimum_filter, (), 1, 3), (ndimage.maximum_filter, (), 1, 3), (ndimage.median_filter, (), 1, 3), (ndimage.rank_filter, (1,), 1, 3), (ndimage.percentile_filter, (40,), 1, 3)]) @pytest.mark.parametrize( 'axes', tuple(itertools.combinations(range(-3, 3), 1)) + tuple(itertools.combinations(range(-3, 3), 2)) + ((0, 1, 2),)) def test_filter_axes(self, filter_func, extra_args, size0, size, axes, xp): # Note: `size` is called `sigma` in `gaussian_filter` array = xp.arange(6 * 8 * 12, dtype=xp.float64) array = xp.reshape(array, (6, 8, 12)) if len(set(ax % array.ndim for ax in axes)) != len(axes): # parametrized cases with duplicate axes raise an error with pytest.raises(ValueError, match="axes must be unique"): filter_func(array, *extra_args, size, axes=axes) return output = filter_func(array, *extra_args, size, axes=axes) # result should be equivalent to sigma=0.0/size=1 on unfiltered axes axes = xp.asarray(axes) all_sizes = tuple(size if ax in (axes % array.ndim) else size0 for ax in range(array.ndim)) expected = filter_func(array, *extra_args, all_sizes) xp_assert_close(output, expected) @skip_xp_backends("cupy", reason="these filters do not yet have axes support") @pytest.mark.parametrize(('filter_func', 'kwargs'), [(ndimage.laplace, {}), (ndimage.gaussian_gradient_magnitude, {"sigma": 1.0}), (ndimage.gaussian_laplace, {"sigma": 0.5})]) def test_derivative_filter_axes(self, xp, filter_func, kwargs): array = xp.arange(6 * 8 * 12, dtype=xp.float64) array = xp.reshape(array, (6, 8, 12)) # duplicate axes raises an error with pytest.raises(ValueError, match="axes must be unique"): filter_func(array, axes=(1, 1), **kwargs) # compare results to manually looping over the non-filtered axes output = filter_func(array, axes=(1, 2), **kwargs) expected = xp.empty_like(output) expected = [] for i in range(array.shape[0]): expected.append(filter_func(array[i, ...], **kwargs)) expected = xp.stack(expected, axis=0) xp_assert_close(output, expected) output = filter_func(array, axes=(0, -1), **kwargs) expected = [] for i in range(array.shape[1]): expected.append(filter_func(array[:, i, :], **kwargs)) expected = xp.stack(expected, axis=1) xp_assert_close(output, expected) output = filter_func(array, axes=(1), **kwargs) expected = [] for i in range(array.shape[0]): exp_inner = [] for j in range(array.shape[2]): exp_inner.append(filter_func(array[i, :, j], **kwargs)) expected.append(xp.stack(exp_inner, axis=-1)) expected = xp.stack(expected, axis=0) xp_assert_close(output, expected) @skip_xp_backends("cupy", reason="generic_filter does not yet have axes support") @pytest.mark.parametrize( 'axes', tuple(itertools.combinations(range(-3, 3), 1)) + tuple(itertools.combinations(range(-3, 3), 2)) + ((0, 1, 2),)) def test_generic_filter_axes(self, xp, axes): array = xp.arange(6 * 8 * 12, dtype=xp.float64) array = xp.reshape(array, (6, 8, 12)) size = 3 if len(set(ax % array.ndim for ax in axes)) != len(axes): # parametrized cases with duplicate axes raise an error with pytest.raises(ValueError, match="axes must be unique"): ndimage.generic_filter(array, np.amax, size=size, axes=axes) return # choose np.amax as the function so we can compare to maximum_filter output = ndimage.generic_filter(array, np.amax, size=size, axes=axes) expected = ndimage.maximum_filter(array, size=size, axes=axes) xp_assert_close(output, expected) @skip_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339") @pytest.mark.parametrize('func', [ndimage.correlate, ndimage.convolve]) @pytest.mark.parametrize( 'dtype', [np.float32, np.float64, np.complex64, np.complex128] ) @pytest.mark.parametrize( 'axes', tuple(itertools.combinations(range(-3, 3), 2)) ) @pytest.mark.parametrize('origin', [(0, 0), (-1, 1)]) def test_correlate_convolve_axes(self, xp, func, dtype, axes, origin): array = xp.asarray(np.arange(6 * 8 * 12, dtype=dtype).reshape(6, 8, 12)) weights = xp.arange(3 * 5) weights = xp.reshape(weights, (3, 5)) axes = tuple(ax % array.ndim for ax in axes) if len(tuple(set(axes))) != len(axes): # parametrized cases with duplicate axes raise an error with pytest.raises(ValueError): func(array, weights=weights, axes=axes, origin=origin) return output = func(array, weights=weights, axes=axes, origin=origin) missing_axis = tuple(set(range(3)) - set(axes))[0] # module 'torch' has no attribute 'expand_dims' so use reshape instead # weights_3d = xp.expand_dims(weights, axis=missing_axis) shape_3d = ( weights.shape[:missing_axis] + (1,) + weights.shape[missing_axis:] ) weights_3d = xp.reshape(weights, shape_3d) origin_3d = [0, 0, 0] for i, ax in enumerate(axes): origin_3d[ax] = origin[i] expected = func(array, weights=weights_3d, origin=origin_3d) xp_assert_close(output, expected) kwargs_gauss = dict(radius=[4, 2, 3], order=[0, 1, 2], mode=['reflect', 'nearest', 'constant']) kwargs_other = dict(origin=(-1, 0, 1), mode=['reflect', 'nearest', 'constant']) kwargs_rank = dict(origin=(-1, 0, 1)) @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339") @pytest.mark.parametrize("filter_func, size0, size, kwargs", [(ndimage.gaussian_filter, 0, 1.0, kwargs_gauss), (ndimage.uniform_filter, 1, 3, kwargs_other), (ndimage.maximum_filter, 1, 3, kwargs_other), (ndimage.minimum_filter, 1, 3, kwargs_other), (ndimage.median_filter, 1, 3, kwargs_rank), (ndimage.rank_filter, 1, 3, kwargs_rank), (ndimage.percentile_filter, 1, 3, kwargs_rank)]) @pytest.mark.parametrize('axes', itertools.combinations(range(-3, 3), 2)) def test_filter_axes_kwargs(self, filter_func, size0, size, kwargs, axes, xp): array = xp.arange(6 * 8 * 12, dtype=xp.float64) array = xp.reshape(array, (6, 8, 12)) kwargs = {key: np.array(val) for key, val in kwargs.items()} axes = np.array(axes) n_axes = axes.size if filter_func == ndimage.rank_filter: args = (2,) # (rank,) elif filter_func == ndimage.percentile_filter: args = (30,) # (percentile,) else: args = () # form kwargs that specify only the axes in `axes` reduced_kwargs = {key: val[axes] for key, val in kwargs.items()} if len(set(axes % array.ndim)) != len(axes): # parametrized cases with duplicate axes raise an error with pytest.raises(ValueError, match="axes must be unique"): filter_func(array, *args, [size]*n_axes, axes=axes, **reduced_kwargs) return output = filter_func(array, *args, [size]*n_axes, axes=axes, **reduced_kwargs) # result should be equivalent to sigma=0.0/size=1 on unfiltered axes size_3d = np.full(array.ndim, fill_value=size0) size_3d[axes] = size size_3d = [size_3d[i] for i in range(size_3d.shape[0])] if 'origin' in kwargs: # origin should be zero on the axis that has size 0 origin = np.asarray([0, 0, 0]) origin[axes] = reduced_kwargs['origin'] origin = xp.asarray(origin) kwargs['origin'] = origin expected = filter_func(array, *args, size_3d, **kwargs) xp_assert_close(output, expected) @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339") @pytest.mark.parametrize("filter_func, kwargs", [(ndimage.convolve, {}), (ndimage.correlate, {}), (ndimage.minimum_filter, {}), (ndimage.maximum_filter, {}), (ndimage.median_filter, {}), (ndimage.rank_filter, {"rank": 1}), (ndimage.percentile_filter, {"percentile": 30})]) def test_filter_weights_subset_axes_origins(self, filter_func, kwargs, xp): axes = (-2, -1) origins = (0, 1) array = xp.arange(6 * 8 * 12, dtype=xp.float64) array = xp.reshape(array, (6, 8, 12)) # weights with ndim matching len(axes) footprint = np.ones((3, 5), dtype=bool) footprint[0, 1] = 0 # make non-separable footprint = xp.asarray(footprint) if filter_func in (ndimage.convolve, ndimage.correlate): kwargs["weights"] = footprint else: kwargs["footprint"] = footprint kwargs["axes"] = axes output = filter_func(array, origin=origins, **kwargs) output0 = filter_func(array, origin=0, **kwargs) # output has origin shift on last axis relative to output0, so # expect shifted arrays to be equal. if filter_func == ndimage.convolve: # shift is in the opposite direction for convolve because it # flips the weights array and negates the origin values. xp_assert_equal( output[:, :, :-origins[1]], output0[:, :, origins[1]:]) else: xp_assert_equal( output[:, :, origins[1]:], output0[:, :, :-origins[1]]) @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339") @pytest.mark.parametrize( 'filter_func, args', [(ndimage.convolve, (np.ones((3, 3, 3)),)), # args = (weights,) (ndimage.correlate,(np.ones((3, 3, 3)),)), # args = (weights,) (ndimage.gaussian_filter, (1.0,)), # args = (sigma,) (ndimage.uniform_filter, (3,)), # args = (size,) (ndimage.minimum_filter, (3,)), # args = (size,) (ndimage.maximum_filter, (3,)), # args = (size,) (ndimage.median_filter, (3,)), # args = (size,) (ndimage.rank_filter, (2, 3)), # args = (rank, size) (ndimage.percentile_filter, (30, 3))]) # args = (percentile, size) @pytest.mark.parametrize( 'axes', [(1.5,), (0, 1, 2, 3), (3,), (-4,)] ) def test_filter_invalid_axes(self, filter_func, args, axes, xp): array = xp.arange(6 * 8 * 12, dtype=xp.float64) array = xp.reshape(array, (6, 8, 12)) args = [ xp.asarray(arg) if isinstance(arg, np.ndarray) else arg for arg in args ] if any(isinstance(ax, float) for ax in axes): error_class = TypeError match = "cannot be interpreted as an integer" else: error_class = ValueError match = "out of range" with pytest.raises(error_class, match=match): filter_func(array, *args, axes=axes) @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339") @pytest.mark.parametrize( 'filter_func, kwargs', [(ndimage.convolve, {}), (ndimage.correlate, {}), (ndimage.minimum_filter, {}), (ndimage.maximum_filter, {}), (ndimage.median_filter, {}), (ndimage.rank_filter, dict(rank=3)), (ndimage.percentile_filter, dict(percentile=30))]) @pytest.mark.parametrize( 'axes', [(0, ), (1, 2), (0, 1, 2)] ) @pytest.mark.parametrize('separable_footprint', [False, True]) def test_filter_invalid_footprint_ndim(self, filter_func, kwargs, axes, separable_footprint, xp): array = xp.arange(6 * 8 * 12, dtype=xp.float64) array = xp.reshape(array, (6, 8, 12)) # create a footprint with one too many dimensions footprint = np.ones((3,) * (len(axes) + 1)) if not separable_footprint: footprint[(0,) * footprint.ndim] = 0 footprint = xp.asarray(footprint) if (filter_func in [ndimage.minimum_filter, ndimage.maximum_filter] and separable_footprint): match = "sequence argument must have length equal to input rank" elif filter_func in [ndimage.convolve, ndimage.correlate]: match = re.escape(f"weights.ndim ({footprint.ndim}) must match " f"len(axes) ({len(axes)})") else: match = re.escape(f"footprint.ndim ({footprint.ndim}) must match " f"len(axes) ({len(axes)})") if filter_func in [ndimage.convolve, ndimage.correlate]: kwargs["weights"] = footprint else: kwargs["footprint"] = footprint with pytest.raises(RuntimeError, match=match): filter_func(array, axes=axes, **kwargs) @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339") @pytest.mark.parametrize('n_mismatch', [1, 3]) @pytest.mark.parametrize('filter_func, kwargs, key, val', _cases_axes_tuple_length_mismatch()) def test_filter_tuple_length_mismatch(self, n_mismatch, filter_func, kwargs, key, val, xp): # Test for the intended RuntimeError when a kwargs has an invalid size array = xp.arange(6 * 8 * 12, dtype=xp.float64) array = xp.reshape(array, (6, 8, 12)) axes = (0, 1) kwargs = dict(**kwargs, axes=axes) kwargs[key] = (val,) * n_mismatch if filter_func in [ndimage.convolve, ndimage.correlate]: kwargs["weights"] = xp.ones((5,) * len(axes)) err_msg = "sequence argument must have length equal to input rank" with pytest.raises(RuntimeError, match=err_msg): filter_func(array, **kwargs) @pytest.mark.parametrize('dtype', types + complex_types) def test_prewitt01(self, dtype, xp): dtype = getattr(xp, dtype) array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], dtype=dtype) t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0) t = ndimage.correlate1d(t, xp.asarray([1.0, 1.0, 1.0]), 1) output = ndimage.prewitt(array, 0) assert_array_almost_equal(t, output) @uses_output_array @pytest.mark.parametrize('dtype', types + complex_types) def test_prewitt02(self, dtype, xp): dtype = getattr(xp, dtype) array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], dtype=dtype) t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0) t = ndimage.correlate1d(t, xp.asarray([1.0, 1.0, 1.0]), 1) output = xp.zeros(array.shape, dtype=dtype) ndimage.prewitt(array, 0, output) assert_array_almost_equal(t, output) @pytest.mark.parametrize('dtype', types + complex_types) def test_prewitt03(self, dtype, xp): dtype = getattr(xp, dtype) if is_cupy(xp) and dtype in [xp.uint32, xp.uint64]: pytest.xfail("uint UB? XXX") array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], dtype=dtype) t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 1) t = ndimage.correlate1d(t, xp.asarray([1.0, 1.0, 1.0]), 0) output = ndimage.prewitt(array, 1) assert_array_almost_equal(t, output) @pytest.mark.parametrize('dtype', types + complex_types) def test_prewitt04(self, dtype, xp): dtype = getattr(xp, dtype) array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], dtype=dtype) t = ndimage.prewitt(array, -1) output = ndimage.prewitt(array, 1) assert_array_almost_equal(t, output) @pytest.mark.parametrize('dtype', types + complex_types) def test_sobel01(self, dtype, xp): dtype = getattr(xp, dtype) array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], dtype=dtype) t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0) t = ndimage.correlate1d(t, xp.asarray([1.0, 2.0, 1.0]), 1) output = ndimage.sobel(array, 0) assert_array_almost_equal(t, output) @uses_output_array @pytest.mark.parametrize('dtype', types + complex_types) def test_sobel02(self, dtype, xp): dtype = getattr(xp, dtype) array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], dtype=dtype) t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0) t = ndimage.correlate1d(t, xp.asarray([1.0, 2.0, 1.0]), 1) output = xp.zeros(array.shape, dtype=dtype) ndimage.sobel(array, 0, output) assert_array_almost_equal(t, output) @pytest.mark.parametrize('dtype', types + complex_types) def test_sobel03(self, dtype, xp): if is_cupy(xp) and dtype in ["uint32", "uint64"]: pytest.xfail("uint UB? XXX") dtype = getattr(xp, dtype) array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], dtype=dtype) t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 1) t = ndimage.correlate1d(t, xp.asarray([1.0, 2.0, 1.0]), 0) output = xp.zeros(array.shape, dtype=dtype) output = ndimage.sobel(array, 1) assert_array_almost_equal(t, output) @pytest.mark.parametrize('dtype', types + complex_types) def test_sobel04(self, dtype, xp): dtype = getattr(xp, dtype) array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], dtype=dtype) t = ndimage.sobel(array, -1) output = ndimage.sobel(array, 1) assert_array_almost_equal(t, output) @pytest.mark.parametrize('dtype', ["int32", "float32", "float64", "complex64", "complex128"]) def test_laplace01(self, dtype, xp): dtype = getattr(xp, dtype) array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], dtype=dtype) * 100 tmp1 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 0) tmp2 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 1) output = ndimage.laplace(array) assert_array_almost_equal(tmp1 + tmp2, output) @uses_output_array @pytest.mark.parametrize('dtype', ["int32", "float32", "float64", "complex64", "complex128"]) def test_laplace02(self, dtype, xp): dtype = getattr(xp, dtype) array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], dtype=dtype) * 100 tmp1 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 0) tmp2 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 1) output = xp.zeros(array.shape, dtype=dtype) ndimage.laplace(array, output=output) assert_array_almost_equal(tmp1 + tmp2, output) @pytest.mark.parametrize('dtype', ["int32", "float32", "float64", "complex64", "complex128"]) def test_gaussian_laplace01(self, dtype, xp): dtype = getattr(xp, dtype) array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], dtype=dtype) * 100 tmp1 = ndimage.gaussian_filter(array, 1.0, [2, 0]) tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 2]) output = ndimage.gaussian_laplace(array, 1.0) assert_array_almost_equal(tmp1 + tmp2, output) @uses_output_array @pytest.mark.parametrize('dtype', ["int32", "float32", "float64", "complex64", "complex128"]) def test_gaussian_laplace02(self, dtype, xp): dtype = getattr(xp, dtype) array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], dtype=dtype) * 100 tmp1 = ndimage.gaussian_filter(array, 1.0, [2, 0]) tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 2]) output = xp.zeros(array.shape, dtype=dtype) ndimage.gaussian_laplace(array, 1.0, output) assert_array_almost_equal(tmp1 + tmp2, output) @uses_output_array @pytest.mark.parametrize('dtype', types + complex_types) def test_generic_laplace01(self, dtype, xp): def derivative2(input, axis, output, mode, cval, a, b): sigma = np.asarray([a, b / 2.0]) order = [0] * input.ndim order[axis] = 2 return ndimage.gaussian_filter(input, sigma, order, output, mode, cval) dtype = getattr(xp, dtype) array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], dtype=dtype) output = xp.zeros(array.shape, dtype=dtype) tmp = ndimage.generic_laplace(array, derivative2, extra_arguments=(1.0,), extra_keywords={'b': 2.0}) ndimage.gaussian_laplace(array, 1.0, output) assert_array_almost_equal(tmp, output) @pytest.mark.parametrize('dtype', ["int32", "float32", "float64", "complex64", "complex128"]) def test_gaussian_gradient_magnitude01(self, dtype, xp): is_int_dtype = dtype == "int32" dtype = getattr(xp, dtype) array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], dtype=dtype) * 100 tmp1 = ndimage.gaussian_filter(array, 1.0, [1, 0]) tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 1]) output = ndimage.gaussian_gradient_magnitude(array, 1.0) expected = tmp1 * tmp1 + tmp2 * tmp2 expected_float = xp.astype(expected, xp.float64) if is_int_dtype else expected expected = xp.astype(xp.sqrt(expected_float), dtype) xp_assert_close(output, expected, rtol=1e-6, atol=1e-6) @uses_output_array @pytest.mark.parametrize('dtype', ["int32", "float32", "float64", "complex64", "complex128"]) def test_gaussian_gradient_magnitude02(self, dtype, xp): is_int_dtype = dtype == 'int32' dtype = getattr(xp, dtype) array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], dtype=dtype) * 100 tmp1 = ndimage.gaussian_filter(array, 1.0, [1, 0]) tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 1]) output = xp.zeros(array.shape, dtype=dtype) ndimage.gaussian_gradient_magnitude(array, 1.0, output) expected = tmp1 * tmp1 + tmp2 * tmp2 fl_expected = xp.astype(expected, xp.float64) if is_int_dtype else expected expected = xp.astype(xp.sqrt(fl_expected), dtype) xp_assert_close(output, expected, rtol=1e-6, atol=1e-6) def test_generic_gradient_magnitude01(self, xp): array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], dtype=xp.float64) def derivative(input, axis, output, mode, cval, a, b): sigma = [a, b / 2.0] order = [0] * input.ndim order[axis] = 1 return ndimage.gaussian_filter(input, sigma, order, output, mode, cval) tmp1 = ndimage.gaussian_gradient_magnitude(array, 1.0) tmp2 = ndimage.generic_gradient_magnitude( array, derivative, extra_arguments=(1.0,), extra_keywords={'b': 2.0}) assert_array_almost_equal(tmp1, tmp2) def test_uniform01(self, xp): array = xp.asarray([2, 4, 6]) size = 2 output = ndimage.uniform_filter1d(array, size, origin=-1) assert_array_almost_equal(xp.asarray([3, 5, 6]), output) def test_uniform01_complex(self, xp): array = xp.asarray([2 + 1j, 4 + 2j, 6 + 3j], dtype=xp.complex128) size = 2 output = ndimage.uniform_filter1d(array, size, origin=-1) assert_array_almost_equal(xp.real(output), xp.asarray([3., 5, 6])) assert_array_almost_equal(xp.imag(output), xp.asarray([1.5, 2.5, 3])) def test_uniform02(self, xp): array = xp.asarray([1, 2, 3]) filter_shape = [0] output = ndimage.uniform_filter(array, filter_shape) assert_array_almost_equal(array, output) def test_uniform03(self, xp): array = xp.asarray([1, 2, 3]) filter_shape = [1] output = ndimage.uniform_filter(array, filter_shape) assert_array_almost_equal(array, output) def test_uniform04(self, xp): array = xp.asarray([2, 4, 6]) filter_shape = [2] output = ndimage.uniform_filter(array, filter_shape) assert_array_almost_equal(xp.asarray([2, 3, 5]), output) def test_uniform05(self, xp): array = xp.asarray([]) filter_shape = [1] output = ndimage.uniform_filter(array, filter_shape) assert_array_almost_equal(xp.asarray([]), output) @uses_output_dtype @pytest.mark.parametrize('dtype_array', types) @pytest.mark.parametrize('dtype_output', types) def test_uniform06(self, dtype_array, dtype_output, xp): dtype_array = getattr(xp, dtype_array) dtype_output = getattr(xp, dtype_output) filter_shape = [2, 2] array = xp.asarray([[4, 8, 12], [16, 20, 24]], dtype=dtype_array) output = ndimage.uniform_filter( array, filter_shape, output=dtype_output) assert_array_almost_equal(xp.asarray([[4, 6, 10], [10, 12, 16]]), output) assert output.dtype.type == dtype_output @uses_output_dtype @pytest.mark.parametrize('dtype_array', complex_types) @pytest.mark.parametrize('dtype_output', complex_types) def test_uniform06_complex(self, dtype_array, dtype_output, xp): dtype_array = getattr(xp, dtype_array) dtype_output = getattr(xp, dtype_output) filter_shape = [2, 2] array = xp.asarray([[4, 8 + 5j, 12], [16, 20, 24]], dtype=dtype_array) output = ndimage.uniform_filter( array, filter_shape, output=dtype_output) assert_array_almost_equal(xp.asarray([[4, 6, 10], [10, 12, 16]]), output.real) assert output.dtype.type == dtype_output def test_minimum_filter01(self, xp): array = xp.asarray([1, 2, 3, 4, 5]) filter_shape = xp.asarray([2]) output = ndimage.minimum_filter(array, filter_shape) assert_array_almost_equal(xp.asarray([1, 1, 2, 3, 4]), output) def test_minimum_filter02(self, xp): array = xp.asarray([1, 2, 3, 4, 5]) filter_shape = xp.asarray([3]) output = ndimage.minimum_filter(array, filter_shape) assert_array_almost_equal(xp.asarray([1, 1, 2, 3, 4]), output) def test_minimum_filter03(self, xp): array = xp.asarray([3, 2, 5, 1, 4]) filter_shape = xp.asarray([2]) output = ndimage.minimum_filter(array, filter_shape) assert_array_almost_equal(xp.asarray([3, 2, 2, 1, 1]), output) def test_minimum_filter04(self, xp): array = xp.asarray([3, 2, 5, 1, 4]) filter_shape = xp.asarray([3]) output = ndimage.minimum_filter(array, filter_shape) assert_array_almost_equal(xp.asarray([2, 2, 1, 1, 1]), output) def test_minimum_filter05(self, xp): array = xp.asarray([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) filter_shape = xp.asarray([2, 3]) output = ndimage.minimum_filter(array, filter_shape) assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1], [2, 2, 1, 1, 1], [5, 3, 3, 1, 1]]), output) @uses_output_array def test_minimum_filter05_overlap(self, xp): array = xp.asarray([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) filter_shape = xp.asarray([2, 3]) ndimage.minimum_filter(array, filter_shape, output=array) assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1], [2, 2, 1, 1, 1], [5, 3, 3, 1, 1]]), array) def test_minimum_filter06(self, xp): array = xp.asarray([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = xp.asarray([[1, 1, 1], [1, 1, 1]]) output = ndimage.minimum_filter(array, footprint=footprint) assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1], [2, 2, 1, 1, 1], [5, 3, 3, 1, 1]]), output) # separable footprint should allow mode sequence output2 = ndimage.minimum_filter(array, footprint=footprint, mode=['reflect', 'reflect']) assert_array_almost_equal(output2, output) def test_minimum_filter07(self, xp): array = xp.asarray([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) output = ndimage.minimum_filter(array, footprint=footprint) assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1], [2, 3, 1, 3, 1], [5, 5, 3, 3, 1]]), output) with assert_raises(RuntimeError): ndimage.minimum_filter(array, footprint=footprint, mode=['reflect', 'constant']) def test_minimum_filter08(self, xp): array = xp.asarray([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) output = ndimage.minimum_filter(array, footprint=footprint, origin=-1) assert_array_almost_equal(xp.asarray([[3, 1, 3, 1, 1], [5, 3, 3, 1, 1], [3, 3, 1, 1, 1]]), output) def test_minimum_filter09(self, xp): array = xp.asarray([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) output = ndimage.minimum_filter(array, footprint=footprint, origin=[-1, 0]) assert_array_almost_equal(xp.asarray([[2, 3, 1, 3, 1], [5, 5, 3, 3, 1], [5, 3, 3, 1, 1]]), output) def test_maximum_filter01(self, xp): array = xp.asarray([1, 2, 3, 4, 5]) filter_shape = xp.asarray([2]) output = ndimage.maximum_filter(array, filter_shape) assert_array_almost_equal(xp.asarray([1, 2, 3, 4, 5]), output) def test_maximum_filter02(self, xp): array = xp.asarray([1, 2, 3, 4, 5]) filter_shape = xp.asarray([3]) output = ndimage.maximum_filter(array, filter_shape) assert_array_almost_equal(xp.asarray([2, 3, 4, 5, 5]), output) def test_maximum_filter03(self, xp): array = xp.asarray([3, 2, 5, 1, 4]) filter_shape = xp.asarray([2]) output = ndimage.maximum_filter(array, filter_shape) assert_array_almost_equal(xp.asarray([3, 3, 5, 5, 4]), output) def test_maximum_filter04(self, xp): array = xp.asarray([3, 2, 5, 1, 4]) filter_shape = xp.asarray([3]) output = ndimage.maximum_filter(array, filter_shape) assert_array_almost_equal(xp.asarray([3, 5, 5, 5, 4]), output) def test_maximum_filter05(self, xp): array = xp.asarray([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) filter_shape = xp.asarray([2, 3]) output = ndimage.maximum_filter(array, filter_shape) assert_array_almost_equal(xp.asarray([[3, 5, 5, 5, 4], [7, 9, 9, 9, 5], [8, 9, 9, 9, 7]]), output) def test_maximum_filter06(self, xp): array = xp.asarray([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = xp.asarray([[1, 1, 1], [1, 1, 1]]) output = ndimage.maximum_filter(array, footprint=footprint) assert_array_almost_equal(xp.asarray([[3, 5, 5, 5, 4], [7, 9, 9, 9, 5], [8, 9, 9, 9, 7]]), output) # separable footprint should allow mode sequence output2 = ndimage.maximum_filter(array, footprint=footprint, mode=['reflect', 'reflect']) assert_array_almost_equal(output2, output) def test_maximum_filter07(self, xp): array = xp.asarray([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) output = ndimage.maximum_filter(array, footprint=footprint) assert_array_almost_equal(xp.asarray([[3, 5, 5, 5, 4], [7, 7, 9, 9, 5], [7, 9, 8, 9, 7]]), output) # non-separable footprint should not allow mode sequence with assert_raises(RuntimeError): ndimage.maximum_filter(array, footprint=footprint, mode=['reflect', 'reflect']) def test_maximum_filter08(self, xp): array = xp.asarray([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) output = ndimage.maximum_filter(array, footprint=footprint, origin=-1) assert_array_almost_equal(xp.asarray([[7, 9, 9, 5, 5], [9, 8, 9, 7, 5], [8, 8, 7, 7, 7]]), output) def test_maximum_filter09(self, xp): array = xp.asarray([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) output = ndimage.maximum_filter(array, footprint=footprint, origin=[-1, 0]) assert_array_almost_equal(xp.asarray([[7, 7, 9, 9, 5], [7, 9, 8, 9, 7], [8, 8, 8, 7, 7]]), output) @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339") @pytest.mark.parametrize( 'axes', tuple(itertools.combinations(range(-3, 3), 2)) ) @pytest.mark.parametrize( 'filter_func, kwargs', [(ndimage.minimum_filter, {}), (ndimage.maximum_filter, {}), (ndimage.median_filter, {}), (ndimage.rank_filter, dict(rank=3)), (ndimage.percentile_filter, dict(percentile=60))] ) def test_minmax_nonseparable_axes(self, filter_func, axes, kwargs, xp): array = xp.arange(6 * 8 * 12, dtype=xp.float32) array = xp.reshape(array, (6, 8, 12)) # use 2D triangular footprint because it is non-separable footprint = xp.asarray(np.tri(5)) axes = np.asarray(axes) if len(set(axes % array.ndim)) != len(axes): # parametrized cases with duplicate axes raise an error with pytest.raises(ValueError): filter_func(array, footprint=footprint, axes=axes, **kwargs) return output = filter_func(array, footprint=footprint, axes=axes, **kwargs) missing_axis = tuple(set(range(3)) - set(axes % array.ndim))[0] footprint_3d = xp.expand_dims(footprint, axis=missing_axis) expected = filter_func(array, footprint=footprint_3d, **kwargs) xp_assert_close(output, expected) def test_rank01(self, xp): array = xp.asarray([1, 2, 3, 4, 5]) output = ndimage.rank_filter(array, 1, size=2) xp_assert_equal(array, output) output = ndimage.percentile_filter(array, 100, size=2) xp_assert_equal(array, output) output = ndimage.median_filter(array, 2) xp_assert_equal(array, output) def test_rank02(self, xp): array = xp.asarray([1, 2, 3, 4, 5]) output = ndimage.rank_filter(array, 1, size=[3]) xp_assert_equal(array, output) output = ndimage.percentile_filter(array, 50, size=3) xp_assert_equal(array, output) output = ndimage.median_filter(array, (3,)) xp_assert_equal(array, output) def test_rank03(self, xp): array = xp.asarray([3, 2, 5, 1, 4]) output = ndimage.rank_filter(array, 1, size=[2]) xp_assert_equal(xp.asarray([3, 3, 5, 5, 4]), output) output = ndimage.percentile_filter(array, 100, size=2) xp_assert_equal(xp.asarray([3, 3, 5, 5, 4]), output) def test_rank04(self, xp): array = xp.asarray([3, 2, 5, 1, 4]) expected = xp.asarray([3, 3, 2, 4, 4]) output = ndimage.rank_filter(array, 1, size=3) xp_assert_equal(expected, output) output = ndimage.percentile_filter(array, 50, size=3) xp_assert_equal(expected, output) output = ndimage.median_filter(array, size=3) xp_assert_equal(expected, output) def test_rank05(self, xp): array = xp.asarray([3, 2, 5, 1, 4]) expected = xp.asarray([3, 3, 2, 4, 4]) output = ndimage.rank_filter(array, -2, size=3) xp_assert_equal(expected, output) def test_rank06(self, xp): array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]]) expected = [[2, 2, 1, 1, 1], [3, 3, 2, 1, 1], [5, 5, 3, 3, 1]] expected = xp.asarray(expected) output = ndimage.rank_filter(array, 1, size=[2, 3]) xp_assert_equal(expected, output) output = ndimage.percentile_filter(array, 17, size=(2, 3)) xp_assert_equal(expected, output) @xfail_xp_backends("cupy", reason="cupy/cupy#8406") @uses_output_array def test_rank06_overlap(self, xp): array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]]) array_copy = xp.asarray(array, copy=True) expected = [[2, 2, 1, 1, 1], [3, 3, 2, 1, 1], [5, 5, 3, 3, 1]] expected = xp.asarray(expected) ndimage.rank_filter(array, 1, size=[2, 3], output=array) xp_assert_equal(expected, array) ndimage.percentile_filter(array_copy, 17, size=(2, 3), output=array_copy) xp_assert_equal(expected, array_copy) def test_rank07(self, xp): array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]]) expected = [[3, 5, 5, 5, 4], [5, 5, 7, 5, 4], [6, 8, 8, 7, 5]] expected = xp.asarray(expected) output = ndimage.rank_filter(array, -2, size=[2, 3]) xp_assert_equal(expected, output) def test_rank08(self, xp): array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]]) expected = [[3, 3, 2, 4, 4], [5, 5, 5, 4, 4], [5, 6, 7, 5, 5]] expected = xp.asarray(expected) output = ndimage.percentile_filter(array, 50.0, size=(2, 3)) xp_assert_equal(expected, output) output = ndimage.rank_filter(array, 3, size=(2, 3)) xp_assert_equal(expected, output) output = ndimage.median_filter(array, size=(2, 3)) xp_assert_equal(expected, output) # non-separable: does not allow mode sequence with assert_raises(RuntimeError): ndimage.percentile_filter(array, 50.0, size=(2, 3), mode=['reflect', 'constant']) with assert_raises(RuntimeError): ndimage.rank_filter(array, 3, size=(2, 3), mode=['reflect']*2) with assert_raises(RuntimeError): ndimage.median_filter(array, size=(2, 3), mode=['reflect']*2) @pytest.mark.parametrize('dtype', types) def test_rank09(self, dtype, xp): dtype = getattr(xp, dtype) expected = [[3, 3, 2, 4, 4], [3, 5, 2, 5, 1], [5, 5, 8, 3, 5]] expected = xp.asarray(expected) footprint = xp.asarray([[1, 0, 1], [0, 1, 0]]) array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], dtype=dtype) output = ndimage.rank_filter(array, 1, footprint=footprint) assert_array_almost_equal(expected, output) output = ndimage.percentile_filter(array, 35, footprint=footprint) assert_array_almost_equal(expected, output) def test_rank10(self, xp): array = xp.asarray([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) expected = [[2, 2, 1, 1, 1], [2, 3, 1, 3, 1], [5, 5, 3, 3, 1]] expected = xp.asarray(expected) footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) output = ndimage.rank_filter(array, 0, footprint=footprint) xp_assert_equal(expected, output) output = ndimage.percentile_filter(array, 0.0, footprint=footprint) xp_assert_equal(expected, output) def test_rank11(self, xp): array = xp.asarray([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) expected = [[3, 5, 5, 5, 4], [7, 7, 9, 9, 5], [7, 9, 8, 9, 7]] expected = xp.asarray(expected) footprint = xp.asarray([[1, 0, 1], [1, 1, 0]]) output = ndimage.rank_filter(array, -1, footprint=footprint) xp_assert_equal(expected, output) output = ndimage.percentile_filter(array, 100.0, footprint=footprint) xp_assert_equal(expected, output) @pytest.mark.parametrize('dtype', types) def test_rank12(self, dtype, xp): dtype = getattr(xp, dtype) expected = [[3, 3, 2, 4, 4], [3, 5, 2, 5, 1], [5, 5, 8, 3, 5]] expected = xp.asarray(expected, dtype=dtype) footprint = xp.asarray([[1, 0, 1], [0, 1, 0]]) array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], dtype=dtype) output = ndimage.rank_filter(array, 1, footprint=footprint) assert_array_almost_equal(expected, output) output = ndimage.percentile_filter(array, 50.0, footprint=footprint) xp_assert_equal(expected, output) output = ndimage.median_filter(array, footprint=footprint) xp_assert_equal(expected, output) @pytest.mark.parametrize('dtype', types) def test_rank13(self, dtype, xp): dtype = getattr(xp, dtype) expected = [[5, 2, 5, 1, 1], [5, 8, 3, 5, 5], [6, 6, 5, 5, 5]] expected = xp.asarray(expected, dtype=dtype) footprint = xp.asarray([[1, 0, 1], [0, 1, 0]]) array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], dtype=dtype) output = ndimage.rank_filter(array, 1, footprint=footprint, origin=-1) xp_assert_equal(expected, output) @pytest.mark.parametrize('dtype', types) def test_rank14(self, dtype, xp): dtype = getattr(xp, dtype) expected = [[3, 5, 2, 5, 1], [5, 5, 8, 3, 5], [5, 6, 6, 5, 5]] expected = xp.asarray(expected, dtype=dtype) footprint = xp.asarray([[1, 0, 1], [0, 1, 0]]) array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], dtype=dtype) output = ndimage.rank_filter(array, 1, footprint=footprint, origin=[-1, 0]) xp_assert_equal(expected, output) @pytest.mark.parametrize('dtype', types) def test_rank15(self, dtype, xp): dtype = getattr(xp, dtype) expected = [[2, 3, 1, 4, 1], [5, 3, 7, 1, 1], [5, 5, 3, 3, 3]] expected = xp.asarray(expected, dtype=dtype) footprint = xp.asarray([[1, 0, 1], [0, 1, 0]]) array = xp.asarray([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], dtype=dtype) output = ndimage.rank_filter(array, 0, footprint=footprint, origin=[-1, 0]) xp_assert_equal(expected, output) # NumPy-only because test is for list input def test_rank16(self): # test that lists are accepted and interpreted as numpy arrays array = [3, 2, 5, 1, 4] # expected values are: median(3, 2, 5) = 3, median(2, 5, 1) = 2, etc expected = np.asarray([3, 3, 2, 4, 4]) output = ndimage.rank_filter(array, -2, size=3) xp_assert_equal(expected, output) def test_rank17(self, xp): array = xp.asarray([3, 2, 5, 1, 4]) if not hasattr(array, 'flags'): return array.flags.writeable = False expected = xp.asarray([3, 3, 2, 4, 4]) output = ndimage.rank_filter(array, -2, size=3) xp_assert_equal(expected, output) def test_rank18(self, xp): # module 'array_api_strict' has no attribute 'float16' tested_dtypes = ['int8', 'int16', 'int32', 'int64', 'float32', 'float64', 'uint8', 'uint16', 'uint32', 'uint64'] for dtype_str in tested_dtypes: dtype = getattr(xp, dtype_str) x = xp.asarray([3, 2, 5, 1, 4], dtype=dtype) y = ndimage.rank_filter(x, -2, size=3) assert y.dtype == x.dtype def test_rank19(self, xp): # module 'array_api_strict' has no attribute 'float16' tested_dtypes = ['int8', 'int16', 'int32', 'int64', 'float32', 'float64', 'uint8', 'uint16', 'uint32', 'uint64'] for dtype_str in tested_dtypes: dtype = getattr(xp, dtype_str) x = xp.asarray([[3, 2, 5, 1, 4], [3, 2, 5, 1, 4]], dtype=dtype) y = ndimage.rank_filter(x, -2, size=3) assert y.dtype == x.dtype @skip_xp_backends(np_only=True, exceptions=["cupy"], reason="off-by-ones on alt backends") @xfail_xp_backends("cupy", reason="does not support extra_arguments") @pytest.mark.parametrize('dtype', types) def test_generic_filter1d01(self, dtype, xp): weights = xp.asarray([1.1, 2.2, 3.3]) def _filter_func(input, output, fltr, total): fltr = fltr / total for ii in range(input.shape[0] - 2): output[ii] = input[ii] * fltr[0] output[ii] += input[ii + 1] * fltr[1] output[ii] += input[ii + 2] * fltr[2] a = np.arange(12, dtype=dtype).reshape(3, 4) a = xp.asarray(a) dtype = getattr(xp, dtype) r1 = ndimage.correlate1d(a, weights / xp.sum(weights), 0, origin=-1) r2 = ndimage.generic_filter1d( a, _filter_func, 3, axis=0, origin=-1, extra_arguments=(weights,), extra_keywords={'total': xp.sum(weights)}) assert_array_almost_equal(r1, r2) @xfail_xp_backends("cupy", reason="does not support extra_arguments") @pytest.mark.parametrize('dtype', types) def test_generic_filter01(self, dtype, xp): if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"): pytest.xfail("https://github.com/pytorch/pytorch/issues/58734") dtype_str = dtype dtype = getattr(xp, dtype_str) filter_ = xp.asarray([[1.0, 2.0], [3.0, 4.0]]) footprint = xp.asarray([[1.0, 0.0], [0.0, 1.0]]) cf = xp.asarray([1., 4.]) def _filter_func(buffer, weights, total=1.0): weights = np.asarray(cf) / np.asarray(total) return np.sum(buffer * weights) a = np.arange(12, dtype=dtype_str).reshape(3, 4) a = xp.asarray(a) r1 = ndimage.correlate(a, filter_ * footprint) if dtype_str in float_types: r1 /= 5 else: r1 //= 5 r2 = ndimage.generic_filter( a, _filter_func, footprint=footprint, extra_arguments=(cf,), extra_keywords={'total': xp.sum(cf)}) assert_array_almost_equal(r1, r2) # generic_filter doesn't allow mode sequence with assert_raises(RuntimeError): r2 = ndimage.generic_filter( a, _filter_func, mode=['reflect', 'reflect'], footprint=footprint, extra_arguments=(cf,), extra_keywords={'total': xp.sum(cf)}) @pytest.mark.parametrize( 'mode, expected_value', [('nearest', [1, 1, 2]), ('wrap', [3, 1, 2]), ('reflect', [1, 1, 2]), ('mirror', [2, 1, 2]), ('constant', [0, 1, 2])] ) def test_extend01(self, mode, expected_value, xp): array = xp.asarray([1, 2, 3]) weights = xp.asarray([1, 0]) output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) expected_value = xp.asarray(expected_value) xp_assert_equal(output, expected_value) @pytest.mark.parametrize( 'mode, expected_value', [('nearest', [1, 1, 1]), ('wrap', [3, 1, 2]), ('reflect', [3, 3, 2]), ('mirror', [1, 2, 3]), ('constant', [0, 0, 0])] ) def test_extend02(self, mode, expected_value, xp): array = xp.asarray([1, 2, 3]) weights = xp.asarray([1, 0, 0, 0, 0, 0, 0, 0]) output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) expected_value = xp.asarray(expected_value) xp_assert_equal(output, expected_value) @pytest.mark.parametrize( 'mode, expected_value', [('nearest', [2, 3, 3]), ('wrap', [2, 3, 1]), ('reflect', [2, 3, 3]), ('mirror', [2, 3, 2]), ('constant', [2, 3, 0])] ) def test_extend03(self, mode, expected_value, xp): array = xp.asarray([1, 2, 3]) weights = xp.asarray([0, 0, 1]) output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) expected_value = xp.asarray(expected_value) xp_assert_equal(output, expected_value) @pytest.mark.parametrize( 'mode, expected_value', [('nearest', [3, 3, 3]), ('wrap', [2, 3, 1]), ('reflect', [2, 1, 1]), ('mirror', [1, 2, 3]), ('constant', [0, 0, 0])] ) def test_extend04(self, mode, expected_value, xp): array = xp.asarray([1, 2, 3]) weights = xp.asarray([0, 0, 0, 0, 0, 0, 0, 0, 1]) output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) expected_value = xp.asarray(expected_value) xp_assert_equal(output, expected_value) @pytest.mark.parametrize( 'mode, expected_value', [('nearest', [[1, 1, 2], [1, 1, 2], [4, 4, 5]]), ('wrap', [[9, 7, 8], [3, 1, 2], [6, 4, 5]]), ('reflect', [[1, 1, 2], [1, 1, 2], [4, 4, 5]]), ('mirror', [[5, 4, 5], [2, 1, 2], [5, 4, 5]]), ('constant', [[0, 0, 0], [0, 1, 2], [0, 4, 5]])] ) def test_extend05(self, mode, expected_value, xp): array = xp.asarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) weights = xp.asarray([[1, 0], [0, 0]]) output = ndimage.correlate(array, weights, mode=mode, cval=0) expected_value = xp.asarray(expected_value) xp_assert_equal(output, expected_value) @pytest.mark.parametrize( 'mode, expected_value', [('nearest', [[5, 6, 6], [8, 9, 9], [8, 9, 9]]), ('wrap', [[5, 6, 4], [8, 9, 7], [2, 3, 1]]), ('reflect', [[5, 6, 6], [8, 9, 9], [8, 9, 9]]), ('mirror', [[5, 6, 5], [8, 9, 8], [5, 6, 5]]), ('constant', [[5, 6, 0], [8, 9, 0], [0, 0, 0]])] ) def test_extend06(self, mode, expected_value, xp): array = xp.asarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) weights = xp.asarray([[0, 0, 0], [0, 0, 0], [0, 0, 1]]) output = ndimage.correlate(array, weights, mode=mode, cval=0) expected_value = xp.asarray(expected_value) xp_assert_equal(output, expected_value) @pytest.mark.parametrize( 'mode, expected_value', [('nearest', [3, 3, 3]), ('wrap', [2, 3, 1]), ('reflect', [2, 1, 1]), ('mirror', [1, 2, 3]), ('constant', [0, 0, 0])] ) def test_extend07(self, mode, expected_value, xp): array = xp.asarray([1, 2, 3]) weights = xp.asarray([0, 0, 0, 0, 0, 0, 0, 0, 1]) output = ndimage.correlate(array, weights, mode=mode, cval=0) expected_value = xp.asarray(expected_value) xp_assert_equal(output, expected_value) @pytest.mark.parametrize( 'mode, expected_value', [('nearest', [[3], [3], [3]]), ('wrap', [[2], [3], [1]]), ('reflect', [[2], [1], [1]]), ('mirror', [[1], [2], [3]]), ('constant', [[0], [0], [0]])] ) def test_extend08(self, mode, expected_value, xp): array = xp.asarray([[1], [2], [3]]) weights = xp.asarray([[0], [0], [0], [0], [0], [0], [0], [0], [1]]) output = ndimage.correlate(array, weights, mode=mode, cval=0) expected_value = xp.asarray(expected_value) xp_assert_equal(output, expected_value) @pytest.mark.parametrize( 'mode, expected_value', [('nearest', [3, 3, 3]), ('wrap', [2, 3, 1]), ('reflect', [2, 1, 1]), ('mirror', [1, 2, 3]), ('constant', [0, 0, 0])] ) def test_extend09(self, mode, expected_value, xp): array = xp.asarray([1, 2, 3]) weights = xp.asarray([0, 0, 0, 0, 0, 0, 0, 0, 1]) output = ndimage.correlate(array, weights, mode=mode, cval=0) expected_value = xp.asarray(expected_value) xp_assert_equal(output, expected_value) @pytest.mark.parametrize( 'mode, expected_value', [('nearest', [[3], [3], [3]]), ('wrap', [[2], [3], [1]]), ('reflect', [[2], [1], [1]]), ('mirror', [[1], [2], [3]]), ('constant', [[0], [0], [0]])] ) def test_extend10(self, mode, expected_value, xp): array = xp.asarray([[1], [2], [3]]) weights = xp.asarray([[0], [0], [0], [0], [0], [0], [0], [0], [1]]) output = ndimage.correlate(array, weights, mode=mode, cval=0) expected_value = xp.asarray(expected_value) xp_assert_equal(output, expected_value) @xfail_xp_backends("cupy", reason="TypeError") @make_xp_test_case(ndimage.generic_filter) def test_ticket_701(xp): # Test generic filter sizes arr = xp.asarray(np.arange(4).reshape(2, 2)) def func(x): return np.min(x) # NB: np.min not xp.min for callables res = ndimage.generic_filter(arr, func, size=(1, 1)) # The following raises an error unless ticket 701 is fixed res2 = ndimage.generic_filter(arr, func, size=1) xp_assert_equal(res, res2) def test_gh_5430(): # At least one of these raises an error unless gh-5430 is # fixed. In py2k an int is implemented using a C long, so # which one fails depends on your system. In py3k there is only # one arbitrary precision integer type, so both should fail. sigma = np.int32(1) out = ndimage._ni_support._normalize_sequence(sigma, 1) assert out == [sigma] sigma = np.int64(1) out = ndimage._ni_support._normalize_sequence(sigma, 1) assert out == [sigma] # This worked before; make sure it still works sigma = 1 out = ndimage._ni_support._normalize_sequence(sigma, 1) assert out == [sigma] # This worked before; make sure it still works sigma = [1, 1] out = ndimage._ni_support._normalize_sequence(sigma, 2) assert out == sigma # Also include the OPs original example to make sure we fixed the issue x = np.random.normal(size=(256, 256)) perlin = np.zeros_like(x) for i in 2**np.arange(6): perlin += ndimage.gaussian_filter(x, i, mode="wrap") * i**2 # This also fixes gh-4106, show that the OPs example now runs. x = np.int64(21) ndimage._ni_support._normalize_sequence(x, 0) @skip_xp_backends("cupy", reason="tests a private scipy utility") def test_gaussian_kernel1d(xp): radius = 10 sigma = 2 sigma2 = sigma * sigma x = np.arange(-radius, radius + 1, dtype=np.float64) x = xp.asarray(x) phi_x = xp.exp(-0.5 * x * x / sigma2) phi_x /= xp.sum(phi_x) xp_assert_close(phi_x, xp.asarray(_gaussian_kernel1d(sigma, 0, radius))) xp_assert_close(-phi_x * x / sigma2, xp.asarray(_gaussian_kernel1d(sigma, 1, radius))) xp_assert_close(phi_x * (x * x / sigma2 - 1) / sigma2, xp.asarray(_gaussian_kernel1d(sigma, 2, radius))) xp_assert_close(phi_x * (3 - x * x / sigma2) * x / (sigma2 * sigma2), xp.asarray(_gaussian_kernel1d(sigma, 3, radius))) @make_xp_test_case(ndimage.gaussian_filter, ndimage.gaussian_filter1d) def test_orders_gauss(xp): # Check order inputs to Gaussians arr = xp.zeros((1,)) xp_assert_equal(ndimage.gaussian_filter(arr, 1, order=0), xp.asarray([0.])) xp_assert_equal(ndimage.gaussian_filter(arr, 1, order=3), xp.asarray([0.])) assert_raises(ValueError, ndimage.gaussian_filter, arr, 1, -1) xp_assert_equal(ndimage.gaussian_filter1d(arr, 1, axis=-1, order=0), xp.asarray([0.])) xp_assert_equal(ndimage.gaussian_filter1d(arr, 1, axis=-1, order=3), xp.asarray([0.])) assert_raises(ValueError, ndimage.gaussian_filter1d, arr, 1, -1, -1) @xfail_xp_backends("cupy", reason="TypeError") @make_xp_test_case( ndimage.generic_filter, ndimage.generic_filter1d, ndimage.percentile_filter, ) def test_valid_origins1(xp): """Regression test for #1311.""" def func(x): return xp.mean(x) data = xp.asarray([1, 2, 3, 4, 5], dtype=xp.float64) assert_raises(ValueError, ndimage.generic_filter, data, func, size=3, origin=2) assert_raises(ValueError, ndimage.generic_filter1d, data, func, filter_size=3, origin=2) assert_raises(ValueError, ndimage.percentile_filter, data, 0.2, size=3, origin=2) @xfail_xp_backends("cupy", reason="TypeError") @pytest.mark.parametrize( "filter_func", [ make_xp_pytest_param(ndimage.uniform_filter), make_xp_pytest_param(ndimage.minimum_filter), make_xp_pytest_param(ndimage.maximum_filter), make_xp_pytest_param(ndimage.maximum_filter1d), make_xp_pytest_param(ndimage.median_filter), make_xp_pytest_param(ndimage.minimum_filter1d), ], ) def test_valid_origins2(xp, filter_func): """Regression test for #1311.""" data = xp.asarray([1, 2, 3, 4, 5], dtype=xp.float64) # This should work, since for size == 3, the valid range for origin is # -1 to 1. list(filter_func(data, 3, origin=-1)) list(filter_func(data, 3, origin=1)) # Just check this raises an error instead of silently accepting or # segfaulting. assert_raises(ValueError, filter_func, data, 3, origin=2) @make_xp_test_case( ndimage.correlate1d, ndimage.correlate, ndimage.convolve1d, ndimage.convolve, ) def test_bad_convolve_and_correlate_origins(xp): """Regression test for gh-822.""" # Before gh-822 was fixed, these would generate seg. faults or # other crashes on many system. assert_raises(ValueError, ndimage.correlate1d, [0, 1, 2, 3, 4, 5], [1, 1, 2, 0], origin=2) assert_raises(ValueError, ndimage.correlate, [0, 1, 2, 3, 4, 5], [0, 1, 2], origin=[2]) assert_raises(ValueError, ndimage.correlate, xp.ones((3, 5)), xp.ones((2, 2)), origin=[0, 1]) assert_raises(ValueError, ndimage.convolve1d, xp.arange(10), xp.ones(3), origin=-2) assert_raises(ValueError, ndimage.convolve, xp.arange(10), xp.ones(3), origin=[-2]) assert_raises(ValueError, ndimage.convolve, xp.ones((3, 5)), xp.ones((2, 2)), origin=[0, -2]) @pytest.mark.parametrize( "filter_func,args,kwargs", [ make_xp_pytest_param(ndimage.gaussian_filter, [1], {}), make_xp_pytest_param(ndimage.prewitt, [], {}), make_xp_pytest_param(ndimage.sobel, [], {}), make_xp_pytest_param(ndimage.laplace, [], {}), make_xp_pytest_param(ndimage.gaussian_laplace, [1], {}), make_xp_pytest_param(ndimage.maximum_filter, [], {"size": 5}), make_xp_pytest_param(ndimage.minimum_filter, [], {"size": 5}), make_xp_pytest_param(ndimage.gaussian_gradient_magnitude, [1], {}), make_xp_pytest_param(ndimage.uniform_filter, [5], {}), ], ) def test_multiple_modes(xp, filter_func, args, kwargs): # Test that the filters with multiple mode capabilities for different # dimensions give the same result as applying a single mode. arr = xp.asarray([[1., 0., 0.], [1., 1., 0.], [0., 0., 0.]]) mode1 = 'reflect' mode2 = ['reflect', 'reflect'] xp_assert_equal(filter_func(arr, *args, mode=mode1, **kwargs), filter_func(arr, *args, mode=mode2, **kwargs)) @make_xp_test_case( ndimage.gaussian_filter1d, ndimage.gaussian_filter, ndimage.uniform_filter1d, ndimage.uniform_filter, ndimage.maximum_filter1d, ndimage.maximum_filter, ndimage.minimum_filter1d, ndimage.minimum_filter, ) def test_multiple_modes_sequentially(xp): # Test that the filters with multiple mode capabilities for different # dimensions give the same result as applying the filters with # different modes sequentially arr = xp.asarray([[1., 0., 0.], [1., 1., 0.], [0., 0., 0.]]) modes = ['reflect', 'wrap'] expected = ndimage.gaussian_filter1d(arr, 1, axis=0, mode=modes[0]) expected = ndimage.gaussian_filter1d(expected, 1, axis=1, mode=modes[1]) xp_assert_equal(expected, ndimage.gaussian_filter(arr, 1, mode=modes)) expected = ndimage.uniform_filter1d(arr, 5, axis=0, mode=modes[0]) expected = ndimage.uniform_filter1d(expected, 5, axis=1, mode=modes[1]) xp_assert_equal(expected, ndimage.uniform_filter(arr, 5, mode=modes)) expected = ndimage.maximum_filter1d(arr, size=5, axis=0, mode=modes[0]) expected = ndimage.maximum_filter1d(expected, size=5, axis=1, mode=modes[1]) xp_assert_equal(expected, ndimage.maximum_filter(arr, size=5, mode=modes)) expected = ndimage.minimum_filter1d(arr, size=5, axis=0, mode=modes[0]) expected = ndimage.minimum_filter1d(expected, size=5, axis=1, mode=modes[1]) xp_assert_equal(expected, ndimage.minimum_filter(arr, size=5, mode=modes)) @make_xp_test_case(ndimage.prewitt) def test_multiple_modes_prewitt(xp): # Test prewitt filter for multiple extrapolation modes arr = xp.asarray([[1., 0., 0.], [1., 1., 0.], [0., 0., 0.]]) expected = xp.asarray([[1., -3., 2.], [1., -2., 1.], [1., -1., 0.]]) modes = ['reflect', 'wrap'] xp_assert_equal(expected, ndimage.prewitt(arr, mode=modes)) @make_xp_test_case(ndimage.sobel) def test_multiple_modes_sobel(xp): # Test sobel filter for multiple extrapolation modes arr = xp.asarray([[1., 0., 0.], [1., 1., 0.], [0., 0., 0.]]) expected = xp.asarray([[1., -4., 3.], [2., -3., 1.], [1., -1., 0.]]) modes = ['reflect', 'wrap'] xp_assert_equal(expected, ndimage.sobel(arr, mode=modes)) @make_xp_test_case(ndimage.laplace) def test_multiple_modes_laplace(xp): # Test laplace filter for multiple extrapolation modes arr = xp.asarray([[1., 0., 0.], [1., 1., 0.], [0., 0., 0.]]) expected = xp.asarray([[-2., 2., 1.], [-2., -3., 2.], [1., 1., 0.]]) modes = ['reflect', 'wrap'] xp_assert_equal(expected, ndimage.laplace(arr, mode=modes)) @make_xp_test_case(ndimage.gaussian_laplace) def test_multiple_modes_gaussian_laplace(xp): # Test gaussian_laplace filter for multiple extrapolation modes arr = xp.asarray([[1., 0., 0.], [1., 1., 0.], [0., 0., 0.]]) expected = xp.asarray([[-0.28438687, 0.01559809, 0.19773499], [-0.36630503, -0.20069774, 0.07483620], [0.15849176, 0.18495566, 0.21934094]]) modes = ['reflect', 'wrap'] assert_almost_equal(expected, ndimage.gaussian_laplace(arr, 1, mode=modes)) @make_xp_test_case(ndimage.gaussian_gradient_magnitude) def test_multiple_modes_gaussian_gradient_magnitude(xp): # Test gaussian_gradient_magnitude filter for multiple # extrapolation modes arr = xp.asarray([[1., 0., 0.], [1., 1., 0.], [0., 0., 0.]]) expected = xp.asarray([[0.04928965, 0.09745625, 0.06405368], [0.23056905, 0.14025305, 0.04550846], [0.19894369, 0.14950060, 0.06796850]]) modes = ['reflect', 'wrap'] calculated = ndimage.gaussian_gradient_magnitude(arr, 1, mode=modes) assert_almost_equal(expected, calculated) @make_xp_test_case(ndimage.uniform_filter) def test_multiple_modes_uniform(xp): # Test uniform filter for multiple extrapolation modes arr = xp.asarray([[1., 0., 0.], [1., 1., 0.], [0., 0., 0.]]) expected = xp.asarray([[0.32, 0.40, 0.48], [0.20, 0.28, 0.32], [0.28, 0.32, 0.40]]) modes = ['reflect', 'wrap'] assert_almost_equal(expected, ndimage.uniform_filter(arr, 5, mode=modes)) def _count_nonzero(arr): # XXX: a simplified count_nonzero replacement; replace once # https://github.com/data-apis/array-api/pull/803/ is in # this assumes arr.dtype == xp.bool xp = array_namespace(arr) return xp.sum(xp.astype(arr, xp.int8)) @make_xp_test_case( ndimage.gaussian_filter, ndimage.gaussian_filter1d, ndimage.gaussian_laplace, ndimage.gaussian_gradient_magnitude, ) def test_gaussian_truncate(xp): # Test that Gaussian filters can be truncated at different widths. # These tests only check that the result has the expected number # of nonzero elements. arr = np.zeros((100, 100), dtype=np.float64) arr[50, 50] = 1 arr = xp.asarray(arr) num_nonzeros_2 = _count_nonzero(ndimage.gaussian_filter(arr, 5, truncate=2) > 0) assert num_nonzeros_2 == 21**2 num_nonzeros_5 = _count_nonzero( ndimage.gaussian_filter(arr, 5, truncate=5) > 0 ) assert num_nonzeros_5 == 51**2 # Test truncate when sigma is a sequence. f = ndimage.gaussian_filter(arr, [0.5, 2.5], truncate=3.5) fpos = f > 0 n0 = _count_nonzero(xp.any(fpos, axis=0)) assert n0 == 19 n1 = _count_nonzero(xp.any(fpos, axis=1)) assert n1 == 5 # Test gaussian_filter1d. x = np.zeros(51) x[25] = 1 x = xp.asarray(x) f = ndimage.gaussian_filter1d(x, sigma=2, truncate=3.5) n = _count_nonzero(f > 0) assert n == 15 # Test gaussian_laplace y = ndimage.gaussian_laplace(x, sigma=2, truncate=3.5) nonzero_indices = xp.nonzero(y != 0)[0] n = xp.max(nonzero_indices) - xp.min(nonzero_indices) + 1 assert n == 15 # Test gaussian_gradient_magnitude y = ndimage.gaussian_gradient_magnitude(x, sigma=2, truncate=3.5) nonzero_indices = xp.nonzero(y != 0)[0] n = xp.max(nonzero_indices) - xp.min(nonzero_indices) + 1 assert n == 15 @xfail_xp_backends("cupy", reason="cupy/cupy#8402") @make_xp_test_case(ndimage.gaussian_filter1d, ndimage.gaussian_filter) def test_gaussian_radius(xp): # Test that Gaussian filters with radius argument produce the same # results as the filters with corresponding truncate argument. # radius = int(truncate * sigma + 0.5) # Test gaussian_filter1d x = np.zeros(7) x[3] = 1 x = xp.asarray(x) f1 = ndimage.gaussian_filter1d(x, sigma=2, truncate=1.5) f2 = ndimage.gaussian_filter1d(x, sigma=2, radius=3) xp_assert_equal(f1, f2) # Test gaussian_filter when sigma is a number. a = np.zeros((9, 9)) a[4, 4] = 1 a = xp.asarray(a) f1 = ndimage.gaussian_filter(a, sigma=0.5, truncate=3.5) f2 = ndimage.gaussian_filter(a, sigma=0.5, radius=2) xp_assert_equal(f1, f2) # Test gaussian_filter when sigma is a sequence. a = np.zeros((50, 50)) a[25, 25] = 1 a = xp.asarray(a) f1 = ndimage.gaussian_filter(a, sigma=[0.5, 2.5], truncate=3.5) f2 = ndimage.gaussian_filter(a, sigma=[0.5, 2.5], radius=[2, 9]) xp_assert_equal(f1, f2) @xfail_xp_backends("cupy", reason="cupy/cupy#8402") @make_xp_test_case(ndimage.gaussian_filter1d) def test_gaussian_radius_invalid(xp): # radius must be a nonnegative integer with assert_raises(ValueError): ndimage.gaussian_filter1d(xp.zeros(8), sigma=1, radius=-1) with assert_raises(ValueError): ndimage.gaussian_filter1d(xp.zeros(8), sigma=1, radius=1.1) @uses_output_array
TestNdimageFilters
python
ansible__ansible
test/units/modules/test_known_hosts.py
{ "start": 306, "end": 4319 }
class ____(unittest.TestCase): def _create_file(self, content): tmp_file = tempfile.NamedTemporaryFile(prefix='ansible-test-', suffix='-known_hosts', delete=False) tmp_file.write(to_bytes(content)) tmp_file.close() self.addCleanup(os.unlink, tmp_file.name) return tmp_file.name def test_no_existing_file(self): path = "/tmp/this_file_does_not_exists_known_hosts" key = 'example.com ssh-rsa AAAAetc\n' diff = compute_diff(path, found_line=None, replace_or_add=False, state='present', key=key) self.assertEqual(diff, { 'before_header': '/dev/null', 'after_header': path, 'before': '', 'after': 'example.com ssh-rsa AAAAetc\n', }) def test_key_addition(self): path = self._create_file( 'two.example.com ssh-rsa BBBBetc\n' ) key = 'one.example.com ssh-rsa AAAAetc\n' diff = compute_diff(path, found_line=None, replace_or_add=False, state='present', key=key) self.assertEqual(diff, { 'before_header': path, 'after_header': path, 'before': 'two.example.com ssh-rsa BBBBetc\n', 'after': 'two.example.com ssh-rsa BBBBetc\none.example.com ssh-rsa AAAAetc\n', }) def test_no_change(self): path = self._create_file( 'one.example.com ssh-rsa AAAAetc\n' 'two.example.com ssh-rsa BBBBetc\n' ) key = 'one.example.com ssh-rsa AAAAetc\n' diff = compute_diff(path, found_line=1, replace_or_add=False, state='present', key=key) self.assertEqual(diff, { 'before_header': path, 'after_header': path, 'before': 'one.example.com ssh-rsa AAAAetc\ntwo.example.com ssh-rsa BBBBetc\n', 'after': 'one.example.com ssh-rsa AAAAetc\ntwo.example.com ssh-rsa BBBBetc\n', }) def test_key_change(self): path = self._create_file( 'one.example.com ssh-rsa AAAaetc\n' 'two.example.com ssh-rsa BBBBetc\n' ) key = 'one.example.com ssh-rsa AAAAetc\n' diff = compute_diff(path, found_line=1, replace_or_add=True, state='present', key=key) self.assertEqual(diff, { 'before_header': path, 'after_header': path, 'before': 'one.example.com ssh-rsa AAAaetc\ntwo.example.com ssh-rsa BBBBetc\n', 'after': 'two.example.com ssh-rsa BBBBetc\none.example.com ssh-rsa AAAAetc\n', }) def test_key_removal(self): path = self._create_file( 'one.example.com ssh-rsa AAAAetc\n' 'two.example.com ssh-rsa BBBBetc\n' ) key = 'one.example.com ssh-rsa AAAAetc\n' diff = compute_diff(path, found_line=1, replace_or_add=False, state='absent', key=key) self.assertEqual(diff, { 'before_header': path, 'after_header': path, 'before': 'one.example.com ssh-rsa AAAAetc\ntwo.example.com ssh-rsa BBBBetc\n', 'after': 'two.example.com ssh-rsa BBBBetc\n', }) def test_key_removal_no_change(self): path = self._create_file( 'two.example.com ssh-rsa BBBBetc\n' ) key = 'one.example.com ssh-rsa AAAAetc\n' diff = compute_diff(path, found_line=None, replace_or_add=False, state='absent', key=key) self.assertEqual(diff, { 'before_header': path, 'after_header': path, 'before': 'two.example.com ssh-rsa BBBBetc\n', 'after': 'two.example.com ssh-rsa BBBBetc\n', }) def test_sanity_check(self): basic._load_params = lambda: {} # Module used internally to execute ssh-keygen system executable module = AnsibleModule(argument_spec={}) host = '10.0.0.1' key = '%s ssh-rsa ASDF foo@bar' % (host,) keygen = module.get_bin_path('ssh-keygen') sanity_check(module, host, key, keygen)
KnownHostsDiffTestCase
python
pytorch__pytorch
test/cpp_api_parity/sample_module.py
{ "start": 392, "end": 3462 }
class ____(torch.nn.Module): def __init__(self, has_parity, has_submodule): super().__init__() self.has_parity = has_parity if has_submodule: self.submodule = SampleModule(self.has_parity, False) self.has_submodule = has_submodule self.register_parameter("param", torch.nn.Parameter(torch.empty(3, 4))) self.reset_parameters() def reset_parameters(self): with torch.no_grad(): self.param.fill_(1) def forward(self, x): submodule_forward_result = ( self.submodule(x) if hasattr(self, "submodule") else 0 ) if self.has_parity: return x + self.param * 2 + submodule_forward_result else: return x + self.param * 4 + submodule_forward_result + 3 torch.nn.SampleModule = SampleModule SAMPLE_MODULE_CPP_SOURCE = """\n namespace torch { namespace nn { struct C10_EXPORT SampleModuleOptions { SampleModuleOptions(bool has_parity, bool has_submodule) : has_parity_(has_parity), has_submodule_(has_submodule) {} TORCH_ARG(bool, has_parity); TORCH_ARG(bool, has_submodule); }; struct C10_EXPORT SampleModuleImpl : public torch::nn::Cloneable<SampleModuleImpl> { explicit SampleModuleImpl(SampleModuleOptions options) : options(std::move(options)) { if (options.has_submodule()) { submodule = register_module( "submodule", std::make_shared<SampleModuleImpl>(SampleModuleOptions(options.has_parity(), false))); } reset(); } void reset() { param = register_parameter("param", torch::ones({3, 4})); } torch::Tensor forward(torch::Tensor x) { return x + param * 2 + (submodule ? submodule->forward(x) : torch::zeros_like(x)); } SampleModuleOptions options; torch::Tensor param; std::shared_ptr<SampleModuleImpl> submodule{nullptr}; }; TORCH_MODULE(SampleModule); } // namespace nn } // namespace torch """ module_tests = [ dict( module_name="SampleModule", desc="has_parity", constructor_args=(True, True), cpp_constructor_args="torch::nn::SampleModuleOptions(true, true)", input_size=(3, 4), cpp_input_args=["torch::randn({3, 4})"], has_parity=True, ), dict( fullname="SampleModule_no_parity", constructor=lambda: SampleModule(has_parity=False, has_submodule=True), cpp_constructor_args="torch::nn::SampleModuleOptions(false, true)", input_size=(3, 4), cpp_input_args=["torch::randn({3, 4})"], has_parity=False, ), # This is to test that setting the `test_cpp_api_parity=False` flag skips # the C++ API parity test accordingly (otherwise this test would run and # throw a parity error). dict( fullname="SampleModule_THIS_TEST_SHOULD_BE_SKIPPED", constructor=lambda: SampleModule(False, True), cpp_constructor_args="torch::nn::SampleModuleOptions(false, true)", input_size=(3, 4), cpp_input_args=["torch::randn({3, 4})"], test_cpp_api_parity=False, ), ]
SampleModule
python
modin-project__modin
modin/pandas/accessor.py
{ "start": 6305, "end": 14422 }
class ____: """ Namespace class for accessing additional Modin functions that are not available in pandas. Parameters ---------- data : DataFrame or Series Object to operate on. """ _data: Union[DataFrame, Series] def __init__(self, data: Union[DataFrame, Series]): self._data = data def to_pandas(self): """ Convert a Modin DataFrame/Series object to a pandas DataFrame/Series object. Returns ------- pandas.Series or pandas.DataFrame """ return self._data._to_pandas() def to_ray(self): """ Convert a Modin DataFrame/Series to a Ray Dataset. Returns ------- ray.data.Dataset Converted object with type depending on input. Notes ----- Modin DataFrame/Series can only be converted to a Ray Dataset if Modin uses a Ray engine. """ return to_ray(self._data) def to_dask(self): """ Convert a Modin DataFrame/Series to a Dask DataFrame/Series. Returns ------- dask.dataframe.DataFrame or dask.dataframe.Series Converted object with type depending on input. Notes ----- Modin DataFrame/Series can only be converted to a Dask DataFrame/Series if Modin uses a Dask engine. """ return to_dask(self._data) def to_pickle_glob( self, filepath_or_buffer, compression: CompressionOptions = "infer", protocol: int = pickle.HIGHEST_PROTOCOL, storage_options: StorageOptions = None, ) -> None: """ Pickle (serialize) object to file. This experimental feature provides parallel writing into multiple pickle files which are defined by glob pattern, otherwise (without glob pattern) default pandas implementation is used. Parameters ---------- filepath_or_buffer : str File path where the pickled object will be stored. compression : {{'infer', 'gzip', 'bz2', 'zip', 'xz', None}}, default: 'infer' A string representing the compression to use in the output file. By default, infers from the file extension in specified path. Compression mode may be any of the following possible values: {{'infer', 'gzip', 'bz2', 'zip', 'xz', None}}. If compression mode is 'infer' and path_or_buf is path-like, then detect compression mode from the following extensions: '.gz', '.bz2', '.zip' or '.xz'. (otherwise no compression). If dict given and mode is 'zip' or inferred as 'zip', other entries passed as additional compression options. protocol : int, default: pickle.HIGHEST_PROTOCOL Int which indicates which protocol should be used by the pickler, default HIGHEST_PROTOCOL (see `pickle docs <https://docs.python.org/3/library/pickle.html>`_ paragraph 12.1.2 for details). The possible values are 0, 1, 2, 3, 4, 5. A negative value for the protocol parameter is equivalent to setting its value to HIGHEST_PROTOCOL. storage_options : dict, optional Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc., if using a URL that will be parsed by fsspec, e.g., starting "s3://", "gcs://". An error will be raised if providing this argument with a non-fsspec URL. See the fsspec and backend storage implementation docs for the set of allowed keys and values. """ from modin.experimental.pandas.io import to_pickle_glob to_pickle_glob( self._data, filepath_or_buffer=filepath_or_buffer, compression=compression, protocol=protocol, storage_options=storage_options, ) def to_parquet_glob( self, path, engine="auto", compression="snappy", index=None, partition_cols=None, storage_options: StorageOptions = None, **kwargs, ) -> None: # noqa: PR01 """ Write a DataFrame to the binary parquet format. This experimental feature provides parallel writing into multiple parquet files which are defined by glob pattern, otherwise (without glob pattern) default pandas implementation is used. Notes ----- * Only string type supported for `path` argument. * The rest of the arguments are the same as for `pandas.to_parquet`. """ from modin.experimental.pandas.io import to_parquet_glob if path is None: raise NotImplementedError( "`to_parquet_glob` doesn't support path=None, use `to_parquet` in that case." ) to_parquet_glob( self._data, path=path, engine=engine, compression=compression, index=index, partition_cols=partition_cols, storage_options=storage_options, **kwargs, ) def to_json_glob( self, path_or_buf=None, orient=None, date_format=None, double_precision=10, force_ascii=True, date_unit="ms", default_handler=None, lines=False, compression="infer", index=None, indent=None, storage_options: StorageOptions = None, mode="w", ) -> None: # noqa: PR01 """ Convert the object to a JSON string. Notes ----- * Only string type supported for `path_or_buf` argument. * The rest of the arguments are the same as for `pandas.to_json`. """ from modin.experimental.pandas.io import to_json_glob if path_or_buf is None: raise NotImplementedError( "`to_json_glob` doesn't support path_or_buf=None, use `to_json` in that case." ) to_json_glob( self._data, path_or_buf=path_or_buf, orient=orient, date_format=date_format, double_precision=double_precision, force_ascii=force_ascii, date_unit=date_unit, default_handler=default_handler, lines=lines, compression=compression, index=index, indent=indent, storage_options=storage_options, mode=mode, ) def to_xml_glob( self, path_or_buffer=None, index=True, root_name="data", row_name="row", na_rep=None, attr_cols=None, elem_cols=None, namespaces=None, prefix=None, encoding="utf-8", xml_declaration=True, pretty_print=True, parser="lxml", stylesheet=None, compression="infer", storage_options=None, ) -> None: # noqa: PR01 """ Render a DataFrame to an XML document. Notes ----- * Only string type supported for `path_or_buffer` argument. * The rest of the arguments are the same as for `pandas.to_xml`. """ from modin.experimental.pandas.io import to_xml_glob if path_or_buffer is None: raise NotImplementedError( "`to_xml_glob` doesn't support path_or_buffer=None, use `to_xml` in that case." ) to_xml_glob( self._data, path_or_buffer=path_or_buffer, index=index, root_name=root_name, row_name=row_name, na_rep=na_rep, attr_cols=attr_cols, elem_cols=elem_cols, namespaces=namespaces, prefix=prefix, encoding=encoding, xml_declaration=xml_declaration, pretty_print=pretty_print, parser=parser, stylesheet=stylesheet, compression=compression, storage_options=storage_options, )
ModinAPI
python
Pylons__pyramid
tests/test_integration.py
{ "start": 11547, "end": 12210 }
class ____(IntegrationBase, unittest.TestCase): package = 'tests.pkgs.fixtureapp' def test_another(self): res = self.testapp.get('/another.html', status=200) self.assertEqual(res.body, b'fixture') def test_root(self): res = self.testapp.get('/', status=200) self.assertEqual(res.body, b'fixture') def test_dummyskin(self): self.testapp.get('/dummyskin.html', status=404) def test_error(self): res = self.testapp.get('/error.html', status=200) self.assertEqual(res.body, b'supressed') def test_protected(self): self.testapp.get('/protected.html', status=403)
TestFixtureApp
python
mlflow__mlflow
mlflow/tracing/trace_manager.py
{ "start": 1661, "end": 8139 }
class ____: """ Manage spans and traces created by the tracing system in memory. """ _instance_lock = threading.RLock() _instance = None @classmethod def get_instance(cls): if cls._instance is None: with cls._instance_lock: if cls._instance is None: cls._instance = InMemoryTraceManager() return cls._instance def __init__(self): # In-memory cache to store trace_od -> _Trace mapping. self._traces = get_trace_cache_with_timeout() # Store mapping between OpenTelemetry trace ID and MLflow trace ID self._otel_id_to_mlflow_trace_id: dict[int, str] = {} self._lock = threading.RLock() # Lock for _traces def register_trace(self, otel_trace_id: int, trace_info: TraceInfo): """ Register a new trace info object to the in-memory trace registry. Args: otel_trace_id: The OpenTelemetry trace ID for the new trace. trace_info: The trace info object to be stored. """ # Check for a new timeout setting whenever a new trace is created. self._check_timeout_update() with self._lock: self._traces[trace_info.trace_id] = _Trace(trace_info) self._otel_id_to_mlflow_trace_id[otel_trace_id] = trace_info.trace_id def register_span(self, span: LiveSpan): """ Store the given span in the in-memory trace data. Args: span: The span to be stored. """ if not isinstance(span, LiveSpan): _logger.debug(f"Invalid span object {type(span)} is passed. Skipping.") return with self._lock: trace_data_dict = self._traces[span.request_id].span_dict trace_data_dict[span.span_id] = span def register_prompt(self, trace_id: str, prompt: PromptVersion): """ Register a prompt to link to the trace with the given trace ID. Args: trace_id: The ID of the trace to which the prompt belongs. prompt: The prompt version to be registered. """ with self._lock: if prompt not in self._traces[trace_id].prompts: self._traces[trace_id].prompts.append(prompt) # NB: Set prompt URIs in trace tags for linking. This is a short-term solution until # LinkPromptsToTraces endpoint is implemented in the backend. # TODO: Remove this once LinkPromptsToTraces endpoint is implemented in the backend. try: current_tag = self._traces[trace_id].info.tags.get(LINKED_PROMPTS_TAG_KEY) updated_tag = update_linked_prompts_tag(current_tag, [prompt]) self._traces[trace_id].info.tags[LINKED_PROMPTS_TAG_KEY] = updated_tag except Exception: _logger.debug(f"Failed to update prompts tag for trace {trace_id}", exc_info=True) raise @contextlib.contextmanager def get_trace(self, trace_id: str) -> Generator[_Trace | None, None, None]: """ Yield the trace info for the given trace ID.. This is designed to be used as a context manager to ensure the trace info is accessed with the lock held. """ with self._lock: yield self._traces.get(trace_id) def get_span_from_id(self, trace_id: str, span_id: str) -> LiveSpan | None: """ Get a span object for the given trace_id and span_id. """ with self._lock: trace = self._traces.get(trace_id) return trace.span_dict.get(span_id) if trace else None def get_root_span_id(self, trace_id) -> str | None: """ Get the root span ID for the given trace ID. """ with self._lock: trace = self._traces.get(trace_id) if trace: for span in trace.span_dict.values(): if span.parent_id is None: return span.span_id return None def get_mlflow_trace_id_from_otel_id(self, otel_trace_id: int) -> str | None: """ Get the MLflow trace ID for the given OpenTelemetry trace ID. """ return self._otel_id_to_mlflow_trace_id.get(otel_trace_id) def set_trace_metadata(self, trace_id: str, key: str, value: str): """ Set the trace metadata for the given request ID. """ with self.get_trace(trace_id) as trace: if trace: trace.info.trace_metadata[key] = value def pop_trace(self, otel_trace_id: int) -> ManagerTrace | None: """ Pop trace data for the given OpenTelemetry trace ID and return it as a ManagerTrace wrapper containing the trace and prompts. """ with self._lock: mlflow_trace_id = self._otel_id_to_mlflow_trace_id.pop(otel_trace_id, None) internal_trace = self._traces.pop(mlflow_trace_id, None) if mlflow_trace_id else None if internal_trace is None: return None return ManagerTrace( trace=internal_trace.to_mlflow_trace(), prompts=internal_trace.prompts ) def _check_timeout_update(self): """ TTL/Timeout may be updated by users after initial cache creation. This method checks for the update and create a new cache instance with the updated timeout. """ new_timeout = MLFLOW_TRACE_TIMEOUT_SECONDS.get() if new_timeout != getattr(self._traces, "timeout", None): if len(self._traces) > 0: _logger.warning( f"The timeout of the trace buffer has been updated to {new_timeout} seconds. " "This operation discards all in-progress traces at the moment. Please make " "sure to update the timeout when there are no in-progress traces." ) with self._lock: # We need to check here again in case this method runs in parallel if new_timeout != getattr(self._traces, "timeout", None): self._traces = get_trace_cache_with_timeout() @classmethod def reset(cls): """Clear all the aggregated trace data. This should only be used for testing.""" if cls._instance: with cls._instance._lock: cls._instance._traces.clear() cls._instance = None
InMemoryTraceManager
python
getsentry__sentry
tests/sentry/seer/explorer/test_tools.py
{ "start": 44210, "end": 51540 }
class ____(APITransactionTestCase): def test_get_repository_definition_success(self): """Test successful repository lookup""" Repository.objects.create( organization_id=self.organization.id, name="getsentry/seer", provider="integrations:github", external_id="12345678", integration_id=123, status=ObjectStatus.ACTIVE, ) result = get_repository_definition( organization_id=self.organization.id, repo_full_name="getsentry/seer", ) assert result is not None assert result["organization_id"] == self.organization.id assert result["integration_id"] == "123" assert result["provider"] == "integrations:github" assert result["owner"] == "getsentry" assert result["name"] == "seer" assert result["external_id"] == "12345678" def test_get_repository_definition_invalid_format(self): """Test that invalid repo name format returns None""" result = get_repository_definition( organization_id=self.organization.id, repo_full_name="invalid-format", ) assert result is None def test_get_repository_definition_not_found(self): """Test that nonexistent repository returns None""" result = get_repository_definition( organization_id=self.organization.id, repo_full_name="nonexistent/repo", ) assert result is None def test_get_repository_definition_wrong_org(self): """Test that repository from different org returns None""" other_org = self.create_organization() Repository.objects.create( organization_id=other_org.id, name="getsentry/seer", provider="integrations:github", external_id="12345678", integration_id=123, status=ObjectStatus.ACTIVE, ) result = get_repository_definition( organization_id=self.organization.id, repo_full_name="getsentry/seer", ) assert result is None def test_get_repository_definition_inactive_repo(self): """Test that inactive repository returns None""" Repository.objects.create( organization_id=self.organization.id, name="getsentry/seer", provider="integrations:github", external_id="12345678", integration_id=123, status=ObjectStatus.DISABLED, ) result = get_repository_definition( organization_id=self.organization.id, repo_full_name="getsentry/seer", ) assert result is None def test_get_repository_definition_no_integration_id(self): """Test repository without integration_id""" Repository.objects.create( organization_id=self.organization.id, name="getsentry/seer", provider="integrations:github", external_id="12345678", integration_id=None, status=ObjectStatus.ACTIVE, ) result = get_repository_definition( organization_id=self.organization.id, repo_full_name="getsentry/seer", ) assert result is not None assert result["integration_id"] is None def test_get_repository_definition_unsupported_provider(self): """Test that repositories with unsupported providers are filtered out""" # Create a GitLab repo (unsupported provider) Repository.objects.create( organization_id=self.organization.id, name="getsentry/seer", provider="integrations:gitlab", external_id="12345678", integration_id=123, status=ObjectStatus.ACTIVE, ) result = get_repository_definition( organization_id=self.organization.id, repo_full_name="getsentry/seer", ) # Should return None since GitLab is not a supported provider assert result is None def test_get_repository_definition_github_enterprise(self): """Test that GitHub Enterprise provider is supported""" Repository.objects.create( organization_id=self.organization.id, name="getsentry/seer", provider="integrations:github_enterprise", external_id="12345678", integration_id=123, status=ObjectStatus.ACTIVE, ) result = get_repository_definition( organization_id=self.organization.id, repo_full_name="getsentry/seer", ) assert result is not None assert result["provider"] == "integrations:github_enterprise" def test_get_repository_definition_multiple_providers(self): """Test that when multiple repos with different supported providers exist, first one is returned""" # Create two repos with same name but different providers Repository.objects.create( organization_id=self.organization.id, name="getsentry/seer", provider="integrations:github", external_id="12345678", integration_id=123, status=ObjectStatus.ACTIVE, ) Repository.objects.create( organization_id=self.organization.id, name="getsentry/seer", provider="integrations:github_enterprise", external_id="87654321", integration_id=456, status=ObjectStatus.ACTIVE, ) # Should return one of them without raising MultipleObjectsReturned result = get_repository_definition( organization_id=self.organization.id, repo_full_name="getsentry/seer", ) assert result is not None # Should return the first matching repo (in this case, GitHub) assert result["provider"] in [ "integrations:github", "integrations:github_enterprise", ] assert result["owner"] == "getsentry" assert result["name"] == "seer" def test_get_repository_definition_filters_unsupported_with_supported(self): """Test that unsupported providers are ignored even when a supported one exists""" # Create unsupported provider repo Repository.objects.create( organization_id=self.organization.id, name="getsentry/seer", provider="integrations:gitlab", external_id="99999999", integration_id=999, status=ObjectStatus.ACTIVE, ) # Create supported provider repo Repository.objects.create( organization_id=self.organization.id, name="getsentry/seer", provider="integrations:github", external_id="12345678", integration_id=123, status=ObjectStatus.ACTIVE, ) result = get_repository_definition( organization_id=self.organization.id, repo_full_name="getsentry/seer", ) # Should return the GitHub repo, not GitLab assert result is not None assert result["provider"] == "integrations:github" assert result["external_id"] == "12345678"
TestGetRepositoryDefinition
python
lazyprogrammer__machine_learning_examples
rl2/cartpole/q_learning.py
{ "start": 2308, "end": 4731 }
class ____: def __init__(self, env, feature_transformer): self.env = env self.models = [] self.feature_transformer = feature_transformer for i in range(env.action_space.n): model = SGDRegressor(feature_transformer.dimensions) self.models.append(model) def predict(self, s): X = self.feature_transformer.transform(np.atleast_2d(s)) result = np.stack([m.predict(X) for m in self.models]).T return result def update(self, s, a, G): X = self.feature_transformer.transform(np.atleast_2d(s)) self.models[a].partial_fit(X, [G]) def sample_action(self, s, eps): if np.random.random() < eps: return self.env.action_space.sample() else: return np.argmax(self.predict(s)) def play_one(env, model, eps, gamma): observation = env.reset() done = False totalreward = 0 iters = 0 while not done and iters < 2000: # if we reach 2000, just quit, don't want this going forever # the 200 limit seems a bit early action = model.sample_action(observation, eps) prev_observation = observation observation, reward, done, info = env.step(action) if done: reward = -200 # update the model next = model.predict(observation) # print(next.shape) assert(next.shape == (1, env.action_space.n)) G = reward + gamma*np.max(next) model.update(prev_observation, action, G) if reward == 1: # if we changed the reward to -200 totalreward += reward iters += 1 return totalreward def main(): env = gym.make('CartPole-v0') ft = FeatureTransformer(env) model = Model(env, ft) gamma = 0.99 if 'monitor' in sys.argv: filename = os.path.basename(__file__).split('.')[0] monitor_dir = './' + filename + '_' + str(datetime.now()) env = wrappers.Monitor(env, monitor_dir) N = 500 totalrewards = np.empty(N) costs = np.empty(N) for n in range(N): eps = 1.0/np.sqrt(n+1) totalreward = play_one(env, model, eps, gamma) totalrewards[n] = totalreward if n % 100 == 0: print("episode:", n, "total reward:", totalreward, "eps:", eps, "avg reward (last 100):", totalrewards[max(0, n-100):(n+1)].mean()) print("avg reward for last 100 episodes:", totalrewards[-100:].mean()) print("total steps:", totalrewards.sum()) plt.plot(totalrewards) plt.title("Rewards") plt.show() plot_running_avg(totalrewards) if __name__ == '__main__': main()
Model
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 66968, "end": 68325 }
class ____: def test_laplace(self): # test against Laplace (special case for kappa=1) points = np.array([1, 2, 3]) pdf1 = stats.laplace_asymmetric.pdf(points, 1) pdf2 = stats.laplace.pdf(points) assert_allclose(pdf1, pdf2) def test_asymmetric_laplace_pdf(self): # test asymmetric Laplace points = np.array([1, 2, 3]) kappa = 2 kapinv = 1/kappa pdf1 = stats.laplace_asymmetric.pdf(points, kappa) pdf2 = stats.laplace_asymmetric.pdf(points*(kappa**2), kapinv) assert_allclose(pdf1, pdf2) def test_asymmetric_laplace_log_10_16(self): # test asymmetric Laplace points = np.array([-np.log(16), np.log(10)]) kappa = 2 pdf1 = stats.laplace_asymmetric.pdf(points, kappa) cdf1 = stats.laplace_asymmetric.cdf(points, kappa) sf1 = stats.laplace_asymmetric.sf(points, kappa) pdf2 = np.array([1/10, 1/250]) cdf2 = np.array([1/5, 1 - 1/500]) sf2 = np.array([4/5, 1/500]) ppf1 = stats.laplace_asymmetric.ppf(cdf2, kappa) ppf2 = points isf1 = stats.laplace_asymmetric.isf(sf2, kappa) isf2 = points assert_allclose(np.concatenate((pdf1, cdf1, sf1, ppf1, isf1)), np.concatenate((pdf2, cdf2, sf2, ppf2, isf2)))
TestLaplaceasymmetric
python
pytorch__pytorch
torch/_dynamo/bytecode_transformation.py
{ "start": 1991, "end": 3811 }
class ____: """A mutable version of dis.Instruction""" opcode: int opname: str arg: Optional[int] argval: Any offset: Optional[int] = None starts_line: Optional[int] = None is_jump_target: bool = False positions: Optional["dis.Positions"] = None # extra fields to make modification easier: target: Optional["Instruction"] = None exn_tab_entry: Optional[InstructionExnTabEntry] = None argrepr: Optional[str] = None def __hash__(self) -> int: return id(self) def __eq__(self, other: object) -> bool: return id(self) == id(other) def short_inst_repr(self) -> str: return f"Instruction(opname={self.opname}, offset={self.offset})" def copy_positions(self, other: "Instruction") -> None: self.starts_line = other.starts_line self.positions = other.positions if sys.version_info >= (3, 13): def convert_instruction(i: dis.Instruction) -> Instruction: return Instruction( i.opcode, i.opname, i.arg, i.argval, i.offset, i.line_number, i.is_jump_target, i.positions, ) elif sys.version_info >= (3, 11): def convert_instruction(i: dis.Instruction) -> Instruction: return Instruction( i.opcode, i.opname, i.arg, i.argval, i.offset, i.starts_line, i.is_jump_target, i.positions, ) else: def convert_instruction(i: dis.Instruction) -> Instruction: return Instruction( i.opcode, i.opname, i.arg, i.argval, i.offset, i.starts_line, i.is_jump_target, None, )
Instruction
python
tornadoweb__tornado
tornado/test/httpclient_test.py
{ "start": 2220, "end": 2450 }
class ____(RequestHandler): def get(self, count): count = int(count) if count > 0: self.redirect(self.reverse_url("countdown", count - 1)) else: self.write("Zero")
CountdownHandler
python
airbytehq__airbyte
airbyte-integrations/connectors/source-zenloop/source_zenloop/streams.py
{ "start": 6215, "end": 7159 }
class ____(ChildStreamMixin, ZenloopStream): # API Doc: https://docs.zenloop.com/reference/get-list-of-properties primary_key = "id" has_date_param = False extra_params = {"page": "1"} parent_stream_class = Surveys def path( self, stream_state: Mapping[str, Any] = None, stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None ) -> str: # take optional survey_id if entered if self.survey_id: return f"surveys/{self.survey_id}/properties" # slice all survey_id's if nothing provided else: return f"surveys/{stream_slice['survey_slice']}/properties" def parse_response(self, response: requests.Response, **kwargs) -> Iterable[Mapping]: response_json = response.json() # select properties and surveys to be able to link properties to a survey yield from response_json.get("properties", [])
Properties
python
scrapy__scrapy
tests/AsyncCrawlerProcess/twisted_reactor_custom_settings_same.py
{ "start": 63, "end": 254 }
class ____(scrapy.Spider): name = "asyncio_reactor1" custom_settings = { "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", }
AsyncioReactorSpider1
python
dateutil__dateutil
src/dateutil/tz/win.py
{ "start": 8730, "end": 12935 }
class ____(tzwinbase): """ Class representing the local time zone information in the Windows registry While :class:`dateutil.tz.tzlocal` makes system calls (via the :mod:`time` module) to retrieve time zone information, ``tzwinlocal`` retrieves the rules directly from the Windows registry and creates an object like :class:`dateutil.tz.tzwin`. Because Windows does not have an equivalent of :func:`time.tzset`, on Windows, :class:`dateutil.tz.tzlocal` instances will always reflect the time zone settings *at the time that the process was started*, meaning changes to the machine's time zone settings during the run of a program on Windows will **not** be reflected by :class:`dateutil.tz.tzlocal`. Because ``tzwinlocal`` reads the registry directly, it is unaffected by this issue. """ def __init__(self): with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle: with winreg.OpenKey(handle, TZLOCALKEYNAME) as tzlocalkey: keydict = valuestodict(tzlocalkey) self._std_abbr = keydict["StandardName"] self._dst_abbr = keydict["DaylightName"] try: tzkeyname = text_type('{kn}\\{sn}').format(kn=TZKEYNAME, sn=self._std_abbr) with winreg.OpenKey(handle, tzkeyname) as tzkey: _keydict = valuestodict(tzkey) self._display = _keydict["Display"] except OSError: self._display = None stdoffset = -keydict["Bias"]-keydict["StandardBias"] dstoffset = stdoffset-keydict["DaylightBias"] self._std_offset = datetime.timedelta(minutes=stdoffset) self._dst_offset = datetime.timedelta(minutes=dstoffset) # For reasons unclear, in this particular key, the day of week has been # moved to the END of the SYSTEMTIME structure. tup = struct.unpack("=8h", keydict["StandardStart"]) (self._stdmonth, self._stdweeknumber, # Last = 5 self._stdhour, self._stdminute) = tup[1:5] self._stddayofweek = tup[7] tup = struct.unpack("=8h", keydict["DaylightStart"]) (self._dstmonth, self._dstweeknumber, # Last = 5 self._dsthour, self._dstminute) = tup[1:5] self._dstdayofweek = tup[7] self._dst_base_offset_ = self._dst_offset - self._std_offset self.hasdst = self._get_hasdst() def __repr__(self): return "tzwinlocal()" def __str__(self): # str will return the standard name, not the daylight name. return "tzwinlocal(%s)" % repr(self._std_abbr) def __reduce__(self): return (self.__class__, ()) def picknthweekday(year, month, dayofweek, hour, minute, whichweek): """ dayofweek == 0 means Sunday, whichweek 5 means last instance """ first = datetime.datetime(year, month, 1, hour, minute) # This will work if dayofweek is ISO weekday (1-7) or Microsoft-style (0-6), # Because 7 % 7 = 0 weekdayone = first.replace(day=((dayofweek - first.isoweekday()) % 7) + 1) wd = weekdayone + ((whichweek - 1) * ONEWEEK) if (wd.month != month): wd -= ONEWEEK return wd def valuestodict(key): """Convert a registry key's values to a dictionary.""" dout = {} size = winreg.QueryInfoKey(key)[1] tz_res = None for i in range(size): key_name, value, dtype = winreg.EnumValue(key, i) if dtype == winreg.REG_DWORD or dtype == winreg.REG_DWORD_LITTLE_ENDIAN: # If it's a DWORD (32-bit integer), it's stored as unsigned - convert # that to a proper signed integer if value & (1 << 31): value = value - (1 << 32) elif dtype == winreg.REG_SZ: # If it's a reference to the tzres DLL, load the actual string if value.startswith('@tzres'): tz_res = tz_res or tzres() value = tz_res.name_from_string(value) value = value.rstrip('\x00') # Remove trailing nulls dout[key_name] = value return dout
tzwinlocal
python
doocs__leetcode
solution/1200-1299/1206.Design Skiplist/Solution.py
{ "start": 0, "end": 151 }
class ____: __slots__ = ['val', 'next'] def __init__(self, val: int, level: int): self.val = val self.next = [None] * level
Node
python
pytorch__pytorch
torch/_dynamo/variables/base.py
{ "start": 5908, "end": 6504 }
class ____(AttributeMutation): """ This case of VariableTracker.mutation_type marker indicates 1. Dynamo allows mutation on the value's attributes. 2. The value exists before Dynamo tracing started. For instance, Dynamo could model a pre-existing object with this marker, indicating that if we encounter mutations to this object, we need to buffer then re-apply those mutations after the graph runs, since the object might be used afterwards in Python. """ def __init__(self) -> None: super().__init__(SourceType.Existing)
AttributeMutationExisting
python
tornadoweb__tornado
maint/test/redbot/red_test.py
{ "start": 718, "end": 960 }
class ____(RequestHandler): @asynchronous @gen.engine def get(self): self.write('hello ') yield gen.Task(self.flush) self.write('world') yield gen.Task(self.flush) self.finish()
ChunkedHandler
python
getsentry__sentry
src/sentry/workflow_engine/endpoints/validators/base/detector.py
{ "start": 1310, "end": 10535 }
class ____(CamelSnakeSerializer): enforce_single_datasource = False """ Set to True in subclasses to enforce that only a single data source can be configured. This prevents invalid configurations for detector types that don't support multiple data sources. """ name = serializers.CharField( required=True, max_length=200, help_text="Name of the monitor", ) type = serializers.CharField() config = serializers.JSONField(default=dict) owner = ActorField(required=False, allow_null=True) description = serializers.CharField(required=False, allow_null=True, allow_blank=True) enabled = serializers.BooleanField(required=False) condition_group = BaseDataConditionGroupValidator(required=False) def validate_type(self, value: str) -> builtins.type[GroupType]: type = grouptype.registry.get_by_slug(value) if type is None: organization = self.context.get("organization") if organization: error_message = get_unknown_detector_type_error(value, organization) else: error_message = f"Unknown detector type '{value}'" raise serializers.ValidationError(error_message) if type.detector_settings is None or type.detector_settings.validator is None: raise serializers.ValidationError("Detector type not compatible with detectors") # TODO: Probably need to check a feature flag to decide if a given # org/user is allowed to add a detector return type @property def data_sources(self) -> serializers.ListField: # TODO - improve typing here to enforce that the child is the correct type # otherwise, can look at creating a custom field. # This should be a list of `BaseDataSourceValidator`s raise NotImplementedError @property def data_conditions(self) -> BaseDataConditionValidator: raise NotImplementedError def validate_data_sources(self, value: list[dict[str, Any]]) -> list[dict[str, Any]]: """ Validate data sources, enforcing single data source if configured. """ if self.enforce_single_datasource and len(value) > 1: raise serializers.ValidationError( "Only one data source is allowed for this detector type." ) return value def get_quota(self) -> DetectorQuota: return DetectorQuota(has_exceeded=False, limit=-1, count=-1) def enforce_quota(self, validated_data) -> None: """ Enforce quota limits for detector creation. Raise ValidationError if quota limits are exceeded. Only Metric Issues Detector has quota limits. """ detector_quota = self.get_quota() if detector_quota.has_exceeded: raise serializers.ValidationError( f"Used {detector_quota.count}/{detector_quota.limit} of allowed {validated_data["type"].slug} monitors." ) def update(self, instance: Detector, validated_data: dict[str, Any]): with transaction.atomic(router.db_for_write(Detector)): if "name" in validated_data: instance.name = validated_data.get("name", instance.name) # Handle description field update if "description" in validated_data: instance.description = validated_data.get("description", instance.description) # Handle enable/disable detector if "enabled" in validated_data: enabled = validated_data.get("enabled") assert isinstance(enabled, bool) toggle_detector(instance, enabled) # Handle owner field update if "owner" in validated_data: owner = validated_data.get("owner") if owner: if owner.is_user: instance.owner_user_id = owner.id instance.owner_team_id = None elif owner.is_team: instance.owner_user_id = None instance.owner_team_id = owner.id else: # Clear owner if None is passed instance.owner_user_id = None instance.owner_team_id = None if "condition_group" in validated_data: condition_group = validated_data.pop("condition_group") data_conditions: list[DataConditionType] = condition_group.get("conditions") if data_conditions and instance.workflow_condition_group: group_validator = BaseDataConditionGroupValidator() group_validator.update(instance.workflow_condition_group, condition_group) # Handle config field update if "config" in validated_data: instance.config = validated_data.get("config", instance.config) try: enforce_config_schema(instance) except JSONSchemaValidationError as error: raise serializers.ValidationError({"config": [str(error)]}) instance.save() create_audit_entry( request=self.context["request"], organization=self.context["organization"], target_object=instance.id, event=audit_log.get_event_id("DETECTOR_EDIT"), data=instance.get_audit_log_data(), ) return instance def delete(self) -> None: """ Delete the detector by scheduling it for deletion. Subclasses can override this to perform detector-specific cleanup before deletion (e.g., removing billing seats, cleaning up external resources). They should call super().delete() to perform the actual deletion. """ assert self.instance is not None RegionScheduledDeletion.schedule(self.instance, days=0, actor=self.context["request"].user) self.instance.update(status=ObjectStatus.PENDING_DELETION) def _create_data_source(self, validated_data_source, detector: Detector): data_source_creator = validated_data_source["_creator"] data_source = data_source_creator.create() detector_data_source = DataSource.objects.create( organization_id=self.context["project"].organization_id, source_id=data_source.id, type=validated_data_source["data_source_type"], ) DataSourceDetector.objects.create(data_source=detector_data_source, detector=detector) def create(self, validated_data): # If quotas are exceeded, we will prevent creation of new detectors. # Do not disable or prevent the users from updating existing detectors. self.enforce_quota(validated_data) with transaction.atomic(router.db_for_write(Detector)): condition_group = DataConditionGroup.objects.create( logic_type=DataConditionGroup.Type.ANY, organization_id=self.context["organization"].id, ) if "condition_group" in validated_data: for condition in validated_data["condition_group"]["conditions"]: DataCondition.objects.create( comparison=condition["comparison"], condition_result=condition["condition_result"], type=condition["type"], condition_group=condition_group, ) owner = validated_data.get("owner") owner_user_id = None owner_team_id = None if owner: if owner.is_user: owner_user_id = owner.id elif owner.is_team: owner_team_id = owner.id detector = Detector( project_id=self.context["project"].id, name=validated_data["name"], description=validated_data.get("description"), workflow_condition_group=condition_group, type=validated_data["type"].slug, config=validated_data.get("config", {}), owner_user_id=owner_user_id, owner_team_id=owner_team_id, created_by_id=self.context["request"].user.id, ) try: enforce_config_schema(detector) except JSONSchemaValidationError as error: # Surface schema errors as a user-facing validation error raise serializers.ValidationError({"config": [str(error)]}) detector.save() if "data_sources" in validated_data: for validated_data_source in validated_data["data_sources"]: self._create_data_source(validated_data_source, detector) create_audit_entry( request=self.context["request"], organization=self.context["organization"], target_object=detector.id, event=audit_log.get_event_id("DETECTOR_ADD"), data=detector.get_audit_log_data(), ) return detector
BaseDetectorTypeValidator
python
spack__spack
lib/spack/spack/util/windows_registry.py
{ "start": 15287, "end": 15529 }
class ____(RegistryError): """Runtime Error describing issue with invalid key access to Windows registry""" def __init__(self, key): message = f"Cannot query invalid key: {key}" super().__init__(message)
InvalidKeyError
python
apache__airflow
task-sdk/src/airflow/sdk/execution_time/context.py
{ "start": 13866, "end": 14818 }
class ____: """Wrapper to access Variable values in template.""" def __init__(self, deserialize_json: bool) -> None: self._deserialize_json = deserialize_json def __eq__(self, other): if not isinstance(other, VariableAccessor): return False # All instances of VariableAccessor are equal since it is a stateless dynamic accessor return True def __hash__(self): return hash(self.__class__.__name__) def __repr__(self) -> str: return "<VariableAccessor (dynamic access)>" def __getattr__(self, key: str) -> Any: return _get_variable(key, self._deserialize_json) def get(self, key, default: Any = NOTSET) -> Any: try: return _get_variable(key, self._deserialize_json) except AirflowRuntimeError as e: if e.error.error == ErrorType.VARIABLE_NOT_FOUND: return default raise
VariableAccessor
python
rushter__MLAlgorithms
mla/knn.py
{ "start": 1682, "end": 2079 }
class ____(KNNBase): """Nearest neighbors classifier. Note: if there is a tie for the most common label among the neighbors, then the predicted label is arbitrary.""" def aggregate(self, neighbors_targets): """Return the most common target label.""" most_common_label = Counter(neighbors_targets).most_common(1)[0][0] return most_common_label
KNNClassifier
python
django__django
django/contrib/admin/utils.py
{ "start": 17193, "end": 22002 }
class ____(Exception): pass def get_model_from_relation(field): if hasattr(field, "path_infos"): return field.path_infos[-1].to_opts.model else: raise NotRelationField def reverse_field_path(model, path): """Create a reversed field path. E.g. Given (Order, "user__groups"), return (Group, "user__order"). Final field must be a related model, not a data field. """ reversed_path = [] parent = model pieces = path.split(LOOKUP_SEP) for piece in pieces: field = parent._meta.get_field(piece) # skip trailing data field if extant: if len(reversed_path) == len(pieces) - 1: # final iteration try: get_model_from_relation(field) except NotRelationField: break # Field should point to another model if field.is_relation and not (field.auto_created and not field.concrete): related_name = field.related_query_name() parent = field.remote_field.model else: related_name = field.field.name parent = field.related_model reversed_path.insert(0, related_name) return (parent, LOOKUP_SEP.join(reversed_path)) def get_fields_from_path(model, path): """Return list of Fields given path relative to model. e.g. (ModelX, "user__groups__name") -> [ <django.db.models.fields.related.ForeignKey object at 0x...>, <django.db.models.fields.related.ManyToManyField object at 0x...>, <django.db.models.fields.CharField object at 0x...>, ] """ pieces = path.split(LOOKUP_SEP) fields = [] for piece in pieces: if fields: parent = get_model_from_relation(fields[-1]) else: parent = model fields.append(parent._meta.get_field(piece)) return fields def construct_change_message(form, formsets, add): """ Construct a JSON structure describing changes from a changed object. Translations are deactivated so that strings are stored untranslated. Translation happens later on LogEntry access. """ # Evaluating `form.changed_data` prior to disabling translations is # required to avoid fields affected by localization from being included # incorrectly, e.g. where date formats differ such as MM/DD/YYYY vs # DD/MM/YYYY. changed_data = form.changed_data with translation_override(None): # Deactivate translations while fetching verbose_name for form # field labels and using `field_name`, if verbose_name is not provided. # Translations will happen later on LogEntry access. changed_field_labels = _get_changed_field_labels_from_form(form, changed_data) change_message = [] if add: change_message.append({"added": {}}) elif form.changed_data: change_message.append({"changed": {"fields": changed_field_labels}}) if formsets: with translation_override(None): for formset in formsets: for added_object in formset.new_objects: change_message.append( { "added": { "name": str(added_object._meta.verbose_name), "object": str(added_object), } } ) for changed_object, changed_fields in formset.changed_objects: change_message.append( { "changed": { "name": str(changed_object._meta.verbose_name), "object": str(changed_object), "fields": _get_changed_field_labels_from_form( formset.forms[0], changed_fields ), } } ) for deleted_object in formset.deleted_objects: change_message.append( { "deleted": { "name": str(deleted_object._meta.verbose_name), "object": str(deleted_object), } } ) return change_message def _get_changed_field_labels_from_form(form, changed_data): changed_field_labels = [] for field_name in changed_data: try: verbose_field_name = form.fields[field_name].label or field_name except KeyError: verbose_field_name = field_name changed_field_labels.append(str(verbose_field_name)) return changed_field_labels
NotRelationField
python
Textualize__rich
benchmarks/benchmarks.py
{ "start": 1828, "end": 2163 }
class ____: def setup(self): self.console = Console( file=StringIO(), color_system="truecolor", legacy_windows=False ) def time_wrapping_unicode_heavy_warm_cache(self): for _ in range(20): Text(snippets.UNICODE_HEAVY_TEXT).wrap(self.console, 12, overflow="fold")
TextHotCacheSuite
python
numpy__numpy
numpy/_build_utils/tempita/_tempita.py
{ "start": 13216, "end": 14008 }
class ____(dict): def __init__(self, **kw): for name, value in kw.items(): setattr(self, name, value) def __setattr__(self, name, value): self[name] = value def __getattr__(self, name): try: return self[name] except KeyError: raise AttributeError(name) def __getitem__(self, key): if "default" in self: try: return dict.__getitem__(self, key) except KeyError: return dict.__getitem__(self, "default") else: return dict.__getitem__(self, key) def __repr__(self): return "<%s %s>" % ( self.__class__.__name__, " ".join(["%s=%r" % (k, v) for k, v in sorted(self.items())]), )
bunch
python
conda__conda
conda/auxlib/entity.py
{ "start": 17704, "end": 17869 }
class ____(Field): _type = str def box(self, instance, instance_type, val): return str(val) if isinstance(val, NumberField._type) else val
StringField
python
ray-project__ray
doc/source/serve/doc_code/http_guide/http_guide.py
{ "start": 533, "end": 968 }
class ____: @app.get("/") def root(self): return "Hello, world!" serve.run(MyFastAPIDeployment.bind(), route_prefix="/hello") resp = requests.get("http://localhost:8000/hello") assert resp.json() == "Hello, world!" # __end_fastapi__ # __begin_fastapi_multi_routes__ import ray import requests from fastapi import FastAPI from ray import serve app = FastAPI() @serve.deployment @serve.ingress(app)
MyFastAPIDeployment
python
rq__rq
tests/test_cron_job.py
{ "start": 166, "end": 12641 }
class ____(RQTestCase): """Tests for the CronJob class""" def setUp(self): super().setUp() self.queue = Queue(connection=self.connection) def test_cron_job_initialization(self): """CronJob correctly initializes with the provided parameters""" # Test with minimum required parameters (interval) cron_job = CronJob(func=say_hello, queue_name=self.queue.name, interval=60) self.assertEqual(cron_job.func, say_hello) self.assertEqual(cron_job.args, ()) self.assertEqual(cron_job.kwargs, {}) self.assertEqual(cron_job.interval, 60) self.assertIsNone(cron_job.cron) self.assertEqual(cron_job.queue_name, self.queue.name) # Test with all parameters args = (1, 2, 3) kwargs = {'name': 'Test'} interval = 60 timeout = 180 result_ttl = 600 ttl = 300 failure_ttl = 400 meta = {'key': 'value'} cron_job = CronJob( func=say_hello, queue_name=self.queue.name, args=args, kwargs=kwargs, interval=interval, job_timeout=timeout, result_ttl=result_ttl, ttl=ttl, failure_ttl=failure_ttl, meta=meta, ) self.assertEqual(cron_job.func, say_hello) self.assertEqual(cron_job.args, args) self.assertEqual(cron_job.kwargs, kwargs) self.assertEqual(cron_job.interval, interval) self.assertEqual(cron_job.queue_name, self.queue.name) # Check job options dict self.assertEqual(cron_job.job_options['job_timeout'], timeout) self.assertEqual(cron_job.job_options['result_ttl'], result_ttl) self.assertEqual(cron_job.job_options['ttl'], ttl) self.assertEqual(cron_job.job_options['failure_ttl'], failure_ttl) self.assertEqual(cron_job.job_options['meta'], meta) def test_get_next_run_time(self): """Test that get_next_run_time correctly calculates the next run time""" # Test with cron job (returns far future for no latest_run_time initially) cron_job = CronJob(func=say_hello, queue_name=self.queue.name, cron='0 9 * * *') # Without latest_run_time set, get_next_run_time uses current time next_run = cron_job.get_next_run_time() self.assertIsInstance(next_run, datetime) # Test with a specific interval interval = 60 # 60 seconds cron_job = CronJob(func=say_hello, queue_name=self.queue.name, interval=interval) now = utils.now() cron_job.set_run_time(now) next_run_time = cron_job.get_next_run_time() # Check that next_run_time is about interval seconds from now # Allow 2 seconds tolerance for test execution time self.assertTrue( now + timedelta(seconds=interval - 5) <= next_run_time <= now + timedelta(seconds=interval + 5), f'Next run time {next_run_time} not within expected range', ) def test_should_run(self): """Test should_run method logic""" # Job with interval that has not run yet always returns True cron_job = CronJob(func=say_hello, queue_name=self.queue.name, interval=3600) self.assertTrue(cron_job.should_run()) # Job with future next_run_time should not run yet cron_job.latest_run_time = utils.now() - timedelta(seconds=5) cron_job.next_run_time = utils.now() + timedelta(minutes=5) self.assertFalse(cron_job.should_run()) # Job with past next_run_time should run cron_job.next_run_time = utils.now() - timedelta(seconds=5) self.assertTrue(cron_job.should_run()) def test_enqueue(self): """Test that enqueue correctly creates a job in the queue""" cron_job = CronJob( func=say_hello, queue_name=self.queue.name, args=('Hello',), interval=60, ) job = cron_job.enqueue(self.connection) # Fetch job from queue and verify jobs = self.queue.get_jobs() self.assertEqual(len(jobs), 1) self.assertEqual(jobs[0].id, job.id) def test_enqueue_with_job_timeout(self): """Test that job_timeout is properly set on the job and not passed to the function""" timeout_value = 180 cron_job = CronJob( func=say_hello, queue_name=self.queue.name, args=('World',), interval=60, job_timeout=timeout_value, ) job = cron_job.enqueue(self.connection) self.assertEqual(job.timeout, timeout_value) # Verify job can be executed without TypeError job.perform() def test_set_run_time(self): """Test that set_run_time correctly sets latest run time and updates next run time""" # Test with cron job cron_job = CronJob(func=say_hello, queue_name=self.queue.name, cron='0 9 * * *') test_time = utils.now() cron_job.set_run_time(test_time) # Check latest_run_time is set correctly self.assertEqual(cron_job.latest_run_time, test_time) # Since cron is set, next_run_time should be calculated self.assertIsNotNone(cron_job.next_run_time) # Test with an interval interval = 60 # 60 seconds cron_job = CronJob(func=say_hello, queue_name=self.queue.name, interval=interval) cron_job.set_run_time(test_time) # Check latest_run_time is set correctly self.assertEqual(cron_job.latest_run_time, test_time) # Check that next_run_time is calculated correctly next_run_time = test_time + timedelta(seconds=interval) self.assertEqual(cron_job.next_run_time, next_run_time) # Test updating the run time test_time = test_time + timedelta(seconds=30) cron_job.set_run_time(test_time) # Check latest_run_time is updated self.assertEqual(cron_job.latest_run_time, test_time) # Check that next_run_time is recalculated new_expected_next_run = test_time + timedelta(seconds=interval) self.assertEqual(cron_job.next_run_time, new_expected_next_run) def test_cron_job_initialization_with_cron_string(self): """CronJob correctly initializes with cron string parameters""" cron_expr = '0 9 * * 1-5' # 9 AM weekdays cron_job = CronJob(func=say_hello, queue_name=self.queue.name, cron=cron_expr) self.assertEqual(cron_job.func, say_hello) self.assertEqual(cron_job.cron, cron_expr) self.assertIsNone(cron_job.interval) self.assertEqual(cron_job.queue_name, self.queue.name) # next_run_time should be set immediately upon initialization self.assertIsNotNone(cron_job.next_run_time) # latest_run_time should still be None (hasn't run yet) self.assertIsNone(cron_job.latest_run_time) # For comparison, interval jobs don't set next_run_time during initialization interval_job = CronJob(func=say_hello, queue_name=self.queue.name, interval=60) self.assertIsNone(interval_job.next_run_time) # Not set until first run def test_get_next_run_time_with_cron_string(self): """Test that get_next_run_time correctly calculates next run time using cron expression""" # Test daily at 9 AM cron_expr = '0 9 * * *' cron_job = CronJob(func=say_hello, queue_name=self.queue.name, cron=cron_expr) # Set a base time to 8 AM today base_time = datetime(2023, 10, 27, 8, 0, 0) cron_job.set_run_time(base_time) next_run_time = cron_job.get_next_run_time() expected_next_run = datetime(2023, 10, 27, 9, 0, 0) # 9 AM same day self.assertEqual(next_run_time, expected_next_run) # If we're already past 9 AM, should schedule for next day base_time = datetime(2023, 10, 27, 10, 0, 0) cron_job.set_run_time(base_time) next_run_time = cron_job.get_next_run_time() expected_next_run = datetime(2023, 10, 28, 9, 0, 0) # 9 AM next day self.assertEqual(next_run_time, expected_next_run) def test_should_run_with_cron_string(self): """Test should_run method logic with cron expressions""" # Job with cron that has not run yet should NOT run immediately (crontab behavior) cron_job = CronJob(func=say_hello, queue_name=self.queue.name, cron='0 9 * * *') # next_run_time should already be set during initialization self.assertIsNotNone(cron_job.next_run_time) # Job with future next_run_time should not run yet cron_job.next_run_time = utils.now() + timedelta(hours=1) self.assertFalse(cron_job.should_run()) # Job with past next_run_time should run cron_job.next_run_time = utils.now() - timedelta(minutes=5) self.assertTrue(cron_job.should_run()) def test_cron_weekday_expressions(self): """Test cron expressions with specific weekday patterns""" # Monday to Friday at 9 AM cron_expr = '0 9 * * 1-5' cron_job = CronJob(func=say_hello, queue_name=self.queue.name, cron=cron_expr) # Set to Friday 9 AM friday_time = datetime(2023, 10, 27, 9, 0, 0) # Assuming this is a Friday cron_job.set_run_time(friday_time) next_run_time = cron_job.get_next_run_time() # Next run should be Monday (skip weekend) # We can verify it's not Saturday or Sunday by checking the weekday self.assertIn(next_run_time.weekday(), [0, 1, 2, 3, 4]) # Monday=0, Friday=4 self.assertEqual(next_run_time.hour, 9) self.assertEqual(next_run_time.minute, 0) def test_cron_job_serialization_roundtrip(self): """Test CronJob serialization and deserialization with both interval and cron jobs""" # Test with interval job interval_job = CronJob( func=say_hello, queue_name=self.queue.name, args=('test', 'args'), # These won't be serialized kwargs={'test': 'kwarg'}, # These won't be serialized interval=60, job_timeout=30, result_ttl=600, meta={'test': 'meta'}, ) # Serialize and deserialize interval_data = interval_job.to_dict() restored_interval = CronJob.from_dict(interval_data) # Check serialized data structure self.assertEqual(interval_data['func_name'], 'tests.fixtures.say_hello') self.assertEqual(interval_data['queue_name'], self.queue.name) self.assertEqual(interval_data['interval'], 60) self.assertIsNone(interval_data['cron']) self.assertEqual(interval_data['job_timeout'], 30) self.assertEqual(interval_data['result_ttl'], 600) self.assertEqual(interval_data['meta'], {'test': 'meta'}) # Check restored fields match original self.assertEqual(restored_interval.queue_name, interval_job.queue_name) self.assertEqual(restored_interval.interval, interval_job.interval) self.assertEqual(restored_interval.cron, interval_job.cron) self.assertEqual(restored_interval.job_options, interval_job.job_options) self.assertIsNone(restored_interval.func) # Test with cron job cron_job = CronJob( func=say_hello, queue_name='priority_queue', cron='0 9 * * MON-FRI', ttl=300, failure_ttl=1800 ) # Serialize and deserialize cron_data = cron_job.to_dict() restored_cron = CronJob.from_dict(cron_data) # Check serialized data structure self.assertEqual(cron_data['func_name'], 'tests.fixtures.say_hello') self.assertEqual(cron_data['queue_name'], 'priority_queue') self.assertIsNone(cron_data['interval']) self.assertEqual(cron_data['cron'], '0 9 * * MON-FRI') self.assertEqual(cron_data['ttl'], 300) self.assertEqual(cron_data['failure_ttl'], 1800) # result_ttl should have default value self.assertEqual(cron_data['result_ttl'], 500) # Check restored fields match original self.assertEqual(restored_cron.queue_name, cron_job.queue_name) self.assertEqual(restored_cron.interval, cron_job.interval) self.assertEqual(restored_cron.cron, cron_job.cron) self.assertEqual(restored_cron.job_options, cron_job.job_options) self.assertIsNone(restored_cron.func)
TestCronJob
python
nedbat__coveragepy
coverage/files.py
{ "start": 7688, "end": 8604 }
class ____: """A matcher for modules in a tree.""" def __init__(self, module_names: Iterable[str], name: str = "unknown") -> None: self.modules = list(module_names) self.name = name def __repr__(self) -> str: return f"<ModuleMatcher {self.name} {self.modules!r}>" def info(self) -> list[str]: """A list of strings for displaying when dumping state.""" return self.modules def match(self, module_name: str) -> bool: """Does `module_name` indicate a module in one of our packages?""" if not module_name: return False for m in self.modules: if module_name.startswith(m): if module_name == m: return True if module_name[len(m)] == ".": # This is a module in the package return True return False
ModuleMatcher
python
getsentry__sentry
src/sentry/integrations/github/integration.py
{ "start": 45943, "end": 50059 }
class ____: def dispatch(self, request: HttpRequest, pipeline: IntegrationPipeline) -> HttpResponseBase: self.active_user_organization = determine_active_organization(request) if self.active_user_organization is None: return error( request, None, error_short=GitHubInstallationError.MISSING_ORGANIZATION, error_long=ERR_INTEGRATION_MISSING_ORGANIZATION, ) has_scm_multi_org = features.has( "organizations:integrations-scm-multi-org", organization=self.active_user_organization.organization, ) with record_event( IntegrationPipelineViewType.ORGANIZATION_SELECTION ).capture() as lifecycle: installation_info = pipeline.fetch_state("existing_installation_info") or [] if len(installation_info) == 0: return pipeline.next_step() # add an option for users to install on a new GH organization installation_info.append( { "installation_id": "-1", "github_account": "Integrate with a new GitHub organization", "avatar_url": "", } ) if chosen_installation_id := request.GET.get("chosen_installation_id"): if chosen_installation_id == "-1": return pipeline.next_step() # Validate the same org is installing and that they have the multi org feature installing_organization_slug = pipeline.fetch_state("installing_organization_slug") is_same_installing_org = ( (installing_organization_slug is not None) and installing_organization_slug == self.active_user_organization.organization.slug ) if not has_scm_multi_org or not is_same_installing_org: lifecycle.record_failure(GitHubInstallationError.FEATURE_NOT_AVAILABLE) return error( request, self.active_user_organization, error_short=GitHubInstallationError.FEATURE_NOT_AVAILABLE, ) # Verify that the given GH installation belongs to the person installing the pipeline installation_ids = [ installation["installation_id"] for installation in installation_info ] if chosen_installation_id not in installation_ids: lifecycle.record_failure( failure_reason=GitHubInstallationError.INVALID_INSTALLATION ) return error( request, self.active_user_organization, error_short=GitHubInstallationError.INVALID_INSTALLATION, error_long=ERR_INTEGRATION_INVALID_INSTALLATION, ) pipeline.bind_state("chosen_installation", chosen_installation_id) return pipeline.next_step() pipeline.bind_state( "installing_organization_slug", self.active_user_organization.organization.slug ) serialized_organization = organization_service.serialize_organization( id=self.active_user_organization.organization.id, as_user=( serialize_rpc_user(request.user) if isinstance(request.user, User) else None ), ) return render_react_view( request=request, pipeline_name="githubInstallationSelect", props={ "installation_info": installation_info, "has_scm_multi_org": has_scm_multi_org, "organization": serialized_organization, "organization_slug": self.active_user_organization.organization.slug, }, )
GithubOrganizationSelection
python
ipython__ipython
IPython/extensions/deduperreload/deduperreload.py
{ "start": 3338, "end": 4481 }
class ____(ast.NodeVisitor): def __init__(self) -> None: self.is_constexpr = True self._allow_builtins_exceptions = True @contextlib.contextmanager def disallow_builtins_exceptions(self) -> Generator[None, None, None]: prev_allow = self._allow_builtins_exceptions self._allow_builtins_exceptions = False try: yield finally: self._allow_builtins_exceptions = prev_allow def visit_Attribute(self, node: ast.Attribute) -> None: with self.disallow_builtins_exceptions(): self.visit(node.value) def visit_Name(self, node: ast.Name) -> None: if self._allow_builtins_exceptions and hasattr(builtins, node.id): return self.is_constexpr = False def visit(self, node: ast.AST) -> None: if not self.is_constexpr: # can short-circuit if we've already detected that it's not a constexpr return super().visit(node) def __call__(self, node: ast.AST) -> bool: self.is_constexpr = True self.visit(node) return self.is_constexpr
ConstexprDetector
python
allegroai__clearml
clearml/backend_api/services/v2_20/projects.py
{ "start": 82731, "end": 86232 }
class ____(Request): """ Get a list of all hyper parameter sections and names used in tasks within the given project. :param project: Project ID :type project: str :param page: Page number :type page: int :param page_size: Page size :type page_size: int :param include_subprojects: If set to 'true' and the project field is set then the result includes hyper parameters from the subproject tasks :type include_subprojects: bool """ _service = "projects" _action = "get_hyper_parameters" _version = "2.20" _schema = { "definitions": {}, "properties": { "include_subprojects": { "default": True, "description": "If set to 'true' and the project field is set then the result includes hyper parameters from the subproject tasks", "type": "boolean", }, "page": {"default": 0, "description": "Page number", "type": "integer"}, "page_size": { "default": 500, "description": "Page size", "type": "integer", }, "project": {"description": "Project ID", "type": "string"}, }, "required": ["project"], "type": "object", } def __init__( self, project: str, page: Optional[int] = 0, page_size: Optional[int] = 500, include_subprojects: Optional[bool] = True, **kwargs: Any ) -> None: super(GetHyperParametersRequest, self).__init__(**kwargs) self.project = project self.page = page self.page_size = page_size self.include_subprojects = include_subprojects @schema_property("project") def project(self) -> str: return self._property_project @project.setter def project(self, value: str) -> None: if value is None: self._property_project = None return self.assert_isinstance(value, "project", six.string_types) self._property_project = value @schema_property("page") def page(self) -> Optional[int]: return self._property_page @page.setter def page(self, value: Optional[int]) -> None: if value is None: self._property_page = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "page", six.integer_types) self._property_page = value @schema_property("page_size") def page_size(self) -> Optional[int]: return self._property_page_size @page_size.setter def page_size(self, value: Optional[int]) -> None: if value is None: self._property_page_size = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "page_size", six.integer_types) self._property_page_size = value @schema_property("include_subprojects") def include_subprojects(self) -> Optional[bool]: return self._property_include_subprojects @include_subprojects.setter def include_subprojects(self, value: Optional[bool]) -> None: if value is None: self._property_include_subprojects = None return self.assert_isinstance(value, "include_subprojects", (bool,)) self._property_include_subprojects = value
GetHyperParametersRequest
python
anthropics__anthropic-sdk-python
src/anthropic/types/text_block_param.py
{ "start": 374, "end": 659 }
class ____(TypedDict, total=False): text: Required[str] type: Required[Literal["text"]] cache_control: Optional[CacheControlEphemeralParam] """Create a cache control breakpoint at this content block.""" citations: Optional[Iterable[TextCitationParam]]
TextBlockParam
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 941466, "end": 942214 }
class ____(sgqlc.types.relay.Connection): """The connection type for RepositoryRule.""" __schema__ = github_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field(sgqlc.types.list_of("RepositoryRuleEdge"), graphql_name="edges") """A list of edges.""" nodes = sgqlc.types.Field(sgqlc.types.list_of("RepositoryRule"), graphql_name="nodes") """A list of nodes.""" page_info = sgqlc.types.Field(sgqlc.types.non_null(PageInfo), graphql_name="pageInfo") """Information to aid in pagination.""" total_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="totalCount") """Identifies the total count of items in the connection."""
RepositoryRuleConnection
python
streamlit__streamlit
lib/tests/streamlit/elements/divider_test.py
{ "start": 919, "end": 2345 }
class ____(DeltaGeneratorTestCase): """Test ability to marshall divider protos.""" def test_divider(self): st.divider() c = self.get_delta_from_queue().new_element assert c.markdown.body == "---" @parameterized.expand( [ (500, WidthConfigFields.PIXEL_WIDTH, 500), ("stretch", WidthConfigFields.USE_STRETCH, True), (None, WidthConfigFields.USE_STRETCH, True), ] ) def test_divider_width(self, width_value, expected_field, expected_value): """Test divider width configurations.""" if width_value is None: st.divider() else: st.divider(width=width_value) c = self.get_delta_from_queue().new_element assert c.markdown.body == "---" assert c.width_config.WhichOneof("width_spec") == expected_field.value if expected_field == WidthConfigFields.PIXEL_WIDTH: assert c.width_config.pixel_width == expected_value else: assert c.width_config.use_stretch @parameterized.expand( [ "invalid", -100, 0, 100.5, None, ] ) def test_divider_invalid_width(self, width_value): """Test that invalid width values raise an exception.""" with pytest.raises(StreamlitInvalidWidthError): st.divider(width=width_value)
DividerTest
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 12263, "end": 12365 }
class ____(models.Model): books = models.ForeignKey(HardbackBook, on_delete=models.CASCADE)
Bookcase
python
pytorch__pytorch
torch/package/package_exporter.py
{ "start": 1186, "end": 1955 }
class ____(Enum): """Represents one of the actions that :class:`PackageExporter` can take on a module. See :meth:`PackageExporter.extern` and friends for a description of what the actions do. """ INTERN = 1 EXTERN = 2 MOCK = 3 DENY = 4 # Special case: when a module is mocked, PackageExporter writes out a # `_mock` module that implements our mocking stubs. If we re-package code, # we may encounter a `_mock` module from the original package. If we do, # just ignore it and write a `_mock` module once. REPACKAGED_MOCK_MODULE = 5 # Special case: PackageImporter adds a fake module # (`torch_package_importer`) that allows packaged code to access it. Don't # re-export this. SKIP = 6
_ModuleProviderAction
python
huggingface__transformers
src/transformers/models/falcon/modeling_falcon.py
{ "start": 55933, "end": 59639 }
class ____(FalconPreTrainedModel): def __init__(self, config: FalconConfig): super().__init__(config) self.num_labels = config.num_labels self.transformer = FalconModel(config) if getattr(config, "classifier_dropout", None) is not None: classifier_dropout = config.classifier_dropout elif getattr(config, "hidden_dropout", None) is not None: classifier_dropout = config.hidden_dropout else: classifier_dropout = 0.1 self.dropout = nn.Dropout(classifier_dropout) self.classifier = nn.Linear(config.hidden_size, config.num_labels) # Initialize weights and apply final processing self.post_init() @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, attention_mask: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[tuple[torch.Tensor], TokenClassifierOutput]: r""" input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`): `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()` (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary. If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as `input_ids`. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict transformer_outputs = self.transformer( input_ids, past_key_values=past_key_values, attention_mask=attention_mask, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) hidden_states = transformer_outputs[0] hidden_states = self.dropout(hidden_states) logits = self.classifier(hidden_states) loss = None if labels is not None: batch_size, seq_length = labels.shape loss_fct = CrossEntropyLoss() loss = loss_fct( logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length) ) if not return_dict: output = (logits,) + transformer_outputs[2:] return ((loss,) + output) if loss is not None else output return TokenClassifierOutput( loss=loss, logits=logits, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, ) @auto_docstring
FalconForTokenClassification
python
getsentry__sentry
tests/sentry/users/api/endpoints/test_userroles_index.py
{ "start": 170, "end": 1168 }
class ____(APITestCase): endpoint = "sentry-api-0-userroles" def setUp(self) -> None: super().setUp() self.user = self.create_user(is_superuser=True) self.login_as(user=self.user, superuser=True) self.add_user_permission(self.user, "users.admin") def test_fails_without_superuser(self) -> None: self.user = self.create_user(is_superuser=False) self.login_as(self.user) UserRole.objects.create(name="test-role") resp = self.get_response(name="test-role") assert resp.status_code == 403 self.user.update(is_superuser=True) resp = self.get_response(name="test-role") assert resp.status_code == 403 def test_fails_without_users_admin_permission(self) -> None: self.user = self.create_user(is_superuser=True) self.login_as(self.user, superuser=True) resp = self.get_response(name="test-role") assert resp.status_code == 403 @control_silo_test
UserRolesTest
python
langchain-ai__langchain
libs/partners/anthropic/langchain_anthropic/chat_models.py
{ "start": 102564, "end": 112444 }
class ____(TypedDict): type: Literal["tool_use"] name: str input: dict id: str def _lc_tool_calls_to_anthropic_tool_use_blocks( tool_calls: list[ToolCall], ) -> list[_AnthropicToolUse]: return [ _AnthropicToolUse( type="tool_use", name=tool_call["name"], input=tool_call["args"], id=cast("str", tool_call["id"]), ) for tool_call in tool_calls ] def _convert_to_anthropic_output_format(schema: dict | type) -> dict[str, Any]: """Convert JSON schema, Pydantic model, or `TypedDict` into Claude `output_format`. See Claude docs on [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs). """ from anthropic import transform_schema is_pydantic_class = isinstance(schema, type) and is_basemodel_subclass(schema) if is_pydantic_class or isinstance(schema, dict): json_schema = transform_schema(schema) else: # TypedDict json_schema = transform_schema(convert_to_json_schema(schema)) return {"type": "json_schema", "schema": json_schema} def _make_message_chunk_from_anthropic_event( event: anthropic.types.RawMessageStreamEvent, *, stream_usage: bool = True, coerce_content_to_string: bool, block_start_event: anthropic.types.RawMessageStreamEvent | None = None, ) -> tuple[AIMessageChunk | None, anthropic.types.RawMessageStreamEvent | None]: """Convert Anthropic streaming event to `AIMessageChunk`. Args: event: Raw streaming event from Anthropic SDK stream_usage: Whether to include usage metadata in the output chunks. coerce_content_to_string: Whether to convert structured content to plain text strings. When `True`, only text content is preserved; when `False`, structured content like tool calls and citations are maintained. block_start_event: Previous content block start event, used for tracking tool use blocks and maintaining context across related events. Returns: Tuple with - `AIMessageChunk`: Converted message chunk with appropriate content and metadata, or `None` if the event doesn't produce a chunk - `RawMessageStreamEvent`: Updated `block_start_event` for tracking content blocks across sequential events, or `None` if not applicable Note: Not all Anthropic events result in message chunks. Events like internal state changes return `None` for the message chunk while potentially updating the `block_start_event` for context tracking. """ message_chunk: AIMessageChunk | None = None # Reference: Anthropic SDK streaming implementation # https://github.com/anthropics/anthropic-sdk-python/blob/main/src/anthropic/lib/streaming/_messages.py # noqa: E501 if event.type == "message_start" and stream_usage: # Capture model name, but don't include usage_metadata yet # as it will be properly reported in message_delta with complete info if hasattr(event.message, "model"): response_metadata: dict[str, Any] = {"model_name": event.message.model} else: response_metadata = {} message_chunk = AIMessageChunk( content="" if coerce_content_to_string else [], response_metadata=response_metadata, ) elif ( event.type == "content_block_start" and event.content_block is not None and ( "tool_result" in event.content_block.type or "tool_use" in event.content_block.type or "document" in event.content_block.type or "redacted_thinking" in event.content_block.type ) ): if coerce_content_to_string: warnings.warn("Received unexpected tool content block.", stacklevel=2) content_block = event.content_block.model_dump() content_block["index"] = event.index if event.content_block.type == "tool_use": tool_call_chunk = create_tool_call_chunk( index=event.index, id=event.content_block.id, name=event.content_block.name, args="", ) tool_call_chunks = [tool_call_chunk] else: tool_call_chunks = [] message_chunk = AIMessageChunk( content=[content_block], tool_call_chunks=tool_call_chunks, ) block_start_event = event # Process incremental content updates elif event.type == "content_block_delta": # Text and citation deltas (incremental text content) if event.delta.type in ("text_delta", "citations_delta"): if coerce_content_to_string and hasattr(event.delta, "text"): text = getattr(event.delta, "text", "") message_chunk = AIMessageChunk(content=text) else: content_block = event.delta.model_dump() content_block["index"] = event.index # All citation deltas are part of a text block content_block["type"] = "text" if "citation" in content_block: # Assign citations to a list if present content_block["citations"] = [content_block.pop("citation")] message_chunk = AIMessageChunk(content=[content_block]) # Reasoning elif event.delta.type in {"thinking_delta", "signature_delta"}: content_block = event.delta.model_dump() content_block["index"] = event.index content_block["type"] = "thinking" message_chunk = AIMessageChunk(content=[content_block]) # Tool input JSON (streaming tool arguments) elif event.delta.type == "input_json_delta": content_block = event.delta.model_dump() content_block["index"] = event.index start_event_block = ( getattr(block_start_event, "content_block", None) if block_start_event else None ) if ( start_event_block is not None and getattr(start_event_block, "type", None) == "tool_use" ): tool_call_chunk = create_tool_call_chunk( index=event.index, id=None, name=None, args=event.delta.partial_json, ) tool_call_chunks = [tool_call_chunk] else: tool_call_chunks = [] message_chunk = AIMessageChunk( content=[content_block], tool_call_chunks=tool_call_chunks, ) # Process final usage metadata and completion info elif event.type == "message_delta" and stream_usage: usage_metadata = _create_usage_metadata(event.usage) response_metadata = { "stop_reason": event.delta.stop_reason, "stop_sequence": event.delta.stop_sequence, } if context_management := getattr(event, "context_management", None): response_metadata["context_management"] = context_management.model_dump() message_chunk = AIMessageChunk( content="" if coerce_content_to_string else [], usage_metadata=usage_metadata, response_metadata=response_metadata, ) if message_chunk.response_metadata.get("stop_reason"): # Mark final Anthropic stream chunk message_chunk.chunk_position = "last" # Unhandled event types (e.g., `content_block_stop`, `ping` events) # https://platform.claude.com/docs/en/build-with-claude/streaming#other-events else: pass if message_chunk: message_chunk.response_metadata["model_provider"] = "anthropic" return message_chunk, block_start_event def _create_usage_metadata(anthropic_usage: BaseModel) -> UsageMetadata: """Create LangChain `UsageMetadata` from Anthropic `Usage` data. Note: Anthropic's `input_tokens` excludes cached tokens, so we manually add `cache_read` and `cache_creation` tokens to get the true total. """ input_token_details: dict = { "cache_read": getattr(anthropic_usage, "cache_read_input_tokens", None), "cache_creation": getattr(anthropic_usage, "cache_creation_input_tokens", None), } # Add cache TTL information if provided (5-minute and 1-hour ephemeral cache) cache_creation = getattr(anthropic_usage, "cache_creation", None) # Currently just copying over the 5m and 1h keys, but if more are added in the # future we'll need to expand this tuple cache_creation_keys = ("ephemeral_5m_input_tokens", "ephemeral_1h_input_tokens") if cache_creation: if isinstance(cache_creation, BaseModel): cache_creation = cache_creation.model_dump() for k in cache_creation_keys: input_token_details[k] = cache_creation.get(k) # Calculate total input tokens: Anthropic's `input_tokens` excludes cached tokens, # so we need to add them back to get the true total input token count input_tokens = ( (getattr(anthropic_usage, "input_tokens", 0) or 0) # Base input tokens + (input_token_details["cache_read"] or 0) # Tokens read from cache + (input_token_details["cache_creation"] or 0) # Tokens used to create cache ) output_tokens = getattr(anthropic_usage, "output_tokens", 0) or 0 return UsageMetadata( input_tokens=input_tokens, output_tokens=output_tokens, total_tokens=input_tokens + output_tokens, input_token_details=InputTokenDetails( **{k: v for k, v in input_token_details.items() if v is not None}, ), )
_AnthropicToolUse
python
tensorflow__tensorflow
tensorflow/python/ops/control_flow_v2_func_graphs.py
{ "start": 1963, "end": 2131 }
class ____(ControlFlowFuncGraph): """FuncGraph for the body of tf.while_loop(). This is used to distinguish while bodies from other functions. """
WhileBodyFuncGraph
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_set.py
{ "start": 665, "end": 1731 }
class ____(importlib.abc.MetaPathFinder): def find_spec(self, fullname, path, target=None): # Check if the import is the problematic one if fullname in redirect_imports: try: # Attempt to import the standalone module name = fullname.removeprefix("test.") r = importlib.import_module(name) # Redirect the module in sys.modules sys.modules[fullname] = r # Return a module spec from the found module return importlib.util.find_spec(name) except ImportError: return None return None # Add the custom finder to sys.meta_path sys.meta_path.insert(0, RedirectImportFinder()) # ======= END DYNAMO PATCH ======= import unittest from test import support from test.support import warnings_helper import gc import weakref import operator import copy import pickle from random import randrange, shuffle import warnings import collections import collections.abc import itertools
RedirectImportFinder
python
run-llama__llama_index
llama-index-core/llama_index/core/objects/tool_node_mapping.py
{ "start": 3873, "end": 5046 }
class ____(BaseQueryToolNodeMapping): """Simple query tool mapping.""" def __init__(self, objs: Optional[Sequence[QueryEngineTool]] = None) -> None: objs = objs or [] self._tools = {tool.metadata.name: tool for tool in objs} def validate_object(self, obj: QueryEngineTool) -> None: if not isinstance(obj, QueryEngineTool): raise ValueError(f"Object must be of type {QueryEngineTool}") @classmethod def from_objects( cls, objs: Sequence[QueryEngineTool], *args: Any, **kwargs: Any ) -> "BaseObjectNodeMapping": return cls(objs) def _add_object(self, tool: QueryEngineTool) -> None: if tool.metadata.name is None: raise ValueError("Tool name must be set") self._tools[tool.metadata.name] = tool def to_node(self, obj: QueryEngineTool) -> TextNode: """To node.""" return convert_tool_to_node(obj) def _from_node(self, node: BaseNode) -> QueryEngineTool: """From node.""" if node.metadata is None: raise ValueError("Metadata must be set") return self._tools[node.metadata["name"]]
SimpleQueryToolNodeMapping
python
apache__airflow
devel-common/src/tests_common/test_utils/mock_executor.py
{ "start": 1345, "end": 5307 }
class ____(BaseExecutor): """TestExecutor is used for unit testing purposes.""" supports_pickling = False mock_module_path = "mock.executor.path" mock_alias = "mock_executor" def __init__(self, do_update=True, *args, **kwargs): self.do_update = do_update self.callback_sink = MagicMock() # A list of "batches" of tasks self.history = [] # All the tasks, in a stable sort order self.sorted_tasks = [] self.name = ExecutorName(module_path=self.mock_module_path, alias=self.mock_alias) # If multiprocessing runs in spawn mode, # arguments are to be pickled but lambda is not picclable. # So we should pass self.success instead of lambda. self.mock_task_results = defaultdict(self.success) # Mock JWT generator for token generation mock_jwt_generator = MagicMock() mock_jwt_generator.generate.return_value = "mock-token" self.jwt_generator = mock_jwt_generator super().__init__(*args, **kwargs) def success(self): return State.SUCCESS def _process_workloads(self, workload_list: Sequence[workloads.All]) -> None: """Process the given workloads - mock implementation.""" # For mock executor, we don't actually process the workloads, # they get processed in heartbeat() pass def heartbeat(self): if not self.do_update: return with create_session() as session: self.history.append(list(self.queued_tasks.values())) # Create a stable/predictable sort order for events in self.history # for tests! def sort_by(item): key, workload = item (dag_id, task_id, date, try_number, map_index) = key # For workloads, use the task instance priority if available prio = getattr(workload.ti, "priority_weight", 1) if hasattr(workload, "ti") else 1 # Sort by priority (DESC), then date,task, try return -prio, date, dag_id, task_id, map_index, try_number open_slots = self.parallelism - len(self.running) sorted_queue = sorted(self.queued_tasks.items(), key=sort_by) for key, workload in sorted_queue[:open_slots]: self.queued_tasks.pop(key) state = self.mock_task_results[key] ti = TaskInstance.get_task_instance( task_id=workload.ti.task_id, run_id=workload.ti.run_id, dag_id=workload.ti.dag_id, map_index=workload.ti.map_index, lock_for_update=True, ) ti.set_state(state, session=session) self.change_state(key, state) session.flush() def terminate(self): pass def end(self): self.sync() def change_state(self, key, state, info=None, remove_running=False): super().change_state(key, state, info=info, remove_running=remove_running) # The normal event buffer is cleared after reading, we want to keep # a list of all events for testing self.sorted_tasks.append((key, (state, info))) def mock_task_fail(self, dag_id, task_id, run_id: str, try_number=1): """ Mock for test failures. Set the mock outcome of running this particular task instances to FAILED. If the task identified by the tuple ``(dag_id, task_id, date, try_number)`` is run by this executor its state will be FAILED. """ assert isinstance(run_id, str) self.mock_task_results[TaskInstanceKey(dag_id, task_id, run_id, try_number)] = State.FAILED def get_mock_loader_side_effect(self): return lambda *x: { (None,): self, (self.mock_module_path,): self, (self.mock_alias,): self, }[x]
MockExecutor
python
scrapy__scrapy
tests/test_pipeline_files.py
{ "start": 26337, "end": 27990 }
class ____: def setup_method(self): self.tempdir = mkdtemp() self.crawler = get_crawler(None, {"FILES_STORE": self.tempdir}) def teardown_method(self): rmtree(self.tempdir) def test_simple(self): class Pipeline(FilesPipeline): pass with warnings.catch_warnings(record=True) as w: pipe = Pipeline.from_crawler(self.crawler) assert pipe.crawler == self.crawler assert pipe._fingerprinter assert len(w) == 0 assert pipe.store def test_has_from_crawler_and_init(self): class Pipeline(FilesPipeline): _from_crawler_called = False @classmethod def from_crawler(cls, crawler): settings = crawler.settings store_uri = settings["FILES_STORE"] o = cls(store_uri, crawler=crawler) o._from_crawler_called = True return o with warnings.catch_warnings(record=True) as w: pipe = Pipeline.from_crawler(self.crawler) assert pipe.crawler == self.crawler assert pipe._fingerprinter assert len(w) == 0 assert pipe.store assert pipe._from_crawler_called @pytest.mark.parametrize("store", [None, ""]) def test_files_pipeline_raises_notconfigured_when_files_store_invalid(store): settings = Settings() settings.clear() settings.set("FILES_STORE", store, priority="cmdline") crawler = get_crawler(settings_dict=settings) with pytest.raises(NotConfigured): FilesPipeline.from_crawler(crawler)
TestBuildFromCrawler
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/functions.py
{ "start": 65765, "end": 66171 }
class ____(GenericFunction[_T]): r"""Implement the ``CUBE`` grouping operation. This function is used as part of the GROUP BY of a statement, e.g. :meth:`_expression.Select.group_by`:: stmt = select( func.sum(table.c.value), table.c.col_1, table.c.col_2 ).group_by(func.cube(table.c.col_1, table.c.col_2)) """ _has_args = True inherit_cache = True
cube
python
getsentry__sentry
tests/sentry/web/frontend/test_error_500.py
{ "start": 142, "end": 357 }
class ____(TestCase): def test_renders(self) -> None: resp = self.client.get(reverse("error-500")) assert resp.status_code == 500 self.assertTemplateUsed(resp, "sentry/500.html")
Error500Test
python
pytorch__pytorch
torch/utils/data/sampler.py
{ "start": 3752, "end": 4234 }
class ____(Sampler[int]): r"""Samples elements sequentially, always in the same order. Args: data_source (Sized): data source to sample from. Must implement __len__. """ data_source: Sized def __init__(self, data_source: Sized) -> None: self.data_source = data_source def __iter__(self) -> Iterator[int]: return iter(range(len(self.data_source))) def __len__(self) -> int: return len(self.data_source)
SequentialSampler
python
kamyu104__LeetCode-Solutions
Python/find-if-array-can-be-sorted.py
{ "start": 36, "end": 671 }
class ____(object): def canSortArray(self, nums): """ :type nums: List[int] :rtype: bool """ def popcount(x): return bin(x).count("1") left = mx = 0 for right in xrange(len(nums)): if right+1 != len(nums) and popcount(nums[right+1]) == popcount(nums[right]): continue if mx > min(nums[i] for i in xrange(left, right+1)): return False mx = max(nums[i] for i in xrange(left, right+1)) left = right+1 return True # Time: O(n) # Space: O(n) import itertools # sort
Solution