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
more-itertools__more-itertools
more_itertools/more.py
{ "start": 68093, "end": 80238 }
class ____(Sequence): """An extension of the built-in ``range()`` function whose arguments can be any orderable numeric type. With only *stop* specified, *start* defaults to ``0`` and *step* defaults to ``1``. The output items will match the type of *stop*: >>> list(numeric_range(3.5)) [0.0, 1.0, 2.0, 3.0] With only *start* and *stop* specified, *step* defaults to ``1``. The output items will match the type of *start*: >>> from decimal import Decimal >>> start = Decimal('2.1') >>> stop = Decimal('5.1') >>> list(numeric_range(start, stop)) [Decimal('2.1'), Decimal('3.1'), Decimal('4.1')] With *start*, *stop*, and *step* specified the output items will match the type of ``start + step``: >>> from fractions import Fraction >>> start = Fraction(1, 2) # Start at 1/2 >>> stop = Fraction(5, 2) # End at 5/2 >>> step = Fraction(1, 2) # Count by 1/2 >>> list(numeric_range(start, stop, step)) [Fraction(1, 2), Fraction(1, 1), Fraction(3, 2), Fraction(2, 1)] If *step* is zero, ``ValueError`` is raised. Negative steps are supported: >>> list(numeric_range(3, -1, -1.0)) [3.0, 2.0, 1.0, 0.0] Be aware of the limitations of floating-point numbers; the representation of the yielded numbers may be surprising. ``datetime.datetime`` objects can be used for *start* and *stop*, if *step* is a ``datetime.timedelta`` object: >>> import datetime >>> start = datetime.datetime(2019, 1, 1) >>> stop = datetime.datetime(2019, 1, 3) >>> step = datetime.timedelta(days=1) >>> items = iter(numeric_range(start, stop, step)) >>> next(items) datetime.datetime(2019, 1, 1, 0, 0) >>> next(items) datetime.datetime(2019, 1, 2, 0, 0) """ _EMPTY_HASH = hash(range(0, 0)) def __init__(self, *args): argc = len(args) if argc == 1: (self._stop,) = args self._start = type(self._stop)(0) self._step = type(self._stop - self._start)(1) elif argc == 2: self._start, self._stop = args self._step = type(self._stop - self._start)(1) elif argc == 3: self._start, self._stop, self._step = args elif argc == 0: raise TypeError( f'numeric_range expected at least 1 argument, got {argc}' ) else: raise TypeError( f'numeric_range expected at most 3 arguments, got {argc}' ) self._zero = type(self._step)(0) if self._step == self._zero: raise ValueError('numeric_range() arg 3 must not be zero') self._growing = self._step > self._zero def __bool__(self): if self._growing: return self._start < self._stop else: return self._start > self._stop def __contains__(self, elem): if self._growing: if self._start <= elem < self._stop: return (elem - self._start) % self._step == self._zero else: if self._start >= elem > self._stop: return (self._start - elem) % (-self._step) == self._zero return False def __eq__(self, other): if isinstance(other, numeric_range): empty_self = not bool(self) empty_other = not bool(other) if empty_self or empty_other: return empty_self and empty_other # True if both empty else: return ( self._start == other._start and self._step == other._step and self._get_by_index(-1) == other._get_by_index(-1) ) else: return False def __getitem__(self, key): if isinstance(key, int): return self._get_by_index(key) elif isinstance(key, slice): step = self._step if key.step is None else key.step * self._step if key.start is None or key.start <= -self._len: start = self._start elif key.start >= self._len: start = self._stop else: # -self._len < key.start < self._len start = self._get_by_index(key.start) if key.stop is None or key.stop >= self._len: stop = self._stop elif key.stop <= -self._len: stop = self._start else: # -self._len < key.stop < self._len stop = self._get_by_index(key.stop) return numeric_range(start, stop, step) else: raise TypeError( 'numeric range indices must be ' f'integers or slices, not {type(key).__name__}' ) def __hash__(self): if self: return hash((self._start, self._get_by_index(-1), self._step)) else: return self._EMPTY_HASH def __iter__(self): values = (self._start + (n * self._step) for n in count()) if self._growing: return takewhile(partial(gt, self._stop), values) else: return takewhile(partial(lt, self._stop), values) def __len__(self): return self._len @cached_property def _len(self): if self._growing: start = self._start stop = self._stop step = self._step else: start = self._stop stop = self._start step = -self._step distance = stop - start if distance <= self._zero: return 0 else: # distance > 0 and step > 0: regular euclidean division q, r = divmod(distance, step) return int(q) + int(r != self._zero) def __reduce__(self): return numeric_range, (self._start, self._stop, self._step) def __repr__(self): if self._step == 1: return f"numeric_range({self._start!r}, {self._stop!r})" return ( f"numeric_range({self._start!r}, {self._stop!r}, {self._step!r})" ) def __reversed__(self): return iter( numeric_range( self._get_by_index(-1), self._start - self._step, -self._step ) ) def count(self, value): return int(value in self) def index(self, value): if self._growing: if self._start <= value < self._stop: q, r = divmod(value - self._start, self._step) if r == self._zero: return int(q) else: if self._start >= value > self._stop: q, r = divmod(self._start - value, -self._step) if r == self._zero: return int(q) raise ValueError(f"{value} is not in numeric range") def _get_by_index(self, i): if i < 0: i += self._len if i < 0 or i >= self._len: raise IndexError("numeric range object index out of range") return self._start + i * self._step def count_cycle(iterable, n=None): """Cycle through the items from *iterable* up to *n* times, yielding the number of completed cycles along with each item. If *n* is omitted the process repeats indefinitely. >>> list(count_cycle('AB', 3)) [(0, 'A'), (0, 'B'), (1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')] """ if n is not None: return product(range(n), iterable) seq = tuple(iterable) if not seq: return iter(()) counter = count() if n is None else range(n) return zip(repeat_each(counter, len(seq)), cycle(seq)) def mark_ends(iterable): """Yield 3-tuples of the form ``(is_first, is_last, item)``. >>> list(mark_ends('ABC')) [(True, False, 'A'), (False, False, 'B'), (False, True, 'C')] Use this when looping over an iterable to take special action on its first and/or last items: >>> iterable = ['Header', 100, 200, 'Footer'] >>> total = 0 >>> for is_first, is_last, item in mark_ends(iterable): ... if is_first: ... continue # Skip the header ... if is_last: ... continue # Skip the footer ... total += item >>> print(total) 300 """ it = iter(iterable) for a in it: first = True for b in it: yield first, False, a a = b first = False yield first, True, a def locate(iterable, pred=bool, window_size=None): """Yield the index of each item in *iterable* for which *pred* returns ``True``. *pred* defaults to :func:`bool`, which will select truthy items: >>> list(locate([0, 1, 1, 0, 1, 0, 0])) [1, 2, 4] Set *pred* to a custom function to, e.g., find the indexes for a particular item. >>> list(locate(['a', 'b', 'c', 'b'], lambda x: x == 'b')) [1, 3] If *window_size* is given, then the *pred* function will be called with that many items. This enables searching for sub-sequences: >>> iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3] >>> pred = lambda *args: args == (1, 2, 3) >>> list(locate(iterable, pred=pred, window_size=3)) [1, 5, 9] Use with :func:`seekable` to find indexes and then retrieve the associated items: >>> from itertools import count >>> from more_itertools import seekable >>> source = (3 * n + 1 if (n % 2) else n // 2 for n in count()) >>> it = seekable(source) >>> pred = lambda x: x > 100 >>> indexes = locate(it, pred=pred) >>> i = next(indexes) >>> it.seek(i) >>> next(it) 106 """ if window_size is None: return compress(count(), map(pred, iterable)) if window_size < 1: raise ValueError('window size must be at least 1') it = windowed(iterable, window_size, fillvalue=_marker) return compress(count(), starmap(pred, it)) def longest_common_prefix(iterables): """Yield elements of the longest common prefix among given *iterables*. >>> ''.join(longest_common_prefix(['abcd', 'abc', 'abf'])) 'ab' """ return (c[0] for c in takewhile(all_equal, zip(*iterables))) def lstrip(iterable, pred): """Yield the items from *iterable*, but strip any from the beginning for which *pred* returns ``True``. For example, to remove a set of items from the start of an iterable: >>> iterable = (None, False, None, 1, 2, None, 3, False, None) >>> pred = lambda x: x in {None, False, ''} >>> list(lstrip(iterable, pred)) [1, 2, None, 3, False, None] This function is analogous to to :func:`str.lstrip`, and is essentially an wrapper for :func:`itertools.dropwhile`. """ return dropwhile(pred, iterable) def rstrip(iterable, pred): """Yield the items from *iterable*, but strip any from the end for which *pred* returns ``True``. For example, to remove a set of items from the end of an iterable: >>> iterable = (None, False, None, 1, 2, None, 3, False, None) >>> pred = lambda x: x in {None, False, ''} >>> list(rstrip(iterable, pred)) [None, False, None, 1, 2, None, 3] This function is analogous to :func:`str.rstrip`. """ cache = [] cache_append = cache.append cache_clear = cache.clear for x in iterable: if pred(x): cache_append(x) else: yield from cache cache_clear() yield x def strip(iterable, pred): """Yield the items from *iterable*, but strip any from the beginning and end for which *pred* returns ``True``. For example, to remove a set of items from both ends of an iterable: >>> iterable = (None, False, None, 1, 2, None, 3, False, None) >>> pred = lambda x: x in {None, False, ''} >>> list(strip(iterable, pred)) [1, 2, None, 3] This function is analogous to :func:`str.strip`. """ return rstrip(lstrip(iterable, pred), pred)
numeric_range
python
psf__black
src/black/comments.py
{ "start": 1018, "end": 27409 }
class ____: """Describes a piece of syntax that is a comment. It's not a :class:`blib2to3.pytree.Leaf` so that: * it can be cached (`Leaf` objects should not be reused more than once as they store their lineno, column, prefix, and parent information); * `newlines` and `consumed` fields are kept separate from the `value`. This simplifies handling of special marker comments like ``# fmt: off/on``. """ type: int # token.COMMENT or STANDALONE_COMMENT value: str # content of the comment newlines: int # how many newlines before the comment consumed: int # how many characters of the original leaf's prefix did we consume form_feed: bool # is there a form feed before the comment leading_whitespace: str # leading whitespace before the comment, if any def generate_comments(leaf: LN, mode: Mode) -> Iterator[Leaf]: """Clean the prefix of the `leaf` and generate comments from it, if any. Comments in lib2to3 are shoved into the whitespace prefix. This happens in `pgen2/driver.py:Driver.parse_tokens()`. This was a brilliant implementation move because it does away with modifying the grammar to include all the possible places in which comments can be placed. The sad consequence for us though is that comments don't "belong" anywhere. This is why this function generates simple parentless Leaf objects for comments. We simply don't know what the correct parent should be. No matter though, we can live without this. We really only need to differentiate between inline and standalone comments. The latter don't share the line with any code. Inline comments are emitted as regular token.COMMENT leaves. Standalone are emitted with a fake STANDALONE_COMMENT token identifier. """ total_consumed = 0 for pc in list_comments( leaf.prefix, is_endmarker=leaf.type == token.ENDMARKER, mode=mode ): total_consumed = pc.consumed prefix = make_simple_prefix(pc.newlines, pc.form_feed) yield Leaf(pc.type, pc.value, prefix=prefix) normalize_trailing_prefix(leaf, total_consumed) @lru_cache(maxsize=4096) def list_comments(prefix: str, *, is_endmarker: bool, mode: Mode) -> list[ProtoComment]: """Return a list of :class:`ProtoComment` objects parsed from the given `prefix`.""" result: list[ProtoComment] = [] if not prefix or "#" not in prefix: return result consumed = 0 nlines = 0 ignored_lines = 0 form_feed = False for index, full_line in enumerate(re.split("\r?\n|\r", prefix)): consumed += len(full_line) + 1 # adding the length of the split '\n' match = re.match(r"^(\s*)(\S.*|)$", full_line) assert match whitespace, line = match.groups() if not line: nlines += 1 if "\f" in full_line: form_feed = True if not line.startswith("#"): # Escaped newlines outside of a comment are not really newlines at # all. We treat a single-line comment following an escaped newline # as a simple trailing comment. if line.endswith("\\"): ignored_lines += 1 continue if index == ignored_lines and not is_endmarker: comment_type = token.COMMENT # simple trailing comment else: comment_type = STANDALONE_COMMENT comment = make_comment(line, mode=mode) result.append( ProtoComment( type=comment_type, value=comment, newlines=nlines, consumed=consumed, form_feed=form_feed, leading_whitespace=whitespace, ) ) form_feed = False nlines = 0 return result def normalize_trailing_prefix(leaf: LN, total_consumed: int) -> None: """Normalize the prefix that's left over after generating comments. Note: don't use backslashes for formatting or you'll lose your voting rights. """ remainder = leaf.prefix[total_consumed:] if "\\" not in remainder: nl_count = remainder.count("\n") form_feed = "\f" in remainder and remainder.endswith("\n") leaf.prefix = make_simple_prefix(nl_count, form_feed) return leaf.prefix = "" def make_comment(content: str, mode: Mode) -> str: """Return a consistently formatted comment from the given `content` string. All comments (except for "##", "#!", "#:", '#'") should have a single space between the hash sign and the content. If `content` didn't start with a hash sign, one is provided. Comments containing fmt directives are preserved exactly as-is to respect user intent (e.g., `#no space # fmt: skip` stays as-is). """ content = content.rstrip() if not content: return "#" # Preserve comments with fmt directives exactly as-is if content.startswith("#") and _contains_fmt_directive(content): return content if content[0] == "#": content = content[1:] if ( content and content[0] == "\N{NO-BREAK SPACE}" and not is_type_comment_string("# " + content.lstrip(), mode=mode) ): content = " " + content[1:] # Replace NBSP by a simple space if ( Preview.standardize_type_comments in mode and content and "\N{NO-BREAK SPACE}" not in content and is_type_comment_string("#" + content, mode=mode) ): type_part, value_part = content.split(":", 1) content = type_part.strip() + ": " + value_part.strip() if content and content[0] not in COMMENT_EXCEPTIONS: content = " " + content return "#" + content def normalize_fmt_off( node: Node, mode: Mode, lines: Collection[tuple[int, int]] ) -> None: """Convert content between `# fmt: off`/`# fmt: on` into standalone comments.""" try_again = True while try_again: try_again = convert_one_fmt_off_pair(node, mode, lines) def _should_process_fmt_comment( comment: ProtoComment, leaf: Leaf ) -> tuple[bool, bool, bool]: """Check if comment should be processed for fmt handling. Returns (should_process, is_fmt_off, is_fmt_skip). """ is_fmt_off = _contains_fmt_directive(comment.value, FMT_OFF) is_fmt_skip = _contains_fmt_directive(comment.value, FMT_SKIP) if not is_fmt_off and not is_fmt_skip: return False, False, False # Invalid use when `# fmt: off` is applied before a closing bracket if is_fmt_off and leaf.type in CLOSING_BRACKETS: return False, False, False return True, is_fmt_off, is_fmt_skip def _is_valid_standalone_fmt_comment( comment: ProtoComment, leaf: Leaf, is_fmt_off: bool, is_fmt_skip: bool ) -> bool: """Check if comment is a valid standalone fmt directive. We only want standalone comments. If there's no previous leaf or if the previous leaf is indentation, it's a standalone comment in disguise. """ if comment.type == STANDALONE_COMMENT: return True prev = preceding_leaf(leaf) if not prev: return True # Treat STANDALONE_COMMENT nodes as whitespace for check if is_fmt_off and prev.type not in WHITESPACE and prev.type != STANDALONE_COMMENT: return False if is_fmt_skip and prev.type in WHITESPACE: return False return True def _handle_comment_only_fmt_block( leaf: Leaf, comment: ProtoComment, previous_consumed: int, mode: Mode, ) -> bool: """Handle fmt:off/on blocks that contain only comments. Returns True if a block was converted, False otherwise. """ all_comments = list_comments(leaf.prefix, is_endmarker=False, mode=mode) # Find the first fmt:off and its matching fmt:on fmt_off_idx = None fmt_on_idx = None for idx, c in enumerate(all_comments): if fmt_off_idx is None and c.value in FMT_OFF: fmt_off_idx = idx if fmt_off_idx is not None and idx > fmt_off_idx and c.value in FMT_ON: fmt_on_idx = idx break # Only proceed if we found both directives if fmt_on_idx is None or fmt_off_idx is None: return False comment = all_comments[fmt_off_idx] fmt_on_comment = all_comments[fmt_on_idx] original_prefix = leaf.prefix # Build the hidden value start_pos = comment.consumed end_pos = fmt_on_comment.consumed content_between_and_fmt_on = original_prefix[start_pos:end_pos] hidden_value = comment.value + "\n" + content_between_and_fmt_on if hidden_value.endswith("\n"): hidden_value = hidden_value[:-1] # Build the standalone comment prefix - preserve all content before fmt:off # including any comments that precede it if fmt_off_idx == 0: # No comments before fmt:off, use previous_consumed pre_fmt_off_consumed = previous_consumed else: # Use the consumed position of the last comment before fmt:off # This preserves all comments and content before the fmt:off directive pre_fmt_off_consumed = all_comments[fmt_off_idx - 1].consumed standalone_comment_prefix = ( original_prefix[:pre_fmt_off_consumed] + "\n" * comment.newlines ) fmt_off_prefix = original_prefix.split(comment.value)[0] if "\n" in fmt_off_prefix: fmt_off_prefix = fmt_off_prefix.split("\n")[-1] standalone_comment_prefix += fmt_off_prefix # Update leaf prefix leaf.prefix = original_prefix[fmt_on_comment.consumed :] # Insert the STANDALONE_COMMENT parent = leaf.parent assert parent is not None, "INTERNAL ERROR: fmt: on/off handling (prefix only)" leaf_idx = None for idx, child in enumerate(parent.children): if child is leaf: leaf_idx = idx break assert leaf_idx is not None, "INTERNAL ERROR: fmt: on/off handling (leaf index)" parent.insert_child( leaf_idx, Leaf( STANDALONE_COMMENT, hidden_value, prefix=standalone_comment_prefix, fmt_pass_converted_first_leaf=None, ), ) return True def convert_one_fmt_off_pair( node: Node, mode: Mode, lines: Collection[tuple[int, int]] ) -> bool: """Convert content of a single `# fmt: off`/`# fmt: on` into a standalone comment. Returns True if a pair was converted. """ for leaf in node.leaves(): # Skip STANDALONE_COMMENT nodes that were created by fmt:off/on processing # to avoid reprocessing them in subsequent iterations if ( leaf.type == STANDALONE_COMMENT and hasattr(leaf, "fmt_pass_converted_first_leaf") and leaf.fmt_pass_converted_first_leaf is None ): continue previous_consumed = 0 for comment in list_comments(leaf.prefix, is_endmarker=False, mode=mode): should_process, is_fmt_off, is_fmt_skip = _should_process_fmt_comment( comment, leaf ) if not should_process: previous_consumed = comment.consumed continue if not _is_valid_standalone_fmt_comment( comment, leaf, is_fmt_off, is_fmt_skip ): previous_consumed = comment.consumed continue ignored_nodes = list(generate_ignored_nodes(leaf, comment, mode)) # Handle comment-only blocks if not ignored_nodes and is_fmt_off: if _handle_comment_only_fmt_block( leaf, comment, previous_consumed, mode ): return True continue # Need actual nodes to process if not ignored_nodes: continue # Handle regular fmt blocks _handle_regular_fmt_block( ignored_nodes, comment, previous_consumed, is_fmt_skip, lines, leaf, ) return True return False def _handle_regular_fmt_block( ignored_nodes: list[LN], comment: ProtoComment, previous_consumed: int, is_fmt_skip: bool, lines: Collection[tuple[int, int]], leaf: Leaf, ) -> None: """Handle fmt blocks with actual AST nodes.""" first = ignored_nodes[0] # Can be a container node with the `leaf`. parent = first.parent prefix = first.prefix if comment.value in FMT_OFF: first.prefix = prefix[comment.consumed :] if is_fmt_skip: first.prefix = "" standalone_comment_prefix = prefix else: standalone_comment_prefix = prefix[:previous_consumed] + "\n" * comment.newlines hidden_value = "".join(str(n) for n in ignored_nodes) comment_lineno = leaf.lineno - comment.newlines if comment.value in FMT_OFF: fmt_off_prefix = "" if len(lines) > 0 and not any( line[0] <= comment_lineno <= line[1] for line in lines ): # keeping indentation of comment by preserving original whitespaces. fmt_off_prefix = prefix.split(comment.value)[0] if "\n" in fmt_off_prefix: fmt_off_prefix = fmt_off_prefix.split("\n")[-1] standalone_comment_prefix += fmt_off_prefix hidden_value = comment.value + "\n" + hidden_value if is_fmt_skip: hidden_value += comment.leading_whitespace + comment.value if hidden_value.endswith("\n"): # That happens when one of the `ignored_nodes` ended with a NEWLINE # leaf (possibly followed by a DEDENT). hidden_value = hidden_value[:-1] first_idx: int | None = None for ignored in ignored_nodes: index = ignored.remove() if first_idx is None: first_idx = index assert parent is not None, "INTERNAL ERROR: fmt: on/off handling (1)" assert first_idx is not None, "INTERNAL ERROR: fmt: on/off handling (2)" parent.insert_child( first_idx, Leaf( STANDALONE_COMMENT, hidden_value, prefix=standalone_comment_prefix, fmt_pass_converted_first_leaf=first_leaf_of(first), ), ) def generate_ignored_nodes( leaf: Leaf, comment: ProtoComment, mode: Mode ) -> Iterator[LN]: """Starting from the container of `leaf`, generate all leaves until `# fmt: on`. If comment is skip, returns leaf only. Stops at the end of the block. """ if _contains_fmt_directive(comment.value, FMT_SKIP): yield from _generate_ignored_nodes_from_fmt_skip(leaf, comment, mode) return container: LN | None = container_of(leaf) while container is not None and container.type != token.ENDMARKER: if is_fmt_on(container, mode=mode): return # fix for fmt: on in children if children_contains_fmt_on(container, mode=mode): for index, child in enumerate(container.children): if isinstance(child, Leaf) and is_fmt_on(child, mode=mode): if child.type in CLOSING_BRACKETS: # This means `# fmt: on` is placed at a different bracket level # than `# fmt: off`. This is an invalid use, but as a courtesy, # we include this closing bracket in the ignored nodes. # The alternative is to fail the formatting. yield child return if ( child.type == token.INDENT and index < len(container.children) - 1 and children_contains_fmt_on( container.children[index + 1], mode=mode ) ): # This means `# fmt: on` is placed right after an indentation # level, and we shouldn't swallow the previous INDENT token. return if children_contains_fmt_on(child, mode=mode): return yield child else: if container.type == token.DEDENT and container.next_sibling is None: # This can happen when there is no matching `# fmt: on` comment at the # same level as `# fmt: on`. We need to keep this DEDENT. return yield container container = container.next_sibling def _find_compound_statement_context(parent: Node) -> Node | None: """Return the body node of a compound statement if we should respect fmt: skip. This handles one-line compound statements like: if condition: body # fmt: skip When Black expands such statements, they temporarily look like: if condition: body # fmt: skip In both cases, we want to return the body node (either the simple_stmt directly or the suite containing it). """ if parent.type != syms.simple_stmt: return None if not isinstance(parent.parent, Node): return None # Case 1: Expanded form after Black's initial formatting pass. # The one-liner has been split across multiple lines: # if True: # print("a"); print("b") # fmt: skip # Structure: compound_stmt -> suite -> simple_stmt if ( parent.parent.type == syms.suite and isinstance(parent.parent.parent, Node) and parent.parent.parent.type in _COMPOUND_STATEMENTS ): return parent.parent # Case 2: Original one-line form from the input source. # The statement is still on a single line: # if True: print("a"); print("b") # fmt: skip # Structure: compound_stmt -> simple_stmt if parent.parent.type in _COMPOUND_STATEMENTS: return parent return None def _should_keep_compound_statement_inline( body_node: Node, simple_stmt_parent: Node ) -> bool: """Check if a compound statement should be kept on one line. Returns True only for compound statements with semicolon-separated bodies, like: if True: print("a"); print("b") # fmt: skip """ # Check if there are semicolons in the body for leaf in body_node.leaves(): if leaf.type == token.SEMI: # Verify it's a single-line body (one simple_stmt) if body_node.type == syms.suite: # After formatting: check suite has one simple_stmt child simple_stmts = [ child for child in body_node.children if child.type == syms.simple_stmt ] return len(simple_stmts) == 1 and simple_stmts[0] is simple_stmt_parent else: # Original form: body_node IS the simple_stmt return body_node is simple_stmt_parent return False def _get_compound_statement_header( body_node: Node, simple_stmt_parent: Node ) -> list[LN]: """Get header nodes for a compound statement that should be preserved inline.""" if not _should_keep_compound_statement_inline(body_node, simple_stmt_parent): return [] # Get the compound statement (parent of body) compound_stmt = body_node.parent if compound_stmt is None or compound_stmt.type not in _COMPOUND_STATEMENTS: return [] # Collect all header leaves before the body header_leaves: list[LN] = [] for child in compound_stmt.children: if child is body_node: break if isinstance(child, Leaf): if child.type not in (token.NEWLINE, token.INDENT): header_leaves.append(child) else: header_leaves.extend(child.leaves()) return header_leaves def _generate_ignored_nodes_from_fmt_skip( leaf: Leaf, comment: ProtoComment, mode: Mode ) -> Iterator[LN]: """Generate all leaves that should be ignored by the `# fmt: skip` from `leaf`.""" prev_sibling = leaf.prev_sibling parent = leaf.parent ignored_nodes: list[LN] = [] # Need to properly format the leaf prefix to compare it to comment.value, # which is also formatted comments = list_comments(leaf.prefix, is_endmarker=False, mode=mode) if not comments or comment.value != comments[0].value: return if prev_sibling is not None: leaf.prefix = leaf.prefix[comment.consumed :] if Preview.fix_fmt_skip_in_one_liners not in mode: siblings = [prev_sibling] while ( "\n" not in prev_sibling.prefix and prev_sibling.prev_sibling is not None ): prev_sibling = prev_sibling.prev_sibling siblings.insert(0, prev_sibling) yield from siblings return # Generates the nodes to be ignored by `fmt: skip`. # Nodes to ignore are the ones on the same line as the # `# fmt: skip` comment, excluding the `# fmt: skip` # node itself. # Traversal process (starting at the `# fmt: skip` node): # 1. Move to the `prev_sibling` of the current node. # 2. If `prev_sibling` has children, go to its rightmost leaf. # 3. If there's no `prev_sibling`, move up to the parent # node and repeat. # 4. Continue until: # a. You encounter an `INDENT` or `NEWLINE` node (indicates # start of the line). # b. You reach the root node. # Include all visited LEAVES in the ignored list, except INDENT # or NEWLINE leaves. current_node = prev_sibling ignored_nodes = [current_node] if current_node.prev_sibling is None and current_node.parent is not None: current_node = current_node.parent while "\n" not in current_node.prefix and current_node.prev_sibling is not None: leaf_nodes = list(current_node.prev_sibling.leaves()) current_node = leaf_nodes[-1] if leaf_nodes else current_node if current_node.type in (token.NEWLINE, token.INDENT): current_node.prefix = "" break # Special case for with expressions # Without this, we can stuck inside the asexpr_test's children's children if ( current_node.parent and current_node.parent.type == syms.asexpr_test and current_node.parent.parent and current_node.parent.parent.type == syms.with_stmt ): current_node = current_node.parent ignored_nodes.insert(0, current_node) if current_node.prev_sibling is None and current_node.parent is not None: current_node = current_node.parent # Special handling for compound statements with semicolon-separated bodies if Preview.fix_fmt_skip_in_one_liners in mode and isinstance(parent, Node): body_node = _find_compound_statement_context(parent) if body_node is not None: header_nodes = _get_compound_statement_header(body_node, parent) if header_nodes: ignored_nodes = header_nodes + ignored_nodes yield from ignored_nodes elif ( parent is not None and parent.type == syms.suite and leaf.type == token.NEWLINE ): # The `# fmt: skip` is on the colon line of the if/while/def/class/... # statements. The ignored nodes should be previous siblings of the # parent suite node. leaf.prefix = "" parent_sibling = parent.prev_sibling while parent_sibling is not None and parent_sibling.type != syms.suite: ignored_nodes.insert(0, parent_sibling) parent_sibling = parent_sibling.prev_sibling # Special case for `async_stmt` where the ASYNC token is on the # grandparent node. grandparent = parent.parent if ( grandparent is not None and grandparent.prev_sibling is not None and grandparent.prev_sibling.type == token.ASYNC ): ignored_nodes.insert(0, grandparent.prev_sibling) yield from iter(ignored_nodes) def is_fmt_on(container: LN, mode: Mode) -> bool: """Determine whether formatting is switched on within a container. Determined by whether the last `# fmt:` comment is `on` or `off`. """ fmt_on = False for comment in list_comments(container.prefix, is_endmarker=False, mode=mode): if comment.value in FMT_ON: fmt_on = True elif comment.value in FMT_OFF: fmt_on = False return fmt_on def children_contains_fmt_on(container: LN, mode: Mode) -> bool: """Determine if children have formatting switched on.""" for child in container.children: leaf = first_leaf_of(child) if leaf is not None and is_fmt_on(leaf, mode=mode): return True return False def contains_pragma_comment(comment_list: list[Leaf]) -> bool: """ Returns: True iff one of the comments in @comment_list is a pragma used by one of the more common static analysis tools for python (e.g. mypy, flake8, pylint). """ for comment in comment_list: if comment.value.startswith(("# type:", "# noqa", "# pylint:")): return True return False def _contains_fmt_directive( comment_line: str, directives: set[str] = FMT_OFF | FMT_ON | FMT_SKIP ) -> bool: """ Checks if the given comment contains format directives, alone or paired with other comments. Defaults to checking all directives (skip, off, on, yapf), but can be narrowed to specific ones. Matching styles: # foobar <-- single comment # foobar # foobar # foobar <-- multiple comments # foobar; foobar <-- list of comments (; separated) """ semantic_comment_blocks = [ comment_line, *[ _COMMENT_PREFIX + comment.strip() for comment in comment_line.split(_COMMENT_PREFIX)[1:] ], *[ _COMMENT_PREFIX + comment.strip() for comment in comment_line.strip(_COMMENT_PREFIX).split( _COMMENT_LIST_SEPARATOR ) ], ] return any(comment in directives for comment in semantic_comment_blocks)
ProtoComment
python
mozilla__bleach
bleach/_vendor/parse.py
{ "start": 10926, "end": 11060 }
class ____(_SplitResultBase, _NetlocResultMixinStr): __slots__ = () def geturl(self): return urlunsplit(self)
SplitResult
python
google__pytype
pytype/overriding_checks.py
{ "start": 520, "end": 1089 }
class ____(enum.Enum): """Constants representing various signature mismatch errors.""" NO_ERROR = enum.auto() DEFAULT_PARAMETER_MISMATCH = enum.auto() DEFAULT_VALUE_MISMATCH = enum.auto() KWONLY_PARAMETER_COUNT_MISMATCH = enum.auto() KWONLY_PARAMETER_NAME_MISMATCH = enum.auto() KWONLY_PARAMETER_TYPE_MISMATCH = enum.auto() POSITIONAL_PARAMETER_COUNT_MISMATCH = enum.auto() POSITIONAL_PARAMETER_NAME_MISMATCH = enum.auto() POSITIONAL_PARAMETER_TYPE_MISMATCH = enum.auto() RETURN_TYPE_MISMATCH = enum.auto() @dataclasses.dataclass
SignatureErrorType
python
bokeh__bokeh
src/bokeh/core/property/nothing.py
{ "start": 1270, "end": 2126 }
class ____(Property[NoReturn]): """ The bottom type of bokeh's type system. It doesn't accept any values. """ def __init__(self, *, help: str | None = None) -> None: super().__init__(default=Undefined, help=help) def validate(self, value: Any, detail: bool = True) -> None: raise ValueError("no value is allowed") #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
Nothing
python
weaviate__weaviate-python-client
weaviate/collections/classes/config_vectorizers.py
{ "start": 10022, "end": 10509 }
class ____(_VectorizerConfigCreate): vectorizer: Union[Vectorizers, _EnumLikeStr] = Field( default=Vectorizers.TEXT2VEC_MISTRAL, frozen=True, exclude=True ) model: Optional[str] vectorizeClassName: bool baseURL: Optional[AnyHttpUrl] def _to_dict(self) -> Dict[str, Any]: ret_dict = super()._to_dict() if self.baseURL is not None: ret_dict["baseURL"] = self.baseURL.unicode_string() return ret_dict
_Text2VecMistralConfig
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-aws-datalake/destination_aws_datalake/stream_writer.py
{ "start": 1120, "end": 17160 }
class ____: def __init__(self, aws_handler: AwsHandler, config: ConnectorConfig, configured_stream: ConfiguredAirbyteStream) -> None: self._aws_handler: AwsHandler = aws_handler self._config: ConnectorConfig = config self._configured_stream: ConfiguredAirbyteStream = configured_stream self._schema: Dict[str, Any] = configured_stream.stream.json_schema["properties"] self._sync_mode: DestinationSyncMode = configured_stream.destination_sync_mode self._table_exists: bool = False self._table: str = configured_stream.stream.name self._database: str = self._configured_stream.stream.namespace or self._config.lakeformation_database_name self._messages = [] self._partial_flush_count = 0 logger.info(f"Creating StreamWriter for {self._database}:{self._table}") def _get_date_columns(self) -> List[str]: date_columns = [] for key, val in self._schema.items(): typ = val.get("type") typ = self._get_json_schema_type(typ) if isinstance(typ, str) and typ == "string": if val.get("format") in ["date-time", "date"]: date_columns.append(key) return date_columns def _add_partition_column(self, col: str, df: pd.DataFrame) -> Dict[str, str]: partitioning = self._config.partitioning if partitioning == PartitionOptions.NONE: return {} partitions = partitioning.value.split("/") fields = {} for partition in partitions: date_col = f"{col}_{partition.lower()}" fields[date_col] = "bigint" # defaulting to 0 since both governed tables # and pyarrow don't play well with __HIVE_DEFAULT_PARTITION__ # - pyarrow will fail to cast the column to any other type than string # - governed tables will fail when trying to query a table with partitions that have __HIVE_DEFAULT_PARTITION__ # aside from the above, awswrangler will remove data from a table if the partition value is null # see: https://github.com/aws/aws-sdk-pandas/issues/921 if partition == "YEAR": df[date_col] = df[col].dt.strftime("%Y").fillna("0").astype("Int64") elif partition == "MONTH": df[date_col] = df[col].dt.strftime("%m").fillna("0").astype("Int64") elif partition == "DAY": df[date_col] = df[col].dt.strftime("%d").fillna("0").astype("Int64") elif partition == "DATE": fields[date_col] = "date" df[date_col] = df[col].dt.strftime("%Y-%m-%d") return fields def _drop_additional_top_level_properties(self, record: Dict[str, Any]) -> Dict[str, Any]: """ Helper that removes any unexpected top-level properties from the record. Since the json schema is used to build the table and cast types correctly, we need to remove any unexpected properties that can't be casted accurately. """ schema_keys = self._schema.keys() records_keys = record.keys() difference = list(set(records_keys).difference(set(schema_keys))) for key in difference: del record[key] return record def _json_schema_cast_value(self, value, schema_entry) -> Any: typ = schema_entry.get("type") typ = self._get_json_schema_type(typ) props = schema_entry.get("properties") items = schema_entry.get("items") if typ == "string": format = schema_entry.get("format") if format == "date-time": return pd.to_datetime(value, errors="coerce", utc=True) return str(value) if value and value != "" else None elif typ == "integer": return pd.to_numeric(value, errors="coerce") elif typ == "number": if self._config.glue_catalog_float_as_decimal: return Decimal(str(value)) if value else Decimal("0") return pd.to_numeric(value, errors="coerce") elif typ == "boolean": return bool(value) elif typ == "null": return None elif typ == "object": if value in EMPTY_VALUES: return None if isinstance(value, dict) and props: for key, val in value.items(): if key in props: value[key] = self._json_schema_cast_value(val, props[key]) return value elif typ == "array" and items: if value in EMPTY_VALUES: return None if isinstance(value, list): return [self._json_schema_cast_value(item, items) for item in value] return value def _json_schema_cast(self, record: Dict[str, Any]) -> Dict[str, Any]: """ Helper that fixes obvious type violations in a record's top level keys that may cause issues when casting data to pyarrow types. Such as: - Objects having empty strings or " " or "-" as value instead of null or {} - Arrays having empty strings or " " or "-" as value instead of null or [] """ for key, schema_type in self._schema.items(): typ = self._schema[key].get("type") typ = self._get_json_schema_type(typ) record[key] = self._json_schema_cast_value(record.get(key), schema_type) return record def _get_non_null_json_schema_types(self, typ: Union[str, List[str]]) -> Union[str, List[str]]: if isinstance(typ, list): return list(filter(lambda x: x != "null", typ)) return typ def _json_schema_type_has_mixed_types(self, typ: Union[str, List[str]]) -> bool: if isinstance(typ, list): typ = self._get_non_null_json_schema_types(typ) if len(typ) > 1: return True return False def _get_json_schema_type(self, types: Union[List[str], str]) -> str: if isinstance(types, str): return types if not isinstance(types, list): return "string" types = self._get_non_null_json_schema_types(types) # when multiple types, cast to string if self._json_schema_type_has_mixed_types(types): return "string" return types[0] def _get_pandas_dtypes_from_json_schema(self, df: pd.DataFrame) -> Dict[str, str]: column_types = {} typ = "string" for col in df.columns: if col in self._schema: typ = self._schema[col].get("type", "string") airbyte_type = self._schema[col].get("airbyte_type") # special case where the json schema type contradicts the airbyte type if airbyte_type and typ == "number" and airbyte_type == "integer": typ = "integer" typ = self._get_json_schema_type(typ) column_types[col] = PANDAS_TYPE_MAPPING.get(typ, "string") return column_types def _get_json_schema_types(self) -> Dict[str, str]: types = {} for key, val in self._schema.items(): typ = val.get("type") types[key] = self._get_json_schema_type(typ) return types def _is_invalid_struct_or_array(self, schema: Dict[str, Any]) -> bool: """ Helper that detects issues with nested objects/arrays in the json schema. When a complex data type is detected (schema with oneOf) or a nested object without properties the columns' dtype will be casted to string to avoid pyarrow conversion issues. """ result = True def check_properties(schema): nonlocal result for val in schema.values(): # Complex types can't be casted to an athena/glue type if val.get("oneOf"): result = False continue raw_typ = val.get("type") # If the type is a list, check for mixed types # complex objects with mixed types can't be reliably casted if isinstance(raw_typ, list) and self._json_schema_type_has_mixed_types(raw_typ): result = False continue typ = self._get_json_schema_type(raw_typ) # If object check nested properties if typ == "object": properties = val.get("properties") if not properties: result = False else: check_properties(properties) # If array check nested properties if typ == "array": items = val.get("items") if not items: result = False continue if isinstance(items, list): items = items[0] item_properties = items.get("properties") if item_properties: check_properties(item_properties) check_properties(schema) return result def _get_glue_dtypes_from_json_schema(self, schema: Dict[str, Any]) -> Tuple[Dict[str, str], List[str]]: """ Helper that infers glue dtypes from a json schema. """ type_mapper = GLUE_TYPE_MAPPING_DECIMAL if self._config.glue_catalog_float_as_decimal else GLUE_TYPE_MAPPING_DOUBLE column_types = {} json_columns = set() for col, definition in schema.items(): result_typ = None col_typ = definition.get("type") airbyte_type = definition.get("airbyte_type") col_format = definition.get("format") col_typ = self._get_json_schema_type(col_typ) # special case where the json schema type contradicts the airbyte type if airbyte_type and col_typ == "number" and airbyte_type == "integer": col_typ = "integer" if col_typ == "string" and col_format == "date-time": result_typ = "timestamp" if col_typ == "string" and col_format == "date": result_typ = "date" if col_typ == "object": properties = definition.get("properties") allow_additional_properties = definition.get("additionalProperties", False) if properties and not allow_additional_properties and self._is_invalid_struct_or_array(properties): object_props, _ = self._get_glue_dtypes_from_json_schema(properties) result_typ = f"struct<{','.join([f'{k}:{v}' for k, v in object_props.items()])}>" else: json_columns.add(col) result_typ = "string" if col_typ == "array": items = definition.get("items", {}) if isinstance(items, list): items = items[0] raw_item_type = items.get("type") airbyte_raw_item_type = items.get("airbyte_type") # special case where the json schema type contradicts the airbyte type if airbyte_raw_item_type and raw_item_type == "number" and airbyte_raw_item_type == "integer": raw_item_type = "integer" item_type = self._get_json_schema_type(raw_item_type) item_properties = items.get("properties") # if array has no "items", cast to string if not items: json_columns.add(col) result_typ = "string" # if array with objects elif isinstance(items, dict) and item_properties: # Check if nested object has properties and no mixed type objects if self._is_invalid_struct_or_array(item_properties): item_dtypes, _ = self._get_glue_dtypes_from_json_schema(item_properties) inner_struct = f"struct<{','.join([f'{k}:{v}' for k, v in item_dtypes.items()])}>" result_typ = f"array<{inner_struct}>" else: json_columns.add(col) result_typ = "string" elif item_type and self._json_schema_type_has_mixed_types(raw_item_type): json_columns.add(col) result_typ = "string" # array with single type elif item_type and not self._json_schema_type_has_mixed_types(raw_item_type): result_typ = f"array<{type_mapper[item_type]}>" if result_typ is None: result_typ = type_mapper.get(col_typ, "string") column_types[col] = result_typ return column_types, json_columns @property def _cursor_fields(self) -> Optional[List[str]]: return self._configured_stream.cursor_field def append_message(self, message: Dict[str, Any]): clean_message = self._drop_additional_top_level_properties(message) clean_message = self._json_schema_cast(clean_message) self._messages.append(clean_message) def reset(self): logger.info(f"Deleting table {self._database}:{self._table}") success = self._aws_handler.delete_table(self._database, self._table) if not success: logger.warning(f"Failed to reset table {self._database}:{self._table}") def flush(self, partial: bool = False): logger.debug(f"Flushing {len(self._messages)} messages to table {self._database}:{self._table}") df = pd.DataFrame(self._messages) # best effort to convert pandas types df = df.astype(self._get_pandas_dtypes_from_json_schema(df), errors="ignore") if len(df) < 1: logger.info(f"No messages to write to {self._database}:{self._table}") return partition_fields = {} date_columns = self._get_date_columns() for col in date_columns: if col in df.columns: df[col] = pd.to_datetime(df[col], format="mixed", utc=True) # Create date column for partitioning if self._cursor_fields and col in self._cursor_fields: fields = self._add_partition_column(col, df) partition_fields.update(fields) dtype, json_casts = self._get_glue_dtypes_from_json_schema(self._schema) dtype = {**dtype, **partition_fields} partition_fields = list(partition_fields.keys()) # Make sure complex types that can't be converted # to a struct or array are converted to a json string # so they can be queried with json_extract for col in json_casts: if col in df.columns: df[col] = df[col].apply(lambda x: json.dumps(x, cls=DictEncoder)) if self._sync_mode == DestinationSyncMode.overwrite and self._partial_flush_count < 1: logger.debug(f"Overwriting {len(df)} records to {self._database}:{self._table}") self._aws_handler.write( df, self._database, self._table, dtype, partition_fields, ) elif self._sync_mode == DestinationSyncMode.append or self._partial_flush_count > 0: logger.debug(f"Appending {len(df)} records to {self._database}:{self._table}") self._aws_handler.append( df, self._database, self._table, dtype, partition_fields, ) else: self._messages = [] raise Exception(f"Unsupported sync mode: {self._sync_mode}") if partial: self._partial_flush_count += 1 del df self._messages.clear()
StreamWriter
python
getsentry__sentry
src/sentry/api/serializers/models/plugin.py
{ "start": 1229, "end": 3998 }
class ____(Serializer): def __init__(self, project=None): self.project = project def serialize(self, obj, attrs, user, **kwargs): from sentry.releases.endpoints.project_releases_token import _get_webhook_url doc = "" if self.project is not None: release_token = ProjectOption.objects.get_value(self.project, "sentry:release-token") if release_token is not None: webhook_url = _get_webhook_url(self.project, obj.slug, release_token) if hasattr(obj, "get_release_doc_html"): try: doc = obj.get_release_doc_html(webhook_url) except NotImplementedError: pass contexts: list[str] = [] if hasattr(obj, "get_custom_contexts"): contexts.extend(x.type for x in obj.get_custom_contexts() or ()) deprecation_date = getattr(obj, "deprecation_date", None) d = { "id": obj.slug, "name": str(obj.get_title()), "slug": obj.slug or slugify(str(obj.get_title())), "shortName": str(obj.get_short_title()), "type": obj.get_plugin_type(), "canDisable": obj.can_disable, "isTestable": hasattr(obj, "is_testable") and obj.is_testable(), "hasConfiguration": obj.has_project_conf(), "contexts": contexts, "doc": doc, "firstPartyAlternative": getattr(obj, "alternative", None), "deprecationDate": ( deprecation_date.strftime("%b %-d, %Y") if deprecation_date else None ), "altIsSentryApp": getattr(obj, "alt_is_sentry_app", None), } if self.project: d["enabled"] = obj.is_enabled(self.project) if obj.version: d["version"] = str(obj.version) if obj.author: d["author"] = {"name": str(obj.author), "url": str(obj.author_url)} d["isDeprecated"] = is_plugin_deprecated(obj, self.project) d["isHidden"] = d["isDeprecated"] or (not d.get("enabled", False) and obj.is_hidden()) if obj.description: d["description"] = str(obj.description) d["features"] = list({f.featureGate.value for f in obj.feature_descriptions}) d["featureDescriptions"] = [ { "description": f.description.strip(), "featureGate": obj.feature_flag_name(f.featureGate.value), } for f in obj.feature_descriptions ] if obj.resource_links: d["resourceLinks"] = [ {"title": title, "url": url} for [title, url] in obj.resource_links ] return d
PluginSerializer
python
coleifer__peewee
tests/sqlite.py
{ "start": 2580, "end": 2702 }
class ____(FTSModel, TestModel): message = TextField() class Meta: options = {'tokenize': 'porter'}
Document
python
coleifer__peewee
tests/fields.py
{ "start": 43547, "end": 45631 }
class ____(ModelTestCase): offset_to_names = ( (-10, ()), (5, ('s1',)), (10, ('s1', 's10')), (11, ('s1', 's10')), (60, ('s1', 's10', 's60')), (61, ('s1', 's10', 's60'))) requires = [Schedule, Task] def setUp(self): super(TestDateTimeMath, self).setUp() with self.database.atomic(): s1 = Schedule.create(interval=1) s10 = Schedule.create(interval=10) s60 = Schedule.create(interval=60) self.dt = datetime.datetime(2019, 1, 1, 12) for s, n in ((s1, 's1'), (s10, 's10'), (s60, 's60')): Task.create(schedule=s, name=n, last_run=self.dt) def _do_test_date_time_math(self, next_occurrence_expression): for offset, names in self.offset_to_names: dt = Value(self.dt + datetime.timedelta(seconds=offset)) query = (Task .select(Task, Schedule) .join(Schedule) .where(dt >= next_occurrence_expression) .order_by(Schedule.interval)) tnames = [task.name for task in query] self.assertEqual(list(names), tnames) @requires_pglike def test_date_time_math_pg(self): second = SQL("INTERVAL '1 second'") next_occurrence = Task.last_run + (Schedule.interval * second) self._do_test_date_time_math(next_occurrence) @requires_sqlite def test_date_time_math_sqlite(self): # Convert to a timestamp, add the scheduled seconds, then convert back # to a datetime string for comparison with the last occurrence. next_ts = Task.last_run.to_timestamp() + Schedule.interval next_occurrence = fn.datetime(next_ts, 'unixepoch') self._do_test_date_time_math(next_occurrence) @requires_mysql def test_date_time_math_mysql(self): nl = NodeList((SQL('INTERVAL'), Schedule.interval, SQL('SECOND'))) next_occurrence = fn.date_add(Task.last_run, nl) self._do_test_date_time_math(next_occurrence)
TestDateTimeMath
python
realpython__materials
build-a-django-content-aggregator/source_code_step_1/podcasts/apps.py
{ "start": 36, "end": 91 }
class ____(AppConfig): name = "podcasts"
PodcastsConfig
python
airbytehq__airbyte
airbyte-integrations/connectors/source-monday/unit_tests/integrations/monday_requests/teams_requests_builder.py
{ "start": 184, "end": 569 }
class ____(MondayBaseRequestBuilder): @classmethod def teams_endpoint(cls, authenticator: Authenticator) -> "TeamsRequestBuilder": return cls().with_authenticator(authenticator) @property def request_body(self): params = super().query_params or {} params["query"] = "{teams{id,name,picture_url,users{id}}}" return params
TeamsRequestBuilder
python
kamyu104__LeetCode-Solutions
Python/shortest-distance-after-road-addition-queries-i.py
{ "start": 888, "end": 1737 }
class ____(object): def shortestDistanceAfterQueries(self, n, queries): """ :type n: int :type queries: List[List[int]] :rtype: List[int] """ def dijkstra(u, v): adj[u].append((v, 1)) min_heap = [(dist[u], u)] while min_heap: curr, u = heapq.heappop(min_heap) if curr > dist[u]: continue for v, w in adj[u]: if curr+w >= dist[v]: continue dist[v] = curr+w heapq.heappush(min_heap, (dist[v], v)) return dist[-1] adj = [[] for _ in xrange(n)] for u in xrange(n-1): adj[u].append((u+1, 1)) dist = range(n) return [dijkstra(u, v) for u, v in queries]
Solution2
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/vertex_ai/custom_job.py
{ "start": 2233, "end": 178455 }
class ____(GoogleBaseHook, OperationHelper): """Hook for Google Cloud Vertex AI Custom Job APIs.""" def __init__( self, gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: super().__init__( gcp_conn_id=gcp_conn_id, impersonation_chain=impersonation_chain, **kwargs, ) self._job: None | ( CustomContainerTrainingJob | CustomPythonPackageTrainingJob | CustomTrainingJob ) = None def get_pipeline_service_client( self, region: str | None = None, ) -> PipelineServiceClient: """Return PipelineServiceClient object.""" if region and region != "global": client_options = ClientOptions(api_endpoint=f"{region}-aiplatform.googleapis.com:443") else: client_options = ClientOptions() return PipelineServiceClient( credentials=self.get_credentials(), client_info=CLIENT_INFO, client_options=client_options ) def get_job_service_client( self, region: str | None = None, ) -> JobServiceClient: """Return JobServiceClient object.""" if region and region != "global": client_options = ClientOptions(api_endpoint=f"{region}-aiplatform.googleapis.com:443") else: client_options = ClientOptions() return JobServiceClient( credentials=self.get_credentials(), client_info=CLIENT_INFO, client_options=client_options ) def get_custom_container_training_job( self, display_name: str, container_uri: str, command: Sequence[str] = (), model_serving_container_image_uri: str | None = None, model_serving_container_predict_route: str | None = None, model_serving_container_health_route: str | None = None, model_serving_container_command: Sequence[str] | None = None, model_serving_container_args: Sequence[str] | None = None, model_serving_container_environment_variables: dict[str, str] | None = None, model_serving_container_ports: Sequence[int] | None = None, model_description: str | None = None, model_instance_schema_uri: str | None = None, model_parameters_schema_uri: str | None = None, model_prediction_schema_uri: str | None = None, project: str | None = None, location: str | None = None, labels: dict[str, str] | None = None, training_encryption_spec_key_name: str | None = None, model_encryption_spec_key_name: str | None = None, staging_bucket: str | None = None, ) -> CustomContainerTrainingJob: """Return CustomContainerTrainingJob object.""" return CustomContainerTrainingJob( display_name=display_name, container_uri=container_uri, command=command, model_serving_container_image_uri=model_serving_container_image_uri, model_serving_container_predict_route=model_serving_container_predict_route, model_serving_container_health_route=model_serving_container_health_route, model_serving_container_command=model_serving_container_command, model_serving_container_args=model_serving_container_args, model_serving_container_environment_variables=model_serving_container_environment_variables, model_serving_container_ports=model_serving_container_ports, model_description=model_description, model_instance_schema_uri=model_instance_schema_uri, model_parameters_schema_uri=model_parameters_schema_uri, model_prediction_schema_uri=model_prediction_schema_uri, project=project, location=location, credentials=self.get_credentials(), labels=labels, training_encryption_spec_key_name=training_encryption_spec_key_name, model_encryption_spec_key_name=model_encryption_spec_key_name, staging_bucket=staging_bucket, ) def get_custom_python_package_training_job( self, display_name: str, python_package_gcs_uri: str, python_module_name: str, container_uri: str, model_serving_container_image_uri: str | None = None, model_serving_container_predict_route: str | None = None, model_serving_container_health_route: str | None = None, model_serving_container_command: Sequence[str] | None = None, model_serving_container_args: Sequence[str] | None = None, model_serving_container_environment_variables: dict[str, str] | None = None, model_serving_container_ports: Sequence[int] | None = None, model_description: str | None = None, model_instance_schema_uri: str | None = None, model_parameters_schema_uri: str | None = None, model_prediction_schema_uri: str | None = None, project: str | None = None, location: str | None = None, labels: dict[str, str] | None = None, training_encryption_spec_key_name: str | None = None, model_encryption_spec_key_name: str | None = None, staging_bucket: str | None = None, ) -> CustomPythonPackageTrainingJob: """Return CustomPythonPackageTrainingJob object.""" return CustomPythonPackageTrainingJob( display_name=display_name, container_uri=container_uri, python_package_gcs_uri=python_package_gcs_uri, python_module_name=python_module_name, model_serving_container_image_uri=model_serving_container_image_uri, model_serving_container_predict_route=model_serving_container_predict_route, model_serving_container_health_route=model_serving_container_health_route, model_serving_container_command=model_serving_container_command, model_serving_container_args=model_serving_container_args, model_serving_container_environment_variables=model_serving_container_environment_variables, model_serving_container_ports=model_serving_container_ports, model_description=model_description, model_instance_schema_uri=model_instance_schema_uri, model_parameters_schema_uri=model_parameters_schema_uri, model_prediction_schema_uri=model_prediction_schema_uri, project=project, location=location, credentials=self.get_credentials(), labels=labels, training_encryption_spec_key_name=training_encryption_spec_key_name, model_encryption_spec_key_name=model_encryption_spec_key_name, staging_bucket=staging_bucket, ) def get_custom_training_job( self, display_name: str, script_path: str, container_uri: str, requirements: Sequence[str] | None = None, model_serving_container_image_uri: str | None = None, model_serving_container_predict_route: str | None = None, model_serving_container_health_route: str | None = None, model_serving_container_command: Sequence[str] | None = None, model_serving_container_args: Sequence[str] | None = None, model_serving_container_environment_variables: dict[str, str] | None = None, model_serving_container_ports: Sequence[int] | None = None, model_description: str | None = None, model_instance_schema_uri: str | None = None, model_parameters_schema_uri: str | None = None, model_prediction_schema_uri: str | None = None, project: str | None = None, location: str | None = None, labels: dict[str, str] | None = None, training_encryption_spec_key_name: str | None = None, model_encryption_spec_key_name: str | None = None, staging_bucket: str | None = None, ) -> CustomTrainingJob: """Return CustomTrainingJob object.""" return CustomTrainingJob( display_name=display_name, script_path=script_path, container_uri=container_uri, requirements=requirements, model_serving_container_image_uri=model_serving_container_image_uri, model_serving_container_predict_route=model_serving_container_predict_route, model_serving_container_health_route=model_serving_container_health_route, model_serving_container_command=model_serving_container_command, model_serving_container_args=model_serving_container_args, model_serving_container_environment_variables=model_serving_container_environment_variables, model_serving_container_ports=model_serving_container_ports, model_description=model_description, model_instance_schema_uri=model_instance_schema_uri, model_parameters_schema_uri=model_parameters_schema_uri, model_prediction_schema_uri=model_prediction_schema_uri, project=project, location=location, credentials=self.get_credentials(), labels=labels, training_encryption_spec_key_name=training_encryption_spec_key_name, model_encryption_spec_key_name=model_encryption_spec_key_name, staging_bucket=staging_bucket, ) @staticmethod def extract_model_id(obj: dict[str, Any]) -> str: """Return unique id of the Model.""" return obj["name"].rpartition("/")[-1] @staticmethod def extract_model_id_from_training_pipeline(training_pipeline: dict[str, Any]) -> str: """Return a unique Model ID from a serialized TrainingPipeline proto.""" return training_pipeline["model_to_upload"]["name"].rpartition("/")[-1] @staticmethod def extract_training_id(resource_name: str) -> str: """Return unique id of the Training pipeline.""" return resource_name.rpartition("/")[-1] @staticmethod def extract_custom_job_id(custom_job_name: str) -> str: """Return unique id of the Custom Job pipeline.""" return custom_job_name.rpartition("/")[-1] @staticmethod def extract_custom_job_id_from_training_pipeline(training_pipeline: dict[str, Any]) -> str: """Return a unique Custom Job id from a serialized TrainingPipeline proto.""" return training_pipeline["training_task_metadata"]["backingCustomJob"].rpartition("/")[-1] def cancel_job(self) -> None: """Cancel Job for training pipeline.""" if self._job: self._job.cancel() def _run_job( self, job: (CustomTrainingJob | CustomContainerTrainingJob | CustomPythonPackageTrainingJob), dataset: None | ( datasets.ImageDataset | datasets.TabularDataset | datasets.TextDataset | datasets.VideoDataset ) = None, annotation_schema_uri: str | None = None, model_display_name: str | None = None, model_labels: dict[str, str] | None = None, base_output_dir: str | None = None, service_account: str | None = None, network: str | None = None, bigquery_destination: str | None = None, args: list[str | float | int] | None = None, environment_variables: dict[str, str] | None = None, replica_count: int = 1, machine_type: str = "n1-standard-4", accelerator_type: str = "ACCELERATOR_TYPE_UNSPECIFIED", accelerator_count: int = 0, boot_disk_type: str = "pd-ssd", boot_disk_size_gb: int = 100, training_fraction_split: float | None = None, validation_fraction_split: float | None = None, test_fraction_split: float | None = None, training_filter_split: str | None = None, validation_filter_split: str | None = None, test_filter_split: str | None = None, predefined_split_column_name: str | None = None, timestamp_split_column_name: str | None = None, tensorboard: str | None = None, sync=True, parent_model: str | None = None, is_default_version: bool | None = None, model_version_aliases: list[str] | None = None, model_version_description: str | None = None, psc_interface_config: PscInterfaceConfig | None = None, ) -> tuple[models.Model | None, str, str]: """Run a training pipeline job and wait until its completion.""" model = job.run( dataset=dataset, annotation_schema_uri=annotation_schema_uri, model_display_name=model_display_name, model_labels=model_labels, base_output_dir=base_output_dir, service_account=service_account, network=network, bigquery_destination=bigquery_destination, args=args, environment_variables=environment_variables, replica_count=replica_count, machine_type=machine_type, accelerator_type=accelerator_type, accelerator_count=accelerator_count, boot_disk_type=boot_disk_type, boot_disk_size_gb=boot_disk_size_gb, training_fraction_split=training_fraction_split, validation_fraction_split=validation_fraction_split, test_fraction_split=test_fraction_split, training_filter_split=training_filter_split, validation_filter_split=validation_filter_split, test_filter_split=test_filter_split, predefined_split_column_name=predefined_split_column_name, timestamp_split_column_name=timestamp_split_column_name, tensorboard=tensorboard, sync=sync, parent_model=parent_model, is_default_version=is_default_version, model_version_aliases=model_version_aliases, model_version_description=model_version_description, psc_interface_config=psc_interface_config, ) training_id = self.extract_training_id(job.resource_name) custom_job_id = self.extract_custom_job_id( job.gca_resource.training_task_metadata.get("backingCustomJob") ) if model: model.wait() else: self.log.warning( "Training did not produce a Managed Model returning None. Training Pipeline is not " "configured to upload a Model. Create the Training Pipeline with " "model_serving_container_image_uri and model_display_name passed in. " "Ensure that your training script saves to model to os.environ['AIP_MODEL_DIR']." ) return model, training_id, custom_job_id @GoogleBaseHook.fallback_to_default_project_id def cancel_training_pipeline( self, project_id: str, region: str, training_pipeline: str, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), ) -> None: """ Cancel a TrainingPipeline. Starts asynchronous cancellation on the TrainingPipeline. The server makes the best effort to cancel the pipeline, but success is not guaranteed. Clients can use [PipelineService.GetTrainingPipeline][google.cloud.aiplatform.v1.PipelineService.GetTrainingPipeline] or other methods to check whether the cancellation succeeded or whether the pipeline completed despite cancellation. On successful cancellation, the TrainingPipeline is not deleted; instead it becomes a pipeline with a [TrainingPipeline.error][google.cloud.aiplatform.v1.TrainingPipeline.error] value with a [google.rpc.Status.code][google.rpc.Status.code] of 1, corresponding to ``Code.CANCELLED``, and [TrainingPipeline.state][google.cloud.aiplatform.v1.TrainingPipeline.state] is set to ``CANCELLED``. :param project_id: Required. The ID of the Google Cloud project that the service belongs to. :param region: Required. The ID of the Google Cloud region that the service belongs to. :param training_pipeline: Required. The name of the TrainingPipeline to cancel. :param retry: Designation of what errors, if any, should be retried. :param timeout: The timeout for this request. :param metadata: Strings which should be sent along with the request as metadata. """ client = self.get_pipeline_service_client(region) name = client.training_pipeline_path(project_id, region, training_pipeline) client.cancel_training_pipeline( request={ "name": name, }, retry=retry, timeout=timeout, metadata=metadata, ) @GoogleBaseHook.fallback_to_default_project_id def cancel_custom_job( self, project_id: str, region: str, custom_job: str, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), ) -> None: """ Cancel a CustomJob. Starts asynchronous cancellation on the CustomJob. The server makes the best effort to cancel the job, but success is not guaranteed. Clients can use [JobService.GetCustomJob][google.cloud.aiplatform.v1.JobService.GetCustomJob] or other methods to check whether the cancellation succeeded or whether the job completed despite cancellation. On successful cancellation, the CustomJob is not deleted; instead it becomes a job with a [CustomJob.error][google.cloud.aiplatform.v1.CustomJob.error] value with a [google.rpc.Status.code][google.rpc.Status.code] of 1, corresponding to ``Code.CANCELLED``, and [CustomJob.state][google.cloud.aiplatform.v1.CustomJob.state] is set to ``CANCELLED``. :param project_id: Required. The ID of the Google Cloud project that the service belongs to. :param region: Required. The ID of the Google Cloud region that the service belongs to. :param custom_job: Required. The name of the CustomJob to cancel. :param retry: Designation of what errors, if any, should be retried. :param timeout: The timeout for this request. :param metadata: Strings which should be sent along with the request as metadata. """ client = self.get_job_service_client(region) name = JobServiceClient.custom_job_path(project_id, region, custom_job) client.cancel_custom_job( request={ "name": name, }, retry=retry, timeout=timeout, metadata=metadata, ) @GoogleBaseHook.fallback_to_default_project_id def create_training_pipeline( self, project_id: str, region: str, training_pipeline: TrainingPipeline, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), ) -> TrainingPipeline: """ Create a TrainingPipeline. A created TrainingPipeline right away will be attempted to be run. :param project_id: Required. The ID of the Google Cloud project that the service belongs to. :param region: Required. The ID of the Google Cloud region that the service belongs to. :param training_pipeline: Required. The TrainingPipeline to create. :param retry: Designation of what errors, if any, should be retried. :param timeout: The timeout for this request. :param metadata: Strings which should be sent along with the request as metadata. """ client = self.get_pipeline_service_client(region) parent = client.common_location_path(project_id, region) result = client.create_training_pipeline( request={ "parent": parent, "training_pipeline": training_pipeline, }, retry=retry, timeout=timeout, metadata=metadata, ) return result @GoogleBaseHook.fallback_to_default_project_id def create_custom_job( self, project_id: str, region: str, custom_job: CustomJob, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), ) -> CustomJob: """ Create a CustomJob. A created CustomJob right away will be attempted to be run. :param project_id: Required. The ID of the Google Cloud project that the service belongs to. :param region: Required. The ID of the Google Cloud region that the service belongs to. :param custom_job: Required. The CustomJob to create. This corresponds to the ``custom_job`` field on the ``request`` instance; if ``request`` is provided, this should not be set. :param retry: Designation of what errors, if any, should be retried. :param timeout: The timeout for this request. :param metadata: Strings which should be sent along with the request as metadata. """ client = self.get_job_service_client(region) parent = JobServiceClient.common_location_path(project_id, region) result = client.create_custom_job( request={ "parent": parent, "custom_job": custom_job, }, retry=retry, timeout=timeout, metadata=metadata, ) return result @GoogleBaseHook.fallback_to_default_project_id def create_custom_container_training_job( self, project_id: str, region: str, display_name: str, container_uri: str, command: Sequence[str] = (), model_serving_container_image_uri: str | None = None, model_serving_container_predict_route: str | None = None, model_serving_container_health_route: str | None = None, model_serving_container_command: Sequence[str] | None = None, model_serving_container_args: Sequence[str] | None = None, model_serving_container_environment_variables: dict[str, str] | None = None, model_serving_container_ports: Sequence[int] | None = None, model_description: str | None = None, model_instance_schema_uri: str | None = None, model_parameters_schema_uri: str | None = None, model_prediction_schema_uri: str | None = None, parent_model: str | None = None, is_default_version: bool | None = None, model_version_aliases: list[str] | None = None, model_version_description: str | None = None, labels: dict[str, str] | None = None, training_encryption_spec_key_name: str | None = None, model_encryption_spec_key_name: str | None = None, staging_bucket: str | None = None, # RUN dataset: None | ( datasets.ImageDataset | datasets.TabularDataset | datasets.TextDataset | datasets.VideoDataset ) = None, annotation_schema_uri: str | None = None, model_display_name: str | None = None, model_labels: dict[str, str] | None = None, base_output_dir: str | None = None, service_account: str | None = None, network: str | None = None, bigquery_destination: str | None = None, args: list[str | float | int] | None = None, environment_variables: dict[str, str] | None = None, replica_count: int = 1, machine_type: str = "n1-standard-4", accelerator_type: str = "ACCELERATOR_TYPE_UNSPECIFIED", accelerator_count: int = 0, boot_disk_type: str = "pd-ssd", boot_disk_size_gb: int = 100, training_fraction_split: float | None = None, validation_fraction_split: float | None = None, test_fraction_split: float | None = None, training_filter_split: str | None = None, validation_filter_split: str | None = None, test_filter_split: str | None = None, predefined_split_column_name: str | None = None, timestamp_split_column_name: str | None = None, tensorboard: str | None = None, sync=True, psc_interface_config: PscInterfaceConfig | None = None, ) -> tuple[models.Model | None, str, str]: """ Create Custom Container Training Job. :param display_name: Required. The user-defined name of this TrainingPipeline. :param command: The command to be invoked when the container is started. It overrides the entrypoint instruction in Dockerfile when provided :param container_uri: Required: Uri of the training container image in the GCR. :param model_serving_container_image_uri: If the training produces a managed Vertex AI Model, the URI of the Model serving container suitable for serving the model produced by the training script. :param model_serving_container_predict_route: If the training produces a managed Vertex AI Model, An HTTP path to send prediction requests to the container, and which must be supported by it. If not specified a default HTTP path will be used by Vertex AI. :param model_serving_container_health_route: If the training produces a managed Vertex AI Model, an HTTP path to send health check requests to the container, and which must be supported by it. If not specified a standard HTTP path will be used by AI Platform. :param model_serving_container_command: The command with which the container is run. Not executed within a shell. The Docker image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. :param model_serving_container_args: The arguments to the command. The Docker image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. :param model_serving_container_environment_variables: The environment variables that are to be present in the container. Should be a dictionary where keys are environment variable names and values are environment variable values for those names. :param model_serving_container_ports: Declaration of ports that are exposed by the container. This field is primarily informational, it gives Vertex AI information about the network connections the container uses. Listing or not a port here has no impact on whether the port is actually exposed, any port listening on the default "0.0.0.0" address inside a container will be accessible from the network. :param model_description: The description of the Model. :param model_instance_schema_uri: Optional. Points to a YAML file stored on Google Cloud Storage describing the format of a single instance, which are used in ``PredictRequest.instances``, ``ExplainRequest.instances`` and ``BatchPredictionJob.input_config``. The schema is defined as an OpenAPI 3.0.2 `Schema Object <https://tinyurl.com/y538mdwt#schema-object>`__. AutoML Models always have this field populated by AI Platform. Note: The URI given on output will be immutable and probably different, including the URI scheme, than the one given on input. The output URI will point to a location where the user only has a read access. :param model_parameters_schema_uri: Optional. Points to a YAML file stored on Google Cloud Storage describing the parameters of prediction and explanation via ``PredictRequest.parameters``, ``ExplainRequest.parameters`` and ``BatchPredictionJob.model_parameters``. The schema is defined as an OpenAPI 3.0.2 `Schema Object <https://tinyurl.com/y538mdwt#schema-object>`__. AutoML Models always have this field populated by AI Platform, if no parameters are supported it is set to an empty string. Note: The URI given on output will be immutable and probably different, including the URI scheme, than the one given on input. The output URI will point to a location where the user only has a read access. :param model_prediction_schema_uri: Optional. Points to a YAML file stored on Google Cloud Storage describing the format of a single prediction produced by this Model, which are returned via ``PredictResponse.predictions``, ``ExplainResponse.explanations``, and ``BatchPredictionJob.output_config``. The schema is defined as an OpenAPI 3.0.2 `Schema Object <https://tinyurl.com/y538mdwt#schema-object>`__. AutoML Models always have this field populated by AI Platform. Note: The URI given on output will be immutable and probably different, including the URI scheme, than the one given on input. The output URI will point to a location where the user only has a read access. :param parent_model: Optional. The resource name or model ID of an existing model. The new model uploaded by this job will be a version of `parent_model`. Only set this field when training a new version of an existing model. :param is_default_version: Optional. When set to True, the newly uploaded model version will automatically have alias "default" included. Subsequent uses of the model produced by this job without a version specified will use this "default" version. When set to False, the "default" alias will not be moved. Actions targeting the model version produced by this job will need to specifically reference this version by ID or alias. New model uploads, i.e. version 1, will always be "default" aliased. :param model_version_aliases: Optional. User provided version aliases so that the model version uploaded by this job can be referenced via alias instead of auto-generated version ID. A default version alias will be created for the first version of the model. The format is [a-z][a-zA-Z0-9-]{0,126}[a-z0-9] :param model_version_description: Optional. The description of the model version being uploaded by this job. :param project_id: Project to run training in. :param region: Location to run training in. :param labels: Optional. The labels with user-defined metadata to organize TrainingPipelines. Label keys and values can be no longer than 64 characters, can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. :param training_encryption_spec_key_name: Optional. The Cloud KMS resource identifier of the customer managed encryption key used to protect the training pipeline. Has the form: ``projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key``. The key needs to be in the same region as where the compute resource is created. If set, this TrainingPipeline will be secured by this key. Note: Model trained by this TrainingPipeline is also secured by this key if ``model_to_upload`` is not set separately. :param model_encryption_spec_key_name: Optional. The Cloud KMS resource identifier of the customer managed encryption key used to protect the model. Has the form: ``projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key``. The key needs to be in the same region as where the compute resource is created. If set, the trained Model will be secured by this key. :param staging_bucket: Bucket used to stage source and training artifacts. :param dataset: Vertex AI to fit this training against. :param annotation_schema_uri: Google Cloud Storage URI points to a YAML file describing annotation schema. The schema is defined as an OpenAPI 3.0.2 [Schema Object] (https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#schema-object) Only Annotations that both match this schema and belong to DataItems not ignored by the split method are used in respectively training, validation or test role, depending on the role of the DataItem they are on. When used in conjunction with ``annotations_filter``, the Annotations used for training are filtered by both ``annotations_filter`` and ``annotation_schema_uri``. :param model_display_name: If the script produces a managed Vertex AI Model. The display name of the Model. The name can be up to 128 characters long and can be consist of any UTF-8 characters. If not provided upon creation, the job's display_name is used. :param model_labels: Optional. The labels with user-defined metadata to organize your Models. Label keys and values can be no longer than 64 characters, can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. :param base_output_dir: GCS output directory of job. If not provided a timestamped directory in the staging directory will be used. Vertex AI sets the following environment variables when it runs your training code: - AIP_MODEL_DIR: a Cloud Storage URI of a directory intended for saving model artifacts, i.e. <base_output_dir>/model/ - AIP_CHECKPOINT_DIR: a Cloud Storage URI of a directory intended for saving checkpoints, i.e. <base_output_dir>/checkpoints/ - AIP_TENSORBOARD_LOG_DIR: a Cloud Storage URI of a directory intended for saving TensorBoard logs, i.e. <base_output_dir>/logs/ :param service_account: Specifies the service account for workload run-as account. Users submitting jobs must have act-as permission on this run-as account. :param network: The full name of the Compute Engine network to which the job should be peered. Private services access must already be configured for the network. If left unspecified, the job is not peered with any network. :param bigquery_destination: Provide this field if `dataset` is a BiqQuery dataset. The BigQuery project location where the training data is to be written to. In the given project a new dataset is created with name ``dataset_<dataset-id>_<annotation-type>_<timestamp-of-training-call>`` where timestamp is in YYYY_MM_DDThh_mm_ss_sssZ format. All training input data will be written into that dataset. In the dataset three tables will be created, ``training``, ``validation`` and ``test``. - AIP_DATA_FORMAT = "bigquery". - AIP_TRAINING_DATA_URI ="bigquery_destination.dataset_*.training" - AIP_VALIDATION_DATA_URI = "bigquery_destination.dataset_*.validation" - AIP_TEST_DATA_URI = "bigquery_destination.dataset_*.test" :param args: Command line arguments to be passed to the Python script. :param environment_variables: Environment variables to be passed to the container. Should be a dictionary where keys are environment variable names and values are environment variable values for those names. At most 10 environment variables can be specified. The Name of the environment variable must be unique. :param replica_count: The number of worker replicas. If replica count = 1 then one chief replica will be provisioned. If replica_count > 1 the remainder will be provisioned as a worker replica pool. :param machine_type: The type of machine to use for training. :param accelerator_type: Hardware accelerator type. One of ACCELERATOR_TYPE_UNSPECIFIED, NVIDIA_TESLA_K80, NVIDIA_TESLA_P100, NVIDIA_TESLA_V100, NVIDIA_TESLA_P4, NVIDIA_TESLA_T4 :param accelerator_count: The number of accelerators to attach to a worker replica. :param boot_disk_type: Type of the boot disk, default is `pd-ssd`. Valid values: `pd-ssd` (Persistent Disk Solid State Drive) or `pd-standard` (Persistent Disk Hard Disk Drive). :param boot_disk_size_gb: Size in GB of the boot disk, default is 100GB. boot disk size must be within the range of [100, 64000]. :param training_fraction_split: Optional. The fraction of the input data that is to be used to train the Model. This is ignored if Dataset is not provided. :param validation_fraction_split: Optional. The fraction of the input data that is to be used to validate the Model. This is ignored if Dataset is not provided. :param test_fraction_split: Optional. The fraction of the input data that is to be used to evaluate the Model. This is ignored if Dataset is not provided. :param training_filter_split: Optional. A filter on DataItems of the Dataset. DataItems that match this filter are used to train the Model. A filter with same syntax as the one used in DatasetService.ListDataItems may be used. If a single DataItem is matched by more than one of the FilterSplit filters, then it is assigned to the first set that applies to it in the training, validation, test order. This is ignored if Dataset is not provided. :param validation_filter_split: Optional. A filter on DataItems of the Dataset. DataItems that match this filter are used to validate the Model. A filter with same syntax as the one used in DatasetService.ListDataItems may be used. If a single DataItem is matched by more than one of the FilterSplit filters, then it is assigned to the first set that applies to it in the training, validation, test order. This is ignored if Dataset is not provided. :param test_filter_split: Optional. A filter on DataItems of the Dataset. DataItems that match this filter are used to test the Model. A filter with same syntax as the one used in DatasetService.ListDataItems may be used. If a single DataItem is matched by more than one of the FilterSplit filters, then it is assigned to the first set that applies to it in the training, validation, test order. This is ignored if Dataset is not provided. :param predefined_split_column_name: Optional. The key is a name of one of the Dataset's data columns. The value of the key (either the label's value or value in the column) must be one of {``training``, ``validation``, ``test``}, and it defines to which set the given piece of data is assigned. If for a piece of data the key is not present or has an invalid value, that piece is ignored by the pipeline. Supported only for tabular and time series Datasets. :param timestamp_split_column_name: Optional. The key is a name of one of the Dataset's data columns. The value of the key values of the key (the values in the column) must be in RFC 3339 `date-time` format, where `time-offset` = `"Z"` (e.g. 1985-04-12T23:20:50.52Z). If for a piece of data the key is not present or has an invalid value, that piece is ignored by the pipeline. Supported only for tabular and time series Datasets. :param tensorboard: Optional. The name of a Vertex AI resource to which this CustomJob will upload logs. Format: ``projects/{project}/locations/{location}/tensorboards/{tensorboard}`` For more information on configuring your service account please visit: https://cloud.google.com/vertex-ai/docs/experiments/tensorboard-training :param sync: Whether to execute the AI Platform job synchronously. If False, this method will be executed in concurrent Future and any downstream object will be immediately returned and synced when the Future has completed. :param psc_interface_config: Optional. Configuration for Private Service Connect interface used for training. """ self._job = self.get_custom_container_training_job( project=project_id, location=region, display_name=display_name, container_uri=container_uri, command=command, model_serving_container_image_uri=model_serving_container_image_uri, model_serving_container_predict_route=model_serving_container_predict_route, model_serving_container_health_route=model_serving_container_health_route, model_serving_container_command=model_serving_container_command, model_serving_container_args=model_serving_container_args, model_serving_container_environment_variables=model_serving_container_environment_variables, model_serving_container_ports=model_serving_container_ports, model_description=model_description, model_instance_schema_uri=model_instance_schema_uri, model_parameters_schema_uri=model_parameters_schema_uri, model_prediction_schema_uri=model_prediction_schema_uri, labels=labels, training_encryption_spec_key_name=training_encryption_spec_key_name, model_encryption_spec_key_name=model_encryption_spec_key_name, staging_bucket=staging_bucket, ) if not self._job: raise AirflowException("CustomJob was not created") model, training_id, custom_job_id = self._run_job( job=self._job, dataset=dataset, annotation_schema_uri=annotation_schema_uri, model_display_name=model_display_name, model_labels=model_labels, base_output_dir=base_output_dir, service_account=service_account, network=network, bigquery_destination=bigquery_destination, args=args, environment_variables=environment_variables, replica_count=replica_count, machine_type=machine_type, accelerator_type=accelerator_type, accelerator_count=accelerator_count, boot_disk_type=boot_disk_type, boot_disk_size_gb=boot_disk_size_gb, training_fraction_split=training_fraction_split, validation_fraction_split=validation_fraction_split, test_fraction_split=test_fraction_split, training_filter_split=training_filter_split, validation_filter_split=validation_filter_split, test_filter_split=test_filter_split, predefined_split_column_name=predefined_split_column_name, timestamp_split_column_name=timestamp_split_column_name, tensorboard=tensorboard, sync=sync, parent_model=parent_model, is_default_version=is_default_version, model_version_aliases=model_version_aliases, model_version_description=model_version_description, psc_interface_config=psc_interface_config, ) return model, training_id, custom_job_id @GoogleBaseHook.fallback_to_default_project_id def create_custom_python_package_training_job( self, project_id: str, region: str, display_name: str, python_package_gcs_uri: str, python_module_name: str, container_uri: str, model_serving_container_image_uri: str | None = None, model_serving_container_predict_route: str | None = None, model_serving_container_health_route: str | None = None, model_serving_container_command: Sequence[str] | None = None, model_serving_container_args: Sequence[str] | None = None, model_serving_container_environment_variables: dict[str, str] | None = None, model_serving_container_ports: Sequence[int] | None = None, model_description: str | None = None, model_instance_schema_uri: str | None = None, model_parameters_schema_uri: str | None = None, model_prediction_schema_uri: str | None = None, labels: dict[str, str] | None = None, training_encryption_spec_key_name: str | None = None, model_encryption_spec_key_name: str | None = None, staging_bucket: str | None = None, # RUN dataset: None | ( datasets.ImageDataset | datasets.TabularDataset | datasets.TextDataset | datasets.VideoDataset ) = None, annotation_schema_uri: str | None = None, model_display_name: str | None = None, model_labels: dict[str, str] | None = None, base_output_dir: str | None = None, service_account: str | None = None, network: str | None = None, bigquery_destination: str | None = None, args: list[str | float | int] | None = None, environment_variables: dict[str, str] | None = None, replica_count: int = 1, machine_type: str = "n1-standard-4", accelerator_type: str = "ACCELERATOR_TYPE_UNSPECIFIED", accelerator_count: int = 0, boot_disk_type: str = "pd-ssd", boot_disk_size_gb: int = 100, training_fraction_split: float | None = None, validation_fraction_split: float | None = None, test_fraction_split: float | None = None, training_filter_split: str | None = None, validation_filter_split: str | None = None, test_filter_split: str | None = None, predefined_split_column_name: str | None = None, timestamp_split_column_name: str | None = None, tensorboard: str | None = None, parent_model: str | None = None, is_default_version: bool | None = None, model_version_aliases: list[str] | None = None, model_version_description: str | None = None, sync=True, psc_interface_config: PscInterfaceConfig | None = None, ) -> tuple[models.Model | None, str, str]: """ Create Custom Python Package Training Job. :param display_name: Required. The user-defined name of this TrainingPipeline. :param python_package_gcs_uri: Required: GCS location of the training python package. :param python_module_name: Required: The module name of the training python package. :param container_uri: Required: Uri of the training container image in the GCR. :param model_serving_container_image_uri: If the training produces a managed Vertex AI Model, the URI of the Model serving container suitable for serving the model produced by the training script. :param model_serving_container_predict_route: If the training produces a managed Vertex AI Model, An HTTP path to send prediction requests to the container, and which must be supported by it. If not specified a default HTTP path will be used by Vertex AI. :param model_serving_container_health_route: If the training produces a managed Vertex AI Model, an HTTP path to send health check requests to the container, and which must be supported by it. If not specified a standard HTTP path will be used by AI Platform. :param model_serving_container_command: The command with which the container is run. Not executed within a shell. The Docker image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. :param model_serving_container_args: The arguments to the command. The Docker image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. :param model_serving_container_environment_variables: The environment variables that are to be present in the container. Should be a dictionary where keys are environment variable names and values are environment variable values for those names. :param model_serving_container_ports: Declaration of ports that are exposed by the container. This field is primarily informational, it gives Vertex AI information about the network connections the container uses. Listing or not a port here has no impact on whether the port is actually exposed, any port listening on the default "0.0.0.0" address inside a container will be accessible from the network. :param model_description: The description of the Model. :param model_instance_schema_uri: Optional. Points to a YAML file stored on Google Cloud Storage describing the format of a single instance, which are used in ``PredictRequest.instances``, ``ExplainRequest.instances`` and ``BatchPredictionJob.input_config``. The schema is defined as an OpenAPI 3.0.2 `Schema Object <https://tinyurl.com/y538mdwt#schema-object>`__. AutoML Models always have this field populated by AI Platform. Note: The URI given on output will be immutable and probably different, including the URI scheme, than the one given on input. The output URI will point to a location where the user only has a read access. :param model_parameters_schema_uri: Optional. Points to a YAML file stored on Google Cloud Storage describing the parameters of prediction and explanation via ``PredictRequest.parameters``, ``ExplainRequest.parameters`` and ``BatchPredictionJob.model_parameters``. The schema is defined as an OpenAPI 3.0.2 `Schema Object <https://tinyurl.com/y538mdwt#schema-object>`__. AutoML Models always have this field populated by AI Platform, if no parameters are supported it is set to an empty string. Note: The URI given on output will be immutable and probably different, including the URI scheme, than the one given on input. The output URI will point to a location where the user only has a read access. :param model_prediction_schema_uri: Optional. Points to a YAML file stored on Google Cloud Storage describing the format of a single prediction produced by this Model, which are returned via ``PredictResponse.predictions``, ``ExplainResponse.explanations``, and ``BatchPredictionJob.output_config``. The schema is defined as an OpenAPI 3.0.2 `Schema Object <https://tinyurl.com/y538mdwt#schema-object>`__. AutoML Models always have this field populated by AI Platform. Note: The URI given on output will be immutable and probably different, including the URI scheme, than the one given on input. The output URI will point to a location where the user only has a read access. :param parent_model: Optional. The resource name or model ID of an existing model. The new model uploaded by this job will be a version of `parent_model`. Only set this field when training a new version of an existing model. :param is_default_version: Optional. When set to True, the newly uploaded model version will automatically have alias "default" included. Subsequent uses of the model produced by this job without a version specified will use this "default" version. When set to False, the "default" alias will not be moved. Actions targeting the model version produced by this job will need to specifically reference this version by ID or alias. New model uploads, i.e. version 1, will always be "default" aliased. :param model_version_aliases: Optional. User provided version aliases so that the model version uploaded by this job can be referenced via alias instead of auto-generated version ID. A default version alias will be created for the first version of the model. The format is [a-z][a-zA-Z0-9-]{0,126}[a-z0-9] :param model_version_description: Optional. The description of the model version being uploaded by this job. :param project_id: Project to run training in. :param region: Location to run training in. :param labels: Optional. The labels with user-defined metadata to organize TrainingPipelines. Label keys and values can be no longer than 64 characters, can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. :param training_encryption_spec_key_name: Optional. The Cloud KMS resource identifier of the customer managed encryption key used to protect the training pipeline. Has the form: ``projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key``. The key needs to be in the same region as where the compute resource is created. If set, this TrainingPipeline will be secured by this key. Note: Model trained by this TrainingPipeline is also secured by this key if ``model_to_upload`` is not set separately. :param model_encryption_spec_key_name: Optional. The Cloud KMS resource identifier of the customer managed encryption key used to protect the model. Has the form: ``projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key``. The key needs to be in the same region as where the compute resource is created. If set, the trained Model will be secured by this key. :param staging_bucket: Bucket used to stage source and training artifacts. :param dataset: Vertex AI to fit this training against. :param annotation_schema_uri: Google Cloud Storage URI points to a YAML file describing annotation schema. The schema is defined as an OpenAPI 3.0.2 [Schema Object] (https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#schema-object) Only Annotations that both match this schema and belong to DataItems not ignored by the split method are used in respectively training, validation or test role, depending on the role of the DataItem they are on. When used in conjunction with ``annotations_filter``, the Annotations used for training are filtered by both ``annotations_filter`` and ``annotation_schema_uri``. :param model_display_name: If the script produces a managed Vertex AI Model. The display name of the Model. The name can be up to 128 characters long and can be consist of any UTF-8 characters. If not provided upon creation, the job's display_name is used. :param model_labels: Optional. The labels with user-defined metadata to organize your Models. Label keys and values can be no longer than 64 characters, can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. :param base_output_dir: GCS output directory of job. If not provided a timestamped directory in the staging directory will be used. Vertex AI sets the following environment variables when it runs your training code: - AIP_MODEL_DIR: a Cloud Storage URI of a directory intended for saving model artifacts, i.e. <base_output_dir>/model/ - AIP_CHECKPOINT_DIR: a Cloud Storage URI of a directory intended for saving checkpoints, i.e. <base_output_dir>/checkpoints/ - AIP_TENSORBOARD_LOG_DIR: a Cloud Storage URI of a directory intended for saving TensorBoard logs, i.e. <base_output_dir>/logs/ :param service_account: Specifies the service account for workload run-as account. Users submitting jobs must have act-as permission on this run-as account. :param network: The full name of the Compute Engine network to which the job should be peered. Private services access must already be configured for the network. If left unspecified, the job is not peered with any network. :param bigquery_destination: Provide this field if `dataset` is a BiqQuery dataset. The BigQuery project location where the training data is to be written to. In the given project a new dataset is created with name ``dataset_<dataset-id>_<annotation-type>_<timestamp-of-training-call>`` where timestamp is in YYYY_MM_DDThh_mm_ss_sssZ format. All training input data will be written into that dataset. In the dataset three tables will be created, ``training``, ``validation`` and ``test``. - AIP_DATA_FORMAT = "bigquery". - AIP_TRAINING_DATA_URI ="bigquery_destination.dataset_*.training" - AIP_VALIDATION_DATA_URI = "bigquery_destination.dataset_*.validation" - AIP_TEST_DATA_URI = "bigquery_destination.dataset_*.test" :param args: Command line arguments to be passed to the Python script. :param environment_variables: Environment variables to be passed to the container. Should be a dictionary where keys are environment variable names and values are environment variable values for those names. At most 10 environment variables can be specified. The Name of the environment variable must be unique. :param replica_count: The number of worker replicas. If replica count = 1 then one chief replica will be provisioned. If replica_count > 1 the remainder will be provisioned as a worker replica pool. :param machine_type: The type of machine to use for training. :param accelerator_type: Hardware accelerator type. One of ACCELERATOR_TYPE_UNSPECIFIED, NVIDIA_TESLA_K80, NVIDIA_TESLA_P100, NVIDIA_TESLA_V100, NVIDIA_TESLA_P4, NVIDIA_TESLA_T4 :param accelerator_count: The number of accelerators to attach to a worker replica. :param boot_disk_type: Type of the boot disk, default is `pd-ssd`. Valid values: `pd-ssd` (Persistent Disk Solid State Drive) or `pd-standard` (Persistent Disk Hard Disk Drive). :param boot_disk_size_gb: Size in GB of the boot disk, default is 100GB. boot disk size must be within the range of [100, 64000]. :param training_fraction_split: Optional. The fraction of the input data that is to be used to train the Model. This is ignored if Dataset is not provided. :param validation_fraction_split: Optional. The fraction of the input data that is to be used to validate the Model. This is ignored if Dataset is not provided. :param test_fraction_split: Optional. The fraction of the input data that is to be used to evaluate the Model. This is ignored if Dataset is not provided. :param training_filter_split: Optional. A filter on DataItems of the Dataset. DataItems that match this filter are used to train the Model. A filter with same syntax as the one used in DatasetService.ListDataItems may be used. If a single DataItem is matched by more than one of the FilterSplit filters, then it is assigned to the first set that applies to it in the training, validation, test order. This is ignored if Dataset is not provided. :param validation_filter_split: Optional. A filter on DataItems of the Dataset. DataItems that match this filter are used to validate the Model. A filter with same syntax as the one used in DatasetService.ListDataItems may be used. If a single DataItem is matched by more than one of the FilterSplit filters, then it is assigned to the first set that applies to it in the training, validation, test order. This is ignored if Dataset is not provided. :param test_filter_split: Optional. A filter on DataItems of the Dataset. DataItems that match this filter are used to test the Model. A filter with same syntax as the one used in DatasetService.ListDataItems may be used. If a single DataItem is matched by more than one of the FilterSplit filters, then it is assigned to the first set that applies to it in the training, validation, test order. This is ignored if Dataset is not provided. :param predefined_split_column_name: Optional. The key is a name of one of the Dataset's data columns. The value of the key (either the label's value or value in the column) must be one of {``training``, ``validation``, ``test``}, and it defines to which set the given piece of data is assigned. If for a piece of data the key is not present or has an invalid value, that piece is ignored by the pipeline. Supported only for tabular and time series Datasets. :param timestamp_split_column_name: Optional. The key is a name of one of the Dataset's data columns. The value of the key values of the key (the values in the column) must be in RFC 3339 `date-time` format, where `time-offset` = `"Z"` (e.g. 1985-04-12T23:20:50.52Z). If for a piece of data the key is not present or has an invalid value, that piece is ignored by the pipeline. Supported only for tabular and time series Datasets. :param tensorboard: Optional. The name of a Vertex AI resource to which this CustomJob will upload logs. Format: ``projects/{project}/locations/{location}/tensorboards/{tensorboard}`` For more information on configuring your service account please visit: https://cloud.google.com/vertex-ai/docs/experiments/tensorboard-training :param sync: Whether to execute the AI Platform job synchronously. If False, this method will be executed in concurrent Future and any downstream object will be immediately returned and synced when the Future has completed. :param psc_interface_config: Optional. Configuration for Private Service Connect interface used for training. """ self._job = self.get_custom_python_package_training_job( project=project_id, location=region, display_name=display_name, python_package_gcs_uri=python_package_gcs_uri, python_module_name=python_module_name, container_uri=container_uri, model_serving_container_image_uri=model_serving_container_image_uri, model_serving_container_predict_route=model_serving_container_predict_route, model_serving_container_health_route=model_serving_container_health_route, model_serving_container_command=model_serving_container_command, model_serving_container_args=model_serving_container_args, model_serving_container_environment_variables=model_serving_container_environment_variables, model_serving_container_ports=model_serving_container_ports, model_description=model_description, model_instance_schema_uri=model_instance_schema_uri, model_parameters_schema_uri=model_parameters_schema_uri, model_prediction_schema_uri=model_prediction_schema_uri, labels=labels, training_encryption_spec_key_name=training_encryption_spec_key_name, model_encryption_spec_key_name=model_encryption_spec_key_name, staging_bucket=staging_bucket, ) if not self._job: raise AirflowException("CustomJob was not created") model, training_id, custom_job_id = self._run_job( job=self._job, dataset=dataset, annotation_schema_uri=annotation_schema_uri, model_display_name=model_display_name, model_labels=model_labels, base_output_dir=base_output_dir, service_account=service_account, network=network, bigquery_destination=bigquery_destination, args=args, environment_variables=environment_variables, replica_count=replica_count, machine_type=machine_type, accelerator_type=accelerator_type, accelerator_count=accelerator_count, boot_disk_type=boot_disk_type, boot_disk_size_gb=boot_disk_size_gb, training_fraction_split=training_fraction_split, validation_fraction_split=validation_fraction_split, test_fraction_split=test_fraction_split, training_filter_split=training_filter_split, validation_filter_split=validation_filter_split, test_filter_split=test_filter_split, predefined_split_column_name=predefined_split_column_name, timestamp_split_column_name=timestamp_split_column_name, tensorboard=tensorboard, sync=sync, parent_model=parent_model, is_default_version=is_default_version, model_version_aliases=model_version_aliases, model_version_description=model_version_description, psc_interface_config=psc_interface_config, ) return model, training_id, custom_job_id @GoogleBaseHook.fallback_to_default_project_id def create_custom_training_job( self, project_id: str, region: str, display_name: str, script_path: str, container_uri: str, requirements: Sequence[str] | None = None, model_serving_container_image_uri: str | None = None, model_serving_container_predict_route: str | None = None, model_serving_container_health_route: str | None = None, model_serving_container_command: Sequence[str] | None = None, model_serving_container_args: Sequence[str] | None = None, model_serving_container_environment_variables: dict[str, str] | None = None, model_serving_container_ports: Sequence[int] | None = None, model_description: str | None = None, model_instance_schema_uri: str | None = None, model_parameters_schema_uri: str | None = None, model_prediction_schema_uri: str | None = None, parent_model: str | None = None, is_default_version: bool | None = None, model_version_aliases: list[str] | None = None, model_version_description: str | None = None, labels: dict[str, str] | None = None, training_encryption_spec_key_name: str | None = None, model_encryption_spec_key_name: str | None = None, staging_bucket: str | None = None, # RUN dataset: None | ( datasets.ImageDataset | datasets.TabularDataset | datasets.TextDataset | datasets.VideoDataset ) = None, annotation_schema_uri: str | None = None, model_display_name: str | None = None, model_labels: dict[str, str] | None = None, base_output_dir: str | None = None, service_account: str | None = None, network: str | None = None, bigquery_destination: str | None = None, args: list[str | float | int] | None = None, environment_variables: dict[str, str] | None = None, replica_count: int = 1, machine_type: str = "n1-standard-4", accelerator_type: str = "ACCELERATOR_TYPE_UNSPECIFIED", accelerator_count: int = 0, boot_disk_type: str = "pd-ssd", boot_disk_size_gb: int = 100, training_fraction_split: float | None = None, validation_fraction_split: float | None = None, test_fraction_split: float | None = None, training_filter_split: str | None = None, validation_filter_split: str | None = None, test_filter_split: str | None = None, predefined_split_column_name: str | None = None, timestamp_split_column_name: str | None = None, tensorboard: str | None = None, sync=True, psc_interface_config: PscInterfaceConfig | None = None, ) -> tuple[models.Model | None, str, str]: """ Create Custom Training Job. :param display_name: Required. The user-defined name of this TrainingPipeline. :param script_path: Required. Local path to training script. :param container_uri: Required: Uri of the training container image in the GCR. :param requirements: List of python packages dependencies of script. :param model_serving_container_image_uri: If the training produces a managed Vertex AI Model, the URI of the Model serving container suitable for serving the model produced by the training script. :param model_serving_container_predict_route: If the training produces a managed Vertex AI Model, An HTTP path to send prediction requests to the container, and which must be supported by it. If not specified a default HTTP path will be used by Vertex AI. :param model_serving_container_health_route: If the training produces a managed Vertex AI Model, an HTTP path to send health check requests to the container, and which must be supported by it. If not specified a standard HTTP path will be used by AI Platform. :param model_serving_container_command: The command with which the container is run. Not executed within a shell. The Docker image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. :param model_serving_container_args: The arguments to the command. The Docker image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. :param model_serving_container_environment_variables: The environment variables that are to be present in the container. Should be a dictionary where keys are environment variable names and values are environment variable values for those names. :param model_serving_container_ports: Declaration of ports that are exposed by the container. This field is primarily informational, it gives Vertex AI information about the network connections the container uses. Listing or not a port here has no impact on whether the port is actually exposed, any port listening on the default "0.0.0.0" address inside a container will be accessible from the network. :param model_description: The description of the Model. :param model_instance_schema_uri: Optional. Points to a YAML file stored on Google Cloud Storage describing the format of a single instance, which are used in ``PredictRequest.instances``, ``ExplainRequest.instances`` and ``BatchPredictionJob.input_config``. The schema is defined as an OpenAPI 3.0.2 `Schema Object <https://tinyurl.com/y538mdwt#schema-object>`__. AutoML Models always have this field populated by AI Platform. Note: The URI given on output will be immutable and probably different, including the URI scheme, than the one given on input. The output URI will point to a location where the user only has a read access. :param model_parameters_schema_uri: Optional. Points to a YAML file stored on Google Cloud Storage describing the parameters of prediction and explanation via ``PredictRequest.parameters``, ``ExplainRequest.parameters`` and ``BatchPredictionJob.model_parameters``. The schema is defined as an OpenAPI 3.0.2 `Schema Object <https://tinyurl.com/y538mdwt#schema-object>`__. AutoML Models always have this field populated by AI Platform, if no parameters are supported it is set to an empty string. Note: The URI given on output will be immutable and probably different, including the URI scheme, than the one given on input. The output URI will point to a location where the user only has a read access. :param model_prediction_schema_uri: Optional. Points to a YAML file stored on Google Cloud Storage describing the format of a single prediction produced by this Model, which are returned via ``PredictResponse.predictions``, ``ExplainResponse.explanations``, and ``BatchPredictionJob.output_config``. The schema is defined as an OpenAPI 3.0.2 `Schema Object <https://tinyurl.com/y538mdwt#schema-object>`__. AutoML Models always have this field populated by AI Platform. Note: The URI given on output will be immutable and probably different, including the URI scheme, than the one given on input. The output URI will point to a location where the user only has a read access. :param parent_model: Optional. The resource name or model ID of an existing model. The new model uploaded by this job will be a version of `parent_model`. Only set this field when training a new version of an existing model. :param is_default_version: Optional. When set to True, the newly uploaded model version will automatically have alias "default" included. Subsequent uses of the model produced by this job without a version specified will use this "default" version. When set to False, the "default" alias will not be moved. Actions targeting the model version produced by this job will need to specifically reference this version by ID or alias. New model uploads, i.e. version 1, will always be "default" aliased. :param model_version_aliases: Optional. User provided version aliases so that the model version uploaded by this job can be referenced via alias instead of auto-generated version ID. A default version alias will be created for the first version of the model. The format is [a-z][a-zA-Z0-9-]{0,126}[a-z0-9] :param model_version_description: Optional. The description of the model version being uploaded by this job. :param project_id: Project to run training in. :param region: Location to run training in. :param labels: Optional. The labels with user-defined metadata to organize TrainingPipelines. Label keys and values can be no longer than 64 characters, can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. :param training_encryption_spec_key_name: Optional. The Cloud KMS resource identifier of the customer managed encryption key used to protect the training pipeline. Has the form: ``projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key``. The key needs to be in the same region as where the compute resource is created. If set, this TrainingPipeline will be secured by this key. Note: Model trained by this TrainingPipeline is also secured by this key if ``model_to_upload`` is not set separately. :param model_encryption_spec_key_name: Optional. The Cloud KMS resource identifier of the customer managed encryption key used to protect the model. Has the form: ``projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key``. The key needs to be in the same region as where the compute resource is created. If set, the trained Model will be secured by this key. :param staging_bucket: Bucket used to stage source and training artifacts. :param dataset: Vertex AI to fit this training against. :param annotation_schema_uri: Google Cloud Storage URI points to a YAML file describing annotation schema. The schema is defined as an OpenAPI 3.0.2 [Schema Object] (https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#schema-object) Only Annotations that both match this schema and belong to DataItems not ignored by the split method are used in respectively training, validation or test role, depending on the role of the DataItem they are on. When used in conjunction with ``annotations_filter``, the Annotations used for training are filtered by both ``annotations_filter`` and ``annotation_schema_uri``. :param model_display_name: If the script produces a managed Vertex AI Model. The display name of the Model. The name can be up to 128 characters long and can be consist of any UTF-8 characters. If not provided upon creation, the job's display_name is used. :param model_labels: Optional. The labels with user-defined metadata to organize your Models. Label keys and values can be no longer than 64 characters, can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. :param base_output_dir: GCS output directory of job. If not provided a timestamped directory in the staging directory will be used. Vertex AI sets the following environment variables when it runs your training code: - AIP_MODEL_DIR: a Cloud Storage URI of a directory intended for saving model artifacts, i.e. <base_output_dir>/model/ - AIP_CHECKPOINT_DIR: a Cloud Storage URI of a directory intended for saving checkpoints, i.e. <base_output_dir>/checkpoints/ - AIP_TENSORBOARD_LOG_DIR: a Cloud Storage URI of a directory intended for saving TensorBoard logs, i.e. <base_output_dir>/logs/ :param service_account: Specifies the service account for workload run-as account. Users submitting jobs must have act-as permission on this run-as account. :param network: The full name of the Compute Engine network to which the job should be peered. Private services access must already be configured for the network. If left unspecified, the job is not peered with any network. :param bigquery_destination: Provide this field if `dataset` is a BiqQuery dataset. The BigQuery project location where the training data is to be written to. In the given project a new dataset is created with name ``dataset_<dataset-id>_<annotation-type>_<timestamp-of-training-call>`` where timestamp is in YYYY_MM_DDThh_mm_ss_sssZ format. All training input data will be written into that dataset. In the dataset three tables will be created, ``training``, ``validation`` and ``test``. - AIP_DATA_FORMAT = "bigquery". - AIP_TRAINING_DATA_URI ="bigquery_destination.dataset_*.training" - AIP_VALIDATION_DATA_URI = "bigquery_destination.dataset_*.validation" - AIP_TEST_DATA_URI = "bigquery_destination.dataset_*.test" :param args: Command line arguments to be passed to the Python script. :param environment_variables: Environment variables to be passed to the container. Should be a dictionary where keys are environment variable names and values are environment variable values for those names. At most 10 environment variables can be specified. The Name of the environment variable must be unique. :param replica_count: The number of worker replicas. If replica count = 1 then one chief replica will be provisioned. If replica_count > 1 the remainder will be provisioned as a worker replica pool. :param machine_type: The type of machine to use for training. :param accelerator_type: Hardware accelerator type. One of ACCELERATOR_TYPE_UNSPECIFIED, NVIDIA_TESLA_K80, NVIDIA_TESLA_P100, NVIDIA_TESLA_V100, NVIDIA_TESLA_P4, NVIDIA_TESLA_T4 :param accelerator_count: The number of accelerators to attach to a worker replica. :param boot_disk_type: Type of the boot disk, default is `pd-ssd`. Valid values: `pd-ssd` (Persistent Disk Solid State Drive) or `pd-standard` (Persistent Disk Hard Disk Drive). :param boot_disk_size_gb: Size in GB of the boot disk, default is 100GB. boot disk size must be within the range of [100, 64000]. :param training_fraction_split: Optional. The fraction of the input data that is to be used to train the Model. This is ignored if Dataset is not provided. :param validation_fraction_split: Optional. The fraction of the input data that is to be used to validate the Model. This is ignored if Dataset is not provided. :param test_fraction_split: Optional. The fraction of the input data that is to be used to evaluate the Model. This is ignored if Dataset is not provided. :param training_filter_split: Optional. A filter on DataItems of the Dataset. DataItems that match this filter are used to train the Model. A filter with same syntax as the one used in DatasetService.ListDataItems may be used. If a single DataItem is matched by more than one of the FilterSplit filters, then it is assigned to the first set that applies to it in the training, validation, test order. This is ignored if Dataset is not provided. :param validation_filter_split: Optional. A filter on DataItems of the Dataset. DataItems that match this filter are used to validate the Model. A filter with same syntax as the one used in DatasetService.ListDataItems may be used. If a single DataItem is matched by more than one of the FilterSplit filters, then it is assigned to the first set that applies to it in the training, validation, test order. This is ignored if Dataset is not provided. :param test_filter_split: Optional. A filter on DataItems of the Dataset. DataItems that match this filter are used to test the Model. A filter with same syntax as the one used in DatasetService.ListDataItems may be used. If a single DataItem is matched by more than one of the FilterSplit filters, then it is assigned to the first set that applies to it in the training, validation, test order. This is ignored if Dataset is not provided. :param predefined_split_column_name: Optional. The key is a name of one of the Dataset's data columns. The value of the key (either the label's value or value in the column) must be one of {``training``, ``validation``, ``test``}, and it defines to which set the given piece of data is assigned. If for a piece of data the key is not present or has an invalid value, that piece is ignored by the pipeline. Supported only for tabular and time series Datasets. :param timestamp_split_column_name: Optional. The key is a name of one of the Dataset's data columns. The value of the key values of the key (the values in the column) must be in RFC 3339 `date-time` format, where `time-offset` = `"Z"` (e.g. 1985-04-12T23:20:50.52Z). If for a piece of data the key is not present or has an invalid value, that piece is ignored by the pipeline. Supported only for tabular and time series Datasets. :param tensorboard: Optional. The name of a Vertex AI resource to which this CustomJob will upload logs. Format: ``projects/{project}/locations/{location}/tensorboards/{tensorboard}`` For more information on configuring your service account please visit: https://cloud.google.com/vertex-ai/docs/experiments/tensorboard-training :param sync: Whether to execute the AI Platform job synchronously. If False, this method will be executed in concurrent Future and any downstream object will be immediately returned and synced when the Future has completed. :param psc_interface_config: Optional. Configuration for Private Service Connect interface used for training. """ self._job = self.get_custom_training_job( project=project_id, location=region, display_name=display_name, script_path=script_path, container_uri=container_uri, requirements=requirements, model_serving_container_image_uri=model_serving_container_image_uri, model_serving_container_predict_route=model_serving_container_predict_route, model_serving_container_health_route=model_serving_container_health_route, model_serving_container_command=model_serving_container_command, model_serving_container_args=model_serving_container_args, model_serving_container_environment_variables=model_serving_container_environment_variables, model_serving_container_ports=model_serving_container_ports, model_description=model_description, model_instance_schema_uri=model_instance_schema_uri, model_parameters_schema_uri=model_parameters_schema_uri, model_prediction_schema_uri=model_prediction_schema_uri, labels=labels, training_encryption_spec_key_name=training_encryption_spec_key_name, model_encryption_spec_key_name=model_encryption_spec_key_name, staging_bucket=staging_bucket, ) if not self._job: raise AirflowException("CustomJob was not created") model, training_id, custom_job_id = self._run_job( job=self._job, dataset=dataset, annotation_schema_uri=annotation_schema_uri, model_display_name=model_display_name, model_labels=model_labels, base_output_dir=base_output_dir, service_account=service_account, network=network, bigquery_destination=bigquery_destination, args=args, environment_variables=environment_variables, replica_count=replica_count, machine_type=machine_type, accelerator_type=accelerator_type, accelerator_count=accelerator_count, boot_disk_type=boot_disk_type, boot_disk_size_gb=boot_disk_size_gb, training_fraction_split=training_fraction_split, validation_fraction_split=validation_fraction_split, test_fraction_split=test_fraction_split, training_filter_split=training_filter_split, validation_filter_split=validation_filter_split, test_filter_split=test_filter_split, predefined_split_column_name=predefined_split_column_name, timestamp_split_column_name=timestamp_split_column_name, tensorboard=tensorboard, sync=sync, parent_model=parent_model, is_default_version=is_default_version, model_version_aliases=model_version_aliases, model_version_description=model_version_description, psc_interface_config=psc_interface_config, ) return model, training_id, custom_job_id @GoogleBaseHook.fallback_to_default_project_id def submit_custom_container_training_job( self, *, project_id: str, region: str, display_name: str, container_uri: str, command: Sequence[str] = (), model_serving_container_image_uri: str | None = None, model_serving_container_predict_route: str | None = None, model_serving_container_health_route: str | None = None, model_serving_container_command: Sequence[str] | None = None, model_serving_container_args: Sequence[str] | None = None, model_serving_container_environment_variables: dict[str, str] | None = None, model_serving_container_ports: Sequence[int] | None = None, model_description: str | None = None, model_instance_schema_uri: str | None = None, model_parameters_schema_uri: str | None = None, model_prediction_schema_uri: str | None = None, parent_model: str | None = None, is_default_version: bool | None = None, model_version_aliases: list[str] | None = None, model_version_description: str | None = None, labels: dict[str, str] | None = None, training_encryption_spec_key_name: str | None = None, model_encryption_spec_key_name: str | None = None, staging_bucket: str | None = None, # RUN dataset: None | ( datasets.ImageDataset | datasets.TabularDataset | datasets.TextDataset | datasets.VideoDataset ) = None, annotation_schema_uri: str | None = None, model_display_name: str | None = None, model_labels: dict[str, str] | None = None, base_output_dir: str | None = None, service_account: str | None = None, network: str | None = None, bigquery_destination: str | None = None, args: list[str | float | int] | None = None, environment_variables: dict[str, str] | None = None, replica_count: int = 1, machine_type: str = "n1-standard-4", accelerator_type: str = "ACCELERATOR_TYPE_UNSPECIFIED", accelerator_count: int = 0, boot_disk_type: str = "pd-ssd", boot_disk_size_gb: int = 100, training_fraction_split: float | None = None, validation_fraction_split: float | None = None, test_fraction_split: float | None = None, training_filter_split: str | None = None, validation_filter_split: str | None = None, test_filter_split: str | None = None, predefined_split_column_name: str | None = None, timestamp_split_column_name: str | None = None, tensorboard: str | None = None, psc_interface_config: PscInterfaceConfig | None = None, ) -> CustomContainerTrainingJob: """ Create and submit a Custom Container Training Job pipeline, then exit without waiting for it to complete. :param display_name: Required. The user-defined name of this TrainingPipeline. :param command: The command to be invoked when the container is started. It overrides the entrypoint instruction in Dockerfile when provided :param container_uri: Required: Uri of the training container image in the GCR. :param model_serving_container_image_uri: If the training produces a managed Vertex AI Model, the URI of the Model serving container suitable for serving the model produced by the training script. :param model_serving_container_predict_route: If the training produces a managed Vertex AI Model, An HTTP path to send prediction requests to the container, and which must be supported by it. If not specified a default HTTP path will be used by Vertex AI. :param model_serving_container_health_route: If the training produces a managed Vertex AI Model, an HTTP path to send health check requests to the container, and which must be supported by it. If not specified a standard HTTP path will be used by AI Platform. :param model_serving_container_command: The command with which the container is run. Not executed within a shell. The Docker image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. :param model_serving_container_args: The arguments to the command. The Docker image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. :param model_serving_container_environment_variables: The environment variables that are to be present in the container. Should be a dictionary where keys are environment variable names and values are environment variable values for those names. :param model_serving_container_ports: Declaration of ports that are exposed by the container. This field is primarily informational, it gives Vertex AI information about the network connections the container uses. Listing or not a port here has no impact on whether the port is actually exposed, any port listening on the default "0.0.0.0" address inside a container will be accessible from the network. :param model_description: The description of the Model. :param model_instance_schema_uri: Optional. Points to a YAML file stored on Google Cloud Storage describing the format of a single instance, which are used in ``PredictRequest.instances``, ``ExplainRequest.instances`` and ``BatchPredictionJob.input_config``. The schema is defined as an OpenAPI 3.0.2 `Schema Object <https://tinyurl.com/y538mdwt#schema-object>`__. AutoML Models always have this field populated by AI Platform. Note: The URI given on output will be immutable and probably different, including the URI scheme, than the one given on input. The output URI will point to a location where the user only has a read access. :param model_parameters_schema_uri: Optional. Points to a YAML file stored on Google Cloud Storage describing the parameters of prediction and explanation via ``PredictRequest.parameters``, ``ExplainRequest.parameters`` and ``BatchPredictionJob.model_parameters``. The schema is defined as an OpenAPI 3.0.2 `Schema Object <https://tinyurl.com/y538mdwt#schema-object>`__. AutoML Models always have this field populated by AI Platform, if no parameters are supported it is set to an empty string. Note: The URI given on output will be immutable and probably different, including the URI scheme, than the one given on input. The output URI will point to a location where the user only has a read access. :param model_prediction_schema_uri: Optional. Points to a YAML file stored on Google Cloud Storage describing the format of a single prediction produced by this Model, which are returned via ``PredictResponse.predictions``, ``ExplainResponse.explanations``, and ``BatchPredictionJob.output_config``. The schema is defined as an OpenAPI 3.0.2 `Schema Object <https://tinyurl.com/y538mdwt#schema-object>`__. AutoML Models always have this field populated by AI Platform. Note: The URI given on output will be immutable and probably different, including the URI scheme, than the one given on input. The output URI will point to a location where the user only has a read access. :param parent_model: Optional. The resource name or model ID of an existing model. The new model uploaded by this job will be a version of `parent_model`. Only set this field when training a new version of an existing model. :param is_default_version: Optional. When set to True, the newly uploaded model version will automatically have alias "default" included. Subsequent uses of the model produced by this job without a version specified will use this "default" version. When set to False, the "default" alias will not be moved. Actions targeting the model version produced by this job will need to specifically reference this version by ID or alias. New model uploads, i.e. version 1, will always be "default" aliased. :param model_version_aliases: Optional. User provided version aliases so that the model version uploaded by this job can be referenced via alias instead of auto-generated version ID. A default version alias will be created for the first version of the model. The format is [a-z][a-zA-Z0-9-]{0,126}[a-z0-9] :param model_version_description: Optional. The description of the model version being uploaded by this job. :param project_id: Project to run training in. :param region: Location to run training in. :param labels: Optional. The labels with user-defined metadata to organize TrainingPipelines. Label keys and values can be no longer than 64 characters, can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. :param training_encryption_spec_key_name: Optional. The Cloud KMS resource identifier of the customer managed encryption key used to protect the training pipeline. Has the form: ``projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key``. The key needs to be in the same region as where the compute resource is created. If set, this TrainingPipeline will be secured by this key. Note: Model trained by this TrainingPipeline is also secured by this key if ``model_to_upload`` is not set separately. :param model_encryption_spec_key_name: Optional. The Cloud KMS resource identifier of the customer managed encryption key used to protect the model. Has the form: ``projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key``. The key needs to be in the same region as where the compute resource is created. If set, the trained Model will be secured by this key. :param staging_bucket: Bucket used to stage source and training artifacts. :param dataset: Vertex AI to fit this training against. :param annotation_schema_uri: Google Cloud Storage URI points to a YAML file describing annotation schema. The schema is defined as an OpenAPI 3.0.2 [Schema Object] (https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#schema-object) Only Annotations that both match this schema and belong to DataItems not ignored by the split method are used in respectively training, validation or test role, depending on the role of the DataItem they are on. When used in conjunction with ``annotations_filter``, the Annotations used for training are filtered by both ``annotations_filter`` and ``annotation_schema_uri``. :param model_display_name: If the script produces a managed Vertex AI Model. The display name of the Model. The name can be up to 128 characters long and can be consist of any UTF-8 characters. If not provided upon creation, the job's display_name is used. :param model_labels: Optional. The labels with user-defined metadata to organize your Models. Label keys and values can be no longer than 64 characters, can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. :param base_output_dir: GCS output directory of job. If not provided a timestamped directory in the staging directory will be used. Vertex AI sets the following environment variables when it runs your training code: - AIP_MODEL_DIR: a Cloud Storage URI of a directory intended for saving model artifacts, i.e. <base_output_dir>/model/ - AIP_CHECKPOINT_DIR: a Cloud Storage URI of a directory intended for saving checkpoints, i.e. <base_output_dir>/checkpoints/ - AIP_TENSORBOARD_LOG_DIR: a Cloud Storage URI of a directory intended for saving TensorBoard logs, i.e. <base_output_dir>/logs/ :param service_account: Specifies the service account for workload run-as account. Users submitting jobs must have act-as permission on this run-as account. :param network: The full name of the Compute Engine network to which the job should be peered. Private services access must already be configured for the network. If left unspecified, the job is not peered with any network. :param bigquery_destination: Provide this field if `dataset` is a BiqQuery dataset. The BigQuery project location where the training data is to be written to. In the given project a new dataset is created with name ``dataset_<dataset-id>_<annotation-type>_<timestamp-of-training-call>`` where timestamp is in YYYY_MM_DDThh_mm_ss_sssZ format. All training input data will be written into that dataset. In the dataset three tables will be created, ``training``, ``validation`` and ``test``. - AIP_DATA_FORMAT = "bigquery". - AIP_TRAINING_DATA_URI ="bigquery_destination.dataset_*.training" - AIP_VALIDATION_DATA_URI = "bigquery_destination.dataset_*.validation" - AIP_TEST_DATA_URI = "bigquery_destination.dataset_*.test" :param args: Command line arguments to be passed to the Python script. :param environment_variables: Environment variables to be passed to the container. Should be a dictionary where keys are environment variable names and values are environment variable values for those names. At most 10 environment variables can be specified. The Name of the environment variable must be unique. :param replica_count: The number of worker replicas. If replica count = 1 then one chief replica will be provisioned. If replica_count > 1 the remainder will be provisioned as a worker replica pool. :param machine_type: The type of machine to use for training. :param accelerator_type: Hardware accelerator type. One of ACCELERATOR_TYPE_UNSPECIFIED, NVIDIA_TESLA_K80, NVIDIA_TESLA_P100, NVIDIA_TESLA_V100, NVIDIA_TESLA_P4, NVIDIA_TESLA_T4 :param accelerator_count: The number of accelerators to attach to a worker replica. :param boot_disk_type: Type of the boot disk, default is `pd-ssd`. Valid values: `pd-ssd` (Persistent Disk Solid State Drive) or `pd-standard` (Persistent Disk Hard Disk Drive). :param boot_disk_size_gb: Size in GB of the boot disk, default is 100GB. boot disk size must be within the range of [100, 64000]. :param training_fraction_split: Optional. The fraction of the input data that is to be used to train the Model. This is ignored if Dataset is not provided. :param validation_fraction_split: Optional. The fraction of the input data that is to be used to validate the Model. This is ignored if Dataset is not provided. :param test_fraction_split: Optional. The fraction of the input data that is to be used to evaluate the Model. This is ignored if Dataset is not provided. :param training_filter_split: Optional. A filter on DataItems of the Dataset. DataItems that match this filter are used to train the Model. A filter with same syntax as the one used in DatasetService.ListDataItems may be used. If a single DataItem is matched by more than one of the FilterSplit filters, then it is assigned to the first set that applies to it in the training, validation, test order. This is ignored if Dataset is not provided. :param validation_filter_split: Optional. A filter on DataItems of the Dataset. DataItems that match this filter are used to validate the Model. A filter with same syntax as the one used in DatasetService.ListDataItems may be used. If a single DataItem is matched by more than one of the FilterSplit filters, then it is assigned to the first set that applies to it in the training, validation, test order. This is ignored if Dataset is not provided. :param test_filter_split: Optional. A filter on DataItems of the Dataset. DataItems that match this filter are used to test the Model. A filter with same syntax as the one used in DatasetService.ListDataItems may be used. If a single DataItem is matched by more than one of the FilterSplit filters, then it is assigned to the first set that applies to it in the training, validation, test order. This is ignored if Dataset is not provided. :param predefined_split_column_name: Optional. The key is a name of one of the Dataset's data columns. The value of the key (either the label's value or value in the column) must be one of {``training``, ``validation``, ``test``}, and it defines to which set the given piece of data is assigned. If for a piece of data the key is not present or has an invalid value, that piece is ignored by the pipeline. Supported only for tabular and time series Datasets. :param timestamp_split_column_name: Optional. The key is a name of one of the Dataset's data columns. The value of the key values of the key (the values in the column) must be in RFC 3339 `date-time` format, where `time-offset` = `"Z"` (e.g. 1985-04-12T23:20:50.52Z). If for a piece of data the key is not present or has an invalid value, that piece is ignored by the pipeline. Supported only for tabular and time series Datasets. :param tensorboard: Optional. The name of a Vertex AI resource to which this CustomJob will upload logs. Format: ``projects/{project}/locations/{location}/tensorboards/{tensorboard}`` For more information on configuring your service account please visit: https://cloud.google.com/vertex-ai/docs/experiments/tensorboard-training :param psc_interface_config: Optional. Configuration for Private Service Connect interface used for training. """ self._job = self.get_custom_container_training_job( project=project_id, location=region, display_name=display_name, container_uri=container_uri, command=command, model_serving_container_image_uri=model_serving_container_image_uri, model_serving_container_predict_route=model_serving_container_predict_route, model_serving_container_health_route=model_serving_container_health_route, model_serving_container_command=model_serving_container_command, model_serving_container_args=model_serving_container_args, model_serving_container_environment_variables=model_serving_container_environment_variables, model_serving_container_ports=model_serving_container_ports, model_description=model_description, model_instance_schema_uri=model_instance_schema_uri, model_parameters_schema_uri=model_parameters_schema_uri, model_prediction_schema_uri=model_prediction_schema_uri, labels=labels, training_encryption_spec_key_name=training_encryption_spec_key_name, model_encryption_spec_key_name=model_encryption_spec_key_name, staging_bucket=staging_bucket, ) if not self._job: raise AirflowException("CustomContainerTrainingJob instance creation failed.") self._job.submit( dataset=dataset, annotation_schema_uri=annotation_schema_uri, model_display_name=model_display_name, model_labels=model_labels, base_output_dir=base_output_dir, service_account=service_account, network=network, bigquery_destination=bigquery_destination, args=args, environment_variables=environment_variables, replica_count=replica_count, machine_type=machine_type, accelerator_type=accelerator_type, accelerator_count=accelerator_count, boot_disk_type=boot_disk_type, boot_disk_size_gb=boot_disk_size_gb, training_fraction_split=training_fraction_split, validation_fraction_split=validation_fraction_split, test_fraction_split=test_fraction_split, training_filter_split=training_filter_split, validation_filter_split=validation_filter_split, test_filter_split=test_filter_split, predefined_split_column_name=predefined_split_column_name, timestamp_split_column_name=timestamp_split_column_name, tensorboard=tensorboard, parent_model=parent_model, is_default_version=is_default_version, model_version_aliases=model_version_aliases, model_version_description=model_version_description, sync=False, psc_interface_config=psc_interface_config, ) return self._job @GoogleBaseHook.fallback_to_default_project_id def submit_custom_python_package_training_job( self, *, project_id: str, region: str, display_name: str, python_package_gcs_uri: str, python_module_name: str, container_uri: str, model_serving_container_image_uri: str | None = None, model_serving_container_predict_route: str | None = None, model_serving_container_health_route: str | None = None, model_serving_container_command: Sequence[str] | None = None, model_serving_container_args: Sequence[str] | None = None, model_serving_container_environment_variables: dict[str, str] | None = None, model_serving_container_ports: Sequence[int] | None = None, model_description: str | None = None, model_instance_schema_uri: str | None = None, model_parameters_schema_uri: str | None = None, model_prediction_schema_uri: str | None = None, labels: dict[str, str] | None = None, training_encryption_spec_key_name: str | None = None, model_encryption_spec_key_name: str | None = None, staging_bucket: str | None = None, # RUN dataset: None | ( datasets.ImageDataset | datasets.TabularDataset | datasets.TextDataset | datasets.VideoDataset ) = None, annotation_schema_uri: str | None = None, model_display_name: str | None = None, model_labels: dict[str, str] | None = None, base_output_dir: str | None = None, service_account: str | None = None, network: str | None = None, bigquery_destination: str | None = None, args: list[str | float | int] | None = None, environment_variables: dict[str, str] | None = None, replica_count: int = 1, machine_type: str = "n1-standard-4", accelerator_type: str = "ACCELERATOR_TYPE_UNSPECIFIED", accelerator_count: int = 0, boot_disk_type: str = "pd-ssd", boot_disk_size_gb: int = 100, training_fraction_split: float | None = None, validation_fraction_split: float | None = None, test_fraction_split: float | None = None, training_filter_split: str | None = None, validation_filter_split: str | None = None, test_filter_split: str | None = None, predefined_split_column_name: str | None = None, timestamp_split_column_name: str | None = None, tensorboard: str | None = None, parent_model: str | None = None, is_default_version: bool | None = None, model_version_aliases: list[str] | None = None, model_version_description: str | None = None, psc_interface_config: PscInterfaceConfig | None = None, ) -> CustomPythonPackageTrainingJob: """ Create and submit a Custom Python Package Training Job pipeline, then exit without waiting for it to complete. :param display_name: Required. The user-defined name of this TrainingPipeline. :param python_package_gcs_uri: Required: GCS location of the training python package. :param python_module_name: Required: The module name of the training python package. :param container_uri: Required: Uri of the training container image in the GCR. :param model_serving_container_image_uri: If the training produces a managed Vertex AI Model, the URI of the Model serving container suitable for serving the model produced by the training script. :param model_serving_container_predict_route: If the training produces a managed Vertex AI Model, An HTTP path to send prediction requests to the container, and which must be supported by it. If not specified a default HTTP path will be used by Vertex AI. :param model_serving_container_health_route: If the training produces a managed Vertex AI Model, an HTTP path to send health check requests to the container, and which must be supported by it. If not specified a standard HTTP path will be used by AI Platform. :param model_serving_container_command: The command with which the container is run. Not executed within a shell. The Docker image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. :param model_serving_container_args: The arguments to the command. The Docker image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. :param model_serving_container_environment_variables: The environment variables that are to be present in the container. Should be a dictionary where keys are environment variable names and values are environment variable values for those names. :param model_serving_container_ports: Declaration of ports that are exposed by the container. This field is primarily informational, it gives Vertex AI information about the network connections the container uses. Listing or not a port here has no impact on whether the port is actually exposed, any port listening on the default "0.0.0.0" address inside a container will be accessible from the network. :param model_description: The description of the Model. :param model_instance_schema_uri: Optional. Points to a YAML file stored on Google Cloud Storage describing the format of a single instance, which are used in ``PredictRequest.instances``, ``ExplainRequest.instances`` and ``BatchPredictionJob.input_config``. The schema is defined as an OpenAPI 3.0.2 `Schema Object <https://tinyurl.com/y538mdwt#schema-object>`__. AutoML Models always have this field populated by AI Platform. Note: The URI given on output will be immutable and probably different, including the URI scheme, than the one given on input. The output URI will point to a location where the user only has a read access. :param model_parameters_schema_uri: Optional. Points to a YAML file stored on Google Cloud Storage describing the parameters of prediction and explanation via ``PredictRequest.parameters``, ``ExplainRequest.parameters`` and ``BatchPredictionJob.model_parameters``. The schema is defined as an OpenAPI 3.0.2 `Schema Object <https://tinyurl.com/y538mdwt#schema-object>`__. AutoML Models always have this field populated by AI Platform, if no parameters are supported it is set to an empty string. Note: The URI given on output will be immutable and probably different, including the URI scheme, than the one given on input. The output URI will point to a location where the user only has a read access. :param model_prediction_schema_uri: Optional. Points to a YAML file stored on Google Cloud Storage describing the format of a single prediction produced by this Model, which are returned via ``PredictResponse.predictions``, ``ExplainResponse.explanations``, and ``BatchPredictionJob.output_config``. The schema is defined as an OpenAPI 3.0.2 `Schema Object <https://tinyurl.com/y538mdwt#schema-object>`__. AutoML Models always have this field populated by AI Platform. Note: The URI given on output will be immutable and probably different, including the URI scheme, than the one given on input. The output URI will point to a location where the user only has a read access. :param parent_model: Optional. The resource name or model ID of an existing model. The new model uploaded by this job will be a version of `parent_model`. Only set this field when training a new version of an existing model. :param is_default_version: Optional. When set to True, the newly uploaded model version will automatically have alias "default" included. Subsequent uses of the model produced by this job without a version specified will use this "default" version. When set to False, the "default" alias will not be moved. Actions targeting the model version produced by this job will need to specifically reference this version by ID or alias. New model uploads, i.e. version 1, will always be "default" aliased. :param model_version_aliases: Optional. User provided version aliases so that the model version uploaded by this job can be referenced via alias instead of auto-generated version ID. A default version alias will be created for the first version of the model. The format is [a-z][a-zA-Z0-9-]{0,126}[a-z0-9] :param model_version_description: Optional. The description of the model version being uploaded by this job. :param project_id: Project to run training in. :param region: Location to run training in. :param labels: Optional. The labels with user-defined metadata to organize TrainingPipelines. Label keys and values can be no longer than 64 characters, can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. :param training_encryption_spec_key_name: Optional. The Cloud KMS resource identifier of the customer managed encryption key used to protect the training pipeline. Has the form: ``projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key``. The key needs to be in the same region as where the compute resource is created. If set, this TrainingPipeline will be secured by this key. Note: Model trained by this TrainingPipeline is also secured by this key if ``model_to_upload`` is not set separately. :param model_encryption_spec_key_name: Optional. The Cloud KMS resource identifier of the customer managed encryption key used to protect the model. Has the form: ``projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key``. The key needs to be in the same region as where the compute resource is created. If set, the trained Model will be secured by this key. :param staging_bucket: Bucket used to stage source and training artifacts. :param dataset: Vertex AI to fit this training against. :param annotation_schema_uri: Google Cloud Storage URI points to a YAML file describing annotation schema. The schema is defined as an OpenAPI 3.0.2 [Schema Object] (https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#schema-object) Only Annotations that both match this schema and belong to DataItems not ignored by the split method are used in respectively training, validation or test role, depending on the role of the DataItem they are on. When used in conjunction with ``annotations_filter``, the Annotations used for training are filtered by both ``annotations_filter`` and ``annotation_schema_uri``. :param model_display_name: If the script produces a managed Vertex AI Model. The display name of the Model. The name can be up to 128 characters long and can be consist of any UTF-8 characters. If not provided upon creation, the job's display_name is used. :param model_labels: Optional. The labels with user-defined metadata to organize your Models. Label keys and values can be no longer than 64 characters, can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. :param base_output_dir: GCS output directory of job. If not provided a timestamped directory in the staging directory will be used. Vertex AI sets the following environment variables when it runs your training code: - AIP_MODEL_DIR: a Cloud Storage URI of a directory intended for saving model artifacts, i.e. <base_output_dir>/model/ - AIP_CHECKPOINT_DIR: a Cloud Storage URI of a directory intended for saving checkpoints, i.e. <base_output_dir>/checkpoints/ - AIP_TENSORBOARD_LOG_DIR: a Cloud Storage URI of a directory intended for saving TensorBoard logs, i.e. <base_output_dir>/logs/ :param service_account: Specifies the service account for workload run-as account. Users submitting jobs must have act-as permission on this run-as account. :param network: The full name of the Compute Engine network to which the job should be peered. Private services access must already be configured for the network. If left unspecified, the job is not peered with any network. :param bigquery_destination: Provide this field if `dataset` is a BiqQuery dataset. The BigQuery project location where the training data is to be written to. In the given project a new dataset is created with name ``dataset_<dataset-id>_<annotation-type>_<timestamp-of-training-call>`` where timestamp is in YYYY_MM_DDThh_mm_ss_sssZ format. All training input data will be written into that dataset. In the dataset three tables will be created, ``training``, ``validation`` and ``test``. - AIP_DATA_FORMAT = "bigquery". - AIP_TRAINING_DATA_URI ="bigquery_destination.dataset_*.training" - AIP_VALIDATION_DATA_URI = "bigquery_destination.dataset_*.validation" - AIP_TEST_DATA_URI = "bigquery_destination.dataset_*.test" :param args: Command line arguments to be passed to the Python script. :param environment_variables: Environment variables to be passed to the container. Should be a dictionary where keys are environment variable names and values are environment variable values for those names. At most 10 environment variables can be specified. The Name of the environment variable must be unique. :param replica_count: The number of worker replicas. If replica count = 1 then one chief replica will be provisioned. If replica_count > 1 the remainder will be provisioned as a worker replica pool. :param machine_type: The type of machine to use for training. :param accelerator_type: Hardware accelerator type. One of ACCELERATOR_TYPE_UNSPECIFIED, NVIDIA_TESLA_K80, NVIDIA_TESLA_P100, NVIDIA_TESLA_V100, NVIDIA_TESLA_P4, NVIDIA_TESLA_T4 :param accelerator_count: The number of accelerators to attach to a worker replica. :param boot_disk_type: Type of the boot disk, default is `pd-ssd`. Valid values: `pd-ssd` (Persistent Disk Solid State Drive) or `pd-standard` (Persistent Disk Hard Disk Drive). :param boot_disk_size_gb: Size in GB of the boot disk, default is 100GB. boot disk size must be within the range of [100, 64000]. :param training_fraction_split: Optional. The fraction of the input data that is to be used to train the Model. This is ignored if Dataset is not provided. :param validation_fraction_split: Optional. The fraction of the input data that is to be used to validate the Model. This is ignored if Dataset is not provided. :param test_fraction_split: Optional. The fraction of the input data that is to be used to evaluate the Model. This is ignored if Dataset is not provided. :param training_filter_split: Optional. A filter on DataItems of the Dataset. DataItems that match this filter are used to train the Model. A filter with same syntax as the one used in DatasetService.ListDataItems may be used. If a single DataItem is matched by more than one of the FilterSplit filters, then it is assigned to the first set that applies to it in the training, validation, test order. This is ignored if Dataset is not provided. :param validation_filter_split: Optional. A filter on DataItems of the Dataset. DataItems that match this filter are used to validate the Model. A filter with same syntax as the one used in DatasetService.ListDataItems may be used. If a single DataItem is matched by more than one of the FilterSplit filters, then it is assigned to the first set that applies to it in the training, validation, test order. This is ignored if Dataset is not provided. :param test_filter_split: Optional. A filter on DataItems of the Dataset. DataItems that match this filter are used to test the Model. A filter with same syntax as the one used in DatasetService.ListDataItems may be used. If a single DataItem is matched by more than one of the FilterSplit filters, then it is assigned to the first set that applies to it in the training, validation, test order. This is ignored if Dataset is not provided. :param predefined_split_column_name: Optional. The key is a name of one of the Dataset's data columns. The value of the key (either the label's value or value in the column) must be one of {``training``, ``validation``, ``test``}, and it defines to which set the given piece of data is assigned. If for a piece of data the key is not present or has an invalid value, that piece is ignored by the pipeline. Supported only for tabular and time series Datasets. :param timestamp_split_column_name: Optional. The key is a name of one of the Dataset's data columns. The value of the key values of the key (the values in the column) must be in RFC 3339 `date-time` format, where `time-offset` = `"Z"` (e.g. 1985-04-12T23:20:50.52Z). If for a piece of data the key is not present or has an invalid value, that piece is ignored by the pipeline. Supported only for tabular and time series Datasets. :param tensorboard: Optional. The name of a Vertex AI resource to which this CustomJob will upload logs. Format: ``projects/{project}/locations/{location}/tensorboards/{tensorboard}`` For more information on configuring your service account please visit: https://cloud.google.com/vertex-ai/docs/experiments/tensorboard-training :param psc_interface_config: Optional. Configuration for Private Service Connect interface used for training. """ self._job = self.get_custom_python_package_training_job( project=project_id, location=region, display_name=display_name, python_package_gcs_uri=python_package_gcs_uri, python_module_name=python_module_name, container_uri=container_uri, model_serving_container_image_uri=model_serving_container_image_uri, model_serving_container_predict_route=model_serving_container_predict_route, model_serving_container_health_route=model_serving_container_health_route, model_serving_container_command=model_serving_container_command, model_serving_container_args=model_serving_container_args, model_serving_container_environment_variables=model_serving_container_environment_variables, model_serving_container_ports=model_serving_container_ports, model_description=model_description, model_instance_schema_uri=model_instance_schema_uri, model_parameters_schema_uri=model_parameters_schema_uri, model_prediction_schema_uri=model_prediction_schema_uri, labels=labels, training_encryption_spec_key_name=training_encryption_spec_key_name, model_encryption_spec_key_name=model_encryption_spec_key_name, staging_bucket=staging_bucket, ) if not self._job: raise AirflowException("CustomPythonPackageTrainingJob instance creation failed.") self._job.run( dataset=dataset, annotation_schema_uri=annotation_schema_uri, model_display_name=model_display_name, model_labels=model_labels, base_output_dir=base_output_dir, service_account=service_account, network=network, bigquery_destination=bigquery_destination, args=args, environment_variables=environment_variables, replica_count=replica_count, machine_type=machine_type, accelerator_type=accelerator_type, accelerator_count=accelerator_count, boot_disk_type=boot_disk_type, boot_disk_size_gb=boot_disk_size_gb, training_fraction_split=training_fraction_split, validation_fraction_split=validation_fraction_split, test_fraction_split=test_fraction_split, training_filter_split=training_filter_split, validation_filter_split=validation_filter_split, test_filter_split=test_filter_split, predefined_split_column_name=predefined_split_column_name, timestamp_split_column_name=timestamp_split_column_name, tensorboard=tensorboard, parent_model=parent_model, is_default_version=is_default_version, model_version_aliases=model_version_aliases, model_version_description=model_version_description, sync=False, psc_interface_config=psc_interface_config, ) return self._job @GoogleBaseHook.fallback_to_default_project_id def submit_custom_training_job( self, *, project_id: str, region: str, display_name: str, script_path: str, container_uri: str, requirements: Sequence[str] | None = None, model_serving_container_image_uri: str | None = None, model_serving_container_predict_route: str | None = None, model_serving_container_health_route: str | None = None, model_serving_container_command: Sequence[str] | None = None, model_serving_container_args: Sequence[str] | None = None, model_serving_container_environment_variables: dict[str, str] | None = None, model_serving_container_ports: Sequence[int] | None = None, model_description: str | None = None, model_instance_schema_uri: str | None = None, model_parameters_schema_uri: str | None = None, model_prediction_schema_uri: str | None = None, parent_model: str | None = None, is_default_version: bool | None = None, model_version_aliases: list[str] | None = None, model_version_description: str | None = None, labels: dict[str, str] | None = None, training_encryption_spec_key_name: str | None = None, model_encryption_spec_key_name: str | None = None, staging_bucket: str | None = None, # RUN dataset: None | ( datasets.ImageDataset | datasets.TabularDataset | datasets.TextDataset | datasets.VideoDataset ) = None, annotation_schema_uri: str | None = None, model_display_name: str | None = None, model_labels: dict[str, str] | None = None, base_output_dir: str | None = None, service_account: str | None = None, network: str | None = None, bigquery_destination: str | None = None, args: list[str | float | int] | None = None, environment_variables: dict[str, str] | None = None, replica_count: int = 1, machine_type: str = "n1-standard-4", accelerator_type: str = "ACCELERATOR_TYPE_UNSPECIFIED", accelerator_count: int = 0, boot_disk_type: str = "pd-ssd", boot_disk_size_gb: int = 100, training_fraction_split: float | None = None, validation_fraction_split: float | None = None, test_fraction_split: float | None = None, training_filter_split: str | None = None, validation_filter_split: str | None = None, test_filter_split: str | None = None, predefined_split_column_name: str | None = None, timestamp_split_column_name: str | None = None, tensorboard: str | None = None, psc_interface_config: PscInterfaceConfig | None = None, ) -> CustomTrainingJob: """ Create and submit a Custom Training Job pipeline, then exit without waiting for it to complete. Neither the training model nor backing custom job are available at the moment when the training pipeline is submitted, both are created only after a period of time. Therefore, it is not possible to extract and return them in this method, this should be done with a separate client request. :param display_name: Required. The user-defined name of this TrainingPipeline. :param script_path: Required. Local path to training script. :param container_uri: Required: Uri of the training container image in the GCR. :param requirements: List of python packages dependencies of script. :param model_serving_container_image_uri: If the training produces a managed Vertex AI Model, the URI of the Model serving container suitable for serving the model produced by the training script. :param model_serving_container_predict_route: If the training produces a managed Vertex AI Model, An HTTP path to send prediction requests to the container, and which must be supported by it. If not specified a default HTTP path will be used by Vertex AI. :param model_serving_container_health_route: If the training produces a managed Vertex AI Model, an HTTP path to send health check requests to the container, and which must be supported by it. If not specified a standard HTTP path will be used by AI Platform. :param model_serving_container_command: The command with which the container is run. Not executed within a shell. The Docker image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. :param model_serving_container_args: The arguments to the command. The Docker image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. :param model_serving_container_environment_variables: The environment variables that are to be present in the container. Should be a dictionary where keys are environment variable names and values are environment variable values for those names. :param model_serving_container_ports: Declaration of ports that are exposed by the container. This field is primarily informational, it gives Vertex AI information about the network connections the container uses. Listing or not a port here has no impact on whether the port is actually exposed, any port listening on the default "0.0.0.0" address inside a container will be accessible from the network. :param model_description: The description of the Model. :param model_instance_schema_uri: Optional. Points to a YAML file stored on Google Cloud Storage describing the format of a single instance, which are used in ``PredictRequest.instances``, ``ExplainRequest.instances`` and ``BatchPredictionJob.input_config``. The schema is defined as an OpenAPI 3.0.2 `Schema Object <https://tinyurl.com/y538mdwt#schema-object>`__. AutoML Models always have this field populated by AI Platform. Note: The URI given on output will be immutable and probably different, including the URI scheme, than the one given on input. The output URI will point to a location where the user only has a read access. :param model_parameters_schema_uri: Optional. Points to a YAML file stored on Google Cloud Storage describing the parameters of prediction and explanation via ``PredictRequest.parameters``, ``ExplainRequest.parameters`` and ``BatchPredictionJob.model_parameters``. The schema is defined as an OpenAPI 3.0.2 `Schema Object <https://tinyurl.com/y538mdwt#schema-object>`__. AutoML Models always have this field populated by AI Platform, if no parameters are supported it is set to an empty string. Note: The URI given on output will be immutable and probably different, including the URI scheme, than the one given on input. The output URI will point to a location where the user only has a read access. :param model_prediction_schema_uri: Optional. Points to a YAML file stored on Google Cloud Storage describing the format of a single prediction produced by this Model, which are returned via ``PredictResponse.predictions``, ``ExplainResponse.explanations``, and ``BatchPredictionJob.output_config``. The schema is defined as an OpenAPI 3.0.2 `Schema Object <https://tinyurl.com/y538mdwt#schema-object>`__. AutoML Models always have this field populated by AI Platform. Note: The URI given on output will be immutable and probably different, including the URI scheme, than the one given on input. The output URI will point to a location where the user only has a read access. :param parent_model: Optional. The resource name or model ID of an existing model. The new model uploaded by this job will be a version of `parent_model`. Only set this field when training a new version of an existing model. :param is_default_version: Optional. When set to True, the newly uploaded model version will automatically have alias "default" included. Subsequent uses of the model produced by this job without a version specified will use this "default" version. When set to False, the "default" alias will not be moved. Actions targeting the model version produced by this job will need to specifically reference this version by ID or alias. New model uploads, i.e. version 1, will always be "default" aliased. :param model_version_aliases: Optional. User provided version aliases so that the model version uploaded by this job can be referenced via alias instead of auto-generated version ID. A default version alias will be created for the first version of the model. The format is [a-z][a-zA-Z0-9-]{0,126}[a-z0-9] :param model_version_description: Optional. The description of the model version being uploaded by this job. :param project_id: Project to run training in. :param region: Location to run training in. :param labels: Optional. The labels with user-defined metadata to organize TrainingPipelines. Label keys and values can be no longer than 64 characters, can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. :param training_encryption_spec_key_name: Optional. The Cloud KMS resource identifier of the customer managed encryption key used to protect the training pipeline. Has the form: ``projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key``. The key needs to be in the same region as where the compute resource is created. If set, this TrainingPipeline will be secured by this key. Note: Model trained by this TrainingPipeline is also secured by this key if ``model_to_upload`` is not set separately. :param model_encryption_spec_key_name: Optional. The Cloud KMS resource identifier of the customer managed encryption key used to protect the model. Has the form: ``projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key``. The key needs to be in the same region as where the compute resource is created. If set, the trained Model will be secured by this key. :param staging_bucket: Bucket used to stage source and training artifacts. :param dataset: Vertex AI to fit this training against. :param annotation_schema_uri: Google Cloud Storage URI points to a YAML file describing annotation schema. The schema is defined as an OpenAPI 3.0.2 [Schema Object] (https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#schema-object) Only Annotations that both match this schema and belong to DataItems not ignored by the split method are used in respectively training, validation or test role, depending on the role of the DataItem they are on. When used in conjunction with ``annotations_filter``, the Annotations used for training are filtered by both ``annotations_filter`` and ``annotation_schema_uri``. :param model_display_name: If the script produces a managed Vertex AI Model. The display name of the Model. The name can be up to 128 characters long and can be consist of any UTF-8 characters. If not provided upon creation, the job's display_name is used. :param model_labels: Optional. The labels with user-defined metadata to organize your Models. Label keys and values can be no longer than 64 characters, can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. :param base_output_dir: GCS output directory of job. If not provided a timestamped directory in the staging directory will be used. Vertex AI sets the following environment variables when it runs your training code: - AIP_MODEL_DIR: a Cloud Storage URI of a directory intended for saving model artifacts, i.e. <base_output_dir>/model/ - AIP_CHECKPOINT_DIR: a Cloud Storage URI of a directory intended for saving checkpoints, i.e. <base_output_dir>/checkpoints/ - AIP_TENSORBOARD_LOG_DIR: a Cloud Storage URI of a directory intended for saving TensorBoard logs, i.e. <base_output_dir>/logs/ :param service_account: Specifies the service account for workload run-as account. Users submitting jobs must have act-as permission on this run-as account. :param network: The full name of the Compute Engine network to which the job should be peered. Private services access must already be configured for the network. If left unspecified, the job is not peered with any network. :param bigquery_destination: Provide this field if `dataset` is a BiqQuery dataset. The BigQuery project location where the training data is to be written to. In the given project a new dataset is created with name ``dataset_<dataset-id>_<annotation-type>_<timestamp-of-training-call>`` where timestamp is in YYYY_MM_DDThh_mm_ss_sssZ format. All training input data will be written into that dataset. In the dataset three tables will be created, ``training``, ``validation`` and ``test``. - AIP_DATA_FORMAT = "bigquery". - AIP_TRAINING_DATA_URI ="bigquery_destination.dataset_*.training" - AIP_VALIDATION_DATA_URI = "bigquery_destination.dataset_*.validation" - AIP_TEST_DATA_URI = "bigquery_destination.dataset_*.test" :param args: Command line arguments to be passed to the Python script. :param environment_variables: Environment variables to be passed to the container. Should be a dictionary where keys are environment variable names and values are environment variable values for those names. At most 10 environment variables can be specified. The Name of the environment variable must be unique. :param replica_count: The number of worker replicas. If replica count = 1 then one chief replica will be provisioned. If replica_count > 1 the remainder will be provisioned as a worker replica pool. :param machine_type: The type of machine to use for training. :param accelerator_type: Hardware accelerator type. One of ACCELERATOR_TYPE_UNSPECIFIED, NVIDIA_TESLA_K80, NVIDIA_TESLA_P100, NVIDIA_TESLA_V100, NVIDIA_TESLA_P4, NVIDIA_TESLA_T4 :param accelerator_count: The number of accelerators to attach to a worker replica. :param boot_disk_type: Type of the boot disk, default is `pd-ssd`. Valid values: `pd-ssd` (Persistent Disk Solid State Drive) or `pd-standard` (Persistent Disk Hard Disk Drive). :param boot_disk_size_gb: Size in GB of the boot disk, default is 100GB. boot disk size must be within the range of [100, 64000]. :param training_fraction_split: Optional. The fraction of the input data that is to be used to train the Model. This is ignored if Dataset is not provided. :param validation_fraction_split: Optional. The fraction of the input data that is to be used to validate the Model. This is ignored if Dataset is not provided. :param test_fraction_split: Optional. The fraction of the input data that is to be used to evaluate the Model. This is ignored if Dataset is not provided. :param training_filter_split: Optional. A filter on DataItems of the Dataset. DataItems that match this filter are used to train the Model. A filter with same syntax as the one used in DatasetService.ListDataItems may be used. If a single DataItem is matched by more than one of the FilterSplit filters, then it is assigned to the first set that applies to it in the training, validation, test order. This is ignored if Dataset is not provided. :param validation_filter_split: Optional. A filter on DataItems of the Dataset. DataItems that match this filter are used to validate the Model. A filter with same syntax as the one used in DatasetService.ListDataItems may be used. If a single DataItem is matched by more than one of the FilterSplit filters, then it is assigned to the first set that applies to it in the training, validation, test order. This is ignored if Dataset is not provided. :param test_filter_split: Optional. A filter on DataItems of the Dataset. DataItems that match this filter are used to test the Model. A filter with same syntax as the one used in DatasetService.ListDataItems may be used. If a single DataItem is matched by more than one of the FilterSplit filters, then it is assigned to the first set that applies to it in the training, validation, test order. This is ignored if Dataset is not provided. :param predefined_split_column_name: Optional. The key is a name of one of the Dataset's data columns. The value of the key (either the label's value or value in the column) must be one of {``training``, ``validation``, ``test``}, and it defines to which set the given piece of data is assigned. If for a piece of data the key is not present or has an invalid value, that piece is ignored by the pipeline. Supported only for tabular and time series Datasets. :param timestamp_split_column_name: Optional. The key is a name of one of the Dataset's data columns. The value of the key values of the key (the values in the column) must be in RFC 3339 `date-time` format, where `time-offset` = `"Z"` (e.g. 1985-04-12T23:20:50.52Z). If for a piece of data the key is not present or has an invalid value, that piece is ignored by the pipeline. Supported only for tabular and time series Datasets. :param tensorboard: Optional. The name of a Vertex AI resource to which this CustomJob will upload logs. Format: ``projects/{project}/locations/{location}/tensorboards/{tensorboard}`` For more information on configuring your service account please visit: https://cloud.google.com/vertex-ai/docs/experiments/tensorboard-training :param psc_interface_config: Optional. Configuration for Private Service Connect interface used for training. """ self._job = self.get_custom_training_job( project=project_id, location=region, display_name=display_name, script_path=script_path, container_uri=container_uri, requirements=requirements, model_serving_container_image_uri=model_serving_container_image_uri, model_serving_container_predict_route=model_serving_container_predict_route, model_serving_container_health_route=model_serving_container_health_route, model_serving_container_command=model_serving_container_command, model_serving_container_args=model_serving_container_args, model_serving_container_environment_variables=model_serving_container_environment_variables, model_serving_container_ports=model_serving_container_ports, model_description=model_description, model_instance_schema_uri=model_instance_schema_uri, model_parameters_schema_uri=model_parameters_schema_uri, model_prediction_schema_uri=model_prediction_schema_uri, labels=labels, training_encryption_spec_key_name=training_encryption_spec_key_name, model_encryption_spec_key_name=model_encryption_spec_key_name, staging_bucket=staging_bucket, ) if not self._job: raise AirflowException("CustomTrainingJob instance creation failed.") self._job.submit( dataset=dataset, annotation_schema_uri=annotation_schema_uri, model_display_name=model_display_name, model_labels=model_labels, base_output_dir=base_output_dir, service_account=service_account, network=network, bigquery_destination=bigquery_destination, args=args, environment_variables=environment_variables, replica_count=replica_count, machine_type=machine_type, accelerator_type=accelerator_type, accelerator_count=accelerator_count, boot_disk_type=boot_disk_type, boot_disk_size_gb=boot_disk_size_gb, training_fraction_split=training_fraction_split, validation_fraction_split=validation_fraction_split, test_fraction_split=test_fraction_split, training_filter_split=training_filter_split, validation_filter_split=validation_filter_split, test_filter_split=test_filter_split, predefined_split_column_name=predefined_split_column_name, timestamp_split_column_name=timestamp_split_column_name, tensorboard=tensorboard, parent_model=parent_model, is_default_version=is_default_version, model_version_aliases=model_version_aliases, model_version_description=model_version_description, sync=False, psc_interface_config=psc_interface_config, ) return self._job @GoogleBaseHook.fallback_to_default_project_id def delete_training_pipeline( self, project_id: str, region: str, training_pipeline: str, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), ) -> Operation: """ Delete a TrainingPipeline. :param project_id: Required. The ID of the Google Cloud project that the service belongs to. :param region: Required. The ID of the Google Cloud region that the service belongs to. :param training_pipeline: Required. The name of the TrainingPipeline resource to be deleted. :param retry: Designation of what errors, if any, should be retried. :param timeout: The timeout for this request. :param metadata: Strings which should be sent along with the request as metadata. """ client = self.get_pipeline_service_client(region) name = client.training_pipeline_path(project_id, region, training_pipeline) result = client.delete_training_pipeline( request={"name": name}, retry=retry, timeout=timeout, metadata=metadata, ) return result @GoogleBaseHook.fallback_to_default_project_id def delete_custom_job( self, project_id: str, region: str, custom_job: str, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), ) -> Operation: """ Delete a CustomJob. :param project_id: Required. The ID of the Google Cloud project that the service belongs to. :param region: Required. The ID of the Google Cloud region that the service belongs to. :param custom_job: Required. The name of the CustomJob to delete. :param retry: Designation of what errors, if any, should be retried. :param timeout: The timeout for this request. :param metadata: Strings which should be sent along with the request as metadata. """ client = self.get_job_service_client(region) name = client.custom_job_path(project_id, region, custom_job) result = client.delete_custom_job( request={ "name": name, }, retry=retry, timeout=timeout, metadata=metadata, ) return result @GoogleBaseHook.fallback_to_default_project_id def get_training_pipeline( self, project_id: str, region: str, training_pipeline: str, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), ) -> TrainingPipeline: """ Get a TrainingPipeline. :param project_id: Required. The ID of the Google Cloud project that the service belongs to. :param region: Required. The ID of the Google Cloud region that the service belongs to. :param training_pipeline: Required. The name of the TrainingPipeline resource. :param retry: Designation of what errors, if any, should be retried. :param timeout: The timeout for this request. :param metadata: Strings which should be sent along with the request as metadata. """ client = self.get_pipeline_service_client(region) name = client.training_pipeline_path(project_id, region, training_pipeline) result = client.get_training_pipeline( request={ "name": name, }, retry=retry, timeout=timeout, metadata=metadata, ) return result @GoogleBaseHook.fallback_to_default_project_id def get_custom_job( self, project_id: str, region: str, custom_job: str, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), ) -> CustomJob: """ Get a CustomJob. :param project_id: Required. The ID of the Google Cloud project that the service belongs to. :param region: Required. The ID of the Google Cloud region that the service belongs to. :param custom_job: Required. The name of the CustomJob to get. :param retry: Designation of what errors, if any, should be retried. :param timeout: The timeout for this request. :param metadata: Strings which should be sent along with the request as metadata. """ client = self.get_job_service_client(region) name = JobServiceClient.custom_job_path(project_id, region, custom_job) result = client.get_custom_job( request={ "name": name, }, retry=retry, timeout=timeout, metadata=metadata, ) return result @GoogleBaseHook.fallback_to_default_project_id def list_training_pipelines( self, project_id: str, region: str, page_size: int | None = None, page_token: str | None = None, filter: str | None = None, read_mask: str | None = None, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), ) -> ListTrainingPipelinesPager: """ List TrainingPipelines in a Location. :param project_id: Required. The ID of the Google Cloud project that the service belongs to. :param region: Required. The ID of the Google Cloud region that the service belongs to. :param filter: Optional. The standard list filter. Supported fields: - ``display_name`` supports = and !=. - ``state`` supports = and !=. Some examples of using the filter are: - ``state="PIPELINE_STATE_SUCCEEDED" AND display_name="my_pipeline"`` - ``state="PIPELINE_STATE_RUNNING" OR display_name="my_pipeline"`` - ``NOT display_name="my_pipeline"`` - ``state="PIPELINE_STATE_FAILED"`` :param page_size: Optional. The standard list page size. :param page_token: Optional. The standard list page token. Typically obtained via [ListTrainingPipelinesResponse.next_page_token][google.cloud.aiplatform.v1.ListTrainingPipelinesResponse.next_page_token] of the previous [PipelineService.ListTrainingPipelines][google.cloud.aiplatform.v1.PipelineService.ListTrainingPipelines] call. :param read_mask: Optional. Mask specifying which fields to read. :param retry: Designation of what errors, if any, should be retried. :param timeout: The timeout for this request. :param metadata: Strings which should be sent along with the request as metadata. """ client = self.get_pipeline_service_client(region) parent = client.common_location_path(project_id, region) result = client.list_training_pipelines( request={ "parent": parent, "page_size": page_size, "page_token": page_token, "filter": filter, "read_mask": read_mask, }, retry=retry, timeout=timeout, metadata=metadata, ) return result @GoogleBaseHook.fallback_to_default_project_id def list_custom_jobs( self, project_id: str, region: str, page_size: int | None, page_token: str | None, filter: str | None, read_mask: str | None, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), ) -> ListCustomJobsPager: """ List CustomJobs in a Location. :param project_id: Required. The ID of the Google Cloud project that the service belongs to. :param region: Required. The ID of the Google Cloud region that the service belongs to. :param filter: Optional. The standard list filter. Supported fields: - ``display_name`` supports = and !=. - ``state`` supports = and !=. Some examples of using the filter are: - ``state="PIPELINE_STATE_SUCCEEDED" AND display_name="my_pipeline"`` - ``state="PIPELINE_STATE_RUNNING" OR display_name="my_pipeline"`` - ``NOT display_name="my_pipeline"`` - ``state="PIPELINE_STATE_FAILED"`` :param page_size: Optional. The standard list page size. :param page_token: Optional. The standard list page token. Typically obtained via [ListTrainingPipelinesResponse.next_page_token][google.cloud.aiplatform.v1.ListTrainingPipelinesResponse.next_page_token] of the previous [PipelineService.ListTrainingPipelines][google.cloud.aiplatform.v1.PipelineService.ListTrainingPipelines] call. :param read_mask: Optional. Mask specifying which fields to read. :param retry: Designation of what errors, if any, should be retried. :param timeout: The timeout for this request. :param metadata: Strings which should be sent along with the request as metadata. """ client = self.get_job_service_client(region) parent = JobServiceClient.common_location_path(project_id, region) result = client.list_custom_jobs( request={ "parent": parent, "page_size": page_size, "page_token": page_token, "filter": filter, "read_mask": read_mask, }, retry=retry, timeout=timeout, metadata=metadata, ) return result
CustomJobHook
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/callable3.py
{ "start": 267, "end": 568 }
class ____(Generic[T]): def method1(self, val: Callable[[ClassA[R]], T]) -> R | None: return None b1: ClassB[tuple[int, ClassA[str]]] = ClassB() v1: Callable[[ClassA[str]], tuple[int, ClassA[str]]] = lambda r: (42, r) ret = b1.method1(v1) reveal_type(ret, expected_text="str | None")
ClassB
python
tensorflow__tensorflow
tensorflow/python/trackable/trackable_utils_test.py
{ "start": 822, "end": 1924 }
class ____(test.TestCase): def test_order_by_dependency(self): """Tests order_by_dependency correctness.""" # Visual graph (vertical lines point down, so 1 depends on 2): # 1 # / \ # 2 --> 3 <-- 4 # | # 5 # One possible order: [5, 3, 4, 2, 1] dependencies = {1: [2, 3], 2: [3], 3: [5], 4: [3], 5: []} sorted_arr = list(trackable_utils.order_by_dependency(dependencies)) indices = {x: sorted_arr.index(x) for x in range(1, 6)} self.assertEqual(indices[5], 0) self.assertEqual(indices[3], 1) self.assertGreater(indices[1], indices[2]) # 2 must appear before 1 def test_order_by_no_dependency(self): sorted_arr = list(trackable_utils.order_by_dependency( {x: [] for x in range(15)})) self.assertEqual(set(sorted_arr), set(range(15))) def test_order_by_dependency_invalid_map(self): with self.assertRaisesRegex( ValueError, "Found values in the dependency map which are not keys"): trackable_utils.order_by_dependency({1: [2]}) if __name__ == "__main__": test.main()
TrackableUtilsTest
python
aio-libs__aiohttp
aiohttp/web_exceptions.py
{ "start": 11438, "end": 11510 }
class ____(HTTPServerError): status_code = 505
HTTPVersionNotSupported
python
airbytehq__airbyte
airbyte-integrations/connectors/source-facebook-marketing/unit_tests/test_async_job_manager.py
{ "start": 943, "end": 12687 }
class ____: def test_jobs_empty(self, api, some_config): manager = InsightAsyncJobManager(api=api, jobs=[], account_id=some_config["account_ids"][0]) jobs = list(manager.completed_jobs()) assert not jobs def test_jobs_completed_immediately(self, api, mocker, time_mock, update_job_mock, some_config): """ Manager should emit jobs without waiting if they are already completed. (Manager doesn't "restart"; it just yields terminal jobs.) """ jobs = [ mocker.Mock(spec=InsightAsyncJob, started=True, completed=True, new_jobs=[]), mocker.Mock(spec=InsightAsyncJob, started=True, completed=True, new_jobs=[]), ] # update_in_batch is called but does nothing here manager = InsightAsyncJobManager(api=api, jobs=jobs, account_id=some_config["account_ids"][0]) completed_jobs = list(manager.completed_jobs()) assert completed_jobs == jobs time_mock.sleep.assert_not_called() def test_jobs_wait(self, api, mocker, time_mock, update_job_mock, some_config): """ Manager should yield completed jobs and wait for others to complete. We'll flip completion flags across sequential polls. """ jobs = [ mocker.Mock(spec=InsightAsyncJob, started=True, completed=False, new_jobs=[]), mocker.Mock(spec=InsightAsyncJob, started=True, completed=False, new_jobs=[]), ] def side_effect(): # 1st poll: only jobs[1] becomes completed jobs[1].completed = True yield # 2nd poll: nothing new -> manager must sleep yield # 3rd poll: jobs[0] becomes completed jobs[0].completed = True yield update_job_mock.side_effect = side_effect() manager = InsightAsyncJobManager(api=api, jobs=jobs, account_id=some_config["account_ids"][0]) it = manager.completed_jobs() # First completed job (no waiting yet) assert next(it) == jobs[1] time_mock.sleep.assert_not_called() # Second completed job; during this call the manager should sleep once assert next(it) == jobs[0] time_mock.sleep.assert_called_with(InsightAsyncJobManager.JOB_STATUS_UPDATE_SLEEP_SECONDS) # No more jobs assert next(manager.completed_jobs(), None) is None def test_new_jobs_are_adopted(self, api, mocker, time_mock, update_job_mock, some_config): """ If a running job emits .new_jobs, the manager should replace it with those jobs in the running set, and then yield them when they complete. """ # Parent jobs list: job0 is already completed; job1 will emit children job0 = mocker.Mock(spec=InsightAsyncJob, started=True, completed=True, new_jobs=[]) job1 = mocker.Mock(spec=InsightAsyncJob, started=True, completed=False, new_jobs=[]) # Children that appear after first poll child1 = mocker.Mock(spec=InsightAsyncJob, started=True, completed=True, new_jobs=[]) child2 = mocker.Mock(spec=InsightAsyncJob, started=True, completed=True, new_jobs=[]) def side_effect(): # First poll → job1 emits two children job1.new_jobs = [child1, child2] yield # Second poll → nothing to change; children already terminal yield update_job_mock.side_effect = side_effect() manager = InsightAsyncJobManager(api=api, jobs=[job0, job1], account_id=some_config["account_ids"][0]) it = manager.completed_jobs() # First completed is job0 assert next(it) == job0 # Then the two adopted children (order preserved from new_jobs) assert next(it) == child1 assert next(it) == child2 assert next(manager.completed_jobs(), None) is None def test_parent_job_is_emitted_when_provided_as_new_job(self, api, mocker, update_job_mock, some_config): """ If a job emits a ParentAsyncJob in .new_jobs, the manager should adopt it and yield it when it's completed (manager doesn't expand or manage children here). """ job = mocker.Mock(spec=InsightAsyncJob, started=True, completed=False, new_jobs=[]) parent = mocker.Mock(spec=ParentAsyncJob, started=True, completed=True, new_jobs=[]) def side_effect(): # On first poll, the job emits a ParentAsyncJob job.new_jobs = [parent] yield # On subsequent polls, nothing new yield update_job_mock.side_effect = side_effect() manager = InsightAsyncJobManager(api=api, jobs=[job], account_id=some_config["account_ids"][0]) it = manager.completed_jobs() # After adoption, the parent is terminal and should be yielded assert next(it) == parent assert next(manager.completed_jobs(), None) is None def test_stale_throttle_is_refreshed_before_phase2_scheduling(self, api, mocker, time_mock, update_job_mock, some_config): """ When APILimit has a stale high throttle value, the manager should still be able to start work because job.start() calls APILimit.try_consume(), which refreshes throttle internally. If the actual backend throttle is low, the job should start and be yielded as completed. """ # Single job in iterator (already terminal so the manager will yield it once started) job = mocker.Mock(spec=InsightAsyncJob, started=False, completed=True, new_jobs=[]) # start() should attempt to consume capacity, which triggers refresh_throttle() def start_side_effect(limit): assert limit.try_consume() is True job.started = True job.start.side_effect = start_side_effect manager = InsightAsyncJobManager(api=api, jobs=[job], account_id=some_config["account_ids"][0]) # Simulate stale/high cached throttle that would block if not refreshed manager._api_limit._current_throttle = 95.0 # > default throttle_limit=90 # Backend actually reports low throttle on refresh api.api.ads_insights_throttle = MyFacebookAdsApi.Throttle(0.0, 0.0) # No-op polling update_job_mock.side_effect = lambda *args, **kwargs: None out = list(manager.completed_jobs()) # Job should have been started after refresh and yielded as completed job.start.assert_called_once() assert out == [job] # We pinged account during APILimit.try_consume() -> refresh_throttle() api.get_account.assert_called_with(account_id=some_config["account_ids"][0]) api.get_account.return_value.get_insights.assert_called() def test_jobs_left_in_iterator_are_scheduled_in_waves_with_capacity_cap(self, api, mocker, time_mock, update_job_mock, some_config): """ With max_jobs_in_queue=2, manager should schedule 2 at a time in waves. Do not rely on strict intra-wave ordering; just verify wave sizes and membership. """ jobs = [mocker.Mock(spec=InsightAsyncJob, started=False, completed=False, new_jobs=[]) for _ in range(5)] manager = InsightAsyncJobManager( api=api, jobs=jobs, account_id=some_config["account_ids"][0], max_jobs_in_queue=2, ) # Mock job.start(): consume capacity and mark started only if allowed for j in jobs: def _mk_side_effect(job=j): def _start(limit): # emulate APILimit.try_consume behavior _ = limit.try_consume() # returns True/False if not job.started and not limit.capacity_reached and not limit.limit_reached: job.started = True return _start j.start.side_effect = _mk_side_effect() # update_in_batch: complete all *currently running* jobs and release capacity def complete_current_running(*_args, **_kwargs): for rj in list(manager._running_jobs): rj.completed = True manager._api_limit.release() update_job_mock.side_effect = complete_current_running # Wave 1 it = manager.completed_jobs() wave1 = [next(it), next(it)] assert set(wave1) == set(jobs[:2]) # Wave 2 wave2 = [next(it), next(it)] assert set(wave2) == set(jobs[2:4]) # Wave 3 (remaining single job) wave3 = [next(it)] assert wave3 == [jobs[4]] # No extra sleeps (every poll produced completions) time_mock.sleep.assert_not_called() def test_start_existing_running_jobs_before_pulling_new(self, api, mocker, update_job_mock, some_config): """ Manager must prioritize starting jobs already in the running set before pulling new ones. With capacity=1 and a pending (not-started) running job, no new jobs should be pulled. """ # One pending job already in the running set pending = mocker.Mock(spec=InsightAsyncJob, started=False, completed=False, new_jobs=[]) # Two more jobs available upstream more_jobs = [mocker.Mock(spec=InsightAsyncJob, started=False, completed=False, new_jobs=[]) for _ in range(2)] manager = InsightAsyncJobManager( api=api, jobs=iter(more_jobs), account_id=some_config["account_ids"][0], max_jobs_in_queue=1, # capacity cap = 1 ) manager._running_jobs = [pending] # Make pending.start succeed in consuming capacity and mark as started def start_ok(limit): assert limit.try_consume() is True pending.started = True pending.start.side_effect = start_ok # update will not change anything for this test update_job_mock.side_effect = lambda *args, **kwargs: None # Call the scheduler manager._start_jobs() # Capacity is 1, pending job took it, so no new jobs should be appended assert manager._running_jobs == [pending] assert pending.start.call_count == 1 # Upstream jobs were not touched yet assert all(j.start.call_count == 0 for j in more_jobs) def test_no_throttle_refresh_when_capacity_capped(self, api, mocker, update_job_mock, some_config): """ If concurrency capacity is already reached, manager should NOT refresh throttle while attempting to (re)start jobs. """ # Prepare API mocks acct = mocker.Mock() api.get_account.return_value = acct # Two running jobs, both "started" already; inflight will be set to capacity=1 running_job = mocker.Mock(spec=InsightAsyncJob, started=False, completed=False, new_jobs=[]) manager = InsightAsyncJobManager( api=api, jobs=[], account_id=some_config["account_ids"][0], max_jobs_in_queue=1, ) manager._running_jobs = [running_job] # Simulate capacity already fully used manager._api_limit._inflight = 1 # at capacity # When job tries to start, APILimit.try_consume should early-return False WITHOUT pinging def start_blocked(limit): assert limit.capacity_reached is True assert limit.try_consume() is False # early return path, no refresh running_job.start.side_effect = start_blocked update_job_mock.side_effect = lambda *args, **kwargs: None manager._start_jobs() # Since capacity was reached, there must be NO throttle ping api.get_account.assert_not_called()
TestInsightAsyncManager
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/scatter_nd_ops_test.py
{ "start": 34350, "end": 34889 }
class ____(ScatterNdTest): def setUp(self): super().setUp() config.enable_op_determinism() def tearDown(self): super().tearDown() config.disable_op_determinism() def testDeterminism(self): indices = array_ops.zeros([100000, 1], dtypes.int32) values = np.random.randn(100000) shape = [1] val = self.evaluate(self.scatter_nd(indices, values, shape)) for _ in range(5): val2 = self.evaluate(self.scatter_nd(indices, values, shape)) self.assertAllEqual(val, val2)
ScatterNdDeterminismTest
python
huggingface__transformers
src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py
{ "start": 35835, "end": 43642 }
class ____(Qwen2_5OmniPreTrainedModel): config: Qwen2_5OmniAudioEncoderConfig main_input_name = "input_features" input_modalities = "audio" _no_split_modules = ["Qwen2_5OmniAudioEncoderLayer"] _supports_sdpa = True def __init__(self, config: Qwen2_5OmniAudioEncoderConfig): super().__init__(config) self.dropout = config.dropout embed_dim = config.d_model self.num_mel_bins = config.num_mel_bins self.max_source_positions = config.max_source_positions self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0 self.n_window = config.n_window self.conv1 = nn.Conv1d(self.num_mel_bins, embed_dim, kernel_size=3, padding=1) self.conv2 = nn.Conv1d(embed_dim, embed_dim, kernel_size=3, stride=2, padding=1) self.positional_embedding = SinusoidsPositionEmbedding(self.max_source_positions, embed_dim) self.audio_bos_eos_token = nn.Embedding(2, config.output_dim) self.layers = nn.ModuleList([Qwen2_5OmniAudioEncoderLayer(config) for _ in range(config.encoder_layers)]) self.ln_post = nn.LayerNorm(config.d_model) self.avg_pooler = nn.AvgPool1d(2, stride=2) self.proj = nn.Linear(config.d_model, config.output_dim) self.gradient_checkpointing = False # Initialize weights and apply final processing self.post_init() def _freeze_parameters(self): for param in self.parameters(): param.requires_grad = False self._requires_grad = False def get_input_embeddings(self) -> nn.Module: return self.conv1 def set_input_embeddings(self, value: nn.Module): self.conv1 = value def _prepare_attention_mask(self, inputs_tensor: torch.Tensor, cu_seqlens: torch.Tensor) -> torch.Tensor: # Flash Attention 2 doesn't need a 4D mask and relies on `cu_seqlens/max_seqlen` # NOTE: the created attention masl only approximates the ragged FA2 attention by # allowing bidirectional attention within `cu_seqlens` blocks, and not attending between # blocks. Though it will not be a 100% match for FA2's `varlen` path if self.config._attn_implementation == "flash_attention_2": return None seq_length = inputs_tensor.shape[0] attention_mask = torch.full( [1, 1, seq_length, seq_length], torch.finfo(inputs_tensor.dtype).min, device=inputs_tensor.device, dtype=inputs_tensor.dtype, ) for i in range(1, len(cu_seqlens)): attention_mask[..., cu_seqlens[i - 1] : cu_seqlens[i], cu_seqlens[i - 1] : cu_seqlens[i]] = 0 return attention_mask @auto_docstring def forward( self, input_features, feature_lens=None, aftercnn_lens=None, **kwargs, ): r""" feature_lens (`torch.LongTensor` of shape `(batch_size,)`): mel length aftercnn_lens (`torch.LongTensor` of shape `(batch_size,)`): mel length after cnn """ chunk_num = torch.ceil(feature_lens / (self.n_window * 2)).long() chunk_lengths = torch.tensor( [self.n_window * 2] * chunk_num.sum(), dtype=torch.long, device=feature_lens.device, ) tail_chunk_index = F.pad(chunk_num, (1, 0), value=-1).cumsum(0)[1:] chunk_lengths[tail_chunk_index] = feature_lens % (self.n_window * 2) chunk_lengths = torch.where(chunk_lengths == 0, self.n_window * 2, chunk_lengths) chunk_list = input_features.split(chunk_lengths.tolist(), dim=1) padded_feature, padded_mask, padded_mask_after_cnn = self.padded_and_mask_function( chunk_list, chunk_lengths, padding_value=0, padding_side="right" ) padded_embed = nn.functional.gelu(self.conv1(padded_feature)) * padded_mask padded_embed = nn.functional.gelu(self.conv2(padded_embed)).transpose(1, 2) padded_embed = padded_embed + self.positional_embedding.positional_embedding[ : padded_embed.shape[1], : ].unsqueeze(0).to(padded_embed.dtype) hidden_states = padded_embed[padded_mask_after_cnn] cu_seqlens = torch.cat( ( torch.zeros(1, device=padded_mask_after_cnn.device, dtype=torch.int32), padded_mask_after_cnn.sum(1).cumsum(0), ) ).to(torch.int32) attention_mask = self._prepare_attention_mask(hidden_states, cu_seqlens) for encoder_layer in self.layers: layer_outputs = encoder_layer( hidden_states, cu_seqlens=cu_seqlens, attention_mask=attention_mask, **kwargs, ) hidden_states = layer_outputs[0] hidden_states_list = hidden_states.split(aftercnn_lens.tolist(), dim=0) token_audio_list = [] for each_audio_states in hidden_states_list: each_audio_states = self.avg_pooler(each_audio_states.transpose(0, 1)).transpose_(0, 1) each_audio_states = self.ln_post(each_audio_states) each_audio_states = self.proj(each_audio_states) token_audio_list.append(each_audio_states) token_audio = torch.cat(token_audio_list, dim=0) return BaseModelOutput(last_hidden_state=token_audio) def padded_and_mask_function(self, tensor_list, tensor_len, padding_value=0, padding_side="right"): """ Pads a sequence of tensors to their maximum length on indicated `padding_side`. Then prepares a mask so that pad tokens are not attended to. """ max_len = tensor_len.max() dim = tensor_list[0].shape[0] padded_tensor = torch.full( size=(len(tensor_list), dim, max_len), fill_value=padding_value, dtype=self.dtype, device=tensor_list[0].device, ) batch_mask = torch.zeros( (len(tensor_len), max_len), dtype=torch.long, device=padded_tensor.device, ) for i, length in enumerate(tensor_len): batch_mask[i, :length] = 1 padded_tensor[i, :, :length] = tensor_list[i] feature_lens_after_cnn = (tensor_len - 1) // 2 + 1 max_len_after_cnn = feature_lens_after_cnn.max() batch_mask_after_cnn = torch.zeros( (len(tensor_len), max_len_after_cnn), dtype=torch.long, device=padded_tensor.device, ) for i, length in enumerate(feature_lens_after_cnn): batch_mask_after_cnn[i, :length] = 1 return ( padded_tensor, batch_mask.unsqueeze(1), batch_mask_after_cnn.bool(), ) # Ignore copy def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor): """ Computes the output length of the convolutional layers and the output length of the audio encoder """ input_lengths = (input_lengths - 1) // 2 + 1 output_lengths = (input_lengths - 2) // 2 + 1 return input_lengths, output_lengths def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1) def apply_rotary_pos_emb_vision(tensor: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor: orig_dtype = tensor.dtype tensor = tensor.float() cos = freqs.cos() sin = freqs.sin() cos = cos.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float() sin = sin.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float() output = (tensor * cos) + (rotate_half(tensor) * sin) output = output.to(orig_dtype) return output
Qwen2_5OmniAudioEncoder
python
scipy__scipy
scipy/signal/tests/test_spectral.py
{ "start": 911, "end": 7600 }
class ____: def test_real_onesided_even(self): x = np.zeros(16) x[0] = 1 f, p = periodogram(x) assert_allclose(f, np.linspace(0, 0.5, 9)) q = np.ones(9) q[0] = 0 q[-1] /= 2.0 q /= 8 assert_allclose(p, q) def test_real_onesided_odd(self): x = np.zeros(15) x[0] = 1 f, p = periodogram(x) assert_allclose(f, np.arange(8.0)/15.0) q = np.ones(8) q[0] = 0 q *= 2.0/15.0 assert_allclose(p, q, atol=1e-15) def test_real_twosided(self): x = np.zeros(16) x[0] = 1 f, p = periodogram(x, return_onesided=False) assert_allclose(f, fftfreq(16, 1.0)) q = np.full(16, 1/16.0) q[0] = 0 assert_allclose(p, q) def test_real_spectrum(self): x = np.zeros(16) x[0] = 1 f, p = periodogram(x, scaling='spectrum') g, q = periodogram(x, scaling='density') assert_allclose(f, np.linspace(0, 0.5, 9)) assert_allclose(p, q/16.0) def test_integer_even(self): x = np.zeros(16, dtype=int) x[0] = 1 f, p = periodogram(x) assert_allclose(f, np.linspace(0, 0.5, 9)) q = np.ones(9) q[0] = 0 q[-1] /= 2.0 q /= 8 assert_allclose(p, q) def test_integer_odd(self): x = np.zeros(15, dtype=int) x[0] = 1 f, p = periodogram(x) assert_allclose(f, np.arange(8.0)/15.0) q = np.ones(8) q[0] = 0 q *= 2.0/15.0 assert_allclose(p, q, atol=1e-15) def test_integer_twosided(self): x = np.zeros(16, dtype=int) x[0] = 1 f, p = periodogram(x, return_onesided=False) assert_allclose(f, fftfreq(16, 1.0)) q = np.full(16, 1/16.0) q[0] = 0 assert_allclose(p, q) def test_complex(self): x = np.zeros(16, np.complex128) x[0] = 1.0 + 2.0j f, p = periodogram(x, return_onesided=False) assert_allclose(f, fftfreq(16, 1.0)) q = np.full(16, 5.0/16.0) q[0] = 0 assert_allclose(p, q) def test_unk_scaling(self): assert_raises(ValueError, periodogram, np.zeros(4, np.complex128), scaling='foo') @pytest.mark.skipif( sys.maxsize <= 2**32, reason="On some 32-bit tolerance issue" ) def test_nd_axis_m1(self): x = np.zeros(20, dtype=np.float64) x = x.reshape((2,1,10)) x[:,:,0] = 1.0 f, p = periodogram(x) assert_array_equal(p.shape, (2, 1, 6)) assert_array_almost_equal_nulp(p[0,0,:], p[1,0,:], 60) f0, p0 = periodogram(x[0,0,:]) assert_array_almost_equal_nulp(p0[np.newaxis,:], p[1,:], 60) @pytest.mark.skipif( sys.maxsize <= 2**32, reason="On some 32-bit tolerance issue" ) def test_nd_axis_0(self): x = np.zeros(20, dtype=np.float64) x = x.reshape((10,2,1)) x[0,:,:] = 1.0 f, p = periodogram(x, axis=0) assert_array_equal(p.shape, (6,2,1)) assert_array_almost_equal_nulp(p[:,0,0], p[:,1,0], 60) f0, p0 = periodogram(x[:,0,0]) assert_array_almost_equal_nulp(p0, p[:,1,0]) def test_window_external(self): x = np.zeros(16) x[0] = 1 f, p = periodogram(x, 10, 'hann') win = signal.get_window('hann', 16) fe, pe = periodogram(x, 10, win) assert_array_almost_equal_nulp(p, pe) assert_array_almost_equal_nulp(f, fe) win_err = signal.get_window('hann', 32) assert_raises(ValueError, periodogram, x, 10, win_err) # win longer than signal def test_padded_fft(self): x = np.zeros(16) x[0] = 1 f, p = periodogram(x) fp, pp = periodogram(x, nfft=32) assert_allclose(f, fp[::2]) assert_allclose(p, pp[::2]) assert_array_equal(pp.shape, (17,)) def test_empty_input(self): f, p = periodogram([]) assert_array_equal(f.shape, (0,)) assert_array_equal(p.shape, (0,)) for shape in [(0,), (3,0), (0,5,2)]: f, p = periodogram(np.empty(shape)) assert_array_equal(f.shape, shape) assert_array_equal(p.shape, shape) def test_empty_input_other_axis(self): for shape in [(3,0), (0,5,2)]: f, p = periodogram(np.empty(shape), axis=1) assert_array_equal(f.shape, shape) assert_array_equal(p.shape, shape) def test_short_nfft(self): x = np.zeros(18) x[0] = 1 f, p = periodogram(x, nfft=16) assert_allclose(f, np.linspace(0, 0.5, 9)) q = np.ones(9) q[0] = 0 q[-1] /= 2.0 q /= 8 assert_allclose(p, q) def test_nfft_is_xshape(self): x = np.zeros(16) x[0] = 1 f, p = periodogram(x, nfft=16) assert_allclose(f, np.linspace(0, 0.5, 9)) q = np.ones(9) q[0] = 0 q[-1] /= 2.0 q /= 8 assert_allclose(p, q) def test_real_onesided_even_32(self): x = np.zeros(16, 'f') x[0] = 1 f, p = periodogram(x) assert_allclose(f, np.linspace(0, 0.5, 9)) q = np.ones(9, 'f') q[0] = 0 q[-1] /= 2.0 q /= 8 assert_allclose(p, q) assert_(p.dtype == q.dtype) def test_real_onesided_odd_32(self): x = np.zeros(15, 'f') x[0] = 1 f, p = periodogram(x) assert_allclose(f, np.arange(8.0)/15.0) q = np.ones(8, 'f') q[0] = 0 q *= 2.0/15.0 assert_allclose(p, q, atol=1e-7) assert_(p.dtype == q.dtype) def test_real_twosided_32(self): x = np.zeros(16, 'f') x[0] = 1 f, p = periodogram(x, return_onesided=False) assert_allclose(f, fftfreq(16, 1.0)) q = np.full(16, 1/16.0, 'f') q[0] = 0 assert_allclose(p, q) assert_(p.dtype == q.dtype) def test_complex_32(self): x = np.zeros(16, 'F') x[0] = 1.0 + 2.0j f, p = periodogram(x, return_onesided=False) assert_allclose(f, fftfreq(16, 1.0)) q = np.full(16, 5.0/16.0, 'f') q[0] = 0 assert_allclose(p, q) assert_(p.dtype == q.dtype) def test_shorter_window_error(self): x = np.zeros(16) x[0] = 1 win = signal.get_window('hann', 10) expected_msg = ('the size of the window must be the same size ' 'of the input on the specified axis') with assert_raises(ValueError, match=expected_msg): periodogram(x, window=win)
TestPeriodogram
python
spack__spack
lib/spack/spack/test/hooks/absolutify_elf_sonames.py
{ "start": 525, "end": 2891 }
class ____: def __init__(self): self.calls = [] def __call__(self, *args, **kwargs): self.calls.append(args) @property def returncode(self): return 0 @pytest.mark.requires_executables("gcc") @skip_unless_linux def test_shared_libraries_visitor(tmp_path: pathlib.Path): """Integration test for soname rewriting""" gcc = Executable("gcc") # Create a directory structure like this: # ./no-soname.so # just a shared library without a soname # ./soname.so # a shared library with a soname # ./executable.so # an executable masquerading as a shared lib # ./libskipme.so # a shared library with a soname # ./mydir/parent_dir -> .. # a symlinked dir, causing a cycle # ./mydir/skip_symlink -> ../libskipme # a symlink to a library with fs.working_dir(str(tmp_path)): with open("hello.c", "w", encoding="utf-8") as f: f.write("int main(){return 0;}") gcc("hello.c", "-o", "no-soname.so", "--shared") gcc("hello.c", "-o", "soname.so", "--shared", "-Wl,-soname,example.so") gcc("hello.c", "-pie", "-o", "executable.so") gcc("hello.c", "-o", "libskipme.so", "-Wl,-soname,libskipme.so") os.mkdir("my_dir") os.symlink("..", os.path.join("my_dir", "parent_dir")) os.symlink(os.path.join("..", "libskipme.so"), os.path.join("my_dir", "skip_symlink")) # Visit the whole prefix, but exclude `skip_symlink` visitor = SharedLibrariesVisitor(exclude_list=["skip_symlink"]) fs.visit_directory_tree(str(tmp_path), visitor) relative_paths = visitor.get_shared_libraries_relative_paths() assert "no-soname.so" in relative_paths assert "soname.so" in relative_paths assert "executable.so" not in relative_paths assert "libskipme.so" not in relative_paths # Run the full hook of finding libs and setting sonames. patchelf = ExecutableIntercept() find_and_patch_sonames(str(tmp_path), ["skip_symlink"], patchelf) assert len(patchelf.calls) == 2 elf_1 = tmp_path / "no-soname.so" elf_2 = tmp_path / "soname.so" assert ("--set-soname", str(elf_1), str(elf_1)) in patchelf.calls assert ("--set-soname", str(elf_2), str(elf_2)) in patchelf.calls
ExecutableIntercept
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/ext/associationproxy.py
{ "start": 41899, "end": 44363 }
class ____(AssociationProxyInstance[_T]): """an :class:`.AssociationProxyInstance` that has an object as a target.""" _target_is_object: bool = True _is_canonical = True def adapt_to_entity( self, aliased_insp: AliasedInsp[Any] ) -> AliasedAssociationProxyInstance[_T]: return AliasedAssociationProxyInstance(self, aliased_insp) def contains(self, other: Any, **kw: Any) -> ColumnElement[bool]: """Produce a proxied 'contains' expression using EXISTS. This expression will be a composed product using the :meth:`.Relationship.Comparator.any`, :meth:`.Relationship.Comparator.has`, and/or :meth:`.Relationship.Comparator.contains` operators of the underlying proxied attributes. """ target_assoc = self._unwrap_target_assoc_proxy if target_assoc is not None: return self._comparator._criterion_exists( target_assoc.contains(other) if not target_assoc.scalar else target_assoc == other ) elif ( self._target_is_object and self.scalar and not self._value_is_scalar ): return self._comparator.has( getattr(self.target_class, self.value_attr).contains(other) ) elif self._target_is_object and self.scalar and self._value_is_scalar: raise exc.InvalidRequestError( "contains() doesn't apply to a scalar object endpoint; use ==" ) else: return self._comparator._criterion_exists( **{self.value_attr: other} ) def __eq__(self, obj: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501 # note the has() here will fail for collections; eq_() # is only allowed with a scalar. if obj is None: return or_( self._comparator.has(**{self.value_attr: obj}), self._comparator == None, ) else: return self._comparator.has(**{self.value_attr: obj}) def __ne__(self, obj: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501 # note the has() here will fail for collections; eq_() # is only allowed with a scalar. return self._comparator.has( getattr(self.target_class, self.value_attr) != obj )
ObjectAssociationProxyInstance
python
pandas-dev__pandas
asv_bench/benchmarks/io/csv.py
{ "start": 5569, "end": 6975 }
class ____(BaseIO): fname = "__test__.csv" @staticmethod def _create_df(rows, cols): index_cols = { "index1": np.random.randint(0, rows, rows), "index2": np.full(rows, 1, dtype=int), "index3": np.full(rows, 1, dtype=int), } data_cols = { f"col{i}": np.random.uniform(0, 100000.0, rows) for i in range(cols) } df = DataFrame({**index_cols, **data_cols}) return df def setup(self): ROWS = 100000 COLS = 5 # For tests using .head(), create an initial dataframe with this many times # more rows HEAD_ROW_MULTIPLIER = 10 self.df_standard_index = self._create_df(ROWS, COLS) self.df_custom_index_then_head = ( self._create_df(ROWS * HEAD_ROW_MULTIPLIER, COLS) .set_index(["index1", "index2", "index3"]) .head(ROWS) ) self.df_head_then_custom_index = ( self._create_df(ROWS * HEAD_ROW_MULTIPLIER, COLS) .head(ROWS) .set_index(["index1", "index2", "index3"]) ) def time_standard_index(self): self.df_standard_index.to_csv(self.fname) def time_multiindex(self): self.df_head_then_custom_index.to_csv(self.fname) def time_head_of_multiindex(self): self.df_custom_index_then_head.to_csv(self.fname)
ToCSVIndexes
python
dagster-io__dagster
python_modules/libraries/dagster-shared/dagster_shared/serdes/objects/definition_metadata.py
{ "start": 708, "end": 772 }
class ____: name: str type: str @record
DgResourceMetadata
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_W.py
{ "start": 1889, "end": 3118 }
class ____(Benchmark): r""" Wavy objective function. This class defines the W / Wavy [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Wavy}}(x) = 1 - \frac{1}{n} \sum_{i=1}^{n} \cos(kx_i)e^{-\frac{x_i^2}{2}} Where, in this exercise, :math:`k = 10`. The number of local minima is :math:`kn` and :math:`(k + 1)n` for odd and even :math:`k` respectively. Here, :math:`x_i \in [-\pi, \pi]` for :math:`i = 1, 2`. *Global optimum*: :math:`f(x) = 0` for :math:`x = [0, 0]` .. [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([-pi] * self.N, [pi] * self.N)) self.global_optimum = [[0.0 for _ in range(self.N)]] self.fglob = 0.0 def fun(self, x, *args): self.nfev += 1 return 1.0 - (1.0 / self.N) * sum(cos(10 * x) * exp(-x ** 2.0 / 2.0))
Wavy
python
kamyu104__LeetCode-Solutions
Python/maximum-number-of-operations-to-move-ones-to-the-end.py
{ "start": 38, "end": 413 }
class ____(object): def maxOperations(self, s): """ :type s: str :rtype: int """ result = curr = 0 for i in xrange(len(s)): if s[i] == '1': curr += 1 elif i+1 == len(s) or s[i+1] == '1': result += curr return result # Time: O(n) # Space: O(1) # greedy
Solution
python
davidhalter__jedi
jedi/inference/syntax_tree.py
{ "start": 35234, "end": 36373 }
class ____(ContextualizedNode): def infer(self): return _infer_subscript_list(self.context, self.node) def _infer_subscript_list(context, index): """ Handles slices in subscript nodes. """ if index == ':': # Like array[:] return ValueSet([iterable.Slice(context, None, None, None)]) elif index.type == 'subscript' and not index.children[0] == '.': # subscript basically implies a slice operation # e.g. array[:3] result = [] for el in index.children: if el == ':': if not result: result.append(None) elif el.type == 'sliceop': if len(el.children) == 2: result.append(el.children[1]) else: result.append(el) result += [None] * (3 - len(result)) return ValueSet([iterable.Slice(context, *result)]) elif index.type == 'subscriptlist': return ValueSet([iterable.SequenceLiteralValue(context.inference_state, context, index)]) # No slices return context.infer_node(index)
ContextualizedSubscriptListNode
python
ansible__ansible
test/lib/ansible_test/_internal/become.py
{ "start": 2130, "end": 2516 }
class ____(Su): """Become using 'su' in ansible-test and then after bootstrapping use 'sudo' for other ansible commands.""" @classmethod def name(cls) -> str: """The name of this plugin.""" return 'su_sudo' @property def method(self) -> str: """The name of the Ansible become plugin that is equivalent to this.""" return 'sudo'
SuSudo
python
spyder-ide__spyder
spyder/widgets/sidebardialog.py
{ "start": 2215, "end": 20121 }
class ____(QDialog, SpyderFontsMixin): """Sidebar dialog.""" # Constants ITEMS_MARGIN = 2 * AppStyle.MarginSize ITEMS_PADDING = ( AppStyle.MarginSize if (MAC or WIN) else 2 * AppStyle.MarginSize ) CONTENTS_WIDTH = 230 if MAC else (200 if WIN else 240) ICON_SIZE = 20 # To be set by childs TITLE = "" ICON = QIcon() MIN_WIDTH = 800 MIN_HEIGHT = 600 FIXED_SIZE = False PAGES_MINIMUM_WIDTH = 600 PAGE_CLASSES: List[Type[SidebarPage]] = [] def __init__(self, parent=None): QDialog.__init__(self, parent) # ---- Attributes self.items_font = self.get_font( SpyderFontType.Interface, font_size_delta=1 ) self._is_shown = False self._separators = [] self._active_pages = {} # ---- Size if self.FIXED_SIZE: self.setFixedWidth(self.MIN_WIDTH) self.setFixedHeight(self.MIN_HEIGHT) else: self.setMinimumWidth(self.MIN_WIDTH) self.setMinimumHeight(self.MIN_HEIGHT) # ---- Widgets self.pages_widget = QStackedWidget(self) self.contents_widget = QListWidget(self) buttons_box, buttons_layout = self.create_buttons() # Destroying the C++ object right after closing the dialog box, # otherwise it may be garbage-collected in another QThread # (e.g. the editor's analysis thread in Spyder), thus leading to # a segmentation fault on UNIX or an application crash on Windows self.setAttribute(Qt.WA_DeleteOnClose) self.setWindowTitle(self.TITLE) self.setWindowIcon(self.ICON) # ---- Widgets setup self.pages_widget.setMinimumWidth(self.PAGES_MINIMUM_WIDTH) self.contents_widget.setMovement(QListView.Static) self.contents_widget.setSpacing(3) self.contents_widget.setCurrentRow(0) self.contents_widget.setIconSize(QSize(self.ICON_SIZE, self.ICON_SIZE)) self.contents_widget.setFixedWidth(self.CONTENTS_WIDTH) # Don't show horizontal scrollbar because it doesn't look good. Instead # we show tooltips if the text doesn't fit in contents_widget width. self.contents_widget.setHorizontalScrollBarPolicy( Qt.ScrollBarAlwaysOff ) # ---- Layout contents_and_pages_layout = QGridLayout() contents_and_pages_layout.addWidget(self.contents_widget, 0, 0) contents_and_pages_layout.addWidget(self.pages_widget, 0, 1) contents_and_pages_layout.setContentsMargins(0, 0, 0, 0) contents_and_pages_layout.setColumnStretch(0, 1) contents_and_pages_layout.setColumnStretch(1, 3) contents_and_pages_layout.setHorizontalSpacing(0) layout = QVBoxLayout() layout.addLayout(contents_and_pages_layout) layout.addSpacing( - (2 * AppStyle.MarginSize) if MAC else AppStyle.MarginSize ) layout.addLayout(buttons_layout) self.setLayout(layout) # ---- Stylesheet self.setStyleSheet(self._main_stylesheet) self._contents_css = self._generate_contents_stylesheet() self.contents_widget.setStyleSheet(self._contents_css.toString()) self.contents_widget.verticalScrollBar().setStyleSheet( self._contents_scrollbar_stylesheet ) # ---- Signals and slots self.pages_widget.currentChanged.connect(self.current_page_changed) self.contents_widget.currentRowChanged.connect( self.pages_widget.setCurrentIndex) buttons_box.accepted.connect(self.accept) buttons_box.rejected.connect(self.reject) buttons_box.clicked.connect(self.button_clicked) # Add pages to the dialog self._add_pages() # Set index to the initial page if self.PAGE_CLASSES: self.set_current_index(0) # ---- Public API to be overridden by children # ------------------------------------------------------------------------- def button_clicked(self, button): """Actions to perform after one of the dialog's buttons is clicked.""" pass def current_page_changed(self, index): """Actions to perform after the current page in the dialog changes.""" pass def create_buttons(self): """ Create the buttons that will be displayed in the dialog. Override this method if you want different buttons in it. """ bbox = SpyderDialogButtonBox(QDialogButtonBox.Ok) layout = QHBoxLayout() layout.addWidget(bbox) return bbox, layout # ---- Public API # ------------------------------------------------------------------------- def get_current_index(self): """Return current page index""" return self.contents_widget.currentRow() def set_current_index(self, index): """Set current page index""" self.contents_widget.setCurrentRow(index) def get_item(self, index: int | None = None) -> QListWidgetItem: """Get item on the left panel corresponding to `index`.""" if index is None: index = self.get_current_index() return self.contents_widget.item(index) def get_page( self, index: int | None = None ) -> Union[QWidget, SidebarPage] | None: """Return page widget on the right panel corresponding to `index`.""" if index is None: page = self.pages_widget.currentWidget() else: page = self.pages_widget.widget(index) # Not all pages are config pages (e.g. separators have a simple QWidget # as their config page). So, we need to check for this. if page and hasattr(page, 'widget'): return page.widget() def hide_page(self, index=None): """Hide page corresponding to `index`.""" if index is None: index = self.get_current_index() self._active_pages[index] = False # Hide entry from contents_widget self.contents_widget.item(index).setHidden(True) # If the current page is not the first one (index=0), then we set as # the new current one the first active page before it. if index > 1: # With this we move backwards from index-1 up to 0 until we find # an active page. for i in range(index - 1, -1, -1): if self._active_pages.get(i): self.set_current_index(i) break elif index == 1: # If the current page is the second one, we set the first one as # current. self.set_current_index(0) def add_separator(self): """Add a horizontal line to separate different sections.""" # Solution taken from https://stackoverflow.com/a/24819554/438386 item = QListWidgetItem(self.contents_widget) item.setFlags(Qt.NoItemFlags) size = ( AppStyle.MarginSize * 3 if (MAC or WIN) else AppStyle.MarginSize * 5 ) item.setSizeHint(QSize(size, size)) hline = QFrame(self.contents_widget) hline.setFrameShape(QFrame.HLine) hline.setStyleSheet(self._separators_stylesheet) self.contents_widget.setItemWidget(item, hline) # This is necessary to keep in sync the contents_widget and # pages_widget indexes. self.pages_widget.addWidget(QWidget(self)) # Save separators to perform certain operations only on them self._separators.append(hline) def add_page(self, page: SidebarPage, initialize: bool = True): """Add page instance to the dialog.""" if initialize: page.initialize() page.show_this_page.connect(lambda row=self.contents_widget.count(): self.contents_widget.setCurrentRow(row)) # Container widget so that we can set margins around the page layout = QHBoxLayout() layout.addWidget(page) # The smaller margin to the right is necessary to compensate for the # space added by the vertical scrollbar layout.setContentsMargins(27, 27, 15, 27) # This is necessary to show the full contents of the page in case it # doesn't fit vertically in the available space. layout.setSizeConstraint(QLayout.SetFixedSize) container = QWidget(self) container.setLayout(layout) container.page = page # Add container to a scroll area in case the page contents don't fit # in the dialog scrollarea = PageScrollArea(self) scrollarea.setObjectName('sidebardialog-scrollarea') scrollarea.setWidgetResizable(False) scrollarea.setWidget(container) scrollarea.setAlignment(Qt.AlignHCenter) scrollarea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.pages_widget.addWidget(scrollarea) # Add plugin entry item to contents widget item = QListWidgetItem(self.contents_widget) item.setText(str(page.get_name())) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) # In case the page doesn't have an icon try: item.setIcon(page.get_icon()) except TypeError: pass # Set font for items item.setFont(self.items_font) # Save which pages are active in case we need to hide some self._active_pages[self.contents_widget.count() - 1] = True def number_of_pages(self): """Get the number of pages in the dialog.""" return self.pages_widget.count() # ---- Qt methods # ------------------------------------------------------------------------- def showEvent(self, event): """Adjustments when the widget is shown.""" if not self._is_shown: self._add_tooltips() self._adjust_items_margin() self._is_shown = True super().showEvent(event) # This is necessary to paint the separators as expected when there # are elided items in contents_widget. with signals_blocked(self): height = self.height() self.resize(self.width(), height + 1) self.resize(self.width(), height - 1) def resizeEvent(self, event): """ Reimplement Qt method to perform several operations when resizing. """ QDialog.resizeEvent(self, event) self._on_resize_event() # ---- Private API # ------------------------------------------------------------------------- def _add_tooltips(self): """ Check if it's necessary to add tooltips to the contents_widget items. """ contents_width = self.contents_widget.width() metrics = QFontMetricsF(self.items_font) for i in range(self.contents_widget.count()): item = self.contents_widget.item(i) # Item width item_width = self.contents_widget.visualItemRect(item).width() # Set tooltip if item_width >= contents_width: item.setToolTip(item.text()) else: # This covers the case when item_width is too close to # contents_width without the scrollbar being visible, which # can't be detected by Qt with the check above. scrollbar = self.contents_widget.verticalScrollBar() if scrollbar.isVisible(): if MAC: # This is a crude heuristic to detect if we need to add # tooltips on Mac. However, it's the best we can do # (the approach for other OSes below ends up adding # tooltips to all items) and it works for all our # localized languages. text_width = metrics.boundingRect(item.text()).width() if text_width + 70 > item_width - 5: item.setToolTip(item.text()) else: if item_width > (contents_width - scrollbar.width()): item.setToolTip(item.text()) def _adjust_items_margin(self): """ Adjust margins of contents_widget items depending on if its vertical scrollbar is visible. Notes ----- We need to do this only in Mac because Qt doesn't account for the scrollbar width in most widgets. """ if MAC: scrollbar = self.contents_widget.verticalScrollBar() extra_margin = ( AppStyle.MacScrollBarWidth if scrollbar.isVisible() else 0 ) item_margin = ( f'0px {self.ITEMS_MARGIN + extra_margin}px ' f'0px {self.ITEMS_MARGIN}px' ) self._contents_css['QListView::item'].setValues( margin=item_margin ) self.contents_widget.setStyleSheet(self._contents_css.toString()) def _adjust_separators_width(self): """ Adjust the width of separators present in contents_widget depending on if its vertical scrollbar is visible. Notes ----- We need to do this only in Mac because Qt doesn't set the widths correctly when there are elided items. """ if MAC: scrollbar = self.contents_widget.verticalScrollBar() for sep in self._separators: if self.CONTENTS_WIDTH != 230: raise ValueError( "The values used here for the separators' width were " "the ones reported by Qt for a contents_widget width " "of 230px. Since this value changed, you need to " "update them." ) # These are the values reported by Qt when CONTENTS_WIDTH = 230 # and the interface language is English. if scrollbar.isVisible(): sep.setFixedWidth(188) else: sep.setFixedWidth(204) @property def _main_stylesheet(self): """Main style for this widget.""" # Use the preferences tabbar stylesheet as the base one and extend it. tabs_stylesheet = PREFERENCES_TABBAR_STYLESHEET.get_copy() css = tabs_stylesheet.get_stylesheet() # Remove border of all scroll areas for pages css['QScrollArea#sidebardialog-scrollarea'].setValues( border='0px', ) # Add more spacing between QGroupBoxes than normal. css.QGroupBox.setValues( marginBottom='15px', ) # Substract extra padding css["QToolTip"].setValues( paddingRight="-2px", ) # Substract extra padding that comes from QLineEdit css["QLineEdit QToolTip"].setValues( padding="-2px -3px", ) # This is necessary to correctly show disabled buttons in this kind of # dialogs (oddly QDarkstyle doesn't set this color as expected). css["QPushButton:disabled"].setValues( backgroundColor=SpyderPalette.COLOR_BACKGROUND_4, ) css["QPushButton:checked:disabled"].setValues( backgroundColor=SpyderPalette.COLOR_BACKGROUND_6, ) return css.toString() def _generate_contents_stylesheet(self): """Generate stylesheet for the contents widget""" css = qstylizer.style.StyleSheet() # This also sets the background color of the vertical scrollbar # associated to this widget css.setValues( backgroundColor=SpyderPalette.COLOR_BACKGROUND_2 ) # Main style css.QListView.setValues( padding=f'{self.ITEMS_MARGIN}px 0px', border=f'1px solid {SpyderPalette.COLOR_BACKGROUND_2}', ) # Remove border color on focus css['QListView:focus'].setValues( border=f'1px solid {SpyderPalette.COLOR_BACKGROUND_2}', ) # Add margin and padding for items css['QListView::item'].setValues( padding=f'{self.ITEMS_PADDING}px', margin=f'0px {self.ITEMS_MARGIN}px' ) # Set border radius and background color for hover, active and inactive # states of items css['QListView::item:hover'].setValues( borderRadius=SpyderPalette.SIZE_BORDER_RADIUS, ) for state in ['item:selected:active', 'item:selected:!active']: css[f'QListView::{state}'].setValues( borderRadius=SpyderPalette.SIZE_BORDER_RADIUS, backgroundColor=SpyderPalette.COLOR_BACKGROUND_4 ) return css @property def _contents_scrollbar_stylesheet(self): css = qstylizer.style.StyleSheet() # Give border a darker color to stand out over the background css.setValues( border=f"1px solid {SpyderPalette.COLOR_BACKGROUND_5}" ) return css.toString() @property def _separators_stylesheet(self): css = qstylizer.style.StyleSheet() # This makes separators stand out better over the background css.setValues( backgroundColor=SpyderPalette.COLOR_BACKGROUND_5 ) return css.toString() @qdebounced(timeout=40) def _on_resize_event(self): """Method to run when Qt emits a resize event.""" self._add_tooltips() self._adjust_items_margin() self._adjust_separators_width() def _add_pages(self): """Add pages to the dialog.""" for PageClass in self.PAGE_CLASSES: page = PageClass(self) self.add_page(page)
SidebarDialog
python
dagster-io__dagster
python_modules/libraries/dagster-dg-core/dagster_dg_core/utils/__init__.py
{ "start": 14163, "end": 25908 }
class ____(DgClickHelpMixin, ClickAliasedGroup): # pyright: ignore[reportIncompatibleMethodOverride] def __init__(self, *args, unlaunched: bool = False, **kwargs): """DgClickGroup with conditional hiding for unlaunched features. Args: unlaunched: If True, the group will be hidden unless DG_SHOW_UNLAUNCHED_COMMANDS environment variable is set. """ if unlaunched: kwargs["hidden"] = not show_dg_unlaunched_commands() super().__init__(*args, **kwargs) # ######################## # ##### JSON SCHEMA # ######################## _JSON_SCHEMA_TYPE_TO_CLICK_TYPE = {"string": str, "integer": int, "number": float, "boolean": bool} def _get_field_type_info_from_field_info(field_info: Mapping[str, Any]) -> Mapping[str, Any]: """Extract the dict holding field type info (in particular, the type and whether it is an array) from a JSON schema field info dict. If the field info is not a union type, returns itself. If the field info is a union type, returns the first non-null type. If the field info has no type info, default to type info for type "string". """ if field_info.get("type"): return field_info else: return next( (t for t in field_info.get("anyOf", []) if t.get("type") not in (None, "null")), {"type": "string"}, ) def json_schema_property_to_click_option( key: str, field_info: Mapping[str, Any], required: bool ) -> click.Option: # Extract the dict holding field type info (in particular, the type and whether it is an array) # This might be nested in an anyOf block field_type_info = _get_field_type_info_from_field_info(field_info) is_array_type = field_type_info.get("type") == "array" field_type = ( field_type_info.get("items", {}).get("type") or field_type_info.get("type") or "string" ) option_name = f"--{key.replace('_', '-')}" # Handle object type fields as JSON strings if field_type == "object": option_type = str # JSON string input help_text = f"[scaffolder parameter] {key} (JSON string)" callback = parse_json_option # Handle other basic types else: option_type = _JSON_SCHEMA_TYPE_TO_CLICK_TYPE[field_type] help_text = f"(scaffolder param) {key}" callback = None return click.Option( [option_name], type=option_type, required=required, help=help_text, callback=callback, multiple=is_array_type, ) def parse_json_option(context: click.Context, param: click.Option, value: str): """Callback to parse JSON string options into Python objects.""" if value: try: return json.loads(value) except json.JSONDecodeError: raise click.BadParameter(f"Invalid JSON string for '{param.name}'.") return value # ######################## # ##### TOML MANIPULATION # ######################## TomlPath: TypeAlias = tuple[Union[str, int], ...] TomlDoc: TypeAlias = Union["tomlkit.TOMLDocument", dict[str, Any]] def load_toml_as_dict(path: Path) -> dict[str, Any]: import tomlkit return tomlkit.parse(path.read_text()).unwrap() def get_toml_node( doc: TomlDoc, path: TomlPath, expected_type: Union[type[T], tuple[type[T], ...]], ) -> T: """Given a tomlkit-parsed document/table (`doc`),retrieve the nested value at `path` and ensure it is of type `expected_type`. Returns the value if so, or raises a KeyError / TypeError if not. """ value = _gather_toml_nodes(doc, path)[-1] if not isinstance(value, expected_type): expected_types = expected_type if isinstance(expected_type, tuple) else (expected_type,) type_str = " or ".join(t.__name__ for t in expected_types) raise TypeError( f"Expected '{toml_path_to_str(path)}' to be {type_str}, " f"but got {type(value).__name__} instead." ) return value def has_toml_node(doc: TomlDoc, path: TomlPath) -> bool: """Given a tomlkit-parsed document/table (`doc`), return whether a value is defined at `path`.""" result = _gather_toml_nodes(doc, path, error_on_missing=False) return False if result is None else True def delete_toml_node(doc: TomlDoc, path: TomlPath) -> None: """Given a tomlkit-parsed document/table (`doc`), delete the nested value at `path`. Raises an error if the leading keys do not already lead to a TOML container node. """ import tomlkit nodes = _gather_toml_nodes(doc, path) container = nodes[-2] if len(nodes) > 1 else doc key_or_index = path[-1] if isinstance(container, dict): assert isinstance(key_or_index, str) # We already know this from _traverse_toml_path del container[key_or_index] elif isinstance(container, tomlkit.TOMLDocument): assert isinstance(key_or_index, str) # We already know this from _traverse_toml_path container.remove(key_or_index) elif isinstance(container, list): assert isinstance(key_or_index, int) # We already know this from _traverse_toml_path container.pop(key_or_index) else: raise Exception("Unreachable.") def set_toml_node(doc: TomlDoc, path: TomlPath, value: object) -> None: """Given a tomlkit-parsed document/table (`doc`),set a nested value at `path` to `value`. Raises an error if the leading keys do not already lead to a TOML container node. """ container = _gather_toml_nodes(doc, path[:-1])[-1] if len(path) > 1 else doc key_or_index = path[-1] # type: ignore # pyright bug if isinstance(container, dict): if not isinstance(key_or_index, str): raise TypeError(f"Expected key to be a string, but got {type(key_or_index).__name__}") container[key_or_index] = value elif isinstance(container, list): if not isinstance(key_or_index, int): raise TypeError(f"Expected key to be an integer, but got {type(key_or_index).__name__}") container[key_or_index] = value else: raise Exception("Unreachable.") @overload def _gather_toml_nodes( doc: TomlDoc, path: TomlPath, error_on_missing: Literal[True] = ... ) -> list[Any]: ... @overload def _gather_toml_nodes( doc: TomlDoc, path: TomlPath, error_on_missing: Literal[False] = ... ) -> Optional[list[Any]]: ... def _gather_toml_nodes( doc: TomlDoc, path: TomlPath, error_on_missing: bool = True ) -> Optional[list[Any]]: nodes: list[Any] = [] current: Any = doc for key in path: if isinstance(key, str): if not isinstance(current, dict) or key not in current: if error_on_missing: raise KeyError(f"Key '{key}' not found in path: {toml_path_to_str(path)}") return None current = current[key] elif isinstance(key, int): if not isinstance(current, list) or key < 0 or key >= len(current): if error_on_missing: raise KeyError(f"Index '{key}' not found in path: {toml_path_to_str(path)}") return None current = current[key] else: raise TypeError(f"Expected key to be a string or integer, but got {type(key)}") nodes.append(current) return nodes def toml_path_to_str(path: TomlPath) -> str: if len(path) == 0: return "" first = path[0] if not isinstance(first, str): raise TypeError(f"Expected first element of path to be a string, but got {type(first)}") elif len(path) == 1: return first else: str_path = first for item in path[1:]: if isinstance(item, int): str_path += f"[{item}]" elif isinstance(item, str): str_path += f".{item}" else: raise TypeError( f"Expected path elements to be strings or integers, but got {type(item)}" ) return str_path def toml_path_from_str(path: str) -> TomlPath: tokens = [] for segment in path.split("."): # Split each segment by bracketed chunks, e.g. "key[1]" -> ["key", "[1]"] parts = re.split(r"(\[\d+\])", segment) for p in parts: if not p: # Skip empty strings continue if p.startswith("[") and p.endswith("]"): tokens.append(int(p[1:-1])) # Convert "[1]" to integer 1 else: tokens.append(p) return tuple(tokens) def create_toml_node( doc: dict[str, Any], path: tuple[Union[str, int], ...], value: object, ) -> None: """Set a toml node at a path that consists of a sequence of keys and integer indices. Intermediate containers that don't yet exist will be created along the way based on the types of the keys. Note that this does not support TOMLDocument objects, only plain dictionaries. The reason is that the correct type of container to insert at intermediate nodes is ambiguous for TOMLDocmuent objects. """ import tomlkit if isinstance(doc, tomlkit.TOMLDocument): raise TypeError( "`create_toml_node` only works on the plain dictionary representation of a TOML document." ) current: Any = doc for i, key in enumerate(path): is_final_key = i == len(path) - 1 if isinstance(key, str): if not isinstance(current, dict): raise KeyError(f"Key '{key}' not found in path: {toml_path_to_str(path)}") elif is_final_key: current[key] = value elif key not in current: current[key] = _get_new_container_node(path[i + 1]) current = current[key] elif isinstance(key, int): if not isinstance(current, list): raise KeyError(f"Index '{key}' not found in path: {toml_path_to_str(path)}") is_key_in_range = key >= 0 and key < len(current) is_append_key = key == len(current) if is_final_key and is_key_in_range: current[key] = value elif is_final_key and is_append_key: current.append(value) elif is_key_in_range: current = current[key] elif is_append_key: current.append(_get_new_container_node(path[i + 1])) current = current[key] else: raise KeyError(f"Key '{key}' not found in path: {toml_path_to_str(path)}") else: raise TypeError(f"Expected key to be a string or integer, but got {type(key)}") def _get_new_container_node( representative_key: Union[int, str], ) -> Union[dict[str, Any], list[Any]]: return [] if isinstance(representative_key, int) else {} @contextlib.contextmanager def capture_stdout() -> Iterator[TextIO]: """Capture stdout and return it as a string.""" stdout = sys.stdout string_buffer = io.StringIO() try: sys.stdout = string_buffer yield string_buffer finally: sys.stdout = stdout @contextlib.contextmanager def activate_venv(venv_path: Union[str, Path]) -> Iterator[None]: """Simulated activation of the passed in virtual environment for the current process.""" venv_path = (Path(venv_path) if isinstance(venv_path, str) else venv_path).absolute() with environ( { "VIRTUAL_ENV": str(venv_path), "PATH": os.pathsep.join( [ str(venv_path / ("Scripts" if sys.platform == "win32" else "bin")), os.getenv("PATH", ""), ] ), } ): yield
DgClickGroup
python
django__django
django/contrib/sitemaps/__init__.py
{ "start": 5990, "end": 6951 }
class ____(Sitemap): priority = None changefreq = None def __init__(self, info_dict, priority=None, changefreq=None, protocol=None): self.queryset = info_dict["queryset"] self.date_field = info_dict.get("date_field") self.priority = self.priority or priority self.changefreq = self.changefreq or changefreq self.protocol = self.protocol or protocol def items(self): # Make sure to return a clone; we don't want premature evaluation. return self.queryset.filter() def lastmod(self, item): if self.date_field is not None: return getattr(item, self.date_field) return None def get_latest_lastmod(self): if self.date_field is not None: return ( self.queryset.order_by("-" + self.date_field) .values_list(self.date_field, flat=True) .first() ) return None
GenericSitemap
python
scipy__scipy
benchmarks/benchmarks/lsq_problems.py
{ "start": 14178, "end": 15429 }
class ____(LSQBenchmarkProblem): """The problem of fitting kinetic parameters for an enzyme reaction, [1]_. Number of variables --- 4, number of residuals --- 11, no bounds. .. [1] Brett M. Averick et al. "The MINPACK-2 Test Problem Collection", p. 29 """ INITIAL_GUESSES = [ np.array([2.5, 3.9, 4.15, 3.9]) * 1e-1 ] def __init__(self, x0_ind): super().__init__(4, 11, 3.075057e-04, x0_ind) self.u = np.array([4.0, 2.0, 1.0, 5.0e-1, 2.5e-1, 1.67e-1, 1.25e-1, 1.0e-1, 8.33e-2, 7.14e-2, 6.25e-2]) self.y = np.array([1.957e-1, 1.947e-1, 1.735e-1, 1.6e-1, 8.44e-2, 6.27e-2, 4.56e-2, 3.42e-2, 3.23e-2, 2.35e-2, 2.46e-2]) def fun(self, x): return (x[0] * (self.u ** 2 + x[1] * self.u) / (self.u ** 2 + x[2] * self.u + x[3]) - self.y) def jac(self, x): J = np.empty((self.m, self.n)) den = self.u ** 2 + x[2] * self.u + x[3] num = self.u ** 2 + x[1] * self.u J[:, 0] = num / den J[:, 1] = x[0] * self.u / den J[:, 2] = -x[0] * num * self.u / den ** 2 J[:, 3] = -x[0] * num / den ** 2 return J
EnzymeReaction
python
huggingface__transformers
src/transformers/models/vision_text_dual_encoder/processing_vision_text_dual_encoder.py
{ "start": 819, "end": 1668 }
class ____(ProcessorMixin): r""" Constructs a VisionTextDualEncoder processor which wraps an image processor and a tokenizer into a single processor. [`VisionTextDualEncoderProcessor`] offers all the functionalities of [`AutoImageProcessor`] and [`AutoTokenizer`]. See the [`~VisionTextDualEncoderProcessor.__call__`] and [`~VisionTextDualEncoderProcessor.decode`] for more information. Args: image_processor ([`AutoImageProcessor`], *optional*): The image processor is a required input. tokenizer ([`PreTrainedTokenizer`], *optional*): The tokenizer is a required input. """ def __init__(self, image_processor=None, tokenizer=None, **kwargs): super().__init__(image_processor, tokenizer) __all__ = ["VisionTextDualEncoderProcessor"]
VisionTextDualEncoderProcessor
python
mlflow__mlflow
mlflow/webhooks/types.py
{ "start": 4394, "end": 4953 }
class ____(TypedDict): """Payload sent when an alias is deleted from a model version. Example payload: .. code-block:: python { "name": "example_model", "alias": "example_alias", } """ name: str """The name of the registered model.""" alias: str """The alias being deleted.""" @classmethod def example(cls) -> "ModelVersionAliasDeletedPayload": return cls( name="example_model", alias="example_alias", )
ModelVersionAliasDeletedPayload
python
PrefectHQ__prefect
src/prefect/server/database/orm_models.py
{ "start": 9915, "end": 11117 }
class ____(Base): """ SQLAlchemy model of artifacts. """ key: Mapped[Optional[str]] = mapped_column(index=True) task_run_id: Mapped[Optional[uuid.UUID]] = mapped_column(index=True) flow_run_id: Mapped[Optional[uuid.UUID]] = mapped_column(index=True) type: Mapped[Optional[str]] data: Mapped[Optional[Any]] = mapped_column(sa_JSON) description: Mapped[Optional[str]] # Suffixed with underscore as attribute name 'metadata' is reserved for the MetaData instance when using a declarative base class. metadata_: Mapped[Optional[dict[str, str]]] = mapped_column(sa_JSON) @declared_attr.directive @classmethod def __table_args__(cls) -> Iterable[sa.Index]: return ( sa.Index( "ix_artifact__key", cls.key, ), sa.Index( "ix_artifact__key_created_desc", cls.key, cls.created.desc(), postgresql_include=[ "id", "updated", "type", "task_run_id", "flow_run_id", ], ), )
Artifact
python
etianen__django-reversion
tests/test_app/tests/test_models.py
{ "start": 17321, "end": 17741 }
class ____(TestBase): def setUp(self): reversion.register(TestModelWithUniqueConstraint) def testTransactionInRollbackState(self): with reversion.create_revision(): try: TestModelWithUniqueConstraint.objects.create(name='A') TestModelWithUniqueConstraint.objects.create(name='A') except Exception: pass
TransactionRollbackTest
python
kamyu104__LeetCode-Solutions
Python/koko-eating-bananas.py
{ "start": 33, "end": 534 }
class ____(object): def minEatingSpeed(self, piles, H): """ :type piles: List[int] :type H: int :rtype: int """ def possible(piles, H, K): return sum((pile-1)//K+1 for pile in piles) <= H left, right = 1, max(piles) while left <= right: mid = left + (right-left)//2 if possible(piles, H, mid): right = mid-1 else: left = mid+1 return left
Solution
python
langchain-ai__langchain
libs/partners/perplexity/tests/integration_tests/test_chat_models_standard.py
{ "start": 237, "end": 927 }
class ____(ChatModelIntegrationTests): @property def chat_model_class(self) -> type[BaseChatModel]: return ChatPerplexity @property def chat_model_params(self) -> dict: return {"model": "sonar"} @pytest.mark.xfail(reason="TODO: handle in integration.") def test_double_messages_conversation(self, model: BaseChatModel) -> None: super().test_double_messages_conversation(model) @pytest.mark.xfail(reason="Raises 400: Custom stop words not supported.") def test_stop_sequence(self, model: BaseChatModel) -> None: super().test_stop_sequence(model) # TODO, API regressed for some reason after 2025-04-15
TestPerplexityStandard
python
tensorflow__tensorflow
tensorflow/python/framework/convert_to_constants.py
{ "start": 32928, "end": 33200 }
class ____(_FunctionConverterData): """Container for ConcreteFunction-based conversion data in Eager mode.""" def _eval(self, tensor): """Returns the value in the tensor. Must be implemented in sub-classes.""" return tensor.numpy()
_FunctionConverterDataInEager
python
joke2k__faker
faker/typing.py
{ "start": 931, "end": 1192 }
class ____: name: str timezones: Sequence[str] alpha_2_code: str alpha_3_code: str continent: str capital: str __all__ = ["OrderedDictType", "CreditCard", "CardType", "Country", "DateParseType", "HueType", "SexLiteral", "SeedType"]
Country
python
django__django
tests/defer/tests.py
{ "start": 11721, "end": 14620 }
class ____(AssertionMixin, TestCase): def test_defer_proxy(self): """ Ensure select_related together with only on a proxy model behaves as expected. See #17876. """ related = Secondary.objects.create(first="x1", second="x2") ChildProxy.objects.create(name="p1", value="xx", related=related) children = ChildProxy.objects.select_related().only("id", "name") self.assertEqual(len(children), 1) child = children[0] self.assert_delayed(child, 2) self.assertEqual(child.name, "p1") self.assertEqual(child.value, "xx") def test_defer_inheritance_pk_chaining(self): """ When an inherited model is fetched from the DB, its PK is also fetched. When getting the PK of the parent model it is useful to use the already fetched parent model PK if it happens to be available. """ s1 = Secondary.objects.create(first="x1", second="y1") bc = BigChild.objects.create(name="b1", value="foo", related=s1, other="bar") bc_deferred = BigChild.objects.only("name").get(pk=bc.pk) with self.assertNumQueries(0): bc_deferred.id self.assertEqual(bc_deferred.pk, bc_deferred.id) def test_eq(self): s1 = Secondary.objects.create(first="x1", second="y1") s1_defer = Secondary.objects.only("pk").get(pk=s1.pk) self.assertEqual(s1, s1_defer) self.assertEqual(s1_defer, s1) def test_refresh_not_loading_deferred_fields(self): s = Secondary.objects.create() rf = Primary.objects.create(name="foo", value="bar", related=s) rf2 = Primary.objects.only("related", "value").get() rf.name = "new foo" rf.value = "new bar" rf.save() with self.assertNumQueries(1): rf2.refresh_from_db() self.assertEqual(rf2.value, "new bar") with self.assertNumQueries(1): self.assertEqual(rf2.name, "new foo") def test_custom_refresh_on_deferred_loading(self): s = Secondary.objects.create() rf = RefreshPrimaryProxy.objects.create(name="foo", value="bar", related=s) rf2 = RefreshPrimaryProxy.objects.only("related").get() rf.name = "new foo" rf.value = "new bar" rf.save() with self.assertNumQueries(1): # Customized refresh_from_db() reloads all deferred fields on # access of any of them. self.assertEqual(rf2.name, "new foo") self.assertEqual(rf2.value, "new bar") def test_refresh_when_one_field_deferred(self): s = Secondary.objects.create() PrimaryOneToOne.objects.create(name="foo", value="bar", related=s) s = Secondary.objects.defer("first").get() p_before = s.primary_o2o s.refresh_from_db() self.assertIsNot(s.primary_o2o, p_before)
TestDefer2
python
django__django
tests/i18n/test_compilation.py
{ "start": 915, "end": 2690 }
class ____(MessageCompilationTests): LOCALE = "es_AR" MO_FILE = "locale/%s/LC_MESSAGES/django.mo" % LOCALE MO_FILE_EN = "locale/en/LC_MESSAGES/django.mo" def test_bom_rejection(self): stderr = StringIO() with self.assertRaisesMessage( CommandError, "compilemessages generated one or more errors." ): call_command( "compilemessages", locale=[self.LOCALE], verbosity=0, stderr=stderr ) self.assertIn("file has a BOM (Byte Order Mark)", stderr.getvalue()) self.assertFalse(os.path.exists(self.MO_FILE)) def test_no_write_access(self): mo_file_en = Path(self.MO_FILE_EN) err_buffer = StringIO() # Put parent directory in read-only mode. old_mode = mo_file_en.parent.stat().st_mode mo_file_en.parent.chmod(stat.S_IRUSR | stat.S_IXUSR) # Ensure .po file is more recent than .mo file. mo_file_en.with_suffix(".po").touch() try: with self.assertRaisesMessage( CommandError, "compilemessages generated one or more errors." ): call_command( "compilemessages", locale=["en"], stderr=err_buffer, verbosity=0 ) self.assertIn("not writable location", err_buffer.getvalue()) finally: mo_file_en.parent.chmod(old_mode) def test_no_compile_when_unneeded(self): mo_file_en = Path(self.MO_FILE_EN) mo_file_en.touch() stdout = StringIO() call_command("compilemessages", locale=["en"], stdout=stdout, verbosity=1) msg = "%s” is already compiled and up to date." % mo_file_en.with_suffix(".po") self.assertIn(msg, stdout.getvalue())
PoFileTests
python
scikit-learn__scikit-learn
sklearn/externals/_arff.py
{ "start": 14924, "end": 15224 }
class ____: def __init__(self, values): self.values = {v: i for i, v in enumerate(values)} self.values[0] = 0 def __call__(self, value): try: return self.values[value] except KeyError: raise BadNominalValue(value)
EncodedNominalConversor
python
MongoEngine__mongoengine
tests/fields/test_enum_field.py
{ "start": 403, "end": 562 }
class ____(Document): status = EnumField(Status) statuses = ListField(EnumField(Status)) color_mapping = DictField(EnumField(Color))
ModelComplexEnum
python
pandas-dev__pandas
pandas/tests/io/excel/test_writers.py
{ "start": 2075, "end": 12228 }
class ____: @pytest.mark.parametrize( "header,expected", [(None, [np.nan] * 4), (0, {"Unnamed: 0": [np.nan] * 3})], ) def test_read_one_empty_col_no_header(self, tmp_excel, header, expected): # xref gh-12292 filename = "no_header" df = DataFrame([["", 1, 100], ["", 2, 200], ["", 3, 300], ["", 4, 400]]) df.to_excel(tmp_excel, sheet_name=filename, index=False, header=False) result = pd.read_excel( tmp_excel, sheet_name=filename, usecols=[0], header=header ) expected = DataFrame(expected) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "header,expected_extra", [(None, [0]), (0, [])], ) def test_read_one_empty_col_with_header(self, tmp_excel, header, expected_extra): filename = "with_header" df = DataFrame([["", 1, 100], ["", 2, 200], ["", 3, 300], ["", 4, 400]]) df.to_excel(tmp_excel, sheet_name="with_header", index=False, header=True) result = pd.read_excel( tmp_excel, sheet_name=filename, usecols=[0], header=header ) expected = DataFrame(expected_extra + [np.nan] * 4) tm.assert_frame_equal(result, expected) def test_set_column_names_in_parameter(self, tmp_excel): # GH 12870 : pass down column names associated with # keyword argument names refdf = DataFrame([[1, "foo"], [2, "bar"], [3, "baz"]], columns=["a", "b"]) with ExcelWriter(tmp_excel) as writer: refdf.to_excel(writer, sheet_name="Data_no_head", header=False, index=False) refdf.to_excel(writer, sheet_name="Data_with_head", index=False) refdf.columns = ["A", "B"] with ExcelFile(tmp_excel) as reader: xlsdf_no_head = pd.read_excel( reader, sheet_name="Data_no_head", header=None, names=["A", "B"] ) xlsdf_with_head = pd.read_excel( reader, sheet_name="Data_with_head", index_col=None, names=["A", "B"], ) tm.assert_frame_equal(xlsdf_no_head, refdf) tm.assert_frame_equal(xlsdf_with_head, refdf) def test_creating_and_reading_multiple_sheets(self, tmp_excel): # see gh-9450 # # Test reading multiple sheets, from a runtime # created Excel file with multiple sheets. def tdf(col_sheet_name): d, i = [11, 22, 33], [1, 2, 3] return DataFrame(d, i, columns=[col_sheet_name]) sheets = ["AAA", "BBB", "CCC"] dfs = [tdf(s) for s in sheets] dfs = dict(zip(sheets, dfs)) with ExcelWriter(tmp_excel) as ew: for sheetname, df in dfs.items(): df.to_excel(ew, sheet_name=sheetname) dfs_returned = pd.read_excel(tmp_excel, sheet_name=sheets, index_col=0) for s in sheets: tm.assert_frame_equal(dfs[s], dfs_returned[s]) def test_read_excel_multiindex_empty_level(self, tmp_excel): # see gh-12453 df = DataFrame( { ("One", "x"): {0: 1}, ("Two", "X"): {0: 3}, ("Two", "Y"): {0: 7}, ("Zero", ""): {0: 0}, } ) expected = DataFrame( { ("One", "x"): {0: 1}, ("Two", "X"): {0: 3}, ("Two", "Y"): {0: 7}, ("Zero", "Unnamed: 4_level_1"): {0: 0}, } ) df.to_excel(tmp_excel) actual = pd.read_excel(tmp_excel, header=[0, 1], index_col=0) tm.assert_frame_equal(actual, expected) df = DataFrame( { ("Beg", ""): {0: 0}, ("Middle", "x"): {0: 1}, ("Tail", "X"): {0: 3}, ("Tail", "Y"): {0: 7}, } ) expected = DataFrame( { ("Beg", "Unnamed: 1_level_1"): {0: 0}, ("Middle", "x"): {0: 1}, ("Tail", "X"): {0: 3}, ("Tail", "Y"): {0: 7}, } ) df.to_excel(tmp_excel) actual = pd.read_excel(tmp_excel, header=[0, 1], index_col=0) tm.assert_frame_equal(actual, expected) @pytest.mark.parametrize("c_idx_names", ["a", None]) @pytest.mark.parametrize("r_idx_names", ["b", None]) @pytest.mark.parametrize("c_idx_levels", [1, 3]) @pytest.mark.parametrize("r_idx_levels", [1, 3]) def test_excel_multindex_roundtrip( self, tmp_excel, c_idx_names, r_idx_names, c_idx_levels, r_idx_levels, ): # see gh-4679 # Empty name case current read in as # unnamed levels, not Nones. check_names = bool(r_idx_names) or r_idx_levels <= 1 if c_idx_levels == 1: columns = Index(list("abcde")) else: columns = MultiIndex.from_arrays( [range(5) for _ in range(c_idx_levels)], names=[f"{c_idx_names}-{i}" for i in range(c_idx_levels)], ) if r_idx_levels == 1: index = Index(list("ghijk")) else: index = MultiIndex.from_arrays( [range(5) for _ in range(r_idx_levels)], names=[f"{r_idx_names}-{i}" for i in range(r_idx_levels)], ) df = DataFrame( 1.1 * np.ones((5, 5)), columns=columns, index=index, ) df.to_excel(tmp_excel) act = pd.read_excel( tmp_excel, index_col=list(range(r_idx_levels)), header=list(range(c_idx_levels)), ) tm.assert_frame_equal(df, act, check_names=check_names) df.iloc[0, :] = np.nan df.to_excel(tmp_excel) act = pd.read_excel( tmp_excel, index_col=list(range(r_idx_levels)), header=list(range(c_idx_levels)), ) tm.assert_frame_equal(df, act, check_names=check_names) df.iloc[-1, :] = np.nan df.to_excel(tmp_excel) act = pd.read_excel( tmp_excel, index_col=list(range(r_idx_levels)), header=list(range(c_idx_levels)), ) tm.assert_frame_equal(df, act, check_names=check_names) def test_read_excel_parse_dates(self, tmp_excel): # see gh-11544, gh-12051 df = DataFrame( {"col": [1, 2, 3], "date_strings": date_range("2012-01-01", periods=3)} ) df2 = df.copy() df2["date_strings"] = df2["date_strings"].dt.strftime("%m/%d/%Y") df2.to_excel(tmp_excel) res = pd.read_excel(tmp_excel, index_col=0) tm.assert_frame_equal(df2, res) res = pd.read_excel(tmp_excel, parse_dates=["date_strings"], index_col=0) expected = df[:] expected["date_strings"] = expected["date_strings"].astype("M8[us]") tm.assert_frame_equal(res, expected) res = pd.read_excel( tmp_excel, parse_dates=["date_strings"], date_format="%m/%d/%Y", index_col=0 ) expected["date_strings"] = expected["date_strings"].astype("M8[us]") tm.assert_frame_equal(expected, res) def test_multiindex_interval_datetimes(self, tmp_excel): # GH 30986 midx = MultiIndex.from_arrays( [ range(4), pd.interval_range( start=pd.Timestamp("2020-01-01"), periods=4, freq="6ME" ), ] ) df = DataFrame(range(4), index=midx) df.to_excel(tmp_excel) result = pd.read_excel(tmp_excel, index_col=[0, 1]) expected = DataFrame( range(4), MultiIndex.from_arrays( [ range(4), [ "(2020-01-31 00:00:00, 2020-07-31 00:00:00]", "(2020-07-31 00:00:00, 2021-01-31 00:00:00]", "(2021-01-31 00:00:00, 2021-07-31 00:00:00]", "(2021-07-31 00:00:00, 2022-01-31 00:00:00]", ], ] ), columns=Index([0]), ) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("merge_cells", [True, False, "columns"]) def test_excel_round_trip_with_periodindex(self, tmp_excel, merge_cells): # GH#60099 df = DataFrame( {"A": [1, 2]}, index=MultiIndex.from_arrays( [ period_range(start="2006-10-06", end="2006-10-07", freq="D"), ["X", "Y"], ], names=["date", "category"], ), ) df.to_excel(tmp_excel, merge_cells=merge_cells) result = pd.read_excel(tmp_excel, index_col=[0, 1]) expected = DataFrame( {"A": [1, 2]}, MultiIndex.from_arrays( [ [ pd.to_datetime("2006-10-06 00:00:00").as_unit("s"), pd.to_datetime("2006-10-07 00:00:00").as_unit("s"), ], ["X", "Y"], ], names=["date", "category"], ), ) time_format = "datetime64[us]" expected.index = expected.index.set_levels( expected.index.levels[0].astype(time_format), level=0 ) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "engine,ext", [ pytest.param( "openpyxl", ".xlsx", marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")], ), pytest.param( "openpyxl", ".xlsm", marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")], ), pytest.param( "xlsxwriter", ".xlsx", marks=[td.skip_if_no("xlsxwriter"), td.skip_if_no("xlrd")], ), pytest.param("odf", ".ods", marks=td.skip_if_no("odf")), ], ) @pytest.mark.usefixtures("set_engine")
TestRoundTrip
python
scrapy__scrapy
tests/test_squeues_request.py
{ "start": 654, "end": 3319 }
class ____(ABC): @property @abstractmethod def is_fifo(self) -> bool: raise NotImplementedError @pytest.mark.parametrize("test_peek", [True, False]) def test_one_element(self, q: queuelib.queue.BaseQueue, test_peek: bool): if test_peek and not HAVE_PEEK: pytest.skip("The queuelib queues do not define peek") if not test_peek and HAVE_PEEK: pytest.skip("The queuelib queues define peek") assert len(q) == 0 if test_peek: assert q.peek() is None assert q.pop() is None req = Request("http://www.example.com") q.push(req) assert len(q) == 1 if test_peek: result = q.peek() assert result is not None assert result.url == req.url else: with pytest.raises( NotImplementedError, match="The underlying queue class does not implement 'peek'", ): q.peek() result = q.pop() assert result is not None assert result.url == req.url assert len(q) == 0 if test_peek: assert q.peek() is None assert q.pop() is None q.close() @pytest.mark.parametrize("test_peek", [True, False]) def test_order(self, q: queuelib.queue.BaseQueue, test_peek: bool): if test_peek and not HAVE_PEEK: pytest.skip("The queuelib queues do not define peek") if not test_peek and HAVE_PEEK: pytest.skip("The queuelib queues define peek") assert len(q) == 0 if test_peek: assert q.peek() is None assert q.pop() is None req1 = Request("http://www.example.com/1") req2 = Request("http://www.example.com/2") req3 = Request("http://www.example.com/3") q.push(req1) q.push(req2) q.push(req3) if not test_peek: with pytest.raises( NotImplementedError, match="The underlying queue class does not implement 'peek'", ): q.peek() reqs = [req1, req2, req3] if self.is_fifo else [req3, req2, req1] for i, req in enumerate(reqs): assert len(q) == 3 - i if test_peek: result = q.peek() assert result is not None assert result.url == req.url result = q.pop() assert result is not None assert result.url == req.url assert len(q) == 0 if test_peek: assert q.peek() is None assert q.pop() is None q.close()
TestRequestQueueBase
python
huggingface__transformers
src/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py
{ "start": 30083, "end": 30767 }
class ____(nn.Module): """XLM-RoBERTa-XL Head for masked language modeling.""" def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.decoder = nn.Linear(config.hidden_size, config.vocab_size) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) def forward(self, features, **kwargs): x = self.dense(features) x = gelu(x) x = self.layer_norm(x) # project back to size of vocabulary with bias x = self.decoder(x) return x
XLMRobertaXLLMHead
python
pandas-dev__pandas
pandas/tests/series/methods/test_unique.py
{ "start": 138, "end": 2219 }
class ____: def test_unique_uint64(self): ser = Series([1, 2, 2**63, 2**63], dtype=np.uint64) res = ser.unique() exp = np.array([1, 2, 2**63], dtype=np.uint64) tm.assert_numpy_array_equal(res, exp) def test_unique_data_ownership(self): # it works! GH#1807 Series(Series(["a", "c", "b"]).unique()).sort_values() def test_unique(self): # GH#714 also, dtype=float ser = Series([1.2345] * 100) ser[::2] = np.nan result = ser.unique() assert len(result) == 2 # explicit f4 dtype ser = Series([1.2345] * 100, dtype="f4") ser[::2] = np.nan result = ser.unique() assert len(result) == 2 def test_unique_nan_object_dtype(self): # NAs in object arrays GH#714 ser = Series(["foo"] * 100, dtype="O") ser[::2] = np.nan result = ser.unique() assert len(result) == 2 def test_unique_none(self): # decision about None ser = Series([1, 2, 3, None, None, None], dtype=object) result = ser.unique() expected = np.array([1, 2, 3, None], dtype=object) tm.assert_numpy_array_equal(result, expected) def test_unique_categorical(self): # GH#18051 cat = Categorical([]) ser = Series(cat) result = ser.unique() tm.assert_categorical_equal(result, cat) cat = Categorical([np.nan]) ser = Series(cat) result = ser.unique() tm.assert_categorical_equal(result, cat) def test_tz_unique(self): # GH 46128 dti1 = date_range("2016-01-01", periods=3) ii1 = IntervalIndex.from_breaks(dti1) ser1 = Series(ii1) uni1 = ser1.unique() tm.assert_interval_array_equal(ser1.array, uni1) dti2 = date_range("2016-01-01", periods=3, tz="US/Eastern") ii2 = IntervalIndex.from_breaks(dti2) ser2 = Series(ii2) uni2 = ser2.unique() tm.assert_interval_array_equal(ser2.array, uni2) assert uni1.dtype != uni2.dtype
TestUnique
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_assorted_poly.py
{ "start": 1799, "end": 5342 }
class ____(fixtures.MappedTest): """test self-referential relationships on polymorphic mappers""" @classmethod def define_tables(cls, metadata): global people, managers people = Table( "people", metadata, Column( "person_id", Integer, normalize_sequence( config, Sequence("person_id_seq", optional=True) ), primary_key=True, ), Column( "manager_id", Integer, ForeignKey( "managers.person_id", use_alter=True, name="mpid_fq" ), ), Column("name", String(50)), Column("type", String(30)), ) managers = Table( "managers", metadata, Column( "person_id", Integer, ForeignKey("people.person_id"), primary_key=True, ), Column("status", String(30)), Column("manager_name", String(50)), ) @classmethod def setup_classes(cls): class Person(cls.Comparable): pass class Manager(Person): pass def test_parent_refs_descendant(self): Person, Manager = self.classes("Person", "Manager") self.mapper_registry.map_imperatively( Person, people, properties={ "manager": relationship( Manager, primaryjoin=(people.c.manager_id == managers.c.person_id), uselist=False, post_update=True, ) }, ) self.mapper_registry.map_imperatively( Manager, managers, inherits=Person, inherit_condition=people.c.person_id == managers.c.person_id, ) eq_( class_mapper(Person).get_property("manager").synchronize_pairs, [(managers.c.person_id, people.c.manager_id)], ) session = fixture_session() p = Person(name="some person") m = Manager(name="some manager") p.manager = m session.add(p) session.flush() session.expunge_all() p = session.get(Person, p.person_id) m = session.get(Manager, m.person_id) assert p.manager is m def test_descendant_refs_parent(self): Person, Manager = self.classes("Person", "Manager") self.mapper_registry.map_imperatively(Person, people) self.mapper_registry.map_imperatively( Manager, managers, inherits=Person, inherit_condition=people.c.person_id == managers.c.person_id, properties={ "employee": relationship( Person, primaryjoin=(people.c.manager_id == managers.c.person_id), foreign_keys=[people.c.manager_id], uselist=False, post_update=True, ) }, ) session = fixture_session() p = Person(name="some person") m = Manager(name="some manager") m.employee = p session.add(m) session.flush() session.expunge_all() p = session.get(Person, p.person_id) m = session.get(Manager, m.person_id) assert m.employee is p
RelationshipTest1
python
python-pillow__Pillow
Tests/test_file_png.py
{ "start": 29644, "end": 30242 }
class ____(PillowLeakTestCase): mem_limit = 2 * 1024 # max increase in K iterations = 100 # Leak is 56k/iteration, this will leak 5.6megs def test_leak_load(self, monkeypatch: pytest.MonkeyPatch) -> None: with open("Tests/images/hopper.png", "rb") as f: DATA = BytesIO(f.read(16 * 1024)) monkeypatch.setattr(ImageFile, "LOAD_TRUNCATED_IMAGES", True) with Image.open(DATA) as im: im.load() def core() -> None: with Image.open(DATA) as im: im.load() self._test_leak(core)
TestTruncatedPngPLeaks
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclassConverter1.py
{ "start": 268, "end": 811 }
class ____: ... def converter_simple(s: str) -> int: return int(s) def converter_with_param_before_args(s: str, *args: int, **kwargs: int) -> int: return int(s) def converter_with_args(*args: str) -> int: return int(args[0]) def converter_with_extra_defaulted_params( s: str, extra: int = 1, *, extraKwarg: int = 1 ) -> int: return int(s) def converter_with_default_for_first_param(s: str = "1") -> int: return int(s) def converter_with_more_specialized_return_type(s: str) -> int: return int(s)
ModelBase
python
getsentry__sentry
src/sentry/preprod/api/bases/preprod_artifact_endpoint.py
{ "start": 313, "end": 485 }
class ____(APIException): status_code = status.HTTP_404_NOT_FOUND default_detail = "The requested preprod artifact does not exist"
PreprodArtifactResourceDoesNotExist
python
django__django
django/db/models/aggregates.py
{ "start": 13082, "end": 13456 }
class ____(NumericOutputFieldMixin, Aggregate): name = "Variance" arity = 1 def __init__(self, expression, sample=False, **extra): self.function = "VAR_SAMP" if sample else "VAR_POP" super().__init__(expression, **extra) def _get_repr_options(self): return {**super()._get_repr_options(), "sample": self.function == "VAR_SAMP"}
Variance
python
google__flatbuffers
tests/flatc/flatc_schema_tests.py
{ "start": 636, "end": 2233 }
class ____: def EnumValAttributes(self): # Generate .bfbs schema first flatc( ["--schema", "--binary", "--bfbs-builtins", "enum_val_attributes.fbs"] ) assert_file_exists("enum_val_attributes.bfbs") # Then turn it into JSON flatc([ "--json", "--strict-json", str(reflection_fbs_path()), "--", "enum_val_attributes.bfbs", ]) # The attributes should be present in JSON schema_json = json.loads(get_file_contents("enum_val_attributes.json")) assert schema_json["enums"][0]["name"] == "ValAttributes" assert schema_json["enums"][0]["values"][0]["name"] == "Val1" assert ( schema_json["enums"][0]["values"][0]["attributes"][0]["key"] == "display_name" ) assert ( schema_json["enums"][0]["values"][0]["attributes"][0]["value"] == "Value 1" ) assert schema_json["enums"][0]["values"][1]["name"] == "Val2" assert ( schema_json["enums"][0]["values"][1]["attributes"][0]["key"] == "display_name" ) assert ( schema_json["enums"][0]["values"][1]["attributes"][0]["value"] == "Value 2" ) assert schema_json["enums"][0]["values"][2]["name"] == "Val3" assert ( schema_json["enums"][0]["values"][2]["attributes"][0]["key"] == "deprecated" ) assert ( schema_json["enums"][0]["values"][2]["attributes"][1]["key"] == "display_name" ) assert ( schema_json["enums"][0]["values"][2]["attributes"][1]["value"] == "Value 3 (deprecated)" )
SchemaTests
python
ray-project__ray
doc/source/serve/doc_code/app_builder.py
{ "start": 820, "end": 1383 }
class ____: def __init__(self, message: str): self._message = message print("Message:", self._message) def __call__(self, request): return self._message def typed_app_builder(args: HelloWorldArgs) -> Application: return HelloWorld.bind(args.message) # __end_typed_builder__ serve.run(typed_app_builder(HelloWorldArgs(message="Hello baz"))) resp = requests.get("http://localhost:8000") assert resp.text == "Hello baz" # __begin_composed_builder__ from pydantic import BaseModel from ray.serve import Application
HelloWorld
python
pandas-dev__pandas
pandas/tests/tools/test_to_datetime.py
{ "start": 19341, "end": 66148 }
class ____: def test_to_datetime_mixed_string_resos(self): # GH#62801 vals = [ "2016-01-01 01:02:03", "2016-01-01 01:02:03.001", "2016-01-01 01:02:03.001002", "2016-01-01 01:02:03.001002003", ] expected = DatetimeIndex([Timestamp(x).as_unit("ns") for x in vals]) result1 = DatetimeIndex(vals) tm.assert_index_equal(result1, expected) result2 = to_datetime(vals, format="ISO8601") tm.assert_index_equal(result2, expected) result3 = to_datetime(vals, format="mixed") tm.assert_index_equal(result3, expected) def test_to_datetime_none(self): # GH#23055 assert to_datetime(None) is NaT @pytest.mark.filterwarnings("ignore:Could not infer format") def test_to_datetime_overflow(self): # we should get an OutOfBoundsDatetime, NOT OverflowError # TODO: Timestamp raises ValueError("could not convert string to Timestamp") # can we make these more consistent? arg = "08335394550" msg = 'Parsing "08335394550" to datetime overflows' with pytest.raises(OutOfBoundsDatetime, match=msg): to_datetime(arg) with pytest.raises(OutOfBoundsDatetime, match=msg): to_datetime([arg]) res = to_datetime(arg, errors="coerce") assert res is NaT res = to_datetime([arg], errors="coerce") exp = Index([NaT], dtype="M8[s]") tm.assert_index_equal(res, exp) def test_to_datetime_mixed_datetime_and_string(self): # GH#47018 adapted old doctest with new behavior d1 = datetime(2020, 1, 1, 17, tzinfo=timezone(-timedelta(hours=1))) d2 = datetime(2020, 1, 1, 18, tzinfo=timezone(-timedelta(hours=1))) res = to_datetime(["2020-01-01 17:00 -0100", d2]) expected = to_datetime([d1, d2]).tz_convert(timezone(timedelta(minutes=-60))) tm.assert_index_equal(res, expected) def test_to_datetime_mixed_string_and_numeric(self): # GH#55780 np.array(vals) would incorrectly cast the number to str vals = ["2016-01-01", 0] expected = DatetimeIndex([Timestamp(x) for x in vals]) result = to_datetime(vals, format="mixed") result2 = to_datetime(vals[::-1], format="mixed")[::-1] result3 = DatetimeIndex(vals) result4 = DatetimeIndex(vals[::-1])[::-1] tm.assert_index_equal(result, expected) tm.assert_index_equal(result2, expected) tm.assert_index_equal(result3, expected) tm.assert_index_equal(result4, expected) @pytest.mark.parametrize( "format", ["%Y-%m-%d", "%Y-%d-%m"], ids=["ISO8601", "non-ISO8601"] ) def test_to_datetime_mixed_date_and_string(self, format): # https://github.com/pandas-dev/pandas/issues/50108 d1 = date(2020, 1, 2) res = to_datetime(["2020-01-01", d1], format=format) expected = DatetimeIndex(["2020-01-01", "2020-01-02"], dtype="M8[us]") tm.assert_index_equal(res, expected) @pytest.mark.parametrize( "fmt", ["%Y-%d-%m %H:%M:%S%z", "%Y-%m-%d %H:%M:%S%z"], ids=["non-ISO8601 format", "ISO8601 format"], ) @pytest.mark.parametrize( "utc, args, expected", [ pytest.param( True, ["2000-01-01 01:00:00-08:00", "2000-01-01 02:00:00-08:00"], DatetimeIndex( ["2000-01-01 09:00:00+00:00", "2000-01-01 10:00:00+00:00"], dtype="datetime64[us, UTC]", ), id="all tz-aware, with utc", ), pytest.param( False, ["2000-01-01 01:00:00+00:00", "2000-01-01 02:00:00+00:00"], DatetimeIndex( ["2000-01-01 01:00:00+00:00", "2000-01-01 02:00:00+00:00"], ).as_unit("us"), id="all tz-aware, without utc", ), pytest.param( True, ["2000-01-01 01:00:00-08:00", "2000-01-01 02:00:00+00:00"], DatetimeIndex( ["2000-01-01 09:00:00+00:00", "2000-01-01 02:00:00+00:00"], dtype="datetime64[us, UTC]", ), id="all tz-aware, mixed offsets, with utc", ), pytest.param( True, ["2000-01-01 01:00:00", "2000-01-01 02:00:00+00:00"], DatetimeIndex( ["2000-01-01 01:00:00+00:00", "2000-01-01 02:00:00+00:00"], dtype="datetime64[us, UTC]", ), id="tz-aware string, naive pydatetime, with utc", ), ], ) @pytest.mark.parametrize( "constructor", [Timestamp, lambda x: Timestamp(x).to_pydatetime()], ) def test_to_datetime_mixed_datetime_and_string_with_format( self, fmt, utc, args, expected, constructor ): # https://github.com/pandas-dev/pandas/issues/49298 # https://github.com/pandas-dev/pandas/issues/50254 # note: ISO8601 formats go down a fastpath, so we need to check both # an ISO8601 format and a non-ISO8601 one ts1 = constructor(args[0]) ts2 = args[1] result = to_datetime([ts1, ts2], format=fmt, utc=utc) if constructor is Timestamp: expected = expected.as_unit("us") tm.assert_index_equal(result, expected) @pytest.mark.parametrize( "fmt", ["%Y-%d-%m %H:%M:%S%z", "%Y-%m-%d %H:%M:%S%z"], ids=["non-ISO8601 format", "ISO8601 format"], ) @pytest.mark.parametrize( "constructor", [Timestamp, lambda x: Timestamp(x).to_pydatetime()], ) def test_to_datetime_mixed_dt_and_str_with_format_mixed_offsets_utc_false_removed( self, fmt, constructor ): # https://github.com/pandas-dev/pandas/issues/49298 # https://github.com/pandas-dev/pandas/issues/50254 # GH#57275 # note: ISO8601 formats go down a fastpath, so we need to check both # an ISO8601 format and a non-ISO8601 one args = ["2000-01-01 01:00:00", "2000-01-01 02:00:00+00:00"] ts1 = constructor(args[0]) ts2 = args[1] msg = "Mixed timezones detected. Pass utc=True in to_datetime" with pytest.raises(ValueError, match=msg): to_datetime([ts1, ts2], format=fmt, utc=False) @pytest.mark.parametrize( "fmt, expected", [ pytest.param( "%Y-%m-%d %H:%M:%S%z", [ Timestamp("2000-01-01 09:00:00+0100", tz="UTC+01:00"), Timestamp("2000-01-02 02:00:00+0200", tz="UTC+02:00"), NaT, ], id="ISO8601, non-UTC", ), pytest.param( "%Y-%d-%m %H:%M:%S%z", [ Timestamp("2000-01-01 09:00:00+0100", tz="UTC+01:00"), Timestamp("2000-02-01 02:00:00+0200", tz="UTC+02:00"), NaT, ], id="non-ISO8601, non-UTC", ), ], ) def test_to_datetime_mixed_offsets_with_none_tz_utc_false_removed( self, fmt, expected ): # https://github.com/pandas-dev/pandas/issues/50071 # GH#57275 msg = "Mixed timezones detected. Pass utc=True in to_datetime" with pytest.raises(ValueError, match=msg): to_datetime( ["2000-01-01 09:00:00+01:00", "2000-01-02 02:00:00+02:00", None], format=fmt, utc=False, ) @pytest.mark.parametrize( "fmt, expected", [ pytest.param( "%Y-%m-%d %H:%M:%S%z", DatetimeIndex( ["2000-01-01 08:00:00+00:00", "2000-01-02 00:00:00+00:00", "NaT"], dtype="datetime64[us, UTC]", ), id="ISO8601, UTC", ), pytest.param( "%Y-%d-%m %H:%M:%S%z", DatetimeIndex( ["2000-01-01 08:00:00+00:00", "2000-02-01 00:00:00+00:00", "NaT"], dtype="datetime64[us, UTC]", ), id="non-ISO8601, UTC", ), ], ) def test_to_datetime_mixed_offsets_with_none(self, fmt, expected): # https://github.com/pandas-dev/pandas/issues/50071 result = to_datetime( ["2000-01-01 09:00:00+01:00", "2000-01-02 02:00:00+02:00", None], format=fmt, utc=True, ) tm.assert_index_equal(result, expected) @pytest.mark.parametrize( "fmt", ["%Y-%d-%m %H:%M:%S%z", "%Y-%m-%d %H:%M:%S%z"], ids=["non-ISO8601 format", "ISO8601 format"], ) @pytest.mark.parametrize( "args", [ pytest.param( ["2000-01-01 01:00:00-08:00", "2000-01-01 02:00:00-07:00"], id="all tz-aware, mixed timezones, without utc", ), ], ) @pytest.mark.parametrize( "constructor", [Timestamp, lambda x: Timestamp(x).to_pydatetime()], ) def test_to_datetime_mixed_datetime_and_string_with_format_raises( self, fmt, args, constructor ): # https://github.com/pandas-dev/pandas/issues/49298 # note: ISO8601 formats go down a fastpath, so we need to check both # an ISO8601 format and a non-ISO8601 one ts1 = constructor(args[0]) ts2 = constructor(args[1]) with pytest.raises( ValueError, match="cannot be converted to datetime64 unless utc=True" ): to_datetime([ts1, ts2], format=fmt, utc=False) def test_to_datetime_np_str(self): # GH#32264 # GH#48969 value = np.str_("2019-02-04 10:18:46.297000+0000") ser = Series([value]) exp = Timestamp("2019-02-04 10:18:46.297000", tz="UTC") assert to_datetime(value) == exp assert to_datetime(ser.iloc[0]) == exp res = to_datetime([value]) expected = Index([exp]) tm.assert_index_equal(res, expected) res = to_datetime(ser) expected = Series(expected) tm.assert_series_equal(res, expected) @pytest.mark.parametrize( "s, _format, dt", [ ["2015-1-1", "%G-%V-%u", datetime(2014, 12, 29, 0, 0)], ["2015-1-4", "%G-%V-%u", datetime(2015, 1, 1, 0, 0)], ["2015-1-7", "%G-%V-%u", datetime(2015, 1, 4, 0, 0)], ["2024-52-1", "%G-%V-%u", datetime(2024, 12, 23, 0, 0)], ["2024-52-7", "%G-%V-%u", datetime(2024, 12, 29, 0, 0)], ["2025-1-1", "%G-%V-%u", datetime(2024, 12, 30, 0, 0)], ["2020-53-1", "%G-%V-%u", datetime(2020, 12, 28, 0, 0)], ], ) def test_to_datetime_iso_week_year_format(self, s, _format, dt): # See GH#16607 assert to_datetime(s, format=_format) == dt @pytest.mark.parametrize( "msg, s, _format", [ [ "Week 53 does not exist in ISO year 2024", "2024 53 1", "%G %V %u", ], [ "Week 53 does not exist in ISO year 2023", "2023 53 1", "%G %V %u", ], ], ) def test_invalid_iso_week_53(self, msg, s, _format): # See GH#60885 with pytest.raises(ValueError, match=msg): to_datetime(s, format=_format) @pytest.mark.parametrize( "msg, s, _format", [ [ "ISO week directive '%V' is incompatible with the year directive " "'%Y'. Use the ISO year '%G' instead.", "1999 50", "%Y %V", ], [ "ISO year directive '%G' must be used with the ISO week directive " "'%V' and a weekday directive '%A', '%a', '%w', or '%u'.", "1999 51", "%G %V", ], [ "ISO year directive '%G' must be used with the ISO week directive " "'%V' and a weekday directive '%A', '%a', '%w', or '%u'.", "1999 Monday", "%G %A", ], [ "ISO year directive '%G' must be used with the ISO week directive " "'%V' and a weekday directive '%A', '%a', '%w', or '%u'.", "1999 Mon", "%G %a", ], [ "ISO year directive '%G' must be used with the ISO week directive " "'%V' and a weekday directive '%A', '%a', '%w', or '%u'.", "1999 6", "%G %w", ], [ "ISO year directive '%G' must be used with the ISO week directive " "'%V' and a weekday directive '%A', '%a', '%w', or '%u'.", "1999 6", "%G %u", ], [ "ISO year directive '%G' must be used with the ISO week directive " "'%V' and a weekday directive '%A', '%a', '%w', or '%u'.", "2051", "%G", ], [ "Day of the year directive '%j' is not compatible with ISO year " "directive '%G'. Use '%Y' instead.", "1999 51 6 256", "%G %V %u %j", ], [ "ISO week directive '%V' is incompatible with the year directive " "'%Y'. Use the ISO year '%G' instead.", "1999 51 Sunday", "%Y %V %A", ], [ "ISO week directive '%V' is incompatible with the year directive " "'%Y'. Use the ISO year '%G' instead.", "1999 51 Sun", "%Y %V %a", ], [ "ISO week directive '%V' is incompatible with the year directive " "'%Y'. Use the ISO year '%G' instead.", "1999 51 1", "%Y %V %w", ], [ "ISO week directive '%V' is incompatible with the year directive " "'%Y'. Use the ISO year '%G' instead.", "1999 51 1", "%Y %V %u", ], [ "ISO week directive '%V' must be used with the ISO year directive " "'%G' and a weekday directive '%A', '%a', '%w', or '%u'.", "20", "%V", ], [ "ISO week directive '%V' must be used with the ISO year directive " "'%G' and a weekday directive '%A', '%a', '%w', or '%u'.", "1999 51 Sunday", "%V %A", ], [ "ISO week directive '%V' must be used with the ISO year directive " "'%G' and a weekday directive '%A', '%a', '%w', or '%u'.", "1999 51 Sun", "%V %a", ], [ "ISO week directive '%V' must be used with the ISO year directive " "'%G' and a weekday directive '%A', '%a', '%w', or '%u'.", "1999 51 1", "%V %w", ], [ "ISO week directive '%V' must be used with the ISO year directive " "'%G' and a weekday directive '%A', '%a', '%w', or '%u'.", "1999 51 1", "%V %u", ], [ "Day of the year directive '%j' is not compatible with ISO year " "directive '%G'. Use '%Y' instead.", "1999 50", "%G %j", ], [ "ISO week directive '%V' must be used with the ISO year directive " "'%G' and a weekday directive '%A', '%a', '%w', or '%u'.", "20 Monday", "%V %A", ], ], ) @pytest.mark.parametrize("errors", ["raise", "coerce"]) def test_error_iso_week_year(self, msg, s, _format, errors): # See GH#16607, GH#50308 # This test checks for errors thrown when giving the wrong format # However, as discussed on PR#25541, overriding the locale # causes a different error to be thrown due to the format being # locale specific, but the test data is in english. # Therefore, the tests only run when locale is not overwritten, # as a sort of solution to this problem. if locale.getlocale() != ("zh_CN", "UTF-8") and locale.getlocale() != ( "it_IT", "UTF-8", ): with pytest.raises(ValueError, match=msg): to_datetime(s, format=_format, errors=errors) @pytest.mark.parametrize("tz", [None, "US/Central"]) def test_to_datetime_dtarr(self, tz): # DatetimeArray dti = date_range("1965-04-03", periods=19, freq="2W", tz=tz) arr = dti._data result = to_datetime(arr) assert result is arr # Doesn't work on Windows since tzpath not set correctly @td.skip_if_windows @pytest.mark.parametrize("utc", [True, False]) @pytest.mark.parametrize("tz", [None, "US/Central"]) def test_to_datetime_arrow(self, tz, utc, index_or_series): pa = pytest.importorskip("pyarrow") dti = date_range("1965-04-03", periods=19, freq="2W", tz=tz) dti = index_or_series(dti) dti_arrow = dti.astype(pd.ArrowDtype(pa.timestamp(unit="ns", tz=tz))) result = to_datetime(dti_arrow, utc=utc) expected = to_datetime(dti, utc=utc).astype( pd.ArrowDtype(pa.timestamp(unit="ns", tz=tz if not utc else "UTC")) ) if not utc and index_or_series is not Series: # Doesn't hold for utc=True, since that will astype # to_datetime also returns a new object for series assert result is dti_arrow if index_or_series is Series: tm.assert_series_equal(result, expected) else: tm.assert_index_equal(result, expected) def test_to_datetime_pydatetime(self): actual = to_datetime(datetime(2008, 1, 15)) assert actual == datetime(2008, 1, 15) def test_to_datetime_YYYYMMDD(self): actual = to_datetime("20080115") assert actual == datetime(2008, 1, 15) @td.skip_if_windows # `tm.set_timezone` does not work in windows @pytest.mark.skipif(WASM, reason="tzset is not available on WASM") def test_to_datetime_now(self): # See GH#18666 with tm.set_timezone("US/Eastern"): # GH#18705 now = Timestamp("now") pdnow = to_datetime("now") pdnow2 = to_datetime(["now"])[0] # These should all be equal with infinite perf; this gives # a generous margin of 10 seconds assert abs(pdnow._value - now._value) < 1e10 assert abs(pdnow2._value - now._value) < 1e10 assert pdnow.tzinfo is None assert pdnow2.tzinfo is None @td.skip_if_windows # `tm.set_timezone` does not work on Windows @pytest.mark.skipif(WASM, reason="tzset is not available on WASM") @pytest.mark.parametrize("tz", ["Pacific/Auckland", "US/Samoa"]) def test_to_datetime_today(self, tz): # See GH#18666 # Test with one timezone far ahead of UTC and another far behind, so # one of these will _almost_ always be in a different day from UTC. # Unfortunately this test between 12 and 1 AM Samoa time # this both of these timezones _and_ UTC will all be in the same day, # so this test will not detect the regression introduced in #18666. with tm.set_timezone(tz): nptoday = np.datetime64("today").astype("datetime64[us]").astype(np.int64) pdtoday = to_datetime("today") pdtoday2 = to_datetime(["today"])[0] tstoday = Timestamp("today") tstoday2 = Timestamp.today() # These should all be equal with infinite perf; this gives # a generous margin of 10 seconds assert abs(pdtoday.normalize()._value - nptoday) < 1e10 assert abs(pdtoday2.normalize()._value - nptoday) < 1e10 assert abs(pdtoday._value - tstoday._value) < 1e10 assert abs(pdtoday._value - tstoday2._value) < 1e10 assert pdtoday.tzinfo is None assert pdtoday2.tzinfo is None @pytest.mark.parametrize("arg", ["now", "today"]) def test_to_datetime_today_now_unicode_bytes(self, arg): to_datetime([arg]) @pytest.mark.filterwarnings( "ignore:Timestamp.utcnow is deprecated:DeprecationWarning" ) @pytest.mark.skipif(WASM, reason="tzset is not available on WASM") @pytest.mark.parametrize( "format, expected_ds", [ ("%Y-%m-%d %H:%M:%S%z", "2020-01-03"), ("%Y-%d-%m %H:%M:%S%z", "2020-03-01"), (None, "2020-01-03"), ], ) @pytest.mark.parametrize( "string, attribute", [ ("now", "utcnow"), ("today", "today"), ], ) def test_to_datetime_now_with_format(self, format, expected_ds, string, attribute): # https://github.com/pandas-dev/pandas/issues/50359 result = to_datetime(["2020-01-03 00:00:00Z", string], format=format, utc=True) expected = DatetimeIndex( [expected_ds, getattr(Timestamp, attribute)()], dtype="datetime64[s, UTC]" ) assert (expected - result).max().total_seconds() < 1 @pytest.mark.parametrize( "dt", [np.datetime64("2000-01-01"), np.datetime64("2000-01-02")] ) def test_to_datetime_dt64s(self, cache, dt): assert to_datetime(dt, cache=cache) == Timestamp(dt) @pytest.mark.parametrize( "arg, format", [ ("2001-01-01", "%Y-%m-%d"), ("01-01-2001", "%d-%m-%Y"), ], ) def test_to_datetime_dt64s_and_str(self, arg, format): # https://github.com/pandas-dev/pandas/issues/50036 result = to_datetime([arg, np.datetime64("2020-01-01")], format=format) expected = DatetimeIndex(["2001-01-01", "2020-01-01"]) tm.assert_index_equal(result, expected) @pytest.mark.parametrize( "dt", [np.datetime64("1000-01-01"), np.datetime64("5000-01-02")] ) @pytest.mark.parametrize("errors", ["raise", "coerce"]) def test_to_datetime_dt64s_out_of_ns_bounds(self, cache, dt, errors): # GH#50369 We cast to the nearest supported reso, i.e. "s" ts = to_datetime(dt, errors=errors, cache=cache) assert isinstance(ts, Timestamp) assert ts.unit == "s" assert ts.asm8 == dt ts = Timestamp(dt) assert ts.unit == "s" assert ts.asm8 == dt def test_to_datetime_dt64d_out_of_bounds(self, cache): dt64 = np.datetime64(np.iinfo(np.int64).max, "D") msg = "Out of bounds second timestamp: 25252734927768524-07-27" with pytest.raises(OutOfBoundsDatetime, match=msg): Timestamp(dt64) with pytest.raises(OutOfBoundsDatetime, match=msg): to_datetime(dt64, errors="raise", cache=cache) assert to_datetime(dt64, errors="coerce", cache=cache) is NaT @pytest.mark.parametrize("unit", ["s", "D"]) def test_to_datetime_array_of_dt64s(self, cache, unit): # https://github.com/pandas-dev/pandas/issues/31491 # Need at least 50 to ensure cache is used. dts = [ np.datetime64("2000-01-01", unit), np.datetime64("2000-01-02", unit), ] * 30 # Assuming all datetimes are in bounds, to_datetime() returns # an array that is equal to Timestamp() parsing result = to_datetime(dts, cache=cache) expected = DatetimeIndex([Timestamp(x).asm8 for x in dts], dtype="M8[s]") tm.assert_index_equal(result, expected) # A list of datetimes where the last one is out of bounds dts_with_oob = dts + [np.datetime64("9999-01-01")] # As of GH#51978 we do not raise in this case to_datetime(dts_with_oob, errors="raise") result = to_datetime(dts_with_oob, errors="coerce", cache=cache) expected = DatetimeIndex(np.array(dts_with_oob, dtype="M8[s]")) tm.assert_index_equal(result, expected) def test_to_datetime_tz(self, cache): # xref 8260 # uniform returns a DatetimeIndex arr = [ Timestamp("2013-01-01 13:00:00-0800", tz="US/Pacific"), Timestamp("2013-01-02 14:00:00-0800", tz="US/Pacific"), ] result = to_datetime(arr, cache=cache) expected = DatetimeIndex( ["2013-01-01 13:00:00", "2013-01-02 14:00:00"], tz="US/Pacific" ) tm.assert_index_equal(result, expected) def test_to_datetime_tz_mixed(self, cache): # mixed tzs will raise if errors='raise' # https://github.com/pandas-dev/pandas/issues/50585 arr = [ Timestamp("2013-01-01 13:00:00", tz="US/Pacific"), Timestamp("2013-01-02 14:00:00", tz="US/Eastern"), ] msg = ( "Tz-aware datetime.datetime cannot be " "converted to datetime64 unless utc=True" ) with pytest.raises(ValueError, match=msg): to_datetime(arr, cache=cache) result = to_datetime(arr, cache=cache, errors="coerce") expected = DatetimeIndex( ["2013-01-01 13:00:00-08:00", "NaT"], dtype="datetime64[us, US/Pacific]" ) tm.assert_index_equal(result, expected) def test_to_datetime_different_offsets_removed(self, cache): # inspired by asv timeseries.ToDatetimeNONISO8601 benchmark # see GH-26097 for more # GH#57275 ts_string_1 = "March 1, 2018 12:00:00+0400" ts_string_2 = "March 1, 2018 12:00:00+0500" arr = [ts_string_1] * 5 + [ts_string_2] * 5 msg = "Mixed timezones detected. Pass utc=True in to_datetime" with pytest.raises(ValueError, match=msg): to_datetime(arr, cache=cache) def test_to_datetime_tz_pytz(self, cache): # see gh-8260 pytz = pytest.importorskip("pytz") us_eastern = pytz.timezone("US/Eastern") arr = np.array( [ us_eastern.localize( datetime(year=2000, month=1, day=1, hour=3, minute=0) ), us_eastern.localize( datetime(year=2000, month=6, day=1, hour=3, minute=0) ), ], dtype=object, ) result = to_datetime(arr, utc=True, cache=cache) expected = DatetimeIndex( ["2000-01-01 08:00:00+00:00", "2000-06-01 07:00:00+00:00"], dtype="datetime64[us, UTC]", freq=None, ) tm.assert_index_equal(result, expected) @pytest.mark.parametrize( "init_constructor, end_constructor", [ (Index, DatetimeIndex), (list, DatetimeIndex), (np.array, DatetimeIndex), (Series, Series), ], ) def test_to_datetime_utc_true(self, cache, init_constructor, end_constructor): # See gh-11934 & gh-6415 data = ["20100102 121314", "20100102 121315"] expected_data = [ Timestamp("2010-01-02 12:13:14", tz="utc"), Timestamp("2010-01-02 12:13:15", tz="utc"), ] result = to_datetime( init_constructor(data), format="%Y%m%d %H%M%S", utc=True, cache=cache ) expected = end_constructor(expected_data) tm.assert_equal(result, expected) @pytest.mark.parametrize( "scalar, expected", [ ["20100102 121314", Timestamp("2010-01-02 12:13:14", tz="utc")], ["20100102 121315", Timestamp("2010-01-02 12:13:15", tz="utc")], ], ) def test_to_datetime_utc_true_scalar(self, cache, scalar, expected): # Test scalar case as well result = to_datetime(scalar, format="%Y%m%d %H%M%S", utc=True, cache=cache) assert result == expected def test_to_datetime_utc_true_with_series_single_value(self, cache): # GH 15760 UTC=True with Series ts = 1.5e18 result = to_datetime(Series([ts]), utc=True, cache=cache) expected = Series([Timestamp(ts, tz="utc")]) tm.assert_series_equal(result, expected) def test_to_datetime_utc_true_with_series_tzaware_string(self, cache): ts = "2013-01-01 00:00:00-01:00" expected_ts = "2013-01-01 01:00:00" data = Series([ts] * 3) result = to_datetime(data, utc=True, cache=cache) expected = Series([Timestamp(expected_ts, tz="utc")] * 3) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "date, dtype", [ ("2013-01-01 01:00:00", "datetime64[ns]"), ("2013-01-01 01:00:00", "datetime64[ns, UTC]"), ], ) def test_to_datetime_utc_true_with_series_datetime_ns(self, cache, date, dtype): expected = Series( [Timestamp("2013-01-01 01:00:00", tz="UTC")], dtype="M8[ns, UTC]" ) result = to_datetime(Series([date], dtype=dtype), utc=True, cache=cache) tm.assert_series_equal(result, expected) def test_to_datetime_tz_psycopg2(self, request, cache): # xref 8260 psycopg2_tz = pytest.importorskip("psycopg2.tz") # misc cases tz1 = psycopg2_tz.FixedOffsetTimezone(offset=-300, name=None) tz2 = psycopg2_tz.FixedOffsetTimezone(offset=-240, name=None) arr = np.array( [ datetime(2000, 1, 1, 3, 0, tzinfo=tz1), datetime(2000, 6, 1, 3, 0, tzinfo=tz2), ], dtype=object, ) result = to_datetime(arr, errors="coerce", utc=True, cache=cache) expected = DatetimeIndex( ["2000-01-01 08:00:00+00:00", "2000-06-01 07:00:00+00:00"], dtype="datetime64[us, UTC]", freq=None, ) tm.assert_index_equal(result, expected) # dtype coercion i = DatetimeIndex( ["2000-01-01 08:00:00"], tz=psycopg2_tz.FixedOffsetTimezone(offset=-300, name=None), ).as_unit("us") assert not is_datetime64_ns_dtype(i) # tz coercion result = to_datetime(i, errors="coerce", cache=cache) tm.assert_index_equal(result, i) result = to_datetime(i, errors="coerce", utc=True, cache=cache) expected = DatetimeIndex(["2000-01-01 13:00:00"], dtype="datetime64[us, UTC]") tm.assert_index_equal(result, expected) @pytest.mark.parametrize("arg", [True, False]) def test_datetime_bool(self, cache, arg): # GH13176 msg = r"dtype bool cannot be converted to datetime64\[ns\]" with pytest.raises(TypeError, match=msg): to_datetime(arg) assert to_datetime(arg, errors="coerce", cache=cache) is NaT def test_datetime_bool_arrays_mixed(self, cache): msg = f"{type(cache)} is not convertible to datetime" with pytest.raises(TypeError, match=msg): to_datetime([False, datetime.today()], cache=cache) with pytest.raises( ValueError, match=( r'^time data "True" doesn\'t match format "%Y%m%d". ' f"{PARSING_ERR_MSG}$" ), ): to_datetime(["20130101", True], cache=cache) tm.assert_index_equal( to_datetime([0, False, NaT, 0.0], errors="coerce", cache=cache), DatetimeIndex( [to_datetime(0, cache=cache), NaT, NaT, to_datetime(0, cache=cache)] ), ) @pytest.mark.parametrize("arg", [bool, to_datetime]) def test_datetime_invalid_datatype(self, arg): # GH13176 msg = "is not convertible to datetime" with pytest.raises(TypeError, match=msg): to_datetime(arg) @pytest.mark.parametrize("errors", ["coerce", "raise"]) def test_invalid_format_raises(self, errors): # https://github.com/pandas-dev/pandas/issues/50255 with pytest.raises( ValueError, match="':' is a bad directive in format 'H%:M%:S%" ): to_datetime(["00:00:00"], format="H%:M%:S%", errors=errors) @pytest.mark.parametrize("value", ["a", "00:01:99"]) @pytest.mark.parametrize("format", [None, "%H:%M:%S"]) def test_datetime_invalid_scalar(self, value, format): # GH24763 res = to_datetime(value, errors="coerce", format=format) assert res is NaT msg = "|".join( [ r'^time data "a" doesn\'t match format "%H:%M:%S". ' f"{PARSING_ERR_MSG}$", r'^Given date string "a" not likely a datetime$', r'^unconverted data remains when parsing with format "%H:%M:%S": "9". ' f"{PARSING_ERR_MSG}$", rf"^second must be in 0..59{NOT_99}: 00:01:99$", ] ) with pytest.raises(ValueError, match=msg): to_datetime(value, errors="raise", format=format) @pytest.mark.parametrize("value", ["3000/12/11 00:00:00"]) @pytest.mark.parametrize("format", [None, "%H:%M:%S"]) def test_datetime_outofbounds_scalar(self, value, format): # GH24763 res = to_datetime(value, errors="coerce", format=format) if format is None: assert isinstance(res, Timestamp) assert res == Timestamp(value) else: assert res is NaT if format is not None: msg = r'^time data ".*" doesn\'t match format ".*"' with pytest.raises(ValueError, match=msg): to_datetime(value, errors="raise", format=format) else: res = to_datetime(value, errors="raise", format=format) assert isinstance(res, Timestamp) assert res == Timestamp(value) @pytest.mark.parametrize( ("values"), [(["a"]), (["00:01:99"]), (["a", "b", "99:00:00"])] ) @pytest.mark.parametrize("format", [(None), ("%H:%M:%S")]) def test_datetime_invalid_index(self, values, format): # GH24763 # Not great to have logic in tests, but this one's hard to # parametrise over if format is None and len(values) > 1: warn = UserWarning else: warn = None with tm.assert_produces_warning( warn, match="Could not infer format", raise_on_extra_warnings=False ): res = to_datetime(values, errors="coerce", format=format) tm.assert_index_equal(res, DatetimeIndex([NaT] * len(values))) msg = "|".join( [ r'^Given date string "a" not likely a datetime$', r'^time data "a" doesn\'t match format "%H:%M:%S". ' f"{PARSING_ERR_MSG}$", r'^unconverted data remains when parsing with format "%H:%M:%S": "9". ' f"{PARSING_ERR_MSG}$", rf"^second must be in 0..59{NOT_99}: 00:01:99$", ] ) with pytest.raises(ValueError, match=msg): with tm.assert_produces_warning( warn, match="Could not infer format", raise_on_extra_warnings=False ): to_datetime(values, errors="raise", format=format) @pytest.mark.parametrize("utc", [True, None]) @pytest.mark.parametrize("format", ["%Y%m%d %H:%M:%S", None]) @pytest.mark.parametrize("constructor", [list, tuple, np.array, Index, deque]) def test_to_datetime_cache(self, utc, format, constructor): date = "20130101 00:00:00" test_dates = [date] * 10**5 data = constructor(test_dates) result = to_datetime(data, utc=utc, format=format, cache=True) expected = to_datetime(data, utc=utc, format=format, cache=False) tm.assert_index_equal(result, expected) def test_to_datetime_from_deque(self): # GH 29403 result = to_datetime(deque([Timestamp("2010-06-02 09:30:00")] * 51)) expected = to_datetime([Timestamp("2010-06-02 09:30:00")] * 51) tm.assert_index_equal(result, expected) @pytest.mark.parametrize("utc", [True, None]) @pytest.mark.parametrize("format", ["%Y%m%d %H:%M:%S", None]) def test_to_datetime_cache_series(self, utc, format): date = "20130101 00:00:00" test_dates = [date] * 10**5 data = Series(test_dates) result = to_datetime(data, utc=utc, format=format, cache=True) expected = to_datetime(data, utc=utc, format=format, cache=False) tm.assert_series_equal(result, expected) def test_to_datetime_cache_scalar(self): date = "20130101 00:00:00" result = to_datetime(date, cache=True) expected = Timestamp("20130101 00:00:00") assert result == expected @pytest.mark.parametrize( "datetimelikes,expected_values,exp_unit", ( ( (None, np.nan) + (NaT,) * start_caching_at, (NaT,) * (start_caching_at + 2), "s", ), ( (None, Timestamp("2012-07-26").as_unit("s")) + (NaT,) * start_caching_at, (NaT, Timestamp("2012-07-26").as_unit("s")) + (NaT,) * start_caching_at, "s", ), ( (None,) + (NaT,) * start_caching_at + ("2012 July 26", Timestamp("2012-07-26")), (NaT,) * (start_caching_at + 1) + (Timestamp("2012-07-26"), Timestamp("2012-07-26")), "us", ), ), ) def test_convert_object_to_datetime_with_cache( self, datetimelikes, expected_values, exp_unit ): # GH#39882 ser = Series( datetimelikes, dtype="object", ) result_series = to_datetime(ser, errors="coerce") expected_series = Series( expected_values, dtype=f"datetime64[{exp_unit}]", ) tm.assert_series_equal(result_series, expected_series) @pytest.mark.parametrize( "input", [ Series([NaT] * 20 + [None] * 20, dtype="object"), Series([NaT] * 60 + [None] * 60, dtype="object"), Series([None] * 20), Series([None] * 60), Series([""] * 20), Series([""] * 60), Series([pd.NA] * 20), Series([pd.NA] * 60), Series([np.nan] * 20), Series([np.nan] * 60), ], ) def test_to_datetime_converts_null_like_to_nat(self, cache, input): # GH35888 expected = Series([NaT] * len(input), dtype="M8[s]") result = to_datetime(input, cache=cache) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "date, format", [ ("2017-20", "%Y-%W"), ("20 Sunday", "%W %A"), ("20 Sun", "%W %a"), ("2017-21", "%Y-%U"), ("20 Sunday", "%U %A"), ("20 Sun", "%U %a"), ], ) def test_week_without_day_and_calendar_year(self, date, format): # GH16774 msg = "Cannot use '%W' or '%U' without day and year" with pytest.raises(ValueError, match=msg): to_datetime(date, format=format) def test_to_datetime_coerce(self): # GH#26122, GH#57275 ts_strings = [ "March 1, 2018 12:00:00+0400", "March 1, 2018 12:00:00+0500", "20100240", ] msg = "Mixed timezones detected. Pass utc=True in to_datetime" with pytest.raises(ValueError, match=msg): to_datetime(ts_strings, errors="coerce") @pytest.mark.parametrize( "string_arg, format", [("March 1, 2018", "%B %d, %Y"), ("2018-03-01", "%Y-%m-%d")], ) @pytest.mark.parametrize( "outofbounds", [ datetime(9999, 1, 1), date(9999, 1, 1), np.datetime64("9999-01-01"), "January 1, 9999", "9999-01-01", ], ) def test_to_datetime_coerce_oob(self, string_arg, format, outofbounds): # https://github.com/pandas-dev/pandas/issues/50255 ts_strings = [string_arg, outofbounds] result = to_datetime(ts_strings, errors="coerce", format=format) if isinstance(outofbounds, str) and ( format.startswith("%B") ^ outofbounds.startswith("J") ): # the strings don't match the given format, so they raise and we coerce expected = DatetimeIndex([datetime(2018, 3, 1), NaT], dtype="M8[us]") elif isinstance(outofbounds, datetime): expected = DatetimeIndex( [datetime(2018, 3, 1), outofbounds], dtype="M8[us]" ) else: expected = DatetimeIndex( [datetime(2018, 3, 1), outofbounds], dtype="M8[us]" ) tm.assert_index_equal(result, expected) def test_to_datetime_malformed_no_raise(self): # GH 28299 # GH 48633 ts_strings = ["200622-12-31", "111111-24-11"] with tm.assert_produces_warning( UserWarning, match="Could not infer format", raise_on_extra_warnings=False ): result = to_datetime(ts_strings, errors="coerce") # TODO: should Index get "s" by default here? exp = Index([NaT, NaT], dtype="M8[s]") tm.assert_index_equal(result, exp) def test_to_datetime_malformed_raise(self): # GH 48633 ts_strings = ["200622-12-31", "111111-24-11"] msg = ( 'Parsed string "200622-12-31" gives an invalid tzoffset, which must ' r"be between -timedelta\(hours=24\) and timedelta\(hours=24\)" ) with pytest.raises( ValueError, match=msg, ): with tm.assert_produces_warning( UserWarning, match="Could not infer format" ): to_datetime( ts_strings, errors="raise", ) def test_iso_8601_strings_with_same_offset(self): # GH 17697, 11736 ts_str = "2015-11-18 15:30:00+05:30" result = to_datetime(ts_str) expected = Timestamp(ts_str) assert result == expected expected = DatetimeIndex([Timestamp(ts_str)] * 2) result = to_datetime([ts_str] * 2) tm.assert_index_equal(result, expected) result = DatetimeIndex([ts_str] * 2) tm.assert_index_equal(result, expected) def test_iso_8601_strings_with_different_offsets_removed(self): # GH#17697, GH#11736, GH#50887, GH#57275 ts_strings = ["2015-11-18 15:30:00+05:30", "2015-11-18 16:30:00+06:30", NaT] msg = "Mixed timezones detected. Pass utc=True in to_datetime" with pytest.raises(ValueError, match=msg): to_datetime(ts_strings) def test_iso_8601_strings_with_different_offsets_utc(self): ts_strings = ["2015-11-18 15:30:00+05:30", "2015-11-18 16:30:00+06:30", NaT] result = to_datetime(ts_strings, utc=True) expected = DatetimeIndex( [Timestamp(2015, 11, 18, 10), Timestamp(2015, 11, 18, 10), NaT], tz="UTC" ) tm.assert_index_equal(result, expected) def test_mixed_offsets_with_native_datetime_utc_false_raises(self): # GH#25978, GH#57275 vals = [ "nan", Timestamp("1990-01-01"), "2015-03-14T16:15:14.123-08:00", "2019-03-04T21:56:32.620-07:00", None, "today", "now", ] ser = Series(vals) assert all(ser[i] is vals[i] for i in range(len(vals))) # GH#40111 msg = "Mixed timezones detected. Pass utc=True in to_datetime" with pytest.raises(ValueError, match=msg): to_datetime(ser) def test_non_iso_strings_with_tz_offset(self): result = to_datetime(["March 1, 2018 12:00:00+0400"] * 2) expected = DatetimeIndex( [datetime(2018, 3, 1, 12, tzinfo=timezone(timedelta(minutes=240)))] * 2 ) tm.assert_index_equal(result, expected) @pytest.mark.parametrize( "ts, expected", [ (Timestamp("2018-01-01"), Timestamp("2018-01-01", tz="UTC")), ( Timestamp("2018-01-01", tz="US/Pacific"), Timestamp("2018-01-01 08:00", tz="UTC"), ), ], ) def test_timestamp_utc_true(self, ts, expected): # GH 24415 result = to_datetime(ts, utc=True) assert result == expected @pytest.mark.parametrize("dt_str", ["00010101", "13000101", "30000101", "99990101"]) def test_to_datetime_with_format_out_of_bounds(self, dt_str): # GH 9107 res = to_datetime(dt_str, format="%Y%m%d") dtobj = datetime.strptime(dt_str, "%Y%m%d") expected = Timestamp(dtobj) assert res == expected assert res.unit == expected.unit def test_to_datetime_utc(self): arr = np.array([parse("2012-06-13T01:39:00Z")], dtype=object) result = to_datetime(arr, utc=True) assert result.tz is timezone.utc def test_to_datetime_fixed_offset(self): from pandas.tests.indexes.datetimes.test_timezones import FixedOffset fixed_off = FixedOffset(-420, "-07:00") dates = [ datetime(2000, 1, 1, tzinfo=fixed_off), datetime(2000, 1, 2, tzinfo=fixed_off), datetime(2000, 1, 3, tzinfo=fixed_off), ] result = to_datetime(dates) assert result.tz == fixed_off @pytest.mark.parametrize( "date", [ ["2020-10-26 00:00:00+06:00", "2020-10-26 00:00:00+01:00"], ["2020-10-26 00:00:00+06:00", Timestamp("2018-01-01", tz="US/Pacific")], [ "2020-10-26 00:00:00+06:00", datetime(2020, 1, 1, 18).astimezone( zoneinfo.ZoneInfo("Australia/Melbourne") ), ], ], ) def test_to_datetime_mixed_offsets_with_utc_false_removed(self, date): # GH#50887, GH#57275 msg = "Mixed timezones detected. Pass utc=True in to_datetime" with pytest.raises(ValueError, match=msg): to_datetime(date, utc=False)
TestToDatetime
python
getsentry__sentry
tests/sentry/lang/javascript/test_sourcemaps.py
{ "start": 3220, "end": 3442 }
class ____(TestCase): def test_basic(self) -> None: smap_view = SourceMapView.from_json_bytes(sourcemap) assert list(smap_view.iter_sources()) == [(0, "foo/file1.js"), (1, "foo/file2.js")]
IterSourcesTest
python
bokeh__bokeh
src/bokeh/core/property/numeric.py
{ "start": 5936, "end": 7009 }
class ____(Float): """ Accept floating point percentage values. ``Percent`` can be useful and semantically meaningful for specifying things like alpha values and extents. Args: default (float, optional) : A default value for attributes created from this property to have. help (str or None, optional) : A documentation string for this property. (default: None) Example: .. code-block:: python >>> class PercentModel(HasProps): ... prop = Percent() ... >>> m = PercentModel() >>> m.prop = 0.0 >>> m.prop = 0.2 >>> m.prop = 1.0 >>> m.prop = -2 # ValueError !! >>> m.prop = 5 # ValueError !! """ def validate(self, value: Any, detail: bool = True) -> None: super().validate(value, detail) if 0.0 <= value <= 1.0: return msg = "" if not detail else f"expected a value in range [0, 1], got {value!r}" raise ValueError(msg)
Percent
python
google__pytype
pytype/tests/test_attr2.py
{ "start": 1022, "end": 7751 }
class ____(test_base.BaseTest): """Tests for attr.ib with converters.""" def test_annotated_converter(self): self.Check(""" import attr def convert(input: str) -> int: return int(input) @attr.s class Foo: x = attr.ib(converter=convert) Foo(x='123') """) def test_type_and_converter(self): self.Check(""" import attr def convert(input: str): return int(input) @attr.s class Foo: x = attr.ib(type=int, converter=convert) Foo(x='123') """) def test_unannotated_converter_with_type(self): # TODO(b/135553563): This test should fail once we get better type checking # of converter functions. This would need us to run the converter every time # we construct a new instance of Foo. self.Check(""" import attr def convert(input): return int(input) @attr.s class Foo: x = attr.ib(type=int, converter=convert) Foo(x='123') Foo(x=[1,2,3]) # does not complain, input is treated as Any """) def test_annotated_converter_with_mismatched_type(self): self.CheckWithErrors(""" import attr def convert(input: str) -> int: return int(input) @attr.s class Foo: x = attr.ib(type=str, converter=convert) # annotation-type-mismatch foo = Foo(x=123) # wrong-arg-types assert_type(foo.x, str) """) def test_converter_without_return_annotation(self): self.CheckWithErrors(""" import attr def convert(input: str): return int(input) @attr.s class Foo: x = attr.ib(converter=convert) foo = Foo(x=123) # wrong-arg-types assert_type(foo.x, int) """) def test_converter_with_union_type(self): self.Check(""" import attr from typing import Union def convert(input: str): if __random__: return input return int(input) @attr.s class Foo: x = attr.ib(converter=convert) foo = Foo(x='123') assert_type(foo.x, Union[int, str]) """) def test_wrong_converter_arity(self): # TODO(b/135553563): Add a custom error message self.CheckWithErrors(""" import attr def convert(x, y) -> int: return 42 @attr.s class Foo: x = attr.ib(type=str, converter=convert) # wrong-arg-types """) def test_converter_with_default_args(self): self.Check(""" import attr def convert(x, y=10) -> int: return 42 @attr.s class Foo: x = attr.ib(converter=convert) """) def test_converter_with_varargs(self): self.Check(""" import attr def convert(*args, **kwargs) -> int: return 42 @attr.s class Foo: x = attr.ib(converter=convert) """) def test_converter_conflicts_with_type(self): self.CheckWithErrors(""" import attr def convert(input: str) -> int: return int(input) @attr.s class Foo: x = attr.ib(type=list, converter=convert) # annotation-type-mismatch foo = Foo(x='123') assert_type(foo.x, list) """) def test_converter_conflicts_with_annotation(self): self.CheckWithErrors(""" import attr def convert(input: str) -> int: return int(input) @attr.s class Foo: x: list = attr.ib(converter=convert) # annotation-type-mismatch foo = Foo(x='123') assert_type(foo.x, list) """) def test_converter_conflicts_with_default(self): self.CheckWithErrors(""" import attr def convert(input: str) -> int: return int(input) @attr.s class Foo: x = attr.ib(converter=convert, default='a') # annotation-type-mismatch foo = Foo(x='123') assert_type(foo.x, int) """) def test_type_compatible_with_converter(self): # type is not identical to converter type but includes it. self.Check(""" import attr from typing import Optional def convert(input: str) -> int: return int(input) @attr.s class Foo: x = attr.ib(type=Optional[int], converter=convert) foo = Foo(x='123') assert_type(foo.x, Optional[int]) """) def test_callable_as_converter(self): self.Check(""" import attr from typing import Callable def f() -> Callable[[int], str]: return __any_object__ @attr.s class Foo: x = attr.ib(converter=f()) foo = Foo(x=0) assert_type(foo.x, str) """) def test_partial_as_converter(self): self.Check(""" import attr import functools def f(x: int) -> str: return '' @attr.s class Foo: x = attr.ib(converter=functools.partial(f)) foo = Foo(x=0) assert_type(foo.x, str) """) def test_partial_with_positional_args_as_converter(self): self.Check(""" import attr import functools def f(x: str, y: int) -> int: del x return y @attr.s class Foo: x = attr.ib(converter=functools.partial(f, "foo")) foo = Foo(x=0) assert_type(foo.x, int) """) def test_partial_with_star_args_as_converter(self): self.Check(""" import attr import functools def f(*args: str) -> str: return "".join(args) @attr.s class Foo: x = attr.ib(converter=functools.partial(f, "foo", "bar")) foo = Foo(x=0) assert_type(foo.x, str) """) def test_partial_as_converter_with_factory(self): # This is a smoke test for signature construction in the functools overlay. self.Check(""" import collections import functools import attr @attr.s(auto_attribs=True) class Foo(object): x = attr.ib( factory=dict, converter=functools.partial(collections.defaultdict, lambda: 0), ) """) def test_partial_overloaded_as_converter(self): self.Check(""" import attr import functools from typing import overload @overload def f(x: int, y: int) -> int: return '' @overload def f(x: str, y: int) -> str: return '' @attr.s class Foo: x = attr.ib(converter=functools.partial(f, 42)) foo = Foo(x=0) assert_type(foo.x, int) """) def test_partial_class_as_converter(self): self.Check(""" import attr import functools class C: def __init__(self, x: int, y: int) -> None: self.x = x @attr.s class Foo: x = attr.ib(converter=functools.partial(C, 42)) foo = Foo(x=0) assert_type(foo.x, C) """)
TestAttribConverters
python
spack__spack
lib/spack/spack/util/spack_yaml.py
{ "start": 11699, "end": 17515 }
class ____: """Handles the loading and dumping of Spack's YAML files.""" def __init__(self, yaml_type: YAMLType) -> None: self.yaml = YAML(typ="rt", pure=True) if yaml_type == YAMLType.GENERIC_YAML: self.yaml.Representer = SafeRepresenter elif yaml_type == YAMLType.ANNOTATED_SPACK_CONFIG_FILE: self.yaml.Representer = LineAnnotationRepresenter self.yaml.Emitter = LineAnnotationEmitter self.yaml.Constructor = OrderedLineConstructor else: self.yaml.Representer = OrderedLineRepresenter self.yaml.Constructor = OrderedLineConstructor self.yaml.Representer.add_representer(DictWithLineInfo, _represent_dict_with_line_info) def load(self, stream: IO): """Loads the YAML data from a stream and returns it. Args: stream: stream to load from. Raises: SpackYAMLError: if anything goes wrong while loading """ try: return self.yaml.load(stream) except error.MarkedYAMLError as e: msg = "error parsing YAML" error_mark = e.context_mark if e.context_mark else e.problem_mark if error_mark: line, column = error_mark.line, error_mark.column filename = error_mark.name msg += f": near {filename}, {str(line)}, {str(column)}" else: filename = stream.name msg += f": {stream.name}" msg += f": {e.problem}" raise SpackYAMLError(msg, e, filename) from e except Exception as e: msg = "cannot load Spack YAML configuration" filename = stream.name raise SpackYAMLError(msg, e, filename) from e def dump(self, data, stream: Optional[IO] = None, *, transform=None) -> None: """Dumps the YAML data to a stream. Args: data: data to be dumped stream: stream to dump the data into. Raises: SpackYAMLError: if anything goes wrong while dumping """ try: return self.yaml.dump(data, stream=stream, transform=transform) except Exception as e: msg = "cannot dump Spack YAML configuration" filename = stream.name if stream else None raise SpackYAMLError(msg, str(e), filename) from e def as_string(self, data) -> str: """Returns a string representing the YAML data passed as input.""" result = io.StringIO() self.dump(data, stream=result) return result.getvalue() def load_config(str_or_file): """Load but modify the loader instance so that it will add __line__ attributes to the returned object.""" handler = ConfigYAML(yaml_type=YAMLType.SPACK_CONFIG_FILE) return handler.load(str_or_file) def load(*args, **kwargs): handler = ConfigYAML(yaml_type=YAMLType.GENERIC_YAML) return handler.load(*args, **kwargs) @return_string_when_no_stream def dump_config(data, stream, *, default_flow_style=False, blame=False): if blame: handler = ConfigYAML(yaml_type=YAMLType.ANNOTATED_SPACK_CONFIG_FILE) handler.yaml.default_flow_style = default_flow_style handler.yaml.width = maxint return _dump_annotated(handler, data, stream) handler = ConfigYAML(yaml_type=YAMLType.SPACK_CONFIG_FILE) handler.yaml.default_flow_style = default_flow_style handler.yaml.width = maxint return handler.dump(data, stream) def _dump_annotated(handler, data, stream=None): sio = io.StringIO() handler.dump(data, sio) # write_line_break() is not called by YAML for empty lines, so we # skip empty lines here with \n+. lines = re.split(r"\n+", sio.getvalue().rstrip()) getvalue = None if stream is None: stream = io.StringIO() getvalue = stream.getvalue # write out annotations and lines, accounting for color width = max(clen(a) for a in _ANNOTATIONS) formats = ["%%-%ds %%s\n" % (width + cextra(a)) for a in _ANNOTATIONS] for fmt, annotation, line in zip(formats, _ANNOTATIONS, lines): stream.write(fmt % (annotation, line)) if getvalue: return getvalue() def sorted_dict(data): """Descend into data and sort all dictionary keys.""" if isinstance(data, dict): return type(data)((k, sorted_dict(v)) for k, v in sorted(data.items())) elif isinstance(data, (list, tuple)): return type(data)(sorted_dict(v) for v in data) return data def extract_comments(data): """Extract and returns comments from some YAML data""" return getattr(data, comments.Comment.attrib, None) def set_comments(data, *, data_comments): """Set comments on some YAML data""" return setattr(data, comments.Comment.attrib, data_comments) def name_mark(name): """Returns a mark with just a name""" return error.StringMark(name, None, None, None, None, None) def anchorify(data: Union[dict, list], identifier: Callable[[Any], str] = repr) -> None: """Replace identical dict/list branches in tree with references to earlier instances. The YAML serializer generate anchors for them, resulting in small yaml files.""" anchors: Dict[str, Union[dict, list]] = {} stack: List[Union[dict, list]] = [data] while stack: item = stack.pop() for key, value in item.items() if isinstance(item, dict) else enumerate(item): if not isinstance(value, (dict, list)): continue id = identifier(value) anchor = anchors.get(id) if anchor is None: anchors[id] = value stack.append(value) else: item[key] = anchor # replace with reference
ConfigYAML
python
tornadoweb__tornado
tornado/test/web_test.py
{ "start": 114955, "end": 115754 }
class ____(SimpleHandlerTestCase): class Handler(RequestHandler): def get(self): self.set_status(401) self.set_header("WWW-Authenticate", 'Basic realm="something"') if self.get_argument("finish_value", ""): raise Finish("authentication required") else: self.write("authentication required") raise Finish() def test_finish_exception(self): for u in ["/", "/?finish_value=1"]: response = self.fetch(u) self.assertEqual(response.code, 401) self.assertEqual( 'Basic realm="something"', response.headers.get("WWW-Authenticate") ) self.assertEqual(b"authentication required", response.body)
FinishExceptionTest
python
ethereum__web3.py
web3/contract/contract.py
{ "start": 6859, "end": 7084 }
class ____(BaseContractEvents[ContractEvent]): def __init__( self, abi: ABI, w3: "Web3", address: ChecksumAddress | None = None ) -> None: super().__init__(abi, w3, ContractEvent, address)
ContractEvents
python
doocs__leetcode
solution/2300-2399/2351.First Letter to Appear Twice/Solution.py
{ "start": 0, "end": 185 }
class ____: def repeatedCharacter(self, s: str) -> str: cnt = Counter() for c in s: cnt[c] += 1 if cnt[c] == 2: return c
Solution
python
huggingface__transformers
tests/models/lfm2_moe/test_modeling_lfm2_moe.py
{ "start": 1641, "end": 6261 }
class ____(CausalLMModelTest, unittest.TestCase): all_model_classes = (Lfm2MoeModel, Lfm2MoeForCausalLM) if is_torch_available() else () pipeline_model_mapping = ( { "feature-extraction": Lfm2MoeModel, "text-generation": Lfm2MoeForCausalLM, } if is_torch_available() else {} ) model_tester_class = Lfm2MoeModelTester # used in `test_torch_compile_for_training` _torch_compile_train_cls = Lfm2MoeForCausalLM if is_torch_available() else None def _check_past_key_values_for_generate(self, batch_size, past_key_values, seq_length, config): self.assertIsInstance(past_key_values, Lfm2MoeHybridConvCache) # (batch, kv heads, seq_length, head_dim) num_heads = getattr(config, "num_key_value_heads", config.num_attention_heads) head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) attention_shape = (batch_size, num_heads, seq_length, head_dim) conv_shape = (batch_size, config.hidden_size, config.conv_L_cache) for i in range(config.num_hidden_layers): if config.layer_types[i] == "full_attention": self.assertEqual(past_key_values.key_cache[i].shape, attention_shape) self.assertEqual(past_key_values.value_cache[i].shape, attention_shape) else: self.assertEqual(past_key_values.conv_cache[i].shape, conv_shape) def _check_caches_are_equal(self, cache1: Lfm2MoeHybridConvCache, cache2: Lfm2MoeHybridConvCache): if not isinstance(cache1, Lfm2MoeHybridConvCache) or not isinstance(cache2, Lfm2MoeHybridConvCache): raise ValueError("The wrong cache is being used!") if not len(cache1) == len(cache2): raise ValueError("Both caches do not have the same number of layers.") num_layers = len(cache1) for idx in range(num_layers): torch.testing.assert_close(cache1.key_cache[idx], cache2.key_cache[idx]) torch.testing.assert_close(cache1.value_cache[idx], cache2.value_cache[idx]) torch.testing.assert_close(cache1.conv_cache[idx], cache2.conv_cache[idx]) def test_attention_outputs(self): """Lfm2Moe alternates between attention and short-conv layers.""" config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.return_dict = True # force eager attention to support output attentions config._attn_implementation = "eager" seq_len = getattr(self.model_tester, "seq_length", None) for model_class in self.all_model_classes: inputs_dict["output_attentions"] = True inputs_dict["output_hidden_states"] = False config.return_dict = True model = model_class._from_config(config, attn_implementation="eager").to(torch_device).eval() config = model.config with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) attentions = outputs.attentions self.assertEqual(len(attentions), sum(layer == "full_attention" for layer in config.layer_types)) # check that output_attentions also work using config del inputs_dict["output_attentions"] config.output_attentions = True model = model_class(config).to(torch_device).eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) attentions = outputs.attentions self.assertEqual(len(attentions), sum(layer == "full_attention" for layer in config.layer_types)) self.assertListEqual(list(attentions[0].shape[-3:]), [config.num_attention_heads, seq_len, seq_len]) out_len = len(outputs) # Check attention is always last and order is fine inputs_dict["output_attentions"] = True inputs_dict["output_hidden_states"] = True model = model_class(config).to(torch_device).eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) self_attentions = outputs.attentions self.assertEqual(out_len + 1, len(outputs)) self.assertEqual(len(self_attentions), sum(layer == "full_attention" for layer in config.layer_types)) self.assertListEqual(list(self_attentions[0].shape[-3:]), [config.num_attention_heads, seq_len, seq_len]) @require_torch_accelerator @require_read_token @slow
Lfm2MoeModelTest
python
ionelmc__pytest-benchmark
src/pytest_benchmark/storage/elasticsearch.py
{ "start": 387, "end": 933 }
class ____(JSONSerializer): def default(self, data): if isinstance(data, (date, datetime)): return data.isoformat() elif isinstance(data, Decimal): return float(data) elif isinstance(data, uuid.UUID): return str(data) else: return f'UNSERIALIZABLE[{data!r}]' def _mask_hosts(hosts): m = re.compile('^([^:]+)://[^@]+@') sub_fun = partial(m.sub, '\\1://***:***@') masked_hosts = list(map(sub_fun, hosts)) return masked_hosts
BenchmarkJSONSerializer
python
PrefectHQ__prefect
tests/infrastructure/provisioners/test_ecs.py
{ "start": 9360, "end": 13116 }
class ____: async def test_requires_provisioning_no_block(self, credentials_block_resource): needs_provisioning = await credentials_block_resource.requires_provisioning() assert needs_provisioning @pytest.mark.usefixtures("existing_credentials_block") async def test_requires_provisioning_with_block(self, credentials_block_resource): needs_provisioning = await credentials_block_resource.requires_provisioning() assert not needs_provisioning @pytest.mark.usefixtures("existing_iam_user", "register_block_types") async def test_provision(self, prefect_client, credentials_block_resource): advance_mock = MagicMock() base_job_template = { "variables": { "type": "object", "properties": {"aws_credentials": {}}, } } # Provision credentials block await credentials_block_resource.provision( base_job_template=base_job_template, advance=advance_mock, client=prefect_client, ) # Check if the block document exists block_document = await prefect_client.read_block_document_by_name( "work-pool-aws-credentials", "aws-credentials" ) assert isinstance(block_document.data["aws_access_key_id"], str) assert isinstance(block_document.data["aws_secret_access_key"], str) assert base_job_template["variables"]["properties"]["aws_credentials"] == { "default": {"$ref": {"block_document_id": str(block_document.id)}}, } advance_mock.assert_called() @pytest.mark.usefixtures("existing_credentials_block") async def test_provision_preexisting_block(self, prefect_client): advance_mock = MagicMock() base_job_template = { "variables": { "type": "object", "properties": {"aws_credentials": {}}, } } credentials_block_resource = CredentialsBlockResource( user_name="prefect-ecs-user", block_document_name="work-pool-aws-credentials", ) await credentials_block_resource.provision( base_job_template=base_job_template, advance=advance_mock, client=prefect_client, ) block_document = await prefect_client.read_block_document_by_name( "work-pool-aws-credentials", "aws-credentials" ) assert base_job_template["variables"]["properties"]["aws_credentials"] == { "default": {"$ref": {"block_document_id": str(block_document.id)}}, } advance_mock.assert_not_called() @pytest.mark.usefixtures("existing_credentials_block") async def test_get_task_count_block_exists(self, credentials_block_resource): count = await credentials_block_resource.get_task_count() assert count == 0 async def test_get_task_count_block_does_not_exist( self, credentials_block_resource ): count = await credentials_block_resource.get_task_count() assert count == 2 @pytest.mark.usefixtures("existing_credentials_block") async def test_get_planned_actions_block_exists(self, credentials_block_resource): actions = await credentials_block_resource.get_planned_actions() assert actions == [] async def test_get_planned_actions_block_does_not_exist( self, credentials_block_resource ): actions = await credentials_block_resource.get_planned_actions() assert actions == ["Storing generated AWS credentials in a block"] @pytest.fixture def authentication_resource(): return AuthenticationResource(work_pool_name="work-pool")
TestCredentialsBlockResource
python
neetcode-gh__leetcode
python/1603-design-parking-system.py
{ "start": 0, "end": 476 }
class ____: def __init__(self, big: int, medium: int, small: int): # [total_occupied, max_capacity] self.parking = { 1: [0 ,big], 2: [0, medium], 3: [0, small] } def addCar(self, carType: int) -> bool: new_total = self.parking[carType][0] + 1 if new_total <= self.parking[carType][1]: self.parking[carType][0] += 1 return True return False
ParkingSystem
python
getsentry__sentry
src/sentry/rules/conditions/event_attribute.py
{ "start": 8465, "end": 9022 }
class ____(AttributeHandler): minimum_path_length = 2 @classmethod def _handle(cls, path: list[str], event: GroupEvent) -> list[str]: if path[1] not in ("type", "value"): return [] values = getattr(event.interfaces.get("exception"), "values", []) result = [] for e in values: if e is None: continue if hasattr(e, path[1]): result.append(getattr(e, path[1])) return result @attribute_registry.register("error")
ExceptionAttributeHandler
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_health/asset_materialization_health.py
{ "start": 3770, "end": 14489 }
class ____(LoadableBy[AssetKey]): """For tracking the materialization health of an asset, we only care about the most recent completed materialization attempt for each asset/partition. This record keeps track of the assets/partitions that have ever been successfully materialized and those that are currently in a failed state. From this information we can derive the subset that is currently in a successfully materialized state. If an asset/partition is currently being materialized, it will not move to a new state until after the materialization attempt is complete. In the future, we may want to expand this to track the last N materialization successes/failures for each asset. We could also maintain a list of in progress materializations, but that requires streamline to be better able to handle runs being deleted. materialized_subset: The subset of the asset that has ever been successfully materialized. failed_subset: The subset of the asset that is currently in a failed state. partitions_snap: The partitions definition for the asset. None if it is not a partitioned asset. latest_terminal_run_id: The id of the latest run with a successful or failed materialization event for the asset. """ materialized_subset: SerializableEntitySubset[AssetKey] failed_subset: SerializableEntitySubset[AssetKey] partitions_snap: Optional[PartitionsSnap] latest_terminal_run_id: Optional[str] latest_materialization_timestamp: Optional[float] = None latest_failed_to_materialize_timestamp: Optional[float] = None @property def partitions_def(self) -> Optional[PartitionsDefinition]: if self.partitions_snap is None: return None return self.partitions_snap.get_partitions_definition() @property def currently_materialized_subset(self) -> SerializableEntitySubset[AssetKey]: """The subset of the asset that is currently in a successfully materialized state.""" return self.materialized_subset.compute_difference(self.failed_subset) @property def health_status(self) -> AssetHealthStatus: if self.materialized_subset.is_empty and self.failed_subset.is_empty: return AssetHealthStatus.UNKNOWN elif not self.failed_subset.is_empty: return AssetHealthStatus.DEGRADED else: return AssetHealthStatus.HEALTHY @classmethod async def compute_for_asset( cls, asset_key: AssetKey, partitions_def: Optional[PartitionsDefinition], loading_context: LoadingContext, ) -> "AssetMaterializationHealthState": """Creates an AssetMaterializationHealthState for the given asset. Requires fetching the AssetRecord and potentially the latest run from the DB, or regenerating the partition status cache. """ asset_record = await AssetRecord.gen(loading_context, asset_key) if partitions_def is not None: ( materialized_partition_subset, failed_partition_subset, _, ) = await get_partition_subsets( loading_context.instance, loading_context, asset_key, loading_context.instance, partitions_def, ) if materialized_partition_subset is None or failed_partition_subset is None: check.failed("Expected partitions subset for a partitioned asset") last_run_id = None latest_materialization_timestamp = None latest_failed_to_materialize_timestamp = None if asset_record is not None: entry = asset_record.asset_entry latest_record = max( [ entry.last_materialization_record, entry.last_failed_to_materialize_record, ], key=lambda record: -1 if record is None else record.storage_id, ) last_run_id = latest_record.run_id if latest_record else None latest_materialization_timestamp = ( entry.last_materialization_record.timestamp if entry.last_materialization_record else None ) latest_failed_to_materialize_timestamp = ( entry.last_failed_to_materialize_record.timestamp if entry.last_failed_to_materialize_record else None ) return cls( materialized_subset=SerializableEntitySubset( key=asset_key, value=materialized_partition_subset ), failed_subset=SerializableEntitySubset( key=asset_key, value=failed_partition_subset ), partitions_snap=PartitionsSnap.from_def(partitions_def), latest_terminal_run_id=last_run_id, latest_materialization_timestamp=latest_materialization_timestamp, latest_failed_to_materialize_timestamp=latest_failed_to_materialize_timestamp, ) if asset_record is None: return AssetMaterializationHealthState( materialized_subset=SerializableEntitySubset(key=asset_key, value=False), failed_subset=SerializableEntitySubset(key=asset_key, value=False), partitions_snap=None, latest_terminal_run_id=None, latest_materialization_timestamp=None, latest_failed_to_materialize_timestamp=None, ) asset_entry = asset_record.asset_entry latest_materialization_timestamp = ( asset_entry.last_materialization_record.timestamp if asset_entry.last_materialization_record else None ) latest_failed_to_materialize_timestamp = ( asset_entry.last_failed_to_materialize_record.timestamp if asset_entry.last_failed_to_materialize_record else None ) if asset_entry.last_run_id is None: return AssetMaterializationHealthState( materialized_subset=SerializableEntitySubset(key=asset_key, value=False), failed_subset=SerializableEntitySubset(key=asset_key, value=False), partitions_snap=None, latest_terminal_run_id=None, latest_materialization_timestamp=latest_materialization_timestamp, latest_failed_to_materialize_timestamp=latest_failed_to_materialize_timestamp, ) has_ever_materialized = asset_entry.last_materialization is not None ( is_currently_failed, latest_terminal_run_id, ) = await _get_is_currently_failed_and_latest_terminal_run_id(loading_context, asset_record) return cls( materialized_subset=SerializableEntitySubset( key=asset_key, value=has_ever_materialized ), failed_subset=SerializableEntitySubset(key=asset_key, value=is_currently_failed), partitions_snap=None, latest_terminal_run_id=latest_terminal_run_id, latest_materialization_timestamp=latest_materialization_timestamp, latest_failed_to_materialize_timestamp=latest_failed_to_materialize_timestamp, ) @classmethod def _blocking_batch_load( cls, keys: Iterable[AssetKey], context: LoadingContext ) -> Iterable[Optional["AssetMaterializationHealthState"]]: asset_materialization_health_states = ( context.instance.get_asset_materialization_health_state_for_assets(list(keys)) ) return [asset_materialization_health_states.get(key) for key in keys] async def _get_is_currently_failed_and_latest_terminal_run_id( loading_context: LoadingContext, asset_record: AssetRecord ) -> tuple[bool, Optional[str]]: """Determines if the asset is currently in a failed state. If we are storing failure events for the asset, this can be determined by looking at the AssetRecord. For assets where we are not storing failure events, we have to derive the failure state from the latest run record. Also returns the id of the latest run with a successful or failed materialization event for the asset. """ asset_entry = asset_record.asset_entry if loading_context.instance.can_read_failure_events_for_asset(asset_record): latest_record = max( [ asset_entry.last_materialization_record, asset_entry.last_failed_to_materialize_record, ], key=lambda record: -1 if record is None else record.storage_id, ) return ( latest_record.storage_id == asset_entry.last_failed_to_materialize_storage_id if latest_record else False, latest_record.run_id if latest_record else None, ) if asset_entry.last_run_id is None: return False, None # if failure events are not stored, we usually have to fetch the run record to check if the # asset is currently failed. However, if the latest run id is the same as the last materialization run id, # then we know the asset is in a successfully materialized state. if ( asset_entry.last_materialization and asset_entry.last_run_id == asset_entry.last_materialization.run_id ): return False, asset_entry.last_materialization.run_id run_record = await RunRecord.gen(loading_context, asset_entry.last_run_id) if run_record is None or not run_record.dagster_run.is_finished or run_record.end_time is None: # the run is deleted or in progress. With the information we have available, we cannot know # if the asset is in a failed state prior to this run. Historically, we have resorted to # reporting the asset as materialized if it has ever been materialized, and otherwise report it # as not materialized. return ( False, asset_entry.last_materialization.run_id if asset_entry.last_materialization else None, ) if ( asset_entry.last_materialization and asset_entry.last_materialization.timestamp > run_record.end_time ): # the latest materialization was reported manually return False, asset_entry.last_materialization.run_id # if the run failed, then report the asset as failed return run_record.dagster_run.is_failure, run_record.dagster_run.run_id @whitelist_for_serdes @record.record
AssetMaterializationHealthState
python
huggingface__transformers
src/transformers/models/llava_onevision/modeling_llava_onevision.py
{ "start": 6258, "end": 11808 }
class ____(nn.Module): def __init__(self, config: LlavaOnevisionConfig): super().__init__() # We have hidden_size * the number of vision feature layers num_feature_layers = 1 if isinstance(config.vision_feature_layer, int) else len(config.vision_feature_layer) self.linear_1 = nn.Linear( config.vision_config.hidden_size * num_feature_layers, config.text_config.hidden_size, bias=config.multimodal_projector_bias, ) self.act = ACT2FN[config.projector_hidden_act] self.linear_2 = nn.Linear( config.text_config.hidden_size, config.text_config.hidden_size, bias=config.multimodal_projector_bias ) def forward(self, image_features): hidden_states = self.linear_1(image_features) hidden_states = self.act(hidden_states) hidden_states = self.linear_2(hidden_states) return hidden_states def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size): """ Calculate the shape of the image patch grid after the preprocessing for images of any resolution. Args: image_size (`tuple`): The size of the input image in the format (width, height). grid_pinpoints (`List`): A list containing possible resolutions. Each item in the list should be a tuple or list of the form `(height, width)`. patch_size (`int`): The size of each image patch. Returns: tuple: The shape of the image patch grid in the format (width, height). """ if not isinstance(grid_pinpoints, list): raise TypeError("grid_pinpoints should be a list of tuples or lists") # ! VERY IMPORTANT if image_size is tensor, must convert to into tuple, otherwise it will cause wrong calculate if not isinstance(image_size, (list, tuple)): if not isinstance(image_size, (torch.Tensor, np.ndarray)): raise TypeError( f"image_size invalid type: {type(image_size)} not valid, should be either list, tuple, np.ndarray or tensor" ) image_size = image_size.tolist() height, width = select_best_resolution(image_size, grid_pinpoints) return height // patch_size, width // patch_size def image_size_to_num_patches(image_size, grid_pinpoints, patch_size: int): """ Calculate the number of patches after the preprocessing for images of any resolution. Args: image_size (`torch.LongTensor` or `np.ndarray` or `tuple[int, int]`): The size of the input image in the format (height, width). ? grid_pinpoints (`List`): A list containing possible resolutions. Each item in the list should be a tuple or list of the form `(height, width)`. patch_size (`int`): The size of each image patch. Returns: int: the number of patches """ if not isinstance(grid_pinpoints, list): raise TypeError("grid_pinpoints should be a list of tuples or lists") # ! VERY IMPORTANT if image_size is tensor, must convert to into tuple, otherwise it will cause wrong calculate if not isinstance(image_size, (list, tuple)): if not isinstance(image_size, (torch.Tensor, np.ndarray)): raise TypeError(f"image_size invalid type {type(image_size)} with value {image_size}") image_size = image_size.tolist() best_resolution = select_best_resolution(image_size, grid_pinpoints) height, width = best_resolution num_patches = 0 # consider change to ceil(height/patch_size)*ceil(width/patch_size) + 1 for i in range(0, height, patch_size): for j in range(0, width, patch_size): num_patches += 1 # add the base patch num_patches += 1 return num_patches def unpad_image(tensor, original_size): """ Unpads a PyTorch tensor of a padded and resized image. Args: tensor (`torch.Tensor`): The image tensor, assumed to be of shape (num_channels, height, width). original_size (`tuple`): The original size of the image (height, width). Returns: `torch.Tensor`: The unpadded image tensor. """ if not isinstance(original_size, (list, tuple)): if not isinstance(original_size, (torch.Tensor, np.ndarray)): raise TypeError( f"image_size invalid type: {type(original_size)} not valid, should be either list, tuple, np.ndarray or tensor" ) original_size = original_size.tolist() original_height, original_width = original_size current_height, current_width = tensor.shape[1:] original_aspect_ratio = original_width / original_height current_aspect_ratio = current_width / current_height if original_aspect_ratio > current_aspect_ratio: scale_factor = current_width / original_width new_height = int(round(original_height * scale_factor, 7)) padding = (current_height - new_height) // 2 unpadded_tensor = tensor[:, padding : current_height - padding, :] else: scale_factor = current_height / original_height new_width = int(round(original_width * scale_factor, 7)) padding = (current_width - new_width) // 2 unpadded_tensor = tensor[:, :, padding : current_width - padding] return unpadded_tensor @auto_docstring( custom_intro=""" The Llava-Next model which consists of a vision backbone and a language model without language modeling head. """ )
LlavaOnevisionMultiModalProjector
python
sphinx-doc__sphinx
sphinx/domains/c/_ast.py
{ "start": 11534, "end": 12524 }
class ____(ASTExpression): def __init__(self, expr: ASTExpression) -> None: self.expr = expr def __eq__(self, other: object) -> bool: if not isinstance(other, ASTParenExpr): return NotImplemented return self.expr == other.expr def __hash__(self) -> int: return hash(self.expr) def _stringify(self, transform: StringifyTransform) -> str: return '(' + transform(self.expr) + ')' def get_id(self, version: int) -> str: return self.expr.get_id(version) # type: ignore[attr-defined] def describe_signature( self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol ) -> None: signode += addnodes.desc_sig_punctuation('(', '(') self.expr.describe_signature(signode, mode, env, symbol) signode += addnodes.desc_sig_punctuation(')', ')') # Postfix expressions ################################################################################
ASTParenExpr
python
getsentry__sentry
src/sentry/api/bases/organizationmember.py
{ "start": 1975, "end": 2411 }
class ____(serializers.IntegerField): """ Allow "me" in addition to integers """ def to_internal_value(self, data: float | int | str) -> Any: if data == "me": return data return super().to_internal_value(data) def run_validation(self, data: object | None = empty) -> object | None: if data == "me": return data return super().run_validation(data)
MemberIdField
python
kamyu104__LeetCode-Solutions
Python/number-of-ways-to-select-buildings.py
{ "start": 52, "end": 495 }
class ____(object): def numberOfWays(self, s): """ :type s: str :rtype: int """ K = 3 dp = [[0]*2 for _ in xrange(K)] # dp[i][j]: number of ways of selecting i+1 buildings ending with type j for c in s: j = ord(c)-ord('0') dp[0][j] += 1 for i in xrange(1, len(dp)): dp[i][j] += dp[i-1][1^j] return dp[-1][0]+dp[-1][1]
Solution
python
huggingface__transformers
src/transformers/models/pegasus_x/modeling_pegasus_x.py
{ "start": 5834, "end": 11436 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__( self, embed_dim: int, num_heads: int, dropout: float = 0.0, is_decoder: bool = False, bias: bool = True, is_causal: bool = False, config: Optional[PegasusXConfig] = None, layer_idx: Optional[int] = None, ): super().__init__() self.embed_dim = embed_dim self.num_heads = num_heads self.dropout = dropout self.head_dim = embed_dim // num_heads self.config = config if (self.head_dim * num_heads) != self.embed_dim: raise ValueError( f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}" f" and `num_heads`: {num_heads})." ) self.scaling = self.head_dim**-0.5 self.is_decoder = is_decoder self.is_causal = is_causal self.layer_idx = layer_idx if layer_idx is None and self.is_decoder: logger.warning_once( f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and " "will lead to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` " "when creating this class." ) self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias) self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias) self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias) self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) def forward( self, hidden_states: torch.Tensor, key_value_states: Optional[torch.Tensor] = None, past_key_values: Optional[Cache] = None, attention_mask: Optional[torch.Tensor] = None, output_attentions: bool = False, cache_position: Optional[torch.Tensor] = None, # TODO: we need a refactor so that the different attention modules can get their specific kwargs # ATM, we have mixed things encoder, decoder, and encoder-decoder attn **kwargs: Unpack[FlashAttentionKwargs], ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]: """Input shape: Batch x Time x Channel""" # if key_value_states are provided this layer is used as a cross-attention layer # for the decoder is_cross_attention = key_value_states is not None # determine input shapes bsz, tgt_len = hidden_states.shape[:-1] src_len = key_value_states.shape[1] if is_cross_attention else tgt_len q_input_shape = (bsz, tgt_len, -1, self.head_dim) kv_input_shape = (bsz, src_len, -1, self.head_dim) # get query proj query_states = self.q_proj(hidden_states).view(*q_input_shape).transpose(1, 2) is_updated = False if past_key_values is not None: if isinstance(past_key_values, EncoderDecoderCache): is_updated = past_key_values.is_updated.get(self.layer_idx) if is_cross_attention: # after the first generated id, we can subsequently re-use all key/value_states from cache curr_past_key_values = past_key_values.cross_attention_cache else: curr_past_key_values = past_key_values.self_attention_cache else: curr_past_key_values = past_key_values current_states = key_value_states if is_cross_attention else hidden_states if is_cross_attention and past_key_values is not None and is_updated: # reuse k,v, cross_attentions key_states = curr_past_key_values.layers[self.layer_idx].keys value_states = curr_past_key_values.layers[self.layer_idx].values else: key_states = self.k_proj(current_states) value_states = self.v_proj(current_states) key_states = key_states.view(*kv_input_shape).transpose(1, 2) value_states = value_states.view(*kv_input_shape).transpose(1, 2) if past_key_values is not None: # save all key/value_states to cache to be re-used for fast auto-regressive generation cache_position = cache_position if not is_cross_attention else None key_states, value_states = curr_past_key_values.update( key_states, value_states, self.layer_idx, {"cache_position": cache_position} ) # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache): past_key_values.is_updated[self.layer_idx] = True attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] attn_output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.dropout, scaling=self.scaling, output_attentions=output_attentions, **kwargs, ) attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous() attn_output = self.out_proj(attn_output) return attn_output, attn_weights
PegasusXAttention
python
pytorch__pytorch
torch/_dynamo/exc.py
{ "start": 3129, "end": 3503 }
class ____(TorchDynamoException): def __init__(self) -> None: super().__init__( textwrap.dedent( """ Must call `torch._dynamo.reset()` before changing backends. Detected two calls to `torch.compile()` with a different backend compiler arguments. """ ) )
ResetRequired
python
kubernetes-client__python
kubernetes/client/models/v1_api_resource.py
{ "start": 383, "end": 13876 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'categories': 'list[str]', 'group': 'str', 'kind': 'str', 'name': 'str', 'namespaced': 'bool', 'short_names': 'list[str]', 'singular_name': 'str', 'storage_version_hash': 'str', 'verbs': 'list[str]', 'version': 'str' } attribute_map = { 'categories': 'categories', 'group': 'group', 'kind': 'kind', 'name': 'name', 'namespaced': 'namespaced', 'short_names': 'shortNames', 'singular_name': 'singularName', 'storage_version_hash': 'storageVersionHash', 'verbs': 'verbs', 'version': 'version' } def __init__(self, categories=None, group=None, kind=None, name=None, namespaced=None, short_names=None, singular_name=None, storage_version_hash=None, verbs=None, version=None, local_vars_configuration=None): # noqa: E501 """V1APIResource - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._categories = None self._group = None self._kind = None self._name = None self._namespaced = None self._short_names = None self._singular_name = None self._storage_version_hash = None self._verbs = None self._version = None self.discriminator = None if categories is not None: self.categories = categories if group is not None: self.group = group self.kind = kind self.name = name self.namespaced = namespaced if short_names is not None: self.short_names = short_names self.singular_name = singular_name if storage_version_hash is not None: self.storage_version_hash = storage_version_hash self.verbs = verbs if version is not None: self.version = version @property def categories(self): """Gets the categories of this V1APIResource. # noqa: E501 categories is a list of the grouped resources this resource belongs to (e.g. 'all') # noqa: E501 :return: The categories of this V1APIResource. # noqa: E501 :rtype: list[str] """ return self._categories @categories.setter def categories(self, categories): """Sets the categories of this V1APIResource. categories is a list of the grouped resources this resource belongs to (e.g. 'all') # noqa: E501 :param categories: The categories of this V1APIResource. # noqa: E501 :type: list[str] """ self._categories = categories @property def group(self): """Gets the group of this V1APIResource. # noqa: E501 group is the preferred group of the resource. Empty implies the group of the containing resource list. For subresources, this may have a different value, for example: Scale\". # noqa: E501 :return: The group of this V1APIResource. # noqa: E501 :rtype: str """ return self._group @group.setter def group(self, group): """Sets the group of this V1APIResource. group is the preferred group of the resource. Empty implies the group of the containing resource list. For subresources, this may have a different value, for example: Scale\". # noqa: E501 :param group: The group of this V1APIResource. # noqa: E501 :type: str """ self._group = group @property def kind(self): """Gets the kind of this V1APIResource. # noqa: E501 kind is the kind for the resource (e.g. 'Foo' is the kind for a resource 'foo') # noqa: E501 :return: The kind of this V1APIResource. # noqa: E501 :rtype: str """ return self._kind @kind.setter def kind(self, kind): """Sets the kind of this V1APIResource. kind is the kind for the resource (e.g. 'Foo' is the kind for a resource 'foo') # noqa: E501 :param kind: The kind of this V1APIResource. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and kind is None: # noqa: E501 raise ValueError("Invalid value for `kind`, must not be `None`") # noqa: E501 self._kind = kind @property def name(self): """Gets the name of this V1APIResource. # noqa: E501 name is the plural name of the resource. # noqa: E501 :return: The name of this V1APIResource. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): """Sets the name of this V1APIResource. name is the plural name of the resource. # noqa: E501 :param name: The name of this V1APIResource. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and name is None: # noqa: E501 raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 self._name = name @property def namespaced(self): """Gets the namespaced of this V1APIResource. # noqa: E501 namespaced indicates if a resource is namespaced or not. # noqa: E501 :return: The namespaced of this V1APIResource. # noqa: E501 :rtype: bool """ return self._namespaced @namespaced.setter def namespaced(self, namespaced): """Sets the namespaced of this V1APIResource. namespaced indicates if a resource is namespaced or not. # noqa: E501 :param namespaced: The namespaced of this V1APIResource. # noqa: E501 :type: bool """ if self.local_vars_configuration.client_side_validation and namespaced is None: # noqa: E501 raise ValueError("Invalid value for `namespaced`, must not be `None`") # noqa: E501 self._namespaced = namespaced @property def short_names(self): """Gets the short_names of this V1APIResource. # noqa: E501 shortNames is a list of suggested short names of the resource. # noqa: E501 :return: The short_names of this V1APIResource. # noqa: E501 :rtype: list[str] """ return self._short_names @short_names.setter def short_names(self, short_names): """Sets the short_names of this V1APIResource. shortNames is a list of suggested short names of the resource. # noqa: E501 :param short_names: The short_names of this V1APIResource. # noqa: E501 :type: list[str] """ self._short_names = short_names @property def singular_name(self): """Gets the singular_name of this V1APIResource. # noqa: E501 singularName is the singular name of the resource. This allows clients to handle plural and singular opaquely. The singularName is more correct for reporting status on a single item and both singular and plural are allowed from the kubectl CLI interface. # noqa: E501 :return: The singular_name of this V1APIResource. # noqa: E501 :rtype: str """ return self._singular_name @singular_name.setter def singular_name(self, singular_name): """Sets the singular_name of this V1APIResource. singularName is the singular name of the resource. This allows clients to handle plural and singular opaquely. The singularName is more correct for reporting status on a single item and both singular and plural are allowed from the kubectl CLI interface. # noqa: E501 :param singular_name: The singular_name of this V1APIResource. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and singular_name is None: # noqa: E501 raise ValueError("Invalid value for `singular_name`, must not be `None`") # noqa: E501 self._singular_name = singular_name @property def storage_version_hash(self): """Gets the storage_version_hash of this V1APIResource. # noqa: E501 The hash value of the storage version, the version this resource is converted to when written to the data store. Value must be treated as opaque by clients. Only equality comparison on the value is valid. This is an alpha feature and may change or be removed in the future. The field is populated by the apiserver only if the StorageVersionHash feature gate is enabled. This field will remain optional even if it graduates. # noqa: E501 :return: The storage_version_hash of this V1APIResource. # noqa: E501 :rtype: str """ return self._storage_version_hash @storage_version_hash.setter def storage_version_hash(self, storage_version_hash): """Sets the storage_version_hash of this V1APIResource. The hash value of the storage version, the version this resource is converted to when written to the data store. Value must be treated as opaque by clients. Only equality comparison on the value is valid. This is an alpha feature and may change or be removed in the future. The field is populated by the apiserver only if the StorageVersionHash feature gate is enabled. This field will remain optional even if it graduates. # noqa: E501 :param storage_version_hash: The storage_version_hash of this V1APIResource. # noqa: E501 :type: str """ self._storage_version_hash = storage_version_hash @property def verbs(self): """Gets the verbs of this V1APIResource. # noqa: E501 verbs is a list of supported kube verbs (this includes get, list, watch, create, update, patch, delete, deletecollection, and proxy) # noqa: E501 :return: The verbs of this V1APIResource. # noqa: E501 :rtype: list[str] """ return self._verbs @verbs.setter def verbs(self, verbs): """Sets the verbs of this V1APIResource. verbs is a list of supported kube verbs (this includes get, list, watch, create, update, patch, delete, deletecollection, and proxy) # noqa: E501 :param verbs: The verbs of this V1APIResource. # noqa: E501 :type: list[str] """ if self.local_vars_configuration.client_side_validation and verbs is None: # noqa: E501 raise ValueError("Invalid value for `verbs`, must not be `None`") # noqa: E501 self._verbs = verbs @property def version(self): """Gets the version of this V1APIResource. # noqa: E501 version is the preferred version of the resource. Empty implies the version of the containing resource list For subresources, this may have a different value, for example: v1 (while inside a v1beta1 version of the core resource's group)\". # noqa: E501 :return: The version of this V1APIResource. # noqa: E501 :rtype: str """ return self._version @version.setter def version(self, version): """Sets the version of this V1APIResource. version is the preferred version of the resource. Empty implies the version of the containing resource list For subresources, this may have a different value, for example: v1 (while inside a v1beta1 version of the core resource's group)\". # noqa: E501 :param version: The version of this V1APIResource. # noqa: E501 :type: str """ self._version = version def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1APIResource): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1APIResource): return True return self.to_dict() != other.to_dict()
V1APIResource
python
keon__algorithms
algorithms/linkedlist/kth_to_last.py
{ "start": 0, "end": 2707 }
class ____(): def __init__(self, val=None): self.val = val self.next = None def kth_to_last_eval(head, k): """ This is a suboptimal, hacky method using eval(), which is not safe for user input. We guard against danger by ensuring k in an int """ if not isinstance(k, int) or not head.val: return False nexts = '.'.join(['next' for n in range(1, k+1)]) seeker = str('.'.join(['head', nexts])) while head: if eval(seeker) is None: return head else: head = head.next return False def kth_to_last_dict(head, k): """ This is a brute force method where we keep a dict the size of the list Then we check it for the value we need. If the key is not in the dict, our and statement will short circuit and return False """ if not (head and k > -1): return False d = dict() count = 0 while head: d[count] = head head = head.next count += 1 return len(d)-k in d and d[len(d)-k] def kth_to_last(head, k): """ This is an optimal method using iteration. We move p1 k steps ahead into the list. Then we move p1 and p2 together until p1 hits the end. """ if not (head or k > -1): return False p1 = head p2 = head for i in range(1, k+1): if p1 is None: # Went too far, k is not valid raise IndexError p1 = p1.next while p1: p1 = p1.next p2 = p2.next return p2 def print_linked_list(head): string = "" while head.next: string += head.val + " -> " head = head.next string += head.val print(string) def test(): # def make_test_li # A A B C D C F G a1 = Node("A") a2 = Node("A") b = Node("B") c1 = Node("C") d = Node("D") c2 = Node("C") f = Node("F") g = Node("G") a1.next = a2 a2.next = b b.next = c1 c1.next = d d.next = c2 c2.next = f f.next = g print_linked_list(a1) # test kth_to_last_eval kth = kth_to_last_eval(a1, 4) try: assert kth.val == "D" except AssertionError as e: e.args += ("Expecting D, got %s" % kth.val,) raise # test kth_to_last_dict kth = kth_to_last_dict(a1, 4) try: assert kth.val == "D" except AssertionError as e: e.args += ("Expecting D, got %s" % kth.val,) raise # test kth_to_last kth = kth_to_last(a1, 4) try: assert kth.val == "D" except AssertionError as e: e.args += ("Expecting D, got %s" % kth.val,) raise print("all passed.") if __name__ == '__main__': test()
Node
python
bokeh__bokeh
src/bokeh/resources.py
{ "start": 7713, "end": 7896 }
class ____: urls: UrlsFn messages: list[RuntimeMessage] = field(default_factory=list) hashes: HashesFn | None = None ResourceAttr = Literal["__css__", "__javascript__"]
Urls
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 929255, "end": 930034 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "actor", "created_at", "current_title", "previous_title", "subject", ) actor = sgqlc.types.Field(Actor, graphql_name="actor") created_at = sgqlc.types.Field( sgqlc.types.non_null(DateTime), graphql_name="createdAt" ) current_title = sgqlc.types.Field( sgqlc.types.non_null(String), graphql_name="currentTitle" ) previous_title = sgqlc.types.Field( sgqlc.types.non_null(String), graphql_name="previousTitle" ) subject = sgqlc.types.Field( sgqlc.types.non_null("RenamedTitleSubject"), graphql_name="subject" )
RenamedTitleEvent
python
Pylons__pyramid
docs/tutorials/wiki/src/tests/tests/test_views.py
{ "start": 30, "end": 350 }
class ____: def test_it_redirects_to_front_page(self): from tutorial.views.default import view_wiki context = testing.DummyResource() request = testing.DummyRequest() response = view_wiki(context, request) assert response.location == 'http://example.com/FrontPage'
Test_view_wiki
python
dask__dask
dask/dataframe/dask_expr/_indexing.py
{ "start": 10191, "end": 10703 }
class ____(LocList): _parameters = ["meta", "cindexer"] def _lower(self): return None @functools.cached_property def _meta(self): if self.cindexer is None: return self.operand("meta") else: return self.operand("meta").loc[:, self.cindexer] @functools.cached_property def _layer_information(self): divisions = [None, None] dsk = {(self._name, 0): DataNode((self._name, 0), self._meta)} return dsk, divisions
LocEmpty
python
pytorch__pytorch
test/distributed/test_symmetric_memory.py
{ "start": 45962, "end": 49107 }
class ____(TestCase): @requires_cuda @skipIf( not TEST_WITH_ROCM and _get_torch_cuda_version() < (12, 0), "stream_write_value32 currently only supports cuda version>=12.0", ) @skipIf( not PLATFORM_SUPPORTS_SYMM_MEM, "SymmMem is not supported on this ROCm arch" ) def test_stream_write_value32(self): tensor = torch.zeros(4, dtype=torch.uint32, device="cuda") expect = torch.tril(torch.ones(4, 4, device="cuda")).to(torch.uint32) for i in range(4): _SymmetricMemory.stream_write_value32(tensor, i, 1) torch.testing.assert_close(tensor, expect[i]) with self.assertRaises(RuntimeError): _SymmetricMemory.stream_write_value32(tensor, offset=-1, val=1) with self.assertRaises(RuntimeError): _SymmetricMemory.stream_write_value32(tensor, offset=0, val=4294967296) @skipIf( not PLATFORM_SUPPORTS_SYMM_MEM, "SymmMem is not supported on this ROCm arch" ) @requires_cuda def test_memset32(self): t = _SymmetricMemory.empty_strided_p2p( (64,), (1,), dtype=torch.uint32, device=torch.device("cuda:0"), group_name="0", ).fill_(0) _SymmetricMemory.memset32(t, offset=32, val=1, count=16) self.assertTrue(t[:32].eq(0).all()) self.assertTrue(t[32:48].eq(1).all()) self.assertTrue(t[48:].eq(0).all()) with self.assertRaisesRegex( RuntimeError, "input must be a flat, contiguous uint32 tensor" ): _SymmetricMemory.memset32(t.view(8, 8), offset=0, val=1, count=1) with self.assertRaisesRegex( RuntimeError, "input must be a flat, contiguous uint32 tensor" ): _SymmetricMemory.memset32(t.view(torch.float32), offset=0, val=1, count=1) with self.assertRaisesRegex( RuntimeError, "offset must be greater than or equal to 0" ): _SymmetricMemory.memset32(t, offset=-1, val=1, count=1) with self.assertRaisesRegex( RuntimeError, r"val must be in the range of.*\(uint32_t\)" ): _SymmetricMemory.memset32(t, offset=0, val=4294967296, count=1) with self.assertRaisesRegex(RuntimeError, "count must be a positive integer"): _SymmetricMemory.memset32(t, offset=0, val=1, count=-1) with self.assertRaisesRegex(RuntimeError, "count must be a positive integer"): _SymmetricMemory.memset32(t, offset=0, val=1, count=0) with self.assertRaisesRegex( RuntimeError, r"offset \+ count.*exceeded the numel of the input" ): _SymmetricMemory.memset32(t, offset=64, val=1, count=1) with self.assertRaisesRegex( RuntimeError, r"offset \+ count.*exceeded the numel of the input" ): _SymmetricMemory.memset32(t, offset=0, val=1, count=65) _SymmetricMemory.memset32(t, offset=0, val=1, count=64) _SymmetricMemory.memset32(t, offset=63, val=1, count=1) if __name__ == "__main__": run_tests()
SymmMemSingleProcTest
python
modin-project__modin
modin/config/envvars.py
{ "start": 23498, "end": 23690 }
class ____(EnvironmentVariable, type=ExactStr): """What password to use for connecting to Redis.""" varname = "MODIN_REDIS_PASSWORD" default = secrets.token_hex(32)
RayRedisPassword
python
spyder-ide__spyder
spyder/widgets/collectionseditor.py
{ "start": 2807, "end": 3412 }
class ____: Close = 'close' Copy = 'copy_action' Duplicate = 'duplicate_action' Edit = 'edit_action' Histogram = 'histogram_action' Insert = 'insert_action' InsertAbove = 'insert_above_action' InsertBelow = 'insert_below_action' Paste = 'paste_action' Plot = 'plot_action' Refresh = 'refresh_action' Remove = 'remove_action' Rename = 'rename_action' ResizeColumns = 'resize_columns_action' ResizeRows = 'resize_rows_action' Save = 'save_action' ShowImage = 'show_image_action' ViewObject = 'view_object_action'
CollectionsEditorActions
python
PrefectHQ__prefect
tests/server/models/test_logs.py
{ "start": 2085, "end": 4763 }
class ____: async def test_read_logs_timestamp_after_inclusive(self, session, logs, log_data): after = log_data[1].timestamp log_filter = LogFilter(timestamp={"after_": after}) logs = await models.logs.read_logs( session=session, log_filter=log_filter, sort=LogSort.TIMESTAMP_ASC ) assert len(logs) == 2 # We get a log with the same timestamp as the given timestamp. assert logs[0].timestamp == after # We get a log with a timestamp after the given timestamp. assert logs[1].timestamp > after async def test_read_logs_timestamp_before_inclusive(self, session, logs, log_data): before = log_data[1].timestamp log_filter = LogFilter(timestamp={"before_": before}) logs = await models.logs.read_logs( session=session, log_filter=log_filter, sort=LogSort.TIMESTAMP_ASC ) assert len(logs) == 2 # We get a log with a timestamp before the given timestamp. assert logs[0].timestamp < before # We get a log with the same timestamp as the given timestamp. assert logs[1].timestamp == before async def test_read_logs_flow_run_id(self, session, logs, flow_run_id): log_filter = LogFilter(flow_run_id={"any_": [flow_run_id]}) logs = await models.logs.read_logs(session=session, log_filter=log_filter) assert len(logs) == 3 assert all([log.flow_run_id == flow_run_id for log in logs]) async def test_read_logs_task_run_id(self, session, logs, task_run_id): log_filter = LogFilter(task_run_id={"any_": [task_run_id]}) logs = await models.logs.read_logs(session=session, log_filter=log_filter) assert len(logs) == 1 assert all([log.task_run_id == task_run_id for log in logs]) async def test_read_logs_task_run_id_is_null(self, session, logs, flow_run_id): log_filter = LogFilter( flow_run_id={"any_": [flow_run_id]}, task_run_id=LogFilterTaskRunId(is_null_=True), ) logs_filtered = await models.logs.read_logs( session=session, log_filter=log_filter ) assert len(logs_filtered) == 2 assert all([log.task_run_id is None for log in logs_filtered]) async def test_read_logs_task_run_id_is_not_null(self, session, logs, flow_run_id): log_filter = LogFilter( flow_run_id={"any_": [flow_run_id]}, task_run_id={"is_null_": False} ) logs = await models.logs.read_logs(session=session, log_filter=log_filter) assert len(logs) == 1 assert all([log.task_run_id is not None for log in logs])
TestReadLogs
python
django__django
tests/managers_regress/models.py
{ "start": 1755, "end": 1893 }
class ____(AbstractBase1, AbstractBase3): data = models.CharField(max_length=25) def __str__(self): return self.data
Child3
python
walkccc__LeetCode
solutions/1043. Partition Array for Maximum Sum/1043.py
{ "start": 0, "end": 314 }
class ____: def maxSumAfterPartitioning(self, arr: list[int], k: int) -> int: n = len(arr) dp = [0] * (n + 1) for i in range(1, n + 1): mx = -math.inf for j in range(1, min(i, k) + 1): mx = max(mx, arr[i - j]) dp[i] = max(dp[i], dp[i - j] + mx * j) return dp[n]
Solution
python
huggingface__transformers
src/transformers/generation/logits_process.py
{ "start": 31819, "end": 35673 }
class ____(LogitsProcessor): """ [`LogitsProcessor`] that performs min-p, i.e. keeps all tokens that are above a minimum probability, scaled by the probability of the most likely token. As a result, the filter becomes more aggressive in the presence of high-probability tokens, which is a sign of a confident output that we shouldn't deviate from. Often used together with [`TemperatureLogitsWarper`]. Used as an alternative to [`TopPLogitsWarper`] and [`TopKLogitsWarper`]. Created by @menhguin and @kalomaze (github handles). Code adapted from [this external PR](https://github.com/oobabooga/text-generation-webui/pull/4449/files) Args: min_p (`float`): Minimum token probability, which will be scaled by the probability of the most likely token. It must be a value between 0 and 1. Typical values are in the 0.01-0.2 range, comparably selective as setting `top_p` in the 0.99-0.8 range (use the opposite of normal `top_p` values). filter_value (`float`, *optional*, defaults to -inf): All filtered values will be set to this float value. min_tokens_to_keep (`int`, *optional*, defaults to 1): Minimum number of tokens that cannot be filtered. Examples: ```python >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed >>> set_seed(1) >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2") >>> inputs = tokenizer("A sequence: 1, 2", return_tensors="pt") >>> # With sampling, the output is unexpected -- sometimes too unexpected. >>> outputs = model.generate(**inputs, do_sample=True) >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) A sequence: 1, 2, 3 | < 4 (left-hand pointer) ; <BLANKLINE> <BLANKLINE> >>> # With `min_p` sampling, the output gets restricted to high-probability tokens. >>> # Pro tip: In practice, LLMs use `min_p` in the 0.01-0.2 range. >>> outputs = model.generate(**inputs, do_sample=True, min_p=0.1) >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) A sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9 ``` """ def __init__(self, min_p: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1): if not (0 <= min_p <= 1.0): raise ValueError(f"`min_p` has to be a float in the [0, 1] interval, but is {min_p}") if not isinstance(min_tokens_to_keep, int) or (min_tokens_to_keep < 1): raise ValueError(f"`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}") self.min_p = min_p self.filter_value = filter_value self.min_tokens_to_keep = min_tokens_to_keep def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor: # Convert logits to probabilities probs = torch.softmax(scores, dim=-1) # Get the probability of the top token for each sequence in the batch top_probs = probs.amax(dim=-1, keepdim=True) # Calculate the actual min_p threshold by scaling min_p with the top token's probability scaled_min_p = self.min_p * top_probs # Create a mask for tokens that have a probability less than the scaled min_p tokens_to_remove = probs < scaled_min_p # Keep at least min_tokens_to_keep tokens (clip k to vocab size if needed, avoids index out of range) k = min(self.min_tokens_to_keep, probs.shape[-1]) sorted_indices = torch.topk(probs, k, dim=-1).indices tokens_to_remove.scatter_(-1, sorted_indices, False) scores_processed = scores.masked_fill(tokens_to_remove, self.filter_value) return scores_processed
MinPLogitsWarper
python
modin-project__modin
modin/core/storage_formats/pandas/parsers.py
{ "start": 22672, "end": 23991 }
class ____(PandasParser): @staticmethod @doc(_doc_parse_func, parameters=_doc_parse_parameters_common) def parse(fname, **kwargs): num_splits = kwargs.pop("num_splits", None) start = kwargs.pop("start", None) end = kwargs.pop("end", None) if start is not None and end is not None: # pop "compression" from kwargs because bio is uncompressed with OpenFile( fname, "rb", kwargs.pop("compression", "infer"), **(kwargs.pop("storage_options", None) or {}), ) as bio: bio.seek(start) to_read = b"" + bio.read(end - start) columns = kwargs.pop("columns") pandas_df = pandas.read_json(BytesIO(to_read), **kwargs) else: # This only happens when we are reading with only one worker (Default) return pandas.read_json(fname, **kwargs) if not pandas_df.columns.equals(columns): raise ModinAssumptionError("Columns must be the same across all rows.") partition_columns = pandas_df.columns return _split_result_for_readers(1, num_splits, pandas_df) + [ len(pandas_df), pandas_df.dtypes, partition_columns, ]
PandasJSONParser
python
joke2k__faker
tests/providers/test_internet.py
{ "start": 28449, "end": 29440 }
class ____: """Test ar_AA internet provider methods""" @patch( "faker.providers.internet.Provider.user_name", lambda x: "اصيل", ) def test_ascii_safe_email(self, faker): email = faker.ascii_safe_email() validate_email(email) assert email.split("@")[0] == "asyl" @patch( "faker.providers.internet.Provider.user_name", lambda x: "اصيل", ) def test_ascii_free_email(self, faker): email = faker.ascii_free_email() validate_email(email) assert email.split("@")[0] == "asyl" @patch( "faker.providers.internet.Provider.user_name", lambda x: "اصيل", ) def test_ascii_company_email(self, faker): email = faker.ascii_company_email() validate_email(email) assert email.split("@")[0] == "asyl" def test_slug(self, faker): num_of_samples = 100 for _ in range(num_of_samples): assert faker.slug() != ""
TestArAa
python
pypa__setuptools
setuptools/_distutils/tests/test_dist.py
{ "start": 456, "end": 711 }
class ____(Command): """Sample distutils extension command.""" user_options: ClassVar[list[tuple[str, str, str]]] = [ ("sample-option=", "S", "help text"), ] def initialize_options(self): self.sample_option = None
test_dist
python
pypa__pipenv
pipenv/patched/pip/_internal/utils/misc.py
{ "start": 19116, "end": 23570 }
class ____(BuildBackendHookCaller): def __init__( self, config_holder: Any, source_dir: str, build_backend: str, backend_path: Optional[str] = None, runner: Optional[Callable[..., None]] = None, python_executable: Optional[str] = None, ): super().__init__( source_dir, build_backend, backend_path, runner, python_executable ) self.config_holder = config_holder def build_wheel( self, wheel_directory: str, config_settings: Optional[Mapping[str, Any]] = None, metadata_directory: Optional[str] = None, ) -> str: cs = self.config_holder.config_settings return super().build_wheel( wheel_directory, config_settings=cs, metadata_directory=metadata_directory ) def build_sdist( self, sdist_directory: str, config_settings: Optional[Mapping[str, Any]] = None, ) -> str: cs = self.config_holder.config_settings return super().build_sdist(sdist_directory, config_settings=cs) def build_editable( self, wheel_directory: str, config_settings: Optional[Mapping[str, Any]] = None, metadata_directory: Optional[str] = None, ) -> str: cs = self.config_holder.config_settings return super().build_editable( wheel_directory, config_settings=cs, metadata_directory=metadata_directory ) def get_requires_for_build_wheel( self, config_settings: Optional[Mapping[str, Any]] = None ) -> Sequence[str]: cs = self.config_holder.config_settings return super().get_requires_for_build_wheel(config_settings=cs) def get_requires_for_build_sdist( self, config_settings: Optional[Mapping[str, Any]] = None ) -> Sequence[str]: cs = self.config_holder.config_settings return super().get_requires_for_build_sdist(config_settings=cs) def get_requires_for_build_editable( self, config_settings: Optional[Mapping[str, Any]] = None ) -> Sequence[str]: cs = self.config_holder.config_settings return super().get_requires_for_build_editable(config_settings=cs) def prepare_metadata_for_build_wheel( self, metadata_directory: str, config_settings: Optional[Mapping[str, Any]] = None, _allow_fallback: bool = True, ) -> str: cs = self.config_holder.config_settings return super().prepare_metadata_for_build_wheel( metadata_directory=metadata_directory, config_settings=cs, _allow_fallback=_allow_fallback, ) def prepare_metadata_for_build_editable( self, metadata_directory: str, config_settings: Optional[Mapping[str, Any]] = None, _allow_fallback: bool = True, ) -> Optional[str]: cs = self.config_holder.config_settings return super().prepare_metadata_for_build_editable( metadata_directory=metadata_directory, config_settings=cs, _allow_fallback=_allow_fallback, ) def warn_if_run_as_root() -> None: """Output a warning for sudo users on Unix. In a virtual environment, sudo pip still writes to virtualenv. On Windows, users may run pip as Administrator without issues. This warning only applies to Unix root users outside of virtualenv. """ if running_under_virtualenv(): return if not hasattr(os, "getuid"): return # On Windows, there are no "system managed" Python packages. Installing as # Administrator via pip is the correct way of updating system environments. # # We choose sys.platform over utils.compat.WINDOWS here to enable Mypy platform # checks: https://mypy.readthedocs.io/en/stable/common_issues.html if sys.platform == "win32" or sys.platform == "cygwin": return if os.getuid() != 0: return logger.warning( "Running pip as the 'root' user can result in broken permissions and " "conflicting behaviour with the system package manager, possibly " "rendering your system unusable. " "It is recommended to use a virtual environment instead: " "https://pip.pypa.io/warnings/venv. " "Use the --root-user-action option if you know what you are doing and " "want to suppress this warning." )
ConfiguredBuildBackendHookCaller
python
sqlalchemy__sqlalchemy
test/orm/declarative/test_reflection.py
{ "start": 975, "end": 6319 }
class ____(DeclarativeReflectionBase): @classmethod def define_tables(cls, metadata): Table( "users", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("name", String(50)), test_needs_fk=True, ) Table( "addresses", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("email", String(50)), Column("user_id", Integer, ForeignKey("users.id")), test_needs_fk=True, ) Table( "imhandles", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("user_id", Integer), Column("network", String(50)), Column("handle", String(50)), test_needs_fk=True, ) def test_basic(self): class User(Base, ComparableEntity): __tablename__ = "users" __autoload_with__ = testing.db addresses = relationship("Address", backref="user") class Address(Base, ComparableEntity): __tablename__ = "addresses" __autoload_with__ = testing.db u1 = User( name="u1", addresses=[Address(email="one"), Address(email="two")] ) sess = fixture_session() sess.add(u1) sess.flush() sess.expunge_all() eq_( sess.query(User).all(), [ User( name="u1", addresses=[Address(email="one"), Address(email="two")], ) ], ) a1 = sess.query(Address).filter(Address.email == "two").one() eq_(a1, Address(email="two")) eq_(a1.user, User(name="u1")) def test_rekey_wbase(self): class User(Base, ComparableEntity): __tablename__ = "users" __autoload_with__ = testing.db nom = Column("name", String(50), key="nom") addresses = relationship("Address", backref="user") class Address(Base, ComparableEntity): __tablename__ = "addresses" __autoload_with__ = testing.db u1 = User( nom="u1", addresses=[Address(email="one"), Address(email="two")] ) sess = fixture_session() sess.add(u1) sess.flush() sess.expunge_all() eq_( sess.query(User).all(), [ User( nom="u1", addresses=[Address(email="one"), Address(email="two")], ) ], ) a1 = sess.query(Address).filter(Address.email == "two").one() eq_(a1, Address(email="two")) eq_(a1.user, User(nom="u1")) assert_raises(TypeError, User, name="u3") def test_rekey_wdecorator(self): @registry.mapped class User(ComparableMixin): __tablename__ = "users" __autoload_with__ = testing.db nom = Column("name", String(50), key="nom") addresses = relationship("Address", backref="user") @registry.mapped class Address(ComparableMixin): __tablename__ = "addresses" __autoload_with__ = testing.db u1 = User( nom="u1", addresses=[Address(email="one"), Address(email="two")] ) sess = fixture_session() sess.add(u1) sess.flush() sess.expunge_all() eq_( sess.query(User).all(), [ User( nom="u1", addresses=[Address(email="one"), Address(email="two")], ) ], ) a1 = sess.query(Address).filter(Address.email == "two").one() eq_(a1, Address(email="two")) eq_(a1.user, User(nom="u1")) assert_raises(TypeError, User, name="u3") def test_supplied_fk(self): class IMHandle(Base, ComparableEntity): __tablename__ = "imhandles" __autoload_with__ = testing.db user_id = Column("user_id", Integer, ForeignKey("users.id")) class User(Base, ComparableEntity): __tablename__ = "users" __autoload_with__ = testing.db handles = relationship("IMHandle", backref="user") u1 = User( name="u1", handles=[ IMHandle(network="blabber", handle="foo"), IMHandle(network="lol", handle="zomg"), ], ) sess = fixture_session() sess.add(u1) sess.flush() sess.expunge_all() eq_( sess.query(User).all(), [ User( name="u1", handles=[ IMHandle(network="blabber", handle="foo"), IMHandle(network="lol", handle="zomg"), ], ) ], ) a1 = sess.query(IMHandle).filter(IMHandle.handle == "zomg").one() eq_(a1, IMHandle(network="lol", handle="zomg")) eq_(a1.user, User(name="u1"))
DeclarativeReflectionTest
python
python__mypy
mypyc/ir/class_ir.py
{ "start": 3158, "end": 3329 }
class ____(NamedTuple): cls: "ClassIR" # noqa: UP037 name: str method: FuncIR shadow_method: FuncIR | None VTableEntries = list[VTableMethod]
VTableMethod
python
pytest-dev__pytest-xdist
testing/test_dsession.py
{ "start": 10850, "end": 18113 }
class ____: def test_ideal_case(self, pytester: pytest.Pytester) -> None: config = pytester.parseconfig("--tx=2*popen") sched = WorkStealingScheduling(config) node1, node2 = MockNode(), MockNode() sched.add_node(node1) sched.add_node(node2) collection = [f"test_workstealing.py::test_{i}" for i in range(16)] assert not sched.collection_is_completed sched.add_node_collection(node1, collection) assert not sched.collection_is_completed sched.add_node_collection(node2, collection) assert bool(sched.collection_is_completed) assert sched.node2collection[node1] == collection assert sched.node2collection[node2] == collection sched.schedule() assert not sched.pending assert not sched.tests_finished assert node1.sent == list(range(8)) assert node2.sent == list(range(8, 16)) for i in range(8): sent1, sent2 = node1.sent[i], node2.sent[i] assert isinstance(sent1, int) and isinstance(sent2, int) sched.mark_test_complete(node1, sent1) sched.mark_test_complete(node2, sent2) assert bool(sched.tests_finished) assert node1.stolen == [] assert node2.stolen == [] def test_stealing(self, pytester: pytest.Pytester) -> None: config = pytester.parseconfig("--tx=2*popen") sched = WorkStealingScheduling(config) node1, node2 = MockNode(), MockNode() sched.add_node(node1) sched.add_node(node2) collection = [f"test_workstealing.py::test_{i}" for i in range(16)] sched.add_node_collection(node1, collection) sched.add_node_collection(node2, collection) assert sched.collection_is_completed sched.schedule() assert node1.sent == list(range(8)) assert node2.sent == list(range(8, 16)) for i in range(8): sent = node1.sent[i] assert isinstance(sent, int) sched.mark_test_complete(node1, sent) assert node2.stolen == list(range(12, 16)) sched.remove_pending_tests_from_node(node2, node2.stolen) for i in range(4): sent = node2.sent[i] assert isinstance(sent, int) sched.mark_test_complete(node2, sent) assert node1.stolen == [14, 15] sched.remove_pending_tests_from_node(node1, node1.stolen) sched.mark_test_complete(node1, 12) sched.mark_test_complete(node2, 14) assert node2.stolen == list(range(12, 16)) assert node1.stolen == [14, 15] assert sched.tests_finished def test_steal_on_add_node(self, pytester: pytest.Pytester) -> None: node = MockNode() config = pytester.parseconfig("--tx=popen") sched = WorkStealingScheduling(config) sched.add_node(node) collection = [f"test_workstealing.py::test_{i}" for i in range(5)] sched.add_node_collection(node, collection) assert sched.collection_is_completed sched.schedule() assert not sched.pending sched.mark_test_complete(node, 0) node2 = MockNode() sched.add_node(node2) sched.add_node_collection(node2, collection) assert sched.collection_is_completed sched.schedule() assert node.stolen == [3, 4] sched.remove_pending_tests_from_node(node, node.stolen) sched.mark_test_complete(node, 1) sched.mark_test_complete(node2, 3) assert sched.tests_finished assert node2.stolen == [] def test_schedule_fewer_tests_than_nodes(self, pytester: pytest.Pytester) -> None: config = pytester.parseconfig("--tx=3*popen") sched = WorkStealingScheduling(config) node1, node2, node3 = MockNode(), MockNode(), MockNode() sched.add_node(node1) sched.add_node(node2) sched.add_node(node3) col = ["xyz"] * 2 sched.add_node_collection(node1, col) sched.add_node_collection(node2, col) sched.add_node_collection(node3, col) sched.schedule() assert node1.sent == [] assert node1.stolen == [] assert node2.sent == [0] assert node2.stolen == [] assert node3.sent == [1] assert node3.stolen == [] assert not sched.pending assert sched.tests_finished def test_schedule_fewer_than_two_tests_per_node( self, pytester: pytest.Pytester ) -> None: config = pytester.parseconfig("--tx=3*popen") sched = WorkStealingScheduling(config) node1, node2, node3 = MockNode(), MockNode(), MockNode() sched.add_node(node1) sched.add_node(node2) sched.add_node(node3) col = ["xyz"] * 5 sched.add_node_collection(node1, col) sched.add_node_collection(node2, col) sched.add_node_collection(node3, col) sched.schedule() assert node1.sent == [0] assert node2.sent == [1, 2] assert node3.sent == [3, 4] assert not sched.pending assert not sched.tests_finished sent10 = node1.sent[0] assert isinstance(sent10, int) sent20 = node2.sent[0] assert isinstance(sent20, int) sent30 = node3.sent[0] assert isinstance(sent30, int) sent31 = node3.sent[1] assert isinstance(sent31, int) sched.mark_test_complete(node1, sent10) sched.mark_test_complete(node2, sent20) sched.mark_test_complete(node3, sent30) sched.mark_test_complete(node3, sent31) assert bool(sched.tests_finished) assert node1.stolen == [] assert node2.stolen == [] assert node3.stolen == [] def test_add_remove_node(self, pytester: pytest.Pytester) -> None: node = MockNode() config = pytester.parseconfig("--tx=popen") sched = WorkStealingScheduling(config) sched.add_node(node) collection = ["test_file.py::test_func"] sched.add_node_collection(node, collection) assert sched.collection_is_completed sched.schedule() assert not sched.pending crashitem = sched.remove_node(node) assert crashitem == collection[0] def test_different_tests_collected(self, pytester: pytest.Pytester) -> None: class CollectHook: def __init__(self) -> None: self.reports: list[pytest.CollectReport] = [] def pytest_collectreport(self, report: pytest.CollectReport) -> None: self.reports.append(report) collect_hook = CollectHook() config = pytester.parseconfig("--tx=2*popen") config.pluginmanager.register(collect_hook, "collect_hook") sched = WorkStealingScheduling(config) node1, node2 = MockNode(), MockNode() sched.add_node(node1) sched.add_node(node2) sched.add_node_collection(node1, ["a.py::test_1"]) sched.add_node_collection(node2, ["a.py::test_2"]) sched.schedule() assert len(collect_hook.reports) == 1 rep = collect_hook.reports[0] assert isinstance(rep.longrepr, str) assert "Different tests were collected between" in rep.longrepr
TestWorkStealingScheduling
python
huggingface__transformers
src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
{ "start": 25537, "end": 26691 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config self.layer = nn.ModuleList( [InstructBlipVideoQFormerLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.gradient_checkpointing = False @can_return_tuple def forward( self, hidden_states, attention_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, query_length=0, **kwargs: Unpack[TransformersKwargs], ): for i in range(self.config.num_hidden_layers): layer_module = self.layer[i] hidden_states = layer_module( hidden_states, attention_mask, encoder_hidden_states, # as a positional argument for gradient checkpointing encoder_attention_mask=encoder_attention_mask, query_length=query_length, **kwargs, ) return BaseModelOutputWithPastAndCrossAttentions( last_hidden_state=hidden_states, )
InstructBlipVideoQFormerEncoder
python
pydantic__pydantic
pydantic/_internal/_model_construction.py
{ "start": 35423, "end": 38277 }
class ____: """Wrapper for `weakref.ref` that enables `pickle` serialization. Cloudpickle fails to serialize `weakref.ref` objects due to an arcane error related to abstract base classes (`abc.ABC`). This class works around the issue by wrapping `weakref.ref` instead of subclassing it. See https://github.com/pydantic/pydantic/issues/6763 for context. Semantics: - If not pickled, behaves the same as a `weakref.ref`. - If pickled along with the referenced object, the same `weakref.ref` behavior will be maintained between them after unpickling. - If pickled without the referenced object, after unpickling the underlying reference will be cleared (`__call__` will always return `None`). """ def __init__(self, obj: Any): if obj is None: # The object will be `None` upon deserialization if the serialized weakref # had lost its underlying object. self._wr = None else: self._wr = weakref.ref(obj) def __call__(self) -> Any: if self._wr is None: return None else: return self._wr() def __reduce__(self) -> tuple[Callable, tuple[weakref.ReferenceType | None]]: return _PydanticWeakRef, (self(),) def build_lenient_weakvaluedict(d: dict[str, Any] | None) -> dict[str, Any] | None: """Takes an input dictionary, and produces a new value that (invertibly) replaces the values with weakrefs. We can't just use a WeakValueDictionary because many types (including int, str, etc.) can't be stored as values in a WeakValueDictionary. The `unpack_lenient_weakvaluedict` function can be used to reverse this operation. """ if d is None: return None result = {} for k, v in d.items(): try: proxy = _PydanticWeakRef(v) except TypeError: proxy = v result[k] = proxy return result def unpack_lenient_weakvaluedict(d: dict[str, Any] | None) -> dict[str, Any] | None: """Inverts the transform performed by `build_lenient_weakvaluedict`.""" if d is None: return None result = {} for k, v in d.items(): if isinstance(v, _PydanticWeakRef): v = v() if v is not None: result[k] = v else: result[k] = v return result @cache def default_ignored_types() -> tuple[type[Any], ...]: from ..fields import ComputedFieldInfo ignored_types = [ FunctionType, property, classmethod, staticmethod, PydanticDescriptorProxy, ComputedFieldInfo, TypeAliasType, # from `typing_extensions` ] if sys.version_info >= (3, 12): ignored_types.append(typing.TypeAliasType) return tuple(ignored_types)
_PydanticWeakRef
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/roles.py
{ "start": 4813, "end": 5024 }
class ____(AllowsLambdaRole, UsesInspection, StructuralRole): __slots__ = () _role_name = ( "Join target, typically a FROM expression, or ORM " "relationship attribute" )
JoinTargetRole
python
django__django
django/db/migrations/utils.py
{ "start": 245, "end": 4401 }
class ____: def __init__(self, obj): self.pattern = obj.pattern self.flags = obj.flags def __eq__(self, other): if not isinstance(other, RegexObject): return NotImplemented return self.pattern == other.pattern and self.flags == other.flags def get_migration_name_timestamp(): return datetime.datetime.now().strftime("%Y%m%d_%H%M") def resolve_relation(model, app_label=None, model_name=None): """ Turn a model class or model reference string and return a model tuple. app_label and model_name are used to resolve the scope of recursive and unscoped model relationship. """ if isinstance(model, str): if model == RECURSIVE_RELATIONSHIP_CONSTANT: if app_label is None or model_name is None: raise TypeError( "app_label and model_name must be provided to resolve " "recursive relationships." ) return app_label, model_name if "." in model: app_label, model_name = model.split(".", 1) return app_label, model_name.lower() if app_label is None: raise TypeError( "app_label must be provided to resolve unscoped model relationships." ) return app_label, model.lower() return model._meta.app_label, model._meta.model_name def field_references( model_tuple, field, reference_model_tuple, reference_field_name=None, reference_field=None, ): """ Return either False or a FieldReference if `field` references provided context. False positives can be returned if `reference_field_name` is provided without `reference_field` because of the introspection limitation it incurs. This should not be an issue when this function is used to determine whether or not an optimization can take place. """ remote_field = field.remote_field if not remote_field: return False references_to = None references_through = None if resolve_relation(remote_field.model, *model_tuple) == reference_model_tuple: to_fields = getattr(field, "to_fields", None) if ( reference_field_name is None or # Unspecified to_field(s). to_fields is None or # Reference to primary key. ( None in to_fields and (reference_field is None or reference_field.primary_key) ) or # Reference to field. reference_field_name in to_fields ): references_to = (remote_field, to_fields) through = getattr(remote_field, "through", None) if through and resolve_relation(through, *model_tuple) == reference_model_tuple: through_fields = remote_field.through_fields if ( reference_field_name is None or # Unspecified through_fields. through_fields is None or # Reference to field. reference_field_name in through_fields ): references_through = (remote_field, through_fields) if not (references_to or references_through): return False return FieldReference(references_to, references_through) def get_references(state, model_tuple, field_tuple=()): """ Generator of (model_state, name, field, reference) referencing provided context. If field_tuple is provided only references to this particular field of model_tuple will be generated. """ for state_model_tuple, model_state in state.models.items(): for name, field in model_state.fields.items(): reference = field_references( state_model_tuple, field, model_tuple, *field_tuple ) if reference: yield model_state, name, field, reference def field_is_referenced(state, model_tuple, field_tuple): """Return whether `field_tuple` is referenced by any state models.""" return next(get_references(state, model_tuple, field_tuple), None) is not None
RegexObject