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 | airbytehq__airbyte | airbyte-integrations/connectors/source-iterable/source_iterable/streams.py | {
"start": 17409,
"end": 17502
} | class ____(IterableExportEventsStreamAdjustableRange):
data_field = "inAppClick"
| InAppClick |
python | networkx__networkx | networkx/algorithms/tests/test_cycles.py | {
"start": 6812,
"end": 25929
} | class ____:
@staticmethod
def K(n):
return nx.complete_graph(n)
@staticmethod
def D(n):
return nx.complete_graph(n).to_directed()
@staticmethod
def edgeset_function(g):
if g.is_directed():
return directed_cycle_edgeset
elif g.is_multigraph():
return multigraph_cycle_edgeset
else:
return undirected_cycle_edgeset
def check_cycle(self, g, c, es, cache, source, original_c, length_bound, chordless):
if length_bound is not None and len(c) > length_bound:
raise RuntimeError(
f"computed cycle {original_c} exceeds length bound {length_bound}"
)
if source == "computed":
if es in cache:
raise RuntimeError(
f"computed cycle {original_c} has already been found!"
)
else:
cache[es] = tuple(original_c)
else:
if es in cache:
cache.pop(es)
else:
raise RuntimeError(f"expected cycle {original_c} was not computed")
if not all(g.has_edge(*e) for e in es):
raise RuntimeError(
f"{source} claimed cycle {original_c} is not a cycle of g"
)
if chordless and len(g.subgraph(c).edges) > len(c):
raise RuntimeError(f"{source} cycle {original_c} is not chordless")
def check_cycle_algorithm(
self,
g,
expected_cycles,
length_bound=None,
chordless=False,
algorithm=None,
):
if algorithm is None:
algorithm = nx.chordless_cycles if chordless else nx.simple_cycles
# note: we shuffle the labels of g to rule out accidentally-correct
# behavior which occurred during the development of chordless cycle
# enumeration algorithms
relabel = list(range(len(g)))
rng = random.Random(42)
rng.shuffle(relabel)
label = dict(zip(g, relabel))
unlabel = dict(zip(relabel, g))
h = nx.relabel_nodes(g, label, copy=True)
edgeset = self.edgeset_function(h)
params = {}
if length_bound is not None:
params["length_bound"] = length_bound
cycle_cache = {}
for c in algorithm(h, **params):
original_c = [unlabel[x] for x in c]
es = edgeset(c)
self.check_cycle(
h, c, es, cycle_cache, "computed", original_c, length_bound, chordless
)
if isinstance(expected_cycles, int):
if len(cycle_cache) != expected_cycles:
raise RuntimeError(
f"expected {expected_cycles} cycles, got {len(cycle_cache)}"
)
return
for original_c in expected_cycles:
c = [label[x] for x in original_c]
es = edgeset(c)
self.check_cycle(
h, c, es, cycle_cache, "expected", original_c, length_bound, chordless
)
if len(cycle_cache):
for c in cycle_cache.values():
raise RuntimeError(
f"computed cycle {c} is valid but not in the expected cycle set!"
)
def check_cycle_enumeration_integer_sequence(
self,
g_family,
cycle_counts,
length_bound=None,
chordless=False,
algorithm=None,
):
for g, num_cycles in zip(g_family, cycle_counts):
self.check_cycle_algorithm(
g,
num_cycles,
length_bound=length_bound,
chordless=chordless,
algorithm=algorithm,
)
def test_directed_chordless_cycle_digons(self):
g = nx.DiGraph()
nx.add_cycle(g, range(5))
nx.add_cycle(g, range(5)[::-1])
g.add_edge(0, 0)
expected_cycles = [(0,), (1, 2), (2, 3), (3, 4)]
self.check_cycle_algorithm(g, expected_cycles, chordless=True)
self.check_cycle_algorithm(g, expected_cycles, chordless=True, length_bound=2)
expected_cycles = [c for c in expected_cycles if len(c) < 2]
self.check_cycle_algorithm(g, expected_cycles, chordless=True, length_bound=1)
def test_chordless_cycles_multigraph_self_loops(self):
G = nx.MultiGraph([(1, 1), (2, 2), (1, 2), (1, 2)])
expected_cycles = [[1], [2]]
self.check_cycle_algorithm(G, expected_cycles, chordless=True)
G.add_edges_from([(2, 3), (3, 4), (3, 4), (1, 3)])
expected_cycles = [[1], [2], [3, 4]]
self.check_cycle_algorithm(G, expected_cycles, chordless=True)
def test_directed_chordless_cycle_undirected(self):
g = nx.DiGraph([(1, 2), (2, 3), (3, 4), (4, 5), (5, 0), (5, 1), (0, 2)])
expected_cycles = [(0, 2, 3, 4, 5), (1, 2, 3, 4, 5)]
self.check_cycle_algorithm(g, expected_cycles, chordless=True)
g = nx.DiGraph()
nx.add_cycle(g, range(5))
nx.add_cycle(g, range(4, 9))
g.add_edge(7, 3)
expected_cycles = [(0, 1, 2, 3, 4), (3, 4, 5, 6, 7), (4, 5, 6, 7, 8)]
self.check_cycle_algorithm(g, expected_cycles, chordless=True)
g.add_edge(3, 7)
expected_cycles = [(0, 1, 2, 3, 4), (3, 7), (4, 5, 6, 7, 8)]
self.check_cycle_algorithm(g, expected_cycles, chordless=True)
expected_cycles = [(3, 7)]
self.check_cycle_algorithm(g, expected_cycles, chordless=True, length_bound=4)
g.remove_edge(7, 3)
expected_cycles = [(0, 1, 2, 3, 4), (4, 5, 6, 7, 8)]
self.check_cycle_algorithm(g, expected_cycles, chordless=True)
g = nx.DiGraph((i, j) for i in range(10) for j in range(i))
expected_cycles = []
self.check_cycle_algorithm(g, expected_cycles, chordless=True)
def test_chordless_cycles_directed(self):
G = nx.DiGraph()
nx.add_cycle(G, range(5))
nx.add_cycle(G, range(4, 12))
expected = [[*range(5)], [*range(4, 12)]]
self.check_cycle_algorithm(G, expected, chordless=True)
self.check_cycle_algorithm(
G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
)
G.add_edge(7, 3)
expected.append([*range(3, 8)])
self.check_cycle_algorithm(G, expected, chordless=True)
self.check_cycle_algorithm(
G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
)
G.add_edge(3, 7)
expected[-1] = [7, 3]
self.check_cycle_algorithm(G, expected, chordless=True)
self.check_cycle_algorithm(
G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
)
expected.pop()
G.remove_edge(7, 3)
self.check_cycle_algorithm(G, expected, chordless=True)
self.check_cycle_algorithm(
G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
)
def test_directed_chordless_cycle_diclique(self):
g_family = [self.D(n) for n in range(10)]
expected_cycles = [(n * n - n) // 2 for n in range(10)]
self.check_cycle_enumeration_integer_sequence(
g_family, expected_cycles, chordless=True
)
expected_cycles = [(n * n - n) // 2 for n in range(10)]
self.check_cycle_enumeration_integer_sequence(
g_family, expected_cycles, length_bound=2
)
def test_directed_chordless_loop_blockade(self):
g = nx.DiGraph((i, i) for i in range(10))
nx.add_cycle(g, range(10))
expected_cycles = [(i,) for i in range(10)]
self.check_cycle_algorithm(g, expected_cycles, chordless=True)
self.check_cycle_algorithm(g, expected_cycles, length_bound=1)
g = nx.MultiDiGraph(g)
g.add_edges_from((i, i) for i in range(0, 10, 2))
expected_cycles = [(i,) for i in range(1, 10, 2)]
self.check_cycle_algorithm(g, expected_cycles, chordless=True)
def test_simple_cycles_notable_clique_sequences(self):
# A000292: Number of labeled graphs on n+3 nodes that are triangles.
g_family = [self.K(n) for n in range(2, 12)]
expected = [0, 1, 4, 10, 20, 35, 56, 84, 120, 165, 220]
self.check_cycle_enumeration_integer_sequence(
g_family, expected, length_bound=3
)
def triangles(g, **kwargs):
yield from (c for c in nx.simple_cycles(g, **kwargs) if len(c) == 3)
# directed complete graphs have twice as many triangles thanks to reversal
g_family = [self.D(n) for n in range(2, 12)]
expected = [2 * e for e in expected]
self.check_cycle_enumeration_integer_sequence(
g_family, expected, length_bound=3, algorithm=triangles
)
def four_cycles(g, **kwargs):
yield from (c for c in nx.simple_cycles(g, **kwargs) if len(c) == 4)
# A050534: the number of 4-cycles in the complete graph K_{n+1}
expected = [0, 0, 0, 3, 15, 45, 105, 210, 378, 630, 990]
g_family = [self.K(n) for n in range(1, 12)]
self.check_cycle_enumeration_integer_sequence(
g_family, expected, length_bound=4, algorithm=four_cycles
)
# directed complete graphs have twice as many 4-cycles thanks to reversal
expected = [2 * e for e in expected]
g_family = [self.D(n) for n in range(1, 15)]
self.check_cycle_enumeration_integer_sequence(
g_family, expected, length_bound=4, algorithm=four_cycles
)
# A006231: the number of elementary circuits in a complete directed graph with n nodes
expected = [0, 1, 5, 20, 84, 409, 2365]
g_family = [self.D(n) for n in range(1, 8)]
self.check_cycle_enumeration_integer_sequence(g_family, expected)
# A002807: Number of cycles in the complete graph on n nodes K_{n}.
expected = [0, 0, 0, 1, 7, 37, 197, 1172]
g_family = [self.K(n) for n in range(8)]
self.check_cycle_enumeration_integer_sequence(g_family, expected)
def test_directed_chordless_cycle_parallel_multiedges(self):
g = nx.MultiGraph()
nx.add_cycle(g, range(5))
expected = [[*range(5)]]
self.check_cycle_algorithm(g, expected, chordless=True)
nx.add_cycle(g, range(5))
expected = [*cycle_edges(range(5))]
self.check_cycle_algorithm(g, expected, chordless=True)
nx.add_cycle(g, range(5))
expected = []
self.check_cycle_algorithm(g, expected, chordless=True)
g = nx.MultiDiGraph()
nx.add_cycle(g, range(5))
expected = [[*range(5)]]
self.check_cycle_algorithm(g, expected, chordless=True)
nx.add_cycle(g, range(5))
self.check_cycle_algorithm(g, [], chordless=True)
nx.add_cycle(g, range(5))
self.check_cycle_algorithm(g, [], chordless=True)
g = nx.MultiDiGraph()
nx.add_cycle(g, range(5))
nx.add_cycle(g, range(5)[::-1])
expected = [*cycle_edges(range(5))]
self.check_cycle_algorithm(g, expected, chordless=True)
nx.add_cycle(g, range(5))
self.check_cycle_algorithm(g, [], chordless=True)
def test_chordless_cycles_graph(self):
G = nx.Graph()
nx.add_cycle(G, range(5))
nx.add_cycle(G, range(4, 12))
expected = [[*range(5)], [*range(4, 12)]]
self.check_cycle_algorithm(G, expected, chordless=True)
self.check_cycle_algorithm(
G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
)
G.add_edge(7, 3)
expected.append([*range(3, 8)])
expected.append([4, 3, 7, 8, 9, 10, 11])
self.check_cycle_algorithm(G, expected, chordless=True)
self.check_cycle_algorithm(
G, [c for c in expected if len(c) <= 5], length_bound=5, chordless=True
)
def test_chordless_cycles_giant_hamiltonian(self):
# ... o - e - o - e - o ... # o = odd, e = even
# ... ---/ \-----/ \--- ... # <-- "long" edges
#
# each long edge belongs to exactly one triangle, and one giant cycle
# of length n/2. The remaining edges each belong to a triangle
n = 1000
assert n % 2 == 0
G = nx.Graph()
for v in range(n):
if not v % 2:
G.add_edge(v, (v + 2) % n)
G.add_edge(v, (v + 1) % n)
expected = [[*range(0, n, 2)]] + [
[x % n for x in range(i, i + 3)] for i in range(0, n, 2)
]
self.check_cycle_algorithm(G, expected, chordless=True)
self.check_cycle_algorithm(
G, [c for c in expected if len(c) <= 3], length_bound=3, chordless=True
)
# ... o -> e -> o -> e -> o ... # o = odd, e = even
# ... <---/ \---<---/ \---< ... # <-- "long" edges
#
# this time, we orient the short and long edges in opposition
# the cycle structure of this graph is the same, but we need to reverse
# the long one in our representation. Also, we need to drop the size
# because our partitioning algorithm uses strongly connected components
# instead of separating graphs by their strong articulation points
n = 100
assert n % 2 == 0
G = nx.DiGraph()
for v in range(n):
G.add_edge(v, (v + 1) % n)
if not v % 2:
G.add_edge((v + 2) % n, v)
expected = [[*range(n - 2, -2, -2)]] + [
[x % n for x in range(i, i + 3)] for i in range(0, n, 2)
]
self.check_cycle_algorithm(G, expected, chordless=True)
self.check_cycle_algorithm(
G, [c for c in expected if len(c) <= 3], length_bound=3, chordless=True
)
def test_simple_cycles_acyclic_tournament(self):
n = 10
G = nx.DiGraph((x, y) for x in range(n) for y in range(x))
self.check_cycle_algorithm(G, [])
self.check_cycle_algorithm(G, [], chordless=True)
for k in range(n + 1):
self.check_cycle_algorithm(G, [], length_bound=k)
self.check_cycle_algorithm(G, [], length_bound=k, chordless=True)
def test_simple_cycles_graph(self):
testG = nx.cycle_graph(8)
cyc1 = tuple(range(8))
self.check_cycle_algorithm(testG, [cyc1])
testG.add_edge(4, -1)
nx.add_path(testG, [3, -2, -3, -4])
self.check_cycle_algorithm(testG, [cyc1])
testG.update(nx.cycle_graph(range(8, 16)))
cyc2 = tuple(range(8, 16))
self.check_cycle_algorithm(testG, [cyc1, cyc2])
testG.update(nx.cycle_graph(range(4, 12)))
cyc3 = tuple(range(4, 12))
expected = {
(0, 1, 2, 3, 4, 5, 6, 7), # cyc1
(8, 9, 10, 11, 12, 13, 14, 15), # cyc2
(4, 5, 6, 7, 8, 9, 10, 11), # cyc3
(4, 5, 6, 7, 8, 15, 14, 13, 12, 11), # cyc2 + cyc3
(0, 1, 2, 3, 4, 11, 10, 9, 8, 7), # cyc1 + cyc3
(0, 1, 2, 3, 4, 11, 12, 13, 14, 15, 8, 7), # cyc1 + cyc2 + cyc3
}
self.check_cycle_algorithm(testG, expected)
assert len(expected) == (2**3 - 1) - 1 # 1 disjoint comb: cyc1 + cyc2
# Basis size = 5 (2 loops overlapping gives 5 small loops
# E
# / \ Note: A-F = 10-15
# 1-2-3-4-5
# / | | \ cyc1=012DAB -- left
# 0 D F 6 cyc2=234E -- top
# \ | | / cyc3=45678F -- right
# B-A-9-8-7 cyc4=89AC -- bottom
# \ / cyc5=234F89AD -- middle
# C
#
# combinations of 5 basis elements: 2^5 - 1 (one includes no cycles)
#
# disjoint combs: (11 total) not simple cycles
# Any pair not including cyc5 => choose(4, 2) = 6
# Any triple not including cyc5 => choose(4, 3) = 4
# Any quad not including cyc5 => choose(4, 4) = 1
#
# we expect 31 - 11 = 20 simple cycles
#
testG = nx.cycle_graph(12)
testG.update(nx.cycle_graph([12, 10, 13, 2, 14, 4, 15, 8]).edges)
expected = (2**5 - 1) - 11 # 11 disjoint combinations
self.check_cycle_algorithm(testG, expected)
def test_simple_cycles_bounded(self):
# iteratively construct a cluster of nested cycles running in the same direction
# there should be one cycle of every length
d = nx.DiGraph()
expected = []
for n in range(10):
nx.add_cycle(d, range(n))
expected.append(n)
for k, e in enumerate(expected):
self.check_cycle_algorithm(d, e, length_bound=k)
# iteratively construct a path of undirected cycles, connected at articulation
# points. there should be one cycle of every length except 2: no digons
g = nx.Graph()
top = 0
expected = []
for n in range(10):
expected.append(n if n < 2 else n - 1)
if n == 2:
# no digons in undirected graphs
continue
nx.add_cycle(g, range(top, top + n))
top += n
for k, e in enumerate(expected):
self.check_cycle_algorithm(g, e, length_bound=k)
def test_simple_cycles_bound_corner_cases(self):
G = nx.cycle_graph(4)
DG = nx.cycle_graph(4, create_using=nx.DiGraph)
assert list(nx.simple_cycles(G, length_bound=0)) == []
assert list(nx.simple_cycles(DG, length_bound=0)) == []
assert list(nx.chordless_cycles(G, length_bound=0)) == []
assert list(nx.chordless_cycles(DG, length_bound=0)) == []
def test_simple_cycles_bound_error(self):
with pytest.raises(ValueError):
G = nx.DiGraph()
for c in nx.simple_cycles(G, -1):
assert False
with pytest.raises(ValueError):
G = nx.Graph()
for c in nx.simple_cycles(G, -1):
assert False
with pytest.raises(ValueError):
G = nx.Graph()
for c in nx.chordless_cycles(G, -1):
assert False
with pytest.raises(ValueError):
G = nx.DiGraph()
for c in nx.chordless_cycles(G, -1):
assert False
def test_chordless_cycles_clique(self):
g_family = [self.K(n) for n in range(2, 15)]
expected = [0, 1, 4, 10, 20, 35, 56, 84, 120, 165, 220, 286, 364]
self.check_cycle_enumeration_integer_sequence(
g_family, expected, chordless=True
)
# directed cliques have as many digons as undirected graphs have edges
expected = [(n * n - n) // 2 for n in range(15)]
g_family = [self.D(n) for n in range(15)]
self.check_cycle_enumeration_integer_sequence(
g_family, expected, chordless=True
)
# These tests might fail with hash randomization since they depend on
# edge_dfs. For more information, see the comments in:
# networkx/algorithms/traversal/tests/test_edgedfs.py
| TestCycleEnumeration |
python | ansible__ansible | test/units/module_utils/basic/test_no_log.py | {
"start": 401,
"end": 1694
} | class ____:
dataset: tuple[tuple[t.Any, frozenset[str]], ...] = (
('string', frozenset(['string'])),
('', frozenset()),
(1, frozenset(['1'])),
(1.0, frozenset(['1.0'])),
(False, frozenset()),
(['1', '2', '3'], frozenset(['1', '2', '3'])),
(('1', '2', '3'), frozenset(['1', '2', '3'])),
({'one': 1, 'two': 'dos'}, frozenset(['1', 'dos'])),
(
{
'one': 1,
'two': 'dos',
'three': [
'amigos', 'musketeers', None, {
'ping': 'pong',
'base': (
'balls', 'raquets'
)
}
]
},
frozenset(['1', 'dos', 'amigos', 'musketeers', 'pong', 'balls', 'raquets'])
),
(u'Toshio くらとみ', frozenset(['Toshio くらとみ'])),
('Toshio くらとみ', frozenset(['Toshio くらとみ'])),
)
def test_return_datastructure_name(self):
for data, expected in self.dataset:
assert frozenset(_return_datastructure_name(data)) == expected
def test_unknown_type(self):
with pytest.raises(Exception):
frozenset(_return_datastructure_name(object()))
| TestReturnValues |
python | scipy__scipy | scipy/stats/_warnings_errors.py | {
"start": 927,
"end": 1196
} | class ____(RuntimeError):
"""Represents an error condition when fitting a distribution to data."""
def __init__(self, msg=None):
if msg is None:
msg = ("An error occurred when fitting a distribution to data.")
self.args = (msg,)
| FitError |
python | kamyu104__LeetCode-Solutions | Python/convert-the-temperature.py | {
"start": 36,
"end": 236
} | class ____(object):
def convertTemperature(self, celsius):
"""
:type celsius: float
:rtype: List[float]
"""
return [celsius+273.15, celsius*1.80+32.00]
| Solution |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/oracle/cx_oracle.py | {
"start": 36924,
"end": 54831
} | class ____(OracleDialect):
supports_statement_cache = True
execution_ctx_cls = OracleExecutionContext_cx_oracle
statement_compiler = OracleCompiler_cx_oracle
supports_sane_rowcount = True
supports_sane_multi_rowcount = True
insert_executemany_returning = True
insert_executemany_returning_sort_by_parameter_order = True
update_executemany_returning = True
delete_executemany_returning = True
bind_typing = interfaces.BindTyping.SETINPUTSIZES
driver = "cx_oracle"
colspecs = util.update_copy(
OracleDialect.colspecs,
{
sqltypes.TIMESTAMP: _CXOracleTIMESTAMP,
sqltypes.Numeric: _OracleNumeric,
sqltypes.Float: _OracleFloat,
oracle.BINARY_FLOAT: _OracleBINARY_FLOAT,
oracle.BINARY_DOUBLE: _OracleBINARY_DOUBLE,
sqltypes.Integer: _OracleInteger,
oracle.NUMBER: _OracleNUMBER,
sqltypes.Date: _CXOracleDate,
sqltypes.LargeBinary: _OracleBinary,
sqltypes.Boolean: oracle._OracleBoolean,
sqltypes.Interval: _OracleInterval,
oracle.INTERVAL: _OracleInterval,
sqltypes.Text: _OracleText,
sqltypes.String: _OracleString,
sqltypes.UnicodeText: _OracleUnicodeTextCLOB,
sqltypes.CHAR: _OracleChar,
sqltypes.NCHAR: _OracleNChar,
sqltypes.Enum: _OracleEnum,
oracle.LONG: _OracleLong,
oracle.RAW: _OracleRaw,
sqltypes.Unicode: _OracleUnicodeStringCHAR,
sqltypes.NVARCHAR: _OracleUnicodeStringNCHAR,
sqltypes.Uuid: _OracleUUID,
oracle.NCLOB: _OracleUnicodeTextNCLOB,
oracle.ROWID: _OracleRowid,
},
)
execute_sequence_format = list
_cursor_var_unicode_kwargs = util.immutabledict()
def __init__(
self,
auto_convert_lobs=True,
coerce_to_decimal=True,
arraysize=None,
encoding_errors=None,
**kwargs,
):
OracleDialect.__init__(self, **kwargs)
self.arraysize = arraysize
self.encoding_errors = encoding_errors
if encoding_errors:
self._cursor_var_unicode_kwargs = {
"encodingErrors": encoding_errors
}
self.auto_convert_lobs = auto_convert_lobs
self.coerce_to_decimal = coerce_to_decimal
if self._use_nchar_for_unicode:
self.colspecs = self.colspecs.copy()
self.colspecs[sqltypes.Unicode] = _OracleUnicodeStringNCHAR
self.colspecs[sqltypes.UnicodeText] = _OracleUnicodeTextNCLOB
dbapi_module = self.dbapi
self._load_version(dbapi_module)
if dbapi_module is not None:
# these constants will first be seen in SQLAlchemy datatypes
# coming from the get_dbapi_type() method. We then
# will place the following types into setinputsizes() calls
# on each statement. Oracle constants that are not in this
# list will not be put into setinputsizes().
self.include_set_input_sizes = {
dbapi_module.DATETIME,
dbapi_module.DB_TYPE_NVARCHAR, # used for CLOB, NCLOB
dbapi_module.DB_TYPE_RAW, # used for BLOB
dbapi_module.NCLOB, # not currently used except for OUT param
dbapi_module.CLOB, # not currently used except for OUT param
dbapi_module.LOB, # not currently used
dbapi_module.BLOB, # not currently used except for OUT param
dbapi_module.NCHAR,
dbapi_module.FIXED_NCHAR,
dbapi_module.FIXED_CHAR,
dbapi_module.TIMESTAMP,
int, # _OracleInteger,
# _OracleBINARY_FLOAT, _OracleBINARY_DOUBLE,
dbapi_module.NATIVE_FLOAT,
}
self._paramval = lambda value: value.getvalue()
def _load_version(self, dbapi_module):
version = (0, 0, 0)
if dbapi_module is not None:
m = re.match(r"(\d+)\.(\d+)(?:\.(\d+))?", dbapi_module.version)
if m:
version = tuple(
int(x) for x in m.group(1, 2, 3) if x is not None
)
self.cx_oracle_ver = version
if self.cx_oracle_ver < (8,) and self.cx_oracle_ver > (0, 0, 0):
raise exc.InvalidRequestError(
"cx_Oracle version 8 and above are supported"
)
@classmethod
def import_dbapi(cls):
import cx_Oracle
return cx_Oracle
def initialize(self, connection):
super().initialize(connection)
self._detect_decimal_char(connection)
def get_isolation_level(self, dbapi_connection):
# sources:
# general idea of transaction id, have to start one, etc.
# https://stackoverflow.com/questions/10711204/how-to-check-isoloation-level
# how to decode xid cols from v$transaction to match
# https://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:9532779900346079444
# Oracle tuple comparison without using IN:
# https://www.sql-workbench.eu/comparison/tuple_comparison.html
with dbapi_connection.cursor() as cursor:
# this is the only way to ensure a transaction is started without
# actually running DML. There's no way to see the configured
# isolation level without getting it from v$transaction which
# means transaction has to be started.
outval = cursor.var(str)
cursor.execute(
"""
begin
:trans_id := dbms_transaction.local_transaction_id( TRUE );
end;
""",
{"trans_id": outval},
)
trans_id = outval.getvalue()
xidusn, xidslot, xidsqn = trans_id.split(".", 2)
cursor.execute(
"SELECT CASE BITAND(t.flag, POWER(2, 28)) "
"WHEN 0 THEN 'READ COMMITTED' "
"ELSE 'SERIALIZABLE' END AS isolation_level "
"FROM v$transaction t WHERE "
"(t.xidusn, t.xidslot, t.xidsqn) = "
"((:xidusn, :xidslot, :xidsqn))",
{"xidusn": xidusn, "xidslot": xidslot, "xidsqn": xidsqn},
)
row = cursor.fetchone()
if row is None:
raise exc.InvalidRequestError(
"could not retrieve isolation level"
)
result = row[0]
return result
def get_isolation_level_values(self, dbapi_connection):
return super().get_isolation_level_values(dbapi_connection) + [
"AUTOCOMMIT"
]
def set_isolation_level(self, dbapi_connection, level):
if level == "AUTOCOMMIT":
dbapi_connection.autocommit = True
else:
dbapi_connection.autocommit = False
dbapi_connection.rollback()
with dbapi_connection.cursor() as cursor:
cursor.execute(f"ALTER SESSION SET ISOLATION_LEVEL={level}")
def detect_autocommit_setting(self, dbapi_conn) -> bool:
return bool(dbapi_conn.autocommit)
def _detect_decimal_char(self, connection):
# we have the option to change this setting upon connect,
# or just look at what it is upon connect and convert.
# to minimize the chance of interference with changes to
# NLS_TERRITORY or formatting behavior of the DB, we opt
# to just look at it
dbapi_connection = connection.connection
with dbapi_connection.cursor() as cursor:
# issue #8744
# nls_session_parameters is not available in some Oracle
# modes like "mount mode". But then, v$nls_parameters is not
# available if the connection doesn't have SYSDBA priv.
#
# simplify the whole thing and just use the method that we were
# doing in the test suite already, selecting a number
def output_type_handler(
cursor, name, defaultType, size, precision, scale
):
return cursor.var(
self.dbapi.STRING, 255, arraysize=cursor.arraysize
)
cursor.outputtypehandler = output_type_handler
cursor.execute("SELECT 1.1 FROM DUAL")
value = cursor.fetchone()[0]
decimal_char = value.lstrip("0")[1]
assert not decimal_char[0].isdigit()
self._decimal_char = decimal_char
if self._decimal_char != ".":
_detect_decimal = self._detect_decimal
_to_decimal = self._to_decimal
self._detect_decimal = lambda value: _detect_decimal(
value.replace(self._decimal_char, ".")
)
self._to_decimal = lambda value: _to_decimal(
value.replace(self._decimal_char, ".")
)
def _detect_decimal(self, value):
if "." in value:
return self._to_decimal(value)
else:
return int(value)
_to_decimal = decimal.Decimal
def _generate_connection_outputtype_handler(self):
"""establish the default outputtypehandler established at the
connection level.
"""
dialect = self
cx_Oracle = dialect.dbapi
number_handler = _OracleNUMBER(
asdecimal=True
)._cx_oracle_outputtypehandler(dialect)
float_handler = _OracleNUMBER(
asdecimal=False
)._cx_oracle_outputtypehandler(dialect)
def output_type_handler(
cursor, name, default_type, size, precision, scale
):
if (
default_type == cx_Oracle.NUMBER
and default_type is not cx_Oracle.NATIVE_FLOAT
):
if not dialect.coerce_to_decimal:
return None
elif precision == 0 and scale in (0, -127):
# ambiguous type, this occurs when selecting
# numbers from deep subqueries
return cursor.var(
cx_Oracle.STRING,
255,
outconverter=dialect._detect_decimal,
arraysize=cursor.arraysize,
)
elif precision and scale > 0:
return number_handler(
cursor, name, default_type, size, precision, scale
)
else:
return float_handler(
cursor, name, default_type, size, precision, scale
)
# if unicode options were specified, add a decoder, otherwise
# cx_Oracle should return Unicode
elif (
dialect._cursor_var_unicode_kwargs
and default_type
in (
cx_Oracle.STRING,
cx_Oracle.FIXED_CHAR,
)
and default_type is not cx_Oracle.CLOB
and default_type is not cx_Oracle.NCLOB
):
return cursor.var(
str,
size,
cursor.arraysize,
**dialect._cursor_var_unicode_kwargs,
)
elif dialect.auto_convert_lobs and default_type in (
cx_Oracle.CLOB,
cx_Oracle.NCLOB,
):
typ = (
cx_Oracle.DB_TYPE_VARCHAR
if default_type is cx_Oracle.CLOB
else cx_Oracle.DB_TYPE_NVARCHAR
)
return cursor.var(
typ,
_CX_ORACLE_MAGIC_LOB_SIZE,
cursor.arraysize,
**dialect._cursor_var_unicode_kwargs,
)
elif dialect.auto_convert_lobs and default_type in (
cx_Oracle.BLOB,
):
return cursor.var(
cx_Oracle.DB_TYPE_RAW,
_CX_ORACLE_MAGIC_LOB_SIZE,
cursor.arraysize,
)
return output_type_handler
def on_connect(self):
output_type_handler = self._generate_connection_outputtype_handler()
def on_connect(conn):
conn.outputtypehandler = output_type_handler
return on_connect
def create_connect_args(self, url):
opts = dict(url.query)
database = url.database
service_name = opts.pop("service_name", None)
if database or service_name:
# if we have a database, then we have a remote host
port = url.port
if port:
port = int(port)
else:
port = 1521
if database and service_name:
raise exc.InvalidRequestError(
'"service_name" option shouldn\'t '
'be used with a "database" part of the url'
)
if database:
makedsn_kwargs = {"sid": database}
if service_name:
makedsn_kwargs = {"service_name": service_name}
dsn = self.dbapi.makedsn(url.host, port, **makedsn_kwargs)
else:
# we have a local tnsname
dsn = url.host
if dsn is not None:
opts["dsn"] = dsn
if url.password is not None:
opts["password"] = url.password
if url.username is not None:
opts["user"] = url.username
def convert_cx_oracle_constant(value):
if isinstance(value, str):
try:
int_val = int(value)
except ValueError:
value = value.upper()
return getattr(self.dbapi, value)
else:
return int_val
else:
return value
util.coerce_kw_type(opts, "mode", convert_cx_oracle_constant)
util.coerce_kw_type(opts, "threaded", bool)
util.coerce_kw_type(opts, "events", bool)
util.coerce_kw_type(opts, "purity", convert_cx_oracle_constant)
return ([], opts)
def _get_server_version_info(self, connection):
return tuple(int(x) for x in connection.connection.version.split("."))
def is_disconnect(self, e, connection, cursor):
(error,) = e.args
if isinstance(
e, (self.dbapi.InterfaceError, self.dbapi.DatabaseError)
) and "not connected" in str(e):
return True
if hasattr(error, "code") and error.code in {
28,
3114,
3113,
3135,
1033,
2396,
}:
# ORA-00028: your session has been killed
# ORA-03114: not connected to ORACLE
# ORA-03113: end-of-file on communication channel
# ORA-03135: connection lost contact
# ORA-01033: ORACLE initialization or shutdown in progress
# ORA-02396: exceeded maximum idle time, please connect again
# TODO: Others ?
return True
if re.match(r"^(?:DPI-1010|DPI-1080|DPY-1001|DPY-4011)", str(e)):
# DPI-1010: not connected
# DPI-1080: connection was closed by ORA-3113
# python-oracledb's DPY-1001: not connected to database
# python-oracledb's DPY-4011: the database or network closed the
# connection
# TODO: others?
return True
return False
def create_xid(self):
id_ = random.randint(0, 2**128)
return (0x1234, "%032x" % id_, "%032x" % 9)
def do_executemany(self, cursor, statement, parameters, context=None):
if isinstance(parameters, tuple):
parameters = list(parameters)
cursor.executemany(statement, parameters)
def do_begin_twophase(self, connection, xid):
connection.connection.begin(*xid)
connection.connection.info["cx_oracle_xid"] = xid
def do_prepare_twophase(self, connection, xid):
result = connection.connection.prepare()
connection.info["cx_oracle_prepared"] = result
def do_rollback_twophase(
self, connection, xid, is_prepared=True, recover=False
):
self.do_rollback(connection.connection)
# TODO: need to end XA state here
def do_commit_twophase(
self, connection, xid, is_prepared=True, recover=False
):
if not is_prepared:
self.do_commit(connection.connection)
else:
if recover:
raise NotImplementedError(
"2pc recovery not implemented for cx_Oracle"
)
oci_prepared = connection.info["cx_oracle_prepared"]
if oci_prepared:
self.do_commit(connection.connection)
# TODO: need to end XA state here
def do_set_input_sizes(self, cursor, list_of_tuples, context):
if self.positional:
# not usually used, here to support if someone is modifying
# the dialect to use positional style
cursor.setinputsizes(
*[dbtype for key, dbtype, sqltype in list_of_tuples]
)
else:
collection = (
(key, dbtype)
for key, dbtype, sqltype in list_of_tuples
if dbtype
)
cursor.setinputsizes(**{key: dbtype for key, dbtype in collection})
def do_recover_twophase(self, connection):
raise NotImplementedError(
"recover two phase query for cx_Oracle not implemented"
)
dialect = OracleDialect_cx_oracle
| OracleDialect_cx_oracle |
python | ApeWorX__ape | src/ape/managers/project.py | {
"start": 40232,
"end": 41819
} | class ____(dict[str, "ProjectManager"]):
"""
A mapping of versions to dependencies.
This class exists to allow both v-prefixed versions
as well none v-prefixed versions.
"""
def __init__(self, name: str):
self._name = name
super().__init__()
@log_instead_of_fail(default="<DependencyVersionMap>")
def __repr__(self) -> str:
keys = ",".join(list(self.keys()))
return f"<{self._name} versions='{keys}'>"
def __contains__(self, version: Any) -> bool:
if not isinstance(version, str):
return False
options = _version_to_options(version)
return any(dict.__contains__(self, v) for v in options) # type: ignore
def __getitem__(self, version: str) -> "ProjectManager":
options = _version_to_options(version)
for vers in options:
if not dict.__contains__(self, vers): # type: ignore
continue
# Found.
return dict.__getitem__(self, vers) # type: ignore
raise KeyError(version)
def get( # type: ignore
self, version: str, default: Optional["ProjectManager"] = None
) -> Optional["ProjectManager"]:
options = _version_to_options(version)
for vers in options:
if not dict.__contains__(self, vers): # type: ignore
continue
# Found.
return dict.get(self, vers) # type: ignore
return default
def extend(self, data: dict):
for key, val in data.items():
self[key] = val
| DependencyVersionMap |
python | django__django | tests/admin_docs/views.py | {
"start": 391,
"end": 489
} | class ____(View):
def __call__(self, request):
return HttpResponse()
| XViewCallableObject |
python | dask__dask | dask/dataframe/dask_expr/_reductions.py | {
"start": 23193,
"end": 23333
} | class ____(PivotTableAbstract):
chunk = staticmethod(methods.pivot_sum)
aggregate_func = staticmethod(methods.pivot_agg)
| PivotTableSum |
python | openai__openai-python | src/openai/resources/realtime/realtime.py | {
"start": 22438,
"end": 23512
} | class ____(BaseRealtimeConnectionResource):
def update(self, *, session: session_update_event_param.Session, event_id: str | Omit = omit) -> None:
"""
Send this event to update the session’s configuration.
The client may send this event at any time to update any field
except for `voice` and `model`. `voice` can be updated only if there have been no other audio outputs yet.
When the server receives a `session.update`, it will respond
with a `session.updated` event showing the full, effective configuration.
Only the fields that are present in the `session.update` are updated. To clear a field like
`instructions`, pass an empty string. To clear a field like `tools`, pass an empty array.
To clear a field like `turn_detection`, pass `null`.
"""
self._connection.send(
cast(
RealtimeClientEventParam,
strip_not_given({"type": "session.update", "session": session, "event_id": event_id}),
)
)
| RealtimeSessionResource |
python | pandas-dev__pandas | pandas/_config/config.py | {
"start": 2566,
"end": 3069
} | class ____(NamedTuple):
key: str
defval: Any
doc: str
validator: Callable[[object], Any] | None
cb: Callable[[str], Any] | None
# holds deprecated option metadata
_deprecated_options: dict[str, DeprecatedOption] = {}
# holds registered option metadata
_registered_options: dict[str, RegisteredOption] = {}
# holds the current values for registered options
_global_config: dict[str, Any] = {}
# keys which have a special meaning
_reserved_keys: list[str] = ["all"]
| RegisteredOption |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/hooks/test_wasb.py | {
"start": 2238,
"end": 33493
} | class ____:
@pytest.fixture(autouse=True)
def setup_method(self, create_mock_connections):
self.login = "login"
self.wasb_test_key = "wasb_test_key"
self.connection_type = "wasb"
self.azure_test_connection_string = "azure_test_connection_string"
self.azure_shared_key_test = "azure_shared_key_test"
self.ad_conn_id = "ad_conn_id"
self.sas_conn_id = "sas_token_id"
self.extra__wasb__sas_conn_id = "extra__wasb__sas_conn_id"
self.http_sas_conn_id = "http_sas_conn_id"
self.extra__wasb__http_sas_conn_id = "extra__wasb__http_sas_conn_id"
self.public_read_conn_id = "pub_read_id"
self.public_read_conn_id_without_host = "pub_read_id_without_host"
self.managed_identity_conn_id = "managed_identity_conn_id"
self.account_key_conn_id = "account_key_conn_id"
self.authority = "https://test_authority.com"
self.proxies = PROXIES
self.client_secret_auth_config = {
"proxies": self.proxies,
"connection_verify": False,
"authority": self.authority,
}
conns = create_mock_connections(
Connection(
conn_id="wasb_test_key",
conn_type=self.connection_type,
login=self.login,
password="key",
),
Connection(
conn_id=self.public_read_conn_id,
conn_type=self.connection_type,
host="https://accountname.blob.core.windows.net",
extra={"proxies": self.proxies},
),
Connection(
conn_id=self.public_read_conn_id_without_host,
conn_type=self.connection_type,
login=self.login,
extra={"proxies": self.proxies},
),
Connection(
conn_id=self.azure_test_connection_string,
conn_type=self.connection_type,
extra={"connection_string": CONN_STRING, "proxies": self.proxies},
),
Connection(
conn_id=self.azure_shared_key_test,
conn_type=self.connection_type,
host="https://accountname.blob.core.windows.net",
extra={"shared_access_key": "token", "proxies": self.proxies},
),
Connection(
conn_id=self.ad_conn_id,
conn_type=self.connection_type,
host="conn_host",
login="appID",
password="appsecret",
extra={
"tenant_id": "token",
"proxies": self.proxies,
"client_secret_auth_config": self.client_secret_auth_config,
},
),
Connection(
conn_id=self.managed_identity_conn_id,
conn_type=self.connection_type,
extra={"proxies": self.proxies},
),
Connection(
conn_id=self.account_key_conn_id,
conn_type=self.connection_type,
login="testaccount",
extra={"account_key": "test_account_key", "proxies": self.proxies},
),
Connection(
conn_id="sas_conn_id",
conn_type=self.connection_type,
login=self.login,
extra={"sas_token": "token", "proxies": self.proxies},
),
Connection(
conn_id=self.extra__wasb__sas_conn_id,
conn_type=self.connection_type,
login=self.login,
extra={"extra__wasb__sas_token": "token", "proxies": self.proxies},
),
Connection(
conn_id=self.http_sas_conn_id,
conn_type=self.connection_type,
extra={"sas_token": "https://login.blob.core.windows.net/token", "proxies": self.proxies},
),
Connection(
conn_id=self.extra__wasb__http_sas_conn_id,
conn_type=self.connection_type,
extra={
"extra__wasb__sas_token": "https://login.blob.core.windows.net/token",
"proxies": self.proxies,
},
),
)
self.connection_map = {conn.conn_id: conn for conn in conns}
def test_key(self, mocked_blob_service_client):
hook = WasbHook(wasb_conn_id=self.wasb_test_key)
mocked_blob_service_client.assert_not_called() # Not expected during initialisation
hook.get_conn()
mocked_blob_service_client.assert_called_once_with(
account_url=f"https://{self.login}.blob.core.windows.net/", credential="key"
)
def test_public_read(self, mocked_blob_service_client):
WasbHook(wasb_conn_id=self.public_read_conn_id, public_read=True).get_conn()
mocked_blob_service_client.assert_called_once_with(
account_url="https://accountname.blob.core.windows.net", proxies=self.proxies
)
def test_connection_string(self, mocked_blob_service_client):
WasbHook(wasb_conn_id=self.azure_test_connection_string).get_conn()
mocked_blob_service_client.from_connection_string.assert_called_once_with(
CONN_STRING, proxies=self.proxies, connection_string=CONN_STRING
)
def test_shared_key_connection(self, mocked_blob_service_client):
WasbHook(wasb_conn_id=self.azure_shared_key_test).get_conn()
mocked_blob_service_client.assert_called_once_with(
account_url="https://accountname.blob.core.windows.net",
credential="token",
proxies=self.proxies,
shared_access_key="token",
)
def test_blob_service_client_setter_overrides_cache(self, monkeypatch):
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
default_client = mock.MagicMock(name="default_client")
monkeypatch.setattr(hook, "get_conn", mock.MagicMock(return_value=default_client))
hook._blob_service_client = None
assert hook.blob_service_client is default_client
hook.get_conn.assert_called_once()
new_client = mock.MagicMock(name="new_client")
hook.blob_service_client = new_client
hook.get_conn.reset_mock()
assert hook.blob_service_client is new_client
hook.get_conn.assert_not_called()
def test_managed_identity(self, mocked_default_azure_credential, mocked_blob_service_client):
mocked_default_azure_credential.assert_not_called()
mocked_default_azure_credential.return_value = "foo-bar"
WasbHook(wasb_conn_id=self.managed_identity_conn_id).get_conn()
mocked_default_azure_credential.assert_called_with(
managed_identity_client_id=None, workload_identity_tenant_id=None
)
mocked_blob_service_client.assert_called_once_with(
account_url="https://None.blob.core.windows.net/",
credential="foo-bar",
proxies=self.proxies,
)
def test_azure_directory_connection(self, mocked_client_secret_credential, mocked_blob_service_client):
mocked_client_secret_credential.return_value = "spam-egg"
WasbHook(wasb_conn_id=self.ad_conn_id).get_conn()
mocked_client_secret_credential.assert_called_once_with(
tenant_id="token",
client_id="appID",
client_secret="appsecret",
proxies=self.client_secret_auth_config["proxies"],
connection_verify=self.client_secret_auth_config["connection_verify"],
authority=self.client_secret_auth_config["authority"],
)
mocked_blob_service_client.assert_called_once_with(
account_url="https://appID.blob.core.windows.net/",
credential="spam-egg",
tenant_id="token",
proxies=self.proxies,
)
def test_variable_type_checking(self):
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
ok_container = object.__new__(ContainerClient)
hook.check_for_variable_type("container", ok_container, ContainerClient)
wrong_container = object.__new__(BlobServiceClient)
with pytest.raises(TypeError) as ei:
hook.check_for_variable_type("container", wrong_container, ContainerClient)
msg = str(ei.value)
for s in ["container", "WasbHook", "ContainerClient", "BlobServiceClient"]:
assert s in msg
def test_account_key_connection(self, mocked_blob_service_client):
"""Test that account_key from extra is used when no password is provided."""
WasbHook(wasb_conn_id=self.account_key_conn_id).get_conn()
mocked_blob_service_client.assert_called_once_with(
account_url="https://testaccount.blob.core.windows.net/",
credential="test_account_key",
proxies=self.proxies,
account_key="test_account_key",
)
@pytest.mark.parametrize(
"mocked_connection",
[
Connection(
conn_id="testconn",
conn_type="wasb",
login="testaccountname",
host="testaccountID",
)
],
indirect=True,
)
def test_active_directory_id_used_as_host(
self, mocked_connection, mocked_default_azure_credential, mocked_blob_service_client
):
mocked_default_azure_credential.return_value = "fake-credential"
WasbHook(wasb_conn_id="testconn").get_conn()
mocked_blob_service_client.assert_called_once_with(
account_url="https://testaccountname.blob.core.windows.net/",
credential="fake-credential",
)
@pytest.mark.parametrize(
"mocked_connection",
[
Connection(
conn_id="testconn",
conn_type="wasb",
login="testaccountname",
host="testaccountID",
extra={"sas_token": "SAStoken"},
)
],
indirect=True,
)
def test_sas_token_provided_and_active_directory_id_used_as_host(
self, mocked_connection, mocked_blob_service_client
):
WasbHook(wasb_conn_id="testconn").get_conn()
mocked_blob_service_client.assert_called_once_with(
account_url="https://testaccountname.blob.core.windows.net/SAStoken",
sas_token="SAStoken",
)
@pytest.mark.parametrize(
"mocked_connection",
[
pytest.param(
Connection(
conn_type="wasb",
login="foo",
extra={"shared_access_key": "token", "proxies": PROXIES},
),
id="shared-key-without-host",
),
pytest.param(
Connection(conn_type="wasb", login="foo", extra={"proxies": PROXIES}),
id="public-read-without-host",
),
],
indirect=True,
)
def test_account_url_without_host(
self, mocked_connection, mocked_blob_service_client, mocked_default_azure_credential
):
mocked_default_azure_credential.return_value = "default-creds"
WasbHook(wasb_conn_id=mocked_connection.conn_id).get_conn()
if "shared_access_key" in mocked_connection.extra_dejson:
mocked_blob_service_client.assert_called_once_with(
account_url=f"https://{mocked_connection.login}.blob.core.windows.net/",
credential=mocked_connection.extra_dejson["shared_access_key"],
proxies=mocked_connection.extra_dejson["proxies"],
shared_access_key=mocked_connection.extra_dejson["shared_access_key"],
)
else:
mocked_blob_service_client.assert_called_once_with(
account_url=f"https://{mocked_connection.login}.blob.core.windows.net/",
credential="default-creds",
proxies=mocked_connection.extra_dejson["proxies"],
)
@pytest.mark.parametrize(
argnames=("conn_id_str", "extra_key"),
argvalues=[
("sas_conn_id", "sas_token"),
("extra__wasb__sas_conn_id", "extra__wasb__sas_token"),
("http_sas_conn_id", "sas_token"),
("extra__wasb__http_sas_conn_id", "extra__wasb__sas_token"),
],
)
def test_sas_token_connection(self, conn_id_str, extra_key):
hook = WasbHook(wasb_conn_id=conn_id_str)
conn = hook.get_conn()
hook_conn = hook.get_connection(hook.conn_id)
sas_token = hook_conn.extra_dejson[extra_key]
assert isinstance(conn, BlobServiceClient)
assert conn.url.startswith("https://")
if hook_conn.login:
assert hook_conn.login in conn.url
assert conn.url.endswith(sas_token + "/")
@pytest.mark.parametrize(
argnames="conn_id_str",
argvalues=[
"azure_test_connection_string",
"azure_shared_key_test",
"ad_conn_id",
"managed_identity_conn_id",
"account_key_conn_id",
"sas_conn_id",
"extra__wasb__sas_conn_id",
"http_sas_conn_id",
"extra__wasb__http_sas_conn_id",
],
)
def test_connection_extra_arguments(self, conn_id_str):
conn = WasbHook(wasb_conn_id=conn_id_str).get_conn()
assert conn._config.proxy_policy.proxies == self.proxies
def test_connection_extra_arguments_public_read(self):
hook = WasbHook(wasb_conn_id=self.public_read_conn_id, public_read=True)
conn = hook.get_conn()
assert conn._config.proxy_policy.proxies == self.proxies
def test_extra_client_secret_auth_config_ad_connection(self):
hook = WasbHook(wasb_conn_id=self.ad_conn_id)
conn = hook.get_conn()
assert conn.credential._authority == self.authority
@pytest.mark.parametrize(
("provided_host", "expected_host"),
[
(
"https://testaccountname.blob.core.windows.net",
"https://testaccountname.blob.core.windows.net",
),
("testhost", "https://accountlogin.blob.core.windows.net/"),
("testhost.dns", "https://testhost.dns"),
("testhost.blob.net", "https://testhost.blob.net"),
(
"testhostakjhdisdfbearioyo.blob.core.windows.net",
"https://testhostakjhdisdfbearioy.blob.core.windows.net",
), # more than 24 characters
],
)
def test_proper_account_url_update(
self, mocked_blob_service_client, provided_host, expected_host, create_mock_connection
):
conn = create_mock_connection(
Connection(
conn_type=self.connection_type,
password="testpass",
login="accountlogin",
host=provided_host,
)
)
WasbHook(wasb_conn_id=conn.conn_id).get_conn()
mocked_blob_service_client.assert_called_once_with(account_url=expected_host, credential="testpass")
def test_check_for_blob(self, mocked_blob_service_client):
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
assert hook.check_for_blob(container_name="mycontainer", blob_name="myblob")
mock_blob_client = mocked_blob_service_client.return_value.get_blob_client
mock_blob_client.assert_called_once_with(container="mycontainer", blob="myblob")
mock_blob_client.return_value.get_blob_properties.assert_called()
@mock.patch.object(WasbHook, "get_blobs_list", return_value=["blobs"])
def test_check_for_prefix(self, get_blobs_list):
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
assert hook.check_for_prefix("container", "prefix", timeout=3)
get_blobs_list.assert_called_once_with(container_name="container", prefix="prefix", timeout=3)
@mock.patch.object(WasbHook, "get_blobs_list", return_value=[])
def test_check_for_prefix_empty(self, get_blobs_list):
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
assert not hook.check_for_prefix("container", "prefix", timeout=3)
get_blobs_list.assert_called_once_with(container_name="container", prefix="prefix", timeout=3)
def test_get_blobs_list(self, mocked_blob_service_client):
mock_container = create_autospec(ContainerClient, instance=True)
mocked_blob_service_client.return_value.get_container_client.return_value = mock_container
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
hook.get_blobs_list(container_name="mycontainer", prefix="my", include=None, delimiter="/")
mock_container_client = mocked_blob_service_client.return_value.get_container_client
mock_container_client.assert_called_once_with("mycontainer")
mock_container_client.return_value.walk_blobs.assert_called_once_with(
name_starts_with="my", include=None, delimiter="/"
)
def test_get_blobs_list_recursive(self, mocked_blob_service_client):
mock_container = create_autospec(ContainerClient, instance=True)
mocked_blob_service_client.return_value.get_container_client.return_value = mock_container
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
hook.get_blobs_list_recursive(
container_name="mycontainer", prefix="test", include=None, endswith="file_extension"
)
mock_container_client = mocked_blob_service_client.return_value.get_container_client
mock_container_client.assert_called_once_with("mycontainer")
mock_container_client.return_value.list_blobs.assert_called_once_with(
name_starts_with="test", include=None
)
def test_get_blobs_list_recursive_endswith(self, mocked_blob_service_client):
mock_container = create_autospec(ContainerClient, instance=True)
mocked_blob_service_client.return_value.get_container_client.return_value = mock_container
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
mocked_blob_service_client.return_value.get_container_client.return_value.list_blobs.return_value = [
BlobProperties(name="test/abc.py"),
BlobProperties(name="test/inside_test/abc.py"),
BlobProperties(name="test/abc.csv"),
]
blob_list_output = hook.get_blobs_list_recursive(
container_name="mycontainer", prefix="test", include=None, endswith=".py"
)
assert blob_list_output == ["test/abc.py", "test/inside_test/abc.py"]
@pytest.mark.parametrize(argnames="create_container", argvalues=[True, False])
@mock.patch.object(WasbHook, "upload")
def test_load_file(self, mock_upload, create_container):
with mock.patch("builtins.open", mock.mock_open(read_data="data")):
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
hook.load_file("path", "container", "blob", create_container, max_connections=1)
mock_upload.assert_called_with(
container_name="container",
blob_name="blob",
data=mock.ANY,
create_container=create_container,
max_connections=1,
)
@pytest.mark.parametrize(argnames="create_container", argvalues=[True, False])
@mock.patch.object(WasbHook, "upload")
def test_load_string(self, mock_upload, create_container):
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
hook.load_string("big string", "container", "blob", create_container, max_connections=1)
mock_upload.assert_called_once_with(
container_name="container",
blob_name="blob",
data="big string",
create_container=create_container,
max_connections=1,
)
@mock.patch.object(WasbHook, "download")
def test_get_file(self, mock_download):
with mock.patch("builtins.open", mock.mock_open(read_data="data")):
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
hook.get_file("path", "container", "blob", max_connections=1)
mock_download.assert_called_once_with(container_name="container", blob_name="blob", max_connections=1)
mock_download.return_value.readall.assert_called()
@mock.patch.object(WasbHook, "download")
def test_read_file(self, mock_download, mocked_blob_service_client):
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
hook.read_file("container", "blob", max_connections=1)
mock_download.assert_called_once_with("container", "blob", max_connections=1)
@pytest.mark.parametrize(argnames="create_container", argvalues=[True, False])
def test_upload(self, mocked_blob_service_client, create_container):
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
hook.upload(
container_name="mycontainer",
blob_name="myblob",
data=b"mydata",
create_container=create_container,
blob_type="BlockBlob",
length=4,
)
mock_blob_client = mocked_blob_service_client.return_value.get_blob_client
mock_blob_client.assert_called_once_with(container="mycontainer", blob="myblob")
mock_blob_client.return_value.upload_blob.assert_called_once_with(b"mydata", "BlockBlob", length=4)
mock_container_client = mocked_blob_service_client.return_value.get_container_client
if create_container:
mock_container_client.assert_called_with("mycontainer")
else:
mock_container_client.assert_not_called()
def test_download(self, mocked_blob_service_client):
blob_client = mocked_blob_service_client.return_value.get_blob_client
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
hook.download(container_name="mycontainer", blob_name="myblob", offset=2, length=4)
blob_client.assert_called_once_with(container="mycontainer", blob="myblob")
blob_client.return_value.download_blob.assert_called_once_with(offset=2, length=4)
def test_get_container_client(self, mocked_blob_service_client):
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
hook._get_container_client("mycontainer")
mocked_blob_service_client.return_value.get_container_client.assert_called_once_with("mycontainer")
def test_get_blob_client(self, mocked_blob_service_client):
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
hook._get_blob_client(container_name="mycontainer", blob_name="myblob")
mock_instance = mocked_blob_service_client.return_value.get_blob_client
mock_instance.assert_called_once_with(container="mycontainer", blob="myblob")
def test_create_container(self, mocked_blob_service_client):
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
hook.create_container(container_name="mycontainer")
mock_instance = mocked_blob_service_client.return_value.get_container_client
mock_instance.assert_called_once_with("mycontainer")
mock_instance.return_value.create_container.assert_called()
def test_delete_container(self, mocked_blob_service_client):
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
hook.delete_container("mycontainer")
mocked_container_client = mocked_blob_service_client.return_value.get_container_client
mocked_container_client.assert_called_once_with("mycontainer")
mocked_container_client.return_value.delete_container.assert_called()
@pytest.mark.parametrize("exc", [ValueError, RuntimeError])
def test_delete_container_generic_exception(self, exc: type[Exception]):
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
with (
mock.patch.object(WasbHook, "_get_container_client") as m,
mock.patch.object(hook.log, "error") as log_mock,
):
m.return_value.delete_container.side_effect = exc("FakeException")
with pytest.raises(exc, match="FakeException"):
hook.delete_container("mycontainer")
log_mock.assert_called_with("Error deleting container: %s", "mycontainer")
def test_delete_container_resource_not_found(self):
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
with (
mock.patch.object(WasbHook, "_get_container_client") as m,
mock.patch.object(hook.log, "warning") as log_mock,
):
m.return_value.delete_container.side_effect = ResourceNotFoundError("FakeException")
hook.delete_container("mycontainer")
log_mock.assert_called_with("Unable to delete container %s (not found)", "mycontainer")
@mock.patch.object(WasbHook, "delete_blobs")
def test_delete_single_blob(self, delete_blobs, mocked_blob_service_client):
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
hook.delete_file("container", "blob", is_prefix=False)
delete_blobs.assert_called_once_with("container", "blob")
@mock.patch.object(WasbHook, "delete_blobs")
@mock.patch.object(WasbHook, "get_blobs_list")
@mock.patch.object(WasbHook, "check_for_blob")
def test_delete_multiple_blobs(self, mock_check, mock_get_blobslist, mock_delete_blobs):
mock_check.return_value = False
mock_get_blobslist.return_value = ["blob_prefix/blob1", "blob_prefix/blob2"]
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
hook.delete_file("container", "blob_prefix", is_prefix=True)
mock_get_blobslist.assert_called_once_with("container", prefix="blob_prefix", delimiter="")
mock_delete_blobs.assert_any_call(
"container",
"blob_prefix/blob1",
"blob_prefix/blob2",
)
assert mock_delete_blobs.call_count == 1
@mock.patch.object(WasbHook, "delete_blobs")
@mock.patch.object(WasbHook, "get_blobs_list")
@mock.patch.object(WasbHook, "check_for_blob")
def test_delete_more_than_256_blobs(self, mock_check, mock_get_blobslist, mock_delete_blobs):
mock_check.return_value = False
mock_get_blobslist.return_value = [f"blob_prefix/blob{i}" for i in range(300)]
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
hook.delete_file("container", "blob_prefix", is_prefix=True)
mock_get_blobslist.assert_called_once_with("container", prefix="blob_prefix", delimiter="")
# The maximum number of blobs that can be deleted in a single request is 256 using the underlying
# `ContainerClient.delete_blobs()` method. Therefore the deletes need to be in batches of <= 256.
# Therefore, providing a list of 300 blobs to delete should yield 2 calls of
# `ContainerClient.delete_blobs()` in this test.
assert mock_delete_blobs.call_count == 2
@mock.patch.object(WasbHook, "_get_blob_client")
def test_copy_blobs(self, mock_get_blob_client):
# Arrange
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
source_container_name = "source-container"
source_blob_name = "source-blob"
destination_container_name = "destination-container"
destination_blob_name = "destination-blob"
# Mock the blob clients
mock_source_blob_client = mock.MagicMock()
mock_destination_blob_client = mock.MagicMock()
mock_get_blob_client.side_effect = [mock_source_blob_client, mock_destination_blob_client]
# Mock the URL of the source blob
mock_source_blob_client.url = "https://source-url"
hook.copy_blobs(
source_container_name, source_blob_name, destination_container_name, destination_blob_name
)
mock_get_blob_client.assert_any_call(container_name=source_container_name, blob_name=source_blob_name)
mock_get_blob_client.assert_any_call(
container_name=destination_container_name, blob_name=destination_blob_name
)
mock_destination_blob_client.start_copy_from_url.assert_called_once_with("https://source-url")
@mock.patch.object(WasbHook, "get_blobs_list")
@mock.patch.object(WasbHook, "check_for_blob")
def test_delete_nonexisting_blob_fails(self, mock_check, mock_getblobs, mocked_blob_service_client):
mock_getblobs.return_value = []
mock_check.return_value = False
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
with pytest.raises(AirflowException, match=re.escape("Blob(s) not found: nonexisting_blob")):
hook.delete_file("container", "nonexisting_blob", is_prefix=False, ignore_if_missing=False)
@mock.patch.object(WasbHook, "get_blobs_list")
def test_delete_multiple_nonexisting_blobs_fails(self, mock_getblobs):
mock_getblobs.return_value = []
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
with pytest.raises(AirflowException, match=re.escape("Blob(s) not found: nonexisting_blob_prefix")):
hook.delete_file("container", "nonexisting_blob_prefix", is_prefix=True, ignore_if_missing=False)
def test_connection_success(self, mocked_blob_service_client):
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
hook.get_conn().get_account_information().return_value = {
"sku_name": "Standard_RAGRS",
"account_kind": "StorageV2",
}
status, msg = hook.test_connection()
assert status is True
assert msg == "Successfully connected to Azure Blob Storage."
def test_connection_failure(self, mocked_blob_service_client):
hook = WasbHook(wasb_conn_id=self.azure_shared_key_test)
hook.get_conn().get_account_information = mock.PropertyMock(
side_effect=Exception("Authentication failed.")
)
status, msg = hook.test_connection()
assert status is False
assert msg == "Authentication failed."
@pytest.mark.parametrize(
"conn_id_str",
[
"wasb_test_key",
"pub_read_id",
"pub_read_id_without_host",
"azure_test_connection_string",
"azure_shared_key_test",
"ad_conn_id",
"managed_identity_conn_id",
"account_key_conn_id",
"sas_conn_id",
"extra__wasb__sas_conn_id",
"http_sas_conn_id",
"extra__wasb__http_sas_conn_id",
],
)
def test_extract_account_name_from_connection(self, conn_id_str, mocked_blob_service_client):
expected_account_name = "testname"
if conn_id_str == "azure_test_connection_string":
mocked_blob_service_client.from_connection_string().account_name = expected_account_name
else:
mocked_blob_service_client.return_value.account_name = expected_account_name
wasb_hook = WasbHook(wasb_conn_id=conn_id_str)
account_name = wasb_hook.get_conn().account_name
assert account_name == expected_account_name, (
f"Expected account name {expected_account_name} but got {account_name}"
)
| TestWasbHook |
python | readthedocs__readthedocs.org | readthedocs/organizations/tests/test_views.py | {
"start": 16745,
"end": 17405
} | class ____(RequestFactoryTestMixin, TestCase):
"""Tests for invite handling in views."""
def setUp(self):
self.owner = get(User)
self.organization = get(
Organization,
owners=[self.owner],
)
self.team = get(Team, organization=self.organization)
def test_redirect(self):
token = "123345"
resp = self.client.get(reverse("organization_invite_redeem", args=[token]))
self.assertEqual(resp.status_code, 302)
self.assertEqual(resp["location"], reverse("invitations_redeem", args=[token]))
@override_settings(RTD_ALLOW_ORGANIZATIONS=True)
| OrganizationInviteViewTests |
python | wandb__wandb | wandb/vendor/pygments/lexers/c_like.py | {
"start": 10577,
"end": 12813
} | class ____(CLexer):
"""
For NVIDIA `CUDA™ <http://developer.nvidia.com/category/zone/cuda-zone>`_
source.
.. versionadded:: 1.6
"""
name = 'CUDA'
filenames = ['*.cu', '*.cuh']
aliases = ['cuda', 'cu']
mimetypes = ['text/x-cuda']
function_qualifiers = set(('__device__', '__global__', '__host__',
'__noinline__', '__forceinline__'))
variable_qualifiers = set(('__device__', '__constant__', '__shared__',
'__restrict__'))
vector_types = set(('char1', 'uchar1', 'char2', 'uchar2', 'char3', 'uchar3',
'char4', 'uchar4', 'short1', 'ushort1', 'short2', 'ushort2',
'short3', 'ushort3', 'short4', 'ushort4', 'int1', 'uint1',
'int2', 'uint2', 'int3', 'uint3', 'int4', 'uint4', 'long1',
'ulong1', 'long2', 'ulong2', 'long3', 'ulong3', 'long4',
'ulong4', 'longlong1', 'ulonglong1', 'longlong2',
'ulonglong2', 'float1', 'float2', 'float3', 'float4',
'double1', 'double2', 'dim3'))
variables = set(('gridDim', 'blockIdx', 'blockDim', 'threadIdx', 'warpSize'))
functions = set(('__threadfence_block', '__threadfence', '__threadfence_system',
'__syncthreads', '__syncthreads_count', '__syncthreads_and',
'__syncthreads_or'))
execution_confs = set(('<<<', '>>>'))
def get_tokens_unprocessed(self, text):
for index, token, value in CLexer.get_tokens_unprocessed(self, text):
if token is Name:
if value in self.variable_qualifiers:
token = Keyword.Type
elif value in self.vector_types:
token = Keyword.Type
elif value in self.variables:
token = Name.Builtin
elif value in self.execution_confs:
token = Keyword.Pseudo
elif value in self.function_qualifiers:
token = Keyword.Reserved
elif value in self.functions:
token = Name.Function
yield index, token, value
| CudaLexer |
python | doocs__leetcode | solution/0300-0399/0345.Reverse Vowels of a String/Solution.py | {
"start": 0,
"end": 434
} | class ____:
def reverseVowels(self, s: str) -> str:
vowels = "aeiouAEIOU"
i, j = 0, len(s) - 1
cs = list(s)
while i < j:
while i < j and cs[i] not in vowels:
i += 1
while i < j and cs[j] not in vowels:
j -= 1
if i < j:
cs[i], cs[j] = cs[j], cs[i]
i, j = i + 1, j - 1
return "".join(cs)
| Solution |
python | getsentry__sentry | tests/sentry/tasks/test_post_process.py | {
"start": 82458,
"end": 87948
} | class ____(BasePostProgressGroupMixin):
def test_user_report_gets_environment(self) -> None:
project = self.create_project()
environment = Environment.objects.create(
organization_id=project.organization_id, name="production"
)
environment.add_project(project)
event_id = "a" * 32
event = self.create_event(
data={"environment": environment.name, "event_id": event_id},
project_id=project.id,
)
UserReport.objects.create(
project_id=project.id,
event_id=event_id,
name="foo",
email="bar@example.com",
comments="It Broke!!!",
)
self.call_post_process_group(
is_new=True,
is_regression=False,
is_new_group_environment=True,
event=event,
)
assert UserReport.objects.get(event_id=event_id).environment_id == environment.id
def test_user_report_gets_environment_with_new_link_features(self) -> None:
project = self.create_project()
environment = Environment.objects.create(
organization_id=project.organization_id, name="production"
)
environment.add_project(project)
event_id = "a" * 32
event = self.store_event(
data={"environment": environment.name, "event_id": event_id},
project_id=project.id,
)
UserReport.objects.create(
project_id=project.id,
event_id=event_id,
name="foo",
email="bar@example.com",
comments="It Broke!!!",
)
self.call_post_process_group(
is_new=True,
is_regression=False,
is_new_group_environment=True,
event=event,
)
assert UserReport.objects.get(event_id=event_id).environment_id == environment.id
@patch("sentry.feedback.usecases.ingest.create_feedback.produce_occurrence_to_kafka")
def test_user_report_shims_to_feedback(
self, mock_produce_occurrence_to_kafka: MagicMock
) -> None:
project = self.create_project()
environment = Environment.objects.create(
organization_id=project.organization_id, name="production"
)
environment.add_project(project)
event_id = "a" * 32
UserReport.objects.create(
project_id=project.id,
event_id=event_id,
name="Foo Bar",
email="bar@example.com",
comments="It Broke!!!",
)
event = self.store_event(
data={"environment": environment.name, "event_id": event_id},
project_id=project.id,
)
self.call_post_process_group(
is_new=True,
is_regression=False,
is_new_group_environment=True,
event=event,
)
report1 = UserReport.objects.get(project_id=project.id, event_id=event.event_id)
assert report1.group_id == event.group_id
assert report1.environment_id == event.get_environment().id
assert len(mock_produce_occurrence_to_kafka.mock_calls) == 1
mock_event_data = mock_produce_occurrence_to_kafka.call_args_list[0][1]["event_data"]
assert mock_event_data["contexts"]["feedback"]["contact_email"] == "bar@example.com"
assert mock_event_data["contexts"]["feedback"]["message"] == "It Broke!!!"
assert mock_event_data["contexts"]["feedback"]["name"] == "Foo Bar"
assert mock_event_data["environment"] == environment.name
assert mock_event_data["tags"]["environment"] == environment.name
assert mock_event_data["tags"]["level"] == "error"
assert mock_event_data["tags"]["user.email"] == "bar@example.com"
assert mock_event_data["platform"] == "other"
assert mock_event_data["contexts"]["feedback"]["associated_event_id"] == event.event_id
assert mock_event_data["level"] == "error"
@patch("sentry.feedback.usecases.ingest.create_feedback.produce_occurrence_to_kafka")
def test_user_reports_no_shim_if_group_exists_on_report(
self, mock_produce_occurrence_to_kafka: MagicMock
) -> None:
project = self.create_project()
environment = Environment.objects.create(
organization_id=project.organization_id, name="production"
)
environment.add_project(project)
event_id = "a" * 32
UserReport.objects.create(
project_id=project.id,
event_id=event_id,
name="Foo Bar",
email="bar@example.com",
comments="It Broke!!!",
environment_id=environment.id,
)
event = self.store_event(
data={"environment": environment.name, "event_id": event_id},
project_id=project.id,
)
self.call_post_process_group(
is_new=True,
is_regression=False,
is_new_group_environment=True,
event=event,
)
# since the environment already exists on this user report, we know that
# the report and the event have already been linked, so no feedback shim should be produced
report1 = UserReport.objects.get(project_id=project.id, event_id=event.event_id)
assert report1.environment_id == event.get_environment().id
assert len(mock_produce_occurrence_to_kafka.mock_calls) == 0
| UserReportEventLinkTestMixin |
python | pytorch__pytorch | torch/testing/_internal/common_fsdp.py | {
"start": 21821,
"end": 24594
} | class ____(FSDPTestModel):
"""This class wraps a :class:`FSDPTestModel` to optionally add a delay
after computing the loss and/or before the gradient reduction."""
def __init__(
self,
module: nn.Module,
delay_after_loss_ms: int,
delay_before_reduction_ms: int,
):
super().__init__()
self.delay_after_loss_ms = delay_after_loss_ms
self.delay_before_reduction_ms = delay_before_reduction_ms
self.module = module
def get_input(self, device):
return self.module.get_input(device) # type: ignore[operator]
def forward(self, x):
return self.module(x)
def get_loss(self, input, output):
loss = self.module.get_loss(input, output) # type: ignore[operator]
if self.delay_after_loss_ms > 0:
if TEST_HPU or TEST_XPU:
time.sleep(self.delay_after_loss_ms / 1000)
elif TEST_CUDA:
torch.cuda._sleep(int(self.delay_after_loss_ms * get_cycles_per_ms()))
return loss
def run_backward(self, loss):
orig_reduce_scatter = torch.distributed.reduce_scatter_tensor
def _delayed_reduce_scatter(*args, **kwargs):
if self.delay_before_reduction_ms > 0:
if TEST_CUDA:
torch.cuda._sleep(
int(self.delay_before_reduction_ms * get_cycles_per_ms())
)
elif TEST_HPU or TEST_XPU:
time.sleep(self.delay_before_reduction_ms / 1000)
return orig_reduce_scatter(*args, **kwargs)
with mock.patch(
"torch.distributed.reduce_scatter_tensor", _delayed_reduce_scatter
):
self.module.run_backward(loss) # type: ignore[operator]
@staticmethod
def init(
module_class: type[FSDPTestModel],
*model_args: Any,
delay_after_loss_ms: int,
delay_before_reduction_ms: int,
**model_kwargs: Any,
):
"""
Args:
module_class (Type[FSDPTestModel]): Wrapped module class to which
to add delays.
model_args: Positional arguments forwarded to the ``module_class``
``init()``.
delay_after_loss_ms (int): Delay after computing the loss/before
the optimizer step (in ms).
delay_before_reduction_ms (int): Delay before reduce-scattering
gradients (in ms).
model_kwargs: Keyword arguments forwarded to the ``module_class``
``init()``.
"""
return ModuleWithDelay(
module_class.init(*model_args, **model_kwargs),
delay_after_loss_ms,
delay_before_reduction_ms,
)
| ModuleWithDelay |
python | agronholm__apscheduler | src/apscheduler/datastores/sqlalchemy.py | {
"start": 2454,
"end": 3295
} | class ____(TypeDecorator[timedelta]):
impl = BigInteger()
cache_ok = True
def process_bind_param(
self, value: timedelta | None, dialect: Dialect
) -> float | None:
return value.total_seconds() * 1000000 if value is not None else None
def process_result_value(
self, value: int | None, dialect: Dialect
) -> timedelta | None:
return timedelta(seconds=value / 1000000) if value is not None else None
def marshal_timestamp(timestamp: datetime | None, key: str) -> Mapping[str, Any]:
if timestamp is None:
return {key: None, key + "_utcoffset": None}
return {
key: int(timestamp.timestamp() * 1000_000),
key + "_utcoffset": cast(timedelta, timestamp.utcoffset()).total_seconds()
// 60,
}
@attrs.define(eq=False, frozen=True)
| EmulatedInterval |
python | django__django | tests/test_utils/test_testcase.py | {
"start": 459,
"end": 913
} | class ____(SimpleTestCase):
def test_is_picklable_with_non_picklable_properties(self):
"""ParallelTestSuite requires that all TestCases are picklable."""
self.non_picklable = lambda: 0
self.assertEqual(self, pickle.loads(pickle.dumps(self)))
def test_is_picklable_with_non_picklable_object(self):
unpicklable_obj = UnpicklableObject()
self.assertEqual(is_pickable(unpicklable_obj), False)
| TestSimpleTestCase |
python | streamlit__streamlit | lib/streamlit/testing/v1/element_tree.py | {
"start": 38299,
"end": 39896
} | class ____(Widget):
"""A representation of ``st.text_input``."""
_value: str | None | InitialValue
proto: TextInputProto = field(repr=False)
label: str
max_chars: int
autocomplete: str
placeholder: str
help: str
form_id: str
def __init__(self, proto: TextInputProto, root: ElementTree) -> None:
super().__init__(proto, root)
self._value = InitialValue()
self.type = "text_input"
def set_value(self, v: str | None) -> TextInput:
"""Set the value of the widget."""
self._value = v
return self
@property
def _widget_state(self) -> WidgetState:
ws = WidgetState()
ws.id = self.id
if self.value is not None:
ws.string_value = self.value
return ws
@property
def value(self) -> str | None:
"""The current value of the widget. (str)""" # noqa: D400
if not isinstance(self._value, InitialValue):
return self._value
state = self.root.session_state
assert state
# Awkward to do this with `cast`
return state[self.id] # type: ignore
def input(self, v: str) -> TextInput:
"""
Set the value of the widget only if the value does not exceed the\
maximum allowed characters.
"""
# TODO: should input be setting or appending?
if self.max_chars and len(v) > self.max_chars:
return self
return self.set_value(v)
TimeValue: TypeAlias = time | datetime
DateTimeWidgetValue: TypeAlias = datetime
@dataclass(repr=False)
| TextInput |
python | streamlit__streamlit | lib/tests/streamlit/runtime/caching/cache_data_api_test.py | {
"start": 2806,
"end": 9020
} | class ____(unittest.TestCase):
def setUp(self) -> None:
# Caching functions rely on an active script run ctx
add_script_run_ctx(threading.current_thread(), create_mock_script_run_ctx())
mock_runtime = MagicMock(spec=Runtime)
mock_runtime.cache_storage_manager = MemoryCacheStorageManager()
Runtime._instance = mock_runtime
def tearDown(self):
# Some of these tests reach directly into _cache_info and twiddle it.
# Reset default values on teardown.
st.cache_data.clear()
@patch.object(st, "exception")
def test_mutate_return(self, exception):
"""Mutating a memoized return value is legal, and *won't* affect
future accessors of the data."""
@st.cache_data
def f():
return [0, 1]
r1 = f()
r1[0] = 1
r2 = f()
exception.assert_not_called()
assert r1 == [1, 1]
assert r2 == [0, 1]
def test_cached_member_function_with_hash_func(self):
"""@st.cache_data can be applied to class member functions
with corresponding hash_func.
"""
class TestClass:
@st.cache_data(
hash_funcs={
"tests.streamlit.runtime.caching.cache_data_api_test."
"CacheDataTest.test_cached_member_function_with_hash_func."
"<locals>.TestClass": id
}
)
def member_func(self):
return "member func!"
@classmethod
@st.cache_data
def class_method(cls):
return "class method!"
@staticmethod
@st.cache_data
def static_method():
return "static method!"
obj = TestClass()
assert obj.member_func() == "member func!"
assert obj.class_method() == "class method!"
assert obj.static_method() == "static method!"
def test_function_name_does_not_use_hashfuncs(self):
"""Hash funcs should only be used on arguments to a function,
and not when computing the key for a function's unique MemCache.
"""
str_hash_func = Mock(return_value=None)
@st.cache_data(hash_funcs={str: str_hash_func})
def foo(string_arg):
return []
# If our str hash_func is called multiple times, it's probably because
# it's being used to compute the function's function_key (as opposed to
# the value_key). It should only be used to compute the value_key!
foo("ahoy")
str_hash_func.assert_called_once_with("ahoy")
def test_user_hash_error(self):
class MyObj:
# we specify __repr__ here, to avoid `MyObj object at 0x1347a3f70`
# in error message
def __repr__(self):
return "MyObj class"
def bad_hash_func(x):
x += 10 # Throws a TypeError since x has type MyObj.
return x
@st.cache_data(hash_funcs={MyObj: bad_hash_func})
def user_hash_error_func(x):
pass
with pytest.raises(UserHashError) as ctx:
my_obj = MyObj()
user_hash_error_func(my_obj)
expected_message = """unsupported operand type(s) for +=: 'MyObj' and 'int'
This error is likely due to a bug in `bad_hash_func()`, which is a
user-defined hash function that was passed into the `@st.cache_data` decorator of
`user_hash_error_func()`.
`bad_hash_func()` failed when hashing an object of type
`tests.streamlit.runtime.caching.cache_data_api_test.CacheDataTest.test_user_hash_error.<locals>.MyObj`. If you don't know where that object is coming from,
try looking at the hash chain below for an object that you do recognize, then
pass that to `hash_funcs` instead:
```
Object of type tests.streamlit.runtime.caching.cache_data_api_test.CacheDataTest.test_user_hash_error.<locals>.MyObj: MyObj class
```
If you think this is actually a Streamlit bug, please
[file a bug report here](https://github.com/streamlit/streamlit/issues/new/choose).""" # noqa: E501
assert str(ctx.value) == expected_message
def test_cached_st_function_clear_args(self):
self.x = 0
@st.cache_data()
def foo(y):
self.x += y
return self.x
assert foo(1) == 1
foo.clear(2)
assert foo(1) == 1
foo.clear(1)
assert foo(1) == 2
def test_cached_class_method_clear_args(self):
self.x = 0
class ExampleClass:
@st.cache_data
def foo(_self, y):
self.x += y
return self.x
example_instance = ExampleClass()
# Calling method foo produces the side effect of incrementing self.x
# and returning it as the result.
# calling foo(1) should return 1
assert example_instance.foo(1) == 1
# calling foo.clear(2) should clear the cache for the argument 2,
# and keep the cache for the argument 1, therefore calling foo(1) should return
# cached value 1
example_instance.foo.clear(2)
assert example_instance.foo(1) == 1
# calling foo.clear(1) should clear the cache for the argument 1,
# therefore calling foo(1) should return the new value 2
example_instance.foo.clear(1)
assert example_instance.foo(1) == 2
# Try the same with a keyword argument:
example_instance.foo.clear(y=1)
assert example_instance.foo(1) == 3
def test_cached_class_method_clear(self):
self.x = 0
class ExampleClass:
@st.cache_data
def foo(_self, y):
self.x += y
return self.x
example_instance = ExampleClass()
# Calling method foo produces the side effect of incrementing self.x
# and returning it as the result.
# calling foo(1) should return 1
assert example_instance.foo(1) == 1
example_instance.foo.clear()
# calling foo.clear() should clear all cached values:
# So the call to foo() should return the new value 2
assert example_instance.foo(1) == 2
| CacheDataTest |
python | fluentpython__example-code-2e | 10-dp-1class-func/untyped/strategy_best3.py | {
"start": 1625,
"end": 2515
} | class ____: # the Context
def __init__(self, customer, cart, promotion=None):
self.customer = customer
self.cart = list(cart)
self.promotion = promotion
def total(self):
if not hasattr(self, '__total'):
self.__total = sum(item.total() for item in self.cart)
return self.__total
def due(self):
if self.promotion is None:
discount = 0
else:
discount = self.promotion(self)
return self.total() - discount
def __repr__(self):
return f'<Order total: {self.total():.2f} due: {self.due():.2f}>'
# tag::STRATEGY_BEST3[]
promos = [func for name, func in
inspect.getmembers(promotions, inspect.isfunction)]
def best_promo(order):
"""Select best discount available
"""
return max(promo(order) for promo in promos)
# end::STRATEGY_BEST3[]
| Order |
python | nryoung__algorithms | tests/test_factorization.py | {
"start": 444,
"end": 879
} | class ____(unittest.TestCase):
def test_pollard_rho(self):
x = random.randint(1, 100000000000)
factors = pollard_rho(x)
res = 1
for j in factors:
res *= j
self.assertEqual(x, res)
def test_pollard_rho_x_is_zero(self):
x = 0
factors = pollard_rho(x)
res = 1
for j in factors:
res *= j
self.assertEqual(x, res)
| TestPollardRho |
python | pyinstaller__pyinstaller | PyInstaller/utils/conftest.py | {
"start": 5259,
"end": 26380
} | class ____:
def __init__(self, tmp_path, request, bundle_mode):
self._tmp_path = tmp_path
self._request = request
self._mode = bundle_mode
self._spec_dir = tmp_path
self._dist_dir = tmp_path / 'dist'
self._build_dir = tmp_path / 'build'
self._is_spec = False
def test_spec(self, specfile, *args, **kwargs):
"""
Test a Python script that is referenced in the supplied .spec file.
"""
__tracebackhide__ = True
specfile = _get_spec_dir(self._request) / specfile
# 'test_script' should handle .spec properly as script.
self._is_spec = True
return self.test_script(specfile, *args, **kwargs)
def test_source(self, source, *args, **kwargs):
"""
Test a Python script given as source code.
The source will be written into a file named like the test-function. This file will then be passed to
`test_script`. If you need other related file, e.g., as `.toc`-file for testing the content, put it at at the
normal place. Just mind to take the basnename from the test-function's name.
:param script: Source code to create executable from. This will be saved into a temporary file which is then
passed on to `test_script`.
:param test_id: Test-id for parametrized tests. If given, it will be appended to the script filename, separated
by two underscores.
All other arguments are passed straight on to `test_script`.
"""
__tracebackhide__ = True
# For parametrized test append the test-id.
scriptfile = gen_sourcefile(self._tmp_path, source, kwargs.setdefault('test_id'))
del kwargs['test_id']
return self.test_script(scriptfile, *args, **kwargs)
def _display_message(self, step_name, message):
# Print the given message to both stderr and stdout, and it with APP-BUILDER to make it clear where it
# originates from.
print(f'[APP-BUILDER:{step_name}] {message}', file=sys.stdout)
print(f'[APP-BUILDER:{step_name}] {message}', file=sys.stderr)
def test_script(
self, script, pyi_args=None, app_name=None, app_args=None, runtime=None, run_from_path=False, **kwargs
):
"""
Main method to wrap all phases of testing a Python script.
:param script: Name of script to create executable from.
:param pyi_args: Additional arguments to pass to PyInstaller when creating executable.
:param app_name: Name of the executable. This is equivalent to argument --name=APPNAME.
:param app_args: Additional arguments to pass to
:param runtime: Time in seconds how long to keep executable running.
:param toc_log: List of modules that are expected to be bundled with the executable.
"""
__tracebackhide__ = True
# Skip interactive tests (the ones with `runtime` set) if `psutil` is unavailable, as we need it to properly
# clean up the process tree.
if runtime and psutil is None:
pytest.skip('Interactive tests require psutil for proper cleanup.')
if pyi_args is None:
pyi_args = []
if app_args is None:
app_args = []
if app_name:
if not self._is_spec:
pyi_args.extend(['--name', app_name])
else:
# Derive name from script name.
app_name = os.path.splitext(os.path.basename(script))[0]
# Relative path means that a script from _script_dir is referenced.
if not os.path.isabs(script):
script = _get_script_dir(self._request) / script
self.script = str(script) # might be a pathlib.Path at this point!
assert os.path.exists(self.script), f'Script {self.script!r} not found.'
self._display_message('TEST-SCRIPT', 'Starting build...')
if not self._test_building(args=pyi_args):
pytest.fail(f'Building of {script} failed.')
self._display_message('TEST-SCRIPT', 'Build finished, now running executable...')
self._test_executables(app_name, args=app_args, runtime=runtime, run_from_path=run_from_path, **kwargs)
self._display_message('TEST-SCRIPT', 'Running executable finished.')
def _test_executables(self, name, args, runtime, run_from_path, **kwargs):
"""
Run created executable to make sure it works.
Multipackage-tests generate more than one exe-file and all of them have to be run.
:param args: CLI options to pass to the created executable.
:param runtime: Time in seconds how long to keep the executable running.
:return: Exit code of the executable.
"""
__tracebackhide__ = True
exes = self._find_executables(name)
# Empty list means that PyInstaller probably failed to create any executable.
assert exes != [], 'No executable file was found.'
for exe in exes:
# Try to find .toc log file. .toc log file has the same basename as exe file.
toc_log = os.path.splitext(os.path.basename(exe))[0] + '.toc'
toc_log = _get_logs_dir(self._request) / toc_log
if toc_log.exists():
if not self._examine_executable(exe, toc_log):
pytest.fail(f'Matching .toc of {exe} failed.')
retcode = self._run_executable(exe, args, run_from_path, runtime)
if retcode != kwargs.get('retcode', 0):
pytest.fail(f'Running exe {exe} failed with return-code {retcode}.')
def _find_executables(self, name):
"""
Search for all executables generated by the testcase.
If the test-case is called e.g. 'test_multipackage1', this is searching for each of 'test_multipackage1.exe'
and 'multipackage1_?.exe' in both one-file- and one-dir-mode.
:param name: Name of the executable to look for.
:return: List of executables
"""
exes = []
onedir_pt = str(self._dist_dir / name / name)
onefile_pt = str(self._dist_dir / name)
patterns = [
onedir_pt,
onefile_pt,
# Multipackage one-dir
onedir_pt + '_?',
# Multipackage one-file
onefile_pt + '_?'
]
# For Windows append .exe extension to patterns.
if is_win:
patterns = [pt + '.exe' for pt in patterns]
# For macOS append pattern for .app bundles.
if is_darwin:
# e.g: ./dist/name.app/Contents/MacOS/name
app_bundle_pt = str(self._dist_dir / f'{name}.app' / 'Contents' / 'MacOS' / name)
patterns.append(app_bundle_pt)
# Apply file patterns.
for pattern in patterns:
for prog in glob.glob(pattern):
if os.path.isfile(prog):
exes.append(prog)
return exes
def _run_executable(self, prog, args, run_from_path, runtime):
"""
Run executable created by PyInstaller.
:param args: CLI options to pass to the created executable.
"""
# Run the test in a clean environment to make sure they're really self-contained.
prog_env = copy.deepcopy(os.environ)
prog_env['PATH'] = ''
del prog_env['PATH']
# For Windows we need to keep minimal PATH for successful running of some tests.
if is_win:
# Minimum Windows PATH is in most cases: C:\Windows\system32;C:\Windows
prog_env['PATH'] = os.pathsep.join(winutils.get_system_path())
# Same for Cygwin - if /usr/bin is not in PATH, cygwin1.dll cannot be discovered.
if is_cygwin:
prog_env['PATH'] = os.pathsep.join(['/usr/local/bin', '/usr/bin'])
# On macOS, we similarly set up minimal PATH with system directories, in case utilities from there are used by
# tested python code (for example, matplotlib >= 3.9.0 uses `system_profiler` that is found in /usr/sbin).
if is_darwin:
# The following paths are registered when application is launched via Finder, and are a subset of what is
# typically available in the shell.
prog_env['PATH'] = os.pathsep.join(['/usr/bin', '/bin', '/usr/sbin', '/sbin'])
exe_path = prog
if run_from_path:
# Run executable in the temp directory. Add the directory containing the executable to $PATH. Basically,
# pretend we are a shell executing the program from $PATH.
prog_cwd = str(self._tmp_path)
prog_name = os.path.basename(prog)
prog_env['PATH'] = os.pathsep.join([prog_env.get('PATH', ''), os.path.dirname(prog)])
else:
# Run executable in the directory where it is.
prog_cwd = os.path.dirname(prog)
# The executable will be called with argv[0] as relative not absolute path.
prog_name = os.path.join(os.curdir, os.path.basename(prog))
args = [prog_name] + args
# Using sys.stdout/sys.stderr for subprocess fixes printing messages in Windows command prompt. Py.test is then
# able to collect stdout/sterr messages and display them if a test fails.
return self._run_executable_(args, exe_path, prog_env, prog_cwd, runtime)
def _run_executable_(self, args, exe_path, prog_env, prog_cwd, runtime):
# Use psutil.Popen, if available; otherwise, fall back to subprocess.Popen
popen_implementation = subprocess.Popen if psutil is None else psutil.Popen
# Run the executable
self._display_message('RUN-EXE', f'Running {exe_path!r}, args: {args!r}')
start_time = time.time()
process = popen_implementation(args, executable=exe_path, env=prog_env, cwd=prog_cwd)
# Wait for the process to finish. If no run-time (= timeout) is specified, we expect the process to exit on
# its own, and use global _EXE_TIMEOUT. If run-time is specified, we expect the application to be running
# for at least the specified amount of time, which is useful in "interactive" test applications that are not
# expected exit on their own.
stdout = stderr = None
try:
timeout = runtime if runtime else _EXE_TIMEOUT
stdout, stderr = process.communicate(timeout=timeout)
elapsed = time.time() - start_time
retcode = process.returncode
self._display_message(
'RUN-EXE', f'Process exited on its own after {elapsed:.1f} seconds with return code {retcode}.'
)
except (subprocess.TimeoutExpired) if psutil is None else (psutil.TimeoutExpired, subprocess.TimeoutExpired):
if runtime:
# When 'runtime' is set, the expired timeout is a good sign that the executable was running successfully
# for the specified time.
self._display_message('RUN-EXE', f'Process reached expected run-time of {runtime} seconds.')
retcode = 0
else:
# Executable is still running and it is not interactive. Clean up the process tree, and fail the test.
self._display_message('RUN-EXE', f'Timeout while running executable (timeout: {timeout} seconds)!')
retcode = 1
if psutil is None:
# We are using subprocess.Popen(). Without psutil, we have no access to process tree; this poses a
# problem for onefile builds, where we would need to first kill the child (main application) process,
# and let the onefile parent perform its cleanup. As a best-effort approach, we can first call
# process.terminate(); on POSIX systems, this sends SIGTERM to the parent process, and in most
# situations, the bootloader will forward it to the child process. Then wait 5 seconds, and call
# process.kill() if necessary. On Windows, however, both process.terminate() and process.kill() do
# the same. Therefore, we should avoid running "interactive" tests with expected run-time if we do
# not have psutil available.
try:
self._display_message('RUN-EXE', 'Stopping the process using Popen.terminate()...')
process.terminate()
stdout, stderr = process.communicate(timeout=5)
self._display_message('RUN-EXE', 'Process stopped.')
except subprocess.TimeoutExpired:
# Kill the process.
try:
self._display_message('RUN-EXE', 'Stopping the process using Popen.kill()...')
process.kill()
# process.communicate() waits for end-of-file, which may never arrive if there is a child
# process still alive. Nothing we can really do about it here, so add a short timeout and
# display a warning.
stdout, stderr = process.communicate(timeout=1)
self._display_message('RUN-EXE', 'Process stopped.')
except subprocess.TimeoutExpired:
self._display_message('RUN-EXE', 'Failed to stop the process (or its child process(es))!')
else:
# We are using psutil.Popen(). First, force-kill all child processes; in onefile mode, this includes
# the application process, whose termination should trigger cleanup and exit of the parent onefile
# process.
self._display_message('RUN-EXE', 'Stopping child processes...')
for child_process in list(process.children(recursive=True)):
with contextlib.suppress(psutil.NoSuchProcess):
self._display_message('RUN-EXE', f'Stopping child process {child_process.pid}...')
child_process.kill()
# Give the main process 5 seconds to exit on its own (to accommodate cleanup in onefile mode).
try:
self._display_message('RUN-EXE', f'Waiting for main process ({process.pid}) to stop...')
stdout, stderr = process.communicate(timeout=5)
self._display_message('RUN-EXE', 'Process stopped on its own.')
except (psutil.TimeoutExpired, subprocess.TimeoutExpired):
# End of the line - kill the main process.
self._display_message('RUN-EXE', 'Stopping the process using Popen.kill()...')
with contextlib.suppress(psutil.NoSuchProcess):
process.kill()
# Try to retrieve stdout/stderr - but keep a short timeout, just in case...
try:
stdout, stderr = process.communicate(timeout=1)
self._display_message('RUN-EXE', 'Process stopped.')
except (psutil.TimeoutExpired, subprocess.TimeoutExpire):
self._display_message('RUN-EXE', 'Failed to stop the process (or its child process(es))!')
self._display_message('RUN-EXE', f'Done! Return code: {retcode}')
return retcode
def _test_building(self, args):
"""
Run building of test script.
:param args: additional CLI options for PyInstaller.
Return True if build succeeded False otherwise.
"""
if self._is_spec:
default_args = [
'--distpath', str(self._dist_dir),
'--workpath', str(self._build_dir),
'--log-level', 'INFO',
] # yapf: disable
else:
default_args = [
'--debug=bootloader',
'--noupx',
'--specpath', str(self._spec_dir),
'--distpath', str(self._dist_dir),
'--workpath', str(self._build_dir),
'--path', str(_get_modules_dir(self._request)),
'--log-level', 'INFO',
] # yapf: disable
# Choose bundle mode.
if self._mode == 'onedir':
default_args.append('--onedir')
elif self._mode == 'onefile':
default_args.append('--onefile')
# if self._mode is None then just the spec file was supplied.
pyi_args = [self.script, *default_args, *args]
# TODO: fix return code in running PyInstaller programmatically.
PYI_CONFIG = configure.get_config()
# Override CACHEDIR for PyInstaller; relocate cache into `self._tmp_path`.
PYI_CONFIG['cachedir'] = str(self._tmp_path)
pyi_main.run(pyi_args, PYI_CONFIG)
retcode = 0
return retcode == 0
def _examine_executable(self, exe, toc_log):
"""
Compare log files (now used mostly by multipackage test_name).
:return: True if .toc files match
"""
self._display_message('EXAMINE-EXE', f'Matching against TOC log: {str(toc_log)!r}')
fname_list = pkg_archive_contents(exe)
with open(toc_log, 'r', encoding='utf-8') as f:
pattern_list = eval(f.read())
# Alphabetical order of patterns.
pattern_list.sort()
missing = []
for pattern in pattern_list:
for fname in fname_list:
if re.match(pattern, fname):
self._display_message('EXAMINE-EXE', f'Entry found: {pattern!r} --> {fname!r}')
break
else:
# No matching entry found
missing.append(pattern)
self._display_message('EXAMINE-EXE', f'Entry MISSING: {pattern!r}')
# We expect the missing list to be empty
return not missing
# Scope 'session' should keep the object unchanged for whole tests. This fixture caches basic module graph dependencies
# that are same for every executable.
@pytest.fixture(scope='session')
def pyi_modgraph():
# Explicitly set the log level since the plugin `pytest-catchlog` (un-) sets the root logger's level to NOTSET for
# the setup phase, which will lead to TRACE messages been written out.
import PyInstaller.log as logging
logging.logger.setLevel(logging.DEBUG)
initialize_modgraph()
# Run by default test as onedir and onefile.
@pytest.fixture(params=['onedir', 'onefile'])
def pyi_builder(tmp_path, monkeypatch, request, pyi_modgraph):
# Save/restore environment variable PATH.
monkeypatch.setenv('PATH', os.environ['PATH'])
# PyInstaller or a test case might manipulate 'sys.path'. Reset it for every test.
monkeypatch.syspath_prepend(None)
# Set current working directory to
monkeypatch.chdir(tmp_path)
# Clean up configuration and force PyInstaller to do a clean configuration for another app/test. The value is same
# as the original value.
monkeypatch.setattr('PyInstaller.config.CONF', {'pathex': []})
yield AppBuilder(tmp_path, request, request.param)
# Clean up the temporary directory of a successful test
if _PYI_BUILDER_CLEANUP and request.node.rep_setup.passed and request.node.rep_call.passed:
if tmp_path.exists():
shutil.rmtree(tmp_path, ignore_errors=True)
# Fixture for .spec based tests. With .spec it does not make sense to differentiate onefile/onedir mode.
@pytest.fixture
def pyi_builder_spec(tmp_path, request, monkeypatch, pyi_modgraph):
# Save/restore environment variable PATH.
monkeypatch.setenv('PATH', os.environ['PATH'])
# Set current working directory to
monkeypatch.chdir(tmp_path)
# PyInstaller or a test case might manipulate 'sys.path'. Reset it for every test.
monkeypatch.syspath_prepend(None)
# Clean up configuration and force PyInstaller to do a clean configuration for another app/test. The value is same
# as the original value.
monkeypatch.setattr('PyInstaller.config.CONF', {'pathex': []})
yield AppBuilder(tmp_path, request, None)
# Clean up the temporary directory of a successful test
if _PYI_BUILDER_CLEANUP and request.node.rep_setup.passed and request.node.rep_call.passed:
if tmp_path.exists():
shutil.rmtree(tmp_path, ignore_errors=True)
@pytest.fixture
def pyi_windowed_builder(pyi_builder: AppBuilder):
"""A pyi_builder equivalent for testing --windowed applications."""
# psutil.Popen() somehow bypasses an application's windowed/console mode so that any application built in
# --windowed mode but invoked with psutil still receives valid std{in,out,err} handles and behaves exactly like
# a console application. In short, testing windowed mode with psutil is a null test. We must instead use subprocess.
def _run_executable_(args, exe_path, prog_env, prog_cwd, runtime):
return subprocess.run([exe_path, *args], env=prog_env, cwd=prog_cwd, timeout=runtime).returncode
pyi_builder._run_executable_ = _run_executable_
yield pyi_builder
| AppBuilder |
python | PyCQA__pylint | tests/functional/i/inherit_non_class.py | {
"start": 357,
"end": 462
} | class ____:
""" Empty class. """
def return_class():
""" Return a class. """
return Good3
| Empty |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/typing/__init__.py | {
"start": 5601,
"end": 5923
} | class ____(TypedDict):
"""
Deserialized Column constructor options.
Notes
-----
Used to deserialize Column and DataFrame containers.
"""
is_sorted: plc.types.Sorted
order: plc.types.Order
null_order: plc.types.NullOrder
name: str | None
dtype: DataType
| DeserializedColumnOptions |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 50698,
"end": 80146
} | class ____(
FieldChannelMixin,
core.FieldOrDatumDefWithConditionMarkPropFieldDefGradientstringnull,
):
r"""
Color schema wrapper.
Parameters
----------
shorthand : str, dict, Sequence[str], :class:`RepeatRef`
shorthand for field, aggregate, and type
aggregate : dict, :class:`Aggregate`, :class:`ArgmaxDef`, :class:`ArgminDef`, :class:`NonArgAggregateOp`, Literal['average', 'count', 'distinct', 'max', 'mean', 'median', 'min', 'missing', 'product', 'q1', 'q3', 'ci0', 'ci1', 'stderr', 'stdev', 'stdevp', 'sum', 'valid', 'values', 'variance', 'variancep', 'exponential', 'exponentialb']
Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``,
``"min"``, ``"max"``, ``"count"``).
**Default value:** ``undefined`` (None)
**See also:** `aggregate <https://vega.github.io/vega-lite/docs/aggregate.html>`__
documentation.
bandPosition : float
Relative position on a band of a stacked, binned, time unit, or band scale. For
example, the marks will be positioned at the beginning of the band if set to ``0``,
and at the middle of the band if set to ``0.5``.
bin : bool, dict, :class:`BinParams`, None
A flag for binning a ``quantitative`` field, `an object defining binning parameters
<https://vega.github.io/vega-lite/docs/bin.html#bin-parameters>`__, or indicating
that the data for ``x`` or ``y`` channel are binned before they are imported into
Vega-Lite (``"binned"``).
* If ``true``, default `binning parameters
<https://vega.github.io/vega-lite/docs/bin.html#bin-parameters>`__ will be
applied.
* If ``"binned"``, this indicates that the data for the ``x`` (or ``y``) channel are
already binned. You can map the bin-start field to ``x`` (or ``y``) and the
bin-end field to ``x2`` (or ``y2``). The scale and axis will be formatted similar
to binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can
also set the axis's `tickMinStep
<https://vega.github.io/vega-lite/docs/axis.html#ticks>`__ property.
**Default value:** ``false``
**See also:** `bin <https://vega.github.io/vega-lite/docs/bin.html>`__
documentation.
condition : dict, :class:`ConditionalValueDefGradientstringnullExprRef`, :class:`ConditionalParameterValueDefGradientstringnullExprRef`, :class:`ConditionalPredicateValueDefGradientstringnullExprRef`, Sequence[dict, :class:`ConditionalValueDefGradientstringnullExprRef`, :class:`ConditionalParameterValueDefGradientstringnullExprRef`, :class:`ConditionalPredicateValueDefGradientstringnullExprRef`]
One or more value definition(s) with `a parameter or a test predicate
<https://vega.github.io/vega-lite/docs/condition.html>`__.
**Note:** A field definition's ``condition`` property can only contain `conditional
value definitions <https://vega.github.io/vega-lite/docs/condition.html#value>`__
since Vega-Lite only allows at most one encoded field per encoding channel.
field : str, dict, :class:`Field`, :class:`FieldName`, :class:`RepeatRef`
**Required.** A string defining the name of the field from which to pull a data
value or an object defining iterated values from the `repeat
<https://vega.github.io/vega-lite/docs/repeat.html>`__ operator.
**See also:** `field <https://vega.github.io/vega-lite/docs/field.html>`__
documentation.
**Notes:** 1) Dots (``.``) and brackets (``[`` and ``]``) can be used to access
nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"``). If
field names contain dots or brackets but are not nested, you can use ``\\`` to
escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"``). See more details
about escaping in the `field documentation
<https://vega.github.io/vega-lite/docs/field.html>`__. 2) ``field`` is not required
if ``aggregate`` is ``count``.
legend : dict, :class:`Legend`, None
An object defining properties of the legend. If ``null``, the legend for the
encoding channel will be removed.
**Default value:** If undefined, default `legend properties
<https://vega.github.io/vega-lite/docs/legend.html>`__ are applied.
**See also:** `legend <https://vega.github.io/vega-lite/docs/legend.html>`__
documentation.
scale : dict, :class:`Scale`, None
An object defining properties of the channel's scale, which is the function that
transforms values in the data domain (numbers, dates, strings, etc) to visual values
(pixels, colors, sizes) of the encoding channels.
If ``null``, the scale will be `disabled and the data value will be directly encoded
<https://vega.github.io/vega-lite/docs/scale.html#disable>`__.
**Default value:** If undefined, default `scale properties
<https://vega.github.io/vega-lite/docs/scale.html>`__ are applied.
**See also:** `scale <https://vega.github.io/vega-lite/docs/scale.html>`__
documentation.
sort : dict, :class:`Sort`, Sequence[str], Sequence[bool], Sequence[float], :class:`SortArray`, :class:`SortOrder`, :class:`AllSortString`, :class:`SortByChannel`, :class:`SortByEncoding`, :class:`EncodingSortField`, :class:`SortByChannelDesc`, Sequence[dict, :class:`DateTime`], Literal['-x', '-y', '-color', '-fill', '-stroke', '-strokeWidth', '-size', '-shape', '-fillOpacity', '-strokeOpacity', '-opacity', '-text', 'ascending', 'descending', 'x', 'y', 'color', 'fill', 'stroke', 'strokeWidth', 'size', 'shape', 'fillOpacity', 'strokeOpacity', 'opacity', 'text'], None
Sort order for the encoded field.
For continuous fields (quantitative or temporal), ``sort`` can be either
``"ascending"`` or ``"descending"``.
For discrete fields, ``sort`` can be one of the following:
* ``"ascending"`` or ``"descending"`` -- for sorting by the values' natural order in
JavaScript.
* `A string indicating an encoding channel name to sort by
<https://vega.github.io/vega-lite/docs/sort.html#sort-by-encoding>`__ (e.g.,
``"x"`` or ``"y"``) with an optional minus prefix for descending sort (e.g.,
``"-x"`` to sort by x-field, descending). This channel string is short-form of `a
sort-by-encoding definition
<https://vega.github.io/vega-lite/docs/sort.html#sort-by-encoding>`__. For
example, ``"sort": "-x"`` is equivalent to ``"sort": {"encoding": "x", "order":
"descending"}``.
* `A sort field definition
<https://vega.github.io/vega-lite/docs/sort.html#sort-field>`__ for sorting by
another field.
* `An array specifying the field values in preferred order
<https://vega.github.io/vega-lite/docs/sort.html#sort-array>`__. In this case, the
sort order will obey the values in the array, followed by any unspecified values
in their original order. For discrete time field, values in the sort array can be
`date-time definition objects
<https://vega.github.io/vega-lite/docs/datetime.html>`__. In addition, for time
units ``"month"`` and ``"day"``, the values can be the month or day names (case
insensitive) or their 3-letter initials (e.g., ``"Mon"``, ``"Tue"``).
* ``null`` indicating no sort.
**Default value:** ``"ascending"``
**Note:** ``null`` and sorting by another channel is not supported for ``row`` and
``column``.
**See also:** `sort <https://vega.github.io/vega-lite/docs/sort.html>`__
documentation.
timeUnit : dict, :class:`TimeUnit`, :class:`MultiTimeUnit`, :class:`BinnedTimeUnit`, :class:`SingleTimeUnit`, :class:`TimeUnitParams`, :class:`UtcMultiTimeUnit`, :class:`UtcSingleTimeUnit`, :class:`LocalMultiTimeUnit`, :class:`LocalSingleTimeUnit`, Literal['binnedyear', 'binnedyearquarter', 'binnedyearquartermonth', 'binnedyearmonth', 'binnedyearmonthdate', 'binnedyearmonthdatehours', 'binnedyearmonthdatehoursminutes', 'binnedyearmonthdatehoursminutesseconds', 'binnedyearweek', 'binnedyearweekday', 'binnedyearweekdayhours', 'binnedyearweekdayhoursminutes', 'binnedyearweekdayhoursminutesseconds', 'binnedyeardayofyear', 'binnedutcyear', 'binnedutcyearquarter', 'binnedutcyearquartermonth', 'binnedutcyearmonth', 'binnedutcyearmonthdate', 'binnedutcyearmonthdatehours', 'binnedutcyearmonthdatehoursminutes', 'binnedutcyearmonthdatehoursminutesseconds', 'binnedutcyearweek', 'binnedutcyearweekday', 'binnedutcyearweekdayhours', 'binnedutcyearweekdayhoursminutes', 'binnedutcyearweekdayhoursminutesseconds', 'binnedutcyeardayofyear', 'utcyear', 'utcquarter', 'utcmonth', 'utcweek', 'utcday', 'utcdayofyear', 'utcdate', 'utchours', 'utcminutes', 'utcseconds', 'utcmilliseconds', 'year', 'quarter', 'month', 'week', 'day', 'dayofyear', 'date', 'hours', 'minutes', 'seconds', 'milliseconds', 'utcyearquarter', 'utcyearquartermonth', 'utcyearmonth', 'utcyearmonthdate', 'utcyearmonthdatehours', 'utcyearmonthdatehoursminutes', 'utcyearmonthdatehoursminutesseconds', 'utcyearweek', 'utcyearweekday', 'utcyearweekdayhours', 'utcyearweekdayhoursminutes', 'utcyearweekdayhoursminutesseconds', 'utcyeardayofyear', 'utcquartermonth', 'utcmonthdate', 'utcmonthdatehours', 'utcmonthdatehoursminutes', 'utcmonthdatehoursminutesseconds', 'utcweekday', 'utcweekdayhours', 'utcweekdayhoursminutes', 'utcweekdayhoursminutesseconds', 'utcdayhours', 'utcdayhoursminutes', 'utcdayhoursminutesseconds', 'utchoursminutes', 'utchoursminutesseconds', 'utcminutesseconds', 'utcsecondsmilliseconds', 'yearquarter', 'yearquartermonth', 'yearmonth', 'yearmonthdate', 'yearmonthdatehours', 'yearmonthdatehoursminutes', 'yearmonthdatehoursminutesseconds', 'yearweek', 'yearweekday', 'yearweekdayhours', 'yearweekdayhoursminutes', 'yearweekdayhoursminutesseconds', 'yeardayofyear', 'quartermonth', 'monthdate', 'monthdatehours', 'monthdatehoursminutes', 'monthdatehoursminutesseconds', 'weekday', 'weekdayhours', 'weekdayhoursminutes', 'weekdayhoursminutesseconds', 'dayhours', 'dayhoursminutes', 'dayhoursminutesseconds', 'hoursminutes', 'hoursminutesseconds', 'minutesseconds', 'secondsmilliseconds']
Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours``) for a temporal
field. or `a temporal field that gets casted as ordinal
<https://vega.github.io/vega-lite/docs/type.html#cast>`__.
**Default value:** ``undefined`` (None)
**See also:** `timeUnit <https://vega.github.io/vega-lite/docs/timeunit.html>`__
documentation.
title : str, :class:`Text`, Sequence[str], None
A title for the field. If ``null``, the title will be removed.
**Default value:** derived from the field's name and transformation function
(``aggregate``, ``bin`` and ``timeUnit``). If the field has an aggregate function,
the function is displayed as part of the title (e.g., ``"Sum of Profit"``). If the
field is binned or has a time unit applied, the applied function is shown in
parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"``).
Otherwise, the title is simply the field name.
**Notes**:
1) You can customize the default field title format by providing the `fieldTitle
<https://vega.github.io/vega-lite/docs/config.html#top-level-config>`__ property in
the `config <https://vega.github.io/vega-lite/docs/config.html>`__ or `fieldTitle
function via the compile function's options
<https://vega.github.io/vega-lite/usage/compile.html#field-title>`__.
2) If both field definition's ``title`` and axis, header, or legend ``title`` are
defined, axis/header/legend title will be used.
type : :class:`StandardType`, Literal['quantitative', 'ordinal', 'temporal', 'nominal']
The type of measurement (``"quantitative"``, ``"temporal"``, ``"ordinal"``, or
``"nominal"``) for the encoded field or constant value (``datum``). It can also be a
``"geojson"`` type for encoding `'geoshape'
<https://vega.github.io/vega-lite/docs/geoshape.html>`__.
Vega-Lite automatically infers data types in many cases as discussed below. However,
type is required for a field if: (1) the field is not nominal and the field encoding
has no specified ``aggregate`` (except ``argmin`` and ``argmax``), ``bin``, scale
type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal
scale for a field with ``bin`` or ``timeUnit``.
**Default value:**
1) For a data ``field``, ``"nominal"`` is the default data type unless the field
encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or
``timeUnit`` that satisfies the following criteria:
* ``"quantitative"`` is the default type if (1) the encoded field contains ``bin``
or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is
``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a
quantitative scale <https://vega.github.io/vega-lite/docs/scale.html#type>`__.
* ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit``
or (2) the specified scale type is a time or utc scale
* ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort
order
<https://vega.github.io/vega-lite/docs/sort.html#specifying-custom-sort-order>`__,
(2) the specified scale type is an ordinal/point/band scale, or (3) the encoding
channel is ``order``.
2) For a constant value in data domain (``datum``):
* ``"quantitative"`` if the datum is a number
* ``"nominal"`` if the datum is a string
* ``"temporal"`` if the datum is `a date time object
<https://vega.github.io/vega-lite/docs/datetime.html>`__
**Note:**
* Data ``type`` describes the semantics of the data rather than the primitive data
types (number, string, etc.). The same primitive data type can have different
types of measurement. For example, numeric data can represent quantitative,
ordinal, or nominal data.
* Data values for a temporal field can be either a date-time string (e.g.,
``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"``) or a
timestamp number (e.g., ``1552199579097``).
* When using with `bin <https://vega.github.io/vega-lite/docs/bin.html>`__, the
``type`` property can be either ``"quantitative"`` (for using a linear bin scale)
or `"ordinal" (for using an ordinal bin scale)
<https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__.
* When using with `timeUnit
<https://vega.github.io/vega-lite/docs/timeunit.html>`__, the ``type`` property
can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal"
(for using an ordinal scale)
<https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__.
* When using with `aggregate
<https://vega.github.io/vega-lite/docs/aggregate.html>`__, the ``type`` property
refers to the post-aggregation data type. For example, we can calculate count
``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct",
"field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``.
* Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError``) do not have
``type`` as they must have exactly the same type as their primary channels (e.g.,
``x``, ``y``).
**See also:** `type <https://vega.github.io/vega-lite/docs/type.html>`__
documentation.
"""
_class_is_valid_at_instantiation = False
_encoding_name = "color"
@overload
def aggregate(self, _: NonArgAggregateOp_T, /) -> Color: ...
@overload
def aggregate(self, *, argmax: Optional[str | SchemaBase] = Undefined) -> Color: ...
@overload
def aggregate(self, *, argmin: Optional[str | SchemaBase] = Undefined) -> Color: ...
@overload
def bandPosition(self, _: float, /) -> Color: ...
@overload
def bin(self, _: bool | Bin | None, /) -> Color: ...
@overload
def bin(
self,
*,
anchor: Optional[float] = Undefined,
base: Optional[float] = Undefined,
binned: Optional[bool] = Undefined,
divide: Optional[Sequence[float]] = Undefined,
extent: Optional[Parameter | SchemaBase | Sequence[float] | Map] = Undefined,
maxbins: Optional[float] = Undefined,
minstep: Optional[float] = Undefined,
nice: Optional[bool] = Undefined,
step: Optional[float] = Undefined,
steps: Optional[Sequence[float]] = Undefined,
) -> Color: ...
@overload
def condition(
self,
*,
test: Optional[str | SchemaBase | Map] = Undefined,
value: Optional[str | Parameter | SchemaBase | Map | None] = Undefined,
) -> Color: ...
@overload
def condition(
self,
*,
empty: Optional[bool] = Undefined,
param: Optional[str | SchemaBase] = Undefined,
value: Optional[str | Parameter | SchemaBase | Map | None] = Undefined,
) -> Color: ...
@overload
def condition(
self, _: list[core.ConditionalValueDefGradientstringnullExprRef], /
) -> Color: ...
@overload
def field(self, _: str | RepeatRef, /) -> Color: ...
@overload
def field(
self,
*,
repeat: Optional[Literal["row", "column", "repeat", "layer"]] = Undefined,
) -> Color: ...
@overload
def legend(self, _: Legend | None, /) -> Color: ...
@overload
def legend(
self,
*,
aria: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
clipHeight: Optional[float | Parameter | SchemaBase | Map] = Undefined,
columnPadding: Optional[float | Parameter | SchemaBase | Map] = Undefined,
columns: Optional[float | Parameter | SchemaBase | Map] = Undefined,
cornerRadius: Optional[float | Parameter | SchemaBase | Map] = Undefined,
description: Optional[str | Parameter | SchemaBase | Map] = Undefined,
direction: Optional[SchemaBase | Orientation_T] = Undefined,
fillColor: Optional[
str | Parameter | SchemaBase | Map | ColorName_T | None
] = Undefined,
format: Optional[str | SchemaBase | Map] = Undefined,
formatType: Optional[str] = Undefined,
gradientLength: Optional[float | Parameter | SchemaBase | Map] = Undefined,
gradientOpacity: Optional[float | Parameter | SchemaBase | Map] = Undefined,
gradientStrokeColor: Optional[
str | Parameter | SchemaBase | Map | ColorName_T | None
] = Undefined,
gradientStrokeWidth: Optional[float | Parameter | SchemaBase | Map] = Undefined,
gradientThickness: Optional[float | Parameter | SchemaBase | Map] = Undefined,
gridAlign: Optional[Parameter | SchemaBase | Map | LayoutAlign_T] = Undefined,
labelAlign: Optional[Parameter | SchemaBase | Map | Align_T] = Undefined,
labelBaseline: Optional[
Parameter | SchemaBase | Map | TextBaseline_T
] = Undefined,
labelColor: Optional[
str | Parameter | SchemaBase | Map | ColorName_T | None
] = Undefined,
labelExpr: Optional[str] = Undefined,
labelFont: Optional[str | Parameter | SchemaBase | Map] = Undefined,
labelFontSize: Optional[float | Parameter | SchemaBase | Map] = Undefined,
labelFontStyle: Optional[str | Parameter | SchemaBase | Map] = Undefined,
labelFontWeight: Optional[
Parameter | SchemaBase | Map | FontWeight_T
] = Undefined,
labelLimit: Optional[float | Parameter | SchemaBase | Map] = Undefined,
labelOffset: Optional[float | Parameter | SchemaBase | Map] = Undefined,
labelOpacity: Optional[float | Parameter | SchemaBase | Map] = Undefined,
labelOverlap: Optional[
bool | Parameter | SchemaBase | Literal["greedy", "parity"] | Map
] = Undefined,
labelPadding: Optional[float | Parameter | SchemaBase | Map] = Undefined,
labelSeparation: Optional[float | Parameter | SchemaBase | Map] = Undefined,
legendX: Optional[float | Parameter | SchemaBase | Map] = Undefined,
legendY: Optional[float | Parameter | SchemaBase | Map] = Undefined,
offset: Optional[float | Parameter | SchemaBase | Map] = Undefined,
orient: Optional[SchemaBase | LegendOrient_T] = Undefined,
padding: Optional[float | Parameter | SchemaBase | Map] = Undefined,
rowPadding: Optional[float | Parameter | SchemaBase | Map] = Undefined,
strokeColor: Optional[
str | Parameter | SchemaBase | Map | ColorName_T | None
] = Undefined,
symbolDash: Optional[
Parameter | SchemaBase | Sequence[float] | Map
] = Undefined,
symbolDashOffset: Optional[float | Parameter | SchemaBase | Map] = Undefined,
symbolFillColor: Optional[
str | Parameter | SchemaBase | Map | ColorName_T | None
] = Undefined,
symbolLimit: Optional[float | Parameter | SchemaBase | Map] = Undefined,
symbolOffset: Optional[float | Parameter | SchemaBase | Map] = Undefined,
symbolOpacity: Optional[float | Parameter | SchemaBase | Map] = Undefined,
symbolSize: Optional[float | Parameter | SchemaBase | Map] = Undefined,
symbolStrokeColor: Optional[
str | Parameter | SchemaBase | Map | ColorName_T | None
] = Undefined,
symbolStrokeWidth: Optional[float | Parameter | SchemaBase | Map] = Undefined,
symbolType: Optional[str | Parameter | SchemaBase | Map] = Undefined,
tickCount: Optional[
float | Parameter | SchemaBase | Map | TimeInterval_T
] = Undefined,
tickMinStep: Optional[float | Parameter | SchemaBase | Map] = Undefined,
title: Optional[str | SchemaBase | Sequence[str] | None] = Undefined,
titleAlign: Optional[Parameter | SchemaBase | Map | Align_T] = Undefined,
titleAnchor: Optional[Parameter | SchemaBase | Map | TitleAnchor_T] = Undefined,
titleBaseline: Optional[
Parameter | SchemaBase | Map | TextBaseline_T
] = Undefined,
titleColor: Optional[
str | Parameter | SchemaBase | Map | ColorName_T | None
] = Undefined,
titleFont: Optional[str | Parameter | SchemaBase | Map] = Undefined,
titleFontSize: Optional[float | Parameter | SchemaBase | Map] = Undefined,
titleFontStyle: Optional[str | Parameter | SchemaBase | Map] = Undefined,
titleFontWeight: Optional[
Parameter | SchemaBase | Map | FontWeight_T
] = Undefined,
titleLimit: Optional[float | Parameter | SchemaBase | Map] = Undefined,
titleLineHeight: Optional[float | Parameter | SchemaBase | Map] = Undefined,
titleOpacity: Optional[float | Parameter | SchemaBase | Map] = Undefined,
titleOrient: Optional[Parameter | SchemaBase | Map | Orient_T] = Undefined,
titlePadding: Optional[float | Parameter | SchemaBase | Map] = Undefined,
type: Optional[Literal["symbol", "gradient"]] = Undefined,
values: Optional[
Parameter
| SchemaBase
| Sequence[str]
| Sequence[bool]
| Sequence[float]
| Sequence[Temporal | SchemaBase | Map]
| Map
] = Undefined,
zindex: Optional[float] = Undefined,
) -> Color: ...
@overload
def scale(self, _: Scale | None, /) -> Color: ...
@overload
def scale(
self,
*,
align: Optional[float | Parameter | SchemaBase | Map] = Undefined,
base: Optional[float | Parameter | SchemaBase | Map] = Undefined,
bins: Optional[SchemaBase | Sequence[float] | Map] = Undefined,
clamp: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
constant: Optional[float | Parameter | SchemaBase | Map] = Undefined,
domain: Optional[
Parameter
| SchemaBase
| Literal["unaggregated"]
| Sequence[
str | bool | float | Temporal | Parameter | SchemaBase | Map | None
]
| Map
] = Undefined,
domainMax: Optional[
float | Temporal | Parameter | SchemaBase | Map
] = Undefined,
domainMid: Optional[float | Parameter | SchemaBase | Map] = Undefined,
domainMin: Optional[
float | Temporal | Parameter | SchemaBase | Map
] = Undefined,
domainRaw: Optional[Parameter | SchemaBase | Map] = Undefined,
exponent: Optional[float | Parameter | SchemaBase | Map] = Undefined,
interpolate: Optional[
Parameter | SchemaBase | Map | ScaleInterpolateEnum_T
] = Undefined,
nice: Optional[
bool | float | Parameter | SchemaBase | Map | TimeInterval_T
] = Undefined,
padding: Optional[float | Parameter | SchemaBase | Map] = Undefined,
paddingInner: Optional[float | Parameter | SchemaBase | Map] = Undefined,
paddingOuter: Optional[float | Parameter | SchemaBase | Map] = Undefined,
range: Optional[
SchemaBase
| Sequence[str | float | Parameter | SchemaBase | Sequence[float] | Map]
| Map
| RangeEnum_T
] = Undefined,
rangeMax: Optional[str | float | Parameter | SchemaBase | Map] = Undefined,
rangeMin: Optional[str | float | Parameter | SchemaBase | Map] = Undefined,
reverse: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
round: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
scheme: Optional[Parameter | SchemaBase | Map | ColorScheme_T] = Undefined,
type: Optional[SchemaBase | ScaleType_T] = Undefined,
zero: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
) -> Color: ...
@overload
def sort(
self,
_: Sequence[str]
| Sequence[bool]
| Sequence[float]
| Sequence[DateTime | Temporal]
| AllSortString_T
| None,
/,
) -> Color: ...
@overload
def sort(
self,
*,
field: Optional[str | SchemaBase | Map] = Undefined,
op: Optional[SchemaBase | NonArgAggregateOp_T] = Undefined,
order: Optional[SchemaBase | SortOrder_T | None] = Undefined,
) -> Color: ...
@overload
def sort(
self,
*,
encoding: Optional[SchemaBase | SortByChannel_T] = Undefined,
order: Optional[SchemaBase | SortOrder_T | None] = Undefined,
) -> Color: ...
@overload
def timeUnit(
self,
_: TimeUnitParams | MultiTimeUnit_T | BinnedTimeUnit_T | SingleTimeUnit_T,
/,
) -> Color: ...
@overload
def timeUnit(
self,
*,
binned: Optional[bool] = Undefined,
maxbins: Optional[float] = Undefined,
step: Optional[float] = Undefined,
unit: Optional[SchemaBase | MultiTimeUnit_T | SingleTimeUnit_T] = Undefined,
utc: Optional[bool] = Undefined,
) -> Color: ...
@overload
def title(self, _: str | Sequence[str] | None, /) -> Color: ...
@overload
def type(self, _: StandardType_T, /) -> Color: ...
def __init__(
self,
shorthand: Optional[str | SchemaBase | Sequence[str] | Map] = Undefined,
aggregate: Optional[SchemaBase | Map | NonArgAggregateOp_T] = Undefined,
bandPosition: Optional[float] = Undefined,
bin: Optional[bool | SchemaBase | Map | None] = Undefined,
condition: Optional[SchemaBase | Sequence[SchemaBase | Map] | Map] = Undefined,
field: Optional[str | SchemaBase | Map] = Undefined,
legend: Optional[SchemaBase | Map | None] = Undefined,
scale: Optional[SchemaBase | Map | None] = Undefined,
sort: Optional[
SchemaBase
| Sequence[str]
| Sequence[bool]
| Sequence[float]
| Sequence[Temporal | SchemaBase | Map]
| Map
| AllSortString_T
| None
] = Undefined,
timeUnit: Optional[
SchemaBase | Map | MultiTimeUnit_T | BinnedTimeUnit_T | SingleTimeUnit_T
] = Undefined,
title: Optional[str | SchemaBase | Sequence[str] | None] = Undefined,
type: Optional[SchemaBase | StandardType_T] = Undefined,
**kwds,
):
super().__init__(
shorthand=shorthand,
aggregate=aggregate,
bandPosition=bandPosition,
bin=bin,
condition=condition,
field=field,
legend=legend,
scale=scale,
sort=sort,
timeUnit=timeUnit,
title=title,
type=type,
**kwds,
)
@with_property_setters
| Color |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dataform.py | {
"start": 13022,
"end": 13761
} | class ____:
@mock.patch(HOOK_STR)
def test_execute(self, hook_mock):
op = DataformRemoveFileOperator(
task_id="remove-file",
project_id=PROJECT_ID,
region=REGION,
repository_id=REPOSITORY_ID,
workspace_id=WORKSPACE_ID,
filepath=FILEPATH,
)
op.execute(context=mock.MagicMock())
hook_mock.return_value.remove_file.assert_called_once_with(
project_id=PROJECT_ID,
region=REGION,
repository_id=REPOSITORY_ID,
workspace_id=WORKSPACE_ID,
filepath=FILEPATH,
retry=DEFAULT,
timeout=None,
metadata=(),
)
| TestDataformRemoveFileOperator |
python | getsentry__sentry | src/sentry/sentry_metrics/consumers/indexer/parsed_message.py | {
"start": 174,
"end": 354
} | class ____(IngestMetric):
"""Internal representation of a parsed ingest metric message for indexer to support generic metrics"""
use_case_id: Required[UseCaseID]
| ParsedMessage |
python | mlflow__mlflow | mlflow/models/evaluation/artifacts.py | {
"start": 1513,
"end": 1863
} | class ____(EvaluationArtifact):
def _save(self, output_artifact_path):
np.save(output_artifact_path, self._content, allow_pickle=False)
def _load_content_from_file(self, local_artifact_path):
self._content = np.load(local_artifact_path, allow_pickle=False)
return self._content
@developer_stable
| NumpyEvaluationArtifact |
python | huggingface__transformers | src/transformers/models/pop2piano/modeling_pop2piano.py | {
"start": 5844,
"end": 6642
} | class ____(nn.Module):
def __init__(self, config: Pop2PianoConfig):
super().__init__()
if config.is_gated_act:
self.DenseReluDense = Pop2PianoDenseGatedActDense(config)
else:
self.DenseReluDense = Pop2PianoDenseActDense(config)
self.layer_norm = Pop2PianoLayerNorm(config.d_model, eps=config.layer_norm_epsilon)
self.dropout = nn.Dropout(config.dropout_rate)
def forward(self, hidden_states):
forwarded_states = self.layer_norm(hidden_states)
forwarded_states = self.DenseReluDense(forwarded_states)
hidden_states = hidden_states + self.dropout(forwarded_states)
return hidden_states
# Copied from transformers.models.t5.modeling_t5.T5Attention with T5->Pop2Piano,t5->pop2piano
| Pop2PianoLayerFF |
python | django-import-export__django-import-export | tests/core/tests/admin_integration/test_import_functionality.py | {
"start": 11597,
"end": 15745
} | class ____(AdminTestMixin, TestCase):
def test_import_log_entry(self):
response = self._do_import_post(self.book_import_url, "books.csv")
self.assertEqual(response.status_code, 200)
confirm_form = response.context["confirm_form"]
data = confirm_form.initial
self._prepend_form_prefix(data)
self._post_url_response(self.book_process_import_url, data, follow=True)
book = LogEntry.objects.latest("id")
self.assertEqual(book.object_repr, "Some book")
self.assertEqual(book.object_id, str(1))
def test_import_log_entry_with_fk(self):
Parent.objects.create(id=1234, name="Some Parent")
response = self._do_import_post(self.child_import_url, "child.csv")
self.assertEqual(response.status_code, 200)
confirm_form = response.context["confirm_form"]
data = confirm_form.initial
self._prepend_form_prefix(data)
self._post_url_response(self.child_process_import_url, data, follow=True)
child = LogEntry.objects.latest("id")
self.assertEqual(child.object_repr, "Some - child of Some Parent")
self.assertEqual(child.object_id, str(1))
@patch("import_export.resources.Resource.skip_row")
def test_import_log_entry_skip_row(self, mock_skip_row):
# test issue 1937 - ensure that skipped rows do not create log entries
mock_skip_row.return_value = True
response = self._do_import_post(self.book_import_url, "books.csv")
self.assertEqual(response.status_code, 200)
confirm_form = response.context["confirm_form"]
data = confirm_form.initial
self._post_url_response(self.book_process_import_url, data, follow=True)
self.assertEqual(0, LogEntry.objects.count())
def test_import_log_entry_error_row(self):
# ensure that error rows do not create log entries
response = self._do_import_post(self.book_import_url, "books.csv")
self.assertEqual(response.status_code, 200)
confirm_form = response.context["confirm_form"]
data = confirm_form.initial
with mock.patch("core.admin.BookResource.skip_row") as mock_skip:
mock_skip.side_effect = ValueError("some unknown error")
self._post_url_response(self.book_process_import_url, data, follow=True)
self.assertEqual(0, LogEntry.objects.count())
def test_import_log_entry_validation_error_row(self):
# ensure that validation error rows do not create log entries
response = self._do_import_post(self.book_import_url, "books.csv")
self.assertEqual(response.status_code, 200)
confirm_form = response.context["confirm_form"]
data = confirm_form.initial
with mock.patch("core.admin.BookResource.skip_row") as mock_skip:
mock_skip.side_effect = ValidationError("some unknown error")
self._post_url_response(self.book_process_import_url, data, follow=True)
self.assertEqual(0, LogEntry.objects.count())
@override_settings(IMPORT_EXPORT_SKIP_ADMIN_LOG=True)
def test_import_log_entry_skip_admin_log(self):
response = self._do_import_post(self.book_import_url, "books.csv")
self.assertEqual(response.status_code, 200)
confirm_form = response.context["confirm_form"]
data = confirm_form.initial
self._post_url_response(self.book_process_import_url, data, follow=True)
self.assertEqual(0, LogEntry.objects.count())
def test_import_log_entry_skip_admin_log_attr(self):
response = self._do_import_post(self.book_import_url, "books.csv")
self.assertEqual(response.status_code, 200)
confirm_form = response.context["confirm_form"]
data = confirm_form.initial
with mock.patch(
"import_export.admin.ImportMixin.skip_admin_log",
new_callable=PropertyMock,
return_value=True,
):
self._post_url_response(self.book_process_import_url, data, follow=True)
self.assertEqual(0, LogEntry.objects.count())
@override_settings(IMPORT_EXPORT_SKIP_ADMIN_CONFIRM=True)
| ImportLogEntryTest |
python | kamyu104__LeetCode-Solutions | Python/convert-an-array-into-a-2d-array-with-conditions.py | {
"start": 88,
"end": 553
} | class ____(object):
def findMatrix(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = []
cnt = collections.Counter()
for x in nums:
if cnt[x] == len(result):
result.append([])
result[cnt[x]].append(x)
cnt[x] += 1
return result
# Time: O(n)
# Space: O(n)
import collections
# freq table, constructive algorithms
| Solution |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/random_flip_test.py | {
"start": 779,
"end": 9037
} | class ____(testing.TestCase):
@parameterized.named_parameters(
("random_flip_horizontal", "horizontal"),
("random_flip_vertical", "vertical"),
("random_flip_both", "horizontal_and_vertical"),
)
def test_random_flip(self, mode):
run_training_check = False if backend.backend() == "numpy" else True
self.run_layer_test(
layers.RandomFlip,
init_kwargs={
"mode": mode,
},
input_shape=(2, 3, 4),
expected_output_shape=(2, 3, 4),
supports_masking=False,
run_training_check=run_training_check,
)
def test_random_flip_horizontal(self):
run_training_check = False if backend.backend() == "numpy" else True
utils.set_random_seed(0)
# Test 3D input: shape (1*2*3)
self.run_layer_test(
MockedRandomFlip,
init_kwargs={
"mode": "horizontal",
"data_format": "channels_last",
"seed": 42,
},
input_data=np.asarray([[[2, 3, 4], [5, 6, 7]]]),
expected_output=backend.convert_to_tensor([[[5, 6, 7], [2, 3, 4]]]),
supports_masking=False,
run_training_check=run_training_check,
)
# Test 4D input: shape (2*1*2*3)
self.run_layer_test(
MockedRandomFlip,
init_kwargs={
"mode": "horizontal",
"data_format": "channels_last",
"seed": 42,
},
input_data=np.asarray(
[
[[[2, 3, 4], [5, 6, 7]]],
[[[2, 3, 4], [5, 6, 7]]],
]
),
expected_output=backend.convert_to_tensor(
[
[[[5, 6, 7], [2, 3, 4]]],
[[[5, 6, 7], [2, 3, 4]]],
]
),
supports_masking=False,
run_training_check=run_training_check,
)
def test_random_flip_vertical(self):
run_training_check = False if backend.backend() == "numpy" else True
utils.set_random_seed(0)
# Test 3D input: shape (2*1*3)
self.run_layer_test(
MockedRandomFlip,
init_kwargs={
"mode": "vertical",
"data_format": "channels_last",
"seed": 42,
},
input_data=np.asarray([[[2, 3, 4]], [[5, 6, 7]]]),
expected_output=backend.convert_to_tensor(
[[[5, 6, 7]], [[2, 3, 4]]]
),
supports_masking=False,
run_training_check=run_training_check,
)
# Test 4D input: shape (2*2*1*3)
self.run_layer_test(
MockedRandomFlip,
init_kwargs={
"mode": "vertical",
"data_format": "channels_last",
"seed": 42,
},
input_data=np.asarray(
[
[
[[2, 3, 4]],
[[5, 6, 7]],
],
[
[[2, 3, 4]],
[[5, 6, 7]],
],
]
),
expected_output=backend.convert_to_tensor(
[
[[[5, 6, 7]], [[2, 3, 4]]],
[[[5, 6, 7]], [[2, 3, 4]]],
]
),
supports_masking=False,
run_training_check=run_training_check,
)
def test_tf_data_compatibility(self):
# Test 3D input: shape (2, 1, 3)
layer = layers.RandomFlip(
"vertical", data_format="channels_last", seed=42
)
input_data = np.array([[[2, 3, 4]], [[5, 6, 7]]])
expected_output = np.array([[[5, 6, 7]], [[2, 3, 4]]])
ds = tf_data.Dataset.from_tensor_slices(input_data).batch(2).map(layer)
output = next(iter(ds)).numpy()
self.assertAllClose(output, expected_output)
# Test 4D input: shape (2, 2, 1, 3)
layer = layers.RandomFlip(
"vertical", data_format="channels_last", seed=42
)
input_data = np.array(
[
[
[[2, 3, 4]],
[[5, 6, 7]],
],
[
[[2, 3, 4]],
[[5, 6, 7]],
],
]
)
expected_output = np.array(
[
[[[5, 6, 7]], [[2, 3, 4]]],
[[[5, 6, 7]], [[2, 3, 4]]],
]
)
ds = tf_data.Dataset.from_tensor_slices(input_data).batch(2).map(layer)
output = next(iter(ds)).numpy()
self.assertAllClose(output, expected_output)
@parameterized.named_parameters(
(
"with_horizontal",
"horizontal",
[[4, 1, 6, 3], [0, 4, 2, 6]],
),
(
"with_vertical",
"vertical",
[[2, 7, 4, 9], [6, 4, 8, 6]],
),
(
"with_horizontal_and_vertical",
"horizontal_and_vertical",
[[4, 7, 6, 9], [0, 4, 2, 6]],
),
)
def test_random_flip_bounding_boxes(self, mode, expected_boxes):
data_format = backend.config.image_data_format()
if data_format == "channels_last":
image_shape = (10, 8, 3)
else:
image_shape = (3, 10, 8)
input_image = np.random.random(image_shape)
bounding_boxes = {
"boxes": np.array(
[
[2, 1, 4, 3],
[6, 4, 8, 6],
]
),
"labels": np.array([[1, 2]]),
}
input_data = {"images": input_image, "bounding_boxes": bounding_boxes}
random_flip_layer = layers.RandomFlip(
mode,
data_format=data_format,
seed=42,
bounding_box_format="xyxy",
)
transformation = {
"flips": np.asarray([[True]]),
"input_shape": input_image.shape,
}
output = random_flip_layer.transform_bounding_boxes(
input_data["bounding_boxes"],
transformation=transformation,
training=True,
)
self.assertAllClose(output["boxes"], expected_boxes)
@parameterized.named_parameters(
(
"with_horizontal",
"horizontal",
[[4, 1, 6, 3], [0, 4, 2, 6]],
),
(
"with_vertical",
"vertical",
[[2, 7, 4, 9], [6, 4, 8, 6]],
),
(
"with_horizontal_and_vertical",
"horizontal_and_vertical",
[[4, 7, 6, 9], [0, 4, 2, 6]],
),
)
def test_random_flip_tf_data_bounding_boxes(self, mode, expected_boxes):
data_format = backend.config.image_data_format()
if data_format == "channels_last":
image_shape = (1, 10, 8, 3)
else:
image_shape = (1, 3, 10, 8)
input_image = np.random.random(image_shape)
bounding_boxes = {
"boxes": np.array(
[
[
[2, 1, 4, 3],
[6, 4, 8, 6],
]
]
),
"labels": np.array([[1, 2]]),
}
input_data = {"images": input_image, "bounding_boxes": bounding_boxes}
ds = tf_data.Dataset.from_tensor_slices(input_data)
random_flip_layer = layers.RandomFlip(
mode,
data_format=data_format,
seed=42,
bounding_box_format="xyxy",
)
transformation = {
"flips": np.asarray([[True]]),
"input_shape": input_image.shape,
}
ds = ds.map(
lambda x: random_flip_layer.transform_bounding_boxes(
x["bounding_boxes"],
transformation=transformation,
training=True,
)
)
output = next(iter(ds))
expected_boxes = np.array(expected_boxes)
self.assertAllClose(output["boxes"], expected_boxes)
| RandomFlipTest |
python | kamyu104__LeetCode-Solutions | Python/check-if-the-sentence-is-pangram.py | {
"start": 37,
"end": 214
} | class ____(object):
def checkIfPangram(self, sentence):
"""
:type sentence: str
:rtype: bool
"""
return len(set(sentence)) == 26
| Solution |
python | pallets__werkzeug | src/werkzeug/exceptions.py | {
"start": 11051,
"end": 11360
} | class ____(HTTPException):
"""*404* `Not Found`
Raise if a resource does not exist and never existed.
"""
code = 404
description = (
"The requested URL was not found on the server. If you entered"
" the URL manually please check your spelling and try again."
)
| NotFound |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_pretty.py | {
"start": 16617,
"end": 17184
} | class ____(Flag):
A = 1
B = 2
def __repr__(self):
return "LyingReprOptions.A|B|C"
@pytest.mark.parametrize(
"rep",
[
"AnEnum.SOME_MEMBER",
"Options.A",
"Options.A | Options.B",
"Options.A | Options.B | Options.C",
"Options(0)",
"EvilReprOptions.A",
"LyingReprOptions.A",
"EvilReprOptions.A | EvilReprOptions.B",
"LyingReprOptions.A | LyingReprOptions.B",
],
)
def test_pretty_prints_enums_as_code(rep):
assert pretty.pretty(eval(rep)) == rep
| LyingReprOptions |
python | getsentry__sentry | src/sentry/sentry_metrics/indexer/base.py | {
"start": 526,
"end": 653
} | class ____(Enum):
CACHE_HIT = "c"
HARDCODED = "h"
DB_READ = "d"
FIRST_SEEN = "f"
RATE_LIMITED = "r"
| FetchType |
python | dask__distributed | distributed/shuffle/_limiter.py | {
"start": 167,
"end": 2798
} | class ____(Generic[_T]):
"""Limit an abstract resource
This allows us to track usage of an abstract resource. If the usage of this
resources goes beyond a defined limit, we can block further execution
Example::
limiter = ResourceLimiter(2)
limiter.increase(1)
limiter.increase(2)
limiter.decrease(1)
# This will block since we're still not below limit
await limiter.wait_for_available()
"""
limit: _T
metrics_label: str | None
_acquired: int
_condition: asyncio.Condition
_waiters: int
def __init__(self, limit: _T, metrics_label: str | None = None):
self.limit = limit
self.metrics_label = metrics_label
self._acquired = 0
self._condition = asyncio.Condition()
self._waiters = 0
def __repr__(self) -> str:
return f"<ResourceLimiter limit: {self.limit} available: {self.available}>"
@property
def available(self) -> _T:
"""How far can the value be increased before blocking"""
if self.limit is None:
return self.limit
return max(0, self.limit - self._acquired)
@property
def full(self) -> bool:
"""Return True if the limit has been reached"""
return self.available is not None and not self.available
@property
def empty(self) -> bool:
"""Return True if nothing has been acquired / the limiter is in a neutral state"""
return self._acquired == 0
async def wait_for_available(self) -> None:
"""Block until the counter drops below limit"""
if self.limit is not None:
# Include non-blocking calls in the calculation of the average
# seconds / count
context_meter.digest_metric(self.metrics_label, 1, "count")
if not self.full:
return
with context_meter.meter(self.metrics_label):
async with self._condition:
self._waiters += 1
await self._condition.wait_for(lambda: not self.full)
self._waiters -= 1
def increase(self, value: int) -> None:
"""Increase the internal counter by value"""
self._acquired += value
async def decrease(self, value: int) -> None:
"""Decrease the internal counter by value"""
if value > self._acquired:
raise RuntimeError(
f"Cannot release more than what was acquired! release: {value} acquired: {self._acquired}"
)
self._acquired -= value
async with self._condition:
self._condition.notify_all()
| ResourceLimiter |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/notification_with_inline_link.py | {
"start": 30,
"end": 247
} | class ____(App):
def on_mount(self) -> None:
self.notify("Click [@click=bell]here[/] for the bell sound.")
if __name__ == "__main__":
app = NotifyWithInlineLinkApp()
app.run()
| NotifyWithInlineLinkApp |
python | django__django | tests/backends/sqlite/test_introspection.py | {
"start": 1952,
"end": 7848
} | class ____(TestCase):
def parse_definition(self, sql, columns):
"""Parse a column or constraint definition."""
statement = sqlparse.parse(sql)[0]
tokens = (token for token in statement.flatten() if not token.is_whitespace)
with connection.cursor():
return connection.introspection._parse_column_or_constraint_definition(
tokens, set(columns)
)
def assertConstraint(self, constraint_details, cols, unique=False, check=False):
self.assertEqual(
constraint_details,
{
"unique": unique,
"columns": cols,
"primary_key": False,
"foreign_key": None,
"check": check,
"index": False,
},
)
def test_unique_column(self):
tests = (
('"ref" integer UNIQUE,', ["ref"]),
("ref integer UNIQUE,", ["ref"]),
('"customname" integer UNIQUE,', ["customname"]),
("customname integer UNIQUE,", ["customname"]),
)
for sql, columns in tests:
with self.subTest(sql=sql):
constraint, details, check, _ = self.parse_definition(sql, columns)
self.assertIsNone(constraint)
self.assertConstraint(details, columns, unique=True)
self.assertIsNone(check)
def test_unique_constraint(self):
tests = (
('CONSTRAINT "ref" UNIQUE ("ref"),', "ref", ["ref"]),
("CONSTRAINT ref UNIQUE (ref),", "ref", ["ref"]),
(
'CONSTRAINT "customname1" UNIQUE ("customname2"),',
"customname1",
["customname2"],
),
(
"CONSTRAINT customname1 UNIQUE (customname2),",
"customname1",
["customname2"],
),
)
for sql, constraint_name, columns in tests:
with self.subTest(sql=sql):
constraint, details, check, _ = self.parse_definition(sql, columns)
self.assertEqual(constraint, constraint_name)
self.assertConstraint(details, columns, unique=True)
self.assertIsNone(check)
def test_unique_constraint_multicolumn(self):
tests = (
(
'CONSTRAINT "ref" UNIQUE ("ref", "customname"),',
"ref",
["ref", "customname"],
),
("CONSTRAINT ref UNIQUE (ref, customname),", "ref", ["ref", "customname"]),
)
for sql, constraint_name, columns in tests:
with self.subTest(sql=sql):
constraint, details, check, _ = self.parse_definition(sql, columns)
self.assertEqual(constraint, constraint_name)
self.assertConstraint(details, columns, unique=True)
self.assertIsNone(check)
def test_check_column(self):
tests = (
('"ref" varchar(255) CHECK ("ref" != \'test\'),', ["ref"]),
("ref varchar(255) CHECK (ref != 'test'),", ["ref"]),
(
'"customname1" varchar(255) CHECK ("customname2" != \'test\'),',
["customname2"],
),
(
"customname1 varchar(255) CHECK (customname2 != 'test'),",
["customname2"],
),
)
for sql, columns in tests:
with self.subTest(sql=sql):
constraint, details, check, _ = self.parse_definition(sql, columns)
self.assertIsNone(constraint)
self.assertIsNone(details)
self.assertConstraint(check, columns, check=True)
def test_check_constraint(self):
tests = (
('CONSTRAINT "ref" CHECK ("ref" != \'test\'),', "ref", ["ref"]),
("CONSTRAINT ref CHECK (ref != 'test'),", "ref", ["ref"]),
(
'CONSTRAINT "customname1" CHECK ("customname2" != \'test\'),',
"customname1",
["customname2"],
),
(
"CONSTRAINT customname1 CHECK (customname2 != 'test'),",
"customname1",
["customname2"],
),
)
for sql, constraint_name, columns in tests:
with self.subTest(sql=sql):
constraint, details, check, _ = self.parse_definition(sql, columns)
self.assertEqual(constraint, constraint_name)
self.assertIsNone(details)
self.assertConstraint(check, columns, check=True)
def test_check_column_with_operators_and_functions(self):
tests = (
('"ref" integer CHECK ("ref" BETWEEN 1 AND 10),', ["ref"]),
('"ref" varchar(255) CHECK ("ref" LIKE \'test%\'),', ["ref"]),
(
'"ref" varchar(255) CHECK (LENGTH(ref) > "max_length"),',
["ref", "max_length"],
),
)
for sql, columns in tests:
with self.subTest(sql=sql):
constraint, details, check, _ = self.parse_definition(sql, columns)
self.assertIsNone(constraint)
self.assertIsNone(details)
self.assertConstraint(check, columns, check=True)
def test_check_and_unique_column(self):
tests = (
('"ref" varchar(255) CHECK ("ref" != \'test\') UNIQUE,', ["ref"]),
("ref varchar(255) UNIQUE CHECK (ref != 'test'),", ["ref"]),
)
for sql, columns in tests:
with self.subTest(sql=sql):
constraint, details, check, _ = self.parse_definition(sql, columns)
self.assertIsNone(constraint)
self.assertConstraint(details, columns, unique=True)
self.assertConstraint(check, columns, check=True)
| ParsingTests |
python | apache__airflow | helm-tests/tests/helm_tests/airflow_core/test_worker.py | {
"start": 47750,
"end": 48338
} | class ____:
"""Tests worker service."""
def test_should_add_component_specific_labels(self):
docs = render_chart(
values={
"executor": "CeleryExecutor",
"workers": {
"labels": {"test_label": "test_label_value"},
},
},
show_only=["templates/workers/worker-service.yaml"],
)
assert "test_label" in jmespath.search("metadata.labels", docs[0])
assert jmespath.search("metadata.labels", docs[0])["test_label"] == "test_label_value"
| TestWorkerService |
python | sympy__sympy | sympy/core/expr.py | {
"start": 142807,
"end": 144603
} | class ____:
def __init__(self, op, args=None, validator=None, check=True):
if not hasattr(op, "__call__"):
raise TypeError("op {} needs to be callable".format(op))
self.op = op
if args is None:
self.args = []
else:
self.args = args
self.validator = validator
if (validator is not None) and check:
self.validate()
@staticmethod
def _build_args(args):
return [i.build() if isinstance(i, ExprBuilder) else i for i in args]
def validate(self):
if self.validator is None:
return
args = self._build_args(self.args)
self.validator(*args)
def build(self, check=True):
args = self._build_args(self.args)
if self.validator and check:
self.validator(*args)
return self.op(*args)
def append_argument(self, arg, check=True):
self.args.append(arg)
if self.validator and check:
self.validate(*self.args)
def __getitem__(self, item):
if item == 0:
return self.op
else:
return self.args[item-1]
def __repr__(self):
return str(self.build())
def search_element(self, elem):
for i, arg in enumerate(self.args):
if isinstance(arg, ExprBuilder):
ret = arg.search_index(elem)
if ret is not None:
return (i,) + ret
elif id(arg) == id(elem):
return (i,)
return None
from .mul import Mul
from .add import Add
from .power import Pow
from .function import Function, _derivative_dispatch
from .mod import Mod
from .exprtools import factor_terms
from .numbers import Float, Integer, Rational, _illegal, int_valued
| ExprBuilder |
python | django__django | django/contrib/gis/db/models/functions.py | {
"start": 6069,
"end": 6169
} | class ____(GeoFunc):
output_field = FloatField()
arity = 2
geom_param_pos = (0, 1)
| Azimuth |
python | openai__openai-python | examples/parsing_tools.py | {
"start": 242,
"end": 485
} | class ____(str, Enum):
id = "id"
status = "status"
expected_delivery_date = "expected_delivery_date"
delivered_at = "delivered_at"
shipped_at = "shipped_at"
ordered_at = "ordered_at"
canceled_at = "canceled_at"
| Column |
python | django__django | tests/sitemaps_tests/urls/http.py | {
"start": 3152,
"end": 3449
} | class ____(Sitemap):
changefreq = "never"
priority = 0.5
location = "/location/"
def items(self):
return [object()]
def lastmod(self, obj):
return datetime(2013, 3, 13, 10, 0, 0)
def get_latest_lastmod(self):
return None
| GetLatestLastmodNoneSiteMap |
python | pallets__werkzeug | src/werkzeug/exceptions.py | {
"start": 15778,
"end": 16841
} | class ____(HTTPException):
"""*416* `Requested Range Not Satisfiable`
The client asked for an invalid part of the file.
.. versionadded:: 0.7
"""
code = 416
description = "The server cannot provide the requested range."
def __init__(
self,
length: int | None = None,
units: str = "bytes",
description: str | None = None,
response: SansIOResponse | None = None,
) -> None:
"""Takes an optional `Content-Range` header value based on ``length``
parameter.
"""
super().__init__(description=description, response=response)
self.length = length
self.units = units
def get_headers(
self,
environ: WSGIEnvironment | None = None,
scope: dict[str, t.Any] | None = None,
) -> list[tuple[str, str]]:
headers = super().get_headers(environ, scope)
if self.length is not None:
headers.append(("Content-Range", f"{self.units} */{self.length}"))
return headers
| RequestedRangeNotSatisfiable |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vectorizers.py | {
"start": 18071,
"end": 18283
} | class ____(_Multi2VecBase):
vectorizer: Union[Vectorizers, _EnumLikeStr] = Field(
default=Vectorizers.MULTI2VEC_CLIP, frozen=True, exclude=True
)
inferenceUrl: Optional[str]
| _Multi2VecClipConfig |
python | kamyu104__LeetCode-Solutions | Python/minimum-distance-to-the-target-element.py | {
"start": 29,
"end": 433
} | class ____(object):
def getMinDistance(self, nums, target, start):
"""
:type nums: List[int]
:type target: int
:type start: int
:rtype: int
"""
for i in xrange(len(nums)):
if (start-i >= 0 and nums[start-i] == target) or \
(start+i < len(nums) and nums[start+i] == target):
break
return i
| Solution |
python | pytransitions__transitions | tests/test_graphviz.py | {
"start": 1142,
"end": 13161
} | class ____(TestTransitions):
machine_cls = GraphMachine # type: Type[GraphMachine]
graph_engine = "graphviz" # type: Union[Literal["pygraphviz"], Literal["graphviz"], Literal["mermaid"]]
edge_re = re.compile(r"^\s+(?P<src>\w+)\s*->\s*(?P<dst>\w+)\s*(?P<attr>\[.*\]?)\s*$")
node_re = re.compile(r"^\s+(?P<node>\w+)\s+(?P<attr>\[.*\]?)\s*$")
def parse_dot(self, graph):
if self.graph_engine == "pygraphviz":
dot = graph.string()
else:
dot = graph.source
nodes = set()
edges = []
for line in dot.split('\n'):
match = self.edge_re.search(line)
if match:
nodes.add(match.group("src"))
nodes.add(match.group("dst"))
edges.append(match.group("attr"))
else:
match = self.node_re.search(line)
if match and match.group("node") not in ["node", "graph", "edge"]:
nodes.add(match.group("node"))
return dot, nodes, edges
def tearDown(self):
pass
# for m in ['pygraphviz', 'graphviz']:
# if 'transitions.extensions.diagrams_' + m in sys.modules:
# del sys.modules['transitions.extensions.diagrams_' + m]
def setUp(self):
self.stuff = Stuff(machine_cls=self.machine_cls, extra_kwargs={'graph_engine': self.graph_engine})
self.states = ['A', 'B', 'C', 'D'] # type: List[Union[str, Collection[str]]]
self.transitions = [
{'trigger': 'walk', 'source': 'A', 'dest': 'B'},
{'trigger': 'run', 'source': 'B', 'dest': 'C'},
{'trigger': 'sprint', 'source': 'C', 'dest': 'D', 'conditions': 'is_fast'},
{'trigger': 'sprint', 'source': 'C', 'dest': 'B'}
] # type: Sequence[TransitionConfigDict]
def test_diagram(self):
m = self.machine_cls(states=self.states, transitions=self.transitions, initial='A', auto_transitions=False,
title='a test', graph_engine=self.graph_engine)
graph = m.get_graph()
self.assertIsNotNone(graph)
self.assertTrue(graph.directed)
_, nodes, edges = self.parse_dot(graph)
# Test that graph properties match the Machine
self.assertEqual(set(m.states.keys()), nodes)
self.assertEqual(len(edges), len(self.transitions))
for e in edges:
# label should be equivalent to the event name
match = re.match(r'\[label=([^\]]+)\]', e)
self.assertIsNotNone(match and getattr(m, match.group(1)))
# write diagram to temp file
target = tempfile.NamedTemporaryFile(suffix='.png', delete=False)
graph.draw(target.name, format='png', prog='dot')
self.assertTrue(os.path.getsize(target.name) > 0)
# backwards compatibility check
m.get_graph().draw(target.name, format='png', prog='dot')
self.assertTrue(os.path.getsize(target.name) > 0)
# cleanup temp file
target.close()
os.unlink(target.name)
def test_transition_custom_model(self):
m = self.machine_cls(model=None, states=self.states, transitions=self.transitions, initial='A',
auto_transitions=False, title='a test', graph_engine=self.graph_engine)
model = DummyModel()
m.add_model(model)
model.walk()
def test_add_custom_state(self):
m = self.machine_cls(states=self.states, transitions=self.transitions, initial='A', auto_transitions=False,
title='a test', graph_engine=self.graph_engine)
m.add_state('X')
m.add_transition('foo', '*', 'X')
m.foo()
def test_if_multiple_edges_are_supported(self):
transitions = [
['event_0', 'a', 'b'],
['event_1', 'a', 'b'],
['event_2', 'a', 'b'],
['event_3', 'a', 'b'],
]
m = self.machine_cls(
states=['a', 'b'],
transitions=transitions,
initial='a',
auto_transitions=False,
graph_engine=self.graph_engine
)
graph = m.get_graph()
self.assertIsNotNone(graph)
triggers = [transition[0] for transition in transitions]
dot, _, _ = self.parse_dot(graph)
for trigger in triggers:
self.assertTrue(trigger in dot)
def test_multi_model_state(self):
m1 = Stuff(machine_cls=None, extra_kwargs={'graph_engine': self.graph_engine})
m2 = Stuff(machine_cls=None, extra_kwargs={'graph_engine': self.graph_engine})
m = self.machine_cls(model=[m1, m2], states=self.states, transitions=self.transitions, initial='A',
graph_engine=self.graph_engine)
m1.walk()
self.assertEqual(m.model_graphs[id(m1)].custom_styles['node'][m1.state], 'active')
self.assertEqual(m.model_graphs[id(m2)].custom_styles['node'][m1.state], '')
# backwards compatibility test
dot1, _, _ = self.parse_dot(m1.get_graph())
dot, _, _ = self.parse_dot(m.get_graph())
self.assertEqual(dot, dot1)
def test_model_method_collision(self):
class GraphModel:
def get_graph(self):
return "This method already exists"
model = GraphModel()
with self.assertRaises(AttributeError):
m = self.machine_cls(model=model)
self.assertEqual(model.get_graph(), "This method already exists")
def test_to_method_filtering(self):
m = self.machine_cls(states=['A', 'B', 'C'], initial='A', graph_engine=self.graph_engine)
m.add_transition('to_state_A', 'B', 'A')
m.add_transition('to_end', '*', 'C')
_, _, edges = self.parse_dot(m.get_graph())
self.assertEqual(len([e for e in edges if e == '[label=to_state_A]']), 1)
self.assertEqual(len([e for e in edges if e == '[label=to_end]']), 3)
m2 = self.machine_cls(states=['A', 'B', 'C'], initial='A', show_auto_transitions=True,
graph_engine=self.graph_engine)
_, _, edges = self.parse_dot(m2.get_graph())
self.assertEqual(len(edges), 9)
self.assertEqual(len([e for e in edges if e == '[label=to_A]']), 3)
self.assertEqual(len([e for e in edges if e == '[label=to_C]']), 3)
def test_loops(self):
m = self.machine_cls(states=['A'], initial='A', graph_engine=self.graph_engine)
m.add_transition('reflexive', 'A', '=')
m.add_transition('fixed', 'A', None)
g1 = m.get_graph()
if self.graph_engine == "pygraphviz":
dot_string = g1.string()
else:
dot_string = g1.source
try:
self.assertRegex(dot_string, r'A\s+->\s*A\s+\[label="(fixed|reflexive)')
except AttributeError: # Python 2 backwards compatibility
self.assertRegexpMatches(dot_string, r'A\s+->\s*A\s+\[label="(fixed|reflexive)')
def test_roi(self):
m = self.machine_cls(states=['A', 'B', 'C', 'D', 'E', 'F'], initial='A', graph_engine=self.graph_engine)
m.add_transition('to_state_A', 'B', 'A')
m.add_transition('to_state_C', 'B', 'C')
m.add_transition('to_state_F', 'B', 'F')
g1 = m.get_graph(show_roi=True)
dot, nodes, edges = self.parse_dot(g1)
self.assertEqual(0, len(edges))
self.assertIn(r'label="A\l"', dot)
# make sure that generating a graph without ROI has not influence on the later generated graph
# this has to be checked since graph.custom_style is a class property and is persistent for multiple
# calls of graph.generate()
m.to_C()
m.to_E()
_ = m.get_graph()
g2 = m.get_graph(show_roi=True)
dot, _, _ = self.parse_dot(g2)
self.assertNotIn(r'label="A\l"', dot)
m.to_B()
g3 = m.get_graph(show_roi=True)
_, nodes, edges = self.parse_dot(g3)
self.assertEqual(len(edges), 3) # to_state_{A,C,F}
self.assertEqual(len(nodes), 5) # B + A,C,F (edges) + E (previous)
def test_state_tags(self):
@add_state_features(Tags, Timeout)
class CustomMachine(self.machine_cls): # type: ignore
pass
self.states[0] = {'name': 'A', 'tags': ['new', 'polling'], 'timeout': 5, 'on_enter': 'say_hello',
'on_exit': 'say_goodbye', 'on_timeout': 'do_something'}
m = CustomMachine(states=self.states, transitions=self.transitions, initial='A', show_state_attributes=True,
graph_engine=self.graph_engine)
g = m.get_graph(show_roi=True)
def test_label_attribute(self):
class LabelState(self.machine_cls.state_cls): # type: ignore
def __init__(self, *args, **kwargs):
self.label = kwargs.pop('label')
super(LabelState, self).__init__(*args, **kwargs)
class CustomMachine(self.machine_cls): # type: ignore
state_cls = LabelState
m = CustomMachine(states=[{'name': 'A', 'label': 'LabelA'},
{'name': 'B', 'label': 'NotLabelA'}],
transitions=[{'trigger': 'event', 'source': 'A', 'dest': 'B', 'label': 'LabelEvent'}],
initial='A', graph_engine=self.graph_engine)
dot, _, _ = self.parse_dot(m.get_graph())
self.assertIn(r'label="LabelA\l"', dot)
self.assertIn(r'label="NotLabelA\l"', dot)
self.assertIn("label=LabelEvent", dot)
self.assertNotIn(r'label="A\l"', dot)
self.assertNotIn("label=event", dot)
def test_binary_stream(self):
from io import BytesIO
m = self.machine_cls(states=['A', 'B', 'C'], initial='A', auto_transitions=True,
title='A test', show_conditions=True, graph_engine=self.graph_engine)
b1 = BytesIO()
g = m.get_graph()
g.draw(b1, format='png', prog='dot')
b2 = g.draw(None, format='png', prog='dot')
self.assertEqual(b2, b1.getvalue())
b1.close()
def test_graphviz_fallback(self):
try:
from unittest import mock # will raise an ImportError in Python 2.7
from transitions.extensions.diagrams_graphviz import Graph
from transitions.extensions import diagrams_pygraphviz
from importlib import reload
with mock.patch.dict('sys.modules', {'pygraphviz': None}):
# load and reload diagrams_pygraphviz to make sure
# an ImportError is raised for pygraphviz
reload(diagrams_pygraphviz)
m = self.machine_cls(states=['A', 'B', 'C'], initial='A', graph_engine="pygraphviz")
# make sure to reload after test is done to avoid side effects with other tests
reload(diagrams_pygraphviz)
# print(m.graph_cls, pgv)
self.assertTrue(issubclass(m.graph_cls, Graph))
except ImportError:
pass
def test_function_callbacks_annotation(self):
m = self.machine_cls(states=['A', 'B'], initial='A', graph_engine=self.graph_engine, show_conditions=True)
m.add_transition('advance', 'A', 'B', conditions=m.is_A, unless=m.is_B)
_, nodes, edges = self.parse_dot(m.get_graph())
self.assertIn("[is_state(A", edges[0])
def test_update_on_remove_transition(self):
m = self.machine_cls(states=self.states, transitions=self.transitions, initial='A',
graph_engine=self.graph_engine, show_state_attributes=True)
_, _, edges = self.parse_dot(m.get_graph())
assert "[label=walk]" in edges
m.remove_transition(trigger="walk", source="A", dest="B")
_, _, edges = self.parse_dot(m.get_graph())
assert not any("walk" == t["trigger"] for t in m.markup["transitions"])
assert "[label=walk]" not in edges
@skipIf(pgv is None, 'Graph diagram test requires graphviz')
| TestDiagrams |
python | python-openxml__python-docx | tests/image/test_image.py | {
"start": 9732,
"end": 10926
} | class ____:
def it_constructs_the_right_class_for_a_given_image_stream(self, call_fixture):
stream, expected_class = call_fixture
image_header = _ImageHeaderFactory(stream)
assert isinstance(image_header, expected_class)
def it_raises_on_unrecognized_image_stream(self):
stream = io.BytesIO(b"foobar 666 not an image stream")
with pytest.raises(UnrecognizedImageError):
_ImageHeaderFactory(stream)
# fixtures -------------------------------------------------------
@pytest.fixture(
params=[
("python-icon.png", Png),
("python-icon.jpeg", Jfif),
("exif-420-dpi.jpg", Exif),
("sonic.gif", Gif),
("72-dpi.tiff", Tiff),
("little-endian.tif", Tiff),
("python.bmp", Bmp),
]
)
def call_fixture(self, request):
image_filename, expected_class = request.param
image_path = test_file(image_filename)
with open(image_path, "rb") as f:
blob = f.read()
image_stream = io.BytesIO(blob)
image_stream.seek(666)
return image_stream, expected_class
| Describe_ImageHeaderFactory |
python | mlflow__mlflow | dev/clint/src/clint/linter.py | {
"start": 10851,
"end": 12442
} | class ____(ast.NodeVisitor):
def __init__(self, linter: "Linter") -> None:
self.linter = linter
self.stack: list[ast.AST] = []
def visit(self, node: ast.AST) -> None:
self.stack.append(node)
super().visit(node)
self.stack.pop()
def visit_Name(self, node: ast.Name) -> None:
if rules.IncorrectTypeAnnotation.check(node):
self.linter._check(Range.from_node(node), rules.IncorrectTypeAnnotation(node.id))
if self._is_bare_generic_type(node):
self.linter._check(Range.from_node(node), rules.UnparameterizedGenericType(node.id))
self.generic_visit(node)
def visit_Attribute(self, node: ast.Attribute) -> None:
if self._is_bare_generic_type(node):
self.linter._check(
Range.from_node(node), rules.UnparameterizedGenericType(ast.unparse(node))
)
self.generic_visit(node)
def _is_bare_generic_type(self, node: ast.Name | ast.Attribute) -> bool:
"""Check if this node is a bare generic type (e.g., `dict` or `list` without parameters)."""
if not rules.UnparameterizedGenericType.is_generic_type(node, self.linter.resolver):
return False
# Check if this node is the value of a Subscript (e.g., the 'dict' in 'dict[str, int]').
# `[:-1]` skips the current node, which is the one being checked.
for parent in reversed(self.stack[:-1]):
if isinstance(parent, ast.Subscript) and parent.value is node:
return False
return True
| TypeAnnotationVisitor |
python | huggingface__transformers | examples/pytorch/summarization/run_summarization.py | {
"start": 4832,
"end": 32163
} | class ____:
"""
Arguments pertaining to what data we are going to input our model for training and eval.
"""
lang: Optional[str] = field(default=None, metadata={"help": "Language id for summarization."})
dataset_name: Optional[str] = field(
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
)
dataset_config_name: Optional[str] = field(
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
)
text_column: Optional[str] = field(
default=None,
metadata={"help": "The name of the column in the datasets containing the full texts (for summarization)."},
)
summary_column: Optional[str] = field(
default=None,
metadata={"help": "The name of the column in the datasets containing the summaries (for summarization)."},
)
train_file: Optional[str] = field(
default=None, metadata={"help": "The input training data file (a jsonlines or csv file)."}
)
validation_file: Optional[str] = field(
default=None,
metadata={
"help": (
"An optional input evaluation data file to evaluate the metrics (rouge) on (a jsonlines or csv file)."
)
},
)
test_file: Optional[str] = field(
default=None,
metadata={
"help": "An optional input test data file to evaluate the metrics (rouge) on (a jsonlines or csv file)."
},
)
overwrite_cache: bool = field(
default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
)
preprocessing_num_workers: Optional[int] = field(
default=None,
metadata={"help": "The number of processes to use for the preprocessing."},
)
max_source_length: Optional[int] = field(
default=1024,
metadata={
"help": (
"The maximum total input sequence length after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded."
)
},
)
max_target_length: Optional[int] = field(
default=128,
metadata={
"help": (
"The maximum total sequence length for target text after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded."
)
},
)
val_max_target_length: Optional[int] = field(
default=None,
metadata={
"help": (
"The maximum total sequence length for validation target text after tokenization. Sequences longer "
"than this will be truncated, sequences shorter will be padded. Will default to `max_target_length`. "
"This argument is also used to override the ``max_length`` param of ``model.generate``, which is used "
"during ``evaluate`` and ``predict``."
)
},
)
pad_to_max_length: bool = field(
default=False,
metadata={
"help": (
"Whether to pad all samples to model maximum sentence length. "
"If False, will pad the samples dynamically when batching to the maximum length in the batch. More "
"efficient on GPU but very bad for TPU."
)
},
)
max_train_samples: Optional[int] = field(
default=None,
metadata={
"help": (
"For debugging purposes or quicker training, truncate the number of training examples to this "
"value if set."
)
},
)
max_eval_samples: Optional[int] = field(
default=None,
metadata={
"help": (
"For debugging purposes or quicker training, truncate the number of evaluation examples to this "
"value if set."
)
},
)
max_predict_samples: Optional[int] = field(
default=None,
metadata={
"help": (
"For debugging purposes or quicker training, truncate the number of prediction examples to this "
"value if set."
)
},
)
num_beams: Optional[int] = field(
default=1,
metadata={
"help": (
"Number of beams to use for evaluation. This argument will be passed to ``model.generate``, "
"which is used during ``evaluate`` and ``predict``."
)
},
)
ignore_pad_token_for_loss: bool = field(
default=True,
metadata={
"help": "Whether to ignore the tokens corresponding to padded labels in the loss computation or not."
},
)
source_prefix: Optional[str] = field(
default=None, metadata={"help": "A prefix to add before every source text (useful for T5 models)."}
)
forced_bos_token: Optional[str] = field(
default=None,
metadata={
"help": (
"The token to force as the first generated token after the decoder_start_token_id. "
"Useful for multilingual models like mBART where the first generated token"
"needs to be the target language token (Usually it is the target language token)"
)
},
)
def __post_init__(self):
if (
self.dataset_name is None
and self.train_file is None
and self.validation_file is None
and self.test_file is None
):
raise ValueError("Need either a dataset name or a training, validation, or test file.")
else:
if self.train_file is not None:
extension = self.train_file.split(".")[-1]
assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
if self.validation_file is not None:
extension = self.validation_file.split(".")[-1]
assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."
if self.test_file is not None:
extension = self.test_file.split(".")[-1]
assert extension in ["csv", "json"], "`test_file` should be a csv or a json file."
if self.val_max_target_length is None:
self.val_max_target_length = self.max_target_length
summarization_name_mapping = {
"amazon_reviews_multi": ("review_body", "review_title"),
"big_patent": ("description", "abstract"),
"cnn_dailymail": ("article", "highlights"),
"orange_sum": ("text", "summary"),
"pn_summary": ("article", "summary"),
"psc": ("extract_text", "summary_text"),
"samsum": ("dialogue", "summary"),
"thaisum": ("body", "summary"),
"xglue": ("news_body", "news_title"),
"xsum": ("document", "summary"),
"wiki_summary": ("article", "highlights"),
"multi_news": ("document", "summary"),
}
def main():
# See all possible arguments in src/transformers/training_args.py
# or by passing the --help flag to this script.
# We now keep distinct sets of args, for a cleaner separation of concerns.
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments))
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
# If we pass only one argument to the script and it's the path to a json file,
# let's parse it to get our arguments.
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
# Setup logging
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
handlers=[logging.StreamHandler(sys.stdout)],
)
if training_args.should_log:
# The default of training_args.log_level is passive, so we set log level at info here to have that default.
transformers.utils.logging.set_verbosity_info()
log_level = training_args.get_process_log_level()
logger.setLevel(log_level)
datasets.utils.logging.set_verbosity(log_level)
transformers.utils.logging.set_verbosity(log_level)
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_process_index}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, "
+ f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
if data_args.source_prefix is None and model_args.model_name_or_path in [
"google-t5/t5-small",
"google-t5/t5-base",
"google-t5/t5-large",
"google-t5/t5-3b",
"google-t5/t5-11b",
]:
logger.warning(
"You're running a t5 model but didn't provide a source prefix, which is the expected, e.g. with "
"`--source_prefix 'summarize: ' `"
)
# Set seed before initializing model.
set_seed(training_args.seed)
# Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
# (the dataset will be downloaded automatically from the datasets Hub).
#
# For CSV/JSON files this script will use the first column for the full texts and the second column for the
# summaries (unless you specify column names for this with the `text_column` and `summary_column` arguments).
#
# In distributed training, the load_dataset function guarantee that only one local process can concurrently
# download the dataset.
if data_args.dataset_name is not None:
# Downloading and loading a dataset from the hub.
raw_datasets = load_dataset(
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
token=model_args.token,
trust_remote_code=model_args.trust_remote_code,
)
else:
data_files = {}
if data_args.train_file is not None:
data_files["train"] = data_args.train_file
extension = data_args.train_file.split(".")[-1]
if data_args.validation_file is not None:
data_files["validation"] = data_args.validation_file
extension = data_args.validation_file.split(".")[-1]
if data_args.test_file is not None:
data_files["test"] = data_args.test_file
extension = data_args.test_file.split(".")[-1]
raw_datasets = load_dataset(
extension,
data_files=data_files,
cache_dir=model_args.cache_dir,
token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.
# Load pretrained model and tokenizer
#
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
config = AutoConfig.from_pretrained(
model_args.config_name if model_args.config_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
token=model_args.token,
trust_remote_code=model_args.trust_remote_code,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
revision=model_args.model_revision,
token=model_args.token,
trust_remote_code=model_args.trust_remote_code,
)
model = AutoModelForSeq2SeqLM.from_pretrained(
model_args.model_name_or_path,
from_tf=bool(".ckpt" in model_args.model_name_or_path),
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
token=model_args.token,
trust_remote_code=model_args.trust_remote_code,
)
# We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
# on a small vocab and want a smaller embedding size, remove this test.
embedding_size = model.get_input_embeddings().weight.shape[0]
if len(tokenizer) > embedding_size:
model.resize_token_embeddings(len(tokenizer))
if model.config.decoder_start_token_id is None and isinstance(tokenizer, (MBartTokenizer, MBartTokenizerFast)):
if isinstance(tokenizer, MBartTokenizer):
model.config.decoder_start_token_id = tokenizer.lang_code_to_id[data_args.lang]
else:
model.config.decoder_start_token_id = tokenizer.convert_tokens_to_ids(data_args.lang)
if model.config.decoder_start_token_id is None:
raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined")
if (
hasattr(model.config, "max_position_embeddings")
and model.config.max_position_embeddings < data_args.max_source_length
):
if model_args.resize_position_embeddings is None:
logger.warning(
"Increasing the model's number of position embedding vectors from"
f" {model.config.max_position_embeddings} to {data_args.max_source_length}."
)
model.resize_position_embeddings(data_args.max_source_length)
elif model_args.resize_position_embeddings:
model.resize_position_embeddings(data_args.max_source_length)
else:
raise ValueError(
f"`--max_source_length` is set to {data_args.max_source_length}, but the model only has"
f" {model.config.max_position_embeddings} position encodings. Consider either reducing"
f" `--max_source_length` to {model.config.max_position_embeddings} or to automatically resize the"
" model's position encodings by passing `--resize_position_embeddings`."
)
prefix = data_args.source_prefix if data_args.source_prefix is not None else ""
# Preprocessing the datasets.
# We need to tokenize inputs and targets.
if training_args.do_train:
if "train" not in raw_datasets:
raise ValueError("--do_train requires a train dataset")
column_names = raw_datasets["train"].column_names
elif training_args.do_eval:
if "validation" not in raw_datasets:
raise ValueError("--do_eval requires a validation dataset")
column_names = raw_datasets["validation"].column_names
elif training_args.do_predict:
if "test" not in raw_datasets:
raise ValueError("--do_predict requires a test dataset")
column_names = raw_datasets["test"].column_names
else:
logger.info("There is nothing to do. Please pass `do_train`, `do_eval` and/or `do_predict`.")
return
if isinstance(tokenizer, tuple(MULTILINGUAL_TOKENIZERS)):
assert data_args.lang is not None, (
f"{tokenizer.__class__.__name__} is a multilingual tokenizer which requires --lang argument"
)
tokenizer.src_lang = data_args.lang
tokenizer.tgt_lang = data_args.lang
# For multilingual translation models like mBART-50 and M2M100 we need to force the target language token
# as the first generated token. We ask the user to explicitly provide this as --forced_bos_token argument.
forced_bos_token_id = (
tokenizer.lang_code_to_id[data_args.forced_bos_token] if data_args.forced_bos_token is not None else None
)
model.config.forced_bos_token_id = forced_bos_token_id
# Get the column names for input/target.
dataset_columns = summarization_name_mapping.get(data_args.dataset_name)
if data_args.text_column is None:
text_column = dataset_columns[0] if dataset_columns is not None else column_names[0]
else:
text_column = data_args.text_column
if text_column not in column_names:
raise ValueError(
f"--text_column' value '{data_args.text_column}' needs to be one of: {', '.join(column_names)}"
)
if data_args.summary_column is None:
summary_column = dataset_columns[1] if dataset_columns is not None else column_names[1]
else:
summary_column = data_args.summary_column
if summary_column not in column_names:
raise ValueError(
f"--summary_column' value '{data_args.summary_column}' needs to be one of: {', '.join(column_names)}"
)
# Temporarily set max_target_length for training.
max_target_length = data_args.max_target_length
padding = "max_length" if data_args.pad_to_max_length else False
if training_args.label_smoothing_factor > 0 and not hasattr(model, "prepare_decoder_input_ids_from_labels"):
logger.warning(
"label_smoothing is enabled but the `prepare_decoder_input_ids_from_labels` method is not defined for "
f"`{model.__class__.__name__}`. This will lead to loss being calculated twice and will take up more memory"
)
def preprocess_function(examples):
# remove pairs where at least one record is None
inputs, targets = [], []
for i in range(len(examples[text_column])):
if examples[text_column][i] and examples[summary_column][i]:
inputs.append(examples[text_column][i])
targets.append(examples[summary_column][i])
inputs = [prefix + inp for inp in inputs]
model_inputs = tokenizer(inputs, max_length=data_args.max_source_length, padding=padding, truncation=True)
# Tokenize targets with the `text_target` keyword argument
labels = tokenizer(text_target=targets, max_length=max_target_length, padding=padding, truncation=True)
# If we are padding here, replace all tokenizer.pad_token_id in the labels by -100 when we want to ignore
# padding in the loss.
if padding == "max_length" and data_args.ignore_pad_token_for_loss:
labels["input_ids"] = [
[(l if l != tokenizer.pad_token_id else -100) for l in label] for label in labels["input_ids"]
]
model_inputs["labels"] = labels["input_ids"]
return model_inputs
if training_args.do_train:
train_dataset = raw_datasets["train"]
if data_args.max_train_samples is not None:
max_train_samples = min(len(train_dataset), data_args.max_train_samples)
train_dataset = train_dataset.select(range(max_train_samples))
with training_args.main_process_first(desc="train dataset map pre-processing"):
train_dataset = train_dataset.map(
preprocess_function,
batched=True,
num_proc=data_args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not data_args.overwrite_cache,
desc="Running tokenizer on train dataset",
)
if training_args.do_eval:
max_target_length = data_args.val_max_target_length
eval_dataset = raw_datasets["validation"]
if data_args.max_eval_samples is not None:
max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples)
eval_dataset = eval_dataset.select(range(max_eval_samples))
with training_args.main_process_first(desc="validation dataset map pre-processing"):
eval_dataset = eval_dataset.map(
preprocess_function,
batched=True,
num_proc=data_args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not data_args.overwrite_cache,
desc="Running tokenizer on validation dataset",
)
if training_args.do_predict:
max_target_length = data_args.val_max_target_length
predict_dataset = raw_datasets["test"]
if data_args.max_predict_samples is not None:
max_predict_samples = min(len(predict_dataset), data_args.max_predict_samples)
predict_dataset = predict_dataset.select(range(max_predict_samples))
with training_args.main_process_first(desc="prediction dataset map pre-processing"):
predict_dataset = predict_dataset.map(
preprocess_function,
batched=True,
num_proc=data_args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not data_args.overwrite_cache,
desc="Running tokenizer on prediction dataset",
)
# Data collator
label_pad_token_id = -100 if data_args.ignore_pad_token_for_loss else tokenizer.pad_token_id
data_collator = DataCollatorForSeq2Seq(
tokenizer,
model=model,
label_pad_token_id=label_pad_token_id,
pad_to_multiple_of=8 if training_args.fp16 else None,
)
# Metric
metric = evaluate.load("rouge", cache_dir=model_args.cache_dir)
def postprocess_text(preds, labels):
preds = [pred.strip() for pred in preds]
labels = [label.strip() for label in labels]
# rougeLSum expects newline after each sentence
preds = ["\n".join(nltk.sent_tokenize(pred)) for pred in preds]
labels = ["\n".join(nltk.sent_tokenize(label)) for label in labels]
return preds, labels
def compute_metrics(eval_preds):
preds, labels = eval_preds
if isinstance(preds, tuple):
preds = preds[0]
# Replace -100s used for padding as we can't decode them
preds = np.where(preds != -100, preds, tokenizer.pad_token_id)
decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)
labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
# Some simple post-processing
decoded_preds, decoded_labels = postprocess_text(decoded_preds, decoded_labels)
result = metric.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=True)
result = {k: round(v * 100, 4) for k, v in result.items()}
prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in preds]
result["gen_len"] = np.mean(prediction_lens)
return result
# Override the decoding parameters of Seq2SeqTrainer
training_args.generation_max_length = (
training_args.generation_max_length
if training_args.generation_max_length is not None
else data_args.val_max_target_length
)
training_args.generation_num_beams = (
data_args.num_beams if data_args.num_beams is not None else training_args.generation_num_beams
)
# Initialize our Trainer
trainer = Seq2SeqTrainer(
model=model,
args=training_args,
train_dataset=train_dataset if training_args.do_train else None,
eval_dataset=eval_dataset if training_args.do_eval else None,
processing_class=tokenizer,
data_collator=data_collator,
compute_metrics=compute_metrics if training_args.predict_with_generate else None,
)
# Training
if training_args.do_train:
checkpoint = None
if training_args.resume_from_checkpoint is not None:
checkpoint = training_args.resume_from_checkpoint
train_result = trainer.train(resume_from_checkpoint=checkpoint)
trainer.save_model() # Saves the tokenizer too for easy upload
metrics = train_result.metrics
max_train_samples = (
data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset)
)
metrics["train_samples"] = min(max_train_samples, len(train_dataset))
trainer.log_metrics("train", metrics)
trainer.save_metrics("train", metrics)
trainer.save_state()
# Evaluation
results = {}
if training_args.do_eval:
logger.info("*** Evaluate ***")
if isinstance(eval_dataset, dict):
metrics = {}
for eval_ds_name, eval_ds in eval_dataset.items():
dataset_metrics = trainer.evaluate(eval_dataset=eval_ds, metric_key_prefix=f"eval_{eval_ds_name}")
metrics.update(dataset_metrics)
else:
metrics = trainer.evaluate(metric_key_prefix="eval")
max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset)
metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset))
trainer.log_metrics("eval", metrics)
trainer.save_metrics("eval", metrics)
if training_args.do_predict:
logger.info("*** Predict ***")
predict_results = trainer.predict(predict_dataset, metric_key_prefix="predict")
metrics = predict_results.metrics
max_predict_samples = (
data_args.max_predict_samples if data_args.max_predict_samples is not None else len(predict_dataset)
)
metrics["predict_samples"] = min(max_predict_samples, len(predict_dataset))
trainer.log_metrics("predict", metrics)
trainer.save_metrics("predict", metrics)
if trainer.is_world_process_zero():
if training_args.predict_with_generate:
predictions = predict_results.predictions
predictions = np.where(predictions != -100, predictions, tokenizer.pad_token_id)
predictions = tokenizer.batch_decode(
predictions, skip_special_tokens=True, clean_up_tokenization_spaces=True
)
predictions = [pred.strip() for pred in predictions]
output_prediction_file = os.path.join(training_args.output_dir, "generated_predictions.txt")
with open(output_prediction_file, "w") as writer:
writer.write("\n".join(predictions))
kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "summarization"}
if data_args.dataset_name is not None:
kwargs["dataset_tags"] = data_args.dataset_name
if data_args.dataset_config_name is not None:
kwargs["dataset_args"] = data_args.dataset_config_name
kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
else:
kwargs["dataset"] = data_args.dataset_name
if data_args.lang is not None:
kwargs["language"] = data_args.lang
if training_args.push_to_hub:
trainer.push_to_hub(**kwargs)
else:
trainer.create_model_card(**kwargs)
return results
def _mp_fn(index):
# For xla_spawn (TPUs)
main()
if __name__ == "__main__":
main()
| DataTrainingArguments |
python | plotly__plotly.py | plotly/graph_objs/icicle/_tiling.py | {
"start": 233,
"end": 5081
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "icicle"
_path_str = "icicle.tiling"
_valid_props = {"flip", "orientation", "pad"}
@property
def flip(self):
"""
Determines if the positions obtained from solver are flipped on
each axis.
The 'flip' property is a flaglist and may be specified
as a string containing:
- Any combination of ['x', 'y'] joined with '+' characters
(e.g. 'x+y')
Returns
-------
Any
"""
return self["flip"]
@flip.setter
def flip(self, val):
self["flip"] = val
@property
def orientation(self):
"""
When set in conjunction with `tiling.flip`, determines on which
side the root nodes are drawn in the chart. If
`tiling.orientation` is "v" and `tiling.flip` is "", the root
nodes appear at the top. If `tiling.orientation` is "v" and
`tiling.flip` is "y", the root nodes appear at the bottom. If
`tiling.orientation` is "h" and `tiling.flip` is "", the root
nodes appear at the left. If `tiling.orientation` is "h" and
`tiling.flip` is "x", the root nodes appear at the right.
The 'orientation' property is an enumeration that may be specified as:
- One of the following enumeration values:
['v', 'h']
Returns
-------
Any
"""
return self["orientation"]
@orientation.setter
def orientation(self, val):
self["orientation"] = val
@property
def pad(self):
"""
Sets the inner padding (in px).
The 'pad' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["pad"]
@pad.setter
def pad(self, val):
self["pad"] = val
@property
def _prop_descriptions(self):
return """\
flip
Determines if the positions obtained from solver are
flipped on each axis.
orientation
When set in conjunction with `tiling.flip`, determines
on which side the root nodes are drawn in the chart. If
`tiling.orientation` is "v" and `tiling.flip` is "",
the root nodes appear at the top. If
`tiling.orientation` is "v" and `tiling.flip` is "y",
the root nodes appear at the bottom. If
`tiling.orientation` is "h" and `tiling.flip` is "",
the root nodes appear at the left. If
`tiling.orientation` is "h" and `tiling.flip` is "x",
the root nodes appear at the right.
pad
Sets the inner padding (in px).
"""
def __init__(self, arg=None, flip=None, orientation=None, pad=None, **kwargs):
"""
Construct a new Tiling object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.icicle.Tiling`
flip
Determines if the positions obtained from solver are
flipped on each axis.
orientation
When set in conjunction with `tiling.flip`, determines
on which side the root nodes are drawn in the chart. If
`tiling.orientation` is "v" and `tiling.flip` is "",
the root nodes appear at the top. If
`tiling.orientation` is "v" and `tiling.flip` is "y",
the root nodes appear at the bottom. If
`tiling.orientation` is "h" and `tiling.flip` is "",
the root nodes appear at the left. If
`tiling.orientation` is "h" and `tiling.flip` is "x",
the root nodes appear at the right.
pad
Sets the inner padding (in px).
Returns
-------
Tiling
"""
super().__init__("tiling")
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.icicle.Tiling
constructor must be a dict or
an instance of :class:`plotly.graph_objs.icicle.Tiling`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("flip", arg, flip)
self._set_property("orientation", arg, orientation)
self._set_property("pad", arg, pad)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Tiling |
python | streamlit__streamlit | lib/streamlit/errors.py | {
"start": 18715,
"end": 19074
} | class ____(LocalizableStreamlitException):
"""Exception raised when trying to set values where writes are not allowed."""
def __init__(self, key: str) -> None:
super().__init__(
"Values for the widget with `key` '{key}' cannot be set using `st.session_state`.",
key=key,
)
| StreamlitValueAssignmentNotAllowedError |
python | pytorch__pytorch | torch/distributed/fsdp/_fully_shard/_fsdp_collectives.py | {
"start": 2467,
"end": 2887
} | class ____(DefaultAllocMixin, AllGather):
def __call__(
self,
output_tensor: torch.Tensor,
input_tensor: torch.Tensor,
group: dist.ProcessGroup,
async_op: bool = False,
) -> Optional[dist.Work]:
return dist.all_gather_into_tensor(
output_tensor,
input_tensor,
group=group,
async_op=async_op,
)
| DefaultAllGather |
python | getsentry__sentry | src/sentry/auth/email.py | {
"start": 953,
"end": 4534
} | class ____:
email: str
organization: Organization | None
def resolve(self, candidates: Collection[UserEmail]) -> User:
"""Pick the user best matching the email address."""
if not candidates:
raise ValueError
if len(candidates) == 1:
(unique_email,) = candidates
return unique_email.user
for step_cls in self.get_steps():
step = step_cls(self)
last_candidates = candidates
candidates = tuple(step.apply(candidates))
if len(candidates) == 1:
# Success: We've narrowed down to only one candidate
(choice,) = candidates
step.if_conclusive(last_candidates, choice)
return choice.user
if len(candidates) == 0:
# If the step eliminated all, ignore it and go to the next step
candidates = last_candidates
self.if_inconclusive(candidates)
raise AmbiguousUserFromEmail(self.email, [ue.user for ue in candidates])
def if_inconclusive(self, remaining_candidates: Collection[UserEmail]) -> None:
"""Hook to call if no step resolves to a single user."""
metrics.incr("auth.email_resolution.no_resolution", sample_rate=1.0)
@dataclass
class ResolutionStep(abc.ABC):
parent: _EmailResolver
@abc.abstractmethod
def apply(self, candidates: Collection[UserEmail]) -> Iterable[UserEmail]:
raise NotImplementedError
def if_conclusive(self, candidates: Collection[UserEmail], choice: UserEmail) -> None:
"""Hook to call if this step resolves to a single user."""
class IsVerified(ResolutionStep):
"""Prefer verified email addresses."""
def apply(self, candidates: Collection[UserEmail]) -> Iterable[UserEmail]:
return (ue for ue in candidates if ue.is_verified)
def if_conclusive(self, candidates: Collection[UserEmail], choice: UserEmail) -> None:
metrics.incr("auth.email_resolution.by_verification", sample_rate=1.0)
class HasOrgMembership(ResolutionStep):
"""Prefer users who belong to the organization."""
def apply(self, candidates: Collection[UserEmail]) -> Iterable[UserEmail]:
if not self.parent.organization:
return ()
candidate_ids = [ue.user_id for ue in candidates]
member_summaries = organization_service.get_member_summaries_by_ids(
organization_id=self.parent.organization.id, user_ids=candidate_ids
)
users_in_org = {member_summary.user_id for member_summary in member_summaries}
return (ue for ue in candidates if ue.user_id in users_in_org)
def if_conclusive(self, candidates: Collection[UserEmail], choice: UserEmail) -> None:
metrics.incr("auth.email_resolution.by_org_membership", sample_rate=1.0)
class IsPrimary(ResolutionStep):
"""Prefer users whose primary address matches the address in question."""
def apply(self, candidates: Collection[UserEmail]) -> Iterable[UserEmail]:
return (ue for ue in candidates if ue.is_primary())
def if_conclusive(self, candidates: Collection[UserEmail], choice: UserEmail) -> None:
metrics.incr("auth.email_resolution.by_primary_email", sample_rate=1.0)
def get_steps(self) -> Iterable[type[ResolutionStep]]:
return (
self.IsVerified,
self.HasOrgMembership,
self.IsPrimary,
)
| _EmailResolver |
python | tensorflow__tensorflow | tensorflow/python/keras/engine/training_generator_v1.py | {
"start": 27024,
"end": 30841
} | class ____(training_utils_v1.TrainingLoop):
"""TrainingLoop that handle inputs like python generator.
This is the default handler for most of the input data types, includes
symbolic tensors or Numpy array-like, Datasets and iterators in graph mode
(since they generate symbolic tensors). This Function is used to handle model
with `run_eagerly` = True.
"""
def fit(self,
model,
x=None,
y=None,
batch_size=None,
epochs=1,
verbose=1,
callbacks=None,
validation_split=0.,
validation_data=None,
shuffle=True,
class_weight=None,
sample_weight=None,
initial_epoch=0,
steps_per_epoch=None,
validation_steps=None,
validation_freq=1,
**kwargs):
batch_size = model._validate_or_infer_batch_size(batch_size,
steps_per_epoch, x)
x, y, sample_weights = model._standardize_user_data(
x,
y,
sample_weight=sample_weight,
class_weight=class_weight,
batch_size=batch_size,
check_steps=True,
steps_name='steps_per_epoch',
steps=steps_per_epoch,
validation_split=validation_split,
shuffle=shuffle)
if validation_data:
validation_data = model._prepare_validation_data(validation_data,
batch_size,
validation_steps)
elif validation_split and 0. < validation_split < 1.:
(x, y, sample_weights, val_x, val_y,
val_sample_weights) = (
training_utils_v1.split_training_and_validation_data(
x, y, sample_weights, validation_split))
validation_data = (val_x, val_y, val_sample_weights)
else:
if validation_steps:
raise ValueError('`validation_steps` should not be specified if '
'`validation_data` is None.')
return fit_generator(
model, (x, y, sample_weights),
steps_per_epoch=steps_per_epoch,
batch_size=batch_size,
epochs=epochs,
verbose=verbose,
callbacks=callbacks,
validation_data=validation_data,
validation_steps=validation_steps,
validation_freq=validation_freq,
workers=0,
shuffle=shuffle,
initial_epoch=initial_epoch,
steps_name='steps_per_epoch')
def evaluate(self,
model,
x=None,
y=None,
batch_size=None,
verbose=1,
sample_weight=None,
steps=None,
callbacks=None,
**kwargs):
batch_size = model._validate_or_infer_batch_size(batch_size, steps, x)
x, y, sample_weights = model._standardize_user_data(
x,
y,
sample_weight=sample_weight,
batch_size=batch_size,
check_steps=True,
steps_name='steps',
steps=steps)
return evaluate_generator(
model, (x, y, sample_weights),
steps=steps,
batch_size=batch_size,
verbose=verbose,
workers=0,
callbacks=callbacks)
def predict(self,
model,
x,
batch_size=None,
verbose=0,
steps=None,
callbacks=None,
**kwargs):
batch_size = model._validate_or_infer_batch_size(batch_size, steps, x)
x, _, _ = model._standardize_user_data(
x, check_steps=True, steps_name='steps', steps=steps)
return predict_generator(
model,
x,
steps=steps,
batch_size=batch_size,
verbose=verbose,
workers=0,
callbacks=callbacks)
| GeneratorLikeTrainingLoop |
python | huggingface__transformers | src/transformers/models/hgnet_v2/modeling_hgnet_v2.py | {
"start": 12136,
"end": 14477
} | class ____(HGNetV2PreTrainedModel, BackboneMixin):
has_attentions = False
def __init__(self, config: HGNetV2Config):
super().__init__(config)
super()._init_backbone(config)
self.depths = config.depths
self.num_features = [config.embedding_size] + config.hidden_sizes
self.embedder = HGNetV2Embeddings(config)
self.encoder = HGNetV2Encoder(config)
# initialize weights and apply final processing
self.post_init()
@auto_docstring
def forward(
self, pixel_values: Tensor, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None
) -> BackboneOutput:
r"""
Examples:
```python
>>> from transformers import HGNetV2Config, HGNetV2Backbone
>>> import torch
>>> config = HGNetV2Config()
>>> model = HGNetV2Backbone(config)
>>> pixel_values = torch.randn(1, 3, 224, 224)
>>> with torch.no_grad():
... outputs = model(pixel_values)
>>> feature_maps = outputs.feature_maps
>>> list(feature_maps[-1].shape)
[1, 2048, 7, 7]
```"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
embedding_output = self.embedder(pixel_values)
outputs = self.encoder(embedding_output, output_hidden_states=True, return_dict=True)
hidden_states = outputs.hidden_states
feature_maps = ()
for idx, stage in enumerate(self.stage_names):
if stage in self.out_features:
feature_maps += (hidden_states[idx],)
if not return_dict:
output = (feature_maps,)
if output_hidden_states:
output += (outputs.hidden_states,)
return output
return BackboneOutput(
feature_maps=feature_maps,
hidden_states=outputs.hidden_states if output_hidden_states else None,
attentions=None,
)
@auto_docstring(
custom_intro="""
HGNetV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
ImageNet.
"""
)
| HGNetV2Backbone |
python | crytic__slither | slither/detectors/operations/cache_array_length.py | {
"start": 480,
"end": 8915
} | class ____(AbstractDetector):
"""
Detects `for` loops that use `length` member of some storage array in their loop condition and don't modify it.
"""
ARGUMENT = "cache-array-length"
HELP = (
"Detects `for` loops that use `length` member of some storage array in their loop condition and don't "
"modify it."
)
IMPACT = DetectorClassification.OPTIMIZATION
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#cache-array-length"
WIKI_TITLE = "Cache array length"
WIKI_DESCRIPTION = (
"Detects `for` loops that use `length` member of some storage array in their loop condition "
"and don't modify it. "
)
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract C
{
uint[] array;
function f() public
{
for (uint i = 0; i < array.length; i++)
{
// code that does not modify length of `array`
}
}
}
```
Since the `for` loop in `f` doesn't modify `array.length`, it is more gas efficient to cache it in some local variable and use that variable instead, like in the following example:
```solidity
contract C
{
uint[] array;
function f() public
{
uint array_length = array.length;
for (uint i = 0; i < array_length; i++)
{
// code that does not modify length of `array`
}
}
}
```
"""
WIKI_RECOMMENDATION = (
"Cache the lengths of storage arrays if they are used and not modified in `for` loops."
)
@staticmethod
def _is_identifier_member_access_comparison(exp: BinaryOperation) -> bool:
"""
Checks whether a BinaryOperation `exp` is an operation on Identifier and MemberAccess.
"""
return (
isinstance(exp.expression_left, Identifier)
and isinstance(exp.expression_right, MemberAccess)
) or (
isinstance(exp.expression_left, MemberAccess)
and isinstance(exp.expression_right, Identifier)
)
@staticmethod
def _extract_array_from_length_member_access(exp: MemberAccess) -> StateVariable:
"""
Given a member access `exp`, it returns state array which `length` member is accessed through `exp`.
If array is not a state array or its `length` member is not referenced, it returns `None`.
"""
if exp.member_name != "length":
return None
if not isinstance(exp.expression, Identifier):
return None
if not isinstance(exp.expression.value, StateVariable):
return None
if not isinstance(exp.expression.value.type, ArrayType):
return None
return exp.expression.value
@staticmethod
def _is_loop_referencing_array_length(
node: Node, visited: Set[Node], array: StateVariable, depth: int
) -> True:
"""
For a given loop, checks if it references `array.length` at some point.
Will also return True if `array.length` is referenced but not changed.
This may potentially generate false negatives in the detector, but it was done this way because:
- situations when array `length` is referenced but not modified in loop are rare
- checking if `array.length` is indeed modified would require much more work
"""
visited.add(node)
if node.type == NodeType.STARTLOOP:
depth += 1
if node.type == NodeType.ENDLOOP:
depth -= 1
if depth == 0:
return False
# Array length may change in the following situations:
# - when `push` is called
# - when `pop` is called
# - when `delete` is called on the entire array
# - when external function call is made (instructions from internal function calls are already in
# `node.all_slithir_operations()`, so we don't need to handle internal calls separately)
if node.type == NodeType.EXPRESSION:
for op in node.all_slithir_operations():
if isinstance(op, Length) and op.value == array:
# op accesses array.length, not necessarily modifying it
return True
if isinstance(op, Delete):
# take into account only delete entire array, since delete array[i] doesn't change `array.length`
if (
isinstance(op.expression, UnaryOperation)
and isinstance(op.expression.expression, Identifier)
and op.expression.expression.value == array
):
return True
if (
isinstance(op, HighLevelCall)
and isinstance(op.function, Function)
and not op.function.view
and not op.function.pure
):
return True
for son in node.sons:
if son not in visited:
if CacheArrayLength._is_loop_referencing_array_length(son, visited, array, depth):
return True
return False
@staticmethod
def _handle_loops(nodes: List[Node], non_optimal_array_len_usages: List[Node]) -> None:
"""
For each loop, checks if it has a comparison with `length` array member and, if it has, checks whether that
array size could potentially change in that loop.
If it cannot, the loop condition is added to `non_optimal_array_len_usages`.
There may be some false negatives here - see docs for `_is_loop_referencing_array_length` for more information.
"""
for node in nodes:
if node.type == NodeType.STARTLOOP:
if_node = node.sons[0]
if if_node.type != NodeType.IFLOOP:
continue
if not isinstance(if_node.expression, BinaryOperation):
continue
exp: BinaryOperation = if_node.expression
if not CacheArrayLength._is_identifier_member_access_comparison(exp):
continue
array: StateVariable
if isinstance(exp.expression_right, MemberAccess):
array = CacheArrayLength._extract_array_from_length_member_access(
exp.expression_right
)
else: # isinstance(exp.expression_left, MemberAccess) == True
array = CacheArrayLength._extract_array_from_length_member_access(
exp.expression_left
)
if array is None:
continue
visited: Set[Node] = set()
if not CacheArrayLength._is_loop_referencing_array_length(
if_node, visited, array, 1
):
non_optimal_array_len_usages.append(if_node)
@staticmethod
def _get_non_optimal_array_len_usages_for_function(f: Function) -> List[Node]:
"""
Finds non-optimal usages of array length in loop conditions in a given function.
"""
non_optimal_array_len_usages: List[Node] = []
CacheArrayLength._handle_loops(f.nodes, non_optimal_array_len_usages)
return non_optimal_array_len_usages
@staticmethod
def _get_non_optimal_array_len_usages(functions: List[Function]) -> List[Node]:
"""
Finds non-optimal usages of array length in loop conditions in given functions.
"""
non_optimal_array_len_usages: List[Node] = []
for f in functions:
non_optimal_array_len_usages += (
CacheArrayLength._get_non_optimal_array_len_usages_for_function(f)
)
return non_optimal_array_len_usages
def _detect(self):
results = []
non_optimal_array_len_usages = CacheArrayLength._get_non_optimal_array_len_usages(
self.compilation_unit.functions
)
for usage in non_optimal_array_len_usages:
info = [
"Loop condition ",
usage,
" should use cached array length instead of referencing `length` member "
"of the storage array.\n ",
]
res = self.generate_result(info)
results.append(res)
return results
| CacheArrayLength |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-ads/source_google_ads/streams.py | {
"start": 4266,
"end": 10483
} | class ____(GoogleAdsStream, CheckpointMixin, ABC):
primary_key = None
days_of_data_storage = None
cursor_field = "segments.date"
cursor_time_format = "YYYY-MM-DD"
# Slice duration is set to 14 days, because for conversion_window_days default value is 14.
# Range less than 14 days will break the integration tests.
slice_duration = pendulum.duration(days=14)
# slice step is difference from one slice end_date and next slice start_date
slice_step = pendulum.duration(days=1)
def __init__(self, start_date: str, conversion_window_days: int, end_date: str = None, **kwargs):
self.conversion_window_days = conversion_window_days
self._start_date = start_date
self._end_date = end_date
self._state = {}
super().__init__(**kwargs)
@property
def state_checkpoint_interval(self) -> int:
# default page size is 10000, so set to 10% of it
return 1000
@property
def state(self) -> MutableMapping[str, Any]:
return self._state
@state.setter
def state(self, value: MutableMapping[str, Any]):
self._state.update(value)
def get_current_state(self, customer_id, default=None):
default = default or self.state.get(self.cursor_field)
if self.state is not None:
customer = self.state.get(customer_id, {})
if isinstance(customer, MutableMapping):
return customer.get(self.cursor_field)
else:
return default
def stream_slices(self, stream_state: Mapping[str, Any] = None, **kwargs) -> Iterable[Optional[MutableMapping[str, any]]]:
for customer in self.customers:
stream_state = stream_state or {}
if stream_state.get(customer.id):
start_date = stream_state[customer.id].get(self.cursor_field) or self._start_date
# We should keep backward compatibility with the previous version
elif stream_state.get(self.cursor_field) and len(self.customers) == 1:
start_date = stream_state.get(self.cursor_field) or self._start_date
else:
start_date = self._start_date
end_date = self._end_date
for chunk in chunk_date_range(
start_date=start_date,
end_date=end_date,
conversion_window=self.conversion_window_days,
days_of_data_storage=self.days_of_data_storage,
time_zone=customer.time_zone,
time_format=self.cursor_time_format,
slice_duration=self.slice_duration,
slice_step=self.slice_step,
):
if chunk:
chunk["customer_id"] = customer.id
chunk["login_customer_id"] = customer.login_customer_id
yield chunk
def _update_state(self, customer_id: str, record: MutableMapping[str, Any]):
"""Update the state based on the latest record's cursor value."""
current_state = self.get_current_state(customer_id)
if current_state:
date_in_current_stream = pendulum.parse(current_state)
date_in_latest_record = pendulum.parse(record[self.cursor_field])
cursor_value = (max(date_in_current_stream, date_in_latest_record)).format(self.cursor_time_format)
self.state = {customer_id: {self.cursor_field: cursor_value}}
else:
self.state = {customer_id: {self.cursor_field: record[self.cursor_field]}}
def _handle_expired_page_exception(self, exception: ExpiredPageTokenError, stream_slice: MutableMapping[str, Any], customer_id: str):
"""
Handle Google Ads EXPIRED_PAGE_TOKEN error by updating the stream slice.
"""
start_date, end_date = parse_dates(stream_slice)
current_state = self.get_current_state(customer_id)
if end_date - start_date <= self.slice_step:
# If range days less than slice_step, no need in retry, because it's the minimum date range
raise exception
elif current_state == stream_slice["start_date"]:
# It couldn't read all the records within one day, it will enter an infinite loop,
# so raise the error
raise exception
# Retry reading records from where it crushed
stream_slice["start_date"] = self.get_current_state(customer_id, default=stream_slice["start_date"])
def read_records(
self, sync_mode: SyncMode, cursor_field: List[str] = None, stream_slice: MutableMapping[str, Any] = None, **kwargs
) -> Iterable[Mapping[str, Any]]:
"""
This method is overridden to handle GoogleAdsException with EXPIRED_PAGE_TOKEN error code,
and update `start_date` key in the `stream_slice` with the latest read record's cursor value, then retry the sync.
"""
while True:
customer_id = stream_slice and stream_slice["customer_id"]
try:
# count records to update slice date range with latest record time when limit is hit
records = super().read_records(sync_mode, stream_slice=stream_slice)
for record in records:
self._update_state(customer_id, record)
yield record
except ExpiredPageTokenError as exception:
# handle expired page error that was caught in parent class by updating stream_slice
self._handle_expired_page_exception(exception, stream_slice, customer_id)
else:
return
def get_query(self, stream_slice: Mapping[str, Any] = None) -> str:
fields = GoogleAds.get_fields_from_schema(self.get_json_schema())
table_name = get_resource_name(self.name)
start_date, end_date = stream_slice.get("start_date"), stream_slice.get("end_date")
cursor_condition = [f"{self.cursor_field} >= '{start_date}' AND {self.cursor_field} <= '{end_date}'"]
query = GoogleAds.convert_schema_into_query(
fields=fields, table_name=table_name, conditions=cursor_condition, order_field=self.cursor_field
)
return query
| IncrementalGoogleAdsStream |
python | getsentry__sentry | src/sentry/explore/endpoints/explore_saved_query_starred.py | {
"start": 534,
"end": 900
} | class ____(serializers.Serializer):
starred = serializers.BooleanField(required=True)
position = serializers.IntegerField(required=False)
def validate(self, data):
if not data["starred"] and "position" in data:
raise serializers.ValidationError("Position is only allowed when starring a query.")
return data
| StarQuerySerializer |
python | python-markdown__markdown | markdown/postprocessors.py | {
"start": 2219,
"end": 3803
} | class ____(Postprocessor):
""" Restore raw html to the document. """
BLOCK_LEVEL_REGEX = re.compile(r'^\<\/?([^ >]+)')
def run(self, text: str) -> str:
""" Iterate over html stash and restore html. """
def substitute_match(m: re.Match[str]) -> str:
if key := m.group(1):
wrapped = True
else:
key = m.group(2)
wrapped = False
if (key := int(key)) >= self.md.htmlStash.html_counter:
return m.group(0)
html = self.stash_to_string(self.md.htmlStash.rawHtmlBlocks[key])
if not wrapped or self.isblocklevel(html):
return pattern.sub(substitute_match, html)
return pattern.sub(substitute_match, f"<p>{html}</p>")
if self.md.htmlStash.html_counter:
base_placeholder = util.HTML_PLACEHOLDER % r'([0-9]+)'
pattern = re.compile(f'<p>{ base_placeholder }</p>|{ base_placeholder }')
return pattern.sub(substitute_match, text)
else:
return text
def isblocklevel(self, html: str) -> bool:
""" Check is block of HTML is block-level. """
m = self.BLOCK_LEVEL_REGEX.match(html)
if m:
if m.group(1)[0] in ('!', '?', '@', '%'):
# Comment, PHP etc...
return True
return self.md.is_block_level(m.group(1))
return False
def stash_to_string(self, text: str) -> str:
""" Convert a stashed object to a string. """
return str(text)
| RawHtmlPostprocessor |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/scheduler/scheduler.py | {
"start": 816,
"end": 916
} | class ____(DagsterError):
"""Base class for all Dagster Scheduler errors."""
| DagsterSchedulerError |
python | apache__airflow | providers/slack/tests/unit/slack/notifications/test_slack_webhook.py | {
"start": 1082,
"end": 6227
} | class ____:
def test_class_and_notifier_are_same(self):
assert send_slack_webhook_notification is SlackWebhookNotifier
@mock.patch("airflow.providers.slack.notifications.slack_webhook.SlackWebhookHook")
@pytest.mark.parametrize(
("slack_op_kwargs", "hook_extra_kwargs"),
[
pytest.param({}, DEFAULT_HOOKS_PARAMETERS, id="default-hook-parameters"),
pytest.param(
{"timeout": 42, "proxy": "http://spam.egg", "retry_handlers": []},
{"timeout": 42, "proxy": "http://spam.egg", "retry_handlers": []},
id="with-extra-hook-parameters",
),
],
)
def test_slack_webhook_notifier(self, mock_slack_hook, slack_op_kwargs, hook_extra_kwargs):
notifier = send_slack_webhook_notification(
slack_webhook_conn_id="test_conn_id",
text="foo-bar",
blocks="spam-egg",
attachments="baz-qux",
unfurl_links=True,
unfurl_media=False,
**slack_op_kwargs,
)
notifier.notify({})
mock_slack_hook.return_value.send.assert_called_once_with(
text="foo-bar",
blocks="spam-egg",
unfurl_links=True,
unfurl_media=False,
attachments="baz-qux",
)
mock_slack_hook.assert_called_once_with(slack_webhook_conn_id="test_conn_id", **hook_extra_kwargs)
@pytest.mark.asyncio
@mock.patch("airflow.providers.slack.notifications.slack_webhook.SlackWebhookHook")
async def test_async_slack_webhook_notifier(self, mock_slack_hook):
mock_hook = mock_slack_hook.return_value
mock_hook.async_send = mock.AsyncMock()
notifier = send_slack_webhook_notification(
slack_webhook_conn_id="test_conn_id",
text="foo-bar",
blocks="spam-egg",
attachments="baz-qux",
unfurl_links=True,
unfurl_media=False,
)
await notifier.async_notify({})
mock_hook.async_send.assert_called_once_with(
text="foo-bar",
blocks="spam-egg",
unfurl_links=True,
unfurl_media=False,
attachments="baz-qux",
)
@mock.patch("airflow.providers.slack.notifications.slack_webhook.SlackWebhookHook")
def test_slack_webhook_templated(self, mock_slack_hook, create_dag_without_db):
notifier = send_slack_webhook_notification(
text="Who am I? {{ username }}",
blocks=[{"type": "header", "text": {"type": "plain_text", "text": "{{ dag.dag_id }}"}}],
attachments=[{"image_url": "{{ dag.dag_id }}.png"}],
)
notifier(
{
"dag": create_dag_without_db("test_send_slack_webhook_notification_templated"),
"username": "not-a-root",
}
)
mock_slack_hook.return_value.send.assert_called_once_with(
text="Who am I? not-a-root",
blocks=[
{
"type": "header",
"text": {"type": "plain_text", "text": "test_send_slack_webhook_notification_templated"},
}
],
attachments=[{"image_url": "test_send_slack_webhook_notification_templated.png"}],
unfurl_links=None,
unfurl_media=None,
)
@pytest.mark.asyncio
@mock.patch("airflow.providers.slack.notifications.slack_webhook.SlackWebhookHook")
async def test_async_slack_webhook_templated(self, mock_slack_hook, create_dag_without_db):
"""Test async notification with template rendering."""
mock_hook = mock_slack_hook.return_value
mock_hook.async_send = mock.AsyncMock()
notifier = send_slack_webhook_notification(
text="Who am I? {{ username }}",
blocks=[{"type": "header", "text": {"type": "plain_text", "text": "{{ dag.dag_id }}"}}],
attachments=[{"image_url": "{{ dag.dag_id }}.png"}],
)
# Call notifier first to handle template rendering
notifier(
{
"dag": create_dag_without_db("test_async_send_slack_webhook_notification_templated"),
"username": "not-a-root",
}
)
# Then call async_notify with rendered templates
await notifier.async_notify(
{
"dag": create_dag_without_db("test_async_send_slack_webhook_notification_templated"),
"username": "not-a-root",
}
)
mock_hook.async_send.assert_called_once_with(
text="Who am I? not-a-root",
blocks=[
{
"type": "header",
"text": {
"type": "plain_text",
"text": "test_async_send_slack_webhook_notification_templated",
},
}
],
attachments=[{"image_url": "test_async_send_slack_webhook_notification_templated.png"}],
unfurl_links=None,
unfurl_media=None,
)
| TestSlackNotifier |
python | pypa__warehouse | warehouse/predicates.py | {
"start": 1339,
"end": 2638
} | class ____:
def __init__(self, val, config):
self.val = bool(val)
def text(self):
return f"require_active_organization = {self.val}"
phash = text
def __call__(self, context: Organization | Team, request):
"""Check organizations are enabled globally and this organization is
operational.
1. `AdminFlagValue.DISABLE_ORGANIZATIONS` flag is off.
2. Organization is operational (uses consolidated is_in_good_standing()
method).
"""
if self.val is False:
return True
organization = (
context if isinstance(context, Organization) else context.organization
)
if organization.is_in_good_standing():
return True
elif (
# Organization accounts are disabled.
request.flags.enabled(AdminFlagValue.DISABLE_ORGANIZATIONS)
):
return False
else:
raise HTTPSeeOther(request.route_path("manage.organizations"))
def includeme(config):
config.add_route_predicate("domain", DomainPredicate)
config.add_view_predicate("require_headers", HeadersPredicate)
config.add_view_predicate(
"require_active_organization", ActiveOrganizationPredicate
)
| ActiveOrganizationPredicate |
python | walkccc__LeetCode | solutions/2255. Count Prefixes of a Given String/2255.py | {
"start": 0,
"end": 117
} | class ____:
def countPrefixes(self, words: list[str], s: str) -> int:
return sum(map(s.startswith, words))
| Solution |
python | pytorch__pytorch | torch/_functorch/pyfunctorch.py | {
"start": 7830,
"end": 10824
} | class ____(FuncTorchInterpreter):
def __init__(self, cdata: CInterpreter):
assert cdata.key() == TransformType.Functionalize
self._cdata = cdata
@cached_property
# pyrefly: ignore [bad-override]
def _cptr(self):
return CFunctionalizeInterpreterPtr(self._cdata)
def process(self, op, args, kwargs):
kernel = op.functorch_table[TransformType.Functionalize]
return kernel(self, *args, **kwargs)
def functionalize_add_back_views(self):
return self._cptr.functionalizeAddBackViews()
def get_state(self):
return (self.key().name, self.level())
def coerce_cinterpreter(cinterpreter: CInterpreter) -> FuncTorchInterpreter:
key = cinterpreter.key()
if key == TransformType.Grad:
return GradInterpreter(cinterpreter)
if key == TransformType.Vmap:
return VmapInterpreter(cinterpreter)
if key == TransformType.Jvp:
return JvpInterpreter(cinterpreter)
if key == TransformType.Functionalize:
return FunctionalizeInterpreter(cinterpreter)
raise RuntimeError(f"NYI: PyDispatcher has not implemented support for {key}")
def retrieve_current_functorch_interpreter() -> FuncTorchInterpreter:
interpreter = torch._C._functorch.peek_interpreter_stack()
assert interpreter is not None
return coerce_cinterpreter(interpreter)
def retrieve_all_functorch_interpreters() -> list[FuncTorchInterpreter]:
cis = torch._C._functorch.get_interpreter_stack()
if cis is None:
return []
return [coerce_cinterpreter(ci) for ci in cis]
def compare_functorch_state(states: list[tuple[Any, ...]]) -> bool:
# There are four possible cases covered here:
# 1. Current stack empty AND stack when generated not empty -> Invalidate
# 2. Current stack not empty AND stack when generated empty -> Invalidate
# 3. Current stack and generated stack empty -> Valid FX graph
# 4. Current stack and generated stack not empty -> Valid if both states match
peek = torch._C._functorch.peek_interpreter_stack()
if (peek is None and len(states) != 0) or (peek is not None and len(states) == 0):
return False
cis = retrieve_all_functorch_interpreters()
return len(cis) == len(states) and all(
ci.check_state(state) for ci, state in zip(cis, states)
)
def dispatch_functorch(op, args, kwargs):
interpreter = retrieve_current_functorch_interpreter()
# In traditional PyTorch operators, DispatchKey::FuncTorchTensorWrapper's
# unwrap_dead_tensors fallback handles unwrapping dead tensor wrappers.
# PyDispatcher sidesteps the PyTorch dispatcher when dealing with functorch
# transforms, so we manually unwrap the dead tensors here.
# This logic won't need to exist when we have mode-only functorch.
args, kwargs = pytree.tree_map_only(
torch.Tensor, torch._C._functorch.unwrap_if_dead, (args, kwargs)
)
return interpreter.process(op, args, kwargs)
| FunctionalizeInterpreter |
python | numba__numba | numba/tests/test_linalg.py | {
"start": 13576,
"end": 21365
} | class ____(EnableNRTStatsMixin, TestCase):
"""
Provides setUp and common data/error modes for testing np.linalg functions.
"""
# supported dtypes
dtypes = (np.float64, np.float32, np.complex128, np.complex64)
def setUp(self):
# Collect leftovers from previous test cases before checking for leaks
gc.collect()
super(TestLinalgBase, self).setUp()
def sample_vector(self, n, dtype):
# Be careful to generate only exactly representable float values,
# to avoid rounding discrepancies between Numpy and Numba
base = np.arange(n)
if issubclass(dtype, np.complexfloating):
return (base * (1 - 0.5j) + 2j).astype(dtype)
else:
return (base * 0.5 + 1).astype(dtype)
def specific_sample_matrix(
self, size, dtype, order, rank=None, condition=None):
"""
Provides a sample matrix with an optionally specified rank or condition
number.
size: (rows, columns), the dimensions of the returned matrix.
dtype: the dtype for the returned matrix.
order: the memory layout for the returned matrix, 'F' or 'C'.
rank: the rank of the matrix, an integer value, defaults to full rank.
condition: the condition number of the matrix (defaults to 1.)
NOTE: Only one of rank or condition may be set.
"""
# default condition
d_cond = 1.
if len(size) != 2:
raise ValueError("size must be a length 2 tuple.")
if order not in ['F', 'C']:
raise ValueError("order must be one of 'F' or 'C'.")
if dtype not in [np.float32, np.float64, np.complex64, np.complex128]:
raise ValueError("dtype must be a numpy floating point type.")
if rank is not None and condition is not None:
raise ValueError("Only one of rank or condition can be specified.")
if condition is None:
condition = d_cond
if condition < 1:
raise ValueError("Condition number must be >=1.")
np.random.seed(0) # repeatable seed
m, n = size
if m < 0 or n < 0:
raise ValueError("Negative dimensions given for matrix shape.")
minmn = min(m, n)
if rank is None:
rv = minmn
else:
if rank <= 0:
raise ValueError("Rank must be greater than zero.")
if not isinstance(rank, Integral):
raise ValueError("Rank must an integer.")
rv = rank
if rank > minmn:
raise ValueError("Rank given greater than full rank.")
if m == 1 or n == 1:
# vector, must be rank 1 (enforced above)
# condition of vector is also 1
if condition != d_cond:
raise ValueError(
"Condition number was specified for a vector (always 1.).")
maxmn = max(m, n)
Q = self.sample_vector(maxmn, dtype).reshape(m, n)
else:
# Build a sample matrix via combining SVD like inputs.
# Create matrices of left and right singular vectors.
# This could use Modified Gram-Schmidt and perhaps be quicker,
# at present it uses QR decompositions to obtain orthonormal
# matrices.
tmp = self.sample_vector(m * m, dtype).reshape(m, m)
U, _ = np.linalg.qr(tmp)
# flip the second array, else for m==n the identity matrix appears
tmp = self.sample_vector(n * n, dtype)[::-1].reshape(n, n)
V, _ = np.linalg.qr(tmp)
# create singular values.
sv = np.linspace(d_cond, condition, rv)
S = np.zeros((m, n))
idx = np.nonzero(np.eye(m, n))
S[idx[0][:rv], idx[1][:rv]] = sv
Q = np.dot(np.dot(U, S), V.T) # construct
Q = np.array(Q, dtype=dtype, order=order) # sort out order/type
return Q
def assert_error(self, cfunc, args, msg, err=ValueError):
with self.assertRaises(err) as raises:
cfunc(*args)
self.assertIn(msg, str(raises.exception))
def assert_non_square(self, cfunc, args):
msg = "Last 2 dimensions of the array must be square."
self.assert_error(cfunc, args, msg, np.linalg.LinAlgError)
def assert_wrong_dtype(self, name, cfunc, args):
msg = "np.linalg.%s() only supported on float and complex arrays" % name
self.assert_error(cfunc, args, msg, errors.TypingError)
def assert_wrong_dimensions(self, name, cfunc, args, la_prefix=True):
prefix = "np.linalg" if la_prefix else "np"
msg = "%s.%s() only supported on 2-D arrays" % (prefix, name)
self.assert_error(cfunc, args, msg, errors.TypingError)
def assert_no_nan_or_inf(self, cfunc, args):
msg = "Array must not contain infs or NaNs."
self.assert_error(cfunc, args, msg, np.linalg.LinAlgError)
def assert_contig_sanity(self, got, expected_contig):
"""
This checks that in a computed result from numba (array, possibly tuple
of arrays) all the arrays are contiguous in memory and that they are
all at least one of "C_CONTIGUOUS" or "F_CONTIGUOUS". The computed
result of the contiguousness is then compared against a hardcoded
expected result.
got: is the computed results from numba
expected_contig: is "C" or "F" and is the expected type of
contiguousness across all input values
(and therefore tests).
"""
if isinstance(got, tuple):
# tuple present, check all results
for a in got:
self.assert_contig_sanity(a, expected_contig)
else:
if not isinstance(got, Number):
# else a single array is present
c_contig = got.flags.c_contiguous
f_contig = got.flags.f_contiguous
# check that the result (possible set of) is at least one of
# C or F contiguous.
msg = "Results are not at least one of all C or F contiguous."
self.assertTrue(c_contig | f_contig, msg)
msg = "Computed contiguousness does not match expected."
if expected_contig == "C":
self.assertTrue(c_contig, msg)
elif expected_contig == "F":
self.assertTrue(f_contig, msg)
else:
raise ValueError("Unknown contig")
def assert_raise_on_singular(self, cfunc, args):
msg = "Matrix is singular to machine precision."
self.assert_error(cfunc, args, msg, err=np.linalg.LinAlgError)
def assert_is_identity_matrix(self, got, rtol=None, atol=None):
"""
Checks if a matrix is equal to the identity matrix.
"""
# check it is square
self.assertEqual(got.shape[-1], got.shape[-2])
# create identity matrix
eye = np.eye(got.shape[-1], dtype=got.dtype)
resolution = 5 * np.finfo(got.dtype).resolution
if rtol is None:
rtol = 10 * resolution
if atol is None:
atol = 100 * resolution # zeros tend to be fuzzy
# check it matches
np.testing.assert_allclose(got, eye, rtol, atol)
def assert_invalid_norm_kind(self, cfunc, args):
"""
For use in norm() and cond() tests.
"""
msg = "Invalid norm order for matrices."
self.assert_error(cfunc, args, msg, ValueError)
def assert_raise_on_empty(self, cfunc, args):
msg = 'Arrays cannot be empty'
self.assert_error(cfunc, args, msg, np.linalg.LinAlgError)
| TestLinalgBase |
python | kubernetes-client__python | kubernetes/base/dynamic/exceptions.py | {
"start": 3197,
"end": 3283
} | class ____(DynamicApiError):
""" 405: StatusMethodNotAllowed """
| MethodNotAllowedError |
python | tensorflow__tensorflow | tensorflow/python/distribute/ps_values.py | {
"start": 22511,
"end": 28187
} | class ____(lookup_ops.StaticHashTable):
"""A distributed StaticHashTable for ParameterServerStrategy.
An instance of DistributedTable has copies of a StaticHashTable and its
resource handle on the coordinator of each worker, created at the
DistributedTable instance initialization time with initializers on each
worker. Users can call methods on a DistributedTable as if it were a
StaticHashTable, which leads to execution with the resource local to the
consumer worker (or the coordinator, if calling from the coordinator). This
implementation relies on the fact that the methods of StaticHashTable are
queried with the resource handle (instead of the python object).
Currently, at saving time, a DistributedTable is saved as a StaticHashTable on
the coordinator, and restoring a DistributedTable from SavedModel is not
supported.
"""
def __init__(self, strategy, wrapped_creator):
distribute_lib.distribution_strategy_input_api_counter.get_cell(
self.__class__.__name__, "PSSDistributedLookupTable").increase_by(1)
self._coordinator_instance = wrapped_creator()
self._wrapped_creator = wrapped_creator
self._coordinator = strategy._cluster_coordinator
# self._distributed_table is a RemoteValue mapping worker_index to
# RemoteValue that wraps a resource handle on the worker
self._distributed_table = None
self._distributed_table_creation_lock = threading.Lock()
if not save_context.in_save_context():
self._maybe_build_distributed_table()
def __getattr__(self, attr):
# This allows copy.copy(DistributedTable), e.g. at saving time.
# (DistributedVariable uses the same fix.) When copying an object, copy.copy
# doesn't invoke its __init__ method, instead it makes a new empty object,
# then copies the attributes over. copy.copy looks for attributes like
# "__setstate__" in case the object implements its custom unpickling. Since
# DistributedTable doesn't have those attributes defined, __getattr__ will
# be invoked, which tries to access the `_coordinator_instance` attribute.
# But that doesn't exist either because this is an empty object, and again
# __getattr__ is invoked, leading to an infinite recursion.
if attr == "_coordinator_instance":
raise AttributeError()
if attr in self._coordinator_instance.__dict__:
attr_value = self._coordinator_instance.__dict__[attr]
if callable(attr_value):
def wrapper(*args, **kwargs):
return attr_value(self, *args, **kwargs)
return wrapper
elif isinstance(attr_value, property):
return attr_value
else:
return getattr(self._coordinator_instance, attr)
else:
return getattr(self._coordinator_instance, attr)
def resource_handle_call_time_value(self):
"""Returns a closure to run for a resource handle at call time and its spec.
This function is called in self.resource_handle to create a placeholder
which returns a resource handle on some worker or on the coordinator.
"""
def closure():
# function to be evaluated at function call time, returning a nest of
# tensors compatible with `spec`.
dispatch_context = coordinator_context.get_current_dispatch_context()
if dispatch_context:
remote_value = self._distributed_table._values[ # pylint: disable=protected-access
dispatch_context.worker_index]
ret = dispatch_context.maybe_get_remote_value(remote_value)
return ret
else:
return self._coordinator_instance.resource_handle
return closure, tensor.TensorSpec([], dtype=dtypes.resource)
def _maybe_build_distributed_table(self):
"""Create table objects and resources on each worker if hasn't been created."""
with self._distributed_table_creation_lock:
if not self._distributed_table:
def create_copy():
new_table = self._wrapped_creator()
ret = new_table.resource_handle
return ret
self._distributed_table = (
self._coordinator._create_per_worker_resources(create_copy)) # pylint: disable=protected-access
@property
def resource_handle(self):
if context.executing_eagerly() or save_context.in_save_context():
return self._coordinator_instance.resource_handle
else:
self._maybe_build_distributed_table()
closure, spec = self.resource_handle_call_time_value()
return ops.get_default_graph().capture_call_time_value(
closure,
spec,
default_value=self._coordinator_instance.resource_handle)
@property
def is_distributed_table(self):
return True
def __tf_experimental_restore_capture__(
self, concrete_function, internal_capture):
closure, spec = self.resource_handle_call_time_value()
concrete_function.graph.replace_capture_with_deferred_capture(
self._coordinator_instance.resource_handle,
closure,
spec,
default_value=self._coordinator_instance.resource_handle,
placeholder=internal_capture)
return concrete_function.graph.deferred_external_captures[-1]
_local_resource_restore_context = threading.local()
def get_current_local_resource_restore_context():
try:
return _local_resource_restore_context.current
except AttributeError:
return None
@contextlib.contextmanager
def with_local_resource_restore_context(instance):
previous_context = getattr(_local_resource_restore_context, "current", None)
_local_resource_restore_context.current = LocalResourceRestoreContext(
instance)
yield
_local_resource_restore_context.current = previous_context
| DistributedTable |
python | wandb__wandb | wandb/vendor/pygments/lexers/configs.py | {
"start": 3033,
"end": 4729
} | class ____(RegexLexer):
"""
Lexer for configuration files in Java's properties format.
Note: trailing whitespace counts as part of the value as per spec
.. versionadded:: 1.4
"""
name = 'Properties'
aliases = ['properties', 'jproperties']
filenames = ['*.properties']
mimetypes = ['text/x-java-properties']
tokens = {
'root': [
(r'^(\w+)([ \t])(\w+\s*)$', bygroups(Name.Attribute, Text, String)),
(r'^\w+(\\[ \t]\w*)*$', Name.Attribute),
(r'(^ *)([#!].*)', bygroups(Text, Comment)),
# More controversial comments
(r'(^ *)((?:;|//).*)', bygroups(Text, Comment)),
(r'(.*?)([ \t]*)([=:])([ \t]*)(.*(?:(?<=\\)\n.*)*)',
bygroups(Name.Attribute, Text, Operator, Text, String)),
(r'\s', Text),
],
}
def _rx_indent(level):
# Kconfig *always* interprets a tab as 8 spaces, so this is the default.
# Edit this if you are in an environment where KconfigLexer gets expanded
# input (tabs expanded to spaces) and the expansion tab width is != 8,
# e.g. in connection with Trac (trac.ini, [mimeviewer], tab_width).
# Value range here is 2 <= {tab_width} <= 8.
tab_width = 8
# Regex matching a given indentation {level}, assuming that indentation is
# a multiple of {tab_width}. In other cases there might be problems.
if tab_width == 2:
space_repeat = '+'
else:
space_repeat = '{1,%d}' % (tab_width - 1)
if level == 1:
level_repeat = ''
else:
level_repeat = '{%s}' % level
return r'(?:\t| %s\t| {%s})%s.*\n' % (space_repeat, tab_width, level_repeat)
| PropertiesLexer |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/call7.py | {
"start": 1401,
"end": 1606
} | class ____(TypedDict, total=False):
opt1: bool
opt2: str
def func6(code: str | None = None, **options: Unpack[Options]):
pass
func6(**{})
func6(**{"opt1": True})
func6(**{"opt2": "hi"})
| Options |
python | pyca__cryptography | tests/hazmat/primitives/test_rsa.py | {
"start": 5087,
"end": 13398
} | class ____:
@pytest.mark.parametrize(
("public_exponent", "key_size"),
itertools.product(
(3, 65537),
(1024, 1536, 2048),
),
)
def test_generate_rsa_keys(self, backend, public_exponent, key_size):
if backend._fips_enabled:
if key_size < backend._fips_rsa_min_key_size:
pytest.skip(f"Key size not FIPS compliant: {key_size}")
if public_exponent < backend._fips_rsa_min_public_exponent:
pytest.skip(f"Exponent not FIPS compliant: {public_exponent}")
skey = rsa.generate_private_key(public_exponent, key_size, backend)
assert skey.key_size == key_size
_check_rsa_private_numbers(skey.private_numbers())
pkey = skey.public_key()
assert isinstance(pkey.public_numbers(), rsa.RSAPublicNumbers)
def test_generate_bad_public_exponent(self, backend):
with pytest.raises(ValueError):
rsa.generate_private_key(
public_exponent=1, key_size=2048, backend=backend
)
with pytest.raises(ValueError):
rsa.generate_private_key(
public_exponent=4, key_size=2048, backend=backend
)
with pytest.raises(ValueError):
rsa.generate_private_key(
public_exponent=65535, key_size=2048, backend=backend
)
def test_cant_generate_insecure_tiny_key(self, backend):
with pytest.raises(ValueError):
rsa.generate_private_key(
public_exponent=65537, key_size=511, backend=backend
)
with pytest.raises(ValueError):
rsa.generate_private_key(
public_exponent=65537, key_size=256, backend=backend
)
@pytest.mark.parametrize(
"pkcs1_example",
load_vectors_from_file(
os.path.join(
"asymmetric", "RSA", "pkcs-1v2-1d2-vec", "pss-vect.txt"
),
load_pkcs1_vectors,
),
)
def test_load_pss_vect_example_keys(self, pkcs1_example):
secret, public = pkcs1_example
private_num = rsa.RSAPrivateNumbers(
p=secret["p"],
q=secret["q"],
d=secret["private_exponent"],
dmp1=secret["dmp1"],
dmq1=secret["dmq1"],
iqmp=secret["iqmp"],
public_numbers=rsa.RSAPublicNumbers(
e=secret["public_exponent"], n=secret["modulus"]
),
)
_check_rsa_private_numbers(private_num)
public_num = rsa.RSAPublicNumbers(
e=public["public_exponent"], n=public["modulus"]
)
assert public_num
public_num2 = private_num.public_numbers
assert public_num2
assert public_num.n == public_num2.n
assert public_num.e == public_num2.e
@pytest.mark.parametrize(
"path",
[
os.path.join("asymmetric", "PKCS8", "rsa_pss_2048.pem"),
os.path.join("asymmetric", "PKCS8", "rsa_pss_2048_hash.pem"),
os.path.join("asymmetric", "PKCS8", "rsa_pss_2048_hash_mask.pem"),
os.path.join(
"asymmetric", "PKCS8", "rsa_pss_2048_hash_mask_diff.pem"
),
os.path.join(
"asymmetric", "PKCS8", "rsa_pss_2048_hash_mask_salt.pem"
),
],
)
def test_load_pss_keys_strips_constraints(self, path, backend):
key = load_vectors_from_file(
filename=path,
loader=lambda p: serialization.load_pem_private_key(
p.read(), password=None, unsafe_skip_rsa_key_validation=True
),
mode="rb",
)
# These keys have constraints that prohibit PKCS1v15 signing,
# but for now we load them without the constraint and test that
# it's truly removed by performing a disallowed signature.
assert isinstance(key, rsa.RSAPrivateKey)
signature = key.sign(b"whatever", padding.PKCS1v15(), hashes.SHA224())
key.public_key().verify(
signature, b"whatever", padding.PKCS1v15(), hashes.SHA224()
)
def test_load_pss_pub_keys_strips_constraints(self, backend):
key = load_vectors_from_file(
filename=os.path.join(
"asymmetric", "PKCS8", "rsa_pss_2048_pub.der"
),
loader=lambda p: serialization.load_der_public_key(
p.read(),
),
mode="rb",
)
assert isinstance(key, rsa.RSAPublicKey)
with pytest.raises(InvalidSignature):
key.verify(
b"badsig", b"whatever", padding.PKCS1v15(), hashes.SHA256()
)
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
os.path.join("asymmetric", "RSA", "oaep-label.txt"),
load_nist_vectors,
),
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=b"label",
)
),
skip_message="Does not support RSA OAEP labels",
)
def test_oaep_label_decrypt(self, vector, backend):
private_key = serialization.load_der_private_key(
binascii.unhexlify(vector["key"]),
None,
backend,
unsafe_skip_rsa_key_validation=True,
)
assert isinstance(private_key, rsa.RSAPrivateKey)
assert vector["oaepdigest"] == b"SHA512"
decrypted = private_key.decrypt(
binascii.unhexlify(vector["input"]),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA512()),
algorithm=hashes.SHA512(),
label=binascii.unhexlify(vector["oaeplabel"]),
),
)
assert vector["output"][1:-1] == decrypted
@pytest.mark.parametrize(
("msg", "label"),
[
(b"amazing encrypted msg", b"some label"),
(b"amazing encrypted msg", b""),
],
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=b"label",
)
),
skip_message="Does not support RSA OAEP labels",
)
def test_oaep_label_roundtrip(self, rsa_key_2048, msg, label, backend):
private_key = rsa_key_2048
ct = private_key.public_key().encrypt(
msg,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=label,
),
)
pt = private_key.decrypt(
ct,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=label,
),
)
assert pt == msg
@pytest.mark.parametrize(
("enclabel", "declabel"),
[(b"label1", b"label2"), (b"label3", b""), (b"", b"label4")],
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=b"label",
)
),
skip_message="Does not support RSA OAEP labels",
)
def test_oaep_wrong_label(self, rsa_key_2048, enclabel, declabel, backend):
private_key = rsa_key_2048
msg = b"test"
ct = private_key.public_key().encrypt(
msg,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=enclabel,
),
)
with pytest.raises(ValueError):
private_key.decrypt(
ct,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=declabel,
),
)
| TestRSA |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/classes.py | {
"start": 508,
"end": 626
} | class ____(List[Union[int, float]]): # NoQA: UP006,UP007
"""A subclass of List[Union[int, float]]"""
pass
| Quux |
python | google__jax | tests/tree_util_test.py | {
"start": 56459,
"end": 59320
} | class ____(jtu.JaxTestCase):
def test_register_dataclass_with_field_specifier(self):
@tree_util.register_dataclass
@dataclasses.dataclass
class Foo:
x: int
y: int = dataclasses.field(metadata=dict(static=True))
f = Foo(2, 3)
self.assertLen(jax.tree.leaves(f), 1)
def test_register_dataclass_field_errors(self):
class Foo: # not a dataclass
x: int
y: int
msg = ("register_dataclass: data_fields and meta_fields are required"
" when nodetype is not a dataclass. Got nodetype=<class '.*Foo'>")
with self.assertRaisesRegex(TypeError, msg):
tree_util.register_dataclass(Foo)
msg = ("register_dataclass: data_fields and meta_fields must both be specified"\
r" when either is specified. Got data_fields=\['x'\] meta_fields=None.")
with self.assertRaisesRegex(TypeError, msg):
tree_util.register_dataclass(Foo, data_fields=['x'])
msg = ("register_dataclass: data_fields and meta_fields must both be specified"\
r" when either is specified. Got data_fields=None meta_fields=\['y'\].")
with self.assertRaisesRegex(TypeError, msg):
tree_util.register_dataclass(Foo, meta_fields=['y'])
def test_register_dataclass_missing_fields(self):
@dataclasses.dataclass
class Foo:
x: int
y: int
z: float = dataclasses.field(init=False)
with self.assertRaisesRegex(
ValueError,
"data_fields and meta_fields must include all dataclass fields.*"
"Missing fields: {'y'}",
):
tree_util.register_dataclass(Foo, data_fields=["x"], meta_fields=[])
# ``z`` is not required, because it's not included in ``__init__``.
tree_util.register_dataclass(Foo, data_fields=["x"], meta_fields=["y"])
def test_register_dataclass_unexpected_fields(self):
@dataclasses.dataclass
class Foo:
x: int
y: float
with self.assertRaisesRegex(
ValueError,
"data_fields and meta_fields must include all dataclass fields.*"
"Unexpected fields: {'z'}",
):
tree_util.register_dataclass(
Foo, data_fields=["x"], meta_fields=["y", "z"]
)
def test_register_dataclass_drop_fields(self):
@dataclasses.dataclass
class Foo:
x: int
y: int = dataclasses.field(default=42)
# ``y`` is explicitly excluded.
tree_util.register_dataclass(
Foo, data_fields=["x"], meta_fields=[], drop_fields=["y"]
)
def test_register_dataclass_invalid_plain_class(self):
class Foo:
x: int
y: int
def __init__(self, x, y):
self.x = x
self.y = y
# ``y`` is missing, but no validation is done for plain classes.
tree_util.register_dataclass(Foo, data_fields=["x"], meta_fields=[])
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
| RegistrationTest |
python | walkccc__LeetCode | solutions/2014. Longest Subsequence Repeated k Times/2014.py | {
"start": 0,
"end": 970
} | class ____:
def longestSubsequenceRepeatedK(self, s: str, k: int) -> str:
ans = ''
count = [0] * 26
possibleChars = []
# Stores subsequences, where the length grows by 1 each time.
q = collections.deque([''])
for c in s:
count[ord(c) - ord('a')] += 1
for c in string.ascii_lowercase:
if count[ord(c) - ord('a')] >= k:
possibleChars.append(c)
def isSubsequence(subseq: str, s: str, k: int) -> bool:
i = 0 # subseq's index
for c in s:
if c == subseq[i]:
i += 1
if i == len(subseq):
k -= 1
if k == 0:
return True
i = 0
return False
while q:
currSubseq = q.popleft()
if len(currSubseq) * k > len(s):
return ans
for c in possibleChars:
newSubseq = currSubseq + c
if isSubsequence(newSubseq, s, k):
q.append(newSubseq)
ans = newSubseq
return ans
| Solution |
python | pennersr__django-allauth | allauth/socialaccount/providers/eventbrite/provider.py | {
"start": 332,
"end": 709
} | class ____(ProviderAccount):
"""ProviderAccount subclass for Eventbrite."""
def get_avatar_url(self):
"""Return avatar url."""
return self.account.extra_data["image_id"]
def to_str(self):
emails = self.account.extra_data.get("emails")
if emails:
return emails[0]["email"]
return super().to_str()
| EventbriteAccount |
python | PyCQA__pylint | pylint/utils/file_state.py | {
"start": 694,
"end": 9628
} | class ____:
"""Hold internal state specific to the currently analyzed file."""
def __init__(
self,
modname: str,
msg_store: MessageDefinitionStore,
node: nodes.Module | None = None,
*,
is_base_filestate: bool = False,
) -> None:
self.base_name = modname
self._module_msgs_state: MessageStateDict = {}
self._raw_module_msgs_state: MessageStateDict = {}
self._ignored_msgs: defaultdict[tuple[str, int], set[int]] = (
collections.defaultdict(set)
)
self._suppression_mapping: dict[tuple[str, int], int] = {}
self._module = node
if node:
self._effective_max_line_number = node.tolineno
else:
self._effective_max_line_number = None
self._msgs_store = msg_store
self._is_base_filestate = is_base_filestate
"""If this FileState is the base state made during initialization of
PyLinter.
"""
def _set_state_on_block_lines(
self,
msgs_store: MessageDefinitionStore,
node: nodes.NodeNG,
msg: MessageDefinition,
msg_state: dict[int, bool],
) -> None:
"""Recursively walk (depth first) AST to collect block level options
line numbers and set the state correctly.
"""
for child in node.get_children():
self._set_state_on_block_lines(msgs_store, child, msg, msg_state)
# first child line number used to distinguish between disable
# which are the first child of scoped node with those defined later.
# For instance in the code below:
#
# 1. def meth8(self):
# 2. """test late disabling"""
# 3. pylint: disable=not-callable, useless-suppression
# 4. print(self.blip)
# 5. pylint: disable=no-member, useless-suppression
# 6. print(self.bla)
#
# E1102 should be disabled from line 1 to 6 while E1101 from line 5 to 6
#
# this is necessary to disable locally messages applying to class /
# function using their fromlineno
if (
isinstance(node, (nodes.Module, nodes.ClassDef, nodes.FunctionDef))
and node.body
):
firstchildlineno = node.body[0].fromlineno
else:
firstchildlineno = node.tolineno
self._set_message_state_in_block(msg, msg_state, node, firstchildlineno)
def _set_message_state_in_block(
self,
msg: MessageDefinition,
lines: dict[int, bool],
node: nodes.NodeNG,
firstchildlineno: int,
) -> None:
"""Set the state of a message in a block of lines."""
first = node.fromlineno
last = node.tolineno
for lineno, state in list(lines.items()):
original_lineno = lineno
if first > lineno or last < lineno:
continue
# Set state for all lines for this block, if the
# warning is applied to nodes.
if msg.scope == WarningScope.NODE:
if lineno > firstchildlineno:
state = True
first_, last_ = node.block_range(lineno)
# pylint: disable=useless-suppression
# For block nodes first_ is their definition line. For example, we
# set the state of line zero for a module to allow disabling
# invalid-name for the module. For example:
# 1. # pylint: disable=invalid-name
# 2. ...
# OR
# 1. """Module docstring"""
# 2. # pylint: disable=invalid-name
# 3. ...
#
# But if we already visited line 0 we don't need to set its state again
# 1. # pylint: disable=invalid-name
# 2. # pylint: enable=invalid-name
# 3. ...
# The state should come from line 1, not from line 2
# Therefore, if the 'fromlineno' is already in the states we just start
# with the lineno we were originally visiting.
# pylint: enable=useless-suppression
if (
first_ == node.fromlineno
and first_ >= firstchildlineno
and node.fromlineno in self._module_msgs_state.get(msg.msgid, ())
):
first_ = lineno
else:
first_ = lineno
last_ = last
for line in range(first_, last_ + 1):
# Do not override existing entries. This is especially important
# when parsing the states for a scoped node where some line-disables
# have already been parsed.
if (
(
isinstance(node, nodes.Module)
and node.fromlineno <= line < lineno
)
or (
not isinstance(node, nodes.Module)
and node.fromlineno < line < lineno
)
) and line in self._module_msgs_state.get(msg.msgid, ()):
continue
if line in lines: # state change in the same block
state = lines[line]
original_lineno = line
self._set_message_state_on_line(msg, line, state, original_lineno)
del lines[lineno]
def _set_message_state_on_line(
self,
msg: MessageDefinition,
line: int,
state: bool,
original_lineno: int,
) -> None:
"""Set the state of a message on a line."""
# Update suppression mapping
if not state:
self._suppression_mapping[(msg.msgid, line)] = original_lineno
else:
self._suppression_mapping.pop((msg.msgid, line), None)
# Update message state for respective line
try:
self._module_msgs_state[msg.msgid][line] = state
except KeyError:
self._module_msgs_state[msg.msgid] = {line: state}
def set_msg_status(
self,
msg: MessageDefinition,
line: int,
status: bool,
scope: str = "package",
) -> None:
"""Set status (enabled/disable) for a given message at a given line."""
assert line > 0
if scope != "line":
# Expand the status to cover all relevant block lines
self._set_state_on_block_lines(
self._msgs_store, self._module, msg, {line: status}
)
else:
self._set_message_state_on_line(msg, line, status, line)
# Store the raw value
try:
self._raw_module_msgs_state[msg.msgid][line] = status
except KeyError:
self._raw_module_msgs_state[msg.msgid] = {line: status}
def handle_ignored_message(
self, state_scope: Literal[0, 1, 2] | None, msgid: str, line: int | None
) -> None:
"""Report an ignored message.
state_scope is either MSG_STATE_SCOPE_MODULE or MSG_STATE_SCOPE_CONFIG,
depending on whether the message was disabled locally in the module,
or globally.
"""
if state_scope == MSG_STATE_SCOPE_MODULE:
assert isinstance(line, int) # should always be int inside module scope
try:
orig_line = self._suppression_mapping[(msgid, line)]
self._ignored_msgs[(msgid, orig_line)].add(line)
except KeyError:
pass
def iter_spurious_suppression_messages(
self,
msgs_store: MessageDefinitionStore,
) -> Iterator[
tuple[
Literal["useless-suppression", "suppressed-message"],
int,
tuple[str] | tuple[str, int],
]
]:
for warning, lines in self._raw_module_msgs_state.items():
for line, enable in lines.items():
if (
not enable
and (warning, line) not in self._ignored_msgs
and warning not in INCOMPATIBLE_WITH_USELESS_SUPPRESSION
):
yield "useless-suppression", line, (
msgs_store.get_msg_display_string(warning),
)
# don't use iteritems here, _ignored_msgs may be modified by add_message
for (warning, from_), ignored_lines in list(self._ignored_msgs.items()):
for line in ignored_lines:
yield "suppressed-message", line, (
msgs_store.get_msg_display_string(warning),
from_,
)
def get_effective_max_line_number(self) -> int | None:
return self._effective_max_line_number # type: ignore[no-any-return]
| FileState |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/ndb/property_subclasses/my_models.py | {
"start": 2445,
"end": 2869
} | class ____(ndb.StructuredProperty):
def __init__(self, **kwds):
super(FuzzyDateProperty, self).__init__(FuzzyDateModel, **kwds)
def _validate(self, value):
assert isinstance(value, FuzzyDate)
def _to_base_type(self, value):
return FuzzyDateModel(first=value.first, last=value.last)
def _from_base_type(self, value):
return FuzzyDate(value.first, value.last)
| FuzzyDateProperty |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/quantization_ops/quantization_ops_test.py | {
"start": 6032,
"end": 7900
} | class ____(test_util.TensorFlowTestCase):
@test_util.run_in_graph_and_eager_modes
def test_invalid_inputs(self):
inputs = constant_op.constant(
np.int8(0), shape=[3, 3, 3, 3], dtype=dtypes.qint8)
bias = constant_op.constant(np.int8(0), shape=[3], dtype=dtypes.qint8)
with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
"must be rank 0"):
self.evaluate(
nn_ops.quantized_bias_add(
input=inputs,
bias=bias,
min_input=[],
max_input=1.0,
min_bias=0.0,
max_bias=1.0,
out_type=dtypes.qint32))
with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
"must be rank 0"):
self.evaluate(
nn_ops.quantized_bias_add(
input=inputs,
bias=bias,
min_input=0.0,
max_input=[],
min_bias=0.0,
max_bias=1.0,
out_type=dtypes.qint32))
with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
"must be rank 0"):
self.evaluate(
nn_ops.quantized_bias_add(
input=inputs,
bias=bias,
min_input=0.0,
max_input=1.0,
min_bias=[],
max_bias=1.0,
out_type=dtypes.qint32))
with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
"must be rank 0"):
self.evaluate(
nn_ops.quantized_bias_add(
input=inputs,
bias=bias,
min_input=0.0,
max_input=1.0,
min_bias=0.0,
max_bias=[],
out_type=dtypes.qint32))
| QuantizedBiasedAddTest |
python | run-llama__llama_index | llama-index-integrations/voice_agents/llama-index-voice-agents-elevenlabs/llama_index/voice_agents/elevenlabs/events.py | {
"start": 769,
"end": 862
} | class ____(BaseVoiceAgentEvent):
model_config = ConfigDict(extra="allow")
| InterruptionEvent |
python | apache__airflow | task-sdk/tests/task_sdk/execution_time/test_supervisor.py | {
"start": 39511,
"end": 50305
} | class ____:
@pytest.fixture
def mock_process(self, mocker):
process = mocker.Mock(spec=psutil.Process)
process.pid = 12345
return process
@pytest.fixture
def watched_subprocess(self, mocker, mock_process):
proc = ActivitySubprocess(
process_log=mocker.MagicMock(),
id=TI_ID,
pid=12345,
stdin=mocker.Mock(),
client=mocker.Mock(),
process=mock_process,
)
# Mock the selector
mock_selector = mocker.Mock(spec=selectors.DefaultSelector)
mock_selector.select.return_value = []
# Set the selector on the process
proc.selector = mock_selector
return proc
def test_kill_process_already_exited(self, watched_subprocess, mock_process):
"""Test behavior when the process has already exited."""
mock_process.wait.side_effect = psutil.NoSuchProcess(pid=1234)
watched_subprocess.kill(signal.SIGINT, force=True)
mock_process.send_signal.assert_called_once_with(signal.SIGINT)
mock_process.wait.assert_called_once()
assert watched_subprocess._exit_code == -1
def test_kill_process_custom_signal(self, watched_subprocess, mock_process):
"""Test that the process is killed with the correct signal."""
mock_process.wait.return_value = 0
signal_to_send = signal.SIGUSR1
watched_subprocess.kill(signal_to_send, force=False)
mock_process.send_signal.assert_called_once_with(signal_to_send)
mock_process.wait.assert_called_once_with(timeout=0)
@pytest.mark.parametrize(
("signal_to_send", "exit_after"),
[
pytest.param(
signal.SIGINT,
signal.SIGINT,
id="SIGINT-success-without-escalation",
),
pytest.param(
signal.SIGINT,
signal.SIGTERM,
id="SIGINT-escalates-to-SIGTERM",
),
pytest.param(
signal.SIGINT,
None,
id="SIGINT-escalates-to-SIGTERM-then-SIGKILL",
),
pytest.param(
signal.SIGTERM,
None,
id="SIGTERM-escalates-to-SIGKILL",
),
pytest.param(
signal.SIGKILL,
None,
id="SIGKILL-success-without-escalation",
),
],
)
def test_kill_escalation_path(self, signal_to_send, exit_after, captured_logs, client_with_ti_start):
def subprocess_main():
import signal
def _handler(sig, frame):
print(f"Signal {sig} received", file=sys.stderr)
if exit_after == sig:
sleep(0.1)
# We exit 0 as that's what task_runner.py tries hard to do. The only difference if we exit
# with non-zero is extra logs
exit(0)
sleep(5)
print("Should not get here")
signal.signal(signal.SIGINT, _handler)
signal.signal(signal.SIGTERM, _handler)
try:
CommsDecoder()._get_response()
print("Ready")
sleep(10)
except Exception as e:
print(e)
# Shouldn't get here
exit(5)
ti_id = uuid7()
proc = ActivitySubprocess.start(
dag_rel_path=os.devnull,
bundle_info=FAKE_BUNDLE,
what=TaskInstance(
id=ti_id, task_id="b", dag_id="c", run_id="d", try_number=1, dag_version_id=uuid7()
),
client=client_with_ti_start,
target=subprocess_main,
)
# Ensure we get one normal run, to give the proc time to register it's custom sighandler
time.sleep(0.1)
proc._service_subprocess(max_wait_time=1)
proc.kill(signal_to_send=signal_to_send, escalation_delay=0.5, force=True)
# Wait for the subprocess to finish
assert proc.wait() == exit_after or -signal.SIGKILL
exit_after = exit_after or signal.SIGKILL
logs = [{"event": m["event"], "logger": m["logger"]} for m in captured_logs]
expected_logs = [
{"logger": "task.stdout", "event": "Ready"},
]
# Work out what logs we expect to see
if signal_to_send == signal.SIGINT:
expected_logs.append({"logger": "task.stderr", "event": "Signal 2 received"})
if signal_to_send == signal.SIGTERM or (
signal_to_send == signal.SIGINT and exit_after != signal.SIGINT
):
if signal_to_send == signal.SIGINT:
expected_logs.append(
{
"event": "Process did not terminate in time; escalating",
"logger": "supervisor",
}
)
expected_logs.append({"logger": "task.stderr", "event": "Signal 15 received"})
if exit_after == signal.SIGKILL:
if signal_to_send in {signal.SIGINT, signal.SIGTERM}:
expected_logs.append(
{
"event": "Process did not terminate in time; escalating",
"logger": "supervisor",
}
)
expected_logs.extend(({"event": "Process exited", "logger": "supervisor"},))
assert logs == expected_logs
def test_service_subprocess(self, watched_subprocess, mock_process, mocker):
"""Test `_service_subprocess` processes selector events and handles subprocess exit."""
# Given
# Mock file objects and handlers
mock_stdout = mocker.Mock()
mock_stderr = mocker.Mock()
# Handlers for stdout and stderr
mock_stdout_handler = mocker.Mock(return_value=False) # Simulate EOF for stdout
mock_stderr_handler = mocker.Mock(return_value=True) # Continue processing for stderr
mock_on_close = mocker.Mock()
# Mock selector to return events
mock_key_stdout = mocker.Mock(fileobj=mock_stdout, data=(mock_stdout_handler, mock_on_close))
mock_key_stderr = mocker.Mock(fileobj=mock_stderr, data=(mock_stderr_handler, mock_on_close))
watched_subprocess.selector.select.return_value = [(mock_key_stdout, None), (mock_key_stderr, None)]
# Mock to simulate process exited successfully
mock_process.wait.return_value = 0
# Our actual test
watched_subprocess._service_subprocess(max_wait_time=1.0)
# Validations!
# Validate selector interactions
watched_subprocess.selector.select.assert_called_once_with(timeout=1.0)
# Validate handler calls
mock_stdout_handler.assert_called_once_with(mock_stdout)
mock_stderr_handler.assert_called_once_with(mock_stderr)
# Validate unregistering and closing of EOF file object
mock_on_close.assert_called_once_with(mock_stdout)
# Validate that `_check_subprocess_exit` is called
mock_process.wait.assert_called_once_with(timeout=0)
def test_max_wait_time_prevents_cpu_spike(self, watched_subprocess, mock_process, monkeypatch):
"""Test that max_wait_time calculation prevents CPU spike when heartbeat timeout is reached."""
# Mock the configuration to reproduce the CPU spike scenario
# Set heartbeat timeout to be very small relative to MIN_HEARTBEAT_INTERVAL
monkeypatch.setattr("airflow.sdk.execution_time.supervisor.HEARTBEAT_TIMEOUT", 1)
monkeypatch.setattr("airflow.sdk.execution_time.supervisor.MIN_HEARTBEAT_INTERVAL", 10)
# Set up a scenario where the last successful heartbeat was a long time ago
# This will cause the heartbeat calculation to result in a negative value
mock_process._last_successful_heartbeat = time.monotonic() - 100 # 100 seconds ago
# Mock process to still be alive (not exited)
mock_process.wait.side_effect = psutil.TimeoutExpired(pid=12345, seconds=0)
# Call _service_subprocess which is used in _monitor_subprocess
# This tests the max_wait_time calculation directly
watched_subprocess._service_subprocess(max_wait_time=0.005) # Very small timeout to verify our fix
# Verify that selector.select was called with a minimum timeout of 0.01
# This proves our fix prevents the timeout=0 scenario that causes CPU spike
watched_subprocess.selector.select.assert_called_once()
call_args = watched_subprocess.selector.select.call_args
timeout_arg = call_args[1]["timeout"] if "timeout" in call_args[1] else call_args[0][0]
# The timeout should be at least 0.01 (our minimum), never 0
assert timeout_arg >= 0.01, f"Expected timeout >= 0.01, got {timeout_arg}"
@pytest.mark.parametrize(
("heartbeat_timeout", "min_interval", "heartbeat_ago", "expected_min_timeout"),
[
# Normal case: heartbeat is recent, should use calculated value
pytest.param(30, 5, 5, 0.01, id="normal_heartbeat"),
# Edge case: heartbeat timeout exceeded, should use minimum
pytest.param(10, 20, 50, 0.01, id="heartbeat_timeout_exceeded"),
# Bug reproduction case: timeout < interval, heartbeat very old
pytest.param(5, 10, 100, 0.01, id="cpu_spike_scenario"),
],
)
def test_max_wait_time_calculation_edge_cases(
self,
watched_subprocess,
mock_process,
monkeypatch,
heartbeat_timeout,
min_interval,
heartbeat_ago,
expected_min_timeout,
):
"""Test max_wait_time calculation in various edge case scenarios."""
monkeypatch.setattr("airflow.sdk.execution_time.supervisor.HEARTBEAT_TIMEOUT", heartbeat_timeout)
monkeypatch.setattr("airflow.sdk.execution_time.supervisor.MIN_HEARTBEAT_INTERVAL", min_interval)
watched_subprocess._last_successful_heartbeat = time.monotonic() - heartbeat_ago
mock_process.wait.side_effect = psutil.TimeoutExpired(pid=12345, seconds=0)
# Call the method and verify timeout is never less than our minimum
watched_subprocess._service_subprocess(
max_wait_time=999
) # Large value, should be overridden by calculation
# Extract the timeout that was actually used
watched_subprocess.selector.select.assert_called_once()
call_args = watched_subprocess.selector.select.call_args
actual_timeout = call_args[1]["timeout"] if "timeout" in call_args[1] else call_args[0][0]
assert actual_timeout >= expected_min_timeout
@dataclass
| TestWatchedSubprocessKill |
python | mlflow__mlflow | tests/langchain/sample_code/langchain_chat_agent.py | {
"start": 630,
"end": 1950
} | class ____(ChatOpenAI, extra="allow"):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._responses = iter([AIMessage(content="1")])
self._stream_responses = iter(
[
AIMessageChunk(content="1"),
AIMessageChunk(content="2"),
AIMessageChunk(content="3"),
]
)
def _generate(self, *args, **kwargs):
return ChatResult(generations=[ChatGeneration(message=next(self._responses))])
def _stream(self, *args, **kwargs):
for r in self._stream_responses:
yield ChatGenerationChunk(message=r)
mlflow.langchain.autolog()
# Helper functions
def extract_user_query_string(messages):
return messages[-1]["content"]
def extract_chat_history(messages):
return messages[:-1]
# Define components
prompt = ChatPromptTemplate.from_template(
"""Previous conversation:
{chat_history}
User's question:
{question}"""
)
model = FakeOpenAI()
output_parser = ChatAgentOutputParser()
# Chain definition
chain = (
{
"question": itemgetter("messages") | RunnableLambda(extract_user_query_string),
"chat_history": itemgetter("messages") | RunnableLambda(extract_chat_history),
}
| prompt
| model
| output_parser
)
| FakeOpenAI |
python | google__pytype | pytype/tools/analyze_project/pytype_runner.py | {
"start": 547,
"end": 639
} | class ____:
CHECK = 'check'
INFER = 'infer'
GENERATE_DEFAULT = 'generate default'
| Action |
python | pypa__virtualenv | src/virtualenv/create/via_global_ref/api.py | {
"start": 254,
"end": 685
} | class ____(CreatorMeta):
def __init__(self) -> None:
super().__init__()
self.copy_error = None
self.symlink_error = None
if not fs_supports_symlink():
self.symlink_error = "the filesystem does not supports symlink"
@property
def can_copy(self):
return not self.copy_error
@property
def can_symlink(self):
return not self.symlink_error
| ViaGlobalRefMeta |
python | python__mypy | mypy/test/testinfer.py | {
"start": 5591,
"end": 7526
} | class ____(Suite):
"""Test cases for checker.DisjointDict, which is used for type inference with operands."""
def new(self) -> DisjointDict[int, str]:
return DisjointDict()
def test_independent_maps(self) -> None:
d = self.new()
d.add_mapping({0, 1}, {"group1"})
d.add_mapping({2, 3, 4}, {"group2"})
d.add_mapping({5, 6, 7}, {"group3"})
self.assertEqual(
d.items(), [({0, 1}, {"group1"}), ({2, 3, 4}, {"group2"}), ({5, 6, 7}, {"group3"})]
)
def test_partial_merging(self) -> None:
d = self.new()
d.add_mapping({0, 1}, {"group1"})
d.add_mapping({1, 2}, {"group2"})
d.add_mapping({3, 4}, {"group3"})
d.add_mapping({5, 0}, {"group4"})
d.add_mapping({5, 6}, {"group5"})
d.add_mapping({4, 7}, {"group6"})
self.assertEqual(
d.items(),
[
({0, 1, 2, 5, 6}, {"group1", "group2", "group4", "group5"}),
({3, 4, 7}, {"group3", "group6"}),
],
)
def test_full_merging(self) -> None:
d = self.new()
d.add_mapping({0, 1, 2}, {"a"})
d.add_mapping({3, 4, 2}, {"b"})
d.add_mapping({10, 11, 12}, {"c"})
d.add_mapping({13, 14, 15}, {"d"})
d.add_mapping({14, 10, 16}, {"e"})
d.add_mapping({0, 10}, {"f"})
self.assertEqual(
d.items(),
[({0, 1, 2, 3, 4, 10, 11, 12, 13, 14, 15, 16}, {"a", "b", "c", "d", "e", "f"})],
)
def test_merge_with_multiple_overlaps(self) -> None:
d = self.new()
d.add_mapping({0, 1, 2}, {"a"})
d.add_mapping({3, 4, 5}, {"b"})
d.add_mapping({1, 2, 4, 5}, {"c"})
d.add_mapping({6, 1, 2, 4, 5}, {"d"})
d.add_mapping({6, 1, 2, 4, 5}, {"e"})
self.assertEqual(d.items(), [({0, 1, 2, 3, 4, 5, 6}, {"a", "b", "c", "d", "e"})])
| OperandDisjointDictSuite |
python | python__mypy | mypy/report.py | {
"start": 6695,
"end": 11201
} | class ____(AbstractReporter):
"""Report frequencies of different kinds of Any types."""
def __init__(self, reports: Reports, output_dir: str) -> None:
super().__init__(reports, output_dir)
self.counts: dict[str, tuple[int, int]] = {}
self.any_types_counter: dict[str, collections.Counter[int]] = {}
def on_file(
self,
tree: MypyFile,
modules: dict[str, MypyFile],
type_map: dict[Expression, Type],
options: Options,
) -> None:
visitor = stats.StatisticsVisitor(
inferred=True,
filename=tree.fullname,
modules=modules,
typemap=type_map,
all_nodes=True,
visit_untyped_defs=False,
)
tree.accept(visitor)
self.any_types_counter[tree.fullname] = visitor.type_of_any_counter
num_unanalyzed_lines = list(visitor.line_map.values()).count(stats.TYPE_UNANALYZED)
# count each line of dead code as one expression of type "Any"
num_any = visitor.num_any_exprs + num_unanalyzed_lines
num_total = visitor.num_imprecise_exprs + visitor.num_precise_exprs + num_any
if num_total > 0:
self.counts[tree.fullname] = (num_any, num_total)
def on_finish(self) -> None:
self._report_any_exprs()
self._report_types_of_anys()
def _write_out_report(
self, filename: str, header: list[str], rows: list[list[str]], footer: list[str]
) -> None:
row_len = len(header)
assert all(len(row) == row_len for row in rows + [header, footer])
min_column_distance = 3 # minimum distance between numbers in two columns
widths = [-1] * row_len
for row in rows + [header, footer]:
for i, value in enumerate(row):
widths[i] = max(widths[i], len(value))
for i, w in enumerate(widths):
# Do not add min_column_distance to the first column.
if i > 0:
widths[i] = w + min_column_distance
with open(os.path.join(self.output_dir, filename), "w") as f:
header_str = ("{:>{}}" * len(widths)).format(*itertools.chain(*zip(header, widths)))
separator = "-" * len(header_str)
f.write(header_str + "\n")
f.write(separator + "\n")
for row_values in rows:
r = ("{:>{}}" * len(widths)).format(*itertools.chain(*zip(row_values, widths)))
f.write(r + "\n")
f.write(separator + "\n")
footer_str = ("{:>{}}" * len(widths)).format(*itertools.chain(*zip(footer, widths)))
f.write(footer_str + "\n")
def _report_any_exprs(self) -> None:
total_any = sum(num_any for num_any, _ in self.counts.values())
total_expr = sum(total for _, total in self.counts.values())
total_coverage = 100.0
if total_expr > 0:
total_coverage = (float(total_expr - total_any) / float(total_expr)) * 100
column_names = ["Name", "Anys", "Exprs", "Coverage"]
rows: list[list[str]] = []
for filename in sorted(self.counts):
(num_any, num_total) = self.counts[filename]
coverage = (float(num_total - num_any) / float(num_total)) * 100
coverage_str = f"{coverage:.2f}%"
rows.append([filename, str(num_any), str(num_total), coverage_str])
rows.sort(key=lambda x: x[0])
total_row = ["Total", str(total_any), str(total_expr), f"{total_coverage:.2f}%"]
self._write_out_report("any-exprs.txt", column_names, rows, total_row)
def _report_types_of_anys(self) -> None:
total_counter: collections.Counter[int] = collections.Counter()
for counter in self.any_types_counter.values():
for any_type, value in counter.items():
total_counter[any_type] += value
file_column_name = "Name"
total_row_name = "Total"
column_names = [file_column_name] + list(type_of_any_name_map.values())
rows: list[list[str]] = []
for filename, counter in self.any_types_counter.items():
rows.append([filename] + [str(counter[typ]) for typ in type_of_any_name_map])
rows.sort(key=lambda x: x[0])
total_row = [total_row_name] + [str(total_counter[typ]) for typ in type_of_any_name_map]
self._write_out_report("types-of-anys.txt", column_names, rows, total_row)
register_reporter("any-exprs", AnyExpressionsReporter)
| AnyExpressionsReporter |
python | doocs__leetcode | solution/1000-1099/1000.Minimum Cost to Merge Stones/Solution.py | {
"start": 0,
"end": 698
} | class ____:
def mergeStones(self, stones: List[int], K: int) -> int:
n = len(stones)
if (n - 1) % (K - 1):
return -1
s = list(accumulate(stones, initial=0))
f = [[[inf] * (K + 1) for _ in range(n + 1)] for _ in range(n + 1)]
for i in range(1, n + 1):
f[i][i][1] = 0
for l in range(2, n + 1):
for i in range(1, n - l + 2):
j = i + l - 1
for k in range(1, K + 1):
for h in range(i, j):
f[i][j][k] = min(f[i][j][k], f[i][h][1] + f[h + 1][j][k - 1])
f[i][j][1] = f[i][j][K] + s[j] - s[i - 1]
return f[1][n][1]
| Solution |
python | eventlet__eventlet | eventlet/support/greendns.py | {
"start": 6070,
"end": 11371
} | class ____:
"""Class to parse the hosts file
Attributes
----------
:fname: The filename of the hosts file in use.
:interval: The time between checking for hosts file modification
"""
LINES_RE = re.compile(r"""
\s* # Leading space
([^\r\n#]*?) # The actual match, non-greedy so as not to include trailing space
\s* # Trailing space
(?:[#][^\r\n]+)? # Comments
(?:$|[\r\n]+) # EOF or newline
""", re.VERBOSE)
def __init__(self, fname=None, interval=HOSTS_TTL):
self._v4 = {} # name -> ipv4
self._v6 = {} # name -> ipv6
self._aliases = {} # name -> canonical_name
self.interval = interval
self.fname = fname
if fname is None:
if os.name == 'posix':
self.fname = '/etc/hosts'
elif os.name == 'nt':
self.fname = os.path.expandvars(
r'%SystemRoot%\system32\drivers\etc\hosts')
self._last_load = 0
if self.fname:
self._load()
def _readlines(self):
"""Read the contents of the hosts file
Return list of lines, comment lines and empty lines are
excluded.
Note that this performs disk I/O so can be blocking.
"""
try:
with open(self.fname, 'rb') as fp:
fdata = fp.read()
except OSError:
return []
udata = fdata.decode(errors='ignore')
return filter(None, self.LINES_RE.findall(udata))
def _load(self):
"""Load hosts file
This will unconditionally (re)load the data from the hosts
file.
"""
lines = self._readlines()
self._v4.clear()
self._v6.clear()
self._aliases.clear()
for line in lines:
parts = line.split()
if len(parts) < 2:
continue
ip = parts.pop(0)
if is_ipv4_addr(ip):
ipmap = self._v4
elif is_ipv6_addr(ip):
if ip.startswith('fe80'):
# Do not use link-local addresses, OSX stores these here
continue
ipmap = self._v6
else:
continue
cname = parts.pop(0).lower()
ipmap[cname] = ip
for alias in parts:
alias = alias.lower()
ipmap[alias] = ip
self._aliases[alias] = cname
self._last_load = time.time()
def query(self, qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN,
tcp=False, source=None, raise_on_no_answer=True):
"""Query the hosts file
The known rdtypes are dns.rdatatype.A, dns.rdatatype.AAAA and
dns.rdatatype.CNAME.
The ``rdclass`` parameter must be dns.rdataclass.IN while the
``tcp`` and ``source`` parameters are ignored.
Return a HostAnswer instance or raise a dns.resolver.NoAnswer
exception.
"""
now = time.time()
if self._last_load + self.interval < now:
self._load()
rdclass = dns.rdataclass.IN
if isinstance(qname, str):
name = qname
qname = dns.name.from_text(qname)
elif isinstance(qname, bytes):
name = qname.decode("ascii")
qname = dns.name.from_text(qname)
else:
name = str(qname)
name = name.lower()
rrset = dns.rrset.RRset(qname, rdclass, rdtype)
rrset.ttl = self._last_load + self.interval - now
if rdclass == dns.rdataclass.IN and rdtype == dns.rdatatype.A:
addr = self._v4.get(name)
if not addr and qname.is_absolute():
addr = self._v4.get(name[:-1])
if addr:
rrset.add(dns.rdtypes.IN.A.A(rdclass, rdtype, addr))
elif rdclass == dns.rdataclass.IN and rdtype == dns.rdatatype.AAAA:
addr = self._v6.get(name)
if not addr and qname.is_absolute():
addr = self._v6.get(name[:-1])
if addr:
rrset.add(dns.rdtypes.IN.AAAA.AAAA(rdclass, rdtype, addr))
elif rdclass == dns.rdataclass.IN and rdtype == dns.rdatatype.CNAME:
cname = self._aliases.get(name)
if not cname and qname.is_absolute():
cname = self._aliases.get(name[:-1])
if cname:
rrset.add(dns.rdtypes.ANY.CNAME.CNAME(
rdclass, rdtype, dns.name.from_text(cname)))
return HostsAnswer(qname, rdtype, rdclass, rrset, raise_on_no_answer)
def getaliases(self, hostname):
"""Return a list of all the aliases of a given cname"""
# Due to the way store aliases this is a bit inefficient, this
# clearly was an afterthought. But this is only used by
# gethostbyname_ex so it's probably fine.
aliases = []
if hostname in self._aliases:
cannon = self._aliases[hostname]
else:
cannon = hostname
aliases.append(cannon)
for alias, cname in self._aliases.items():
if cannon == cname:
aliases.append(alias)
aliases.remove(hostname)
return aliases
| HostsResolver |
python | getsentry__sentry | src/sentry/statistical_detectors/algorithm.py | {
"start": 2771,
"end": 3009
} | class ____(ABC):
@abstractmethod
def update(
self,
raw: Mapping[str | bytes, bytes | float | int | str],
payload: DetectorPayload,
) -> tuple[TrendType, float, DetectorState | None]: ...
| DetectorAlgorithm |
python | numba__llvmlite | llvmlite/binding/value.py | {
"start": 13537,
"end": 13770
} | class ____(_ValueIterator):
kind = 'instruction'
def _dispose(self):
self._capi.LLVMPY_DisposeInstructionsIter(self)
def _next(self):
return ffi.lib.LLVMPY_InstructionsIterNext(self)
| _InstructionsIterator |
python | pytorch__pytorch | torch/utils/_pytree.py | {
"start": 64933,
"end": 65350
} | class ____:
"""
_TreeSpecSchema is the schema used to serialize the TreeSpec
It contains the following fields:
- type: A string name of the type. null for the case of a LeafSpec.
- context: Any format which is json dumpable
- children_spec: A list of children serialized specs.
"""
type: str | None
context: DumpableContext
children_spec: list["_TreeSpecSchema"]
| _TreeSpecSchema |
python | scipy__scipy | scipy/stats/tests/test_mstats_basic.py | {
"start": 35019,
"end": 35725
} | class ____:
def setup_method(self):
self.a1 = [3, 4, 5, 10, -3, -5, 6]
self.a2 = [3, -6, -2, 8, 7, 4, 2, 1]
self.a3 = [3., 4, 5, 10, -3, -5, -6, 7.0]
def test_percentile(self):
x = np.arange(8) * 0.5
assert_equal(mstats.scoreatpercentile(x, 0), 0.)
assert_equal(mstats.scoreatpercentile(x, 100), 3.5)
assert_equal(mstats.scoreatpercentile(x, 50), 1.75)
def test_2D(self):
x = ma.array([[1, 1, 1],
[1, 1, 1],
[4, 4, 3],
[1, 1, 1],
[1, 1, 1]])
assert_equal(mstats.scoreatpercentile(x, 50), [1, 1, 1])
@skip_xp_invalid_arg
| TestPercentile |
python | plotly__plotly.py | plotly/graph_objs/cone/_lighting.py | {
"start": 233,
"end": 7731
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "cone"
_path_str = "cone.lighting"
_valid_props = {
"ambient",
"diffuse",
"facenormalsepsilon",
"fresnel",
"roughness",
"specular",
"vertexnormalsepsilon",
}
@property
def ambient(self):
"""
Ambient light increases overall color visibility but can wash
out the image.
The 'ambient' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
int|float
"""
return self["ambient"]
@ambient.setter
def ambient(self, val):
self["ambient"] = val
@property
def diffuse(self):
"""
Represents the extent that incident rays are reflected in a
range of angles.
The 'diffuse' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
int|float
"""
return self["diffuse"]
@diffuse.setter
def diffuse(self, val):
self["diffuse"] = val
@property
def facenormalsepsilon(self):
"""
Epsilon for face normals calculation avoids math issues arising
from degenerate geometry.
The 'facenormalsepsilon' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
int|float
"""
return self["facenormalsepsilon"]
@facenormalsepsilon.setter
def facenormalsepsilon(self, val):
self["facenormalsepsilon"] = val
@property
def fresnel(self):
"""
Represents the reflectance as a dependency of the viewing
angle; e.g. paper is reflective when viewing it from the edge
of the paper (almost 90 degrees), causing shine.
The 'fresnel' property is a number and may be specified as:
- An int or float in the interval [0, 5]
Returns
-------
int|float
"""
return self["fresnel"]
@fresnel.setter
def fresnel(self, val):
self["fresnel"] = val
@property
def roughness(self):
"""
Alters specular reflection; the rougher the surface, the wider
and less contrasty the shine.
The 'roughness' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
int|float
"""
return self["roughness"]
@roughness.setter
def roughness(self, val):
self["roughness"] = val
@property
def specular(self):
"""
Represents the level that incident rays are reflected in a
single direction, causing shine.
The 'specular' property is a number and may be specified as:
- An int or float in the interval [0, 2]
Returns
-------
int|float
"""
return self["specular"]
@specular.setter
def specular(self, val):
self["specular"] = val
@property
def vertexnormalsepsilon(self):
"""
Epsilon for vertex normals calculation avoids math issues
arising from degenerate geometry.
The 'vertexnormalsepsilon' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
int|float
"""
return self["vertexnormalsepsilon"]
@vertexnormalsepsilon.setter
def vertexnormalsepsilon(self, val):
self["vertexnormalsepsilon"] = val
@property
def _prop_descriptions(self):
return """\
ambient
Ambient light increases overall color visibility but
can wash out the image.
diffuse
Represents the extent that incident rays are reflected
in a range of angles.
facenormalsepsilon
Epsilon for face normals calculation avoids math issues
arising from degenerate geometry.
fresnel
Represents the reflectance as a dependency of the
viewing angle; e.g. paper is reflective when viewing it
from the edge of the paper (almost 90 degrees), causing
shine.
roughness
Alters specular reflection; the rougher the surface,
the wider and less contrasty the shine.
specular
Represents the level that incident rays are reflected
in a single direction, causing shine.
vertexnormalsepsilon
Epsilon for vertex normals calculation avoids math
issues arising from degenerate geometry.
"""
def __init__(
self,
arg=None,
ambient=None,
diffuse=None,
facenormalsepsilon=None,
fresnel=None,
roughness=None,
specular=None,
vertexnormalsepsilon=None,
**kwargs,
):
"""
Construct a new Lighting object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.cone.Lighting`
ambient
Ambient light increases overall color visibility but
can wash out the image.
diffuse
Represents the extent that incident rays are reflected
in a range of angles.
facenormalsepsilon
Epsilon for face normals calculation avoids math issues
arising from degenerate geometry.
fresnel
Represents the reflectance as a dependency of the
viewing angle; e.g. paper is reflective when viewing it
from the edge of the paper (almost 90 degrees), causing
shine.
roughness
Alters specular reflection; the rougher the surface,
the wider and less contrasty the shine.
specular
Represents the level that incident rays are reflected
in a single direction, causing shine.
vertexnormalsepsilon
Epsilon for vertex normals calculation avoids math
issues arising from degenerate geometry.
Returns
-------
Lighting
"""
super().__init__("lighting")
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.cone.Lighting
constructor must be a dict or
an instance of :class:`plotly.graph_objs.cone.Lighting`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("ambient", arg, ambient)
self._set_property("diffuse", arg, diffuse)
self._set_property("facenormalsepsilon", arg, facenormalsepsilon)
self._set_property("fresnel", arg, fresnel)
self._set_property("roughness", arg, roughness)
self._set_property("specular", arg, specular)
self._set_property("vertexnormalsepsilon", arg, vertexnormalsepsilon)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Lighting |
python | getsentry__sentry | src/sentry/auth/providers/fly/provider.py | {
"start": 3462,
"end": 3817
} | class ____(FlyOAuth2Provider):
"""
When a customer is no longer on a Fly.io sponsored plan, we change their provider
to the "non-partner" version of Fly SSO so that it can be disabled.
"""
name = SPONSOR_OAUTH_NAME[ChannelName.FLY_NON_PARTNER]
key = ChannelName.FLY_NON_PARTNER.value
is_partner = False
| NonPartnerFlyOAuth2Provider |
python | google__pytype | pytype/overlays/fiddle_overlay.py | {
"start": 1987,
"end": 7175
} | class ____(abstract.PyTDClass, mixin.HasSlots):
"""Factory for creating fiddle.Config classes."""
def __init__(self, name, ctx, module):
pytd_cls = ctx.loader.lookup_pytd(module, name)
# fiddle.Config/Partial loads as a LateType, convert to pytd.Class
if isinstance(pytd_cls, pytd.Constant):
pytd_cls = ctx.convert.constant_to_value(pytd_cls).pytd_cls
super().__init__(name, pytd_cls, ctx)
mixin.HasSlots.init_mixin(self)
self.set_native_slot("__getitem__", self.getitem_slot)
# For consistency with the rest of the overlay
self.fiddle_type_name = _CLASS_ALIASES[name]
self.module = module
def __repr__(self):
return f"FiddleBuildableBuilder[{self.name}]"
def _match_pytd_init(self, node, init_var, args):
init = init_var.data[0]
old_pytd_sigs = []
for signature in init.signatures:
old_pytd_sig = signature.pytd_sig
signature.pytd_sig = old_pytd_sig.Replace(
params=tuple(p.Replace(optional=True) for p in old_pytd_sig.params)
)
old_pytd_sigs.append(old_pytd_sig)
try:
init.match_args(node, args)
finally:
for signature, old_pytd_sig in zip(init.signatures, old_pytd_sigs):
signature.pytd_sig = old_pytd_sig
def _match_interpreter_init(self, node, init_var, args):
# Buildables support partial initialization, so give every parameter a
# default when matching __init__.
init = init_var.data[0]
old_defaults = {}
for k in init.signature.param_names:
old_defaults[k] = init.signature.defaults.get(k)
init.signature.defaults[k] = self.ctx.new_unsolvable(node)
# TODO(mdemello): We are calling the function and discarding the return
# value, when ideally we should just call function.match_all_args().
try:
function.call_function(self.ctx, node, init_var, args)
finally:
for k, default in old_defaults.items():
if default:
init.signature.defaults[k] = default
else:
del init.signature.defaults[k]
def _make_init_args(self, node, underlying, args, kwargs):
"""Unwrap Config instances for arg matching."""
def unwrap(arg_var):
# If an arg has a Config object, just use its underlying type and don't
# bother with the rest of the bindings (assume strict arg matching)
for d in arg_var.data:
if isinstance(d, Buildable):
if isinstance(d.underlying, _FUNCTION_OR_METHOD_TYPES):
# If the underlying type is a function, do not try to instantiate it
return self.ctx.new_unsolvable(node)
else:
# Match either Config[A] or A
# TODO(mdemello): This is to prevent issues when a dataclass field
# has type Config[A] rather than A, in which case blindly unwrapping
# an arg of type Config[A] is wrong. We should ideally do arg-by-arg
# matching here instead of trying to construct function args without
# reference to the signature we are matching.
return self.ctx.join_variables(
node, [arg_var, d.underlying.instantiate(node)]
)
return arg_var
new_args = (underlying.instantiate(node),)
new_args += tuple(unwrap(arg) for arg in args[1:])
new_kwargs = {k: unwrap(arg) for k, arg in kwargs.items()}
return function.Args(posargs=new_args, namedargs=new_kwargs)
def _check_init_args(self, node, underlying, args, kwargs):
# Configs can be initialized either with no args, e.g. Config(Class) or with
# initial values, e.g. Config(Class, x=10, y=20). We need to check here that
# the extra args match the underlying __init__ signature.
if len(args) > 1 or kwargs:
_, init_var = self.ctx.attribute_handler.get_attribute(
node, underlying, "__init__"
)
if abstract_utils.is_dataclass(underlying):
# Only do init matching for dataclasses for now
args = self._make_init_args(node, underlying, args, kwargs)
init = init_var.data[0]
if isinstance(init, abstract.PyTDFunction):
self._match_pytd_init(node, init_var, args)
else:
self._match_interpreter_init(node, init_var, args)
def new_slot(
self, node, unused_cls, *args, **kwargs
) -> tuple[Node, "cfg.Variable"]:
"""Create a Config or Partial instance from args."""
# pass
if not args:
return node, self.ctx.new_unsolvable(node)
underlying = args[0].data[0]
self._check_init_args(node, underlying, args, kwargs)
# Now create the Config object.
node, ret = make_instance(self.name, underlying, node, self.ctx)
return node, ret.to_variable(node)
def getitem_slot(self, node, index_var) -> tuple[Node, "cfg.Variable"]:
"""Specialize the generic class with the value of index_var."""
underlying = index_var.data[0]
ret = BuildableType.make(
self.fiddle_type_name, underlying, self.ctx, module=self.module
)
return node, ret.to_variable(node)
def get_own_new(self, node, value) -> tuple[Node, Variable]:
new = abstract.NativeFunction("__new__", self.new_slot, self.ctx)
return node, new.to_variable(node)
| BuildableBuilder |
python | Textualize__textual | src/textual/widgets/_text_area.py | {
"start": 2847,
"end": 3247
} | class ____:
"""A container for a language which has been registered with the TextArea."""
name: str
"""The name of the language"""
language: "Language" | None
"""The tree-sitter language object if that has been overridden, or None if it is a built-in language."""
highlight_query: str
"""The tree-sitter highlight query to use for syntax highlighting."""
| TextAreaLanguage |
python | joke2k__faker | faker/exceptions.py | {
"start": 286,
"end": 506
} | class ____(BaseFakerException):
"""The requested feature is not available on this system."""
def __init__(self, msg: str, name: str) -> None:
self.name = name
super().__init__(msg)
| UnsupportedFeature |
python | getsentry__sentry | src/sentry/api/endpoints/organization_events_spans_histogram.py | {
"start": 1467,
"end": 2828
} | class ____(OrganizationEventsV2EndpointBase):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
def get(self, request: Request, organization: Organization) -> Response:
try:
snuba_params = self.get_snuba_params(request, organization)
except NoProjects:
return Response({})
with sentry_sdk.start_span(op="discover.endpoint", name="spans_histogram"):
serializer = SpansHistogramSerializer(data=request.GET)
if serializer.is_valid():
data = serializer.validated_data
with handle_query_errors():
results = discover.spans_histogram_query(
span=data["span"],
user_query=data.get("query"),
snuba_params=snuba_params,
num_buckets=data["numBuckets"],
precision=data["precision"],
min_value=data.get("min"),
max_value=data.get("max"),
data_filter=data.get("dataFilter"),
referrer="api.organization-events-spans-histogram",
)
return Response(results)
else:
return Response(serializer.errors, status=400)
| OrganizationEventsSpansHistogramEndpoint |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.