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
celery__celery
celery/bin/worker.py
{ "start": 660, "end": 981 }
class ____(ParamType): """Celery Beat flag.""" name = "beat" def convert(self, value, param, ctx): if ctx.obj.app.IS_WINDOWS and value: self.fail('-B option does not work on Windows. ' 'Please run celery beat as a separate service.') return value
CeleryBeat
python
kamyu104__LeetCode-Solutions
Python/find-the-minimum-area-to-cover-all-ones-ii.py
{ "start": 8054, "end": 11771 }
class ____(object): def minimumSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ # RMQ - Sparse Table # Template: https://github.com/kamyu104/GoogleCodeJam-Farewell-Rounds/blob/main/Round%20D/genetic_sequences2.py3 # Time: ctor: O(NlogN) * O(fn) # query: O(fn) # Space: O(NlogN) class SparseTable(object): def __init__(self, arr, fn): self.fn = fn self.bit_length = [0] n = len(arr) k = n.bit_length()-1 # log2_floor(n) for i in xrange(k+1): self.bit_length.extend(i+1 for _ in xrange(min(1<<i, (n+1)-len(self.bit_length)))) self.st = [[0]*n for _ in xrange(k+1)] self.st[0] = arr[:] for i in xrange(1, k+1): # Time: O(NlogN) * O(fn) for j in xrange((n-(1<<i))+1): self.st[i][j] = fn(self.st[i-1][j], self.st[i-1][j+(1<<(i-1))]) def query(self, L, R): # Time: O(fn) i = self.bit_length[R-L+1]-1 # log2_floor(R-L+1) return self.fn(self.st[i][L], self.st[i][R-(1<<i)+1]) def minimumArea(min_i, max_i, min_j, max_j): min_r = min(st_min_i[min_i].query(min_j, max_j), max_i+1) max_r = max(st_max_i[max_i].query(min_j, max_j), min_i-1) min_c = min(st_min_j[min_j].query(min_i, max_i), max_j+1) max_c = max(st_max_j[max_j].query(min_i, max_i), min_j-1) return (max_r-min_r+1)*(max_c-min_c+1) if min_r <= max_i else 0 result = float("inf") for _ in xrange(4): st_min_i = [None]*len(grid) curr = [len(grid)]*len(grid[0]) for i in reversed(xrange(len(grid))): for j in xrange(len(grid[0])): if grid[i][j]: curr[j] = i st_min_i[i] = SparseTable(curr, min) st_max_i = [None]*len(grid) curr = [-1]*len(grid[0]) for i in xrange(len(grid)): for j in xrange(len(grid[0])): if grid[i][j]: curr[j] = i st_max_i[i] = SparseTable(curr, max) st_min_j = [None]*len(grid[0]) curr = [len(grid[0])]*len(grid) for j in reversed(xrange(len(grid[0]))): for i in xrange(len(grid)): if grid[i][j]: curr[i] = j st_min_j[j] = SparseTable(curr, min) st_max_j = [None]*len(grid[0]) curr = [-1]*len(grid) for j in xrange(len(grid[0])): for i in xrange(len(grid)): if grid[i][j]: curr[i] = j st_max_j[j] = SparseTable(curr, max) for i in xrange(len(grid)-1): a = minimumArea(0, i, 0, len(grid[0])-1) for j in xrange(len(grid[0])-1): b = minimumArea(i+1, len(grid)-1, 0, j) c = minimumArea(i+1, len(grid)-1, j+1, len(grid[0])-1) result = min(result, a+b+c) for i in xrange(len(grid)-2): a = minimumArea(0, i, 0, len(grid[0])-1) for j in xrange(i+1, len(grid)-1): b = minimumArea(i+1, j, 0, len(grid[0])-1) c = minimumArea(j+1, len(grid)-1, 0, len(grid[0])-1) result = min(result, a+b+c) grid = zip(*grid[::-1]) return result # Time: O(max(n, m)^2 * log(max(n, m))) # Space: O(1) # prefix sum, binary search
Solution3
python
networkx__networkx
networkx/algorithms/shortest_paths/tests/test_unweighted.py
{ "start": 518, "end": 5879 }
class ____: @classmethod def setup_class(cls): from networkx import convert_node_labels_to_integers as cnlti cls.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted") cls.cycle = nx.cycle_graph(7) cls.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph()) def test_bidirectional_shortest_path(self): assert nx.bidirectional_shortest_path(self.cycle, 0, 3) == [0, 1, 2, 3] assert nx.bidirectional_shortest_path(self.cycle, 0, 4) == [0, 6, 5, 4] validate_grid_path( 4, 4, 1, 12, nx.bidirectional_shortest_path(self.grid, 1, 12) ) assert nx.bidirectional_shortest_path(self.directed_cycle, 0, 3) == [0, 1, 2, 3] # test source = target assert nx.bidirectional_shortest_path(self.cycle, 3, 3) == [3] @pytest.mark.parametrize( ("src", "tgt"), ( (8, 3), # source not in graph (3, 8), # target not in graph (8, 10), # neither source nor target in graph (8, 8), # src == tgt, neither in graph - tests order of input checks ), ) def test_bidirectional_shortest_path_src_tgt_not_in_graph(self, src, tgt): with pytest.raises( nx.NodeNotFound, match=f"(Source {src}|Target {tgt}) is not in G", ): nx.bidirectional_shortest_path(self.cycle, src, tgt) def test_shortest_path_length(self): assert nx.shortest_path_length(self.cycle, 0, 3) == 3 assert nx.shortest_path_length(self.grid, 1, 12) == 5 assert nx.shortest_path_length(self.directed_cycle, 0, 4) == 4 # now with weights assert nx.shortest_path_length(self.cycle, 0, 3, weight=True) == 3 assert nx.shortest_path_length(self.grid, 1, 12, weight=True) == 5 assert nx.shortest_path_length(self.directed_cycle, 0, 4, weight=True) == 4 def test_single_source_shortest_path(self): p = nx.single_source_shortest_path(self.directed_cycle, 3) assert p[0] == [3, 4, 5, 6, 0] p = nx.single_source_shortest_path(self.cycle, 0) assert p[3] == [0, 1, 2, 3] p = nx.single_source_shortest_path(self.cycle, 0, cutoff=0) assert p == {0: [0]} def test_single_source_shortest_path_length(self): pl = nx.single_source_shortest_path_length lengths = {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1} assert dict(pl(self.cycle, 0)) == lengths lengths = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6} assert dict(pl(self.directed_cycle, 0)) == lengths def test_single_target_shortest_path(self): p = nx.single_target_shortest_path(self.directed_cycle, 0) assert p[3] == [3, 4, 5, 6, 0] p = nx.single_target_shortest_path(self.cycle, 0) assert p[3] == [3, 2, 1, 0] p = nx.single_target_shortest_path(self.cycle, 0, cutoff=0) assert p == {0: [0]} # test missing targets target = 8 with pytest.raises(nx.NodeNotFound, match=f"Target {target} not in G"): nx.single_target_shortest_path(self.cycle, target) def test_single_target_shortest_path_length(self): pl = nx.single_target_shortest_path_length lengths = {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1} assert pl(self.cycle, 0) == lengths lengths = {0: 0, 1: 6, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1} assert pl(self.directed_cycle, 0) == lengths # test missing targets target = 8 with pytest.raises(nx.NodeNotFound, match=f"Target {target} is not in G"): nx.single_target_shortest_path_length(self.cycle, target) def test_all_pairs_shortest_path(self): p = dict(nx.all_pairs_shortest_path(self.cycle)) assert p[0][3] == [0, 1, 2, 3] p = dict(nx.all_pairs_shortest_path(self.grid)) validate_grid_path(4, 4, 1, 12, p[1][12]) def test_all_pairs_shortest_path_length(self): l = dict(nx.all_pairs_shortest_path_length(self.cycle)) assert l[0] == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1} l = dict(nx.all_pairs_shortest_path_length(self.grid)) assert l[1][16] == 6 def test_predecessor_path(self): G = nx.path_graph(4) assert nx.predecessor(G, 0) == {0: [], 1: [0], 2: [1], 3: [2]} assert nx.predecessor(G, 0, 3) == [2] def test_predecessor_cycle(self): G = nx.cycle_graph(4) pred = nx.predecessor(G, 0) assert pred[0] == [] assert pred[1] == [0] assert pred[2] in [[1, 3], [3, 1]] assert pred[3] == [0] def test_predecessor_cutoff(self): G = nx.path_graph(4) p = nx.predecessor(G, 0, 3) assert 4 not in p def test_predecessor_target(self): G = nx.path_graph(4) p = nx.predecessor(G, 0, 3) assert p == [2] p = nx.predecessor(G, 0, 3, cutoff=2) assert p == [] p, s = nx.predecessor(G, 0, 3, return_seen=True) assert p == [2] assert s == 3 p, s = nx.predecessor(G, 0, 3, cutoff=2, return_seen=True) assert p == [] assert s == -1 def test_predecessor_missing_source(self): source = 8 with pytest.raises(nx.NodeNotFound, match=f"Source {source} not in G"): nx.predecessor(self.cycle, source)
TestUnweightedPath
python
PrefectHQ__prefect
tests/server/orchestration/api/ui/test_flow_runs.py
{ "start": 1798, "end": 2717 }
class ____: async def test_read_flow_runs_200(self, flow_runs, client): response = await client.post("/ui/flow_runs/history") assert response.status_code == status.HTTP_200_OK assert len(response.json()) == 3 async def test_read_flow_runs(self, flow_runs, client): response = await client.post("/ui/flow_runs/history", json=dict(sort="ID_DESC")) flow_runs = sorted(flow_runs, key=lambda x: x.id, reverse=True) data = parse_obj_as(List[SimpleFlowRun], response.json()) for i in range(3): assert data[i].id == flow_runs[i].id assert data[i].state_type == flow_runs[i].state_type assert data[i].timestamp == flow_runs[i].expected_start_time # less than or equal because this is dynamically computed for running states assert data[i].duration <= flow_runs[i].estimated_run_time
TestReadFlowRunHistory
python
tensorflow__tensorflow
tensorflow/python/ops/ragged/ragged_where_op_test.py
{ "start": 1099, "end": 9492 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): @parameterized.parameters([ #========================================================================= # Docstring Examples #========================================================================= dict( # shape=[D1, (D2)] condition=ragged_factory_ops.constant_value( [[True, False, True], [False, True]]), expected=[[0, 0], [0, 2], [1, 1]]), dict( # shape=[D1, (D2)] condition=ragged_factory_ops.constant_value( [[True, False, True], [False, True]]), x=ragged_factory_ops.constant_value( [['A', 'B', 'C'], ['D', 'E']]), y=ragged_factory_ops.constant_value( [['a', 'b', 'c'], ['d', 'e']]), expected=ragged_factory_ops.constant_value( [[b'A', b'b', b'C'], [b'd', b'E']])), dict( # shape=[D1, (D2)] condition=ragged_factory_ops.constant_value([True, False]), x=ragged_factory_ops.constant_value([['A', 'B', 'C'], ['D', 'E']]), y=ragged_factory_ops.constant_value([['a', 'b', 'c'], ['d', 'e']]), expected=ragged_factory_ops.constant_value( [[b'A', b'B', b'C'], [b'd', b'e']])), #========================================================================= # Coordinate-retrieval mode #========================================================================= dict( # shape=[D1] condition=[True, False, True, False, True], expected=[[0], [2], [4]]), dict( # shape=[D1, D2] condition=[[True, False], [False, True]], expected=[[0, 0], [1, 1]]), dict( # shape=[D1, (D2)] condition=ragged_factory_ops.constant_value( [[True, False, True], [False, True]]), expected=[[0, 0], [0, 2], [1, 1]]), dict( # shape=[D1, (D2), (D3)] condition=ragged_factory_ops.constant_value([ [[True, False, True], [False, True]], [[True], [], [False], [False, True, False]] ]), expected=[[0, 0, 0], [0, 0, 2], [0, 1, 1], [1, 0, 0], [1, 3, 1]]), dict( # shape=[D1, (D2), D3] condition=ragged_factory_ops.constant_value([ [[True, False], [False, True]], [[True, False], [False, False], [True, False], [False, True]] ], ragged_rank=1), expected=[[0, 0, 0], [0, 1, 1], [1, 0, 0], [1, 2, 0], [1, 3, 1]]), dict( # shape=[D1, (D2), (D3), (D4)] condition=ragged_factory_ops.constant_value([ [[[], [True]]], [[[True, False, True], [False, True]], [[True], [], [False], [False, True, False]]] ]), expected=[[0, 0, 1, 0], [1, 0, 0, 0], [1, 0, 0, 2], [1, 0, 1, 1], [1, 1, 0, 0], [1, 1, 3, 1]]), #========================================================================= # Elementwise value-selection mode #========================================================================= dict( # shape=[] condition=True, x='A', y='a', expected=b'A'), dict( # shape=[] condition=False, x='A', y='a', expected=b'a'), dict( # shape=[D1] condition=[True, False, True], x=['A', 'B', 'C'], y=['a', 'b', 'c'], expected=[b'A', b'b', b'C']), dict( # shape=[D1, D2] condition=[[True, False], [False, True]], x=[['A', 'B'], ['D', 'E']], y=[['a', 'b'], ['d', 'e']], expected=[[b'A', b'b'], [b'd', b'E']]), dict( # shape=[D1, (D2)] condition=ragged_factory_ops.constant_value( [[True, False, True], [False, True]]), x=ragged_factory_ops.constant_value([['A', 'B', 'C'], ['D', 'E']]), y=ragged_factory_ops.constant_value([['a', 'b', 'c'], ['d', 'e']]), expected=ragged_factory_ops.constant_value( [[b'A', b'b', b'C'], [b'd', b'E']])), dict( # shape=[D1, (D2), D3] condition=ragged_factory_ops.constant_value([ [[True, False], [False, True]], [[True, False], [False, False], [True, False], [False, True]] ], ragged_rank=1), x=ragged_factory_ops.constant_value([ [['A', 'B'], ['C', 'D']], [['E', 'F'], ['G', 'H'], ['I', 'J'], ['K', 'L']] ], ragged_rank=1), y=ragged_factory_ops.constant_value([ [['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h'], ['i', 'j'], ['k', 'l']] ], ragged_rank=1), expected=ragged_factory_ops.constant_value([ [[b'A', b'b'], [b'c', b'D']], [[b'E', b'f'], [b'g', b'h'], [b'I', b'j'], [b'k', b'L']] ], ragged_rank=1)), dict( # shape=[D1, (D2), (D3), (D4)] condition=ragged_factory_ops.constant_value([ [[[], [True]]], [[[True, False, True], [False, True]], [[True], [], [False], [False, True, False]]] ]), x=ragged_factory_ops.constant_value([ [[[], ['A']]], [[['B', 'C', 'D'], ['E', 'F']], [['G'], [], ['H'], ['I', 'J', 'K']]] ]), y=ragged_factory_ops.constant_value([ [[[], ['a']]], [[['b', 'c', 'd'], ['e', 'f']], [['g'], [], ['h'], ['i', 'j', 'k']]] ]), expected=ragged_factory_ops.constant_value([ [[[], [b'A']]], [[[b'B', b'c', b'D'], [b'e', b'F']], [[b'G'], [], [b'h'], [b'i', b'J', b'k']]] ])), #========================================================================= # Elementwise row-selection mode #========================================================================= dict( # x.shape=[D1, D2], y.shape=[D1, D2] condition=[True, False, True], x=[['A', 'B'], ['C', 'D'], ['E', 'F']], y=[['a', 'b'], ['c', 'd'], ['e', 'f']], expected=[[b'A', b'B'], [b'c', b'd'], [b'E', b'F']]), dict( # x.shape=[D1, D2], y.shape=[D1, (D2)] condition=[True, False, True], x=[['A', 'B'], ['C', 'D'], ['E', 'F']], y=ragged_factory_ops.constant_value( [['a', 'b'], ['c'], ['d', 'e']]), expected=ragged_factory_ops.constant_value( [[b'A', b'B'], [b'c'], [b'E', b'F']])), dict( # x.shape=[D1, (D2)], y.shape=[D1, (D2)] condition=[True, False, True], x=ragged_factory_ops.constant_value( [['A', 'B', 'C'], ['D', 'E'], ['F', 'G']]), y=ragged_factory_ops.constant_value( [['a', 'b'], ['c'], ['d', 'e']]), expected=ragged_factory_ops.constant_value( [[b'A', b'B', b'C'], [b'c'], [b'F', b'G']])), dict( # shape=[D1, (D2), (D3), (D4)] condition=ragged_factory_ops.constant_value([True, False]), x=ragged_factory_ops.constant_value([ [[[], ['A']]], [[['B', 'C', 'D'], ['E', 'F']], [['G'], [], ['H'], ['I', 'J', 'K']]] ]), y=ragged_factory_ops.constant_value([[[['a']]], [[['b']]]]), expected=ragged_factory_ops.constant_value( [[[[], [b'A']]], [[[b'b']]]])), ]) # pyformat: disable def testRaggedWhere(self, condition, expected, x=None, y=None): result = ragged_where_op.where(condition, x, y) self.assertAllEqual(result, expected) @parameterized.parameters([ dict( condition=[True, False], x=[1, 2], error=ValueError, message='x and y must be either both None or both non-None'), dict( condition=ragged_factory_ops.constant_value([[True, False, True], [False, True]]), x=ragged_factory_ops.constant_value([['A', 'B', 'C'], ['D', 'E']]), y=[['a', 'b'], ['d', 'e']], error=ValueError, message='Input shapes do not match.'), ]) def testRaggedWhereErrors(self, condition, error, message, x=None, y=None): with self.assertRaisesRegex(error, message): ragged_where_op.where(condition, x, y) @test_util.run_all_in_graph_and_eager_modes
RaggedWhereV1OpTest
python
walkccc__LeetCode
solutions/479. Largest Palindrome Product/479.py
{ "start": 0, "end": 357 }
class ____: def largestPalindrome(self, n: int) -> int: if n == 1: return 9 MOD = 1337 upper = pow(10, n) - 1 lower = pow(10, n - 1) - 1 for i in range(upper, lower, -1): cand = int(str(i) + str(i)[::-1]) j = upper while j * j >= cand: if cand % j == 0: return cand % MOD j -= 1
Solution
python
kamyu104__LeetCode-Solutions
Python/stone-removal-game.py
{ "start": 36, "end": 364 }
class ____(object): def canAliceWin(self, n): """ :type n: int :rtype: bool """ c = 10 # (c+(c-l+1))*l/2 <= n # l^2-(2*c+1)*l-2*n >= 0 # l <= ((2*c+1)-((2*c+1)**2-8*n)**0.5)/2 l = int(((2*c+1)-((2*c+1)**2-8*n)**0.5)/2) return l%2 == 1
Solution
python
coleifer__peewee
tests/manytomany.py
{ "start": 214, "end": 276 }
class ____(TestModel): username = TextField(unique=True)
User
python
astropy__astropy
astropy/time/formats.py
{ "start": 67831, "end": 69495 }
class ____(TimeISOT): name = "datetime64" def _check_val_type(self, val1, val2): if not val1.dtype.kind == "M": if val1.size > 0: raise TypeError( f"Input values for {self.name} class must be datetime64 objects" ) else: val1 = np.array([], "datetime64[D]") if val2 is not None: raise ValueError( f"{self.name} objects do not accept a val2 but you provided {val2}" ) return val1, None def set_jds(self, val1, val2): # If there are any masked values in the ``val1`` datetime64 array # ('NaT') then stub them with a valid date so downstream parse_string # will work. The value under the mask is arbitrary but a "modern" date # is good. mask = np.isnat(val1) masked = np.any(mask) if masked: val1 = val1.copy() val1[mask] = "2000" # Make sure M(onth) and Y(ear) dates will parse and convert to bytestring if val1.dtype.name in ["datetime64[M]", "datetime64[Y]"]: val1 = val1.astype("datetime64[D]") val1 = val1.astype("S") # Standard ISO string parsing now super().set_jds(val1, val2) # Finally apply mask if necessary if masked: self.jd1 = Masked(self.jd1, mask=mask) self.jd2 = Masked(self.jd2, mask=mask) @property def value(self): precision = self.precision self.precision = 9 ret = super().value self.precision = precision return ret.astype("datetime64")
TimeDatetime64
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/ghost/trainer.py
{ "start": 824, "end": 20972 }
class ____(Trainer): """ The GhostTrainer trains agents in adversarial games (there are teams in opposition) using a self-play mechanism. In adversarial settings with self-play, at any time, there is only a single learning team. The other team(s) is "ghosted" which means that its agents are executing fixed policies and not learning. The GhostTrainer wraps a standard RL trainer which trains the learning team and ensures that only the trajectories collected by the learning team are used for training. The GhostTrainer also maintains past policy snapshots to be used as the fixed policies when the team is not learning. The GhostTrainer is 1:1 with brain_names as the other trainers, and is responsible for one or more teams. Note, a GhostTrainer can have only one team in asymmetric games where there is only one team with a particular behavior i.e. Hide and Seek. The GhostController manages high level coordination between multiple ghost trainers. The learning team id is cycled throughout a training run. """ def __init__( self, trainer, brain_name, controller, reward_buff_cap, trainer_settings, training, artifact_path, ): """ Creates a GhostTrainer. :param trainer: The trainer of the policy/policies being trained with self_play :param brain_name: The name of the brain associated with trainer config :param controller: GhostController that coordinates all ghost trainers and calculates ELO :param reward_buff_cap: Max reward history to track in the reward buffer :param trainer_settings: The parameters for the trainer. :param training: Whether the trainer is set for training. :param artifact_path: Path to store artifacts from this trainer. """ super().__init__( brain_name, trainer_settings, training, artifact_path, reward_buff_cap ) self.trainer = trainer self.controller = controller self._internal_trajectory_queues: Dict[str, AgentManagerQueue[Trajectory]] = {} self._internal_policy_queues: Dict[str, AgentManagerQueue[Policy]] = {} self._team_to_name_to_policy_queue: DefaultDict[ int, Dict[str, AgentManagerQueue[Policy]] ] = defaultdict(dict) self._name_to_parsed_behavior_id: Dict[str, BehaviorIdentifiers] = {} # assign ghost's stats collection to wrapped trainer's self._stats_reporter = self.trainer.stats_reporter # Set the logging to print ELO in the console self._stats_reporter.add_property(StatsPropertyType.SELF_PLAY, True) self_play_parameters = trainer_settings.self_play self.window = self_play_parameters.window self.play_against_latest_model_ratio = ( self_play_parameters.play_against_latest_model_ratio ) if ( self.play_against_latest_model_ratio > 1.0 or self.play_against_latest_model_ratio < 0.0 ): logger.warning( "The play_against_latest_model_ratio is not between 0 and 1." ) self.steps_between_save = self_play_parameters.save_steps self.steps_between_swap = self_play_parameters.swap_steps self.steps_to_train_team = self_play_parameters.team_change if self.steps_to_train_team > self.get_max_steps: logger.warning( "The max steps of the GhostTrainer for behavior name {} is less than team change. This team will not face \ opposition that has been trained if the opposition is managed by a different GhostTrainer as in an \ asymmetric game.".format( self.brain_name ) ) # Counts the number of steps of the ghost policies. Snapshot swapping # depends on this counter whereas snapshot saving and team switching depends # on the wrapped. This ensures that all teams train for the same number of trainer # steps. self.ghost_step: int = 0 # A list of dicts from brain name to a single snapshot for this trainer's policies self.policy_snapshots: List[Dict[str, List[float]]] = [] # A dict from brain name to the current snapshot of this trainer's policies self.current_policy_snapshot: Dict[str, List[float]] = {} self.snapshot_counter: int = 0 # wrapped_training_team and learning team need to be separate # in the situation where new agents are created destroyed # after learning team switches. These agents need to be added # to trainers properly. self._learning_team: int = None self.wrapped_trainer_team: int = None self.last_save: int = 0 self.last_swap: int = 0 self.last_team_change: int = 0 self.initial_elo = GlobalTrainingStatus.get_parameter_state( self.brain_name, StatusType.ELO ) if self.initial_elo is None: self.initial_elo = self_play_parameters.initial_elo self.policy_elos: List[float] = [self.initial_elo] * ( self.window + 1 ) # for learning policy self.current_opponent: int = 0 @property def get_step(self) -> int: """ Returns the number of steps the wrapped trainer has performed :return: the step count of the wrapped trainer """ return self.trainer.get_step @property def reward_buffer(self) -> Deque[float]: """ Returns the reward buffer. The reward buffer contains the cumulative rewards of the most recent episodes completed by agents using this trainer. :return: the reward buffer. """ return self.trainer.reward_buffer @property def current_elo(self) -> float: """ Gets ELO of current policy which is always last in the list :return: ELO of current policy """ return self.policy_elos[-1] def change_current_elo(self, change: float) -> None: """ Changes elo of current policy which is always last in the list :param change: Amount to change current elo by """ self.policy_elos[-1] += change def get_opponent_elo(self) -> float: """ Get elo of current opponent policy :return: ELO of current opponent policy """ return self.policy_elos[self.current_opponent] def change_opponent_elo(self, change: float) -> None: """ Changes elo of current opponent policy :param change: Amount to change current opponent elo by """ self.policy_elos[self.current_opponent] -= change def _process_trajectory(self, trajectory: Trajectory) -> None: """ Determines the final result of an episode and asks the GhostController to calculate the ELO change. The GhostController changes the ELO of the opponent policy since this may be in a different GhostTrainer i.e. in asymmetric games. We assume the last reward determines the winner. :param trajectory: Trajectory. """ if ( trajectory.done_reached and trajectory.all_group_dones_reached and not trajectory.interrupted ): # Assumption is that final reward is >0/0/<0 for win/draw/loss final_reward = ( trajectory.steps[-1].reward + trajectory.steps[-1].group_reward ) result = 0.5 if final_reward > 0: result = 1.0 elif final_reward < 0: result = 0.0 change = self.controller.compute_elo_rating_changes( self.current_elo, result ) self.change_current_elo(change) self._stats_reporter.add_stat("Self-play/ELO", self.current_elo) def advance(self) -> None: """ Steps the trainer, passing trajectories to wrapped trainer and calling trainer advance """ for trajectory_queue in self.trajectory_queues: parsed_behavior_id = self._name_to_parsed_behavior_id[ trajectory_queue.behavior_id ] if parsed_behavior_id.team_id == self._learning_team: # With a future multiagent trainer, this will be indexed by 'role' internal_trajectory_queue = self._internal_trajectory_queues[ parsed_behavior_id.brain_name ] try: # We grab at most the maximum length of the queue. # This ensures that even if the queue is being filled faster than it is # being emptied, the trajectories in the queue are on-policy. for _ in range(trajectory_queue.qsize()): t = trajectory_queue.get_nowait() # adds to wrapped trainers queue internal_trajectory_queue.put(t) self._process_trajectory(t) except AgentManagerQueue.Empty: pass else: # Dump trajectories from non-learning policy try: for _ in range(trajectory_queue.qsize()): t = trajectory_queue.get_nowait() # count ghost steps self.ghost_step += len(t.steps) except AgentManagerQueue.Empty: pass self._next_summary_step = self.trainer._next_summary_step self.trainer.advance() if self.get_step - self.last_team_change > self.steps_to_train_team: self.controller.change_training_team(self.get_step) self.last_team_change = self.get_step next_learning_team = self.controller.get_learning_team # Case 1: No team change. The if statement just continues to push the policy # into the correct queue (or not if not learning team). for brain_name in self._internal_policy_queues: internal_policy_queue = self._internal_policy_queues[brain_name] try: policy = internal_policy_queue.get_nowait() self.current_policy_snapshot[brain_name] = policy.get_weights() except AgentManagerQueue.Empty: continue if ( self._learning_team == next_learning_team and next_learning_team in self._team_to_name_to_policy_queue ): name_to_policy_queue = self._team_to_name_to_policy_queue[ next_learning_team ] if brain_name in name_to_policy_queue: behavior_id = create_name_behavior_id( brain_name, next_learning_team ) policy = self.get_policy(behavior_id) policy.load_weights(self.current_policy_snapshot[brain_name]) name_to_policy_queue[brain_name].put(policy) # CASE 2: Current learning team is managed by this GhostTrainer. # If the learning team changes, the following loop over queues will push the # new policy into the policy queue for the new learning agent if # that policy is managed by this GhostTrainer. Otherwise, it will save the current snapshot. # CASE 3: Current learning team is managed by a different GhostTrainer. # If the learning team changes to a team managed by this GhostTrainer, this loop # will push the current_snapshot into the correct queue. Otherwise, # it will continue skipping and swap_snapshot will continue to handle # pushing fixed snapshots if ( self._learning_team != next_learning_team and next_learning_team in self._team_to_name_to_policy_queue ): name_to_policy_queue = self._team_to_name_to_policy_queue[ next_learning_team ] for brain_name in name_to_policy_queue: behavior_id = create_name_behavior_id(brain_name, next_learning_team) policy = self.get_policy(behavior_id) policy.load_weights(self.current_policy_snapshot[brain_name]) name_to_policy_queue[brain_name].put(policy) # Note save and swap should be on different step counters. # We don't want to save unless the policy is learning. if self.get_step - self.last_save > self.steps_between_save: self._save_snapshot() self.last_save = self.get_step if ( self._learning_team != next_learning_team or self.ghost_step - self.last_swap > self.steps_between_swap ): self._learning_team = next_learning_team self._swap_snapshots() self.last_swap = self.ghost_step def end_episode(self): """ Forwarding call to wrapped trainers end_episode """ self.trainer.end_episode() def save_model(self) -> None: """ Forwarding call to wrapped trainers save_model. """ GlobalTrainingStatus.set_parameter_state( self.brain_name, StatusType.ELO, self.current_elo ) self.trainer.save_model() def create_policy( self, parsed_behavior_id: BehaviorIdentifiers, behavior_spec: BehaviorSpec, ) -> Policy: """ Creates policy with the wrapped trainer's create_policy function The first policy encountered sets the wrapped trainer team. This is to ensure that all agents from the same multi-agent team are grouped. All policies associated with this team are added to the wrapped trainer to be trained. """ policy = self.trainer.create_policy(parsed_behavior_id, behavior_spec) team_id = parsed_behavior_id.team_id self.controller.subscribe_team_id(team_id, self) # First policy or a new agent on the same team encountered if self.wrapped_trainer_team is None or team_id == self.wrapped_trainer_team: internal_trainer_policy = self.trainer.create_policy( parsed_behavior_id, behavior_spec ) self.trainer.add_policy(parsed_behavior_id, internal_trainer_policy) self.current_policy_snapshot[ parsed_behavior_id.brain_name ] = internal_trainer_policy.get_weights() policy.load_weights(internal_trainer_policy.get_weights()) self._save_snapshot() # Need to save after trainer initializes policy self._learning_team = self.controller.get_learning_team self.wrapped_trainer_team = team_id else: # Load the weights of the ghost policy from the wrapped one policy.load_weights( self.trainer.get_policy(parsed_behavior_id).get_weights() ) return policy def create_optimizer(self) -> TorchOptimizer: pass def add_policy( self, parsed_behavior_id: BehaviorIdentifiers, policy: Policy ) -> None: """ Adds policy to GhostTrainer. :param parsed_behavior_id: Behavior ID that the policy should belong to. :param policy: Policy to associate with name_behavior_id. """ name_behavior_id = parsed_behavior_id.behavior_id self._name_to_parsed_behavior_id[name_behavior_id] = parsed_behavior_id self.policies[name_behavior_id] = policy def _save_snapshot(self) -> None: """ Saves a snapshot of the current weights of the policy and maintains the policy_snapshots according to the window size """ for brain_name in self.current_policy_snapshot: current_snapshot_for_brain_name = self.current_policy_snapshot[brain_name] try: self.policy_snapshots[self.snapshot_counter][ brain_name ] = current_snapshot_for_brain_name except IndexError: self.policy_snapshots.append( {brain_name: current_snapshot_for_brain_name} ) self.policy_elos[self.snapshot_counter] = self.current_elo self.snapshot_counter = (self.snapshot_counter + 1) % self.window def _swap_snapshots(self) -> None: """ Swaps the appropriate weight to the policy and pushes it to respective policy queues """ for team_id in self._team_to_name_to_policy_queue: if team_id == self._learning_team: continue elif np.random.uniform() < (1 - self.play_against_latest_model_ratio): x = np.random.randint(len(self.policy_snapshots)) snapshot = self.policy_snapshots[x] else: snapshot = self.current_policy_snapshot x = "current" self.current_opponent = -1 if x == "current" else x name_to_policy_queue = self._team_to_name_to_policy_queue[team_id] for brain_name in self._team_to_name_to_policy_queue[team_id]: behavior_id = create_name_behavior_id(brain_name, team_id) policy = self.get_policy(behavior_id) policy.load_weights(snapshot[brain_name]) name_to_policy_queue[brain_name].put(policy) logger.debug( "Step {}: Swapping snapshot {} to id {} with team {} learning".format( self.ghost_step, x, behavior_id, self._learning_team ) ) def publish_policy_queue(self, policy_queue: AgentManagerQueue[Policy]) -> None: """ Adds a policy queue for every member of the team to the list of queues to publish to when this Trainer makes a policy update. Creates an internal policy queue for the wrapped trainer to push to. The GhostTrainer pushes all policies to the env. :param queue: Policy queue to publish to. """ super().publish_policy_queue(policy_queue) parsed_behavior_id = self._name_to_parsed_behavior_id[policy_queue.behavior_id] self._team_to_name_to_policy_queue[parsed_behavior_id.team_id][ parsed_behavior_id.brain_name ] = policy_queue if parsed_behavior_id.team_id == self.wrapped_trainer_team: # With a future multiagent trainer, this will be indexed by 'role' internal_policy_queue: AgentManagerQueue[Policy] = AgentManagerQueue( parsed_behavior_id.brain_name ) self._internal_policy_queues[ parsed_behavior_id.brain_name ] = internal_policy_queue self.trainer.publish_policy_queue(internal_policy_queue) def subscribe_trajectory_queue( self, trajectory_queue: AgentManagerQueue[Trajectory] ) -> None: """ Adds a trajectory queue for every member of the team to the list of queues for the trainer to ingest Trajectories from. Creates an internal trajectory queue to push trajectories from the learning team. The wrapped trainer subscribes to this queue. :param queue: Trajectory queue to publish to. """ super().subscribe_trajectory_queue(trajectory_queue) parsed_behavior_id = self._name_to_parsed_behavior_id[ trajectory_queue.behavior_id ] if parsed_behavior_id.team_id == self.wrapped_trainer_team: # With a future multiagent trainer, this will be indexed by 'role' internal_trajectory_queue: AgentManagerQueue[ Trajectory ] = AgentManagerQueue(parsed_behavior_id.brain_name) self._internal_trajectory_queues[ parsed_behavior_id.brain_name ] = internal_trajectory_queue self.trainer.subscribe_trajectory_queue(internal_trajectory_queue)
GhostTrainer
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol10.py
{ "start": 355, "end": 423 }
class ____(Base): def b(self) -> None: pass
ImplementsBase
python
huggingface__transformers
src/transformers/models/depth_pro/modeling_depth_pro.py
{ "start": 1212, "end": 1999 }
class ____(ModelOutput): r""" last_hidden_state (`torch.FloatTensor` of shape `(batch_size, n_patches_per_batch, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. features (`Union[torch.FloatTensor, List[torch.FloatTensor]]`, *optional*): Features from encoders. Can be a single feature or a list of features. """ last_hidden_state: Optional[torch.FloatTensor] = None features: Union[torch.FloatTensor, list[torch.FloatTensor]] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None @dataclass @auto_docstring( custom_intro=""" Base class for DepthProForDepthEstimation's output. """ )
DepthProOutput
python
zarr-developers__zarr-python
src/zarr/errors.py
{ "start": 1518, "end": 1682 }
class ____(BaseZarrError): """Raised when a group already exists at a certain path.""" _msg = "A group exists in store {!r} at path {!r}."
ContainsGroupError
python
oauthlib__oauthlib
tests/oauth2/rfc6749/endpoints/test_credentials_preservation.py
{ "start": 496, "end": 5448 }
class ____(TestCase): DEFAULT_REDIRECT_URI = 'http://i.b./path' def setUp(self): self.validator = mock.MagicMock(spec=RequestValidator) self.validator.get_default_redirect_uri.return_value = self.DEFAULT_REDIRECT_URI self.validator.get_code_challenge.return_value = None self.validator.authenticate_client.side_effect = self.set_client self.web = WebApplicationServer(self.validator) self.mobile = MobileApplicationServer(self.validator) def set_client(self, request): request.client = mock.MagicMock() request.client.client_id = 'mocked' return True def test_state_preservation(self): auth_uri = 'http://example.com/path?state=xyz&client_id=abc&response_type=' # authorization grant h, _, s = self.web.create_authorization_response( auth_uri + 'code', scopes=['random']) self.assertEqual(s, 302) self.assertIn('Location', h) self.assertEqual(get_query_credentials(h['Location'])['state'][0], 'xyz') # implicit grant h, _, s = self.mobile.create_authorization_response( auth_uri + 'token', scopes=['random']) self.assertEqual(s, 302) self.assertIn('Location', h) self.assertEqual(get_fragment_credentials(h['Location'])['state'][0], 'xyz') def test_redirect_uri_preservation(self): auth_uri = 'http://example.com/path?redirect_uri=http%3A%2F%2Fi.b%2Fpath&client_id=abc' redirect_uri = 'http://i.b/path' token_uri = 'http://example.com/path' # authorization grant h, _, s = self.web.create_authorization_response( auth_uri + '&response_type=code', scopes=['random']) self.assertEqual(s, 302) self.assertIn('Location', h) self.assertTrue(h['Location'].startswith(redirect_uri)) # confirm_redirect_uri should return false if the redirect uri # was given in the authorization but not in the token request. self.validator.confirm_redirect_uri.return_value = False code = get_query_credentials(h['Location'])['code'][0] _, body, _ = self.web.create_token_response(token_uri, body='grant_type=authorization_code&code=%s' % code) self.assertEqual(json.loads(body)['error'], 'invalid_request') # implicit grant h, _, s = self.mobile.create_authorization_response( auth_uri + '&response_type=token', scopes=['random']) self.assertEqual(s, 302) self.assertIn('Location', h) self.assertTrue(h['Location'].startswith(redirect_uri)) def test_invalid_redirect_uri(self): auth_uri = 'http://example.com/path?redirect_uri=http%3A%2F%2Fi.b%2Fpath&client_id=abc' self.validator.validate_redirect_uri.return_value = False # authorization grant self.assertRaises(errors.MismatchingRedirectURIError, self.web.create_authorization_response, auth_uri + '&response_type=code', scopes=['random']) # implicit grant self.assertRaises(errors.MismatchingRedirectURIError, self.mobile.create_authorization_response, auth_uri + '&response_type=token', scopes=['random']) def test_default_uri(self): auth_uri = 'http://example.com/path?state=xyz&client_id=abc' self.validator.get_default_redirect_uri.return_value = None # authorization grant self.assertRaises(errors.MissingRedirectURIError, self.web.create_authorization_response, auth_uri + '&response_type=code', scopes=['random']) # implicit grant self.assertRaises(errors.MissingRedirectURIError, self.mobile.create_authorization_response, auth_uri + '&response_type=token', scopes=['random']) def test_default_uri_in_token(self): auth_uri = 'http://example.com/path?state=xyz&client_id=abc' token_uri = 'http://example.com/path' # authorization grant h, _, s = self.web.create_authorization_response( auth_uri + '&response_type=code', scopes=['random']) self.assertEqual(s, 302) self.assertIn('Location', h) self.assertTrue(h['Location'].startswith(self.DEFAULT_REDIRECT_URI)) # confirm_redirect_uri should return true if the redirect uri # was not given in the authorization AND not in the token request. self.validator.confirm_redirect_uri.return_value = True code = get_query_credentials(h['Location'])['code'][0] self.validator.validate_code.return_value = True _, body, s = self.web.create_token_response(token_uri, body='grant_type=authorization_code&code=%s' % code) self.assertEqual(s, 200) self.assertEqual(self.validator.confirm_redirect_uri.call_args[0][2], self.DEFAULT_REDIRECT_URI)
PreservationTest
python
huggingface__transformers
src/transformers/utils/generic.py
{ "start": 14089, "end": 14398 }
class ____(str, Enum): """ Enum with more explicit error message for missing values. """ @classmethod def _missing_(cls, value): raise ValueError( f"{value} is not a valid {cls.__name__}, please select one of {list(cls._value2member_map_.keys())}" )
ExplicitEnum
python
getsentry__sentry
src/sentry/integrations/jira/views/sentry_issue_details.py
{ "start": 6856, "end": 9827 }
class ____(JiraSentryUIBaseView): """ Handles requests (from the Sentry integration in Jira) for HTML to display when you click on "Sentry -> Linked Issues" in the RH sidebar of an issue in the Jira UI. Fans the request to all regions and returns the groups from all regions. """ html_file = "sentry/integrations/jira-issue-list.html" def handle_groups(self, groups: list[RpcExternalIssueGroupMetadata]) -> Response: response_context = {"groups": [dict(group) for group in groups]} logger.info( "issue_hook.response", extra={"issue_count": len(groups)}, ) return self.get_response(response_context) def dispatch(self, request: HttpRequest, *args, **kwargs) -> HttpResponseBase: try: return super().dispatch(request, *args, **kwargs) except ApiError as exc: # Sometime set_badge() will fail to connect. response_option = handle_jira_api_error(exc, " to set badge") if response_option: return self.get_response(response_option) raise def get(self, request: Request, issue_key, *args, **kwargs) -> Response: scope = sentry_sdk.get_isolation_scope() try: integration = get_integration_from_request(request, "jira") except AtlassianConnectValidationError as e: scope.set_tag("failure", "AtlassianConnectValidationError") logger.info( "issue_hook.validation_error", extra={ "issue_key": issue_key, "error": str(e), }, ) return self.get_response({"error_message": UNABLE_TO_VERIFY_INSTALLATION}) except ExpiredSignatureError: scope.set_tag("failure", "ExpiredSignatureError") return self.get_response({"refresh_required": True}) has_groups = False groups = [] organization_ids = list( OrganizationIntegration.objects.filter( integration_id=integration.id, status=ObjectStatus.ACTIVE, ).values_list("organization_id", flat=True) ) org_regions = find_regions_for_orgs(organization_ids) for region_name in org_regions: region_groups = issue_service.get_external_issue_groups( region_name=region_name, external_issue_key=issue_key, integration_id=integration.id ) if region_groups is not None: groups.extend(region_groups) has_groups = True if not has_groups: set_badge(integration, issue_key, 0) return self.get_response({"issue_not_linked": True}) response = self.handle_groups(groups) scope.set_tag("status_code", response.status_code) set_badge(integration, issue_key, len(groups)) return response
JiraSentryIssueDetailsControlView
python
lepture__authlib
authlib/jose/rfc7518/ec_key.py
{ "start": 878, "end": 3921 }
class ____(AsymmetricKey): """Key class of the ``EC`` key type.""" kty = "EC" DSS_CURVES = { "P-256": SECP256R1, "P-384": SECP384R1, "P-521": SECP521R1, # https://tools.ietf.org/html/rfc8812#section-3.1 "secp256k1": SECP256K1, } CURVES_DSS = { SECP256R1.name: "P-256", SECP384R1.name: "P-384", SECP521R1.name: "P-521", SECP256K1.name: "secp256k1", } REQUIRED_JSON_FIELDS = ["crv", "x", "y"] PUBLIC_KEY_FIELDS = REQUIRED_JSON_FIELDS PRIVATE_KEY_FIELDS = ["crv", "d", "x", "y"] PUBLIC_KEY_CLS = EllipticCurvePublicKey PRIVATE_KEY_CLS = EllipticCurvePrivateKeyWithSerialization SSH_PUBLIC_PREFIX = b"ecdsa-sha2-" def exchange_shared_key(self, pubkey): # # used in ECDHESAlgorithm private_key = self.get_private_key() if private_key: return private_key.exchange(ec.ECDH(), pubkey) raise ValueError("Invalid key for exchanging shared key") @property def curve_key_size(self): raw_key = self.get_private_key() if not raw_key: raw_key = self.public_key return raw_key.curve.key_size def load_private_key(self): curve = self.DSS_CURVES[self._dict_data["crv"]]() public_numbers = EllipticCurvePublicNumbers( base64_to_int(self._dict_data["x"]), base64_to_int(self._dict_data["y"]), curve, ) private_numbers = EllipticCurvePrivateNumbers( base64_to_int(self.tokens["d"]), public_numbers ) return private_numbers.private_key(default_backend()) def load_public_key(self): curve = self.DSS_CURVES[self._dict_data["crv"]]() public_numbers = EllipticCurvePublicNumbers( base64_to_int(self._dict_data["x"]), base64_to_int(self._dict_data["y"]), curve, ) return public_numbers.public_key(default_backend()) def dumps_private_key(self): numbers = self.private_key.private_numbers() return { "crv": self.CURVES_DSS[self.private_key.curve.name], "x": int_to_base64(numbers.public_numbers.x), "y": int_to_base64(numbers.public_numbers.y), "d": int_to_base64(numbers.private_value), } def dumps_public_key(self): numbers = self.public_key.public_numbers() return { "crv": self.CURVES_DSS[numbers.curve.name], "x": int_to_base64(numbers.x), "y": int_to_base64(numbers.y), } @classmethod def generate_key(cls, crv="P-256", options=None, is_private=False) -> "ECKey": if crv not in cls.DSS_CURVES: raise ValueError(f'Invalid crv value: "{crv}"') raw_key = ec.generate_private_key( curve=cls.DSS_CURVES[crv](), backend=default_backend(), ) if not is_private: raw_key = raw_key.public_key() return cls.import_key(raw_key, options=options)
ECKey
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/partitions/mapping/multi/multi_to_single.py
{ "start": 902, "end": 6166 }
class ____( NamedTuple( "_InferSingleToMultiDimensionDepsResult", [ ("can_infer", bool), ("inference_failure_reason", Optional[str]), ("dimension_dependency", Optional[DimensionDependency]), ], ) ): def __new__( cls, can_infer: bool, inference_failure_reason: Optional[str] = None, dimension_dependency: Optional[DimensionDependency] = None, ): if can_infer and dimension_dependency is None: check.failed("dimension_dependency must be provided if can_infer is True") if not can_infer and inference_failure_reason is None: check.failed("inference_failure_reason must be provided if can_infer is False") return super().__new__( cls, can_infer, inference_failure_reason, dimension_dependency, ) def get_infer_single_to_multi_dimension_deps_result( upstream_partitions_def: PartitionsDefinition, downstream_partitions_def: PartitionsDefinition, partition_dimension_name: Optional[str] = None, ) -> InferSingleToMultiDimensionDepsResult: from dagster._core.definitions.partitions.mapping import TimeWindowPartitionMapping upstream_is_multipartitioned = isinstance(upstream_partitions_def, MultiPartitionsDefinition) multipartitions_defs = [ partitions_def for partitions_def in [upstream_partitions_def, downstream_partitions_def] if isinstance(partitions_def, MultiPartitionsDefinition) ] if len(multipartitions_defs) != 1: return InferSingleToMultiDimensionDepsResult( False, "Can only use MultiToSingleDimensionPartitionMapping when upstream asset is" " multipartitioned and the downstream asset is single dimensional, or vice versa." f" Instead received {len(multipartitions_defs)} multi-partitioned assets.", ) multipartitions_def = cast("MultiPartitionsDefinition", next(iter(multipartitions_defs))) single_dimension_partitions_def = next( iter( { upstream_partitions_def, downstream_partitions_def, } - set(multipartitions_defs) ) ) filtered_multipartition_dims = ( multipartitions_def.partitions_defs if partition_dimension_name is None else [ dim for dim in multipartitions_def.partitions_defs if dim.name == partition_dimension_name ] ) if partition_dimension_name: if len(filtered_multipartition_dims) != 1: return InferSingleToMultiDimensionDepsResult( False, f"Provided partition dimension name {partition_dimension_name} not found in" f" multipartitions definition {multipartitions_def}.", ) matching_dimension_defs = [ dimension_def for dimension_def in filtered_multipartition_dims if dimension_def.partitions_def == single_dimension_partitions_def ] if len(matching_dimension_defs) == 1: return InferSingleToMultiDimensionDepsResult( True, dimension_dependency=DimensionDependency( IdentityPartitionMapping(), upstream_dimension_name=( matching_dimension_defs[0].name if upstream_is_multipartitioned else None ), downstream_dimension_name=( matching_dimension_defs[0].name if not upstream_is_multipartitioned else None ), ), ) elif len(matching_dimension_defs) > 1: return InferSingleToMultiDimensionDepsResult( False, "partition dimension name must be specified when multiple dimensions of the" " MultiPartitionsDefinition match the single dimension partitions def", ) time_dimensions = [ dimension_def for dimension_def in filtered_multipartition_dims if isinstance(dimension_def.partitions_def, TimeWindowPartitionsDefinition) ] if len(time_dimensions) == 1 and isinstance( single_dimension_partitions_def, TimeWindowPartitionsDefinition ): return InferSingleToMultiDimensionDepsResult( True, dimension_dependency=DimensionDependency( TimeWindowPartitionMapping(), upstream_dimension_name=( time_dimensions[0].name if upstream_is_multipartitioned else None ), downstream_dimension_name=( time_dimensions[0].name if not upstream_is_multipartitioned else None ), ), ) return InferSingleToMultiDimensionDepsResult( False, "MultiToSingleDimensionPartitionMapping can only be used when: \n(a) The single dimensional" " partitions definition is a dimension of the MultiPartitionsDefinition.\n(b) The single" " dimensional partitions definition is a TimeWindowPartitionsDefinition and the" " MultiPartitionsDefinition has a single time dimension.", ) @public @beta @whitelist_for_serdes
InferSingleToMultiDimensionDepsResult
python
google__pytype
pytype/typegraph/typegraph_serializer.py
{ "start": 1545, "end": 1656 }
class ____: node: CFGNodeId depth: int bindings: list[BindingId] @dataclasses.dataclass
SerializedQueryStep
python
tensorflow__tensorflow
tensorflow/python/distribute/multi_worker_util_test.py
{ "start": 2635, "end": 3889 }
class ____(test.TestCase): def testClusterWithChief(self): cluster_spec = { "chief": ["127.0.0.1:1234"], "worker": ["127.0.0.1:8964", "127.0.0.1:2333"], "ps": ["127.0.0.1:1926", "127.0.0.1:3141"] } self.assertTrue(multi_worker_util.is_chief(cluster_spec, "chief", 0)) self.assertFalse(multi_worker_util.is_chief(cluster_spec, "worker", 0)) def testClusterWithoutChief(self): cluster_spec = {"worker": ["127.0.0.1:8964", "127.0.0.1:2333"]} self.assertTrue(multi_worker_util.is_chief(cluster_spec, "worker", 0)) self.assertFalse(multi_worker_util.is_chief(cluster_spec, "worker", 1)) with self.assertRaisesRegex( ValueError, "`task_type` 'chief' not found in cluster_spec."): multi_worker_util.is_chief(cluster_spec, "chief", 0) with self.assertRaisesRegex( ValueError, "The `task_id` 2 exceeds the maximum id of worker."): multi_worker_util.is_chief(cluster_spec, "worker", 2) def testEvaluatorIsChief(self): cluster_spec = { "chief": ["127.0.0.1:1234"], "worker": ["127.0.0.1:8964", "127.0.0.1:2333"], "evaluator": ["127.0.0.1:2019"] } self.assertTrue(multi_worker_util.is_chief(cluster_spec, "evaluator", 0))
IsChiefTest
python
sqlalchemy__sqlalchemy
test/orm/test_backref_mutations.py
{ "start": 25256, "end": 26274 }
class ____(_fixtures.FixtureTest): run_inserts = None @classmethod def setup_mappers(cls): keywords, items, item_keywords, Keyword, Item = ( cls.tables.keywords, cls.tables.items, cls.tables.item_keywords, cls.classes.Keyword, cls.classes.Item, ) cls.mapper_registry.map_imperatively( Item, items, properties={ "keywords": relationship( Keyword, secondary=item_keywords, backref="items" ) }, ) cls.mapper_registry.map_imperatively(Keyword, keywords) def test_backref_pop_m2m(self): Keyword, Item = self.classes.Keyword, self.classes.Item k1 = Keyword() k2 = Keyword() i1 = Item() k1.items.append(i1) k2.items.append(i1) k2.items.append(i1) i1.keywords = [] k2.items.remove(i1) assert len(k2.items) == 0
M2MStaleBackrefTest
python
Textualize__textual
tests/test_pilot.py
{ "start": 584, "end": 923 }
class ____(App): CSS = """ # Ensure the button is 16 x 3 Button { min-width: 16; max-width: 16; width: 16; min-height: 3; max-height: 3; height: 3; } """ def compose(self): with Center(): with Middle(): yield Button()
CenteredButtonApp
python
protocolbuffers__protobuf
python/google/protobuf/internal/reflection_cpp_test.py
{ "start": 709, "end": 1079 }
class ____(unittest.TestCase): def testEmptyCompositeContainerDeepCopy(self, message_module): proto1 = message_module.NestedTestAllTypes( payload=message_module.TestAllTypes(optional_string='foo') ) nested2 = copy.deepcopy(proto1.child.repeated_child) self.assertEqual(0, len(nested2)) if __name__ == '__main__': unittest.main()
ReflectionTest
python
keras-team__keras
keras/src/trainers/epoch_iterator_test.py
{ "start": 250, "end": 7849 }
class ____(testing.TestCase): @parameterized.named_parameters( [("iterator", "iterator"), ("enumerate_epoch", "enumerate_epoch")] ) def test_basic_flow(self, call_type): x = np.random.random((100, 16)) y = np.random.random((100, 4)) sample_weight = np.random.random((100,)) batch_size = 16 shuffle = True iterator = epoch_iterator.EpochIterator( x=x, y=y, sample_weight=sample_weight, batch_size=batch_size, shuffle=shuffle, ) steps_seen = [] if call_type == "iterator": generator = iterator else: generator = iterator.enumerate_epoch() for begin_step, end_step, batch in generator: batch = batch[0] steps_seen.append(begin_step) self.assertEqual(begin_step, end_step) self.assertEqual(len(batch), 3) self.assertIsInstance(batch[0], np.ndarray) self.assertEqual(steps_seen, [0, 1, 2, 3, 4, 5, 6]) def test_insufficient_data(self): batch_size = 8 steps_per_epoch = 6 dataset_size = batch_size * (steps_per_epoch - 2) x = np.arange(dataset_size).reshape((dataset_size, 1)) y = x * 2 iterator = epoch_iterator.EpochIterator( x=x, y=y, batch_size=batch_size, steps_per_epoch=steps_per_epoch, ) steps_seen = [] with pytest.warns(match="Your input ran out of data"): for step, _, _ in iterator: steps_seen.append(step) self.assertLen(steps_seen, steps_per_epoch - 2) self.assertIsInstance(iterator, epoch_iterator.EpochIterator) def test_unsupported_y_arg_tfdata(self): with self.assertRaisesRegex(ValueError, "`y` should not be passed"): x = tf.data.Dataset.from_tensor_slices(np.random.random((100, 16))) y = np.random.random((100, 4)) _ = epoch_iterator.EpochIterator(x=x, y=y) def test_unsupported_sample_weights_arg_tfdata(self): with self.assertRaisesRegex( ValueError, "`sample_weights` should not be passed" ): x = tf.data.Dataset.from_tensor_slices(np.random.random((100, 16))) sample_weights = np.random.random((100,)) _ = epoch_iterator.EpochIterator(x=x, sample_weight=sample_weights) @pytest.mark.skipif( backend.backend() != "torch", reason="Need to import torch" ) def test_torch_dataloader(self): import torch class ExampleTorchDataset(torch.utils.data.Dataset): def __init__(self, x, y): self.x = x self.y = y def __len__(self): return len(self.x) def __getitem__(self, idx): return self.x[idx], self.y[idx] torch_dataset = ExampleTorchDataset( np.random.random((64, 2)), np.random.random((64, 1)) ) torch_dataloader = torch.utils.data.DataLoader( torch_dataset, batch_size=8, shuffle=True ) iterator = epoch_iterator.EpochIterator(torch_dataloader) for _, _, batch in iterator: batch = batch[0] self.assertEqual(batch[0].shape, (8, 2)) self.assertEqual(batch[1].shape, (8, 1)) @pytest.mark.skipif( backend.backend() != "torch", reason="Need to import torch" ) def test_unsupported_y_arg_torch_dataloader(self): import torch class ExampleTorchDataset(torch.utils.data.Dataset): def __init__(self, x, y): self.x = x self.y = y def __len__(self): return len(self.x) def __getitem__(self, idx): return self.x[idx], self.y[idx] torch_dataset = ExampleTorchDataset( np.random.random((100, 16)), np.random.random((100, 4)) ) x = torch.utils.data.DataLoader( torch_dataset, batch_size=8, shuffle=True ) y = np.random.random((100, 4)) with self.assertRaisesRegex( ValueError, "When providing `x` as a torch DataLoader, `y` should not", ): _ = epoch_iterator.EpochIterator(x=x, y=y) @pytest.mark.skipif( backend.backend() != "torch", reason="Need to import torch" ) def test_unsupported_sample_weights_arg_torch_dataloader(self): import torch class ExampleTorchDataset(torch.utils.data.Dataset): def __init__(self, x, y): self.x = x self.y = y def __len__(self): return len(self.x) def __getitem__(self, idx): return self.x[idx], self.y[idx] torch_dataset = ExampleTorchDataset( np.random.random((100, 16)), np.random.random((100, 4)) ) x = torch.utils.data.DataLoader( torch_dataset, batch_size=8, shuffle=True ) sample_weights = np.random.random((100,)) with self.assertRaisesRegex( ValueError, "When providing `x` as a torch DataLoader, `sample_weights`", ): _ = epoch_iterator.EpochIterator(x=x, sample_weight=sample_weights) def test_python_generator_input(self): def generator_example(): for i in range(100): yield (np.array([i]), np.array([i * 2])) x = generator_example() epoch_iter = epoch_iterator.EpochIterator(x=x) self.assertIsInstance( epoch_iter.data_adapter, data_adapters.GeneratorDataAdapter, ) def test_unrecognized_data_type(self): x = "unsupported_data" with self.assertRaisesRegex(ValueError, "Unrecognized data type"): _ = epoch_iterator.EpochIterator(x=x) @parameterized.named_parameters( [ {"testcase_name": "infinite", "infinite": True}, {"testcase_name": "finite", "infinite": False}, ] ) def test_epoch_callbacks(self, infinite): class TestPyDataset(data_adapters.py_dataset_adapter.PyDataset): def __init__( self, workers=1, use_multiprocessing=False, max_queue_size=10, infinite=False, ): super().__init__(workers, use_multiprocessing, max_queue_size) self.data = np.random.rand(64, 2) self.batch_size = 16 self.infinite = infinite # check that callbacks are called in the correct order self.tracker = [] @property def num_batches(self): if self.infinite: return None return len(self.data) // self.batch_size def on_epoch_begin(self): self.tracker.append(1) def __getitem__(self, index): idx = index % 2 return self.data[ idx * self.batch_size : (idx + 1) * self.batch_size ] def on_epoch_end(self): self.tracker.append(2) ds = TestPyDataset(infinite=infinite) epoch_iter = epoch_iterator.EpochIterator(x=ds, steps_per_epoch=10) num_epochs = 5 for epoch in range(num_epochs): for _, _, _ in epoch_iter: pass self.assertAllEqual(ds.tracker, [1, 2] * num_epochs)
TestEpochIterator
python
walkccc__LeetCode
solutions/1472. Design Browser History/1472-3.py
{ "start": 0, "end": 107 }
class ____: def __init__(self, url: str): self.prev = None self.next = None self.url = url
Node
python
ray-project__ray
python/ray/util/collective/types.py
{ "start": 1842, "end": 2358 }
class ____(TensorTransportMetadata): """Metadata for tensors stored in the GPU object store for NIXL transport. Args: nixl_serialized_descs: Serialized tensor descriptors for NIXL transport. nixl_agent_meta: The additional metadata of the remote NIXL agent. """ nixl_reg_descs: Optional[Any] = None nixl_serialized_descs: Optional[bytes] = None nixl_agent_meta: Optional[bytes] = None __eq__ = object.__eq__ __hash__ = object.__hash__ @dataclass
NixlTransportMetadata
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 575427, "end": 575946 }
class ____(sgqlc.types.Type): """Autogenerated return type of DequeuePullRequest""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "merge_queue_entry") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation.""" merge_queue_entry = sgqlc.types.Field("MergeQueueEntry", graphql_name="mergeQueueEntry") """The merge queue entry of the dequeued pull request."""
DequeuePullRequestPayload
python
apache__airflow
airflow-core/tests/unit/ti_deps/deps/test_runnable_exec_date_dep.py
{ "start": 2644, "end": 4179 }
class ____: def _get_task_instance(self, logical_date, dag_end_date=None, task_end_date=None): dag = Mock(end_date=dag_end_date) dagrun = Mock(logical_date=logical_date) task = Mock(dag=dag, end_date=task_end_date) return Mock(task=task, get_dagrun=Mock(return_value=dagrun)) def test_logical_date_after_task_end_date(self): """ If the task instance logical date is after the tasks end date this dep should fail """ ti = self._get_task_instance( dag_end_date=datetime(2016, 1, 3), task_end_date=datetime(2016, 1, 1), logical_date=datetime(2016, 1, 2), ) assert not RunnableExecDateDep().is_met(ti=ti) def test_exec_date_after_dag_end_date(self): """ If the task instance logical date is after the dag's end date this dep should fail """ ti = self._get_task_instance( dag_end_date=datetime(2016, 1, 1), task_end_date=datetime(2016, 1, 3), logical_date=datetime(2016, 1, 2), ) assert not RunnableExecDateDep().is_met(ti=ti) def test_all_deps_met(self): """ Test to make sure all the conditions for the dep are met """ ti = self._get_task_instance( dag_end_date=datetime(2016, 1, 2), task_end_date=datetime(2016, 1, 2), logical_date=datetime(2016, 1, 1), ) assert RunnableExecDateDep().is_met(ti=ti)
TestRunnableExecDateDep
python
google__pytype
pytype/matcher.py
{ "start": 2799, "end": 4659 }
class ____: """A collection of matches that discards duplicates.""" def __init__(self, node, keep_all_views): self._node = node self._keep_all_views = keep_all_views self._data: dict[ _ViewKeyType, list[tuple[_SubstKeyType, _ViewType, _SubstType]] ] = collections.defaultdict(list) def insert(self, view, subst): """Insert a subst with associated data.""" if self._keep_all_views: view_key = tuple( sorted( (k.id, v.data.get_type_key()) for k, v in view.accessed_subset.items() ) ) else: view_key = () subst_key = { k: {v.get_type_key() for v in var.data} for k, var in subst.items() } data_item = (subst_key, view, subst) for i, prev_data_item in enumerate(self._data[view_key]): prev_subst_key, prev_view, prev_subst = prev_data_item cur_is_superset, prev_is_superset = _compute_superset_info( subst_key, prev_subst_key ) if prev_is_superset: # A previous substitution is a superset of this one, so we do not need # to keep this one. We do copy over the view and origins. prev_view.update(view) for k, v in subst.items(): prev_subst[k].PasteVariable(v) break if cur_is_superset: # This substitution is a superset of a previous one, so we replace the # previous subst with this one. We do copy over the view and origins. self._data[view_key][i] = data_item view.update(prev_view) for k, v in prev_subst.items(): subst[k].PasteVariable(v) break else: self._data[view_key].append(data_item) def unique(self) -> Iterable[tuple[_ViewType, _SubstType]]: for values in self._data.values(): for _, view, subst in values: yield (view, subst)
_UniqueMatches
python
scikit-learn__scikit-learn
sklearn/utils/tests/test_estimator_checks.py
{ "start": 5774, "end": 6179 }
class ____(BaseEstimator): def __init__(self, p=0): self.p = p def set_params(self, **kwargs): if "p" in kwargs: p = kwargs.pop("p") if p < 0: p = 0 self.p = p return super().set_params(**kwargs) def fit(self, X, y=None): X, y = validate_data(self, X, y) return self
ModifiesValueInsteadOfRaisingError
python
vyperlang__vyper
vyper/ast/nodes.py
{ "start": 43301, "end": 43340 }
class ____(Stmt): __slots__ = ()
Pass
python
kamyu104__LeetCode-Solutions
Python/soup-servings.py
{ "start": 29, "end": 794 }
class ____(object): def soupServings(self, N): """ :type N: int :rtype: float """ def dp(a, b, lookup): if (a, b) in lookup: return lookup[a, b] if a <= 0 and b <= 0: return 0.5 if a <= 0: return 1.0 if b <= 0: return 0.0 lookup[a, b] = 0.25 * (dp(a-4, b, lookup) + dp(a-3, b-1, lookup) + dp(a-2, b-2, lookup) + dp(a-1, b-3, lookup)) return lookup[a, b] if N >= 4800: return 1.0 lookup = {} N = (N+24)//25 return dp(N, N, lookup)
Solution
python
pypa__pipenv
pipenv/vendor/click/types.py
{ "start": 19490, "end": 20103 }
class ____(ParamType): name = "boolean" def convert( self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"] ) -> t.Any: if value in {False, True}: return bool(value) norm = value.strip().lower() if norm in {"1", "true", "t", "yes", "y", "on"}: return True if norm in {"0", "false", "f", "no", "n", "off"}: return False self.fail( _("{value!r} is not a valid boolean.").format(value=value), param, ctx ) def __repr__(self) -> str: return "BOOL"
BoolParamType
python
huggingface__transformers
src/transformers/models/mask2former/convert_mask2former_original_pytorch_checkpoint_to_pytorch.py
{ "start": 3235, "end": 7254 }
class ____: def __call__(self, original_config: object) -> Mask2FormerConfig: model = original_config.MODEL repo_id = "huggingface/label-files" if model.SEM_SEG_HEAD.NUM_CLASSES == 847: filename = "mask2former-ade20k-full-id2label.json" elif model.SEM_SEG_HEAD.NUM_CLASSES == 150: filename = "ade20k-id2label.json" elif model.SEM_SEG_HEAD.NUM_CLASSES == 80: filename = "coco-detection-mmdet-id2label.json" elif model.SEM_SEG_HEAD.NUM_CLASSES == 171: filename = "mask2former-coco-stuff-id2label.json" elif model.SEM_SEG_HEAD.NUM_CLASSES == 133: filename = "coco-panoptic-id2label.json" elif model.SEM_SEG_HEAD.NUM_CLASSES == 19: filename = "cityscapes-id2label.json" elif model.SEM_SEG_HEAD.NUM_CLASSES == 8: filename = "cityscapes-instance-id2label.json" elif model.SEM_SEG_HEAD.NUM_CLASSES == 65: filename = "mapillary-vistas-id2label.json" id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r")) id2label = {int(k): v for k, v in id2label.items()} label2id = {label: idx for idx, label in id2label.items()} if model.SWIN.EMBED_DIM == 96: backbone_config = SwinConfig.from_pretrained( "microsoft/swin-tiny-patch4-window7-224", out_features=["stage1", "stage2", "stage3", "stage4"] ) elif model.SWIN.EMBED_DIM == 128: backbone_config = SwinConfig( embed_dim=128, window_size=12, depths=(2, 2, 18, 2), num_heads=(4, 8, 16, 32), out_features=["stage1", "stage2", "stage3", "stage4"], ) elif model.SWIN.EMBED_DIM == 192: backbone_config = SwinConfig.from_pretrained( "microsoft/swin-large-patch4-window12-384", out_features=["stage1", "stage2", "stage3", "stage4"] ) else: raise ValueError(f"embed dim {model.SWIN.EMBED_DIM} not supported for Swin!") backbone_config.drop_path_rate = model.SWIN.DROP_PATH_RATE backbone_config.attention_probs_dropout_prob = model.SWIN.ATTN_DROP_RATE backbone_config.depths = model.SWIN.DEPTHS config: Mask2FormerConfig = Mask2FormerConfig( ignore_value=model.SEM_SEG_HEAD.IGNORE_VALUE, num_labels=model.SEM_SEG_HEAD.NUM_CLASSES, num_queries=model.MASK_FORMER.NUM_OBJECT_QUERIES, no_object_weight=model.MASK_FORMER.NO_OBJECT_WEIGHT, class_weight=model.MASK_FORMER.CLASS_WEIGHT, mask_weight=model.MASK_FORMER.MASK_WEIGHT, dice_weight=model.MASK_FORMER.DICE_WEIGHT, train_num_points=model.MASK_FORMER.TRAIN_NUM_POINTS, oversample_ratio=model.MASK_FORMER.OVERSAMPLE_RATIO, importance_sample_ratio=model.MASK_FORMER.IMPORTANCE_SAMPLE_RATIO, init_std=0.02, init_xavier_std=1.0, use_auxiliary_loss=model.MASK_FORMER.DEEP_SUPERVISION, feature_strides=[4, 8, 16, 32], backbone_config=backbone_config, id2label=id2label, label2id=label2id, feature_size=model.SEM_SEG_HEAD.CONVS_DIM, mask_feature_size=model.SEM_SEG_HEAD.MASK_DIM, hidden_dim=model.MASK_FORMER.HIDDEN_DIM, encoder_layers=model.SEM_SEG_HEAD.TRANSFORMER_ENC_LAYERS, encoder_feedforward_dim=1024, decoder_layers=model.MASK_FORMER.DEC_LAYERS, num_attention_heads=model.MASK_FORMER.NHEADS, dropout=model.MASK_FORMER.DROPOUT, dim_feedforward=model.MASK_FORMER.DIM_FEEDFORWARD, pre_norm=model.MASK_FORMER.PRE_NORM, enforce_input_proj=model.MASK_FORMER.ENFORCE_INPUT_PROJ, common_stride=model.SEM_SEG_HEAD.COMMON_STRIDE, ) return config
OriginalMask2FormerConfigToOursConverter
python
dask__distributed
distributed/scheduler.py
{ "start": 339659, "end": 341555 }
class ____(SchedulerPlugin): scheduler: Scheduler name: str keys: set[Key] metadata: dict[Key, Any] state: dict[Key, TaskStateState] def __init__(self, scheduler: Scheduler, name: str): self.scheduler = scheduler self.name = name self.keys = set() self.metadata = {} self.state = {} def update_graph( self, scheduler: Scheduler, *, keys: set[Key], **kwargs: Any, ) -> None: self.keys.update(keys) def transition( self, key: Key, start: TaskStateState, finish: TaskStateState, *args: Any, **kwargs: Any, ) -> None: if finish in ("memory", "erred"): ts = self.scheduler.tasks.get(key) if ts is not None and ts.key in self.keys: self.metadata[key] = ts.metadata self.state[key] = finish self.keys.discard(key) def _materialize_graph( expr: Expr, validate: bool, ) -> tuple[dict[Key, T_runspec], dict[str, dict[Key, Any]]]: dsk: dict = expr.__dask_graph__() if validate: for k in dsk: validate_key(k) annotations_by_type: defaultdict[str, dict[Key, Any]] = defaultdict(dict) for annotations_type, value in expr.__dask_annotations__().items(): annotations_by_type[annotations_type].update(value) dsk2 = convert_legacy_graph(dsk) return dsk2, annotations_by_type def _cull(dsk: dict[Key, GraphNode], keys: set[Key]) -> dict[Key, GraphNode]: work = set(keys) seen: set[Key] = set() dsk2 = {} wpop = work.pop wupdate = work.update sadd = seen.add while work: k = wpop() if k in seen or k not in dsk: continue sadd(k) dsk2[k] = v = dsk[k] wupdate(v.dependencies) return dsk2
CollectTaskMetaDataPlugin
python
mlflow__mlflow
mlflow/gateway/uc_function_utils.py
{ "start": 3980, "end": 10209 }
class ____: """ Result of executing a function. We always use a string to present the result value for AI model to consume. """ error: str | None = None format: Literal["SCALAR", "CSV"] | None = None value: str | None = None truncated: bool | None = None def to_json(self) -> str: data = {k: v for (k, v) in self.__dict__.items() if v is not None} return json.dumps(data) def is_scalar(function: "FunctionInfo") -> bool: """ Returns True if the function returns a single row instead of a table. """ from databricks.sdk.service.catalog import ColumnTypeName return function.data_type != ColumnTypeName.TABLE_TYPE def get_execute_function_sql_stmt( function: "FunctionInfo", json_params: dict[str, Any], ) -> ParameterizedStatement: from databricks.sdk.service.catalog import ColumnTypeName from databricks.sdk.service.sql import StatementParameterListItem parts = [] output_params = [] if is_scalar(function): parts.append(f"SELECT {function.full_name}(") else: parts.append(f"SELECT * FROM {function.full_name}(") if function.input_params is None or function.input_params.parameters is None: assert not json_params, "Function has no parameters but parameters were provided." else: args = [] use_named_args = False for p in function.input_params.parameters: if p.name not in json_params: if p.parameter_default is not None: use_named_args = True else: raise ValueError(f"Parameter {p.name} is required but not provided.") else: arg_clause = "" if use_named_args: arg_clause += f"{p.name} => " json_value = json_params[p.name] if p.type_name in ( ColumnTypeName.ARRAY, ColumnTypeName.MAP, ColumnTypeName.STRUCT, ): # Use from_json to restore values of complex types. json_value_str = json.dumps(json_value) # TODO: parametrize type arg_clause += f"from_json(:{p.name}, '{p.type_text}')" output_params.append( StatementParameterListItem(name=p.name, value=json_value_str) ) elif p.type_name == ColumnTypeName.BINARY: # Use ubbase64 to restore binary values. arg_clause += f"unbase64(:{p.name})" output_params.append(StatementParameterListItem(name=p.name, value=json_value)) else: arg_clause += f":{p.name}" output_params.append( StatementParameterListItem(name=p.name, value=json_value, type=p.type_text) ) args.append(arg_clause) parts.append(",".join(args)) parts.append(")") # TODO: check extra params in kwargs statement = "".join(parts) return ParameterizedStatement(statement=statement, parameters=output_params) def execute_function( ws: "WorkspaceClient", warehouse_id: str, function: "FunctionInfo", parameters: dict[str, Any], ) -> FunctionExecutionResult: """ Execute a function with the given arguments and return the result. """ try: import pandas as pd except ImportError as e: raise ImportError( "Could not import pandas python package. Please install it with `pip install pandas`." ) from e from databricks.sdk.service.sql import StatementState # TODO: async so we can run functions in parallel parameterized_statement = get_execute_function_sql_stmt(function, parameters) # TODO: make limits and wait timeout configurable response = ws.statement_execution.execute_statement( statement=parameterized_statement.statement, warehouse_id=warehouse_id, parameters=parameterized_statement.parameters, wait_timeout="30s", row_limit=100, byte_limit=4096, ) status = response.status assert status is not None, f"Statement execution failed: {response}" if status.state != StatementState.SUCCEEDED: error = status.error assert error is not None, "Statement execution failed but no error message was provided." return FunctionExecutionResult(error=f"{error.error_code}: {error.message}") manifest = response.manifest assert manifest is not None truncated = manifest.truncated result = response.result assert result is not None, "Statement execution succeeded but no result was provided." data_array = result.data_array if is_scalar(function): value = None if data_array and len(data_array) > 0 and len(data_array[0]) > 0: value = str(data_array[0][0]) # type: ignore return FunctionExecutionResult(format="SCALAR", value=value, truncated=truncated) else: schema = manifest.schema assert schema is not None and schema.columns is not None, ( "Statement execution succeeded but no schema was provided." ) columns = [c.name for c in schema.columns] if data_array is None: data_array = [] pdf = pd.DataFrame.from_records(data_array, columns=columns) csv_buffer = StringIO() pdf.to_csv(csv_buffer, index=False) return FunctionExecutionResult( format="CSV", value=csv_buffer.getvalue(), truncated=truncated ) def join_uc_functions(uc_functions: list[dict[str, Any]]): calls = [ f""" <uc_function_call> {json.dumps(request, indent=2)} </uc_function_call> <uc_function_result> {json.dumps(result, indent=2)} </uc_function_result> """.strip() for (request, result) in uc_functions ] return "\n\n".join(calls) def _get_tool_name(function: "FunctionInfo") -> str: # The maximum function name length OpenAI supports is 64 characters. return f"{function.catalog_name}__{function.schema_name}__{function.name}"[-64:] @dataclass
FunctionExecutionResult
python
doocs__leetcode
solution/2500-2599/2560.House Robber IV/Solution.py
{ "start": 0, "end": 370 }
class ____: def minCapability(self, nums: List[int], k: int) -> int: def f(x): cnt, j = 0, -2 for i, v in enumerate(nums): if v > x or i == j + 1: continue cnt += 1 j = i return cnt >= k return bisect_left(range(max(nums) + 1), True, key=f)
Solution
python
getsentry__sentry
tests/sentry/preprod/api/endpoints/test_project_preprod_artifact_download.py
{ "start": 345, "end": 8248 }
class ____(TestCase): def setUp(self) -> None: super().setUp() # Create a test file self.file = self.create_file( name="test_artifact.apk", type="application/octet-stream", ) self.file.putfile(BytesIO(b"test content for original file")) # Create a preprod artifact self.preprod_artifact = PreprodArtifact.objects.create( project=self.project, file_id=self.file.id, state=PreprodArtifact.ArtifactState.PROCESSED, artifact_type=PreprodArtifact.ArtifactType.APK, ) def _get_authenticated_request_headers(self, path, data=b""): """Generate the RPC signature authentication headers for the request.""" signature = generate_service_request_signature(path, data, ["test-secret-key"], "Launchpad") return {"HTTP_AUTHORIZATION": f"rpcsignature {signature}"} @override_settings(LAUNCHPAD_RPC_SHARED_SECRET=["test-secret-key"]) def test_download_preprod_artifact_success(self) -> None: url = f"/api/0/internal/{self.organization.slug}/{self.project.slug}/files/preprodartifacts/{self.preprod_artifact.id}/" headers = self._get_authenticated_request_headers(url) response = self.client.get(url, **headers) assert response.status_code == 200 assert response["Content-Type"] == "application/octet-stream" assert "attachment" in response["Content-Disposition"] close_streaming_response(response) @override_settings(LAUNCHPAD_RPC_SHARED_SECRET=["test-secret-key"]) def test_download_preprod_artifact_not_found(self) -> None: url = f"/api/0/internal/{self.organization.slug}/{self.project.slug}/files/preprodartifacts/999999/" headers = self._get_authenticated_request_headers(url) response = self.client.get(url, **headers) assert response.status_code == 404 assert "The requested head preprod artifact does not exist" in response.json()["detail"] @override_settings(LAUNCHPAD_RPC_SHARED_SECRET=["test-secret-key"]) def test_download_preprod_artifact_no_file(self) -> None: # Create an artifact without a file no_file_artifact = PreprodArtifact.objects.create( project=self.project, file_id=None, state=PreprodArtifact.ArtifactState.PROCESSED, ) url = f"/api/0/internal/{self.organization.slug}/{self.project.slug}/files/preprodartifacts/{no_file_artifact.id}/" headers = self._get_authenticated_request_headers(url) with self.feature("organizations:preprod-frontend-routes"): response = self.client.get(url, **headers) assert response.status_code == 404 assert response.json()["detail"] == "The requested resource does not exist" @override_settings(LAUNCHPAD_RPC_SHARED_SECRET=["test-secret-key"]) def test_head_preprod_artifact_success(self) -> None: url = f"/api/0/internal/{self.organization.slug}/{self.project.slug}/files/preprodartifacts/{self.preprod_artifact.id}/" headers = self._get_authenticated_request_headers(url) response = self.client.head(url, **headers) assert response.status_code == 200 assert response["Content-Type"] == "application/octet-stream" assert response["Content-Length"] == str(self.file.size) assert response["Accept-Ranges"] == "bytes" assert "attachment" in response["Content-Disposition"] assert not response.content @override_settings(LAUNCHPAD_RPC_SHARED_SECRET=["test-secret-key"]) def test_download_preprod_artifact_with_range_suffix(self) -> None: test_content = b"0123456789" * 100 file_obj = File.objects.create( name="test_range.bin", type="application/octet-stream", ) file_obj.putfile(BytesIO(test_content)) artifact = PreprodArtifact.objects.create( project=self.project, file_id=file_obj.id, state=PreprodArtifact.ArtifactState.PROCESSED, artifact_type=PreprodArtifact.ArtifactType.APK, ) url = f"/api/0/internal/{self.organization.slug}/{self.project.slug}/files/preprodartifacts/{artifact.id}/" headers = self._get_authenticated_request_headers(url) response = self.client.get(url, HTTP_RANGE="bytes=-10", **headers) assert response.status_code == 206 assert response.content == test_content[-10:] assert response["Content-Length"] == "10" assert ( response["Content-Range"] == f"bytes {len(test_content)-10}-{len(test_content)-1}/{len(test_content)}" ) @override_settings(LAUNCHPAD_RPC_SHARED_SECRET=["test-secret-key"]) def test_download_preprod_artifact_with_range_bounded(self) -> None: test_content = b"0123456789" * 100 file_obj = File.objects.create( name="test_range.bin", type="application/octet-stream", ) file_obj.putfile(BytesIO(test_content)) artifact = PreprodArtifact.objects.create( project=self.project, file_id=file_obj.id, state=PreprodArtifact.ArtifactState.PROCESSED, artifact_type=PreprodArtifact.ArtifactType.APK, ) url = f"/api/0/internal/{self.organization.slug}/{self.project.slug}/files/preprodartifacts/{artifact.id}/" headers = self._get_authenticated_request_headers(url) response = self.client.get(url, HTTP_RANGE="bytes=5-14", **headers) assert response.status_code == 206 assert response.content == test_content[5:15] assert response["Content-Length"] == "10" assert response["Content-Range"] == f"bytes 5-14/{len(test_content)}" @override_settings(LAUNCHPAD_RPC_SHARED_SECRET=["test-secret-key"]) def test_download_preprod_artifact_with_range_unbounded(self) -> None: test_content = b"0123456789" * 100 file_obj = File.objects.create( name="test_range.bin", type="application/octet-stream", ) file_obj.putfile(BytesIO(test_content)) artifact = PreprodArtifact.objects.create( project=self.project, file_id=file_obj.id, state=PreprodArtifact.ArtifactState.PROCESSED, artifact_type=PreprodArtifact.ArtifactType.APK, ) url = f"/api/0/internal/{self.organization.slug}/{self.project.slug}/files/preprodartifacts/{artifact.id}/" headers = self._get_authenticated_request_headers(url) response = self.client.get(url, HTTP_RANGE="bytes=990-", **headers) assert response.status_code == 206 assert response.content == test_content[990:] assert response["Content-Length"] == "10" assert response["Content-Range"] == f"bytes 990-{len(test_content)-1}/{len(test_content)}" @override_settings(LAUNCHPAD_RPC_SHARED_SECRET=["test-secret-key"]) def test_download_preprod_artifact_with_invalid_range(self) -> None: url = f"/api/0/internal/{self.organization.slug}/{self.project.slug}/files/preprodartifacts/{self.preprod_artifact.id}/" headers = self._get_authenticated_request_headers(url) response = self.client.get(url, HTTP_RANGE="bytes=1000-2000", **headers) assert response.status_code == 416 @override_settings(LAUNCHPAD_RPC_SHARED_SECRET=["test-secret-key"]) def test_download_preprod_artifact_with_malformed_range(self) -> None: url = f"/api/0/internal/{self.organization.slug}/{self.project.slug}/files/preprodartifacts/{self.preprod_artifact.id}/" headers = self._get_authenticated_request_headers(url) response = self.client.get(url, HTTP_RANGE="invalid-range-header", **headers) assert response.status_code == 416
ProjectPreprodArtifactDownloadEndpointTest
python
dask__dask
dask/array/_array_expr/_ufunc.py
{ "start": 2257, "end": 8470 }
class ____: _forward_attrs = { "nin", "nargs", "nout", "ntypes", "identity", "signature", "types", } def __init__(self, ufunc): if not isinstance(ufunc, (np.ufunc, da_frompyfunc)): raise TypeError( "must be an instance of `ufunc` or " f"`da_frompyfunc`, got `{type(ufunc).__name__}" ) self._ufunc = ufunc self.__name__ = ufunc.__name__ if isinstance(ufunc, np.ufunc): derived_from(np)(self) def __dask_tokenize__(self): return self.__name__, normalize_token(self._ufunc) def __getattr__(self, key): if key in self._forward_attrs: return getattr(self._ufunc, key) raise AttributeError(f"{type(self).__name__!r} object has no attribute {key!r}") def __dir__(self): return list(self._forward_attrs.union(dir(type(self)), self.__dict__)) def __repr__(self): return repr(self._ufunc) def __call__(self, *args, **kwargs): dsks = [arg for arg in args if hasattr(arg, "_elemwise")] if len(dsks) > 0: for dsk in dsks: result = dsk._elemwise(self._ufunc, *args, **kwargs) if type(result) != type(NotImplemented): return result raise TypeError( f"Parameters of such types are not supported by {self.__name__}" ) else: return self._ufunc(*args, **kwargs) @derived_from(np.ufunc) def outer(self, A, B, **kwargs): if self.nin != 2: raise ValueError("outer product only supported for binary functions") if "out" in kwargs: raise ValueError("`out` kwarg not supported") A_is_dask = is_dask_collection(A) B_is_dask = is_dask_collection(B) if not A_is_dask and not B_is_dask: return self._ufunc.outer(A, B, **kwargs) elif ( A_is_dask and not isinstance(A, Array) or B_is_dask and not isinstance(B, Array) ): raise NotImplementedError( "Dask objects besides `dask.array.Array` " "are not supported at this time." ) A = asarray(A) B = asarray(B) ndim = A.ndim + B.ndim out_inds = tuple(range(ndim)) A_inds = out_inds[: A.ndim] B_inds = out_inds[A.ndim :] dtype = apply_infer_dtype( self._ufunc.outer, [A, B], kwargs, "ufunc.outer", suggest_dtype=False ) if "dtype" in kwargs: func = partial(self._ufunc.outer, dtype=kwargs.pop("dtype")) else: func = self._ufunc.outer return blockwise( func, out_inds, A, A_inds, B, B_inds, dtype=dtype, name=self.__name__ + ".outer-" + _tokenize_deterministic(self._ufunc), **kwargs, ) # ufuncs, copied from this page: # https://docs.scipy.org/doc/numpy/reference/ufuncs.html # math operations add = ufunc(np.add) subtract = ufunc(np.subtract) multiply = ufunc(np.multiply) divide = ufunc(np.divide) logaddexp = ufunc(np.logaddexp) logaddexp2 = ufunc(np.logaddexp2) true_divide = ufunc(np.true_divide) floor_divide = ufunc(np.floor_divide) negative = ufunc(np.negative) positive = ufunc(np.positive) power = ufunc(np.power) float_power = ufunc(np.float_power) remainder = ufunc(np.remainder) mod = ufunc(np.mod) # fmod: see below conj = conjugate = ufunc(np.conjugate) exp = ufunc(np.exp) exp2 = ufunc(np.exp2) log = ufunc(np.log) log2 = ufunc(np.log2) log10 = ufunc(np.log10) log1p = ufunc(np.log1p) expm1 = ufunc(np.expm1) sqrt = ufunc(np.sqrt) square = ufunc(np.square) cbrt = ufunc(np.cbrt) reciprocal = ufunc(np.reciprocal) # trigonometric functions sin = ufunc(np.sin) cos = ufunc(np.cos) tan = ufunc(np.tan) arcsin = ufunc(np.arcsin) arccos = ufunc(np.arccos) arctan = ufunc(np.arctan) arctan2 = ufunc(np.arctan2) hypot = ufunc(np.hypot) sinh = ufunc(np.sinh) cosh = ufunc(np.cosh) tanh = ufunc(np.tanh) arcsinh = ufunc(np.arcsinh) arccosh = ufunc(np.arccosh) arctanh = ufunc(np.arctanh) deg2rad = ufunc(np.deg2rad) rad2deg = ufunc(np.rad2deg) # comparison functions greater = ufunc(np.greater) greater_equal = ufunc(np.greater_equal) less = ufunc(np.less) less_equal = ufunc(np.less_equal) not_equal = ufunc(np.not_equal) equal = ufunc(np.equal) isneginf = partial(equal, -np.inf) isposinf = partial(equal, np.inf) logical_and = ufunc(np.logical_and) logical_or = ufunc(np.logical_or) logical_xor = ufunc(np.logical_xor) logical_not = ufunc(np.logical_not) maximum = ufunc(np.maximum) minimum = ufunc(np.minimum) fmax = ufunc(np.fmax) fmin = ufunc(np.fmin) # bitwise functions bitwise_and = ufunc(np.bitwise_and) bitwise_or = ufunc(np.bitwise_or) bitwise_xor = ufunc(np.bitwise_xor) bitwise_not = ufunc(np.bitwise_not) invert = bitwise_not left_shift = ufunc(np.left_shift) right_shift = ufunc(np.right_shift) # floating functions isfinite = ufunc(np.isfinite) isinf = ufunc(np.isinf) isnan = ufunc(np.isnan) signbit = ufunc(np.signbit) copysign = ufunc(np.copysign) nextafter = ufunc(np.nextafter) spacing = ufunc(np.spacing) # modf: see below ldexp = ufunc(np.ldexp) # frexp: see below fmod = ufunc(np.fmod) floor = ufunc(np.floor) ceil = ufunc(np.ceil) trunc = ufunc(np.trunc) # more math routines, from this page: # https://docs.scipy.org/doc/numpy/reference/routines.math.html degrees = ufunc(np.degrees) radians = ufunc(np.radians) rint = ufunc(np.rint) fabs = ufunc(np.fabs) sign = ufunc(np.sign) absolute = ufunc(np.absolute) abs = absolute # non-ufunc elementwise functions clip = wrap_elemwise(np.clip) isreal = wrap_elemwise(np.isreal) iscomplex = wrap_elemwise(np.iscomplex) real = wrap_elemwise(np.real) imag = wrap_elemwise(np.imag) fix = wrap_elemwise(np.fix) i0 = wrap_elemwise(np.i0) sinc = wrap_elemwise(np.sinc) nan_to_num = wrap_elemwise(np.nan_to_num) @derived_from(np) def angle(x, deg=0): deg = bool(deg) if hasattr(x, "_elemwise"): return x._elemwise(np.angle, x, deg) return np.angle(x, deg=deg)
ufunc
python
getsentry__sentry
src/sentry/search/events/builder/profiles.py
{ "start": 1279, "end": 1409 }
class ____(ProfilesQueryBuilderMixin, TimeseriesQueryBuilder): config_class = ProfilesDatasetConfig
ProfilesTimeseriesQueryBuilder
python
getsentry__sentry
fixtures/safe_migrations_apps/bad_flow_delete_field_pending_with_not_null_app/migrations/0002_delete_without_pending.py
{ "start": 190, "end": 513 }
class ____(CheckedMigration): dependencies = [ ("bad_flow_delete_field_pending_with_not_null_app", "0001_initial"), ] operations = [ SafeRemoveField( model_name="testtable", name="field", deletion_action=DeletionAction.MOVE_TO_PENDING, ), ]
Migration
python
huggingface__transformers
tests/quantization/torchao_integration/test_torchao.py
{ "start": 35955, "end": 36434 }
class ____(TorchAoSerializationTest): device = f"{torch_device}:0" # called only once for all test in this class @classmethod def setUpClass(cls): super().setUpClass() cls.quant_scheme = Int8WeightOnlyConfig() cls.quant_scheme_kwargs = {} cls.EXPECTED_OUTPUT = "What are we having for dinner?\n\nJessica: (smiling)" @require_torch_accelerator @require_torchao_version_greater_or_equal("0.10.0")
TorchAoSerializationW8AcceleratorTest
python
google__pytype
pytype/rewrite/flow/frame_base_test.py
{ "start": 1115, "end": 3709 }
class ____(unittest.TestCase): def test_one_block(self): op0 = FAKE_OP_NO_NEXT(0) code = test_utils.FakeOrderedCode([[op0]]) frame = TestFrame(code.Seal(), {}) frame.step() self.assertEqual(frame.seen_opcodes, [('FAKE_OP_NO_NEXT', 0)]) def test_two_blocks(self): op0 = FAKE_OP(0) op1 = FAKE_OP_NO_NEXT(1) op0.next = op1 code = test_utils.FakeOrderedCode([[op0], [op1]]) frame = TestFrame(code.Seal(), {}) frame.step() frame.step() self.assertEqual(frame.seen_opcodes, [('FAKE_OP', 0), ('FAKE_OP_NO_NEXT', 1)]) def test_frame_consumed(self): op0 = FAKE_OP_NO_NEXT(0) code = test_utils.FakeOrderedCode([[op0]]) frame = TestFrame(code.Seal(), {}) frame.step() with self.assertRaises(frame_base.FrameConsumedError): frame.step() def test_merge_conditions(self): c1 = FakeCondition('a') c2 = FakeCondition('b') op0 = FAKE_OP(0) op1 = FAKE_OP_NO_NEXT(1) op0.next = op1 code = test_utils.FakeOrderedCode([[op0], [op1]]) frame = TestFrame(code.Seal(), {}) frame._states[0] = state.BlockState({}, c1) frame._states[1] = state.BlockState({}, c2) frame.step() # Since FAKE_OP merges into the next op, the condition on the second block # should have been updated to (c1 or c2). condition = frame._states[1]._condition self.assertEqual(condition, conditions.Or(c1, c2)) def test_nomerge_conditions(self): c1 = FakeCondition('a') c2 = FakeCondition('b') op0 = FAKE_OP_NO_NEXT(0) op1 = FAKE_OP_NO_NEXT(1) code = test_utils.FakeOrderedCode([[op0], [op1]]) frame = TestFrame(code.Seal(), {}) frame._states[0] = state.BlockState({}, c1) frame._states[1] = state.BlockState({}, c2) frame.step() # Since FAKE_OP_NO_NEXT does not merge into the next op, the condition on # the second block should remain as c2. condition = frame._states[1]._condition self.assertIs(condition, c2) def test_final_locals(self): op = FAKE_OP_NO_NEXT(0) frame = TestFrame(test_utils.FakeOrderedCode([[op]]).Seal(), {}) self.assertIsNone(frame._final_locals) frame.step() self.assertEqual(frame._final_locals, {}) def test_typing(self): code = test_utils.FakeOrderedCode([[FAKE_OP_NO_NEXT(0)]]).Seal() initial_locals = {'x': variables.Variable.from_value(0)} frame = frame_base.FrameBase(code, initial_locals) assert_type(frame, frame_base.FrameBase[int]) assert_type(frame._current_state, state.BlockState[int]) if __name__ == '__main__': unittest.main()
FrameBaseTest
python
apache__airflow
airflow-core/tests/unit/dag_processing/bundles/test_base.py
{ "start": 1878, "end": 4102 }
class ____(BaseDagBundle): def refresh(self): pass def get_current_version(self): pass def path(self): pass def test_dag_bundle_root_storage_path(): with conf_vars({("dag_processor", "dag_bundle_storage_path"): None}): assert get_bundle_storage_root_path() == Path(tempfile.gettempdir(), "airflow", "dag_bundles") def test_lock_acquisition(): """Test that the lock context manager sets _locked and locks a lock file.""" bundle = BasicBundle(name="locktest") lock_dir = get_bundle_storage_root_path() / "_locks" lock_file = lock_dir / f"{bundle.name}.lock" assert not bundle._locked with bundle.lock(): assert bundle._locked assert lock_file.exists() # Check lock file is now locked with open(lock_file, "w") as f: try: # Try to acquire an exclusive lock in non-blocking mode. fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) locked = False except OSError: locked = True assert locked # After, _locked is False and file unlock has been called. assert bundle._locked is False with open(lock_file, "w") as f: try: fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) unlocked = True fcntl.flock(f, fcntl.LOCK_UN) # Release the lock immediately. except OSError: unlocked = False assert unlocked def test_lock_exception_handling(): """Test that exceptions within the lock context manager still release the lock.""" bundle = BasicBundle(name="locktest") lock_dir = get_bundle_storage_root_path() / "_locks" lock_file = lock_dir / f"{bundle.name}.lock" try: with bundle.lock(): assert bundle._locked raise Exception("...") except Exception: pass # lock file should be unlocked assert not bundle._locked with open(lock_file, "w") as f: try: fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) acquired = True fcntl.flock(f, fcntl.LOCK_UN) except OSError: acquired = False assert acquired
BasicBundle
python
walkccc__LeetCode
solutions/2851. String Transformation/2851.py
{ "start": 0, "end": 2072 }
class ____: # This dynamic programming table dp[k][i] represents the number of ways to # rearrange the String s after k steps such that it starts with s[i]. # A String can be rotated from 1 to n - 1 times. The transition rule is # dp[k][i] = sum(dp[k - 1][j]) for all j != i. For example, when n = 4 and # k = 3, the table looks like this: # # ----------------------------------------------------------- # | | i = 0 | i = 1 | i = 2 | i = 3 | sum = (n - 1)^k | # ----------------------------------------------------------- # | k = 0 | 1 | 0 | 0 | 0 | 1 | # | k = 1 | 0 | 1 | 1 | 1 | 3 | # | k = 2 | 3 | 2 | 2 | 2 | 9 | # | k = 3 | 6 | 7 | 7 | 7 | 27 | # ----------------------------------------------------------- # # By observation, we have # * dp[k][!0] = ((n - 1)^k - (-1)^k) / n # * dp[k][0] = dp[k][!0] + (-1)^k def numberOfWays(self, s: str, t: str, k: int) -> int: MOD = 1_000_000_007 n = len(s) negOnePowK = 1 if k % 2 == 0 else -1 # (-1)^k z = self._zFunction(s + t + t) # indices in `s` s.t. for each `i` in the returned indices, # `s[i..n) + s[0..i) = t`. indices = [i - n for i in range(n, n + n) if z[i] >= n] dp = [0] * 2 # dp[0] := dp[k][0]; dp[1] := dp[k][!0] dp[1] = (pow(n - 1, k, MOD) - negOnePowK) * pow(n, MOD - 2, MOD) dp[0] = dp[1] + negOnePowK return sum(dp[0] if index == 0 else dp[1] for index in indices) % MOD def _zFunction(self, s: str) -> list[int]: """ Returns the z array, where z[i] is the length of the longest prefix of s[i..n) which is also a prefix of s. https://cp-algorithms.com/string/z-function.html#implementation """ n = len(s) z = [0] * n l = 0 r = 0 for i in range(1, n): if i < r: z[i] = min(r - i, z[i - l]) while i + z[i] < n and s[z[i]] == s[i + z[i]]: z[i] += 1 if i + z[i] > r: l = i r = i + z[i] return z
Solution
python
davidhalter__jedi
jedi/inference/base_value.py
{ "start": 793, "end": 5515 }
class ____: def get_root_context(self): value = self if value.parent_context is None: return value.as_context() while True: if value.parent_context is None: return value value = value.parent_context def execute(self, arguments): return self.inference_state.execute(self, arguments=arguments) def execute_with_values(self, *value_list): from jedi.inference.arguments import ValuesArguments arguments = ValuesArguments([ValueSet([value]) for value in value_list]) return self.inference_state.execute(self, arguments) def execute_annotation(self): return self.execute_with_values() def gather_annotation_classes(self): return ValueSet([self]) def merge_types_of_iterate(self, contextualized_node=None, is_async=False): return ValueSet.from_sets( lazy_value.infer() for lazy_value in self.iterate(contextualized_node, is_async) ) def _get_value_filters(self, name_or_str): origin_scope = name_or_str if isinstance(name_or_str, Name) else None yield from self.get_filters(origin_scope=origin_scope) # This covers the case where a stub files are incomplete. if self.is_stub(): from jedi.inference.gradual.conversion import convert_values for c in convert_values(ValueSet({self})): yield from c.get_filters() def goto(self, name_or_str, name_context=None, analysis_errors=True): from jedi.inference import finder filters = self._get_value_filters(name_or_str) names = finder.filter_name(filters, name_or_str) debug.dbg('context.goto %s in (%s): %s', name_or_str, self, names) return names def py__getattribute__(self, name_or_str, name_context=None, position=None, analysis_errors=True): """ :param position: Position of the last statement -> tuple of line, column """ if name_context is None: name_context = self names = self.goto(name_or_str, name_context, analysis_errors) values = ValueSet.from_sets(name.infer() for name in names) if not values: n = name_or_str.value if isinstance(name_or_str, Name) else name_or_str values = self.py__getattribute__alternatives(n) if not names and not values and analysis_errors: if isinstance(name_or_str, Name): from jedi.inference import analysis analysis.add_attribute_error( name_context, self, name_or_str) debug.dbg('context.names_to_types: %s -> %s', names, values) return values def py__await__(self): await_value_set = self.py__getattribute__("__await__") if not await_value_set: debug.warning('Tried to run __await__ on value %s', self) return await_value_set.execute_with_values() def py__name__(self): return self.name.string_name def iterate(self, contextualized_node=None, is_async=False): debug.dbg('iterate %s', self) if is_async: from jedi.inference.lazy_value import LazyKnownValues # TODO if no __aiter__ values are there, error should be: # TypeError: 'async for' requires an object with __aiter__ method, got int return iter([ LazyKnownValues( self.py__getattribute__('__aiter__').execute_with_values() .py__getattribute__('__anext__').execute_with_values() .py__getattribute__('__await__').execute_with_values() .py__stop_iteration_returns() ) # noqa: E124 ]) return self.py__iter__(contextualized_node) def is_sub_class_of(self, class_value): with debug.increase_indent_cm('subclass matching of %s <=> %s' % (self, class_value), color='BLUE'): for cls in self.py__mro__(): if cls.is_same_class(class_value): debug.dbg('matched subclass True', color='BLUE') return True debug.dbg('matched subclass False', color='BLUE') return False def is_same_class(self, class2): # Class matching should prefer comparisons that are not this function. if type(class2).is_same_class != HelperValueMixin.is_same_class: return class2.is_same_class(self) return self == class2 @memoize_method def as_context(self, *args, **kwargs): return self._as_context(*args, **kwargs)
HelperValueMixin
python
django__django
django/db/models/fields/composite.py
{ "start": 1318, "end": 5731 }
class ____(Field): descriptor_class = CompositeAttribute def __init__(self, *args, **kwargs): if ( not args or not all(isinstance(field, str) for field in args) or len(set(args)) != len(args) ): raise ValueError("CompositePrimaryKey args must be unique strings.") if len(args) == 1: raise ValueError("CompositePrimaryKey must include at least two fields.") if kwargs.get("default", NOT_PROVIDED) is not NOT_PROVIDED: raise ValueError("CompositePrimaryKey cannot have a default.") if kwargs.get("db_default", NOT_PROVIDED) is not NOT_PROVIDED: raise ValueError("CompositePrimaryKey cannot have a database default.") if kwargs.get("db_column", None) is not None: raise ValueError("CompositePrimaryKey cannot have a db_column.") if kwargs.setdefault("editable", False): raise ValueError("CompositePrimaryKey cannot be editable.") if not kwargs.setdefault("primary_key", True): raise ValueError("CompositePrimaryKey must be a primary key.") if not kwargs.setdefault("blank", True): raise ValueError("CompositePrimaryKey must be blank.") self.field_names = args super().__init__(**kwargs) def deconstruct(self): # args is always [] so it can be ignored. name, path, _, kwargs = super().deconstruct() return name, path, self.field_names, kwargs @cached_property def fields(self): meta = self.model._meta return tuple(meta.get_field(field_name) for field_name in self.field_names) @cached_property def columns(self): return tuple(field.column for field in self.fields) def contribute_to_class(self, cls, name, private_only=False): super().contribute_to_class(cls, name, private_only=private_only) cls._meta.pk = self setattr(cls, self.attname, self.descriptor_class(self)) def get_attname_column(self): return self.get_attname(), None def __iter__(self): return iter(self.fields) def __len__(self): return len(self.field_names) @cached_property def cached_col(self): return ColPairs(self.model._meta.db_table, self.fields, self.fields, self) def get_col(self, alias, output_field=None): if alias == self.model._meta.db_table and ( output_field is None or output_field == self ): return self.cached_col return ColPairs(alias, self.fields, self.fields, output_field) def get_pk_value_on_save(self, instance): values = [] for field in self.fields: value = field.value_from_object(instance) if value is None: value = field.get_pk_value_on_save(instance) values.append(value) return tuple(values) def _check_field_name(self): if self.name == "pk": return [] return [ checks.Error( "'CompositePrimaryKey' must be named 'pk'.", obj=self, id="fields.E013", ) ] def value_to_string(self, obj): values = [] vals = self.value_from_object(obj) for field, value in zip(self.fields, vals): obj = AttributeSetter(field.attname, value) values.append(field.value_to_string(obj)) return json.dumps(values, ensure_ascii=False) def to_python(self, value): if isinstance(value, str): # Assume we're deserializing. vals = json.loads(value) value = [ field.to_python(val) for field, val in zip(self.fields, vals, strict=True) ] return value CompositePrimaryKey.register_lookup(TupleExact) CompositePrimaryKey.register_lookup(TupleGreaterThan) CompositePrimaryKey.register_lookup(TupleGreaterThanOrEqual) CompositePrimaryKey.register_lookup(TupleLessThan) CompositePrimaryKey.register_lookup(TupleLessThanOrEqual) CompositePrimaryKey.register_lookup(TupleIn) CompositePrimaryKey.register_lookup(TupleIsNull) def unnest(fields): result = [] for field in fields: if isinstance(field, CompositePrimaryKey): result.extend(field.fields) else: result.append(field) return result
CompositePrimaryKey
python
cherrypy__cherrypy
cherrypy/test/test_conn.py
{ "start": 9270, "end": 17832 }
class ____(helper.CPWebCase): setup_server = staticmethod(setup_server) def test_HTTP11_Timeout(self): # If we timeout without sending any data, # the server will close the conn with a 408. if cherrypy.server.protocol_version != 'HTTP/1.1': return self.skip() self.PROTOCOL = 'HTTP/1.1' # Connect but send nothing. self.persistent = True conn = self.HTTP_CONN conn.auto_open = False conn.connect() # Wait for our socket timeout time.sleep(timeout * 2) # The request should have returned 408 already. response = conn.response_class(conn.sock, method='GET') response.begin() self.assertEqual(response.status, 408) conn.close() # Connect but send half the headers only. self.persistent = True conn = self.HTTP_CONN conn.auto_open = False conn.connect() conn.send(b'GET /hello HTTP/1.1') conn.send(('Host: %s' % self.HOST).encode('ascii')) # Wait for our socket timeout time.sleep(timeout * 2) # The conn should have already sent 408. response = conn.response_class(conn.sock, method='GET') response.begin() self.assertEqual(response.status, 408) conn.close() def test_HTTP11_Timeout_after_request(self): # If we timeout after at least one request has succeeded, # the server will close the conn without 408. if cherrypy.server.protocol_version != 'HTTP/1.1': return self.skip() self.PROTOCOL = 'HTTP/1.1' # Make an initial request self.persistent = True conn = self.HTTP_CONN conn.putrequest('GET', '/timeout?t=%s' % timeout, skip_host=True) conn.putheader('Host', self.HOST) conn.endheaders() response = conn.response_class(conn.sock, method='GET') response.begin() self.assertEqual(response.status, 200) self.body = response.read() self.assertBody(str(timeout)) # Make a second request on the same socket conn._output(b'GET /hello HTTP/1.1') conn._output(ntob('Host: %s' % self.HOST, 'ascii')) conn._send_output() response = conn.response_class(conn.sock, method='GET') response.begin() self.assertEqual(response.status, 200) self.body = response.read() self.assertBody('Hello, world!') # Wait for our socket timeout time.sleep(timeout * 2) # Make another request on the same socket, which should error conn._output(b'GET /hello HTTP/1.1') conn._output(ntob('Host: %s' % self.HOST, 'ascii')) conn._send_output() response = conn.response_class(conn.sock, method='GET') msg = "Writing to timed out socket didn't fail as it should have: %s" try: response.begin() except Exception: if not isinstance( sys.exc_info()[1], (socket.error, BadStatusLine), ): self.fail(msg % sys.exc_info()[1]) else: if response.status != 408: self.fail(msg % response.read()) conn.close() # Make another request on a new socket, which should work self.persistent = True conn = self.HTTP_CONN conn.putrequest('GET', '/', skip_host=True) conn.putheader('Host', self.HOST) conn.endheaders() response = conn.response_class(conn.sock, method='GET') response.begin() self.assertEqual(response.status, 200) self.body = response.read() self.assertBody(pov) # Make another request on the same socket, # but timeout on the headers conn.send(b'GET /hello HTTP/1.1') # Wait for our socket timeout time.sleep(timeout * 2) response = conn.response_class(conn.sock, method='GET') try: response.begin() except Exception: if not isinstance( sys.exc_info()[1], (socket.error, BadStatusLine), ): self.fail(msg % sys.exc_info()[1]) else: if response.status != 408: self.fail(msg % response.read()) conn.close() # Retry the request on a new connection, which should work self.persistent = True conn = self.HTTP_CONN conn.putrequest('GET', '/', skip_host=True) conn.putheader('Host', self.HOST) conn.endheaders() response = conn.response_class(conn.sock, method='GET') response.begin() self.assertEqual(response.status, 200) self.body = response.read() self.assertBody(pov) conn.close() def test_HTTP11_pipelining(self): if cherrypy.server.protocol_version != 'HTTP/1.1': return self.skip() self.PROTOCOL = 'HTTP/1.1' # Test pipelining. httplib doesn't support this directly. self.persistent = True conn = self.HTTP_CONN # Put request 1 conn.putrequest('GET', '/hello', skip_host=True) conn.putheader('Host', self.HOST) conn.endheaders() for trial in range(5): # Put next request conn._output(b'GET /hello HTTP/1.1') conn._output(ntob('Host: %s' % self.HOST, 'ascii')) conn._send_output() # Retrieve previous response response = conn.response_class(conn.sock, method='GET') # there is a bug in python3 regarding the buffering of # ``conn.sock``. Until that bug get's fixed we will # monkey patch the ``response`` instance. # https://bugs.python.org/issue23377 response.fp = conn.sock.makefile('rb', 0) response.begin() body = response.read(13) self.assertEqual(response.status, 200) self.assertEqual(body, b'Hello, world!') # Retrieve final response response = conn.response_class(conn.sock, method='GET') response.begin() body = response.read() self.assertEqual(response.status, 200) self.assertEqual(body, b'Hello, world!') conn.close() def test_100_Continue(self): if cherrypy.server.protocol_version != 'HTTP/1.1': return self.skip() self.PROTOCOL = 'HTTP/1.1' self.persistent = True conn = self.HTTP_CONN # Try a page without an Expect request header first. # Note that httplib's response.begin automatically ignores # 100 Continue responses, so we must manually check for it. try: conn.putrequest('POST', '/upload', skip_host=True) conn.putheader('Host', self.HOST) conn.putheader('Content-Type', 'text/plain') conn.putheader('Content-Length', '4') conn.endheaders() conn.send(ntob("d'oh")) response = conn.response_class(conn.sock, method='POST') version, status, reason = response._read_status() self.assertNotEqual(status, 100) finally: conn.close() # Now try a page with an Expect header... try: conn.connect() conn.putrequest('POST', '/upload', skip_host=True) conn.putheader('Host', self.HOST) conn.putheader('Content-Type', 'text/plain') conn.putheader('Content-Length', '17') conn.putheader('Expect', '100-continue') conn.endheaders() response = conn.response_class(conn.sock, method='POST') # ...assert and then skip the 100 response version, status, reason = response._read_status() self.assertEqual(status, 100) while True: line = response.fp.readline().strip() if line: self.fail( '100 Continue should not output any headers. Got %r' % line, ) else: break # ...send the body body = b'I am a small file' conn.send(body) # ...get the final response response.begin() self.status, self.headers, self.body = webtest.shb(response) self.assertStatus(200) self.assertBody("thanks for '%s'" % tonative(body)) finally: conn.close()
PipelineTests
python
ansible__ansible
lib/ansible/_internal/ansible_collections/ansible/_protomatter/plugins/filter/true_type.py
{ "start": 326, "end": 457 }
class ____(object): @staticmethod def filters() -> dict[str, t.Callable]: return dict(true_type=true_type)
FilterModule
python
huggingface__transformers
tests/models/univnet/test_modeling_univnet.py
{ "start": 3343, "end": 7453 }
class ____(ModelTesterMixin, unittest.TestCase): all_model_classes = (UnivNetModel,) if is_torch_available() else () # UnivNetModel currently cannot be traced with torch.jit.trace. # The UnivNetModel is not a transformer and does not use any attention mechanisms, so skip transformer/attention # related tests. test_resize_embeddings = False test_resize_position_embeddings = False # UnivNetModel is not a sequence classification model. test_mismatched_shapes = False # UnivNetModel does not have a base_model_prefix attribute. test_missing_keys = False is_encoder_decoder = False has_attentions = False def setUp(self): self.model_tester = UnivNetModelTester(self) self.config_tester = ConfigTester( self, config_class=UnivNetConfig, has_text_modality=False, common_properties=["num_mel_bins"] ) @unittest.skip(reason="fix this once it gets more usage") def test_multi_gpu_data_parallel_forward(self): super().test_multi_gpu_data_parallel_forward() def test_config(self): self.config_tester.run_common_tests() def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_forward_signature(self): config, _ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) signature = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic arg_names = [*signature.parameters.keys()] expected_arg_names = [ "input_features", ] self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) @unittest.skip(reason="UnivNetModel does not output hidden_states.") def test_hidden_states_output(self): pass @unittest.skip(reason="UnivNetModel.forward does not accept an inputs_embeds argument.") def test_inputs_embeds(self): pass @unittest.skip(reason="UnivNetModel does not use input embeddings and thus has no get_input_embeddings method.") def test_model_get_set_embeddings(self): pass @unittest.skip(reason="UnivNetModel does not support all arguments tested, such as output_hidden_states.") def test_model_outputs_equivalence(self): pass @unittest.skip(reason="UnivNetModel does not output hidden_states.") def test_retain_grad_hidden_states_attentions(self): pass def test_batched_inputs_outputs(self): config, inputs = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) model.to(torch_device) model.eval() batched_spectrogram = inputs["input_features"] batched_noise_sequence = inputs["noise_sequence"] with torch.no_grad(): batched_outputs = model( batched_spectrogram.to(torch_device), batched_noise_sequence.to(torch_device), )[0] self.assertEqual( batched_spectrogram.shape[0], batched_outputs.shape[0], msg="Got different batch dims for input and output", ) def test_unbatched_inputs_outputs(self): config, inputs = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model( inputs["input_features"][:1].to(torch_device), inputs["noise_sequence"][:1].to(torch_device) )[0] self.assertTrue(outputs.shape[0] == 1, msg="Unbatched input should create batched output with bsz = 1") @require_torch_accelerator @slow
UnivNetModelTest
python
Textualize__textual
tests/option_list/test_option_list_movement.py
{ "start": 4734, "end": 6019 }
class ____(App[None]): """Test option list application with no optons.""" def compose(self) -> ComposeResult: yield OptionList() async def test_empty_list_movement() -> None: """Attempting to move around an empty list should be a non-operation.""" async with EmptyOptionListApp().run_test() as pilot: option_list = pilot.app.query_one(OptionList) await pilot.press("tab") for movement in ("up", "down", "home", "end", "pageup", "pagedown"): await pilot.press(movement) assert option_list.highlighted is None @pytest.mark.parametrize( ["movement", "landing"], [ ("up", 99), ("down", 0), ("home", 0), ("end", 99), ("pageup", 0), ("pagedown", 99), ], ) async def test_no_highlight_movement(movement: str, landing: int) -> None: """Attempting to move around in a list with no highlight should select the most appropriate item.""" async with EmptyOptionListApp().run_test() as pilot: option_list = pilot.app.query_one(OptionList) for _ in range(100): option_list.add_option("test") await pilot.press("tab") await pilot.press(movement) assert option_list.highlighted == landing
EmptyOptionListApp
python
scipy__scipy
scipy/special/tests/test_hyp2f1.py
{ "start": 1612, "end": 1740 }
class ____(NamedTuple): a: float b: float c: float z: complex expected: complex rtol: float
Hyp2f1TestCase
python
pypa__warehouse
tests/common/db/packaging.py
{ "start": 1823, "end": 2332 }
class ____(WarehouseFactory): class Meta: model = Release id = factory.Faker("uuid4", cast_to=None) project = factory.SubFactory(ProjectFactory) version = factory.Sequence(lambda n: str(n) + ".0") canonical_version = factory.LazyAttribute( lambda o: packaging.utils.canonicalize_version(o.version) ) _pypi_ordering = factory.Sequence(lambda n: n) uploader = factory.SubFactory(UserFactory) description = factory.SubFactory(DescriptionFactory)
ReleaseFactory
python
ansible__ansible
lib/ansible/modules/service.py
{ "start": 45321, "end": 47738 }
class ____(Service): """ This is the OpenBSD Service manipulation class - it uses rcctl(8) or /etc/rc.d scripts for service control. Enabling a service is only supported if rcctl is present. """ platform = 'OpenBSD' distribution = None def get_service_tools(self): self.enable_cmd = self.module.get_bin_path('rcctl') if self.enable_cmd: self.svc_cmd = self.enable_cmd else: rcdir = '/etc/rc.d' rc_script = "%s/%s" % (rcdir, self.name) if os.path.isfile(rc_script): self.svc_cmd = rc_script if not self.svc_cmd: self.module.fail_json(msg='unable to find svc_cmd') def get_service_status(self): if self.enable_cmd: rc, stdout, stderr = self.execute_command("%s %s %s" % (self.svc_cmd, 'check', self.name)) else: rc, stdout, stderr = self.execute_command("%s %s" % (self.svc_cmd, 'check')) if stderr: self.module.fail_json(msg=stderr) if rc == 1: self.running = False elif rc == 0: self.running = True def service_control(self): if self.enable_cmd: return self.execute_command("%s -f %s %s" % (self.svc_cmd, self.action, self.name), daemonize=True) else: return self.execute_command("%s -f %s" % (self.svc_cmd, self.action)) def service_enable(self): if not self.enable_cmd: return super(OpenBsdService, self).service_enable() rc, stdout, stderr = self.execute_command("%s %s %s %s" % (self.enable_cmd, 'get', self.name, 'status')) status_action = None if self.enable: if rc != 0: status_action = "on" elif self.enable is not None: # should be explicit False at this point if rc != 1: status_action = "off" if status_action is not None: self.changed = True if not self.module.check_mode: rc, stdout, stderr = self.execute_command("%s set %s status %s" % (self.enable_cmd, self.name, status_action)) if rc != 0: if stderr: self.module.fail_json(msg=stderr) else: self.module.fail_json(msg="rcctl failed to modify service status")
OpenBsdService
python
great-expectations__great_expectations
tests/data_context/store/test_store.py
{ "start": 569, "end": 5081 }
class ____: id: Optional[str] foo: str @pytest.mark.unit def test_gx_cloud_response_json_to_object_dict() -> None: data = {"foo": "bar", "baz": "qux"} assert Store.gx_cloud_response_json_to_object_dict(response_json=data) == data @pytest.mark.unit def test_store_name_property_and_defaults() -> None: store = Store() assert store.store_name == "no_store_name" @pytest.mark.unit def test_store_serialize() -> None: store = Store() value = AbstractConfig(id="abc123", name="my_config") assert store.serialize(value) == value @pytest.mark.unit def test_store_deserialize() -> None: store = Store() value = {"a": "b"} assert store.deserialize(value) == value @pytest.mark.unit def test_build_store_from_config_success(): store_name = "my_new_store" store_config = { "module_name": "great_expectations.data_context.store", "class_name": "ExpectationsStore", } store = Store.build_store_from_config( name=store_name, config=store_config, ) assert isinstance(store, Store) @pytest.mark.unit @pytest.mark.parametrize( "store_config,module_name", [ pytest.param(None, "great_expectations.data_context.store", id="config_none"), pytest.param( { "module_name": "great_expectations.data_context.store", "class_name": "ExpectationsStore", }, None, id="module_name_none", ), pytest.param(None, None, id="config_and_module_name_both_none"), ], ) def test_build_store_from_config_failure(store_config: dict, module_name: str): with pytest.raises(gx_exceptions.StoreConfigurationError): Store.build_store_from_config( name="my_new_store", config=store_config, module_name=module_name, ) @pytest.mark.unit def test_store_add_success(): store = Store() key = StringKey("foo") value = "bar" store.add(key=key, value=value) assert store.has_key(key) @pytest.mark.unit @mock.patch.object(InMemoryStoreBackend, "add") def test_store_add_success__adds_id(mock_store_backend_add): """Ensure that if we get an id on the new object, we add an id to the input value""" new_id = str(uuid.uuid4()) def mock_add(key: DataContextKey, value: Any, **kwargs): # our backends currently return new objects, and in the case of cloud, they will have an id return replace(value, id=new_id) mock_store_backend_add.side_effect = mock_add store = Store() key = StringKey("foo") original_value = DummyModel(id=None, foo="bar") store.add(key=key, value=original_value) assert original_value.id == new_id @pytest.mark.unit @mock.patch.object(InMemoryStoreBackend, "add") def test_store_add_success__no_id(mock_store_backend_add): """Ensure that if we get an id on the new object, we add an id to the input value""" def mock_add(key: DataContextKey, value: Any, **kwargs): return replace(value) mock_store_backend_add.side_effect = mock_add store = Store() key = StringKey("foo") original_value = DummyModel(id=None, foo="bar") store.add(key=key, value=original_value) assert original_value.id is None @pytest.mark.unit def test_store_add_failure(): store = Store() key = StringKey("foo") value = "bar" store.add(key=key, value=value) with pytest.raises(StoreBackendError) as e: store.add(key=key, value=value) assert "Store already has the following key" in str(e.value) @pytest.mark.unit def test_store_update_success(): store = Store() key = StringKey("foo") value = "bar" updated_value = "baz" store.add(key=key, value=value) store.update(key=key, value=updated_value) assert store.get(key) == updated_value @pytest.mark.unit def test_store_update_failure(): store = Store() key = StringKey("foo") value = "bar" with pytest.raises(StoreBackendError) as e: store.update(key=key, value=value) assert "Store does not have a value associated the following key" in str(e.value) @pytest.mark.unit @pytest.mark.parametrize("previous_key_exists", [True, False]) def test_store_add_or_update(previous_key_exists: bool): store = Store() key = StringKey("foo") value = "bar" if previous_key_exists: store.add(key=key, value=None) store.add_or_update(key=key, value=value) assert store.get(key) == value
DummyModel
python
Textualize__textual
docs/examples/guide/actions/actions06.py
{ "start": 196, "end": 1353 }
class ____(App): BINDINGS = [ ("n", "next", "Next"), ("p", "previous", "Previous"), ] CSS_PATH = "actions06.tcss" page_no = reactive(0) def compose(self) -> ComposeResult: with HorizontalScroll(id="page-container"): for page_no in range(PAGES_COUNT): yield Placeholder(f"Page {page_no}", id=f"page-{page_no}") yield Footer() def action_next(self) -> None: self.page_no += 1 self.refresh_bindings() # (1)! self.query_one(f"#page-{self.page_no}").scroll_visible() def action_previous(self) -> None: self.page_no -= 1 self.refresh_bindings() # (2)! self.query_one(f"#page-{self.page_no}").scroll_visible() def check_action( self, action: str, parameters: tuple[object, ...] ) -> bool | None: # (3)! """Check if an action may run.""" if action == "next" and self.page_no == PAGES_COUNT - 1: return False if action == "previous" and self.page_no == 0: return False return True if __name__ == "__main__": app = PagesApp() app.run()
PagesApp
python
pytorch__pytorch
torch/cuda/__init__.py
{ "start": 58865, "end": 65752 }
class ____: """Just a simple wrapper to store some metadata for testing purposes.""" def __init__(self, kernel): self.kernel = kernel self.kernel_invoked = False def __call__(self, *args, **kwargs): res = self.kernel(*args, **kwargs) self.kernel_invoked = True return res def _register_triton_kernels(): @_WrappedTritonKernel def kernel_impl(*args, **kwargs): from torch.sparse._triton_ops import bsr_dense_mm # pyrefly: ignore [not-callable] return bsr_dense_mm(*args, skip_checks=True, **kwargs) @_WrappedTritonKernel def addmm_kernel_impl(*args, **kwargs): from torch.sparse._triton_ops import bsr_dense_addmm return bsr_dense_addmm(*args, skip_checks=True, **kwargs) has_triton = importlib.util.find_spec("triton") is not None if has_triton: torch._TritonLibrary.registerOp( "_triton_bsr_dense_mm_out", "_triton_bsr_dense_mm_out(Tensor bsr, Tensor dense, *, Tensor(a!) out) -> Tensor(a!)", kernel_impl, "SparseCsrCUDA", ) torch._TritonLibrary.registerOp( "_triton_bsr_dense_addmm_out", ( "_triton_bsr_dense_addmm_out(Tensor input, Tensor bsr, Tensor dense," " *, Scalar beta, Scalar alpha, Tensor(a!) out) -> Tensor(a!)" ), addmm_kernel_impl, "SparseCsrCUDA", ) _lazy_call(_register_triton_kernels) def _compile_kernel( kernel_source: str, kernel_name: str, compute_capability: Optional[str] = None, cuda_include_dirs: Optional[list] = None, nvcc_options: Optional[list] = None, ): """ Compiles a CUDA kernel using NVRTC and returns a callable function. This function is a wrapper for NVRTC that enables runtime compilation of CUDA kernels. Note that this returns a raw CUDA kernel that operates on raw memory pointers. To use this kernel as a proper PyTorch operator, you should wrap it following the guide at: pytorch.org/tutorials/advanced/python_custom_ops.html Args: kernel_source (str): The CUDA kernel source code as a string kernel_name (str): The name of the kernel function to compile compute_capability (str, optional): The compute capability to target (e.g., "86"). If None, will detect from current device. cuda_include_dirs (list, optional): List of directories containing CUDA headers nvcc_options (list, optional): Additional options to pass to NVRTC Returns: callable: A Python function that can be called with PyTorch tensor arguments to execute the kernel Example: >>> # xdoctest: +SKIP >>> kernel_code = ''' extern "C" __global__ void add_tensors(const float* a, const float* b, float* c, int n) { int i = threadIdx.x + blockIdx.x * blockDim.x; if (i < n) c[i] = a[i] + b[i]; } ''' >>> add_kernel = torch.cuda.compile_kernel(kernel_code, "add_tensors") >>> a = torch.randn(1024, device="cuda") >>> b = torch.randn(1024, device="cuda") >>> c = torch.empty_like(a) >>> add_kernel(grid=(4, 1, 1), block=(256, 1, 1), args=[a, b, c, a.numel()]) """ from torch.cuda._utils import _cuda_load_module, _nvrtc_compile # Compile the kernel to PTX ptx, mangled_name = _nvrtc_compile( kernel_source, kernel_name, compute_capability, cuda_include_dirs, nvcc_options, ) # Load the module and get the kernel result = _cuda_load_module(ptx, [mangled_name]) if isinstance(result, dict): return result[mangled_name] else: # This branch shouldn't be executed if kernel_names is provided, # but MyPy needs this to understand type narrowing return getattr(result, mangled_name) from . import amp, jiterator, nvtx, profiler, sparse, tunable _POOL_HANDLE = NewType("_POOL_HANDLE", tuple[int, int]) __all__ = [ # Typed storage and tensors "BFloat16Storage", "BFloat16Tensor", "BoolStorage", "BoolTensor", "ByteStorage", "ByteTensor", "CharStorage", "CharTensor", "ComplexDoubleStorage", "ComplexFloatStorage", "DoubleStorage", "DoubleTensor", "FloatStorage", "FloatTensor", "HalfStorage", "HalfTensor", "IntStorage", "IntTensor", "LongStorage", "LongTensor", "ShortStorage", "ShortTensor", "CUDAGraph", "CudaError", "DeferredCudaCallError", "Event", "ExternalStream", "Stream", "StreamContext", "GreenContext", "amp", "caching_allocator_alloc", "caching_allocator_delete", "caching_allocator_enable", "can_device_access_peer", "check_error", "cudaStatus", "cudart", "current_blas_handle", "current_device", "current_stream", "default_generators", "default_stream", "device", "device_count", "device_memory_used", "device_of", "empty_cache", "get_allocator_backend", "CUDAPluggableAllocator", "change_current_allocator", "get_arch_list", "get_device_capability", "get_device_name", "get_device_properties", "get_gencode_flags", "get_per_process_memory_fraction", "get_rng_state", "get_rng_state_all", "get_stream_from_external", "get_sync_debug_mode", "graph", "graph_pool_handle", "graphs", "has_half", "has_magma", "host_memory_stats", "host_memory_stats_as_nested_dict", "init", "initial_seed", "ipc_collect", "is_available", "is_bf16_supported", "is_current_stream_capturing", "is_initialized", "is_tf32_supported", "jiterator", "list_gpu_processes", "make_graphed_callables", "manual_seed", "manual_seed_all", "max_memory_allocated", "max_memory_cached", "max_memory_reserved", "mem_get_info", "memory", "memory_allocated", "memory_cached", "memory_reserved", "memory_snapshot", "memory_stats", "memory_stats_as_nested_dict", "memory_summary", "memory_usage", "MemPool", "use_mem_pool", "temperature", "power_draw", "clock_rate", "nccl", "nvtx", "profiler", "random", "reset_accumulated_host_memory_stats", "reset_accumulated_memory_stats", "reset_max_memory_allocated", "reset_max_memory_cached", "reset_peak_host_memory_stats", "reset_peak_memory_stats", "seed", "seed_all", "set_device", "set_per_process_memory_fraction", "set_rng_state", "set_rng_state_all", "set_stream", "set_sync_debug_mode", "sparse", "stream", "streams", "synchronize", "tunable", "utilization", ]
_WrappedTritonKernel
python
django__django
tests/db_functions/text/test_pad.py
{ "start": 190, "end": 2286 }
class ____(TestCase): def test_pad(self): Author.objects.create(name="John", alias="j") none_value = ( "" if connection.features.interprets_empty_strings_as_nulls else None ) tests = ( (LPad("name", 7, Value("xy")), "xyxJohn"), (RPad("name", 7, Value("xy")), "Johnxyx"), (LPad("name", 6, Value("x")), "xxJohn"), (RPad("name", 6, Value("x")), "Johnxx"), # The default pad string is a space. (LPad("name", 6), " John"), (RPad("name", 6), "John "), # If string is longer than length it is truncated. (LPad("name", 2), "Jo"), (RPad("name", 2), "Jo"), (LPad("name", 0), ""), (RPad("name", 0), ""), (LPad("name", None), none_value), (RPad("name", None), none_value), (LPad(Value(None), 1), none_value), (RPad(Value(None), 1), none_value), (LPad("goes_by", 1), none_value), (RPad("goes_by", 1), none_value), ) for function, padded_name in tests: with self.subTest(function=function): authors = Author.objects.annotate(padded_name=function) self.assertQuerySetEqual( authors, [padded_name], lambda a: a.padded_name, ordered=False ) def test_pad_negative_length(self): for function in (LPad, RPad): with self.subTest(function=function): with self.assertRaisesMessage( ValueError, "'length' must be greater or equal to 0." ): function("name", -1) def test_combined_with_length(self): Author.objects.create(name="Rhonda", alias="john_smith") Author.objects.create(name="♥♣♠", alias="bytes") authors = Author.objects.annotate(filled=LPad("name", Length("alias"))) self.assertQuerySetEqual( authors.order_by("alias"), [" ♥♣♠", " Rhonda"], lambda a: a.filled, )
PadTests
python
PyCQA__pylint
tests/functional/g/generic_alias/generic_alias_mixed_py39.py
{ "start": 1044, "end": 1190 }
class ____(typing.Collection[int]): # [abstract-method,abstract-method,abstract-method] # __contains__, __iter__, __len__ pass
DerivedCollection
python
getsentry__sentry-python
sentry_sdk/integrations/cloud_resource_context.py
{ "start": 1217, "end": 7780 }
class ____(Integration): """ Adds cloud resource context to the Senty scope """ identifier = "cloudresourcecontext" cloud_provider = "" aws_token = "" http = urllib3.PoolManager(timeout=HTTP_TIMEOUT) gcp_metadata = None def __init__(self, cloud_provider=""): # type: (str) -> None CloudResourceContextIntegration.cloud_provider = cloud_provider @classmethod def _is_aws(cls): # type: () -> bool try: r = cls.http.request( "PUT", AWS_TOKEN_URL, headers={"X-aws-ec2-metadata-token-ttl-seconds": "60"}, ) if r.status != 200: return False cls.aws_token = r.data.decode() return True except urllib3.exceptions.TimeoutError: logger.debug( "AWS metadata service timed out after %s seconds", HTTP_TIMEOUT ) return False except Exception as e: logger.debug("Error checking AWS metadata service: %s", str(e)) return False @classmethod def _get_aws_context(cls): # type: () -> Dict[str, str] ctx = { "cloud.provider": CLOUD_PROVIDER.AWS, "cloud.platform": CLOUD_PLATFORM.AWS_EC2, } try: r = cls.http.request( "GET", AWS_METADATA_URL, headers={"X-aws-ec2-metadata-token": cls.aws_token}, ) if r.status != 200: return ctx data = json.loads(r.data.decode("utf-8")) try: ctx["cloud.account.id"] = data["accountId"] except Exception: pass try: ctx["cloud.availability_zone"] = data["availabilityZone"] except Exception: pass try: ctx["cloud.region"] = data["region"] except Exception: pass try: ctx["host.id"] = data["instanceId"] except Exception: pass try: ctx["host.type"] = data["instanceType"] except Exception: pass except urllib3.exceptions.TimeoutError: logger.debug( "AWS metadata service timed out after %s seconds", HTTP_TIMEOUT ) except Exception as e: logger.debug("Error fetching AWS metadata: %s", str(e)) return ctx @classmethod def _is_gcp(cls): # type: () -> bool try: r = cls.http.request( "GET", GCP_METADATA_URL, headers={"Metadata-Flavor": "Google"}, ) if r.status != 200: return False cls.gcp_metadata = json.loads(r.data.decode("utf-8")) return True except urllib3.exceptions.TimeoutError: logger.debug( "GCP metadata service timed out after %s seconds", HTTP_TIMEOUT ) return False except Exception as e: logger.debug("Error checking GCP metadata service: %s", str(e)) return False @classmethod def _get_gcp_context(cls): # type: () -> Dict[str, str] ctx = { "cloud.provider": CLOUD_PROVIDER.GCP, "cloud.platform": CLOUD_PLATFORM.GCP_COMPUTE_ENGINE, } try: if cls.gcp_metadata is None: r = cls.http.request( "GET", GCP_METADATA_URL, headers={"Metadata-Flavor": "Google"}, ) if r.status != 200: return ctx cls.gcp_metadata = json.loads(r.data.decode("utf-8")) try: ctx["cloud.account.id"] = cls.gcp_metadata["project"]["projectId"] except Exception: pass try: ctx["cloud.availability_zone"] = cls.gcp_metadata["instance"][ "zone" ].split("/")[-1] except Exception: pass try: # only populated in google cloud run ctx["cloud.region"] = cls.gcp_metadata["instance"]["region"].split("/")[ -1 ] except Exception: pass try: ctx["host.id"] = cls.gcp_metadata["instance"]["id"] except Exception: pass except urllib3.exceptions.TimeoutError: logger.debug( "GCP metadata service timed out after %s seconds", HTTP_TIMEOUT ) except Exception as e: logger.debug("Error fetching GCP metadata: %s", str(e)) return ctx @classmethod def _get_cloud_provider(cls): # type: () -> str if cls._is_aws(): return CLOUD_PROVIDER.AWS if cls._is_gcp(): return CLOUD_PROVIDER.GCP return "" @classmethod def _get_cloud_resource_context(cls): # type: () -> Dict[str, str] cloud_provider = ( cls.cloud_provider if cls.cloud_provider != "" else CloudResourceContextIntegration._get_cloud_provider() ) if cloud_provider in context_getters.keys(): return context_getters[cloud_provider]() return {} @staticmethod def setup_once(): # type: () -> None cloud_provider = CloudResourceContextIntegration.cloud_provider unsupported_cloud_provider = ( cloud_provider != "" and cloud_provider not in context_getters.keys() ) if unsupported_cloud_provider: logger.warning( "Invalid value for cloud_provider: %s (must be in %s). Falling back to autodetection...", CloudResourceContextIntegration.cloud_provider, list(context_getters.keys()), ) context = CloudResourceContextIntegration._get_cloud_resource_context() if context != {}: set_context(CONTEXT_TYPE, context) # Map with the currently supported cloud providers # mapping to functions extracting the context context_getters = { CLOUD_PROVIDER.AWS: CloudResourceContextIntegration._get_aws_context, CLOUD_PROVIDER.GCP: CloudResourceContextIntegration._get_gcp_context, }
CloudResourceContextIntegration
python
pytorch__pytorch
test/test_fx_passes.py
{ "start": 18762, "end": 19356 }
class ____: @staticmethod def forward(x): x = x + 1 # target subgraph to match x = x.relu() z = x.sum() y = x.sigmoid() out = y.sigmoid() + z.sum() return out @staticmethod def pattern(a): a = a.relu() b = a.sigmoid() c = a.sum() return b, c test_cases = [ # match_output, match_placeholder, num_matches TestCase(False, False, 1), TestCase(True, False, 0), TestCase(False, True, 0), TestCase(True, True, 0) ]
MultipleOutputsWithoutDependency
python
modin-project__modin
asv_bench/benchmarks/benchmarks.py
{ "start": 39635, "end": 40055 }
class ____: params = [get_benchmark_shapes("TimeEquals")] param_names = ["shape"] def setup(self, shape): self.df = IMPL.DataFrame(np.random.randn(*shape)) self.df.iloc[-1, -1] = np.nan execute(self.df) # returns a boolean thus not calling execute def time_frame_float_equal(self, shape): self.df.equals(self.df) from .utils import setup # noqa: E402, F401
TimeEquals
python
Pylons__pyramid
tests/test_i18n.py
{ "start": 965, "end": 3092 }
class ____(unittest.TestCase): def _makeOne(self, *arg, **kw): from pyramid.i18n import Localizer return Localizer(*arg, **kw) def test_ctor(self): localizer = self._makeOne('en_US', None) self.assertEqual(localizer.locale_name, 'en_US') self.assertEqual(localizer.translations, None) def test_translate(self): translations = DummyTranslations() localizer = self._makeOne(None, translations) self.assertEqual( localizer.translate('123', domain='1', mapping={}), '123' ) self.assertTrue(localizer.translator) def test_pluralize(self): translations = DummyTranslations() localizer = self._makeOne(None, translations) result = localizer.pluralize( 'singular', 'plural', 1, domain='1', mapping={} ) self.assertEqual(result, 'singular') self.assertTrue(localizer.pluralizer) def test_pluralize_pluralizer_already_added(self): translations = DummyTranslations() localizer = self._makeOne(None, translations) def pluralizer(*arg, **kw): return arg, kw localizer.pluralizer = pluralizer result = localizer.pluralize( 'singular', 'plural', 1, domain='1', mapping={} ) self.assertEqual( result, (('singular', 'plural', 1), {'domain': '1', 'mapping': {}}) ) self.assertTrue(localizer.pluralizer is pluralizer) def test_pluralize_default_translations(self): # test that even without message ids loaded that # "localizer.pluralize" "works" instead of raising an inscrutable # "translations object has no attr 'plural' error; see # see https://github.com/Pylons/pyramid/issues/235 from pyramid.i18n import Translations translations = Translations() translations._catalog = {} localizer = self._makeOne(None, translations) result = localizer.pluralize( 'singular', 'plural', 2, domain='1', mapping={} ) self.assertEqual(result, 'plural')
TestLocalizer
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/links/emr.py
{ "start": 5637, "end": 6252 }
class ____(BaseAwsLink): """Helper class for constructing link to S3 console for Amazon EMR Serverless Logs.""" name = "S3 Logs" key = "emr_serverless_s3_logs" format_str = BASE_AWS_CONSOLE_LINK + ( "/s3/buckets/{bucket_name}?region={region_name}" "&prefix={prefix}/applications/{application_id}/jobs/{job_run_id}/" ) def format_link(self, **kwargs) -> str: bucket, prefix = S3Hook.parse_s3_url(kwargs["log_uri"]) kwargs["bucket_name"] = bucket kwargs["prefix"] = prefix.rstrip("/") return super().format_link(**kwargs)
EmrServerlessS3LogsLink
python
astral-sh__uv
scripts/benchmark/src/benchmark/tools.py
{ "start": 350, "end": 513 }
class ____(enum.Enum): """Enumeration of the benchmarks to run.""" INSTALL_COLD = "install-cold" INSTALL_WARM = "install-warm" RUN = "run"
Benchmark
python
bokeh__bokeh
tests/unit/bokeh/core/property/test_primitive.py
{ "start": 3782, "end": 5915 }
class ____: def test_valid(self) -> None: prop = bcpp.Complex() assert prop.is_valid(0) assert prop.is_valid(1) assert prop.is_valid(0.0) assert prop.is_valid(1.0) assert prop.is_valid(1.0+1.0j) assert prop.is_valid(np.int8(0)) assert prop.is_valid(np.int8(1)) assert prop.is_valid(np.int16(0)) assert prop.is_valid(np.int16(1)) assert prop.is_valid(np.int32(0)) assert prop.is_valid(np.int32(1)) assert prop.is_valid(np.int64(0)) assert prop.is_valid(np.int64(1)) assert prop.is_valid(np.uint8(0)) assert prop.is_valid(np.uint8(1)) assert prop.is_valid(np.uint16(0)) assert prop.is_valid(np.uint16(1)) assert prop.is_valid(np.uint32(0)) assert prop.is_valid(np.uint32(1)) assert prop.is_valid(np.uint64(0)) assert prop.is_valid(np.uint64(1)) assert prop.is_valid(np.float16(0)) assert prop.is_valid(np.float16(1)) assert prop.is_valid(np.float32(0)) assert prop.is_valid(np.float32(1)) assert prop.is_valid(np.float64(0)) assert prop.is_valid(np.float64(1)) assert prop.is_valid(np.complex64(1.0+1.0j)) assert prop.is_valid(np.complex128(1.0+1.0j)) if hasattr(np, "complex256"): assert prop.is_valid(np.complex256(1.0+1.0j)) def test_invalid(self) -> None: prop = bcpp.Complex() assert not prop.is_valid(None) assert not prop.is_valid(False) assert not prop.is_valid(True) assert not prop.is_valid("") assert not prop.is_valid(()) assert not prop.is_valid([]) assert not prop.is_valid({}) assert not prop.is_valid(_TestHasProps()) assert not prop.is_valid(_TestModel()) assert not prop.is_valid(np.bool_(False)) assert not prop.is_valid(np.bool_(True)) def test_has_ref(self) -> None: prop = bcpp.Complex() assert not prop.has_ref def test_str(self) -> None: prop = bcpp.Complex() assert str(prop) == "Complex"
Test_Complex
python
pytorch__pytorch
torch/_dynamo/variables/misc.py
{ "start": 74741, "end": 74830 }
class ____(ConstantLikeVariable): _error_prefix = "re.Match"
ConstantRegexMatchVariable
python
readthedocs__readthedocs.org
readthedocs/storage/__init__.py
{ "start": 1317, "end": 1672 }
class ____(LazyObject): def _setup(self): self._wrapped = get_storage_class(settings.RTD_STATICFILES_STORAGE)() build_media_storage = ConfiguredBuildMediaStorage() build_commands_storage = ConfiguredBuildCommandsStorage() build_tools_storage = ConfiguredBuildToolsStorage() staticfiles_storage = ConfiguredStaticStorage()
ConfiguredStaticStorage
python
davidhalter__parso
parso/python/errors.py
{ "start": 12956, "end": 17629 }
class ____(Normalizer): """ Searches for errors in the syntax tree. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._error_dict = {} self.version = self.grammar.version_info def initialize(self, node): def create_context(node): if node is None: return None parent_context = create_context(node.parent) if node.type in ('classdef', 'funcdef', 'file_input'): return _Context(node, self._add_syntax_error, parent_context) return parent_context self.context = create_context(node) or _Context(node, self._add_syntax_error) self._indentation_count = 0 def visit(self, node): if node.type == 'error_node': with self.visit_node(node): # Don't need to investigate the inners of an error node. We # might find errors in there that should be ignored, because # the error node itself already shows that there's an issue. return '' return super().visit(node) @contextmanager def visit_node(self, node): self._check_type_rules(node) if node.type in _BLOCK_STMTS: with self.context.add_block(node): if len(self.context.blocks) == _MAX_BLOCK_SIZE: self._add_syntax_error(node, "too many statically nested blocks") yield return elif node.type == 'suite': self._indentation_count += 1 if self._indentation_count == _MAX_INDENT_COUNT: self._add_indentation_error(node.children[1], "too many levels of indentation") yield if node.type == 'suite': self._indentation_count -= 1 elif node.type in ('classdef', 'funcdef'): context = self.context self.context = context.parent_context self.context.close_child_context(context) def visit_leaf(self, leaf): if leaf.type == 'error_leaf': if leaf.token_type in ('INDENT', 'ERROR_DEDENT'): # Indents/Dedents itself never have a prefix. They are just # "pseudo" tokens that get removed by the syntax tree later. # Therefore in case of an error we also have to check for this. spacing = list(leaf.get_next_leaf()._split_prefix())[-1] if leaf.token_type == 'INDENT': message = 'unexpected indent' else: message = 'unindent does not match any outer indentation level' self._add_indentation_error(spacing, message) else: if leaf.value.startswith('\\'): message = 'unexpected character after line continuation character' else: match = re.match('\\w{,2}("{1,3}|\'{1,3})', leaf.value) if match is None: message = 'invalid syntax' if ( self.version >= (3, 9) and leaf.value in _get_token_collection( self.version ).always_break_tokens ): message = "f-string: " + message else: if len(match.group(1)) == 1: message = 'EOL while scanning string literal' else: message = 'EOF while scanning triple-quoted string literal' self._add_syntax_error(leaf, message) return '' elif leaf.value == ':': parent = leaf.parent if parent.type in ('classdef', 'funcdef'): self.context = self.context.add_context(parent) # The rest is rule based. return super().visit_leaf(leaf) def _add_indentation_error(self, spacing, message): self.add_issue(spacing, 903, "IndentationError: " + message) def _add_syntax_error(self, node, message): self.add_issue(node, 901, "SyntaxError: " + message) def add_issue(self, node, code, message): # Overwrite the default behavior. # Check if the issues are on the same line. line = node.start_pos[0] args = (code, message, node) self._error_dict.setdefault(line, args) def finalize(self): self.context.finalize() for code, message, node in self._error_dict.values(): self.issues.append(Issue(node, code, message))
ErrorFinder
python
django__django
tests/expressions/models.py
{ "start": 663, "end": 741 }
class ____(Employee): adjusted_salary = models.IntegerField()
RemoteEmployee
python
pypa__hatch
tests/cli/test/test_test.py
{ "start": 17663, "end": 20542 }
class ____: def test_flag(self, hatch, temp_dir, config_file, env_run, mocker): config_file.model.template.plugins["default"]["tests"] = False config_file.save() project_name = "My.App" with temp_dir.as_cwd(): result = hatch("new", project_name) assert result.exit_code == 0, result.output project_path = temp_dir / "my-app" data_path = temp_dir / "data" data_path.mkdir() with project_path.as_cwd(env_vars={ConfigEnvVars.DATA: str(data_path)}): result = hatch("test", "--retries", "2") assert result.exit_code == 0, result.output assert not result.output assert env_run.call_args_list == [ mocker.call("pytest -p no:randomly -r aR --reruns 2 tests", shell=True), ] assert not (data_path / ".config" / "coverage").exists() def test_flag_with_arguments(self, hatch, temp_dir, config_file, env_run, mocker): config_file.model.template.plugins["default"]["tests"] = False config_file.save() project_name = "My.App" with temp_dir.as_cwd(): result = hatch("new", project_name) assert result.exit_code == 0, result.output project_path = temp_dir / "my-app" data_path = temp_dir / "data" data_path.mkdir() with project_path.as_cwd(env_vars={ConfigEnvVars.DATA: str(data_path)}): result = hatch("test", "--retries", "2", "--", "--flag", "--", "arg1", "arg2") assert result.exit_code == 0, result.output assert not result.output assert env_run.call_args_list == [ mocker.call("pytest -p no:randomly -r aR --reruns 2 --flag -- arg1 arg2", shell=True), ] assert not (data_path / ".config" / "coverage").exists() def test_config(self, hatch, temp_dir, config_file, env_run, mocker): config_file.model.template.plugins["default"]["tests"] = False config_file.save() project_name = "My.App" with temp_dir.as_cwd(): result = hatch("new", project_name) assert result.exit_code == 0, result.output project_path = temp_dir / "my-app" data_path = temp_dir / "data" data_path.mkdir() project = Project(project_path) config = dict(project.raw_config) config["tool"]["hatch"]["envs"] = {"hatch-test": {"retries": 2}} project.save_config(config) with project_path.as_cwd(env_vars={ConfigEnvVars.DATA: str(data_path)}): result = hatch("test") assert result.exit_code == 0, result.output assert not result.output assert env_run.call_args_list == [ mocker.call("pytest -p no:randomly -r aR --reruns 2 tests", shell=True), ] assert not (data_path / ".config" / "coverage").exists()
TestRetries
python
python-pillow__Pillow
src/PIL/ImageTk.py
{ "start": 5984, "end": 8132 }
class ____: """ A Tkinter-compatible bitmap image. This can be used everywhere Tkinter expects an image object. The given image must have mode "1". Pixels having value 0 are treated as transparent. Options, if any, are passed on to Tkinter. The most commonly used option is ``foreground``, which is used to specify the color for the non-transparent parts. See the Tkinter documentation for information on how to specify colours. :param image: A PIL image. """ def __init__(self, image: Image.Image | None = None, **kw: Any) -> None: # Tk compatibility: file or data if image is None: image = _get_image_from_kw(kw) if image is None: msg = "Image is required" raise ValueError(msg) self.__mode = image.mode self.__size = image.size self.__photo = tkinter.BitmapImage(data=image.tobitmap(), **kw) def __del__(self) -> None: try: name = self.__photo.name except AttributeError: return self.__photo.name = None try: self.__photo.tk.call("image", "delete", name) except Exception: pass # ignore internal errors def width(self) -> int: """ Get the width of the image. :return: The width, in pixels. """ return self.__size[0] def height(self) -> int: """ Get the height of the image. :return: The height, in pixels. """ return self.__size[1] def __str__(self) -> str: """ Get the Tkinter bitmap image identifier. This method is automatically called by Tkinter whenever a BitmapImage object is passed to a Tkinter method. :return: A Tkinter bitmap image identifier (a string). """ return str(self.__photo) def getimage(photo: PhotoImage) -> Image.Image: """Copies the contents of a PhotoImage to a PIL image memory.""" im = Image.new("RGBA", (photo.width(), photo.height())) _pyimagingtkcall("PyImagingPhotoGet", photo, im.getim()) return im
BitmapImage
python
tensorflow__tensorflow
tensorflow/python/ops/ragged/ragged_map_fn_op_test.py
{ "start": 1715, "end": 12511 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): @parameterized.parameters([ # The following test sets map over a RaggedTensor and apply a # transformation that returns with shape: # [d1, (d2)] -> [d1] dict( fn=mo.reduce_mean, elems=[[1, 2, 3], [4, 5], [6, 7]], elems_dtype=dtypes.int32, expected_output=[2, 4, 6], result_dtype=dtypes.int32, ), dict( fn=string_ops.reduce_join, elems=[['foo', 'bar', 'baz'], ['a'], ['b', 'c']], expected_output=[b'foobarbaz', b'a', b'bc'], elems_dtype=dtypes.string, result_dtype=dtypes.string, ), # [d1, (d2)] -> [d1, 2] dict( fn=_stack_mean_and_sum, elems=[[1, 2, 3], [4, 5], [6, 7]], expected_output=[[2, 6], [4.5, 9], [6.5, 13]], elems_dtype=dtypes.float32, result_dtype=dtypes.float32, expected_ragged_rank=0, ), # [d1, (d2)] -> [d1, (d2)] dict( fn=lambda x: x + np.int64(1), elems=[[1, 2, 3], [4, 5], [6, 7]], expected_output=[[2, 3, 4], [5, 6], [7, 8]], elems_dtype=dtypes.int64, result_dtype=ragged_tensor.RaggedTensorType( dtype=dtypes.int64, ragged_rank=1), ), # [d1, (d2), d3] -> [d1, (d2), d3] dict( fn=lambda x: x + np.int64(1), elems=[[[1, 2], [3, 4]], [], [[5, 6], [7, 8], [9, 0]]], elems_ragged_rank=1, expected_ragged_rank=1, result_dtype=ragged_tensor.RaggedTensorType( dtype=dtypes.int64, ragged_rank=1), expected_output=[[[2, 3], [4, 5]], [], [[6, 7], [8, 9], [10, 1]]], ), # [d1, (d2)] -> [d1, (d2), (d3)] dict( fn=lambda x: ragged_tensor.RaggedTensor.from_row_starts(x, [0]), elems=[[1, 2, 3], [4, 5], [6, 7]], expected_output=[[[1, 2, 3]], [[4, 5]], [[6, 7]]], result_dtype=ragged_tensor.RaggedTensorType( dtype=dtypes.int64, ragged_rank=2), ), # [d1, (d2), (d3)] -> [d1, (d2), (d3)] dict( fn=lambda x: ragged_functional_ops.map_flat_values(mo.add, x, 1), elems=[[[1, 2, 3]], [[4, 5], [6, 7]]], expected_output=[[[2, 3, 4]], [[5, 6], [7, 8]]], result_dtype=ragged_tensor.RaggedTensorType( dtype=dtypes.int64, ragged_rank=2), ), # [d1, (d2), (d3)] -> [d1, (d2)] dict( fn=lambda x: ragged_math_ops.reduce_sum(x, axis=1), elems=[[[1, 2, 3]], [[4, 5], [6, 7]]], expected_output=[[6], [9, 13]], result_dtype=ragged_tensor.RaggedTensorType( dtype=dtypes.int64, ragged_rank=1), ), # [d1, (d2), (d3)] -> [d1, (d3)] dict( fn=lambda x: ragged_math_ops.reduce_sum(x, axis=0), elems=[[[1, 2, 3]], [[4, 5], [6, 7]]], expected_output=[[1, 2, 3], [10, 12]], result_dtype=ragged_tensor.RaggedTensorType( dtype=dtypes.int64, ragged_rank=1), ), # [d1, (d2), (d3)] -> [d1] dict( fn=ragged_math_ops.reduce_sum, elems=[[[1, 2, 3]], [[4, 5], [6, 7]]], expected_output=[6, 22], result_dtype=dtypes.int64, ), # [d1] -> [d1, (d2)] dict( fn=mo.range, elems=[4, 0, 2], expected_output=[[0, 1, 2, 3], [], [0, 1]], result_dtype=ragged_tensor.RaggedTensorType( dtype=dtypes.int64, ragged_rank=1), ), # [d1] -> [d1, (d2), (d3)] dict( fn=lambda x: ragged_math_ops.range(mo.range(x)), elems=[5, 0, 3], expected_output=[[[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3]], [], [[], [0], [0, 1]]], result_dtype=ragged_tensor.RaggedTensorType( dtype=dtypes.int64, ragged_rank=2), ), # [d1, (d2), (d3), (d4a), (d5)] -> [d1, (d2), (d3), (d4b), (d5)] dict( fn=lambda x: x + np.int64(1), elems=[[[[[1, 2, 3]], [[4], [5]]]], [[[[6, 7]]], [[[8], []]]]], expected_output=[[[[[2, 3, 4]], [[5], [6]]]], [[[[7, 8]]], [[[9], []]]]], result_dtype=ragged_tensor.RaggedTensorType( dtype=dtypes.int64, ragged_rank=4), ), # [d1] -> [d1, (d2), (d3)] dict( fn=ragged_math_ops.range, elems=np.array([1, 2, 3], np.int64), expected_output=[[[0]], [[0, 1]], [[0, 1, 2]]], result_dtype=ragged_tensor.RaggedTensorType( dtype=dtypes.int64, ragged_rank=2)), # [0] -> [0, (d2), (d3)] (github issue #36232) dict( fn=ragged_math_ops.range, elems=np.zeros([0], np.int64), expected_output=[], expected_ragged_rank=2, result_dtype=ragged_tensor.RaggedTensorType( dtype=dtypes.int64, ragged_rank=2)), ]) def testRaggedMap( self, fn, elems, expected_output, expected_ragged_rank=None, result_ragged_rank=None, elems_ragged_rank=None, elems_dtype=dtypes.int64, result_dtype=None, infer_shape=True, ): elems = ragged_factory_ops.constant(elems, elems_dtype, elems_ragged_rank) output = ragged_map_ops.map_fn( fn=fn, elems=elems, dtype=result_dtype, infer_shape=infer_shape) expected_rt = ragged_factory_ops.constant( expected_output, ragged_rank=expected_ragged_rank) self.assertAllEqual(expected_rt, output) def testRaggedMapOnStructure(self): batman = ragged_factory_ops.constant([[1, 2, 3], [4], [5, 6, 7]]) # [[10, 20, 30], [40], [50, 60, 70]] robin = ragged_functional_ops.map_flat_values(mo.multiply, batman, 10) features = {'batman': batman, 'robin': robin} def _reduce_sum_from_all(f): return mo.reduce_sum(f['batman']) + mo.reduce_sum(f['robin']) output = ragged_map_ops.map_fn( fn=_reduce_sum_from_all, elems=features, dtype=dtypes.int32, ) self.assertAllEqual(output, [66, 44, 198]) # Test mapping over a dict of RTs can produce a dict of RTs. def testRaggedMapOnStructure_RaggedOutputs(self): batman = ragged_factory_ops.constant([[1, 2, 3], [4], [5, 6, 7]]) # [[10, 20, 30], [40], [50, 60, 70]] robin = ragged_functional_ops.map_flat_values(mo.multiply, batman, 10) features = {'batman': batman, 'robin': robin} def _increment(f): return { 'batman': f['batman'] + 1, 'robin': f['robin'] + 1, } output = ragged_map_ops.map_fn( fn=_increment, elems=features, infer_shape=False, dtype={ 'batman': ragged_tensor.RaggedTensorType( dtype=dtypes.int32, ragged_rank=1), 'robin': ragged_tensor.RaggedTensorType( dtype=dtypes.int32, ragged_rank=1) }, ) self.assertAllEqual(output['batman'], [[2, 3, 4], [5], [6, 7, 8]]) self.assertAllEqual(output['robin'], [[11, 21, 31], [41], [51, 61, 71]]) def testZip(self): x = ragged_factory_ops.constant( [[10, 20], [30, 40], [50, 60], [70], [80, 90, 100]], dtypes.int64) y = array_ops.expand_dims(mo.range(x.nrows(out_type=dtypes.int64)), axis=1) def _zip(foo): y_val, x_val = foo bar = array_ops.tile(y_val, array_ops.shape(x_val)) return array_ops_stack.stack([bar, x_val], axis=1) output = ragged_map_ops.map_fn( _zip, (y, x), dtype=ragged_tensor.RaggedTensorType(dtype=dtypes.int64, ragged_rank=1), infer_shape=False) self.assertAllEqual( output, [[[0, 10], [0, 20]], [[1, 30], [1, 40]], [[2, 50], [2, 60]], [[3, 70]], [[4, 80], [4, 90], [4, 100]]]) def testBatchGather(self): tokens = ragged_factory_ops.constant([['hello', '.', 'there'], ['merhaba'], ['bonjour', '.', 'ca va', '?']]) indices = ragged_factory_ops.constant([[0, 2], [0], [0, 2]]) def gather(x): tokens_val, indices_val = x return array_ops.gather(tokens_val, indices_val) data = tokens, indices out = ragged_map_ops.map_fn( gather, data, dtype=ragged_tensor.RaggedTensorType( dtype=dtypes.string, ragged_rank=1), infer_shape=False) self.assertAllEqual( out, [[b'hello', b'there'], [b'merhaba'], [b'bonjour', b'ca va']]) def testMismatchRaggedRank(self): elems = ragged_factory_ops.constant([[[1, 2, 3]], [[4, 5], [6, 7]]]) fn = lambda x: ragged_math_ops.reduce_sum(x, axis=0) with self.assertRaisesRegex( ValueError, r'(?s)Expected `fn` to return.*But it returned.*'): _ = ragged_map_ops.map_fn( fn, elems, dtype=ragged_tensor.RaggedTensorType( dtype=dtypes.int64, ragged_rank=23)) def testMismatchRaggedRank2(self): elems = ragged_factory_ops.constant([[1, 2, 3], [4, 5], [6, 7]]) fn = lambda x: ragged_tensor.RaggedTensor.from_row_starts(x, [0]) with self.assertRaisesRegex( ValueError, r'(?s)Expected `fn` to return.*But it returned.*'): _ = ragged_map_ops.map_fn( fn, elems, dtype=ragged_tensor.RaggedTensorType( dtype=dtypes.int64, ragged_rank=10)) def testMapOnSparseTensor(self): s = sparse_tensor.SparseTensor( indices=[[0, 0], [0, 1], [1, 0], [1, 1]], values=[0, 5, 0, 4], dense_shape=[2, 2], ) t2 = ragged_tensor.RaggedTensor.from_sparse(s) id_t2 = ragged_map_ops.map_fn( lambda x: x, t2, ) self.assertAllEqual(id_t2, [[0, 5], [0, 4]]) def testRaggedMapWithIncorrectFnOutputSignature(self): x = ragged_factory_ops.constant([[1, 2, 3, 4], [1]]) with self.assertRaisesRegex(errors.InvalidArgumentError, 'All flat_values must have compatible shapes'): y = map_fn_lib.map_fn(lambda r: map_fn_lib.map_fn(lambda y: r, r), x) self.evaluate(y) def testNestedRaggedMapWithFnOutputSignature(self): ragged1d = ragged_tensor.RaggedTensorSpec([None], dtypes.int32) ragged2d = ragged_tensor.RaggedTensorSpec([None, None], dtypes.int32) x = ragged_factory_ops.constant([[1, 2, 3, 4], [1]]) # pylint: disable=g-long-lambda y = map_fn_lib.map_fn( lambda r: map_fn_lib.map_fn( lambda y: r, r, fn_output_signature=ragged1d), x, fn_output_signature=ragged2d) expected = [[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]], [[1]]] self.assertAllEqual(y, expected) if __name__ == '__main__': googletest.main()
RaggedMapOpTest
python
pytorch__pytorch
torch/_inductor/compile_fx_ext.py
{ "start": 1326, "end": 2414 }
class ____: """ This handles the data for serializing Virtualized. """ # The values here get serialized. We don't grab everything because some of # the fields can't be serialized. aot_compilation: Any = None choices: Any = None local_buffer_context: Any = None ops: Any = None kernel: Any = None current_node: Any = None @classmethod def serialize(cls) -> _VirtualizedSerializer: """ Turn the current state of torch._inductor.virtualized.V into a serializable structure. """ kwargs = {} for f in dataclasses.fields(cls): kwargs[f.name] = getattr(V, f.name) return _VirtualizedSerializer(**kwargs) def patch(self) -> _VirtualizedSerializerContextManager: """ Returns a context manager which patches the saved values into the current environment. While patched, any value not listed above will be poisoned so that reads will raise an error. """ return _VirtualizedSerializerContextManager(self)
_VirtualizedSerializer
python
pytorch__pytorch
torch/nn/modules/loss.py
{ "start": 72772, "end": 77061 }
class ____(_WeightedLoss): r"""Creates a criterion that optimizes a multi-class classification hinge loss (margin-based loss) between input :math:`x` (a 2D mini-batch `Tensor`) and output :math:`y` (which is a 1D tensor of target class indices, :math:`0 \leq y \leq \text{x.size}(1)-1`): For each mini-batch sample, the loss in terms of the 1D input :math:`x` and scalar output :math:`y` is: .. math:: \text{loss}(x, y) = \frac{\sum_i \max(0, \text{margin} - x[y] + x[i])^p}{\text{x.size}(0)} where :math:`i \in \left\{0, \; \cdots , \; \text{x.size}(0) - 1\right\}` and :math:`i \neq y`. Optionally, you can give non-equal weighting on the classes by passing a 1D :attr:`weight` tensor into the constructor. The loss function then becomes: .. math:: \text{loss}(x, y) = \frac{\sum_i w[y] * \max(0, \text{margin} - x[y] + x[i])^p}{\text{x.size}(0)} Args: p (int, optional): Has a default value of :math:`1`. :math:`1` and :math:`2` are the only supported values. margin (float, optional): Has a default value of :math:`1`. weight (Tensor, optional): a manual rescaling weight given to each class. If given, it has to be a Tensor of size `C`. Otherwise, it is treated as if having all ones. size_average (bool, optional): Deprecated (see :attr:`reduction`). By default, the losses are averaged over each loss element in the batch. Note that for some losses, there are multiple elements per sample. If the field :attr:`size_average` is set to ``False``, the losses are instead summed for each minibatch. Ignored when :attr:`reduce` is ``False``. Default: ``True`` reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the losses are averaged or summed over observations for each minibatch depending on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per batch element instead and ignores :attr:`size_average`. Default: ``True`` reduction (str, optional): Specifies the reduction to apply to the output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied, ``'mean'``: the sum of the output will be divided by the number of elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average` and :attr:`reduce` are in the process of being deprecated, and in the meantime, specifying either of those two args will override :attr:`reduction`. Default: ``'mean'`` Shape: - Input: :math:`(N, C)` or :math:`(C)`, where :math:`N` is the batch size and :math:`C` is the number of classes. - Target: :math:`(N)` or :math:`()`, where each value is :math:`0 \leq \text{targets}[i] \leq C-1`. - Output: scalar. If :attr:`reduction` is ``'none'``, then same shape as the target. Examples: >>> loss = nn.MultiMarginLoss() >>> x = torch.tensor([[0.1, 0.2, 0.4, 0.8]]) >>> y = torch.tensor([3]) >>> # 0.25 * ((1-(0.8-0.1)) + (1-(0.8-0.2)) + (1-(0.8-0.4))) >>> loss(x, y) tensor(0.32...) """ __constants__ = ["p", "margin", "reduction"] margin: float p: int def __init__( self, p: int = 1, margin: float = 1.0, weight: Optional[Tensor] = None, size_average=None, reduce=None, reduction: str = "mean", ) -> None: super().__init__(weight, size_average, reduce, reduction) if p != 1 and p != 2: raise ValueError("only p == 1 and p == 2 supported") if weight is not None and weight.dim() != 1: raise ValueError( f"MultiMarginLoss: expected weight to be None or 1D tensor, got {weight.dim()}D instead" ) self.p = p self.margin = margin def forward(self, input: Tensor, target: Tensor) -> Tensor: """Runs the forward pass.""" return F.multi_margin_loss( input, target, p=self.p, margin=self.margin, weight=self.weight, reduction=self.reduction, )
MultiMarginLoss
python
redis__redis-py
redis/commands/search/result.py
{ "start": 91, "end": 2624 }
class ____: """ Represents the result of a search query, and has an array of Document objects """ def __init__( self, res, hascontent, duration=0, has_payload=False, with_scores=False, field_encodings: Optional[dict] = None, ): """ - duration: the execution time of the query - has_payload: whether the query has payloads - with_scores: whether the query has scores - field_encodings: a dictionary of field encodings if any is provided """ self.total = res[0] self.duration = duration self.docs = [] step = 1 if hascontent: step = step + 1 if has_payload: step = step + 1 if with_scores: step = step + 1 offset = 2 if with_scores else 1 for i in range(1, len(res), step): id = to_string(res[i]) payload = to_string(res[i + offset]) if has_payload else None # fields_offset = 2 if has_payload else 1 fields_offset = offset + 1 if has_payload else offset score = float(res[i + 1]) if with_scores else None fields = {} if hascontent and res[i + fields_offset] is not None: keys = map(to_string, res[i + fields_offset][::2]) values = res[i + fields_offset][1::2] for key, value in zip(keys, values): if field_encodings is None or key not in field_encodings: fields[key] = to_string(value) continue encoding = field_encodings[key] # If the encoding is None, we don't need to decode the value if encoding is None: fields[key] = value else: fields[key] = to_string(value, encoding=encoding) try: del fields["id"] except KeyError: pass try: fields["json"] = fields["$"] del fields["$"] except KeyError: pass doc = ( Document(id, score=score, payload=payload, **fields) if with_scores else Document(id, payload=payload, **fields) ) self.docs.append(doc) def __repr__(self) -> str: return f"Result{{{self.total} total, docs: {self.docs}}}"
Result
python
pydantic__pydantic
tests/typechecking/decorators.py
{ "start": 3276, "end": 3833 }
class ____(BaseModel): # Mypy somehow reports "Cannot infer function type argument" here: @model_validator(mode='after') # type:ignore[misc] # pyright: ignore[reportArgumentType] def missing_return_value(self) -> None: ... @model_validator(mode='after') def valid_method_no_info(self) -> Self: ... @model_validator(mode='after') def valid_method_info_default(self, info: ValidationInfo) -> Self: ... @model_validator(mode='after') def valid_method_info(self, info: ValidationInfo[int]) -> Self: ...
AfterModelValidator
python
huggingface__transformers
src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py
{ "start": 3458, "end": 3542 }
class ____(Qwen2VLTextConfig): model_type = "qwen2_5_vl_text"
Qwen2_5_VLTextConfig
python
sqlalchemy__sqlalchemy
test/orm/test_unitofworkv2.py
{ "start": 2731, "end": 26145 }
class ____(UOWTest): def test_one_to_many_save(self): users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively( User, users, properties={"addresses": relationship(Address)} ) self.mapper_registry.map_imperatively(Address, addresses) sess = fixture_session() a1, a2 = Address(email_address="a1"), Address(email_address="a2") u1 = User(name="u1", addresses=[a1, a2]) sess.add(u1) self.assert_sql_execution( testing.db, sess.flush, CompiledSQL( "INSERT INTO users (name) VALUES (:name)", {"name": "u1"} ), Conditional( testing.db.dialect.insert_executemany_returning, [ CompiledSQL( "INSERT INTO addresses (user_id, email_address) " "VALUES (:user_id, :email_address) " "RETURNING addresses.id", lambda ctx: [ {"email_address": "a1", "user_id": u1.id}, {"email_address": "a2", "user_id": u1.id}, ], ), ], [ CompiledSQL( "INSERT INTO addresses (user_id, email_address) " "VALUES (:user_id, :email_address)", lambda ctx: {"email_address": "a1", "user_id": u1.id}, ), CompiledSQL( "INSERT INTO addresses (user_id, email_address) " "VALUES (:user_id, :email_address)", lambda ctx: {"email_address": "a2", "user_id": u1.id}, ), ], ), ) def test_one_to_many_delete_all(self): users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively( User, users, properties={"addresses": relationship(Address)} ) self.mapper_registry.map_imperatively(Address, addresses) sess = fixture_session() a1, a2 = Address(email_address="a1"), Address(email_address="a2") u1 = User(name="u1", addresses=[a1, a2]) sess.add(u1) sess.flush() sess.delete(u1) sess.delete(a1) sess.delete(a2) self.assert_sql_execution( testing.db, sess.flush, CompiledSQL( "DELETE FROM addresses WHERE addresses.id = :id", [{"id": a1.id}, {"id": a2.id}], ), CompiledSQL( "DELETE FROM users WHERE users.id = :id", {"id": u1.id} ), ) def test_one_to_many_delete_parent(self): users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively( User, users, properties={"addresses": relationship(Address)} ) self.mapper_registry.map_imperatively(Address, addresses) sess = fixture_session() a1, a2 = Address(email_address="a1"), Address(email_address="a2") u1 = User(name="u1", addresses=[a1, a2]) sess.add(u1) sess.flush() sess.delete(u1) self.assert_sql_execution( testing.db, sess.flush, CompiledSQL( "UPDATE addresses SET user_id=:user_id WHERE " "addresses.id = :addresses_id", lambda ctx: [ {"addresses_id": a1.id, "user_id": None}, {"addresses_id": a2.id, "user_id": None}, ], ), CompiledSQL( "DELETE FROM users WHERE users.id = :id", {"id": u1.id} ), ) def test_many_to_one_save(self): users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively(User, users) self.mapper_registry.map_imperatively( Address, addresses, properties={"user": relationship(User)} ) sess = fixture_session() u1 = User(name="u1") a1, a2 = ( Address(email_address="a1", user=u1), Address(email_address="a2", user=u1), ) sess.add_all([a1, a2]) self.assert_sql_execution( testing.db, sess.flush, CompiledSQL( "INSERT INTO users (name) VALUES (:name)", {"name": "u1"} ), Conditional( testing.db.dialect.insert_executemany_returning, [ CompiledSQL( "INSERT INTO addresses (user_id, email_address) " "VALUES (:user_id, :email_address) " "RETURNING addresses.id", lambda ctx: [ {"email_address": "a1", "user_id": u1.id}, {"email_address": "a2", "user_id": u1.id}, ], ), ], [ CompiledSQL( "INSERT INTO addresses (user_id, email_address) " "VALUES (:user_id, :email_address)", lambda ctx: {"email_address": "a1", "user_id": u1.id}, ), CompiledSQL( "INSERT INTO addresses (user_id, email_address) " "VALUES (:user_id, :email_address)", lambda ctx: {"email_address": "a2", "user_id": u1.id}, ), ], ), ) def test_many_to_one_delete_all(self): users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively(User, users) self.mapper_registry.map_imperatively( Address, addresses, properties={"user": relationship(User)} ) sess = fixture_session() u1 = User(name="u1") a1, a2 = ( Address(email_address="a1", user=u1), Address(email_address="a2", user=u1), ) sess.add_all([a1, a2]) sess.flush() sess.delete(u1) sess.delete(a1) sess.delete(a2) self.assert_sql_execution( testing.db, sess.flush, CompiledSQL( "DELETE FROM addresses WHERE addresses.id = :id", [{"id": a1.id}, {"id": a2.id}], ), CompiledSQL( "DELETE FROM users WHERE users.id = :id", {"id": u1.id} ), ) def test_many_to_one_delete_target(self): users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively(User, users) self.mapper_registry.map_imperatively( Address, addresses, properties={"user": relationship(User)} ) sess = fixture_session() u1 = User(name="u1") a1, a2 = ( Address(email_address="a1", user=u1), Address(email_address="a2", user=u1), ) sess.add_all([a1, a2]) sess.flush() sess.delete(u1) a1.user = a2.user = None self.assert_sql_execution( testing.db, sess.flush, CompiledSQL( "UPDATE addresses SET user_id=:user_id WHERE " "addresses.id = :addresses_id", lambda ctx: [ {"addresses_id": a1.id, "user_id": None}, {"addresses_id": a2.id, "user_id": None}, ], ), CompiledSQL( "DELETE FROM users WHERE users.id = :id", {"id": u1.id} ), ) def test_many_to_one_delete_unloaded(self): users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively(User, users) self.mapper_registry.map_imperatively( Address, addresses, properties={"parent": relationship(User)} ) parent = User(name="p1") c1, c2 = ( Address(email_address="c1", parent=parent), Address(email_address="c2", parent=parent), ) session = fixture_session() session.add_all([c1, c2]) session.add(parent) session.flush() pid = parent.id c1id = c1.id c2id = c2.id session.expire(parent) session.expire(c1) session.expire(c2) session.delete(c1) session.delete(c2) session.delete(parent) # testing that relationships # are loaded even if all ids/references are # expired self.assert_sql_execution( testing.db, session.flush, AllOf( # [ticket:2002] - ensure the m2os are loaded. # the selects here are in fact unexpiring # each row - the m2o comes from the identity map. # the User row might be handled before or the addresses # are loaded so need to use AllOf CompiledSQL( "SELECT addresses.id, addresses.user_id, " "addresses.email_address " "FROM addresses " "WHERE addresses.id = " ":pk_1", lambda ctx: {"pk_1": c1id}, ), CompiledSQL( "SELECT addresses.id, addresses.user_id, " "addresses.email_address " "FROM addresses " "WHERE addresses.id = " ":pk_1", lambda ctx: {"pk_1": c2id}, ), CompiledSQL( "SELECT users.id, users.name " "FROM users WHERE users.id = :pk_1", lambda ctx: {"pk_1": pid}, ), CompiledSQL( "DELETE FROM addresses WHERE addresses.id = :id", lambda ctx: [{"id": c1id}, {"id": c2id}], ), CompiledSQL( "DELETE FROM users WHERE users.id = :id", lambda ctx: {"id": pid}, ), ), ) def test_many_to_one_delete_childonly_unloaded(self): users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively(User, users) self.mapper_registry.map_imperatively( Address, addresses, properties={"parent": relationship(User)} ) parent = User(name="p1") c1, c2 = ( Address(email_address="c1", parent=parent), Address(email_address="c2", parent=parent), ) session = fixture_session() session.add_all([c1, c2]) session.add(parent) session.flush() # pid = parent.id c1id = c1.id c2id = c2.id session.expire(c1) session.expire(c2) session.delete(c1) session.delete(c2) self.assert_sql_execution( testing.db, session.flush, AllOf( # [ticket:2049] - we aren't deleting User, # relationship is simple m2o, no SELECT should be emitted for # it. CompiledSQL( "SELECT addresses.id, addresses.user_id, " "addresses.email_address " "FROM addresses " "WHERE addresses.id = " ":pk_1", lambda ctx: {"pk_1": c1id}, ), CompiledSQL( "SELECT addresses.id, addresses.user_id, " "addresses.email_address " "FROM addresses " "WHERE addresses.id = " ":pk_1", lambda ctx: {"pk_1": c2id}, ), ), CompiledSQL( "DELETE FROM addresses WHERE addresses.id = :id", lambda ctx: [{"id": c1id}, {"id": c2id}], ), ) def test_many_to_one_delete_childonly_unloaded_expired(self): users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively(User, users) self.mapper_registry.map_imperatively( Address, addresses, properties={"parent": relationship(User)} ) parent = User(name="p1") c1, c2 = ( Address(email_address="c1", parent=parent), Address(email_address="c2", parent=parent), ) session = fixture_session() session.add_all([c1, c2]) session.add(parent) session.flush() # pid = parent.id c1id = c1.id c2id = c2.id session.expire(parent) session.expire(c1) session.expire(c2) session.delete(c1) session.delete(c2) self.assert_sql_execution( testing.db, session.flush, AllOf( # the parent User is expired, so it gets loaded here. CompiledSQL( "SELECT addresses.id, addresses.user_id, " "addresses.email_address " "FROM addresses " "WHERE addresses.id = " ":pk_1", lambda ctx: {"pk_1": c1id}, ), CompiledSQL( "SELECT addresses.id, addresses.user_id, " "addresses.email_address " "FROM addresses " "WHERE addresses.id = " ":pk_1", lambda ctx: {"pk_1": c2id}, ), ), CompiledSQL( "DELETE FROM addresses WHERE addresses.id = :id", lambda ctx: [{"id": c1id}, {"id": c2id}], ), ) def test_many_to_one_del_attr(self): users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively(User, users) self.mapper_registry.map_imperatively( Address, addresses, properties={"user": relationship(User)} ) sess = fixture_session() u1 = User(name="u1") a1, a2 = ( Address(email_address="a1", user=u1), Address(email_address="a2", user=u1), ) sess.add_all([a1, a2]) sess.flush() del a1.user self.assert_sql_execution( testing.db, sess.flush, CompiledSQL( "UPDATE addresses SET user_id=:user_id WHERE " "addresses.id = :addresses_id", lambda ctx: [{"addresses_id": a1.id, "user_id": None}], ), ) def test_many_to_one_del_attr_unloaded(self): users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively(User, users) self.mapper_registry.map_imperatively( Address, addresses, properties={"user": relationship(User)} ) sess = fixture_session() u1 = User(name="u1") a1, a2 = ( Address(email_address="a1", user=u1), Address(email_address="a2", user=u1), ) sess.add_all([a1, a2]) sess.flush() # trying to guarantee that the history only includes # PASSIVE_NO_RESULT for "deleted" and nothing else sess.expunge(u1) sess.expire(a1, ["user"]) del a1.user sess.add(a1) self.assert_sql_execution( testing.db, sess.flush, CompiledSQL( "UPDATE addresses SET user_id=:user_id WHERE " "addresses.id = :addresses_id", lambda ctx: [{"addresses_id": a1.id, "user_id": None}], ), ) def test_natural_ordering(self): """test that unconnected items take relationship() into account regardless.""" users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively(User, users) self.mapper_registry.map_imperatively( Address, addresses, properties={"parent": relationship(User)} ) sess = fixture_session() u1 = User(id=1, name="u1") a1 = Address(id=1, user_id=1, email_address="a2") sess.add_all([u1, a1]) self.assert_sql_execution( testing.db, sess.flush, CompiledSQL( "INSERT INTO users (id, name) VALUES (:id, :name)", {"id": 1, "name": "u1"}, ), CompiledSQL( "INSERT INTO addresses (id, user_id, email_address) " "VALUES (:id, :user_id, :email_address)", {"email_address": "a2", "user_id": 1, "id": 1}, ), ) sess.delete(u1) sess.delete(a1) self.assert_sql_execution( testing.db, sess.flush, CompiledSQL( "DELETE FROM addresses WHERE addresses.id = :id", [{"id": 1}] ), CompiledSQL("DELETE FROM users WHERE users.id = :id", [{"id": 1}]), ) def test_natural_selfref(self): """test that unconnected items take relationship() into account regardless.""" Node, nodes = self.classes.Node, self.tables.nodes self.mapper_registry.map_imperatively( Node, nodes, properties={"children": relationship(Node)} ) sess = fixture_session() n1 = Node(id=1) n2 = Node(id=2, parent_id=1) n3 = Node(id=3, parent_id=2) # insert order is determined from add order since they # are the same class sess.add_all([n1, n2, n3]) self.assert_sql_execution( testing.db, sess.flush, CompiledSQL( "INSERT INTO nodes (id, parent_id, data) VALUES " "(:id, :parent_id, :data)", [ {"parent_id": None, "data": None, "id": 1}, {"parent_id": 1, "data": None, "id": 2}, {"parent_id": 2, "data": None, "id": 3}, ], ), ) def test_many_to_many(self): keywords, items, item_keywords, Keyword, Item = ( self.tables.keywords, self.tables.items, self.tables.item_keywords, self.classes.Keyword, self.classes.Item, ) self.mapper_registry.map_imperatively( Item, items, properties={ "keywords": relationship(Keyword, secondary=item_keywords) }, ) self.mapper_registry.map_imperatively(Keyword, keywords) sess = fixture_session() k1 = Keyword(name="k1") i1 = Item(description="i1", keywords=[k1]) sess.add(i1) self.assert_sql_execution( testing.db, sess.flush, CompiledSQL( "INSERT INTO items (description) VALUES (:description)", {"description": "i1"}, ), CompiledSQL( "INSERT INTO keywords (name) VALUES (:name)", {"name": "k1"}, ), CompiledSQL( "INSERT INTO item_keywords (item_id, keyword_id) " "VALUES (:item_id, :keyword_id)", lambda ctx: {"item_id": i1.id, "keyword_id": k1.id}, ), ) # test that keywords collection isn't loaded sess.expire(i1, ["keywords"]) i1.description = "i2" self.assert_sql_execution( testing.db, sess.flush, CompiledSQL( "UPDATE items SET description=:description " "WHERE items.id = :items_id", lambda ctx: {"description": "i2", "items_id": i1.id}, ), ) def test_m2o_flush_size(self): users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively(User, users) self.mapper_registry.map_imperatively( Address, addresses, properties={"user": relationship(User, passive_updates=True)}, ) sess = fixture_session() u1 = User(name="ed") sess.add(u1) self._assert_uow_size(sess, 2) def test_o2m_flush_size(self): users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively( User, users, properties={"addresses": relationship(Address)} ) self.mapper_registry.map_imperatively(Address, addresses) with fixture_session(autoflush=False) as sess: u1 = User(name="ed") sess.add(u1) self._assert_uow_size(sess, 2) sess.flush() u1.name = "jack" self._assert_uow_size(sess, 2) sess.flush() a1 = Address(email_address="foo") sess.add(a1) sess.flush() u1.addresses.append(a1) self._assert_uow_size(sess, 6) sess.commit() with fixture_session(autoflush=False) as sess: u1 = sess.query(User).first() u1.name = "ed" self._assert_uow_size(sess, 2) u1.addresses self._assert_uow_size(sess, 6)
RudimentaryFlushTest
python
ray-project__ray
doc/source/serve/doc_code/intel_gaudi_inference_serve_deepspeed.py
{ "start": 4909, "end": 6137 }
class ____(TextStreamer): def __init__( self, tokenizer, skip_prompt: bool = False, timeout: int = None, **decode_kwargs: Dict[str, Any], ): super().__init__(tokenizer, skip_prompt, **decode_kwargs) self.text_queue = Queue() self.stop_signal = None self.timeout = timeout def on_finalized_text(self, text: str, stream_end: bool = False): self.text_queue.put(text, timeout=self.timeout) if stream_end: self.text_queue.put(self.stop_signal, timeout=self.timeout) def __iter__(self): return self def __next__(self): value = self.text_queue.get(timeout=self.timeout) if value == self.stop_signal: raise StopIteration() else: return value # __worker_def_end__ # __deploy_def_start__ # We need to set these variables for this example. HABANA_ENVS = { "PT_HPU_LAZY_ACC_PAR_MODE": "0", "PT_HPU_ENABLE_REFINE_DYNAMIC_SHAPES": "0", "PT_HPU_ENABLE_WEIGHT_CPU_PERMUTE": "0", "PT_HPU_ENABLE_LAZY_COLLECTIVES": "true", "HABANA_VISIBLE_MODULES": "0,1,2,3,4,5,6,7", } # Define the Ray Serve deployment. @serve.deployment
RayTextIteratorStreamer
python
nedbat__coveragepy
coverage/html.py
{ "start": 1890, "end": 2336 }
class ____: """The data for each source line of HTML output.""" tokens: list[tuple[str, str]] number: TLineNo category: str contexts: list[str] contexts_label: str context_list: list[str] short_annotations: list[str] long_annotations: list[str] html: str = "" context_str: str | None = None annotate: str | None = None annotate_long: str | None = None css_class: str = "" @dataclass
LineData
python
great-expectations__great_expectations
tests/integration/fluent/test_sql_datasources.py
{ "start": 6033, "end": 11064 }
class ____(TypedDict): id: int name: str quoted_upper_col: str quoted_lower_col: str quoted_mixed_case: str quoted_w_dots: str unquoted_upper_col: str unquoted_lower_col: str ColNameParams: TypeAlias = Literal[ # DDL: unquoted_lower_col ------ "unquoted_lower_col", '"unquoted_lower_col"', "UNQUOTED_LOWER_COL", '"UNQUOTED_LOWER_COL"', # DDL: UNQUOTED_UPPER_COL ------ "unquoted_upper_col", '"unquoted_upper_col"', "UNQUOTED_UPPER_COL", '"UNQUOTED_UPPER_COL"', # DDL: "quoted_lower_col" ----- "quoted_lower_col", '"quoted_lower_col"', "QUOTED_LOWER_COL", '"QUOTED_LOWER_COL"', # DDL: "QUOTED_UPPER_COL" ---- "quoted_upper_col", '"quoted_upper_col"', "QUOTED_UPPER_COL", '"QUOTED_UPPER_COL"', # DDL: "quotedMixed" ----- "quotedmixed", "quotedMixed", '"quotedMixed"', "QUOTEDMIXED", # DDL: "quoted.w.dots" ------- "quoted.w.dots", '"quoted.w.dots"', "QUOTED.W.DOTS", '"QUOTED.W.DOTS"', ] ColNameParamId: TypeAlias = Literal[ # DDL: unquoted_lower_col ------ "str unquoted_lower_col", 'str "unquoted_lower_col"', "str UNQUOTED_LOWER_COL", 'str "UNQUOTED_LOWER_COL"', # DDL: UNQUOTED_UPPER_COL ------ "str unquoted_upper_col", 'str "unquoted_upper_col"', "str UNQUOTED_UPPER_COL", 'str "UNQUOTED_UPPER_COL"', # DDL: "quoted_lower_col" ----- "str quoted_lower_col", 'str "quoted_lower_col"', "str QUOTED_LOWER_COL", 'str "QUOTED_LOWER_COL"', # DDl: "QUOTED_UPPER_COL" ---- "str quoted_upper_col", 'str "quoted_upper_col"', "str QUOTED_UPPER_COL", 'str "QUOTED_UPPER_COL"', # DDL: "quotedMixed" ----- "str quotedmixed", "str quotedMixed", 'str "quotedMixed"', "str QUOTEDMIXED", # DDL: "quoted.w.dots" ------- "str quoted.w.dots", 'str "quoted.w.dots"', "str QUOTED.W.DOTS", 'str "QUOTED.W.DOTS"', ] COLUMN_DDL: Final[Mapping[ColNameParams, str]] = { # DDL: unquoted_lower_col ------ "unquoted_lower_col": UNQUOTED_LOWER_COL, '"unquoted_lower_col"': UNQUOTED_LOWER_COL, "UNQUOTED_LOWER_COL": UNQUOTED_LOWER_COL, '"UNQUOTED_LOWER_COL"': UNQUOTED_LOWER_COL, # DDL: UNQUOTED_UPPER_COL ------ "unquoted_upper_col": UNQUOTED_UPPER_COL, '"unquoted_upper_col"': UNQUOTED_UPPER_COL, "UNQUOTED_UPPER_COL": UNQUOTED_UPPER_COL, '"UNQUOTED_UPPER_COL"': UNQUOTED_UPPER_COL, # DDL: "quoted_lower_col" ----- "quoted_lower_col": f'"{QUOTED_LOWER_COL}"', '"quoted_lower_col"': f'"{QUOTED_LOWER_COL}"', "QUOTED_LOWER_COL": f'"{QUOTED_LOWER_COL}"', '"QUOTED_LOWER_COL"': f'"{QUOTED_LOWER_COL}"', # DDl: "QUOTED_UPPER_COL" ---- "quoted_upper_col": f'"{QUOTED_UPPER_COL}"', '"quoted_upper_col"': f'"{QUOTED_UPPER_COL}"', "QUOTED_UPPER_COL": f'"{QUOTED_UPPER_COL}"', '"QUOTED_UPPER_COL"': f'"{QUOTED_UPPER_COL}"', # DDL: "quotedMixed" ----- "quotedmixed": f"{QUOTED_MIXED_CASE.lower()}", "quotedMixed": f"{QUOTED_MIXED_CASE}", '"quotedMixed"': f'"{QUOTED_MIXED_CASE}"', "QUOTEDMIXED": f"{QUOTED_MIXED_CASE.upper()}", # DDL: "quoted.w.dots" ------- "quoted.w.dots": f'"{QUOTED_W_DOTS}"', '"quoted.w.dots"': f'"{QUOTED_W_DOTS}"', "QUOTED.W.DOTS": f'"{QUOTED_W_DOTS}"', '"QUOTED.W.DOTS"': f'"{QUOTED_W_DOTS}"', } # TODO: remove items from this lookup when working on fixes # The presence of a database type in the list indicates that this specific value fails when # used as the `column_name` value for at least one expectation. # It does not mean that it SHOULD or SHOULD NOT fail, but that it currently does. FAILS_EXPECTATION: Final[Mapping[ColNameParamId, list[DatabaseType]]] = { # DDL: unquoted_lower_col ------ "str unquoted_lower_col": [], 'str "unquoted_lower_col"': ["postgres", "sqlite"], "str UNQUOTED_LOWER_COL": ["postgres", "sqlite"], 'str "UNQUOTED_LOWER_COL"': ["sqlite"], # DDL: UNQUOTED_UPPER_COL ------ "str unquoted_upper_col": ["sqlite"], 'str "unquoted_upper_col"': ["postgres", "sqlite"], "str UNQUOTED_UPPER_COL": ["postgres"], 'str "UNQUOTED_UPPER_COL"': ["postgres", "sqlite"], # DDL: "quoted_lower_col" ----- 'str "quoted_lower_col"': ["postgres", "sqlite"], "str QUOTED_LOWER_COL": ["postgres", "sqlite"], 'str "QUOTED_LOWER_COL"': ["sqlite"], # DDl: "QUOTED_UPPER_COL" ---- "str quoted_upper_col": ["sqlite", "postgres"], 'str "quoted_upper_col"': ["sqlite"], "str QUOTED_UPPER_COL": [], 'str "QUOTED_UPPER_COL"': ["postgres", "sqlite"], # DDL: "quotedMixed" ----- "str quotedmixed": [ "postgres", "sqlite", ], 'str "quotedMixed"': [ "postgres", "sqlite", ], "str QUOTEDMIXED": [ "postgres", "sqlite", ], # DDL: "quoted.w.dots" ------- 'str "quoted.w.dots"': ["postgres", "sqlite"], "str QUOTED.W.DOTS": ["sqlite", "postgres"], 'str "QUOTED.W.DOTS"': ["sqlite"], }
Row
python
walkccc__LeetCode
solutions/2712. Minimum Cost to Make All Characters Equal/2712.py
{ "start": 0, "end": 227 }
class ____: def minimumCost(self, s: str) -> int: n = len(s) ans = 0 for i in range(1, n): if s[i] != s[i - 1]: # Invert s[0..i - 1] or s[i..n - 1]. ans += min(i, n - i) return ans
Solution
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 484533, "end": 485159 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field( sgqlc.types.list_of("OrganizationMemberEdge"), graphql_name="edges" ) nodes = sgqlc.types.Field(sgqlc.types.list_of("User"), graphql_name="nodes") page_info = sgqlc.types.Field( sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo" ) total_count = sgqlc.types.Field( sgqlc.types.non_null(Int), graphql_name="totalCount" )
OrganizationMemberConnection
python
wandb__wandb
wandb/agents/pyagent.py
{ "start": 1749, "end": 13585 }
class ____: FLAPPING_MAX_SECONDS = 60 FLAPPING_MAX_FAILURES = 3 MAX_INITIAL_FAILURES = 5 def __init__( self, sweep_id=None, project=None, entity=None, function=None, count=None ): self._sweep_path = sweep_id self._sweep_id = None self._project = project self._entity = entity self._function = function self._count = count # glob_config = os.path.expanduser('~/.config/wandb/settings') # loc_config = 'wandb/settings' # files = (glob_config, loc_config) self._api = InternalApi() self._agent_id = None self._max_initial_failures = wandb.env.get_agent_max_initial_failures( self.MAX_INITIAL_FAILURES ) # if the directory to log to is not set, set it if os.environ.get(wandb.env.DIR) is None: os.environ[wandb.env.DIR] = os.path.abspath(os.getcwd()) def _init(self): # These are not in constructor so that Agent instance can be rerun self._run_threads = {} self._run_status = {} self._queue = queue.Queue() self._exit_flag = False self._exceptions = {} self._start_time = time.time() def _register(self): logger.debug("Agent._register()") agent = self._api.register_agent(socket.gethostname(), sweep_id=self._sweep_id) self._agent_id = agent["id"] logger.debug(f"agent_id = {self._agent_id}") def _setup(self): logger.debug("Agent._setup()") self._init() parts = dict(entity=self._entity, project=self._project, name=self._sweep_path) err = sweep_utils.parse_sweep_id(parts) if err: wandb.termerror(err) return entity = parts.get("entity") or self._entity project = parts.get("project") or self._project sweep_id = parts.get("name") or self._sweep_id if sweep_id: os.environ[wandb.env.SWEEP_ID] = sweep_id if entity: wandb.env.set_entity(entity) if project: wandb.env.set_project(project) if sweep_id: self._sweep_id = sweep_id self._register() def _stop_run(self, run_id): logger.debug(f"Stopping run {run_id}.") self._run_status[run_id] = RunStatus.STOPPED thread = self._run_threads.get(run_id) if thread: _terminate_thread(thread) def _stop_all_runs(self): logger.debug("Stopping all runs.") for run in list(self._run_threads.keys()): self._stop_run(run) def _exit(self): self._stop_all_runs() self._exit_flag = True # _terminate_thread(self._main_thread) def _heartbeat(self): while True: if self._exit_flag: return # if not self._main_thread.is_alive(): # return run_status = { run: True for run, status in self._run_status.items() if status in (RunStatus.QUEUED, RunStatus.RUNNING) } commands = self._api.agent_heartbeat(self._agent_id, {}, run_status) if commands: job = Job(commands[0]) logger.debug(f"Job received: {job}") if job.type in ["run", "resume"]: self._queue.put(job) self._run_status[job.run_id] = RunStatus.QUEUED elif job.type == "stop": self._stop_run(job.run_id) elif job.type == "exit": self._exit() return time.sleep(5) def _run_jobs_from_queue(self): global _INSTANCES _INSTANCES += 1 try: waiting = False count = 0 while True: if self._exit_flag: return try: try: job = self._queue.get(timeout=5) if self._exit_flag: logger.debug("Exiting main loop due to exit flag.") wandb.termlog("Sweep Agent: Exiting.") return except queue.Empty: if not waiting: logger.debug("Paused.") wandb.termlog("Sweep Agent: Waiting for job.") waiting = True time.sleep(5) if self._exit_flag: logger.debug("Exiting main loop due to exit flag.") wandb.termlog("Sweep Agent: Exiting.") return continue if waiting: logger.debug("Resumed.") wandb.termlog("Job received.") waiting = False count += 1 run_id = job.run_id if self._run_status[run_id] == RunStatus.STOPPED: continue logger.debug(f"Spawning new thread for run {run_id}.") thread = threading.Thread(target=self._run_job, args=(job,)) self._run_threads[run_id] = thread thread.start() self._run_status[run_id] = RunStatus.RUNNING thread.join() logger.debug(f"Thread joined for run {run_id}.") if self._run_status[run_id] == RunStatus.RUNNING: self._run_status[run_id] = RunStatus.DONE elif self._run_status[run_id] == RunStatus.ERRORED: exc = self._exceptions[run_id] # Extract to reduce a decision point to avoid ruff c901 log_str, term_str = _get_exception_logger_and_term_strs(exc) logger.error(f"Run {run_id} errored:\n{log_str}") wandb.termerror(f"Run {run_id} errored:{term_str}") if os.getenv(wandb.env.AGENT_DISABLE_FLAPPING) == "true": self._exit_flag = True return elif ( time.time() - self._start_time < self.FLAPPING_MAX_SECONDS ) and (len(self._exceptions) >= self.FLAPPING_MAX_FAILURES): msg = f"Detected {self.FLAPPING_MAX_FAILURES} failed runs in the first {self.FLAPPING_MAX_SECONDS} seconds, killing sweep." logger.error(msg) wandb.termerror(msg) wandb.termlog( "To disable this check set WANDB_AGENT_DISABLE_FLAPPING=true" ) self._exit_flag = True return if ( self._max_initial_failures < len(self._exceptions) and len(self._exceptions) >= count ): msg = f"Detected {self._max_initial_failures} failed runs in a row at start, killing sweep." logger.error(msg) wandb.termerror(msg) wandb.termlog( "To change this value set WANDB_AGENT_MAX_INITIAL_FAILURES=val" ) self._exit_flag = True return if self._count and self._count == count: logger.debug("Exiting main loop because max count reached.") self._exit_flag = True return except KeyboardInterrupt: logger.debug("Ctrl + C detected. Stopping sweep.") wandb.termlog("Ctrl + C detected. Stopping sweep.") self._exit() return except Exception: if self._exit_flag: logger.debug("Exiting main loop due to exit flag.") wandb.termlog("Sweep Agent: Killed.") return else: raise finally: _INSTANCES -= 1 def _run_job(self, job): try: run_id = job.run_id config_file = os.path.join( "wandb", "sweep-" + self._sweep_id, "config-" + run_id + ".yaml" ) os.environ[wandb.env.RUN_ID] = run_id base_dir = os.environ.get(wandb.env.DIR, "") sweep_param_path = os.path.join(base_dir, config_file) os.environ[wandb.env.SWEEP_PARAM_PATH] = sweep_param_path config_util.save_config_file_from_dict(sweep_param_path, job.config) os.environ[wandb.env.SWEEP_ID] = self._sweep_id wandb.teardown() wandb.termlog(f"Agent Starting Run: {run_id} with config:") for k, v in job.config.items(): wandb.termlog("\t{}: {}".format(k, v["value"])) try: self._function() except KeyboardInterrupt: raise except Exception as e: # Log the run's exceptions directly to stderr to match CLI case, and wrap so we # can identify it as coming from the job later later. This will get automatically # logged by console_capture.py. Exception handler below will also handle exceptions # in setup code. exc_repr = _format_exception_traceback(e) print(exc_repr, file=sys.stderr) # noqa: T201 raise _JobError(f"Run threw exception: {str(e)}") from e wandb.finish() except KeyboardInterrupt: raise except Exception as e: wandb.finish(exit_code=1) if self._run_status[run_id] == RunStatus.RUNNING: self._run_status[run_id] = RunStatus.ERRORED self._exceptions[run_id] = e finally: # clean up the environment changes made os.environ.pop(wandb.env.RUN_ID, None) os.environ.pop(wandb.env.SWEEP_ID, None) os.environ.pop(wandb.env.SWEEP_PARAM_PATH, None) def run(self): logger.info( f"Starting sweep agent: entity={self._entity}, project={self._project}, count={self._count}" ) self._setup() # self._main_thread = threading.Thread(target=self._run_jobs_from_queue) self._heartbeat_thread = threading.Thread(target=self._heartbeat) self._heartbeat_thread.daemon = True # self._main_thread.start() self._heartbeat_thread.start() # self._main_thread.join() self._run_jobs_from_queue() def pyagent(sweep_id, function, entity=None, project=None, count=None): """Generic agent entrypoint, used for CLI or jupyter. Args: sweep_id (dict): Sweep ID generated by CLI or sweep API function (func, optional): A function to call instead of the "program" entity (str, optional): W&B Entity project (str, optional): W&B Project count (int, optional): the number of trials to run. """ if not callable(function): raise TypeError("function parameter must be callable!") agent = Agent( sweep_id, function=function, entity=entity, project=project, count=count, ) agent.run() def _format_exception_traceback(exc): return "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
Agent
python
django__django
django/forms/widgets.py
{ "start": 28167, "end": 28640 }
class ____(Select): allow_multiple_selected = True def value_from_datadict(self, data, files, name): try: getter = data.getlist except AttributeError: getter = data.get return getter(name) def value_omitted_from_data(self, data, files, name): # An unselected <select multiple> doesn't appear in POST data, so it's # never known if the value is actually omitted. return False
SelectMultiple
python
tornadoweb__tornado
tornado/routing.py
{ "start": 689, "end": 890 }
class ____. The `tornado.web.Application` class is a `Router` implementation and may be used directly, or the classes in this module may be used for additional flexibility. The `RuleRouter`
implementations
python
openai__openai-python
src/openai/types/eval_update_params.py
{ "start": 271, "end": 757 }
class ____(TypedDict, total=False): metadata: Optional[Metadata] """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and querying for objects via API or the dashboard. Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters. """ name: str """Rename the evaluation."""
EvalUpdateParams
python
ijl__orjson
test/test_default.py
{ "start": 144, "end": 302 }
class ____: def __init__(self): self.name = uuid.uuid4().hex def __str__(self): return f"{self.__class__.__name__}({self.name})"
Custom
python
doocs__leetcode
solution/1600-1699/1674.Minimum Moves to Make Array Complementary/Solution.py
{ "start": 0, "end": 491 }
class ____: def minMoves(self, nums: List[int], limit: int) -> int: d = [0] * (2 * limit + 2) n = len(nums) for i in range(n // 2): x, y = nums[i], nums[-i - 1] if x > y: x, y = y, x d[2] += 2 d[x + 1] -= 2 d[x + 1] += 1 d[x + y] -= 1 d[x + y + 1] += 1 d[y + limit + 1] -= 1 d[y + limit + 1] += 2 return min(accumulate(d[2:]))
Solution
python
huggingface__transformers
src/transformers/models/granitemoeshared/modeling_granitemoeshared.py
{ "start": 23509, "end": 30466 }
class ____(GraniteMoeSharedPreTrainedModel): def __init__(self, config: GraniteMoeSharedConfig): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.layers = nn.ModuleList( [GraniteMoeSharedDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.norm = GraniteMoeSharedRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.rotary_emb = GraniteMoeSharedRotaryEmbedding(config=config) self.gradient_checkpointing = False self.embedding_multiplier = config.embedding_multiplier # Initialize weights and apply final processing self.post_init() @check_model_inputs() @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> MoeModelOutputWithPast: if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if use_cache and past_key_values is None: past_key_values = DynamicCache(config=self.config) if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids) if cache_position is None: past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 cache_position = torch.arange( past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device ) if position_ids is None: position_ids = cache_position.unsqueeze(0) causal_mask = create_causal_mask( # ONLY DIFF WITH MIXTRAL: NO SLIDING config=self.config, input_embeds=inputs_embeds, attention_mask=attention_mask, cache_position=cache_position, past_key_values=past_key_values, position_ids=position_ids, ) inputs_embeds = inputs_embeds * self.embedding_multiplier hidden_states = inputs_embeds # create position embeddings to be shared across the decoder layers position_embeddings = self.rotary_emb(hidden_states, position_ids) for decoder_layer in self.layers[: self.config.num_hidden_layers]: hidden_states = decoder_layer( hidden_states, position_embeddings=position_embeddings, attention_mask=causal_mask, position_ids=position_ids, past_key_values=past_key_values, use_cache=use_cache, cache_position=cache_position, **kwargs, ) hidden_states = self.norm(hidden_states) return MoeModelOutputWithPast( # only diff with Mistral is the output type, we need MoE last_hidden_state=hidden_states, past_key_values=past_key_values, ) def load_balancing_loss_func( gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None], num_experts: Optional[int] = None, top_k=2, attention_mask: Optional[torch.Tensor] = None, ) -> Union[torch.Tensor, int]: r""" Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch. See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between experts is too unbalanced. Args: gate_logits: Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of shape [batch_size X sequence_length, num_experts]. num_experts: Number of experts top_k: The number of experts to route per-token, can be also interpreted as the `top-k` routing parameter. attention_mask (`torch.Tensor`, *optional*): The attention_mask used in forward function shape [batch_size X sequence_length] if not None. Returns: The auxiliary loss. """ if gate_logits is None or not isinstance(gate_logits, tuple): return 0 if isinstance(gate_logits, tuple): compute_device = gate_logits[0].device concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0) routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1) _, selected_experts = torch.topk(routing_weights, top_k, dim=-1) expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts) if attention_mask is None: # Compute the percentage of tokens routed to each experts tokens_per_expert = torch.mean(expert_mask.float(), dim=0) # Compute the average probability of routing to these experts router_prob_per_expert = torch.mean(routing_weights, dim=0) else: batch_size, sequence_length = attention_mask.shape num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length) # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask expert_attention_mask = ( attention_mask[None, :, :, None, None] .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts)) .reshape(-1, top_k, num_experts) .to(compute_device) ) # Compute the percentage of tokens routed to each experts tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum( expert_attention_mask, dim=0 ) # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert router_per_expert_attention_mask = ( attention_mask[None, :, :, None] .expand((num_hidden_layers, batch_size, sequence_length, num_experts)) .reshape(-1, num_experts) .to(compute_device) ) # Compute the average probability of routing to these experts router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum( router_per_expert_attention_mask, dim=0 ) overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0)) return overall_loss * num_experts @auto_docstring
GraniteMoeSharedModel
python
run-llama__llama_index
llama-index-integrations/graph_stores/llama-index-graph-stores-neptune/llama_index/graph_stores/neptune/database.py
{ "start": 291, "end": 2470 }
class ____(NeptuneBaseGraphStore): def __init__( self, host: str, port: int = 8182, use_https: bool = True, client: Any = None, credentials_profile_name: Optional[str] = None, region_name: Optional[str] = None, sign: bool = True, node_label: str = "Entity", **kwargs: Any, ) -> None: """Create a new Neptune Database graph wrapper instance.""" self.node_label = node_label self._client = create_neptune_database_client( host, port, client, credentials_profile_name, region_name, sign, use_https ) def query(self, query: str, params: dict = {}) -> Dict[str, Any]: """Query Neptune database.""" try: logger.debug(f"query() query: {query} parameters: {json.dumps(params)}") return self.client.execute_open_cypher_query( openCypherQuery=query, parameters=json.dumps(params) )["results"] except Exception as e: raise NeptuneQueryException( { "message": "An error occurred while executing the query.", "details": str(e), "query": query, "parameters": str(params), } ) def _get_summary(self) -> Dict: try: response = self.client.get_propertygraph_summary() except Exception as e: raise NeptuneQueryException( { "message": ( "Summary API is not available for this instance of Neptune," "ensure the engine version is >=1.2.1.0" ), "details": str(e), } ) try: summary = response["payload"]["graphSummary"] except Exception: raise NeptuneQueryException( { "message": "Summary API did not return a valid response.", "details": response.content.decode(), } ) else: return summary
NeptuneDatabaseGraphStore
python
openai__openai-python
src/openai/types/beta/realtime/conversation_item_with_reference_param.py
{ "start": 953, "end": 3079 }
class ____(TypedDict, total=False): id: str """ For an item of type (`message` | `function_call` | `function_call_output`) this field allows the client to assign the unique ID of the item. It is not required because the server will generate one if not provided. For an item of type `item_reference`, this field is required and is a reference to any item that has previously existed in the conversation. """ arguments: str """The arguments of the function call (for `function_call` items).""" call_id: str """ The ID of the function call (for `function_call` and `function_call_output` items). If passed on a `function_call_output` item, the server will check that a `function_call` item with the same ID exists in the conversation history. """ content: Iterable[Content] """The content of the message, applicable for `message` items. - Message items of role `system` support only `input_text` content - Message items of role `user` support `input_text` and `input_audio` content - Message items of role `assistant` support `text` content. """ name: str """The name of the function being called (for `function_call` items).""" object: Literal["realtime.item"] """Identifier for the API object being returned - always `realtime.item`.""" output: str """The output of the function call (for `function_call_output` items).""" role: Literal["user", "assistant", "system"] """ The role of the message sender (`user`, `assistant`, `system`), only applicable for `message` items. """ status: Literal["completed", "incomplete", "in_progress"] """The status of the item (`completed`, `incomplete`, `in_progress`). These have no effect on the conversation, but are accepted for consistency with the `conversation.item.created` event. """ type: Literal["message", "function_call", "function_call_output", "item_reference"] """ The type of the item (`message`, `function_call`, `function_call_output`, `item_reference`). """
ConversationItemWithReferenceParam
python
getsentry__sentry
src/sentry/organizations/services/organization/model.py
{ "start": 1773, "end": 2300 }
class ____(RpcModel): id: int = -1 status: int = Field(default_factory=_DefaultEnumHelpers.get_default_team_status_value) organization_id: int = -1 slug: str = "" actor_id: int | None = None org_role: str | None = None name: str = "" def class_name(self) -> str: return "Team" def get_audit_log_data(self) -> dict[str, Any]: return { "id": self.id, "slug": self.slug, "name": self.name, "status": self.status, }
RpcTeam
python
getsentry__sentry
tests/sentry/taskworker/test_retry.py
{ "start": 289, "end": 3661 }
class ____(RuntimeError): """Dummy exception for instanceof tests""" def test_initial_state__defaults() -> None: retry = Retry(times=2) proto = retry.initial_state() assert proto.attempts == 0 assert proto.max_attempts == 2 assert proto.on_attempts_exceeded == ON_ATTEMPTS_EXCEEDED_DISCARD def test_initial_state__discard() -> None: retry = Retry(times=1, times_exceeded=LastAction.Discard) proto = retry.initial_state() assert proto.attempts == 0 assert proto.max_attempts == 1 assert proto.on_attempts_exceeded == ON_ATTEMPTS_EXCEEDED_DISCARD def test_initial_state__deadletter() -> None: retry = Retry(times=5, times_exceeded=LastAction.Deadletter) proto = retry.initial_state() assert proto.attempts == 0 assert proto.max_attempts == 5 assert proto.on_attempts_exceeded == ON_ATTEMPTS_EXCEEDED_DEADLETTER def test_initial_state__delay_on_retry() -> None: retry = Retry(times=5, delay=1) proto = retry.initial_state() assert proto.attempts == 0 assert proto.delay_on_retry == 1 def test_should_retry_no_matching_error() -> None: retry = Retry(times=5) state = retry.initial_state() err = Exception("something bad") assert not retry.should_retry(state, err) state.attempts = 5 assert not retry.should_retry(state, err) def test_should_retry_retryerror() -> None: retry = Retry(times=5) state = retry.initial_state() err = RetryTaskError("something bad") assert retry.should_retry(state, err) state.attempts = 4 assert not retry.should_retry(state, err) def test_should_retry_multiprocessing_timeout() -> None: retry = Retry(times=3) state = retry.initial_state() timeout = TimeoutError("timeouts should retry if there are attempts left") assert retry.should_retry(state, timeout) state.attempts = 1 assert retry.should_retry(state, timeout) # attempt = 2 is actually the third attempt. state.attempts = 2 assert not retry.should_retry(state, timeout) state.attempts = 3 assert not retry.should_retry(state, timeout) def test_should_retry_error_allow_list() -> None: retry = Retry(times=3, on=(RuntimeError, KeyError)) state = retry.initial_state() err = RuntimeError("should retry") assert retry.should_retry(state, err) key_err = KeyError("should retry") assert retry.should_retry(state, key_err) err_child = RuntimeChildError("subclasses are retried") assert retry.should_retry(state, err_child) value_err = ValueError("no retry") assert not retry.should_retry(state, value_err) def test_max_attempts_reached() -> None: retry = Retry(times=5) state = retry.initial_state() assert not retry.max_attempts_reached(state) state.attempts = 4 assert retry.max_attempts_reached(state) def test_should_retry_allow_list_ignore_parent() -> None: retry = Retry(times=3, on=(Exception,), ignore=(RuntimeError,)) state = retry.initial_state() runtime_err = RuntimeError("no retry for ignored") assert not retry.should_retry(state, runtime_err) runtime_child = RuntimeChildError("no retry for subclasses of ignored") assert not retry.should_retry(state, runtime_child) val_err = ValueError("other exceptions are retried") assert retry.should_retry(state, val_err)
RuntimeChildError
python
huggingface__transformers
src/transformers/models/sam_hq/processing_samhq.py
{ "start": 1589, "end": 11957 }
class ____(ProcessorMixin): r""" Constructs a SAM HQ processor which wraps a SAM image processor and an 2D points & Bounding boxes processor into a single processor. [`SamHQProcessor`] offers all the functionalities of [`SamImageProcessor`]. See the docstring of [`~SamImageProcessor.__call__`] for more information. Args: image_processor (`SamImageProcessor`): An instance of [`SamImageProcessor`]. The image processor is a required input. """ def __init__(self, image_processor): super().__init__(image_processor) # Ensure image_processor is properly initialized if not hasattr(self, "image_processor"): raise ValueError("image_processor was not properly initialized") if not hasattr(self.image_processor, "size"): raise ValueError("image_processor.size is not set") self.target_size = self.image_processor.size["longest_edge"] def __call__( self, images: Optional[ImageInput] = None, text: Optional[Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]] = None, **kwargs: Unpack[SamHQProcessorKwargs], ) -> BatchEncoding: """ This method uses [`SamImageProcessor.__call__`] method to prepare image(s) for the model. It also prepares 2D points and bounding boxes for the model if they are provided. """ output_kwargs = self._merge_kwargs( SamHQProcessorKwargs, tokenizer_init_kwargs={}, **kwargs, ) input_points = output_kwargs["images_kwargs"].pop("input_points", None) input_labels = output_kwargs["images_kwargs"].pop("input_labels", None) input_boxes = output_kwargs["images_kwargs"].pop("input_boxes", None) point_pad_value = output_kwargs["images_kwargs"].pop("point_pad_value", None) encoding_image_processor = self.image_processor( images, **output_kwargs["images_kwargs"], ) original_sizes = encoding_image_processor["original_sizes"] if hasattr(original_sizes, "numpy"): original_sizes = original_sizes.numpy() input_points, input_labels, input_boxes = self._check_and_preprocess_points( input_points=input_points, input_labels=input_labels, input_boxes=input_boxes, ) encoding_image_processor = self._normalize_and_convert( encoding_image_processor, original_sizes, input_points=input_points, input_labels=input_labels, input_boxes=input_boxes, return_tensors=output_kwargs["images_kwargs"].get("return_tensors"), point_pad_value=point_pad_value, ) return encoding_image_processor def _normalize_and_convert( self, encoding_image_processor, original_sizes, input_points=None, input_labels=None, input_boxes=None, return_tensors="pt", point_pad_value=-10, ): """ Normalize and convert the image processor output to the expected format. """ # Process input points if input_points is not None: input_points = self._normalize_batch_coordinates(input_points, original_sizes) if not all(point.shape == input_points[0].shape for point in input_points): if input_labels is not None: input_points, input_labels = self._pad_points_and_labels( input_points, input_labels, point_pad_value ) input_points = np.array(input_points) # Process input labels if input_labels is not None: input_labels = np.array(input_labels) # Process input boxes if input_boxes is not None: input_boxes = self._normalize_batch_coordinates(input_boxes, original_sizes, is_bounding_box=True) input_boxes = np.array(input_boxes) # Update processor with converted inputs if input_boxes is not None: encoding_image_processor["input_boxes"] = self._to_tensor(input_boxes, 3, return_tensors) if input_points is not None: encoding_image_processor["input_points"] = self._to_tensor(input_points, 4, return_tensors) if input_labels is not None: encoding_image_processor["input_labels"] = self._to_tensor(input_labels, 3, return_tensors) return encoding_image_processor def _pad_points_and_labels(self, input_points, input_labels, point_pad_value): r""" The method pads the 2D points and labels to the maximum number of points in the batch. """ expected_nb_points = max(point.shape[0] for point in input_points) processed_input_points = [] for i, point in enumerate(input_points): if point.shape[0] != expected_nb_points: point = np.concatenate( [point, np.zeros((expected_nb_points - point.shape[0], 2)) + point_pad_value], axis=0 ) input_labels[i] = np.append(input_labels[i], [point_pad_value]) processed_input_points.append(point) input_points = processed_input_points return input_points, input_labels def _normalize_coordinates( self, target_size: int, coords: np.ndarray, original_size, is_bounding_box=False ) -> np.ndarray: """ Expects a numpy array of length 2 in the final dimension. Requires the original image size in (H,W) format. """ old_h, old_w = original_size new_h, new_w = self.image_processor._get_preprocess_shape(original_size, longest_edge=target_size) coords = deepcopy(coords).astype(float) if is_bounding_box: coords = coords.reshape(-1, 2, 2) coords[..., 0] = coords[..., 0] * (new_w / old_w) coords[..., 1] = coords[..., 1] * (new_h / old_h) if is_bounding_box: coords = coords.reshape(-1, 4) return coords def _preprocess_input(self, inputs, error_message, expected_nesting=1, dtype=None): """ Preprocess input by converting torch tensors to numpy arrays and validating structure. Args: inputs: The input to process error_message: Error message if validation fails expected_nesting: Expected nesting level (1 for points/labels, 2 for boxes) dtype: Optional data type for numpy array conversion Returns: Processed input as list of numpy arrays or None """ if inputs is None: return None # Convert torch tensor to list if applicable if hasattr(inputs, "numpy"): inputs = inputs.numpy().tolist() # Validate structure based on expected nesting valid = isinstance(inputs, list) current = inputs for _ in range(expected_nesting): if not valid or not current: break valid = valid and isinstance(current[0], list) current = current[0] if current else None if not valid: raise ValueError(error_message) # Convert to numpy arrays return [np.array(item, dtype=dtype) for item in inputs] def _check_and_preprocess_points( self, input_points=None, input_labels=None, input_boxes=None, ): r""" Check and preprocesses the 2D points, labels and bounding boxes. It checks if the input is valid and if they are, it converts the coordinates of the points and bounding boxes. If a user passes directly a `torch.Tensor`, it is converted to a `numpy.ndarray` and then to a `list`. """ # Process each input type input_points = self._preprocess_input(input_points, "Input points must be a list of list of floating points.") input_labels = self._preprocess_input(input_labels, "Input labels must be a list of list integers.") input_boxes = self._preprocess_input( input_boxes, "Input boxes must be a list of list of list of floating points.", expected_nesting=2, dtype=np.float32, ) return input_points, input_labels, input_boxes @property def model_input_names(self): image_processor_input_names = self.image_processor.model_input_names return list(image_processor_input_names + ["original_sizes", "reshaped_input_sizes"]) def post_process_masks(self, *args, **kwargs): return self.image_processor.post_process_masks(*args, **kwargs) def _to_tensor(self, array, min_dim, return_tensors): """ Convert numpy array to tensor and ensure proper dimensionality. Args: array: The numpy array to convert min_dim: The minimum number of dimensions the result should have return_tensors: The type of tensors to return (e.g., "pt" for PyTorch tensors) Returns: The converted array or tensor with proper dimensions """ if return_tensors == "pt": array = torch.from_numpy(array) return array.unsqueeze(1) if array.ndim < min_dim else array return array def _normalize_batch_coordinates(self, inputs, original_sizes, is_bounding_box=False): """ Normalize coordinates based on original sizes. Args: inputs: List of coordinate arrays original_sizes: Original sizes of the images is_bounding_box: Whether inputs are bounding boxes Returns: Normalized coordinates as list """ if len(original_sizes) != len(inputs): # Use first original size for all inputs return [ self._normalize_coordinates(self.target_size, item, original_sizes[0], is_bounding_box=is_bounding_box) for item in inputs ] else: # Use paired original sizes for each input return [ self._normalize_coordinates(self.target_size, item, size, is_bounding_box=is_bounding_box) for item, size in zip(inputs, original_sizes) ] __all__ = ["SamHQProcessor"]
SamHQProcessor
python
sphinx-doc__sphinx
sphinx/search/ja.py
{ "start": 27507, "end": 28549 }
class ____(SearchLanguage): """Japanese search implementation: uses no stemmer, but word splitting is quite complicated. """ lang = 'ja' language_name = 'Japanese' def __init__(self, options: dict[str, str]) -> None: super().__init__(options) dotted_path = options.get('type') if dotted_path is None: self.splitter = DefaultSplitter(options) else: try: splitter_cls = import_object( dotted_path, "html_search_options['type'] setting" ) self.splitter = splitter_cls(options) except ExtensionError as exc: msg = f"Splitter module {dotted_path!r} can't be imported" raise ExtensionError(msg) from exc def split(self, input: str) -> list[str]: return self.splitter.split(input) def word_filter(self, stemmed_word: str) -> bool: return len(stemmed_word) > 1 def stem(self, word: str) -> str: return word
SearchJapanese
python
sympy__sympy
sympy/solvers/ode/single.py
{ "start": 106741, "end": 111969 }
class ____(SingleODESolver): r""" This hint implements the Lie group method of solving first order differential equations. The aim is to convert the given differential equation from the given coordinate system into another coordinate system where it becomes invariant under the one-parameter Lie group of translations. The converted ODE can be easily solved by quadrature. It makes use of the :py:meth:`sympy.solvers.ode.infinitesimals` function which returns the infinitesimals of the transformation. The coordinates `r` and `s` can be found by solving the following Partial Differential Equations. .. math :: \xi\frac{\partial r}{\partial x} + \eta\frac{\partial r}{\partial y} = 0 .. math :: \xi\frac{\partial s}{\partial x} + \eta\frac{\partial s}{\partial y} = 1 The differential equation becomes separable in the new coordinate system .. math :: \frac{ds}{dr} = \frac{\frac{\partial s}{\partial x} + h(x, y)\frac{\partial s}{\partial y}}{ \frac{\partial r}{\partial x} + h(x, y)\frac{\partial r}{\partial y}} After finding the solution by integration, it is then converted back to the original coordinate system by substituting `r` and `s` in terms of `x` and `y` again. Examples ======== >>> from sympy import Function, dsolve, exp, pprint >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(f(x).diff(x) + 2*x*f(x) - x*exp(-x**2), f(x), ... hint='lie_group')) / 2\ 2 | x | -x f(x) = |C1 + --|*e \ 2 / References ========== - Solving differential equations by Symmetry Groups, John Starrett, pp. 1 - pp. 14 """ hint = "lie_group" has_integral = False def _has_additional_params(self): return 'xi' in self.ode_problem.params and 'eta' in self.ode_problem.params def _matches(self): eq = self.ode_problem.eq f = self.ode_problem.func.func order = self.ode_problem.order x = self.ode_problem.sym df = f(x).diff(x) y = Dummy('y') d = Wild('d', exclude=[df, f(x).diff(x, 2)]) e = Wild('e', exclude=[df]) does_match = False if self._has_additional_params() and order == 1: xi = self.ode_problem.params['xi'] eta = self.ode_problem.params['eta'] self.r3 = {'xi': xi, 'eta': eta} r = collect(eq, df, exact=True).match(d + e * df) if r: r['d'] = d r['e'] = e r['y'] = y r[d] = r[d].subs(f(x), y) r[e] = r[e].subs(f(x), y) self.r3.update(r) does_match = True return does_match def _get_general_solution(self, *, simplify_flag: bool = True): eq = self.ode_problem.eq x = self.ode_problem.sym func = self.ode_problem.func order = self.ode_problem.order df = func.diff(x) try: eqsol = solve(eq, df) except NotImplementedError: eqsol = [] desols = [] for s in eqsol: sol = _ode_lie_group(s, func, order, match=self.r3) if sol: desols.extend(sol) if desols == []: raise NotImplementedError("The given ODE " + str(eq) + " cannot be solved by" + " the lie group method") return desols solver_map = { 'factorable': Factorable, 'nth_linear_constant_coeff_homogeneous': NthLinearConstantCoeffHomogeneous, 'nth_linear_euler_eq_homogeneous': NthLinearEulerEqHomogeneous, 'nth_linear_constant_coeff_undetermined_coefficients': NthLinearConstantCoeffUndeterminedCoefficients, 'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients': NthLinearEulerEqNonhomogeneousUndeterminedCoefficients, 'separable': Separable, '1st_exact': FirstExact, '1st_linear': FirstLinear, 'Bernoulli': Bernoulli, 'Riccati_special_minus2': RiccatiSpecial, '1st_rational_riccati': RationalRiccati, '1st_homogeneous_coeff_best': HomogeneousCoeffBest, '1st_homogeneous_coeff_subs_indep_div_dep': HomogeneousCoeffSubsIndepDivDep, '1st_homogeneous_coeff_subs_dep_div_indep': HomogeneousCoeffSubsDepDivIndep, 'almost_linear': AlmostLinear, 'linear_coefficients': LinearCoefficients, 'separable_reduced': SeparableReduced, 'nth_linear_constant_coeff_variation_of_parameters': NthLinearConstantCoeffVariationOfParameters, 'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters': NthLinearEulerEqNonhomogeneousVariationOfParameters, 'Liouville': Liouville, '2nd_linear_airy': SecondLinearAiry, '2nd_linear_bessel': SecondLinearBessel, '2nd_linear_bessel_transform': SecondLinearBesselTransform, '2nd_hypergeometric': SecondHypergeometric, 'nth_order_reducible': NthOrderReducible, '2nd_nonlinear_autonomous_conserved': SecondNonlinearAutonomousConserved, 'nth_algebraic': NthAlgebraic, 'lie_group': LieGroup, } # Avoid circular import: from .ode import dsolve, ode_sol_simplicity, odesimp, homogeneous_order
LieGroup
python
pennersr__django-allauth
allauth/socialaccount/providers/netiq/provider.py
{ "start": 265, "end": 921 }
class ____(OAuth2Provider): id = "netiq" name = "NetIQ" account_class = NetIQAccount oauth2_adapter_class = NetIQOAuth2Adapter def get_default_scope(self): return ["openid", "profile", "email"] def extract_uid(self, data): uid_field = self.app.settings.get("uid_field", "sub") return str(data[uid_field]) def extract_extra_data(self, data): return data def extract_common_fields(self, data): return dict( email=data["email"], last_name=data["family_name"], first_name=data["given_name"], ) provider_classes = [NetIQProvider]
NetIQProvider
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/assets/graph/asset_graph_differ.py
{ "start": 859, "end": 1007 }
class ____(NamedTuple): added: Set[str] changed: Set[str] removed: Set[str] T = TypeVar("T") @whitelist_for_serdes @record
MappedKeyDiff