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
huggingface__transformers
tests/models/clvp/test_modeling_clvp.py
{ "start": 6009, "end": 7091 }
class ____(ModelTesterMixin, unittest.TestCase): all_model_classes = (ClvpEncoder,) if is_torch_available() else () def setUp(self): self.model_tester = ClvpEncoderTester(self) self.encoder_config_tester = ConfigTester(self, config_class=ClvpEncoderConfig, hidden_size=32) def tearDown(self): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch cleanup(torch_device) def test_config(self): self.encoder_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) @unittest.skip(reason="ClvpEncoder does not output loss") def test_training(self): pass @unittest.skip(reason="ClvpEncoder does not output loss") def test_training_gradient_checkpointing(self): pass @unittest.skip(reason="ClvpEncoder does not output loss") def test_gradient_checkpointing_enable_disable(self): pass
ClvpEncoderTest
python
huggingface__transformers
tests/models/poolformer/test_modeling_poolformer.py
{ "start": 4255, "end": 8020 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else () pipeline_model_mapping = ( {"image-feature-extraction": PoolFormerModel, "image-classification": PoolFormerForImageClassification} if is_torch_available() else {} ) test_resize_embeddings = False has_attentions = False test_torch_exportable = True def setUp(self): self.model_tester = PoolFormerModelTester(self) self.config_tester = PoolFormerConfigTester(self, config_class=PoolFormerConfig) 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_batching_equivalence(self, atol=2e-4, rtol=2e-4): super().test_batching_equivalence(atol=atol, rtol=rtol) @unittest.skip(reason="PoolFormer does not use inputs_embeds") def test_inputs_embeds(self): pass @unittest.skip(reason="PoolFormer does not have get_input_embeddings method and get_output_embeddings methods") def test_model_get_set_embeddings(self): pass def test_hidden_states_output(self): def check_hidden_states_output(inputs_dict, config, model_class): model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) hidden_states = outputs.hidden_states expected_num_layers = self.model_tester.num_encoder_blocks self.assertEqual(len(hidden_states), expected_num_layers) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:]), [ self.model_tester.hidden_sizes[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ], ) config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: inputs_dict["output_hidden_states"] = True check_hidden_states_output(inputs_dict, config, model_class) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] config.output_hidden_states = True check_hidden_states_output(inputs_dict, config, model_class) def test_training(self): if not self.model_tester.is_training: self.skipTest(reason="model_tester.is_training is set to False") config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.return_dict = True for model_class in self.all_model_classes: if model_class in get_values(MODEL_MAPPING): continue model = model_class(config) model.to(torch_device) model.train() inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) loss = model(**inputs).loss loss.backward() @slow def test_model_from_pretrained(self): model_name = "sail/poolformer_s12" model = PoolFormerModel.from_pretrained(model_name) self.assertIsNotNone(model) # We will verify our results on an image of cute cats def prepare_img(): image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") return image @require_torch
PoolFormerModelTest
python
pytorch__pytorch
torch/utils/_sympy/functions.py
{ "start": 36615, "end": 37269 }
class ____(MinMaxBase, Application): # type: ignore[misc] r""" Return, if possible, the maximum value of the list. """ zero = S.Infinity identity = S.NegativeInfinity def _eval_is_positive(self): # type:ignore[override] return fuzzy_or(a.is_positive for a in self.args) # type: ignore[attr-defined] def _eval_is_nonnegative(self): # type:ignore[override] return fuzzy_or(a.is_nonnegative for a in self.args) # type: ignore[attr-defined] def _eval_is_negative(self): # type:ignore[override] # pyrefly: ignore [missing-attribute] return fuzzy_and(a.is_negative for a in self.args)
Max
python
google__jax
tests/errors_test.py
{ "start": 12666, "end": 13377 }
class ____(jtu.JaxTestCase): @jtu.sample_product( errorclass=[ errorclass for errorclass in dir(jax.errors) if errorclass.endswith('Error') and errorclass not in [ 'JaxIndexError', 'JAXTypeError', 'JaxRuntimeError', ] ], ) def testErrorsURL(self, errorclass): class FakeTracer(core.Tracer): aval = None ErrorClass = getattr(jax.errors, errorclass) err = ErrorClass(FakeTracer(None)) self.assertIn(f'https://docs.jax.dev/en/latest/errors.html#jax.errors.{errorclass}', str(err)) if __name__ == '__main__': absltest.main(testLoader=jtu.JaxTestLoader())
CustomErrorsTest
python
spack__spack
lib/spack/spack/vendor/ruamel/yaml/tokens.py
{ "start": 9325, "end": 9389 }
class ____(Token): __slots__ = () id = '-'
BlockEntryToken
python
getsentry__sentry
tests/sentry/utils/test_query.py
{ "start": 6447, "end": 8908 }
class ____(TestCase): def setUp(self) -> None: super().setUp() UserReport.objects.all().delete() def test_basic(self) -> None: total = 10 records = [] for i in range(total): records.append(self.create_userreport(project=self.project, event_id=str(i) * 32)) result = bulk_delete_objects(UserReport, id__in=[r.id for r in records]) assert result, "Could be more work to do" assert len(UserReport.objects.all()) == 0 assert bulk_delete_objects(UserReport) is False def test_basic_tuple(self) -> None: total = 10 records = [] for i in range(total): records.append(self.create_userreport(project=self.project, event_id=str(i) * 32)) result = bulk_delete_objects(UserReport, id__in=tuple([r.id for r in records])) assert result, "Could be more work to do" assert len(UserReport.objects.all()) == 0 def test_basic_set(self) -> None: total = 10 records = [] for i in range(total): records.append(self.create_userreport(project=self.project, event_id=str(i) * 32)) result = bulk_delete_objects(UserReport, id__in={r.id for r in records}) assert result, "Could be more work to do" assert len(UserReport.objects.all()) == 0 def test_limiting(self) -> None: total = 10 records = [] for i in range(total): records.append(self.create_userreport(project=self.project, event_id=str(i) * 32)) result = bulk_delete_objects(UserReport, id__in=[r.id for r in records], limit=5) assert result, "Still more work to do" assert len(UserReport.objects.all()) == 5 def test_bulk_delete_single_query(self) -> None: repo = self.create_repo() # Commit is chosen because there are foreign keys and a naive delete # will attempt to cascade Commit.objects.create(organization_id=repo.organization_id, repository_id=repo.id) assert len(Commit.objects.all()) == 1 before = len(connections[Commit.objects.db].queries_log) assert bulk_delete_objects(Commit) after = len(connections[Commit.objects.db].queries_log) assert after == before + 1 assert len(Commit.objects.all()) == 0 def test_bulk_delete_empty_queryset(self) -> None: assert bulk_delete_objects(UserReport, id__in=()) is False
BulkDeleteObjectsTest
python
sympy__sympy
sympy/tensor/array/expressions/array_expressions.py
{ "start": 63794, "end": 76986 }
class ____: """ Utility class to help manipulate array contraction objects. This class takes as input an ``ArrayContraction`` object and turns it into an editable object. The field ``args_with_ind`` of this class is a list of ``_ArgE`` objects which can be used to easily edit the contraction structure of the expression. Once editing is finished, the ``ArrayContraction`` object may be recreated by calling the ``.to_array_contraction()`` method. """ def __init__(self, base_array: typing.Union[ArrayContraction, ArrayDiagonal, ArrayTensorProduct]): expr: Basic diagonalized: tuple[tuple[int, ...], ...] contraction_indices: list[tuple[int]] if isinstance(base_array, ArrayContraction): mapping = _get_mapping_from_subranks(base_array.subranks) expr = base_array.expr contraction_indices = base_array.contraction_indices diagonalized = () elif isinstance(base_array, ArrayDiagonal): if isinstance(base_array.expr, ArrayContraction): mapping = _get_mapping_from_subranks(base_array.expr.subranks) expr = base_array.expr.expr diagonalized = ArrayContraction._push_indices_down(base_array.expr.contraction_indices, base_array.diagonal_indices) contraction_indices = base_array.expr.contraction_indices elif isinstance(base_array.expr, ArrayTensorProduct): mapping = {} expr = base_array.expr diagonalized = base_array.diagonal_indices contraction_indices = [] else: mapping = {} expr = base_array.expr diagonalized = base_array.diagonal_indices contraction_indices = [] elif isinstance(base_array, ArrayTensorProduct): expr = base_array contraction_indices = [] diagonalized = () else: raise NotImplementedError() if isinstance(expr, ArrayTensorProduct): args = list(expr.args) else: args = [expr] args_with_ind: list[_ArgE] = [_ArgE(arg) for arg in args] for i, contraction_tuple in enumerate(contraction_indices): for j in contraction_tuple: arg_pos, rel_pos = mapping[j] args_with_ind[arg_pos].indices[rel_pos] = i self.args_with_ind: list[_ArgE] = args_with_ind self.number_of_contraction_indices: int = len(contraction_indices) self._track_permutation: list[list[int]] | None = None mapping = _get_mapping_from_subranks(base_array.subranks) # Trick: add diagonalized indices as negative indices into the editor object: for i, e in enumerate(diagonalized): for j in e: arg_pos, rel_pos = mapping[j] self.args_with_ind[arg_pos].indices[rel_pos] = -1 - i def insert_after(self, arg: _ArgE, new_arg: _ArgE): pos = self.args_with_ind.index(arg) self.args_with_ind.insert(pos + 1, new_arg) def get_new_contraction_index(self): self.number_of_contraction_indices += 1 return self.number_of_contraction_indices - 1 def refresh_indices(self): updates = {} for arg_with_ind in self.args_with_ind: updates.update({i: -1 for i in arg_with_ind.indices if i is not None}) for i, e in enumerate(sorted(updates)): updates[e] = i self.number_of_contraction_indices = len(updates) for arg_with_ind in self.args_with_ind: arg_with_ind.indices = [updates.get(i, None) for i in arg_with_ind.indices] def merge_scalars(self): scalars = [] for arg_with_ind in self.args_with_ind: if len(arg_with_ind.indices) == 0: scalars.append(arg_with_ind) for i in scalars: self.args_with_ind.remove(i) scalar = Mul.fromiter([i.element for i in scalars]) if len(self.args_with_ind) == 0: self.args_with_ind.append(_ArgE(scalar)) else: from sympy.tensor.array.expressions.from_array_to_matrix import _a2m_tensor_product self.args_with_ind[0].element = _a2m_tensor_product(scalar, self.args_with_ind[0].element) def to_array_contraction(self): # Count the ranks of the arguments: counter = 0 # Create a collector for the new diagonal indices: diag_indices = defaultdict(list) count_index_freq = Counter() for arg_with_ind in self.args_with_ind: count_index_freq.update(Counter(arg_with_ind.indices)) free_index_count = count_index_freq[None] # Construct the inverse permutation: inv_perm1 = [] inv_perm2 = [] # Keep track of which diagonal indices have already been processed: done = set() # Counter for the diagonal indices: counter4 = 0 for arg_with_ind in self.args_with_ind: # If some diagonalization axes have been removed, they should be # permuted in order to keep the permutation. # Add permutation here counter2 = 0 # counter for the indices for i in arg_with_ind.indices: if i is None: inv_perm1.append(counter4) counter2 += 1 counter4 += 1 continue if i >= 0: continue # Reconstruct the diagonal indices: diag_indices[-1 - i].append(counter + counter2) if count_index_freq[i] == 1 and i not in done: inv_perm1.append(free_index_count - 1 - i) done.add(i) elif i not in done: inv_perm2.append(free_index_count - 1 - i) done.add(i) counter2 += 1 # Remove negative indices to restore a proper editor object: arg_with_ind.indices = [i if i is not None and i >= 0 else None for i in arg_with_ind.indices] counter += len([i for i in arg_with_ind.indices if i is None or i < 0]) inverse_permutation = inv_perm1 + inv_perm2 permutation = _af_invert(inverse_permutation) # Get the diagonal indices after the detection of HadamardProduct in the expression: diag_indices_filtered = [tuple(v) for v in diag_indices.values() if len(v) > 1] self.merge_scalars() self.refresh_indices() args = [arg.element for arg in self.args_with_ind] contraction_indices = self.get_contraction_indices() expr = _array_contraction(_array_tensor_product(*args), *contraction_indices) expr2 = _array_diagonal(expr, *diag_indices_filtered) if self._track_permutation is not None: permutation2 = _af_invert([j for i in self._track_permutation for j in i]) expr2 = _permute_dims(expr2, permutation2) expr3 = _permute_dims(expr2, permutation) return expr3 def get_contraction_indices(self) -> list[list[int]]: contraction_indices: list[list[int]] = [[] for i in range(self.number_of_contraction_indices)] current_position: int = 0 for arg_with_ind in self.args_with_ind: for j in arg_with_ind.indices: if j is not None: contraction_indices[j].append(current_position) current_position += 1 return contraction_indices def get_mapping_for_index(self, ind) -> list[_IndPos]: if ind >= self.number_of_contraction_indices: raise ValueError("index value exceeding the index range") positions: list[_IndPos] = [] for i, arg_with_ind in enumerate(self.args_with_ind): for j, arg_ind in enumerate(arg_with_ind.indices): if ind == arg_ind: positions.append(_IndPos(i, j)) return positions def get_contraction_indices_to_ind_rel_pos(self) -> list[list[_IndPos]]: contraction_indices: list[list[_IndPos]] = [[] for i in range(self.number_of_contraction_indices)] for i, arg_with_ind in enumerate(self.args_with_ind): for j, ind in enumerate(arg_with_ind.indices): if ind is not None: contraction_indices[ind].append(_IndPos(i, j)) return contraction_indices def count_args_with_index(self, index: int) -> int: """ Count the number of arguments that have the given index. """ counter: int = 0 for arg_with_ind in self.args_with_ind: if index in arg_with_ind.indices: counter += 1 return counter def get_args_with_index(self, index: int) -> list[_ArgE]: """ Get a list of arguments having the given index. """ ret: list[_ArgE] = [i for i in self.args_with_ind if index in i.indices] return ret @property def number_of_diagonal_indices(self): data = set() for arg in self.args_with_ind: data.update({i for i in arg.indices if i is not None and i < 0}) return len(data) def track_permutation_start(self): permutation = [] perm_diag = [] counter = 0 counter2 = -1 for arg_with_ind in self.args_with_ind: perm = [] for i in arg_with_ind.indices: if i is not None: if i < 0: perm_diag.append(counter2) counter2 -= 1 continue perm.append(counter) counter += 1 permutation.append(perm) max_ind = max(max(i) if i else -1 for i in permutation) if permutation else -1 perm_diag = [max_ind - i for i in perm_diag] self._track_permutation = permutation + [perm_diag] def track_permutation_merge(self, destination: _ArgE, from_element: _ArgE): index_destination = self.args_with_ind.index(destination) index_element = self.args_with_ind.index(from_element) self._track_permutation[index_destination].extend(self._track_permutation[index_element]) # type: ignore self._track_permutation.pop(index_element) # type: ignore def get_absolute_free_range(self, arg: _ArgE) -> typing.Tuple[int, int]: """ Return the range of the free indices of the arg as absolute positions among all free indices. """ counter = 0 for arg_with_ind in self.args_with_ind: number_free_indices = len([i for i in arg_with_ind.indices if i is None]) if arg_with_ind == arg: return counter, counter + number_free_indices counter += number_free_indices raise IndexError("argument not found") def get_absolute_range(self, arg: _ArgE) -> typing.Tuple[int, int]: """ Return the absolute range of indices for arg, disregarding dummy indices. """ counter = 0 for arg_with_ind in self.args_with_ind: number_indices = len(arg_with_ind.indices) if arg_with_ind == arg: return counter, counter + number_indices counter += number_indices raise IndexError("argument not found") def get_rank(expr): if isinstance(expr, (MatrixExpr, MatrixElement)): return 2 if isinstance(expr, _CodegenArrayAbstract): return len(expr.shape) if isinstance(expr, NDimArray): return expr.rank() if isinstance(expr, Indexed): return expr.rank if isinstance(expr, IndexedBase): shape = expr.shape if shape is None: return -1 else: return len(shape) if hasattr(expr, "shape"): return len(expr.shape) return 0 def _get_subrank(expr): if isinstance(expr, _CodegenArrayAbstract): return expr.subrank() return get_rank(expr) def _get_subranks(expr): if isinstance(expr, _CodegenArrayAbstract): return expr.subranks else: return [get_rank(expr)] def get_shape(expr): if hasattr(expr, "shape"): return expr.shape return () def nest_permutation(expr): if isinstance(expr, PermuteDims): return expr.nest_permutation() else: return expr def _array_tensor_product(*args, **kwargs): return ArrayTensorProduct(*args, canonicalize=True, **kwargs) def _array_contraction(expr, *contraction_indices, **kwargs): return ArrayContraction(expr, *contraction_indices, canonicalize=True, **kwargs) def _array_diagonal(expr, *diagonal_indices, **kwargs): return ArrayDiagonal(expr, *diagonal_indices, canonicalize=True, **kwargs) def _permute_dims(expr, permutation, **kwargs): return PermuteDims(expr, permutation, canonicalize=True, **kwargs) def _array_add(*args, **kwargs): return ArrayAdd(*args, canonicalize=True, **kwargs) def _get_array_element_or_slice(expr, indices): return ArrayElement(expr, indices)
_EditArrayContraction
python
pytorch__pytorch
torch/_dynamo/variables/functions.py
{ "start": 55868, "end": 57407 }
class ____(UserFunctionVariable): def __init__( self, wrapped: UserFunctionVariable, context: "ContextWrappingVariable", **kwargs: Any, ) -> None: kwargs.pop("fn", None) super().__init__(wrapped.fn, **kwargs) self.wrapped = wrapped self.context = context def call_function( self, tx: "InstructionTranslator", args: Sequence[VariableTracker], kwargs: dict[str, VariableTracker], ) -> VariableTracker: self.context.enter(tx) result = super().call_function(tx, args, kwargs) self.context.exit(tx) return result def reconstruct(self, codegen: "PyCodegen") -> None: codegen.add_push_null(lambda: codegen(self.context)) # type: ignore[arg-type] codegen(self.wrapped) codegen.extend_output(create_call_function(1, False)) def invoke_and_store_as_constant( tx: "InstructionTranslator", fn: Callable[..., Any], name: str, args: Sequence[VariableTracker], kwargs: dict[str, VariableTracker], ) -> VariableTracker: def convert(x: VariableTracker) -> Any: if isinstance(x, variables.TensorVariable): return x.get_real_value() return x.as_python_constant() args = [convert(x) for x in args] kwargs = {k: convert(v) for k, v in kwargs.items()} res = fn(*args, **kwargs) return tx.output.register_attr_or_module( res, name, source=ConstantSource(name), )
WrappedUserFunctionVariable
python
arrow-py__arrow
tests/test_arrow.py
{ "start": 15857, "end": 17837 }
class ____: """These tests relate to issues #376 and #551. The key points in both issues are that arrow will assign a UTC timezone if none is provided and .to() will change other attributes to be correct whereas .replace() only changes the specified attribute. Issue 376 >>> arrow.get('2016-11-06').to('America/New_York').ceil('day') < Arrow [2016-11-05T23:59:59.999999-04:00] > Issue 551 >>> just_before = arrow.get('2018-11-04T01:59:59.999999') >>> just_before 2018-11-04T01:59:59.999999+00:00 >>> just_after = just_before.shift(microseconds=1) >>> just_after 2018-11-04T02:00:00+00:00 >>> just_before_eastern = just_before.replace(tzinfo='US/Eastern') >>> just_before_eastern 2018-11-04T01:59:59.999999-04:00 >>> just_after_eastern = just_after.replace(tzinfo='US/Eastern') >>> just_after_eastern 2018-11-04T02:00:00-05:00 """ def test_dst(self): self.before_1 = arrow.Arrow( 2016, 11, 6, 3, 59, tzinfo=ZoneInfo("America/New_York") ) self.before_2 = arrow.Arrow(2016, 11, 6, tzinfo=ZoneInfo("America/New_York")) self.after_1 = arrow.Arrow(2016, 11, 6, 4, tzinfo=ZoneInfo("America/New_York")) self.after_2 = arrow.Arrow( 2016, 11, 6, 23, 59, tzinfo=ZoneInfo("America/New_York") ) self.before_3 = arrow.Arrow( 2018, 11, 4, 3, 59, tzinfo=ZoneInfo("America/New_York") ) self.before_4 = arrow.Arrow(2018, 11, 4, tzinfo=ZoneInfo("America/New_York")) self.after_3 = arrow.Arrow(2018, 11, 4, 4, tzinfo=ZoneInfo("America/New_York")) self.after_4 = arrow.Arrow( 2018, 11, 4, 23, 59, tzinfo=ZoneInfo("America/New_York") ) assert self.before_1.day == self.before_2.day assert self.after_1.day == self.after_2.day assert self.before_3.day == self.before_4.day assert self.after_3.day == self.after_4.day
TestArrowFalsePositiveDst
python
openai__openai-python
src/openai/types/responses/response_output_text_param.py
{ "start": 2759, "end": 3113 }
class ____(TypedDict, total=False): annotations: Required[Iterable[Annotation]] """The annotations of the text output.""" text: Required[str] """The text output from the model.""" type: Required[Literal["output_text"]] """The type of the output text. Always `output_text`.""" logprobs: Iterable[Logprob]
ResponseOutputTextParam
python
huggingface__transformers
src/transformers/models/mbart/modeling_mbart.py
{ "start": 19818, "end": 20513 }
class ____(PreTrainedModel): config: MBartConfig base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["MBartDecoderLayer", "MBartEncoderLayer", "MBartAttention"] _supports_flash_attn = True _supports_sdpa = True _supports_flex_attn = True _can_compile_fullgraph = True @property def dummy_inputs(self): pad_token = self.config.pad_token_id input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device) dummy_inputs = { "attention_mask": input_ids.ne(pad_token), "input_ids": input_ids, } return dummy_inputs
MBartPreTrainedModel
python
pytransitions__transitions
transitions/extensions/diagrams_mermaid.py
{ "start": 422, "end": 5471 }
class ____(BaseGraph): """Graph creation for transitions.core.Machine. Attributes: custom_styles (dict): A dictionary of styles for the current graph """ def __init__(self, machine): self.custom_styles = {} self.reset_styling() super(Graph, self).__init__(machine) def set_previous_transition(self, src, dst): self.custom_styles["edge"][src][dst] = "previous" self.set_node_style(src, "previous") def set_node_style(self, state, style): self.custom_styles["node"][state.name if hasattr(state, "name") else state] = style def reset_styling(self): self.custom_styles = { "edge": defaultdict(lambda: defaultdict(str)), "node": defaultdict(str), } def _add_nodes(self, states, container): for state in states: container.append("state \"{}\" as {}".format(self._convert_state_attributes(state), state["name"])) container.append("Class {} s_{}".format(state["name"], self.custom_styles["node"][state["name"]] or "default")) def _add_edges(self, transitions, container): edge_labels = defaultdict(lambda: defaultdict(list)) for transition in transitions: try: dst = transition["dest"] except KeyError: dst = transition["source"] edge_labels[transition["source"]][dst].append(self._transition_label(transition)) for src, dests in edge_labels.items(): for dst, labels in dests.items(): container.append("{} --> {}: {}".format(src, dst, " | ".join(labels))) def generate(self): """Triggers the generation of a graph. With graphviz backend, this does nothing since graph trees need to be built from scratch with the configured styles. """ # we cannot really generate a graph in advance with graphviz def get_graph(self, title=None, roi_state=None): title = title if title else self.machine.title fsm_graph = ['---', title, '---', 'stateDiagram-v2'] fsm_graph.extend(_to_mermaid(self.machine.machine_attributes, " ")) for style_name, style_attrs in self.machine.style_attributes["node"].items(): if style_name: fsm_graph.append("classDef s_{} {}".format( style_name, ','.join(_to_mermaid(style_attrs, ":")))) fsm_graph.append("") states, transitions = self._get_elements() if roi_state: active_states = set() sep = getattr(self.machine.state_cls, "separator", None) for state in self._flatten(roi_state): active_states.add(state) if sep: state = sep.join(state.split(sep)[:-1]) while state: active_states.add(state) state = sep.join(state.split(sep)[:-1]) transitions = [ t for t in transitions if t["source"] in active_states or self.custom_styles["edge"][t["source"]][t["dest"]] ] active_states = active_states.union({ t for trans in transitions for t in [trans["source"], trans.get("dest", trans["source"])] }) active_states = active_states.union({k for k, style in self.custom_styles["node"].items() if style}) states = filter_states(copy.deepcopy(states), active_states, self.machine.state_cls) self._add_nodes(states, fsm_graph) fsm_graph.append("") self._add_edges(transitions, fsm_graph) if self.machine.initial and (roi_state is None or roi_state == self.machine.initial): fsm_graph.append("[*] --> {}".format(self.machine.initial)) indent = 0 for i in range(len(fsm_graph)): next_indent = indent if fsm_graph[i].startswith("stateDiagram") or fsm_graph[i].endswith("{"): next_indent += 2 elif fsm_graph[i].startswith("}"): indent -= 2 next_indent -= 2 fsm_graph[i] = " " * indent + fsm_graph[i] indent = next_indent return DigraphMock("\n".join(fsm_graph)) def _convert_state_attributes(self, state): label = state.get("label", state["name"]) if self.machine.show_state_attributes: if "tags" in state: label += " [" + ", ".join(state["tags"]) + "]" if "on_enter" in state: label += r"\n- enter:\n + " + r"\n + ".join(state["on_enter"]) if "on_exit" in state: label += r"\n- exit:\n + " + r"\n + ".join(state["on_exit"]) if "timeout" in state: label += r'\n- timeout(' + state['timeout'] + 's) -> (' + ', '.join(state['on_timeout']) + ')' # end each label with a left-aligned newline return label
Graph
python
kubernetes-client__python
kubernetes/client/models/v1beta1_device_attribute.py
{ "start": 383, "end": 5916 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'bool': 'bool', 'int': 'int', 'string': 'str', 'version': 'str' } attribute_map = { 'bool': 'bool', 'int': 'int', 'string': 'string', 'version': 'version' } def __init__(self, bool=None, int=None, string=None, version=None, local_vars_configuration=None): # noqa: E501 """V1beta1DeviceAttribute - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._bool = None self._int = None self._string = None self._version = None self.discriminator = None if bool is not None: self.bool = bool if int is not None: self.int = int if string is not None: self.string = string if version is not None: self.version = version @property def bool(self): """Gets the bool of this V1beta1DeviceAttribute. # noqa: E501 BoolValue is a true/false value. # noqa: E501 :return: The bool of this V1beta1DeviceAttribute. # noqa: E501 :rtype: bool """ return self._bool @bool.setter def bool(self, bool): """Sets the bool of this V1beta1DeviceAttribute. BoolValue is a true/false value. # noqa: E501 :param bool: The bool of this V1beta1DeviceAttribute. # noqa: E501 :type: bool """ self._bool = bool @property def int(self): """Gets the int of this V1beta1DeviceAttribute. # noqa: E501 IntValue is a number. # noqa: E501 :return: The int of this V1beta1DeviceAttribute. # noqa: E501 :rtype: int """ return self._int @int.setter def int(self, int): """Sets the int of this V1beta1DeviceAttribute. IntValue is a number. # noqa: E501 :param int: The int of this V1beta1DeviceAttribute. # noqa: E501 :type: int """ self._int = int @property def string(self): """Gets the string of this V1beta1DeviceAttribute. # noqa: E501 StringValue is a string. Must not be longer than 64 characters. # noqa: E501 :return: The string of this V1beta1DeviceAttribute. # noqa: E501 :rtype: str """ return self._string @string.setter def string(self, string): """Sets the string of this V1beta1DeviceAttribute. StringValue is a string. Must not be longer than 64 characters. # noqa: E501 :param string: The string of this V1beta1DeviceAttribute. # noqa: E501 :type: str """ self._string = string @property def version(self): """Gets the version of this V1beta1DeviceAttribute. # noqa: E501 VersionValue is a semantic version according to semver.org spec 2.0.0. Must not be longer than 64 characters. # noqa: E501 :return: The version of this V1beta1DeviceAttribute. # noqa: E501 :rtype: str """ return self._version @version.setter def version(self, version): """Sets the version of this V1beta1DeviceAttribute. VersionValue is a semantic version according to semver.org spec 2.0.0. Must not be longer than 64 characters. # noqa: E501 :param version: The version of this V1beta1DeviceAttribute. # noqa: E501 :type: str """ self._version = version def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1beta1DeviceAttribute): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1beta1DeviceAttribute): return True return self.to_dict() != other.to_dict()
V1beta1DeviceAttribute
python
huggingface__transformers
tests/models/bigbird_pegasus/test_modeling_bigbird_pegasus.py
{ "start": 109133, "end": 110214 }
class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): all_model_classes = (BigBirdPegasusDecoder, BigBirdPegasusForCausalLM) if is_torch_available() else () is_encoder_decoder = False def setUp( self, ): self.model_tester = BigBirdPegasusStandaloneDecoderModelTester(self, is_training=False) self.config_tester = ConfigTester(self, config_class=BigBirdPegasusConfig) def test_config(self): self.config_tester.run_common_tests() def test_decoder_model_past(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past(*config_and_inputs) def test_decoder_model_attn_mask_past(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_attention_mask_past(*config_and_inputs) @unittest.skip("Decoder cannot retain gradients") def test_retain_grad_hidden_states_attentions(self): return
BigBirdPegasusStandaloneDecoderModelTest
python
automl__auto-sklearn
autosklearn/ensembles/singlebest_ensemble.py
{ "start": 5339, "end": 8491 }
class ____(AbstractSingleModelEnsemble): """Ensemble consisting of a single model. This class is used by the :class:`MultiObjectiveDummyEnsemble` to represent ensembles consisting of a single model, and this class should not be used on its own. Do not use by yourself! Parameters ---------- task_type: int An identifier indicating which task is being performed. metrics: Sequence[Scorer] | Scorer The metrics used to evaluate the models. backend : Backend Gives access to the backend of Auto-sklearn. Not used. model_index : int Index of the model that constitutes the ensemble. This index will be used to select the correct predictions that will be passed during ``fit`` and ``predict``. random_state: int | RandomState | None = None Not used. """ def __init__( self, task_type: int, metrics: Sequence[Scorer] | Scorer, backend: Backend, model_index: int, random_state: int | np.random.RandomState | None = None, ): super().__init__( task_type=task_type, metrics=metrics, random_state=random_state, backend=backend, ) self.indices_ = [model_index] def fit( self, base_models_predictions: np.ndarray | list[np.ndarray], true_targets: np.ndarray, model_identifiers: list[tuple[int, int, float]], runs: Sequence[Run], X_data: SUPPORTED_FEAT_TYPES | None = None, ) -> SingleModelEnsemble: """Dummy implementation of the ``fit`` method. Actualy work of passing the model index is done in the constructor. This method only stores the identifier of the selected model and computes it's validation loss. Parameters ---------- base_models_predictions: np.ndarray shape = (n_base_models, n_data_points, n_targets) n_targets is the number of classes in case of classification, n_targets is 0 or 1 in case of regression Can be a list of 2d numpy arrays as well to prevent copying all predictions into a single, large numpy array. true_targets : array of shape [n_targets] model_identifiers : identifier for each base model. Can be used for practical text output of the ensemble. runs: Sequence[Run] Additional information for each run executed by SMAC that was considered by the ensemble builder. Not used. X_data : list-like | spmatrix | None = None X data to feed to a metric if it requires it Returns ------- self """ self.identifiers_ = [model_identifiers[self.indices_[0]]] loss = calculate_losses( solution=true_targets, prediction=base_models_predictions[self.indices_[0]], task_type=self.task_type, metrics=self.metrics, X_data=X_data, ) self.best_model_score_ = loss[self.metrics[0].name] return self
SingleModelEnsemble
python
pytorch__pytorch
torch/ao/nn/quantized/dynamic/modules/conv.py
{ "start": 15534, "end": 18425 }
class ____(nnq.ConvTranspose3d): r"""A dynamically quantized transposed convolution module with floating point tensors as inputs and outputs. For details on input arguments, parameters, and implementation see :class:`~torch.nn.ConvTranspose3d`. For special notes, please, see :class:`~torch.ao.nn.quantized.dynamic.Conv3d` Attributes: weight (Tensor): packed tensor derived from the learnable weight parameter. scale (Tensor): scalar for the output scale zero_point (Tensor): scalar for the output zero point See :class:`~torch.nn.ConvTranspose3d` for other attributes. Examples:: >>> # xdoctest: +SKIP >>> # With cubic kernels and equal stride >>> m = nnq.ConvTranspose3d(16, 33, 3, stride=2) >>> # non-cubic kernels and unequal stride and with padding >>> m = nnq.ConvTranspose3d(16, 33, (3, 3, 5), stride=(2, 1, 1), padding=(4, 2, 2)) >>> output = m(input) >>> # exact output size can be also specified as an argument >>> downsample = nnq.Conv3d(16, 16, 3, stride=2, padding=1) >>> upsample = nnq.ConvTranspose3d(16, 16, 3, stride=2, padding=1) >>> h = downsample(input) >>> h.size() torch.Size([1, 16, 6, 6, 6]) >>> output = upsample(h, output_size=input.size()) >>> output.size() torch.Size([1, 16, 12, 12, 12]) """ _FLOAT_MODULE: ClassVar[type[nn.ConvTranspose3d]] = nn.ConvTranspose3d def __init__( self, in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, groups=1, bias=True, dilation=1, padding_mode="zeros", device=None, dtype=None, ): warnings.warn( f"The current implementation of the {self._get_name()} module has poor numerical accuracy and its use is not recommended", # noqa: B950 stacklevel=2, ) factory_kwargs = {"device": device, "dtype": dtype} super().__init__( in_channels, out_channels, kernel_size, stride, padding, output_padding, groups, bias, dilation, padding_mode, **factory_kwargs, ) def _get_name(self): return "DynamicQuantizedConvTranspose3d" def forward(self, input: Tensor, reduce_range: bool = True) -> Tensor: # Temporarily using len(shape) instead of ndim due to JIT issue # https://github.com/pytorch/pytorch/issues/23890 if len(input.shape) != 5: raise ValueError("Input shape must be `(N, C, T, H, W)`!") return ops.quantized.conv_transpose3d_dynamic( input, self._packed_params, reduce_range )
ConvTranspose3d
python
dagster-io__dagster
python_modules/automation/automation/dagster_docs/docstring_rules/base.py
{ "start": 3206, "end": 4298 }
class ____: """Base class for all docstring validation rules.""" def __init__(self, name: str, enabled: bool = True): self.name = name self.enabled = enabled def validate(self, context: ValidationContext, result: ValidationResult) -> ValidationResult: """Apply this rule's validation logic. Args: context: Validation context with docstring and metadata result: Current validation result to add findings to Returns: Updated ValidationResult with any new errors/warnings """ if self.should_skip(context): return result return self._validate_impl(context, result) def should_skip(self, context: ValidationContext) -> bool: """Check if this rule should be skipped for the current context.""" return not self.enabled def _validate_impl( self, context: ValidationContext, result: ValidationResult ) -> ValidationResult: """Override this method to implement rule-specific validation logic.""" return result
ValidationRule
python
huggingface__transformers
src/transformers/trainer_pt_utils.py
{ "start": 11015, "end": 14510 }
class ____: """ Container to store intermediate results of evaluation loop. Args: do_nested_concat (`bool`, *optional*, defaults to `True`): If set to `True`, each iteration will recursively concatenate a new object containing tensors to the existing stored tensors, provided that the structure of the existing object and the new one are identical. If set to `False`, all newly added tensors will be stored in a list. padding_index (`int`, *optional*, defaults to -100): Value used to pad tensors of different shapes when `do_nested_concat=True`. """ def __init__(self, do_nested_concat: bool = True, padding_index: int = -100): self.do_nested_concat = do_nested_concat self.padding_index = padding_index self.tensors = None self.arrays = None def add(self, tensors) -> None: """Add tensors to the stored objects. If `do_nested_concat=True`, the tensors will be concatenated recursively.""" if self.tensors is None: self.tensors = tensors if self.do_nested_concat else [tensors] elif self.do_nested_concat: self.tensors = nested_concat(self.tensors, tensors, padding_index=self.padding_index) else: self.tensors.append(tensors) def to_cpu_and_numpy(self) -> None: """Move tensors in stored objects to CPU and convert them to numpy arrays.""" # Check if we have something to add, if not just return if self.tensors is None: return new_arrays = nested_numpify(self.tensors) if self.arrays is None: self.arrays = new_arrays elif self.do_nested_concat: self.arrays = nested_concat(self.arrays, new_arrays, padding_index=self.padding_index) else: self.arrays.extend(new_arrays) # reset device tensors after adding to cpu self.tensors = None def get_arrays(self): """Returns the numpified and moved to CPU stored objects.""" self.to_cpu_and_numpy() return self.arrays def get_tpu_sampler(dataset: torch.utils.data.Dataset, batch_size: int): if xr.world_size() <= 1: return RandomSampler(dataset) return DistributedSampler(dataset, num_replicas=xr.world_size(), rank=xr.global_ordinal()) def nested_new_like(arrays, num_samples, padding_index=-100): """Create the same nested structure as `arrays` with a first dimension always at `num_samples`.""" if isinstance(arrays, (list, tuple)): return type(arrays)(nested_new_like(x, num_samples) for x in arrays) return np.full_like(arrays, padding_index, shape=(num_samples, *arrays.shape[1:])) def expand_like(arrays, new_seq_length, padding_index=-100): """Expand the `arrays` so that the second dimension grows to `new_seq_length`. Uses `padding_index` for padding.""" result = np.full_like(arrays, padding_index, shape=(arrays.shape[0], new_seq_length) + arrays.shape[2:]) result[:, : arrays.shape[1]] = arrays return result def nested_truncate(tensors, limit): "Truncate `tensors` at `limit` (even if it's a nested list/tuple/dict of tensors)." if isinstance(tensors, (list, tuple)): return type(tensors)(nested_truncate(t, limit) for t in tensors) if isinstance(tensors, Mapping): return type(tensors)({k: nested_truncate(t, limit) for k, t in tensors.items()}) return tensors[:limit] @dataclass
EvalLoopContainer
python
doocs__leetcode
solution/0000-0099/0006.Zigzag Conversion/Solution.py
{ "start": 0, "end": 342 }
class ____: def convert(self, s: str, numRows: int) -> str: if numRows == 1: return s g = [[] for _ in range(numRows)] i, k = 0, -1 for c in s: g[i].append(c) if i == 0 or i == numRows - 1: k = -k i += k return ''.join(chain(*g))
Solution
python
dagster-io__dagster
python_modules/libraries/dagster-dbt/dagster_dbt/cloud_v2/resources.py
{ "start": 1814, "end": 2168 }
class ____(NamedTuple): """The DbtCloudCredentials to access your dbt Cloud workspace. Args: account_id (int): The ID of your dbt Cloud account. token (str): Your dbt Cloud API token. access_url (str): Your dbt Cloud workspace URL. """ account_id: int token: str access_url: str @public
DbtCloudCredentials
python
getsentry__sentry
tests/sentry/issues/auto_source_code_config/test_process_event.py
{ "start": 21030, "end": 21820 }
class ____(LanguageSpecificDeriveCodeMappings): platform = "ruby" def test_auto_source_code_config_rb(self) -> None: self._process_and_assert_configuration_changes( repo_trees={REPO1: ["some/path/test.rb"]}, frames=[self.frame("some/path/test.rb", True)], platform=self.platform, expected_new_code_mappings=[self.code_mapping("", "")], ) def test_auto_source_code_config_rake(self) -> None: self._process_and_assert_configuration_changes( repo_trees={REPO1: ["lib/tasks/crontask.rake"]}, frames=[self.frame("lib/tasks/crontask.rake", True)], platform=self.platform, expected_new_code_mappings=[self.code_mapping("", "")], )
TestRubyDeriveCodeMappings
python
celery__celery
t/unit/backends/test_cache.py
{ "start": 5787, "end": 6621 }
class ____: @contextmanager def mock_memcache(self): memcache = types.ModuleType('memcache') memcache.Client = MemcachedClient memcache.Client.__module__ = memcache.__name__ prev, sys.modules['memcache'] = sys.modules.get('memcache'), memcache try: yield True finally: if prev is not None: sys.modules['memcache'] = prev @contextmanager def mock_pylibmc(self): pylibmc = types.ModuleType('pylibmc') pylibmc.Client = MemcachedClient pylibmc.Client.__module__ = pylibmc.__name__ prev = sys.modules.get('pylibmc') sys.modules['pylibmc'] = pylibmc try: yield True finally: if prev is not None: sys.modules['pylibmc'] = prev
MockCacheMixin
python
astropy__astropy
astropy/table/table_helpers.py
{ "start": 3373, "end": 5071 }
class ____: """ Minimal mixin using a simple wrapper around a numpy array. TODO: think about the future of this class as it is mostly for demonstration purposes (of the mixin protocol). Consider taking it out of core and putting it into a tutorial. One advantage of having this in core is that it is getting tested in the mixin testing though it doesn't work for multidim data. """ info = ArrayWrapperInfo() def __init__(self, data, copy=True): if isinstance(data, ArrayWrapper): # this is done to preserve byteorder through copies arr = data.data else: arr = data self.data = np.array(arr, copy=copy) if "info" in getattr(data, "__dict__", ()): self.info = data.info def __getitem__(self, item): if isinstance(item, (int, np.integer)): out = self.data[item] else: out = self.__class__(self.data[item], copy=False) if "info" in self.__dict__: out.info = self.info return out def __setitem__(self, item, value): self.data[item] = value def __len__(self): return len(self.data) def __eq__(self, other): """Minimal equality testing, mostly for mixin unit tests.""" if isinstance(other, ArrayWrapper): return self.data == other.data else: return self.data == other @property def dtype(self): return self.data.dtype @property def shape(self): return self.data.shape def __repr__(self): return f"<{self.__class__.__name__} name='{self.info.name}' data={self.data}>"
ArrayWrapper
python
getsentry__sentry
src/sentry/core/endpoints/scim/members.py
{ "start": 2591, "end": 3529 }
class ____(Field): """ A SCIM PATCH operation value can either be a boolean, or an object depending on the client. """ def to_representation(self, value) -> dict | bool: if isinstance(value, bool): return value elif isinstance(value, dict): return value elif isinstance(value, str): value = resolve_maybe_bool_value(value) if value is not None: return value raise ValidationError("value must be a boolean or object") def to_internal_value(self, data) -> dict | bool: if isinstance(data, bool): return data elif isinstance(data, dict): return data elif isinstance(data, str): value = resolve_maybe_bool_value(data) if value is not None: return value raise ValidationError("value must be a boolean or object")
OperationValue
python
wandb__wandb
wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py
{ "start": 13492, "end": 14203 }
class ____(Value): __slots__ = ('loc', 'value',) _fields = ('value',) def __init__(self, value, loc=None): self.loc = loc self.value = value def __eq__(self, other): return ( self is other or ( isinstance(other, BooleanValue) and # self.loc == other.loc and self.value == other.value ) ) def __repr__(self): return ('BooleanValue(' 'value={self.value!r}' ')').format(self=self) def __copy__(self): return type(self)( self.value, self.loc ) def __hash__(self): return id(self)
BooleanValue
python
spack__spack
lib/spack/spack/test/llnl/util/filesystem.py
{ "start": 1207, "end": 2845 }
class ____: """Tests for ``filesystem.copy``""" def test_file_dest(self, stage): """Test using a filename as the destination.""" with fs.working_dir(str(stage)): fs.copy("source/1", "dest/1") assert os.path.exists("dest/1") def test_dir_dest(self, stage): """Test using a directory as the destination.""" with fs.working_dir(str(stage)): fs.copy("source/1", "dest") assert os.path.exists("dest/1") def test_glob_src(self, stage): """Test using a glob as the source.""" with fs.working_dir(str(stage)): fs.copy("source/a/*/*", "dest") assert os.path.exists("dest/2") assert os.path.exists("dest/3") def test_non_existing_src(self, stage): """Test using a non-existing source.""" with fs.working_dir(str(stage)): with pytest.raises(OSError, match="No such file or directory"): fs.copy("source/none", "dest") def test_multiple_src_file_dest(self, stage): """Test a glob that matches multiple source files and a dest that is not a directory.""" with fs.working_dir(str(stage)): match = ".* matches multiple files but .* is not a directory" with pytest.raises(ValueError, match=match): fs.copy("source/a/*/*", "dest/1") def check_added_exe_permissions(src, dst): src_mode = os.stat(src).st_mode dst_mode = os.stat(dst).st_mode for perm in [stat.S_IXUSR, stat.S_IXGRP, stat.S_IXOTH]: if src_mode & perm: assert dst_mode & perm
TestCopy
python
allegroai__clearml
clearml/backend_api/services/v2_23/events.py
{ "start": 108132, "end": 109136 }
class ____(Response): """ Response of events.get_scalar_metrics_and_variants endpoint. :param metrics: :type metrics: dict """ _service = "events" _action = "get_scalar_metrics_and_variants" _version = "2.23" _schema = { "definitions": {}, "properties": {"metrics": {"additionalProperties": True, "type": ["object", "null"]}}, "type": "object", } def __init__(self, metrics: Optional[dict] = None, **kwargs: Any) -> None: super(GetScalarMetricsAndVariantsResponse, self).__init__(**kwargs) self.metrics = metrics @schema_property("metrics") def metrics(self) -> Optional[dict]: return self._property_metrics @metrics.setter def metrics(self, value: Optional[dict]) -> None: if value is None: self._property_metrics = None return self.assert_isinstance(value, "metrics", (dict,)) self._property_metrics = value
GetScalarMetricsAndVariantsResponse
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/paramInference2.py
{ "start": 743, "end": 1102 }
class ____(Parent2): def method1(self, fn, *args, **kwargs): reveal_type(self, expected_text="Self@Child2") reveal_type(fn, expected_text="(...) -> Unknown") reveal_type(args, expected_text="tuple[Unknown, ...]") reveal_type(kwargs, expected_text="dict[str, Unknown]") return super().method1(fn, *args, **kwargs)
Child2
python
pallets__werkzeug
tests/test_datastructures.py
{ "start": 10416, "end": 10577 }
class ____(_ImmutableDictTests): storage_class = ds.ImmutableDict @pytest.mark.filterwarnings("ignore:'OrderedMultiDict':DeprecationWarning")
TestImmutableDict
python
ray-project__ray
python/ray/train/tests/test_iter_torch_batches_gpu.py
{ "start": 3012, "end": 3413 }
class ____(NumpyBatchCollateFn): """Collate function that returns only the id array as a tensor.""" def __call__(self, batch: Dict[str, np.ndarray]) -> torch.Tensor: """Return only the id array as a tensor.""" assert isinstance(batch, dict) tensor_dict = convert_ndarray_batch_to_torch_tensor_batch(batch) return tensor_dict["id"]
SingleTensorNumpyBatchCollateFn
python
pandas-dev__pandas
asv_bench/benchmarks/algos/isin.py
{ "start": 9274, "end": 9620 }
class ____: def setup(self): self.range_idx = Index(range(1000)) self.index = Index(list(range(1000))) self.series = Series(np.random.randint(100_000, size=1000)) def time_isin_range_index(self): self.series.isin(self.range_idx) def time_isin_index(self): self.series.isin(self.index)
IsInIndexes
python
facebookresearch__faiss
tests/test_binary_io.py
{ "start": 1354, "end": 2333 }
class ____(unittest.TestCase): def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) d = 32 nt = 200 nb = 1500 nq = 500 (self.xt, self.xb, self.xq) = make_binary_dataset(d, nb, nt, nq) def test_ivf_flat(self): d = self.xq.shape[1] * 8 quantizer = faiss.IndexBinaryFlat(d) index = faiss.IndexBinaryIVF(quantizer, d, 8) index.cp.min_points_per_centroid = 5 # quiet warning index.nprobe = 4 index.train(self.xt) index.add(self.xb) D, I = index.search(self.xq, 3) fd, tmpnam = tempfile.mkstemp() os.close(fd) try: faiss.write_index_binary(index, tmpnam) index2 = faiss.read_index_binary(tmpnam) D2, I2 = index2.search(self.xq, 3) assert (I2 == I).all() assert (D2 == D).all() finally: os.remove(tmpnam)
TestBinaryIVF
python
PyCQA__pylint
doc/data/messages/s/self-cls-assignment/good.py
{ "start": 0, "end": 185 }
class ____: @classmethod def list_fruits(cls): fruit = "apple" print(fruit) def print_color(self, *colors): color = colors[1] print(color)
Fruit
python
getsentry__sentry
tests/sentry/seer/autofix/test_autofix.py
{ "start": 39342, "end": 40838 }
class ____(APITestCase, SnubaTestCase): def setUp(self) -> None: super().setUp() self.organization.update_option("sentry:gen_ai_consent_v2024_11_14", True) self.organization.update_option("sentry:hide_ai_features", True) @patch("sentry.models.Group.get_recommended_event_for_environments") @patch("sentry.models.Group.get_latest_event") @patch("sentry.seer.autofix.autofix._get_serialized_event") def test_trigger_autofix_with_hide_ai_features_enabled( self, mock_get_serialized_event, mock_get_latest_event, mock_get_recommended_event, mock_get_seer_org_acknowledgement, ): """Tests that autofix is blocked when organization has hideAiFeatures set to True""" mock_get_recommended_event.return_value = None mock_get_latest_event.return_value = None # We should never reach _get_serialized_event since hideAiFeatures should block the request mock_get_serialized_event.return_value = (None, None) group = self.create_group() user = self.create_user() response = trigger_autofix(group=group, user=user, instruction="Test instruction") assert response.status_code == 403 assert "AI features are disabled for this organization" in response.data["detail"] # Verify _get_serialized_event was not called since AI features are disabled mock_get_serialized_event.assert_not_called()
TestTriggerAutofixWithHideAiFeatures
python
huggingface__transformers
src/transformers/models/ernie/modeling_ernie.py
{ "start": 41593, "end": 46085 }
class ____(ErniePreTrainedModel): _tied_weights_keys = { "cls.predictions.decoder.bias": "cls.predictions.bias", "cls.predictions.decoder.weight": "ernie.embeddings.word_embeddings.weight", } def __init__(self, config): super().__init__(config) if config.is_decoder: logger.warning( "If you want to use `ErnieForMaskedLM` make sure `config.is_decoder=False` for " "bi-directional self-attention." ) self.ernie = ErnieModel(config, add_pooling_layer=False) self.cls = ErnieOnlyMLMHead(config) # Initialize weights and apply final processing self.post_init() def get_output_embeddings(self): return self.cls.predictions.decoder def set_output_embeddings(self, new_embeddings): self.cls.predictions.decoder = new_embeddings self.cls.predictions.bias = new_embeddings.bias @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, task_type_ids: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple[torch.Tensor], MaskedLMOutput]: r""" task_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Task type embedding is a special embedding to represent the characteristic of different tasks, such as word-aware pre-training task, structure-aware pre-training task and semantic-aware pre-training task. We assign a `task_type_id` to each task and the `task_type_id` is in the range `[0, config.task_type_vocab_size-1] labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]` """ outputs = self.ernie( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, task_type_ids=task_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, return_dict=True, **kwargs, ) sequence_output = outputs[0] prediction_scores = self.cls(sequence_output) masked_lm_loss = None if labels is not None: loss_fct = CrossEntropyLoss() # -100 index = padding token masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)) return MaskedLMOutput( loss=masked_lm_loss, logits=prediction_scores, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs): input_shape = input_ids.shape effective_batch_size = input_shape[0] # add a dummy token if self.config.pad_token_id is None: raise ValueError("The PAD token should be defined for generation") attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1) dummy_token = torch.full( (effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device ) input_ids = torch.cat([input_ids, dummy_token], dim=1) return {"input_ids": input_ids, "attention_mask": attention_mask} @classmethod def can_generate(cls) -> bool: """ Legacy correction: ErnieForMaskedLM can't call `generate()` from `GenerationMixin`, even though it has a `prepare_inputs_for_generation` method. """ return False
ErnieForMaskedLM
python
doocs__leetcode
solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution2.py
{ "start": 0, "end": 133 }
class ____: def maxProduct(self, nums: List[int]) -> int: nums.sort() return (nums[-1] - 1) * (nums[-2] - 1)
Solution
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/stack_op_test.py
{ "start": 12814, "end": 15892 }
class ____(test.TestCase): def testSimple(self): self.assertAllEqual([1, 0, 2], ops.convert_to_tensor([1, constant_op.constant(0), 2])) self.assertAllEqual([[0, 0, 0], [0, 1, 0], [0, 0, 0]], ops.convert_to_tensor([[0, 0, 0], [0, constant_op.constant(1), 0], [0, 0, 0]])) self.assertAllEqual([[0, 0, 0], [0, 1, 0], [0, 0, 0]], ops.convert_to_tensor([[0, 0, 0], constant_op.constant([0, 1, 0]), [0, 0, 0]])) self.assertAllEqual([[0, 0, 0], [0, 1, 0], [0, 0, 0]], ops.convert_to_tensor([ constant_op.constant([0, 0, 0]), constant_op.constant([0, 1, 0]), constant_op.constant([0, 0, 0]) ])) def testWithNDArray(self): with self.session(): result = ops.convert_to_tensor([[[0., 0.], constant_op.constant([1., 1.])], np.array( [[2., 2.], [3., 3.]], dtype=np.float32)]) self.assertAllEqual([[[0., 0.], [1., 1.]], [[2., 2.], [3., 3.]]], self.evaluate(result)) def testDtype(self): t_0 = ops.convert_to_tensor([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]) self.assertEqual(dtypes.float32, t_0.dtype) t_1 = ops.convert_to_tensor([[0., 0., 0.], constant_op.constant( [0., 0., 0.], dtype=dtypes.float64), [0., 0., 0.]]) self.assertEqual(dtypes.float64, t_1.dtype) t_2 = ops.convert_to_tensor( [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]], dtype=dtypes.float64) self.assertEqual(dtypes.float64, t_2.dtype) t_3 = ops.convert_to_tensor( [[0., 0., 0.], constant_op.constant([0., 0., 0.], dtype=dtypes.float64), [0., 0., 0.] ], dtype=dtypes.float32) self.assertEqual(dtypes.float32, t_3.dtype) t_4 = ops.convert_to_tensor( [constant_op.constant([0., 0., 0.], dtype=dtypes.float64)], dtype=dtypes.float32) self.assertEqual(dtypes.float32, t_4.dtype) with self.assertRaises(TypeError): ops.convert_to_tensor([ constant_op.constant( [0., 0., 0.], dtype=dtypes.float32), constant_op.constant( [0., 0., 0.], dtype=dtypes.float64), [0., 0., 0.] ]) def testDtypeConversionWhenTensorDtypeMismatch(self): t_0 = ops.convert_to_tensor([0., 0., 0.]) self.assertEqual(dtypes.float32, t_0.dtype) t_1 = ops.convert_to_tensor([0, 0, 0]) self.assertEqual(dtypes.int32, t_1.dtype) t_2 = ops.convert_to_tensor([t_0, t_0, t_1], dtype=dtypes.float64) self.assertEqual(dtypes.float64, t_2.dtype) if __name__ == "__main__": test.main()
AutomaticStackingTest
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/pool/impl.py
{ "start": 9246, "end": 10433 }
class ____(Pool): """A Pool which does not pool connections. Instead it literally opens and closes the underlying DB-API connection per each connection open/close. Reconnect-related functions such as ``recycle`` and connection invalidation are not supported by this Pool implementation, since no connections are held persistently. The :class:`.NullPool` class **is compatible** with asyncio and :func:`_asyncio.create_async_engine`. """ def status(self) -> str: return "NullPool" def _do_return_conn(self, record: ConnectionPoolEntry) -> None: record.close() def _do_get(self) -> ConnectionPoolEntry: return self._create_connection() def recreate(self) -> NullPool: self.logger.info("Pool recreating") return self.__class__( self._creator, recycle=self._recycle, echo=self.echo, logging_name=self._orig_logging_name, reset_on_return=self._reset_on_return, pre_ping=self._pre_ping, _dispatch=self.dispatch, dialect=self._dialect, ) def dispose(self) -> None: pass
NullPool
python
tensorflow__tensorflow
tensorflow/python/data/experimental/benchmarks/map_defun_benchmark.py
{ "start": 1124, "end": 2639 }
class ____(benchmark_base.DatasetBenchmarkBase): """Benchmarks for MapDefunOp.""" def _run(self, op, name, num_iters, benchmark_id): wall_time = self.run_op_benchmark(op=op, iters=num_iters, warmup=True) zero_division_delta = 1e-100 wall_time = wall_time + zero_division_delta self.report_benchmark( name=name, iters=num_iters, wall_time=wall_time, extras={ "examples_per_sec": 1 / float(wall_time), "model_name": "map_defun.benchmark.%d" % benchmark_id, "parameters": "%d" % num_iters, }) def benchmark_defun_vs_map_fn(self): """Benchmarks to compare the performance of MapDefun vs tf.map_fn.""" @def_function.function( input_signature=[tensor_spec.TensorSpec([], dtypes.int32)]) def defun(x): return array_ops.identity(x) def fn(x): return array_ops.identity(x) base = math_ops.range(10000) for input_size in [10, 100, 1000, 10000]: num_iters = 10000 // input_size map_defun_op = map_defun.map_defun(defun, [base], [dtypes.int32], [()]) map_fn_op = map_fn.map_fn(fn, base) self._run( op=map_defun_op, name="with_defun_size_%d" % input_size, num_iters=num_iters, benchmark_id=1) self._run( op=map_fn_op, name="without_defun_size_%d" % input_size, num_iters=num_iters, benchmark_id=2) if __name__ == "__main__": benchmark_base.test.main()
MapDefunBenchmark
python
django__django
django/db/migrations/operations/fields.py
{ "start": 5367, "end": 7071 }
class ____(FieldOperation): """Remove a field from a model.""" category = OperationCategory.REMOVAL def deconstruct(self): kwargs = { "model_name": self.model_name, "name": self.name, } return (self.__class__.__name__, [], kwargs) def state_forwards(self, app_label, state): state.remove_field(app_label, self.model_name_lower, self.name) def database_forwards(self, app_label, schema_editor, from_state, to_state): from_model = from_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, from_model): schema_editor.remove_field( from_model, from_model._meta.get_field(self.name) ) def database_backwards(self, app_label, schema_editor, from_state, to_state): to_model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, to_model): from_model = from_state.apps.get_model(app_label, self.model_name) schema_editor.add_field(from_model, to_model._meta.get_field(self.name)) def describe(self): return "Remove field %s from %s" % (self.name, self.model_name) @property def migration_name_fragment(self): return "remove_%s_%s" % (self.model_name_lower, self.name_lower) def reduce(self, operation, app_label): from .models import DeleteModel if ( isinstance(operation, DeleteModel) and operation.name_lower == self.model_name_lower ): return [operation] return super().reduce(operation, app_label)
RemoveField
python
mlflow__mlflow
mlflow/server/graphql/autogenerated_graphql_schema.py
{ "start": 8243, "end": 8548 }
class ____(graphene.InputObjectType): experiment_ids = graphene.List(graphene.String) filter = graphene.String() run_view_type = graphene.Field(MlflowViewType) max_results = graphene.Int() order_by = graphene.List(graphene.String) page_token = graphene.String()
MlflowSearchRunsInput
python
gevent__gevent
src/greentest/3.14/test_httpservers.py
{ "start": 47390, "end": 58429 }
class ____(unittest.TestCase): """Test the functionality of the BaseHTTPServer. Test the support for the Expect 100-continue header. """ HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK') def setUp (self): self.handler = SocketlessRequestHandler() def send_typical_request(self, message): input = BytesIO(message) output = BytesIO() self.handler.rfile = input self.handler.wfile = output self.handler.handle_one_request() output.seek(0) return output.readlines() def verify_get_called(self): self.assertTrue(self.handler.get_called) def verify_expected_headers(self, headers): for fieldName in b'Server: ', b'Date: ', b'Content-Type: ': self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1) def verify_http_server_response(self, response): match = self.HTTPResponseMatch.search(response) self.assertIsNotNone(match) def test_unprintable_not_logged(self): # We call the method from the class directly as our Socketless # Handler subclass overrode it... nice for everything BUT this test. self.handler.client_address = ('127.0.0.1', 1337) log_message = BaseHTTPRequestHandler.log_message with mock.patch.object(sys, 'stderr', StringIO()) as fake_stderr: log_message(self.handler, '/foo') log_message(self.handler, '/\033bar\000\033') log_message(self.handler, '/spam %s.', 'a') log_message(self.handler, '/spam %s.', '\033\x7f\x9f\xa0beans') log_message(self.handler, '"GET /foo\\b"ar\007 HTTP/1.0"') stderr = fake_stderr.getvalue() self.assertNotIn('\033', stderr) # non-printable chars are caught. self.assertNotIn('\000', stderr) # non-printable chars are caught. lines = stderr.splitlines() self.assertIn('/foo', lines[0]) self.assertIn(r'/\x1bbar\x00\x1b', lines[1]) self.assertIn('/spam a.', lines[2]) self.assertIn('/spam \\x1b\\x7f\\x9f\xa0beans.', lines[3]) self.assertIn(r'"GET /foo\\b"ar\x07 HTTP/1.0"', lines[4]) def test_http_1_1(self): result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n') self.verify_http_server_response(result[0]) self.verify_expected_headers(result[1:-1]) self.verify_get_called() self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n') self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1') self.assertEqual(self.handler.command, 'GET') self.assertEqual(self.handler.path, '/') self.assertEqual(self.handler.request_version, 'HTTP/1.1') self.assertSequenceEqual(self.handler.headers.items(), ()) def test_http_1_0(self): result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n') self.verify_http_server_response(result[0]) self.verify_expected_headers(result[1:-1]) self.verify_get_called() self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n') self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0') self.assertEqual(self.handler.command, 'GET') self.assertEqual(self.handler.path, '/') self.assertEqual(self.handler.request_version, 'HTTP/1.0') self.assertSequenceEqual(self.handler.headers.items(), ()) def test_http_0_9(self): result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n') self.assertEqual(len(result), 1) self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n') self.verify_get_called() def test_extra_space(self): result = self.send_typical_request( b'GET /spaced out HTTP/1.1\r\n' b'Host: dummy\r\n' b'\r\n' ) self.assertStartsWith(result[0], b'HTTP/1.1 400 ') self.verify_expected_headers(result[1:result.index(b'\r\n')]) self.assertFalse(self.handler.get_called) def test_with_continue_1_0(self): result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n') self.verify_http_server_response(result[0]) self.verify_expected_headers(result[1:-1]) self.verify_get_called() self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n') self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0') self.assertEqual(self.handler.command, 'GET') self.assertEqual(self.handler.path, '/') self.assertEqual(self.handler.request_version, 'HTTP/1.0') headers = (("Expect", "100-continue"),) self.assertSequenceEqual(self.handler.headers.items(), headers) def test_with_continue_1_1(self): result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n') self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n') self.assertEqual(result[1], b'\r\n') self.assertEqual(result[2], b'HTTP/1.1 200 OK\r\n') self.verify_expected_headers(result[2:-1]) self.verify_get_called() self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n') self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1') self.assertEqual(self.handler.command, 'GET') self.assertEqual(self.handler.path, '/') self.assertEqual(self.handler.request_version, 'HTTP/1.1') headers = (("Expect", "100-continue"),) self.assertSequenceEqual(self.handler.headers.items(), headers) def test_header_buffering_of_send_error(self): input = BytesIO(b'GET / HTTP/1.1\r\n\r\n') output = AuditableBytesIO() handler = SocketlessRequestHandler() handler.rfile = input handler.wfile = output handler.request_version = 'HTTP/1.1' handler.requestline = '' handler.command = None handler.send_error(418) self.assertEqual(output.numWrites, 2) def test_header_buffering_of_send_response_only(self): input = BytesIO(b'GET / HTTP/1.1\r\n\r\n') output = AuditableBytesIO() handler = SocketlessRequestHandler() handler.rfile = input handler.wfile = output handler.request_version = 'HTTP/1.1' handler.send_response_only(418) self.assertEqual(output.numWrites, 0) handler.end_headers() self.assertEqual(output.numWrites, 1) def test_header_buffering_of_send_header(self): input = BytesIO(b'GET / HTTP/1.1\r\n\r\n') output = AuditableBytesIO() handler = SocketlessRequestHandler() handler.rfile = input handler.wfile = output handler.request_version = 'HTTP/1.1' handler.send_header('Foo', 'foo') handler.send_header('bar', 'bar') self.assertEqual(output.numWrites, 0) handler.end_headers() self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n') self.assertEqual(output.numWrites, 1) def test_header_unbuffered_when_continue(self): def _readAndReseek(f): pos = f.tell() f.seek(0) data = f.read() f.seek(pos) return data input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n') output = BytesIO() self.handler.rfile = input self.handler.wfile = output self.handler.request_version = 'HTTP/1.1' self.handler.handle_one_request() self.assertNotEqual(_readAndReseek(output), b'') result = _readAndReseek(output).split(b'\r\n') self.assertEqual(result[0], b'HTTP/1.1 100 Continue') self.assertEqual(result[1], b'') self.assertEqual(result[2], b'HTTP/1.1 200 OK') def test_with_continue_rejected(self): usual_handler = self.handler # Save to avoid breaking any subsequent tests. self.handler = RejectingSocketlessRequestHandler() result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n') self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n') self.verify_expected_headers(result[1:-1]) # The expect handler should short circuit the usual get method by # returning false here, so get_called should be false self.assertFalse(self.handler.get_called) self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1) self.handler = usual_handler # Restore to avoid breaking any subsequent tests. def test_request_length(self): # Issue #10714: huge request lines are discarded, to avoid Denial # of Service attacks. result = self.send_typical_request(b'GET ' + b'x' * 65537) self.assertEqual(result[0], b'HTTP/1.1 414 URI Too Long\r\n') self.assertFalse(self.handler.get_called) self.assertIsInstance(self.handler.requestline, str) def test_header_length(self): # Issue #6791: same for headers result = self.send_typical_request( b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n') self.assertEqual(result[0], b'HTTP/1.1 431 Line too long\r\n') self.assertFalse(self.handler.get_called) self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1') def test_too_many_headers(self): result = self.send_typical_request( b'GET / HTTP/1.1\r\n' + b'X-Foo: bar\r\n' * 101 + b'\r\n') self.assertEqual(result[0], b'HTTP/1.1 431 Too many headers\r\n') self.assertFalse(self.handler.get_called) self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1') def test_html_escape_on_error(self): result = self.send_typical_request( b'<script>alert("hello")</script> / HTTP/1.1') result = b''.join(result) text = '<script>alert("hello")</script>' self.assertIn(html.escape(text, quote=False).encode('ascii'), result) def test_close_connection(self): # handle_one_request() should be repeatedly called until # it sets close_connection def handle_one_request(): self.handler.close_connection = next(close_values) self.handler.handle_one_request = handle_one_request close_values = iter((True,)) self.handler.handle() self.assertRaises(StopIteration, next, close_values) close_values = iter((False, False, True)) self.handler.handle() self.assertRaises(StopIteration, next, close_values) def test_date_time_string(self): now = time.time() # this is the old code that formats the timestamp year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now) expected = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( self.handler.weekdayname[wd], day, self.handler.monthname[month], year, hh, mm, ss ) self.assertEqual(self.handler.date_time_string(timestamp=now), expected)
BaseHTTPRequestHandlerTestCase
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_quotes/docstring_singles.py
{ "start": 91, "end": 772 }
class ____(MakeKlass(''' class params \t not a docstring ''')): ''' Single quotes multiline class docstring ''' ''' this is not a docstring ''' # The colon in the list indexing below is an edge case for the docstring scanner def f(self, bar=''' definitely not a docstring''', val=l[Cls():3]): ''' Single quotes multiline function docstring ''' some_expression = 'hello world' ''' this is not a docstring ''' if l: ''' Looks like a docstring, but in reality it isn't - only modules, classes and functions ''' pass
Cls
python
huggingface__transformers
src/transformers/models/llama4/configuration_llama4.py
{ "start": 16999, "end": 20438 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Llama4Model`]. It is used to instantiate an Llama4 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the Llama4 109B. e.g. [meta-llama/Llama-4-Scout-17B-16E](https://huggingface.co/meta-llama/Llama-4-Scout-17B-16E) Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: vision_config (`Llama4VisionConfig`, *optional*): The Llama4 Vision config. text_config (`Llama4TextConfig`, *optional*): The Llama4 Text config. boi_token_index (`int`, *optional*, defaults to 200080): The begin-of-image token index to wrap the image prompt. eoi_token_index (`int`, *optional*, defaults to 200081): The end-of-image token index to wrap the image prompt. image_token_index (`int`, *optional*, defaults to 200092): The image token index to encode the image prompt. tie_word_embeddings (`bool`, *optional*, defaults to `False`): Whether the model's input and output word embeddings should be tied. ```python >>> from transformers import Llama4Model, Llama4Config >>> # Initializing a Llama4 7B style configuration >>> configuration = Llama4Config() >>> # Initializing a model from the Llama4 7B style configuration >>> model = Llama4Model(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "llama4" attribute_map = { "image_token_id": "image_token_index", "boi_token_id": "boi_token_index", "eoi_token_id": "eoi_token_index", } sub_configs = {"text_config": Llama4TextConfig, "vision_config": Llama4VisionConfig} base_model_tp_plan = { "multi_modal_projector.linear_1": "colwise_rep", } def __init__( self, vision_config=None, text_config=None, boi_token_index=200080, eoi_token_index=200081, image_token_index=200092, tie_word_embeddings=False, **kwargs, ): if vision_config is None: self.vision_config = Llama4VisionConfig() logger.info("vision_config is None, using default llama4 vision config") elif isinstance(vision_config, dict): self.vision_config = Llama4VisionConfig(**vision_config) elif isinstance(vision_config, Llama4VisionConfig): self.vision_config = vision_config self.boi_token_index = boi_token_index self.eoi_token_index = eoi_token_index self.image_token_index = image_token_index if text_config is None: self.text_config = Llama4TextConfig() logger.info("text_config is None, using default llama4 text config") elif isinstance(text_config, dict): self.text_config = Llama4TextConfig(**text_config) elif isinstance(text_config, Llama4TextConfig): self.text_config = text_config super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs) __all__ = ["Llama4Config", "Llama4TextConfig", "Llama4VisionConfig"]
Llama4Config
python
bokeh__bokeh
src/bokeh/core/property/dataspec.py
{ "start": 2585, "end": 8213 }
class ____(Either): """ Base class for properties that accept either a fixed value, or a string name that references a column in a :class:`~bokeh.models.sources.ColumnDataSource`. Many Bokeh models have properties that a user might want to set either to a single fixed value, or to have the property take values from some column in a data source. As a concrete example consider a glyph with an ``x`` property for location. We might want to set all the glyphs that get drawn to have the same location, say ``x=10``. It would be convenient to just be able to write: .. code-block:: python glyph.x = 10 Alternatively, maybe each glyph that gets drawn should have a different location, according to the "pressure" column of a data source. In this case we would like to be able to write: .. code-block:: python glyph.x = "pressure" Bokeh ``DataSpec`` properties (and subclasses) afford this ease of and consistency of expression. Ultimately, all ``DataSpec`` properties resolve to dictionary values, with either a ``"value"`` key, or a ``"field"`` key, depending on how it is set. For instance: .. code-block:: python glyph.x = 10 # => { 'value': 10 } glyph.x = "pressure" # => { 'field': 'pressure' } When these underlying dictionary values are received in the browser, BokehJS knows how to interpret them and take the correct, expected action (i.e., draw the glyph at ``x=10``, or draw the glyph with ``x`` coordinates from the "pressure" column). In this way, both use-cases may be expressed easily in python, without having to handle anything differently, from the user perspective. It is worth noting that ``DataSpec`` properties can also be set directly with properly formed dictionary values: .. code-block:: python glyph.x = { 'value': 10 } # same as glyph.x = 10 glyph.x = { 'field': 'pressure' } # same as glyph.x = "pressure" Setting the property directly as a dict can be useful in certain situations. For instance some ``DataSpec`` subclasses also add a ``"units"`` key to the dictionary. This key is often set automatically, but the dictionary format provides a direct mechanism to override as necessary. Additionally, ``DataSpec`` can have a ``"transform"`` key, that specifies a client-side transform that should be applied to any fixed or field values before they are uses. As an example, you might want to apply a ``Jitter`` transform to the ``x`` values: .. code-block:: python glyph.x = { 'value': 10, 'transform': Jitter(width=0.4) } Note that ``DataSpec`` is not normally useful on its own. Typically, a model will define properties using one of the subclasses such as :class:`~bokeh.core.properties.NumberSpec` or :class:`~bokeh.core.properties.ColorSpec`. For example, a Bokeh model with ``x``, ``y`` and ``color`` properties that can handle fixed values or columns automatically might look like: .. code-block:: python class SomeModel(Model): x = NumberSpec(default=0, help="docs for x") y = NumberSpec(default=0, help="docs for y") color = ColorSpec(help="docs for color") # defaults to None """ def __init__(self, value_type, default, *, help: str | None = None) -> None: super().__init__( String, value_type, Instance(Value), Instance(Field), Instance(Expr), Struct( value=value_type, transform=Optional(Instance("bokeh.models.transforms.Transform")), ), Struct( field=String, transform=Optional(Instance("bokeh.models.transforms.Transform")), ), Struct( expr=Instance("bokeh.models.expressions.Expression"), transform=Optional(Instance("bokeh.models.transforms.Transform")), ), default=default, help=help, ) self.value_type = self._validate_type_param(value_type) self.accepts(Instance("bokeh.models.expressions.Expression"), lambda obj: Expr(obj)) def transform(self, value: Any): if isinstance(value, dict): if "value" in value: return Value(**value) if "field" in value: return Field(**value) if "expr" in value: return Expr(**value) return super().transform(value) def make_descriptors(self, base_name: str): """ Return a list of ``DataSpecPropertyDescriptor`` instances to install on a class, in order to delegate attribute access to this property. Args: base_name (str) : the name of the property these descriptors are for Returns: list[DataSpecPropertyDescriptor] The descriptors returned are collected by the ``MetaHasProps`` metaclass and added to ``HasProps`` subclasses during class creation. """ return [ DataSpecPropertyDescriptor(base_name, self) ] def to_serializable(self, obj: HasProps, name: str, val: Any) -> Vectorized: # Check for spec type value try: self.value_type.replace(String, Nothing()).validate(val, False) return Value(val) except ValueError: pass # Check for data source field name if isinstance(val, str): return Field(val) return val
DataSpec
python
wireservice__csvkit
csvkit/utilities/sql2csv.py
{ "start": 124, "end": 4504 }
class ____(CSVKitUtility): description = 'Execute a SQL query on a database and output the result to a CSV file.' # Overrides all flags except --linenumbers, --verbose, --version. override_flags = ['f', 'b', 'd', 'e', 'H', 'I', 'K', 'L', 'p', 'q', 'S', 't', 'u', 'z', 'zero', 'add-bom'] def add_arguments(self): self.argparser.add_argument( '--db', dest='connection_string', default='sqlite://', help='A SQLAlchemy connection string to connect to a database.') self.argparser.add_argument( '--engine-option', dest='engine_option', nargs=2, action='append', default=[], help="A keyword argument to SQLAlchemy's create_engine(), as a space-separated pair. " "This option can be specified multiple times. For example: thick_mode True") self.argparser.add_argument( '--execution-option', dest='execution_option', nargs=2, action='append', # https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection.execution_options.params.no_parameters # https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.Connection.execution_options.params.stream_results # https://docs.sqlalchemy.org/en/20/core/connections.html#using-server-side-cursors-a-k-a-stream-results default=[['no_parameters', True], ['stream_results', True]], help="A keyword argument to SQLAlchemy's execution_options(), as a space-separated pair. " "This option can be specified multiple times. For example: stream_results True") self.argparser.add_argument( metavar='FILE', nargs='?', dest='input_path', help='The file to use as SQL query. If FILE and --query are omitted, the query is piped data via STDIN.') self.argparser.add_argument( '--query', help="The SQL query to execute. Overrides FILE and STDIN.") self.argparser.add_argument( '-e', '--encoding', dest='encoding', default='utf-8', help='Specify the encoding of the input query file.') self.argparser.add_argument( '-H', '--no-header-row', dest='no_header_row', action='store_true', help='Do not output column names.') self.argparser.set_defaults( delimiter=None, doublequote=None, escapechar=None, encoding='utf-8', field_size_limit=None, quotechar=None, quoting=None, skipinitialspace=None, tabs=None, ) def main(self): if self.additional_input_expected() and not self.args.query: self.argparser.error('You must provide an input file or piped data.') try: engine = create_engine(self.args.connection_string, **parse_list(self.args.engine_option)) except ImportError as e: raise ImportError( "You don't appear to have the necessary database backend installed for connection string you're " "trying to use. Available backends include:\n\nPostgreSQL:\tpip install psycopg2\nMySQL:\t\tpip " "install mysql-connector-python OR pip install mysqlclient\n\nFor details on connection strings " "and other backends, please see the SQLAlchemy documentation on dialects at:\n\n" "https://www.sqlalchemy.org/docs/dialects/" ) from e connection = engine.connect() if self.args.query: query = self.args.query.strip() else: query = "" self.input_file = self._open_input_file(self.args.input_path) for line in self.input_file: query += line self.input_file.close() rows = connection.execution_options(**parse_list(self.args.execution_option)).exec_driver_sql(query) output = agate.csv.writer(self.output_file, **self.writer_kwargs) if rows.returns_rows: if not self.args.no_header_row: output.writerow(rows._metadata.keys) for row in rows: output.writerow(row) connection.close() engine.dispose() def launch_new_instance(): utility = SQL2CSV() utility.run() if __name__ == '__main__': launch_new_instance()
SQL2CSV
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI019_0.py
{ "start": 1218, "end": 1309 }
class ____[T]: def __new__(cls, *args: Any, **kwargs: Any) -> Self: ...
PEP695GoodDunderNew
python
sqlalchemy__sqlalchemy
test/ext/test_associationproxy.py
{ "start": 2446, "end": 2752 }
class ____: def __init__(self): self.values = list() @collection.appender def append(self, obj): self.values.append(obj) @collection.remover def remove(self, obj): self.values.remove(obj) def __iter__(self): return iter(self.values)
ObjectCollection
python
xlwings__xlwings
xlwings/_xlwindows.py
{ "start": 17254, "end": 22427 }
class ____(base_classes.App): def __init__(self, spec=None, add_book=True, xl=None, visible=None): # visible is only required on mac pythoncom.CoInitialize() if spec is not None: warn("spec is ignored on Windows.") if xl is None: # new instance self._xl = COMRetryObjectWrapper(DispatchEx("Excel.Application")) if add_book: self._xl.Workbooks.Add() self._hwnd = None elif isinstance(xl, int): self._xl = None self._hwnd = xl else: self._xl = xl self._hwnd = None self._pid = self.pid @property def xl(self): if self._xl is None: self._xl = get_xl_app_from_hwnd(self._hwnd) return self._xl @xl.setter def xl(self, value): self._xl = value api = xl @property def engine(self): return engine @property def selection(self): try: _ = ( self.xl.Selection.Address ) # Force exception outside of the retry wrapper e.g., if chart is selected return Range(xl=self.xl.Selection) except pywintypes.com_error: return None def activate(self, steal_focus=False): # makes the Excel instance the foreground Excel instance, # but not the foreground desktop app if the current foreground # app isn't already an Excel instance hwnd = windll.user32.GetForegroundWindow() if steal_focus or is_hwnd_xl_app(hwnd): windll.user32.SetForegroundWindow(self.xl.Hwnd) else: windll.user32.SetWindowPos(self.xl.Hwnd, hwnd, 0, 0, 0, 0, 0x1 | 0x2 | 0x10) @property def visible(self): return self.xl.Visible @visible.setter def visible(self, visible): self.xl.Visible = visible def quit(self): self.xl.DisplayAlerts = False self.xl.Quit() self.xl = None try: Apps.cleanup() except: # noqa: E722 pass def kill(self): PROCESS_TERMINATE = 1 handle = win32api.OpenProcess(PROCESS_TERMINATE, False, self._pid) win32api.TerminateProcess(handle, -1) win32api.CloseHandle(handle) try: Apps.cleanup() except: # noqa: E722 pass @property def screen_updating(self): return self.xl.ScreenUpdating @screen_updating.setter def screen_updating(self, value): self.xl.ScreenUpdating = value @property def display_alerts(self): return self.xl.DisplayAlerts @display_alerts.setter def display_alerts(self, value): self.xl.DisplayAlerts = value @property def enable_events(self): return self.xl.EnableEvents @enable_events.setter def enable_events(self, value): self.xl.EnableEvents = value @property def interactive(self): return self.xl.Interactive @interactive.setter def interactive(self, value): self.xl.Interactive = value @property def startup_path(self): return self.xl.StartupPath @property def calculation(self): return calculation_i2s[self.xl.Calculation] @calculation.setter def calculation(self, value): self.xl.Calculation = calculation_s2i[value] def calculate(self): self.xl.Calculate() @property def version(self): return self.xl.Version @property def books(self): return Books(xl=self.xl.Workbooks, app=self) @property def hwnd(self): if self._hwnd is None: self._hwnd = self._xl.Hwnd return self._hwnd @property def path(self): return self.xl.Path @property def pid(self): return win32process.GetWindowThreadProcessId(self.hwnd)[1] def run(self, macro, args): return self.xl.Run(macro, *args) @property def status_bar(self): return self.xl.StatusBar @status_bar.setter def status_bar(self, value): self.xl.StatusBar = value @property def cut_copy_mode(self): modes = {2: "cut", 1: "copy"} return modes.get(self.xl.CutCopyMode) @cut_copy_mode.setter def cut_copy_mode(self, value): self.xl.CutCopyMode = value def alert(self, prompt, title, buttons, mode, callback): buttons_dict = { None: win32con.MB_OK, "ok": win32con.MB_OK, "ok_cancel": win32con.MB_OKCANCEL, "yes_no": win32con.MB_YESNO, "yes_no_cancel": win32con.MB_YESNOCANCEL, } modes = { "info": win32con.MB_ICONINFORMATION, "critical": win32con.MB_ICONWARNING, } style = buttons_dict[buttons] if mode: style += modes[mode] rv = win32api.MessageBox( self.hwnd, "" if prompt is None else prompt, "" if title is None else title, style, ) return_values = {1: "ok", 2: "cancel", 6: "yes", 7: "no"} return return_values[rv]
App
python
fluentpython__example-code-2e
15-more-types/petbox/petbox.py
{ "start": 173, "end": 236 }
class ____: """Domestic animal kept for companionship."""
Pet
python
pytest-dev__pytest
testing/io/test_terminalwriter.py
{ "start": 1959, "end": 7193 }
class ____: @pytest.fixture(params=["path", "stringio"]) def tw(self, request, tmp_path: Path) -> Generator[terminalwriter.TerminalWriter]: f: io.TextIOWrapper | StringIO if request.param == "path": p = tmp_path.joinpath("tmpfile") f = open(str(p), "w+", encoding="utf8") tw = terminalwriter.TerminalWriter(f) def getlines(): f.flush() with open(str(p), encoding="utf8") as fp: return fp.readlines() elif request.param == "stringio": f = io.StringIO() tw = terminalwriter.TerminalWriter(f) def getlines(): f.seek(0) return f.readlines() tw.getlines = getlines # type: ignore tw.getvalue = lambda: "".join(getlines()) # type: ignore with f: yield tw def test_line(self, tw) -> None: tw.line("hello") lines = tw.getlines() assert len(lines) == 1 assert lines[0] == "hello\n" def test_line_unicode(self, tw) -> None: msg = "b\u00f6y" tw.line(msg) lines = tw.getlines() assert lines[0] == msg + "\n" def test_sep_no_title(self, tw) -> None: tw.sep("-", fullwidth=60) lines = tw.getlines() assert len(lines) == 1 assert lines[0] == "-" * (60 - win32) + "\n" def test_sep_with_title(self, tw) -> None: tw.sep("-", "hello", fullwidth=60) lines = tw.getlines() assert len(lines) == 1 assert lines[0] == "-" * 26 + " hello " + "-" * (27 - win32) + "\n" def test_sep_longer_than_width(self, tw) -> None: tw.sep("-", "a" * 10, fullwidth=5) (line,) = tw.getlines() # even though the string is wider than the line, still have a separator assert line == "- aaaaaaaaaa -\n" @pytest.mark.skipif(sys.platform == "win32", reason="win32 has no native ansi") @pytest.mark.parametrize("bold", (True, False)) @pytest.mark.parametrize("color", ("red", "green")) def test_markup(self, tw, bold: bool, color: str) -> None: text = tw.markup("hello", **{color: True, "bold": bold}) assert "hello" in text def test_markup_bad(self, tw) -> None: with pytest.raises(ValueError): tw.markup("x", wronkw=3) with pytest.raises(ValueError): tw.markup("x", wronkw=0) def test_line_write_markup(self, tw) -> None: tw.hasmarkup = True tw.line("x", bold=True) tw.write("x\n", red=True) lines = tw.getlines() if sys.platform != "win32": assert len(lines[0]) >= 2, lines assert len(lines[1]) >= 2, lines def test_attr_fullwidth(self, tw) -> None: tw.sep("-", "hello", fullwidth=70) tw.fullwidth = 70 tw.sep("-", "hello") lines = tw.getlines() assert len(lines[0]) == len(lines[1]) @pytest.mark.skipif(sys.platform == "win32", reason="win32 has no native ansi") def test_attr_hasmarkup() -> None: file = io.StringIO() tw = terminalwriter.TerminalWriter(file) assert not tw.hasmarkup tw.hasmarkup = True tw.line("hello", bold=True) s = file.getvalue() assert len(s) > len("hello\n") assert "\x1b[1m" in s assert "\x1b[0m" in s def assert_color(expected: bool, default: bool | None = None) -> None: file = io.StringIO() if default is None: default = not expected file.isatty = lambda: default # type: ignore tw = terminalwriter.TerminalWriter(file=file) assert tw.hasmarkup is expected tw.line("hello", bold=True) s = file.getvalue() if expected: assert len(s) > len("hello\n") assert "\x1b[1m" in s assert "\x1b[0m" in s else: assert s == "hello\n" def test_should_do_markup_PY_COLORS_eq_1(monkeypatch: MonkeyPatch) -> None: monkeypatch.setitem(os.environ, "PY_COLORS", "1") assert_color(True) def test_should_not_do_markup_PY_COLORS_eq_0(monkeypatch: MonkeyPatch) -> None: monkeypatch.setitem(os.environ, "PY_COLORS", "0") assert_color(False) def test_should_not_do_markup_NO_COLOR(monkeypatch: MonkeyPatch) -> None: monkeypatch.setitem(os.environ, "NO_COLOR", "1") assert_color(False) def test_should_do_markup_FORCE_COLOR(monkeypatch: MonkeyPatch) -> None: monkeypatch.setitem(os.environ, "FORCE_COLOR", "1") assert_color(True) @pytest.mark.parametrize( ["NO_COLOR", "FORCE_COLOR", "expected"], [ ("1", "1", False), ("", "1", True), ("1", "", False), ], ) def test_NO_COLOR_and_FORCE_COLOR( monkeypatch: MonkeyPatch, NO_COLOR: str, FORCE_COLOR: str, expected: bool, ) -> None: monkeypatch.setitem(os.environ, "NO_COLOR", NO_COLOR) monkeypatch.setitem(os.environ, "FORCE_COLOR", FORCE_COLOR) assert_color(expected) def test_empty_NO_COLOR_and_FORCE_COLOR_ignored(monkeypatch: MonkeyPatch) -> None: monkeypatch.setenv("TERM", "xterm-256color") monkeypatch.setitem(os.environ, "NO_COLOR", "") monkeypatch.setitem(os.environ, "FORCE_COLOR", "") assert_color(True, True) assert_color(False, False)
TestTerminalWriter
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/cache.py
{ "start": 1860, "end": 2361 }
class ____(_TransformedFnCache): """A function cache based on code objects. Code objects are good proxies for the source code of a function. This cache efficiently handles functions that share code objects, such as functions defined in a loop, bound methods, etc. The cache falls back to the function object, if it doesn't have a code object. """ def _get_key(self, entity): if hasattr(entity, '__code__'): return entity.__code__ else: return entity
CodeObjectCache
python
mlflow__mlflow
mlflow/store/tracking/dbmodels/models.py
{ "start": 9022, "end": 10317 }
class ____(Base): """ DB model for :py:class:`mlflow.entities.RunTag`. These are recorded in ``experiment_tags`` table. """ __tablename__ = "experiment_tags" key = Column(String(250)) """ Tag key: `String` (limit 250 characters). *Primary Key* for ``tags`` table. """ value = Column(String(5000), nullable=True) """ Value associated with tag: `String` (limit 5000 characters). Could be *null*. """ experiment_id = Column(Integer, ForeignKey("experiments.experiment_id")) """ Experiment ID to which this tag belongs: *Foreign Key* into ``experiments`` table. """ experiment = relationship("SqlExperiment", backref=backref("tags", cascade="all")) """ SQLAlchemy relationship (many:one) with :py:class:`mlflow.store.dbmodels.models.SqlExperiment`. """ __table_args__ = (PrimaryKeyConstraint("key", "experiment_id", name="experiment_tag_pk"),) def __repr__(self): return f"<SqlExperimentTag({self.key}, {self.value})>" def to_mlflow_entity(self): """ Convert DB model to corresponding MLflow entity. Returns: mlflow.entities.RunTag: Description of the return value. """ return ExperimentTag(key=self.key, value=self.value)
SqlExperimentTag
python
readthedocs__readthedocs.org
readthedocs/redirects/migrations/0006_add_new_fields.py
{ "start": 148, "end": 2751 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("redirects", "0005_allow_to_force_redirects"), ] operations = [ migrations.AddField( model_name="redirect", name="description", field=models.CharField( blank=True, max_length=255, verbose_name="Description", null=True, default="", ), ), migrations.AddField( model_name="redirect", name="enabled", field=models.BooleanField( default=True, help_text="Enable or disable the redirect.", verbose_name="Enabled", null=True, ), ), migrations.AddField( model_name="redirect", name="position", field=models.PositiveIntegerField( default=0, help_text="Order of execution of the redirect.", null=True, verbose_name="Position", ), ), migrations.AlterField( model_name="redirect", name="http_status", field=models.SmallIntegerField( choices=[ (302, "302 - Temporary Redirect"), (301, "301 - Permanent Redirect"), ], default=302, verbose_name="HTTP status code", ), ), migrations.AlterField( model_name="redirect", name="status", field=models.BooleanField(choices=[], default=True, null=True), ), migrations.AlterField( model_name="redirect", name="redirect_type", field=models.CharField( choices=[ ("page", "Page Redirect"), ("exact", "Exact Redirect"), ("clean_url_to_html", "Clean URL to HTML (file/ to file.html)"), ("html_to_clean_url", "HTML to clean URL (file.html to file/)"), ], help_text="The type of redirect you wish to use.", max_length=255, verbose_name="Redirect Type", ), ), migrations.AlterModelOptions( name="redirect", options={ "ordering": ("position", "-update_dt"), "verbose_name": "redirect", "verbose_name_plural": "redirects", }, ), ]
Migration
python
ApeWorX__ape
tests/functional/test_types.py
{ "start": 5408, "end": 7638 }
class ____: def test_use_for_int_in_pydantic_model(self): value = 100000000000000000000000000000000000000000000 class MyBasicModel(BaseModel): val: int model = MyBasicModel.model_validate({"val": CurrencyValueComparable(value)}) assert model.val == value # Ensure serializes. dumped = model.model_dump() assert dumped["val"] == value @pytest.mark.parametrize("mode", ("json", "python")) def test_use_in_model_annotation(self, mode): value = 100000000000000000000000000000000000000000000 class MyAnnotatedModel(BaseModel): val: CurrencyValueComparable val_optional: Optional[CurrencyValueComparable] model = MyAnnotatedModel.model_validate({"val": value, "val_optional": value}) assert isinstance(model.val, CurrencyValueComparable) assert model.val == value # Show can use currency-comparable expected_currency_value = "100000000000000000000000000 ETH" assert model.val == expected_currency_value assert model.val_optional == expected_currency_value # Ensure serializes. dumped = model.model_dump(mode=mode) assert dumped["val"] == value assert dumped["val_optional"] == value def test_validate_from_currency_value(self): class MyAnnotatedModel(BaseModel): val: CurrencyValueComparable val_optional: Optional[CurrencyValueComparable] val_in_dict: dict[str, Any] value = "100000000000000000000000000 ETH" expected = 100000000000000000000000000000000000000000000 data = { "val": value, "val_optional": value, "val_in_dict": {"value": CurrencyValueComparable(expected)}, } model = MyAnnotatedModel.model_validate(data) for actual in (model.val, model.val_optional, model.val_in_dict["value"]): for ex in (value, expected): assert actual == ex def test_hashable(self): mapping: dict[int, str] = {0: "0", 1: "1"} key = CurrencyValueComparable(0) assert key in mapping assert mapping[key] == "0"
TestCurrencyValueComparable
python
django__django
tests/file_storage/tests.py
{ "start": 40202, "end": 42761 }
class ____(SimpleTestCase): def setUp(self): self.temp_storage_location = tempfile.mkdtemp( suffix="filefield_callable_storage" ) self.addCleanup(shutil.rmtree, self.temp_storage_location) def test_callable_base_class_error_raises(self): class NotStorage: pass msg = ( "FileField.storage must be a subclass/instance of " "django.core.files.storage.base.Storage" ) for invalid_type in (NotStorage, str, list, set, tuple): with self.subTest(invalid_type=invalid_type): with self.assertRaisesMessage(TypeError, msg): FileField(storage=invalid_type) def test_file_field_storage_none_uses_default_storage(self): self.assertEqual(FileField().storage, default_storage) def test_callable_function_storage_file_field(self): storage = FileSystemStorage(location=self.temp_storage_location) def get_storage(): return storage obj = FileField(storage=get_storage) self.assertEqual(obj.storage, storage) self.assertEqual(obj.storage.location, storage.location) def test_callable_class_storage_file_field(self): class GetStorage(FileSystemStorage): pass obj = FileField(storage=GetStorage) self.assertIsInstance(obj.storage, BaseStorage) def test_callable_storage_file_field_in_model(self): obj = Storage() self.assertEqual(obj.storage_callable.storage, temp_storage) self.assertEqual(obj.storage_callable.storage.location, temp_storage_location) self.assertIsInstance(obj.storage_callable_class.storage, BaseStorage) def test_deconstruction(self): """ Deconstructing gives the original callable, not the evaluated value. """ obj = Storage() *_, kwargs = obj._meta.get_field("storage_callable").deconstruct() storage = kwargs["storage"] self.assertIs(storage, callable_storage) def test_deconstruction_storage_callable_default(self): """ A callable that returns default_storage is not omitted when deconstructing. """ obj = Storage() *_, kwargs = obj._meta.get_field("storage_callable_default").deconstruct() self.assertIs(kwargs["storage"], callable_default_storage) # Tests for a race condition on file saving (#4948). # This is written in such a way that it'll always pass on platforms # without threading.
FieldCallableFileStorageTests
python
huggingface__transformers
src/transformers/models/lfm2/modeling_lfm2.py
{ "start": 6935, "end": 15871 }
class ____: """ Attention and conv cache for Lfm2. It stores the Key and Value states as a list of tensors, one for each layer. Attention layer cache shape: `[batch_size, num_heads, seq_len, head_dim]`. Conv layer cache shape: `[batch_size, hidden_size, L_cache-1]`. """ # Override @property existing in Cache max_batch_size = None is_compileable = False key_cache = None value_cache = None def __init__( self, config: Lfm2Config, max_batch_size: int, dtype: torch.dtype = torch.float32, device: Union[torch.device, str, None] = None, ): self.key_cache = [] self.value_cache = [] self.max_batch_size = max_batch_size self.layer_types = config.layer_types self.first_attention_layer = self.layer_types.index("full_attention") self.conv_L_cache = config.conv_L_cache self._dtype = dtype self.conv_cache: list[torch.Tensor] = [] device = torch.device(device) if device is not None else None for _ in range(config.num_hidden_layers): conv_state = torch.zeros( self.max_batch_size, config.hidden_size, self.conv_L_cache, dtype=self._dtype, device=device, ) self.conv_cache.append(conv_state) self.key_cache.append(torch.tensor([])) self.value_cache.append(torch.tensor([])) def update( self, key_states: torch.Tensor, value_states: torch.Tensor, layer_idx: int, cache_kwargs: Optional[dict[str, Any]] = None, ) -> tuple[torch.Tensor, torch.Tensor]: """ Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`. Parameters: key_states (`torch.Tensor`): The new key states to cache. value_states (`torch.Tensor`): The new value states to cache. layer_idx (`int`): The index of the layer to cache the states for. cache_kwargs (`Dict[str, Any]`, `optional`): Additional arguments for the cache subclass. No additional arguments are used in `DynamicCache`. Return: A tuple containing the updated key and value states. """ # Update the cache if self.key_cache[layer_idx].numel() == 0: self.key_cache[layer_idx] = key_states self.value_cache[layer_idx] = value_states else: self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=-2) self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=-2) return self.key_cache[layer_idx], self.value_cache[layer_idx] def reorder_cache(self, beam_idx: torch.LongTensor): """Reorders the cache for beam search, given the selected beam indices.""" for layer_idx in range(len(self.key_cache)): if self.key_cache[layer_idx].numel(): device = self.key_cache[layer_idx].device self.key_cache[layer_idx] = self.key_cache[layer_idx].index_select(0, beam_idx.to(device)) device = self.value_cache[layer_idx].device self.value_cache[layer_idx] = self.value_cache[layer_idx].index_select(0, beam_idx.to(device)) if self.conv_cache[layer_idx].numel(): device = self.conv_cache[layer_idx].device self.conv_cache[layer_idx] = self.conv_cache[layer_idx].index_select(0, beam_idx.to(device)) def get_seq_length(self, layer_idx: Optional[int] = 0) -> int: """Returns the sequence length of the cached states. A layer index can be optionally passed.""" # take any layer that contains cache and not empty tensor layer_idx = self.first_attention_layer if self.layer_types[layer_idx] != "full_attention" else layer_idx if len(self.key_cache) <= layer_idx or self.key_cache[layer_idx].numel() == 0: return 0 return self.key_cache[layer_idx].shape[-2] def get_mask_sizes(self, cache_position: torch.Tensor, layer_idx: int) -> tuple[int, int]: """ Return a tuple (kv_length, kv_offset) corresponding to the length and offset that will be returned for the given layer at `layer_idx`. The masks are then prepared according to the given lengths (kv_length, kv_offset) and patterns (i.e. sliding_window, chunk_size), for each layer. """ full_mask_kv_offset = 0 query_length = cache_position.shape[0] past_seen_tokens = self.get_seq_length() kv_length = query_length + past_seen_tokens return kv_length, full_mask_kv_offset def crop(self, max_length: int): """Crop the cache to the given length""" if max_length < 0: max_length = self.get_seq_length() - abs(max_length) if self.get_seq_length() <= max_length: return for idx in range(len(self.key_cache)): if self.key_cache[idx].numel(): self.key_cache[idx] = self.key_cache[idx][..., :max_length, :] self.value_cache[idx] = self.value_cache[idx][..., :max_length, :] def __len__(self) -> int: return len(self.key_cache) def reset(self): for layer_idx in range(len(self.conv_cache)): # In-place ops prevent breaking the static address self.conv_cache[layer_idx].zero_() def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1) @use_kernel_func_from_hub("rotary_pos_emb") def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): """Applies Rotary Position Embedding to the query and key tensors. Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. position_ids (`torch.Tensor`, *optional*): Deprecated and unused. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ cos = cos.unsqueeze(unsqueeze_dim) sin = sin.unsqueeze(unsqueeze_dim) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) def eager_attention_forward( module: nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: Optional[torch.Tensor], scaling: float, dropout: float = 0.0, **kwargs: Unpack[TransformersKwargs], ): key_states = repeat_kv(key, module.num_key_value_groups) value_states = repeat_kv(value, module.num_key_value_groups) attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling if attention_mask is not None: causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] attn_weights = attn_weights + causal_mask attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) attn_output = torch.matmul(attn_weights, value_states) attn_output = attn_output.transpose(1, 2).contiguous() return attn_output, attn_weights
Lfm2HybridConvCache
python
pytorch__pytorch
benchmarks/tensorexpr/pooling.py
{ "start": 1478, "end": 1748 }
class ____(PoolingBench): def __init__(self, *args): super().__init__("avgpool", *args) @staticmethod def module(): return "avgpool" benchmark.register_benchmark_class(MaxPoolBench) benchmark.register_benchmark_class(AvgPoolBench)
AvgPoolBench
python
django__django
tests/multiple_database/models.py
{ "start": 658, "end": 1101 }
class ____(models.Model): name = models.CharField(max_length=100, unique=True) objects = PersonManager() class Meta: ordering = ("name",) def __str__(self): return self.name # This book manager doesn't do anything interesting; it just # exists to strip out the 'extra_arg' argument to certain # calls. This argument is used to establish that the BookManager # is actually getting used when it should be.
Person
python
getsentry__sentry
src/sentry/monitors/serializers.py
{ "start": 5042, "end": 5178 }
class ____(TypedDict): targets: list[MonitorAlertRuleTargetSerializerResponse] environment: str
MonitorAlertRuleSerializerResponse
python
getsentry__sentry
src/sentry/auth/services/auth/model.py
{ "start": 1465, "end": 1559 }
class ____(RpcModel): is_required: bool = False is_valid: bool = False
RpcMemberSsoState
python
pandas-dev__pandas
pandas/tests/indexing/interval/test_interval.py
{ "start": 229, "end": 5349 }
class ____: @pytest.fixture def series_with_interval_index(self): return Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6))) def test_getitem_with_scalar(self, series_with_interval_index, indexer_sl): ser = series_with_interval_index.copy() expected = ser.iloc[:3] tm.assert_series_equal(expected, indexer_sl(ser)[:3]) tm.assert_series_equal(expected, indexer_sl(ser)[:2.5]) tm.assert_series_equal(expected, indexer_sl(ser)[0.1:2.5]) if indexer_sl is tm.loc: tm.assert_series_equal(expected, ser.loc[-1:3]) expected = ser.iloc[1:4] tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 2.5, 3.5]]) tm.assert_series_equal(expected, indexer_sl(ser)[[2, 3, 4]]) tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 3, 4]]) expected = ser.iloc[2:5] tm.assert_series_equal(expected, indexer_sl(ser)[ser >= 2]) @pytest.mark.parametrize("direction", ["increasing", "decreasing"]) def test_getitem_nonoverlapping_monotonic(self, direction, closed, indexer_sl): tpls = [(0, 1), (2, 3), (4, 5)] if direction == "decreasing": tpls = tpls[::-1] idx = IntervalIndex.from_tuples(tpls, closed=closed) ser = Series(list("abc"), idx) for key, expected in zip(idx.left, ser): if idx.closed_left: assert indexer_sl(ser)[key] == expected else: with pytest.raises(KeyError, match=str(key)): indexer_sl(ser)[key] for key, expected in zip(idx.right, ser): if idx.closed_right: assert indexer_sl(ser)[key] == expected else: with pytest.raises(KeyError, match=str(key)): indexer_sl(ser)[key] for key, expected in zip(idx.mid, ser): assert indexer_sl(ser)[key] == expected def test_getitem_non_matching(self, series_with_interval_index, indexer_sl): ser = series_with_interval_index.copy() # this is a departure from our current # indexing scheme, but simpler with pytest.raises(KeyError, match=r"\[-1\] not in index"): indexer_sl(ser)[[-1, 3, 4, 5]] with pytest.raises(KeyError, match=r"\[-1\] not in index"): indexer_sl(ser)[[-1, 3]] def test_loc_getitem_large_series(self, monkeypatch): size_cutoff = 20 with monkeypatch.context(): monkeypatch.setattr(libindex, "_SIZE_CUTOFF", size_cutoff) ser = Series( np.arange(size_cutoff), index=IntervalIndex.from_breaks(np.arange(size_cutoff + 1)), ) result1 = ser.loc[:8] result2 = ser.loc[0:8] result3 = ser.loc[0:8:1] tm.assert_series_equal(result1, result2) tm.assert_series_equal(result1, result3) def test_loc_getitem_frame(self): # CategoricalIndex with IntervalIndex categories df = DataFrame({"A": range(10)}) ser = pd.cut(df.A, 5) df["B"] = ser df = df.set_index("B") result = df.loc[4] expected = df.iloc[4:6] tm.assert_frame_equal(result, expected) with pytest.raises(KeyError, match="10"): df.loc[10] # single list-like result = df.loc[[4]] expected = df.iloc[4:6] tm.assert_frame_equal(result, expected) # non-unique result = df.loc[[4, 5]] expected = df.take([4, 5, 4, 5]) tm.assert_frame_equal(result, expected) msg = ( r"None of \[Index\(\[10\], dtype='object', name='B'\)\] " r"are in the \[index\]" ) with pytest.raises(KeyError, match=msg): df.loc[[10]] # partial missing with pytest.raises(KeyError, match=r"\[10\] not in index"): df.loc[[10, 4]] def test_getitem_interval_with_nans(self, frame_or_series, indexer_sl): # GH#41831 index = IntervalIndex([np.nan, np.nan]) key = index[:-1] obj = frame_or_series(range(2), index=index) if frame_or_series is DataFrame and indexer_sl is tm.setitem: obj = obj.T result = indexer_sl(obj)[key] expected = obj tm.assert_equal(result, expected) def test_setitem_interval_with_slice(self): # GH#54722 ii = IntervalIndex.from_breaks(range(4, 15)) ser = Series(range(10), index=ii) orig = ser.copy() # This should be a no-op (used to raise) ser.loc[1:3] = 20 tm.assert_series_equal(ser, orig) ser.loc[6:8] = 19 orig.iloc[1:4] = 19 tm.assert_series_equal(ser, orig) ser2 = Series(range(5), index=ii[::2]) orig2 = ser2.copy() # this used to raise ser2.loc[6:8] = 22 # <- raises on main, sets on branch orig2.iloc[1] = 22 tm.assert_series_equal(ser2, orig2) ser2.loc[5:7] = 21 orig2.iloc[:2] = 21 tm.assert_series_equal(ser2, orig2)
TestIntervalIndex
python
spyder-ide__spyder
spyder/api/shellconnect/mixins.py
{ "start": 2163, "end": 2741 }
class ____: """ Mixin for widgets that will be added to the stacked widget part of ShellConnectMainWidget. """ sig_show_empty_message_requested = Signal(bool) """ Signal to request that the empty message will be shown/hidden. Parameters ---------- show_empty_message: bool Whether show the empty message or this widget must be shown. """ def __init__(self): # This attribute is necessary to track if this widget has content to # display or not. self.is_empty = True
ShellConnectWidgetForStackMixin
python
django__django
tests/model_fields/test_charfield.py
{ "start": 1398, "end": 1760 }
class ____(SimpleTestCase): def test_deconstruct(self): field = models.CharField() *_, kwargs = field.deconstruct() self.assertEqual(kwargs, {}) field = models.CharField(db_collation="utf8_esperanto_ci") *_, kwargs = field.deconstruct() self.assertEqual(kwargs, {"db_collation": "utf8_esperanto_ci"})
TestMethods
python
pytorch__pytorch
tools/experimental/torchfuzz/operators/tensor_pointwise.py
{ "start": 2712, "end": 2995 }
class ____(PointwiseOperator): """Operator for element-wise addition.""" def __init__(self, weight: float = 1.0): super().__init__("add", "+") self.weight = float(weight) @property def torch_op_name(self) -> str: return "torch.add"
AddOperator
python
ansible__ansible
test/lib/ansible_test/_internal/commands/integration/filters.py
{ "start": 5537, "end": 6396 }
class ____[TPosixConfig: PosixConfig](TargetFilter[TPosixConfig]): """Target filter for POSIX hosts.""" def filter_targets(self, targets: list[IntegrationTarget], exclude: set[str]) -> None: """Filter the list of targets, adding any which this host profile cannot support to the provided exclude list.""" super().filter_targets(targets, exclude) if not self.allow_root and not self.config.have_root: self.skip('needs/root', 'which require --allow-root or running as root', targets, exclude) self.skip(f'skip/python{self.config.python.version}', f'which are not supported by Python {self.config.python.version}', targets, exclude) self.skip(f'skip/python{self.config.python.major_version}', f'which are not supported by Python {self.config.python.major_version}', targets, exclude)
PosixTargetFilter
python
getsentry__sentry
tests/sentry/silo/test_silo_aware_transaction_patch.py
{ "start": 530, "end": 1051 }
class ____(TestCase): def test_correctly_accepts_using_for_atomic(self) -> None: transaction_in_test = siloed_atomic(using="foobar") assert transaction_in_test.using == "foobar" def test_accepts_cross_silo_atomics_in_monolith_mode(self) -> None: siloed_atomic(using=router.db_for_write(Organization)) siloed_atomic(using=router.db_for_write(OrganizationMapping)) @no_silo_test # use inline override_settings to test individual silo modes
TestSiloAwareTransactionPatchInSingleDbMode
python
pytest-dev__pluggy
src/pluggy/_tracing.py
{ "start": 1656, "end": 2006 }
class ____: def __init__(self, root: TagTracer, tags: tuple[str, ...]) -> None: self.root = root self.tags = tags def __call__(self, *args: object) -> None: self.root._processmessage(self.tags, args) def get(self, name: str) -> TagTracerSub: return self.__class__(self.root, self.tags + (name,))
TagTracerSub
python
facelessuser__pymdown-extensions
tests/test_extensions/test_superfences.py
{ "start": 14021, "end": 15075 }
class ____(util.MdCase): """Test highlight line wraps.""" extension = ['pymdownx.highlight', 'pymdownx.superfences'] extension_configs = { 'pymdownx.highlight': { 'anchor_linenums': True, 'linenums_style': 'table' } } def test_linespans(self): """Test wrapping a line in line spans.""" self.check_markdown( r''' ```python linenums="2" import test ``` ''', r''' <div class="highlight"><table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre><span></span><span class="normal"><a href="#__codelineno-0-2">2</a></span></pre></div></td><td class="code"><div><pre><span></span><code><a id="__codelineno-0-2" name="__codelineno-0-2"></a><span class="kn">import</span><span class="w"> </span><span class="nn">test</span> </code></pre></div></td></tr></table></div> ''', # noqa: E501 True )
TestHighlightAnchorLinenumsPymdownsTable
python
doocs__leetcode
solution/0900-0999/0946.Validate Stack Sequences/Solution.py
{ "start": 0, "end": 311 }
class ____: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: stk = [] i = 0 for x in pushed: stk.append(x) while stk and stk[-1] == popped[i]: stk.pop() i += 1 return i == len(popped)
Solution
python
cookiecutter__cookiecutter
tests/test_prompt.py
{ "start": 19695, "end": 28317 }
class ____: """Class to unite boolean prompt related tests.""" @pytest.mark.parametrize( 'run_as_docker', ( True, False, ), ) def test_should_invoke_read_user_yes_no(self, mocker, run_as_docker) -> None: """Verify correct function called for boolean variables.""" read_user_yes_no = mocker.patch('cookiecutter.prompt.read_user_yes_no') read_user_yes_no.return_value = run_as_docker read_user_variable = mocker.patch('cookiecutter.prompt.read_user_variable') context = {'cookiecutter': {'run_as_docker': run_as_docker}} cookiecutter_dict = prompt.prompt_for_config(context) assert not read_user_variable.called read_user_yes_no.assert_called_once_with( 'run_as_docker', run_as_docker, {}, DEFAULT_PREFIX ) assert cookiecutter_dict == {'run_as_docker': run_as_docker} def test_boolean_parameter_no_input(self) -> None: """Verify boolean parameter sent to prompt for config with no input.""" context = { 'cookiecutter': { 'run_as_docker': True, } } cookiecutter_dict = prompt.prompt_for_config(context, no_input=True) assert cookiecutter_dict == context['cookiecutter'] @pytest.mark.parametrize( 'context', ( {'cookiecutter': {'foo': '{{cookiecutter.nope}}'}}, {'cookiecutter': {'foo': ['123', '{{cookiecutter.nope}}', '456']}}, {'cookiecutter': {'foo': {'{{cookiecutter.nope}}': 'value'}}}, {'cookiecutter': {'foo': {'key': '{{cookiecutter.nope}}'}}}, ), ids=[ 'Undefined variable in cookiecutter dict', 'Undefined variable in cookiecutter dict with choices', 'Undefined variable in cookiecutter dict with dict_key', 'Undefined variable in cookiecutter dict with key_value', ], ) def test_undefined_variable(context) -> None: """Verify `prompt.prompt_for_config` raises correct error.""" with pytest.raises(exceptions.UndefinedVariableInTemplate) as err: prompt.prompt_for_config(context, no_input=True) error = err.value assert error.message == "Unable to render variable 'foo'" assert error.context == context @pytest.mark.parametrize( "template_dir,expected", [ ["fake-nested-templates", "fake-project"], ["fake-nested-templates-old-style", "fake-package"], ], ) def test_cookiecutter_nested_templates(template_dir: str, expected: Path | str) -> None: """Test nested_templates generation.""" from cookiecutter import prompt main_dir = (Path("tests") / template_dir).resolve() cookiecuter_context = json.loads((main_dir / "cookiecutter.json").read_text()) context = {"cookiecutter": cookiecuter_context} output_dir = prompt.choose_nested_template(context, main_dir, no_input=True) expected = (Path(main_dir) / expected).resolve() assert output_dir == f"{expected}" @pytest.mark.skipif(sys.platform.startswith('win'), reason="Linux / macos test") @pytest.mark.parametrize( "path", [ "", "/tmp", "/foo", ], ) def test_cookiecutter_nested_templates_invalid_paths(path: str) -> None: """Test nested_templates generation.""" from cookiecutter import prompt main_dir = (Path("tests") / "fake-nested-templates").resolve() cookiecuter_context = json.loads((main_dir / "cookiecutter.json").read_text()) cookiecuter_context["templates"]["fake-project"]["path"] = path context = {"cookiecutter": cookiecuter_context} with pytest.raises(ValueError) as exc: prompt.choose_nested_template(context, main_dir, no_input=True) assert "Illegal template path" in str(exc) @pytest.mark.skipif(not sys.platform.startswith('win'), reason="Win only test") @pytest.mark.parametrize( "path", [ "", "C:/tmp", "D:/tmp", ], ) def test_cookiecutter_nested_templates_invalid_win_paths(path: str) -> None: """Test nested_templates generation.""" from cookiecutter import prompt main_dir = (Path("tests") / "fake-nested-templates").resolve() cookiecuter_context = json.loads((main_dir / "cookiecutter.json").read_text()) cookiecuter_context["templates"]["fake-project"]["path"] = path context = {"cookiecutter": cookiecuter_context} with pytest.raises(ValueError) as exc: prompt.choose_nested_template(context, main_dir, no_input=True) assert "Illegal template path" in str(exc) def test_prompt_should_ask_and_rm_repo_dir(mocker, tmp_path) -> None: """In `prompt_and_delete()`, if the user agrees to delete/reclone the \ repo, the repo should be deleted.""" mock_read_user = mocker.patch( 'cookiecutter.prompt.read_user_yes_no', return_value=True ) repo_dir = Path(tmp_path, 'repo') repo_dir.mkdir() deleted = prompt.prompt_and_delete(str(repo_dir)) assert mock_read_user.called assert not repo_dir.exists() assert deleted def test_prompt_should_ask_and_exit_on_user_no_answer(mocker, tmp_path) -> None: """In `prompt_and_delete()`, if the user decline to delete/reclone the \ repo, cookiecutter should exit.""" mock_read_user = mocker.patch( 'cookiecutter.prompt.read_user_yes_no', return_value=False, ) mock_sys_exit = mocker.patch('sys.exit', return_value=True) repo_dir = Path(tmp_path, 'repo') repo_dir.mkdir() deleted = prompt.prompt_and_delete(str(repo_dir)) assert mock_read_user.called assert repo_dir.exists() assert not deleted assert mock_sys_exit.called def test_prompt_should_ask_and_rm_repo_file(mocker, tmp_path) -> None: """In `prompt_and_delete()`, if the user agrees to delete/reclone a \ repo file, the repo should be deleted.""" mock_read_user = mocker.patch( 'cookiecutter.prompt.read_user_yes_no', return_value=True, autospec=True ) repo_file = tmp_path.joinpath('repo.zip') repo_file.write_text('this is zipfile content') deleted = prompt.prompt_and_delete(str(repo_file)) assert mock_read_user.called assert not repo_file.exists() assert deleted def test_prompt_should_ask_and_keep_repo_on_no_reuse(mocker, tmp_path) -> None: """In `prompt_and_delete()`, if the user wants to keep their old \ cloned template repo, it should not be deleted.""" mock_read_user = mocker.patch( 'cookiecutter.prompt.read_user_yes_no', return_value=False, autospec=True ) repo_dir = Path(tmp_path, 'repo') repo_dir.mkdir() with pytest.raises(SystemExit): prompt.prompt_and_delete(str(repo_dir)) assert mock_read_user.called assert repo_dir.exists() def test_prompt_should_ask_and_keep_repo_on_reuse(mocker, tmp_path) -> None: """In `prompt_and_delete()`, if the user wants to keep their old \ cloned template repo, it should not be deleted.""" def answer(question, _default): return 'okay to delete' not in question mock_read_user = mocker.patch( 'cookiecutter.prompt.read_user_yes_no', side_effect=answer, autospec=True ) repo_dir = Path(tmp_path, 'repo') repo_dir.mkdir() deleted = prompt.prompt_and_delete(str(repo_dir)) assert mock_read_user.called assert repo_dir.exists() assert not deleted def test_prompt_should_not_ask_if_no_input_and_rm_repo_dir(mocker, tmp_path) -> None: """Prompt should not ask if no input and rm dir. In `prompt_and_delete()`, if `no_input` is True, the call to `prompt.read_user_yes_no()` should be suppressed. """ mock_read_user = mocker.patch( 'cookiecutter.prompt.read_user_yes_no', return_value=True, autospec=True ) repo_dir = Path(tmp_path, 'repo') repo_dir.mkdir() deleted = prompt.prompt_and_delete(str(repo_dir), no_input=True) assert not mock_read_user.called assert not repo_dir.exists() assert deleted def test_prompt_should_not_ask_if_no_input_and_rm_repo_file(mocker, tmp_path) -> None: """Prompt should not ask if no input and rm file. In `prompt_and_delete()`, if `no_input` is True, the call to `prompt.read_user_yes_no()` should be suppressed. """ mock_read_user = mocker.patch( 'cookiecutter.prompt.read_user_yes_no', return_value=True, autospec=True ) repo_file = tmp_path.joinpath('repo.zip') repo_file.write_text('this is zipfile content') deleted = prompt.prompt_and_delete(str(repo_file), no_input=True) assert not mock_read_user.called assert not repo_file.exists() assert deleted
TestReadUserYesNo
python
scipy__scipy
benchmarks/benchmarks/spatial.py
{ "start": 6435, "end": 8332 }
class ____(LimitedParamBenchmark): params = [ [(3,1000,1000), (8,1000,1000), (16,1000,1000)], [1, 2, np.inf], [0.2, 0.5], BOX_SIZES, LEAF_SIZES, ['cKDTree', 'cKDTree_weighted'], ] param_names = ['(m, n1, n2)', 'p', 'probe radius', 'boxsize', 'leafsize', 'cls'] num_param_combinations = 17 def setup(self, mn1n2, p, probe_radius, boxsize, leafsize, cls): LimitedParamBenchmark.setup(self, mn1n2, p, probe_radius, boxsize, leafsize, cls) m, n1, n2 = mn1n2 self.data1 = np.random.uniform(size=(n1, m)) self.data2 = np.random.uniform(size=(n2, m)) self.w1 = np.ones(n1) self.w2 = np.ones(n2) self.T1 = cKDTree(self.data1, boxsize=boxsize, leafsize=leafsize) self.T2 = cKDTree(self.data2, boxsize=boxsize, leafsize=leafsize) def time_sparse_distance_matrix(self, mn1n2, p, probe_radius, boxsize, leafsize, cls): self.T1.sparse_distance_matrix(self.T2, probe_radius, p=p) def time_count_neighbors(self, mn1n2, p, probe_radius, boxsize, leafsize, cls): """ Count neighbors kd-tree dim | # points T1 | # points T2 | p | probe radius | BoxSize | LeafSize | cls """ if cls != 'cKDTree_weighted': self.T1.count_neighbors(self.T2, probe_radius, p=p) else: self.T1.count_neighbors(self.T2, probe_radius, weights=(self.w1, self.w2), p=p) # Retain old benchmark results (remove this if changing the benchmark) time_sparse_distance_matrix.version = ( "9aa921dce6da78394ab29d949be27953484613dcf9c9632c01ae3973d4b29596" ) time_count_neighbors.version = ( "830287f1cf51fa6ba21854a60b03b2a6c70b2f2485c3cdcfb19a360e0a7e2ca2" )
Neighbors
python
pytorch__pytorch
test/torch_np/numpy_tests/linalg/test_linalg.py
{ "start": 57336, "end": 57411 }
class ____(_TestNorm, _TestNormSingleBase, TestCase): pass
TestNormSingle
python
django__django
tests/apps/query_performing_app/apps.py
{ "start": 1383, "end": 2036 }
class ____(BaseAppConfig): def _perform_query(self): from ..models import TotallyNormal connection = connections[self.database] table_meta = TotallyNormal._meta with connection.cursor() as cursor: cursor.executemany( "INSERT INTO %s (%s) VALUES(%%s)" % ( connection.introspection.identifier_converter(table_meta.db_table), connection.ops.quote_name(table_meta.get_field("name").column), ), [("test name 1",), ("test name 2",)], ) self.query_results = []
CursorQueryManyAppConfig
python
jmcnamara__XlsxWriter
xlsxwriter/test/vml/test_write_fill.py
{ "start": 289, "end": 1030 }
class ____(unittest.TestCase): """ Test the Vml _write_fill() method. """ def setUp(self): self.fh = StringIO() self.vml = Vml() self.vml._set_filehandle(self.fh) def test_write_comment_fill(self): """Test the _write_comment_fill() method""" self.vml._write_comment_fill() exp = """<v:fill color2="#ffffe1"/>""" got = self.fh.getvalue() self.assertEqual(exp, got) def test_write_button_fill(self): """Test the _write_button_fill() method""" self.vml._write_button_fill() exp = """<v:fill color2="buttonFace [67]" o:detectmouseclick="t"/>""" got = self.fh.getvalue() self.assertEqual(exp, got)
TestWriteVfill
python
sympy__sympy
doc/ext/convert-svg-to-pdf.py
{ "start": 433, "end": 3683 }
class ____(ImageConverter): conversion_rules = [ ('image/svg+xml', 'application/pdf'), ] def is_available(self) -> bool: """Confirms if converter is available or not.""" return True def chrome_command(self) -> str | None: if platform.win32_ver()[0]: if os.system("where chrome") == 0: return "chrome" path = os.path.join(os.environ["PROGRAMW6432"], "Google\\Chrome\\Application\\chrome.exe") if os.path.exists(path): return f'"{path}"' return None if os.system("chrome --version") == 0: return "chrome" if platform.mac_ver()[0]: return "'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'" elif platform.libc_ver()[0]: return "google-chrome" return None def chromium_command(self) -> str | None: if platform.win32_ver()[0]: if os.system("where chromium") == 0: return "chromium" path = os.path.join(os.environ["PROGRAMW6432"], "Chromium\\Application\\chrome.exe") if os.path.exists(path): return f'"{path}"' return None if os.system("chromium --version") == 0: return "chromium" if platform.mac_ver()[0]: path = "/Applications/Chromium.app/Contents/MacOS/Chromium" if os.path.exists(path): return path elif platform.libc_ver()[0]: if os.system("chromium-browser --version") == 0: return "chromium-browser" return None def command_runner(self, chrome: str | None, _to: str, temp_name: str) -> int: if not chrome: return 1 command = f'{chrome} --headless --disable-gpu --disable-software-rasterizer --print-to-pdf={_to} {temp_name}' logger.info(command) return os.system(command) def convert(self, _from: str, _to: str) -> bool: """Converts the image from SVG to PDF using chrome.""" svg = Path(_from).read_text() HTML = "<html><head><style>body {margin: 0; }</style><script>function init() {const element = document.querySelector('svg');const positionInfo = element.getBoundingClientRect();const height = positionInfo.height;const width = positionInfo.width;const style = document.createElement('style');style.innerHTML = `@page {margin: 0; size: ${width}px ${height}px}`;document.head.appendChild(style); }window.onload = init;</script></head><body>%s</body></html>" % (svg) temp_name = f'{_from}.html' Path(temp_name).write_text(HTML) chromium = self.chromium_command() code = self.command_runner(chromium, _to, temp_name) if code != 0: chrome = self.chrome_command() code = self.command_runner(chrome, _to, temp_name) if code != 0: logger.error('Fail to convert svg to pdf. Make sure Chromium or Chrome is installed.') exit(1) return True def setup(app: Sphinx) -> dict[str, Any]: app.add_post_transform(Converter) return { 'version': 'builtin', 'parallel_read_safe': True, 'parallel_write_safe': True, }
Converter
python
numpy__numpy
numpy/lib/tests/test_function_base.py
{ "start": 22782, "end": 23108 }
class ____: def test_basic(self): a = [3, 4, 5, 10, -3, -5, 6.0] assert_equal(np.amax(a), 10.0) b = [[3, 6.0, 9.0], [4, 10.0, 5.0], [8, 3.0, 2.0]] assert_equal(np.amax(b, axis=0), [8.0, 10.0, 9.0]) assert_equal(np.amax(b, axis=1), [9.0, 10.0, 8.0])
TestAmax
python
pytorch__pytorch
test/dynamo/test_sets.py
{ "start": 17018, "end": 21422 }
class ____(_FrozensetBase): # Set Methods # + add # + clear # - copy (inherited from frozenset) # - difference (inherited from frozenset) # + difference_update # + discard # - intersection (inherited from frozenset) # + intersection_update # - isdisjoint (inherited from frozenset) # - issubset (inherited from frozenset) # - issuperset (inherited from frozenset) # + pop # + remove # - symmetric_difference (inherited from frozenset) # + symmetric_difference_update # - union (inherited from frozenset) # + update @make_dynamo_test def test_add(self): p = self.thetype("abc") p.add("d") self.assertEqual(p, {"a", "b", "c", "d"}) p.add("a") self.assertEqual(p, {"a", "b", "c", "d"}) self.assertRaises(TypeError, p.add, ["ab"]) self.assertRaises(TypeError, p.add) set.add(p, "e") self.assertEqual(p, {"a", "b", "c", "d", "e"}) @make_dynamo_test def test_clear(self): p = self.thetype("abc") p.clear() self.assertEqual(p, set()) p = self.thetype("abc") self.thetype.clear(p) self.assertEqual(len(p), 0) @make_dynamo_test def test_remove(self): p = self.thetype("abc") self.assertEqual(p.remove("a"), None) self.assertEqual(p, {"b", "c"}) self.assertRaises(KeyError, p.remove, "a") p = self.thetype("abc") self.thetype.remove(p, "b") self.assertEqual(p, self.thetype({"a", "c"})) @make_dynamo_test def test_intersection_update(self): set1 = self.thetype({"apple", "banana", "cherry"}) set2 = self.thetype({"google", "microsoft", "apple"}) set3 = self.thetype({"shoes", "flipflops", "apple"}) self.assertIsNone(set1.intersection_update(set2, set3)) self.assertEqual(set1, {"apple"}) self.assertRaises(TypeError, set1.intersection_update, [[]]) p, q = map(self.thetype, ["abc", "bef"]) self.thetype.intersection_update(p, q) self.assertEqual(p, {"b"}) @make_dynamo_test def test_difference_update(self): set1 = self.thetype({"apple", "banana", "cherry"}) set2 = self.thetype({"google", "microsoft", "apple"}) set3 = self.thetype({"shoes", "flipflops", "sneakers"}) self.assertIsNone(set1.difference_update(set2, set3)) self.assertEqual(set1, {"banana", "cherry"}) self.assertRaises(TypeError, set1.difference_update, [[]]) p, q = map(self.thetype, ["abc", "bef"]) self.thetype.difference_update(p, q) self.assertEqual(p, {"a", "c"}) @make_dynamo_test def test_symmetric_difference_update(self): set1 = self.thetype({"apple", "banana", "cherry"}) set2 = self.thetype({"google", "microsoft", "apple"}) self.assertIsNone(set1.symmetric_difference_update(set2)) self.assertEqual(set1, {"banana", "cherry", "google", "microsoft"}) self.assertRaises(TypeError, set1.symmetric_difference_update) self.assertRaises(TypeError, set1.symmetric_difference_update, [[]]) p, q = map(self.thetype, ["abc", "bef"]) self.thetype.symmetric_difference_update(p, q) self.assertEqual(p, {"a", "c", "e", "f"}) @make_dynamo_test def test_pop(self): set1 = self.thetype({"apple", "banana", "cherry"}) e = set1.pop() self.assertNotIn(e, set1) s = self.thetype() self.assertRaises(KeyError, s.pop) p = self.thetype("a") self.assertEqual(self.thetype.pop(p), "a") @make_dynamo_test def test_update(self): p, q, r = map(self.thetype, ["abc", "bc", "bef"]) p.update(q, r) self.assertEqual(p, {"a", "b", "c", "e", "f"}) self.assertRaises(TypeError, p.update, [[]]) self.thetype.update(q, r) self.assertEqual(q, {"b", "c", "e", "f"}) @make_dynamo_test def test_discard(self): set1 = self.thetype({"apple", "banana", "cherry"}) set2 = self.thetype({"google", "microsoft", "apple"}) set1.discard("banana") set2.discard("cherry") self.assertEqual(set1, {"apple", "cherry"}) self.assertEqual(set2, {"google", "microsoft", "apple"}) p = self.thetype("abc") self.thetype.discard(p, "a") self.assertEqual(p, {"b", "c"})
_SetBase
python
psf__black
src/blib2to3/pygram.py
{ "start": 571, "end": 900 }
class ____: def __init__(self, grammar: Grammar) -> None: """Initializer. Creates an attribute for each grammar symbol (nonterminal), whose value is the symbol's type (an int >= 256). """ for name, symbol in grammar.symbol2number.items(): setattr(self, name, symbol)
Symbols
python
fastapi__sqlmodel
tests/test_enums_models.py
{ "start": 384, "end": 436 }
class ____(BaseModel, table=True): pass
InheritModel
python
django-import-export__django-import-export
import_export/formats/base_formats.py
{ "start": 3585, "end": 3692 }
class ____(TextFormat): TABLIB_MODULE = "tablib.formats._json" CONTENT_TYPE = "application/json"
JSON
python
kamyu104__LeetCode-Solutions
Python/different-ways-to-add-parentheses.py
{ "start": 465, "end": 1394 }
class ____(object): # @param {string} input # @return {integer[]} def diffWaysToCompute(self, input): tokens = re.split('(\D)', input) nums = map(int, tokens[::2]) ops = map({'+': operator.add, '-': operator.sub, '*': operator.mul}.get, tokens[1::2]) lookup = [[None for _ in xrange(len(nums))] for _ in xrange(len(nums))] def diffWaysToComputeRecu(left, right): if left == right: return [nums[left]] if lookup[left][right]: return lookup[left][right] lookup[left][right] = [ops[i](x, y) for i in xrange(left, right) for x in diffWaysToComputeRecu(left, i) for y in diffWaysToComputeRecu(i + 1, right)] return lookup[left][right] return diffWaysToComputeRecu(0, len(nums) - 1)
Solution
python
run-llama__llama_index
llama-index-core/llama_index/core/node_parser/file/markdown.py
{ "start": 462, "end": 5322 }
class ____(NodeParser): """ Markdown node parser. Splits a document into Nodes using Markdown header-based splitting logic. Each node contains its text content and the path of headers leading to it. Args: include_metadata (bool): whether to include metadata in nodes include_prev_next_rel (bool): whether to include prev/next relationships header_path_separator (str): separator char used for section header path metadata """ header_path_separator: str = Field( default="/", description="Separator char used for section header path metadata." ) @classmethod def from_defaults( cls, include_metadata: bool = True, include_prev_next_rel: bool = True, header_path_separator: str = "/", callback_manager: Optional[CallbackManager] = None, ) -> "MarkdownNodeParser": callback_manager = callback_manager or CallbackManager([]) return cls( include_metadata=include_metadata, include_prev_next_rel=include_prev_next_rel, header_path_separator=header_path_separator, callback_manager=callback_manager, ) def get_nodes_from_node(self, node: BaseNode) -> List[TextNode]: """Get nodes from document by splitting on headers.""" text = node.get_content(metadata_mode=MetadataMode.NONE) markdown_nodes = [] lines = text.split("\n") current_section = "" # Keep track of (markdown level, text) for headers header_stack: List[tuple[int, str]] = [] code_block = False for line in lines: # Track if we're inside a code block to avoid parsing headers in code if line.lstrip().startswith("```"): code_block = not code_block current_section += line + "\n" continue # Only parse headers if we're not in a code block if not code_block: header_match = re.match(r"^(#+)\s(.*)", line) if header_match: # Save the previous section before starting a new one if current_section.strip(): markdown_nodes.append( self._build_node_from_split( current_section.strip(), node, self.header_path_separator.join( h[1] for h in header_stack[:-1] ), ) ) header_level = len(header_match.group(1)) header_text = header_match.group(2) # Compare against top-of-stack item’s markdown level. # Pop headers of equal or higher markdown level; not necessarily current stack size / depth. # Hierarchy depth gets deeper one level at a time, but markdown headers can jump from H1 to H3, for example. while header_stack and header_stack[-1][0] >= header_level: header_stack.pop() # Add the new header header_stack.append((header_level, header_text)) current_section = "#" * header_level + f" {header_text}\n" continue current_section += line + "\n" # Add the final section if current_section.strip(): markdown_nodes.append( self._build_node_from_split( current_section.strip(), node, self.header_path_separator.join(h[1] for h in header_stack[:-1]), ) ) return markdown_nodes def _build_node_from_split( self, text_split: str, node: BaseNode, header_path: str, ) -> TextNode: """Build node from single text split.""" node = build_nodes_from_splits([text_split], node, id_func=self.id_func)[0] if self.include_metadata: separator = self.header_path_separator node.metadata["header_path"] = ( # ex: "/header1/header2/" || "/" separator + header_path + separator if header_path else separator ) return node def _parse_nodes( self, nodes: Sequence[BaseNode], show_progress: bool = False, **kwargs: Any, ) -> List[BaseNode]: """Parse nodes.""" all_nodes: List[BaseNode] = [] nodes_with_progress = get_tqdm_iterable(nodes, show_progress, "Parsing nodes") for node in nodes_with_progress: nodes = self.get_nodes_from_node(node) all_nodes.extend(nodes) return all_nodes
MarkdownNodeParser
python
ray-project__ray
rllib/utils/tests/test_torch_utils.py
{ "start": 243, "end": 6445 }
class ____(unittest.TestCase): @classmethod def setUpClass(cls) -> None: ray.init() @classmethod def tearDownClass(cls) -> None: ray.shutdown() def test_convert_to_torch_tensor(self): # Tests whether convert_to_torch_tensor works as expected # Test None self.assertTrue(convert_to_torch_tensor(None) is None) # Test single array array = np.array([1, 2, 3]) tensor = torch.from_numpy(array) self.assertTrue(all(convert_to_torch_tensor(array) == tensor)) # Test torch tensor self.assertTrue(convert_to_torch_tensor(tensor) is tensor) # Test conversion to 32-bit float tensor_2 = torch.tensor([1.0, 2.0, 3.0], dtype=torch.float64) self.assertTrue(convert_to_torch_tensor(tensor_2).dtype is torch.float32) # Test nested structure with objects tested above converted = convert_to_torch_tensor( {"a": (array, tensor), "b": tensor_2, "c": None} ) self.assertTrue(all(convert_to_torch_tensor(converted["a"][0]) == tensor)) self.assertTrue(converted["a"][1] is tensor) self.assertTrue(converted["b"].dtype is torch.float32) self.assertTrue(converted["c"] is None) def test_copy_torch_tensors(self): array = np.array([1, 2, 3], dtype=np.float32) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") tensor = torch.from_numpy(array).to(device) tensor_2 = torch.tensor([1.0, 2.0, 3.0], dtype=torch.float64).to(device) # Test single tensor copied_tensor = copy_torch_tensors(tensor, device) self.assertTrue(copied_tensor.device == device) self.assertNotEqual(id(copied_tensor), id(tensor)) self.assertTrue(all(copied_tensor == tensor)) # check that dtypes aren't modified copied_tensor_2 = copy_torch_tensors(tensor_2, device) self.assertTrue(copied_tensor_2.dtype == tensor_2.dtype) self.assertFalse(copied_tensor_2.dtype == torch.float32) # Test nested structure can be converted nested_structure = {"a": tensor, "b": tensor_2, "c": 1} copied_nested_structure = copy_torch_tensors(nested_structure, device) self.assertTrue(copied_nested_structure["a"].device == device) self.assertTrue(copied_nested_structure["b"].device == device) self.assertTrue(copied_nested_structure["c"] == 1) self.assertNotEqual(id(copied_nested_structure["a"]), id(tensor)) self.assertNotEqual(id(copied_nested_structure["b"]), id(tensor_2)) self.assertTrue(all(copied_nested_structure["a"] == tensor)) self.assertTrue(all(copied_nested_structure["b"] == tensor_2)) # if gpu is available test moving tensor from cpu to gpu and vice versa if torch.cuda.is_available(): tensor = torch.from_numpy(array).to("cpu") copied_tensor = copy_torch_tensors(tensor, "cuda:0") self.assertFalse(copied_tensor.device == torch.device("cpu")) self.assertTrue(copied_tensor.device == torch.device("cuda:0")) self.assertNotEqual(id(copied_tensor), id(tensor)) self.assertTrue( all(copied_tensor.detach().cpu().numpy() == tensor.detach().numpy()) ) tensor = torch.from_numpy(array).to("cuda:0") copied_tensor = copy_torch_tensors(tensor, "cpu") self.assertFalse(copied_tensor.device == torch.device("cuda:0")) self.assertTrue(copied_tensor.device == torch.device("cpu")) self.assertNotEqual(id(copied_tensor), id(tensor)) self.assertTrue( all(copied_tensor.detach().numpy() == tensor.detach().cpu().numpy()) ) def test_large_gradients_clipping(self): large_gradients = { f"gradient_{i}": torch.full((256, 256), 1e22) for i in range(20) } total_norm = clip_gradients( large_gradients, grad_clip=40, grad_clip_by="global_norm" ) self.assertFalse(total_norm.isinf()) print(f"total norm for large gradients: {total_norm}") small_gradients = { f"gradient_{i}": torch.full((256, 256), 1e-22) for i in range(20) } total_norm = clip_gradients( small_gradients, grad_clip=40, grad_clip_by="global_norm" ) self.assertFalse(total_norm.isneginf()) print(f"total norm for small gradients: {total_norm}") def test_two_hot(self): # Test value that's exactly on one of the bucket boundaries. This used to return # a two-hot vector with a NaN in it, as k == kp1 at that boundary. check( two_hot(torch.tensor([0.0]), 10, -5.0, 5.0), np.array([[0, 0, 0, 0, 0.5, 0.5, 0, 0, 0, 0]]), ) # Test violating the boundaries (upper and lower). upper_bound = np.zeros((255,)) upper_bound[-1] = 1.0 lower_bound = np.zeros((255,)) lower_bound[0] = 1.0 check( two_hot(torch.tensor([20.1, 50.0, 150.0, -20.00001])), np.array([upper_bound, upper_bound, upper_bound, lower_bound]), ) # Test other cases. check( two_hot(torch.tensor([2.5]), 11, -5.0, 5.0), np.array([[0, 0, 0, 0, 0, 0, 0, 0.5, 0.5, 0, 0]]), ) check( two_hot(torch.tensor([2.5, 0.1]), 10, -5.0, 5.0), np.array( [ [0, 0, 0, 0, 0, 0, 0.25, 0.75, 0, 0], [0, 0, 0, 0, 0.41, 0.59, 0, 0, 0, 0], ] ), ) check( two_hot(torch.tensor([0.1]), 4, -1.0, 1.0), np.array([[0, 0.35, 0.65, 0]]), ) check( two_hot(torch.tensor([-0.5, -1.2]), 9, -6.0, 3.0), np.array( [ [0, 0, 0, 0, 0.11111, 0.88889, 0, 0, 0], [0, 0, 0, 0, 0.73333, 0.26667, 0, 0, 0], ] ), ) if __name__ == "__main__": import sys import pytest sys.exit(pytest.main(["-v", __file__]))
TestTorchUtils
python
PyCQA__pylint
tests/functional/i/invalid/invalid_enum_extension.py
{ "start": 1014, "end": 1085 }
class ____(IntFlag): SUPPORT_OPEN = 1 SUPPORT_CLOSE = 2
CustomFlags
python
walkccc__LeetCode
solutions/3517. Smallest Palindromic Rearrangement I/3517.py
{ "start": 0, "end": 235 }
class ____: def smallestPalindrome(self, s: str) -> str: n = len(s) sortedHalf = sorted(s[:n // 2]) return ''.join(sortedHalf + ([s[n // 2]] if n % 2 else []) + sortedHalf[::-1])
Solution
python
django__django
tests/admin_inlines/models.py
{ "start": 8895, "end": 8961 }
class ____(Course): class Meta: proxy = True
CourseProxy
python
pandas-dev__pandas
pandas/tests/test_take.py
{ "start": 9542, "end": 11908 }
class ____: # The take method found in pd.api.extensions def test_bounds_check_large(self): arr = np.array([1, 2]) msg = "indices are out-of-bounds" with pytest.raises(IndexError, match=msg): algos.take(arr, [2, 3], allow_fill=True) msg = "index 2 is out of bounds for( axis 0 with)? size 2" with pytest.raises(IndexError, match=msg): algos.take(arr, [2, 3], allow_fill=False) def test_bounds_check_small(self): arr = np.array([1, 2, 3], dtype=np.int64) indexer = [0, -1, -2] msg = r"'indices' contains values less than allowed \(-2 < -1\)" with pytest.raises(ValueError, match=msg): algos.take(arr, indexer, allow_fill=True) result = algos.take(arr, indexer) expected = np.array([1, 3, 2], dtype=np.int64) tm.assert_numpy_array_equal(result, expected) @pytest.mark.parametrize("allow_fill", [True, False]) def test_take_empty(self, allow_fill): arr = np.array([], dtype=np.int64) # empty take is ok result = algos.take(arr, [], allow_fill=allow_fill) tm.assert_numpy_array_equal(arr, result) msg = "|".join( [ "cannot do a non-empty take from an empty axes.", "indices are out-of-bounds", ] ) with pytest.raises(IndexError, match=msg): algos.take(arr, [0], allow_fill=allow_fill) def test_take_na_empty(self): result = algos.take(np.array([]), [-1, -1], allow_fill=True, fill_value=0.0) expected = np.array([0.0, 0.0]) tm.assert_numpy_array_equal(result, expected) def test_take_coerces_list(self): # GH#52981 coercing is deprecated, disabled in 3.0 arr = [1, 2, 3] msg = ( "pd.api.extensions.take requires a numpy.ndarray, ExtensionArray, " "Index, Series, or NumpyExtensionArray got list" ) with pytest.raises(TypeError, match=msg): algos.take(arr, [0, 0]) def test_take_NumpyExtensionArray(self): # GH#59177 arr = array([1 + 1j, 2, 3]) # NumpyEADtype('complex128') (NumpyExtensionArray) assert algos.take(arr, [2]) == 2 arr = array([1, 2, 3]) # Int64Dtype() (ExtensionArray) assert algos.take(arr, [2]) == 2
TestExtensionTake
python
spack__spack
lib/spack/spack/vendor/archspec/cpu/alias.py
{ "start": 384, "end": 2562 }
class ____: """A test that must be passed for a feature alias to succeed. Args: rules (dict): dictionary of rules to be met. Each key must be a valid alias predicate """ # pylint: disable=too-few-public-methods def __init__(self, rules): self.rules = rules self.predicates = [] for name, args in rules.items(): self.predicates.append(_FEATURE_ALIAS_PREDICATE[name](args)) def __call__(self, microarchitecture): return all(feature_test(microarchitecture) for feature_test in self.predicates) def _feature_aliases(): """Returns the dictionary of all defined feature aliases.""" json_data = TARGETS_JSON["feature_aliases"] aliases = {} for alias, rules in json_data.items(): aliases[alias] = FeatureAliasTest(rules) return aliases FEATURE_ALIASES = LazyDictionary(_feature_aliases) def alias_predicate(func): """Decorator to register a predicate that can be used to evaluate feature aliases. """ name = func.__name__ # Check we didn't register anything else with the same name if name in _FEATURE_ALIAS_PREDICATE: msg = f'the alias predicate "{name}" already exists' raise KeyError(msg) _FEATURE_ALIAS_PREDICATE[name] = func return func @alias_predicate def reason(_): """This predicate returns always True and it's there to allow writing a documentation string in the JSON file to explain why an alias is needed. """ return lambda x: True @alias_predicate def any_of(list_of_features): """Returns a predicate that is True if any of the feature in the list is in the microarchitecture being tested, False otherwise. """ def _impl(microarchitecture): return any(x in microarchitecture for x in list_of_features) return _impl @alias_predicate def families(list_of_families): """Returns a predicate that is True if the architecture family of the microarchitecture being tested is in the list, False otherwise. """ def _impl(microarchitecture): return str(microarchitecture.family) in list_of_families return _impl
FeatureAliasTest
python
getsentry__sentry
src/sentry/explore/endpoints/bases.py
{ "start": 171, "end": 1402 }
class ____(OrganizationPermission): # Relaxed permissions for saved queries in Explore scope_map = { "GET": ["org:read", "org:write", "org:admin"], "POST": ["org:read", "org:write", "org:admin"], "PUT": ["org:read", "org:write", "org:admin"], "DELETE": ["org:read", "org:write", "org:admin"], } def has_object_permission(self, request, view, obj): if isinstance(obj, Organization): return super().has_object_permission(request, view, obj) if isinstance(obj, ExploreSavedQuery): # 1. Saved Query contains certain projects if obj.projects.exists(): return request.access.has_projects_access(obj.projects.all()) # 2. Saved Query covers all projects or all my projects # allow when Open Membership if obj.organization.flags.allow_joinleave: return True # allow for Managers and Owners if request.access.has_scope("org:write"): return True # allow for creator if request.user.id == obj.created_by_id: return True return False return True
ExploreSavedQueryPermission
python
django__django
tests/admin_views/admin.py
{ "start": 29522, "end": 29609 }
class ____(admin.ModelAdmin): list_display = ("name", "content_object")
FunkyTagAdmin
python
huggingface__transformers
tests/models/t5gemma/test_modeling_t5gemma.py
{ "start": 67767, "end": 69149 }
class ____(unittest.TestCase): def build_model_and_check_forward_pass(self, **kwargs): tester = T5GemmaModelTester(self, **kwargs) config, *inputs = tester.prepare_config_and_inputs() ( input_ids, decoder_input_ids, attention_mask, decoder_attention_mask, lm_labels, ) = inputs model = T5GemmaForConditionalGeneration(config=config).to(torch_device).eval() outputs = model( input_ids=input_ids, decoder_input_ids=decoder_input_ids, decoder_attention_mask=decoder_attention_mask, labels=lm_labels, ) # outputs = model(*inputs) assert len(outputs) == 5 assert outputs["logits"].size() == (tester.batch_size, tester.seq_length, tester.vocab_size) assert outputs["loss"].size() == () return model.model def test_small_decoder(self): model = self.build_model_and_check_forward_pass(num_hidden_layers=1, encoder_num_hidden_layers=2) assert len(model.encoder.layers) == 2 assert len(model.decoder.layers) == 1 def test_defaulting_to_symmetry(self): model = self.build_model_and_check_forward_pass(num_hidden_layers=2, encoder_num_hidden_layers=2) assert len(model.decoder.layers) == len(model.encoder.layers) == 2
TestAsymmetricT5Gemma
python
cython__cython
tests/run/pep557_dataclasses.py
{ "start": 1229, "end": 1533 }
class ____: """ >>> IceCream("vanilla") IceCream(flavour='vanilla', num_toppings=2) >>> IceCream("vanilla") == IceCream("vanilla", num_toppings=3) False >>> IceCream("vanilla") == IceCream("vanilla", num_toppings=2) True """ flavour: str num_toppings: int = 2
IceCream
python
pytorch__pytorch
test/distributed/checkpoint/test_hsdp_checkpoint.py
{ "start": 1075, "end": 1532 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.net1 = nn.Linear(5, 8) self.relu = nn.ReLU() self.net2 = nn.Linear(8, 4) self.net3 = nn.Linear(4, 12) def forward(self, x): x = F.relu(self.net1(x)) x = F.relu(self.net2(x)) x = F.relu(self.net3(x)) return x def get_input(self): return torch.rand(4, 5, device=device_type)
SimpleModel
python
Textualize__rich
rich/palette.py
{ "start": 199, "end": 3286 }
class ____: """A palette of available colors.""" def __init__(self, colors: Sequence[Tuple[int, int, int]]): self._colors = colors def __getitem__(self, number: int) -> ColorTriplet: return ColorTriplet(*self._colors[number]) def __rich__(self) -> "Table": from rich.color import Color from rich.style import Style from rich.text import Text from rich.table import Table table = Table( "index", "RGB", "Color", title="Palette", caption=f"{len(self._colors)} colors", highlight=True, caption_justify="right", ) for index, color in enumerate(self._colors): table.add_row( str(index), repr(color), Text(" " * 16, style=Style(bgcolor=Color.from_rgb(*color))), ) return table # This is somewhat inefficient and needs caching @lru_cache(maxsize=1024) def match(self, color: Tuple[int, int, int]) -> int: """Find a color from a palette that most closely matches a given color. Args: color (Tuple[int, int, int]): RGB components in range 0 > 255. Returns: int: Index of closes matching color. """ red1, green1, blue1 = color _sqrt = sqrt get_color = self._colors.__getitem__ def get_color_distance(index: int) -> float: """Get the distance to a color.""" red2, green2, blue2 = get_color(index) red_mean = (red1 + red2) // 2 red = red1 - red2 green = green1 - green2 blue = blue1 - blue2 return _sqrt( (((512 + red_mean) * red * red) >> 8) + 4 * green * green + (((767 - red_mean) * blue * blue) >> 8) ) min_index = min(range(len(self._colors)), key=get_color_distance) return min_index if __name__ == "__main__": # pragma: no cover import colorsys from typing import Iterable from rich.color import Color from rich.console import Console, ConsoleOptions from rich.segment import Segment from rich.style import Style class ColorBox: def __rich_console__( self, console: Console, options: ConsoleOptions ) -> Iterable[Segment]: height = console.size.height - 3 for y in range(0, height): for x in range(options.max_width): h = x / options.max_width l = y / (height + 1) r1, g1, b1 = colorsys.hls_to_rgb(h, l, 1.0) r2, g2, b2 = colorsys.hls_to_rgb(h, l + (1 / height / 2), 1.0) bgcolor = Color.from_rgb(r1 * 255, g1 * 255, b1 * 255) color = Color.from_rgb(r2 * 255, g2 * 255, b2 * 255) yield Segment("▄", Style(color=color, bgcolor=bgcolor)) yield Segment.line() console = Console() console.print(ColorBox())
Palette
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/waiters/test_bedrock_agent.py
{ "start": 1324, "end": 1558 }
class ____: @pytest.fixture(autouse=True) def mock_conn(self, monkeypatch): self.client = boto3.client("bedrock-agent") monkeypatch.setattr(BedrockAgentHook, "conn", self.client)
TestBedrockAgentCustomWaitersBase
python
doocs__leetcode
solution/1000-1099/1006.Clumsy Factorial/Solution.py
{ "start": 0, "end": 416 }
class ____: def clumsy(self, n: int) -> int: k = 0 stk = [n] for x in range(n - 1, 0, -1): if k == 0: stk.append(stk.pop() * x) elif k == 1: stk.append(int(stk.pop() / x)) elif k == 2: stk.append(x) else: stk.append(-x) k = (k + 1) % 4 return sum(stk)
Solution
python
ray-project__ray
python/ray/experimental/channel/common.py
{ "start": 1807, "end": 3918 }
class ____: def register_custom_serializer(self) -> None: """ Register any custom serializers needed to pass data of this type. This method should be run on the reader(s) and writer of a channel, which are the driver and/or Ray actors. NOTE: When custom serializers are registered with Ray, the registered deserializer is shipped with the serialized value and used on the receiving end. Therefore, the deserializer function should *not* capture state that is meant to be worker-local, such as the worker's default device. Instead, these should be extracted from the worker-local _SerializationContext. """ pass def create_channel( self, writer: Optional["ray.actor.ActorHandle"], reader_and_node_list: List[Tuple["ray.actor.ActorHandle", str]], driver_actor_id: Optional[str] = None, ) -> "ChannelInterface": """ Instantiate a ChannelInterface class that can be used to pass data of this type. Args: writer: The actor that may write to the channel. None signifies the driver. reader_and_node_list: A list of tuples, where each tuple contains a reader actor handle and the node ID where the actor is located. driver_actor_id: If this is a CompositeChannel that is read by a driver and that driver is an actual actor, this will be the actor ID of that driver actor. Returns: A ChannelInterface that can be used to pass data of this type. """ raise NotImplementedError def requires_accelerator(self) -> bool: # By default, channels do not require accelerator. return False def get_custom_communicator(self) -> Optional[Communicator]: """ Return the custom communicator group if one is specified. """ return None def set_communicator_id(self, group_id: str) -> None: raise NotImplementedError @DeveloperAPI @dataclass
ChannelOutputType
python
huggingface__transformers
src/transformers/models/sam3_tracker_video/modeling_sam3_tracker_video.py
{ "start": 25082, "end": 27987 }
class ____(ModelOutput): r""" iou_scores (`torch.FloatTensor` of shape `(batch_size, point_batch_size, num_masks)`): The Intersection over Union (IoU) scores of the predicted masks. pred_masks (`torch.FloatTensor` of shape `(batch_size, point_batch_size, num_masks, height, width)`): The predicted low-resolution masks. This is an alias for `low_res_masks`. These masks need to be post-processed by the processor to be brought to the original image size. object_score_logits (`torch.FloatTensor` of shape `(batch_size, point_batch_size, 1)`): Logits for the object score, indicating if an object is present. image_embeddings (`tuple(torch.FloatTensor)`): The features from the FPN, which are used by the mask decoder. This is a tuple of `torch.FloatTensor` where each tensor has shape `(batch_size, channels, height, width)`. vision_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of each stage) of shape `(batch_size, height, width, hidden_size)`. Hidden-states of the vision model at the output of each stage. vision_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the vision model. mask_decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the mask decoder. high_res_masks (`torch.FloatTensor` of shape `(batch_size, point_batch_size, num_masks, image_size, image_size)`, *optional*): The predicted masks, upscaled to the original image size. Only used for Sam3TrackerVideoModel. object_pointer (`torch.FloatTensor` of shape `(batch_size, point_batch_size, hidden_size)`, *optional*): A tensor representing the object pointer, used for tracking in videos. Only used for Sam3TrackerVideoModel. """ iou_scores: Optional[torch.FloatTensor] = None pred_masks: Optional[torch.FloatTensor] = None object_score_logits: Optional[torch.FloatTensor] = None image_embeddings: tuple[torch.FloatTensor, ...] = None vision_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None vision_attentions: Optional[tuple[torch.FloatTensor, ...]] = None mask_decoder_attentions: Optional[tuple[torch.FloatTensor, ...]] = None high_res_masks: Optional[torch.FloatTensor] = None object_pointer: Optional[torch.FloatTensor] = None @dataclass @auto_docstring(custom_intro="Base class for the Sam2 model's output.")
Sam3TrackerVideoImageSegmentationOutput
python
apache__airflow
providers/microsoft/azure/tests/unit/microsoft/azure/operators/test_powerbi_list.py
{ "start": 2229, "end": 5136 }
class ____: @mock.patch.object(BaseHook, "get_connection", side_effect=get_airflow_connection) def test_powerbi_operator_async_get_dataset_list_success(self, connection): """Assert that get_dataset_list log success message""" operator = PowerBIDatasetListOperator( **CONFIG_DATASETS, ) context = {"ti": MagicMock()} context["ti"].task_id = TASK_ID with pytest.raises(TaskDeferred) as exc: operator.execute( context=context, ) assert isinstance(exc.value.trigger, PowerBIDatasetListTrigger) assert exc.value.trigger.dataset_ids is None assert str(exc.value.trigger.group_id) == GROUP_ID def test_powerbi_operator_async_execute_complete_success(self): """Assert that execute_complete log success message""" operator = PowerBIDatasetListOperator( **CONFIG_DATASETS, ) context = {"ti": MagicMock()} operator.execute_complete( context=context, event=SUCCESS_LIST_EVENT_DATASETS, ) assert context["ti"].xcom_push.call_count == 1 def test_powerbi_operator_async_execute_complete_fail(self): """Assert that execute_complete raise exception on error""" operator = PowerBIDatasetListOperator( **CONFIG_DATASETS, ) context = {"ti": MagicMock()} with pytest.raises(AirflowException) as exc: operator.execute_complete( context=context, event={ "status": "error", "message": "error", "dataset_ids": None, }, ) assert context["ti"].xcom_push.call_count == 1 assert str(exc.value) == "error" def test_powerbi_operator_dataset_list_fail(self): """Assert that execute_complete raise exception on dataset list fail""" operator = PowerBIDatasetListOperator( **CONFIG_DATASETS, ) context = {"ti": MagicMock()} with pytest.raises(AirflowException) as exc: operator.execute_complete( context=context, event={ "status": "error", "message": "error message", "dataset_ids": None, }, ) assert context["ti"].xcom_push.call_count == 1 assert str(exc.value) == "error message" def test_execute_complete_no_event(self): """Test execute_complete when event is None or empty.""" operator = PowerBIDatasetListOperator( **CONFIG_DATASETS, ) context = {"ti": MagicMock()} operator.execute_complete( context=context, event=None, ) assert context["ti"].xcom_push.call_count == 0
TestPowerBIDatasetListOperator