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 | optuna__optuna | optuna/visualization/_contour.py | {
"start": 1500,
"end": 1656
} | class ____(NamedTuple):
sorted_params: list[str]
sub_plot_infos: list[list[_SubContourInfo]]
reverse_scale: bool
target_name: str
| _ContourInfo |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/model_query_cache.py | {
"start": 539,
"end": 703
} | class ____:
def foo(self, x):
return 0
def bar(self, x):
return 1
def decorated(f, *args, **kwargs):
pass
@decorated
| DoesNotExtendsBase |
python | facelessuser__pymdown-extensions | pymdownx/superfences.py | {
"start": 10241,
"end": 31676
} | class ____(Preprocessor):
"""
Preprocessor to find fenced code blocks.
Because this is done as a preprocessor, it might be too greedy.
We will stash the blocks code and restore if we mistakenly processed
text from an indented code block.
"""
CODE_WRAP = '<pre%s><code%s>%s</code></pre>'
def __init__(self, md):
"""Initialize."""
super().__init__(md)
self.tab_len = self.md.tab_length
self.checked_hl_settings = False
self.codehilite_conf = {}
def normalize_ws(self, text):
"""Normalize whitespace."""
return text.expandtabs(self.tab_len)
def rebuild_block(self, lines):
"""Dedent the fenced block lines."""
return '\n'.join([line[self.ws_virtual_len:] for line in lines])
def get_hl_settings(self):
"""Check for Highlight extension to get its configurations."""
if not self.checked_hl_settings:
self.checked_hl_settings = True
config = None
self.highlighter = None
for ext in self.md.registeredExtensions:
self.highlight_ext = ext
try:
config = ext.get_pymdownx_highlight_settings()
self.highlighter = ext.get_pymdownx_highlighter()
break
except AttributeError:
pass
self.attr_list = 'attr_list' in self.md.treeprocessors
css_class = self.config['css_class']
self.css_class = css_class if css_class else config['css_class']
self.relaxed_headers = self.config.get('relaxed_headers', False)
self.extend_pygments_lang = config.get('extend_pygments_lang', None)
self.guess_lang = config['guess_lang']
self.pygments_style = config['pygments_style']
self.use_pygments = config['use_pygments']
self.noclasses = config['noclasses']
self.linenums = config['linenums']
self.linenums_style = config.get('linenums_style', 'table')
self.linenums_class = config.get('linenums_class', 'linenums')
self.linenums_special = config.get('linenums_special', -1)
self.language_prefix = config.get('language_prefix', 'language-')
self.code_attr_on_pre = config.get('code_attr_on_pre', False)
self.auto_title = config.get('auto_title', False)
self.auto_title_map = config.get('auto_title_map', {})
self.line_spans = config.get('line_spans', '')
self.line_anchors = config.get('line_anchors', '')
self.anchor_linenums = config.get('anchor_linenums', False)
self.pygments_lang_class = config.get('pygments_lang_class', False)
self.stripnl = config.get('stripnl', True)
self.default_lang = config.get('default_lang', True)
def clear(self):
"""Reset the class variables."""
self.ws = None
self.ws_len = 0
self.ws_virtual_len = 0
self.fence = None
self.lang = None
self.quote_level = 0
self.code = []
self.empty_lines = 0
self.fence_end = None
self.options = {}
self.classes = []
self.id = ''
self.attrs = {}
self.formatter = None
def eval_fence(self, ws, content, start, end):
"""Evaluate a normal fence."""
if (ws + content).strip() == '':
# Empty line is okay
self.empty_lines += 1
self.code.append(ws + content)
elif len(ws) != self.ws_virtual_len and content != '':
# Not indented enough
self.clear()
elif self.fence_end.match(content) is not None and not content.startswith((' ', '\t')):
# End of fence
try:
self.process_nested_block(ws, content, start, end)
except SuperFencesException:
raise
except Exception:
self.clear()
else:
# Content line
self.empty_lines = 0
self.code.append(ws + content)
def eval_quoted(self, ws, content, quote_level, start, end):
"""Evaluate fence inside a blockquote."""
if quote_level > self.quote_level:
# Quote level exceeds the starting quote level
self.clear()
elif quote_level <= self.quote_level:
if content == '':
# Empty line is okay
self.code.append(ws + content)
self.empty_lines += 1
elif len(ws) < self.ws_len:
# Not indented enough
self.clear()
elif self.empty_lines and quote_level < self.quote_level:
# Quote levels don't match and we are signified
# the end of the block with an empty line
self.clear()
elif self.fence_end.match(content) is not None:
# End of fence
try:
self.process_nested_block(ws, content, start, end)
except SuperFencesException:
raise
except Exception:
self.clear()
else:
# Content line
self.empty_lines = 0
self.code.append(ws + content)
def process_nested_block(self, ws, content, start, end):
"""Process the contents of the nested block."""
self.last = ws + self.normalize_ws(content)
code = None
if self.formatter is not None:
self.line_count = end - start - 2
code = self.formatter(
src=self.rebuild_block(self.code),
language=self.lang,
md=self.md,
options=self.options,
classes=self.classes,
id_value=self.id,
attrs=self.attrs if self.attr_list else {}
)
if code is not None:
self._store(self.normalize_ws('\n'.join(self.code)) + '\n', code, start, end)
self.clear()
def normalize_hl_line(self, number):
"""
Normalize highlight line number.
Clamp outrages numbers. Numbers out of range will be only one increment out range.
This prevents people from create massive buffers of line numbers that exceed real
number of code lines.
"""
number = int(number)
if number < 1:
number = 0
elif number > self.line_count:
number = self.line_count + 1
return number
def parse_hl_lines(self, hl_lines):
"""Parse the lines to highlight."""
lines = []
if hl_lines:
for entry in hl_lines.split():
line_range = [self.normalize_hl_line(e) for e in entry.split('-')]
if len(line_range) > 1:
if line_range[0] <= line_range[1]:
lines.extend(list(range(line_range[0], line_range[1] + 1)))
elif 1 <= line_range[0] <= self.line_count:
lines.extend(line_range)
return lines
def parse_line_start(self, linestart):
"""Parse line start."""
return int(linestart) if linestart else -1
def parse_line_step(self, linestep):
"""Parse line start."""
step = int(linestep) if linestep else -1
return step if step > 1 else -1
def parse_line_special(self, linespecial):
"""Parse line start."""
return int(linespecial) if linespecial else -1
def parse_fence_line(self, line):
"""Parse fence line."""
ws_len = 0
ws_virtual_len = 0
ws = []
index = 0
for c in line:
if ws_virtual_len >= self.ws_virtual_len:
break
if c not in PREFIX_CHARS:
break
ws_len += 1
if c == '\t':
tab_size = self.tab_len - (index % self.tab_len)
ws_virtual_len += tab_size
ws.append(' ' * tab_size)
else:
tab_size = 1
ws_virtual_len += 1
ws.append(c)
index += tab_size
return ''.join(ws), line[ws_len:]
def parse_whitespace(self, line):
"""Parse the whitespace (blockquote syntax is counted as well)."""
self.ws_len = 0
self.ws_virtual_len = 0
ws = []
for c in line:
if c not in PREFIX_CHARS:
break
self.ws_len += 1
ws.append(c)
ws = self.normalize_ws(''.join(ws))
self.ws_virtual_len = len(ws)
return ws
def parse_options(self, m):
"""Get options."""
okay = False
if m.group('lang'):
self.lang = m.group('lang')
string = m.group('options')
self.options = {}
self.attrs = {}
self.formatter = None
values = {}
if string:
for m2 in RE_OPTIONS.finditer(string):
key = m2.group('key')
value = m2.group('value')
if value is None:
value = key
values[key] = value
# Run per language validator
for entry in reversed(self.extension.superfences):
if entry["test"](self.lang):
options = {}
attrs = {}
validator = entry.get("validator", functools.partial(_validator, validator=default_validator))
try:
okay = validator(self.lang, values, options, attrs, self.md)
except SuperFencesException:
raise
except Exception:
pass
if attrs:
okay = False
if okay:
self.formatter = entry.get("formatter")
self.options = options
break
if not okay and self.relaxed_headers:
return self.handle_unrecognized(m)
return okay
def handle_unrecognized(self, m):
"""Handle unrecognized code headers."""
okay = False
if not self.relaxed_headers:
return okay
if m.group('lang'):
self.lang = m.group('lang')
self.options = {}
self.attrs = {}
self.formatter = None
# Run per language validator
for entry in reversed(self.extension.superfences):
if entry["test"](self.lang):
options = {}
attrs = {}
validator = entry.get("validator", functools.partial(_validator, validator=default_validator))
try:
okay = validator(self.lang, {}, options, attrs, self.md)
except SuperFencesException:
raise
except Exception:
pass
if okay:
self.formatter = entry.get("formatter")
self.options = options
if self.attr_list:
self.attrs = attrs
break
if not okay:
self.lang = None # pragma: no cover
return True
def handle_attrs(self, m):
"""Handle attribute list."""
okay = False
attributes = get_attrs(m.group('attrs').replace('\t', ' ' * self.tab_len))
self.options = {}
self.attrs = {}
self.formatter = None
values = {}
for k, v in attributes:
if k == 'id':
self.id = v
elif k == '.':
self.classes.append(v)
else:
values[k] = v
if m.group('lang'):
self.lang = m.group('lang')
else:
self.lang = self.classes.pop(0) if self.classes else ''
# Run per language validator
for entry in reversed(self.extension.superfences):
if entry["test"](self.lang):
options = {}
attrs = {}
validator = entry.get("validator", functools.partial(_validator, validator=default_validator))
try:
okay = validator(self.lang, values, options, attrs, self.md)
except SuperFencesException:
raise
except Exception:
pass
if okay:
self.formatter = entry.get("formatter")
self.options = options
if self.attr_list:
self.attrs = attrs
break
if not okay and self.relaxed_headers:
return self.handle_unrecognized(m) # pragma: no cover
return okay
def search_nested(self, lines):
"""Search for nested fenced blocks."""
count = 0
for line in lines:
# Strip carriage returns if the lines end with them.
# This is necessary since we are handling preserved tabs
# Before whitespace normalization.
line = line.rstrip('\r')
if self.fence is None:
ws = self.parse_whitespace(line)
# Found the start of a fenced block.
m = RE_NESTED_FENCE_START.match(line, self.ws_len)
if m is not None:
# Parse options
if m.group('unrecognized'):
okay = self.handle_unrecognized(m)
elif m.group('attrs'):
okay = self.handle_attrs(m)
else:
okay = self.parse_options(m)
if okay:
# Valid fence options, handle fence
start = count
self.first = ws + self.normalize_ws(m.group(0))
self.ws = ws
self.quote_level = self.ws.count(">")
self.empty_lines = 0
self.fence = m.group('fence')
self.fence_end = re.compile(NESTED_FENCE_END % self.fence)
else:
# Option parsing failed, abandon fence
self.clear()
else:
# Evaluate lines
# - Determine if it is the ending line or content line
# - If is a content line, make sure it is all indented
# with the opening and closing lines (lines with just
# whitespace will be stripped so those don't matter).
# - When content lines are inside blockquotes, make sure
# the nested block quote levels make sense according to
# blockquote rules.
ws, content = self.parse_fence_line(line)
end = count + 1
quote_level = ws.count(">")
if self.quote_level:
# Handle blockquotes
self.eval_quoted(ws, content, quote_level, start, end)
elif quote_level == 0:
# Handle all other cases
self.eval_fence(ws, content, start, end)
else:
# Looks like we got a blockquote line
# when not in a blockquote.
self.clear()
count += 1
return self.reassemble(lines)
def reassemble(self, lines):
"""Reassemble text."""
# Now that we are done iterating the lines,
# let's replace the original content with the
# fenced blocks.
while len(self.stack):
fenced, start, end = self.stack.pop()
lines = lines[:start] + [fenced] + lines[end:]
return lines
def highlight(self, src="", language="", options=None, md=None, **kwargs):
"""
Syntax highlight the code block.
If configuration is not empty, then the CodeHilite extension
is enabled, so we call into it to highlight the code.
"""
classes = kwargs['classes']
id_value = kwargs['id_value']
attrs = kwargs['attrs']
if classes is None: # pragma: no cover
classes = []
# Default format options
linestep = None
linestart = None
linespecial = None
hl_lines = None
title = None
if self.use_pygments:
if 'hl_lines' in options:
m = RE_HL_LINES.match(options['hl_lines'])
hl_lines = m.group('hl_lines')
del options['hl_lines']
if 'linenums' in options:
m = RE_LINENUMS.match(options['linenums'])
linestart = m.group('linestart')
linestep = m.group('linestep')
linespecial = m.group('linespecial')
del options['linenums']
if 'title' in options:
title = options['title']
del options['title']
linestep = self.parse_line_step(linestep)
linestart = self.parse_line_start(linestart)
linespecial = self.parse_line_special(linespecial)
hl_lines = self.parse_hl_lines(hl_lines)
self.highlight_ext.pygments_code_block += 1
el = self.highlighter(
guess_lang=self.guess_lang,
pygments_style=self.pygments_style,
use_pygments=self.use_pygments,
noclasses=self.noclasses,
linenums=self.linenums,
linenums_style=self.linenums_style,
linenums_special=self.linenums_special,
linenums_class=self.linenums_class,
extend_pygments_lang=self.extend_pygments_lang,
language_prefix=self.language_prefix,
code_attr_on_pre=self.code_attr_on_pre,
auto_title=self.auto_title,
auto_title_map=self.auto_title_map,
line_spans=self.line_spans,
line_anchors=self.line_anchors,
anchor_linenums=self.anchor_linenums,
pygments_lang_class=self.pygments_lang_class,
stripnl=self.stripnl,
default_lang=self.default_lang
).highlight(
src,
language,
self.css_class,
hl_lines=hl_lines,
linestart=linestart,
linestep=linestep,
linespecial=linespecial,
classes=classes,
id_value=id_value,
attrs=attrs,
title=title,
code_block_count=self.highlight_ext.pygments_code_block
)
return el
def _store(self, source, code, start, end):
"""
Store the fenced blocks in the stack to be replaced when done iterating.
Store the original text in case we need to restore if we are too greedy.
"""
# Save the fenced blocks to add once we are done iterating the lines
placeholder = self.md.htmlStash.store(code)
self.stack.append(('{}{}'.format(self.ws, placeholder), start, end))
if not self.disabled_indented:
# If an indented block consumes this placeholder,
# we can restore the original source
self.extension.stash.store(
placeholder[1:-1],
"{}\n{}{}".format(self.first, self.normalize_ws(source), self.last),
self.ws_virtual_len
)
def reindent(self, text, pos, level):
"""Reindent the code to where it is supposed to be."""
indented = []
for line in text.split('\n'):
index = pos - level
indented.append(line[index:])
return indented
def restore_raw_text(self, lines):
"""Revert a prematurely converted fenced block."""
new_lines = []
for line in lines:
m = FENCED_BLOCK_RE.match(line)
if m:
key = m.group(2)
indent_level = len(m.group(1))
original = None
original, pos = self.extension.stash.get(key, (None, None))
if original is not None:
code = self.reindent(original, pos, indent_level)
new_lines.extend(code)
self.extension.stash.remove(key)
if original is None: # pragma: no cover
# Too much work to test this. This is just a fall back in case
# we find a placeholder, and we went to revert it and it wasn't in our stash.
# Most likely this would be caused by someone else. We just want to put it
# back in the block if we can't revert it. Maybe we can do a more directed
# unit test in the future.
new_lines.append(line)
else:
new_lines.append(line)
return new_lines
def run(self, lines):
"""Search for fenced blocks."""
self.get_hl_settings()
self.clear()
self.stack = []
self.disabled_indented = self.config.get("disable_indented_code_blocks", False)
self.preserve_tabs = self.config.get("preserve_tabs", False)
if self.preserve_tabs:
lines = self.restore_raw_text(lines)
return self.search_nested(lines)
| SuperFencesBlockPreprocessor |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/mariadbconnector.py | {
"start": 3778,
"end": 3842
} | class ____(MySQLCompiler):
pass
| MySQLCompiler_mariadbconnector |
python | PyCQA__pylint | tests/functional/r/regression/regression_properties_in_class_context.py | {
"start": 545,
"end": 654
} | class ____(metaclass=Meta2):
@property
def a_method(self):
return "actually a property"
| Parent2 |
python | google__pytype | pytype/pyi/parser.py | {
"start": 3444,
"end": 4277
} | class ____(visitor.BaseVisitor):
"""Converts ast module constants to our own representation."""
def __init__(self, filename):
super().__init__(filename=filename, visit_decorators=True)
def visit_Constant(self, node):
if node.value is Ellipsis:
return definitions.Definitions.ELLIPSIS
return types.Pyval.from_const(node)
def visit_UnaryOp(self, node):
if isinstance(node.op, astlib.USub):
if isinstance(node.operand, types.Pyval):
return node.operand.negated()
raise ParseError(f"Unexpected unary operator: {node.op}")
def visit_Assign(self, node):
if node.type_comment:
# Convert the type comment from a raw string to a string constant.
node.type_comment = types.Pyval(
"str", node.type_comment, *types.node_position(node)
)
| _ConvertConstantsVisitor |
python | numpy__numpy | numpy/random/tests/test_random.py | {
"start": 5767,
"end": 11866
} | class ____:
# valid integer/boolean types
itype = [np.bool, np.int8, np.uint8, np.int16, np.uint16,
np.int32, np.uint32, np.int64, np.uint64]
def test_unsupported_type(self):
rng = random.RandomState()
assert_raises(TypeError, rng.randint, 1, dtype=float)
def test_bounds_checking(self):
rng = random.RandomState()
for dt in self.itype:
lbnd = 0 if dt is np.bool else np.iinfo(dt).min
ubnd = 2 if dt is np.bool else np.iinfo(dt).max + 1
assert_raises(ValueError, rng.randint, lbnd - 1, ubnd, dtype=dt)
assert_raises(ValueError, rng.randint, lbnd, ubnd + 1, dtype=dt)
assert_raises(ValueError, rng.randint, ubnd, lbnd, dtype=dt)
assert_raises(ValueError, rng.randint, 1, 0, dtype=dt)
def test_rng_zero_and_extremes(self):
rng = random.RandomState()
for dt in self.itype:
lbnd = 0 if dt is np.bool else np.iinfo(dt).min
ubnd = 2 if dt is np.bool else np.iinfo(dt).max + 1
tgt = ubnd - 1
assert_equal(rng.randint(tgt, tgt + 1, size=1000, dtype=dt), tgt)
tgt = lbnd
assert_equal(rng.randint(tgt, tgt + 1, size=1000, dtype=dt), tgt)
tgt = (lbnd + ubnd) // 2
assert_equal(rng.randint(tgt, tgt + 1, size=1000, dtype=dt), tgt)
def test_full_range(self):
# Test for ticket #1690
rng = random.RandomState()
for dt in self.itype:
lbnd = 0 if dt is np.bool else np.iinfo(dt).min
ubnd = 2 if dt is np.bool else np.iinfo(dt).max + 1
try:
rng.randint(lbnd, ubnd, dtype=dt)
except Exception as e:
raise AssertionError("No error should have been raised, "
"but one was with the following "
"message:\n\n%s" % str(e))
def test_in_bounds_fuzz(self):
# Don't use fixed seed
rng = random.RandomState()
for dt in self.itype[1:]:
for ubnd in [4, 8, 16]:
vals = rng.randint(2, ubnd, size=2**16, dtype=dt)
assert_(vals.max() < ubnd)
assert_(vals.min() >= 2)
vals = rng.randint(0, 2, size=2**16, dtype=np.bool)
assert_(vals.max() < 2)
assert_(vals.min() >= 0)
def test_repeatability(self):
import hashlib
# We use a sha256 hash of generated sequences of 1000 samples
# in the range [0, 6) for all but bool, where the range
# is [0, 2). Hashes are for little endian numbers.
tgt = {'bool': '509aea74d792fb931784c4b0135392c65aec64beee12b0cc167548a2c3d31e71', # noqa: E501
'int16': '7b07f1a920e46f6d0fe02314155a2330bcfd7635e708da50e536c5ebb631a7d4', # noqa: E501
'int32': 'e577bfed6c935de944424667e3da285012e741892dcb7051a8f1ce68ab05c92f', # noqa: E501
'int64': '0fbead0b06759df2cfb55e43148822d4a1ff953c7eb19a5b08445a63bb64fa9e', # noqa: E501
'int8': '001aac3a5acb935a9b186cbe14a1ca064b8bb2dd0b045d48abeacf74d0203404', # noqa: E501
'uint16': '7b07f1a920e46f6d0fe02314155a2330bcfd7635e708da50e536c5ebb631a7d4', # noqa: E501
'uint32': 'e577bfed6c935de944424667e3da285012e741892dcb7051a8f1ce68ab05c92f', # noqa: E501
'uint64': '0fbead0b06759df2cfb55e43148822d4a1ff953c7eb19a5b08445a63bb64fa9e', # noqa: E501
'uint8': '001aac3a5acb935a9b186cbe14a1ca064b8bb2dd0b045d48abeacf74d0203404'} # noqa: E501
for dt in self.itype[1:]:
rng = random.RandomState(1234)
# view as little endian for hash
if sys.byteorder == 'little':
val = rng.randint(0, 6, size=1000, dtype=dt)
else:
val = rng.randint(0, 6, size=1000, dtype=dt).byteswap()
res = hashlib.sha256(val.view(np.int8)).hexdigest()
assert_(tgt[np.dtype(dt).name] == res)
# bools do not depend on endianness
rng = random.RandomState(1234)
val = rng.randint(0, 2, size=1000, dtype=bool).view(np.int8)
res = hashlib.sha256(val).hexdigest()
assert_(tgt[np.dtype(bool).name] == res)
def test_int64_uint64_corner_case(self):
# When stored in Numpy arrays, `lbnd` is casted
# as np.int64, and `ubnd` is casted as np.uint64.
# Checking whether `lbnd` >= `ubnd` used to be
# done solely via direct comparison, which is incorrect
# because when Numpy tries to compare both numbers,
# it casts both to np.float64 because there is
# no integer superset of np.int64 and np.uint64. However,
# `ubnd` is too large to be represented in np.float64,
# causing it be round down to np.iinfo(np.int64).max,
# leading to a ValueError because `lbnd` now equals
# the new `ubnd`.
dt = np.int64
tgt = np.iinfo(np.int64).max
lbnd = np.int64(np.iinfo(np.int64).max)
ubnd = np.uint64(np.iinfo(np.int64).max + 1)
# None of these function calls should
# generate a ValueError now.
actual = np.random.randint(lbnd, ubnd, dtype=dt)
assert_equal(actual, tgt)
def test_respect_dtype_singleton(self):
# See gh-7203
rng = random.RandomState()
for dt in self.itype:
lbnd = 0 if dt is np.bool else np.iinfo(dt).min
ubnd = 2 if dt is np.bool else np.iinfo(dt).max + 1
sample = rng.randint(lbnd, ubnd, dtype=dt)
assert_equal(sample.dtype, np.dtype(dt))
for dt in (bool, int):
# The legacy rng uses "long" as the default integer:
lbnd = 0 if dt is bool else np.iinfo("long").min
ubnd = 2 if dt is bool else np.iinfo("long").max + 1
# gh-7284: Ensure that we get Python data types
sample = rng.randint(lbnd, ubnd, dtype=dt)
assert_(not hasattr(sample, 'dtype'))
assert_equal(type(sample), dt)
| TestRandint |
python | kamyu104__LeetCode-Solutions | Python/remove-nodes-from-linked-list.py | {
"start": 29,
"end": 123
} | class ____(object):
def __init__(self, val=0, next=None):
pass
# mono stack
| ListNode |
python | pytorch__pytorch | test/dynamo/test_generator.py | {
"start": 4230,
"end": 24948
} | class ____(torch.nn.Module):
def forward(self, L_stack0_0_: "f32[2]", L_stack0_1_: "f32[2]"):
l_stack0_0_ = L_stack0_0_
l_stack0_1_ = L_stack0_1_
add: "f32[2]" = l_stack0_0_ + l_stack0_1_; l_stack0_0_ = l_stack0_1_ = None
return (add,)
""",
)
def test_reconstruct_generator_with_local_var_mutation(self):
def whoo(t):
x = 0
yield t.sin() + x
x += 1
yield t.cos() + x
x += 1
yield t.tan() + x
@torch.compile(backend="eager", fullgraph=False)
def fn(t):
gen = whoo(t)
next(gen)
return t.sin(), gen
t = torch.randn(2)
y, g = fn(t)
self.assertEqual(y, t.sin())
self.assertEqual(list(g), [t.cos() + 1, t.tan() + 2])
def test_reconstruct_generator_with_dict_mutation(self):
counters.clear()
def whoo(t, d):
d[2] = t
yield t.sin()
yield t.cos()
d[3] = t + 1
yield t.tan()
@torch.compile(backend="eager", fullgraph=False)
def fn(t, d):
gen = whoo(t, d)
next(gen)
return t.sin(), whoo(t, d)
t = torch.randn(2)
d = {1: t}
fn(t, d)
self.assertEqual(len(counters["unimplemented"]), 1)
self.assertEqual(
dict(counters["unimplemented"]),
{
"Cannot reconstruct a generator with variable mutations. "
"Dynamo needs to fully exhaust the generator, which may cause "
"unintended variable modifications.": 1
},
)
def test_reconstruct_generator_with_dict_mutation_before(self):
def whoo(t, d):
d[2] = t
yield t.sin()
yield t.cos()
yield t.tan()
@torch.compile(backend="eager", fullgraph=False)
def fn(t, d):
gen = whoo(t, d)
next(gen)
return t.sin(), gen
t = torch.randn(2)
d = {1: t}
y, g = fn(t, d)
self.assertEqual(y, t.sin())
self.assertEqual(list(g), [t.cos(), t.tan()])
self.assertEqual(d, {1: t, 2: t})
def test_reconstruct_generator_with_object_mutation(self):
class Counter:
def __init__(self):
self.x = 0
def incr(self):
self.x += 1
def whoo(t, c):
c.incr()
yield t.sin()
yield t.cos()
c.incr()
yield t.tan()
@torch.compile(backend="eager", fullgraph=False)
def fn(t, c):
gen = whoo(t, c)
next(gen)
return t.sin(), gen
t = torch.randn(2)
c = Counter()
fn(t, c)
self.assertEqual(len(counters["unimplemented"]), 1)
self.assertEqual(
dict(counters["unimplemented"]),
{
"Cannot reconstruct a generator with variable mutations. "
"Dynamo needs to fully exhaust the generator, which may cause "
"unintended variable modifications.": 1
},
)
def test_reconstruct_generator_with_object_mutation_before(self):
class Counter:
def __init__(self):
self.x = 0
def incr(self):
self.x += 1
def whoo(t, c):
c.incr()
yield t.sin()
yield t.cos()
yield t.tan()
@torch.compile(backend="eager", fullgraph=False)
def fn(t, c):
gen = whoo(t, c)
next(gen)
# We should be able to reconstruct the generator as there's no object
# mutation after the first yield
return t.sin(), gen
t = torch.randn(2)
c = Counter()
y, g = fn(t, c)
self.assertEqual(c.x, 1)
self.assertEqual(y, t.sin())
self.assertEqual(list(g), [t.cos(), t.tan()])
def test_graph_break_and_reconstruct_generator(self):
def whoo(t):
yield t.sin()
yield t.cos()
yield t.tan()
def g(t):
torch._dynamo.graph_break()
@torch.compile(backend="eager", fullgraph=False)
def fn(t):
gen = whoo(t)
next(gen)
g(t)
return t.sin(), list(gen)
t = torch.randn(2)
y, gen = fn(t)
self.assertEqual(y, t.sin())
self.assertEqual(list(gen), [t.cos(), t.tan()])
def test_graph_break_in_generator_while_reconstructing(self):
counters.clear()
def whoo():
yield 1
torch._dynamo.graph_break()
yield 2
eager = EagerAndRecordGraphs()
@torch.compile(backend=eager, fullgraph=False)
def fn(t):
gen = whoo()
s = next(gen)
torch._dynamo.graph_break()
s += next(gen)
return t + s
t = torch.randn(2)
y = fn(t)
self.assertEqual(y, t + 3)
self.assertEqual(len(eager.graphs), 0)
def test_generator_as_argument(self):
# The inline tracer needs to be kept in sync if an already advanced generator
# is given to a compiled function.
def whoo():
yield 1
yield 2
yield 3
eager = EagerAndRecordGraphs()
@torch.compile(backend=eager, fullgraph=True)
def fn(t, ctx):
return t + next(ctx)
t = torch.randn(2)
ctx = whoo()
next(ctx)
with self.assertRaisesRegex(
Unsupported, "Detected a method call to a user-defined generator object."
):
fn(t, ctx)
def test_generator_as_argument_2(self):
def whoo(x):
yield x.sin()
yield x.cos()
eager = EagerAndRecordGraphs()
@torch.compile(backend=eager, fullgraph=True)
def fn(t, ctx):
return t + next(ctx)
t = torch.randn(2)
ctx = whoo(t)
next(ctx)
with self.assertRaisesRegex(
Unsupported, "Detected a method call to a user-defined generator object."
):
fn(t, ctx)
def test_generator_as_argument_3(self):
# The inline tracer needs to be kept in sync if an already advanced generator
# is given to a compiled function.
def whoo():
yield 1
yield 2
yield 3
eager = EagerAndRecordGraphs()
@torch.compile(backend=eager, fullgraph=True)
def fn(t, ctx):
return t + next(ctx)
t = torch.randn(2)
ctx = whoo()
with self.assertRaisesRegex(
Unsupported, "Detected a method call to a user-defined generator object."
):
fn(t, ctx)
def test_generator_as_argument_4(self):
def whoo(x):
yield x.sin()
yield x.cos()
eager = EagerAndRecordGraphs()
@torch.compile(backend=eager, fullgraph=True)
def fn(t, ctx):
return t + next(ctx)
t = torch.randn(2)
ctx = whoo(t)
with self.assertRaisesRegex(
Unsupported,
"Detected a method call to a user-defined generator object.",
):
fn(t, ctx)
def test_islice_chain(self):
eager = EagerAndRecordGraphs()
@torch.compile(backend=eager, fullgraph=True)
def fn(t):
tmp1 = [t + 1, t + 2]
tmp2 = [t + 3, t + 4]
return list(itertools.chain(tmp1, tmp2))
t = torch.tensor([1.0])
y = fn(t)
self.assertEqual(y, [t + 1, t + 2, t + 3, t + 4])
def test_zip_generator(self):
def whoo(t):
yield t + 1
yield t + 2
yield t + 3
def fn(t):
return zip(range(3), whoo(t)), t.sin()
t = torch.randn(2)
z, _ = self._compile_check(fn, args=(t,))
self.assertEqual(list(z), list(zip(range(3), whoo(t))))
@unittest.expectedFailure
def test_zip_generator_2(self):
def bar(t, i):
return t + i
def whoo(t):
yield bar(t, 1)
yield bar(t, 2)
yield bar(t, 3)
def fn(t):
return zip(range(3), whoo(t))
t = torch.randn(3)
y = self._compile_check(fn, args=(t,), fullgraph=False)
expected = list(zip(range(3), whoo(t)))
self.assertEqual(expected, list(y))
def test_zip_subgenerator(self):
def subgen(t):
yield t + 1
yield t + 2
def whoo(t):
yield from subgen(t)
yield t + 3
def fn(t):
return zip(range(3), whoo(t)), t.sin()
t = torch.randn(2)
z, _ = self._compile_check(fn, args=(t,))
self.assertEqual(list(z), list(zip(range(3), whoo(t))))
def test_list_zip_generator(self):
def whoo(t):
yield t + 1
yield t + 2
yield t + 3
@torch.compile(backend="eager", fullgraph=True)
def fn(t):
return list(zip(range(3), whoo(t)))
t = torch.randn(3)
y = fn(t)
expected = list(zip(range(3), whoo(t)))
self.assertEqual(expected, y)
def test_zip_infinite_generator(self):
def whoo(t):
i = 0
while True:
yield t + i
i += 1
@torch.compile(backend="eager", fullgraph=True)
def fn(t):
return list(zip(range(3), whoo(t)))
t = torch.randn(3)
y = fn(t)
expected = list(zip(range(3), whoo(t)))
self.assertEqual(expected, y)
@parametrize("container", [list, tuple, dict, OrderedDict])
def test_dict_tuple_list_generator(self, container):
def whoo(t):
yield 1, t + 1
yield 2, t + 2
yield 3, t + 3
def fn(t):
gen = whoo(t)
return container(gen)
t = torch.randn(2)
expected = fn(t)
got = torch.compile(backend="eager", fullgraph=True)(fn)(t)
self.assertEqual(expected, got)
def test_return_generator(self):
def whoo(t):
yield t + 1
yield t + 2
yield t + 3
@torch.compile(backend="eager", fullgraph=True)
def fn(t):
gen = whoo(t)
return gen
t = torch.tensor([1.0])
gen = fn(t)
self.assertEqual(list(gen), [t + 1, t + 2, t + 3])
def test_return_tuple_generator(self):
def whoo(t):
yield t.sin()
yield t.cos()
@torch.compile(backend="eager", fullgraph=True)
def fn(t):
g1, g2 = whoo(t), whoo(t + 1)
return (g1, g2), t.sin()
t = torch.randn(2)
(g1, g2), _ = fn(t)
self.assertEqual(list(g1), [t.sin(), t.cos()])
self.assertEqual(list(g2), [(t + 1).sin(), (t + 1).cos()])
def test_return_advanced_generator(self):
def whoo(t):
yield t + 1
yield t + 2
yield t + 3
@torch.compile(backend="eager", fullgraph=True)
def fn(t):
gen = whoo(t)
next(gen)
return gen
t = torch.tensor([1.0])
gen = fn(t)
self.assertEqual(list(gen), [t + 2, t + 3])
def test_return_exhaust_generator(self):
def whoo(t):
yield t + 1
@torch.compile(backend="eager", fullgraph=True)
def fn(t):
gen = whoo(t)
next(gen)
return gen
t = torch.tensor([1.0])
gen = fn(t)
with self.assertRaises(StopIteration):
next(gen)
@unittest.expectedFailure
def test_reconstruct_generator_tensor_mutation(self):
def whoo(t):
yield t.sin_()
yield t.cos_()
def fn(t):
gen = whoo(t)
return gen
with self.assertRaisesRegex(
Unsupported,
"Cannot reconstruct a generator with variable mutations",
):
self._compile_check(fn)
def test_subgenerator(self):
def subgen(t):
yield t + 1
yield t + 2
def main_gen(t):
yield from subgen(t)
yield t + 3
@torch.compile(backend="eager", fullgraph=True)
def fn(t):
gen = main_gen(t)
return list(gen)
t = torch.randn(2)
y = fn(t)
self.assertEqual(y, [t + 1, t + 2, t + 3])
def test_return_subgenerator(self):
def subgen(t):
yield t + 1
yield t + 2
def main_gen(t):
yield from subgen(t)
yield t + 3
@torch.compile(backend="eager", fullgraph=True)
def fn(t):
gen = main_gen(t)
next(gen)
return gen
t = torch.randn(2)
gen = fn(t)
self.assertEqual(list(gen), [t + 2, t + 3])
def test_dynamo_disable_generator(self):
@torch._dynamo.disable
def main_gen(t):
yield t + 1
yield t + 2
yield t + 3
@torch.compile(backend="eager", fullgraph=False)
def fn(t):
gen = main_gen(t)
return list(gen)
t = torch.randn(2)
y = fn(t)
self.assertEqual(y, [t + 1, t + 2, t + 3])
def test_dynamo_disable_sub_generator(self):
@torch._dynamo.disable
def subgen(t):
yield t + 2
yield t + 3
def main_gen(t):
yield t + 1
yield from subgen(t)
@torch.compile(backend="eager", fullgraph=False)
def fn(t):
gen = main_gen(t)
return list(gen)
t = torch.randn(2)
y = fn(t)
self.assertEqual(y, [t + 1, t + 2, t + 3])
def test_graph_break_outside_generator(self):
def whoo(t):
yield t + 1
yield t + 2
@torch.compile(backend="eager", fullgraph=False)
def fn(t):
gen = whoo(t)
x = next(gen)
torch._dynamo.graph_break()
y = next(gen)
return x + y
t = torch.randn(2)
y = fn(t)
self.assertEqual(y, (t + 1) + (t + 2))
def test_graph_break_before_calling_generator(self):
def whoo(t):
for perm in itertools.product(itertools.permutations((0, 1, 2)), repeat=1):
yield sum(perm[0])
def fn(t):
s = 0
for b, p in itertools.product(whoo(t), itertools.permutations((4, 5))):
s += b
return s
t = torch.randn(2)
expected = fn(t)
got = torch.compile(backend="eager", fullgraph=False)(fn)(t)
self.assertEqual(expected, got)
def test_generator_with_side_effects(self):
counters.clear()
i = 0
def whoo(t):
nonlocal i
for j in range(5):
i += 1
yield t + j
@torch.compile(backend="eager", fullgraph=True)
def fn(t):
return whoo(t), t.sin()
t = torch.randn(2)
fn(t)
self.assertEqual(len(counters["unimplemented"]), 1)
self.assertEqual(
dict(counters["unimplemented"]),
{
"Cannot reconstruct a generator with variable mutations. "
"Dynamo needs to fully exhaust the generator, which may cause "
"unintended variable modifications.": 1
},
)
def test_subgenerator_with_side_effects(self):
i = 0
def subgen(t):
nonlocal i
i += 1
yield t
i += 1
yield t + 1
def whoo(t):
nonlocal i
yield from subgen(t)
i += 1
yield t + 2
i += 1
yield t + 3
i += 1
yield t + 4
@torch.compile(backend="eager", fullgraph=True)
def fn(t):
return whoo(t), t.sin()
t = torch.randn(2)
gen, y = fn(t)
self.assertEqual(y, t.sin())
self.assertEqual(len(list(gen)), 5)
self.assertTrue(
"Cannot reconstruct a generator with variable mutations. "
"Dynamo needs to fully exhaust the generator, which may cause "
"unintended variable modifications." in dict(counters["unimplemented"])
)
def test_generator_with_side_effects_graph_break(self):
i = 0
def whoo(t):
nonlocal i
for j in range(5):
i += 1
yield t + j
@torch.compile(backend="eager", fullgraph=False)
def fn(t):
gen = whoo(t)
torch._dynamo.graph_break()
next(gen)
return gen, t.sin()
t = torch.randn(2)
gen, y = fn(t)
self.assertEqual(y, t.sin())
self.assertEqual(len(list(gen)), 4)
self.assertTrue(
"Cannot reconstruct a generator with variable mutations. "
"Dynamo needs to fully exhaust the generator, which may cause "
"unintended variable modifications." in dict(counters["unimplemented"])
)
def test_generator_with_side_effects_graph_break_2(self):
i = 0
def whoo(t):
nonlocal i
for j in range(5):
i += 1
yield t + j
torch._dynamo.graph_break()
eager = EagerAndRecordGraphs()
@torch.compile(backend=eager, fullgraph=False)
def fn(t):
gen = whoo(t)
return list(zip(range(3), gen))
t = torch.randn(2)
fn(t)
self.assertEqual(len(eager.graphs), 0)
@unittest.skipIf(sys.version_info < (3, 12), "Test CLEANUP_THROW")
@unittest.expectedFailure
def test_cleanup_throw(self):
def nested_generator():
try:
yield 1
yield 2
except StopIteration:
return 123 # noqa: B901
def outer_generator():
yield from nested_generator()
yield 3
@torch.compile(backend="eager", fullgraph=True)
def fn(t):
gen = outer_generator()
next(gen) # Start the outer generator and enter the nested generato
i = 0
try:
# Force an exception while the generator is running
i = gen.throw(StopIteration("stop"))
except RuntimeError:
pass
return (i, t.sin())
t = torch.randn(2)
i, y = self._compile_check(fn, args=(t,))
self.assertEqual(i, 3)
self.assertEqual(y, t.sin())
def test_iter(self):
def whoo():
i = 0
while True:
yield i
i += 1
@torch.compile(backend="eager", fullgraph=True)
def fn(t):
s = 0
for i in whoo():
if i > 5:
break
s += i
return t + s
t = torch.randn(2)
y = fn(t)
self.assertEqual(y, t + sum(range(6)))
def test_list_extend(self):
def f(x):
y = [1]
y.extend(y[-1] + z for z in range(3))
return x + 1, y
self.assertEqual(
f(torch.ones(3)),
torch.compile(f, backend="eager", fullgraph=True)(torch.ones(3)),
)
def test_deque_extendleft(self):
import collections
def f(x):
y = collections.deque([1])
y.extendleft(y[0] + z for z in range(3))
return x + 1, y
self.assertEqual(
f(torch.ones(3)),
torch.compile(f, backend="eager", fullgraph=True)(torch.ones(3)),
)
@make_dynamo_test
def test_generator___contains__(self):
def whoo():
yield 1
yield 2
g = whoo()
self.assertTrue(1 in g)
self.assertTrue(2 in g)
self.assertRaises(StopIteration, next, g)
self.assertFalse(3 in whoo())
@make_dynamo_test
def test_generator___contains___side_effects(self):
n = 0
def whoo():
nonlocal n
n = 1
yield 1
n = 2
yield 2
g = whoo()
self.assertTrue(1 in g)
self.assertEqual(n, 1)
self.assertTrue(2 in g)
self.assertEqual(n, 2)
self.assertRaises(StopIteration, next, g)
self.assertFalse(3 in whoo())
| GraphModule |
python | jazzband__django-waffle | waffle/tests/test_testutils.py | {
"start": 11793,
"end": 12115
} | class ____(OverrideFlagOnClassTestCase):
"""
Extend ``OverrideFlagOnClassTestCase``
and make sure ``override_flag`` change still works.
"""
def test_child_undecorated_method_is_set_properly_for_flag(self):
self.assertFalse(waffle.flag_is_active(req(), 'foo'))
| InheritanceOverrideFlagOnClassTests |
python | walkccc__LeetCode | solutions/1924. Erect the Fence II/1924.py | {
"start": 167,
"end": 3140
} | class ____:
def outerTrees(self, trees: list[list[int]]) -> list[float]:
points = [Point(x, y) for x, y in trees]
disk = self._welzl(points, 0, [])
return [disk.center.x, disk.center.y, disk.radius]
def _welzl(
self,
points: list[Point],
i: int,
planePoints: list[Point],
) -> Disk:
"""Returns the smallest disk that encloses points[i..n).
https://en.wikipedia.org/wiki/Smallest-disk_problem#Welzl's_algorithm
"""
if i == len(points) or len(planePoints) == 3:
return self._trivial(planePoints)
disk = self._welzl(points, i + 1, planePoints)
if self._inside(disk, points[i]):
return disk
return self._welzl(points, i + 1, planePoints + [points[i]])
def _trivial(self, planePoints: list[Point]) -> Disk:
"""Returns the smallest disk that encloses `planePoints`."""
if len(planePoints) == 0:
return Disk(Point(0, 0), 0)
if len(planePoints) == 1:
return Disk(Point(planePoints[0].x, planePoints[0].y), 0)
if len(planePoints) == 2:
return self._getDisk(planePoints[0], planePoints[1])
disk01 = self._getDisk(planePoints[0], planePoints[1])
if self._inside(disk01, planePoints[2]):
return disk01
disk02 = self._getDisk(planePoints[0], planePoints[2])
if self._inside(disk02, planePoints[1]):
return disk02
disk12 = self._getDisk(planePoints[1], planePoints[2])
if self._inside(disk12, planePoints[0]):
return disk12
return self._getDiskFromThree(
planePoints[0],
planePoints[1],
planePoints[2])
def _getDisk(self, A: Point, B: Point) -> Disk:
"""Returns the smallest disk that encloses the points A and B."""
x = (A.x + B.x) / 2
y = (A.y + B.y) / 2
return Disk(Point(x, y), self._distance(A, B) / 2)
def _getDiskFromThree(self, A: Point, B: Point, C: Point) -> Disk:
"""Returns the smallest disk that encloses the points A, B, and C."""
# Calculate midpoints.
mAB = Point((A.x + B.x) / 2, (A.y + B.y) / 2)
mBC = Point((B.x + C.x) / 2, (B.y + C.y) / 2)
# Calculate the slopes and the perpendicular slopes.
slopeAB = math.inf if B.x == A.x else (B.y - A.y) / (B.x - A.x)
slopeBC = math.inf if C.x == B.x else (C.y - B.y) / (C.x - B.x)
perpSlopeAB = math.inf if slopeAB == 0 else -1 / slopeAB
perpSlopeBC = math.inf if slopeBC == 0 else -1 / slopeBC
# Calculate the center.
x = (perpSlopeBC * mBC.x - perpSlopeAB * mAB.x +
mAB.y - mBC.y) / (perpSlopeBC - perpSlopeAB)
y = perpSlopeAB * (x - mAB.x) + mAB.y
center = Point(x, y)
return Disk(center, self._distance(center, A))
def _inside(self, disk: Disk, point: Point) -> bool:
"""Returns True if the point is inside the disk."""
return disk.radius > 0 and self._distance(disk.center, point) <= disk.radius
def _distance(self, A: Point, B: Point) -> float:
dx = A.x - B.x
dy = A.y - B.y
return math.sqrt(dx**2 + dy**2)
| Solution |
python | ansible__ansible | test/units/module_utils/facts/test_facts.py | {
"start": 6227,
"end": 6404
} | class ____(BaseTestFactsPlatform):
platform_id = 'SunOS'
fact_class = network.sunos.SunOSNetwork
collector_class = network.sunos.SunOSNetworkCollector
| TestSunOSNetwork |
python | bokeh__bokeh | src/bokeh/models/tools.py | {
"start": 27179,
"end": 28883
} | class ____(ActionTool):
''' Execute a custom action, e.g. ``CustomJS`` callback when a toolbar
icon is activated.
Example:
.. code-block:: python
tool = CustomAction(icon="icon.png",
callback=CustomJS(code='alert("foo")'))
plot.add_tools(tool)
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
active = Bool(default=False, help="""
If ``True``, the tool is currently engaged for its activity.
""")
disabled = Bool(default=False, help="""
If ``True``, users can't interact with the tool in any way.
""")
description = Override(default="Perform a Custom Action")
callback = Nullable(Instance(Callback), help="""
A Bokeh callback to execute when the custom action icon is activated.
This callback can return a boolean value to indicate the state of
the tool. This is only applicable if ``active_callback`` is ``None``.
""")
active_callback = Nullable(Either(Instance(Callback), Auto), default=None, help="""
A callback that allows to determine the state of the tool.
This callback is used to establish the initial and any subsequent state
of the tool. it must return a boolean value. A value of any other type
will be disregarded.
If ``"auto"`` value is used, then any click of the button will toggle
state. The initial state can be provided using ``active`` property.
If ``None`` value is used, then the tool isn't stateful.
.. note::
This property is experimental and may change at any point.
""")
| CustomAction |
python | huggingface__transformers | src/transformers/models/granitemoeshared/modeling_granitemoeshared.py | {
"start": 13898,
"end": 17100
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: GraniteMoeSharedConfig, layer_idx: int):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
self.scaling = config.attention_multiplier # Only diff with llama
self.attention_dropout = config.attention_dropout
self.is_causal = True
self.q_proj = nn.Linear(
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
)
self.k_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.v_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.o_proj = nn.Linear(
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
)
self.rotary_fn = apply_rotary_pos_emb
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
attention_mask: Optional[torch.Tensor] = None,
past_key_values: Optional[Cache] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> tuple[torch.Tensor, torch.Tensor]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
if past_key_values is not None:
# sin and cos are specific to RoPE models; cache_position needed for the static cache
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
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.attention_dropout,
scaling=self.scaling,
**kwargs,
)
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
| GraniteMoeSharedAttention |
python | getsentry__sentry | tests/sentry/integrations/discord/test_uninstall.py | {
"start": 839,
"end": 4112
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-integration-details"
method = "delete"
def setUp(self) -> None:
self.integration = self.create_discord_integration(self.organization, self.user)
self.login_as(self.user)
def create_discord_integration(
self,
organization: Organization,
user: RpcUser | User,
guild_id: str = GUILD_ID,
**kwargs: Any,
) -> Integration:
integration = Factories.create_integration(
provider="discord",
name="Cool server",
external_id=guild_id,
organization=organization,
**kwargs,
)
return integration
def uninstall(self) -> None:
org_integration = OrganizationIntegration.objects.get(
integration=self.integration, organization_id=self.organization.id
)
with self.tasks():
self.get_success_response(self.organization.slug, self.integration.id)
assert Integration.objects.filter(id=self.integration.id).exists()
assert not OrganizationIntegration.objects.filter(
integration=self.integration,
organization_id=self.organization.id,
status=ObjectStatus.ACTIVE,
).exists()
assert ScheduledDeletion.objects.filter(
model_name="OrganizationIntegration",
object_id=org_integration.id,
).exists()
def mock_discord_guild_leave(self, status: int = 204) -> None:
responses.add(
responses.DELETE,
url=f"{DiscordClient.base_url}{USERS_GUILD_URL.format(guild_id=GUILD_ID)}",
status=status,
)
def assert_leave_guild_api_call_count(self, count: int) -> None:
assert responses.assert_call_count(count=count, url=LEAVE_GUILD_URL)
@responses.activate
def test_uninstall(self) -> None:
self.mock_discord_guild_leave()
self.uninstall()
self.assert_leave_guild_api_call_count(1)
@responses.activate
def test_uninstall_bot_already_left_guild(self) -> None:
self.mock_discord_guild_leave(status=404)
self.uninstall()
self.assert_leave_guild_api_call_count(1)
@responses.activate
@mock.patch("sentry.integrations.discord.integration.logger.error")
def test_uninstall_unexpected_failure(self, mock_log_error: mock.MagicMock) -> None:
self.mock_discord_guild_leave(status=500)
self.uninstall()
self.assert_leave_guild_api_call_count(1)
assert mock_log_error.call_count == 1
@responses.activate
def test_uninstall_multiple_orgs(self) -> None:
self.mock_discord_guild_leave()
other_org = self.create_organization(owner=self.user)
self.integration.add_organization(other_org)
self.uninstall()
# Make sure other org integration persists and we did not make an
# attempt to uninstall the bot from the shared server
assert Integration.objects.filter(id=self.integration.id).exists()
assert OrganizationIntegration.objects.filter(
integration=self.integration, organization_id=other_org.id
).exists()
self.assert_leave_guild_api_call_count(0)
| DiscordUninstallTest |
python | zarr-developers__zarr-python | tests/test_dtype/test_npy/test_complex.py | {
"start": 463,
"end": 1741
} | class ____(_BaseTestFloat):
test_cls = Complex64
valid_dtype = (np.dtype(">c8"), np.dtype("<c8"))
invalid_dtype = (
np.dtype(np.int8),
np.dtype(np.float64),
np.dtype(np.complex128),
)
valid_json_v2 = (
{"name": ">c8", "object_codec_id": None},
{"name": "<c8", "object_codec_id": None},
)
valid_json_v3 = ("complex64",)
invalid_json_v2 = (
"|c8",
"complex64",
"|f8",
)
invalid_json_v3 = (
"|c8",
"|f8",
{"name": "complex64", "configuration": {"endianness": "little"}},
)
scalar_v2_params = (
(Complex64(), (1.0, 1.0)),
(Complex64(), (-1.0, "Infinity")),
(Complex64(), (0, "NaN")),
)
scalar_v3_params = (
(Complex64(), (1.0, 1.0)),
(Complex64(), (-1.0, "Infinity")),
(Complex64(), (0, "NaN")),
)
cast_value_params = (
(Complex64(), complex(1.0, 1.0), np.complex64(complex(1.0, 1.0))),
(Complex64(), complex(-1.0, math.inf), np.complex64(complex(-1.0, math.inf))),
(Complex64(), complex(0, math.nan), np.complex64(complex(0, math.nan))),
)
invalid_scalar_params = ((Complex64(), {"type": "dict"}),)
item_size_params = (Complex64(),)
| TestComplex64 |
python | allegroai__clearml | clearml/backend_api/services/v2_20/projects.py | {
"start": 37500,
"end": 41858
} | class ____(Request):
"""
Create a new project
:param name: Project name Unique within the company.
:type name: str
:param description: Project description.
:type description: str
:param tags: User-defined tags
:type tags: Sequence[str]
:param system_tags: System tags. This field is reserved for system use, please don't use it.
:type system_tags: Sequence[str]
:param default_output_destination: The default output destination URL for new tasks under this project
:type default_output_destination: str
"""
_service = "projects"
_action = "create"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
"default_output_destination": {
"description": "The default output destination URL for new tasks under this project",
"type": "string",
},
"description": {"description": "Project description.", "type": "string"},
"name": {
"description": "Project name Unique within the company.",
"type": "string",
},
"system_tags": {
"description": "System tags. This field is reserved for system use, please don't use it.",
"items": {"type": "string"},
"type": "array",
},
"tags": {
"description": "User-defined tags",
"items": {"type": "string"},
"type": "array",
},
},
"required": ["name"],
"type": "object",
}
def __init__(
self,
name: str,
description: Optional[str] = None,
tags: Optional[List[str]] = None,
system_tags: Optional[List[str]] = None,
default_output_destination: Optional[str] = None,
**kwargs: Any
) -> None:
super(CreateRequest, self).__init__(**kwargs)
self.name = name
self.description = description
self.tags = tags
self.system_tags = system_tags
self.default_output_destination = default_output_destination
@schema_property("name")
def name(self) -> str:
return self._property_name
@name.setter
def name(self, value: str) -> None:
if value is None:
self._property_name = None
return
self.assert_isinstance(value, "name", six.string_types)
self._property_name = value
@schema_property("description")
def description(self) -> Optional[str]:
return self._property_description
@description.setter
def description(self, value: Optional[str]) -> None:
if value is None:
self._property_description = None
return
self.assert_isinstance(value, "description", six.string_types)
self._property_description = value
@schema_property("tags")
def tags(self) -> Optional[List[str]]:
return self._property_tags
@tags.setter
def tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_tags = None
return
self.assert_isinstance(value, "tags", (list, tuple))
self.assert_isinstance(value, "tags", six.string_types, is_array=True)
self._property_tags = value
@schema_property("system_tags")
def system_tags(self) -> Optional[List[str]]:
return self._property_system_tags
@system_tags.setter
def system_tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_system_tags = None
return
self.assert_isinstance(value, "system_tags", (list, tuple))
self.assert_isinstance(value, "system_tags", six.string_types, is_array=True)
self._property_system_tags = value
@schema_property("default_output_destination")
def default_output_destination(self) -> Optional[str]:
return self._property_default_output_destination
@default_output_destination.setter
def default_output_destination(self, value: Optional[str]) -> None:
if value is None:
self._property_default_output_destination = None
return
self.assert_isinstance(value, "default_output_destination", six.string_types)
self._property_default_output_destination = value
| CreateRequest |
python | encode__django-rest-framework | rest_framework/fields.py | {
"start": 55185,
"end": 55883
} | class ____(ChoiceField):
default_error_messages = {
'invalid_choice': _('"{input}" is not a valid path choice.')
}
def __init__(self, path, match=None, recursive=False, allow_files=True,
allow_folders=False, required=None, **kwargs):
# Defer to Django's FilePathField implementation to get the
# valid set of choices.
field = DjangoFilePathField(
path, match=match, recursive=recursive, allow_files=allow_files,
allow_folders=allow_folders, required=required
)
kwargs['choices'] = field.choices
kwargs['required'] = required
super().__init__(**kwargs)
# File types...
| FilePathField |
python | huggingface__transformers | tests/models/wav2vec2_bert/test_modeling_wav2vec2_bert.py | {
"start": 1850,
"end": 15613
} | class ____:
# Ignore copy
def __init__(
self,
parent,
batch_size=13,
seq_length=200, # speech is longer
is_training=False,
hidden_size=16,
feature_projection_input_dim=16,
num_conv_pos_embeddings=16,
num_conv_pos_embedding_groups=2,
num_hidden_layers=2,
num_attention_heads=2,
hidden_dropout_prob=0.1,
intermediate_size=20,
layer_norm_eps=1e-5,
hidden_act="gelu",
initializer_range=0.02,
mask_time_prob=0.5,
mask_time_length=2,
vocab_size=32,
do_stable_layer_norm=False,
num_adapter_layers=2,
adapter_stride=2,
tdnn_dim=(32, 32),
tdnn_kernel=(5, 3),
tdnn_dilation=(1, 2),
xvector_output_dim=32,
position_embeddings_type="relative",
scope=None,
):
self.parent = parent
self.batch_size = batch_size
self.seq_length = seq_length
self.is_training = is_training
self.hidden_size = hidden_size
self.feature_projection_input_dim = feature_projection_input_dim
self.num_conv_pos_embeddings = num_conv_pos_embeddings
self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.hidden_dropout_prob = hidden_dropout_prob
self.intermediate_size = intermediate_size
self.layer_norm_eps = layer_norm_eps
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.vocab_size = vocab_size
self.do_stable_layer_norm = do_stable_layer_norm
self.num_adapter_layers = num_adapter_layers
self.adapter_stride = adapter_stride
self.mask_time_prob = mask_time_prob
self.mask_time_length = mask_time_length
self.scope = scope
self.tdnn_dim = tdnn_dim
self.tdnn_kernel = tdnn_kernel
self.tdnn_dilation = tdnn_dilation
self.xvector_output_dim = xvector_output_dim
self.position_embeddings_type = position_embeddings_type
self.output_seq_length = self.seq_length
self.encoder_seq_length = self.output_seq_length
self.adapter_output_seq_length = self.output_seq_length
for _ in range(num_adapter_layers):
self.adapter_output_seq_length = (self.adapter_output_seq_length - 1) // adapter_stride + 1
# Ignore copy
def prepare_config_and_inputs(self, position_embeddings_type="relative"):
input_shape = [self.batch_size, self.seq_length, self.feature_projection_input_dim]
input_features = floats_tensor(input_shape, self.vocab_size)
attention_mask = random_attention_mask([self.batch_size, self.seq_length])
config = self.get_config(position_embeddings_type=position_embeddings_type)
return config, input_features, attention_mask
# Ignore copy
def get_config(self, position_embeddings_type="relative"):
return Wav2Vec2BertConfig(
hidden_size=self.hidden_size,
feature_projection_input_dim=self.feature_projection_input_dim,
mask_time_prob=self.mask_time_prob,
mask_time_length=self.mask_time_length,
num_conv_pos_embeddings=self.num_conv_pos_embeddings,
num_conv_pos_embedding_groups=self.num_conv_pos_embedding_groups,
num_hidden_layers=self.num_hidden_layers,
num_attention_heads=self.num_attention_heads,
hidden_dropout_prob=self.hidden_dropout_prob,
intermediate_size=self.intermediate_size,
layer_norm_eps=self.layer_norm_eps,
do_stable_layer_norm=self.do_stable_layer_norm,
hidden_act=self.hidden_act,
initializer_range=self.initializer_range,
vocab_size=self.vocab_size,
num_adapter_layers=self.num_adapter_layers,
adapter_stride=self.adapter_stride,
tdnn_dim=self.tdnn_dim,
tdnn_kernel=self.tdnn_kernel,
tdnn_dilation=self.tdnn_dilation,
xvector_output_dim=self.xvector_output_dim,
position_embeddings_type=position_embeddings_type,
)
def create_and_check_model(self, config, input_features, attention_mask):
model = Wav2Vec2BertModel(config=config)
model.to(torch_device)
model.eval()
result = model(input_features, attention_mask=attention_mask)
self.parent.assertEqual(
result.last_hidden_state.shape, (self.batch_size, self.output_seq_length, self.hidden_size)
)
def create_and_check_model_with_adapter(self, config, input_features, attention_mask):
config.add_adapter = True
model = Wav2Vec2BertModel(config=config)
model.to(torch_device)
model.eval()
result = model(input_features, attention_mask=attention_mask)
self.parent.assertEqual(
result.last_hidden_state.shape, (self.batch_size, self.adapter_output_seq_length, self.hidden_size)
)
def create_and_check_model_with_adapter_for_ctc(self, config, input_features, attention_mask):
config.add_adapter = True
config.output_hidden_size = 2 * config.hidden_size
model = Wav2Vec2BertForCTC(config=config)
model.to(torch_device)
model.eval()
result = model(input_features, attention_mask=attention_mask)
self.parent.assertEqual(
result.logits.shape, (self.batch_size, self.adapter_output_seq_length, self.vocab_size)
)
# Ignore copy
def create_and_check_model_with_intermediate_ffn_before_adapter(self, config, input_features, attention_mask):
config.add_adapter = True
config.use_intermediate_ffn_before_adapter = True
model = Wav2Vec2BertModel(config=config)
model.to(torch_device)
model.eval()
result = model(input_features, attention_mask=attention_mask)
self.parent.assertEqual(
result.last_hidden_state.shape,
(self.batch_size, self.adapter_output_seq_length, config.output_hidden_size),
)
# also try with different adapter proj dim
config.output_hidden_size = 8
model = Wav2Vec2BertModel(config=config)
model.to(torch_device)
model.eval()
result = model(input_features, attention_mask=attention_mask)
self.parent.assertEqual(
result.last_hidden_state.shape,
(self.batch_size, self.adapter_output_seq_length, config.output_hidden_size),
)
def create_and_check_model_with_adapter_proj_dim(self, config, input_features, attention_mask):
config.add_adapter = True
config.output_hidden_size = 8
model = Wav2Vec2BertModel(config=config)
model.to(torch_device)
model.eval()
result = model(input_features, attention_mask=attention_mask)
self.parent.assertEqual(
result.last_hidden_state.shape,
(self.batch_size, self.adapter_output_seq_length, config.output_hidden_size),
)
def create_and_check_model_float16(self, config, input_features, attention_mask):
model = Wav2Vec2BertModel(config=config)
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(tmpdirname)
model = Wav2Vec2BertModel.from_pretrained(tmpdirname, dtype=torch.float16)
model.to(torch_device)
model.eval()
with torch.no_grad():
result = model(input_features.type(dtype=torch.float16), attention_mask=attention_mask)
self.parent.assertEqual(
result.last_hidden_state.shape, (self.batch_size, self.output_seq_length, self.hidden_size)
)
def check_ctc_loss(self, config, input_features, *args):
model = Wav2Vec2BertForCTC(config=config)
model.to(torch_device)
# make sure that dropout is disabled
model.eval()
input_features = input_features[:3]
# Ignore copy
attention_mask = torch.ones(input_features.shape[:2], device=torch_device, dtype=torch.long)
input_lengths = [input_features.shape[1] // i for i in [4, 2, 1]]
max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths))
labels = ids_tensor((input_features.shape[0], min(max_length_labels) - 1), model.config.vocab_size)
# pad input
for i in range(len(input_lengths)):
input_features[i, input_lengths[i] :] = 0.0
attention_mask[i, input_lengths[i] :] = 0
model.config.ctc_loss_reduction = "sum"
sum_loss = model(input_features, attention_mask=attention_mask, labels=labels).loss.item()
model.config.ctc_loss_reduction = "mean"
mean_loss = model(input_features, attention_mask=attention_mask, labels=labels).loss.item()
self.parent.assertTrue(isinstance(sum_loss, float))
self.parent.assertTrue(isinstance(mean_loss, float))
def check_seq_classifier_loss(self, config, input_features, *args):
model = Wav2Vec2BertForSequenceClassification(config=config)
model.to(torch_device)
# make sure that dropout is disabled
model.eval()
input_features = input_features[:3]
# Ignore copy
attention_mask = torch.ones(input_features.shape[:2], device=torch_device, dtype=torch.long)
input_lengths = [input_features.shape[1] // i for i in [4, 2, 1]]
labels = ids_tensor((input_features.shape[0], 1), len(model.config.id2label))
# pad input
for i in range(len(input_lengths)):
input_features[i, input_lengths[i] :] = 0.0
attention_mask[i, input_lengths[i] :] = 0
masked_loss = model(input_features, attention_mask=attention_mask, labels=labels).loss.item()
unmasked_loss = model(input_features, labels=labels).loss.item()
self.parent.assertTrue(isinstance(masked_loss, float))
self.parent.assertTrue(isinstance(unmasked_loss, float))
self.parent.assertTrue(masked_loss != unmasked_loss)
def check_ctc_training(self, config, input_features, *args):
config.ctc_zero_infinity = True
model = Wav2Vec2BertForCTC(config=config)
model.to(torch_device)
model.train()
# Ignore copy
input_features = input_features[:3]
input_lengths = [input_features.shape[1] // i for i in [4, 2, 1]]
max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths))
labels = ids_tensor((input_features.shape[0], max(max_length_labels) - 2), model.config.vocab_size)
# pad input
for i in range(len(input_lengths)):
input_features[i, input_lengths[i] :] = 0.0
if max_length_labels[i] < labels.shape[-1]:
# it's important that we make sure that target lengths are at least
# one shorter than logit lengths to prevent -inf
labels[i, max_length_labels[i] - 1 :] = -100
loss = model(input_features, labels=labels).loss
self.parent.assertFalse(torch.isinf(loss).item())
loss.backward()
def check_seq_classifier_training(self, config, input_features, *args):
config.ctc_zero_infinity = True
model = Wav2Vec2BertForSequenceClassification(config=config)
model.to(torch_device)
model.train()
# freeze everything but the classification head
model.freeze_base_model()
input_features = input_features[:3]
# Ignore copy
input_lengths = [input_features.shape[1] // i for i in [4, 2, 1]]
labels = ids_tensor((input_features.shape[0], 1), len(model.config.id2label))
# pad input
for i in range(len(input_lengths)):
input_features[i, input_lengths[i] :] = 0.0
loss = model(input_features, labels=labels).loss
self.parent.assertFalse(torch.isinf(loss).item())
loss.backward()
def check_xvector_training(self, config, input_features, *args):
config.ctc_zero_infinity = True
model = Wav2Vec2BertForXVector(config=config)
model.to(torch_device)
model.train()
# freeze everything but the classification head
model.freeze_base_model()
input_features = input_features[:3]
input_lengths = [input_features.shape[-1] // i for i in [4, 2, 1]]
labels = ids_tensor((input_features.shape[0], 1), len(model.config.id2label))
# pad input
for i in range(len(input_lengths)):
input_features[i, input_lengths[i] :] = 0.0
loss = model(input_features, labels=labels).loss
self.parent.assertFalse(torch.isinf(loss).item())
loss.backward()
def check_labels_out_of_vocab(self, config, input_features, *args):
model = Wav2Vec2BertForCTC(config)
model.to(torch_device)
model.train()
input_features = input_features[:3]
input_lengths = [input_features.shape[-1] // i for i in [4, 2, 1]]
max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths))
labels = ids_tensor((input_features.shape[0], max(max_length_labels) - 2), model.config.vocab_size + 100)
with self.parent.assertRaises(ValueError):
model(input_features, labels=labels)
def prepare_config_and_inputs_for_common(self):
config, input_features, attention_mask = self.prepare_config_and_inputs()
inputs_dict = {"input_features": input_features, "attention_mask": attention_mask}
return config, inputs_dict
@require_torch
| Wav2Vec2BertModelTester |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/destinations.py | {
"start": 117790,
"end": 118304
} | class ____(GeneratedAirbyteDestination):
@public
def __init__(self, name: str, TODO: Optional[str] = None):
"""Airbyte Destination for Scaffold Destination Python.
Documentation for this source is no longer available.
Args:
name (str): The name of the destination.
TODO (Optional[str]): FIX ME
"""
self.TODO = check.opt_str_param(TODO, "TODO")
super().__init__("Scaffold Destination Python", name)
| ScaffoldDestinationPythonDestination |
python | huggingface__transformers | tests/models/ibert/test_modeling_ibert.py | {
"start": 8753,
"end": 15016
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
test_resize_embeddings = False
all_model_classes = (
(
IBertForMaskedLM,
IBertModel,
IBertForSequenceClassification,
IBertForTokenClassification,
IBertForMultipleChoice,
IBertForQuestionAnswering,
)
if is_torch_available()
else ()
)
pipeline_model_mapping = (
{
"feature-extraction": IBertModel,
"fill-mask": IBertForMaskedLM,
"question-answering": IBertForQuestionAnswering,
"text-classification": IBertForSequenceClassification,
"token-classification": IBertForTokenClassification,
"zero-shot": IBertForSequenceClassification,
}
if is_torch_available()
else {}
)
def setUp(self):
self.model_tester = IBertModelTester(self)
self.config_tester = ConfigTester(self, config_class=IBertConfig, hidden_size=37)
def test_config(self):
self.config_tester.run_common_tests()
def test_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*config_and_inputs)
def test_for_masked_lm(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
def test_for_token_classification(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
def test_for_multiple_choice(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
def test_for_question_answering(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
@slow
def test_model_from_pretrained(self):
model_name = "kssteven/ibert-roberta-base"
model = IBertModel.from_pretrained(model_name)
self.assertIsNotNone(model)
def test_create_position_ids_respects_padding_index(self):
"""This is a regression test for https://github.com/huggingface/transformers/issues/1761
The position ids should be masked with the embedding object's padding index. Therefore, the
first available non-padding position index is IBertEmbeddings.padding_idx + 1
"""
config = self.model_tester.prepare_config_and_inputs()[0]
model = IBertEmbeddings(config=config)
input_ids = torch.as_tensor([[12, 31, 13, model.padding_idx]])
expected_positions = torch.as_tensor(
[[0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx]]
)
position_ids = create_position_ids_from_input_ids(input_ids, model.padding_idx)
self.assertEqual(position_ids.shape, expected_positions.shape)
self.assertTrue(torch.all(torch.eq(position_ids, expected_positions)))
def test_create_position_ids_from_inputs_embeds(self):
"""This is a regression test for https://github.com/huggingface/transformers/issues/1761
The position ids should be masked with the embedding object's padding index. Therefore, the
first available non-padding position index is IBertEmbeddings.padding_idx + 1
"""
config = self.model_tester.prepare_config_and_inputs()[0]
embeddings = IBertEmbeddings(config=config)
inputs_embeds = torch.empty(2, 4, 30)
expected_single_positions = [
0 + embeddings.padding_idx + 1,
1 + embeddings.padding_idx + 1,
2 + embeddings.padding_idx + 1,
3 + embeddings.padding_idx + 1,
]
expected_positions = torch.as_tensor([expected_single_positions, expected_single_positions])
position_ids = embeddings.create_position_ids_from_inputs_embeds(inputs_embeds)
self.assertEqual(position_ids.shape, expected_positions.shape)
self.assertTrue(torch.all(torch.eq(position_ids, expected_positions)))
# Override
def test_model_get_set_embeddings(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
model = model_class(config)
self.assertIsInstance(model.get_input_embeddings(), QuantEmbedding)
model.set_input_embeddings(nn.Embedding(10, 10))
x = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(x, nn.Linear))
# Override
def test_feed_forward_chunking(self):
pass # I-BERT does not support chunking
# Override
def test_inputs_embeds(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
model = model_class(config)
model.to(torch_device)
model.eval()
inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class))
if not self.is_encoder_decoder:
input_ids = inputs["input_ids"]
del inputs["input_ids"]
else:
encoder_input_ids = inputs["input_ids"]
decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids)
del inputs["input_ids"]
inputs.pop("decoder_input_ids", None)
wte = model.get_input_embeddings()
if not self.is_encoder_decoder:
embed, embed_scaling_factor = wte(input_ids)
inputs["inputs_embeds"] = embed
else:
inputs["inputs_embeds"] = wte(encoder_input_ids)
inputs["decoder_inputs_embeds"] = wte(decoder_input_ids)
with torch.no_grad():
model(**inputs)[0]
@unittest.skip(reason="ibert overrides scaling to None if inputs_embeds")
def test_inputs_embeds_matches_input_ids(self):
pass
@require_torch
| IBertModelTest |
python | huggingface__transformers | src/transformers/models/gemma3n/modeling_gemma3n.py | {
"start": 72702,
"end": 74868
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: Gemma3nConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.config = config
self.attention_type = config.layer_types[layer_idx]
self.self_attn = Gemma3nAttention(config=config, layer_idx=layer_idx)
self.mlp = Gemma3nMLP(config)
self.input_layernorm = Gemma3nRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = Gemma3nRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.pre_feedforward_layernorm = Gemma3nRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_feedforward_layernorm = Gemma3nRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs,
) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
# Self Attention
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
position_embeddings=position_embeddings,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
cache_position=cache_position,
**kwargs,
)
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.pre_feedforward_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = self.post_feedforward_layernorm(hidden_states)
hidden_states = residual + hidden_states
return hidden_states
@auto_docstring
| Gemma3nDecoderLayer |
python | scrapy__scrapy | tests/test_squeues.py | {
"start": 3942,
"end": 4028
} | class ____(PickleFifoDiskQueueTest):
chunksize = 3
| ChunkSize3PickleFifoDiskQueueTest |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_stackdriver.py | {
"start": 8082,
"end": 8613
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.stackdriver.StackdriverHook")
def test_execute(self, mock_hook):
operator = StackdriverEnableNotificationChannelsOperator(task_id=TEST_TASK_ID, filter_=TEST_FILTER)
operator.execute(context=mock.MagicMock())
mock_hook.return_value.enable_notification_channels.assert_called_once_with(
project_id=None, filter_=TEST_FILTER, retry=DEFAULT, timeout=None, metadata=()
)
| TestStackdriverEnableNotificationChannelsOperator |
python | RaRe-Technologies__gensim | gensim/test/test_translation_matrix.py | {
"start": 389,
"end": 3938
} | class ____(unittest.TestCase):
def setUp(self):
self.source_word_vec_file = datapath("EN.1-10.cbow1_wind5_hs0_neg10_size300_smpl1e-05.txt")
self.target_word_vec_file = datapath("IT.1-10.cbow1_wind5_hs0_neg10_size300_smpl1e-05.txt")
self.word_pairs = [
("one", "uno"), ("two", "due"), ("three", "tre"),
("four", "quattro"), ("five", "cinque"), ("seven", "sette"), ("eight", "otto"),
("dog", "cane"), ("pig", "maiale"), ("fish", "cavallo"), ("birds", "uccelli"),
("apple", "mela"), ("orange", "arancione"), ("grape", "acino"), ("banana", "banana"),
]
self.test_word_pairs = [("ten", "dieci"), ("cat", "gatto")]
self.source_word_vec = KeyedVectors.load_word2vec_format(self.source_word_vec_file, binary=False)
self.target_word_vec = KeyedVectors.load_word2vec_format(self.target_word_vec_file, binary=False)
def test_translation_matrix(self):
model = translation_matrix.TranslationMatrix(self.source_word_vec, self.target_word_vec, self.word_pairs)
model.train(self.word_pairs)
self.assertEqual(model.translation_matrix.shape, (300, 300))
def test_persistence(self):
"""Test storing/loading the entire model."""
tmpf = get_tmpfile('transmat-en-it.pkl')
model = translation_matrix.TranslationMatrix(self.source_word_vec, self.target_word_vec, self.word_pairs)
model.train(self.word_pairs)
model.save(tmpf)
loaded_model = translation_matrix.TranslationMatrix.load(tmpf)
self.assertTrue(np.allclose(model.translation_matrix, loaded_model.translation_matrix))
def test_translate_nn(self):
# Test the nearest neighbor retrieval method
model = translation_matrix.TranslationMatrix(self.source_word_vec, self.target_word_vec, self.word_pairs)
model.train(self.word_pairs)
test_source_word, test_target_word = zip(*self.test_word_pairs)
translated_words = model.translate(
test_source_word, topn=5, source_lang_vec=self.source_word_vec, target_lang_vec=self.target_word_vec,
)
for idx, item in enumerate(self.test_word_pairs):
self.assertTrue(item[1] in translated_words[item[0]])
@pytest.mark.xfail(
True,
reason='blinking test, can be related to <https://github.com/RaRe-Technologies/gensim/issues/2977>'
)
def test_translate_gc(self):
# Test globally corrected neighbour retrieval method
model = translation_matrix.TranslationMatrix(self.source_word_vec, self.target_word_vec, self.word_pairs)
model.train(self.word_pairs)
test_source_word, test_target_word = zip(*self.test_word_pairs)
translated_words = model.translate(
test_source_word, topn=5, gc=1, sample_num=3,
source_lang_vec=self.source_word_vec, target_lang_vec=self.target_word_vec
)
for idx, item in enumerate(self.test_word_pairs):
self.assertTrue(item[1] in translated_words[item[0]])
def read_sentiment_docs(filename):
sentiment_document = namedtuple('SentimentDocument', 'words tags')
alldocs = [] # will hold all docs in original order
with utils.open(filename, mode='rb', encoding='utf-8') as alldata:
for line_no, line in enumerate(alldata):
tokens = utils.to_unicode(line).split()
words = tokens
tags = str(line_no)
alldocs.append(sentiment_document(words, tags))
return alldocs
| TestTranslationMatrix |
python | getsentry__sentry | src/sentry/analytics/events/project_created.py | {
"start": 72,
"end": 341
} | class ____(analytics.Event):
user_id: int | None = None
default_user_id: int | str | None = None
organization_id: int
origin: str | None = None
project_id: int
platform: str | None = None
analytics.register(ProjectCreatedEvent)
| ProjectCreatedEvent |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 3474,
"end": 3873
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.layer1 = BasicModule()
self.scale = torch.randn(1, 10)
def call_and_scale(self, mod, x):
x = mod(x)
x = x * self.scale
return unsupported(x, x)
def forward(self, x):
x1 = self.call_and_scale(self.layer1, x)
return x + x1
| UnsupportedMethodCall |
python | huggingface__transformers | src/transformers/models/evolla/modeling_evolla.py | {
"start": 49042,
"end": 51970
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: EvollaConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = EvollaAttention(config=config, layer_idx=layer_idx)
self.mlp = EvollaMLP(config)
self.input_layernorm = EvollaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = EvollaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
if (layer_idx + 1) % max(config.num_hidden_layers // config.aligner_num_add_layers, 1) == 0:
self.adapter = EvollaSequenceAlignerCrossAttention(
config,
protein_encoder_dim=config.hidden_size,
)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
use_cache: Optional[bool] = False,
cache_position: Optional[torch.LongTensor] = None,
protein_kv_states: Optional[torch.Tensor] = None,
structure_kv_states: Optional[torch.Tensor] = None,
msa_kv_states: Optional[torch.Tensor] = None,
protein_batch_mask: Optional[torch.Tensor] = None,
structure_batch_mask: Optional[torch.Tensor] = None,
msa_batch_mask: Optional[torch.Tensor] = None,
query_attn_mask: Optional[torch.Tensor] = None,
**kwargs,
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
# Self Attention
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
use_cache=use_cache,
cache_position=cache_position,
position_embeddings=position_embeddings,
**kwargs,
)
hidden_states = residual + hidden_states
# Fully Connected
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = residual + hidden_states
if hasattr(self, "adapter"):
hidden_states = self.adapter(
query_states=hidden_states,
protein_kv_states=protein_kv_states,
structure_kv_states=structure_kv_states,
msa_kv_states=msa_kv_states,
query_attn_mask=query_attn_mask,
protein_batch_mask=protein_batch_mask,
structure_batch_mask=structure_batch_mask,
msa_batch_mask=msa_batch_mask,
)
return hidden_states
@auto_docstring
| EvollaDecoderLayer |
python | PrefectHQ__prefect | src/integrations/prefect-dbt/tests/core/test_runner.py | {
"start": 9087,
"end": 13315
} | class ____:
"""Test compiled code functionality."""
def test_get_compiled_code_path_uses_project_name(
self, tmp_path: Path, mock_manifest, mock_manifest_node
):
"""Test that compiled code path uses project name correctly."""
runner = PrefectDbtRunner(manifest=mock_manifest)
runner._project_dir = tmp_path
runner._target_path = Path("target")
result = runner._get_compiled_code_path(mock_manifest_node)
expected_path = (
tmp_path
/ "target"
/ "compiled"
/ "test_project"
/ "models"
/ "test_model.sql"
)
assert result == expected_path
def test_get_compiled_code_returns_empty_when_disabled(self, mock_manifest_node):
"""Test that compiled code returns empty when disabled."""
runner = PrefectDbtRunner(include_compiled_code=False)
result = runner._get_compiled_code(mock_manifest_node)
assert result == ""
def test_get_compiled_code_truncates_when_exceeding_max_length(
self, tmp_path: Path, mock_manifest, mock_manifest_node
):
"""Test that compiled code is truncated when it exceeds MAX_ASSET_DESCRIPTION_LENGTH."""
runner = PrefectDbtRunner(manifest=mock_manifest, include_compiled_code=True)
runner._project_dir = tmp_path
runner._target_path = Path("target")
compiled_path = tmp_path / "target" / "compiled" / "test_project" / "models"
compiled_path.mkdir(parents=True)
sql_file = compiled_path / "test_model.sql"
long_sql_content = "SELECT " + "column_name, " * 200
sql_file.write_text(long_sql_content)
result = runner._get_compiled_code(mock_manifest_node)
# Should return the truncated message instead of the full SQL
expected_message = (
"\n ### Compiled code\n"
f"Compiled code for {mock_manifest_node.name} was omitted because it exceeded the "
f"maximum asset description length of {MAX_ASSET_DESCRIPTION_LENGTH} characters."
)
assert result == expected_message
assert len(result) <= MAX_ASSET_DESCRIPTION_LENGTH
def test_get_compiled_code_returns_empty_for_source_definition_when_enabled(
self, mock_source_definition
):
"""Test that compiled code returns empty for SourceDefinition even when enabled."""
runner = PrefectDbtRunner(include_compiled_code=True)
result = runner._get_compiled_code(mock_source_definition)
assert result == ""
def test_get_compiled_code_returns_empty_for_source_definition_when_disabled(
self, mock_source_definition
):
"""Test that compiled code returns empty for SourceDefinition when disabled."""
runner = PrefectDbtRunner(include_compiled_code=False)
result = runner._get_compiled_code(mock_source_definition)
assert result == ""
def test_get_compiled_code_returns_formatted_sql_when_enabled(
self, tmp_path: Path, mock_manifest, mock_manifest_node
):
"""Test that compiled code returns formatted SQL when enabled."""
runner = PrefectDbtRunner(manifest=mock_manifest, include_compiled_code=True)
runner._project_dir = tmp_path
runner._target_path = Path("target")
# Create compiled SQL file
compiled_path = tmp_path / "target" / "compiled" / "test_project" / "models"
compiled_path.mkdir(parents=True)
sql_file = compiled_path / "test_model.sql"
sql_file.write_text("SELECT * FROM test_table")
result = runner._get_compiled_code(mock_manifest_node)
assert "SELECT * FROM test_table" in result
def test_get_compiled_code_returns_empty_when_file_not_found(
self, tmp_path: Path, mock_manifest, mock_manifest_node
):
"""Test that compiled code returns empty when file not found."""
runner = PrefectDbtRunner(manifest=mock_manifest, include_compiled_code=True)
runner._project_dir = tmp_path
runner._target_path = Path("target")
result = runner._get_compiled_code(mock_manifest_node)
assert result == ""
| TestPrefectDbtRunnerCompiledCode |
python | readthedocs__readthedocs.org | readthedocs/api/v2/serializers.py | {
"start": 5556,
"end": 6448
} | class ____(VersionSerializer):
"""Version serializer that returns admin project data."""
project_serializer_class = ProjectAdminSerializer
canonical_url = serializers.SerializerMethodField()
build_data = serializers.JSONField(required=False, write_only=True, allow_null=True)
def get_canonical_url(self, obj):
# Use the cached object, since it has some
# relationships already cached from calling
# get_docs_url early when serializing the project.
project = self._get_project_serialized(obj).instance
return Resolver().resolve_version(
project=project,
version=obj,
)
class Meta(VersionSerializer.Meta):
fields = VersionSerializer.Meta.fields + [
"build_data",
"canonical_url",
"machine",
"git_identifier",
]
| VersionAdminSerializer |
python | apache__airflow | airflow-core/src/airflow/utils/db.py | {
"start": 52121,
"end": 59171
} | class ____(Sequence[T]):
"""
List-like interface to lazily access a database model query.
The intended use case is inside a task execution context, where we manage an
active SQLAlchemy session in the background.
This is an abstract base class. Each use case should subclass, and implement
the following static methods:
* ``_rebuild_select`` is called when a lazy sequence is unpickled. Since it
is not easy to pickle SQLAlchemy constructs, this class serializes the
SELECT statements into plain text to storage. This method is called on
deserialization to convert the textual clause back into an ORM SELECT.
* ``_process_row`` is called when an item is accessed. The lazy sequence
uses ``session.execute()`` to fetch rows from the database, and this
method should know how to process each row into a value.
:meta private:
"""
_select_asc: Select
_select_desc: Select
_session: Session
_len: int | None = attrs.field(init=False, default=None)
@classmethod
def from_select(
cls,
select: Select,
*,
order_by: Sequence[ColumnElement],
session: Session,
) -> Self:
s1 = select
for col in order_by:
s1 = s1.order_by(col.asc())
s2 = select
for col in order_by:
s2 = s2.order_by(col.desc())
return cls(s1, s2, session=session)
@staticmethod
def _rebuild_select(stmt: TextClause) -> Select:
"""
Rebuild a textual statement into an ORM-configured SELECT statement.
This should do something like ``select(field).from_statement(stmt)`` to
reconfigure ORM information to the textual SQL statement.
"""
raise NotImplementedError
@staticmethod
def _process_row(row: Row) -> T:
"""Process a SELECT-ed row into the end value."""
raise NotImplementedError
def __repr__(self) -> str:
counter = "item" if (length := len(self)) == 1 else "items"
return f"LazySelectSequence([{length} {counter}])"
def __str__(self) -> str:
counter = "item" if (length := len(self)) == 1 else "items"
return f"LazySelectSequence([{length} {counter}])"
def __getstate__(self) -> Any:
# We don't want to go to the trouble of serializing SQLAlchemy objects.
# Converting the statement into a SQL string is the best we can get.
# The literal_binds compile argument inlines all the values into the SQL
# string to simplify cross-process commuinication as much as possible.
# Theoratically we can do the same for count(), but I think it should be
# performant enough to calculate only that eagerly.
s1 = str(self._select_asc.compile(self._session.get_bind(), compile_kwargs={"literal_binds": True}))
s2 = str(self._select_desc.compile(self._session.get_bind(), compile_kwargs={"literal_binds": True}))
return (s1, s2, len(self))
def __setstate__(self, state: Any) -> None:
s1, s2, self._len = state
self._select_asc = self._rebuild_select(text(s1))
self._select_desc = self._rebuild_select(text(s2))
def __bool__(self) -> bool:
return check_query_exists(self._select_asc, session=self._session)
def __eq__(self, other: object) -> bool:
if not isinstance(other, collections.abc.Sequence):
return NotImplemented
z = itertools.zip_longest(iter(self), iter(other), fillvalue=object())
return all(x == y for x, y in z)
def __hash__(self):
return hash(tuple(x for x in iter(self)))
def __reversed__(self) -> Iterator[T]:
return iter(self._process_row(r) for r in self._session.execute(self._select_desc))
def __iter__(self) -> Iterator[T]:
return iter(self._process_row(r) for r in self._session.execute(self._select_asc))
def __len__(self) -> int:
if self._len is None:
self._len = get_query_count(self._select_asc, session=self._session)
return self._len
@overload
def __getitem__(self, key: int) -> T: ...
@overload
def __getitem__(self, key: slice) -> Sequence[T]: ...
def __getitem__(self, key: int | slice) -> T | Sequence[T]:
if isinstance(key, int):
if key >= 0:
stmt = self._select_asc.offset(key)
else:
stmt = self._select_desc.offset(-1 - key)
if (row := self._session.execute(stmt.limit(1)).one_or_none()) is None:
raise IndexError(key)
return self._process_row(row)
if isinstance(key, slice):
# This implements the slicing syntax. We want to optimize negative
# slicing (e.g. seq[-10:]) by not doing an additional COUNT query
# if possible. We can do this unless the start and stop have
# different signs (i.e. one is positive and another negative).
start, stop, reverse = _coerce_slice(key)
if start >= 0:
if stop is None:
stmt = self._select_asc.offset(start)
elif stop >= 0:
stmt = self._select_asc.slice(start, stop)
else:
stmt = self._select_asc.slice(start, len(self) + stop)
rows = [self._process_row(row) for row in self._session.execute(stmt)]
if reverse:
rows.reverse()
else:
if stop is None:
stmt = self._select_desc.limit(-start)
elif stop < 0:
stmt = self._select_desc.slice(-stop, -start)
else:
stmt = self._select_desc.slice(len(self) - stop, -start)
rows = [self._process_row(row) for row in self._session.execute(stmt)]
if not reverse:
rows.reverse()
return rows
raise TypeError(f"Sequence indices must be integers or slices, not {type(key).__name__}")
def _coerce_index(value: Any) -> int | None:
"""
Check slice attribute's type and convert it to int.
See CPython documentation on this:
https://docs.python.org/3/reference/datamodel.html#object.__index__
"""
if value is None or isinstance(value, int):
return value
if (index := getattr(value, "__index__", None)) is not None:
return index()
raise TypeError("slice indices must be integers or None or have an __index__ method")
def _coerce_slice(key: slice) -> tuple[int, int | None, bool]:
"""
Check slice content and convert it for SQL.
See CPython documentation on this:
https://docs.python.org/3/reference/datamodel.html#slice-objects
"""
if key.step is None or key.step == 1:
reverse = False
elif key.step == -1:
reverse = True
else:
raise ValueError("non-trivial slice step not supported")
return _coerce_index(key.start) or 0, _coerce_index(key.stop), reverse
| LazySelectSequence |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/installed_deps_e/package.py | {
"start": 217,
"end": 719
} | class ____(Package):
"""Used by test_installed_deps test case."""
# a
# / \
# b c b --> d build/link
# |\ /| b --> e build/link
# |/ \| c --> d build
# d e c --> e build/link
homepage = "http://www.example.com"
url = "http://www.example.com/e-1.0.tar.gz"
version("1", md5="0123456789abcdef0123456789abcdef")
version("2", md5="abcdef0123456789abcdef0123456789")
version("3", md5="def0123456789abcdef0123456789abc")
| InstalledDepsE |
python | django__django | tests/m2m_regress/models.py | {
"start": 391,
"end": 570
} | class ____(models.Model):
name = models.CharField(max_length=10)
def __str__(self):
return self.name
# Regression for #11956 -- a many to many to the base class
| Tag |
python | scrapy__scrapy | tests/spiders.py | {
"start": 6777,
"end": 7060
} | class ____(SimpleSpider):
name = "asyncdef_asyncio_gen_loop"
async def parse(self, response):
for i in range(10):
await asyncio.sleep(0.1)
yield {"foo": i}
self.logger.info(f"Got response {response.status}")
| AsyncDefAsyncioGenLoopSpider |
python | pytest-dev__pytest | src/_pytest/logging.py | {
"start": 12948,
"end": 14030
} | class ____(logging_StreamHandler):
"""A logging handler that stores log records and the log text."""
def __init__(self) -> None:
"""Create a new log handler."""
super().__init__(StringIO())
self.records: list[logging.LogRecord] = []
def emit(self, record: logging.LogRecord) -> None:
"""Keep the log records in a list in addition to the log text."""
self.records.append(record)
super().emit(record)
def reset(self) -> None:
self.records = []
self.stream = StringIO()
def clear(self) -> None:
self.records.clear()
self.stream = StringIO()
def handleError(self, record: logging.LogRecord) -> None:
if logging.raiseExceptions:
# Fail the test if the log message is bad (emit failed).
# The default behavior of logging is to print "Logging error"
# to stderr with the call stack and some extra details.
# pytest wants to make such mistakes visible during testing.
raise # noqa: PLE0704
@final
| LogCaptureHandler |
python | pola-rs__polars | py-polars/src/polars/dataframe/plotting.py | {
"start": 931,
"end": 8183
} | class ____:
"""DataFrame.plot namespace."""
def __init__(self, df: DataFrame) -> None:
self._chart = alt.Chart(df)
def bar(
self,
x: X | None = None,
y: Y | None = None,
color: Color | None = None,
/,
**kwargs: Unpack[EncodeKwds],
) -> alt.Chart:
"""
Draw bar plot.
Polars does not implement plotting logic itself but instead defers to
`Altair <https://altair-viz.github.io/>`_.
`df.plot.bar(**kwargs)` is shorthand for
`alt.Chart(df).mark_bar().encode(**kwargs).interactive()`,
and is provided for convenience - for full customisability, use a plotting
library directly.
.. versionchanged:: 1.6.0
In prior versions of Polars, HvPlot was the plotting backend. If you would
like to restore the previous plotting functionality, all you need to do
is add `import hvplot.polars` at the top of your script and replace
`df.plot` with `df.hvplot`.
Parameters
----------
x
Column with x-coordinates of bars.
y
Column with y-coordinates of bars.
color
Column to color bars by.
**kwargs
Additional keyword arguments passed to Altair.
Examples
--------
>>> df = pl.DataFrame(
... {
... "day": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] * 2,
... "group": ["a"] * 7 + ["b"] * 7,
... "value": [1, 3, 2, 4, 5, 6, 1, 1, 3, 2, 4, 5, 1, 2],
... }
... )
>>> df.plot.bar(
... x="day", y="value", color="day", column="group"
... ) # doctest: +SKIP
"""
encodings: Encodings = {}
if x is not None:
encodings["x"] = x
if y is not None:
encodings["y"] = y
if color is not None:
encodings["color"] = color
return (
self._chart.mark_bar(tooltip=True)
.encode(**encodings, **kwargs)
.interactive()
)
def line(
self,
x: X | None = None,
y: Y | None = None,
color: Color | None = None,
order: Order | None = None,
/,
**kwargs: Unpack[EncodeKwds],
) -> alt.Chart:
"""
Draw line plot.
Polars does not implement plotting logic itself but instead defers to
`Altair <https://altair-viz.github.io/>`_.
`df.plot.line(**kwargs)` is shorthand for
`alt.Chart(df).mark_line().encode(**kwargs).interactive()`,
and is provided for convenience - for full customisatibility, use a plotting
library directly.
.. versionchanged:: 1.6.0
In prior versions of Polars, HvPlot was the plotting backend. If you would
like to restore the previous plotting functionality, all you need to do
is add `import hvplot.polars` at the top of your script and replace
`df.plot` with `df.hvplot`.
Parameters
----------
x
Column with x-coordinates of lines.
y
Column with y-coordinates of lines.
color
Column to color lines by.
order
Column to use for order of data points in lines.
**kwargs
Additional keyword arguments passed to Altair.
Examples
--------
>>> from datetime import date
>>> df = pl.DataFrame(
... {
... "date": [date(2020, 1, 2), date(2020, 1, 3), date(2020, 1, 4)] * 2,
... "price": [1, 4, 6, 1, 5, 2],
... "stock": ["a", "a", "a", "b", "b", "b"],
... }
... )
>>> df.plot.line(x="date", y="price", color="stock") # doctest: +SKIP
"""
encodings: Encodings = {}
if x is not None:
encodings["x"] = x
if y is not None:
encodings["y"] = y
if color is not None:
encodings["color"] = color
if order is not None:
encodings["order"] = order
return (
self._chart.mark_line(tooltip=True)
.encode(**encodings, **kwargs)
.interactive()
)
def point(
self,
x: X | None = None,
y: Y | None = None,
color: Color | None = None,
size: Size | None = None,
/,
**kwargs: Unpack[EncodeKwds],
) -> alt.Chart:
"""
Draw scatter plot.
Polars does not implement plotting logic itself but instead defers to
`Altair <https://altair-viz.github.io/>`_.
`df.plot.point(**kwargs)` is shorthand for
`alt.Chart(df).mark_point().encode(**kwargs).interactive()`,
and is provided for convenience - for full customisatibility, use a plotting
library directly.
.. versionchanged:: 1.6.0
In prior versions of Polars, HvPlot was the plotting backend. If you would
like to restore the previous plotting functionality, all you need to do
is add `import hvplot.polars` at the top of your script and replace
`df.plot` with `df.hvplot`.
Parameters
----------
x
Column with x-coordinates of points.
y
Column with y-coordinates of points.
color
Column to color points by.
size
Column which determines points' sizes.
**kwargs
Additional keyword arguments passed to Altair.
Examples
--------
>>> df = pl.DataFrame(
... {
... "length": [1, 4, 6],
... "width": [4, 5, 6],
... "species": ["setosa", "setosa", "versicolor"],
... }
... )
>>> df.plot.point(x="length", y="width", color="species") # doctest: +SKIP
"""
encodings: Encodings = {}
if x is not None:
encodings["x"] = x
if y is not None:
encodings["y"] = y
if color is not None:
encodings["color"] = color
if size is not None:
encodings["size"] = size
return (
self._chart.mark_point(tooltip=True)
.encode(
**encodings,
**kwargs,
)
.interactive()
)
# Alias to `point` because of how common it is.
scatter = point
def __getattr__(self, attr: str) -> Callable[..., alt.Chart]:
method = getattr(self._chart, f"mark_{attr}", None)
if method is None:
msg = f"Altair has no method 'mark_{attr}'"
raise AttributeError(msg)
accepts_tooltip_argument = "tooltip" in {
value.name for value in inspect.signature(method).parameters.values()
}
if accepts_tooltip_argument:
def func(**kwargs: EncodeKwds) -> alt.Chart:
return method(tooltip=True).encode(**kwargs).interactive()
else:
def func(**kwargs: EncodeKwds) -> alt.Chart:
return method().encode(**kwargs).interactive()
return func
| DataFramePlot |
python | celery__celery | celery/fixups/django.py | {
"start": 3664,
"end": 7575
} | class ____:
_db_recycles = 0
def __init__(self, app: "Celery") -> None:
self.app = app
self.db_reuse_max = self.app.conf.get('CELERY_DB_REUSE_MAX', None)
self._db = cast("DjangoDBModule", import_module('django.db'))
self._cache = import_module('django.core.cache')
self._settings = symbol_by_name('django.conf:settings')
self.interface_errors = (
symbol_by_name('django.db.utils.InterfaceError'),
)
self.DatabaseError = symbol_by_name('django.db:DatabaseError')
def django_setup(self) -> None:
import django
django.setup()
def validate_models(self) -> None:
from django.core.checks import run_checks
self.django_setup()
if not os.environ.get('CELERY_SKIP_CHECKS'):
run_checks()
def install(self) -> "DjangoWorkerFixup":
signals.beat_embedded_init.connect(self.close_database)
signals.task_prerun.connect(self.on_task_prerun)
signals.task_postrun.connect(self.on_task_postrun)
signals.worker_process_init.connect(self.on_worker_process_init)
self.close_database()
self.close_cache()
return self
def on_worker_process_init(self, **kwargs: Any) -> None:
# Child process must validate models again if on Windows,
# or if they were started using execv.
if os.environ.get('FORKED_BY_MULTIPROCESSING'):
self.validate_models()
# close connections:
# the parent process may have established these,
# so need to close them.
# calling db.close() on some DB connections will cause
# the inherited DB conn to also get broken in the parent
# process so we need to remove it without triggering any
# network IO that close() might cause.
for c in self._db.connections.all():
if c and c.connection:
self._maybe_close_db_fd(c)
# use the _ version to avoid DB_REUSE preventing the conn.close() call
self._close_database()
self.close_cache()
def _maybe_close_db_fd(self, c: "BaseDatabaseWrapper") -> None:
try:
with c.wrap_database_errors:
_maybe_close_fd(c.connection)
except self.interface_errors:
pass
def on_task_prerun(self, sender: "Task", **kwargs: Any) -> None:
"""Called before every task."""
if not getattr(sender.request, 'is_eager', False):
self.close_database()
def on_task_postrun(self, sender: "Task", **kwargs: Any) -> None:
# See https://groups.google.com/group/django-users/browse_thread/thread/78200863d0c07c6d/
if not getattr(sender.request, 'is_eager', False):
self.close_database()
self.close_cache()
def close_database(self, **kwargs: Any) -> None:
if not self.db_reuse_max:
return self._close_database()
if self._db_recycles >= self.db_reuse_max * 2:
self._db_recycles = 0
self._close_database()
self._db_recycles += 1
def _close_database(self) -> None:
for conn in self._db.connections.all():
try:
conn.close()
pool_enabled = self._settings.DATABASES.get(conn.alias, {}).get("OPTIONS", {}).get("pool")
if pool_enabled and hasattr(conn, "close_pool"):
with contextlib.suppress(KeyError):
conn.close_pool()
except self.interface_errors:
pass
except self.DatabaseError as exc:
str_exc = str(exc)
if 'closed' not in str_exc and 'not connected' not in str_exc:
raise
def close_cache(self) -> None:
try:
self._cache.close_caches()
except (TypeError, AttributeError):
pass
| DjangoWorkerFixup |
python | PrefectHQ__prefect | src/prefect/locking/protocol.py | {
"start": 78,
"end": 4240
} | class ____(Protocol):
def acquire_lock(
self,
key: str,
holder: str,
acquire_timeout: Optional[float] = None,
hold_timeout: Optional[float] = None,
) -> bool:
"""
Acquire a lock for a transaction record with the given key. Will block other
actors from updating this transaction record until the lock is
released.
Args:
key: Unique identifier for the transaction record.
holder: Unique identifier for the holder of the lock.
acquire_timeout: Max number of seconds to wait for the record to become
available if it is locked while attempting to acquire a lock. Pass 0
to attempt to acquire a lock without waiting. Blocks indefinitely by
default.
hold_timeout: Max number of seconds to hold the lock for. Holds the lock
indefinitely by default.
Returns:
bool: True if the lock was successfully acquired; False otherwise.
"""
...
async def aacquire_lock(
self,
key: str,
holder: str,
acquire_timeout: Optional[float] = None,
hold_timeout: Optional[float] = None,
) -> bool:
"""
Acquire a lock for a transaction record with the given key. Will block other
actors from updating this transaction record until the lock is
released.
Args:
key: Unique identifier for the transaction record.
holder: Unique identifier for the holder of the lock.
acquire_timeout: Max number of seconds to wait for the record to become
available if it is locked while attempting to acquire a lock. Pass 0
to attempt to acquire a lock without waiting. Blocks indefinitely by
default.
hold_timeout: Max number of seconds to hold the lock for. Holds the lock
indefinitely by default.
Returns:
bool: True if the lock was successfully acquired; False otherwise.
"""
...
def release_lock(self, key: str, holder: str) -> None:
"""
Releases the lock on the corresponding transaction record.
Args:
key: Unique identifier for the transaction record.
holder: Unique identifier for the holder of the lock. Must match the
holder provided when acquiring the lock.
"""
...
def is_locked(self, key: str) -> bool:
"""
Simple check to see if the corresponding record is currently locked.
Args:
key: Unique identifier for the transaction record.
Returns:
True is the record is locked; False otherwise.
"""
...
def is_lock_holder(self, key: str, holder: str) -> bool:
"""
Check if the current holder is the lock holder for the transaction record.
Args:
key: Unique identifier for the transaction record.
holder: Unique identifier for the holder of the lock.
Returns:
bool: True if the current holder is the lock holder; False otherwise.
"""
...
def wait_for_lock(self, key: str, timeout: Optional[float] = None) -> bool:
"""
Wait for the corresponding transaction record to become free.
Args:
key: Unique identifier for the transaction record.
timeout: Maximum time to wait. None means to wait indefinitely.
Returns:
bool: True if the lock becomes free within the timeout; False
otherwise.
"""
...
async def await_for_lock(self, key: str, timeout: Optional[float] = None) -> bool:
"""
Wait for the corresponding transaction record to become free.
Args:
key: Unique identifier for the transaction record.
timeout: Maximum time to wait. None means to wait indefinitely.
Returns:
bool: True if the lock becomes free within the timeout; False
otherwise.
"""
...
| LockManager |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_flow_runs.py | {
"start": 51575,
"end": 64786
} | class ____:
@pytest.fixture
async def paused_flow_run_waiting_for_input(
self,
session,
flow,
):
class SimpleInput(RunInput):
approved: bool
client_state = Paused(pause_key="1")
server_state = schemas.states.Paused(pause_key="1")
keyset = keyset_from_paused_state(client_state)
server_state.state_details.run_input_keyset = keyset
flow_run = await models.flow_runs.create_flow_run(
session=session,
flow_run=schemas.core.FlowRun(
flow_id=flow.id, flow_version="1.0", state=server_state
),
)
assert flow_run
await models.flow_run_input.create_flow_run_input(
session=session,
flow_run_input=schemas.core.FlowRunInput(
flow_run_id=flow_run.id,
key="paused-1-schema",
value=orjson.dumps(SimpleInput.model_json_schema()).decode(),
),
)
await session.commit()
return flow_run
@pytest.fixture
async def paused_flow_run_waiting_for_input_with_default(
self,
session,
flow,
):
class SimpleInput(RunInput):
how_many: Optional[str] = "5"
approved: Optional[bool] = True
client_state = Paused(pause_key="1")
server_state = schemas.states.Paused(pause_key="1")
keyset = keyset_from_paused_state(client_state)
server_state.state_details.run_input_keyset = keyset
flow_run = await models.flow_runs.create_flow_run(
session=session,
flow_run=schemas.core.FlowRun(
flow_id=flow.id, flow_version="1.0", state=server_state
),
)
assert flow_run
await models.flow_run_input.create_flow_run_input(
session=session,
flow_run_input=schemas.core.FlowRunInput(
flow_run_id=flow_run.id,
key="paused-1-schema",
value=orjson.dumps(SimpleInput.model_json_schema()).decode(),
),
)
await session.commit()
return flow_run
async def test_resuming_blocking_pauses(
self, blocking_paused_flow_run, client, session
):
flow_run_id = blocking_paused_flow_run.id
await client.post(
f"/flow_runs/{flow_run_id}/resume",
)
session.expire_all()
resumed_run = await models.flow_runs.read_flow_run(
session=session, flow_run_id=flow_run_id
)
assert resumed_run.state.type == "RUNNING"
async def test_resuming_nonblocking_pauses(
self, nonblocking_paused_flow_run, client, session
):
flow_run_id = nonblocking_paused_flow_run.id
await client.post(
f"/flow_runs/{flow_run_id}/resume",
)
session.expire_all()
resumed_run = await models.flow_runs.read_flow_run(
session=session, flow_run_id=flow_run_id
)
assert resumed_run.state.type == StateType.SCHEDULED
async def test_cannot_resume_nonblocking_pauses_without_deployment(
self, nonblockingpaused_flow_run_without_deployment, client, session
):
flow_run_id = nonblockingpaused_flow_run_without_deployment.id
await client.post(
f"/flow_runs/{flow_run_id}/resume",
)
session.expire_all()
resumed_run = await models.flow_runs.read_flow_run(
session=session, flow_run_id=flow_run_id
)
assert resumed_run.state.type == "PAUSED"
async def test_cannot_resume_flow_runs_without_a_state(self, flow_run, client):
flow_run_id = flow_run.id
response = await client.post(
f"/flow_runs/{flow_run_id}/resume",
)
assert response.json()["status"] == "ABORT"
async def test_cannot_resume_flow_runs_not_in_paused_state(
self, failed_flow_run_with_deployment, client, session
):
flow_run_id = failed_flow_run_with_deployment.id
response = await client.post(
f"/flow_runs/{flow_run_id}/resume",
)
assert response.json()["status"] == "ABORT"
session.expire_all()
resumed_run = await models.flow_runs.read_flow_run(
session=session, flow_run_id=flow_run_id
)
assert resumed_run.state.type == "FAILED"
async def test_resume_flow_run_waiting_for_input_without_input_succeeds_with_defaults(
self, client, paused_flow_run_waiting_for_input_with_default
):
response = await client.post(
f"/flow_runs/{paused_flow_run_waiting_for_input_with_default.id}/resume",
)
assert response.status_code == 201, response.text
assert response.json()["status"] == "ACCEPT"
async def test_resume_flow_run_waiting_for_input_without_input_fails_if_required(
self,
client,
paused_flow_run_waiting_for_input,
):
response = await client.post(
f"/flow_runs/{paused_flow_run_waiting_for_input.id}/resume",
)
assert response.status_code == 200, response.text
assert response.json()["status"] == "REJECT"
assert (
"'approved' is a required property" in response.json()["details"]["reason"]
)
assert response.json()["state"]["id"] == str(
paused_flow_run_waiting_for_input.state_id
)
async def test_cannot_resume_flow_run_waiting_for_input_missing_schema(
self,
client,
paused_flow_run_waiting_for_input,
):
response = await client.delete(
f"/flow_runs/{paused_flow_run_waiting_for_input.id}/input/paused-1-schema",
)
assert response.status_code == 204, response.text
response = await client.post(
f"/flow_runs/{paused_flow_run_waiting_for_input.id}/resume",
json={"run_input": {"approved": True}},
)
assert response.status_code == 200, response.text
assert response.json()["status"] == "REJECT"
assert response.json()["details"]["reason"] == "Run input schema not found."
assert response.json()["state"]["id"] == str(
paused_flow_run_waiting_for_input.state_id
)
async def test_cannot_resume_flow_run_waiting_for_input_schema_not_json(
self,
client,
paused_flow_run_waiting_for_input,
):
response = await client.delete(
f"/flow_runs/{paused_flow_run_waiting_for_input.id}/input/paused-1-schema",
)
assert response.status_code == 204, response.text
response = await client.post(
f"/flow_runs/{paused_flow_run_waiting_for_input.id}/input",
json=dict(
key="paused-1-schema",
value="not json",
),
)
assert response.status_code == 201, response.text
response = await client.post(
f"/flow_runs/{paused_flow_run_waiting_for_input.id}/resume",
json={"run_input": {"approved": True}},
)
assert response.status_code == 200, response.text
assert response.json()["status"] == "REJECT"
assert (
response.json()["details"]["reason"]
== "Run input schema is not valid JSON."
)
assert response.json()["state"]["id"] == str(
paused_flow_run_waiting_for_input.state_id
)
async def test_cannot_resume_flow_run_waiting_for_input_schema_fails_validation(
self,
client,
paused_flow_run_waiting_for_input,
):
response = await client.post(
f"/flow_runs/{paused_flow_run_waiting_for_input.id}/resume",
json={"run_input": {"approved": "not a bool!"}},
)
assert response.status_code == 200, response.text
assert response.json()["status"] == "REJECT"
assert (
"'not a bool!' is not of type 'boolean'"
in response.json()["details"]["reason"]
)
assert response.json()["state"]["id"] == str(
paused_flow_run_waiting_for_input.state_id
)
async def test_resume_flow_run_waiting_for_input_valid_data(
self,
client,
session,
paused_flow_run_waiting_for_input,
):
response = await client.post(
f"/flow_runs/{paused_flow_run_waiting_for_input.id}/resume",
json={"run_input": {"approved": True}},
)
assert response.status_code == 201, response.text
assert response.json()["status"] == "ACCEPT"
flow_run_input = await models.flow_run_input.read_flow_run_input(
session=session,
flow_run_id=paused_flow_run_waiting_for_input.id,
key="paused-1-response",
)
assert flow_run_input
assert orjson.loads(flow_run_input.value) == {"approved": True}
async def test_resume_flow_run_waiting_for_input_with_json_hydrated_input(
self,
session,
client,
paused_flow_run_waiting_for_input_with_default,
):
response = await client.post(
f"/flow_runs/{paused_flow_run_waiting_for_input_with_default.id}/resume",
json={
"run_input": {"how_many": {"__prefect_kind": "json", "value": '"3"'}}
},
)
assert response.status_code == 201, response.text
assert response.json()["status"] == "ACCEPT"
flow_run_input = await models.flow_run_input.read_flow_run_input(
session=session,
flow_run_id=paused_flow_run_waiting_for_input_with_default.id,
key="paused-1-response",
)
assert flow_run_input
assert orjson.loads(flow_run_input.value) == {"how_many": "3"}
assert response.json()["state"]["id"] != str(
paused_flow_run_waiting_for_input_with_default.state_id
)
async def test_resume_flow_run_waiting_for_input_with_jinja_hydrated_input(
self,
session,
client,
paused_flow_run_waiting_for_input_with_default,
):
response = await client.post(
f"/flow_runs/{paused_flow_run_waiting_for_input_with_default.id}/resume",
json={
"run_input": {
"how_many": {"__prefect_kind": "jinja", "template": "{{ 2 + 2 }}"}
}
},
)
assert response.status_code == 201
assert response.json()["status"] == "ACCEPT"
flow_run_input = await models.flow_run_input.read_flow_run_input(
session=session,
flow_run_id=paused_flow_run_waiting_for_input_with_default.id,
key="paused-1-response",
)
assert flow_run_input
assert orjson.loads(flow_run_input.value) == {"how_many": "4"}
assert response.json()["state"]["id"] != str(
paused_flow_run_waiting_for_input_with_default.state_id
)
async def test_resume_flow_run_waiting_for_input_with_workspace_variable_hydrated_input(
self,
session,
client,
paused_flow_run_waiting_for_input_with_default,
):
await models.variables.create_variable(
session,
schemas.actions.VariableCreate(name="my_variable", value="my_value"),
)
await session.commit()
response = await client.post(
f"/flow_runs/{paused_flow_run_waiting_for_input_with_default.id}/resume",
json={
"run_input": {
"how_many": {
"__prefect_kind": "workspace_variable",
"variable_name": "my_variable",
}
}
},
)
assert response.status_code == 201, str(response.content)
assert response.json()["status"] == "ACCEPT"
flow_run_input = await models.flow_run_input.read_flow_run_input(
session=session,
flow_run_id=paused_flow_run_waiting_for_input_with_default.id,
key="paused-1-response",
)
assert flow_run_input
assert orjson.loads(flow_run_input.value) == {"how_many": "my_value"}
assert response.json()["state"]["id"] != str(
paused_flow_run_waiting_for_input_with_default.state_id
)
async def test_resume_flow_run_waiting_for_input_with_malformed_dehydrated_input(
self,
client,
paused_flow_run_waiting_for_input_with_default,
):
response = await client.post(
f"/flow_runs/{paused_flow_run_waiting_for_input_with_default.id}/resume",
json={
"run_input": {
"how_many": {
"__prefect_kind": "json",
"value": '{"invalid": json}',
},
}
},
)
assert response.status_code == 200, response.text
assert response.json()["status"] == "REJECT"
assert response.json()["details"]["reason"].startswith(
"Error hydrating run input: Invalid JSON"
)
| TestResumeFlowrun |
python | walkccc__LeetCode | solutions/2593. Find Score of an Array After Marking All Elements/2593.py | {
"start": 0,
"end": 293
} | class ____:
def findScore(self, nums: list[int]) -> int:
ans = 0
seen = set()
for num, i in sorted([(num, i) for i, num in enumerate(nums)]):
if i in seen:
continue
seen.add(i - 1)
seen.add(i + 1)
seen.add(i)
ans += num
return ans
| Solution |
python | openai__openai-python | src/openai/resources/beta/realtime/sessions.py | {
"start": 21867,
"end": 22098
} | class ____:
def __init__(self, sessions: AsyncSessions) -> None:
self._sessions = sessions
self.create = async_to_streamed_response_wrapper(
sessions.create,
)
| AsyncSessionsWithStreamingResponse |
python | huggingface__transformers | src/transformers/models/mobilebert/modeling_mobilebert.py | {
"start": 44297,
"end": 48885
} | class ____(MobileBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.mobilebert = MobileBertModel(config)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
)
self.dropout = nn.Dropout(classifier_dropout)
self.classifier = nn.Linear(config.hidden_size, 1)
# Initialize weights and apply final processing
self.post_init()
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> Union[tuple[torch.Tensor], MultipleChoiceModelOutput]:
r"""
input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
1]`:
- 0 corresponds to a *sentence A* token,
- 1 corresponds to a *sentence B* token.
[What are token type IDs?](../glossary#token-type-ids)
position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
config.max_position_embeddings - 1]`.
[What are position IDs?](../glossary#position-ids)
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
model's internal embedding lookup matrix.
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
`input_ids` above)
"""
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
inputs_embeds = (
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
if inputs_embeds is not None
else None
)
outputs = self.mobilebert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
return_dict=True,
**kwargs,
)
pooled_output = outputs[1]
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
reshaped_logits = logits.view(-1, num_choices)
loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
loss = loss_fct(reshaped_logits, labels)
return MultipleChoiceModelOutput(
loss=loss,
logits=reshaped_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@auto_docstring
# Copied from transformers.models.bert.modeling_bert.BertForTokenClassification with Bert->MobileBert all-casing
| MobileBertForMultipleChoice |
python | jazzband__django-oauth-toolkit | tests/test_rest_framework.py | {
"start": 1389,
"end": 1471
} | class ____(MockView):
authentication_classes = [OAuth2Authentication]
| OAuth2View |
python | apache__airflow | providers/apache/druid/tests/unit/apache/druid/hooks/test_druid.py | {
"start": 1065,
"end": 9516
} | class ____:
def setup_method(self):
import requests_mock
session = requests.Session()
adapter = requests_mock.Adapter()
session.mount("mock", adapter)
class TestDRuidhook(DruidHook):
self.is_sql_based_ingestion = False
def get_conn_url(self, ingestion_type: IngestionType = IngestionType.BATCH):
if self.conn.schema:
conn_type = self.conn.schema
else:
conn_type = "http"
if ingestion_type == IngestionType.MSQ:
return f"{conn_type}://druid-overlord:8081/druid/v2/sql/task"
return f"{conn_type}://druid-overlord:8081/druid/indexer/v1/task"
self.db_hook = TestDRuidhook()
def test_submit_gone_wrong(self, requests_mock):
task_post = requests_mock.post(
"http://druid-overlord:8081/druid/indexer/v1/task",
text='{"task":"9f8a7359-77d4-4612-b0cd-cc2f6a3c28de"}',
)
status_check = requests_mock.get(
"http://druid-overlord:8081/druid/indexer/v1/task/9f8a7359-77d4-4612-b0cd-cc2f6a3c28de/status",
text='{"status":{"status": "FAILED"}}',
)
# The job failed for some reason
with pytest.raises(AirflowException):
self.db_hook.submit_indexing_job("Long json file")
# PGH005: false positive on ``requests_mock`` argument `called_once`
assert task_post.call_count == 1
assert status_check.call_count == 1
def test_submit_ok(self, requests_mock):
task_post = requests_mock.post(
"http://druid-overlord:8081/druid/indexer/v1/task",
status_code=200,
text='{"task":"9f8a7359-77d4-4612-b0cd-cc2f6a3c28de"}',
)
status_check = requests_mock.get(
"http://druid-overlord:8081/druid/indexer/v1/task/9f8a7359-77d4-4612-b0cd-cc2f6a3c28de/status",
text='{"status":{"status": "SUCCESS"}}',
)
# Exists just as it should
self.db_hook.submit_indexing_job("Long json file")
# PGH005: false positive on ``requests_mock`` argument `called_once`
assert task_post.call_count == 1
assert status_check.call_count == 1
def test_submit_sql_based_ingestion_ok(self, requests_mock):
task_post = requests_mock.post(
"http://druid-overlord:8081/druid/v2/sql/task",
status_code=202,
text='{"taskId":"9f8a7359-77d4-4612-b0cd-cc2f6a3c28de"}',
)
status_check = requests_mock.get(
"http://druid-overlord:8081/druid/indexer/v1/task/9f8a7359-77d4-4612-b0cd-cc2f6a3c28de/status",
text='{"status":{"status": "SUCCESS"}}',
)
# Exists just as it should
self.db_hook.submit_indexing_job("Long json file", IngestionType.MSQ)
# PGH005: false positive on ``requests_mock`` argument `called_once`
assert task_post.call_count == 1
assert status_check.call_count == 1
def test_submit_with_false_ssl_arg(self, requests_mock):
# Timeout so that all three requests are sent
self.db_hook.timeout = 1
self.db_hook.max_ingestion_time = 5
self.db_hook.verify_ssl = False
task_post = requests_mock.post(
"http://druid-overlord:8081/druid/indexer/v1/task",
text='{"task":"9f8a7359-77d4-4612-b0cd-cc2f6a3c28de"}',
)
status_check = requests_mock.get(
"http://druid-overlord:8081/druid/indexer/v1/task/9f8a7359-77d4-4612-b0cd-cc2f6a3c28de/status",
text='{"status":{"status": "RUNNING"}}',
)
shutdown_post = requests_mock.post(
"http://druid-overlord:8081/druid/indexer/v1/task/9f8a7359-77d4-4612-b0cd-cc2f6a3c28de/shutdown",
text='{"task":"9f8a7359-77d4-4612-b0cd-cc2f6a3c28de"}',
)
with pytest.raises(AirflowException):
self.db_hook.submit_indexing_job("Long json file")
assert task_post.call_count == 1
assert task_post.request_history[0].verify is False
assert status_check.call_count > 1
assert status_check.request_history[0].verify is False
assert shutdown_post.call_count == 1
assert shutdown_post.request_history[0].verify is False
def test_submit_with_true_ssl_arg(self, requests_mock):
# Timeout so that all three requests are sent
self.db_hook.timeout = 1
self.db_hook.max_ingestion_time = 5
self.db_hook.verify_ssl = True
task_post = requests_mock.post(
"http://druid-overlord:8081/druid/indexer/v1/task",
text='{"task":"9f8a7359-77d4-4612-b0cd-cc2f6a3c28de"}',
)
status_check = requests_mock.get(
"http://druid-overlord:8081/druid/indexer/v1/task/9f8a7359-77d4-4612-b0cd-cc2f6a3c28de/status",
text='{"status":{"status": "RUNNING"}}',
)
shutdown_post = requests_mock.post(
"http://druid-overlord:8081/druid/indexer/v1/task/9f8a7359-77d4-4612-b0cd-cc2f6a3c28de/shutdown",
text='{"task":"9f8a7359-77d4-4612-b0cd-cc2f6a3c28de"}',
)
with pytest.raises(AirflowException):
self.db_hook.submit_indexing_job("Long json file")
assert task_post.call_count == 1
assert task_post.request_history[0].verify is True
assert status_check.call_count > 1
assert status_check.request_history[0].verify is True
assert shutdown_post.call_count == 1
assert shutdown_post.request_history[0].verify is True
def test_submit_correct_json_body(self, requests_mock):
task_post = requests_mock.post(
"http://druid-overlord:8081/druid/indexer/v1/task",
text='{"task":"9f8a7359-77d4-4612-b0cd-cc2f6a3c28de"}',
)
status_check = requests_mock.get(
"http://druid-overlord:8081/druid/indexer/v1/task/9f8a7359-77d4-4612-b0cd-cc2f6a3c28de/status",
text='{"status":{"status": "SUCCESS"}}',
)
json_ingestion_string = """
{
"task":"9f8a7359-77d4-4612-b0cd-cc2f6a3c28de"
}
"""
self.db_hook.submit_indexing_job(json_ingestion_string)
# PGH005: false positive on ``requests_mock`` argument `called_once`
assert task_post.call_count == 1
assert status_check.call_count == 1
if task_post.called_once:
req_body = task_post.request_history[0].json()
assert req_body["task"] == "9f8a7359-77d4-4612-b0cd-cc2f6a3c28de"
def test_submit_unknown_response(self, requests_mock):
task_post = requests_mock.post(
"http://druid-overlord:8081/druid/indexer/v1/task",
text='{"task":"9f8a7359-77d4-4612-b0cd-cc2f6a3c28de"}',
)
status_check = requests_mock.get(
"http://druid-overlord:8081/druid/indexer/v1/task/9f8a7359-77d4-4612-b0cd-cc2f6a3c28de/status",
text='{"status":{"status": "UNKNOWN"}}',
)
# An unknown error code
with pytest.raises(AirflowException):
self.db_hook.submit_indexing_job("Long json file")
# PGH005: false positive on requests_mock arguments
assert task_post.call_count == 1
assert status_check.call_count == 1
def test_submit_timeout(self, requests_mock):
self.db_hook.timeout = 1
self.db_hook.max_ingestion_time = 5
task_post = requests_mock.post(
"http://druid-overlord:8081/druid/indexer/v1/task",
text='{"task":"9f8a7359-77d4-4612-b0cd-cc2f6a3c28de"}',
)
status_check = requests_mock.get(
"http://druid-overlord:8081/druid/indexer/v1/task/9f8a7359-77d4-4612-b0cd-cc2f6a3c28de/status",
text='{"status":{"status": "RUNNING"}}',
)
shutdown_post = requests_mock.post(
"http://druid-overlord:8081/druid/indexer/v1/task/9f8a7359-77d4-4612-b0cd-cc2f6a3c28de/shutdown",
text='{"task":"9f8a7359-77d4-4612-b0cd-cc2f6a3c28de"}',
)
# Because the jobs keeps running
with pytest.raises(AirflowException):
self.db_hook.submit_indexing_job("Long json file")
assert status_check.called
# PGH005: false positive on ``requests_mock`` argument `called_once`
assert task_post.call_count == 1
assert shutdown_post.call_count == 1
| TestDruidSubmitHook |
python | plotly__plotly.py | plotly/graph_objs/scattersmith/marker/_gradient.py | {
"start": 233,
"end": 4917
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattersmith.marker"
_path_str = "scattersmith.marker.gradient"
_valid_props = {"color", "colorsrc", "type", "typesrc"}
@property
def color(self):
"""
Sets the final color of the gradient fill: the center color for
radial, the right for horizontal, or the bottom for vertical.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def colorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `color`.
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["colorsrc"]
@colorsrc.setter
def colorsrc(self, val):
self["colorsrc"] = val
@property
def type(self):
"""
Sets the type of gradient used to fill the markers
The 'type' property is an enumeration that may be specified as:
- One of the following enumeration values:
['radial', 'horizontal', 'vertical', 'none']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["type"]
@type.setter
def type(self, val):
self["type"] = val
@property
def typesrc(self):
"""
Sets the source reference on Chart Studio Cloud for `type`.
The 'typesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["typesrc"]
@typesrc.setter
def typesrc(self, val):
self["typesrc"] = val
@property
def _prop_descriptions(self):
return """\
color
Sets the final color of the gradient fill: the center
color for radial, the right for horizontal, or the
bottom for vertical.
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
type
Sets the type of gradient used to fill the markers
typesrc
Sets the source reference on Chart Studio Cloud for
`type`.
"""
def __init__(
self, arg=None, color=None, colorsrc=None, type=None, typesrc=None, **kwargs
):
"""
Construct a new Gradient object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scattersmith.marker.Gradient`
color
Sets the final color of the gradient fill: the center
color for radial, the right for horizontal, or the
bottom for vertical.
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
type
Sets the type of gradient used to fill the markers
typesrc
Sets the source reference on Chart Studio Cloud for
`type`.
Returns
-------
Gradient
"""
super().__init__("gradient")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.scattersmith.marker.Gradient
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scattersmith.marker.Gradient`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("colorsrc", arg, colorsrc)
self._set_property("type", arg, type)
self._set_property("typesrc", arg, typesrc)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Gradient |
python | scipy__scipy | scipy/optimize/tests/test_trustregion.py | {
"start": 571,
"end": 4638
} | class ____:
def setup_method(self):
self.x_opt = [1.0, 1.0]
self.easy_guess = [2.0, 2.0]
self.hard_guess = [-1.2, 1.0]
def test_dogleg_accuracy(self):
# test the accuracy and the return_all option
x0 = self.hard_guess
r = minimize(rosen, x0, jac=rosen_der, hess=rosen_hess, tol=1e-8,
method='dogleg', options={'return_all': True},)
assert_allclose(x0, r['allvecs'][0])
assert_allclose(r['x'], r['allvecs'][-1])
assert_allclose(r['x'], self.x_opt)
def test_dogleg_callback(self):
# test the callback mechanism and the maxiter and return_all options
accumulator = Accumulator()
maxiter = 5
r = minimize(rosen, self.hard_guess, jac=rosen_der, hess=rosen_hess,
callback=accumulator, method='dogleg',
options={'return_all': True, 'maxiter': maxiter},)
assert_equal(accumulator.count, maxiter)
assert_equal(len(r['allvecs']), maxiter+1)
assert_allclose(r['x'], r['allvecs'][-1])
assert_allclose(sum(r['allvecs'][1:]), accumulator.accum)
def test_dogleg_user_warning(self):
with pytest.warns(RuntimeWarning,
match=r'Maximum number of iterations'):
minimize(rosen, self.hard_guess, jac=rosen_der,
hess=rosen_hess, method='dogleg',
options={'disp': True, 'maxiter': 1}, )
def test_solver_concordance(self):
# Assert that dogleg uses fewer iterations than ncg on the Rosenbrock
# test function, although this does not necessarily mean
# that dogleg is faster or better than ncg even for this function
# and especially not for other test functions.
f = rosen
g = rosen_der
h = rosen_hess
for x0 in (self.easy_guess, self.hard_guess):
r_dogleg = minimize(f, x0, jac=g, hess=h, tol=1e-8,
method='dogleg', options={'return_all': True})
r_trust_ncg = minimize(f, x0, jac=g, hess=h, tol=1e-8,
method='trust-ncg',
options={'return_all': True})
r_trust_krylov = minimize(f, x0, jac=g, hess=h, tol=1e-8,
method='trust-krylov',
options={'return_all': True})
r_ncg = minimize(f, x0, jac=g, hess=h, tol=1e-8,
method='newton-cg', options={'return_all': True})
r_iterative = minimize(f, x0, jac=g, hess=h, tol=1e-8,
method='trust-exact',
options={'return_all': True})
assert_allclose(self.x_opt, r_dogleg['x'])
assert_allclose(self.x_opt, r_trust_ncg['x'])
assert_allclose(self.x_opt, r_trust_krylov['x'])
assert_allclose(self.x_opt, r_ncg['x'])
assert_allclose(self.x_opt, r_iterative['x'])
assert_(len(r_dogleg['allvecs']) < len(r_ncg['allvecs']))
def test_trust_ncg_hessp(self):
for x0 in (self.easy_guess, self.hard_guess, self.x_opt):
r = minimize(rosen, x0, jac=rosen_der, hessp=rosen_hess_prod,
tol=1e-8, method='trust-ncg')
assert_allclose(self.x_opt, r['x'])
def test_trust_ncg_start_in_optimum(self):
r = minimize(rosen, x0=self.x_opt, jac=rosen_der, hess=rosen_hess,
tol=1e-8, method='trust-ncg')
assert_allclose(self.x_opt, r['x'])
def test_trust_krylov_start_in_optimum(self):
r = minimize(rosen, x0=self.x_opt, jac=rosen_der, hess=rosen_hess,
tol=1e-8, method='trust-krylov')
assert_allclose(self.x_opt, r['x'])
def test_trust_exact_start_in_optimum(self):
r = minimize(rosen, x0=self.x_opt, jac=rosen_der, hess=rosen_hess,
tol=1e-8, method='trust-exact')
assert_allclose(self.x_opt, r['x'])
| TestTrustRegionSolvers |
python | openai__openai-python | src/openai/types/beta/realtime/transcription_session_updated_event.py | {
"start": 266,
"end": 833
} | class ____(BaseModel):
event_id: str
"""The unique ID of the server event."""
session: TranscriptionSession
"""A new Realtime transcription session configuration.
When a session is created on the server via REST API, the session object also
contains an ephemeral key. Default TTL for keys is 10 minutes. This property is
not present when a session is updated via the WebSocket API.
"""
type: Literal["transcription_session.updated"]
"""The event type, must be `transcription_session.updated`."""
| TranscriptionSessionUpdatedEvent |
python | pypa__pip | src/pip/_internal/commands/index.py | {
"start": 956,
"end": 5243
} | class ____(IndexGroupCommand):
"""
Inspect information available from package indexes.
"""
ignore_require_venv = True
usage = """
%prog versions <package>
"""
def add_options(self) -> None:
cmdoptions.add_target_python_options(self.cmd_opts)
self.cmd_opts.add_option(cmdoptions.ignore_requires_python())
self.cmd_opts.add_option(cmdoptions.pre())
self.cmd_opts.add_option(cmdoptions.json())
self.cmd_opts.add_option(cmdoptions.no_binary())
self.cmd_opts.add_option(cmdoptions.only_binary())
index_opts = cmdoptions.make_option_group(
cmdoptions.index_group,
self.parser,
)
self.parser.insert_option_group(0, index_opts)
self.parser.insert_option_group(0, self.cmd_opts)
def handler_map(self) -> dict[str, Callable[[Values, list[str]], None]]:
return {
"versions": self.get_available_package_versions,
}
def run(self, options: Values, args: list[str]) -> int:
handler_map = self.handler_map()
# Determine action
if not args or args[0] not in handler_map:
logger.error(
"Need an action (%s) to perform.",
", ".join(sorted(handler_map)),
)
return ERROR
action = args[0]
# Error handling happens here, not in the action-handlers.
try:
handler_map[action](options, args[1:])
except PipError as e:
logger.error(e.args[0])
return ERROR
return SUCCESS
def _build_package_finder(
self,
options: Values,
session: PipSession,
target_python: TargetPython | None = None,
ignore_requires_python: bool | None = None,
) -> PackageFinder:
"""
Create a package finder appropriate to the index command.
"""
link_collector = LinkCollector.create(session, options=options)
# Pass allow_yanked=False to ignore yanked versions.
selection_prefs = SelectionPreferences(
allow_yanked=False,
allow_all_prereleases=options.pre,
ignore_requires_python=ignore_requires_python,
)
return PackageFinder.create(
link_collector=link_collector,
selection_prefs=selection_prefs,
target_python=target_python,
)
def get_available_package_versions(self, options: Values, args: list[Any]) -> None:
if len(args) != 1:
raise CommandError("You need to specify exactly one argument")
target_python = cmdoptions.make_target_python(options)
query = args[0]
with self._build_session(options) as session:
finder = self._build_package_finder(
options=options,
session=session,
target_python=target_python,
ignore_requires_python=options.ignore_requires_python,
)
versions: Iterable[Version] = (
candidate.version for candidate in finder.find_all_candidates(query)
)
if not options.pre:
# Remove prereleases
versions = (
version for version in versions if not version.is_prerelease
)
versions = set(versions)
if not versions:
raise DistributionNotFound(
f"No matching distribution found for {query}"
)
formatted_versions = [str(ver) for ver in sorted(versions, reverse=True)]
latest = formatted_versions[0]
dist = get_installed_distribution(query)
if options.json:
structured_output = {
"name": query,
"versions": formatted_versions,
"latest": latest,
}
if dist is not None:
structured_output["installed_version"] = str(dist.version)
write_output(json.dumps(structured_output))
else:
write_output(f"{query} ({latest})")
write_output("Available versions: {}".format(", ".join(formatted_versions)))
print_dist_installation_info(latest, dist)
| IndexCommand |
python | apache__airflow | providers/apache/kafka/tests/unit/apache/kafka/triggers/test_msg_queue.py | {
"start": 1715,
"end": 5215
} | class ____:
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
Connection(
conn_id="kafka_d",
conn_type="kafka",
extra=json.dumps(
{"socket.timeout.ms": 10, "bootstrap.servers": "localhost:9092", "group.id": "test_group"}
),
)
)
create_connection_without_db(
Connection(
conn_id="kafka_multi_bootstraps",
conn_type="kafka",
extra=json.dumps(
{
"socket.timeout.ms": 10,
"bootstrap.servers": "localhost:9091,localhost:9092,localhost:9093",
"group.id": "test_groups",
}
),
)
)
@pytest.mark.skipif(not AIRFLOW_V_3_0_PLUS, reason="Requires Airflow 3.0.+")
def test_trigger_serialization(self):
if get_base_airflow_version_tuple() < (3, 0, 1):
pytest.skip("This test is only for Airflow 3.0.1+")
trigger = KafkaMessageQueueTrigger(
kafka_config_id="kafka_d",
apply_function="test.noop",
topics=["noop"],
apply_function_args=[1, 2],
apply_function_kwargs={"one": 1, "two": 2},
poll_timeout=10,
poll_interval=5,
)
assert isinstance(trigger, KafkaMessageQueueTrigger)
assert isinstance(trigger, MessageQueueTrigger)
classpath, kwargs = trigger.serialize()
assert classpath == "airflow.providers.apache.kafka.triggers.await_message.AwaitMessageTrigger"
assert kwargs == {
"kafka_config_id": "kafka_d",
"apply_function": "test.noop",
"topics": ["noop"],
"apply_function_args": [1, 2],
"apply_function_kwargs": {"one": 1, "two": 2},
"poll_timeout": 10,
"poll_interval": 5,
}
@pytest.mark.skipif(not AIRFLOW_V_3_0_PLUS, reason="Requires Airflow 3.0.+")
@pytest.mark.asyncio
async def test_trigger_run_good(self, mocker):
if get_base_airflow_version_tuple() < (3, 0, 1):
pytest.skip("This test is only for Airflow 3.0.1+")
mocker.patch.object(KafkaConsumerHook, "get_consumer", return_value=MockedConsumer)
trigger = KafkaMessageQueueTrigger(
kafka_config_id="kafka_d",
apply_function="unit.apache.kafka.triggers.test_msg_queue.apply_function_true",
topics=["noop"],
poll_timeout=0.0001,
poll_interval=5,
)
task = asyncio.create_task(trigger.run().__anext__())
await asyncio.sleep(1.0)
assert task.done() is True
@pytest.mark.skipif(not AIRFLOW_V_3_0_PLUS, reason="Requires Airflow 3.0.+")
@pytest.mark.asyncio
async def test_trigger_run_bad(self, mocker):
mocker.patch.object(KafkaConsumerHook, "get_consumer", return_value=MockedConsumer)
trigger = KafkaMessageQueueTrigger(
kafka_config_id="kafka_d",
apply_function="unit.apache.kafka.triggers.test_msg_queue.apply_function_false",
topics=["noop"],
poll_timeout=0.0001,
poll_interval=5,
)
task = asyncio.create_task(trigger.run().__anext__())
await asyncio.sleep(1.0)
assert task.done() is False
| TestMessageQueueTrigger |
python | eventlet__eventlet | tests/greenthread_test.py | {
"start": 464,
"end": 2887
} | class ____(LimitedTestCase, Asserts):
def tearDown(self):
global _g_results
super().tearDown()
_g_results = []
def test_simple(self):
gt = greenthread.spawn(passthru, 1, b=2)
self.assertEqual(gt.wait(), ((1,), {'b': 2}))
self.assertEqual(_g_results, [((1,), {'b': 2})])
def test_n(self):
gt = greenthread.spawn_n(passthru, 2, b=3)
assert not gt.dead
greenthread.sleep(0)
assert gt.dead
self.assertEqual(_g_results, [((2,), {'b': 3})])
def test_kill(self):
gt = greenthread.spawn(passthru, 6)
greenthread.kill(gt)
self.assert_dead(gt)
greenthread.sleep(0.001)
self.assertEqual(_g_results, [])
greenthread.kill(gt)
self.assert_dead(gt)
def test_kill_meth(self):
gt = greenthread.spawn(passthru, 6)
gt.kill()
self.assert_dead(gt)
greenthread.sleep(0.001)
self.assertEqual(_g_results, [])
gt.kill()
self.assert_dead(gt)
def test_kill_n(self):
gt = greenthread.spawn_n(passthru, 7)
greenthread.kill(gt)
self.assert_dead(gt)
greenthread.sleep(0.001)
self.assertEqual(_g_results, [])
greenthread.kill(gt)
self.assert_dead(gt)
def test_link(self):
results = []
def link_func(g, *a, **kw):
results.append(g)
results.append(a)
results.append(kw)
gt = greenthread.spawn(passthru, 5)
gt.link(link_func, 4, b=5)
self.assertEqual(gt.wait(), ((5,), {}))
self.assertEqual(results, [gt, (4,), {'b': 5}])
def test_link_after_exited(self):
results = []
def link_func(g, *a, **kw):
results.append(g)
results.append(a)
results.append(kw)
gt = greenthread.spawn(passthru, 5)
self.assertEqual(gt.wait(), ((5,), {}))
gt.link(link_func, 4, b=5)
self.assertEqual(results, [gt, (4,), {'b': 5}])
def test_link_relinks(self):
# test that linking in a linked func doesn't cause infinite recursion.
called = []
def link_func(g):
g.link(link_func_pass)
def link_func_pass(g):
called.append(True)
gt = greenthread.spawn(passthru)
gt.link(link_func)
gt.wait()
self.assertEqual(called, [True])
| Spawn |
python | google__pytype | pytype/pytd/visitors.py | {
"start": 72482,
"end": 72643
} | class ____(Visitor):
"""Convert LateType to (unresolved) ClassType."""
def VisitLateType(self, t):
return pytd.ClassType(t.name, None)
| LateTypeToClassType |
python | matplotlib__matplotlib | lib/matplotlib/projections/polar.py | {
"start": 9391,
"end": 10302
} | class ____(mticker.Locator):
"""
Used to locate theta ticks.
This will work the same as the base locator except in the case that the
view spans the entire circle. In such cases, the previously used default
locations of every 45 degrees are returned.
"""
def __init__(self, base):
self.base = base
self.axis = self.base.axis = _AxisWrapper(self.base.axis)
def set_axis(self, axis):
self.axis = _AxisWrapper(axis)
self.base.set_axis(self.axis)
def __call__(self):
lim = self.axis.get_view_interval()
if _is_full_circle_deg(lim[0], lim[1]):
return np.deg2rad(min(lim)) + np.arange(8) * 2 * np.pi / 8
else:
return np.deg2rad(self.base())
def view_limits(self, vmin, vmax):
vmin, vmax = np.rad2deg((vmin, vmax))
return np.deg2rad(self.base.view_limits(vmin, vmax))
| ThetaLocator |
python | getsentry__sentry | tests/sentry/users/models/test_identity.py | {
"start": 212,
"end": 816
} | class ____(TestCase):
def test_get_provider(self) -> None:
integration = self.create_integration(
organization=self.organization, provider="dummy", external_id="tester_id"
)
provider_model = self.create_identity_provider(integration=integration)
register(DummyProvider)
identity_model = self.create_identity(
user=self.user, identity_provider=provider_model, external_id="identity_id"
)
provider = identity_model.get_provider()
assert provider.name == "Dummy"
assert provider.key == "dummy"
| IdentityTestCase |
python | run-llama__llama_index | llama-index-core/llama_index/core/vector_stores/types.py | {
"start": 5906,
"end": 6202
} | class ____(BaseModel):
"""
Schema for a structured request for vector store
(i.e. to be converted to a VectorStoreQuery).
Currently only used by VectorIndexAutoRetriever.
"""
query: str
filters: List[MetadataFilter]
top_k: Optional[int] = None
| VectorStoreQuerySpec |
python | huggingface__transformers | tests/quantization/fp_quant_integration/test_fp_quant.py | {
"start": 6281,
"end": 6472
} | class ____(FPQuantBaseTest):
@classmethod
def getQuantizationConfig(cls):
return FPQuantConfig(forward_dtype="nvfp4", pseudoquantization=False)
@require_qutlass
| FPQuantNVFP4Test |
python | allegroai__clearml | clearml/backend_api/services/v2_23/datasets.py | {
"start": 164434,
"end": 167101
} | class ____(Response):
"""
Response of datasets.get_schema_keys endpoint.
:param frame_keys: Frame level fields
:type frame_keys: Sequence[str]
:param roi_keys: ROI level fields
:type roi_keys: Sequence[str]
:param source_keys: Source level fields
:type source_keys: Sequence[str]
"""
_service = "datasets"
_action = "get_schema_keys"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"frame_keys": {
"description": "Frame level fields",
"items": {"type": "string"},
"type": ["array", "null"],
},
"roi_keys": {
"description": "ROI level fields",
"items": {"type": "string"},
"type": ["array", "null"],
},
"source_keys": {
"description": "Source level fields",
"items": {"type": "string"},
"type": ["array", "null"],
},
},
"type": "object",
}
def __init__(self, frame_keys=None, roi_keys=None, source_keys=None, **kwargs):
super(GetSchemaKeysResponse, self).__init__(**kwargs)
self.frame_keys = frame_keys
self.roi_keys = roi_keys
self.source_keys = source_keys
@schema_property("frame_keys")
def frame_keys(self):
return self._property_frame_keys
@frame_keys.setter
def frame_keys(self, value):
if value is None:
self._property_frame_keys = None
return
self.assert_isinstance(value, "frame_keys", (list, tuple))
self.assert_isinstance(value, "frame_keys", six.string_types, is_array=True)
self._property_frame_keys = value
@schema_property("roi_keys")
def roi_keys(self):
return self._property_roi_keys
@roi_keys.setter
def roi_keys(self, value):
if value is None:
self._property_roi_keys = None
return
self.assert_isinstance(value, "roi_keys", (list, tuple))
self.assert_isinstance(value, "roi_keys", six.string_types, is_array=True)
self._property_roi_keys = value
@schema_property("source_keys")
def source_keys(self):
return self._property_source_keys
@source_keys.setter
def source_keys(self, value):
if value is None:
self._property_source_keys = None
return
self.assert_isinstance(value, "source_keys", (list, tuple))
self.assert_isinstance(value, "source_keys", six.string_types, is_array=True)
self._property_source_keys = value
| GetSchemaKeysResponse |
python | huggingface__transformers | src/transformers/models/sam2/image_processing_sam2_fast.py | {
"start": 1820,
"end": 14970
} | class ____(ImagesKwargs, total=False):
r"""
mask_size (`dict[str, int]`, *optional*):
The size `{"height": int, "width": int}` to resize the segmentation maps to.
"""
mask_size: dict[str, int]
def _compute_stability_score(masks: "torch.Tensor", mask_threshold: float, stability_score_offset: int):
# One mask is always contained inside the other.
# Save memory by preventing unnecessary cast to torch.int64
intersections = (
(masks > (mask_threshold + stability_score_offset)).sum(-1, dtype=torch.int16).sum(-1, dtype=torch.int32)
)
unions = (masks > (mask_threshold - stability_score_offset)).sum(-1, dtype=torch.int16).sum(-1, dtype=torch.int32)
stability_scores = intersections / unions
return stability_scores
def _mask_to_rle(input_mask: "torch.Tensor"):
"""
Encodes masks the run-length encoding (RLE), in the format expected by pycoco tools.
"""
# Put in fortran order and flatten height and width
batch_size, height, width = input_mask.shape
input_mask = input_mask.permute(0, 2, 1).flatten(1)
# Compute change indices
diff = input_mask[:, 1:] ^ input_mask[:, :-1]
change_indices = diff.nonzero()
# Encode run length
out = []
for i in range(batch_size):
cur_idxs = change_indices[change_indices[:, 0] == i, 1] + 1
if len(cur_idxs) == 0:
# No changes => either all 0 or all 1
# If the entire mask is 0, RLE is [height*width] or if the entire mask is 1, RLE is [0, height*width].
if input_mask[i, 0] == 0:
out.append({"size": [height, width], "counts": [height * width]})
else:
out.append({"size": [height, width], "counts": [0, height * width]})
continue
btw_idxs = cur_idxs[1:] - cur_idxs[:-1]
counts = [] if input_mask[i, 0] == 0 else [0]
counts += [cur_idxs[0].item()] + btw_idxs.tolist() + [height * width - cur_idxs[-1].item()]
out.append({"size": [height, width], "counts": counts})
return out
def _batched_mask_to_box(masks: "torch.Tensor"):
"""
Computes the bounding boxes around the given input masks. The bounding boxes are in the XYXY format which
corresponds the following required indices:
- LEFT: left hand side of the bounding box
- TOP: top of the bounding box
- RIGHT: right of the bounding box
- BOTTOM: bottom of the bounding box
Return [0,0,0,0] for an empty mask. For input shape channel_1 x channel_2 x ... x height x width, the output shape
is channel_1 x channel_2 x ... x 4.
Args:
- masks (`torch.Tensor` of shape `(batch, nb_mask, height, width)`)
"""
# torch.max below raises an error on empty inputs, just skip in this case
if torch.numel(masks) == 0:
return torch.zeros(*masks.shape[:-2], 4, device=masks.device)
# Normalize shape to Cxheightxwidth
shape = masks.shape
height, width = shape[-2:]
# Get top and bottom edges
in_height, _ = torch.max(masks, dim=-1)
in_height_coords = in_height * torch.arange(height, device=in_height.device)[None, :]
bottom_edges, _ = torch.max(in_height_coords, dim=-1)
in_height_coords = in_height_coords + height * (~in_height)
top_edges, _ = torch.min(in_height_coords, dim=-1)
# Get left and right edges
in_width, _ = torch.max(masks, dim=-2)
in_width_coords = in_width * torch.arange(width, device=in_width.device)[None, :]
right_edges, _ = torch.max(in_width_coords, dim=-1)
in_width_coords = in_width_coords + width * (~in_width)
left_edges, _ = torch.min(in_width_coords, dim=-1)
# If the mask is empty the right edge will be to the left of the left edge.
# Replace these boxes with [0, 0, 0, 0]
empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges)
out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1)
out = out * (~empty_filter).unsqueeze(-1)
# Return to original shape
out = out.reshape(*shape[:-2], 4)
return out
def _is_box_near_crop_edge(boxes, crop_box, orig_box, atol=20.0):
"""Filter masks at the edge of a crop, but not at the edge of the original image."""
crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device)
orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device)
left, top, _, _ = crop_box
offset = torch.tensor([[left, top, left, top]], device=boxes.device)
# Check if boxes has a channel dimension
if len(boxes.shape) == 3:
offset = offset.unsqueeze(1)
boxes = (boxes + offset).float()
near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0)
near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0)
near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge)
return torch.any(near_crop_edge, dim=1)
def _pad_masks(masks, crop_box: list[int], orig_height: int, orig_width: int):
left, top, right, bottom = crop_box
if left == 0 and top == 0 and right == orig_width and bottom == orig_height:
return masks
# Coordinate transform masks
pad_x, pad_y = orig_width - (right - left), orig_height - (bottom - top)
pad = (left, pad_x - left, top, pad_y - top)
return torch.nn.functional.pad(masks, pad, value=0)
def _generate_crop_boxes(
image,
target_size: int, # Is it tuple here?
crop_n_layers: int = 0,
overlap_ratio: float = 512 / 1500,
points_per_crop: Optional[int] = 32,
crop_n_points_downscale_factor: Optional[list[int]] = 1,
) -> tuple[list[list[int]], list[int]]:
"""
Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.
Args:
image (Union[`numpy.ndarray`, `PIL.Image`, `torch.Tensor`]):
Image to generate crops for.
target_size (`int`):
Size of the smallest crop.
crop_n_layers (`int`, *optional*):
If `crops_n_layers>0`, mask prediction will be run again on crops of the image. Sets the number of layers
to run, where each layer has 2**i_layer number of image crops.
overlap_ratio (`int`, *optional*):
Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of the
image length. Later layers with more crops scale down this overlap.
points_per_crop (`int`, *optional*):
Number of points to sam2ple per crop.
crop_n_points_downscale_factor (`int`, *optional*):
The number of points-per-side sam2pled in layer n is scaled down by crop_n_points_downscale_factor**n.
input_data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format of the input image. If not provided, it will be inferred.
"""
if isinstance(image, list):
raise ValueError("Only one image is allowed for crop generation.")
original_size = image.shape[-2:]
points_grid = []
for i in range(crop_n_layers + 1):
n_points = int(points_per_crop / (crop_n_points_downscale_factor**i))
points_grid.append(_build_point_grid(n_points))
crop_boxes, layer_idxs = _generate_per_layer_crops(crop_n_layers, overlap_ratio, original_size)
cropped_images, point_grid_per_crop = _generate_crop_images(
crop_boxes, image, points_grid, layer_idxs, target_size, original_size
)
crop_boxes = torch.tensor(crop_boxes)
crop_boxes = crop_boxes.float()
points_per_crop = torch.stack(point_grid_per_crop)
points_per_crop = points_per_crop.unsqueeze(0).permute(0, 2, 1, 3)
cropped_images = torch.stack(cropped_images)
input_labels = torch.ones_like(points_per_crop[:, :, :, 0], dtype=torch.int64)
return crop_boxes, points_per_crop, cropped_images, input_labels
def _generate_per_layer_crops(crop_n_layers, overlap_ratio, original_size):
"""
Generates 2 ** (layers idx + 1) crops for each crop_n_layers. Crops are in the XYWH format : The XYWH format
consists of the following required indices:
- X: X coordinate of the top left of the bounding box
- Y: Y coordinate of the top left of the bounding box
- W: width of the bounding box
- H: height of the bounding box
"""
crop_boxes, layer_idxs = [], []
im_height, im_width = original_size
short_side = min(im_height, im_width)
# Original image
crop_boxes.append([0, 0, im_width, im_height])
layer_idxs.append(0)
for i_layer in range(crop_n_layers):
n_crops_per_side = 2 ** (i_layer + 1)
overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side))
crop_width = int(math.ceil((overlap * (n_crops_per_side - 1) + im_width) / n_crops_per_side))
crop_height = int(math.ceil((overlap * (n_crops_per_side - 1) + im_height) / n_crops_per_side))
crop_box_x0 = [int((crop_width - overlap) * i) for i in range(n_crops_per_side)]
crop_box_y0 = [int((crop_height - overlap) * i) for i in range(n_crops_per_side)]
for left, top in product(crop_box_x0, crop_box_y0):
box = [left, top, min(left + crop_width, im_width), min(top + crop_height, im_height)]
crop_boxes.append(box)
layer_idxs.append(i_layer + 1)
return crop_boxes, layer_idxs
def _build_point_grid(n_per_side: int) -> torch.Tensor:
"""Generates a 2D grid of points evenly spaced in [0,1]x[0,1]."""
offset = 1 / (2 * n_per_side)
points_one_side = torch.linspace(offset, 1 - offset, n_per_side)
points_x = torch.tile(points_one_side[None, :], (n_per_side, 1))
points_y = torch.tile(points_one_side[:, None], (1, n_per_side))
points = torch.stack([points_x, points_y], dim=-1).reshape(-1, 2)
return points
def _generate_crop_images(
crop_boxes, image, points_grid, layer_idxs, target_size, original_size, input_data_format=None
):
"""
Takes as an input bounding boxes that are used to crop the image. Based in the crops, the corresponding points are
also passed.
"""
cropped_images = []
total_points_per_crop = []
for i, crop_box in enumerate(crop_boxes):
left, top, right, bottom = crop_box
cropped_im = image[:, top:bottom, left:right]
cropped_images.append(cropped_im)
cropped_im_size = cropped_im.shape[-2:]
points_scale = torch.tensor(cropped_im_size).flip(dims=(0,)).unsqueeze(0)
points = points_grid[layer_idxs[i]] * points_scale
normalized_points = _normalize_coordinates(target_size, points, original_size)
total_points_per_crop.append(normalized_points)
return cropped_images, total_points_per_crop
def _normalize_coordinates(
target_size: int, coords: torch.Tensor, original_size: tuple[int, int], is_bounding_box=False
) -> torch.Tensor:
"""
Expects a numpy array of length 2 in the final dimension. Requires the original image size in (height, width)
format.
"""
old_height, old_width = original_size
scale = target_size * 1.0 / max(old_height, old_width)
new_height, new_width = old_height * scale, old_width * scale
new_width = int(new_width + 0.5)
new_height = int(new_height + 0.5)
coords = deepcopy(coords).float()
if is_bounding_box:
coords = coords.reshape(-1, 2, 2)
coords[..., 0] = coords[..., 0] * (new_width / old_width)
coords[..., 1] = coords[..., 1] * (new_height / old_height)
if is_bounding_box:
coords = coords.reshape(-1, 4)
return coords
def _rle_to_mask(rle: dict[str, Any]) -> torch.Tensor:
"""Compute a binary mask from an uncompressed RLE."""
height, width = rle["size"]
mask = torch.empty(height * width, dtype=bool)
idx = 0
parity = False
for count in rle["counts"]:
mask[idx : idx + count] = parity
idx += count
parity = not parity
mask = mask.reshape(width, height)
return mask.transpose(0, 1) # Reshape to original shape
def _post_process_for_mask_generation(rle_masks, iou_scores, mask_boxes, amg_crops_nms_thresh=0.7):
"""
Perform NMS (Non Maximum Suppression) on the outputs.
Args:
rle_masks (`torch.Tensor`):
binary masks in the RLE format
iou_scores (`torch.Tensor` of shape (nb_masks, 1)):
iou_scores predicted by the model
mask_boxes (`torch.Tensor`):
The bounding boxes corresponding to segmentation masks
amg_crops_nms_thresh (`float`, *optional*, defaults to 0.7):
NMS threshold.
"""
keep_by_nms = batched_nms(
boxes=mask_boxes.float(),
scores=iou_scores,
idxs=torch.zeros(mask_boxes.shape[0]),
iou_threshold=amg_crops_nms_thresh,
)
iou_scores = iou_scores[keep_by_nms]
rle_masks = [rle_masks[i] for i in keep_by_nms]
mask_boxes = mask_boxes[keep_by_nms]
masks = [_rle_to_mask(rle) for rle in rle_masks]
return masks, iou_scores, rle_masks, mask_boxes
@auto_docstring
| Sam2FastImageProcessorKwargs |
python | great-expectations__great_expectations | great_expectations/experimental/metric_repository/cloud_data_store.py | {
"start": 1460,
"end": 4134
} | class ____(DataStore[StorableTypes]):
"""DataStore implementation for GX Cloud.
Uses JSON:API https://jsonapi.org/
"""
@override
def __init__(self, context: CloudDataContext):
super().__init__(context=context)
assert context.ge_cloud_config is not None
assert self._context.ge_cloud_config is not None
self._session = create_session(
access_token=context.ge_cloud_config.access_token,
retry_count=0, # Do not retry on authentication errors
)
# Finalizer to close the session when the object is garbage collected.
# https://docs.python.org/3.11/library/weakref.html#weakref.finalize
self._finalizer = weakref.finalize(self, close_session, self._session)
def _build_payload(self, value: StorableTypes) -> str:
payload = Payload(data=value.dict(exclude={"metrics": {"__all__": {"__orig_class__"}}}))
return payload.json()
def _build_url(self, value: StorableTypes) -> str:
assert self._context.ge_cloud_config is not None
config = self._context.ge_cloud_config
if config.workspace_id:
return urllib.parse.urljoin(
config.base_url,
f"api/v1/organizations/{config.organization_id}/workspaces/{config.workspace_id}/metric-runs",
)
else:
return urllib.parse.urljoin(
config.base_url,
f"api/v1/organizations/{config.organization_id}/metric-runs",
)
@override
def add(self, value: T) -> uuid.UUID:
"""Add a value to the DataStore.
Args:
value: Value to add to the DataStore. Must be one of StorableTypes.
Returns:
id of the created resource.
"""
url = self._build_url(value)
payload = self._build_payload(value)
response = self._session.post(url=url, data=payload)
response.raise_for_status()
response_json = response.json()
return uuid.UUID(response_json["id"])
def close_session(session: requests.Session):
"""Close the session.
Used by a finalizer to close the session when the CloudDataStore is garbage collected.
This is not a bound method on the CloudDataStore class because of this note
in the Python docs (https://docs.python.org/3.11/library/weakref.html#weakref.finalize):
Note It is important to ensure that func, args and kwargs do not own any references to obj,
either directly or indirectly, since otherwise obj will never be garbage collected.
In particular, func should not be a bound method of obj.
"""
session.close()
| CloudDataStore |
python | PrefectHQ__prefect | src/prefect/settings/models/server/docket.py | {
"start": 185,
"end": 651
} | class ____(PrefectBaseSettings):
"""
Settings for controlling Docket behavior
"""
model_config: ClassVar[SettingsConfigDict] = build_settings_config(
("server", "docket")
)
name: str = Field(
default="prefect-server",
description="The name of the Docket instance.",
)
url: str = Field(
default="memory://",
description="The URL of the Redis server to use for Docket.",
)
| ServerDocketSettings |
python | getsentry__sentry | src/sentry/preprod/api/models/project_preprod_build_details_models.py | {
"start": 1721,
"end": 1910
} | class ____(BaseModel):
state: Literal[PreprodArtifactSizeMetrics.SizeAnalysisState.PROCESSING] = (
PreprodArtifactSizeMetrics.SizeAnalysisState.PROCESSING
)
| SizeInfoProcessing |
python | dagster-io__dagster | python_modules/libraries/dagster-fivetran/dagster_fivetran/translator.py | {
"start": 4539,
"end": 5077
} | class ____:
"""Represents a Fivetran destination, based on data as returned from the API."""
id: str
database: Optional[str]
service: str
@classmethod
def from_destination_details(
cls, destination_details: Mapping[str, Any]
) -> "FivetranDestination":
return cls(
id=destination_details["id"],
database=destination_details.get("config", {}).get("database"),
service=destination_details["service"],
)
@whitelist_for_serdes
@record
| FivetranDestination |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1213570,
"end": 1214550
} | class ____(sgqlc.types.Type, Node, Actor, UniformResourceLocatable):
"""A placeholder user for attribution of imported data on GitHub."""
__schema__ = github_schema
__field_names__ = ("claimant", "created_at", "database_id", "email", "updated_at")
claimant = sgqlc.types.Field("User", graphql_name="claimant")
"""The user that has claimed the data attributed to this mannequin."""
created_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="createdAt")
"""Identifies the date and time when the object was created."""
database_id = sgqlc.types.Field(Int, graphql_name="databaseId")
"""Identifies the primary key from the database."""
email = sgqlc.types.Field(String, graphql_name="email")
"""The mannequin's email on the source instance."""
updated_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="updatedAt")
"""Identifies the date and time when the object was last updated."""
| Mannequin |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-code-hierarchy/llama_index/packs/code_hierarchy/code_hierarchy.py | {
"start": 6937,
"end": 35799
} | class ____(NodeParser):
"""
Split code using a AST parser.
Add metadata about the scope of the code block and relationships between
code blocks.
"""
@classmethod
def class_name(cls) -> str:
"""Get class name."""
return "CodeHierarchyNodeParser"
language: str = Field(
description="The programming language of the code being split."
)
signature_identifiers: Dict[str, _SignatureCaptureOptions] = Field(
description=(
"A dictionary mapping the type of a split mapped to the first and last type"
" of itschildren which identify its signature."
)
)
min_characters: int = Field(
default=80,
description=(
"Minimum number of characters per chunk.Defaults to 80 because that's about"
" how long a replacement comment is in skeleton mode."
),
)
code_splitter: Optional[CodeSplitter] = Field(
description="The text splitter to use when splitting documents."
)
metadata_extractor: Optional[BaseExtractor] = Field(
default=None, description="Metadata extraction pipeline to apply to nodes."
)
callback_manager: CallbackManager = Field(
default_factory=CallbackManager, exclude=True
)
skeleton: bool = Field(
True,
description=(
"Parent nodes have the text of their child nodes replaced with a signature"
" and a comment instructing the language model to visit the child node for"
" the full text of the scope."
),
)
def __init__(
self,
language: str,
skeleton: bool = True,
signature_identifiers: Optional[Dict[str, _SignatureCaptureOptions]] = None,
code_splitter: Optional[CodeSplitter] = None,
callback_manager: Optional[CallbackManager] = None,
metadata_extractor: Optional[BaseExtractor] = None,
chunk_min_characters: int = 80,
):
callback_manager = callback_manager or CallbackManager([])
if signature_identifiers is None and language in _DEFAULT_SIGNATURE_IDENTIFIERS:
signature_identifiers = _DEFAULT_SIGNATURE_IDENTIFIERS[language]
super().__init__(
include_prev_next_rel=False,
language=language,
callback_manager=callback_manager,
metadata_extractor=metadata_extractor,
code_splitter=code_splitter,
signature_identifiers=signature_identifiers,
min_characters=chunk_min_characters,
skeleton=skeleton,
)
def _get_node_name(self, node: Node) -> str:
"""Get the name of a node."""
signature_identifier = self.signature_identifiers[node.type]
def recur(node: Node) -> str:
for child in node.children:
if child.type == signature_identifier.name_identifier:
return child.text.decode()
if child.children:
out = recur(child)
if out:
return out
return ""
return recur(node).strip()
def _get_node_signature(self, text: str, node: Node) -> str:
"""Get the signature of a node."""
signature_identifier = self.signature_identifiers[node.type]
def find_start(node: Node) -> Optional[int]:
if not signature_identifier.start_signature_types:
signature_identifier.start_signature_types = []
for st in signature_identifier.start_signature_types:
if node.type == st.type:
if st.inclusive:
return node.start_byte
return node.end_byte
for child in node.children:
out = find_start(child)
if out is not None:
return out
return None
def find_end(node: Node) -> Optional[int]:
if not signature_identifier.end_signature_types:
signature_identifier.end_signature_types = []
for st in signature_identifier.end_signature_types:
if node.type == st.type:
if st.inclusive:
return node.end_byte
return node.start_byte
for child in node.children:
out = find_end(child)
if out is not None:
return out
return None
start_byte, end_byte = find_start(node), find_end(node)
if start_byte is None:
start_byte = node.start_byte
if end_byte is None:
end_byte = node.end_byte
return bytes(text, "utf-8")[start_byte:end_byte].decode().strip()
def _chunk_node(
self,
parent: Node,
text: str,
_context_list: Optional[List[_ScopeItem]] = None,
_root: bool = True,
) -> _ChunkNodeOutput:
"""
This is really the "main" method of this class. It is recursive and recursively
chunks the text by the options identified in self.signature_identifiers.
It is ran by get_nodes_from_documents.
Args:
parent (Node): The parent node to chunk
text (str): The text of the entire document
_context_list (Optional[List[_ScopeItem]]): The scope context of the
parent node
_root (bool): Whether or not this is the root node
"""
if _context_list is None:
_context_list = []
upstream_children_documents: List[TextNode] = []
all_documents: List[TextNode] = []
# Capture any whitespace before parent.start_byte
# Very important for space sensitive languages like python
start_byte = parent.start_byte
text_bytes = bytes(text, "utf-8")
while start_byte > 0 and text_bytes[start_byte - 1 : start_byte] in (
b" ",
b"\t",
):
start_byte -= 1
# Create this node
current_chunk = text_bytes[start_byte : parent.end_byte].decode()
# Return early if the chunk is too small
if len(current_chunk) < self.min_characters and not _root:
return _ChunkNodeOutput(
this_document=None, all_documents=[], upstream_children_documents=[]
)
# TIP: This is a wonderful place to put a debug breakpoint when
# Trying to integrate a new language. Pay attention to parent.type to learn
# all the available node types and their hierarchy.
if parent.type in self.signature_identifiers or _root:
# Get the new context
if not _root:
new_context = _ScopeItem(
name=self._get_node_name(parent),
type=parent.type,
signature=self._get_node_signature(text=text, node=parent),
)
_context_list.append(new_context)
this_document = TextNode(
text=current_chunk,
metadata={
"inclusive_scopes": [cl.dict() for cl in _context_list],
"start_byte": start_byte,
"end_byte": parent.end_byte,
},
relationships={
NodeRelationship.CHILD: [],
},
)
all_documents.append(this_document)
else:
this_document = None
# Iterate over children
for child in parent.children:
if child.children:
# Recurse on the child
next_chunks = self._chunk_node(
child, text, _context_list=_context_list.copy(), _root=False
)
# If there is a this_document, then we need
# to add the children to this_document
# and flush upstream_children_documents
if this_document is not None:
# If we have been given a document, that means it's children
# are already set, so it needs to become a child of this node
if next_chunks.this_document is not None:
assert not next_chunks.upstream_children_documents, (
"next_chunks.this_document and"
" next_chunks.upstream_children_documents are exclusive."
)
this_document.relationships[NodeRelationship.CHILD].append( # type: ignore
next_chunks.this_document.as_related_node_info()
)
next_chunks.this_document.relationships[
NodeRelationship.PARENT
] = this_document.as_related_node_info()
# Otherwise, we have been given a list of
# upstream_children_documents. We need to make
# them a child of this node
else:
for d in next_chunks.upstream_children_documents:
this_document.relationships[NodeRelationship.CHILD].append( # type: ignore
d.as_related_node_info()
)
d.relationships[NodeRelationship.PARENT] = (
this_document.as_related_node_info()
)
# Otherwise we pass the children upstream
else:
# If we have been given a document, that means it's
# children are already set, so it needs to become a
# child of the next node
if next_chunks.this_document is not None:
assert not next_chunks.upstream_children_documents, (
"next_chunks.this_document and"
" next_chunks.upstream_children_documents are exclusive."
)
upstream_children_documents.append(next_chunks.this_document)
# Otherwise, we have leftover children, they need
# to become children of the next node
else:
upstream_children_documents.extend(
next_chunks.upstream_children_documents
)
# Lastly we need to maintain all documents
all_documents.extend(next_chunks.all_documents)
return _ChunkNodeOutput(
this_document=this_document,
upstream_children_documents=upstream_children_documents,
all_documents=all_documents,
)
@staticmethod
def get_code_hierarchy_from_nodes(
nodes: Sequence[BaseNode],
max_depth: int = -1,
) -> Tuple[Dict[str, Any], str]:
"""
Creates a code hierarchy appropriate to put into a tool description or context
to make it easier to search for code.
Call after `get_nodes_from_documents` and pass that output to this function.
"""
out: Dict[str, Any] = defaultdict(dict)
def get_subdict(keys: List[str]) -> Dict[str, Any]:
# Get the dictionary we are operating on
this_dict = out
for key in keys:
if key not in this_dict:
this_dict[key] = defaultdict(dict)
this_dict = this_dict[key]
return this_dict
def recur_inclusive_scope(node: BaseNode, i: int, keys: List[str]) -> None:
if "inclusive_scopes" not in node.metadata:
raise KeyError("inclusive_scopes not in node.metadata")
if i >= len(node.metadata["inclusive_scopes"]):
return
scope = node.metadata["inclusive_scopes"][i]
this_dict = get_subdict(keys)
if scope["name"] not in this_dict:
this_dict[scope["name"]] = defaultdict(dict)
if i < max_depth or max_depth == -1:
recur_inclusive_scope(node, i + 1, [*keys, scope["name"]])
def dict_to_markdown(d: Dict[str, Any], depth: int = 0) -> str:
markdown = ""
indent = " " * depth # Two spaces per depth level
for key, value in d.items():
if isinstance(value, dict): # Check if value is a dict
# Add the key with a bullet point and increase depth for nested dicts
markdown += f"{indent}- {key}\n{dict_to_markdown(value, depth + 1)}"
else:
# Handle non-dict items if necessary
markdown += f"{indent}- {key}: {value}\n"
return markdown
for node in nodes:
filepath = node.metadata["filepath"].split("/")
filepath[-1] = filepath[-1].split(".")[0]
recur_inclusive_scope(node, 0, filepath)
return out, dict_to_markdown(out)
def _parse_nodes(
self,
nodes: Sequence[BaseNode],
show_progress: bool = False,
**kwargs: Any,
) -> List[BaseNode]:
"""
The main public method of this class.
Parse documents into nodes.
"""
out: List[BaseNode] = []
try:
import tree_sitter_language_pack
except ImportError:
raise ImportError(
"Please install tree_sitter_language_pack to use CodeSplitter."
)
try:
parser = tree_sitter_language_pack.get_parser(self.language)
language = tree_sitter_language_pack.get_language(self.language)
# Construct the path to the SCM file
scm_fname = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"pytree-sitter-queries",
f"tree-sitter-{self.language}-tags.scm",
)
except Exception as e:
print(
f"Could not get parser for language {self.language}. Check "
"https://github.com/Goldziher/tree-sitter-language-pack?tab=readme-ov-file#available-languages "
"for a list of valid languages."
)
raise e # noqa: TRY201
query = None
if self.signature_identifiers is None:
assert os.path.exists(scm_fname), f"Could not find {scm_fname}"
fp = open(scm_fname)
query_scm = fp.read()
query = language.query(query_scm)
nodes_with_progress = get_tqdm_iterable(
nodes, show_progress, "Parsing documents into nodes"
)
for node in nodes_with_progress:
text = node.text
tree = parser.parse(bytes(text, "utf-8"))
if self.signature_identifiers is None:
assert query is not None
self.signature_identifiers = {}
tag_to_type = {}
captures = query.captures(tree.root_node)
for _node, _tag in captures:
tag_to_type[_tag] = _node.type
if _tag.startswith("name.definition"):
# ignore name.
parent_tag = _tag[5:]
assert parent_tag in tag_to_type
parent_type = tag_to_type[parent_tag]
if parent_type not in self.signature_identifiers:
self.signature_identifiers[parent_type] = (
_SignatureCaptureOptions(name_identifier=_node.type)
)
if (
not tree.root_node.children
or tree.root_node.children[0].type != "ERROR"
):
# Chunk the code
_chunks = self._chunk_node(tree.root_node, node.text)
assert _chunks.this_document is not None, "Root node must be a chunk"
chunks = _chunks.all_documents
# Add your metadata to the chunks here
for chunk in chunks:
chunk.metadata = {
"language": self.language,
**chunk.metadata,
**node.metadata,
}
chunk.relationships[NodeRelationship.SOURCE] = (
node.as_related_node_info()
)
if self.skeleton:
self._skeletonize_list(chunks)
# Now further split the code by lines and characters
# TODO: Test this and the relationships it creates
if self.code_splitter:
new_nodes = []
for original_node in chunks:
new_split_nodes = self.code_splitter.get_nodes_from_documents(
[original_node], show_progress=show_progress, **kwargs
)
if not new_split_nodes:
continue
# Force the first new_split_node to have the
# same id as the original_node
new_split_nodes[0].id_ = original_node.id_
# Add the UUID of the next node to the end of all nodes
for i, new_split_node in enumerate(new_split_nodes[:-1]):
new_split_node.text = (
new_split_node.text
+ "\n"
+ self._create_comment_line(new_split_nodes[i + 1], 0)
).strip()
# Add the UUID of the previous node to the beginning of all nodes
for i, new_split_node in enumerate(new_split_nodes[1:]):
new_split_node.text = (
self._create_comment_line(new_split_nodes[i])
+ new_split_node.text
).strip()
# Add the parent child info to all the new_nodes_
# derived from node
for new_split_node in new_split_nodes:
new_split_node.relationships[NodeRelationship.CHILD] = (
original_node.child_nodes
) # type: ignore
new_split_node.relationships[NodeRelationship.PARENT] = (
original_node.parent_node
) # type: ignore
# Go through chunks and replace all
# instances of node.node_id in relationships
# with new_nodes_[0].node_id
for old_node in chunks:
# Handle child nodes, which are a list
new_children = []
for old_nodes_child in old_node.child_nodes or []:
if old_nodes_child.node_id == original_node.node_id:
new_children.append(
new_split_nodes[0].as_related_node_info()
)
new_children.append(old_nodes_child)
old_node.relationships[NodeRelationship.CHILD] = (
new_children
)
# Handle parent node
if (
old_node.parent_node
and old_node.parent_node.node_id
== original_node.node_id
):
old_node.relationships[NodeRelationship.PARENT] = (
new_split_nodes[0].as_related_node_info()
)
# Now save new_nodes_
new_nodes += new_split_nodes
chunks = new_nodes
# Or just extract metadata
if self.metadata_extractor:
chunks = self.metadata_extractor.process_nodes( # type: ignore
chunks
)
out += chunks
else:
raise ValueError(f"Could not parse code with language {self.language}.")
return out
@staticmethod
def _get_indentation(text: str) -> Tuple[str, int, int]:
indent_char = None
minimum_chain = None
# Check that text is at least 1 line long
text_split = text.splitlines()
if len(text_split) == 0:
raise ValueError("Text should be at least one line long.")
for line in text_split:
stripped_line = line.lstrip()
if stripped_line:
# Get whether it's tabs or spaces
spaces_count = line.count(" ", 0, len(line) - len(stripped_line))
tabs_count = line.count("\t", 0, len(line) - len(stripped_line))
if not indent_char:
if spaces_count:
indent_char = " "
if tabs_count:
indent_char = "\t"
# Detect mixed indentation.
if spaces_count > 0 and tabs_count > 0:
raise ValueError("Mixed indentation found.")
if indent_char == " " and tabs_count > 0:
raise ValueError("Mixed indentation found.")
if indent_char == "\t" and spaces_count > 0:
raise ValueError("Mixed indentation found.")
# Get the minimum chain of indent_char
if indent_char:
char_count = line.count(
indent_char, 0, len(line) - len(stripped_line)
)
if minimum_chain is not None:
if char_count > 0:
minimum_chain = min(char_count, minimum_chain)
else:
if char_count > 0:
minimum_chain = char_count
# Handle edge case
if indent_char is None:
indent_char = " "
if minimum_chain is None:
minimum_chain = 4
# Get the first indent count
first_line = text_split[0]
first_indent_count = 0
for char in first_line:
if char == indent_char:
first_indent_count += 1
else:
break
# Return the default indent level if only one indentation level was found.
return indent_char, minimum_chain, first_indent_count // minimum_chain
@staticmethod
def _get_comment_text(node: TextNode) -> str:
"""Gets just the natural language text for a skeletonize comment."""
return f"Code replaced for brevity. See node_id {node.node_id}"
@classmethod
def _create_comment_line(cls, node: TextNode, indention_lvl: int = -1) -> str:
"""
Creates a comment line for a node.
Sometimes we don't use this in a loop because it requires recalculating
a lot of the same information. But it is handy.
"""
# Create the text to replace the child_node.text with
language = node.metadata["language"]
if language not in _COMMENT_OPTIONS:
# TODO: Create a contribution message
raise KeyError("Language not yet supported. Please contribute!")
comment_options = _COMMENT_OPTIONS[language]
(
indentation_char,
indentation_count_per_lvl,
first_indentation_lvl,
) = cls._get_indentation(node.text)
if indention_lvl != -1:
first_indentation_lvl = indention_lvl
else:
first_indentation_lvl += 1
return (
indentation_char * indentation_count_per_lvl * first_indentation_lvl
+ comment_options.comment_template.format(cls._get_comment_text(node))
+ "\n"
)
@classmethod
def _get_replacement_text(cls, child_node: TextNode) -> str:
"""
Manufactures a the replacement text to use to skeletonize a given child node.
"""
signature = child_node.metadata["inclusive_scopes"][-1]["signature"]
language = child_node.metadata["language"]
if language not in _COMMENT_OPTIONS:
# TODO: Create a contribution message
raise KeyError("Language not yet supported. Please contribute!")
comment_options = _COMMENT_OPTIONS[language]
# Create the text to replace the child_node.text with
(
indentation_char,
indentation_count_per_lvl,
first_indentation_lvl,
) = cls._get_indentation(child_node.text)
# Start with a properly indented signature
replacement_txt = (
indentation_char * indentation_count_per_lvl * first_indentation_lvl
+ signature
)
# Add brackets if necessary. Expandable in the
# future to other methods of scoping.
if comment_options.scope_method == _ScopeMethod.BRACKETS:
replacement_txt += " {\n"
replacement_txt += (
indentation_char
* indentation_count_per_lvl
* (first_indentation_lvl + 1)
+ comment_options.comment_template.format(
cls._get_comment_text(child_node)
)
+ "\n"
)
replacement_txt += (
indentation_char * indentation_count_per_lvl * first_indentation_lvl
+ "}"
)
elif comment_options.scope_method == _ScopeMethod.INDENTATION:
replacement_txt += "\n"
replacement_txt += indentation_char * indentation_count_per_lvl * (
first_indentation_lvl + 1
) + comment_options.comment_template.format(
cls._get_comment_text(child_node)
)
elif comment_options.scope_method == _ScopeMethod.HTML_END_TAGS:
tag_name = child_node.metadata["inclusive_scopes"][-1]["name"]
end_tag = f"</{tag_name}>"
replacement_txt += "\n"
replacement_txt += (
indentation_char
* indentation_count_per_lvl
* (first_indentation_lvl + 1)
+ comment_options.comment_template.format(
cls._get_comment_text(child_node)
)
+ "\n"
)
replacement_txt += (
indentation_char * indentation_count_per_lvl * first_indentation_lvl
+ end_tag
)
else:
raise KeyError(f"Unrecognized enum value {comment_options.scope_method}")
return replacement_txt
@classmethod
def _skeletonize(cls, parent_node: TextNode, child_node: TextNode) -> None:
"""WARNING: In Place Operation."""
# Simple protection clauses
if child_node.text not in parent_node.text:
raise ValueError("The child text is not contained inside the parent text.")
if child_node.node_id not in (c.node_id for c in parent_node.child_nodes or []):
raise ValueError("The child node is not a child of the parent node.")
# Now do the replacement
replacement_text = cls._get_replacement_text(child_node=child_node)
index = parent_node.text.find(child_node.text)
# If the text is found, replace only the first occurrence
if index != -1:
parent_node.text = (
parent_node.text[:index]
+ replacement_text
+ parent_node.text[index + len(child_node.text) :]
)
@classmethod
def _skeletonize_list(cls, nodes: List[TextNode]) -> None:
# Create a convenient map for mapping node id's to nodes
node_id_map = {n.node_id: n for n in nodes}
def recur(node: TextNode) -> None:
# If any children exist, skeletonize ourselves, starting at the root DFS
for child in node.child_nodes or []:
child_node = node_id_map[child.node_id]
cls._skeletonize(parent_node=node, child_node=child_node)
recur(child_node)
# Iterate over root nodes and recur
for n in nodes:
if n.parent_node is None:
recur(n)
| CodeHierarchyNodeParser |
python | falconry__falcon | tests/test_before_hooks.py | {
"start": 2647,
"end": 2918
} | class ____(WrappedRespondersResource):
@falcon.before(validate_param, 'x', maxval=1000)
def on_get(self, req, resp):
pass
def on_put(self, req, resp):
# Test passing no extra args
super().on_put(req, resp)
| WrappedRespondersResourceChild |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/sparse_ops/sparse_ops_test.py | {
"start": 31474,
"end": 39565
} | class ____(test_util.TensorFlowTestCase):
# [[1, ?, 2]
# [?, 3, ?]]
# where ? is implicitly-zero.
ind = np.array([[0, 0], [0, 2], [1, 1]]).astype(np.int64)
vals = np.array([1, 1, 1]).astype(np.int32)
dense_shape = np.array([2, 3]).astype(np.int64)
def _compare(self, sp_t, reduction_axes, ndims, keep_dims, do_sum):
densified = self.evaluate(sparse_ops.sparse_tensor_to_dense(sp_t))
np_ans = densified
if reduction_axes is None:
if do_sum:
np_ans = np.sum(np_ans, keepdims=keep_dims)
else:
np_ans = np.max(np_ans, keepdims=keep_dims)
else:
if not isinstance(reduction_axes, list): # Single scalar.
reduction_axes = [reduction_axes]
reduction_axes = np.array(reduction_axes).astype(np.int32)
# Handles negative axes.
reduction_axes = (reduction_axes + ndims) % ndims
# Loop below depends on sorted.
reduction_axes.sort()
for ra in reduction_axes.ravel()[::-1]:
if do_sum:
np_ans = np.sum(np_ans, axis=ra, keepdims=keep_dims)
else:
np_ans = np.max(np_ans, axis=ra, keepdims=keep_dims)
with self.cached_session():
if do_sum:
tf_dense_ans = sparse_ops.sparse_reduce_sum(sp_t, reduction_axes,
keep_dims)
else:
tf_dense_ans = sparse_ops.sparse_reduce_max(sp_t, reduction_axes,
keep_dims)
out_dense = self.evaluate(tf_dense_ans)
if do_sum:
tf_sparse_ans = sparse_ops.sparse_reduce_sum_sparse(sp_t,
reduction_axes,
keep_dims)
else:
tf_sparse_ans = sparse_ops.sparse_reduce_max_sparse(sp_t,
reduction_axes,
keep_dims)
# Convert to dense for comparison purposes.
out_sparse = sparse_ops.sparse_tensor_to_dense(tf_sparse_ans)
self.assertAllClose(np_ans, out_dense)
self.assertAllClose(np_ans, out_sparse)
def _compare_all(self, sp_t, reduction_axes, ndims):
self._compare(sp_t, reduction_axes, ndims, False, False)
self._compare(sp_t, reduction_axes, ndims, False, True)
self._compare(sp_t, reduction_axes, ndims, True, False)
self._compare(sp_t, reduction_axes, ndims, True, True)
# (TODO:b/133851381): Re-enable this test.
def disabledtestSimpleAndRandomInputs(self):
if np.__version__ == "1.13.0":
self.skipTest("numpy 1.13.0 bug")
sp_t = sparse_tensor.SparseTensor(self.ind, self.vals, self.dense_shape)
with test_util.force_cpu():
self._compare_all(sp_t, None, ndims=2)
self._compare_all(sp_t, 0, ndims=2)
self._compare_all(sp_t, [1], ndims=2)
self._compare_all(sp_t, [0, 1], ndims=2)
self._compare_all(sp_t, [1, 0], ndims=2)
self._compare_all(sp_t, [-1], ndims=2)
self._compare_all(sp_t, [1, -2], ndims=2)
np.random.seed(1618)
test_dims = [(1618, 1, 11, 7, 1), (1,), (1, 1, 1)]
with test_util.force_cpu():
for dims in test_dims:
sp_t, unused_nnz = _sparsify(np.random.randn(*dims))
# reduce all using None
self._compare_all(sp_t, None, ndims=len(dims))
# reduce random axes from 1D to N-D
for d in range(1, len(dims) + 1):
axes = np.random.choice(len(dims), size=d, replace=False).tolist()
self._compare_all(sp_t, axes, ndims=len(dims))
def testInvalidAxes(self):
sp_t = sparse_tensor.SparseTensor(self.ind, self.vals, self.dense_shape)
with test_util.force_cpu():
with self.assertRaisesOpError("Invalid reduction dimension -3"):
self.evaluate(sparse_ops.sparse_reduce_sum(sp_t, -3))
with self.assertRaisesOpError("Invalid reduction dimension 2"):
self.evaluate(sparse_ops.sparse_reduce_sum(sp_t, 2))
with self.assertRaisesOpError("Invalid reduction dimension -3"):
self.evaluate(sparse_ops.sparse_reduce_max(sp_t, -3))
with self.assertRaisesOpError("Invalid reduction dimension 2"):
self.evaluate(sparse_ops.sparse_reduce_max(sp_t, 2))
@test_util.run_deprecated_v1
def testGradient(self):
np.random.seed(8161)
test_dims = [(11, 1, 5, 7, 1), (2, 2)]
with self.session(use_gpu=False):
for dims in test_dims:
sp_t, nnz = _sparsify(np.random.randn(*dims))
# reduce random axes from 1D to N-D
for d in range(1, len(dims) + 1):
axes = np.random.choice(len(dims), size=d, replace=False).tolist()
reduced = sparse_ops.sparse_reduce_sum(sp_t, axes)
err = gradient_checker.compute_gradient_error(
sp_t.values, (nnz,), reduced,
self.evaluate(reduced).shape)
self.assertLess(err, 1e-3)
# Tests for negative axes.
reduced = sparse_ops.sparse_reduce_sum(sp_t, -1)
err = gradient_checker.compute_gradient_error(
sp_t.values, (nnz,), reduced,
self.evaluate(reduced).shape)
self.assertLess(err, 1e-3)
def _testSparseReduceShape(self, sp_t, reduction_axes, ndims, keep_dims,
do_sum):
densified = self.evaluate(sparse_ops.sparse_tensor_to_dense(sp_t))
np_op = np.sum
tf_op = sparse_ops.sparse_reduce_sum
if not do_sum:
np_op = np.max
tf_op = sparse_ops.sparse_reduce_max
np_ans = densified
if reduction_axes is None:
np_ans = np_op(np_ans, keepdims=keep_dims)
else:
if not isinstance(reduction_axes, list): # Single scalar.
reduction_axes = [reduction_axes]
reduction_axes = np.array(reduction_axes).astype(np.int32)
# Handles negative axes.
reduction_axes = (reduction_axes + ndims) % ndims
# Loop below depends on sorted.
reduction_axes.sort()
for ra in reduction_axes.ravel()[::-1]:
np_ans = np_op(np_ans, axis=ra, keepdims=keep_dims)
tf_ans = tf_op(sp_t, reduction_axes, keep_dims)
self.assertAllEqual(np_ans.shape, tf_ans.get_shape().as_list())
# (TODO:b/133851381): Re-enable this test
def disabledtestSparseReduceSumOrMaxShape(self):
sp_t = sparse_tensor.SparseTensor(self.ind, self.vals, self.dense_shape)
with test_util.force_cpu():
for do_sum in [True, False]:
for keep_dims in [True, False]:
self._testSparseReduceShape(sp_t, None, 2, keep_dims, do_sum)
self._testSparseReduceShape(sp_t, 0, 2, keep_dims, do_sum)
self._testSparseReduceShape(sp_t, [1], 2, keep_dims, do_sum)
self._testSparseReduceShape(sp_t, [0, 1], 2, keep_dims, do_sum)
self._testSparseReduceShape(sp_t, [1, 0], 2, keep_dims, do_sum)
self._testSparseReduceShape(sp_t, [-1], 2, keep_dims, do_sum)
self._testSparseReduceShape(sp_t, [1, -2], 2, keep_dims, do_sum)
def testIntegerOverflow(self):
with self.cached_session(use_gpu=False):
with self.assertRaises(errors.InvalidArgumentError):
res = sparse_ops.gen_sparse_ops.sparse_reduce_max(
input_indices=[[1, 2], [3, 4]],
input_shape=[2**32, 2**31],
input_values=[1, 3],
reduction_axes=[0],
keep_dims=False,
name=None)
self.evaluate(res)
with self.assertRaises(errors.InvalidArgumentError):
res = sparse_ops.gen_sparse_ops.sparse_reduce_max_sparse(
input_indices=[[1, 2], [3, 4]],
input_shape=[2**32, 2**31],
input_values=[1, 3],
reduction_axes=[0],
keep_dims=False,
name=None)
self.evaluate(res)
with self.assertRaises(errors.InvalidArgumentError):
res = sparse_ops.gen_sparse_ops.sparse_reduce_sum(
input_indices=[[1, 2], [3, 4]],
input_shape=[2**32, 2**31],
input_values=[1, 3],
reduction_axes=[0],
keep_dims=False,
name=None)
self.evaluate(res)
| SparseReduceTest |
python | getsentry__sentry | src/sentry/integrations/base.py | {
"start": 3429,
"end": 4546
} | class ____(StrEnum):
"""
IntegrationFeatures are used for marking supported features on an
integration. Features are marked on the IntegrationProvider itself, as well
as used within the FeatureDescription.
NOTE: Features in this list that are gated by an organization feature flag
*must* match the suffix of the organization feature flag name.
"""
ALERT_RULE = "alert-rule"
CHAT_UNFURL = "chat-unfurl"
COMMITS = "commits"
ENTERPRISE_ALERT_RULE = "enterprise-alert-rule"
ENTERPRISE_INCIDENT_MANAGEMENT = "enterprise-incident-management"
INCIDENT_MANAGEMENT = "incident-management"
ISSUE_BASIC = "issue-basic"
ISSUE_SYNC = "issue-sync"
MOBILE = "mobile"
SERVERLESS = "serverless"
TICKET_RULES = "ticket-rules"
STACKTRACE_LINK = "stacktrace-link"
CODEOWNERS = "codeowners"
USER_MAPPING = "user-mapping"
CODING_AGENT = "coding-agent"
# features currently only existing on plugins:
DATA_FORWARDING = "data-forwarding"
SESSION_REPLAY = "session-replay"
DEPLOYMENT = "deployment"
# Integration Types
| IntegrationFeatures |
python | wandb__wandb | wandb/filesync/step_upload.py | {
"start": 1491,
"end": 1664
} | class ____(NamedTuple):
job: RequestUpload
exc: Optional[BaseException]
Event = Union[RequestUpload, RequestCommitArtifact, RequestFinish, EventJobDone]
| EventJobDone |
python | pytorch__pytorch | benchmarks/functional_autograd_benchmark/torchvision_models.py | {
"start": 21856,
"end": 30767
} | class ____(nn.Module):
"""This class computes the loss for DETR.
The process happens in two steps:
1) we compute hungarian assignment between ground truth boxes and the outputs of the model
2) we supervise each pair of matched ground-truth / prediction (supervise class and box)
"""
def __init__(self, num_classes, matcher, weight_dict, eos_coef, losses):
"""Create the criterion.
Parameters:
num_classes: number of object categories, omitting the special no-object category
matcher: module able to compute a matching between targets and proposals
weight_dict: dict containing as key the names of the losses and as values their relative weight.
eos_coef: relative classification weight applied to the no-object category
losses: list of all the losses to be applied. See get_loss for list of available losses.
"""
super().__init__()
self.num_classes = num_classes
self.matcher = matcher
self.weight_dict = weight_dict
self.eos_coef = eos_coef
self.losses = losses
empty_weight = torch.ones(self.num_classes + 1)
empty_weight[-1] = self.eos_coef
self.register_buffer("empty_weight", empty_weight)
def loss_labels(self, outputs, targets, indices, num_boxes, log=True):
"""Classification loss (NLL)
targets dicts must contain the key "labels" containing a tensor of dim [nb_target_boxes]
"""
assert "pred_logits" in outputs
src_logits = outputs["pred_logits"]
idx = self._get_src_permutation_idx(indices)
target_classes_o = torch.cat(
[t["labels"][J] for t, (_, J) in zip(targets, indices)]
)
target_classes = torch.full(
src_logits.shape[:2],
self.num_classes,
dtype=torch.int64,
device=src_logits.device,
)
target_classes[idx] = target_classes_o
loss_ce = F.cross_entropy(
src_logits.transpose(1, 2), target_classes, self.empty_weight
)
losses = {"loss_ce": loss_ce}
if log:
# TODO this should probably be a separate loss, not hacked in this one here
losses["class_error"] = 100 - accuracy(src_logits[idx], target_classes_o)[0]
return losses
@torch.no_grad()
def loss_cardinality(self, outputs, targets, indices, num_boxes):
"""Compute the cardinality error, ie the absolute error in the number of predicted non-empty boxes
This is not really a loss, it is intended for logging purposes only. It doesn't propagate gradients
"""
pred_logits = outputs["pred_logits"]
device = pred_logits.device
tgt_lengths = torch.as_tensor(
[len(v["labels"]) for v in targets], device=device
)
# Count the number of predictions that are NOT "no-object" (which is the last class)
card_pred = (pred_logits.argmax(-1) != pred_logits.shape[-1] - 1).sum(1)
card_err = F.l1_loss(card_pred.float(), tgt_lengths.float())
losses = {"cardinality_error": card_err}
return losses
def loss_boxes(self, outputs, targets, indices, num_boxes):
"""Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss
targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4]
The target boxes are expected in format (center_x, center_y, h, w), normalized by the image size.
"""
assert "pred_boxes" in outputs
idx = self._get_src_permutation_idx(indices)
src_boxes = outputs["pred_boxes"][idx]
target_boxes = torch.cat(
[t["boxes"][i] for t, (_, i) in zip(targets, indices)], dim=0
)
loss_bbox = F.l1_loss(src_boxes, target_boxes, reduction="none")
losses = {}
losses["loss_bbox"] = loss_bbox.sum() / num_boxes
loss_giou = 1 - torch.diag(
generalized_box_iou(
box_cxcywh_to_xyxy(src_boxes), box_cxcywh_to_xyxy(target_boxes)
)
)
losses["loss_giou"] = loss_giou.sum() / num_boxes
return losses
def loss_masks(self, outputs, targets, indices, num_boxes):
"""Compute the losses related to the masks: the focal loss and the dice loss.
targets dicts must contain the key "masks" containing a tensor of dim [nb_target_boxes, h, w]
"""
assert "pred_masks" in outputs
src_idx = self._get_src_permutation_idx(indices)
tgt_idx = self._get_tgt_permutation_idx(indices)
src_masks = outputs["pred_masks"]
# TODO use valid to mask invalid areas due to padding in loss
target_masks, valid = nested_tensor_from_tensor_list( # noqa: F821
[t["masks"] for t in targets]
).decompose()
target_masks = target_masks.to(src_masks)
src_masks = src_masks[src_idx]
# upsample predictions to the target size
src_masks = interpolate( # noqa: F821
src_masks[:, None],
size=target_masks.shape[-2:],
mode="bilinear",
align_corners=False,
)
src_masks = src_masks[:, 0].flatten(1)
target_masks = target_masks[tgt_idx].flatten(1)
losses = {
"loss_mask": sigmoid_focal_loss( # noqa: F821
src_masks, target_masks, num_boxes
), # noqa: F821
"loss_dice": dice_loss(src_masks, target_masks, num_boxes), # noqa: F821
}
return losses
def _get_src_permutation_idx(self, indices):
# permute predictions following indices
batch_idx = torch.cat(
[torch.full_like(src, i) for i, (src, _) in enumerate(indices)]
)
src_idx = torch.cat([src for (src, _) in indices])
return batch_idx, src_idx
def _get_tgt_permutation_idx(self, indices):
# permute targets following indices
batch_idx = torch.cat(
[torch.full_like(tgt, i) for i, (_, tgt) in enumerate(indices)]
)
tgt_idx = torch.cat([tgt for (_, tgt) in indices])
return batch_idx, tgt_idx
def get_loss(self, loss, outputs, targets, indices, num_boxes, **kwargs):
loss_map = {
"labels": self.loss_labels,
"cardinality": self.loss_cardinality,
"boxes": self.loss_boxes,
"masks": self.loss_masks,
}
assert loss in loss_map, f"do you really want to compute {loss} loss?"
return loss_map[loss](outputs, targets, indices, num_boxes, **kwargs)
def forward(self, outputs, targets):
"""This performs the loss computation.
Parameters:
outputs: dict of tensors, see the output specification of the model for the format
targets: list of dicts, such that len(targets) == batch_size.
The expected keys in each dict depends on the losses applied, see each loss' doc
"""
outputs_without_aux = {k: v for k, v in outputs.items() if k != "aux_outputs"}
# Retrieve the matching between the outputs of the last layer and the targets
indices = self.matcher(outputs_without_aux, targets)
# Compute the average number of target boxes across all nodes, for normalization purposes
num_boxes = sum(len(t["labels"]) for t in targets)
num_boxes = torch.as_tensor(
[num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device
)
if is_dist_avail_and_initialized():
torch.distributed.all_reduce(num_boxes)
num_boxes = torch.clamp(num_boxes / get_world_size(), min=1).item()
# Compute all the requested losses
losses = {}
for loss in self.losses:
losses.update(self.get_loss(loss, outputs, targets, indices, num_boxes))
# In case of auxiliary losses, we repeat this process with the output of each intermediate layer.
if "aux_outputs" in outputs:
for i, aux_outputs in enumerate(outputs["aux_outputs"]):
indices = self.matcher(aux_outputs, targets)
for loss in self.losses:
if loss == "masks":
# Intermediate masks losses are too costly to compute, we ignore them.
continue
kwargs = {}
if loss == "labels":
# Logging is enabled only for the last layer
kwargs = {"log": False}
l_dict = self.get_loss(
loss, aux_outputs, targets, indices, num_boxes, **kwargs
)
l_dict = {k + f"_{i}": v for k, v in l_dict.items()}
losses.update(l_dict)
return losses
| SetCriterion |
python | doocs__leetcode | solution/0000-0099/0013.Roman to Integer/Solution.py | {
"start": 0,
"end": 224
} | class ____:
def romanToInt(self, s: str) -> int:
d = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
return sum((-1 if d[a] < d[b] else 1) * d[a] for a, b in pairwise(s)) + d[s[-1]]
| Solution |
python | Pylons__pyramid | tests/test_session.py | {
"start": 10731,
"end": 12576
} | class ____(SharedCookieSessionTests, unittest.TestCase):
def _makeOne(self, request, **kw):
from pyramid.session import BaseCookieSessionFactory
serializer = DummySerializer()
return BaseCookieSessionFactory(serializer, **kw)(request)
def _serialize(self, value):
return base64.b64encode(json.dumps(value).encode('utf-8'))
def test_reissue_not_triggered(self):
import time
request = testing.DummyRequest()
cookieval = self._serialize((time.time(), 0, {'state': 1}))
request.cookies['session'] = cookieval
session = self._makeOne(request, reissue_time=1)
self.assertEqual(session['state'], 1)
self.assertFalse(session._dirty)
def test_reissue_never(self):
request = testing.DummyRequest()
cookieval = self._serialize((0, 0, {'state': 1}))
request.cookies['session'] = cookieval
session = self._makeOne(request, reissue_time=None, timeout=None)
self.assertEqual(session['state'], 1)
self.assertFalse(session._dirty)
def test_reissue_str_triggered(self):
import time
request = testing.DummyRequest()
cookieval = self._serialize((time.time() - 2, 0, {'state': 1}))
request.cookies['session'] = cookieval
session = self._makeOne(request, reissue_time='0')
self.assertEqual(session['state'], 1)
self.assertTrue(session._dirty)
def test_reissue_invalid(self):
request = testing.DummyRequest()
self.assertRaises(
ValueError, self._makeOne, request, reissue_time='invalid value'
)
def test_cookie_max_age_invalid(self):
request = testing.DummyRequest()
self.assertRaises(
ValueError, self._makeOne, request, max_age='invalid value'
)
| TestBaseCookieSession |
python | vyperlang__vyper | vyper/semantics/types/function.py | {
"start": 1247,
"end": 1363
} | class ____:
name: str
typ: VyperType
ast_source: Optional[vy_ast.VyperNode] = None
@dataclass
| _FunctionArg |
python | sqlalchemy__sqlalchemy | test/sql/test_operators.py | {
"start": 3384,
"end": 3495
} | class ____(operators.ColumnOperators):
def operate(self, op, *other, **kwargs):
return op
| LoopOperate |
python | ray-project__ray | python/ray/dashboard/modules/metrics/dashboards/common.py | {
"start": 810,
"end": 999
} | class ____(Enum):
GRAPH = GRAPH_TARGET_TEMPLATE
HEATMAP = HEATMAP_TARGET_TEMPLATE
HISTOGRAM_BAR_CHART = HISTOGRAM_BAR_CHART_TARGET_TEMPLATE
@DeveloperAPI
@dataclass
| TargetTemplate |
python | django__django | tests/model_fields/test_jsonfield.py | {
"start": 50687,
"end": 51985
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.msg = (
"Using None as the right-hand side of an exact lookup on JSONField to mean "
"JSON scalar 'null' is deprecated. Use JSONNull() instead (or use the "
"__isnull lookup if you meant SQL NULL)."
)
cls.obj = NullableJSONModel.objects.create(value=JSONNull())
def test_filter(self):
with self.assertWarnsMessage(RemovedInDjango70Warning, self.msg):
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value=None), [self.obj]
)
def test_annotation_q_filter(self):
qs = NullableJSONModel.objects.annotate(
has_empty_data=Q(value__isnull=True) | Q(value=None)
).filter(has_empty_data=True)
with self.assertWarnsMessage(RemovedInDjango70Warning, self.msg):
self.assertSequenceEqual(qs, [self.obj])
def test_case_when(self):
qs = NullableJSONModel.objects.annotate(
has_json_null=Case(When(value=None, then=Value(True)), default=Value(False))
).filter(has_json_null=True)
with self.assertWarnsMessage(RemovedInDjango70Warning, self.msg):
self.assertSequenceEqual(qs, [self.obj])
| JSONExactNoneDeprecationTests |
python | great-expectations__great_expectations | great_expectations/data_context/store/json_site_store.py | {
"start": 446,
"end": 2922
} | class ____(Store):
"""
A JsonSiteStore manages the JSON artifacts of our renderers, which allows us to render them into final views in HTML by GX Cloud.
""" # noqa: E501 # FIXME CoP
def __init__(self, store_backend=None, runtime_environment=None, store_name=None) -> None:
if store_backend is not None:
store_backend_module_name = store_backend.get(
"module_name", "great_expectations.data_context.store"
)
store_backend_class_name = store_backend.get("class_name", "InMemoryStoreBackend")
verify_dynamic_loading_support(module_name=store_backend_module_name)
# TODO: GG 20220815 loaded store_backend_class is not used remove this if not needed
_ = load_class(store_backend_class_name, store_backend_module_name)
super().__init__(
store_backend=store_backend,
runtime_environment=runtime_environment,
store_name=store_name,
)
# Gather the call arguments of the present function (include the "module_name" and add the "class_name"), filter # noqa: E501 # FIXME CoP
# out the Falsy values, and set the instance "_config" variable equal to the resulting dictionary. # noqa: E501 # FIXME CoP
self._config = {
"store_backend": store_backend,
"runtime_environment": runtime_environment,
"store_name": store_name,
"module_name": self.__class__.__module__,
"class_name": self.__class__.__name__,
}
filter_properties_dict(properties=self._config, clean_falsy=True, inplace=True)
@override
@staticmethod
def gx_cloud_response_json_to_object_dict(response_json: Dict) -> Dict:
"""
This method takes full json response from GX cloud and outputs a dict appropriate for
deserialization into a GX object
"""
ge_cloud_json_site_id = response_json["data"]["id"]
json_site_dict = response_json["data"]["attributes"]["rendered_data_doc"]
json_site_dict["id"] = ge_cloud_json_site_id
return json_site_dict
def serialize(self, value): # type: ignore[explicit-override] # FIXME
return value.to_json_dict()
def deserialize(self, value): # type: ignore[explicit-override] # FIXME
return RenderedDocumentContent(**loads(value))
@property
@override
def config(self) -> dict:
return self._config
| JsonSiteStore |
python | kamyu104__LeetCode-Solutions | Python/all-oone-data-structure.py | {
"start": 44,
"end": 249
} | class ____(object):
"""
double linked list node
"""
def __init__(self, value, keys):
self.value = value
self.keys = keys
self.prev = None
self.next = None
| Node |
python | huggingface__transformers | tests/models/deepseek_vl/test_image_processing_deepseek_vl.py | {
"start": 1201,
"end": 2961
} | class ____:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
image_size=18,
min_resolution=30,
max_resolution=400,
do_resize=True,
size=None,
do_normalize=True,
image_mean=[0.5, 0.5, 0.5],
image_std=[0.5, 0.5, 0.5],
):
size = size if size is not None else {"height": 18, "width": 18}
self.parent = parent
self.batch_size = batch_size
self.num_channels = num_channels
self.image_size = image_size
self.min_resolution = min_resolution
self.max_resolution = max_resolution
self.do_resize = do_resize
self.size = size
self.do_normalize = do_normalize
self.image_mean = image_mean
self.image_std = image_std
def prepare_image_processor_dict(self):
return {
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_normalize": self.do_normalize,
"do_resize": self.do_resize,
"size": self.size,
}
# Ignore copy
def expected_output_image_shape(self, images):
max_size = max(self.size["height"], self.size["width"])
return self.num_channels, max_size, max_size
def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
return prepare_image_inputs(
batch_size=self.batch_size,
num_channels=self.num_channels,
min_resolution=self.min_resolution,
max_resolution=self.max_resolution,
equal_resolution=equal_resolution,
numpify=numpify,
torchify=torchify,
)
@require_torch
@require_vision
| DeepseekVLImageProcessingTester |
python | mkdocs__mkdocs | mkdocs/tests/config/config_options_legacy_tests.py | {
"start": 54423,
"end": 54967
} | class ____(TestCase):
def test_copy(self):
copy.deepcopy(
base.LegacyConfig(
(('foo', c.MarkdownExtensions()),),
),
)
copy.deepcopy(self.get_config(IpAddressTest.Schema, {'option': '1.2.3.4:5678'}))
copy.deepcopy(IpAddressTest.Schema)
copy.deepcopy(base.get_schema(IpAddressTest.Schema))
copy.deepcopy(self.get_config(EditURITest.Schema, {}))
copy.deepcopy(EditURITest.Schema)
copy.deepcopy(base.get_schema(EditURITest.Schema))
| SchemaTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDictReadOnly2.py | {
"start": 4256,
"end": 4396
} | class ____(TypedDict):
x: ReadOnly[Required[int]]
y: ReadOnly[NotRequired[int]]
# This should generate an error for x but not y.
| TD_B2 |
python | allegroai__clearml | clearml/backend_api/services/v2_23/projects.py | {
"start": 136561,
"end": 137834
} | class ____(Request):
"""
Convert public projects to private
:param ids: Ids of the projects to convert. Only the projects originated by the
company can be converted
:type ids: Sequence[str]
"""
_service = "projects"
_action = "make_private"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"ids": {
"description": "Ids of the projects to convert. Only the projects originated by the company can be converted",
"items": {"type": "string"},
"type": ["array", "null"],
}
},
"type": "object",
}
def __init__(self, ids: Optional[List[str]] = None, **kwargs: Any) -> None:
super(MakePrivateRequest, self).__init__(**kwargs)
self.ids = ids
@schema_property("ids")
def ids(self) -> Optional[List[str]]:
return self._property_ids
@ids.setter
def ids(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_ids = None
return
self.assert_isinstance(value, "ids", (list, tuple))
self.assert_isinstance(value, "ids", six.string_types, is_array=True)
self._property_ids = value
| MakePrivateRequest |
python | pyqtgraph__pyqtgraph | pyqtgraph/debug.py | {
"start": 13953,
"end": 14993
} | class ____(object):
"""
Convenient dictionary for holding weak references to objects.
Mainly used to check whether the objects have been collect yet or not.
Example:
gw = GarbageWatcher()
gw['objName'] = obj
gw['objName2'] = obj2
gw.check()
"""
def __init__(self):
self.objs = weakref.WeakValueDictionary()
self.allNames = []
def add(self, obj, name):
self.objs[name] = obj
self.allNames.append(name)
def __setitem__(self, name, obj):
self.add(obj, name)
def check(self):
"""Print a list of all watched objects and whether they have been collected."""
gc.collect()
dead = self.allNames[:]
alive = []
for k in self.objs:
dead.remove(k)
alive.append(k)
print("Deleted objects:", dead)
print("Live objects:", alive)
def __getitem__(self, item):
return self.objs[item]
| GarbageWatcher |
python | google__pytype | pytype/tests/test_functions2.py | {
"start": 3299,
"end": 10443
} | class ____(test_base.BaseTest):
"""Tests for functions."""
def test_object_to_callable(self):
self.Check("""
class MyClass:
def method(self):
return
def takes_object(o: object):
return
takes_object(MyClass().method)
""")
def test_function_to_callable(self):
ty = self.Infer("""
def f():
def g1(x: int, y: bool) -> str:
return "hello world"
def g2() -> int:
return 42
return g1, g2
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import Callable, Tuple
def f() -> Tuple[Callable[[int, bool], str], Callable[[], int]]: ...
""",
)
def test_function_to_callable_return_only(self):
ty = self.Infer("""
def f():
def g1(x=None) -> int:
return 42
def g2(*args) -> str:
return "hello world"
return g1, g2
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import Callable, Tuple
def f() -> Tuple[Callable[..., int], Callable[..., str]]: ...
""",
)
def test_fake_arguments(self):
self.Check("""
class Foo:
def __init__(self, x: int):
self.y = __any_object__
foo = Foo("foo") # pytype: disable=wrong-arg-types
foo.y # if __init__ fails, this line throws an error
""")
def test_argument_name_conflict(self):
ty, _ = self.InferWithErrors("""
from typing import Dict
def f(x: Dict[str, int]):
x[""] = "" # container-type-mismatch
return x
def g(x: Dict[str, int]):
return x
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import Dict, Union
def f(x: Dict[str, int]) -> Dict[str, Union[str, int]]: ...
def g(x: Dict[str, int]) -> Dict[str, int]: ...
""",
)
def test_argument_type_conflict(self):
ty, _ = self.InferWithErrors("""
from typing import Dict
def f(x: Dict[str, int], y: Dict[str, int]):
x[""] = "" # container-type-mismatch
return x, y
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import Dict, Tuple, Union
def f(
x: Dict[str, int], y: Dict[str, int]
) -> Tuple[Dict[str, Union[str, int]], Dict[str, int]]: ...
""",
)
def test_typecheck_varargs(self):
self.CheckWithErrors("""
def f(*args: int) -> int:
return args[0]
f(*['value']) # wrong-arg-types
f(1, 'hello', 'world') # wrong-arg-types
""")
def test_typecheck_kwargs(self):
self.CheckWithErrors("""
def f(**kwargs: int) -> int:
return len(kwargs.values())
f(**{'arg': 'value'}) # wrong-arg-types
f(arg='value', arg2=3) # wrong-arg-types
""")
def test_pass_func_to_complex_func(self):
# This test gets an unsolvable binding added to the variable containing the
# lambda by making the call to 'f' trigger a TooComplexError.
self.Check("""
from typing import Optional
def f(x1, x2: Optional[str], x3, x4, x5, x6, x7, x8, x9, xA, xB):
pass
def g(x2: Optional[str] = None, x3: Optional[str] = None,
x4: Optional[str] = None, x5: Optional[str] = None,
x6: Optional[str] = None, x7: Optional[str] = None,
x8: Optional[str] = None, x9: Optional[str] = None,
xA: Optional[str] = None, xB: Optional[str] = None):
f(lambda: None, x2, x3, x4, x5, x6, x7, x8, x9, xA, xB)
""")
def test_type_param_args(self):
ty = self.Infer("""
from typing import Any, Type, TypeVar
T = TypeVar('T')
def cast(typ: Type[T], val: Any) -> T:
return val
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import Type, TypeVar
T = TypeVar('T')
def cast(typ: Type[T], val) -> T: ...
""",
)
def test_varargs(self):
self.Check("""
def foo(x: str, y: bytes, *z: int):
pass
foo('abc', b'def', 123)
foo('abc', b'def', 123, 456, 789)
foo('abc', b'def', *[123, 456, 789])
foo('abc', *[b'def', 123, 456, 789])
foo(*['abc', b'def', 123, 456, 789])
def bar(*y: int):
foo('abc', b'def', *y)
""")
def text_varargs_errors(self):
errors = self.CheckWithErrors("""
def foo(x: str, *y: int):
pass
foo(*[1, 2, 3]) # wrong-arg-types[e1]
def bar(*z: int):
foo(*z) # wrong-arg-types[e2]
""")
self.assertErrorRegexes(errors, {"e1": r"str.*int", "e2": r"str.*int"})
def test_varargs_in_pyi(self):
with test_utils.Tempdir() as d:
d.create_file(
"foo.pyi",
"""
def f(x: int, *args): ...
""",
)
self.Check(
"""
import foo
def g(*args):
foo.f(42, *args)
""",
pythonpath=[d.path],
)
def test_varargs_in_pyi_error(self):
with test_utils.Tempdir() as d:
d.create_file(
"foo.pyi",
"""
def f(x: int, *args): ...
""",
)
errors = self.CheckWithErrors(
"""
import foo
def g(*args):
foo.f("", *args) # wrong-arg-types[e]
""",
pythonpath=[d.path],
)
self.assertErrorRegexes(errors, {"e": r"int.*str"})
def test_function_type(self):
self.Check("""
import types
def f(x: types.FunctionType):
pass
f(lambda: None)
""")
def test_bad_function_match(self):
# Tests matching a function against abstract.Empty.
self.CheckWithErrors("""
def f():
pass
def g(x: [][0]):
pass
g(f) # wrong-arg-types
""")
def test_noreturn(self):
self.Check("""
from typing import Any, Callable, NoReturn
def f(x: int) -> NoReturn:
raise NotImplementedError()
def g(x: Callable[[int], Any]):
pass
g(f)
""")
def test_starargs_list(self):
self.Check("""
from typing import List
def f() -> List[int]:
return __any_object__
def g(x, y, z):
pass
def h(x):
return g(x, *f())
""")
def test_namedargs_split(self):
self.Check("""
def f(x):
pass
def g(y):
pass
def h():
kws = {}
if __random__:
kws['x'] = 0
f(**kws)
else:
kws['y'] = 0
g(**kws)
""")
def test_namedargs_split_pyi(self):
with self.DepTree([(
"foo.pyi",
"""
def f(x): ...
def g(y): ...
""",
)]):
self.Check("""
import foo
def h():
kws = {}
if __random__:
kws['x'] = 0
foo.f(**kws)
else:
kws['y'] = 0
foo.g(**kws)
""")
def test_filter_none(self):
self.Check("""
import copy
from typing import Dict, Optional, Union
X = {'a': 1}
def f(x: Optional[Dict[str, bytes]] = None):
y = x or X
z = copy.copy(y)
assert_type(z, Union[Dict[str, int], Dict[str, bytes]])
""")
| TestFunctions |
python | huggingface__transformers | tests/models/llava_onevision/test_image_processing_llava_onevision.py | {
"start": 1239,
"end": 3205
} | class ____:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
image_size=20,
min_resolution=30,
max_resolution=400,
do_resize=True,
size=None,
do_normalize=True,
image_mean=OPENAI_CLIP_MEAN,
image_std=OPENAI_CLIP_STD,
do_convert_rgb=True,
):
super().__init__()
size = size if size is not None else {"height": 20, "width": 20}
self.parent = parent
self.batch_size = batch_size
self.num_channels = num_channels
self.image_size = image_size
self.min_resolution = min_resolution
self.max_resolution = max_resolution
self.do_resize = do_resize
self.size = size
self.do_normalize = do_normalize
self.image_mean = image_mean
self.image_std = image_std
self.do_convert_rgb = do_convert_rgb
def prepare_image_processor_dict(self):
return {
"do_resize": self.do_resize,
"size": self.size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_convert_rgb": self.do_convert_rgb,
}
def expected_output_image_shape(self, images):
return self.num_channels, self.size["height"], self.size["width"]
# Copied from tests.models.clip.test_image_processing_clip.CLIPImageProcessingTester.prepare_image_inputs
def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
return prepare_image_inputs(
batch_size=self.batch_size,
num_channels=self.num_channels,
min_resolution=self.min_resolution,
max_resolution=self.max_resolution,
equal_resolution=equal_resolution,
numpify=numpify,
torchify=torchify,
)
@require_torch
@require_vision
| LlavaOnevisionImageProcessingTester |
python | spyder-ide__spyder | spyder/api/widgets/toolbars.py | {
"start": 10868,
"end": 11905
} | class ____(SpyderToolbar):
"""
Spyder Widget toolbar class.
A toolbar used in Spyder dockable plugins to add internal toolbars
to their interface.
"""
ID = None
"""
Unique string toolbar identifier.
"""
def __init__(self, parent=None, title=None):
super().__init__(parent, title=title or '')
self._icon_size = QSize(16, 16)
# Setup
self.setObjectName("main_widget_toolbar_{}".format(
str(uuid.uuid4())[:8]))
self.setFloatable(False)
self.setMovable(False)
self.setContextMenuPolicy(Qt.PreventContextMenu)
self.setIconSize(self._icon_size)
self._style = ToolbarStyle(None)
self._style.TYPE = 'MainWidget'
self._style.setParent(self)
self.setStyle(self._style)
self.setStyleSheet(str(PANES_TOOLBAR_STYLESHEET))
self._filter = ToolTipFilter()
def set_icon_size(self, icon_size):
self._icon_size = icon_size
self.setIconSize(icon_size)
| MainWidgetToolbar |
python | huggingface__transformers | src/transformers/models/fsmt/modeling_fsmt.py | {
"start": 32490,
"end": 38600
} | class ____(PretrainedFSMTModel):
_tied_weights_keys = {
"encoder.embed_tokens.weight": "decoder.embed_tokens.weight",
"decoder.output_projection.weight": "decoder.embed_tokens.weight",
}
def __init__(self, config: FSMTConfig):
super().__init__(config)
self.encoder = FSMTEncoder(config)
self.decoder = FSMTDecoder(config)
self.post_init()
@auto_docstring
def forward(
self,
input_ids: torch.LongTensor,
attention_mask: Optional[torch.Tensor] = None,
decoder_input_ids: Optional[torch.LongTensor] = None,
decoder_attention_mask: Optional[torch.BoolTensor] = None,
encoder_outputs: Optional[tuple[torch.FloatTensor]] = None,
past_key_values: Optional[Cache] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
return_dict: Optional[bool] = None,
cache_position: Optional[torch.Tensor] = None,
) -> Union[tuple[torch.Tensor], Seq2SeqModelOutput]:
r"""
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
Indices of decoder input sequence tokens in the vocabulary.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are decoder input IDs?](../glossary#decoder-input-ids)
FSMT uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
be used by default.
"""
if decoder_input_ids is None:
use_cache = False
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# make masks if user doesn't supply
if not use_cache and input_ids is not None:
decoder_input_ids, decoder_padding_mask, causal_mask = _prepare_fsmt_decoder_inputs(
self.config,
input_ids,
decoder_input_ids=decoder_input_ids,
decoder_padding_mask=decoder_attention_mask,
causal_mask_dtype=self.decoder.embed_tokens.weight.dtype,
)
else:
decoder_padding_mask, causal_mask = None, None
if decoder_input_ids is None and decoder_inputs_embeds is None:
raise ValueError("Make sure that `decoder_input_ids` or `decoder_inputs_embeds` are passed.")
if use_cache and past_key_values is None:
past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
if encoder_outputs is None:
encoder_outputs = self.encoder(
input_ids=input_ids,
attention_mask=attention_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
# If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=False
elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
encoder_outputs = BaseModelOutput(
last_hidden_state=encoder_outputs[0],
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
)
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
decoder_outputs = self.decoder(
decoder_input_ids,
encoder_outputs[0],
attention_mask,
decoder_padding_mask,
decoder_causal_mask=causal_mask,
inputs_embeds=decoder_inputs_embeds,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
cache_position=cache_position,
)
if not return_dict:
return decoder_outputs + encoder_outputs
return Seq2SeqModelOutput(
last_hidden_state=decoder_outputs.last_hidden_state,
past_key_values=decoder_outputs.past_key_values,
decoder_hidden_states=decoder_outputs.hidden_states,
decoder_attentions=decoder_outputs.attentions,
cross_attentions=decoder_outputs.cross_attentions,
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
encoder_hidden_states=encoder_outputs.hidden_states,
encoder_attentions=encoder_outputs.attentions,
)
def get_input_embeddings(self):
return self.encoder.embed_tokens
def set_input_embeddings(self, value):
self.encoder.embed_tokens = value
def get_output_embeddings(self):
return self.decoder.embed_tokens
def set_output_embeddings(self, value):
self.decoder.embed_tokens = value
@auto_docstring(
custom_intro="""
The FSMT Model with a language modeling head. Can be used for summarization.
"""
)
| FSMTModel |
python | spack__spack | lib/spack/spack/package_base.py | {
"start": 95350,
"end": 106519
} | class ____:
"""Class representing Windows filesystem rpath analog
One instance of this class is associated with a package (only on Windows)
For each lib/binary directory in an associated package, this class introduces
a symlink to any/all dependent libraries/binaries. This includes the packages
own bin/lib directories, meaning the libraries are linked to the binary directory
and vis versa.
"""
def __init__(
self,
package: PackageBase,
base_modification_prefix: Optional[Union[str, pathlib.Path]] = None,
link_install_prefix: bool = True,
):
"""
Args:
package: Package requiring links
base_modification_prefix: Path representation indicating
the root directory in which to establish the simulated rpath, ie where the
symlinks that comprise the "rpath" behavior will be installed.
Note: This is a mutually exclusive option with `link_install_prefix` using
both is an error.
Default: None
link_install_prefix: Link against package's own install or stage root.
Packages that run their own executables during build and require rpaths to
the build directory during build time require this option.
Default: install
root
Note: This is a mutually exclusive option with `base_modification_prefix`, using
both is an error.
"""
self.pkg = package
self._addl_rpaths: set[str] = set()
if link_install_prefix and base_modification_prefix:
raise RuntimeError(
"Invalid combination of arguments given to WindowsSimulated RPath.\n"
"Select either `link_install_prefix` to create an install prefix rpath"
" or specify a `base_modification_prefix` for any other link type. "
"Specifying both arguments is invalid."
)
if not (link_install_prefix or base_modification_prefix):
raise RuntimeError(
"Insufficient arguments given to WindowsSimulatedRpath.\n"
"WindowsSimulatedRPath requires one of link_install_prefix"
" or base_modification_prefix to be specified."
" Neither was provided."
)
self.link_install_prefix = link_install_prefix
if base_modification_prefix:
self.base_modification_prefix = pathlib.Path(base_modification_prefix)
else:
self.base_modification_prefix = pathlib.Path(self.pkg.prefix)
self._additional_library_dependents: set[pathlib.Path] = set()
if not self.link_install_prefix:
tty.debug(f"Generating rpath for non install context: {base_modification_prefix}")
@property
def library_dependents(self):
"""
Set of directories where package binaries/libraries are located.
"""
base_pths = set()
if self.link_install_prefix:
base_pths.add(pathlib.Path(self.pkg.prefix.bin))
base_pths |= self._additional_library_dependents
return base_pths
def add_library_dependent(self, *dest: Union[str, pathlib.Path]):
"""
Add paths to directories or libraries/binaries to set of
common paths that need to link against other libraries
Specified paths should fall outside of a package's common
link paths, i.e. the bin
directories.
"""
for pth in dest:
if os.path.isfile(pth):
new_pth = pathlib.Path(pth).parent
else:
new_pth = pathlib.Path(pth)
path_is_in_prefix = new_pth.is_relative_to(self.base_modification_prefix)
if not path_is_in_prefix:
raise RuntimeError(
f"Attempting to generate rpath symlink out of rpath context:\
{str(self.base_modification_prefix)}"
)
self._additional_library_dependents.add(new_pth)
@property
def rpaths(self):
"""
Set of libraries this package needs to link against during runtime
These packages will each be symlinked into the packages lib and binary dir
"""
dependent_libs = []
for path in self.pkg.rpath:
dependent_libs.extend(list(find_all_shared_libraries(path, recursive=True)))
for extra_path in self._addl_rpaths:
dependent_libs.extend(list(find_all_shared_libraries(extra_path, recursive=True)))
return set([pathlib.Path(x) for x in dependent_libs])
def add_rpath(self, *paths: str):
"""
Add libraries found at the root of provided paths to runtime linking
These are libraries found outside of the typical scope of rpath linking
that require manual inclusion in a runtime linking scheme.
These links are unidirectional, and are only
intended to bring outside dependencies into this package
Args:
*paths : arbitrary number of paths to be added to runtime linking
"""
self._addl_rpaths = self._addl_rpaths | set(paths)
def _link(self, path: pathlib.Path, dest_dir: pathlib.Path):
"""Perform link step of simulated rpathing, installing
simlinks of file in path to the dest_dir
location. This method deliberately prevents
the case where a path points to a file inside the dest_dir.
This is because it is both meaningless from an rpath
perspective, and will cause an error when Developer
mode is not enabled"""
def report_already_linked():
# We have either already symlinked or we are encountering a naming clash
# either way, we don't want to overwrite existing libraries
already_linked = islink(str(dest_file))
tty.debug(
"Linking library %s to %s failed, " % (str(path), str(dest_file))
+ "already linked."
if already_linked
else "library with name %s already exists at location %s."
% (str(file_name), str(dest_dir))
)
file_name = path.name
dest_file = dest_dir / file_name
if not dest_file.exists() and dest_dir.exists() and not dest_file == path:
try:
symlink(str(path), str(dest_file))
# For py2 compatibility, we have to catch the specific Windows error code
# associate with trying to create a file that already exists (winerror 183)
# Catch OSErrors missed by the SymlinkError checks
except OSError as e:
if sys.platform == "win32" and e.errno == errno.EEXIST:
report_already_linked()
else:
raise e
# catch errors we raise ourselves from Spack
except AlreadyExistsError:
report_already_linked()
def establish_link(self):
"""
(sym)link packages to runtime dependencies based on RPath configuration for
Windows heuristics
"""
# from build_environment.py:463
# The top-level package is always RPATHed. It hasn't been installed yet
# so the RPATHs are added unconditionally
# for each binary install dir in self.pkg (i.e. pkg.prefix.bin, pkg.prefix.lib)
# install a symlink to each dependent library
# do not rpath for system libraries included in the dag
# we should not be modifying libraries managed by the Windows system
# as this will negatively impact linker behavior and can result in permission
# errors if those system libs are not modifiable by Spack
if "windows-system" not in getattr(self.pkg, "tags", []):
for library, lib_dir in itertools.product(self.rpaths, self.library_dependents):
self._link(library, lib_dir)
def make_package_test_rpath(pkg: PackageBase, test_dir: Union[str, pathlib.Path]) -> None:
"""Establishes a temp Windows simulated rpath for the pkg in the testing directory so an
executable can test the libraries/executables with proper access to dependent dlls.
Note: this is a no-op on all other platforms besides Windows
Args:
pkg: the package for which the rpath should be computed
test_dir: the testing directory in which we should construct an rpath
"""
# link_install_prefix as false ensures we're not linking into the install prefix
mini_rpath = WindowsSimulatedRPath(pkg, link_install_prefix=False)
# add the testing directory as a location to install rpath symlinks
mini_rpath.add_library_dependent(test_dir)
# check for whether build_directory is available, if not
# assume the stage root is the build dir
build_dir_attr = getattr(pkg, "build_directory", None)
build_directory = build_dir_attr if build_dir_attr else pkg.stage.path
# add the build dir & build dir bin
mini_rpath.add_rpath(os.path.join(build_directory, "bin"))
mini_rpath.add_rpath(os.path.join(build_directory))
# construct rpath
mini_rpath.establish_link()
def deprecated_version(pkg: PackageBase, version: Union[str, StandardVersion]) -> bool:
"""Return True iff the version is deprecated.
Arguments:
pkg: The package whose version is to be checked.
version: The version being checked
"""
if not isinstance(version, StandardVersion):
version = StandardVersion.from_string(version)
details = pkg.versions.get(version)
return details is not None and details.get("deprecated", False)
def preferred_version(pkg: Union[PackageBase, Type[PackageBase]]):
"""
Returns a sorted list of the preferred versions of the package.
Arguments:
pkg: The package whose versions are to be assessed.
"""
version, _ = max(pkg.versions.items(), key=concretization_version_order)
return version
def sort_by_pkg_preference(
versions: Iterable[Union[GitVersion, StandardVersion]],
*,
pkg: Union[PackageBase, Type[PackageBase]],
) -> List[Union[GitVersion, StandardVersion]]:
"""Sorts the list of versions passed in input according to the preferences in the package. The
return value does not contain duplicate versions. Most preferred versions first.
"""
s = [(v, pkg.versions.get(v, {})) for v in dedupe(versions)]
return [v for v, _ in sorted(s, reverse=True, key=concretization_version_order)]
def concretization_version_order(version_info: Tuple[Union[GitVersion, StandardVersion], dict]):
"""Version order key for concretization, where preferred > not preferred,
not deprecated > deprecated, finite > any infinite component; only if all are
the same, do we use default version ordering."""
version, info = version_info
return (
info.get("preferred", False),
not info.get("deprecated", False),
not isinstance(version, GitVersion),
not version.isdevelop(),
not version.is_prerelease(),
version,
)
| WindowsSimulatedRPath |
python | wandb__wandb | wandb/sdk/artifacts/_generated/input_types.py | {
"start": 3941,
"end": 4198
} | class ____(GQLInput):
artifact_id: GQLId = Field(alias="artifactID")
delete_aliases: Optional[bool] = Field(alias="deleteAliases", default=False)
client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None)
| DeleteArtifactInput |
python | ipython__ipython | IPython/core/display.py | {
"start": 14702,
"end": 14928
} | class ____(TextDisplayObject):
def _repr_latex_(self):
s = r"$\displaystyle %s$" % self.data.strip('$')
if self.metadata:
return s, deepcopy(self.metadata)
else:
return s
| Math |
python | sqlalchemy__sqlalchemy | test/ext/test_associationproxy.py | {
"start": 43105,
"end": 43176
} | class ____:
def __init__(self, name):
self.name = name
| Parent |
python | google__jax | tests/pallas/indexing_test.py | {
"start": 27790,
"end": 27949
} | class ____(AdvancedIndexerOpsTest):
INTERPRET = True
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
| AdvancedIndexerOpsInterpretTest |
python | google__jax | jax/_src/custom_partitioning_sharding_rule.py | {
"start": 3768,
"end": 21205
} | class ____:
"""Represents a Shardy sharding rule.
An SdyShardingRule contains the ArrayMappings for operands and results,
optional special factors and optional factor sizes. A factor is a name used in
the ArrayMappings. If a factor is only used in CompoundFactors, its size must
be specified.
By default, a factor is a passthrough factor. Keyword arguments can be used to
specify other factor kinds including reduction_factors, need_replication_factors,
and permutation_factors.
"""
operand_mappings: tuple[ArrayMapping, ...]
result_mappings: tuple[ArrayMapping, ...]
factor_sizes: dict[str, int]
reduction_factors: tuple[str, ...]
need_replication_factors: tuple[str, ...]
permutation_factors: tuple[str, ...]
def __init__(self, operand_mappings: tuple[ArrayMapping, ...],
result_mappings: tuple[ArrayMapping, ...],
*, reduction_factors: tuple[str, ...] = (),
need_replication_factors: tuple[str, ...] = (),
permutation_factors: tuple[str, ...] = (),
**factor_sizes: int):
# Find all factors and mark whether their size can be inferred.
factors_inferrable = {}
for value in operand_mappings + result_mappings:
for dim in value:
if isinstance(dim, str):
factors_inferrable[dim] = True
else:
for factor in dim:
if factor not in factors_inferrable.keys():
factors_inferrable[factor] = False
# Check that factors in factor_sizes are used in the rule.
for factor in factor_sizes:
if factor not in factors_inferrable:
raise ValueError(
f"Factor {factor} is not used in the rule, but size is provided")
# Check that factors that are used for a whole dimension aren't in
# factor_sizes and factors that are never used for a whole dimension are
# in factor_sizes.
for factor, inferable in factors_inferrable.items():
if factor not in factor_sizes and not inferable:
raise ValueError(
f"Factor {factor} is only used in compound factors; must specify"
" its size")
if factor in factor_sizes and inferable:
raise ValueError(
f"Factor {factor} represents a whole dimension; do not specify its"
" size")
special_factors = set()
def check_special_factors(kind, factors):
if not isinstance(factors, tuple):
raise ValueError(f"{kind} must be a tuple of factors")
if len(factors) != len(set(factors)):
raise ValueError(f"{kind} contains duplicated factors")
for factor in factors:
if factor not in factors_inferrable:
raise ValueError(
f"Factor {factor} in {kind} is not used in the rule")
if factor in special_factors:
raise ValueError(f"Factor {factor} can only be in one of the "
f"reduction, need replication, or permutation factor sets.")
special_factors.add(factor)
check_special_factors("reduction_factors", reduction_factors)
check_special_factors("need_replication_factors", need_replication_factors)
check_special_factors("permutation_factors", permutation_factors)
self.operand_mappings = operand_mappings
self.result_mappings = result_mappings
self.factor_sizes = factor_sizes
self.reduction_factors = reduction_factors
self.need_replication_factors = need_replication_factors
self.permutation_factors = permutation_factors
def __str__(self):
def to_str(kind, factors):
if len(factors) > 0:
return f" {kind}={factors}"
return ""
special_factors = (to_str("reduction_factors", self.reduction_factors) +
to_str("need_replication_factors", self.need_replication_factors) +
to_str("permutation_factors", self.permutation_factors))
return (f"SdyShardingRule({self.operand_mappings}, {self.result_mappings}, "
f"{self.factor_sizes}{special_factors})")
def _get_batching_dim_factor_name(batch_group: str,batch_dim_order : int):
"""Constructs a factor name for a batching dimension.
We expand the leading ... into factors representing the batching dimensions
to support building the MLIR representation for the sharding rule. For this
reason, we construct a factor name that won't be used by users for the
batching dimensions.
"""
return f"{_BATCHING_DIM_FACTOR_PREFIX}{batch_group}_{batch_dim_order}"
def _parse_values(
rule: str,
) -> tuple[ArrayMapping, ...]:
"""Parses the LHS or RHS of an Einsum notation like string.
Converts each operand or result in the Einsum notation like string to a tuple
of ArrayMapping. This very closely follows how einops parses their rules in
einops/parsing.py.
Args:
rule: The Einsum notation for the operands or results of an operation.
Returns:
The tuple of ArrayMapping.
Raises:
ValueError: If the rule is not balanced or contains unknown characters.
"""
# Remove unnecessary spaces in the rule to simplify the parsing process.
words = rule.split()
rule = " ".join(words)
# Similar to einops rules, an empty LHS/RHS has a single scalar value.
if not rule:
return (ArrayMapping(),)
all_values = []
# Represent all dimensions of an value. When an value[0]==BATCHING, the
# value may have 0 or more leading dimensions.
value = []
current_factor = None
# A value of None indicates the current dimension is not a compound dimension,
# while a value of [] indicates that we have just started parsing a compound
# dimension.
current_compound_dim: list[str] | None = None
def add_factor(x):
if current_compound_dim is None:
value.append(x)
else:
current_compound_dim.append(x)
rule_len = len(rule)
rule_index = 0
while rule_index < rule_len:
char = rule[rule_index]
rule_index += 1
if char == BATCHING:
if (current_factor is not None or current_compound_dim is not None
or value):
raise ValueError(
"Ellipsis can only be used at the beginning of a dimension")
if rule_index < rule_len and rule[rule_index].isdigit():
batching_group_str = ""
while rule_index < rule_len and rule[rule_index].isdigit():
batching_group_str += rule[rule_index]
rule_index += 1
batching_group = str(int(batching_group_str))
else:
batching_group = "0"
add_factor(f"{BATCHING}{batching_group}")
continue
if char in "(), ":
if current_factor is not None:
add_factor(current_factor)
current_factor = None
if char == "(":
if current_compound_dim is not None:
raise ValueError(
"Compound factors should be one level, nested brackets are not"
" allowed")
current_compound_dim = []
elif char == ")":
if current_compound_dim is None:
raise ValueError("Brackets are not balanced")
if len(current_compound_dim) <= 1:
raise ValueError("Brackets should contain at least two factors")
value.append(CompoundFactor(*current_compound_dim))
current_compound_dim = None
elif char == ",":
all_values.append(ArrayMapping(*value))
value = []
elif char == "_" or char.isdigit() or char.isalpha():
if current_factor is None:
if str.isdigit(char):
raise ValueError(f"Factor names have to start with a letter, but got '{char}'")
current_factor = char
else:
current_factor += char
else:
raise ValueError(f"Unknown character '{char}'")
if current_compound_dim is not None:
raise ValueError(f"Brackets are not balanced in rule: '{rule}'")
if current_factor is not None:
add_factor(current_factor)
all_values.append(ArrayMapping(*value))
return tuple(all_values)
def str_to_sdy_sharding_rule(rule: str, *,
reduction_factors: tuple[str, ...] = (),
need_replication_factors: tuple[str, ...] = (),
permutation_factors: tuple[str, ...] = (),
**factor_sizes: int) -> SdyShardingRule:
"""Constructs a SdyShardingRule object from the Einsum notation like string.
This is done by verifying that the input Einsum notation like string and
with optional special factors and factor sizes represents a valid sharding
rule and converting it to an internal representation.
Args:
rule: The Einsum notation like string for an operation.
reduction_factors: A tuple of factors that are reduction factors.
need_replication_factors: A tuple of factors that are need_replication factors.
permutation_factors: A tuple of factors that are permutation factors.
**factor_sizes: The optional factor sizes.
Raises:
ValueError: If there is any problem with the rule or factor_sizes.
"""
if not isinstance(rule, str):
raise TypeError(f"rule must be a str, but got {type(rule)}")
if not all(isinstance(size, int) for size in factor_sizes.values()):
raise TypeError(
f"factor_sizes must be a dict of str to int, but got {factor_sizes}")
# Replace ... with a single char to simplify parsing.
if BATCHING in rule:
raise ValueError(f"Unknown character '{BATCHING}'")
if "." in rule:
rule = rule.replace("...", BATCHING)
if "." in rule:
raise ValueError("Character '.' must be used inside ellipsis '...'")
try:
operands, results = rule.split("->")
except ValueError as e:
raise ValueError(f"There is no -> in rule: '{rule}'") from e
operand_mappings = _parse_values(operands)
result_mappings = _parse_values(results)
return SdyShardingRule(operand_mappings, result_mappings,
reduction_factors=reduction_factors,
need_replication_factors=need_replication_factors,
permutation_factors=permutation_factors,
**factor_sizes)
def sdy_sharding_rule_to_mlir(
rule: SdyShardingRule,
operand_types: list[IrTypes],
result_types: list[IrTypes],) -> ir.Attribute:
"""Builds the MLIR representation for the sharding rule.
This is done by verifying that the rule is consistent with the types of
the operation and converting the Einsum notation like string to
OpShardingRuleAttr.
"""
if len(rule.operand_mappings) != len(operand_types):
raise ValueError(
f"Sharding rule has {len(rule.operand_mappings)} operands, but the operation"
f" has {len(operand_types)} operands")
if len(rule.result_mappings) != len(result_types):
raise ValueError(
f"Sharding rule has {len(rule.result_mappings)} results, but the operation"
f" has {len(result_types)} results")
if not all(isinstance(t, ir.Type) for t in operand_types + result_types):
raise TypeError(
f"operand_types and result_types must be a list of ir.Type, but got"
f" {operand_types} and {result_types}")
factors_to_indices_sizes: OrderedDict[str, list[int]] = OrderedDict()
types = operand_types + result_types
UNKNOWN = -1 # Representation for unknown factor size or factor index.
def get_message_for_value(i):
if i >= len(operand_types):
return f"{i - len(operand_types)}th result"
else:
return f"{i}th operand"
def get_rank_for_value(i):
return ir.ShapedType(types[i]).rank
def get_size_for_value_dim(i, j):
return ir.ShapedType(types[i]).shape[j]
def add_factor(factor, size):
"""Adds a factor to factors_to_indices_sizes.
`size` may be a dimensions size, a user specified factor size, or UNKNOWN
if a factor is first used as in a compound factor and then used for a
whole dimension. If a factor is not for a leading batching dimension and
it corresponds to multiple sizes, the smallest size is used.
"""
factor_index, factor_size = factors_to_indices_sizes.get(factor, [UNKNOWN, UNKNOWN])
if factor_index != UNKNOWN:
# Not the first time seeing the factor.
if size != UNKNOWN and factor_size != UNKNOWN and factor_size != size:
if _BATCHING_DIM_FACTOR_PREFIX in factor:
raise ValueError(f"Batching dimension {factor[1:]} corresponds to "
f"two sizes: {factor_size} and {size}")
else:
if size < factor_size:
# Use the smaller size to update the factor size.
factor_size = UNKNOWN
if size != UNKNOWN and factor_size == UNKNOWN:
factors_to_indices_sizes[factor] = [factor_index, size]
else:
# First time seeing the factor.
factor_index = len(factors_to_indices_sizes)
factors_to_indices_sizes[factor] = [factor_index, size]
def add_batching_dim_factor(batch_grp, batch_dim_order, factor_size):
add_factor(_get_batching_dim_factor_name(batch_grp, batch_dim_order), factor_size)
def build_dim_mapping_for_compound_factors(i, j, factors):
accumulated_size = 1
all_indices = []
for factor in factors:
factor_index, factor_size = factors_to_indices_sizes[factor]
accumulated_size *= factor_size
all_indices.append(factor_index)
dim_size = get_size_for_value_dim(i, j)
if accumulated_size != dim_size:
raise ValueError(
f"{get_message_for_value(i)} actual size {dim_size} doesn't match"
f" the size {accumulated_size} derived from the compound factors"
f" {factors}")
return sdy.DimMappingAttr.get(factor_indices=all_indices)
def factors_to_indices(factors):
return [factors_to_indices_sizes[factor][0] for factor in factors]
# Add factors and their sizes in the order they appear in the rule,
# including the batching dimensions represented by ellipsis.
batching_group_to_rank: dict[str, int] = {}
for i, mapping in enumerate(rule.operand_mappings + rule.result_mappings):
value = tuple(mapping)
if value and _is_batching(value[0]):
batching_group = _get_batching_group(value[0])
value = value[1:]
else:
batching_group = None
rule_rank = len(value)
op_rank = get_rank_for_value(i)
# The number of dimensions represented by ellipsis.
current_batching_rank = 0
if batching_group is not None and op_rank >= rule_rank:
current_batching_rank = op_rank - rule_rank
if batching_group is not None:
ellipsis_rank = batching_group_to_rank.get(batching_group, None)
if ellipsis_rank is None:
ellipsis_rank = current_batching_rank
batching_group_to_rank[batching_group] = ellipsis_rank
elif ellipsis_rank != current_batching_rank:
raise ValueError(
"Ellipsis represents different number of leading dimensions"
f" {ellipsis_rank} and {current_batching_rank}")
rule_rank += current_batching_rank
if rule_rank != op_rank:
msg = get_message_for_value(i)
raise ValueError(
f"Sharding rule {msg} has rank {rule_rank}, but the operation"
f" {msg} has rank {op_rank}")
for j in range(current_batching_rank):
add_batching_dim_factor(batching_group, j, get_size_for_value_dim(i, j))
for j, dim in enumerate(value):
if isinstance(dim, str):
add_factor(dim, get_size_for_value_dim(i, j + current_batching_rank))
else:
for factor in dim:
add_factor(factor, rule.factor_sizes.get(factor, UNKNOWN))
# Build the tensor mappings for each operand and result.
tensor_mappings = []
for i, mapping in enumerate(rule.operand_mappings + rule.result_mappings):
value = tuple(mapping)
dim_mappings = []
if value and _is_batching(value[0]):
batching_group = _get_batching_group(value[0])
value = value[1:]
if batching_group in batching_group_to_rank:
# This type check error is not correct, disable it:
# Incompatible types in assignment (expression has type "int | None"
current_batching_rank = batching_group_to_rank.get(batching_group) # type: ignore
else:
raise ValueError("Unreachabled code")
else:
current_batching_rank = 0
batching_group = None
for j in range(current_batching_rank):
# This type check error is not correct, disable it:
# Argument 1 to "_get_batching_dim_factor_name" has incompatible type "str | None"; expected "str" [arg-type]
dim_mappings.append(
sdy.DimMappingAttr.get(factor_indices=[
factors_to_indices_sizes[_get_batching_dim_factor_name(batching_group, j)][0]])) # type: ignore
for j, dim in enumerate(value):
if isinstance(dim, str):
dim_mappings.append(
sdy.DimMappingAttr.get(
factor_indices=[factors_to_indices_sizes[dim][0]]))
else:
dim_mappings.append(
build_dim_mapping_for_compound_factors(
i, j + current_batching_rank, dim))
tensor_mappings.append(
sdy.TensorMappingAttr.get(dim_mappings=dim_mappings))
return sdy.OpShardingRuleAttr.get(
factor_sizes=[item[1] for item in factors_to_indices_sizes.values()],
operand_mappings=tensor_mappings[0:len(operand_types)],
result_mappings=tensor_mappings[len(operand_types):],
is_custom=True,
reduction_factors=factors_to_indices(rule.reduction_factors),
need_replication_factors=factors_to_indices(rule.need_replication_factors),
permutation_factors=factors_to_indices(rule.permutation_factors),
)
| SdyShardingRule |
python | ansible__ansible | test/lib/ansible_test/_internal/commands/sanity/bin_symlinks.py | {
"start": 528,
"end": 3073
} | class ____(SanityVersionNeutral):
"""Sanity test for symlinks in the bin directory."""
ansible_only = True
@property
def can_ignore(self) -> bool:
"""True if the test supports ignore entries."""
return False
@property
def no_targets(self) -> bool:
"""True if the test does not use test targets. Mutually exclusive with all_targets."""
return True
def test(self, args: SanityConfig, targets: SanityTargets) -> TestResult:
bin_root = os.path.join(ANSIBLE_SOURCE_ROOT, 'bin')
bin_names = os.listdir(bin_root)
bin_paths = sorted(os.path.join(bin_root, path) for path in bin_names)
errors: list[tuple[str, str]] = []
symlink_map_path = os.path.relpath(symlink_map_full_path, data_context().content.root)
for bin_path in bin_paths:
if not os.path.islink(bin_path):
errors.append((bin_path, 'not a symbolic link'))
continue
dest = os.readlink(bin_path)
if not os.path.exists(bin_path):
errors.append((bin_path, 'points to non-existent path "%s"' % dest))
continue
if not os.path.isfile(bin_path):
errors.append((bin_path, 'points to non-file "%s"' % dest))
continue
map_dest = ANSIBLE_BIN_SYMLINK_MAP.get(os.path.basename(bin_path))
if not map_dest:
errors.append((bin_path, 'missing from ANSIBLE_BIN_SYMLINK_MAP in file "%s"' % symlink_map_path))
continue
if dest != map_dest:
errors.append((bin_path, 'points to "%s" instead of "%s" from ANSIBLE_BIN_SYMLINK_MAP in file "%s"' % (dest, map_dest, symlink_map_path)))
continue
if not os.access(bin_path, os.X_OK):
errors.append((bin_path, 'points to non-executable file "%s"' % dest))
continue
for bin_name, dest in ANSIBLE_BIN_SYMLINK_MAP.items():
if bin_name not in bin_names:
bin_path = os.path.join(bin_root, bin_name)
errors.append((bin_path, 'missing symlink to "%s" defined in ANSIBLE_BIN_SYMLINK_MAP in file "%s"' % (dest, symlink_map_path)))
messages = [SanityMessage(message=message, path=os.path.relpath(path, data_context().content.root), confidence=100) for path, message in errors]
if errors:
return SanityFailure(self.name, messages=messages)
return SanitySuccess(self.name)
| BinSymlinksTest |
python | python__mypy | mypy/renaming.py | {
"start": 14834,
"end": 20494
} | class ____(TraverserVisitor):
"""Perform some limited variable renaming in with statements.
This allows reusing a variable in multiple with statements with
different types. For example, the two instances of 'x' can have
incompatible types:
with C() as x:
f(x)
with D() as x:
g(x)
The above code gets renamed conceptually into this (not valid Python!):
with C() as x':
f(x')
with D() as x:
g(x)
If there's a reference to a variable defined in 'with' outside the
statement, or if there's any trickiness around variable visibility
(e.g. function definitions), we give up and won't perform renaming.
The main use case is to allow binding both readable and writable
binary files into the same variable. These have different types:
with open(fnam, 'rb') as f: ...
with open(fnam, 'wb') as f: ...
"""
def __init__(self) -> None:
# Short names of variables bound in with statements using "as"
# in a surrounding scope
self.bound_vars: list[str] = []
# Stack of names that can't be safely renamed, per scope ('*' means that
# no names can be renamed)
self.skipped: list[set[str]] = []
# References to variables that we may need to rename. Stack of
# scopes; each scope is a mapping from name to list of collections
# of names that refer to the same logical variable.
self.refs: list[dict[str, list[list[NameExpr]]]] = []
def visit_mypy_file(self, file_node: MypyFile) -> None:
"""Rename variables within a file.
This is the main entry point to this class.
"""
with self.enter_scope():
for d in file_node.defs:
d.accept(self)
def visit_func_def(self, fdef: FuncDef) -> None:
self.reject_redefinition_of_vars_in_scope()
with self.enter_scope():
for arg in fdef.arguments:
self.record_skipped(arg.variable.name)
super().visit_func_def(fdef)
def visit_class_def(self, cdef: ClassDef) -> None:
self.reject_redefinition_of_vars_in_scope()
with self.enter_scope():
super().visit_class_def(cdef)
def visit_with_stmt(self, stmt: WithStmt) -> None:
for expr in stmt.expr:
expr.accept(self)
old_len = len(self.bound_vars)
for target in stmt.target:
if target is not None:
self.analyze_lvalue(target)
for target in stmt.target:
if target:
target.accept(self)
stmt.body.accept(self)
while len(self.bound_vars) > old_len:
self.bound_vars.pop()
def analyze_lvalue(self, lvalue: Lvalue) -> None:
if isinstance(lvalue, NameExpr):
name = lvalue.name
if name in self.bound_vars:
# Name bound in a surrounding with statement, so it can be renamed
self.visit_name_expr(lvalue)
else:
var_info = self.refs[-1]
if name not in var_info:
var_info[name] = []
var_info[name].append([])
self.bound_vars.append(name)
elif isinstance(lvalue, (ListExpr, TupleExpr)):
for item in lvalue.items:
self.analyze_lvalue(item)
elif isinstance(lvalue, MemberExpr):
lvalue.expr.accept(self)
elif isinstance(lvalue, IndexExpr):
lvalue.base.accept(self)
lvalue.index.accept(self)
elif isinstance(lvalue, StarExpr):
self.analyze_lvalue(lvalue.expr)
def visit_import(self, imp: Import) -> None:
# We don't support renaming imports
for id, as_id in imp.ids:
self.record_skipped(as_id or id)
def visit_import_from(self, imp: ImportFrom) -> None:
# We don't support renaming imports
for id, as_id in imp.names:
self.record_skipped(as_id or id)
def visit_import_all(self, imp: ImportAll) -> None:
# Give up, since we don't know all imported names yet
self.reject_redefinition_of_vars_in_scope()
def visit_name_expr(self, expr: NameExpr) -> None:
name = expr.name
if name in self.bound_vars:
# Record reference so that it can be renamed later
for scope in reversed(self.refs):
if name in scope:
scope[name][-1].append(expr)
else:
self.record_skipped(name)
@contextmanager
def enter_scope(self) -> Iterator[None]:
self.skipped.append(set())
self.refs.append({})
yield None
self.flush_refs()
def reject_redefinition_of_vars_in_scope(self) -> None:
self.record_skipped("*")
def record_skipped(self, name: str) -> None:
self.skipped[-1].add(name)
def flush_refs(self) -> None:
ref_dict = self.refs.pop()
skipped = self.skipped.pop()
if "*" not in skipped:
for name, refs in ref_dict.items():
if len(refs) <= 1 or name in skipped:
continue
# At module top level we must not rename the final definition,
# as it may be publicly visible
to_rename = refs[:-1]
for i, item in enumerate(to_rename):
rename_refs(item, i)
def rename_refs(names: list[NameExpr], index: int) -> None:
name = names[0].name
new_name = name + "'" * (index + 1)
for expr in names:
expr.name = new_name
| LimitedVariableRenameVisitor |
python | google__flatbuffers | python/flatbuffers/builder.py | {
"start": 1016,
"end": 1240
} | class ____(RuntimeError):
"""Error caused by an Offset arithmetic error.
Probably caused by bad writing of fields. This is considered an unreachable
situation in normal circumstances.
"""
pass
| OffsetArithmeticError |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol6.py | {
"start": 236,
"end": 284
} | class ____(Animal[_T2], Protocol):
pass
| Mammal |
python | gawel__pyquery | pyquery/cssselectpatch.py | {
"start": 293,
"end": 1404
} | class ____(XPathExprOrig):
def __init__(self, path='', element='*', condition='', star_prefix=False):
self.path = path
self.element = element
self.condition = condition
self.post_condition = None
def add_post_condition(self, post_condition):
if self.post_condition:
self.post_condition = '%s and (%s)' % (self.post_condition,
post_condition)
else:
self.post_condition = post_condition
def __str__(self):
path = XPathExprOrig.__str__(self)
if self.post_condition:
path = '%s[%s]' % (path, self.post_condition)
return path
def join(self, combiner, other,
closing_combiner=None, has_inner_condition=False):
res = XPathExprOrig.join(self, combiner, other,
closing_combiner=closing_combiner,
has_inner_condition=has_inner_condition)
self.post_condition = other.post_condition
return res
# keep cssselect < 0.8 compat for now
| XPathExpr |
python | pydata__xarray | xarray/tests/test_backends.py | {
"start": 173626,
"end": 173823
} | class ____(ZarrBase):
@contextlib.contextmanager
def create_zarr_target(self):
with create_tmp_file(suffix=".zarr") as tmp:
yield tmp
@requires_zarr
| TestZarrDirectoryStore |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/elements.py | {
"start": 130128,
"end": 130892
} | class ____(WrapsColumnExpression[bool], UnaryExpression[bool]):
inherit_cache = True
def __init__(self, element, operator, negate):
self.element = element
self.type = type_api.BOOLEANTYPE
self.operator = operator
self.negate = negate
self.modifier = None
self._is_implicitly_boolean = element._is_implicitly_boolean
@property
def wrapped_column_expression(self):
return self.element
def self_group(self, against: Optional[OperatorType] = None) -> Self:
return self
def _negate(self):
if isinstance(self.element, (True_, False_)):
return self.element._negate()
else:
return AsBoolean(self.element, self.negate, self.operator)
| AsBoolean |
python | pydantic__pydantic | tests/mypy/modules/plugin_success.py | {
"start": 6461,
"end": 6695
} | class ____(BaseModel):
model_config = ConfigDict(validate_by_alias=True, validate_by_name=True)
my_field: str = Field(alias='my_alias')
# for this case, we prefer the field name over the alias
m3 = Model3(my_field='foo')
| Model3 |
python | huggingface__transformers | src/transformers/models/glm4_moe/modeling_glm4_moe.py | {
"start": 19482,
"end": 21391
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: Glm4MoeConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = Glm4MoeAttention(config=config, layer_idx=layer_idx)
if layer_idx >= config.first_k_dense_replace:
self.mlp = Glm4MoeMoE(config)
else:
self.mlp = Glm4MoeMLP(config)
self.input_layernorm = Glm4MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = Glm4MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
use_cache: Optional[bool] = False,
cache_position: Optional[torch.LongTensor] = None,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
**kwargs: Unpack[TransformersKwargs],
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
# Self Attention
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
use_cache=use_cache,
cache_position=cache_position,
position_embeddings=position_embeddings,
**kwargs,
)
hidden_states = residual + hidden_states
# Fully Connected
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = residual + hidden_states
return hidden_states
@auto_docstring
| Glm4MoeDecoderLayer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.