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
pytorch__pytorch
test/quantization/eager/test_quantize_eager_qat.py
{ "start": 28859, "end": 48212 }
class ____(QuantizationTestCase): def _test_activation_convert_numerics_impl(self, Act, data): class M(torch.nn.Module): def __init__(self) -> None: super().__init__() self.act = Act() self.quant = QuantStub() self.dequant = DeQuantStub() def forward(self, x): x = self.quant(x) x = self.act(x) x = self.dequant(x) return x m = M().train() m.qconfig = default_qat_qconfig m = prepare_qat(m) before_convert = m(data) m = convert(m) after_convert = m(data) self.assertEqual(before_convert, after_convert) def test_fixed_qparam_ops(self): class M(torch.nn.Module): def __init__(self) -> None: super().__init__() self.sigmoid = torch.nn.Sigmoid() self.hardsigmoid = torch.nn.Hardsigmoid() self.tanh = torch.nn.Tanh() self.quant = QuantStub() self.dequant = DeQuantStub() def forward(self, x): x = self.quant(x) x = self.sigmoid(x) x = self.hardsigmoid(x) x = self.tanh(x) x = self.dequant(x) return x m = M().train() m.qconfig = default_qat_qconfig m = prepare_qat(m) for attr in ["sigmoid", "hardsigmoid", "tanh"]: self.assertEqual( type(getattr(m, attr).activation_post_process), FixedQParamsFakeQuantize ) data = torch.randn(1, 3, 2, 4) before_convert = m(data) m = convert(m) after_convert = m(data) self.assertEqual(before_convert, after_convert) # make sure activation post process is removed for attr in ["sigmoid", "hardsigmoid", "tanh"]: # verify fake quant module is removd self.assertFalse(hasattr(getattr(m, attr), "activation_post_process")) # verify that hooks are removed self.assertTrue(len(getattr(m, attr)._forward_hooks.items()) == 0) # make sure no fake quantize module is inserted for eval mode def checkNoFQModule(m): for attr in ["sigmoid", "hardsigmoid", "tanh"]: self.assertFalse(hasattr(getattr(m, attr), "activation_post_process")) self.assertTrue(len(getattr(m, attr)._forward_hooks.items()) == 0) m = M().eval() m.qconfig = default_qconfig m = prepare(m) checkNoFQModule(m) m = convert(m) checkNoFQModule(m) def test_leaky_relu(self): data = torch.randn(1, 3, 2, 4) self._test_activation_convert_numerics_impl(nn.LeakyReLU, data) def test_relu(self): class M(torch.nn.Module): def __init__(self) -> None: super().__init__() self.relu = nn.ReLU() def forward(self, x): x = self.relu(x) return x m = M().train() m.qconfig = default_qconfig m = prepare_qat(m) # make sure no activation_post_process is inserted for relu self.assertFalse(hasattr(m, "activation_post_process")) m = convert(m) # make sure ReLU module is not changed self.assertTrue(type(m.relu), nn.ReLU) @given( batch_size=st.integers(2, 4), input_channels_per_group=st.sampled_from([2, 3, 4]), height=st.integers(5, 10), width=st.integers(5, 10), output_channels_per_group=st.sampled_from([2, 3]), groups=st.integers(1, 3), kernel_h=st.integers(1, 3), kernel_w=st.integers(1, 3), stride_h=st.integers(1, 2), stride_w=st.integers(1, 2), pad_h=st.integers(0, 2), pad_w=st.integers(0, 2), dilation=st.integers(1, 1), padding_mode=st.sampled_from(["zeros", "circular"]), use_relu=st.booleans(), eps=st.sampled_from([1e-5, 1e-4, 1e-3]), momentum=st.sampled_from([0.1, 0.2, 0.3]), freeze_bn=st.booleans(), zero_gamma=st.booleans(), has_bias=st.booleans(), use_slow_fusion=st.booleans(), ) def test_conv_bn_relu( self, batch_size, input_channels_per_group, height, width, output_channels_per_group, groups, kernel_h, kernel_w, stride_h, stride_w, pad_h, pad_w, dilation, padding_mode, use_relu, eps, momentum, freeze_bn, zero_gamma, has_bias, use_slow_fusion, ): input_channels = input_channels_per_group * groups output_channels = output_channels_per_group * groups dilation_h = dilation_w = dilation conv_op = Conv2d( input_channels, output_channels, (kernel_h, kernel_w), (stride_h, stride_w), (pad_h, pad_w), (dilation_h, dilation_w), groups, has_bias, padding_mode, ).to(dtype=torch.double) bn_op = BatchNorm2d(output_channels, eps, momentum).to(dtype=torch.double) relu_op = ReLU() cls = ConvBnReLU2d if use_relu else ConvBn2d qat_op = cls( input_channels, output_channels, (kernel_h, kernel_w), (stride_h, stride_w), (pad_h, pad_w), (dilation_h, dilation_w), groups, has_bias, padding_mode, eps, momentum, freeze_bn=True, qconfig=default_qat_qconfig, ).to(dtype=torch.double) qat_op._enable_slow_path_for_better_numerical_stability = use_slow_fusion # the approximate fusion will not work if bn.weight has 0 if zero_gamma and use_slow_fusion: torch.nn.init.zeros_(qat_op.bn.weight) qat_op.apply(torch.ao.quantization.disable_fake_quant) if freeze_bn: qat_op.apply(torch.ao.nn.intrinsic.qat.freeze_bn_stats) else: qat_op.apply(torch.ao.nn.intrinsic.qat.update_bn_stats) # align inputs and internal parameters input = torch.randn( batch_size, input_channels, height, width, dtype=torch.double, requires_grad=True, ) conv_op.weight = torch.nn.Parameter(qat_op.weight.detach()) if has_bias: conv_op.bias = torch.nn.Parameter(qat_op.bias.detach()) bn_op.running_mean = qat_op.bn.running_mean.clone() bn_op.running_var = qat_op.bn.running_var.clone() bn_op.weight = torch.nn.Parameter(qat_op.bn.weight.detach()) bn_op.bias = torch.nn.Parameter(qat_op.bn.bias.detach()) def compose(functions): # functions are reversed for natural reading order return reduce(lambda f, g: lambda x: f(g(x)), functions[::-1], lambda x: x) if not use_relu: def relu_op(x): # noqa: F811 return x if freeze_bn: def ref_op(x): x = conv_op(x) x = (x - bn_op.running_mean.reshape([1, -1, 1, 1])) * ( bn_op.weight / torch.sqrt(bn_op.running_var + bn_op.eps) ).reshape([1, -1, 1, 1]) + bn_op.bias.reshape([1, -1, 1, 1]) x = relu_op(x) return x else: ref_op = compose([conv_op, bn_op, relu_op]) input_clone = input.detach().clone().requires_grad_() for _ in range(2): result_ref = ref_op(input) result_actual = qat_op(input_clone) self.assertEqual(result_ref, result_actual) # backward dout = torch.randn(result_ref.size(), dtype=torch.double) loss = (result_ref - dout).sum() loss.backward() input_grad_ref = input.grad.cpu() weight_grad_ref = conv_op.weight.grad.cpu() gamma_grad_ref = bn_op.weight.grad.cpu() beta_grad_ref = bn_op.bias.grad.cpu() running_mean_ref = bn_op.running_mean running_var_ref = bn_op.running_var num_batches_tracked_ref = bn_op.num_batches_tracked loss = (result_actual - dout).sum() loss.backward() input_grad_actual = input_clone.grad.cpu() weight_grad_actual = qat_op.weight.grad.cpu() gamma_grad_actual = qat_op.bn.weight.grad.cpu() beta_grad_actual = qat_op.bn.bias.grad.cpu() running_mean_actual = qat_op.bn.running_mean running_var_actual = qat_op.bn.running_var num_batches_tracked_actual = qat_op.bn.num_batches_tracked precision = 1e-10 self.assertEqual(input_grad_ref, input_grad_actual, atol=precision, rtol=0) self.assertEqual( weight_grad_ref, weight_grad_actual, atol=precision, rtol=0 ) self.assertEqual(gamma_grad_ref, gamma_grad_actual, atol=precision, rtol=0) self.assertEqual(beta_grad_ref, beta_grad_actual, atol=precision, rtol=0) self.assertEqual( num_batches_tracked_ref, num_batches_tracked_actual, atol=precision, rtol=0, ) self.assertEqual( running_mean_ref, running_mean_actual, atol=precision, rtol=0 ) self.assertEqual( running_var_ref, running_var_actual, atol=precision, rtol=0 ) @given( batch_size=st.integers(2, 4), input_channels_per_group=st.sampled_from([2, 3, 4]), height=st.integers(5, 10), width=st.integers(5, 10), output_channels_per_group=st.sampled_from([2, 3]), groups=st.integers(1, 3), kernel_h=st.integers(1, 3), kernel_w=st.integers(1, 3), stride_h=st.integers(1, 2), stride_w=st.integers(1, 2), pad_h=st.integers(0, 2), pad_w=st.integers(0, 2), dilation=st.integers(1, 1), padding_mode=st.sampled_from(["zeros", "circular"]), eps=st.sampled_from([1e-5, 1e-4, 1e-3]), momentum=st.sampled_from([0.1, 0.2, 0.3]), freeze_bn=st.booleans(), bias=st.booleans(), ) def test_conv_bn_folded_vs_unfolded( self, batch_size, input_channels_per_group, height, width, output_channels_per_group, groups, kernel_h, kernel_w, stride_h, stride_w, pad_h, pad_w, dilation, padding_mode, eps, momentum, freeze_bn, bias, ): input_channels = input_channels_per_group * groups output_channels = output_channels_per_group * groups dilation_h = dilation_w = dilation qat_op = ConvBn2d( input_channels, output_channels, (kernel_h, kernel_w), (stride_h, stride_w), (pad_h, pad_w), (dilation_h, dilation_w), groups, bias, # bias padding_mode, eps, momentum, freeze_bn=freeze_bn, qconfig=default_qat_qconfig, ).to(dtype=torch.double) qat_ref_op = _ReferenceConvBn2d( input_channels, output_channels, (kernel_h, kernel_w), (stride_h, stride_w), (pad_h, pad_w), (dilation_h, dilation_w), groups, bias, # bias padding_mode, eps, momentum, freeze_bn=freeze_bn, qconfig=default_qat_qconfig, ).to(dtype=torch.double) qat_op.apply(torch.ao.quantization.disable_fake_quant) qat_ref_op.apply(torch.ao.quantization.disable_fake_quant) # align inputs and internal parameters qat_ref_op.weight = torch.nn.Parameter(qat_op.weight.detach().clone()) qat_ref_op.running_mean = qat_op.bn.running_mean.clone() qat_ref_op.running_var = qat_op.bn.running_var.clone() qat_ref_op.gamma = torch.nn.Parameter(qat_op.bn.weight.detach().clone()) qat_ref_op.beta = torch.nn.Parameter(qat_op.bn.bias.detach().clone()) if qat_op.bias is not None: qat_ref_op.bias = torch.nn.Parameter(qat_op.bias.detach().clone()) lr = 0.01 qat_op_optim = torch.optim.SGD(qat_op.parameters(), lr=lr) qat_ref_op_optim = torch.optim.SGD(qat_ref_op.parameters(), lr=lr) for i in range(5): # make sure that calling model.train() does not override the # bn freeze setting qat_op.train() qat_ref_op.train() qat_op_optim.zero_grad() qat_ref_op_optim.zero_grad() input = torch.randn( batch_size, input_channels, height, width, dtype=torch.double, requires_grad=True, ) input_clone = input.detach().clone().requires_grad_() if i > 2: qat_op.apply(torch.ao.nn.intrinsic.qat.freeze_bn_stats) qat_ref_op.freeze_bn_stats() if i > 3: qat_op.apply(torch.ao.quantization.disable_observer) qat_ref_op.apply(torch.ao.quantization.disable_observer) result_ref = qat_ref_op(input) result_actual = qat_op(input_clone) self.assertEqual(result_ref, result_actual) # backward dout = torch.randn(result_ref.size(), dtype=torch.double) + 10.0 loss = (result_ref - dout).sum() loss.backward() input_grad_ref = input.grad.cpu() weight_grad_ref = qat_ref_op.weight.grad.cpu() gamma_grad_ref = qat_ref_op.gamma.grad.cpu() beta_grad_ref = qat_ref_op.beta.grad.cpu() running_mean_ref = qat_ref_op.running_mean running_var_ref = qat_ref_op.running_var num_batches_tracked_ref = qat_ref_op.num_batches_tracked loss = (result_actual - dout).sum() loss.backward() input_grad_actual = input_clone.grad.cpu() weight_grad_actual = qat_op.weight.grad.cpu() gamma_grad_actual = qat_op.bn.weight.grad.cpu() beta_grad_actual = qat_op.bn.bias.grad.cpu() running_mean_actual = qat_op.bn.running_mean running_var_actual = qat_op.bn.running_var num_batches_tracked_actual = qat_op.bn.num_batches_tracked precision = 1e-5 self.assertEqual(input_grad_ref, input_grad_actual, atol=precision, rtol=0) self.assertEqual( weight_grad_ref, weight_grad_actual, atol=precision, rtol=0 ) self.assertEqual(gamma_grad_ref, gamma_grad_actual, atol=precision, rtol=0) self.assertEqual(beta_grad_ref, beta_grad_actual, atol=precision, rtol=0) self.assertEqual( num_batches_tracked_ref, num_batches_tracked_actual, atol=precision, rtol=0, ) self.assertEqual( running_mean_ref, running_mean_actual, atol=precision, rtol=0 ) self.assertEqual( running_var_ref, running_var_actual, atol=precision, rtol=0 ) qat_op_optim.step() qat_ref_op_optim.step() @override_qengines def test_linear_bn_numerics(self): qengine = torch.backends.quantized.engine m_ref = nn.Sequential( nn.Linear(4, 4), nn.BatchNorm1d(4), ) m_ref_copy = copy.deepcopy(m_ref) m_ref_copy = torch.ao.quantization.fuse_modules_qat(m_ref_copy, [["0", "1"]]) qconfig = torch.ao.quantization.get_default_qat_qconfig(qengine) m_ref_copy[0].qconfig = qconfig m = nniqat.LinearBn1d.from_float(m_ref_copy[0]) # without fake_quants, fused QAT module should match fp32 module m.apply(torch.ao.quantization.disable_fake_quant) data = torch.randn(4, 4) r1 = m_ref(data) r2 = m(data) self.assertTrue(torch.allclose(r1, r2)) @skipIfNoXNNPACK @override_qengines def test_linear_bn_symm_numerics(self): qengine = torch.backends.quantized.engine if qengine != "qnnpack": return # Only qnnpack support symmetric quantization m_ref = nn.Sequential( nn.Linear(4, 4), nn.BatchNorm1d(4), ) m_ref_copy = copy.deepcopy(m_ref) m_ref_copy = torch.ao.quantization.fuse_modules_qat(m_ref_copy, [["0", "1"]]) qconfig = default_symmetric_qnnpack_qat_qconfig m_ref_copy[0].qconfig = qconfig m = nniqat.LinearBn1d.from_float(m_ref_copy[0]) # without fake_quants, fused QAT module should match fp32 module m.apply(torch.ao.quantization.disable_fake_quant) data = torch.randn(4, 4) r1 = m_ref(data) r2 = m(data) self.assertTrue(torch.allclose(r1, r2)) @override_qengines def test_linear_bn_workflow(self): qengine = torch.backends.quantized.engine m = nn.Sequential( QuantStub(), nn.Linear(4, 4), nn.BatchNorm1d(4), ) data = torch.randn(4, 4) m.qconfig = torch.ao.quantization.get_default_qat_qconfig(qengine) m = torch.ao.quantization.fuse_modules_qat(m, [["1", "2"]]) mp = prepare_qat(m) mp(data) mq = convert(mp) self.assertTrue(type(mq[1]) is nnq.Linear) self.assertTrue(type(mq[2]) is nn.Identity) @skipIfNoXNNPACK @override_qengines def test_linear_precomputed_fake_quant(self): qengine = torch.backends.quantized.engine if qengine != "qnnpack": return # Only qnnpack support symmetric quantization m_ref = nn.Linear(4, 4) m_ref_copy = copy.deepcopy(m_ref) qconfig = default_qconfig m_ref_copy.qconfig = qconfig weight_post_process = copy.deepcopy(qconfig.weight()) activation = copy.deepcopy(qconfig.activation()) activation(torch.randn(4, 4)) m_ref_copy.activation_post_process = activation m_ref_copy = nnq.Linear.from_float(m_ref_copy) weight_post_process = qconfig.weight() weight_post_process.min_val = torch.tensor(-1) weight_post_process.max_val = torch.tensor(1) m_ref.weight_post_process = weight_post_process m_ref.activation_post_process = activation m_ref.qconfig = qconfig m_ref = nnq.Linear.from_float(m_ref, use_precomputed_fake_quant=True) self.assertTrue( m_ref._weight_bias()[0].q_scale != m_ref_copy._weight_bias()[0].q_scale ) if __name__ == "__main__": raise RuntimeError( "This test file is not meant to be run directly, use:\n\n" "\tpython test/test_quantization.py TESTNAME\n\n" "instead." )
TestQuantizeEagerQATNumerics
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-weaviate/destination_weaviate/destination.py
{ "start": 851, "end": 2890 }
class ____(Destination): indexer: Indexer embedder: Embedder def _init_indexer(self, config: ConfigModel): self.embedder = ( create_from_config(config.embedding, config.processing) if config.embedding.mode != "no_embedding" else NoEmbedder(config.embedding) ) self.indexer = WeaviateIndexer(config.indexing) def write( self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage] ) -> Iterable[AirbyteMessage]: config_model = ConfigModel.parse_obj(config) self._init_indexer(config_model) writer = Writer( config_model.processing, self.indexer, self.embedder, batch_size=config_model.indexing.batch_size, omit_raw_text=config_model.omit_raw_text, ) yield from writer.write(configured_catalog, input_messages) def check(self, logger: logging.Logger, config: Mapping[str, Any]) -> AirbyteConnectionStatus: parsed_config = ConfigModel.parse_obj(config) self._init_indexer(parsed_config) checks = [self.embedder.check(), self.indexer.check(), DocumentProcessor.check_config(parsed_config.processing)] errors = [error for error in checks if error is not None] if len(errors) > 0: return AirbyteConnectionStatus(status=Status.FAILED, message="\n".join(errors)) else: return AirbyteConnectionStatus(status=Status.SUCCEEDED) def spec(self, *args: Any, **kwargs: Any) -> ConnectorSpecification: return ConnectorSpecification( documentationUrl="https://docs.airbyte.com/integrations/destinations/weaviate", supportsIncremental=True, supported_destination_sync_modes=[DestinationSyncMode.overwrite, DestinationSyncMode.append, DestinationSyncMode.append_dedup], connectionSpecification=ConfigModel.schema(), # type: ignore[attr-defined] )
DestinationWeaviate
python
kamyu104__LeetCode-Solutions
Python/sort-array-by-parity-ii.py
{ "start": 29, "end": 362 }
class ____(object): def sortArrayByParityII(self, A): """ :type A: List[int] :rtype: List[int] """ j = 1 for i in xrange(0, len(A), 2): if A[i] % 2: while A[j] % 2: j += 2 A[i], A[j] = A[j], A[i] return A
Solution
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/pipelines/config.py
{ "start": 8449, "end": 8901 }
class ____(graphene.ObjectType): incoming_fields = non_null_list(graphene.String) class Meta: interfaces = (GrapheneConfigValidationError,) name = "SelectorTypeConfigError" ERROR_DATA_TYPES = ( FieldNotDefinedErrorData, FieldsNotDefinedErrorData, MissingFieldErrorData, MissingFieldsErrorData, RuntimeMismatchErrorData, SelectorTypeErrorData, SerializableErrorInfo, )
GrapheneSelectorTypeConfigError
python
python-attrs__attrs
tests/test_functional.py
{ "start": 893, "end": 981 }
class ____: x = attr.ib() def meth(self): return self.x @attr.s
BaseSlots
python
mlflow__mlflow
mlflow/models/signature.py
{ "start": 2253, "end": 11670 }
class ____: """ ModelSignature specifies schema of model's inputs, outputs and params. ModelSignature can be :py:func:`inferred <mlflow.models.infer_signature>` from training dataset, model predictions using and params for inference, or constructed by hand by passing an input and output :py:class:`Schema <mlflow.types.Schema>`, and params :py:class:`ParamSchema <mlflow.types.ParamSchema>`. """ def __init__( self, # `dataclass` is an invalid type annotation. Use `Any` instead as a workaround. inputs: Schema | Any = None, outputs: Schema | Any = None, params: ParamSchema = None, ): if inputs and not isinstance(inputs, Schema) and not is_dataclass(inputs): raise TypeError( "inputs must be either None, mlflow.models.signature.Schema, or a dataclass," f"got '{type(inputs).__name__}'" ) if outputs and not isinstance(outputs, Schema) and not is_dataclass(outputs): raise TypeError( "outputs must be either None, mlflow.models.signature.Schema, or a dataclass," f"got '{type(outputs).__name__}'" ) if params and not isinstance(params, ParamSchema): raise TypeError( "If params are provided, they must by of type mlflow.models.signature.ParamSchema, " f"got '{type(params).__name__}'" ) if all(x is None for x in [inputs, outputs, params]): raise ValueError("At least one of inputs, outputs or params must be provided") if is_dataclass(inputs): self.inputs = convert_dataclass_to_schema(inputs) else: self.inputs = inputs if is_dataclass(outputs): self.outputs = convert_dataclass_to_schema(outputs) else: self.outputs = outputs self.params = params self.__is_signature_from_type_hint = False self.__is_type_hint_from_example = False @property def _is_signature_from_type_hint(self): return self.__is_signature_from_type_hint @_is_signature_from_type_hint.setter def _is_signature_from_type_hint(self, value): self.__is_signature_from_type_hint = value @property def _is_type_hint_from_example(self): return self.__is_type_hint_from_example @_is_type_hint_from_example.setter def _is_type_hint_from_example(self, value): self.__is_type_hint_from_example = value def to_dict(self) -> dict[str, Any]: """ Serialize into a 'jsonable' dictionary. Input and output schema are represented as json strings. This is so that the representation is compact when embedded in an MLmodel yaml file. Returns: dictionary representation with input and output schema represented as json strings. """ return { "inputs": self.inputs.to_json() if self.inputs else None, "outputs": self.outputs.to_json() if self.outputs else None, "params": self.params.to_json() if self.params else None, } @classmethod def from_dict(cls, signature_dict: dict[str, Any]): """ Deserialize from dictionary representation. Args: signature_dict: Dictionary representation of model signature. Expected dictionary format: `{'inputs': <json string>, 'outputs': <json string>, 'params': <json string>" }` Returns: ModelSignature populated with the data form the dictionary. """ inputs = Schema.from_json(x) if (x := signature_dict.get("inputs")) else None outputs = Schema.from_json(x) if (x := signature_dict.get("outputs")) else None params = ParamSchema.from_json(x) if (x := signature_dict.get("params")) else None return cls(inputs, outputs, params) def __eq__(self, other) -> bool: return ( isinstance(other, ModelSignature) and self.inputs == other.inputs and self.outputs == other.outputs and self.params == other.params ) def __repr__(self) -> str: return ( "inputs: \n" f" {self.inputs!r}\n" "outputs: \n" f" {self.outputs!r}\n" "params: \n" f" {self.params!r}\n" ) def infer_signature( model_input: Any = None, model_output: "MlflowInferableDataset" = None, params: dict[str, Any] | None = None, ) -> ModelSignature: """ Infer an MLflow model signature from the training data (input), model predictions (output) and parameters (for inference). The signature represents model input and output as data frames with (optionally) named columns and data type specified as one of types defined in :py:class:`mlflow.types.DataType`. It also includes parameters schema for inference, . This method will raise an exception if the user data contains incompatible types or is not passed in one of the supported formats listed below. The input should be one of these: - pandas.DataFrame - pandas.Series - dictionary of { name -> numpy.ndarray} - numpy.ndarray - pyspark.sql.DataFrame - scipy.sparse.csr_matrix - scipy.sparse.csc_matrix - dictionary / list of dictionaries of JSON-convertible types The element types should be mappable to one of :py:class:`mlflow.types.DataType`. For pyspark.sql.DataFrame inputs, columns of type DateType and TimestampType are both inferred as type :py:data:`datetime <mlflow.types.DataType.datetime>`, which is coerced to TimestampType at inference. Args: model_input: Valid input to the model. E.g. (a subset of) the training dataset. model_output: Valid model output. E.g. Model predictions for the (subset of) training dataset. params: Valid parameters for inference. It should be a dictionary of parameters that can be set on the model during inference by passing `params` to pyfunc `predict` method. An example of valid parameters: .. code-block:: python from mlflow.models import infer_signature from mlflow.transformers import generate_signature_output # Define parameters for inference params = { "num_beams": 5, "max_length": 30, "do_sample": True, "remove_invalid_values": True, } # Infer the signature including parameters signature = infer_signature( data, generate_signature_output(model, data), params=params, ) # Saving model with model signature mlflow.transformers.save_model( model, path=model_path, signature=signature, ) pyfunc_loaded = mlflow.pyfunc.load_model(model_path) # Passing params to `predict` function directly result = pyfunc_loaded.predict(data, params=params) Returns: ModelSignature """ schemas = {"inputs": model_input, "outputs": model_output} for key, data in schemas.items(): if data is not None: try: schemas[key] = ( convert_dataclass_to_schema(data) if is_dataclass(data) else _infer_schema(data) ) except InvalidDataForSignatureInferenceError: raise except Exception: extra_msg = ( ("Note that MLflow doesn't validate data types during inference for AnyType. ") if key == "inputs" else "" ) _logger.warning( f"Failed to infer schema for {key}. " f"Setting schema to `Schema([ColSpec(type=AnyType())]` as default. {extra_msg}" "To see the full traceback, set logging level to DEBUG.", exc_info=_logger.isEnabledFor(logging.DEBUG), ) schemas[key] = Schema([ColSpec(type=AnyType())]) schemas["params"] = _infer_param_schema(params) if params else None return ModelSignature(**schemas) # `t\w*\.` matches the `typing` module or its alias _LIST_OF_STRINGS_PATTERN = re.compile(r"^(t\w*\.)?list\[str\]$", re.IGNORECASE) def _is_list_str(hint_str): return _LIST_OF_STRINGS_PATTERN.match(hint_str.replace(" ", "")) is not None _LIST_OF_STR_DICT_PATTERN = re.compile( r"^(t\w*\.)?list\[(t\w*\.)?dict\[str,str\]\]$", re.IGNORECASE ) def _is_list_of_string_dict(hint_str): return _LIST_OF_STR_DICT_PATTERN.match(hint_str.replace(" ", "")) is not None def _infer_hint_from_str(hint_str): if _is_list_str(hint_str): return list[str] elif _is_list_of_string_dict(hint_str): return list[dict[str, str]] else: return None def _get_arg_names(f): return list(inspect.signature(f).parameters.keys())
ModelSignature
python
rushter__MLAlgorithms
mla/neuralnet/constraints.py
{ "start": 53, "end": 121 }
class ____(object): def clip(self, p): return p
Constraint
python
spyder-ide__spyder
spyder/plugins/shortcuts/widgets/table.py
{ "start": 3916, "end": 4839 }
class ____(ClearLineEdit): """Textbox for filtering listed shortcuts in the table.""" def __init__(self, parent, callback=None, main=None, regex_base=VALID_FINDER_CHARS): super().__init__(parent) self._parent = parent self.main = main # Widget setup regex = QRegularExpression(regex_base + "{100}") self.setValidator(QRegularExpressionValidator(regex)) # Signals if callback: self.textChanged.connect(callback) def keyPressEvent(self, event): """Qt and FilterLineEdit Override.""" key = event.key() if key in [Qt.Key_Up]: self._parent.previous_row() elif key in [Qt.Key_Down]: self._parent.next_row() elif key in [Qt.Key_Enter, Qt.Key_Return]: self._parent.show_editor() else: super().keyPressEvent(event)
ShortcutFinder
python
jackfrued__Python-100-Days
Day31-35/code/example10.py
{ "start": 467, "end": 848 }
class ____(): def __init__(self, name, country): self.name = name self.country = country def __str__(self): return f'{self.country}: {self.name}' def main(): print(President.__name__) p1 = President('特朗普', '美国') p2 = President('奥巴马', '美国') print(p1 == p2) print(p1) print(p2) if __name__ == '__main__': main()
President
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 368845, "end": 369602 }
class ____(sgqlc.types.Input): """Autogenerated input type of UpdateRef""" __schema__ = github_schema __field_names__ = ("ref_id", "oid", "force", "client_mutation_id") ref_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="refId") """The Node ID of the Ref to be updated.""" oid = sgqlc.types.Field(sgqlc.types.non_null(GitObjectID), graphql_name="oid") """The GitObjectID that the Ref shall be updated to target.""" force = sgqlc.types.Field(Boolean, graphql_name="force") """Permit updates of branch Refs that are not fast-forwards?""" client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation."""
UpdateRefInput
python
pytorch__pytorch
torch/_functorch/_aot_autograd/aot_autograd_result.py
{ "start": 4209, "end": 7891 }
class ____(InductorOutput[CompiledFxGraph]): fx_graph_cache_info: tuple[str, list[str]] fx_graph_guard_expr: Optional[str] def pre_save(self): return def _is_backward(self) -> bool: return False def load(self, example_inputs) -> CompiledFxGraph: from .autograd_cache import FXGraphCacheMiss # [Note: AOTAutogradCache and FXGraphCache Guard interactions] # As mentioned, AOTAutograd takes in the symint inputs from dynamo's list of arguments. # FXGraphCache serializes guards that are needed in the shape_env based on these symint inputs to the graph. # The invariant that AOTAutograd uses here is that the sources for symints given to it by dynamo are exactly # the same as the ones it passes to inductor, for both the forward and backward passes. # (This does not mean that the tensor values passed in are the same: only that their symints are). # That is, AOTAutograd and Inductor never create new guards based on symints with different sources # than those passed to it by inductor. # We pass the post compile function, which sets various fx_config boxed values, # so we can call it only after we're sure both forward and backward have # Clear CompiledTritonKernels before loading from FXGraphCache torch._inductor.async_compile.CompiledTritonKernels.cache_clear() remote_cache = None constants = CompiledFxGraphConstants() if should_use_remote_fx_graph_cache(): remote_cache = FxGraphCache.get_remote_cache() (cache_key, debug_lines) = self.fx_graph_cache_info def check_exact_guard_match(guard_expr, _hints): """ AOTAutogradCache tracks its own guards, so we just need to treat these guard expressions as a second cache key of sorts: we just check for equality, i.e. the FXGraphCache entry with the exact same guards as we originally saved into the cache. """ return guard_expr == self.fx_graph_guard_expr result, cache_info = FxGraphCache.load_with_key( cache_key, debug_lines, example_inputs, local=True, remote_cache=remote_cache, is_backward=self._is_backward(), constants=constants, evaluate_guards=check_exact_guard_match, ) if result is None: log.info("FXGraphCache cache miss for key %s", self.fx_graph_cache_info) torch._logging.trace_structured( "artifact", metadata_fn=lambda: { "name": "fx_graph_cache_miss", # always a hit "encoding": "json", }, payload_fn=lambda: json.dumps(cache_info), ) raise FXGraphCacheMiss # No need to log chromium event because AOTAutograd will log that immediately for us torch._logging.trace_structured( "artifact", metadata_fn=lambda: { "name": "fx_graph_cache_hit", # always a hit "encoding": "json", }, payload_fn=lambda: json.dumps(cache_info), ) self.example_inputs = example_inputs self.constants = constants return result def post_compile( self, result: CompiledFxGraph, fx_config: _CompileFxKwargs ) -> CompiledFxGraph: """ Called after FXGraphCacheLoadable.load, mutates fx_config """ result.post_compile(self.example_inputs, self.constants, fx_config) return result @dataclass
FxGraphCacheLoadable
python
huggingface__transformers
src/transformers/models/esm/modeling_esm.py
{ "start": 11454, "end": 15201 }
class ____(nn.Module): def __init__(self, config, position_embedding_type=None, layer_idx=None, is_cross_attention=False): super().__init__() self.config = config if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention " f"heads ({config.num_attention_heads})" ) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query = nn.Linear(config.hidden_size, self.all_head_size) self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size) self.dropout = config.attention_probs_dropout_prob self.rotary_embeddings = None self.position_embedding_type = position_embedding_type or getattr( config, "position_embedding_type", "absolute" ) if self.position_embedding_type == "rotary": self.rotary_embeddings = RotaryEmbedding(dim=self.attention_head_size) self.scaling = 1.0 # For BC we apply scaling before RoPE self.is_decoder = config.is_decoder self.layer_idx = layer_idx self.is_causal = self.is_decoder and not is_cross_attention def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple[torch.Tensor]: batch_size, seq_length = hidden_states.shape[:-1] hidden_shape = (batch_size, seq_length, -1, self.attention_head_size) query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2) is_cross_attention = encoder_hidden_states is not None current_states = encoder_hidden_states if is_cross_attention else hidden_states attention_mask = encoder_attention_mask if is_cross_attention else attention_mask key_layer = self.key(current_states).view(hidden_shape).transpose(1, 2) value_layer = self.value(current_states).view(hidden_shape).transpose(1, 2) # Matt: Our BERT model (which this code was derived from) scales attention logits down by sqrt(head_dim). # ESM scales the query down by the same factor instead. Modulo numerical stability these are equivalent, # but not when rotary embeddings get involved. Therefore, we scale the query here to match the original # ESM code and fix rotary embeddings. query_layer = query_layer * self.attention_head_size**-0.5 if self.position_embedding_type == "rotary": query_layer, key_layer = self.rotary_embeddings(query_layer, key_layer) attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] attn_output, attn_weights = attention_interface( self, query_layer, key_layer, value_layer, attention_mask, dropout=0.0 if not self.training else self.dropout, scaling=self.scaling, **kwargs, ) attn_output = attn_output.reshape(batch_size, seq_length, -1).contiguous() return attn_output, attn_weights
EsmSelfAttention
python
protocolbuffers__protobuf
cmake/dependencies_generator.py
{ "start": 1258, "end": 2216 }
class ____(object): """A fake MODULE file that we can exec() to get the functions we need.""" def __init__(self, converter): self.converter = converter def module(self, *args, **kwargs): pass def bazel_dep(self, name, version, **kwargs): self.converter.toplevel += textwrap.dedent( """\ set(%(name)s-version "%(version)s") """ % { "name": name, "version": version, } ) def register_toolchains(self, *args, **kwargs): pass def use_repo(self, *args, **kwargs): pass def use_repo_rule(self, *args, **kwargs): return empty_func def single_version_override(self, *args, **kwargs): pass def use_extension(self, *args, **kwargs): return ExtensionFunctions() def local_path_override(self, *args, **kwargs): pass def git_override(self, *args, **kwargs): pass def archive_override(self, *args, **kwargs): pass
ModuleFileFunctions
python
kubernetes-client__python
kubernetes/client/models/v1beta1_resource_claim_template_spec.py
{ "start": 383, "end": 4409 }
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 = { 'metadata': 'V1ObjectMeta', 'spec': 'V1beta1ResourceClaimSpec' } attribute_map = { 'metadata': 'metadata', 'spec': 'spec' } def __init__(self, metadata=None, spec=None, local_vars_configuration=None): # noqa: E501 """V1beta1ResourceClaimTemplateSpec - 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._metadata = None self._spec = None self.discriminator = None if metadata is not None: self.metadata = metadata self.spec = spec @property def metadata(self): """Gets the metadata of this V1beta1ResourceClaimTemplateSpec. # noqa: E501 :return: The metadata of this V1beta1ResourceClaimTemplateSpec. # noqa: E501 :rtype: V1ObjectMeta """ return self._metadata @metadata.setter def metadata(self, metadata): """Sets the metadata of this V1beta1ResourceClaimTemplateSpec. :param metadata: The metadata of this V1beta1ResourceClaimTemplateSpec. # noqa: E501 :type: V1ObjectMeta """ self._metadata = metadata @property def spec(self): """Gets the spec of this V1beta1ResourceClaimTemplateSpec. # noqa: E501 :return: The spec of this V1beta1ResourceClaimTemplateSpec. # noqa: E501 :rtype: V1beta1ResourceClaimSpec """ return self._spec @spec.setter def spec(self, spec): """Sets the spec of this V1beta1ResourceClaimTemplateSpec. :param spec: The spec of this V1beta1ResourceClaimTemplateSpec. # noqa: E501 :type: V1beta1ResourceClaimSpec """ if self.local_vars_configuration.client_side_validation and spec is None: # noqa: E501 raise ValueError("Invalid value for `spec`, must not be `None`") # noqa: E501 self._spec = spec 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, V1beta1ResourceClaimTemplateSpec): 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, V1beta1ResourceClaimTemplateSpec): return True return self.to_dict() != other.to_dict()
V1beta1ResourceClaimTemplateSpec
python
apache__airflow
providers/standard/tests/unit/standard/operators/test_branch_operator.py
{ "start": 2103, "end": 2216 }
class ____(BaseBranchOperator): def choose_branch(self, context): return ["branch_3"]
ChooseBranchThree
python
astral-sh__uv
crates/uv-python/python/packaging/_manylinux.py
{ "start": 2316, "end": 9555 }
class ____(NamedTuple): major: int minor: int def _glibc_version_string_confstr() -> str | None: """ Primary implementation of glibc_version_string using os.confstr. """ # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely # to be broken or missing. This strategy is used in the standard library # platform module. # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183 try: # Should be a string like "glibc 2.17". version_string: str | None = os.confstr("CS_GNU_LIBC_VERSION") assert version_string is not None _, version = version_string.rsplit() except (AssertionError, AttributeError, OSError, ValueError): # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)... return None return version def _glibc_version_string_ctypes() -> str | None: """ Fallback implementation of glibc_version_string using ctypes. """ try: import ctypes except ImportError: return None # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen # manpage says, "If filename is NULL, then the returned handle is for the # main program". This way we can let the linker do the work to figure out # which libc our process is actually using. # # We must also handle the special case where the executable is not a # dynamically linked executable. This can occur when using musl libc, # for example. In this situation, dlopen() will error, leading to an # OSError. Interestingly, at least in the case of musl, there is no # errno set on the OSError. The single string argument used to construct # OSError comes from libc itself and is therefore not portable to # hard code here. In any case, failure to call dlopen() means we # can proceed, so we bail on our attempt. try: process_namespace = ctypes.CDLL(None) except OSError: return None try: gnu_get_libc_version = process_namespace.gnu_get_libc_version except AttributeError: # Symbol doesn't exist -> therefore, we are not linked to # glibc. return None # Call gnu_get_libc_version, which returns a string like "2.5" gnu_get_libc_version.restype = ctypes.c_char_p version_str: str = gnu_get_libc_version() # py2 / py3 compatibility: if not isinstance(version_str, str): version_str = version_str.decode("ascii") return version_str def _glibc_version_string() -> str | None: """Returns glibc version string, or None if not using glibc.""" return _glibc_version_string_confstr() or _glibc_version_string_ctypes() def _parse_glibc_version(version_str: str) -> _GLibCVersion: """Parse glibc version. We use a regexp instead of str.split because we want to discard any random junk that might come after the minor version -- this might happen in patched/forked versions of glibc (e.g. Linaro's version of glibc uses version strings like "2.20-2014.11"). See gh-3588. """ m = re.match(r"(?P<major>[0-9]+)\.(?P<minor>[0-9]+)", version_str) if not m: warnings.warn( f"Expected glibc version with 2 components major.minor, got: {version_str}", RuntimeWarning, ) return _GLibCVersion(-1, -1) return _GLibCVersion(int(m.group("major")), int(m.group("minor"))) @functools.lru_cache() def _get_glibc_version() -> _GLibCVersion: version_str = _glibc_version_string() if version_str is None: return _GLibCVersion(-1, -1) return _parse_glibc_version(version_str) # From PEP 513, PEP 600 def _is_compatible(arch: str, version: _GLibCVersion) -> bool: sys_glibc = _get_glibc_version() if sys_glibc < version: return False # Check for presence of _manylinux module. try: import _manylinux except ImportError: return True if hasattr(_manylinux, "manylinux_compatible"): result = _manylinux.manylinux_compatible(version[0], version[1], arch) if result is not None: return bool(result) return True if version == _GLibCVersion(2, 5): if hasattr(_manylinux, "manylinux1_compatible"): return bool(_manylinux.manylinux1_compatible) if version == _GLibCVersion(2, 12): if hasattr(_manylinux, "manylinux2010_compatible"): return bool(_manylinux.manylinux2010_compatible) if version == _GLibCVersion(2, 17): if hasattr(_manylinux, "manylinux2014_compatible"): return bool(_manylinux.manylinux2014_compatible) return True _LEGACY_MANYLINUX_MAP: dict[_GLibCVersion, str] = { # CentOS 7 w/ glibc 2.17 (PEP 599) _GLibCVersion(2, 17): "manylinux2014", # CentOS 6 w/ glibc 2.12 (PEP 571) _GLibCVersion(2, 12): "manylinux2010", # CentOS 5 w/ glibc 2.5 (PEP 513) _GLibCVersion(2, 5): "manylinux1", } def platform_tags(archs: Sequence[str]) -> Iterator[str]: """Generate manylinux tags compatible to the current platform. :param archs: Sequence of compatible architectures. The first one shall be the closest to the actual architecture and be the part of platform tag after the ``linux_`` prefix, e.g. ``x86_64``. The ``linux_`` prefix is assumed as a prerequisite for the current platform to be manylinux-compatible. :returns: An iterator of compatible manylinux tags. """ if not _have_compatible_abi(sys.executable, archs): return # Oldest glibc to be supported regardless of architecture is (2, 17). too_old_glibc2 = _GLibCVersion(2, 16) if set(archs) & {"x86_64", "i686"}: # On x86/i686 also oldest glibc to be supported is (2, 5). too_old_glibc2 = _GLibCVersion(2, 4) current_glibc = _get_glibc_version() glibc_max_list = [current_glibc] # We can assume compatibility across glibc major versions. # https://sourceware.org/bugzilla/show_bug.cgi?id=24636 # # Build a list of maximum glibc versions so that we can # output the canonical list of all glibc from current_glibc # down to too_old_glibc2, including all intermediary versions. for glibc_major in range(current_glibc.major - 1, 1, -1): glibc_minor = _LAST_GLIBC_MINOR[glibc_major] glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor)) for arch in archs: for glibc_max in glibc_max_list: if glibc_max.major == too_old_glibc2.major: min_minor = too_old_glibc2.minor else: # For other glibc major versions oldest supported is (x, 0). min_minor = -1 for glibc_minor in range(glibc_max.minor, min_minor, -1): glibc_version = _GLibCVersion(glibc_max.major, glibc_minor) if _is_compatible(arch, glibc_version): yield "manylinux_{}_{}_{}".format(*glibc_version, arch) # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags. legacy_tag = _LEGACY_MANYLINUX_MAP.get(glibc_version) if legacy_tag: yield f"{legacy_tag}_{arch}"
_GLibCVersion
python
pytorch__pytorch
torch/distributed/checkpoint/_experimental/checkpointer.py
{ "start": 6568, "end": 11948 }
class ____(Checkpointer): """ Asynchronous implementation of Checkpointer. This class coordinates the writing and loading of model state dictionaries to and from storage using asynchronous operations for saving. It provides efficient async checkpoint operations with staging and background writing capabilities. Attributes: _reader: CheckpointReader for reading state dictionaries from storage. _checkpoint_stager: Stager for async operations. _checkpoint_process: Process for async operations. _write_future: Future representing the ongoing async write operation. Example: checkpointer = AsyncCheckpointer( reader=reader, checkpoint_stager=stager, checkpoint_process=process ) stage_future, write_future = checkpointer.save(state_dict, path) # ... do other work ... write_future.result() # Wait for completion """ def __init__( self, checkpoint_stager: CheckpointStager, checkpoint_process: CheckpointProcess, reader: CheckpointReader, ): """ Initialize an asynchronous checkpointer. Args: checkpoint_stager: Stager for async operations. checkpoint_process: Process for async operations. reader: CheckpointReader for reading checkpoints from storage. """ self._reader = reader self._checkpoint_stager = checkpoint_stager self._checkpoint_process = checkpoint_process self._write_future: Optional[Future[Any]] = None def save( self, path: str, state_dict: STATE_DICT, **kwargs: Any, ) -> Optional[tuple[Future, Future]]: """ Save a state dictionary to storage asynchronously. Args: path: The path where the checkpoint should be saved. state_dict: The state dictionary to save. **kwargs: Additional keyword arguments to pass to the stager and writer. Returns: A tuple of (stage_future, write_future) representing the staging and writing operations. Example: stage_future, write_future = checkpointer.save("/path/to/checkpoint", state_dict) # ... do other work ... write_future.result() # Wait for completion """ logger.info( "Initiating checkpoint save to %s. Will wait for prev checkpoints to complete.", path, ) # Wait for previous checkpoint ops to finish and verify they are successful if self._write_future is not None: self._write_future.result() logger.debug("Starting state dictionary staging") staging_result = self._checkpoint_stager.stage( state_dict=state_dict, **kwargs, ) logger.debug("Starting checkpoint write to %s", path) self._write_future = self._checkpoint_process.write( staging_result, path, **kwargs ) logger.info("Checkpoint save to %s initiated", path) # Return futures for the staging and writing operations if self._write_future is not None: return wrap_future(staging_result), self._write_future else: # This should not happen since we just assigned _write_future above raise RuntimeError("Write future is unexpectedly None") def load( self, path: str, state_dict: Optional[STATE_DICT] = None, *, default_map_location: Any = None, strict: bool = False, **kwargs: Any, ) -> STATE_DICT: """ Load a state dictionary from storage. Loading is always performed synchronously, even in AsyncCheckpointer. Args: path: The path from which to load the checkpoint. state_dict: Optional state dictionary to update with loaded values. If provided, only keys in this dictionary will be loaded. default_map_location: Device mapping function or device name for relocating tensors. strict: If True, raises an error when there are missing keys in the checkpoint. **kwargs: Additional keyword arguments to pass to the reader. Returns: The loaded state dictionary. Raises: RuntimeError: If strict=True and there are missing keys in the checkpoint. FileNotFoundError: If the checkpoint file is not found. """ logger.info("Loading checkpoint from %s", path) loaded_state_dict, missing_keys = self._reader.read( path=path, state_dict=state_dict, map_location=default_map_location, **kwargs, ) if strict and missing_keys is not None and missing_keys != []: raise RuntimeError(f"Checkpoint at {path} is missing keys: {missing_keys}") return loaded_state_dict def close(self) -> None: """ Close the checkpointer and release any resources. This method should be called when the checkpointer is no longer needed to ensure proper cleanup of async resources. """ self._checkpoint_stager.close() self._checkpoint_process.close() logger.info("AsyncCheckpointer closed")
AsyncCheckpointer
python
huggingface__transformers
src/transformers/models/hunyuan_v1_moe/modeling_hunyuan_v1_moe.py
{ "start": 24436, "end": 27532 }
class ____(HunYuanMoEV1PreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} _tp_plan = {"lm_head": "colwise_rep"} _pp_plan = {"lm_head": (["hidden_states"], ["logits"])} def __init__(self, config): super().__init__(config) self.model = HunYuanMoEV1Model(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) # Initialize weights and apply final processing self.post_init() @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs: Unpack[TransformersKwargs], ) -> CausalLMOutputWithPast: r""" Example: ```python >>> from transformers import AutoTokenizer, HunYuanMoEV1ForCausalLM >>> model = HunYuanMoEV1ForCausalLM.from_pretrained("meta-hunyuan_v1_moe/HunYuanMoEV1-2-7b-hf") >>> tokenizer = AutoTokenizer.from_pretrained("meta-hunyuan_v1_moe/HunYuanMoEV1-2-7b-hf") >>> prompt = "Hey, are you conscious? Can you talk to me?" >>> inputs = tokenizer(prompt, return_tensors="pt") >>> # Generate >>> generate_ids = model.generate(inputs.input_ids, max_length=30) >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." ```""" outputs: BaseModelOutputWithPast = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, cache_position=cache_position, **kwargs, ) hidden_states = outputs.last_hidden_state # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :]) loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs) return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
HunYuanMoEV1ForCausalLM
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/pools.py
{ "start": 1434, "end": 1910 }
class ____(BasePool): """Pool serializer for responses.""" occupied_slots: Annotated[int, BeforeValidator(_call_function)] running_slots: Annotated[int, BeforeValidator(_call_function)] queued_slots: Annotated[int, BeforeValidator(_call_function)] scheduled_slots: Annotated[int, BeforeValidator(_call_function)] open_slots: Annotated[int, BeforeValidator(_call_function)] deferred_slots: Annotated[int, BeforeValidator(_call_function)]
PoolResponse
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_event_logs.py
{ "start": 3694, "end": 7167 }
class ____(TestEventLogsEndpoint): @pytest.mark.parametrize( ("event_log_key", "expected_status_code", "expected_body"), [ ( EVENT_NORMAL, 200, { "event": EVENT_NORMAL, }, ), ( EVENT_WITH_OWNER, 200, { "event": EVENT_WITH_OWNER, "owner": OWNER, }, ), ( TASK_INSTANCE_EVENT, 200, { "dag_id": DAG_ID, "dag_display_name": DAG_DISPLAY_NAME, "event": TASK_INSTANCE_EVENT, "map_index": -1, "owner": OWNER_AIRFLOW, "run_id": DAG_RUN_ID, "task_id": TASK_ID, "task_display_name": TASK_DISPLAY_NAME, }, ), ( EVENT_WITH_OWNER_AND_TASK_INSTANCE, 200, { "dag_id": DAG_ID, "dag_display_name": DAG_DISPLAY_NAME, "event": EVENT_WITH_OWNER_AND_TASK_INSTANCE, "map_index": -1, "owner": OWNER, "run_id": DAG_RUN_ID, "task_id": TASK_ID, "task_display_name": TASK_DISPLAY_NAME, "try_number": 0, }, ), ("not_existed_event_log_key", 404, {}), ], ) def test_get_event_log(self, test_client, setup, event_log_key, expected_status_code, expected_body): event_log: Log | None = setup.get(event_log_key, None) event_log_id = event_log.id if event_log else EVENT_NON_EXISTED_ID response = test_client.get(f"/eventLogs/{event_log_id}") assert response.status_code == expected_status_code if expected_status_code != 200: return expected_json = { "event_log_id": event_log_id, "when": from_datetime_to_zulu(event_log.dttm) if event_log.dttm else None, "dag_display_name": expected_body.get("dag_display_name"), "dag_id": expected_body.get("dag_id"), "task_id": expected_body.get("task_id"), "task_display_name": expected_body.get("task_display_name"), "run_id": expected_body.get("run_id"), "map_index": event_log.map_index, "try_number": event_log.try_number, "event": expected_body.get("event"), "logical_date": from_datetime_to_zulu_without_ms(event_log.logical_date) if event_log.logical_date else None, "owner": expected_body.get("owner"), "extra": expected_body.get("extra"), } assert response.json() == expected_json def test_should_raises_401_unauthenticated(self, unauthenticated_test_client, setup): event_log_id = setup[EVENT_NORMAL].id response = unauthenticated_test_client.get(f"/eventLogs/{event_log_id}") assert response.status_code == 401 def test_should_raises_403_forbidden(self, unauthorized_test_client, setup): event_log_id = setup[EVENT_NORMAL].id response = unauthorized_test_client.get(f"/eventLogs/{event_log_id}") assert response.status_code == 403
TestGetEventLog
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/bulk_persistence.py
{ "start": 49276, "end": 65889 }
class ____(_BulkUDCompileState, UpdateDMLState): @classmethod def create_for_statement(cls, statement, compiler, **kw): self = cls.__new__(cls) dml_strategy = statement._annotations.get( "dml_strategy", "unspecified" ) toplevel = not compiler.stack if toplevel and dml_strategy == "bulk": self._setup_for_bulk_update(statement, compiler) elif ( dml_strategy == "core_only" or dml_strategy == "unspecified" and "parententity" not in statement.table._annotations ): UpdateDMLState.__init__(self, statement, compiler, **kw) elif not toplevel or dml_strategy in ("orm", "unspecified"): self._setup_for_orm_update(statement, compiler) return self def _setup_for_orm_update(self, statement, compiler, **kw): orm_level_statement = statement toplevel = not compiler.stack ext_info = statement.table._annotations["parententity"] self.mapper = mapper = ext_info.mapper self._resolved_values = self._get_resolved_values(mapper, statement) self._init_global_attributes( statement, compiler, toplevel=toplevel, process_criteria_for_toplevel=toplevel, ) if statement._values: self._resolved_values = dict(self._resolved_values) new_stmt = statement._clone() if new_stmt.table._annotations["parententity"] is mapper: new_stmt.table = mapper.local_table # note if the statement has _multi_values, these # are passed through to the new statement, which will then raise # InvalidRequestError because UPDATE doesn't support multi_values # right now. if statement._values: new_stmt._values = self._resolved_values new_crit = self._adjust_for_extra_criteria( self.global_attributes, mapper ) if new_crit: new_stmt = new_stmt.where(*new_crit) # if we are against a lambda statement we might not be the # topmost object that received per-execute annotations # do this first as we need to determine if there is # UPDATE..FROM UpdateDMLState.__init__(self, new_stmt, compiler, **kw) use_supplemental_cols = False if not toplevel: synchronize_session = None else: synchronize_session = compiler._annotations.get( "synchronize_session", None ) can_use_returning = compiler._annotations.get( "can_use_returning", None ) if can_use_returning is not False: # even though pre_exec has determined basic # can_use_returning for the dialect, if we are to use # RETURNING we need to run can_use_returning() at this level # unconditionally because is_delete_using was not known # at the pre_exec level can_use_returning = ( synchronize_session == "fetch" and self.can_use_returning( compiler.dialect, mapper, is_multitable=self.is_multitable ) ) if synchronize_session == "fetch" and can_use_returning: use_supplemental_cols = True # NOTE: we might want to RETURNING the actual columns to be # synchronized also. however this is complicated and difficult # to align against the behavior of "evaluate". Additionally, # in a large number (if not the majority) of cases, we have the # "evaluate" answer, usually a fixed value, in memory already and # there's no need to re-fetch the same value # over and over again. so perhaps if it could be RETURNING just # the elements that were based on a SQL expression and not # a constant. For now it doesn't quite seem worth it new_stmt = new_stmt.return_defaults(*new_stmt.table.primary_key) if toplevel: new_stmt = self._setup_orm_returning( compiler, orm_level_statement, new_stmt, dml_mapper=mapper, use_supplemental_cols=use_supplemental_cols, ) self.statement = new_stmt def _setup_for_bulk_update(self, statement, compiler, **kw): """establish an UPDATE statement within the context of bulk insert. This method will be within the "conn.execute()" call that is invoked by persistence._emit_update_statement(). """ statement = cast(dml.Update, statement) an = statement._annotations emit_update_table, _ = ( an["_emit_update_table"], an["_emit_update_mapper"], ) statement = statement._clone() statement.table = emit_update_table UpdateDMLState.__init__(self, statement, compiler, **kw) if self._maintain_values_ordering: raise sa_exc.InvalidRequestError( "bulk ORM UPDATE does not support ordered_values() for " "custom UPDATE statements with bulk parameter sets. Use a " "non-bulk UPDATE statement or use values()." ) if self._dict_parameters: self._dict_parameters = { col: val for col, val in self._dict_parameters.items() if col.table is emit_update_table } self.statement = statement @classmethod def orm_execute_statement( cls, session: Session, statement: dml.Update, params: _CoreAnyExecuteParams, execution_options: OrmExecuteOptionsParameter, bind_arguments: _BindArguments, conn: Connection, ) -> _result.Result: update_options = execution_options.get( "_sa_orm_update_options", cls.default_update_options ) if update_options._populate_existing: load_options = execution_options.get( "_sa_orm_load_options", QueryContext.default_load_options ) load_options += {"_populate_existing": True} execution_options = execution_options.union( {"_sa_orm_load_options": load_options} ) if update_options._dml_strategy not in ( "orm", "auto", "bulk", "core_only", ): raise sa_exc.ArgumentError( "Valid strategies for ORM UPDATE strategy " "are 'orm', 'auto', 'bulk', 'core_only'" ) result: _result.Result[Unpack[TupleAny]] if update_options._dml_strategy == "bulk": enable_check_rowcount = not statement._where_criteria assert update_options._synchronize_session != "fetch" if ( statement._where_criteria and update_options._synchronize_session == "evaluate" ): raise sa_exc.InvalidRequestError( "bulk synchronize of persistent objects not supported " "when using bulk update with additional WHERE " "criteria right now. add synchronize_session=None " "execution option to bypass synchronize of persistent " "objects." ) mapper = update_options._subject_mapper assert mapper is not None assert session._transaction is not None result = _bulk_update( mapper, cast( "Iterable[Dict[str, Any]]", [params] if isinstance(params, dict) else params, ), session._transaction, isstates=False, update_changed_only=False, use_orm_update_stmt=statement, enable_check_rowcount=enable_check_rowcount, ) return cls.orm_setup_cursor_result( session, statement, params, execution_options, bind_arguments, result, ) else: return super().orm_execute_statement( session, statement, params, execution_options, bind_arguments, conn, ) @classmethod def can_use_returning( cls, dialect: Dialect, mapper: Mapper[Any], *, is_multitable: bool = False, is_update_from: bool = False, is_delete_using: bool = False, is_executemany: bool = False, ) -> bool: # normal answer for "should we use RETURNING" at all. normal_answer = ( dialect.update_returning and mapper.local_table.implicit_returning ) if not normal_answer: return False if is_executemany: return dialect.update_executemany_returning # these workarounds are currently hypothetical for UPDATE, # unlike DELETE where they impact MariaDB if is_update_from: return dialect.update_returning_multifrom elif is_multitable and not dialect.update_returning_multifrom: raise sa_exc.CompileError( f'Dialect "{dialect.name}" does not support RETURNING ' "with UPDATE..FROM; for synchronize_session='fetch', " "please add the additional execution option " "'is_update_from=True' to the statement to indicate that " "a separate SELECT should be used for this backend." ) return True @classmethod def _do_post_synchronize_bulk_evaluate( cls, session, params, result, update_options ): if not params: return mapper = update_options._subject_mapper pk_keys = [prop.key for prop in mapper._identity_key_props] identity_map = session.identity_map for param in params: identity_key = mapper.identity_key_from_primary_key( (param[key] for key in pk_keys), update_options._identity_token, ) state = identity_map.fast_get_state(identity_key) if not state: continue evaluated_keys = set(param).difference(pk_keys) dict_ = state.dict # only evaluate unmodified attributes to_evaluate = state.unmodified.intersection(evaluated_keys) for key in to_evaluate: if key in dict_: dict_[key] = param[key] state.manager.dispatch.refresh(state, None, to_evaluate) state._commit(dict_, list(to_evaluate)) # attributes that were formerly modified instead get expired. # this only gets hit if the session had pending changes # and autoflush were set to False. to_expire = evaluated_keys.intersection(dict_).difference( to_evaluate ) if to_expire: state._expire_attributes(dict_, to_expire) @classmethod def _do_post_synchronize_evaluate( cls, session, statement, result, update_options ): matched_objects = cls._get_matched_objects_on_criteria( update_options, session.identity_map.all_states(), ) cls._apply_update_set_values_to_objects( session, update_options, statement, result.context.compiled_parameters[0], [(obj, state, dict_) for obj, state, dict_, _ in matched_objects], result.prefetch_cols(), result.postfetch_cols(), ) @classmethod def _do_post_synchronize_fetch( cls, session, statement, result, update_options ): target_mapper = update_options._subject_mapper returned_defaults_rows = result.returned_defaults_rows if returned_defaults_rows: pk_rows = cls._interpret_returning_rows( result, target_mapper, returned_defaults_rows ) matched_rows = [ tuple(row) + (update_options._identity_token,) for row in pk_rows ] else: matched_rows = update_options._matched_rows objs = [ session.identity_map[identity_key] for identity_key in [ target_mapper.identity_key_from_primary_key( list(primary_key), identity_token=identity_token, ) for primary_key, identity_token in [ (row[0:-1], row[-1]) for row in matched_rows ] if update_options._identity_token is None or identity_token == update_options._identity_token ] if identity_key in session.identity_map ] if not objs: return cls._apply_update_set_values_to_objects( session, update_options, statement, result.context.compiled_parameters[0], [ ( obj, attributes.instance_state(obj), attributes.instance_dict(obj), ) for obj in objs ], result.prefetch_cols(), result.postfetch_cols(), ) @classmethod def _apply_update_set_values_to_objects( cls, session, update_options, statement, effective_params, matched_objects, prefetch_cols, postfetch_cols, ): """apply values to objects derived from an update statement, e.g. UPDATE..SET <values> """ mapper = update_options._subject_mapper target_cls = mapper.class_ evaluator_compiler = evaluator._EvaluatorCompiler(target_cls) resolved_values = cls._get_resolved_values(mapper, statement) resolved_keys_as_propnames = cls._resolved_keys_as_propnames( mapper, resolved_values ) value_evaluators = {} for key, value in resolved_keys_as_propnames: try: _evaluator = evaluator_compiler.process( coercions.expect(roles.ExpressionElementRole, value) ) except evaluator.UnevaluatableError: pass else: value_evaluators[key] = _evaluator evaluated_keys = list(value_evaluators.keys()) attrib = {k for k, v in resolved_keys_as_propnames} states = set() to_prefetch = { c for c in prefetch_cols if c.key in effective_params and c in mapper._columntoproperty and c.key not in evaluated_keys } to_expire = { mapper._columntoproperty[c].key for c in postfetch_cols if c in mapper._columntoproperty }.difference(evaluated_keys) prefetch_transfer = [ (mapper._columntoproperty[c].key, c.key) for c in to_prefetch ] for obj, state, dict_ in matched_objects: dict_.update( { col_to_prop: effective_params[c_key] for col_to_prop, c_key in prefetch_transfer } ) state._expire_attributes(state.dict, to_expire) to_evaluate = state.unmodified.intersection(evaluated_keys) for key in to_evaluate: if key in dict_: # only run eval for attributes that are present. dict_[key] = value_evaluators[key](obj) state.manager.dispatch.refresh(state, None, to_evaluate) state._commit(dict_, list(to_evaluate)) # attributes that were formerly modified instead get expired. # this only gets hit if the session had pending changes # and autoflush were set to False. to_expire = attrib.intersection(dict_).difference(to_evaluate) if to_expire: state._expire_attributes(dict_, to_expire) states.add(state) session._register_altered(states) @CompileState.plugin_for("orm", "delete")
_BulkORMUpdate
python
google__jax
jaxlib/pytree_test.py
{ "start": 920, "end": 1313 }
class ____: def __init__(self, field0, field1): self.field0 = field0 self.field1 = field1 def to_iterable(self): return [self.field0, self.field1], (None,) def from_iterable(state, values): del state return ExampleType2(field0=values[0], field1=values[1]) registry.register_node(ExampleType2, ExampleType2.to_iterable, from_iterable) @dataclasses.dataclass
ExampleType2
python
rq__rq
rq/serializers.py
{ "start": 369, "end": 557 }
class ____: dumps: ClassVar[Callable[[Any], bytes]] = partial(pickle.dumps, protocol=pickle.HIGHEST_PROTOCOL) loads: ClassVar[Callable[[bytes], Any]] = pickle.loads
DefaultSerializer
python
mlflow__mlflow
mlflow/server/job_api.py
{ "start": 2194, "end": 2357 }
class ____(BaseModel): function_fullname: str | None = None params: dict[str, Any] | None = None statuses: list[JobStatus] | None = None
SearchJobPayload
python
dask__distributed
distributed/preloading.py
{ "start": 6737, "end": 8372 }
class ____(Sequence[Preload]): _preloads: list[Preload] def __init__(self, preloads: list[Preload]): self._preloads = preloads async def start(self) -> None: for preload in self._preloads: try: await preload.start() except Exception: logger.exception("Failed to start preload: %s", preload.name) async def teardown(self) -> None: for preload in reversed(self._preloads): try: await preload.teardown() except Exception: logger.exception("Failed to tear down preload: %s", preload.name) def __getitem__(self, index): return self._preloads[index] def __len__(self) -> int: return len(self._preloads) def process_preloads( dask_server: Server | Client, preload: str | Sequence[str], preload_argv: Sequence[str] | Sequence[Sequence[str]], *, file_dir: str | None = None, ) -> PreloadManager: if isinstance(preload, str): preload = [preload] if preload_argv and isinstance(preload_argv[0], str): preload_argv = [cast("list[str]", preload_argv)] * len(preload) elif not preload_argv: preload_argv = [cast("list[str]", [])] * len(preload) if len(preload) != len(preload_argv): raise ValueError( "preload and preload_argv have mismatched lengths " f"{len(preload)} != {len(preload_argv)}" ) return PreloadManager( [ Preload(dask_server, p, argv, file_dir) for p, argv in zip(preload, preload_argv) ] )
PreloadManager
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pydocstyle/D.py
{ "start": 14982, "end": 15174 }
class ____: "After this docstring there's another statement on the same line separated by a semicolon." ; priorities=1 def sort_services(self): pass
StatementOnSameLineAsDocstring
python
keras-team__keras
keras/src/ops/math_test.py
{ "start": 41285, "end": 42557 }
class ____(testing.TestCase): def test_fft_input_not_tuple_or_list(self): fft_op = kmath.FFT() with self.assertRaisesRegex( ValueError, "Input `x` should be a tuple of two tensors" ): fft_op.compute_output_spec(np.array([1, 2, 3])) def test_fft_input_parts_different_shapes(self): fft_op = kmath.FFT() real = np.array([1, 2, 3]) imag = np.array([1, 2]) with self.assertRaisesRegex( ValueError, "Both the real and imaginary parts should have the same shape", ): fft_op.compute_output_spec((real, imag)) def test_fft_input_not_1d(self): fft_op = kmath.FFT() real = np.array(1) imag = np.array(1) with self.assertRaisesRegex(ValueError, "Input should have rank >= 1"): fft_op.compute_output_spec((real, imag)) def test_fft_last_axis_not_fully_defined(self): fft_op = kmath.FFT() real = KerasTensor(shape=(None,), dtype="float32") imag = KerasTensor(shape=(None,), dtype="float32") with self.assertRaisesRegex( ValueError, "Input should have its last dimension fully-defined" ): fft_op.compute_output_spec((real, imag))
FFTTest
python
RaRe-Technologies__gensim
gensim/test/test_corpora.py
{ "start": 8948, "end": 10456 }
class ____(CorpusTestCase): def setUp(self): self.corpus_class = mmcorpus.MmCorpus self.corpus = self.corpus_class(datapath('test_mmcorpus_with_index.mm')) self.file_extension = '.mm' def test_serialize_compressed(self): # MmCorpus needs file write with seek => doesn't support compressed output (only input) pass def test_closed_file_object(self): file_obj = open(datapath('testcorpus.mm')) f = file_obj.closed mmcorpus.MmCorpus(file_obj) s = file_obj.closed self.assertEqual(f, 0) self.assertEqual(s, 0) @unittest.skipIf(GITHUB_ACTIONS_WINDOWS, 'see <https://github.com/RaRe-Technologies/gensim/pull/2836>') def test_load(self): self.assertEqual(self.corpus.num_docs, 9) self.assertEqual(self.corpus.num_terms, 12) self.assertEqual(self.corpus.num_nnz, 28) # confirm we can iterate and that document values match expected for first three docs it = iter(self.corpus) self.assertEqual(next(it), [(0, 1.0), (1, 1.0), (2, 1.0)]) self.assertEqual(next(it), [(0, 1.0), (3, 1.0), (4, 1.0), (5, 1.0), (6, 1.0), (7, 1.0)]) self.assertEqual(next(it), [(2, 1.0), (5, 1.0), (7, 1.0), (8, 1.0)]) # confirm that accessing document by index works self.assertEqual(self.corpus[3], [(1, 1.0), (5, 2.0), (8, 1.0)]) self.assertEqual(tuple(self.corpus.index), (97, 121, 169, 201, 225, 249, 258, 276, 303))
TestMmCorpusWithIndex
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_assets.py
{ "start": 48046, "end": 52518 }
class ____(TestAssets): @pytest.mark.usefixtures("time_freezer") def test_should_respond_200(self, test_client, session): (asset,) = self.create_assets(session, num=1) event_payload = {"asset_id": asset.id, "extra": {"foo": "bar"}} response = test_client.post("/assets/events", json=event_payload) assert response.status_code == 200 assert response.json() == { "id": mock.ANY, "asset_id": asset.id, "uri": "s3://bucket/key/1", "group": "asset", "name": "simple1", "extra": {"foo": "bar", "from_rest_api": True}, "source_task_id": None, "source_dag_id": None, "source_run_id": None, "source_map_index": -1, "created_dagruns": [], "timestamp": from_datetime_to_zulu_without_ms(DEFAULT_DATE), "partition_key": None, } check_last_log(session, dag_id=None, event="create_asset_event", logical_date=None) def test_should_respond_401(self, unauthenticated_test_client): response = unauthenticated_test_client.post("/assets/events", json={"asset_uri": "s3://bucket/key/1"}) assert response.status_code == 401 def test_should_respond_403(self, unauthorized_test_client): response = unauthorized_test_client.post("/assets/events", json={"asset_uri": "s3://bucket/key/1"}) assert response.status_code == 403 def test_invalid_attr_not_allowed(self, test_client, session): self.create_assets(session) event_invalid_payload = {"asset_uri": "s3://bucket/key/1", "extra": {"foo": "bar"}, "fake": {}} response = test_client.post("/assets/events", json=event_invalid_payload) assert response.status_code == 422 @pytest.mark.usefixtures("time_freezer") @pytest.mark.enable_redact def test_should_mask_sensitive_extra(self, test_client, session): (asset,) = self.create_assets(session, num=1) event_payload = {"asset_id": asset.id, "extra": {"password": "bar"}} response = test_client.post("/assets/events", json=event_payload) assert response.status_code == 200 assert response.json() == { "id": mock.ANY, "asset_id": asset.id, "uri": "s3://bucket/key/1", "group": "asset", "name": "simple1", "extra": {"password": "***", "from_rest_api": True}, "source_task_id": None, "source_dag_id": None, "source_run_id": None, "source_map_index": -1, "created_dagruns": [], "timestamp": from_datetime_to_zulu_without_ms(DEFAULT_DATE), "partition_key": None, } def test_should_update_asset_endpoint(self, test_client, session): """Test for a single Asset.""" (asset,) = self.create_assets(session, num=1) event_payload = {"asset_id": asset.id, "extra": {"foo": "bar"}} asset_event_response = test_client.post("/assets/events", json=event_payload) asset_response = test_client.get(f"/assets/{asset.id}") assert asset_response.json()["last_asset_event"]["id"] == asset_event_response.json()["id"] assert ( asset_response.json()["last_asset_event"]["timestamp"] == asset_event_response.json()["timestamp"] ) def test_should_update_assets_endpoint(self, test_client, session): """Test for multiple Assets.""" asset1, asset2 = self.create_assets(session, num=2) # Now, only make a POST to the /assets/events endpoint for one of the Assets for _ in range(2): event_payload = {"asset_id": asset1.id, "extra": {"foo": "bar"}} asset_event_response = test_client.post("/assets/events", json=event_payload) assets_response = test_client.get("/assets") for asset in assets_response.json()["assets"]: # We should expect to see AssetEvents for the first Asset if asset["id"] == asset1.id: assert asset["last_asset_event"]["id"] == asset_event_response.json()["id"] assert asset["last_asset_event"]["timestamp"] == asset_event_response.json()["timestamp"] elif asset["id"] == asset2.id: assert asset["last_asset_event"]["id"] is None assert asset["last_asset_event"]["timestamp"] is None @pytest.mark.need_serialized_dag
TestPostAssetEvents
python
PyCQA__pylint
tests/functional/a/assigning/assigning_non_slot.py
{ "start": 1627, "end": 1993 }
class ____: """ Using properties in the body of the class is safe. """ __slots__ = ['_value'] def _getter(self): return self._value def _setter(self, value): # pylint: disable=attribute-defined-outside-init self._value = value test = property(_getter, _setter) def __init__(self): self.test = 24
PropertyGood2
python
tensorflow__tensorflow
tensorflow/python/keras/metrics.py
{ "start": 99976, "end": 100910 }
class ____(MeanMetricWrapper): """Computes the logarithm of the hyperbolic cosine of the prediction error. `logcosh = log((exp(x) + exp(-x))/2)`, where x is the error (y_pred - y_true) Args: name: (Optional) string name of the metric instance. dtype: (Optional) data type of the metric result. Standalone usage: >>> m = tf.keras.metrics.LogCoshError() >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]]) >>> m.result().numpy() 0.10844523 >>> m.reset_state() >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]], ... sample_weight=[1, 0]) >>> m.result().numpy() 0.21689045 Usage with `compile()` API: ```python model.compile(optimizer='sgd', loss='mse', metrics=[tf.keras.metrics.LogCoshError()]) ``` """ def __init__(self, name='logcosh', dtype=None): super(LogCoshError, self).__init__(logcosh, name, dtype=dtype)
LogCoshError
python
fluentpython__example-code-2e
22-dyn-attr-prop/oscon/schedule_v1.py
{ "start": 404, "end": 1028 }
class ____: def __init__(self, **kwargs): self.__dict__.update(kwargs) # <1> def __repr__(self): return f'<{self.__class__.__name__} serial={self.serial!r}>' # <2> def load(path=JSON_PATH): records = {} # <3> with open(path) as fp: raw_data = json.load(fp) # <4> for collection, raw_records in raw_data['Schedule'].items(): # <5> record_type = collection[:-1] # <6> for raw_record in raw_records: key = f'{record_type}.{raw_record["serial"]}' # <7> records[key] = Record(**raw_record) # <8> return records # end::SCHEDULE1[]
Record
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 303544, "end": 303729 }
class ____(VegaLiteSchema): """Datasets schema wrapper.""" _schema = {"$ref": "#/definitions/Datasets"} def __init__(self, **kwds): super().__init__(**kwds)
Datasets
python
mlflow__mlflow
mlflow/utils/openai_utils.py
{ "start": 3931, "end": 4417 }
class ____(NamedTuple): api_type: str batch_size: int max_requests_per_minute: int max_tokens_per_minute: int api_version: str | None api_base: str deployment_id: str | None organization: str | None = None max_retries: int = 5 timeout: float = 60.0 # See https://github.com/openai/openai-python/blob/cf03fe16a92cd01f2a8867537399c12e183ba58e/openai/__init__.py#L30-L38 # for the list of environment variables that openai-python uses
_OpenAIApiConfig
python
airbytehq__airbyte
airbyte-ci/connectors/connectors_qa/src/connectors_qa/checks/packaging.py
{ "start": 381, "end": 1869 }
class ____(PackagingCheck): name = "Connectors must use Poetry for dependency management" description = "Connectors must use [Poetry](https://python-poetry.org/) for dependency management. This is to ensure that all connectors use a dependency management tool which locks dependencies and ensures reproducible installs." requires_metadata = False runs_on_released_connectors = False applies_to_connector_languages = [ ConnectorLanguage.PYTHON, ConnectorLanguage.LOW_CODE, ] def _run(self, connector: Connector) -> CheckResult: if not (connector.code_directory / consts.PYPROJECT_FILE_NAME).exists(): return self.create_check_result( connector=connector, passed=False, message=f"{consts.PYPROJECT_FILE_NAME} file is missing", ) if not (connector.code_directory / consts.POETRY_LOCK_FILE_NAME).exists(): return self.fail(connector=connector, message=f"{consts.POETRY_LOCK_FILE_NAME} file is missing") if (connector.code_directory / consts.SETUP_PY_FILE_NAME).exists(): return self.fail( connector=connector, message=f"{consts.SETUP_PY_FILE_NAME} file exists. Please remove it and use {consts.PYPROJECT_FILE_NAME} instead", ) return self.pass_( connector=connector, message="Poetry is used for dependency management", )
CheckConnectorUsesPoetry
python
dagster-io__dagster
.buildkite/buildkite-shared/buildkite_shared/python_version.py
{ "start": 107, "end": 2376 }
class ____(Enum): # Ordering is important here, because some steps will take the highest/lowest available version. V3_10 = "3.10" V3_11 = "3.11" V3_12 = "3.12" V3_13 = "3.13" @classmethod def get_all(cls) -> list["AvailablePythonVersion"]: # omitting 3.11 for now to stay below buildkite limits return [cls["V3_10"], cls["V3_12"], cls["V3_13"]] @classmethod def get_default(cls) -> "AvailablePythonVersion": return cls["V3_12"] # Useful for providing to `PackageSpec.unsupported_python_versions` when you only want to test # the default version. @classmethod def get_all_except_default(cls) -> list["AvailablePythonVersion"]: return [v for v in cls.get_all() if v != cls.get_default()] @classmethod def get_pytest_defaults(cls) -> list["AvailablePythonVersion"]: branch_name = safe_getenv("BUILDKITE_BRANCH") commit_message = safe_getenv("BUILDKITE_MESSAGE") if is_release_branch(branch_name): return cls.get_all() else: # environment variable-specified defaults # branch name or commit message-specified defaults test_pythons = os.environ.get("TEST_PYTHON_VERSIONS", "") env_vars = [branch_name, commit_message, test_pythons] specified_versions: list[AvailablePythonVersion] = [] for version in cls.get_all(): marker = f"test-{cls.to_tox_factor(version)}" if any(marker in v for v in env_vars): specified_versions.append(version) if any("test-all" in v for v in env_vars): specified_versions += cls.get_all() return ( list(set(specified_versions)) if len(specified_versions) > 0 else [cls.get_default()] ) @classmethod def from_major_minor(cls, major: int, minor: int) -> "AvailablePythonVersion": key = f"V{major}_{minor}" return cls[key] @classmethod def to_tox_factor(cls, version: "AvailablePythonVersion") -> str: ver_parts = version.value.split(".") major, minor = ver_parts[0], ver_parts[1] return f"py{major}{minor}"
AvailablePythonVersion
python
PrefectHQ__prefect
tests/utilities/schema_tools/test_validation.py
{ "start": 53875, "end": 65090 }
class ____: async def test_pydantic_v1_single_type_tuple(self): """ single_type_tuple: tuple[str] """ schema = { "title": "Parameters", "type": "object", "properties": { "single_type_tuple": { "title": "single_type_tuple", "position": 0, "type": "array", "minItems": 1, "maxItems": 1, "items": [{"type": "string"}], } }, "required": ["single_type_tuple"], } # items cannot be an array with multiple # objects in Draft2020-12, so we change it to prefixItems preprocessed_schema = preprocess_schema(schema) assert preprocessed_schema == { "title": "Parameters", "type": "object", "properties": { "single_type_tuple": { "title": "single_type_tuple", "position": 0, "type": "array", "minItems": 1, "maxItems": 1, "prefixItems": [{"type": "string"}], } }, "required": ["single_type_tuple"], } async def test_pydantic_v1_union_type_tuple(self): """ union_type_tuple: [str | int] """ schema = { "title": "Parameters", "type": "object", "properties": { "union_type_tuple": { "title": "union_type_tuple", "position": 0, "type": "array", "minItems": 1, "maxItems": 1, "items": [{"anyOf": [{"type": "string"}, {"type": "integer"}]}], } }, "required": ["union_type_tuple"], } # items cannot be an array with multiple # objects in Draft2020-12, so we change it to prefixItems preprocessed_schema = preprocess_schema(schema) assert preprocessed_schema == { "title": "Parameters", "type": "object", "properties": { "union_type_tuple": { "title": "union_type_tuple", "position": 0, "type": "array", "minItems": 1, "maxItems": 1, "prefixItems": [ {"anyOf": [{"type": "string"}, {"type": "integer"}]} ], } }, "required": ["union_type_tuple"], } async def test_pydantic_v1_ordered_multi_type_tuple(self): """ ordered_multi_type_tuple: tuple[str, int] """ schema = { "title": "Parameters", "type": "object", "properties": { "ordered_multi_type_tuple": { "title": "ordered_multi_type_tuple", "position": 0, "type": "array", "minItems": 2, "maxItems": 2, "items": [{"type": "string"}, {"type": "integer"}], } }, "required": ["ordered_multi_type_tuple"], } # items cannot be an array with multiple # objects in Draft2020-12, so we change it to prefixItems preprocessed_schema = preprocess_schema(schema) assert preprocessed_schema == { "title": "Parameters", "type": "object", "properties": { "ordered_multi_type_tuple": { "title": "ordered_multi_type_tuple", "position": 0, "type": "array", "minItems": 2, "maxItems": 2, "prefixItems": [{"type": "string"}, {"type": "integer"}], } }, "required": ["ordered_multi_type_tuple"], } async def test_pydantic_v1_model_single_type_tuple(self): """ class MyModel(BaseModel): single_type_tuple: tuple[str] """ schema = { "title": "Parameters", "type": "object", "properties": { "param": { "title": "param", "position": 0, "allOf": [{"$ref": "#/definitions/MyModel"}], } }, "required": ["param"], "definitions": { "MyModel": { "title": "MyModel", "type": "object", "properties": { "single_type_tuple": { "title": "Single Type Tuple", "type": "array", "minItems": 1, "maxItems": 1, "items": [{"type": "string"}], } }, "required": ["single_type_tuple"], } }, } # items cannot be an array in Draft2020-12, so we change it to prefixItems preprocessed_schema = preprocess_schema(schema) assert preprocessed_schema == { "title": "Parameters", "type": "object", "properties": { "param": { "title": "param", "position": 0, "allOf": [{"$ref": "#/definitions/MyModel"}], } }, "required": ["param"], "definitions": { "MyModel": { "title": "MyModel", "type": "object", "properties": { "single_type_tuple": { "title": "Single Type Tuple", "type": "array", "minItems": 1, "maxItems": 1, "prefixItems": [{"type": "string"}], } }, "required": ["single_type_tuple"], } }, } async def test_pydantic_v1_model_union_type_tuple(self): """ class MyModel(BaseModel): union_type_tuple: tuple[str | int] """ schema = { "title": "Parameters", "type": "object", "properties": { "param": { "title": "param", "position": 0, "allOf": [{"$ref": "#/definitions/MyModel"}], } }, "required": ["param"], "definitions": { "MyModel": { "title": "MyModel", "type": "object", "properties": { "union_type_tuple": { "title": "Union Type Tuple", "type": "array", "minItems": 1, "maxItems": 1, "items": [ {"anyOf": [{"type": "string"}, {"type": "integer"}]} ], } }, "required": ["union_type_tuple"], } }, } # items cannot be an array with multiple # objects in Draft2020-12, so we change it to prefixItems preprocessed_schema = preprocess_schema(schema) assert preprocessed_schema == { "title": "Parameters", "type": "object", "properties": { "param": { "title": "param", "position": 0, "allOf": [{"$ref": "#/definitions/MyModel"}], } }, "required": ["param"], "definitions": { "MyModel": { "title": "MyModel", "type": "object", "properties": { "union_type_tuple": { "title": "Union Type Tuple", "type": "array", "minItems": 1, "maxItems": 1, "prefixItems": [ {"anyOf": [{"type": "string"}, {"type": "integer"}]} ], } }, "required": ["union_type_tuple"], } }, } async def test_pydantic_v1_model_ordered_multi_type_tuple(self): """ class MyModel(BaseModel): ordered_multi_type_tuple: tuple[str, int] """ schema = { "title": "Parameters", "type": "object", "properties": { "param": { "title": "param", "position": 0, "allOf": [{"$ref": "#/definitions/MyModel"}], } }, "required": ["param"], "definitions": { "MyModel": { "title": "MyModel", "type": "object", "properties": { "ordered_multi_type_tuple": { "title": "Ordered Multi Type Tuple", "type": "array", "minItems": 2, "maxItems": 2, "items": [{"type": "string"}, {"type": "integer"}], } }, "required": ["ordered_multi_type_tuple"], } }, } # items cannot be an array with multiple # objects in Draft2020-12, so we change it to prefixItems preprocessed_schema = preprocess_schema(schema) assert preprocessed_schema == { "title": "Parameters", "type": "object", "properties": { "param": { "title": "param", "position": 0, "allOf": [{"$ref": "#/definitions/MyModel"}], } }, "required": ["param"], "definitions": { "MyModel": { "title": "MyModel", "type": "object", "properties": { "ordered_multi_type_tuple": { "title": "Ordered Multi Type Tuple", "type": "array", "minItems": 2, "maxItems": 2, "prefixItems": [{"type": "string"}, {"type": "integer"}], } }, "required": ["ordered_multi_type_tuple"], } }, }
TestPreprocessSchemaPydanticV1Tuples
python
protocolbuffers__protobuf
python/google/protobuf/internal/containers.py
{ "start": 7937, "end": 12373 }
class ____(BaseContainer[_T], MutableSequence[_T]): """Simple, list-like container for holding repeated composite fields.""" # Disallows assignment to other attributes. __slots__ = ['_message_descriptor'] def __init__(self, message_listener: Any, message_descriptor: Any) -> None: """ Note that we pass in a descriptor instead of the generated directly, since at the time we construct a _RepeatedCompositeFieldContainer we haven't yet necessarily initialized the type that will be contained in the container. Args: message_listener: A MessageListener implementation. The RepeatedCompositeFieldContainer will call this object's Modified() method when it is modified. message_descriptor: A Descriptor instance describing the protocol type that should be present in this container. We'll use the _concrete_class field of this descriptor when the client calls add(). """ super().__init__(message_listener) self._message_descriptor = message_descriptor def add(self, **kwargs: Any) -> _T: """Adds a new element at the end of the list and returns it. Keyword arguments may be used to initialize the element. """ new_element = self._message_descriptor._concrete_class(**kwargs) new_element._SetListener(self._message_listener) self._values.append(new_element) if not self._message_listener.dirty: self._message_listener.Modified() return new_element def append(self, value: _T) -> None: """Appends one element by copying the message.""" new_element = self._message_descriptor._concrete_class() new_element._SetListener(self._message_listener) new_element.CopyFrom(value) self._values.append(new_element) if not self._message_listener.dirty: self._message_listener.Modified() def insert(self, key: int, value: _T) -> None: """Inserts the item at the specified position by copying.""" new_element = self._message_descriptor._concrete_class() new_element._SetListener(self._message_listener) new_element.CopyFrom(value) self._values.insert(key, new_element) if not self._message_listener.dirty: self._message_listener.Modified() def extend(self, elem_seq: Iterable[_T]) -> None: """Extends by appending the given sequence of elements of the same type as this one, copying each individual message. """ message_class = self._message_descriptor._concrete_class listener = self._message_listener values = self._values for message in elem_seq: new_element = message_class() new_element._SetListener(listener) new_element.MergeFrom(message) values.append(new_element) listener.Modified() def MergeFrom( self, other: Union['RepeatedCompositeFieldContainer[_T]', Iterable[_T]], ) -> None: """Appends the contents of another repeated field of the same type to this one, copying each individual message. """ self.extend(other) def remove(self, elem: _T) -> None: """Removes an item from the list. Similar to list.remove().""" self._values.remove(elem) self._message_listener.Modified() def pop(self, key: Optional[int] = -1) -> _T: """Removes and returns an item at a given index. Similar to list.pop().""" value = self._values[key] self.__delitem__(key) return value @overload def __setitem__(self, key: int, value: _T) -> None: ... @overload def __setitem__(self, key: slice, value: Iterable[_T]) -> None: ... def __setitem__(self, key, value): # This method is implemented to make RepeatedCompositeFieldContainer # structurally compatible with typing.MutableSequence. It is # otherwise unsupported and will always raise an error. raise TypeError( f'{self.__class__.__name__} object does not support item assignment') def __delitem__(self, key: Union[int, slice]) -> None: """Deletes the item at the specified position.""" del self._values[key] self._message_listener.Modified() def __eq__(self, other: Any) -> bool: """Compares the current instance with another one.""" if self is other: return True if not isinstance(other, self.__class__): raise TypeError('Can only compare repeated composite fields against ' 'other repeated composite fields.') return self._values == other._values
RepeatedCompositeFieldContainer
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/call3.py
{ "start": 1698, "end": 1786 }
class ____: def f( self, y: Any, ): ... c1: P1 = C1()
C1
python
getsentry__sentry
tests/sentry/tasks/test_user_report.py
{ "start": 166, "end": 309 }
class ____(TestCase): def test_task_persistent_name(self) -> None: assert user_report.name == "sentry.tasks.user_report"
UserReportTest
python
huggingface__transformers
src/transformers/models/idefics3/modeling_idefics3.py
{ "start": 33346, "end": 43450 }
class ____(Idefics3PreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.text_model.embed_tokens.weight"} # Copied from transformers.models.idefics2.modeling_idefics2.Idefics2ForConditionalGeneration.__init__ with Idefics2->Idefics3 def __init__(self, config): super().__init__(config) self.model = Idefics3Model(config) self.image_token_id = self.config.image_token_id self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False) self.vocab_size = config.text_config.vocab_size # Initialize weights and apply final processing self.post_init() # Copied from transformers.models.idefics2.modeling_idefics2.Idefics2ForConditionalGeneration.enable_input_require_grads def enable_input_require_grads(self): """ Enables the gradients for the input embeddings. This is useful for fine-tuning adapter weights while keeping the model weights fixed. """ def make_inputs_require_grads(module, input, output): output.requires_grad_(True) self._text_require_grads_hook = self.get_input_embeddings().register_forward_hook(make_inputs_require_grads) self._vision_require_grads_hook = self.model.vision_model.get_input_embeddings().register_forward_hook( make_inputs_require_grads ) # Copied from transformers.models.idefics2.modeling_idefics2.Idefics2ForConditionalGeneration.disable_input_require_grads def disable_input_require_grads(self): self._text_require_grads_hook.remove() self._vision_require_grads_hook.remove() # Copied from transformers.models.idefics2.modeling_idefics2.Idefics2ForConditionalGeneration.get_input_embeddings def get_input_embeddings(self): return self.model.text_model.get_input_embeddings() # Copied from transformers.models.idefics2.modeling_idefics2.Idefics2ForConditionalGeneration.set_input_embeddings def set_input_embeddings(self, value): self.model.text_model.set_input_embeddings(value) def get_image_features( self, pixel_values: torch.FloatTensor, pixel_attention_mask: Optional[torch.LongTensor] = None ): return self.model.get_image_features(pixel_values=pixel_values, pixel_attention_mask=pixel_attention_mask) @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, pixel_values: Optional[torch.FloatTensor] = None, pixel_attention_mask: Optional[torch.BoolTensor] = None, image_hidden_states: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, return_dict: Optional[bool] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple, Idefics3CausalLMOutputWithPast]: r""" pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*): Mask to avoid performing attention on padding pixel indices. image_hidden_states (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`): The hidden states of the image encoder after modality projection. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or `model.image_token_id` (where `model` is your instance of `Idefics3ForConditionalGeneration`). Tokens with indices set to `model.image_token_id` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. Example: ```python >>> import requests >>> import torch >>> from PIL import Image >>> from io import BytesIO >>> from transformers import AutoProcessor, AutoModelForImageTextToText >>> from transformers.image_utils import load_image >>> # Note that passing the image urls (instead of the actual pil images) to the processor is also possible >>> image1 = load_image("https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg") >>> image2 = load_image("https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg") >>> image3 = load_image("https://cdn.britannica.com/68/170868-050-8DDE8263/Golden-Gate-Bridge-San-Francisco.jpg") >>> processor = AutoProcessor.from_pretrained("HuggingFaceM4/Idefics3-8B-Llama3") >>> model = AutoModelForImageTextToText.from_pretrained("HuggingFaceM4/Idefics3-8B-Llama3", dtype=torch.bfloat16, device_map="auto") >>> # Create inputs >>> messages = [ ... { ... "role": "user", ... "content": [ ... {"type": "image"}, ... {"type": "text", "text": "In this image, we can see the city of New York, and more specifically the Statue of Liberty."}, ... {"type": "image"}, ... {"type": "text", "text": "What can we see in this image?"}, ... ] ... }, ... { ... "role": "user", ... "content": [ ... {"type": "image"}, ... {"type": "text", "text": "In which city is that bridge located?"}, ... ] ... } ... ] >>> prompts = [processor.apply_chat_template([message], add_generation_prompt=True) for message in messages] >>> images = [[image1, image2], [image3]] >>> inputs = processor(text=prompts, images=images, padding=True, return_tensors="pt").to(model.device) >>> # Generate >>> generated_ids = model.generate(**inputs, max_new_tokens=256) >>> generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True) >>> print(generated_texts[0]) Assistant: There are buildings, trees, lights, and water visible in this image. >>> print(generated_texts[1]) Assistant: The bridge is in San Francisco. ```""" output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) outputs = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, pixel_values=pixel_values, pixel_attention_mask=pixel_attention_mask, image_hidden_states=image_hidden_states, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, cache_position=cache_position, return_dict=True, **kwargs, ) hidden_states = outputs[0] # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :]) loss = None if labels is not None: loss = self.loss_function( logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs ) return Idefics3CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, image_hidden_states=outputs.image_hidden_states, ) # Copied from transformers.models.idefics2.modeling_idefics2.Idefics2ForConditionalGeneration.prepare_inputs_for_generation def prepare_inputs_for_generation( self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, pixel_values=None, pixel_attention_mask=None, image_hidden_states=None, logits_to_keep=None, **kwargs, ): # Overwritten -- there are mutually exclusive inputs (if the logic to make `image_hidden_states` take # precedence is moved to the model, we can remove this fn) model_inputs = super().prepare_inputs_for_generation( input_ids, past_key_values=past_key_values, attention_mask=attention_mask, inputs_embeds=inputs_embeds, cache_position=cache_position, pixel_values=pixel_values, pixel_attention_mask=pixel_attention_mask, image_hidden_states=image_hidden_states, logits_to_keep=logits_to_keep, **kwargs, ) if image_hidden_states is not None or cache_position[0] != 0: model_inputs["pixel_values"] = None model_inputs["pixel_attention_mask"] = None return model_inputs __all__ = ["Idefics3ForConditionalGeneration", "Idefics3PreTrainedModel", "Idefics3Model", "Idefics3VisionTransformer"]
Idefics3ForConditionalGeneration
python
pandas-dev__pandas
pandas/io/excel/_xlsxwriter.py
{ "start": 6035, "end": 9380 }
class ____(ExcelWriter): _engine = "xlsxwriter" _supported_extensions = (".xlsx",) def __init__( # pyright: ignore[reportInconsistentConstructor] self, path: FilePath | WriteExcelBuffer | ExcelWriter, engine: str | None = None, date_format: str | None = None, datetime_format: str | None = None, mode: str = "w", storage_options: StorageOptions | None = None, if_sheet_exists: ExcelWriterIfSheetExists | None = None, engine_kwargs: dict[str, Any] | None = None, **kwargs, ) -> None: # Use the xlsxwriter module as the Excel writer. from xlsxwriter import Workbook engine_kwargs = combine_kwargs(engine_kwargs, kwargs) if mode == "a": raise ValueError("Append mode is not supported with xlsxwriter!") super().__init__( path, engine=engine, date_format=date_format, datetime_format=datetime_format, mode=mode, storage_options=storage_options, if_sheet_exists=if_sheet_exists, engine_kwargs=engine_kwargs, ) try: self._book = Workbook(self._handles.handle, **engine_kwargs) except TypeError: self._handles.handle.close() raise @property def book(self): """ Book instance of class xlsxwriter.Workbook. This attribute can be used to access engine-specific features. """ return self._book @property def sheets(self) -> dict[str, Any]: result = self.book.sheetnames return result def _save(self) -> None: """ Save workbook to disk. """ self.book.close() def _write_cells( self, cells, sheet_name: str | None = None, startrow: int = 0, startcol: int = 0, freeze_panes: tuple[int, int] | None = None, autofilter_range: str | None = None, ) -> None: # Write the frame cells using xlsxwriter. sheet_name = self._get_sheet_name(sheet_name) wks = self.book.get_worksheet_by_name(sheet_name) if wks is None: wks = self.book.add_worksheet(sheet_name) style_dict = {"null": None} if validate_freeze_panes(freeze_panes): wks.freeze_panes(*(freeze_panes)) for cell in cells: val, fmt = self._value_with_fmt(cell.val) stylekey = json.dumps(cell.style) if fmt: stylekey += fmt if stylekey in style_dict: style = style_dict[stylekey] else: style = self.book.add_format(_XlsxStyler.convert(cell.style, fmt)) style_dict[stylekey] = style if cell.mergestart is not None and cell.mergeend is not None: wks.merge_range( startrow + cell.row, startcol + cell.col, startrow + cell.mergestart, startcol + cell.mergeend, val, style, ) else: wks.write(startrow + cell.row, startcol + cell.col, val, style) if autofilter_range: wks.autofilter(autofilter_range)
XlsxWriter
python
pytorch__pytorch
torch/_inductor/fx_passes/group_batch_fusion.py
{ "start": 31074, "end": 38855 }
class ____(BatchFusion): """ Batch layer norm fusion in pre grad pass """ def match(self, node: torch.fx.Node): if CallFunctionVarArgs(torch.nn.functional.layer_norm).match(node): input = get_arg_value(node, 0, "input") weight = get_arg_value(node, 2, "weight") bias = get_arg_value(node, 3, "bias") if self.graph_search_options.get("fuse_nodes_with_same_users", False): users = [user.target for user in node.users] else: users = "" # type: ignore[assignment] group_key = ( ( "batch_layernorm", str(input.meta["example_value"].shape), str(weight.meta["example_value"].shape) if weight is not None else "", str(bias.meta["example_value"].shape) if bias is not None else "", str(get_arg_value(node, 1, "normalized_shape")), str(get_arg_value(node, 4, "eps")), str(users), ) if "example_value" in input.meta and is_node_meta_valid(weight) and is_node_meta_valid(bias) else None ) else: group_key = None return group_key def fuse(self, graph: torch.fx.GraphModule, subset: list[torch.fx.Node]): group_inputs = [] group_shapes = [] group_weights = [] group_biases = [] group_epss = [] group_nodes = [] group_inputs_metadata = [] group_biases_metadata = [] group_weights_metadata = [] for node in subset: group_nodes.append(node) input = get_arg_value(node, 0, "input") group_inputs.append(input) group_inputs_metadata.append(input.meta["example_value"]) group_shapes.append(get_arg_value(node, 1, "normalized_shape")) weight = get_arg_value(node, 2, "weight") group_weights.append(weight) if weight is not None and hasattr(weight, "meta"): group_weights_metadata.append(weight.meta["example_value"]) bias = get_arg_value(node, 3, "bias") group_biases.append(bias) if bias is not None and hasattr(bias, "meta"): group_biases_metadata.append(bias.meta["example_value"]) eps = get_arg_value(node, 4, "eps") if eps is None: eps = 1e-5 group_epss.append(eps) stack_dim = -1 - len(group_shapes[-1]) if all(bias is None for bias in group_biases): group_biases = None # type: ignore[assignment] if all(weight is None for weight in group_weights): group_weights = None # type: ignore[assignment] assert all(eps == group_epss[0] for eps in group_epss), ( "all epsilon values must be equal" ) with graph.inserting_before(subset[0]): # type: ignore[operator] stack_input = graph.call_function( # type: ignore[operator] torch.stack, args=(group_inputs,), kwargs={"dim": stack_dim} ) update_stack_example_value(stack_input, group_inputs_metadata, stack_dim) if group_weights is not None: stack_weight = graph.call_function( # type: ignore[operator] torch.stack, args=(group_weights,), kwargs={"dim": 0} ) update_stack_example_value(stack_weight, group_weights_metadata) else: stack_weight = None if group_biases is not None: stack_bias = graph.call_function( # type: ignore[operator] torch.stack, args=(group_biases,), kwargs={"dim": 0} ) update_stack_example_value(stack_bias, group_biases_metadata) else: stack_bias = None batch_layer_norm = graph.call_function( # type: ignore[operator] torch.nn.functional.layer_norm, args=(stack_input, group_shapes[-1]), kwargs={"eps": group_epss[-1]}, ) batch_layer_norm.meta["example_value"] = stack_input.meta["example_value"] if group_weights is not None and group_biases is not None: previous_batch_layer_norm_meta = batch_layer_norm.meta["example_value"] batch_layer_norm = graph.call_function( # type: ignore[operator] torch.mul, args=(stack_weight, batch_layer_norm) ) update_pointwise_example_value( batch_layer_norm, # pyrefly: ignore [missing-attribute] stack_weight.meta["example_value"], previous_batch_layer_norm_meta, torch.mul, ) previous_batch_layer_norm_meta = batch_layer_norm.meta["example_value"] batch_layer_norm = graph.call_function( # type: ignore[operator] torch.add, args=(stack_bias, batch_layer_norm) ) update_pointwise_example_value( batch_layer_norm, # pyrefly: ignore [missing-attribute] stack_bias.meta["example_value"], previous_batch_layer_norm_meta, torch.add, ) elif group_weights is not None and group_biases is None: previous_batch_layer_norm_meta = batch_layer_norm.meta["example_value"] # pyrefly: ignore [not-callable] batch_layer_norm = graph.call_function( torch.mul, args=(stack_weight, batch_layer_norm) ) update_pointwise_example_value( batch_layer_norm, # pyrefly: ignore [missing-attribute] stack_weight.meta["example_value"], previous_batch_layer_norm_meta, torch.mul, ) elif group_weights is None and group_biases is not None: previous_batch_layer_norm_meta = batch_layer_norm.meta["example_value"] # pyrefly: ignore [not-callable] batch_layer_norm = graph.call_function( torch.add, args=(stack_bias, batch_layer_norm) ) update_pointwise_example_value( batch_layer_norm, # pyrefly: ignore [missing-attribute] stack_bias.meta["example_value"], previous_batch_layer_norm_meta, torch.add, ) batch_layer_norm_unbind = graph.call_function( # type: ignore[operator] torch.unbind, args=(batch_layer_norm,), kwargs={"dim": stack_dim}, ) update_stack_example_value( batch_layer_norm_unbind, batch_layer_norm.meta["example_value"], op=torch.unbind, dim=stack_dim, ) for i, node in enumerate(group_nodes): with graph.inserting_after(batch_layer_norm_unbind): # type: ignore[operator] new_node = graph.call_function( # type: ignore[operator] operator.getitem, args=(batch_layer_norm_unbind, i) ) node.replace_all_uses_with(new_node) new_node.meta.update(node.meta) graph.erase_node(node) # type: ignore[operator] counters["inductor"]["batch_layernorm"] += 1
BatchLayernormFusion
python
doocs__leetcode
solution/0100-0199/0128.Longest Consecutive Sequence/Solution.py
{ "start": 0, "end": 343 }
class ____: def longestConsecutive(self, nums: List[int]) -> int: s = set(nums) ans = 0 d = defaultdict(int) for x in nums: y = x while y in s: s.remove(y) y += 1 d[x] = d[y] + y - x ans = max(ans, d[x]) return ans
Solution
python
euske__pdfminer
pdfminer/converter.py
{ "start": 651, "end": 4270 }
class ____(PDFTextDevice): def __init__(self, rsrcmgr, pageno=1, laparams=None): PDFTextDevice.__init__(self, rsrcmgr) self.pageno = pageno self.laparams = laparams self._stack = [] return def begin_page(self, page, ctm): (x0, y0, x1, y1) = page.mediabox (x0, y0) = apply_matrix_pt(ctm, (x0, y0)) (x1, y1) = apply_matrix_pt(ctm, (x1, y1)) mediabox = (0, 0, abs(x0-x1), abs(y0-y1)) self.cur_item = LTPage(self.pageno, mediabox) return def end_page(self, page): assert not self._stack assert isinstance(self.cur_item, LTPage) if self.laparams is not None: self.cur_item.analyze(self.laparams) self.pageno += 1 self.receive_layout(self.cur_item) return def begin_figure(self, name, bbox, matrix): self._stack.append(self.cur_item) self.cur_item = LTFigure(name, bbox, mult_matrix(matrix, self.ctm)) return def end_figure(self, _): fig = self.cur_item assert isinstance(self.cur_item, LTFigure) self.cur_item = self._stack.pop() self.cur_item.add(fig) return def render_image(self, name, stream): assert isinstance(self.cur_item, LTFigure) item = LTImage(name, stream, (self.cur_item.x0, self.cur_item.y0, self.cur_item.x1, self.cur_item.y1)) self.cur_item.add(item) return def paint_path(self, gstate, stroke, fill, evenodd, path): shape = ''.join(x[0] for x in path) if shape == 'ml': # horizontal/vertical line (_, x0, y0) = path[0] (_, x1, y1) = path[1] (x0, y0) = apply_matrix_pt(self.ctm, (x0, y0)) (x1, y1) = apply_matrix_pt(self.ctm, (x1, y1)) if x0 == x1 or y0 == y1: self.cur_item.add(LTLine(gstate.linewidth, (x0, y0), (x1, y1))) return if shape == 'mlllh': # rectangle (_, x0, y0) = path[0] (_, x1, y1) = path[1] (_, x2, y2) = path[2] (_, x3, y3) = path[3] (x0, y0) = apply_matrix_pt(self.ctm, (x0, y0)) (x1, y1) = apply_matrix_pt(self.ctm, (x1, y1)) (x2, y2) = apply_matrix_pt(self.ctm, (x2, y2)) (x3, y3) = apply_matrix_pt(self.ctm, (x3, y3)) if ((x0 == x1 and y1 == y2 and x2 == x3 and y3 == y0) or (y0 == y1 and x1 == x2 and y2 == y3 and x3 == x0)): self.cur_item.add(LTRect(gstate.linewidth, (x0, y0, x2, y2))) return # other shapes pts = [] for p in path: for i in range(1, len(p), 2): pts.append(apply_matrix_pt(self.ctm, (p[i], p[i+1]))) self.cur_item.add(LTCurve(gstate.linewidth, pts)) return def render_char(self, matrix, font, fontsize, scaling, rise, cid): try: text = font.to_unichr(cid) assert isinstance(text, str), text except PDFUnicodeNotDefined: text = self.handle_undefined_char(font, cid) textwidth = font.char_width(cid) textdisp = font.char_disp(cid) item = LTChar(matrix, font, fontsize, scaling, rise, text, textwidth, textdisp) self.cur_item.add(item) return item.adv def handle_undefined_char(self, font, cid): logging.info('undefined: %r, %r' % (font, cid)) return f'(cid:{cid})' def receive_layout(self, ltpage): return ## PDFPageAggregator ##
PDFLayoutAnalyzer
python
tensorflow__tensorflow
tensorflow/python/client/device_lib_test.py
{ "start": 977, "end": 1564 }
class ____(test_util.TensorFlowTestCase): def testListLocalDevices(self): devices = device_lib.list_local_devices() self.assertGreater(len(devices), 0) self.assertEqual(devices[0].device_type, "CPU") devices = device_lib.list_local_devices(config_pb2.ConfigProto()) self.assertGreater(len(devices), 0) self.assertEqual(devices[0].device_type, "CPU") # GPU test if test.is_gpu_available(): self.assertGreater(len(devices), 1) self.assertIn("GPU", [d.device_type for d in devices]) if __name__ == "__main__": googletest.main()
DeviceLibTest
python
coleifer__peewee
peewee.py
{ "start": 147987, "end": 149031 }
class ____(object): def __init__(self, db, sid=None): self.db = db self.sid = sid or 's' + uuid.uuid4().hex self.quoted_sid = self.sid.join(self.db.quote) def __call__(self, fn): @wraps(fn) def inner(*args, **kwargs): with _savepoint(self.db): return fn(*args, **kwargs) return inner def _begin(self): self.db.execute_sql('SAVEPOINT %s;' % self.quoted_sid) def commit(self, begin=True): self.db.execute_sql('RELEASE SAVEPOINT %s;' % self.quoted_sid) if begin: self._begin() def rollback(self): self.db.execute_sql('ROLLBACK TO SAVEPOINT %s;' % self.quoted_sid) def __enter__(self): self._begin() return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type: self.rollback() else: try: self.commit(begin=False) except: self.rollback() raise # CURSOR REPRESENTATIONS.
_savepoint
python
ray-project__ray
release/llm_tests/serve/probes/test_json_mode.py
{ "start": 1244, "end": 1601 }
class ____(BaseModel): """The format of the answer.""" winner_team_name: str = Field(description="Name of the winning team") loser_team_name: str = Field(description="Name of the losing team") winner_score: int = Field(description="Score of the winning team") loser_score: int = Field(description="Score of the losing team")
BasicResponse
python
gevent__gevent
src/gevent/tests/test__threading_fork_from_dummy.py
{ "start": 411, "end": 2181 }
class ____(greentest.TestCase): def test_fork_from_dummy_thread(self): import os import threading import contextlib import gevent from gevent.threading import _DummyThread if not _DummyThread._NEEDS_CLASS_FORK_FIXUP: self.skipTest('No patch need be applied') def do_it(out): # Be sure we've put the DummyThread in the threading # maps assert isinstance(threading.current_thread(), threading._DummyThread) with open(out, 'wt', encoding='utf-8') as f: with contextlib.redirect_stderr(f): r = os.fork() if r == 0: # In the child. # Our stderr redirect above will capture the # "Exception ignored in _after_fork()" that the interpreter # prints; actually printing the main_thread will result in # raising an exception if our patch doesn't work. main = threading.main_thread() print(main, file=f) print(type(main), file=f) return r with tempfile.NamedTemporaryFile('w+t', suffix='.gevent_threading.txt') as tf: glet = gevent.spawn(do_it, tf.name) glet.join() pid = glet.get() if pid == 0: # Dump the child process quickly os._exit(0) os.waitpid(pid, 0) tf.seek(0, 0) contents = tf.read() self.assertIn("<class 'threading._MainThread'>", contents) self.assertNotIn("_DummyThread", contents) if __name__ == '__main__': unittest.main()
Test
python
milvus-io__pymilvus
pymilvus/client/grpc_handler.py
{ "start": 3921, "end": 93038 }
class ____: # pylint: disable=too-many-instance-attributes def __init__( self, uri: str = Config.GRPC_URI, host: str = "", port: str = "", channel: Optional[grpc.Channel] = None, **kwargs, ) -> None: self._stub = None self._channel = channel addr = kwargs.get("address") self._address = addr if addr is not None else self.__get_address(uri, host, port) self._log_level = None self._user = kwargs.get("user") self._set_authorization(**kwargs) self._setup_db_interceptor(kwargs.get("db_name")) self._setup_grpc_channel() self.callbacks = [] self.schema_cache = {} self._reconnect_handler = None def register_reconnect_handler(self, handler: ReconnectHandler): if handler is not None: self._reconnect_handler = handler self.register_state_change_callback(handler.reconnect_on_idle) def register_state_change_callback(self, callback: Callable): self.callbacks.append(callback) self._channel.subscribe(callback, try_to_connect=True) def deregister_state_change_callbacks(self): for callback in self.callbacks: self._channel.unsubscribe(callback) self.callbacks = [] def __get_address(self, uri: str, host: str, port: str) -> str: if host != "" and port != "" and is_legal_host(host) and is_legal_port(port): return f"{host}:{port}" try: parsed_uri = parse.urlparse(uri) except Exception as e: raise ParamError(message=f"Illegal uri: [{uri}], {e}") from e return parsed_uri.netloc def _set_authorization(self, **kwargs): secure = kwargs.get("secure", False) if not isinstance(secure, bool): raise ParamError(message="secure must be bool type") self._secure = secure self._client_pem_path = kwargs.get("client_pem_path", "") self._client_key_path = kwargs.get("client_key_path", "") self._ca_pem_path = kwargs.get("ca_pem_path", "") self._server_pem_path = kwargs.get("server_pem_path", "") self._server_name = kwargs.get("server_name", "") self._authorization_interceptor = None self._setup_authorization_interceptor( kwargs.get("user"), kwargs.get("password"), kwargs.get("token"), ) def __enter__(self): return self def __exit__(self: object, exc_type: object, exc_val: object, exc_tb: object): pass def _wait_for_channel_ready(self, timeout: Union[float] = 10): if self._channel is None: raise MilvusException( code=Status.CONNECT_FAILED, message="No channel in handler, please setup grpc channel first", ) try: grpc.channel_ready_future(self._channel).result(timeout=timeout) self._setup_identifier_interceptor(self._user, timeout=timeout) except grpc.FutureTimeoutError as e: self.close() raise MilvusException( code=Status.CONNECT_FAILED, message=f"Fail connecting to server on {self._address}, illegal connection params or server unavailable", ) from e except Exception as e: self.close() raise e from e def close(self): self.deregister_state_change_callbacks() if self._channel: self._channel.close() self._channel = None def reset_db_name(self, db_name: str): self.schema_cache.clear() self._setup_db_interceptor(db_name) self._setup_grpc_channel() self._setup_identifier_interceptor(self._user) if self._reconnect_handler is not None: self._reconnect_handler.reset_db_name(db_name) def _setup_authorization_interceptor(self, user: str, password: str, token: str): keys = [] values = [] if token: authorization = base64.b64encode(f"{token}".encode()) keys.append("authorization") values.append(authorization) elif user and password: authorization = base64.b64encode(f"{user}:{password}".encode()) keys.append("authorization") values.append(authorization) if len(keys) > 0 and len(values) > 0: self._authorization_interceptor = interceptor.header_adder_interceptor(keys, values) def _setup_db_interceptor(self, db_name: str): if db_name is None: self._db_interceptor = None else: check_pass_param(db_name=db_name) self._db_interceptor = interceptor.header_adder_interceptor(["dbname"], [db_name]) def _setup_grpc_channel(self): """Create a ddl grpc channel""" if self._channel is None: opts = [ (cygrpc.ChannelArgKey.max_send_message_length, -1), (cygrpc.ChannelArgKey.max_receive_message_length, -1), ("grpc.enable_retries", 1), ("grpc.keepalive_time_ms", 55000), ] if not self._secure: self._channel = grpc.insecure_channel( self._address, options=opts, ) else: if self._server_name != "": opts.append(("grpc.ssl_target_name_override", self._server_name)) root_cert, private_k, cert_chain = None, None, None if self._server_pem_path != "": with Path(self._server_pem_path).open("rb") as f: root_cert = f.read() elif ( self._client_pem_path != "" and self._client_key_path != "" and self._ca_pem_path != "" ): with Path(self._ca_pem_path).open("rb") as f: root_cert = f.read() with Path(self._client_key_path).open("rb") as f: private_k = f.read() with Path(self._client_pem_path).open("rb") as f: cert_chain = f.read() creds = grpc.ssl_channel_credentials( root_certificates=root_cert, private_key=private_k, certificate_chain=cert_chain, ) self._channel = grpc.secure_channel( self._address, creds, options=opts, ) # avoid to add duplicate headers. self._final_channel = self._channel if self._authorization_interceptor: self._final_channel = grpc.intercept_channel( self._final_channel, self._authorization_interceptor ) if self._db_interceptor: self._final_channel = grpc.intercept_channel(self._final_channel, self._db_interceptor) if self._log_level: log_level_interceptor = interceptor.header_adder_interceptor( ["log_level"], [self._log_level] ) self._final_channel = grpc.intercept_channel(self._final_channel, log_level_interceptor) self._log_level = None self._stub = milvus_pb2_grpc.MilvusServiceStub(self._final_channel) def set_onetime_loglevel(self, log_level: str): self._log_level = log_level self._setup_grpc_channel() def _setup_identifier_interceptor(self, user: str, timeout: int = 10): host = socket.gethostname() self._identifier = self.__internal_register(user, host, timeout=timeout) self._identifier_interceptor = interceptor.header_adder_interceptor( ["identifier"], [str(self._identifier)] ) self._final_channel = grpc.intercept_channel( self._final_channel, self._identifier_interceptor ) self._stub = milvus_pb2_grpc.MilvusServiceStub(self._final_channel) @property def server_address(self): return self._address def get_server_type(self): return get_server_type(self.server_address.split(":")[0]) def reset_password( self, user: str, old_password: str, new_password: str, timeout: Optional[float] = None, **kwargs, ): """ reset password and then setup the grpc channel. """ self.update_password(user, old_password, new_password, timeout=timeout, **kwargs) self._setup_authorization_interceptor(user, new_password, None) self._setup_grpc_channel() @retry_on_rpc_failure() def create_collection( self, collection_name: str, fields: Union[CollectionSchema, Dict[str, Iterable]], timeout: Optional[float] = None, **kwargs, ): check_pass_param(collection_name=collection_name, timeout=timeout) request = Prepare.create_collection_request(collection_name, fields, **kwargs) rf = self._stub.CreateCollection.future( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) if kwargs.get("_async", False): return rf status = rf.result() check_status(status) return None @retry_on_rpc_failure() def drop_collection(self, collection_name: str, timeout: Optional[float] = None, **kwargs): check_pass_param(collection_name=collection_name, timeout=timeout) request = Prepare.drop_collection_request(collection_name) status = self._stub.DropCollection( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(status) if collection_name in self.schema_cache: self.schema_cache.pop(collection_name) @retry_on_rpc_failure() def add_collection_field( self, collection_name: str, field_schema: FieldSchema, timeout: Optional[float] = None, **kwargs, ): check_pass_param(collection_name=collection_name, timeout=timeout) request = Prepare.add_collection_field_request(collection_name, field_schema) status = self._stub.AddCollectionField( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(status) @retry_on_rpc_failure() def alter_collection_properties( self, collection_name: str, properties: List, timeout: Optional[float] = None, **kwargs ): check_pass_param(collection_name=collection_name, properties=properties, timeout=timeout) request = Prepare.alter_collection_request(collection_name, properties=properties) status = self._stub.AlterCollection( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(status) @retry_on_rpc_failure() def alter_collection_field_properties( self, collection_name: str, field_name: str, field_params: Dict[str, Any], timeout: Optional[float] = None, **kwargs, ): check_pass_param(collection_name=collection_name, properties=field_params, timeout=timeout) request = Prepare.alter_collection_field_request( collection_name=collection_name, field_name=field_name, field_param=field_params ) status = self._stub.AlterCollectionField( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(status) @retry_on_rpc_failure() def drop_collection_properties( self, collection_name: str, property_keys: List[str], timeout: Optional[float] = None, **kwargs, ): check_pass_param(collection_name=collection_name, timeout=timeout) request = Prepare.alter_collection_request(collection_name, delete_keys=property_keys) status = self._stub.AlterCollection( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(status) @retry_on_rpc_failure() def has_collection(self, collection_name: str, timeout: Optional[float] = None, **kwargs): check_pass_param(collection_name=collection_name, timeout=timeout) request = Prepare.describe_collection_request(collection_name) reply = self._stub.DescribeCollection( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) # For compatibility with Milvus less than 2.3.2, which does not support status.code. if ( reply.status.error_code == common_pb2.UnexpectedError and "can't find collection" in reply.status.reason ): return False if reply.status.error_code == common_pb2.CollectionNotExists: return False if is_successful(reply.status): return True if reply.status.code == ErrorCode.COLLECTION_NOT_FOUND: return False raise MilvusException(reply.status.code, reply.status.reason, reply.status.error_code) @retry_on_rpc_failure() def describe_collection(self, collection_name: str, timeout: Optional[float] = None, **kwargs): check_pass_param(collection_name=collection_name, timeout=timeout) request = Prepare.describe_collection_request(collection_name) response = self._stub.DescribeCollection( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) status = response.status if is_successful(status): return CollectionSchema(raw=response).dict() raise DescribeCollectionException(status.code, status.reason, status.error_code) @retry_on_rpc_failure() def list_collections(self, timeout: Optional[float] = None, **kwargs): request = Prepare.show_collections_request() response = self._stub.ShowCollections( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) status = response.status check_status(status) return list(response.collection_names) @retry_on_rpc_failure() def rename_collections( self, old_name: str, new_name: str, new_db_name: str = "", timeout: Optional[float] = None, **kwargs, ): check_pass_param(collection_name=new_name, timeout=timeout) check_pass_param(collection_name=old_name) if new_db_name: check_pass_param(db_name=new_db_name) request = Prepare.rename_collections_request(old_name, new_name, new_db_name) status = self._stub.RenameCollection( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(status) @retry_on_rpc_failure() def create_partition( self, collection_name: str, partition_name: str, timeout: Optional[float] = None, **kwargs ): check_pass_param( collection_name=collection_name, partition_name=partition_name, timeout=timeout ) request = Prepare.create_partition_request(collection_name, partition_name) response = self._stub.CreatePartition( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(response) @retry_on_rpc_failure() def drop_partition( self, collection_name: str, partition_name: str, timeout: Optional[float] = None, **kwargs ): check_pass_param( collection_name=collection_name, partition_name=partition_name, timeout=timeout ) request = Prepare.drop_partition_request(collection_name, partition_name) response = self._stub.DropPartition( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(response) @retry_on_rpc_failure() def has_partition( self, collection_name: str, partition_name: str, timeout: Optional[float] = None, **kwargs ): check_pass_param( collection_name=collection_name, partition_name=partition_name, timeout=timeout ) request = Prepare.has_partition_request(collection_name, partition_name) response = self._stub.HasPartition( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) status = response.status check_status(status) return response.value @retry_on_rpc_failure() def list_partitions(self, collection_name: str, timeout: Optional[float] = None, **kwargs): check_pass_param(collection_name=collection_name, timeout=timeout) request = Prepare.show_partitions_request(collection_name) response = self._stub.ShowPartitions( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) status = response.status check_status(status) return list(response.partition_names) @retry_on_rpc_failure() def get_partition_stats( self, collection_name: str, partition_name: str, timeout: Optional[float] = None, **kwargs ): check_pass_param(collection_name=collection_name, timeout=timeout) req = Prepare.get_partition_stats_request(collection_name, partition_name) response = self._stub.GetPartitionStatistics( req, timeout=timeout, metadata=_api_level_md(**kwargs) ) status = response.status check_status(status) return response.stats # Seems not inuse def _get_info(self, collection_name: str, timeout: Optional[float] = None, **kwargs): schema = kwargs.get("schema") if not schema: schema = self.describe_collection(collection_name, timeout=timeout) fields_info = schema.get("fields") enable_dynamic = schema.get("enable_dynamic_field", False) return fields_info, enable_dynamic @retry_on_rpc_failure() def insert_rows( self, collection_name: str, entities: Union[Dict, List[Dict]], partition_name: Optional[str] = None, schema: Optional[dict] = None, timeout: Optional[float] = None, **kwargs, ): try: request = self._prepare_row_insert_request( collection_name, entities, partition_name, schema, timeout, **kwargs ) except DataNotMatchException: # try to update schema and retry schema = self.update_schema(collection_name, timeout, **kwargs) request = self._prepare_row_insert_request( collection_name, entities, partition_name, schema, timeout, **kwargs ) except Exception as ex: raise ex from ex resp = self._stub.Insert(request=request, timeout=timeout, metadata=_api_level_md(**kwargs)) if resp.status.error_code == common_pb2.SchemaMismatch: schema = self.update_schema(collection_name, timeout, **kwargs) # recursively calling `insert_rows` handling another schema change happens during retry return self.insert_rows( collection_name=collection_name, entities=entities, partition_name=partition_name, schema=schema, timeout=timeout, **kwargs, ) check_status(resp.status) ts_utils.update_collection_ts(collection_name, resp.timestamp) return MutationResult(resp) def update_schema(self, collection_name: str, timeout: Optional[float] = None, **kwargs): self.schema_cache.pop(collection_name, None) schema = self.describe_collection( collection_name, timeout=timeout, metadata=_api_level_md(**kwargs) ) schema_timestamp = schema.get("update_timestamp", 0) self.schema_cache[collection_name] = { "schema": schema, "schema_timestamp": schema_timestamp, } return schema def _prepare_row_insert_request( self, collection_name: str, entity_rows: Union[List[Dict], Dict], partition_name: Optional[str] = None, schema: Optional[dict] = None, timeout: Optional[float] = None, **kwargs, ): if isinstance(entity_rows, dict): entity_rows = [entity_rows] schema, schema_timestamp = self._get_schema_from_cache_or_remote( collection_name, schema, timeout ) fields_info = schema.get("fields") struct_fields_info = schema.get("struct_array_fields", []) # Default to empty list enable_dynamic = schema.get("enable_dynamic_field", False) return Prepare.row_insert_param( collection_name, entity_rows, partition_name, fields_info, struct_fields_info, enable_dynamic=enable_dynamic, schema_timestamp=schema_timestamp, ) def _get_schema_from_cache_or_remote( self, collection_name: str, schema: Optional[dict] = None, timeout: Optional[float] = None ): """ checks the cache for the schema. If not found, it fetches it remotely and updates the cache """ if collection_name in self.schema_cache: # Use the cached schema and timestamp schema = self.schema_cache[collection_name]["schema"] schema_timestamp = self.schema_cache[collection_name]["schema_timestamp"] else: # Fetch the schema remotely if not in cache if not isinstance(schema, dict): schema = self.describe_collection(collection_name, timeout=timeout) schema_timestamp = schema.get("update_timestamp", 0) # Cache the fetched schema and timestamp self.schema_cache[collection_name] = { "schema": schema, "schema_timestamp": schema_timestamp, } return schema, schema_timestamp def _prepare_batch_insert_request( self, collection_name: str, entities: List, partition_name: Optional[str] = None, timeout: Optional[float] = None, **kwargs, ): param = kwargs.get("insert_param") if param and not isinstance(param, milvus_types.InsertRequest): raise ParamError(message="The value of key 'insert_param' is invalid") if not isinstance(entities, list): raise ParamError(message="'entities' must be a list, please provide valid entity data.") schema = kwargs.get("schema") if not schema: schema = self.describe_collection(collection_name, timeout=timeout, **kwargs) fields_info = schema["fields"] return ( param if param else Prepare.batch_insert_param(collection_name, entities, partition_name, fields_info) ) @retry_on_rpc_failure() def batch_insert( self, collection_name: str, entities: List, partition_name: Optional[str] = None, timeout: Optional[float] = None, **kwargs, ): if not check_invalid_binary_vector(entities): raise ParamError(message="Invalid binary vector data exists") try: request = self._prepare_batch_insert_request( collection_name, entities, partition_name, timeout, **kwargs ) rf = self._stub.Insert.future( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) if kwargs.get("_async", False): cb = kwargs.get("_callback") f = MutationFuture(rf, cb, timeout=timeout, **kwargs) f.add_callback(ts_utils.update_ts_on_mutation(collection_name)) return f response = rf.result() check_status(response.status) m = MutationResult(response) ts_utils.update_collection_ts(collection_name, m.timestamp) except Exception as err: if kwargs.get("_async", False): return MutationFuture(None, None, err) raise err from err else: return m @retry_on_rpc_failure() def delete( self, collection_name: str, expression: str, partition_name: Optional[str] = None, timeout: Optional[float] = None, **kwargs, ): check_pass_param(collection_name=collection_name, timeout=timeout) try: req = Prepare.delete_request( collection_name=collection_name, filter=expression, partition_name=partition_name, consistency_level=kwargs.pop("consistency_level", 0), **kwargs, ) future = self._stub.Delete.future( req, timeout=timeout, metadata=_api_level_md(**kwargs) ) if kwargs.get("_async", False): cb = kwargs.pop("_callback", None) f = MutationFuture(future, cb, timeout=timeout, **kwargs) f.add_callback(ts_utils.update_ts_on_mutation(collection_name)) return f response = future.result() check_status(response.status) m = MutationResult(response) ts_utils.update_collection_ts(collection_name, m.timestamp) except Exception as err: if kwargs.get("_async", False): return MutationFuture(None, None, err) raise err from err else: return m def _prepare_batch_upsert_request( self, collection_name: str, entities: List, partition_name: Optional[str] = None, timeout: Optional[float] = None, **kwargs, ): param = kwargs.get("upsert_param") if param and not isinstance(param, milvus_types.UpsertRequest): raise ParamError(message="The value of key 'upsert_param' is invalid") if not isinstance(entities, list): raise ParamError(message="'entities' must be a list, please provide valid entity data.") # Extract partial_update parameter from kwargs partial_update = kwargs.get("partial_update", False) schema = kwargs.get("schema") if not schema: schema = self.describe_collection(collection_name, timeout=timeout, **kwargs) fields_info = schema["fields"] return ( param if param else Prepare.batch_upsert_param( collection_name, entities, partition_name, fields_info, partial_update=partial_update, ) ) @retry_on_rpc_failure() def upsert( self, collection_name: str, entities: List, partition_name: Optional[str] = None, timeout: Optional[float] = None, **kwargs, ): if not check_invalid_binary_vector(entities): raise ParamError(message="Invalid binary vector data exists") try: request = self._prepare_batch_upsert_request( collection_name, entities, partition_name, timeout, **kwargs ) rf = self._stub.Upsert.future( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) if kwargs.get("_async", False) is True: cb = kwargs.get("_callback") f = MutationFuture(rf, cb, timeout=timeout, **kwargs) f.add_callback(ts_utils.update_ts_on_mutation(collection_name)) return f response = rf.result() check_status(response.status) m = MutationResult(response) ts_utils.update_collection_ts(collection_name, m.timestamp) except Exception as err: if kwargs.get("_async", False): return MutationFuture(None, None, err) raise err from err else: return m def _prepare_row_upsert_request( self, collection_name: str, rows: List, partition_name: Optional[str] = None, timeout: Optional[float] = None, **kwargs, ): if not isinstance(rows, list): raise ParamError(message="'rows' must be a list, please provide valid row data.") # Extract partial_update parameter from kwargs partial_update = kwargs.get("partial_update", False) schema, schema_timestamp = self._get_schema_from_cache_or_remote( collection_name, timeout=timeout ) fields_info = schema.get("fields") struct_fields_info = schema.get("struct_array_fields", []) # Default to empty list enable_dynamic = schema.get("enable_dynamic_field", False) return Prepare.row_upsert_param( collection_name, rows, partition_name, fields_info, struct_fields_info, enable_dynamic=enable_dynamic, schema_timestamp=schema_timestamp, partial_update=partial_update, ) @retry_on_rpc_failure() def upsert_rows( self, collection_name: str, entities: List, partition_name: Optional[str] = None, timeout: Optional[float] = None, **kwargs, ): if isinstance(entities, dict): entities = [entities] try: request = self._prepare_row_upsert_request( collection_name, entities, partition_name, timeout, **kwargs ) except DataNotMatchException: # try to update schema and retry self.update_schema(collection_name, timeout, **kwargs) request = self._prepare_row_upsert_request( collection_name, entities, partition_name, timeout, **kwargs ) except Exception as ex: raise ex from ex response = self._stub.Upsert(request, timeout=timeout, metadata=_api_level_md(**kwargs)) if response.status.error_code == common_pb2.SchemaMismatch: self.update_schema(collection_name, timeout) # recursively calling `upsert_rows` handling another schema change happens during retry return self.upsert_rows( collection_name=collection_name, entities=entities, partition_name=partition_name, timeout=timeout, **kwargs, ) check_status(response.status) m = MutationResult(response) ts_utils.update_collection_ts(collection_name, m.timestamp) return m def _execute_search( self, request: milvus_types.SearchRequest, timeout: Optional[float] = None, **kwargs ): try: if kwargs.get("_async", False): future = self._stub.Search.future( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) func = kwargs.get("_callback") return SearchFuture(future, func) response = self._stub.Search(request, timeout=timeout, metadata=_api_level_md(**kwargs)) check_status(response.status) round_decimal = kwargs.get("round_decimal", -1) return SearchResult( response.results, round_decimal, status=response.status, session_ts=response.session_ts, ) except Exception as e: if kwargs.get("_async", False): return SearchFuture(None, None, e) raise e from e def _execute_hybrid_search( self, request: milvus_types.HybridSearchRequest, timeout: Optional[float] = None, **kwargs ): try: if kwargs.get("_async", False): future = self._stub.HybridSearch.future( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) func = kwargs.get("_callback") return SearchFuture(future, func) response = self._stub.HybridSearch( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(response.status) round_decimal = kwargs.get("round_decimal", -1) return SearchResult(response.results, round_decimal, status=response.status) except Exception as e: if kwargs.get("_async", False): return SearchFuture(None, None, e) raise e from e @retry_on_rpc_failure() def search( self, collection_name: str, data: Union[List[List[float]], utils.SparseMatrixInputType], anns_field: str, param: Dict, limit: int, expression: Optional[str] = None, partition_names: Optional[List[str]] = None, output_fields: Optional[List[str]] = None, round_decimal: int = -1, timeout: Optional[float] = None, ranker: Union[Function, FunctionScore] = None, **kwargs, ): check_pass_param( limit=limit, round_decimal=round_decimal, anns_field=anns_field, search_data=data, partition_name_array=partition_names, output_fields=output_fields, guarantee_timestamp=kwargs.get("guarantee_timestamp"), timeout=timeout, ) request = Prepare.search_requests_with_expr( collection_name, data, anns_field, param, limit, expression, partition_names, output_fields, round_decimal, ranker=ranker, **kwargs, ) return self._execute_search(request, timeout, round_decimal=round_decimal, **kwargs) @retry_on_rpc_failure() def hybrid_search( self, collection_name: str, reqs: List[AnnSearchRequest], rerank: Union[BaseRanker, Function], limit: int, partition_names: Optional[List[str]] = None, output_fields: Optional[List[str]] = None, round_decimal: int = -1, timeout: Optional[float] = None, **kwargs, ): check_pass_param( limit=limit, round_decimal=round_decimal, partition_name_array=partition_names, output_fields=output_fields, guarantee_timestamp=kwargs.get("guarantee_timestamp"), timeout=timeout, ) requests = [] for req in reqs: # Convert EmbeddingList to flat array if present in the request data data = req.data req_kwargs = dict(kwargs) if isinstance(data, list) and data and isinstance(data[0], EmbeddingList): data = [emb_list.to_flat_array() for emb_list in data] req_kwargs["is_embedding_list"] = True search_request = Prepare.search_requests_with_expr( collection_name, data, req.anns_field, req.param, req.limit, req.expr, partition_names=partition_names, round_decimal=round_decimal, expr_params=req.expr_params, **req_kwargs, ) requests.append(search_request) hybrid_search_request = Prepare.hybrid_search_request_with_ranker( collection_name, requests, rerank, limit, partition_names, output_fields, round_decimal, **kwargs, ) return self._execute_hybrid_search( hybrid_search_request, timeout, round_decimal=round_decimal, **kwargs ) @retry_on_rpc_failure() def get_query_segment_info( self, collection_name: str, timeout: float = 30, **kwargs ) -> List[milvus_types.QuerySegmentInfo]: req = Prepare.get_query_segment_info_request(collection_name) response = self._stub.GetQuerySegmentInfo( req, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(response.status) return response.infos @retry_on_rpc_failure() def create_alias( self, collection_name: str, alias: str, timeout: Optional[float] = None, **kwargs ): check_pass_param(collection_name=collection_name, timeout=timeout) request = Prepare.create_alias_request(collection_name, alias) response = self._stub.CreateAlias( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(response) @retry_on_rpc_failure() def drop_alias(self, alias: str, timeout: Optional[float] = None, **kwargs): request = Prepare.drop_alias_request(alias) response = self._stub.DropAlias(request, timeout=timeout, metadata=_api_level_md(**kwargs)) check_status(response) @retry_on_rpc_failure() def alter_alias( self, collection_name: str, alias: str, timeout: Optional[float] = None, **kwargs ): check_pass_param(collection_name=collection_name, timeout=timeout) request = Prepare.alter_alias_request(collection_name, alias) response = self._stub.AlterAlias(request, timeout=timeout, metadata=_api_level_md(**kwargs)) check_status(response) @retry_on_rpc_failure() def describe_alias(self, alias: str, timeout: Optional[float] = None, **kwargs): check_pass_param(alias=alias, timeout=timeout) request = Prepare.describe_alias_request(alias) response = self._stub.DescribeAlias( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(response.status) ret = { "alias": alias, } if response.collection: ret["collection_name"] = response.collection if response.db_name: ret["db_name"] = response.db_name return ret @retry_on_rpc_failure() def list_aliases(self, collection_name: str, timeout: Optional[float] = None, **kwargs): check_pass_param(timeout=timeout) if collection_name: check_pass_param(collection_name=collection_name) request = Prepare.list_aliases_request(collection_name, kwargs.get("db_name", "")) response = self._stub.ListAliases( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(response.status) ret = { "aliases": [], } if response.collection_name: ret["collection_name"] = response.collection_name if response.db_name: ret["db_name"] = response.db_name ret["aliases"].extend(response.aliases) return ret @retry_on_rpc_failure() def create_index( self, collection_name: str, field_name: str, params: Dict, timeout: Optional[float] = None, **kwargs, ): # for historical reason, index_name contained in kwargs. index_name = kwargs.pop("index_name", Config.IndexName) _async = kwargs.get("_async", False) kwargs["_async"] = False index_param = Prepare.create_index_request( collection_name, field_name, params, index_name=index_name ) future = self._stub.CreateIndex.future( index_param, timeout=timeout, metadata=_api_level_md(**kwargs) ) if _async: def _check(): if kwargs.get("sync", True): index_success, fail_reason = self.wait_for_creating_index( collection_name=collection_name, index_name=index_name, timeout=timeout, field_name=field_name, **kwargs, ) if not index_success: raise MilvusException(message=fail_reason) index_future = CreateIndexFuture(future) index_future.add_callback(_check) user_cb = kwargs.get("_callback") if user_cb: index_future.add_callback(user_cb) return index_future status = future.result() check_status(status) if kwargs.get("sync", True): index_success, fail_reason = self.wait_for_creating_index( collection_name=collection_name, index_name=index_name, timeout=timeout, field_name=field_name, **kwargs, ) if not index_success: raise MilvusException(message=fail_reason) return Status(status.code, status.reason) @retry_on_rpc_failure() def alter_index_properties( self, collection_name: str, index_name: str, properties: dict, timeout: Optional[float] = None, **kwargs, ): check_pass_param(collection_name=collection_name, index_name=index_name, timeout=timeout) if properties is None: raise ParamError(message="properties should not be None") request = Prepare.alter_index_properties_request(collection_name, index_name, properties) response = self._stub.AlterIndex(request, timeout=timeout, metadata=_api_level_md(**kwargs)) check_status(response) @retry_on_rpc_failure() def drop_index_properties( self, collection_name: str, index_name: str, property_keys: List[str], timeout: Optional[float] = None, **kwargs, ): check_pass_param(collection_name=collection_name, index_name=index_name, timeout=timeout) request = Prepare.drop_index_properties_request( collection_name, index_name, delete_keys=property_keys ) response = self._stub.AlterIndex(request, timeout=timeout, metadata=_api_level_md(**kwargs)) check_status(response) @retry_on_rpc_failure() def list_indexes(self, collection_name: str, timeout: Optional[float] = None, **kwargs): check_pass_param(collection_name=collection_name, timeout=timeout) request = Prepare.describe_index_request(collection_name, "") response = self._stub.DescribeIndex( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) status = response.status if is_successful(status): return response.index_descriptions if status.code == ErrorCode.INDEX_NOT_FOUND or status.error_code == Status.INDEX_NOT_EXIST: return [] raise MilvusException(status.code, status.reason, status.error_code) @retry_on_rpc_failure() def describe_index( self, collection_name: str, index_name: str, timeout: Optional[float] = None, timestamp: Optional[int] = None, **kwargs, ): check_pass_param(collection_name=collection_name, timeout=timeout) request = Prepare.describe_index_request(collection_name, index_name, timestamp=timestamp) response = self._stub.DescribeIndex( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) status = response.status if status.code == ErrorCode.INDEX_NOT_FOUND or status.error_code == Status.INDEX_NOT_EXIST: return None check_status(status) if len(response.index_descriptions) == 1: info_dict = {kv.key: kv.value for kv in response.index_descriptions[0].params} info_dict["field_name"] = response.index_descriptions[0].field_name info_dict["index_name"] = response.index_descriptions[0].index_name if info_dict.get("params"): info_dict["params"] = json.loads(info_dict["params"]) info_dict["total_rows"] = response.index_descriptions[0].total_rows info_dict["indexed_rows"] = response.index_descriptions[0].indexed_rows info_dict["pending_index_rows"] = response.index_descriptions[0].pending_index_rows info_dict["state"] = common_pb2.IndexState.Name(response.index_descriptions[0].state) return info_dict raise AmbiguousIndexName(message=ExceptionsMessage.AmbiguousIndexName) @retry_on_rpc_failure() def get_index_build_progress( self, collection_name: str, index_name: str, timeout: Optional[float] = None, **kwargs ): request = Prepare.describe_index_request(collection_name, index_name) response = self._stub.DescribeIndex( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) status = response.status check_status(status) if len(response.index_descriptions) == 1: index_desc = response.index_descriptions[0] return { "total_rows": index_desc.total_rows, "indexed_rows": index_desc.indexed_rows, "pending_index_rows": index_desc.pending_index_rows, "state": common_pb2.IndexState.Name(index_desc.state), } raise AmbiguousIndexName(message=ExceptionsMessage.AmbiguousIndexName) @retry_on_rpc_failure() def get_index_state( self, collection_name: str, index_name: str, timeout: Optional[float] = None, timestamp: Optional[int] = None, **kwargs, ): request = Prepare.describe_index_request(collection_name, index_name, timestamp) response = self._stub.DescribeIndex( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) status = response.status check_status(status) if len(response.index_descriptions) == 1: index_desc = response.index_descriptions[0] return index_desc.state, index_desc.index_state_fail_reason # just for create_index. field_name = kwargs.pop("field_name", "") if field_name != "": for index_desc in response.index_descriptions: if index_desc.field_name == field_name: return index_desc.state, index_desc.index_state_fail_reason raise AmbiguousIndexName(message=ExceptionsMessage.AmbiguousIndexName) @retry_on_rpc_failure() def wait_for_creating_index( self, collection_name: str, index_name: str, timeout: Optional[float] = None, **kwargs ): timestamp = self.alloc_timestamp() start = time.time() while True: time.sleep(0.5) state, fail_reason = self.get_index_state( collection_name, index_name, timeout=timeout, timestamp=timestamp, **kwargs ) if state == IndexState.Finished: return True, fail_reason if state == IndexState.Failed: return False, fail_reason end = time.time() if isinstance(timeout, int) and end - start > timeout: msg = ( f"collection {collection_name} create index {index_name} timeout in {timeout}s" ) raise MilvusException(message=msg) @retry_on_rpc_failure() def load_collection( self, collection_name: str, replica_number: Optional[int] = None, timeout: Optional[float] = None, **kwargs, ): check_pass_param(timeout=timeout) request = Prepare.load_collection(collection_name, replica_number, **kwargs) response = self._stub.LoadCollection( request, timeout=timeout, metadata=_api_level_md(**kwargs), ) check_status(response) if kwargs.get("_async", False): return self.wait_for_loading_collection( collection_name=collection_name, is_refresh=request.refresh, timeout=timeout, **kwargs, ) @retry_on_rpc_failure() def load_collection_progress( self, collection_name: str, timeout: Optional[float] = None, **kwargs, ): """Return loading progress of collection""" progress = self.get_loading_progress(collection_name, timeout=timeout) return { "loading_progress": f"{progress:.0f}%", } @retry_on_rpc_failure() def wait_for_loading_collection( self, collection_name: str, timeout: Optional[float] = None, is_refresh: bool = False, **kwargs, ): start = time.time() def can_loop(t: int) -> bool: return True if timeout is None else t <= (start + timeout) while can_loop(time.time()): progress = self.get_loading_progress( collection_name, is_refresh=is_refresh, timeout=timeout, **kwargs, ) if progress >= 100: return time.sleep(Config.WaitTimeDurationWhenLoad) raise MilvusException( message=f"wait for loading collection timeout, collection: {collection_name}" ) @retry_on_rpc_failure() def release_collection(self, collection_name: str, timeout: Optional[float] = None, **kwargs): check_pass_param(collection_name=collection_name, timeout=timeout) request = Prepare.release_collection("", collection_name) response = self._stub.ReleaseCollection( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(response) @retry_on_rpc_failure() def load_partitions( self, collection_name: str, partition_names: List[str], replica_number: Optional[int] = None, timeout: Optional[float] = None, **kwargs, ): check_pass_param(timeout=timeout) request = Prepare.load_partitions( collection_name=collection_name, partition_names=partition_names, replica_number=replica_number, **kwargs, ) response = self._stub.LoadPartitions( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(response) if kwargs.get("sync", True) or not kwargs.get("_async", False): self.wait_for_loading_partitions( collection_name=collection_name, partition_names=partition_names, is_refresh=request.refresh, timeout=timeout, **kwargs, ) @retry_on_rpc_failure() def wait_for_loading_partitions( self, collection_name: str, partition_names: List[str], timeout: Optional[float] = None, is_refresh: bool = False, **kwargs, ): start = time.time() def can_loop(t: int) -> bool: return True if timeout is None else t <= (start + timeout) while can_loop(time.time()): progress = self.get_loading_progress( collection_name=collection_name, partition_names=partition_names, timeout=timeout, is_refresh=is_refresh, **kwargs, ) if progress >= 100: return time.sleep(Config.WaitTimeDurationWhenLoad) raise MilvusException( message=f"wait for loading partition timeout, collection: {collection_name}, partitions: {partition_names}" ) @retry_on_rpc_failure() def get_loading_progress( self, collection_name: str, partition_names: Optional[List[str]] = None, timeout: Optional[float] = None, is_refresh: bool = False, **kwargs, ): request = Prepare.get_loading_progress(collection_name, partition_names) response = self._stub.GetLoadingProgress( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(response.status) if is_refresh: return response.refresh_progress return response.progress @retry_on_rpc_failure() def create_database( self, db_name: str, properties: Optional[dict] = None, timeout: Optional[float] = None, **kwargs, ): check_pass_param(db_name=db_name, timeout=timeout) request = Prepare.create_database_req(db_name, properties=properties) status = self._stub.CreateDatabase( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(status) @retry_on_rpc_failure() def drop_database(self, db_name: str, timeout: Optional[float] = None, **kwargs): request = Prepare.drop_database_req(db_name) status = self._stub.DropDatabase(request, timeout=timeout, metadata=_api_level_md(**kwargs)) check_status(status) @retry_on_rpc_failure() def list_database(self, timeout: Optional[float] = None, **kwargs): check_pass_param(timeout=timeout) request = Prepare.list_database_req() response = self._stub.ListDatabases( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(response.status) return list(response.db_names) @retry_on_rpc_failure() def alter_database( self, db_name: str, properties: dict, timeout: Optional[float] = None, **kwargs ): request = Prepare.alter_database_properties_req(db_name, properties) status = self._stub.AlterDatabase( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(status) @retry_on_rpc_failure() def drop_database_properties( self, db_name: str, property_keys: List[str], timeout: Optional[float] = None, **kwargs ): request = Prepare.drop_database_properties_req(db_name, property_keys) status = self._stub.AlterDatabase( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(status) @retry_on_rpc_failure() def describe_database(self, db_name: str, timeout: Optional[float] = None, **kwargs): request = Prepare.describe_database_req(db_name=db_name) resp = self._stub.DescribeDatabase( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp.status) return DatabaseInfo(resp).to_dict() @retry_on_rpc_failure() def get_load_state( self, collection_name: str, partition_names: Optional[List[str]] = None, timeout: Optional[float] = None, **kwargs, ): request = Prepare.get_load_state(collection_name, partition_names) response = self._stub.GetLoadState( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(response.status) return LoadState(response.state) @retry_on_rpc_failure() def load_partitions_progress( self, collection_name: str, partition_names: List[str], timeout: Optional[float] = None, **kwargs, ): """Return loading progress of partitions""" progress = self.get_loading_progress(collection_name, partition_names, timeout, **kwargs) return { "loading_progress": f"{progress:.0f}%", } @retry_on_rpc_failure() def release_partitions( self, collection_name: str, partition_names: List[str], timeout: Optional[float] = None, **kwargs, ): check_pass_param( collection_name=collection_name, partition_name_array=partition_names, timeout=timeout ) request = Prepare.release_partitions("", collection_name, partition_names) response = self._stub.ReleasePartitions( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(response) @retry_on_rpc_failure() def get_collection_stats(self, collection_name: str, timeout: Optional[float] = None, **kwargs): check_pass_param(collection_name=collection_name, timeout=timeout) index_param = Prepare.get_collection_stats_request(collection_name) response = self._stub.GetCollectionStatistics( index_param, timeout=timeout, metadata=_api_level_md(**kwargs) ) status = response.status check_status(status) return response.stats @retry_on_rpc_failure() def get_flush_state( self, segment_ids: List[int], collection_name: str, flush_ts: int, timeout: Optional[float] = None, **kwargs, ): req = Prepare.get_flush_state_request(segment_ids, collection_name, flush_ts) response = self._stub.GetFlushState(req, timeout=timeout, metadata=_api_level_md(**kwargs)) status = response.status check_status(status) return response.flushed @retry_on_rpc_failure() def get_persistent_segment_infos( self, collection_name: str, timeout: Optional[float] = None, **kwargs ) -> List[milvus_types.PersistentSegmentInfo]: req = Prepare.get_persistent_segment_info_request(collection_name) response = self._stub.GetPersistentSegmentInfo( req, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(response.status) return response.infos def _wait_for_flushed( self, segment_ids: List[int], collection_name: str, flush_ts: int, timeout: Optional[float] = None, **kwargs, ): flush_ret = False start = time.time() while not flush_ret: flush_ret = self.get_flush_state( segment_ids, collection_name, flush_ts, timeout, **kwargs ) end = time.time() if timeout is not None and end - start > timeout: raise MilvusException( message=f"wait for flush timeout, collection: {collection_name}, flusht_ts: {flush_ts}" ) if not flush_ret: time.sleep(0.5) @retry_on_rpc_failure(initial_back_off=1) def flush(self, collection_names: list, timeout: Optional[float] = None, **kwargs): if collection_names in (None, []) or not isinstance(collection_names, list): raise ParamError(message="Collection name list can not be None or empty") check_pass_param(timeout=timeout) for name in collection_names: check_pass_param(collection_name=name) request = Prepare.flush_param(collection_names) future = self._stub.Flush.future(request, timeout=timeout, metadata=_api_level_md(**kwargs)) response = future.result() check_status(response.status) def _check(): for collection_name in collection_names: segment_ids = future.result().coll_segIDs[collection_name].data flush_ts = future.result().coll_flush_ts[collection_name] self._wait_for_flushed(segment_ids, collection_name, flush_ts, timeout=timeout) if kwargs.get("_async", False): flush_future = FlushFuture(future) flush_future.add_callback(_check) user_cb = kwargs.get("_callback") if user_cb: flush_future.add_callback(user_cb) return flush_future _check() return None @retry_on_rpc_failure() def drop_index( self, collection_name: str, field_name: str, index_name: str, timeout: Optional[float] = None, **kwargs, ): check_pass_param(collection_name=collection_name, timeout=timeout) request = Prepare.drop_index_request(collection_name, field_name, index_name) response = self._stub.DropIndex(request, timeout=timeout, metadata=_api_level_md(**kwargs)) check_status(response) @retry_on_rpc_failure() def dummy(self, request_type: Any, timeout: Optional[float] = None, **kwargs): request = Prepare.dummy_request(request_type) return self._stub.Dummy(request, timeout=timeout, metadata=_api_level_md(**kwargs)) # TODO seems not in use @retry_on_rpc_failure() def fake_register_link(self, timeout: Optional[float] = None, **kwargs): request = Prepare.register_link_request() response = self._stub.RegisterLink( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) return response.status # TODO seems not in use @retry_on_rpc_failure() def get( self, collection_name: str, ids: List[int], output_fields: Optional[List[str]] = None, partition_names: Optional[List[str]] = None, timeout: Optional[float] = None, **kwargs, ): # TODO: some check request = Prepare.retrieve_request(collection_name, ids, output_fields, partition_names) return self._stub.Retrieve(request, timeout=timeout, metadata=_api_level_md(**kwargs)) @retry_on_rpc_failure() def query( self, collection_name: str, expr: str, output_fields: Optional[List[str]] = None, partition_names: Optional[List[str]] = None, timeout: Optional[float] = None, strict_float32: bool = False, **kwargs, ): if output_fields is not None and not isinstance(output_fields, (list,)): raise ParamError(message="Invalid query format. 'output_fields' must be a list") request = Prepare.query_request( collection_name, expr, output_fields, partition_names, **kwargs ) response = self._stub.Query(request, timeout=timeout, metadata=_api_level_md(**kwargs)) if Status.EMPTY_COLLECTION in {response.status.code, response.status.error_code}: return [] check_status(response.status) num_fields = len(response.fields_data) # check has fields if num_fields == 0: raise MilvusException(message="No fields returned") # check if all lists are of the same length it = iter(response.fields_data) num_entities = len_of(next(it)) if not all(len_of(field_data) == num_entities for field_data in it): raise MilvusException(message="The length of fields data is inconsistent") _, dynamic_fields = entity_helper.extract_dynamic_field_from_result(response) keys = [field_data.field_name for field_data in response.fields_data] filtered_keys = [k for k in keys if k != "$meta"] results = [dict.fromkeys(filtered_keys) for _ in range(num_entities)] lazy_field_data = [] for field_data in response.fields_data: lazy_extracted = entity_helper.extract_row_data_from_fields_data_v2(field_data, results) if lazy_extracted: lazy_field_data.append(field_data) extra_dict = get_extra_info(response.status) extra_dict[ITERATOR_SESSION_TS_FIELD] = response.session_ts return HybridExtraList( lazy_field_data, results, extra=extra_dict, dynamic_fields=dynamic_fields, strict_float32=strict_float32, ) @retry_on_rpc_failure() def load_balance( self, collection_name: str, src_node_id: int, dst_node_ids: List[int], sealed_segment_ids: List[int], timeout: Optional[float] = None, **kwargs, ): req = Prepare.load_balance_request( collection_name, src_node_id, dst_node_ids, sealed_segment_ids ) status = self._stub.LoadBalance(req, timeout=timeout, metadata=_api_level_md(**kwargs)) check_status(status) @retry_on_rpc_failure() def compact( self, collection_name: str, is_clustering: Optional[bool] = False, is_l0: Optional[bool] = False, target_size: Optional[int] = None, timeout: Optional[float] = None, **kwargs, ) -> int: meta = _api_level_md(**kwargs) # try with only collection_name req = Prepare.manual_compaction( collection_name=collection_name, is_clustering=is_clustering, is_l0=is_l0, target_size=target_size, ) response = self._stub.ManualCompaction(req, timeout=timeout, metadata=meta) if response.status.error_code == common_pb2.CollectionNameNotFound: # should be removed, but to be compatible with old milvus server, keep it for now. request = Prepare.describe_collection_request(collection_name) response = self._stub.DescribeCollection(request, timeout=timeout, metadata=meta) check_status(response.status) req = Prepare.manual_compaction( collection_name, is_clustering, response.collectionID, target_size ) response = self._stub.ManualCompaction(req, timeout=timeout, metadata=meta) check_status(response.status) return response.compactionID @retry_on_rpc_failure() def get_compaction_state( self, compaction_id: int, timeout: Optional[float] = None, **kwargs ) -> CompactionState: req = Prepare.get_compaction_state(compaction_id) response = self._stub.GetCompactionState( req, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(response.status) return CompactionState( compaction_id, State.new(response.state), response.executingPlanNo, response.timeoutPlanNo, response.completedPlanNo, ) @retry_on_rpc_failure() def wait_for_compaction_completed( self, compaction_id: int, timeout: Optional[float] = None, **kwargs ): start = time.time() while True: time.sleep(0.5) compaction_state = self.get_compaction_state(compaction_id, timeout, **kwargs) if compaction_state.state == State.Completed: return True if compaction_state == State.UndefiedState: return False end = time.time() if timeout is not None and end - start > timeout: raise MilvusException( message=f"get compaction state timeout, compaction id: {compaction_id}" ) @retry_on_rpc_failure() def get_compaction_plans( self, compaction_id: int, timeout: Optional[float] = None, **kwargs ) -> CompactionPlans: req = Prepare.get_compaction_state_with_plans(compaction_id) response = self._stub.GetCompactionStateWithPlans( req, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(response.status) cp = CompactionPlans(compaction_id, response.state) cp.plans = [Plan(m.sources, m.target) for m in response.mergeInfos] return cp @retry_on_rpc_failure() def get_replicas( self, collection_name: str, timeout: Optional[float] = None, **kwargs ) -> Replica: collection_id = self.describe_collection(collection_name, timeout, **kwargs)[ "collection_id" ] req = Prepare.get_replicas(collection_id) response = self._stub.GetReplicas(req, timeout=timeout, metadata=_api_level_md(**kwargs)) check_status(response.status) groups = [] for replica in response.replicas: shards = [ Shard(s.dm_channel_name, s.node_ids, s.leaderID) for s in replica.shard_replicas ] groups.append( Group( replica.replicaID, shards, replica.node_ids, replica.resource_group_name, replica.num_outbound_node, ) ) return Replica(groups) @retry_on_rpc_failure() def describe_replica( self, collection_name: str, timeout: Optional[float] = None, **kwargs ) -> List[ReplicaInfo]: collection_id = self.describe_collection(collection_name, timeout, **kwargs)[ "collection_id" ] req = Prepare.get_replicas(collection_id) response = self._stub.GetReplicas(req, timeout=timeout, metadata=_api_level_md(**kwargs)) check_status(response.status) groups = [] for replica in response.replicas: shards = [ Shard(s.dm_channel_name, s.node_ids, s.leaderID) for s in replica.shard_replicas ] groups.append( ReplicaInfo( replica.replicaID, shards, replica.node_ids, replica.resource_group_name, replica.num_outbound_node, ) ) return groups @retry_on_rpc_failure() def do_bulk_insert( self, collection_name: str, partition_name: str, files: List[str], timeout: Optional[float] = None, **kwargs, ) -> int: req = Prepare.do_bulk_insert(collection_name, partition_name, files, **kwargs) response = self._stub.Import(req, timeout=timeout, metadata=_api_level_md(**kwargs)) check_status(response.status) if len(response.tasks) == 0: raise MilvusException( ErrorCode.UNEXPECTED_ERROR, "no task id returned from server", common_pb2.UnexpectedError, ) return response.tasks[0] @retry_on_rpc_failure() def get_bulk_insert_state( self, task_id: int, timeout: Optional[float] = None, **kwargs ) -> BulkInsertState: req = Prepare.get_bulk_insert_state(task_id) resp = self._stub.GetImportState(req, timeout=timeout, metadata=_api_level_md(**kwargs)) check_status(resp.status) return BulkInsertState( task_id, resp.state, resp.row_count, resp.id_list, resp.infos, resp.create_ts ) @retry_on_rpc_failure() def list_bulk_insert_tasks( self, limit: int, collection_name: str, timeout: Optional[float] = None, **kwargs ) -> list: req = Prepare.list_bulk_insert_tasks(limit, collection_name) resp = self._stub.ListImportTasks(req, timeout=timeout, metadata=_api_level_md(**kwargs)) check_status(resp.status) return [ BulkInsertState(t.id, t.state, t.row_count, t.id_list, t.infos, t.create_ts) for t in resp.tasks ] @retry_on_rpc_failure() def create_user(self, user: str, password: str, timeout: Optional[float] = None, **kwargs): check_pass_param(user=user, password=password, timeout=timeout) req = Prepare.create_user_request(user, password) resp = self._stub.CreateCredential(req, timeout=timeout, metadata=_api_level_md(**kwargs)) check_status(resp) @retry_on_rpc_failure() def update_password( self, user: str, old_password: str, new_password: str, timeout: Optional[float] = None, **kwargs, ): req = Prepare.update_password_request(user, old_password, new_password) resp = self._stub.UpdateCredential(req, timeout=timeout, metadata=_api_level_md(**kwargs)) check_status(resp) @retry_on_rpc_failure() def delete_user(self, user: str, timeout: Optional[float] = None, **kwargs): req = Prepare.delete_user_request(user) resp = self._stub.DeleteCredential(req, timeout=timeout, metadata=_api_level_md(**kwargs)) check_status(resp) @retry_on_rpc_failure() def list_usernames(self, timeout: Optional[float] = None, **kwargs): req = Prepare.list_usernames_request() resp = self._stub.ListCredUsers(req, timeout=timeout, metadata=_api_level_md(**kwargs)) check_status(resp.status) return resp.usernames @retry_on_rpc_failure() def create_role(self, role_name: str, timeout: Optional[float] = None, **kwargs): req = Prepare.create_role_request(role_name) resp = self._stub.CreateRole( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp) @retry_on_rpc_failure() def drop_role( self, role_name: str, force_drop: bool = False, timeout: Optional[float] = None, **kwargs ): req = Prepare.drop_role_request(role_name, force_drop=force_drop) resp = self._stub.DropRole( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp) @retry_on_rpc_failure() def add_user_to_role( self, username: str, role_name: str, timeout: Optional[float] = None, **kwargs ): req = Prepare.operate_user_role_request( username, role_name, milvus_types.OperateUserRoleType.AddUserToRole ) resp = self._stub.OperateUserRole( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp) @retry_on_rpc_failure() def remove_user_from_role( self, username: str, role_name: str, timeout: Optional[float] = None, **kwargs ): req = Prepare.operate_user_role_request( username, role_name, milvus_types.OperateUserRoleType.RemoveUserFromRole ) resp = self._stub.OperateUserRole( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp) @retry_on_rpc_failure() def select_one_role( self, role_name: str, include_user_info: bool, timeout: Optional[float] = None, **kwargs ): req = Prepare.select_role_request(role_name, include_user_info) resp = self._stub.SelectRole( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp.status) return RoleInfo(resp.results) @retry_on_rpc_failure() def select_all_role(self, include_user_info: bool, timeout: Optional[float] = None, **kwargs): req = Prepare.select_role_request(None, include_user_info) resp = self._stub.SelectRole( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp.status) return RoleInfo(resp.results) @retry_on_rpc_failure() def select_one_user( self, username: str, include_role_info: bool, timeout: Optional[float] = None, **kwargs ): req = Prepare.select_user_request(username, include_role_info) resp = self._stub.SelectUser( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp.status) return UserInfo(resp.results) @retry_on_rpc_failure() def select_all_user(self, include_role_info: bool, timeout: Optional[float] = None, **kwargs): req = Prepare.select_user_request(None, include_role_info) resp = self._stub.SelectUser( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp.status) return UserInfo(resp.results) @retry_on_rpc_failure() def grant_privilege( self, role_name: str, object: str, object_name: str, privilege: str, db_name: str, timeout: Optional[float] = None, **kwargs, ): req = Prepare.operate_privilege_request( role_name, object, object_name, privilege, db_name, milvus_types.OperatePrivilegeType.Grant, ) resp = self._stub.OperatePrivilege( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp) @retry_on_rpc_failure() def revoke_privilege( self, role_name: str, object: str, object_name: str, privilege: str, db_name: str, timeout: Optional[float] = None, **kwargs, ): req = Prepare.operate_privilege_request( role_name, object, object_name, privilege, db_name, milvus_types.OperatePrivilegeType.Revoke, ) resp = self._stub.OperatePrivilege( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp) @retry_on_rpc_failure() def grant_privilege_v2( self, role_name: str, privilege: str, collection_name: str, db_name: Optional[str] = None, timeout: Optional[float] = None, **kwargs, ): req = Prepare.operate_privilege_v2_request( role_name, privilege, milvus_types.OperatePrivilegeType.Grant, db_name, collection_name, ) resp = self._stub.OperatePrivilegeV2( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp) @retry_on_rpc_failure() def revoke_privilege_v2( self, role_name: str, privilege: str, collection_name: str, db_name: Optional[str] = None, timeout: Optional[float] = None, **kwargs, ): req = Prepare.operate_privilege_v2_request( role_name, privilege, milvus_types.OperatePrivilegeType.Revoke, db_name, collection_name, ) resp = self._stub.OperatePrivilegeV2( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp) @retry_on_rpc_failure() def select_grant_for_one_role( self, role_name: str, db_name: str, timeout: Optional[float] = None, **kwargs ): req = Prepare.select_grant_request(role_name, None, None, db_name) resp = self._stub.SelectGrant( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp.status) return GrantInfo(resp.entities) @retry_on_rpc_failure() def select_grant_for_role_and_object( self, role_name: str, object: str, object_name: str, db_name: str, timeout: Optional[float] = None, **kwargs, ): req = Prepare.select_grant_request(role_name, object, object_name, db_name) resp = self._stub.SelectGrant( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp.status) return GrantInfo(resp.entities) @retry_on_rpc_failure() def get_server_version(self, timeout: Optional[float] = None, **kwargs) -> str: req = Prepare.get_server_version() resp = self._stub.GetVersion(req, timeout=timeout, metadata=_api_level_md(**kwargs)) check_status(resp.status) return resp.version @retry_on_rpc_failure() def create_resource_group(self, name: str, timeout: Optional[float] = None, **kwargs): req = Prepare.create_resource_group(name, **kwargs) resp = self._stub.CreateResourceGroup( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp) @retry_on_rpc_failure() def update_resource_groups( self, configs: Mapping[str, ResourceGroupConfig], timeout: Optional[float] = None, **kwargs ): req = Prepare.update_resource_groups(configs) resp = self._stub.UpdateResourceGroups( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp) @retry_on_rpc_failure() def drop_resource_group(self, name: str, timeout: Optional[float] = None, **kwargs): req = Prepare.drop_resource_group(name) resp = self._stub.DropResourceGroup( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp) @retry_on_rpc_failure() def list_resource_groups(self, timeout: Optional[float] = None, **kwargs): req = Prepare.list_resource_groups() resp = self._stub.ListResourceGroups( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp.status) return list(resp.resource_groups) @retry_on_rpc_failure() def describe_resource_group( self, name: str, timeout: Optional[float] = None, **kwargs ) -> ResourceGroupInfo: req = Prepare.describe_resource_group(name) resp = self._stub.DescribeResourceGroup( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp.status) return ResourceGroupInfo(resp.resource_group) @retry_on_rpc_failure() def transfer_node( self, source: str, target: str, num_node: int, timeout: Optional[float] = None, **kwargs ): req = Prepare.transfer_node(source, target, num_node) resp = self._stub.TransferNode( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp) @retry_on_rpc_failure() def transfer_replica( self, source: str, target: str, collection_name: str, num_replica: int, timeout: Optional[float] = None, **kwargs, ): req = Prepare.transfer_replica(source, target, collection_name, num_replica) resp = self._stub.TransferReplica( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp) @retry_on_rpc_failure() def get_flush_all_state(self, flush_all_ts: int, timeout: Optional[float] = None, **kwargs): req = Prepare.get_flush_all_state_request(flush_all_ts, kwargs.get("db", "")) response = self._stub.GetFlushAllState( req, timeout=timeout, metadata=_api_level_md(**kwargs) ) status = response.status check_status(status) return response.flushed def _wait_for_flush_all(self, flush_all_ts: int, timeout: Optional[float] = None, **kwargs): flush_ret = False start = time.time() while not flush_ret: flush_ret = self.get_flush_all_state(flush_all_ts, timeout, **kwargs) end = time.time() if timeout is not None and end - start > timeout: raise MilvusException( message=f"wait for flush all timeout, flush_all_ts: {flush_all_ts}" ) if not flush_ret: time.sleep(5) @retry_on_rpc_failure() def flush_all(self, timeout: Optional[float] = None, **kwargs): request = Prepare.flush_all_request(kwargs.get("db", "")) future = self._stub.FlushAll.future( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) response = future.result() check_status(response.status) def _check(): self._wait_for_flush_all(response.flush_all_ts, timeout, **kwargs) if kwargs.get("_async", False): flush_future = FlushFuture(future) flush_future.add_callback(_check) user_cb = kwargs.get("_callback") if user_cb: flush_future.add_callback(user_cb) return flush_future _check() return None @retry_on_rpc_failure() @upgrade_reminder def __internal_register(self, user: str, host: str, **kwargs) -> int: req = Prepare.register_request(user, host) response = self._stub.Connect(request=req) check_status(response.status) return response.identifier @retry_on_rpc_failure() @ignore_unimplemented(0) def alloc_timestamp(self, timeout: Optional[float] = None, **kwargs) -> int: request = milvus_types.AllocTimestampRequest() response = self._stub.AllocTimestamp(request, timeout=timeout, metadata=_api_level_md()) check_status(response.status) return response.timestamp @retry_on_rpc_failure() def create_privilege_group( self, privilege_group: str, timeout: Optional[float] = None, **kwargs ): req = Prepare.create_privilege_group_req(privilege_group) resp = self._stub.CreatePrivilegeGroup( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp) @retry_on_rpc_failure() def drop_privilege_group(self, privilege_group: str, timeout: Optional[float] = None, **kwargs): req = Prepare.drop_privilege_group_req(privilege_group) resp = self._stub.DropPrivilegeGroup( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp) @retry_on_rpc_failure() def list_privilege_groups(self, timeout: Optional[float] = None, **kwargs): req = Prepare.list_privilege_groups_req() resp = self._stub.ListPrivilegeGroups( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp.status) return PrivilegeGroupInfo(resp.privilege_groups) @retry_on_rpc_failure() def add_privileges_to_group( self, privilege_group: str, privileges: List[str], timeout: Optional[float] = None, **kwargs ): req = Prepare.operate_privilege_group_req( privilege_group, privileges, milvus_types.OperatePrivilegeGroupType.AddPrivilegesToGroup ) resp = self._stub.OperatePrivilegeGroup( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp) @retry_on_rpc_failure() def remove_privileges_from_group( self, privilege_group: str, privileges: List[str], timeout: Optional[float] = None, **kwargs ): req = Prepare.operate_privilege_group_req( privilege_group, privileges, milvus_types.OperatePrivilegeGroupType.RemovePrivilegesFromGroup, ) resp = self._stub.OperatePrivilegeGroup( req, wait_for_ready=True, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(resp) @retry_on_rpc_failure() def run_analyzer( self, texts: Union[str, List[str]], analyzer_params: Optional[Union[str, Dict]] = None, with_hash: bool = False, with_detail: bool = False, collection_name: Optional[str] = None, field_name: Optional[str] = None, analyzer_names: Optional[Union[str, List[str]]] = None, timeout: Optional[float] = None, **kwargs, ): check_pass_param(timeout=timeout) req = Prepare.run_analyzer( texts, analyzer_params=analyzer_params, with_hash=with_hash, with_detail=with_detail, collection_name=collection_name, field_name=field_name, analyzer_names=analyzer_names, ) resp = self._stub.RunAnalyzer(req, timeout=timeout, metadata=_api_level_md(**kwargs)) check_status(resp.status) if isinstance(texts, str): return AnalyzeResult(resp.results[0], with_hash, with_detail) return [AnalyzeResult(result, with_hash, with_detail) for result in resp.results] @retry_on_rpc_failure() def update_replicate_configuration( self, clusters: Optional[List[Dict]] = None, cross_cluster_topology: Optional[List[Dict]] = None, timeout: Optional[float] = None, **kwargs, ): """ Update replication configuration across Milvus clusters. Args: clusters: The replication configuration to apply cross_cluster_topology: The replication configuration to apply timeout: An optional duration of time in seconds to allow for the RPC **kwargs: Additional arguments Returns: Status: The status of the operation """ request = Prepare.update_replicate_configuration_request( clusters=clusters, cross_cluster_topology=cross_cluster_topology, ) status = self._stub.UpdateReplicateConfiguration( request, timeout=timeout, metadata=_api_level_md(**kwargs) ) check_status(status) return status
GrpcHandler
python
django__django
django/contrib/admin/utils.py
{ "start": 1131, "end": 6214 }
class ____(Exception): """A field is a foreign key attname, i.e. <FK>_id.""" pass def lookup_spawns_duplicates(opts, lookup_path): """ Return True if the given lookup path spawns duplicates. """ lookup_fields = lookup_path.split(LOOKUP_SEP) # Go through the fields (following all relations) and look for an m2m. for field_name in lookup_fields: if field_name == "pk": field_name = opts.pk.name try: field = opts.get_field(field_name) except FieldDoesNotExist: # Ignore query lookups. continue else: if hasattr(field, "path_infos"): # This field is a relation; update opts to follow the relation. path_info = field.path_infos opts = path_info[-1].to_opts if any(path.m2m for path in path_info): # This field is a m2m relation so duplicates must be # handled. return True return False def get_last_value_from_parameters(parameters, key): value = parameters.get(key) return value[-1] if isinstance(value, list) else value def prepare_lookup_value(key, value, separator=","): """ Return a lookup value prepared to be used in queryset filtering. """ if isinstance(value, list): return [prepare_lookup_value(key, v, separator=separator) for v in value] # if key ends with __in, split parameter into separate values if key.endswith("__in"): value = value.split(separator) # if key ends with __isnull, special case '' and the string literals # 'false' and '0' elif key.endswith("__isnull"): value = value.lower() not in ("", "false", "0") return value def build_q_object_from_lookup_parameters(parameters): q_object = models.Q() for param, param_item_list in parameters.items(): q_object &= reduce(or_, (models.Q((param, item)) for item in param_item_list)) return q_object def quote(s): """ Ensure that primary key values do not confuse the admin URLs by escaping any '/', '_' and ':' and similarly problematic characters. Similar to urllib.parse.quote(), except that the quoting is slightly different so that it doesn't get automatically unquoted by the web browser. """ return s.translate(QUOTE_MAP) if isinstance(s, str) else s def unquote(s): """Undo the effects of quote().""" return UNQUOTE_RE.sub(lambda m: UNQUOTE_MAP[m[0]], s) def flatten(fields): """ Return a list which is a single level of flattening of the original list. """ flat = [] for field in fields: if isinstance(field, (list, tuple)): flat.extend(field) else: flat.append(field) return flat def flatten_fieldsets(fieldsets): """Return a list of field names from an admin fieldsets structure.""" field_names = [] for name, opts in fieldsets: field_names.extend(flatten(opts["fields"])) return field_names def get_deleted_objects(objs, request, admin_site): """ Find all objects related to ``objs`` that should also be deleted. ``objs`` must be a homogeneous iterable of objects (e.g. a QuerySet). Return a nested list of strings suitable for display in the template with the ``unordered_list`` filter. """ try: obj = objs[0] except IndexError: return [], {}, set(), [] else: using = router.db_for_write(obj._meta.model) collector = NestedObjects(using=using, origin=objs) collector.collect(objs) perms_needed = set() def format_callback(obj): model = obj.__class__ opts = obj._meta no_edit_link = "%s: %s" % (capfirst(opts.verbose_name), obj) if admin_site.is_registered(model): if not admin_site.get_model_admin(model).has_delete_permission( request, obj ): perms_needed.add(opts.verbose_name) try: admin_url = reverse( "%s:%s_%s_change" % (admin_site.name, opts.app_label, opts.model_name), None, (quote(obj.pk),), ) except NoReverseMatch: # Change url doesn't exist -- don't display link to edit return no_edit_link # Display a link to the admin page. return format_html( '{}: <a href="{}">{}</a>', capfirst(opts.verbose_name), admin_url, obj ) else: # Don't display link to edit, because it either has no # admin or is edited inline. return no_edit_link to_delete = collector.nested(format_callback) protected = [format_callback(obj) for obj in collector.protected] model_count = { model._meta.verbose_name_plural: len(objs) for model, objs in collector.model_objs.items() } return to_delete, model_count, perms_needed, protected
FieldIsAForeignKeyColumnName
python
doocs__leetcode
solution/0900-0999/0917.Reverse Only Letters/Solution.py
{ "start": 0, "end": 410 }
class ____: def reverseOnlyLetters(self, s: str) -> str: cs = list(s) i, j = 0, len(cs) - 1 while i < j: while i < j and not cs[i].isalpha(): i += 1 while i < j and not cs[j].isalpha(): j -= 1 if i < j: cs[i], cs[j] = cs[j], cs[i] i, j = i + 1, j - 1 return "".join(cs)
Solution
python
ansible__ansible
test/units/module_utils/facts/other/test_facter.py
{ "start": 6332, "end": 7974 }
class ____(BaseFactsTest): __test__ = True gather_subset = ['!all', 'facter'] valid_subsets = ['facter'] fact_namespace = 'ansible_facter' collector_class = FacterFactCollector def _mock_module(self): mock_module = Mock() mock_module.params = {'gather_subset': self.gather_subset, 'gather_timeout': 10, 'filter': '*'} mock_module.get_bin_path = Mock(return_value='/not/actually/facter') mock_module.run_command = Mock(return_value=(0, facter_json_output, '')) return mock_module @patch('ansible.module_utils.facts.other.facter.FacterFactCollector.get_facter_output') def test_bogus_json(self, mock_get_facter_output): module = self._mock_module() # bogus json mock_get_facter_output.return_value = '{' fact_collector = self.collector_class() facts_dict = fact_collector.collect(module=module) self.assertIsInstance(facts_dict, dict) self.assertEqual(facts_dict, {}) @patch('ansible.module_utils.facts.other.facter.FacterFactCollector.run_facter') def test_facter_non_zero_return_code(self, mock_run_facter): module = self._mock_module() # bogus json mock_run_facter.return_value = (1, '{}', '') fact_collector = self.collector_class() facts_dict = fact_collector.collect(module=module) self.assertIsInstance(facts_dict, dict) # This assumes no 'facter' entry at all is correct self.assertNotIn('facter', facts_dict) self.assertEqual(facts_dict, {})
TestFacterCollector
python
scrapy__scrapy
scrapy/item.py
{ "start": 465, "end": 534 }
class ____(dict[str, Any]): """Container of field metadata"""
Field
python
sphinx-doc__sphinx
tests/test_domains/test_domain_c.py
{ "start": 905, "end": 43332 }
class ____: c_id_attributes = ['id_attr', 'LIGHTGBM_C_EXPORT'] c_paren_attributes = ['paren_attr'] c_extra_keywords = _macro_keywords def parse(name, string): parser = DefinitionParser(string, location=None, config=Config()) parser.allowFallbackExpressionParsing = False ast = parser.parse_declaration(name, name) parser.assert_end() return ast def _check(name, input, id_dict, output, key, as_text_output): if key is None: key = name key += ' ' if name in {'function', 'member'}: input_actual = input output_ast = output output_as_text = output else: input_actual = input.format(key='') output_ast = output.format(key='') output_as_text = output.format(key=key) if as_text_output is not None: output_as_text = as_text_output # first a simple check of the AST ast = parse(name, input_actual) res = str(ast) if res != output_ast: print() print('Input: ', input) print('Result: ', res) print('Expected: ', output_ast) raise DefinitionError root_symbol = Symbol(None, None, None, None, None) symbol = root_symbol.add_declaration(ast, docname='TestDoc', line=42) parent_node = addnodes.desc() signode = addnodes.desc_signature(input, '') parent_node += signode ast.describe_signature(signode, 'lastIsName', symbol, options={}) res_as_text = parent_node.astext() if res_as_text != output_as_text: print() print('Input: ', input) print('astext(): ', res_as_text) print('Expected: ', output_as_text) raise DefinitionError id_expected = [None] for i in range(1, _max_id + 1): if i in id_dict: id_expected.append(id_dict[i]) else: id_expected.append(id_expected[i - 1]) id_actual = [None] for i in range(1, _max_id + 1): # try: id = ast.get_id(version=i) assert id is not None id_actual.append(id[len(_id_prefix[i]) :]) # except NoOldIdError: # id_actual.append(None) res = [True] for i in range(1, _max_id + 1): res.append(id_expected[i] == id_actual[i]) if not all(res): print('input: %s' % input.rjust(20)) for i in range(1, _max_id + 1): if res[i]: continue print('Error in id version %d.' % i) print('result: %s' % id_actual[i]) print('expected: %s' % id_expected[i]) # print(root_symbol.dump(0)) raise DefinitionError def check(name, input, id_dict, output=None, key=None, as_text_output=None): if output is None: output = input # First, check without semicolon _check(name, input, id_dict, output, key, as_text_output) if name != 'macro': # Second, check with semicolon _check( name, input + ' ;', id_dict, output + ';', key, as_text_output + ';' if as_text_output is not None else None, ) def test_domain_c_ast_expressions() -> None: def expr_check(expr, output=None): parser = DefinitionParser(expr, location=None, config=Config()) parser.allowFallbackExpressionParsing = False ast = parser.parse_expression() parser.assert_end() # first a simple check of the AST if output is None: output = expr res = str(ast) if res != output: print() print('Input: ', input) print('Result: ', res) print('Expected: ', output) raise DefinitionError display_string = ast.get_display_string() if res != display_string: # note: if the expression contains an anon name then this will trigger a falsely print() print('Input: ', expr) print('Result: ', res) print('Display: ', display_string) raise DefinitionError # type expressions expr_check('int*') expr_check('int *const*') expr_check('int *volatile*') expr_check('int *restrict*') expr_check('int *(*)(double)') expr_check('const int*') expr_check('__int64') expr_check('unsigned __int64') # actual expressions # primary expr_check('true') expr_check('false') ints = [ '5', '0', '075', '0x0123456789ABCDEF', '0XF', '0b1', '0B1', "0b0'1'0", "00'1'2", "0x0'1'2", "1'2'3", ] unsigned_suffix = ['', 'u', 'U'] long_suffix = ['', 'l', 'L', 'll', 'LL'] for i in ints: for u in unsigned_suffix: for l in long_suffix: expr = i + u + l expr_check(expr) expr = i + l + u expr_check(expr) for suffix in ('', 'f', 'F', 'l', 'L'): for e in ( '5e42', '5e+42', '5e-42', '5.', '5.e42', '5.e+42', '5.e-42', '.5', '.5e42', '.5e+42', '.5e-42', '5.0', '5.0e42', '5.0e+42', '5.0e-42', "1'2'3e7'8'9", "1'2'3.e7'8'9", ".4'5'6e7'8'9", "1'2'3.4'5'6e7'8'9", ): expr = e + suffix expr_check(expr) for e in ( 'ApF', 'Ap+F', 'Ap-F', 'A.', 'A.pF', 'A.p+F', 'A.p-F', '.A', '.ApF', '.Ap+F', '.Ap-F', 'A.B', 'A.BpF', 'A.Bp+F', 'A.Bp-F', "A'B'Cp1'2'3", "A'B'C.p1'2'3", ".D'E'Fp1'2'3", "A'B'C.D'E'Fp1'2'3", ): expr = '0x' + e + suffix expr_check(expr) expr_check('"abc\\"cba"') # string # character literals for p in ('', 'u8', 'u', 'U', 'L'): expr_check(p + "'a'") expr_check(p + "'\\n'") expr_check(p + "'\\012'") expr_check(p + "'\\0'") expr_check(p + "'\\x0a'") expr_check(p + "'\\x0A'") expr_check(p + "'\\u0a42'") expr_check(p + "'\\u0A42'") expr_check(p + "'\\U0001f34c'") expr_check(p + "'\\U0001F34C'") expr_check('(5)') expr_check('C') # postfix expr_check('A(2)') expr_check('A[2]') expr_check('a.b.c') expr_check('a->b->c') expr_check('i++') expr_check('i--') # unary expr_check('++5') expr_check('--5') expr_check('*5') expr_check('&5') expr_check('+5') expr_check('-5') expr_check('!5') expr_check('not 5') expr_check('~5') expr_check('compl 5') expr_check('sizeof(T)') expr_check('sizeof -42') expr_check('alignof(T)') # cast expr_check('(int)2') # binary op expr_check('5 || 42') expr_check('5 or 42') expr_check('5 && 42') expr_check('5 and 42') expr_check('5 | 42') expr_check('5 bitor 42') expr_check('5 ^ 42') expr_check('5 xor 42') expr_check('5 & 42') expr_check('5 bitand 42') # ['==', '!='] expr_check('5 == 42') expr_check('5 != 42') expr_check('5 not_eq 42') # ['<=', '>=', '<', '>'] expr_check('5 <= 42') expr_check('5 >= 42') expr_check('5 < 42') expr_check('5 > 42') # ['<<', '>>'] expr_check('5 << 42') expr_check('5 >> 42') # ['+', '-'] expr_check('5 + 42') expr_check('5 - 42') # ['*', '/', '%'] expr_check('5 * 42') expr_check('5 / 42') expr_check('5 % 42') # ['.*', '->*'] expr_check('5 .* 42') expr_check('5 ->* 42') # TODO: conditional is unimplemented # conditional # expr_check('5 ? 7 : 3') # assignment expr_check('a = 5') expr_check('a *= 5') expr_check('a /= 5') expr_check('a %= 5') expr_check('a += 5') expr_check('a -= 5') expr_check('a >>= 5') expr_check('a <<= 5') expr_check('a &= 5') expr_check('a and_eq 5') expr_check('a ^= 5') expr_check('a xor_eq 5') expr_check('a |= 5') expr_check('a or_eq 5') def test_domain_c_ast_fundamental_types() -> None: def types(): def signed(t): yield t yield 'signed ' + t yield 'unsigned ' + t # integer types # ------------- yield 'void' yield from ('_Bool', 'bool') yield from signed('char') yield from signed('short') yield from signed('short int') yield from signed('int') yield from ('signed', 'unsigned') yield from signed('long') yield from signed('long int') yield from signed('long long') yield from signed('long long int') yield from ('__int128', '__uint128') # extensions for t in ('__int8', '__int16', '__int32', '__int64', '__int128'): yield from signed(t) # floating point types # -------------------- yield from ('_Decimal32', '_Decimal64', '_Decimal128') for f in ('float', 'double', 'long double'): yield f yield from (f + ' _Complex', f + ' complex') yield from ('_Complex ' + f, 'complex ' + f) yield from ('_Imaginary ' + f, 'imaginary ' + f) # extensions # https://gcc.gnu.org/onlinedocs/gcc/Floating-Types.html#Floating-Types yield from ( '__float80', '_Float64x', '__float128', '_Float128', '__ibm128', ) # https://gcc.gnu.org/onlinedocs/gcc/Half-Precision.html#Half-Precision yield '__fp16' # fixed-point types (extension) # ----------------------------- # https://gcc.gnu.org/onlinedocs/gcc/Fixed-Point.html#Fixed-Point for sat in ('', '_Sat '): for t in ('_Fract', 'fract', '_Accum', 'accum'): for size in ('short ', '', 'long ', 'long long '): for tt in signed(size + t): yield sat + tt for t in types(): input = '{key}%s foo' % t output = ' '.join(input.split()) check('type', input, {1: 'foo'}, key='typedef', output=output) if ' ' in t: # try permutations of all components tcs = t.split() for p in itertools.permutations(tcs): input = '{key}%s foo' % ' '.join(p) output = ' '.join(input.split()) check('type', input, {1: 'foo'}, key='typedef', output=output) def test_domain_c_ast_type_definitions() -> None: check('type', '{key}T', {1: 'T'}) check('type', '{key}bool *b', {1: 'b'}, key='typedef') check('type', '{key}bool *const b', {1: 'b'}, key='typedef') check('type', '{key}bool *const *b', {1: 'b'}, key='typedef') check('type', '{key}bool *volatile *b', {1: 'b'}, key='typedef') check('type', '{key}bool *restrict *b', {1: 'b'}, key='typedef') check('type', '{key}bool *volatile const b', {1: 'b'}, key='typedef') check('type', '{key}bool *volatile const b', {1: 'b'}, key='typedef') check('type', '{key}bool *volatile const *b', {1: 'b'}, key='typedef') check('type', '{key}bool b[]', {1: 'b'}, key='typedef') check('type', '{key}long long int foo', {1: 'foo'}, key='typedef') # test decl specs on right check('type', '{key}bool const b', {1: 'b'}, key='typedef') # from https://github.com/breathe-doc/breathe/issues/267 # (named function parameters for function pointers check( 'type', '{key}void (*gpio_callback_t)(struct device *port, uint32_t pin)', {1: 'gpio_callback_t'}, key='typedef', ) def test_domain_c_ast_macro_definitions() -> None: check('macro', 'M', {1: 'M'}) check('macro', 'M()', {1: 'M'}) check('macro', 'M(arg)', {1: 'M'}) check('macro', 'M(arg1, arg2)', {1: 'M'}) check('macro', 'M(arg1, arg2, arg3)', {1: 'M'}) check('macro', 'M(...)', {1: 'M'}) check('macro', 'M(arg, ...)', {1: 'M'}) check('macro', 'M(arg1, arg2, ...)', {1: 'M'}) check('macro', 'M(arg1, arg2, arg3, ...)', {1: 'M'}) # GNU extension check('macro', 'M(arg1, arg2, arg3...)', {1: 'M'}) with pytest.raises(DefinitionError): check('macro', 'M(arg1, arg2..., arg3)', {1: 'M'}) def test_domain_c_ast_member_definitions() -> None: check('member', 'void a', {1: 'a'}) check('member', '_Bool a', {1: 'a'}) check('member', 'bool a', {1: 'a'}) check('member', 'char a', {1: 'a'}) check('member', 'int a', {1: 'a'}) check('member', 'float a', {1: 'a'}) check('member', 'double a', {1: 'a'}) check('member', 'unsigned long a', {1: 'a'}) check('member', '__int64 a', {1: 'a'}) check('member', 'unsigned __int64 a', {1: 'a'}) check('member', 'int .a', {1: 'a'}) check('member', 'int *a', {1: 'a'}) check('member', 'int **a', {1: 'a'}) check('member', 'const int a', {1: 'a'}) check('member', 'volatile int a', {1: 'a'}) check('member', 'restrict int a', {1: 'a'}) check('member', 'volatile const int a', {1: 'a'}) check('member', 'restrict const int a', {1: 'a'}) check('member', 'restrict volatile int a', {1: 'a'}) check('member', 'restrict volatile const int a', {1: 'a'}) check('member', 'T t', {1: 't'}) check('member', 'int a[]', {1: 'a'}) check('member', 'int (*p)[]', {1: 'p'}) check('member', 'int a[42]', {1: 'a'}) check('member', 'int a = 42', {1: 'a'}) check('member', 'T a = {}', {1: 'a'}) check('member', 'T a = {1}', {1: 'a'}) check('member', 'T a = {1, 2}', {1: 'a'}) check('member', 'T a = {1, 2, 3}', {1: 'a'}) # test from issue https://github.com/sphinx-doc/sphinx/issues/1539 check('member', 'CK_UTF8CHAR model[16]', {1: 'model'}) check('member', 'auto int a', {1: 'a'}) check('member', 'register int a', {1: 'a'}) check('member', 'extern int a', {1: 'a'}) check('member', 'static int a', {1: 'a'}) check('member', 'thread_local int a', {1: 'a'}) check('member', '_Thread_local int a', {1: 'a'}) check('member', 'extern thread_local int a', {1: 'a'}) check('member', 'thread_local extern int a', {1: 'a'}, 'extern thread_local int a') check('member', 'static thread_local int a', {1: 'a'}) check('member', 'thread_local static int a', {1: 'a'}, 'static thread_local int a') check('member', 'int b : 3', {1: 'b'}) def test_domain_c_ast_function_definitions() -> None: check('function', 'void f()', {1: 'f'}) check('function', 'void f(int)', {1: 'f'}) check('function', 'void f(int i)', {1: 'f'}) check('function', 'void f(int i, int j)', {1: 'f'}) check('function', 'void f(...)', {1: 'f'}) check('function', 'void f(int i, ...)', {1: 'f'}) check('function', 'void f(struct T)', {1: 'f'}) check('function', 'void f(struct T t)', {1: 'f'}) check('function', 'void f(union T)', {1: 'f'}) check('function', 'void f(union T t)', {1: 'f'}) check('function', 'void f(enum T)', {1: 'f'}) check('function', 'void f(enum T t)', {1: 'f'}) # test from issue https://github.com/sphinx-doc/sphinx/issues/1539 check('function', 'void f(A x[])', {1: 'f'}) # test from issue https://github.com/sphinx-doc/sphinx/issues/2377 check('function', 'void (*signal(int sig, void (*func)(int)))(int)', {1: 'signal'}) check('function', 'extern void f()', {1: 'f'}) check('function', 'static void f()', {1: 'f'}) check('function', 'inline void f()', {1: 'f'}) # tests derived from https://github.com/sphinx-doc/sphinx/issues/1753 # (skip to keep sanity) check('function', 'void f(float *q(double))', {1: 'f'}) check('function', 'void f(float *(*q)(double))', {1: 'f'}) check('function', 'void f(float (*q)(double))', {1: 'f'}) check('function', 'int (*f(double d))(float)', {1: 'f'}) check('function', 'int (*f(bool b))[5]', {1: 'f'}) check('function', 'void f(int *const p)', {1: 'f'}) check('function', 'void f(int *volatile const p)', {1: 'f'}) # from https://github.com/breathe-doc/breathe/issues/223 check('function', 'void f(struct E e)', {1: 'f'}) check('function', 'void f(enum E e)', {1: 'f'}) check('function', 'void f(union E e)', {1: 'f'}) # array declarators check('function', 'void f(int arr[])', {1: 'f'}) check('function', 'void f(int arr[*])', {1: 'f'}) cvrs = ['', 'const', 'volatile', 'restrict', 'restrict volatile const'] for cvr in cvrs: space = ' ' if len(cvr) != 0 else '' check('function', f'void f(int arr[{cvr}*])', {1: 'f'}) check('function', f'void f(int arr[{cvr}])', {1: 'f'}) check('function', f'void f(int arr[{cvr}{space}42])', {1: 'f'}) check('function', f'void f(int arr[static{space}{cvr} 42])', {1: 'f'}) check( 'function', f'void f(int arr[{cvr}{space}static 42])', {1: 'f'}, output=f'void f(int arr[static{space}{cvr} 42])', ) check( 'function', 'void f(int arr[const static volatile 42])', {1: 'f'}, output='void f(int arr[static volatile const 42])', ) with pytest.raises(DefinitionError): parse('function', 'void f(int for)') # from https://github.com/sphinx-doc/sphinx/issues/8960 check('function', 'void f(void (*p)(int, double), int i)', {1: 'f'}) def test_domain_c_ast_nested_name() -> None: check('struct', '{key}.A', {1: 'A'}) check('struct', '{key}.A.B', {1: 'A.B'}) check('function', 'void f(.A a)', {1: 'f'}) check('function', 'void f(.A.B a)', {1: 'f'}) def test_domain_c_ast_struct_definitions() -> None: check('struct', '{key}A', {1: 'A'}) def test_domain_c_ast_union_definitions() -> None: check('union', '{key}A', {1: 'A'}) def test_domain_c_ast_enum_definitions() -> None: check('enum', '{key}A', {1: 'A'}) check('enumerator', '{key}A', {1: 'A'}) check('enumerator', '{key}A = 42', {1: 'A'}) def test_domain_c_ast_anon_definitions() -> None: check('struct', '@a', {1: '@a'}, as_text_output='struct [anonymous]') check('union', '@a', {1: '@a'}, as_text_output='union [anonymous]') check('enum', '@a', {1: '@a'}, as_text_output='enum [anonymous]') check('struct', '@1', {1: '@1'}, as_text_output='struct [anonymous]') check('struct', '@a.A', {1: '@a.A'}, as_text_output='struct [anonymous].A') def test_domain_c_ast_initializers() -> None: ids_member = {1: 'v'} ids_function = {1: 'f'} # no init check('member', 'T v', ids_member) check('function', 'void f(T v)', ids_function) # with '=', assignment-expression check('member', 'T v = 42', ids_member) check('function', 'void f(T v = 42)', ids_function) # with '=', braced-init check('member', 'T v = {}', ids_member) check('function', 'void f(T v = {})', ids_function) check('member', 'T v = {42, 42, 42}', ids_member) check('function', 'void f(T v = {42, 42, 42})', ids_function) check('member', 'T v = {42, 42, 42,}', ids_member) check('function', 'void f(T v = {42, 42, 42,})', ids_function) # TODO: designator-list def test_domain_c_ast_attributes() -> None: # style: C++ check('member', '[[]] int f', {1: 'f'}) check( 'member', '[ [ ] ] int f', {1: 'f'}, # this will fail when the proper grammar is implemented output='[[ ]] int f', ) check('member', '[[a]] int f', {1: 'f'}) # style: GNU check('member', '__attribute__(()) int f', {1: 'f'}) check('member', '__attribute__((a)) int f', {1: 'f'}) check('member', '__attribute__((a, b)) int f', {1: 'f'}) check('member', '__attribute__((optimize(3))) int f', {1: 'f'}) check('member', '__attribute__((format(printf, 1, 2))) int f', {1: 'f'}) # style: user-defined id check('member', 'id_attr int f', {1: 'f'}) # style: user-defined paren check('member', 'paren_attr() int f', {1: 'f'}) check('member', 'paren_attr(a) int f', {1: 'f'}) check('member', 'paren_attr("") int f', {1: 'f'}) check('member', 'paren_attr(()[{}][]{}) int f', {1: 'f'}) with pytest.raises(DefinitionError): parse('member', 'paren_attr(() int f') with pytest.raises(DefinitionError): parse('member', 'paren_attr([) int f') with pytest.raises(DefinitionError): parse('member', 'paren_attr({) int f') with pytest.raises(DefinitionError): parse('member', 'paren_attr([)]) int f') with pytest.raises(DefinitionError): parse('member', 'paren_attr((])) int f') with pytest.raises(DefinitionError): parse('member', 'paren_attr({]}) int f') # position: decl specs check( 'function', 'static inline __attribute__(()) void f()', {1: 'f'}, output='__attribute__(()) static inline void f()', ) check('function', '[[attr1]] [[attr2]] void f()', {1: 'f'}) # position: declarator check('member', 'int *[[attr1]] [[attr2]] i', {1: 'i'}) check( 'member', 'int *const [[attr1]] [[attr2]] volatile i', {1: 'i'}, output='int *[[attr1]] [[attr2]] volatile const i', ) check('member', 'int *[[attr1]] [[attr2]] *i', {1: 'i'}) # position: parameters check('function', 'void f() [[attr1]] [[attr2]]', {1: 'f'}) # position: enumerator check('enumerator', '{key}Foo [[attr1]] [[attr2]]', {1: 'Foo'}) check('enumerator', '{key}Foo [[attr1]] [[attr2]] = 42', {1: 'Foo'}) # issue https://github.com/breathe-doc/breathe/issues/500 check( 'function', 'LIGHTGBM_C_EXPORT int LGBM_BoosterFree(int handle)', {1: 'LGBM_BoosterFree'}, ) def test_extra_keywords() -> None: with pytest.raises(DefinitionError, match='Expected identifier in nested name'): parse('function', 'void complex(void)') # def test_print() -> None: # # used for getting all the ids out for checking # for a in ids: # print(a) # raise DefinitionError def split_warnings(warning: StringIO) -> list[str]: ws = warning.getvalue().split('\n') assert len(ws) >= 1 assert ws[-1] == '' return ws[:-1] def filter_warnings(warning: StringIO, file: str) -> list[str]: lines = split_warnings(warning) res = [ l for l in lines if 'domain-c' in l and f'{file}.rst' in l and "WARNING: document isn't included in any toctree" not in l ] print(f"Filtered warnings for file '{file}':") for w in res: print(w) return res def extract_role_links(app, filename): t = (app.outdir / filename).read_text(encoding='utf8') lis = [l for l in t.split('\n') if l.startswith('<li')] entries = [] for l in lis: li = ET.fromstring(l) # NoQA: S314 # using known data in tests a_list = list(li.iter('a')) assert len(a_list) == 1 a = a_list[0] target = a.attrib['href'].lstrip('#') title = a.attrib['title'] assert len(a) == 1 code = a[0] assert code.tag == 'code' text = ''.join(code.itertext()) entries.append((target, title, text)) return entries @pytest.mark.sphinx('html', testroot='domain-c', confoverrides={'nitpicky': True}) def test_domain_c_build(app): app.build(force_all=True) ws = filter_warnings(app.warning, 'index') assert len(ws) == 0 @pytest.mark.sphinx('html', testroot='domain-c', confoverrides={'nitpicky': True}) def test_domain_c_build_namespace(app): app.build(force_all=True) ws = filter_warnings(app.warning, 'namespace') assert len(ws) == 0 t = (app.outdir / 'namespace.html').read_text(encoding='utf8') for id_ in ('NS.NSVar', 'NULLVar', 'ZeroVar', 'NS2.NS3.NS2NS3Var', 'PopVar'): assert f'id="c.{id_}"' in t @pytest.mark.sphinx('html', testroot='domain-c', confoverrides={'nitpicky': True}) def test_domain_c_build_anon_dup_decl(app): app.build(force_all=True) ws = filter_warnings(app.warning, 'anon-dup-decl') assert len(ws) == 2 assert 'WARNING: c:identifier reference target not found: @a' in ws[0] assert 'WARNING: c:identifier reference target not found: @b' in ws[1] @pytest.mark.sphinx('html', testroot='_blank', confoverrides={'nitpicky': True}) def test_domain_c_build_semicolon(app): text = """ .. c:member:: int member; .. c:var:: int var; .. c:function:: void f(); .. .. c:macro:: NO_SEMICOLON; .. c:struct:: Struct; .. c:union:: Union; .. c:enum:: Enum; .. c:enumerator:: Enumerator; .. c:type:: Type; .. c:type:: int TypeDef; """ restructuredtext.parse(app, text) ws = split_warnings(app.warning) assert len(ws) == 0 @pytest.mark.sphinx('html', testroot='domain-c', confoverrides={'nitpicky': True}) def test_domain_c_build_function_param_target(app): # the anchor for function parameters should be the function app.build(force_all=True) ws = filter_warnings(app.warning, 'function_param_target') assert len(ws) == 0 entries = extract_role_links(app, 'function_param_target.html') assert entries == [ ('c.function_param_target.f', 'i', 'i'), ('c.function_param_target.f', 'f.i', 'f.i'), ] @pytest.mark.sphinx('html', testroot='domain-c', confoverrides={'nitpicky': True}) def test_domain_c_build_ns_lookup(app): app.build(force_all=True) ws = filter_warnings(app.warning, 'ns_lookup') assert len(ws) == 0 @pytest.mark.sphinx('html', testroot='domain-c', confoverrides={'nitpicky': True}) def test_domain_c_build_field_role(app): app.build(force_all=True) ws = filter_warnings(app.warning, 'field-role') assert len(ws) == 0 def _get_obj(app, query_name): domain = app.env.domains.c_domain for name, _dispname, object_type, docname, anchor, _prio in domain.get_objects(): if name == query_name: return docname, anchor, object_type return query_name, 'not', 'found' @pytest.mark.sphinx( 'html', testroot='domain-c-intersphinx', confoverrides={'nitpicky': True} ) def test_domain_c_build_intersphinx(tmp_path, app): # a splitting of test_ids_vs_tags0 into the primary directives in a remote project, # and then the references in the test project orig_source = """\ .. c:member:: int _member .. c:var:: int _var .. c:function:: void _function() .. c:macro:: _macro .. c:struct:: _struct .. c:union:: _union .. c:enum:: _enum .. c:enumerator:: _enumerator .. c:type:: _type .. c:function:: void _functionParam(int param) """ inv_file = tmp_path / 'inventory' inv_file.write_bytes( b"""\ # Sphinx inventory version 2 # Project: C Intersphinx Test # Version: # The remainder of this file is compressed using zlib. """ + zlib.compress(b"""\ _enum c:enum 1 index.html#c.$ - _enum._enumerator c:enumerator 1 index.html#c.$ - _enumerator c:enumerator 1 index.html#c._enum.$ - _function c:function 1 index.html#c.$ - _functionParam c:function 1 index.html#c.$ - _functionParam.param c:functionParam 1 index.html#c._functionParam - _macro c:macro 1 index.html#c.$ - _member c:member 1 index.html#c.$ - _struct c:struct 1 index.html#c.$ - _type c:type 1 index.html#c.$ - _union c:union 1 index.html#c.$ - _var c:member 1 index.html#c.$ - """) ) app.config.intersphinx_mapping = { 'local': ('https://localhost/intersphinx/c/', str(inv_file)), } app.config.intersphinx_cache_limit = 0 # load the inventory and check if it's done correctly validate_intersphinx_mapping(app, app.config) load_mappings(app) app.build(force_all=True) ws = filter_warnings(app.warning, 'index') assert len(ws) == 0 @pytest.mark.sphinx('html', testroot='_blank') def test_domain_c_parse_cfunction(app): text = ( '.. c:function:: PyObject* ' 'PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)' ) doctree = restructuredtext.parse(app, text) assert_node( doctree[1], addnodes.desc, desctype='function', domain='c', objtype='function', no_index=False, ) entry = _get_obj(app, 'PyType_GenericAlloc') assert entry == ('index', 'c.PyType_GenericAlloc', 'function') @pytest.mark.sphinx('html', testroot='_blank') def test_domain_c_parse_cmember(app): text = '.. c:member:: PyObject* PyTypeObject.tp_bases' doctree = restructuredtext.parse(app, text) assert_node( doctree[1], addnodes.desc, desctype='member', domain='c', objtype='member', no_index=False, ) entry = _get_obj(app, 'PyTypeObject.tp_bases') assert entry == ('index', 'c.PyTypeObject.tp_bases', 'member') @pytest.mark.sphinx('html', testroot='_blank') def test_domain_c_parse_cvar(app): text = '.. c:var:: PyObject* PyClass_Type' doctree = restructuredtext.parse(app, text) assert_node( doctree[1], addnodes.desc, desctype='var', domain='c', objtype='var', no_index=False, ) entry = _get_obj(app, 'PyClass_Type') assert entry == ('index', 'c.PyClass_Type', 'member') @pytest.mark.sphinx('html', testroot='_blank') def test_domain_c_parse_no_index_entry(app): text = '.. c:function:: void f()\n.. c:function:: void g()\n :no-index-entry:\n' doctree = restructuredtext.parse(app, text) assert_node(doctree, (addnodes.index, desc, addnodes.index, desc)) assert_node( doctree[0], addnodes.index, entries=[('single', 'f (C function)', 'c.f', '', None)], ) assert_node(doctree[2], addnodes.index, entries=[]) @pytest.mark.sphinx( 'html', testroot='_blank', confoverrides={ 'c_maximum_signature_line_length': len('str hello(str name)'), }, ) def test_cfunction_signature_with_c_maximum_signature_line_length_equal(app): text = '.. c:function:: str hello(str name)' doctree = restructuredtext.parse(app, text) assert_node( doctree, ( addnodes.index, [ desc, ( [ desc_signature, ( [ desc_signature_line, ( pending_xref, desc_sig_space, [desc_name, [desc_sig_name, 'hello']], desc_parameterlist, ), ], ), ], desc_content, ), ], ), ) assert_node( doctree[1], addnodes.desc, desctype='function', domain='c', objtype='function', no_index=False, ) assert_node( doctree[1][0][0][3], [ desc_parameterlist, desc_parameter, ( [pending_xref, [desc_sig_name, 'str']], desc_sig_space, [desc_sig_name, 'name'], ), ], ) assert_node( doctree[1][0][0][3], desc_parameterlist, multi_line_parameter_list=False ) @pytest.mark.sphinx( 'html', testroot='_blank', confoverrides={ 'c_maximum_signature_line_length': len('str hello(str name)'), }, ) def test_cfunction_signature_with_c_maximum_signature_line_length_force_single(app): text = '.. c:function:: str hello(str names)\n :single-line-parameter-list:' doctree = restructuredtext.parse(app, text) assert_node( doctree, ( addnodes.index, [ desc, ( [ desc_signature, ( [ desc_signature_line, ( pending_xref, desc_sig_space, [desc_name, [desc_sig_name, 'hello']], desc_parameterlist, ), ], ), ], desc_content, ), ], ), ) assert_node( doctree[1], addnodes.desc, desctype='function', domain='c', objtype='function', no_index=False, ) assert_node( doctree[1][0][0][3], [ desc_parameterlist, desc_parameter, ( [pending_xref, [desc_sig_name, 'str']], desc_sig_space, [desc_sig_name, 'names'], ), ], ) assert_node( doctree[1][0][0][3], desc_parameterlist, multi_line_parameter_list=False ) @pytest.mark.sphinx( 'html', testroot='_blank', confoverrides={ 'c_maximum_signature_line_length': len('str hello(str name)'), }, ) def test_cfunction_signature_with_c_maximum_signature_line_length_break(app): text = '.. c:function:: str hello(str names)' doctree = restructuredtext.parse(app, text) assert_node( doctree, ( addnodes.index, [ desc, ( [ desc_signature, ( [ desc_signature_line, ( pending_xref, desc_sig_space, [desc_name, [desc_sig_name, 'hello']], desc_parameterlist, ), ], ), ], desc_content, ), ], ), ) assert_node( doctree[1], addnodes.desc, desctype='function', domain='c', objtype='function', no_index=False, ) assert_node( doctree[1][0][0][3], [ desc_parameterlist, desc_parameter, ( [pending_xref, [desc_sig_name, 'str']], desc_sig_space, [desc_sig_name, 'names'], ), ], ) assert_node(doctree[1][0][0][3], desc_parameterlist, multi_line_parameter_list=True) @pytest.mark.sphinx( 'html', testroot='_blank', confoverrides={ 'maximum_signature_line_length': len('str hello(str name)'), }, ) def test_cfunction_signature_with_maximum_signature_line_length_equal(app): text = '.. c:function:: str hello(str name)' doctree = restructuredtext.parse(app, text) assert_node( doctree, ( addnodes.index, [ desc, ( [ desc_signature, ( [ desc_signature_line, ( pending_xref, desc_sig_space, [desc_name, [desc_sig_name, 'hello']], desc_parameterlist, ), ], ), ], desc_content, ), ], ), ) assert_node( doctree[1], addnodes.desc, desctype='function', domain='c', objtype='function', no_index=False, ) assert_node( doctree[1][0][0][3], [ desc_parameterlist, desc_parameter, ( [pending_xref, [desc_sig_name, 'str']], desc_sig_space, [desc_sig_name, 'name'], ), ], ) assert_node( doctree[1][0][0][3], desc_parameterlist, multi_line_parameter_list=False ) @pytest.mark.sphinx( 'html', testroot='_blank', confoverrides={ 'maximum_signature_line_length': len('str hello(str name)'), }, ) def test_cfunction_signature_with_maximum_signature_line_length_force_single(app): text = '.. c:function:: str hello(str names)\n :single-line-parameter-list:' doctree = restructuredtext.parse(app, text) assert_node( doctree, ( addnodes.index, [ desc, ( [ desc_signature, ( [ desc_signature_line, ( pending_xref, desc_sig_space, [desc_name, [desc_sig_name, 'hello']], desc_parameterlist, ), ], ), ], desc_content, ), ], ), ) assert_node( doctree[1], addnodes.desc, desctype='function', domain='c', objtype='function', no_index=False, ) assert_node( doctree[1][0][0][3], [ desc_parameterlist, desc_parameter, ( [pending_xref, [desc_sig_name, 'str']], desc_sig_space, [desc_sig_name, 'names'], ), ], ) assert_node( doctree[1][0][0][3], desc_parameterlist, multi_line_parameter_list=False ) @pytest.mark.sphinx( 'html', testroot='_blank', confoverrides={ 'maximum_signature_line_length': len('str hello(str name)'), }, ) def test_cfunction_signature_with_maximum_signature_line_length_break(app): text = '.. c:function:: str hello(str names)' doctree = restructuredtext.parse(app, text) assert_node( doctree, ( addnodes.index, [ desc, ( [ desc_signature, ( [ desc_signature_line, ( pending_xref, desc_sig_space, [desc_name, [desc_sig_name, 'hello']], desc_parameterlist, ), ], ), ], desc_content, ), ], ), ) assert_node( doctree[1], addnodes.desc, desctype='function', domain='c', objtype='function', no_index=False, ) assert_node( doctree[1][0][0][3], [ desc_parameterlist, desc_parameter, ( [pending_xref, [desc_sig_name, 'str']], desc_sig_space, [desc_sig_name, 'names'], ), ], ) assert_node(doctree[1][0][0][3], desc_parameterlist, multi_line_parameter_list=True) @pytest.mark.sphinx( 'html', testroot='_blank', confoverrides={ 'c_maximum_signature_line_length': len('str hello(str name)'), 'maximum_signature_line_length': 1, }, ) def test_c_maximum_signature_line_length_overrides_global(app): text = '.. c:function:: str hello(str name)' doctree = restructuredtext.parse(app, text) assert_node( doctree, ( addnodes.index, [ desc, ( [ desc_signature, ([ desc_signature_line, ( pending_xref, desc_sig_space, [desc_name, [desc_sig_name, 'hello']], desc_parameterlist, ), ]), ], desc_content, ), ], ), ) assert_node( doctree[1], addnodes.desc, desctype='function', domain='c', objtype='function', no_index=False, ) assert_node( doctree[1][0][0][3], [ desc_parameterlist, desc_parameter, ( [pending_xref, [desc_sig_name, 'str']], desc_sig_space, [desc_sig_name, 'name'], ), ], ) assert_node( doctree[1][0][0][3], desc_parameterlist, multi_line_parameter_list=False ) @pytest.mark.sphinx('html', testroot='domain-c-c_maximum_signature_line_length') def test_domain_c_c_maximum_signature_line_length_in_html(app): app.build() content = (app.outdir / 'index.html').read_text(encoding='utf-8') expected = """\ <dl> <dd>\ <span class="n"><span class="pre">str</span></span>\ <span class="w"> </span>\ <span class="n"><span class="pre">name</span></span>\ </dd> </dl> <span class="sig-paren">)</span>\ <a class="headerlink" href="#c.hello" title="Link to this definition">¶</a>\ <br />\ </dt> """ assert expected in content @pytest.mark.sphinx( 'text', testroot='domain-c-c_maximum_signature_line_length', ) def test_domain_c_c_maximum_signature_line_length_in_text(app): app.build() content = (app.outdir / 'index.txt').read_text(encoding='utf8') param_line_fmt = STDINDENT * ' ' + '{}\n' expected_parameter_list_hello = '(\n{})'.format(param_line_fmt.format('str name')) assert expected_parameter_list_hello in content
Config
python
facebook__pyre-check
tools/upgrade/filesystem.py
{ "start": 908, "end": 8301 }
class ____(builtin_ast.NodeVisitor): def __init__(self, pyre_only: bool) -> None: self._pyre_only: bool = pyre_only self._targets: List[Target] = [] self._contains_strict: bool = False @override def visit_Call(self, node: builtin_ast.Call) -> None: target_fields = node.keywords name = None check_types = False is_strict = False uses_pyre = True has_typing_settings = False for field in target_fields: name = self._get_name(field, name) check_types = self._get_check_types(field, check_types) is_strict = self._get_strict(field, is_strict, uses_pyre) uses_pyre = self._get_uses_pyre(field, uses_pyre) has_typing_settings = self._get_has_typing_settings( field, has_typing_settings ) if name and has_typing_settings and (not self._pyre_only or uses_pyre): self._targets.append(Target(name, is_strict, uses_pyre, check_types)) self._contains_strict = self._contains_strict or is_strict def _get_name( self, field: builtin_ast.keyword, name: Optional[str] ) -> Optional[str]: value = field.value if field.arg == "name": if isinstance(value, builtin_ast.Str): return value.s return name def _get_check_types(self, field: builtin_ast.keyword, check_types: bool) -> bool: value = field.value if field.arg == "check_types": if isinstance(value, builtin_ast.NameConstant): return check_types or value.value return check_types def _get_strict( self, field: builtin_ast.keyword, is_strict: bool, uses_pyre: bool ) -> bool: value = field.value if field.arg == "check_types_options": if isinstance(value, builtin_ast.Str): return is_strict or (uses_pyre and "strict" in value.s.lower()) elif field.arg == "typing_options": if isinstance(value, builtin_ast.Str): is_strict = is_strict or "strict" in value.s.lower() return is_strict def _get_uses_pyre(self, field: builtin_ast.keyword, uses_pyre: bool) -> bool: value = field.value if field.arg == "check_types_options": if isinstance(value, builtin_ast.Str): return uses_pyre and "mypy" not in value.s.lower() return uses_pyre def _get_has_typing_settings( self, field: builtin_ast.keyword, has_typing_settings: bool ) -> bool: return ( has_typing_settings or field.arg == "type_checker" or field.arg == "typing_options" or field.arg == "check_types_options" or field.arg == "check_types" or field.arg == "typing" ) def result(self) -> List[Target]: return self._targets def contains_strict(self) -> bool: return self._contains_strict def path_exists(filename: str) -> Path: path = Path(filename) if not path.exists(): raise ValueError(f"No file at {filename}") return path def find_targets(search_root: Path, pyre_only: bool = False) -> Dict[str, List[Target]]: LOG.info("Finding typecheck targets in %s", search_root) target_files = find_files(search_root, "TARGETS") target_names = {} total_targets = 0 for target_file in target_files: target_finder = TargetCollector(pyre_only) with open(target_file, "r") as source: tree = builtin_ast.parse(source.read()) target_finder.visit(tree) targets = target_finder.result() if len(targets) > 0: target_names[target_file] = targets total_targets += len(targets) LOG.info( f"Found {total_targets} typecheck targets in {len(target_names)} " + "TARGETS files to analyze" ) return target_names def get_lines_with_modes( lines: List[str], modes: List[LocalMode] ) -> Dict[int, LocalMode]: lines_with_modes: Dict[int, LocalMode] = {} for index, line in enumerate(lines): for mode in modes: if re.match(mode.get_regex(), line): # add one to index, since line numbers start at 1 lines_with_modes[index + 1] = mode continue return lines_with_modes def remove_local_mode(path: Path, modes: List[LocalMode]) -> List[LocalMode]: LOG.info("Processing `%s`", str(path)) text = path.read_text() if "@" "generated" in text or "@" "partially-generated" in text: LOG.warning("Attempting to edit generated file %s, skipping.", str(path)) return [] lines: List[str] = text.split("\n") lines_with_modes = get_lines_with_modes(lines, modes) lines = [ line for index, line in enumerate(lines) if index + 1 not in lines_with_modes ] new_text = "\n".join(lines) ast.check_stable(text, new_text) path.write_text(new_text) return list(lines_with_modes.values()) def replace_local_mode(lines: List[str], mode: LocalMode, path: Path) -> bool: new_lines = [] LOG for line in lines: local_mode_line = False for local_mode in LocalMode: if re.match(local_mode.get_regex(), line): local_mode_line = True if local_mode_line: new_lines.append(mode.get_comment()) else: new_lines.append(line) new_text = "\n".join(new_lines) path.write_text(new_text) return True def add_local_mode( filename: str, mode: LocalMode, ignore_empty_files: bool = False, override: bool = False, ) -> bool: LOG.info("Processing `%s`", filename) path = Path(filename) text = path.read_text() if ignore_empty_files and len(text.strip()) == 0: return False if "@" "generated" in text or "@" "partially-generated" in text: LOG.warning("Attempting to edit generated file %s, skipping.", filename) return False lines: "List[str]" = text.split("\n") # Check if a local mode is already set. for line in lines: for local_mode in LocalMode: if re.match(local_mode.get_regex(), line): if override: return replace_local_mode(lines, mode, path) return False def is_header(line: str) -> bool: is_comment = line.lstrip().startswith("#") is_pyre_ignore = ( ( re.match("^[ \t]*# *pyre-ignore.*$", line) and not re.match("^[ \t]*# *pyre-ignore-all-errors *$", line) ) or re.match("^[ \t]*# *pyre-fixme.*$", line) or re.match("^[ \t]*# *type: ignore.*$", line) ) is_autodeps_header = re.match("[ \t]*# *@manual.*$", line) return is_comment and not is_pyre_ignore and not is_autodeps_header # Add local mode. new_lines = [] past_header = False for line in lines: if not past_header and not is_header(line): past_header = True if len(new_lines) != 0: new_lines.append("") new_lines.append(mode.get_comment()) new_lines.append(line) new_text = "\n".join(new_lines) ast.check_stable(text, new_text) path.write_text(new_text) return True
TargetCollector
python
sqlalchemy__sqlalchemy
test/orm/dml/test_orm_upd_del_inheritance.py
{ "start": 14102, "end": 18149 }
class ____(fixtures.DeclarativeMappedTest): __sparse_driver_backend__ = True @classmethod def setup_classes(cls): Base = cls.DeclarativeBasic class Staff(Base): __tablename__ = "staff" position = Column(String(10), nullable=False) id = Column( Integer, primary_key=True, test_needs_autoincrement=True ) name = Column(String(5)) stats = Column(String(5)) __mapper_args__ = {"polymorphic_on": position} class Sales(Staff): sales_stats = Column(String(5)) __mapper_args__ = {"polymorphic_identity": "sales"} class Support(Staff): support_stats = Column(String(5)) __mapper_args__ = {"polymorphic_identity": "support"} @classmethod def insert_data(cls, connection): with sessionmaker(connection).begin() as session: Sales, Support = ( cls.classes.Sales, cls.classes.Support, ) session.add_all( [ Sales(name="n1", sales_stats="1", stats="a"), Sales(name="n2", sales_stats="2", stats="b"), Support(name="n1", support_stats="3", stats="c"), Support(name="n2", support_stats="4", stats="d"), ] ) @testing.combinations( ("fetch", False), ("fetch", True), ("evaluate", False), ("evaluate", True), ) def test_update(self, fetchstyle, newstyle): Staff, Sales, Support = self.classes("Staff", "Sales", "Support") sess = fixture_session() en1, en2 = ( sess.execute(select(Sales).order_by(Sales.sales_stats)) .scalars() .all() ) mn1, mn2 = ( sess.execute(select(Support).order_by(Support.support_stats)) .scalars() .all() ) if newstyle: sess.execute( update(Sales) .filter_by(name="n1") .values(stats="p") .execution_options(synchronize_session=fetchstyle) ) else: sess.query(Sales).filter_by(name="n1").update( {"stats": "p"}, synchronize_session=fetchstyle ) eq_(en1.stats, "p") eq_(mn1.stats, "c") eq_( sess.execute( select(Staff.position, Staff.name, Staff.stats).order_by( Staff.id ) ).all(), [ ("sales", "n1", "p"), ("sales", "n2", "b"), ("support", "n1", "c"), ("support", "n2", "d"), ], ) @testing.combinations( ("fetch", False), ("fetch", True), ("evaluate", False), ("evaluate", True), ) def test_delete(self, fetchstyle, newstyle): Staff, Sales, Support = self.classes("Staff", "Sales", "Support") sess = fixture_session() en1, en2 = sess.query(Sales).order_by(Sales.sales_stats).all() mn1, mn2 = sess.query(Support).order_by(Support.support_stats).all() if newstyle: sess.execute( delete(Sales) .filter_by(name="n1") .execution_options(synchronize_session=fetchstyle) ) else: sess.query(Sales).filter_by(name="n1").delete( synchronize_session=fetchstyle ) assert en1 not in sess assert en2 in sess assert mn1 in sess assert mn2 in sess eq_( sess.execute( select(Staff.position, Staff.name, Staff.stats).order_by( Staff.id ) ).all(), [ ("sales", "n2", "b"), ("support", "n1", "c"), ("support", "n2", "d"), ], )
SingleTablePolymorphicTest
python
Textualize__textual
src/textual/widgets/_checkbox.py
{ "start": 130, "end": 803 }
class ____(ToggleButton): """A check box widget that represents a boolean value.""" class Changed(ToggleButton.Changed): """Posted when the value of the checkbox changes. This message can be handled using an `on_checkbox_changed` method. """ @property def checkbox(self) -> Checkbox: """The checkbox that was changed.""" assert isinstance(self._toggle_button, Checkbox) return self._toggle_button @property def control(self) -> Checkbox: """An alias for [Changed.checkbox][textual.widgets.Checkbox.Changed.checkbox].""" return self.checkbox
Checkbox
python
kamyu104__LeetCode-Solutions
Python/pour-water.py
{ "start": 33, "end": 624 }
class ____(object): def pourWater(self, heights, V, K): """ :type heights: List[int] :type V: int :type K: int :rtype: List[int] """ for _ in xrange(V): best = K for d in (-1, 1): i = K while 0 <= i+d < len(heights) and \ heights[i+d] <= heights[i]: if heights[i+d] < heights[i]: best = i+d i += d if best != K: break heights[best] += 1 return heights
Solution
python
gevent__gevent
src/greentest/3.10/test_threading.py
{ "start": 55723, "end": 55887 }
class ____(lock_tests.RLockTests): # Condition uses an RLock by default and exports its API. locktype = staticmethod(threading.Condition)
ConditionAsRLockTests
python
doocs__leetcode
solution/0900-0999/0965.Univalued Binary Tree/Solution.py
{ "start": 192, "end": 497 }
class ____: def isUnivalTree(self, root: Optional[TreeNode]) -> bool: def dfs(root: Optional[TreeNode]) -> bool: if root is None: return True return root.val == x and dfs(root.left) and dfs(root.right) x = root.val return dfs(root)
Solution
python
realpython__materials
wordcount/tests/realpython/models.py
{ "start": 420, "end": 572 }
class ____: number: int name: str url: str def __str__(self) -> str: return f"[Task {self.number}: {self.name}]({self.url})"
Task
python
run-llama__llama_index
llama-index-core/llama_index/core/retrievers/fusion_retriever.py
{ "start": 1278, "end": 12413 }
class ____(BaseRetriever): def __init__( self, retrievers: List[BaseRetriever], llm: Optional[LLMType] = None, query_gen_prompt: Optional[str] = None, mode: FUSION_MODES = FUSION_MODES.SIMPLE, similarity_top_k: int = DEFAULT_SIMILARITY_TOP_K, num_queries: int = 4, use_async: bool = True, verbose: bool = False, callback_manager: Optional[CallbackManager] = None, objects: Optional[List[IndexNode]] = None, object_map: Optional[dict] = None, retriever_weights: Optional[List[float]] = None, ) -> None: self.num_queries = num_queries self.query_gen_prompt = query_gen_prompt or QUERY_GEN_PROMPT self.similarity_top_k = similarity_top_k self.mode = mode self.use_async = use_async self._retrievers = retrievers if retriever_weights is None: self._retriever_weights = [1.0 / len(retrievers)] * len(retrievers) else: # Sum of retriever_weights must be 1 total_weight = sum(retriever_weights) self._retriever_weights = [w / total_weight for w in retriever_weights] self._llm = ( resolve_llm(llm, callback_manager=callback_manager) if llm else Settings.llm ) super().__init__( callback_manager=callback_manager, object_map=object_map, objects=objects, verbose=verbose, ) def _get_prompts(self) -> PromptDictType: """Get prompts.""" return {"query_gen_prompt": PromptTemplate(self.query_gen_prompt)} def _update_prompts(self, prompts: PromptDictType) -> None: """Update prompts.""" if "query_gen_prompt" in prompts: self.query_gen_prompt = cast( PromptTemplate, prompts["query_gen_prompt"] ).template def _get_queries(self, original_query: str) -> List[QueryBundle]: prompt_str = self.query_gen_prompt.format( num_queries=self.num_queries - 1, query=original_query, ) response = self._llm.complete(prompt_str) # Strip code block and assume LLM properly put each query on a newline queries = response.text.strip("`").split("\n") queries = [q.strip() for q in queries if q.strip()] if self._verbose: queries_str = "\n".join(queries) print(f"Generated queries:\n{queries_str}") # The LLM often returns more queries than we asked for, so trim the list. return [QueryBundle(q) for q in queries[: self.num_queries - 1]] def _reciprocal_rerank_fusion( self, results: Dict[Tuple[str, int], List[NodeWithScore]] ) -> List[NodeWithScore]: """ Apply reciprocal rank fusion. The original paper uses k=60 for best results: https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf """ k = 60.0 # `k` is a parameter used to control the impact of outlier rankings. fused_scores = {} hash_to_node = {} # compute reciprocal rank scores for nodes_with_scores in results.values(): for rank, node_with_score in enumerate( sorted(nodes_with_scores, key=lambda x: x.score or 0.0, reverse=True) ): hash = node_with_score.node.hash hash_to_node[hash] = node_with_score if hash not in fused_scores: fused_scores[hash] = 0.0 fused_scores[hash] += 1.0 / (rank + k) # sort results reranked_results = dict( sorted(fused_scores.items(), key=lambda x: x[1], reverse=True) ) # adjust node scores reranked_nodes: List[NodeWithScore] = [] for hash, score in reranked_results.items(): reranked_nodes.append(hash_to_node[hash]) reranked_nodes[-1].score = score return reranked_nodes def _relative_score_fusion( self, results: Dict[Tuple[str, int], List[NodeWithScore]], dist_based: Optional[bool] = False, ) -> List[NodeWithScore]: """Apply relative score fusion.""" # MinMax scale scores of each result set (highest value becomes 1, lowest becomes 0) # then scale by the weight of the retriever min_max_scores = {} for query_tuple, nodes_with_scores in results.items(): if not nodes_with_scores: min_max_scores[query_tuple] = (0.0, 0.0) continue scores = [ node_with_score.score or 0.0 for node_with_score in nodes_with_scores ] if dist_based: # Set min and max based on mean and std dev mean_score = sum(scores) / len(scores) std_dev = ( sum((x - mean_score) ** 2 for x in scores) / len(scores) ) ** 0.5 min_score = mean_score - 3 * std_dev max_score = mean_score + 3 * std_dev else: min_score = min(scores) max_score = max(scores) min_max_scores[query_tuple] = (min_score, max_score) for query_tuple, nodes_with_scores in results.items(): for node_with_score in nodes_with_scores: min_score, max_score = min_max_scores[query_tuple] # Scale the score to be between 0 and 1 if max_score == min_score: node_with_score.score = 1.0 if max_score > 0 else 0.0 else: node_with_score.score = (node_with_score.score - min_score) / ( max_score - min_score ) # Scale by the weight of the retriever retriever_idx = query_tuple[1] existing_score = node_with_score.score or 0.0 node_with_score.score = ( existing_score * self._retriever_weights[retriever_idx] ) # Divide by the number of queries node_with_score.score /= self.num_queries # Use a dict to de-duplicate nodes all_nodes: Dict[str, NodeWithScore] = {} # Sum scores for each node for nodes_with_scores in results.values(): for node_with_score in nodes_with_scores: hash = node_with_score.node.hash if hash in all_nodes: cur_score = all_nodes[hash].score or 0.0 all_nodes[hash].score = cur_score + (node_with_score.score or 0.0) else: all_nodes[hash] = node_with_score return sorted(all_nodes.values(), key=lambda x: x.score or 0.0, reverse=True) def _simple_fusion( self, results: Dict[Tuple[str, int], List[NodeWithScore]] ) -> List[NodeWithScore]: """Apply simple fusion.""" # Use a dict to de-duplicate nodes all_nodes: Dict[str, NodeWithScore] = {} for nodes_with_scores in results.values(): for node_with_score in nodes_with_scores: hash = node_with_score.node.hash if hash in all_nodes: max_score = max( node_with_score.score or 0.0, all_nodes[hash].score or 0.0 ) all_nodes[hash].score = max_score else: all_nodes[hash] = node_with_score return sorted(all_nodes.values(), key=lambda x: x.score or 0.0, reverse=True) def _run_nested_async_queries( self, queries: List[QueryBundle] ) -> Dict[Tuple[str, int], List[NodeWithScore]]: tasks, task_queries = [], [] for query in queries: for i, retriever in enumerate(self._retrievers): tasks.append(retriever.aretrieve(query)) task_queries.append((query.query_str, i)) task_results = run_async_tasks(tasks) results = {} for query_tuple, query_result in zip(task_queries, task_results): results[query_tuple] = query_result return results async def _run_async_queries( self, queries: List[QueryBundle] ) -> Dict[Tuple[str, int], List[NodeWithScore]]: tasks, task_queries = [], [] for query in queries: for i, retriever in enumerate(self._retrievers): tasks.append(retriever.aretrieve(query)) task_queries.append((query.query_str, i)) task_results = await asyncio.gather(*tasks) results = {} for query_tuple, query_result in zip(task_queries, task_results): results[query_tuple] = query_result return results def _run_sync_queries( self, queries: List[QueryBundle] ) -> Dict[Tuple[str, int], List[NodeWithScore]]: results = {} for query in queries: for i, retriever in enumerate(self._retrievers): results[(query.query_str, i)] = retriever.retrieve(query) return results def _retrieve(self, query_bundle: QueryBundle) -> List[NodeWithScore]: queries: List[QueryBundle] = [query_bundle] if self.num_queries > 1: queries.extend(self._get_queries(query_bundle.query_str)) if self.use_async: results = self._run_nested_async_queries(queries) else: results = self._run_sync_queries(queries) if self.mode == FUSION_MODES.RECIPROCAL_RANK: return self._reciprocal_rerank_fusion(results)[: self.similarity_top_k] elif self.mode == FUSION_MODES.RELATIVE_SCORE: return self._relative_score_fusion(results)[: self.similarity_top_k] elif self.mode == FUSION_MODES.DIST_BASED_SCORE: return self._relative_score_fusion(results, dist_based=True)[ : self.similarity_top_k ] elif self.mode == FUSION_MODES.SIMPLE: return self._simple_fusion(results)[: self.similarity_top_k] else: raise ValueError(f"Invalid fusion mode: {self.mode}") async def _aretrieve(self, query_bundle: QueryBundle) -> List[NodeWithScore]: queries: List[QueryBundle] = [query_bundle] if self.num_queries > 1: queries.extend(self._get_queries(query_bundle.query_str)) results = await self._run_async_queries(queries) if self.mode == FUSION_MODES.RECIPROCAL_RANK: return self._reciprocal_rerank_fusion(results)[: self.similarity_top_k] elif self.mode == FUSION_MODES.RELATIVE_SCORE: return self._relative_score_fusion(results)[: self.similarity_top_k] elif self.mode == FUSION_MODES.DIST_BASED_SCORE: return self._relative_score_fusion(results, dist_based=True)[ : self.similarity_top_k ] elif self.mode == FUSION_MODES.SIMPLE: return self._simple_fusion(results)[: self.similarity_top_k] else: raise ValueError(f"Invalid fusion mode: {self.mode}")
QueryFusionRetriever
python
doocs__leetcode
solution/1000-1099/1056.Confusing Number/Solution.py
{ "start": 0, "end": 287 }
class ____: def confusingNumber(self, n: int) -> bool: x, y = n, 0 d = [0, 1, -1, -1, -1, -1, 9, -1, 8, 6] while x: x, v = divmod(x, 10) if d[v] < 0: return False y = y * 10 + d[v] return y != n
Solution
python
numba__numba
numba/tests/test_extending.py
{ "start": 34116, "end": 35961 }
class ____(TestCase): # Nested multiprocessing.Pool raises AssertionError: # "daemonic processes are not allowed to have children" _numba_parallel_test_ = False def test_caching_overload_method(self): self._cache_dir = temp_directory(self.__class__.__name__) with override_config("CACHE_DIR", self._cache_dir): self.run_caching_overload_method() def run_caching_overload_method(self): cfunc = jit(nopython=True, cache=True)(cache_overload_method_usecase) self.assertPreciseEqual(cfunc(MyDummy()), 13) _assert_cache_stats(cfunc, 0, 1) llvmir = cfunc.inspect_llvm((mydummy_type,)) # Ensure the inner method is not a declaration decls = [ ln for ln in llvmir.splitlines() if ln.startswith("declare") and "overload_method_length" in ln ] self.assertEqual(len(decls), 0) # Test in a separate process try: ctx = multiprocessing.get_context("spawn") except AttributeError: ctx = multiprocessing q = ctx.Queue() p = ctx.Process( target=run_caching_overload_method, args=(q, self._cache_dir) ) p.start() q.put(MyDummy()) p.join() # Ensure subprocess exited normally self.assertEqual(p.exitcode, 0) res = q.get(timeout=1) self.assertEqual(res, 13) def run_caching_overload_method(q, cache_dir): """ Used by TestOverloadMethodCaching.test_caching_overload_method """ with override_config("CACHE_DIR", cache_dir): arg = q.get() cfunc = jit(nopython=True, cache=True)(cache_overload_method_usecase) res = cfunc(arg) q.put(res) # Check cache stat _assert_cache_stats(cfunc, 1, 0)
TestOverloadMethodCaching
python
airbytehq__airbyte
airbyte-integrations/connectors/source-hubspot/unit_tests/integrations/request_builders/streams.py
{ "start": 224, "end": 923 }
class ____(AbstractRequestBuilder): URL = "https://api.hubapi.com/events/v3/events" def __init__(self): self._token = None self._query_params = {} self._request_body = None self._headers = {} def with_token(self, token: str): self._token = token return self @property def headers(self) -> Dict[str, Any]: return {"Authorization": f"Bearer {self._token}"} def with_query(self, qp): self._query_params = qp return self def build(self) -> HttpRequest: return HttpRequest(url=self.URL, query_params=self._query_params, headers=self.headers, body=self._request_body)
WebAnalyticsRequestBuilder
python
spack__spack
lib/spack/spack/oci/image.py
{ "start": 2978, "end": 8741 }
class ____: """A parsed image of the form domain/name:tag[@digest]. The digest is optional, and domain and tag are automatically filled out with defaults when parsed from string.""" __slots__ = ["scheme", "domain", "name", "tag", "digest"] def __init__( self, *, domain: str, name: str, tag: str = "latest", digest: Optional[Digest] = None, scheme: str = "https", ): self.scheme = scheme self.domain = domain self.name = name self.tag = tag self.digest = digest @classmethod def from_string(cls, string: str, *, scheme: str = "https") -> "ImageReference": match = referencePat.match(string) if not match: raise ValueError(f"Invalid image reference: {string}") image, tag, digest = match.groups() assert isinstance(image, str) assert isinstance(tag, (str, type(None))) assert isinstance(digest, (str, type(None))) match = anchoredNameRegexp.match(image) # This can never happen, since the regex is implied # by the regex above. It's just here to make mypy happy. assert match, f"Invalid image reference: {string}" domain, name = match.groups() assert isinstance(domain, (str, type(None))) assert isinstance(name, str) # Fill out defaults like docker would do... # Based on github.com/distribution/distribution: allow short names like "ubuntu" # and "user/repo" to be interpreted as "library/ubuntu" and "user/repo:latest # Not sure if Spack should follow Docker, but it's what people expect... if not domain: domain = "index.docker.io" name = f"library/{name}" elif ( "." not in domain and ":" not in domain and domain != "localhost" and domain == domain.lower() ): name = f"{domain}/{name}" domain = "index.docker.io" # Lowercase the image name. This is enforced by Docker, although the OCI spec isn't clear? # We do this anyways, cause for example in Github Actions the <organization>/<repository> # part can have uppercase, and may be interpolated when specifying the relevant OCI image. name = name.lower() if not tag: tag = "latest" # sha256 is currently the only algorithm that # we implement, even though the spec allows for more if isinstance(digest, str): digest = Digest.from_string(digest) return cls(domain=domain, name=name, tag=tag, digest=digest, scheme=scheme) @classmethod def from_url(cls, url: str) -> "ImageReference": """Parse an OCI URL into an ImageReference, either oci:// or oci+http://.""" if url.startswith("oci://"): img = url[6:] scheme = "https" elif url.startswith("oci+http://"): img = url[11:] scheme = "http" else: raise ValueError(f"Invalid OCI URL: {url}") return cls.from_string(img, scheme=scheme) def manifest_url(self) -> str: digest_or_tag = self.digest or self.tag return f"{self.scheme}://{self.domain}/v2/{self.name}/manifests/{digest_or_tag}" def blob_url(self, digest: Union[str, Digest]) -> str: if isinstance(digest, str): digest = Digest.from_string(digest) return f"{self.scheme}://{self.domain}/v2/{self.name}/blobs/{digest}" def with_digest(self, digest: Union[str, Digest]) -> "ImageReference": if isinstance(digest, str): digest = Digest.from_string(digest) return ImageReference( domain=self.domain, name=self.name, tag=self.tag, digest=digest, scheme=self.scheme ) def with_tag(self, tag: str) -> "ImageReference": return ImageReference( domain=self.domain, name=self.name, tag=tag, digest=self.digest, scheme=self.scheme ) def uploads_url(self, digest: Optional[Digest] = None) -> str: url = f"{self.scheme}://{self.domain}/v2/{self.name}/blobs/uploads/" if digest: url += f"?digest={digest}" return url def tags_url(self) -> str: return f"{self.scheme}://{self.domain}/v2/{self.name}/tags/list" def endpoint(self, path: str = "") -> str: return urllib.parse.urljoin(f"{self.scheme}://{self.domain}/v2/", path) def __str__(self) -> str: s = f"{self.domain}/{self.name}" if self.tag: s += f":{self.tag}" if self.digest: s += f"@{self.digest}" return s def __eq__(self, __value: object) -> bool: if not isinstance(__value, ImageReference): return NotImplemented return ( self.domain == __value.domain and self.name == __value.name and self.tag == __value.tag and self.digest == __value.digest and self.scheme == __value.scheme ) def ensure_valid_tag(tag: str) -> str: """Ensure a tag is valid for an OCI registry.""" sanitized = re.sub(r"[^\w.-]", "_", tag) if len(sanitized) > 128: return sanitized[:64] + sanitized[-64:] return sanitized def default_config(architecture: str, os: str): return { "architecture": architecture, "os": os, "rootfs": {"type": "layers", "diff_ids": []}, "config": {"Env": []}, } def default_manifest(): return { "mediaType": "application/vnd.oci.image.manifest.v1+json", "schemaVersion": 2, "config": {"mediaType": "application/vnd.oci.image.config.v1+json"}, "layers": [], }
ImageReference
python
ray-project__ray
python/ray/serve/exceptions.py
{ "start": 1355, "end": 1786 }
class ____(RayServeException): """Raised when a Serve deployment is unavailable to receive requests. Currently this happens because the deployment failed to deploy. """ def __init__(self, deployment_id: DeploymentID): self._deployment_id = deployment_id @property def message(self) -> str: return f"{self._deployment_id} is unavailable because it failed to deploy."
DeploymentUnavailableError
python
spack__spack
lib/spack/spack/util/web.py
{ "start": 1912, "end": 2254 }
class ____(URLError): def __init__(self, req: Request, reason): super().__init__(reason) self.req = req def __str__(self): return f"{self.req.get_method()} {self.req.get_full_url()} errored with: {self.reason}" def __reduce__(self): return DetailedURLError, (self.req, self.reason)
DetailedURLError
python
allegroai__clearml
clearml/backend_api/services/v2_20/tasks.py
{ "start": 44927, "end": 71473 }
class ____(NonStrictDataModel): """ :param id: Task id :type id: str :param name: Task Name :type name: str :param user: Associated user id :type user: str :param company: Company ID :type company: str :param type: Type of task. Values: 'training', 'testing' :type type: TaskTypeEnum :param status: :type status: TaskStatusEnum :param comment: Free text comment :type comment: str :param created: Task creation time (UTC) :type created: datetime.datetime :param started: Task start time (UTC) :type started: datetime.datetime :param completed: Task end time (UTC) :type completed: datetime.datetime :param active_duration: Task duration time (seconds) :type active_duration: int :param parent: Parent task id :type parent: str :param project: Project ID of the project to which this task is assigned :type project: str :param output: Task output params :type output: Output :param execution: Task execution params :type execution: Execution :param container: Docker container parameters :type container: dict :param models: Task models :type models: TaskModels :param script: Script info :type script: Script :param tags: User-defined tags list :type tags: Sequence[str] :param system_tags: System tags list. This field is reserved for system use, please don't use it. :type system_tags: Sequence[str] :param status_changed: Last status change time :type status_changed: datetime.datetime :param status_message: free text string representing info about the status :type status_message: str :param status_reason: Reason for last status change :type status_reason: str :param published: Last status change time :type published: datetime.datetime :param last_worker: ID of last worker that handled the task :type last_worker: str :param last_worker_report: Last time a worker reported while working on this task :type last_worker_report: datetime.datetime :param last_update: Last time this task was created, updated, changed or events for this task were reported :type last_update: datetime.datetime :param last_change: Last time any update was done to the task :type last_change: datetime.datetime :param last_iteration: Last iteration reported for this task :type last_iteration: int :param last_metrics: Last metric variants (hash to events), one for each metric hash :type last_metrics: dict :param hyperparams: Task hyper params per section :type hyperparams: dict :param configuration: Task configuration params :type configuration: dict :param runtime: Task runtime mapping :type runtime: dict """ _schema = { "properties": { "active_duration": { "description": "Task duration time (seconds)", "type": ["integer", "null"], }, "comment": {"description": "Free text comment", "type": ["string", "null"]}, "company": {"description": "Company ID", "type": ["string", "null"]}, "completed": { "description": "Task end time (UTC)", "format": "date-time", "type": ["string", "null"], }, "configuration": { "additionalProperties": {"$ref": "#/definitions/configuration_item"}, "description": "Task configuration params", "type": ["object", "null"], }, "container": { "additionalProperties": {"type": ["string", "null"]}, "description": "Docker container parameters", "type": ["object", "null"], }, "created": { "description": "Task creation time (UTC) ", "format": "date-time", "type": ["string", "null"], }, "execution": { "description": "Task execution params", "oneOf": [{"$ref": "#/definitions/execution"}, {"type": "null"}], }, "hyperparams": { "additionalProperties": {"$ref": "#/definitions/section_params"}, "description": "Task hyper params per section", "type": ["object", "null"], }, "id": {"description": "Task id", "type": ["string", "null"]}, "last_change": { "description": "Last time any update was done to the task", "format": "date-time", "type": ["string", "null"], }, "last_iteration": { "description": "Last iteration reported for this task", "type": ["integer", "null"], }, "last_metrics": { "additionalProperties": {"$ref": "#/definitions/last_metrics_variants"}, "description": "Last metric variants (hash to events), one for each metric hash", "type": ["object", "null"], }, "last_update": { "description": "Last time this task was created, edited, changed or events for this task were reported", "format": "date-time", "type": ["string", "null"], }, "last_worker": { "description": "ID of last worker that handled the task", "type": ["string", "null"], }, "last_worker_report": { "description": "Last time a worker reported while working on this task", "format": "date-time", "type": ["string", "null"], }, "models": { "description": "Task models", "oneOf": [{"$ref": "#/definitions/task_models"}, {"type": "null"}], }, "name": {"description": "Task Name", "type": ["string", "null"]}, "output": { "description": "Task output params", "oneOf": [{"$ref": "#/definitions/output"}, {"type": "null"}], }, "parent": {"description": "Parent task id", "type": ["string", "null"]}, "project": { "description": "Project ID of the project to which this task is assigned", "type": ["string", "null"], }, "published": { "description": "Last status change time", "format": "date-time", "type": ["string", "null"], }, "runtime": { "additionalProperties": True, "description": "Task runtime mapping", "type": ["object", "null"], }, "script": { "description": "Script info", "oneOf": [{"$ref": "#/definitions/script"}, {"type": "null"}], }, "started": { "description": "Task start time (UTC)", "format": "date-time", "type": ["string", "null"], }, "status": { "description": "", "oneOf": [{"$ref": "#/definitions/task_status_enum"}, {"type": "null"}], }, "status_changed": { "description": "Last status change time", "format": "date-time", "type": ["string", "null"], }, "status_message": { "description": "free text string representing info about the status", "type": ["string", "null"], }, "status_reason": { "description": "Reason for last status change", "type": ["string", "null"], }, "system_tags": { "description": "System tags list. This field is reserved for system use, please don't use it.", "items": {"type": "string"}, "type": ["array", "null"], }, "tags": { "description": "User-defined tags list", "items": {"type": "string"}, "type": ["array", "null"], }, "type": { "description": "Type of task. Values: 'training', 'testing'", "oneOf": [{"$ref": "#/definitions/task_type_enum"}, {"type": "null"}], }, "user": {"description": "Associated user id", "type": ["string", "null"]}, }, "type": "object", } def __init__( self, id: Optional[str] = None, name: Optional[str] = None, user: Optional[str] = None, company: Optional[str] = None, type: Any = None, status: Any = None, comment: Optional[str] = None, created: Optional[str] = None, started: Optional[str] = None, completed: Optional[str] = None, active_duration: Optional[int] = None, parent: Optional[str] = None, project: Optional[str] = None, output: Any = None, execution: Any = None, container: Optional[dict] = None, models: Any = None, script: Any = None, tags: Optional[List[str]] = None, system_tags: Optional[List[str]] = None, status_changed: Optional[str] = None, status_message: Optional[str] = None, status_reason: Optional[str] = None, published: Optional[str] = None, last_worker: Optional[str] = None, last_worker_report: Optional[str] = None, last_update: Optional[str] = None, last_change: Optional[str] = None, last_iteration: Optional[int] = None, last_metrics: Optional[dict] = None, hyperparams: Optional[dict] = None, configuration: Optional[dict] = None, runtime: Optional[dict] = None, **kwargs: Any ) -> None: super(Task, self).__init__(**kwargs) self.id = id self.name = name self.user = user self.company = company self.type = type self.status = status self.comment = comment self.created = created self.started = started self.completed = completed self.active_duration = active_duration self.parent = parent self.project = project self.output = output self.execution = execution self.container = container self.models = models self.script = script self.tags = tags self.system_tags = system_tags self.status_changed = status_changed self.status_message = status_message self.status_reason = status_reason self.published = published self.last_worker = last_worker self.last_worker_report = last_worker_report self.last_update = last_update self.last_change = last_change self.last_iteration = last_iteration self.last_metrics = last_metrics self.hyperparams = hyperparams self.configuration = configuration self.runtime = runtime @schema_property("id") def id(self) -> Optional[str]: return self._property_id @id.setter def id(self, value: Optional[str]) -> None: if value is None: self._property_id = None return self.assert_isinstance(value, "id", six.string_types) self._property_id = value @schema_property("name") def name(self) -> Optional[str]: return self._property_name @name.setter def name(self, value: Optional[str]) -> None: if value is None: self._property_name = None return self.assert_isinstance(value, "name", six.string_types) self._property_name = value @schema_property("user") def user(self) -> Optional[str]: return self._property_user @user.setter def user(self, value: Optional[str]) -> None: if value is None: self._property_user = None return self.assert_isinstance(value, "user", six.string_types) self._property_user = value @schema_property("company") def company(self) -> Optional[str]: return self._property_company @company.setter def company(self, value: Optional[str]) -> None: if value is None: self._property_company = None return self.assert_isinstance(value, "company", six.string_types) self._property_company = value @schema_property("type") def type(self) -> Any: return self._property_type @type.setter def type(self, value: Any) -> None: if value is None: self._property_type = None return if isinstance(value, six.string_types): try: value = TaskTypeEnum(value) except ValueError: pass else: self.assert_isinstance(value, "type", enum.Enum) self._property_type = value @schema_property("status") def status(self) -> Any: return self._property_status @status.setter def status(self, value: Any) -> None: if value is None: self._property_status = None return if isinstance(value, six.string_types): try: value = TaskStatusEnum(value) except ValueError: pass else: self.assert_isinstance(value, "status", enum.Enum) self._property_status = value @schema_property("comment") def comment(self) -> Optional[str]: return self._property_comment @comment.setter def comment(self, value: Optional[str]) -> None: if value is None: self._property_comment = None return self.assert_isinstance(value, "comment", six.string_types) self._property_comment = value @schema_property("created") def created(self) -> Optional[str]: return self._property_created @created.setter def created(self, value: Optional[str]) -> None: if value is None: self._property_created = None return self.assert_isinstance(value, "created", six.string_types + (datetime,)) if not isinstance(value, datetime): value = parse_datetime(value) self._property_created = value @schema_property("started") def started(self) -> Optional[str]: return self._property_started @started.setter def started(self, value: Optional[str]) -> None: if value is None: self._property_started = None return self.assert_isinstance(value, "started", six.string_types + (datetime,)) if not isinstance(value, datetime): value = parse_datetime(value) self._property_started = value @schema_property("completed") def completed(self) -> Optional[str]: return self._property_completed @completed.setter def completed(self, value: Optional[str]) -> None: if value is None: self._property_completed = None return self.assert_isinstance(value, "completed", six.string_types + (datetime,)) if not isinstance(value, datetime): value = parse_datetime(value) self._property_completed = value @schema_property("active_duration") def active_duration(self) -> Optional[int]: return self._property_active_duration @active_duration.setter def active_duration(self, value: Optional[int]) -> None: if value is None: self._property_active_duration = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "active_duration", six.integer_types) self._property_active_duration = value @schema_property("parent") def parent(self) -> Optional[str]: return self._property_parent @parent.setter def parent(self, value: Optional[str]) -> None: if value is None: self._property_parent = None return self.assert_isinstance(value, "parent", six.string_types) self._property_parent = value @schema_property("project") def project(self) -> Optional[str]: return self._property_project @project.setter def project(self, value: Optional[str]) -> None: if value is None: self._property_project = None return self.assert_isinstance(value, "project", six.string_types) self._property_project = value @schema_property("output") def output(self) -> Any: return self._property_output @output.setter def output(self, value: Any) -> None: if value is None: self._property_output = None return if isinstance(value, dict): value = Output.from_dict(value) else: self.assert_isinstance(value, "output", Output) self._property_output = value @schema_property("execution") def execution(self) -> Any: return self._property_execution @execution.setter def execution(self, value: Any) -> None: if value is None: self._property_execution = None return if isinstance(value, dict): value = Execution.from_dict(value) else: self.assert_isinstance(value, "execution", Execution) self._property_execution = value @schema_property("container") def container(self) -> Optional[dict]: return self._property_container @container.setter def container(self, value: Optional[dict]) -> None: if value is None: self._property_container = None return self.assert_isinstance(value, "container", (dict,)) self._property_container = value @schema_property("models") def models(self) -> Any: return self._property_models @models.setter def models(self, value: Any) -> None: if value is None: self._property_models = None return if isinstance(value, dict): value = TaskModels.from_dict(value) else: self.assert_isinstance(value, "models", TaskModels) self._property_models = value @schema_property("script") def script(self) -> Any: return self._property_script @script.setter def script(self, value: Any) -> None: if value is None: self._property_script = None return if isinstance(value, dict): value = Script.from_dict(value) else: self.assert_isinstance(value, "script", Script) self._property_script = value @schema_property("tags") def tags(self) -> Optional[List[str]]: return self._property_tags @tags.setter def tags(self, value: Optional[List[str]]) -> None: if value is None: self._property_tags = None return self.assert_isinstance(value, "tags", (list, tuple)) self.assert_isinstance(value, "tags", six.string_types, is_array=True) self._property_tags = value @schema_property("system_tags") def system_tags(self) -> Optional[List[str]]: return self._property_system_tags @system_tags.setter def system_tags(self, value: Optional[List[str]]) -> None: if value is None: self._property_system_tags = None return self.assert_isinstance(value, "system_tags", (list, tuple)) self.assert_isinstance(value, "system_tags", six.string_types, is_array=True) self._property_system_tags = value @schema_property("status_changed") def status_changed(self) -> Optional[str]: return self._property_status_changed @status_changed.setter def status_changed(self, value: Optional[str]) -> None: if value is None: self._property_status_changed = None return self.assert_isinstance(value, "status_changed", six.string_types + (datetime,)) if not isinstance(value, datetime): value = parse_datetime(value) self._property_status_changed = value @schema_property("status_message") def status_message(self) -> Optional[str]: return self._property_status_message @status_message.setter def status_message(self, value: Optional[str]) -> None: if value is None: self._property_status_message = None return self.assert_isinstance(value, "status_message", six.string_types) self._property_status_message = value @schema_property("status_reason") def status_reason(self) -> Optional[str]: return self._property_status_reason @status_reason.setter def status_reason(self, value: Optional[str]) -> None: if value is None: self._property_status_reason = None return self.assert_isinstance(value, "status_reason", six.string_types) self._property_status_reason = value @schema_property("published") def published(self) -> Optional[str]: return self._property_published @published.setter def published(self, value: Optional[str]) -> None: if value is None: self._property_published = None return self.assert_isinstance(value, "published", six.string_types + (datetime,)) if not isinstance(value, datetime): value = parse_datetime(value) self._property_published = value @schema_property("last_worker") def last_worker(self) -> Optional[str]: return self._property_last_worker @last_worker.setter def last_worker(self, value: Optional[str]) -> None: if value is None: self._property_last_worker = None return self.assert_isinstance(value, "last_worker", six.string_types) self._property_last_worker = value @schema_property("last_worker_report") def last_worker_report(self) -> Optional[str]: return self._property_last_worker_report @last_worker_report.setter def last_worker_report(self, value: Optional[str]) -> None: if value is None: self._property_last_worker_report = None return self.assert_isinstance(value, "last_worker_report", six.string_types + (datetime,)) if not isinstance(value, datetime): value = parse_datetime(value) self._property_last_worker_report = value @schema_property("last_update") def last_update(self) -> Optional[str]: return self._property_last_update @last_update.setter def last_update(self, value: Optional[str]) -> None: if value is None: self._property_last_update = None return self.assert_isinstance(value, "last_update", six.string_types + (datetime,)) if not isinstance(value, datetime): value = parse_datetime(value) self._property_last_update = value @schema_property("last_change") def last_change(self) -> Optional[str]: return self._property_last_change @last_change.setter def last_change(self, value: Optional[str]) -> None: if value is None: self._property_last_change = None return self.assert_isinstance(value, "last_change", six.string_types + (datetime,)) if not isinstance(value, datetime): value = parse_datetime(value) self._property_last_change = value @schema_property("last_iteration") def last_iteration(self) -> Optional[int]: return self._property_last_iteration @last_iteration.setter def last_iteration(self, value: Optional[int]) -> None: if value is None: self._property_last_iteration = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "last_iteration", six.integer_types) self._property_last_iteration = value @schema_property("last_metrics") def last_metrics(self) -> Optional[dict]: return self._property_last_metrics @last_metrics.setter def last_metrics(self, value: Optional[dict]) -> None: if value is None: self._property_last_metrics = None return self.assert_isinstance(value, "last_metrics", (dict,)) self._property_last_metrics = value @schema_property("hyperparams") def hyperparams(self) -> Optional[dict]: return self._property_hyperparams @hyperparams.setter def hyperparams(self, value: Optional[dict]) -> None: if value is None: self._property_hyperparams = None return self.assert_isinstance(value, "hyperparams", dict) self.assert_isinstance(value.keys(), "hyperparams_keys", six.string_types, is_array=True) self.assert_isinstance(value.values(), "hyperparams_values", (SectionParams, dict), is_array=True) value = dict(((k, SectionParams(**v) if isinstance(v, dict) else v) for (k, v) in value.items())) self._property_hyperparams = value @schema_property("configuration") def configuration(self) -> Optional[dict]: return self._property_configuration @configuration.setter def configuration(self, value: Optional[dict]) -> None: if value is None: self._property_configuration = None return self.assert_isinstance(value, "configuration", dict) self.assert_isinstance(value.keys(), "configuration_keys", six.string_types, is_array=True) self.assert_isinstance( value.values(), "configuration_values", (ConfigurationItem, dict), is_array=True, ) value = dict(((k, ConfigurationItem(**v) if isinstance(v, dict) else v) for (k, v) in value.items())) self._property_configuration = value @schema_property("runtime") def runtime(self) -> Optional[dict]: return self._property_runtime @runtime.setter def runtime(self, value: Optional[dict]) -> None: if value is None: self._property_runtime = None return self.assert_isinstance(value, "runtime", (dict,)) self._property_runtime = value
Task
python
walkccc__LeetCode
solutions/1104. Path In Zigzag Labelled Binary Tree/1104.py
{ "start": 0, "end": 458 }
class ____: def pathInZigZagTree(self, label: int) -> list[int]: def boundarySum(level: int): return 2**level + 2**(level + 1) - 1 ans = [] for l in range(21): if 2**l > label: level = l - 1 break if level % 2 == 1: label = boundarySum(level) - label for l in reversed(range(level + 1)): ans.append(label if l % 2 == 0 else boundarySum(l) - label) label //= 2 return ans[::-1]
Solution
python
getsentry__sentry
tests/sentry/models/test_orgauthtoken.py
{ "start": 1405, "end": 2974 }
class ____(TestCase): def test_creates_outboxes(self) -> None: with assume_test_silo_mode(SiloMode.CONTROL): token = OrgAuthToken.objects.create( organization_id=self.organization.id, name="test token", token_hashed="test-token", scope_list=["org:ci"], ) update_org_auth_token_last_used(token, []) outbox = RegionOutbox.objects.first() assert outbox assert outbox.category == OutboxCategory.ORGAUTHTOKEN_UPDATE_USED assert outbox.object_identifier == token.id assert outbox.payload is not None assert outbox.payload["organization_id"] == self.organization.id assert outbox.payload["org_auth_token_id"] == token.id assert "date_last_used" in outbox.payload assert "project_last_used_id" in outbox.payload def test_create_outbox_debounce(self) -> None: with assume_test_silo_mode(SiloMode.CONTROL): token = OrgAuthToken.objects.create( organization_id=self.organization.id, name="test token", token_hashed="test-token", scope_list=["org:ci"], ) update_org_auth_token_last_used(token, []) update_org_auth_token_last_used(token, []) assert RegionOutbox.objects.count() == 1, "Should be debounced" update_org_auth_token_last_used(token, [123]) assert RegionOutbox.objects.count() == 2, "Different project ids create new outboxes"
UpdateOrgAuthTokenLastUsed
python
django__django
tests/model_inheritance_regress/models.py
{ "start": 4415, "end": 4499 }
class ____(Person, Politician): state = models.CharField(max_length=2)
Congressman
python
pytorch__pytorch
torch/fx/experimental/proxy_tensor.py
{ "start": 55977, "end": 58973 }
class ____(TorchFunctionMode): def __init__(self, tracer: _ProxyTracer) -> None: self.tracer = tracer # The input to torch.amp.autocast_mode._exit_autocast graph node should be the # enter_autocast node. So we have to save the enter autocast node here, and assign it # to the exit_autocast call_function node. self.enter_autocast_nodes: list[torch.fx.Node] = [] def __torch_function__( self, func: Union[OpOverload, Callable], types: tuple[torch._C._TensorMeta, ...], args: tuple[object, ...] = (), kwargs: Optional[dict[str, object]] = None, ) -> object: kwargs = kwargs or {} if func in _side_effectful_need_to_be_preserved_pre_dispatch: # It's for passing the export verifier which needs to verify the meta['val'] # TODO(tmanlaibaatar): we should systematically couple it with export verifier, # instead of hardcoding it here. # T203648563 if func is torch.amp.autocast_mode._exit_autocast: enter_node = self.enter_autocast_nodes.pop() args = (enter_node,) node = self.tracer.create_node("call_function", func, args, {}) # type: ignore[arg-type] if func is torch.amp.autocast_mode._enter_autocast: self.enter_autocast_nodes.append(node) if func in [ torch._C._set_grad_enabled, torch.amp.autocast_mode._enter_autocast, torch.amp.autocast_mode._exit_autocast, ]: node.meta["val"] = None # For autocast, the python APIs run so we don't have to run them again # here. if func is torch._C._set_grad_enabled: # pyrefly: ignore [bad-argument-type] func(*args, **kwargs) return node # We need more complicated handling here because the inputs # to these functions are sometimes tensors or symints where # we need to fetch the proxies properly. if func in [ torch._functorch.predispatch._add_batch_dim, torch._functorch.predispatch._remove_batch_dim, torch._functorch.predispatch._vmap_increment_nesting, torch._functorch.predispatch._vmap_decrement_nesting, torch._functorch.vmap.lazy_load_decompositions, ]: _, proxies, _ = _fetch_proxies_and_all_constant_flag(args, self.tracer) out_proxy = self.tracer.create_proxy( "call_function", func, proxies, {}, ) res = func(*args, **kwargs) track_tensor_tree(res, out_proxy, constant=None, tracer=self.tracer) return res return func(*args, **kwargs) _temp_remove_pre_dispatch_torch_function_mode = _make_temp_remove_mode_context_manager( PreDispatchTorchFunctionMode )
PreDispatchTorchFunctionMode
python
pytorch__pytorch
torch/sparse/_triton_ops.py
{ "start": 28419, "end": 87904 }
class ____: """A light-weight wrapper of a tensor that enables storing tensors as keys with efficient memory reference based comparison as an approximation to data equality based keys. Motivation: the hash value of a torch tensor is tensor instance based that does not use data equality and makes the usage of tensors as keys less useful. For instance, the result of ``len({a.crow_indices(), a.crow_indices()})`` is `2`, although, the tensor results from `crow_indices` method call are equal, in fact, these share the same data storage. On the other hand, for efficient caching of tensors we want to avoid calling torch.equal that compares tensors item-wise. TensorAsKey offers a compromise in that it guarantees key equality of tensors that references data in the same storage in the same manner and without accessing underlying data. However, this approach does not always guarantee correctness. For instance, for a complex tensor ``x``, we have ``TensorAsKey(x) == TensorAsKey(x.conj())`` while ``torch.equal(x, x.conj())`` would return False. """ def __init__(self, obj): def get_tensor_key(obj): # Warning: TensorAsKey does not track negative nor # conjugate bits of its input object because in the use # case of wrapping compressed/plain indices of compressed # sparse tensors (that are always integer tensors with # non-negative items) these bits are never set. However, # when extending the use of TensorAsKey to float or # complex tensors, the values of these bits (see is_neg # and is_conj methods) must be included in the key as # well. assert not (obj.dtype.is_floating_point or obj.dtype.is_complex), obj.dtype return ( obj.data_ptr(), obj.storage_offset(), obj.shape, obj.stride(), obj.dtype, ) self._obj_ref = weakref.ref(obj) if obj.layout is torch.strided: self.key = get_tensor_key(obj) elif obj.layout in {torch.sparse_csr, torch.sparse_bsr}: self.key = ( get_tensor_key(obj.crow_indices()), get_tensor_key(obj.col_indices()), ) elif obj.layout in {torch.sparse_csc, torch.sparse_bsc}: self.key = ( get_tensor_key(obj.ccol_indices()), get_tensor_key(obj.row_indices()), ) else: raise NotImplementedError(obj.layout) self._hash = hash(self.key) def __hash__(self): return self._hash def __eq__(self, other): if not isinstance(other, TensorAsKey): return False if self.obj is None or other.obj is None: # dead objects always compare unequal unless these are # same objects return self is other return self.key == other.key @property def obj(self): """Return object if alive, otherwise None.""" return self._obj_ref() @lru_cache(maxsize=TORCH_SPARSE_BSR_SCATTER_MM_LRU_CACHE_SIZE) def _bsr_scatter_mm_indices_data( indices_format, M, K, N, Ms, Ks, nbatches, SPLIT_N, compressed_sparse_tensor_as_key ): bsr = compressed_sparse_tensor_as_key.obj assert bsr is not None crow_indices, col_indices = bsr.crow_indices(), bsr.col_indices() device = crow_indices.device indices_dtype = torch.int32 if indices_format == "bsr_strided_mm_compressed": Ns = N // SPLIT_N q_offsets_lst = [] b = torch.arange(SPLIT_N, dtype=indices_dtype, device=device) * Ns for m in range(M // Ms): r0 = crow_indices[m].item() r1 = crow_indices[m + 1].item() if r1 == r0: continue q_offsets_lst.append( (col_indices[r0:r1] * (Ks * N)).repeat(SPLIT_N) + b.repeat_interleave(r1 - r0) ) q_offsets = torch.cat(q_offsets_lst) crow_indices_diff = crow_indices.diff() non_zero_row_indices = crow_indices_diff.nonzero() a = non_zero_row_indices * (Ms * N) r_offsets = (a + b).view(-1) c_indices = crow_indices # swizzle operation: mm elements with longer sums are computed first: nnz_per_row = crow_indices_diff[non_zero_row_indices].repeat_interleave(SPLIT_N) nnz_per_row, indices = nnz_per_row.sort(descending=True, stable=True) r_offsets = r_offsets[indices] return (indices_format, c_indices, r_offsets, q_offsets) elif indices_format == "bsr_strided_mm": Ns = N // SPLIT_N p_offsets_lst = [] q_offsets_lst = [] b = torch.arange(SPLIT_N, dtype=indices_dtype, device=device) * Ns for m in range(M // Ms): r0 = crow_indices[m].item() r1 = crow_indices[m + 1].item() if r1 == r0: continue p_offsets_lst.append( torch.arange(r0, r1, dtype=indices_dtype, device=device).repeat(SPLIT_N) ) q_offsets_lst.append( (col_indices[r0:r1] * (Ks * N)).repeat(SPLIT_N) + b.repeat_interleave(r1 - r0) ) q_offsets = torch.cat(q_offsets_lst) crow_indices_diff = crow_indices.diff() non_zero_row_indices = crow_indices_diff.nonzero() a = non_zero_row_indices * (Ms * N) r_offsets = (a + b).view(-1) c_indices = torch.cat( ( crow_indices[:1], torch.cumsum( crow_indices_diff[non_zero_row_indices].repeat_interleave(SPLIT_N), 0, ), ) ) p_offsets = torch.cat(p_offsets_lst) return (indices_format, c_indices, r_offsets, p_offsets, q_offsets) elif indices_format == "scatter_mm": Ns = Ms c_indices = [0] pq_offsets = [] # todo: eliminate inner for-loops for efficiency for b in range(nbatches): for m in range(M // Ms): r0 = crow_indices[m].item() r1 = crow_indices[m + 1].item() for n in range(N // Ns): c_indices.append(c_indices[-1] + r1 - r0) for t in range(r1 - r0): p = r0 + t q = (col_indices[p].item() + b * (K // Ks)) * (N // Ns) + n pq_offsets.append([p, q]) return ( indices_format, torch.tensor(c_indices, dtype=indices_dtype, device=device), torch.tensor(pq_offsets, dtype=indices_dtype, device=device), ) else: raise ValueError( f"Invalid {indices_format=}. Expected bsr_strided_mm_compressed|bsr_strided_mm|scatter_mm" ) def bsr_scatter_mm_indices_data( bsr, other, indices_format="bsr_strided_mm_compressed", **meta_input ): """Computes indices data for :func:`scatter_mm` used in BSR and strided tensor matrix multiplication. """ assert bsr.dense_dim() == 0 assert bsr.ndim == 2 # no batch dims blocksize = bsr.values().shape[-2:] M, K = bsr.shape Ms, Ks = blocksize K_, N = other.shape[-2:] assert K_ == K nbatches = other.shape[:-2].numel() meta = scatter_mm_meta(M, K, N, Ms, Ks, **meta_input) if "allow_tf32" not in meta_input: meta.update(allow_tf32=bsr.dtype in {torch.float16, torch.bfloat16}) SPLIT_N = meta["SPLIT_N"] indices_data = _bsr_scatter_mm_indices_data( indices_format, M, K, N, Ms, Ks, nbatches, SPLIT_N, TensorAsKey(bsr) ) if indices_format == "bsr_strided_mm_compressed": meta.update(is_compressed=True) return indices_data + (meta,) elif indices_format == "bsr_strided_mm": meta.update(is_compressed=False) return indices_data + (meta,) else: return indices_data def bsr_scatter_mm(bsr, other, indices_data=None, out=None): """BSR @ strided -> strided""" assert bsr.ndim == 2 assert other.ndim >= 2 Ms, Ks, Ns = bsr.shape[-2], bsr.shape[-1], other.shape[-1] blocksize = bsr.values().shape[-2:] if indices_data is None: indices_data = bsr_scatter_mm_indices_data( bsr, other, indices_format="bsr_strided_mm_compressed" ) indices_format = indices_data[0] if out is None: out = torch.empty( (*other.shape[:-2], Ms, Ns), dtype=bsr.dtype, device=bsr.device ) out_shape = out.shape out = as1Dbatch(out) if bsr._nnz() == 0: out.zero_() elif indices_format in {"bsr_strided_mm_compressed", "bsr_strided_mm"}: out.zero_() scatter_mm(bsr.values(), other, indices_data, accumulators=out) elif indices_format == "scatter_mm": nbatches = other.shape[:-2].numel() accumulators = torch.zeros( ( nbatches * Ms // blocksize[0] * Ns // blocksize[0], blocksize[0], blocksize[0], ), dtype=bsr.dtype, device=bsr.device, ) others = ( as1Dbatch(other) .transpose(-2, -1) .view( nbatches, Ns // blocksize[0], blocksize[0], Ks // blocksize[1], blocksize[1], ) .movedim( (3, 1, 4, 2), (1, 2, 3, 4) ) # equivalent to .transpose(-3, -2).transpose(-2, -1).transpose(-4, -3) .flatten(0, 2) ) scatter_mm(bsr.values(), others, indices_data, accumulators=accumulators) out.copy_( accumulators.unflatten( 0, (nbatches, Ms // blocksize[0], Ns // blocksize[0]) ) .movedim( (1, 2, 3, 4), (3, 1, 4, 2) ) # equivalent to .transpose(-4, -3).transpose(-2, -1).transpose(-3, -2) .reshape(nbatches, Ns, Ms) .transpose(-2, -1) ) else: raise NotImplementedError(indices_format) return out.view(out_shape) def _int_bsr_dense_addmm( input: torch.Tensor, bsr: torch.Tensor, dense: torch.Tensor, *, beta=1, alpha=1, left_alpha: torch.Tensor | None = None, right_alpha: torch.Tensor | None = None, out: torch.Tensor | None = None, skip_checks: bool = False, max_grid: tuple[int | None, int | None, int | None] | None = None, meta: dict | None = None, ): if out is None and dense.dtype is torch.int8: f_name = "_int_bsr_dense_addmm" crow_indices = bsr.crow_indices() batch_ndim = crow_indices.dim() - 1 M = bsr.shape[batch_ndim] N = dense.shape[-1] original_batch_dims_broadcasted = broadcast_batch_dims(f_name, bsr, dense) out = torch.empty( original_batch_dims_broadcasted + (M, N), dtype=torch.int32, device=dense.device, ) return bsr_dense_addmm( input, bsr, dense, beta=beta, alpha=alpha, left_alpha=left_alpha, right_alpha=right_alpha, out=out, skip_checks=skip_checks, max_grid=max_grid, meta=meta, ) def bsr_dense_addmm( input: torch.Tensor, bsr: torch.Tensor, dense: torch.Tensor, *, beta=1, alpha=1, left_alpha: torch.Tensor | None = None, right_alpha: torch.Tensor | None = None, out: torch.Tensor | None = None, skip_checks: bool = False, max_grid: tuple[int | None, int | None, int | None] | None = None, meta: dict | None = None, ): """Compute out = beta * input + left_alpha.reshape(-1, 1) * (alpha * (bsr @ dense)) * right_alpha.reshape(1, -1) where left_alpha, right_alpha are (* + 1)-D tensors when specified, otherwise, these are treated as tensors filled with ones. """ f_name = "bsr_dense_addmm" values = bsr.values() crow_indices = bsr.crow_indices() col_indices = bsr.col_indices() batch_ndim = crow_indices.dim() - 1 M, K = bsr.shape[batch_ndim : batch_ndim + 2] blocksize = values.shape[batch_ndim + 1 : batch_ndim + 3] N = dense.shape[-1] # todo: implement checks original_batch_dims_broadcasted = broadcast_batch_dims(f_name, bsr, dense) if out is None: out = dense.new_empty(original_batch_dims_broadcasted + (M, N)) if bsr._nnz() == 0 or alpha == 0 or N == 0 or M == 0 or K == 0: if beta == 0: out.zero_() else: out.copy_(input) if beta != 1: out.mul_(beta) return out left_alpha_is_one = False right_alpha_is_one = False if left_alpha is None: left_alpha_is_one = True left_alpha = dense.new_empty(()).expand( *original_batch_dims_broadcasted, M, N ) # not referenced else: left_alpha = left_alpha.view(*original_batch_dims_broadcasted, M, 1).expand( *original_batch_dims_broadcasted, M, N ) if right_alpha is None: right_alpha_is_one = True right_alpha = dense.new_empty(()).expand( *original_batch_dims_broadcasted, M, N ) # not referenced else: right_alpha = right_alpha.view(*original_batch_dims_broadcasted, 1, N).expand( *original_batch_dims_broadcasted, M, N ) assert left_alpha.stride()[-1] == 0 assert right_alpha.stride()[-2] == 0 if meta is None: sparsity = round(1 - bsr._nnz() * blocksize[0] * blocksize[1] / (M * K), 2) meta = bsr_dense_addmm_meta( M, K, N, blocksize[0], blocksize[1], beta, alpha, sparsity=sparsity, dtype=dense.dtype, out_dtype=out.dtype, ) out_backup = out ( crow_indices, col_indices, values, input, dense, left_alpha, right_alpha, out, ) = prepare_inputs(bsr, input, dense, left_alpha, right_alpha, out) BM, BK = blocksize SPLIT_N = meta.get("SPLIT_N", N // BM) BN = N // SPLIT_N out_untiled = out out = tile_to_blocksize(out, (BM, BN)) dense = tile_to_blocksize(dense, (BK, BN)) input = tile_to_blocksize(input, (BM, BN)) left_alpha = tile_to_blocksize(left_alpha, (BM, BN)) right_alpha = tile_to_blocksize(right_alpha, (BM, BN)) # tl.dot supports float16, float32, int32 as accumulator types. dot_out_dtype = { torch.float16: tl.float32, torch.bfloat16: tl.float32, torch.float32: tl.float64, torch.float64: tl.float64, torch.int8: tl.int32, torch.int32: tl.int32, }[out.dtype] n_batches = dense.size(0) n_block_rows = crow_indices.size(-1) - 1 n_block_cols = dense.size(-3) full_grid = (n_batches, n_block_cols, n_block_rows) if max_grid is not None: grid_blocks = tuple(max_grid[:3][::-1]) + (None,) * (3 - len(max_grid[:3])) else: grid_blocks = None tensor_dims_map = { values: (0, None, None), crow_indices: (0, None, -1), col_indices: (0, None, None), input: (0, -3, -4), dense: (0, -3, None), left_alpha: (0, -3, -4), right_alpha: (0, -3, -4), out: (0, -3, -4), } assert alpha != 0 def kernel(grid, *sliced_tensors): # pyrefly: ignore [unsupported-operation] _bsr_strided_addmm_kernel[grid]( *ptr_stride_extractor(*sliced_tensors), # pyrefly: ignore # bad-argument-count beta, alpha, # pyrefly: ignore # bad-keyword-argument, bad-argument-type beta_is_one=beta == 1, # pyrefly: ignore # bad-keyword-argument, bad-argument-type beta_is_nonzero=beta != 0, # pyrefly: ignore # bad-keyword-argument, bad-argument-type alpha_is_one=alpha == 1, # pyrefly: ignore # bad-keyword-argument, bad-argument-type left_alpha_is_one=left_alpha_is_one, # pyrefly: ignore # bad-keyword-argument, bad-argument-type right_alpha_is_one=right_alpha_is_one, # pyrefly: ignore # bad-keyword-argument, bad-argument-type BLOCKSIZE_ROW=BM, # pyrefly: ignore # bad-keyword-argument, bad-argument-type BLOCKSIZE_INNER=BK, # pyrefly: ignore # bad-keyword-argument BLOCKSIZE_COL=BN, # pyrefly: ignore # bad-keyword-argument allow_tf32=dot_out_dtype == tl.float32, # pyrefly: ignore # bad-keyword-argument, bad-argument-type acc_dtype=dot_out_dtype, **meta, ) launch_kernel(kernel, tensor_dims_map, full_grid, grid_blocks) if out.data_ptr() != out_backup.data_ptr(): # prepare_inputs has made a copy of out, copy its content back # to out_backup: out_backup.copy_(out_untiled.view(out_backup.shape)) return out_backup if has_triton(): import triton import triton.language as tl @triton.jit def _sampled_addmm_kernel( alpha, beta, IS_BETA_ZERO: tl.constexpr, BLOCKSIZE_ROW: tl.constexpr, BLOCKSIZE_COL: tl.constexpr, k, TILE_K: tl.constexpr, values_ptr, values_batch_stride, values_nnz_stride, values_row_block_stride, values_col_block_stride, crow_indices_ptr, crow_indices_batch_stride, crow_indices_stride, col_indices_ptr, col_indices_batch_stride, col_indices_stride, mat1_ptr, mat1_batch_stride, mat1_tiled_row_stride, mat1_tiled_col_stride, mat1_row_block_stride, mat1_col_block_stride, mat2_ptr, mat2_batch_stride, mat2_tiled_row_stride, mat2_tiled_col_stride, mat2_row_block_stride, mat2_col_block_stride, acc_dtype: tl.constexpr, allow_tf32: tl.constexpr, ): batch_pid = tl.program_id(axis=1) row_block_pid = tl.program_id(axis=0) crow_indices_offset_ptr = ( crow_indices_ptr + crow_indices_batch_stride * batch_pid + crow_indices_stride * row_block_pid ) nnz_offset = tl.load(crow_indices_offset_ptr) nnz_offset_next = tl.load(crow_indices_offset_ptr + crow_indices_stride) # Compute nnz for the row with number row_block_pid. # If it is zero, skip the row. row_nnz = nnz_offset_next - nnz_offset if row_nnz == 0: return row_block_arange = tl.arange(0, BLOCKSIZE_ROW) col_block_arange = tl.arange(0, BLOCKSIZE_COL) # Pointers are set to the first block of the current row. values_block_ptrs = ( values_ptr + values_batch_stride * batch_pid + values_nnz_stride * nnz_offset + values_row_block_stride * row_block_arange[:, None] + values_col_block_stride * col_block_arange[None, :] ) col_index_nnz_ptr = ( col_indices_ptr + col_indices_batch_stride * batch_pid + col_indices_stride * nnz_offset ) # Advance mat1 to the current tiled row, ignore columns. mat1_block_ptrs = ( mat1_ptr + mat1_batch_stride * batch_pid + mat1_tiled_row_stride * row_block_pid + mat1_row_block_stride * row_block_arange[:, None] ) # Advance mat2 in batch and block col dimension. mat2_block_ptrs = ( mat2_ptr + mat2_batch_stride * batch_pid + mat2_col_block_stride * col_block_arange[None, :] ) k_tile_arange = tl.arange(0, TILE_K) for _ in range(row_nnz): acc_block = tl.zeros((BLOCKSIZE_ROW, BLOCKSIZE_COL), dtype=acc_dtype) # find column block index col_block = tl.load(col_index_nnz_ptr) for k_tile in range(0, k, TILE_K): k_offsets = k_tile + k_tile_arange mask_k = k_offsets < k mat1_block = tl.load( mat1_block_ptrs + mat1_col_block_stride * k_offsets[None, :], # pyrefly: ignore [index-error] mask=mask_k[None, :], other=0.0, ) mat2_block = tl.load( mat2_block_ptrs + mat2_tiled_col_stride * col_block + mat2_row_block_stride * k_offsets[:, None], # pyrefly: ignore [index-error] mask=mask_k[:, None], other=0.0, ) acc_block += tl.dot( mat1_block, mat2_block, allow_tf32=allow_tf32, out_dtype=acc_dtype ) if IS_BETA_ZERO: acc_block *= alpha else: acc_block = alpha * acc_block + beta * tl.load(values_block_ptrs) # write result tl.store(values_block_ptrs, acc_block.to(values_ptr.dtype.element_ty)) # advance val/col_index ptrs to the next block in the row. values_block_ptrs += values_nnz_stride col_index_nnz_ptr += col_indices_stride @triton.jit def _bsr_strided_dense_rowspace_kernel( # values prologue values_ptr, values_batch_stride, values_nnz_stride, values_row_block_stride, values_col_block_stride, # values epilogue # crow_indices prologue crow_indices_ptr, crow_indices_batch_stride, crow_indices_stride, # crow_indices epilogue # col_indices prologue col_indices_ptr, col_indices_batch_stride, col_indices_stride, # col_indices epilogue # dense prologue dense_ptr, dense_batch_stride, dense_tiled_row_stride, dense_tiled_col_stride, dense_row_block_stride, dense_col_block_stride, # dense epilogue # output prologue output_ptr, output_batch_stride, output_tiled_row_stride, output_tiled_col_stride, output_row_block_stride, output_col_block_stride, # output epilogue # # gh-113754: Always keep all constexpr arguments at the end of # triton kernel arguments list because with triton 2.1 or # earlier non-contiguous outputs will corrupt CUDA state due # to a triton bug (fixed in openai/triton#2262). BLOCKSIZE_ROW: tl.constexpr, BLOCKSIZE_COL: tl.constexpr, acc_dtype: tl.constexpr, allow_tf32: tl.constexpr, GROUP_SIZE_ROW: tl.constexpr, ): batch_pid = tl.program_id(axis=2) row_block_pid = tl.program_id(axis=0) col_block_pid = tl.program_id(axis=1) n_block_rows = tl.num_programs(axis=0) n_block_cols = tl.num_programs(axis=1) row_block_pid, col_block_pid = tl.swizzle2d( row_block_pid, col_block_pid, n_block_rows, n_block_cols, GROUP_SIZE_ROW ) crow_indices_offset_ptr = ( crow_indices_ptr + crow_indices_batch_stride * batch_pid + crow_indices_stride * row_block_pid ) nnz_offset = tl.load(crow_indices_offset_ptr) nnz_offset_next = tl.load(crow_indices_offset_ptr + crow_indices_stride) # Compute nnz for the row with number row_block_pid. # If it is zero, skip the row. row_nnz = nnz_offset_next - nnz_offset if row_nnz == 0: return row_block_arange = tl.arange(0, BLOCKSIZE_ROW) col_block_arange = tl.arange(0, BLOCKSIZE_COL) # Pointers are set to the first block of the current row. values_block_ptrs = ( values_ptr + values_batch_stride * batch_pid + values_nnz_stride * nnz_offset + values_row_block_stride * row_block_arange[:, None] + values_col_block_stride * col_block_arange[None, :] ) # NOTE: dense is advanced into all dimensions but the tiled row one. # That will be advanced in the loop according to values in col_indices. dense_block_ptrs = ( dense_ptr + dense_batch_stride * batch_pid + dense_tiled_col_stride * col_block_pid + dense_row_block_stride * col_block_arange[:, None] + dense_col_block_stride * row_block_arange[None, :] ) # Pointers are set to exact write-to locations output_ptrs = ( output_ptr + output_batch_stride * batch_pid + output_tiled_row_stride * row_block_pid + output_tiled_col_stride * col_block_pid + output_row_block_stride * row_block_arange[:, None] + output_col_block_stride * row_block_arange[None, :] ) # Set pointer to the first nonzero element in the current row col_index_nnz_ptr = ( col_indices_ptr + col_indices_batch_stride * batch_pid + col_indices_stride * nnz_offset ) output_acc_block = tl.zeros((BLOCKSIZE_ROW, BLOCKSIZE_COL), dtype=acc_dtype) for _ in range(row_nnz): values_block = tl.load(values_block_ptrs) # find which row of dense needs to get loaded # for multiplication with values_block. dense_row_idx = tl.load(col_index_nnz_ptr) dense_block = tl.load( dense_block_ptrs + dense_tiled_row_stride * dense_row_idx ) # do block mm output_acc_block += tl.dot( values_block, dense_block, allow_tf32=allow_tf32, out_dtype=acc_dtype ) # move val/col_index ptrs to the next block in the row values_block_ptrs += values_nnz_stride col_index_nnz_ptr += col_indices_stride # write back the result tl.store(output_ptrs, output_acc_block.to(output_ptr.dtype.element_ty)) def _run_sampled_addmm_kernel( alpha, beta, is_beta_zero, blocksize, k, tile_k, values, crow_indices, col_indices, mat1, mat2, max_grid, ): n_batches = values.size(0) n_block_rows = crow_indices.size(-1) - 1 full_grid = (n_batches, n_block_rows) if max_grid is not None: grid_blocks = tuple(max_grid[:2][::-1]) + (None,) * (2 - len(max_grid[:2])) else: grid_blocks = None tensor_dims_map = { values: (0, None), crow_indices: (0, -1), col_indices: (0, None), mat1: (0, -4), mat2: (0, None), } if values.dtype in (torch.half, torch.bfloat16): acc_dtype = tl.float32 allow_tf32 = True else: acc_dtype = tl.float64 allow_tf32 = False def kernel(grid, *sliced_tensors): _sampled_addmm_kernel[grid]( alpha, beta, is_beta_zero, *blocksize, # pyrefly: ignore # bad-argument-count k, tile_k, *ptr_stride_extractor(*sliced_tensors), # pyrefly: ignore # bad-keyword-argument, bad-argument-type acc_dtype=acc_dtype, # pyrefly: ignore # bad-keyword-argument, bad-argument-type allow_tf32=allow_tf32, # pyrefly: ignore # unexpected-keyword num_stages=1, # pyrefly: ignore # unexpected-keyword num_warps=4, ) launch_kernel(kernel, tensor_dims_map, full_grid, grid_blocks) def sampled_addmm( input: torch.Tensor, mat1: torch.Tensor, mat2: torch.Tensor, *, beta=1.0, alpha=1.0, out: torch.Tensor | None = None, skip_checks: bool = False, max_grid: tuple[int | None, int | None, int | None] | None = None, ): f_name = "sampled_addmm" check_bsr_layout(f_name, input) input_broadcasted = broadcast_batch_dims_bsr(f_name, input, mat1, mat2) if not skip_checks: check_device(f_name, mat1, input.device) check_device(f_name, mat2, input.device) if beta != 0.0 and input.dtype is torch.bool: check( False, f"{f_name}(): having beta == {beta} not equal to 0.0 with boolean mask is not allowed.", ) if input.dtype is not torch.bool: check_dtype(f_name, mat1, input.dtype) check_dtype(f_name, mat2, input.dtype) else: check_dtype(f_name, mat1, mat2.dtype) check_mm_compatible_shapes(f_name, mat1, mat2) if out is not None: check_bsr_layout(f_name, out) check_device(f_name, out, mat1.device) check_dtype(f_name, out, input.dtype) check( out.shape == input_broadcasted.shape and out._nnz() == input._nnz(), f"{f_name}(): Expects `out` to be of shape {input_broadcasted.shape} " f"and with nnz equal to {input_broadcasted._nnz()} " f"but got out.shape = {out.shape} and out.nnz = {out._nnz()}", ) if out is None: out = input_broadcasted.to(mat1.dtype, copy=True) else: out.copy_(input_broadcasted) if out.numel() == 0 or out._nnz() == 0: return out blocksize = out.values().shape[-2:] k = mat1.size(-1) # NOTE: (m, 0) @ (0, n) == zeros(m, n) if alpha == 0.0 or k == 0: out.values().mul_(beta) return out # prepare inputs by reshaping them to be kernel-compatible out_backup = out crow_indices, col_indices, values, mat1, mat2 = prepare_inputs(out, mat1, mat2) mat1 = tile_to_blocksize(mat1, (blocksize[0], k)) mat2 = tile_to_blocksize(mat2, (k, blocksize[1])) tile_k = max(*blocksize) _run_sampled_addmm_kernel( alpha, beta, beta == 0.0, blocksize, k, tile_k, values, crow_indices, col_indices, mat1, mat2, max_grid, ) # If nnz x block strides are not the same in out_backup.values and values, # it means that out_backup.values and values are not the views of each other, # so we have to copy. if out_backup.values().stride()[-3:] != values.stride()[-3:]: out_backup.values().copy_(values.reshape(out_backup.values().shape)) return out_backup def bsr_dense_mm( bsr: torch.Tensor, dense: torch.Tensor, *, out: torch.Tensor | None = None, skip_checks: bool = False, max_grid: tuple[int | None, int | None, int | None] | None = None, meta: dict | None = None, ): f_name = "bsr_dense_mm" m, _kl = bsr.shape[-2:] if not skip_checks: check_bsr_layout(f_name, bsr) check_device(f_name, bsr, dense.device) check_dtype(f_name, bsr, dense.dtype, (torch.int8,)) check_mm_compatible_shapes(f_name, bsr, dense) n = dense.size(-1) row_block, col_block = bsr.values().shape[-2:] check_blocksize(f_name, (row_block, col_block)) check( not n % 16, f"{f_name}(): dense.size(-1) == {n} should be divisible by 16", ) else: _kr, n = dense.shape[-2:] original_batch_dims_broadcasted = broadcast_batch_dims(f_name, bsr, dense) if out is not None and not skip_checks: expected_out_shape = original_batch_dims_broadcasted + (m, n) check( out.shape == expected_out_shape, "bsr_dense_mm(): `out` argument has wrong shape, " f"expected {expected_out_shape}, but got {out.shape}.", ) check( out.is_contiguous() or out.transpose(-2, -1).is_contiguous(), "bsr_dense_mm(): only row-major/col-major `out` arguments are supported, " "i.e. (out.is_contiguous() or out.transpose(-2, -1).is_contiguous()) " "should be True.", ) # Allocate out if out is None: out = dense.new_empty(original_batch_dims_broadcasted + (m, n)) # Short circuit if lhs is zero if bsr._nnz() == 0: return out.zero_() # with beta==0, addmm ignores input content, so we can use out # as a placeholder for input because their shapes match: return bsr_dense_addmm(out, bsr, dense, alpha=1, beta=0, out=out) @triton.jit def _bsr_softmax_kernel( crow_indices_ptr, crow_indices_batch_stride, crow_indices_stride, values_ptr, values_batch_stride, values_row_block_stride, values_nnz_col_block_stride, row_block, col_block, MAX_ROW_NNZ: tl.constexpr, TILE: tl.constexpr, ): batch_pid = tl.program_id(axis=2) row_block_offset_pid = tl.program_id(axis=1) row_block_pid = tl.program_id(axis=0) crow_indices_offset_ptr = ( crow_indices_ptr + crow_indices_batch_stride * batch_pid + crow_indices_stride * row_block_pid ) nnz_offset = tl.load(crow_indices_offset_ptr) nnz_offset_next = tl.load(crow_indices_offset_ptr + crow_indices_stride) # Compute nnz for the row with number row_block_pid. # If it is zero, skip the row. row_nnz = nnz_offset_next - nnz_offset if row_nnz == 0: return row_arange = tl.arange(0, TILE) mask = row_arange < row_nnz * col_block curr_row_values_ptrs = ( values_ptr + values_batch_stride * batch_pid + values_row_block_stride * row_block_offset_pid + nnz_offset * col_block ) # find max in the row row_tile = tl.load( curr_row_values_ptrs + row_arange, mask=mask, other=-float("inf") ).to(tl.float32) max_row_value = tl.max(row_tile, axis=0) for _ in range(TILE, MAX_ROW_NNZ, TILE): row_arange += TILE mask = row_arange < row_nnz * col_block row_tile = tl.load( curr_row_values_ptrs + row_arange, mask=mask, other=-float("inf") ).to(tl.float32) curr_max_row_value = tl.max(row_tile, axis=0) max_row_value = tl.where( max_row_value > curr_max_row_value, max_row_value, curr_max_row_value ) # find denominator for stable softmax num = tl.exp(row_tile - max_row_value) denom = tl.sum(num, axis=0) for _ in range(TILE, MAX_ROW_NNZ, TILE): row_arange -= TILE mask = row_arange < row_nnz * col_block row_tile = tl.load( curr_row_values_ptrs + row_arange, mask=mask, other=-float("inf") ).to(tl.float32) num = tl.exp(row_tile - max_row_value) denom += tl.sum(num, axis=0) # populate output tl.store( curr_row_values_ptrs + row_arange, (num / denom).to(values_ptr.dtype.element_ty), mask=mask, ) for _ in range(TILE, MAX_ROW_NNZ, TILE): row_arange += TILE mask = row_arange < row_nnz * col_block row_tile = tl.load( curr_row_values_ptrs + row_arange, mask=mask, other=-float("inf") ).to(tl.float32) num = tl.exp(row_tile - max_row_value) tl.store( curr_row_values_ptrs + row_arange, (num / denom).to(values_ptr.dtype.element_ty), mask=mask, ) def bsr_softmax(input, max_row_nnz=None): f_name = "bsr_softmax" check_bsr_layout(f_name, input) check_dtype(f_name, input, input.dtype) if input._nnz() == 0 or input.numel() == 0: return input.clone() m, n = input.shape[-2:] nnz = input._nnz() row_block, col_block = input.values().shape[-2:] if max_row_nnz is None: max_row_nnz = triton.next_power_of_2(n) else: max_row_nnz = triton.next_power_of_2(max_row_nnz) crow_indices = input.crow_indices().unsqueeze(0).flatten(0, -2) # reshape values from # (b1, ..., bn, nnz, row_block, col_block) to # (b1 * ... * bn, row_block, nnz * col_block). # This simplifies batch dim manipulation and unlocks # the possibility to access all nnzs in any given row. if input.values().transpose(-3, -2).is_contiguous(): # Need to clone to avoid `contiguous` returning a view. values = input.values().clone() else: values = input.values() values = ( values.transpose(-3, -2) .contiguous() .unsqueeze(0) .flatten(0, -4) .reshape(-1, row_block, nnz * col_block) ) full_grid = (values.shape[0], row_block, m // row_block) grid_blocks = None tensor_dims_map = { # We span nnz number of blocks, not nnz + 1, # hence crow_indices[..., :-1] crow_indices[..., :-1]: (0, None, -1), values: (0, None, None), } def kernel(grid, *sliced_tensors): _bsr_softmax_kernel[grid]( *ptr_stride_extractor(*sliced_tensors), # pyrefly: ignore # bad-argument-count row_block, col_block, max_row_nnz, # Triton's max numel is bounded by 2 ** 17. min(2**17, max_row_nnz), ) launch_kernel(kernel, tensor_dims_map, full_grid, grid_blocks) values = ( values.reshape(-1, row_block, nnz, col_block) .transpose(-3, -2) .reshape(*input.values().shape) ) return torch.sparse_compressed_tensor( input.crow_indices().clone(), input.col_indices().clone(), values, size=input.shape, layout=input.layout, ) def _scaled_dot_product_attention( query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attn_mask: torch.Tensor | None, dropout_p: float = 0.0, is_causal: bool = False, scale: float | None = None, ): f_name = "_scaled_dot_product_attention" check(not is_causal, f"{f_name}(): is_causal == True is not supported.") check(attn_mask is not None, f"{f_name}(): attn_mask == None is not supported.") assert attn_mask is not None check( attn_mask.layout == torch.sparse_bsr, f"{f_name}(): " f"attn_mask.layout must be {torch.sparse_bsr}, but got " f"attn_mask.layout == {attn_mask.layout}.", ) check_device(f_name, key, query.device) check_device(f_name, value, query.device) check_device(f_name, attn_mask, query.device) check_dtype(f_name, key, query.dtype) check_dtype(f_name, value, query.dtype) if attn_mask.dtype is not torch.bool: check_dtype(f_name, attn_mask, query.dtype) # pyrefly: ignore [not-callable] sdpa = sampled_addmm( attn_mask, query, key.transpose(-2, -1), beta=0.0, skip_checks=False ) if scale is None and query.size(-1) == 0 or scale == 0.0: check( False, f"{f_name}(): current value of scale == {scale} " "results in division by zero.", ) scale_factor = 1 / math.sqrt(query.size(-1)) if scale is None else scale sdpa.values().mul_(scale_factor) # pyrefly: ignore [not-callable] sdpa = bsr_softmax(sdpa) torch.nn.functional.dropout(sdpa.values(), p=dropout_p, inplace=True) # pyrefly: ignore [not-callable] sdpa = bsr_dense_mm(sdpa, value) return sdpa @triton.jit def _scatter_mm2_kernel( M: tl.constexpr, K: tl.constexpr, N: tl.constexpr, blocks_ptr, blocks_stride_P, blocks_stride_M, blocks_stride_K, others_ptr, others_stride_Q, others_stride_K, others_stride_N, accumulators_ptr, accumulators_stride_R, accumulators_stride_M, accumulators_stride_N, pq_offsets_ptr, pq_offsets_stride, pq_ptr, pq_stride_T, pq_stride_1, dot_out_dtype: tl.constexpr, TILE_M: tl.constexpr, TILE_N: tl.constexpr, allow_tf32: tl.constexpr, ): Ms = M // TILE_M pid_t = tl.program_id(axis=0) pid = tl.program_id(axis=1) pid_m = pid // Ms pid_n = pid % Ms rm = pid_m * TILE_M + tl.arange(0, TILE_M) rn = pid_n * TILE_N + tl.arange(0, TILE_N) rk = tl.arange(0, K) A_ptr = blocks_ptr + ( rm[:, None] * blocks_stride_M + rk[None, :] * blocks_stride_K ) B_ptr = others_ptr + ( rk[:, None] * others_stride_K + rn[None, :] * others_stride_N ) g0 = tl.load(pq_offsets_ptr + pid_t * pq_offsets_stride) g1 = tl.load(pq_offsets_ptr + (pid_t + 1) * pq_offsets_stride) if g0 == g1: return acc_block = tl.zeros((TILE_M, TILE_N), dtype=dot_out_dtype) for i in range(g0, g1): p = tl.load(pq_ptr + i * pq_stride_T) q = tl.load(pq_ptr + i * pq_stride_T + pq_stride_1) A = tl.load(A_ptr + p * blocks_stride_P) B = tl.load(B_ptr + q * others_stride_Q) acc_block += tl.dot(A, B, out_dtype=dot_out_dtype, allow_tf32=allow_tf32) C_ptr = ( accumulators_ptr + pid_t * accumulators_stride_R + ( rm[:, None] * accumulators_stride_M + rn[None, :] * accumulators_stride_N ) ) tl.store(C_ptr, acc_block.to(accumulators_ptr.dtype.element_ty)) def _scatter_mm2( blocks: torch.Tensor, others: torch.Tensor, pq_offsets: torch.Tensor, pq_indices: torch.Tensor, accumulators: torch.Tensor, ): _P, M, K = blocks.shape _Q, _, N = others.shape meta = dict( TILE_M=max(16, M // 4), TILE_N=max(16, N // 4), num_stages=1, num_warps=2 ) def grid(META): return ( pq_offsets.shape[0] - 1, triton.cdiv(M, META["TILE_M"]) * triton.cdiv(N, META["TILE_N"]), 1, ) dot_out_dtype = { torch.float16: tl.float32, torch.bfloat16: tl.float32, torch.float32: tl.float64, torch.float64: tl.float64, }[accumulators.dtype] if "allow_tf32" not in meta: meta.update(allow_tf32=dot_out_dtype == tl.float32) _scatter_mm2_kernel[grid]( # pyrefly: ignore # bad-argument-type M, # pyrefly: ignore # bad-argument-type K, # pyrefly: ignore # bad-argument-type N, blocks, blocks.stride(0), blocks.stride(1), blocks.stride(2), others, others.stride(0), others.stride(1), others.stride(2), accumulators, accumulators.stride(0), accumulators.stride(1), accumulators.stride(2), pq_offsets, pq_offsets.stride(0), pq_indices, pq_indices.stride(0), pq_indices.stride(1), # pyrefly: ignore # bad-argument-type dot_out_dtype=dot_out_dtype, # pyrefly: ignore # bad-argument-type **meta, ) @triton.jit def _scatter_mm6_kernel( nbatches, Ms, Ks: tl.constexpr, N, blocks_ptr, blocks_stride_P, blocks_stride_M, blocks_stride_K, others_ptr, others_stride_B, others_stride_K, others_stride_N, accumulators_ptr, accumulators_stride_B, accumulators_stride_M, accumulators_stride_N, c_indices_ptr, r_offsets_ptr, p_offsets_ptr, q_offsets_ptr, is_compressed: tl.constexpr, dot_out_dtype: tl.constexpr, SPLIT_N: tl.constexpr, TILE_M: tl.constexpr, TILE_N: tl.constexpr, GROUP_SIZE: tl.constexpr, allow_tf32: tl.constexpr, ): Ns = N // SPLIT_N BLOCKS_M = Ms // TILE_M BLOCKS_N = Ns // TILE_N pid_t_ = tl.program_id(axis=0) pid = tl.program_id(axis=1) pid_b = pid_t_ % nbatches pid_t = pid_t_ // nbatches num_pid_in_group = GROUP_SIZE * BLOCKS_N group_id = pid // num_pid_in_group first_pid_m = group_id * GROUP_SIZE group_size_m = min(BLOCKS_M - first_pid_m, GROUP_SIZE) pid_m = first_pid_m + (pid % group_size_m) pid_n = (pid % num_pid_in_group) // group_size_m rm = pid_m * TILE_M + tl.arange(0, TILE_M) rn = pid_n * TILE_N + tl.arange(0, TILE_N) rk = tl.arange(0, Ks) A_ptr = blocks_ptr + ( rm[:, None] * blocks_stride_M + rk[None, :] * blocks_stride_K ) B_ptr = ( others_ptr + pid_b * others_stride_B + (rk[:, None] * others_stride_K + rn[None, :] * others_stride_N) ) # When is_compressed is True, r is the only variable that # depends on pid_t. This property allows sorting r values # before calling the kernel. The sorting of r is equivalent to # defining swizzle operator outside of the kernel. r = tl.load(r_offsets_ptr + pid_t) if is_compressed: m = (r // N) // Ms n = (r % N) // Ns r0 = tl.load(c_indices_ptr + m) r1 = tl.load(c_indices_ptr + m + 1) g0 = n * r1 + (SPLIT_N - n) * r0 nnz = r1 - r0 else: g0 = tl.load(c_indices_ptr + pid_t) g1 = tl.load(c_indices_ptr + pid_t + 1) nnz = g1 - g0 q_ptr = q_offsets_ptr + g0 acc_block = tl.zeros((TILE_M, TILE_N), dtype=dot_out_dtype) if is_compressed: A_ptr += r0 * blocks_stride_P # type: ignore[possibly-undefined] for _ in range(nnz): q = tl.load(q_ptr) B = tl.load(B_ptr + q) A = tl.load(A_ptr) acc_block += tl.dot( A, B, out_dtype=dot_out_dtype, allow_tf32=allow_tf32 ) A_ptr += blocks_stride_P q_ptr += 1 else: p_ptr = p_offsets_ptr + g0 for _ in range(nnz): q = tl.load(q_ptr) B = tl.load(B_ptr + q) p = tl.load(p_ptr) A = tl.load(A_ptr + p * blocks_stride_P) p_ptr += 1 q_ptr += 1 acc_block += tl.dot( A, B, out_dtype=dot_out_dtype, allow_tf32=allow_tf32 ) C_ptr = ( accumulators_ptr + r + pid_b * accumulators_stride_B + ( rm[:, None] * accumulators_stride_M + rn[None, :] * accumulators_stride_N ) ) tl.store(C_ptr, acc_block.to(accumulators_ptr.dtype.element_ty)) def _scatter_mm6( blocks: torch.Tensor, others: torch.Tensor, c_indices: torch.Tensor, r_offsets: torch.Tensor, p_offsets: torch.Tensor, q_offsets: torch.Tensor, meta: dict, accumulators: torch.Tensor, force_contiguous: bool = True, ): SPLIT_N = meta["SPLIT_N"] _P, Ms, Ks = blocks.shape B, _K, N = others.shape B_, _M, N_ = accumulators.shape assert N_ == N Ns = N // SPLIT_N assert B_ == B def grid(META): return ( r_offsets.shape[0] * B, triton.cdiv(Ms, META["TILE_M"]) * triton.cdiv(Ns, META["TILE_N"]), ) dot_out_dtype = { torch.float16: tl.float32, torch.bfloat16: tl.float32, torch.float32: tl.float64, torch.float64: tl.float64, }[accumulators.dtype] if "allow_tf32" not in meta: meta.update(allow_tf32=dot_out_dtype == tl.float32) assert c_indices.stride(0) == 1 assert r_offsets.stride(0) == 1 assert p_offsets.stride(0) == 1 assert q_offsets.stride(0) == 1 # Re non-contiguous tensor arguments. Sometimes triton kernel # launches may fail with # # RuntimeError: Triton Error [CUDA]: an illegal memory access was encountered # # that appears to be case when the size of a non-contiguous # tensor argument is larger than a certain threshold. Could # this be related to shared memory or L1 cache size of a GPU # card? In anycase, ensuring that tensor arguments are # contiguous seems to avoid the above exception. So, in the # following we'll always convert tensor arguments to # C-contiguous tensors. if force_contiguous: blocks = blocks.contiguous() others = others.contiguous() if not accumulators.is_contiguous(): accumulators_ = accumulators.contiguous() else: accumulators_ = accumulators else: accumulators_ = accumulators _scatter_mm6_kernel[grid]( B, Ms, # pyrefly: ignore # bad-argument-type Ks, N, blocks, blocks.stride(0), blocks.stride(1), blocks.stride(2), others, others.stride(0), others.stride(1), others.stride(2), accumulators_, accumulators_.stride(0), accumulators_.stride(1), accumulators_.stride(2), c_indices, r_offsets, p_offsets, q_offsets, # pyrefly: ignore # bad-argument-type dot_out_dtype=dot_out_dtype, **meta, ) if force_contiguous and not accumulators.is_contiguous(): accumulators.copy_(accumulators_) @triton.jit def _bsr_strided_addmm_kernel( # values prologue values_ptr, values_batch_stride, values_nnz_stride, values_row_block_stride, values_col_block_stride, # values epilogue # crow_indices prologue crow_indices_ptr, crow_indices_batch_stride, crow_indices_stride, # crow_indices epilogue # col_indices prologue col_indices_ptr, col_indices_batch_stride, col_indices_stride, # col_indices epilogue # input prologue input_ptr, input_batch_stride, input_tiled_row_stride, input_tiled_col_stride, input_row_block_stride, input_col_block_stride, # input epilogue # dense prologue dense_ptr, dense_batch_stride, dense_tiled_row_stride, dense_tiled_col_stride, dense_row_block_stride, dense_col_block_stride, # dense epilogue # left_alpha prologue left_alpha_ptr, left_alpha_batch_stride, left_alpha_tiled_row_stride, left_alpha_tiled_col_stride: tl.constexpr, left_alpha_row_block_stride, left_alpha_col_block_stride: tl.constexpr, # left_alpha epilogue # right_alpha prologue right_alpha_ptr, right_alpha_batch_stride, right_alpha_tiled_row_stride: tl.constexpr, right_alpha_tiled_col_stride, right_alpha_row_block_stride: tl.constexpr, right_alpha_col_block_stride, # right_alpha epilogue # output prologue output_ptr, output_batch_stride, output_tiled_row_stride, output_tiled_col_stride, output_row_block_stride, output_col_block_stride, # output epilogue beta, alpha, beta_is_one: tl.constexpr, beta_is_nonzero: tl.constexpr, alpha_is_one: tl.constexpr, left_alpha_is_one: tl.constexpr, right_alpha_is_one: tl.constexpr, BLOCKSIZE_ROW: tl.constexpr, BLOCKSIZE_COL: tl.constexpr, BLOCKSIZE_INNER: tl.constexpr, acc_dtype: tl.constexpr, allow_tf32: tl.constexpr, GROUP_SIZE_ROW: tl.constexpr, SPLIT_N: tl.constexpr, ): # left/right_alpha tensors are originally (* + 1)-dimensional assert left_alpha_tiled_col_stride == 0 assert left_alpha_col_block_stride == 0 assert right_alpha_tiled_row_stride == 0 assert right_alpha_row_block_stride == 0 batch_pid = tl.program_id(axis=2) row_block_pid = tl.program_id(axis=0) col_block_pid = tl.program_id(axis=1) n_block_rows = tl.num_programs(axis=0) n_block_cols = tl.num_programs(axis=1) row_block_pid, col_block_pid = tl.swizzle2d( row_block_pid, col_block_pid, n_block_rows, n_block_cols, GROUP_SIZE_ROW ) crow_indices_offset_ptr = ( crow_indices_ptr + crow_indices_batch_stride * batch_pid + crow_indices_stride * row_block_pid ) nnz_offset = tl.load(crow_indices_offset_ptr) nnz_offset_next = tl.load(crow_indices_offset_ptr + crow_indices_stride) # Compute nnz for the row with number row_block_pid. row_nnz = nnz_offset_next - nnz_offset row_block_arange = tl.arange(0, BLOCKSIZE_ROW) inner_block_arange = tl.arange(0, BLOCKSIZE_INNER) col_block_arange = tl.arange(0, BLOCKSIZE_COL) # Pointers are set to the first block of the current row. values_block_ptrs = ( values_ptr + values_batch_stride * batch_pid + values_nnz_stride * nnz_offset + values_row_block_stride * row_block_arange[:, None] + values_col_block_stride * inner_block_arange[None, :] ) # NOTE: dense is advanced into all dimensions but the tiled row one. # That will be advanced in the loop according to values in col_indices. dense_block_ptrs = ( dense_ptr + dense_batch_stride * batch_pid + dense_tiled_col_stride * col_block_pid + dense_row_block_stride * inner_block_arange[:, None] + dense_col_block_stride * col_block_arange[None, :] ) # Pointers are set to exact write-to locations output_ptrs = ( output_ptr + output_batch_stride * batch_pid + output_tiled_row_stride * row_block_pid + output_tiled_col_stride * col_block_pid + output_row_block_stride * row_block_arange[:, None] + output_col_block_stride * col_block_arange[None, :] ) # Set pointer to the first nonzero element in the current row col_index_nnz_ptr = ( col_indices_ptr + col_indices_batch_stride * batch_pid + col_indices_stride * nnz_offset ) output_acc_block = tl.zeros((BLOCKSIZE_ROW, BLOCKSIZE_COL), dtype=acc_dtype) for _ in range(row_nnz): values_block = tl.load(values_block_ptrs) # find which row of dense needs to get loaded # for multiplication with values_block. dense_row_idx = tl.load(col_index_nnz_ptr) dense_block = tl.load( dense_block_ptrs + dense_tiled_row_stride * dense_row_idx ) # do block mm output_acc_block += tl.dot( values_block, dense_block, allow_tf32=allow_tf32, out_dtype=acc_dtype ) # move val/col_index ptrs to the next block in the row values_block_ptrs += values_nnz_stride col_index_nnz_ptr += col_indices_stride if not alpha_is_one: output_acc_block *= alpha if not left_alpha_is_one: left_alpha_ptrs = ( left_alpha_ptr + left_alpha_batch_stride * batch_pid + left_alpha_tiled_row_stride * row_block_pid + left_alpha_tiled_col_stride * col_block_pid + left_alpha_row_block_stride * row_block_arange[:, None] + left_alpha_col_block_stride * col_block_arange[None, :] ) output_acc_block *= tl.load(left_alpha_ptrs) if not right_alpha_is_one: right_alpha_ptrs = ( right_alpha_ptr + right_alpha_batch_stride * batch_pid + right_alpha_tiled_row_stride * row_block_pid + right_alpha_tiled_col_stride * col_block_pid + right_alpha_row_block_stride * row_block_arange[:, None] + right_alpha_col_block_stride * col_block_arange[None, :] ) output_acc_block *= tl.load(right_alpha_ptrs) if beta_is_nonzero: input_ptrs = ( input_ptr + input_batch_stride * batch_pid + input_tiled_row_stride * row_block_pid + input_tiled_col_stride * col_block_pid + input_row_block_stride * row_block_arange[:, None] + input_col_block_stride * col_block_arange[None, :] ) if beta_is_one: output_acc_block += tl.load(input_ptrs) else: output_acc_block += beta * tl.load(input_ptrs) # write back the result tl.store(output_ptrs, output_acc_block.to(output_ptr.dtype.element_ty)) else: bsr_softmax = None # type: ignore[assignment] bsr_dense_mm = None # type: ignore[assignment] sampled_addmm = None # type: ignore[assignment] _scaled_dot_product_attention = None # type: ignore[assignment] _scatter_mm2 = None # type: ignore[assignment] _scatter_mm6 = None # type: ignore[assignment] _bsr_strided_addmm_kernel = None # type: ignore[assignment]
TensorAsKey
python
google__pytype
pytype/tools/traces/traces_test.py
{ "start": 6543, "end": 8401 }
class ____(MatchAstTestCase): """Tests for traces.MatchAstVisitor.match_Call.""" def test_basic(self): matches = self._get_traces(""" def f(x): return x + 1.0 f(42) """, ast.Call) self.assertTracesEqual(matches, [ ((3, 0), _CALLFUNC_OP, "f", ("Callable[[Any], Any]", "float"))]) def test_chain(self): matches = self._get_traces(""" class Foo: def f(self, x): return x Foo().f(42) """, ast.Call) self.assertTracesEqual( matches, [ ((4, 0), _CALLFUNC_OP, "Foo", ("type[Foo]", "Foo")), ((4, 0), _CALLMETH_OP, "f", ("Callable[[Any], Any]", "int")), ], ) def test_multiple_bindings(self): matches = self._get_traces(""" class Foo: @staticmethod def f(x): return x class Bar: @staticmethod def f(x): return x + 1.0 f = Foo.f if __random__ else Bar.f f(42) """, ast.Call) self.assertTracesEqual(matches, [ ((10, 0), _CALLFUNC_OP, "f", ("Callable[[Any], Any]", "Union[int, float]"))]) def test_bad_call(self): matches = self._get_traces(""" def f(): pass f(42) """, ast.Call) self.assertTracesEqual( matches, [((2, 0), _CALLFUNC_OP, "f", ("Callable[[], Any]", "Any"))]) def test_literal(self): matches = self._get_traces("''.upper()", ast.Call) self.assertTracesEqual(matches, [ ((1, 0), _CALLMETH_OP, "upper", ("Callable[[], str]", "str"))]) def test_lookahead(self): matches = self._get_traces(""" def f(x, y, z): return x + y + z f( 0, 1, 2, ) """, ast.Call) self.assertTracesEqual(matches, [ ((3, 0), _CALLFUNC_OP, "f", ("Callable[[Any, Any, Any], Any]", "int"))])
MatchCallTest
python
pallets__jinja
docs/examples/cache_extension.py
{ "start": 60, "end": 2053 }
class ____(Extension): # a set of names that trigger the extension. tags = {"cache"} def __init__(self, environment): super().__init__(environment) # add the defaults to the environment environment.extend(fragment_cache_prefix="", fragment_cache=None) def parse(self, parser): # the first token is the token that started the tag. In our case # we only listen to ``'cache'`` so this will be a name token with # `cache` as value. We get the line number so that we can give # that line number to the nodes we create by hand. lineno = next(parser.stream).lineno # now we parse a single expression that is used as cache key. args = [parser.parse_expression()] # if there is a comma, the user provided a timeout. If not use # None as second parameter. if parser.stream.skip_if("comma"): args.append(parser.parse_expression()) else: args.append(nodes.Const(None)) # now we parse the body of the cache block up to `endcache` and # drop the needle (which would always be `endcache` in that case) body = parser.parse_statements(["name:endcache"], drop_needle=True) # now return a `CallBlock` node that calls our _cache_support # helper method on this extension. return nodes.CallBlock( self.call_method("_cache_support", args), [], [], body ).set_lineno(lineno) def _cache_support(self, name, timeout, caller): """Helper callback.""" key = self.environment.fragment_cache_prefix + name # try to load the block from the cache # if there is no fragment in the cache, render it and store # it in the cache. rv = self.environment.fragment_cache.get(key) if rv is not None: return rv rv = caller() self.environment.fragment_cache.add(key, rv, timeout) return rv
FragmentCacheExtension
python
ray-project__ray
rllib/offline/json_reader.py
{ "start": 8570, "end": 16889 }
class ____(InputReader): """Reader object that loads experiences from JSON file chunks. The input files will be read from in random order. """ @PublicAPI def __init__( self, inputs: Union[str, List[str]], ioctx: Optional[IOContext] = None ): """Initializes a JsonReader instance. Args: inputs: Either a glob expression for files, e.g. `/tmp/**/*.json`, or a list of single file paths or URIs, e.g., ["s3://bucket/file.json", "s3://bucket/file2.json"]. ioctx: Current IO context object or None. """ logger.info( "You are using JSONReader. It is recommended to use " + "DatasetReader instead for better sharding support." ) self.ioctx = ioctx or IOContext() self.default_policy = self.policy_map = None self.batch_size = 1 if self.ioctx: self.batch_size = self.ioctx.config.get("train_batch_size", 1) num_workers = self.ioctx.config.get("num_env_runners", 0) if num_workers: self.batch_size = max(math.ceil(self.batch_size / num_workers), 1) if self.ioctx.worker is not None: self.policy_map = self.ioctx.worker.policy_map self.default_policy = self.policy_map.get(DEFAULT_POLICY_ID) if self.default_policy is None: assert len(self.policy_map) == 1 self.default_policy = next(iter(self.policy_map.values())) if isinstance(inputs, str): inputs = os.path.abspath(os.path.expanduser(inputs)) if os.path.isdir(inputs): inputs = [os.path.join(inputs, "*.json"), os.path.join(inputs, "*.zip")] logger.warning(f"Treating input directory as glob patterns: {inputs}") else: inputs = [inputs] if any(urlparse(i).scheme not in [""] + WINDOWS_DRIVES for i in inputs): raise ValueError( "Don't know how to glob over `{}`, ".format(inputs) + "please specify a list of files to read instead." ) else: self.files = [] for i in inputs: self.files.extend(glob.glob(i)) elif isinstance(inputs, (list, tuple)): self.files = list(inputs) else: raise ValueError( "type of inputs must be list or str, not {}".format(inputs) ) if self.files: logger.info("Found {} input files.".format(len(self.files))) else: raise ValueError("No files found matching {}".format(inputs)) self.cur_file = None @override(InputReader) def next(self) -> SampleBatchType: ret = [] count = 0 while count < self.batch_size: batch = self._try_parse(self._next_line()) tries = 0 while not batch and tries < 100: tries += 1 logger.debug("Skipping empty line in {}".format(self.cur_file)) batch = self._try_parse(self._next_line()) if not batch: raise ValueError( "Failed to read valid experience batch from file: {}".format( self.cur_file ) ) batch = self._postprocess_if_needed(batch) count += batch.count ret.append(batch) ret = concat_samples(ret) return ret def read_all_files(self) -> SampleBatchType: """Reads through all files and yields one SampleBatchType per line. When reaching the end of the last file, will start from the beginning again. Yields: One SampleBatch or MultiAgentBatch per line in all input files. """ for path in self.files: file = self._try_open_file(path) while True: line = file.readline() if not line: break batch = self._try_parse(line) if batch is None: break yield batch def _postprocess_if_needed(self, batch: SampleBatchType) -> SampleBatchType: if not self.ioctx.config.get("postprocess_inputs"): return batch batch = convert_ma_batch_to_sample_batch(batch) if isinstance(batch, SampleBatch): out = [] for sub_batch in batch.split_by_episode(): out.append(self.default_policy.postprocess_trajectory(sub_batch)) return concat_samples(out) else: # TODO(ekl) this is trickier since the alignments between agent # trajectories in the episode are not available any more. raise NotImplementedError( "Postprocessing of multi-agent data not implemented yet." ) def _try_open_file(self, path): if urlparse(path).scheme not in [""] + WINDOWS_DRIVES: if smart_open is None: raise ValueError( "You must install the `smart_open` module to read " "from URIs like {}".format(path) ) ctx = smart_open else: # Allow shortcut for home directory ("~/" -> env[HOME]). if path.startswith("~/"): path = os.path.join(os.environ.get("HOME", ""), path[2:]) # If path doesn't exist, try to interpret is as relative to the # rllib directory (located ../../ from this very module). path_orig = path if not os.path.exists(path): path = os.path.join(Path(__file__).parent.parent, path) if not os.path.exists(path): raise FileNotFoundError(f"Offline file {path_orig} not found!") # Unzip files, if necessary and re-point to extracted json file. if re.search("\\.zip$", path): with zipfile.ZipFile(path, "r") as zip_ref: zip_ref.extractall(Path(path).parent) path = re.sub("\\.zip$", ".json", path) assert os.path.exists(path) ctx = open file = ctx(path, "r") return file def _try_parse(self, line: str) -> Optional[SampleBatchType]: line = line.strip() if not line: return None try: batch = self._from_json(line) except Exception: logger.exception( "Ignoring corrupt json record in {}: {}".format(self.cur_file, line) ) return None batch = postprocess_actions(batch, self.ioctx) return batch def _next_line(self) -> str: if not self.cur_file: self.cur_file = self._next_file() line = self.cur_file.readline() tries = 0 while not line and tries < 100: tries += 1 if hasattr(self.cur_file, "close"): # legacy smart_open impls self.cur_file.close() self.cur_file = self._next_file() line = self.cur_file.readline() if not line: logger.debug("Ignoring empty file {}".format(self.cur_file)) if not line: raise ValueError( "Failed to read next line from files: {}".format(self.files) ) return line def _next_file(self) -> FileType: # If this is the first time, we open a file, make sure all workers # start with a different one if possible. if self.cur_file is None and self.ioctx.worker is not None: idx = self.ioctx.worker.worker_index total = self.ioctx.worker.num_workers or 1 path = self.files[round((len(self.files) - 1) * (idx / total))] # After the first file, pick all others randomly. else: path = random.choice(self.files) return self._try_open_file(path) def _from_json(self, data: str) -> SampleBatchType: if isinstance(data, bytes): # smart_open S3 doesn't respect "r" data = data.decode("utf-8") json_data = json.loads(data) return from_json_data(json_data, self.ioctx.worker)
JsonReader
python
boto__boto3
tests/unit/docs/test_waiter.py
{ "start": 660, "end": 2485 }
class ____(BaseDocsTest): def test_document_resource_waiters(self): service_waiter_model = self.botocore_session.get_waiter_model( 'myservice' ) subresource = self.resource.Sample('mysample') waiter_documenter = WaiterResourceDocumenter( subresource, service_waiter_model, self.root_services_path ) waiter_documenter.document_resource_waiters(self.doc_structure) self.assert_contains_lines_in_order( [ '-------\nWaiters\n-------', 'Waiters provide an interface to wait for a resource', ' to reach a specific state.', 'For more information about waiters refer to the', ] ) self.assert_contains_lines_in_order( [ 'wait_until_complete', '.. py:method:: MyService.Sample.wait_until_complete(**kwargs)', ( ' Waits until this Sample is complete. This method calls ' ':py:meth:`MyService.Waiter.sample_operation_complete.wait` ' 'which polls :py:meth:`MyService.Client.sample_operation` ' 'every 15 seconds until a successful state is reached. An ' 'error is raised after 40 failed checks.' ), ' **Request Syntax**', ' ::', ' sample.wait_until_complete(', " Bar='string'", ' )', ' :type Bar: string', ' :param Bar: Documents Bar', ' :returns: None', ], self.get_nested_service_contents( 'myservice', 'sample', 'wait_until_complete' ), )
TestWaiterResourceDocumenter
python
getsentry__sentry
tests/sentry/snuba/test_errors.py
{ "start": 672, "end": 65007 }
class ____(SnubaTestCase, TestCase): def setUp(self) -> None: super().setUp() self.environment = self.create_environment(self.project, name="prod") self.release = self.create_release(self.project, version="first-release") self.now = before_now() self.one_min_ago = before_now(minutes=1) self.two_min_ago = before_now(minutes=2) self.event_time = self.one_min_ago # error event self.event = self.store_event( data={ "message": "oh no", "release": "first-release", "environment": "prod", "platform": "python", "user": {"id": "99", "email": "bruce@example.com", "username": "brucew"}, "timestamp": self.event_time.isoformat(), "tags": [["key1", "value1"]], }, project_id=self.project.id, ) # transaction event data = load_data("transaction", timestamp=self.event_time) data["transaction"] = "a" * 32 data["user"] = {"id": "99", "email": "bruce@example.com", "username": "brucew"} data["release"] = "first-release" data["environment"] = self.environment.name data["tags"] = [["key1", "value1"]] self.store_event(data=data, project_id=self.project.id) self.snuba_params = SnubaParams( organization=self.organization, projects=[self.project], start=before_now(days=1), end=self.now, ) def test_errors_query(self) -> None: result = errors.query( selected_columns=["transaction"], query="", snuba_params=self.snuba_params, referrer="test_errors_query", ) data = result["data"] assert len(data) == 1 assert data[0] == {"transaction": ""} def test_project_mapping(self) -> None: other_project = self.create_project(organization=self.organization) self.snuba_params.projects = [other_project] self.store_event( data={"message": "hello", "timestamp": self.one_min_ago.isoformat()}, project_id=other_project.id, ) result = errors.query( selected_columns=["project", "message"], query="", snuba_params=self.snuba_params, orderby=["project"], referrer="errors", ) data = result["data"] assert len(data) == 1 assert data[0]["project"] == other_project.slug def test_issue_short_id_mapping(self) -> None: tests = [ ("issue", f"issue:{self.event.group.qualified_short_id}"), ("issue", f"issue.id:{self.event.group_id}"), ("issue.id", f"issue:{self.event.group.qualified_short_id}"), ("issue.id", f"issue.id:{self.event.group_id}"), ] for column, query in tests: result = errors.query( selected_columns=[column], query=query, referrer="errors", snuba_params=self.snuba_params, ) data = result["data"] assert len(data) == 1 # The query will translate `issue` into `issue.id`. Additional post processing # is required to insert the `issue` column. assert [item["issue.id"] for item in data] == [self.event.group_id] def test_issue_filters(self) -> None: tests = [ "has:issue", "has:issue.id", f"issue:[{self.event.group.qualified_short_id}]", f"issue.id:[{self.event.group_id}]", ] for query in tests: result = errors.query( selected_columns=["issue", "issue.id"], query=query, snuba_params=self.snuba_params, referrer="errors", ) data = result["data"] assert len(data) == 1 # The query will translate `issue` into `issue.id`. Additional post processing # is required to insert the `issue` column. assert [item["issue.id"] for item in data] == [self.event.group_id] def test_tags_orderby(self) -> None: self.event = self.store_event( data={ "message": "oh no", "release": "first-release", "environment": "prod", "platform": "python", "user": {"id": "99", "email": "bruce@example.com", "username": "brucew"}, "timestamp": self.event_time.isoformat(), "tags": [["key1", "value2"]], }, project_id=self.project.id, ) tests = [ ("key1", "key1", ["value1", "value2"]), ("key1", "-key1", ["value2", "value1"]), ("tags[key1]", "tags[key1]", ["value1", "value2"]), ("tags[key1]", "-tags[key1]", ["value2", "value1"]), ] for column, orderby, expected in tests: result = errors.query( selected_columns=[column], query="", snuba_params=self.snuba_params, orderby=[orderby], referrer="test_discover_query", ) data = result["data"] assert len(data) == len(expected) assert [item[column] for item in data] == expected def test_tags_filter(self) -> None: self.event = self.store_event( data={ "message": "oh no", "release": "first-release", "environment": "prod", "platform": "python", "user": {"id": "99", "email": "bruce@example.com", "username": "brucew"}, "timestamp": self.event_time.isoformat(), "tags": [["key1", "value2"]], }, project_id=self.project.id, ) tests: list[tuple[str, str, list[str]]] = [ ("key1", "", ["value1", "value2"]), ("key1", "has:key1", ["value1", "value2"]), ("key1", "!has:key1", []), ("key1", "key1:value1", ["value1"]), ("key1", "key1:value2", ["value2"]), ("key1", 'key1:""', []), ("key1", "key1:value*", ["value1", "value2"]), ("key1", 'key1:["value1"]', ["value1"]), ("key1", 'key1:["value1", "value2"]', ["value1", "value2"]), ("tags[key1]", "", ["value1", "value2"]), # has does not work with tags[...] syntax # ("tags[key1]", 'has:"tags[key1]"', ["value1", "value2"]), # ("tags[key1]", '!has:"tags[key1]"', []), ("tags[key1]", "tags[key1]:value1", ["value1"]), ("tags[key1]", "tags[key1]:value2", ["value2"]), ("tags[key1]", 'tags[key1]:""', []), ("tags[key1]", "tags[key1]:value*", ["value1", "value2"]), ("tags[key1]", 'tags[key1]:["value1"]', ["value1"]), ("tags[key1]", 'tags[key1]:["value1", "value2"]', ["value1", "value2"]), ] for column, query, expected in tests: result = errors.query( selected_columns=[column], query=query, snuba_params=self.snuba_params, orderby=[column], referrer="test_discover_query", ) data = result["data"] assert len(data) == len(expected), (column, query, expected) assert [item[column] for item in data] == expected def test_tags_colliding_with_fields(self) -> None: event = self.store_event( data={ "message": "oh no", "release": "first-release", "environment": "prod", "platform": "python", "user": {"id": "99", "email": "bruce@example.com", "username": "brucew"}, "timestamp": self.event_time.isoformat(), "tags": [["id", "new"]], }, project_id=self.project.id, ) tests = [ ("id", "", sorted([self.event.event_id, event.event_id])), ("id", f"id:{event.event_id}", [event.event_id]), ("tags[id]", "", ["", "new"]), ("tags[id]", "tags[id]:new", ["new"]), ] for column, query, expected in tests: result = errors.query( selected_columns=[column], query=query, snuba_params=self.snuba_params, orderby=[column], referrer="test_discover_query", ) data = result["data"] assert len(data) == len(expected), (query, expected) assert [item[column] for item in data] == expected def test_reverse_sorting_issue(self) -> None: other_event = self.store_event( data={ "message": "whoopsies", "release": "first-release", "environment": "prod", "platform": "python", "user": {"id": "99", "email": "bruce@example.com", "username": "brucew"}, "timestamp": self.event_time.isoformat(), }, project_id=self.project.id, ) tests = [ # issue is not sortable # "issue", "issue.id", ] for column in tests: for direction in ["", "-"]: result = errors.query( selected_columns=[column], query="", snuba_params=self.snuba_params, orderby=[f"{direction}{column}"], referrer="errors", ) data = result["data"] assert len(data) == 2 expected = [self.event.group_id, other_event.group_id] if direction == "-": expected.reverse() assert [item["issue.id"] for item in data] == expected def test_timestamp_rounding_fields(self) -> None: result = errors.query( selected_columns=["timestamp.to_hour", "timestamp.to_day"], query="", snuba_params=self.snuba_params, referrer="test_discover_query", ) data = result["data"] assert len(data) == 1 hour = self.event_time.replace(minute=0, second=0, microsecond=0) day = hour.replace(hour=0) assert [item["timestamp.to_hour"] for item in data] == [hour.isoformat()] assert [item["timestamp.to_day"] for item in data] == [day.isoformat()] def test_timestamp_rounding_filters(self) -> None: one_day_ago = before_now(days=1) two_day_ago = before_now(days=2) three_day_ago = before_now(days=3) self.snuba_params.start = three_day_ago self.store_event( data={ "message": "oh no", "release": "first-release", "environment": "prod", "platform": "python", "user": {"id": "99", "email": "bruce@example.com", "username": "brucew"}, "timestamp": two_day_ago.isoformat(), }, project_id=self.project.id, ) result = errors.query( selected_columns=["timestamp.to_hour", "timestamp.to_day"], query=f"timestamp.to_hour:<{one_day_ago.isoformat()} timestamp.to_day:<{one_day_ago.isoformat()}", snuba_params=self.snuba_params, referrer="test_discover_query", ) data = result["data"] assert len(data) == 1 hour = two_day_ago.replace(minute=0, second=0, microsecond=0) day = hour.replace(hour=0) assert [item["timestamp.to_hour"] for item in data] == [hour.isoformat()] assert [item["timestamp.to_day"] for item in data] == [day.isoformat()] def test_user_display(self) -> None: # `user.display` should give `username` self.store_event( data={ "message": "oh no", "release": "first-release", "environment": "prod", "platform": "python", "user": {"username": "brucew", "id": "1234", "ip": "127.0.0.1"}, "timestamp": self.event_time.isoformat(), }, project_id=self.project.id, ) # `user.display` should give `id` self.store_event( data={ "message": "oh no", "release": "first-release", "environment": "prod", "platform": "python", "user": {"id": "1234", "ip": "127.0.0.1"}, "timestamp": self.event_time.isoformat(), }, project_id=self.project.id, ) # `user.display` should give `ip` self.store_event( data={ "message": "oh no", "release": "first-release", "environment": "prod", "platform": "python", "user": {"ip_address": "127.0.0.1"}, "timestamp": self.event_time.isoformat(), }, project_id=self.project.id, ) result = errors.query( selected_columns=["user.display"], query="", snuba_params=self.snuba_params, referrer="test_discover_query", ) data = result["data"] assert len(data) == 4 assert {item["user.display"] for item in data} == { "bruce@example.com", "brucew", "1234", "127.0.0.1", } def test_user_display_filter(self) -> None: # `user.display` should give `username` self.store_event( data={ "message": "oh no", "release": "first-release", "environment": "prod", "platform": "python", "user": {"username": "brucew", "ip": "127.0.0.1"}, "timestamp": self.event_time.isoformat(), }, project_id=self.project.id, ) result = errors.query( selected_columns=["user.display"], query="has:user.display user.display:bruce@example.com", snuba_params=self.snuba_params, referrer="test_discover_query", ) data = result["data"] assert len(data) == 1 assert [item["user.display"] for item in data] == ["bruce@example.com"] def test_message_orderby(self) -> None: self.event = self.store_event( data={ "message": "oh yeah", "release": "first-release", "environment": "prod", "platform": "python", "user": {"id": "99", "email": "bruce@example.com", "username": "brucew"}, "timestamp": self.event_time.isoformat(), }, project_id=self.project.id, ) tests = [ ("message", ["oh no", "oh yeah"]), ("-message", ["oh yeah", "oh no"]), ] for orderby, expected in tests: result = errors.query( selected_columns=["message"], query="", snuba_params=self.snuba_params, orderby=[orderby], referrer="test_discover_query", ) data = result["data"] assert len(data) == 2 assert [item["message"] for item in data] == expected def test_message_filter(self) -> None: self.event = self.store_event( data={ "message": "oh yeah", "release": "first-release", "environment": "prod", "platform": "python", "user": {"id": "99", "email": "bruce@example.com", "username": "brucew"}, "timestamp": self.event_time.isoformat(), }, project_id=self.project.id, ) tests: list[tuple[str, list[str]]] = [ ('message:"oh no"', ["oh no"]), ('message:"oh yeah"', ["oh yeah"]), ('message:""', []), ("has:message", ["oh no", "oh yeah"]), ("!has:message", []), ("message:oh*", ["oh no", "oh yeah"]), ('message:"oh *"', ["oh no", "oh yeah"]), ('message:["oh meh"]', []), ('message:["oh yeah"]', ["oh yeah"]), ('message:["oh yeah", "oh no"]', ["oh no", "oh yeah"]), ] for query, expected in tests: result = errors.query( selected_columns=["message"], query=query, snuba_params=self.snuba_params, orderby=["message"], referrer="test_discover_query", ) data = result["data"] assert len(data) == len(expected) assert [item["message"] for item in data] == expected def test_to_other_function(self) -> None: project = self.create_project() for i in range(3): data = load_data("javascript", timestamp=before_now(minutes=5)) data["transaction"] = f"/to_other/{i}" data["release"] = "aaaa" self.store_event(data, project_id=project.id) data = load_data("javascript", timestamp=before_now(minutes=5)) data["transaction"] = "/to_other/y" data["release"] = "yyyy" self.store_event(data, project_id=project.id) data = load_data("javascript", timestamp=before_now(minutes=5)) data["transaction"] = "/to_other/z" data["release"] = "zzzz" self.store_event(data, project_id=project.id) columns1 = ["transaction", 'to_other(release,"aaaa")'] columns2 = ["transaction", 'to_other(release,"aaaa",old,new)'] test_cases = [ (columns1, "", ["this", "this", "this", "that", "that"], "to_other_release__aaaa"), (columns2, "", ["new", "new", "new", "old", "old"], "to_other_release__aaaa__old_new"), ] for cols, query, expected, alias in test_cases: result = errors.query( selected_columns=cols, query=query, orderby=["transaction"], snuba_params=SnubaParams( start=before_now(minutes=10), end=before_now(minutes=2), projects=[project], ), referrer="test_discover_query", ) data = result["data"] assert len(data) == len(expected) assert [x[alias] for x in data] == expected def test_count_if_function(self) -> None: for i in range(3): data = load_data("javascript", timestamp=before_now(minutes=5)) data["release"] = "aaaa" self.store_event(data, project_id=self.project.id) data = load_data("javascript", timestamp=before_now(minutes=5)) data["release"] = "bbbb" self.store_event(data, project_id=self.project.id) data = load_data("javascript", timestamp=before_now(minutes=5)) data["release"] = "cccc" self.store_event(data, project_id=self.project.id) columns1 = ["count()", "count_if(release,equals,aaaa)", "count_if(release,notEquals,aaaa)"] columns2 = ["count()", "count_if(release,less,bbbb)", "count_if(release,lessOrEquals,bbbb)"] test_cases = [ ( columns1, "", { "count": 5, "count_if_release_equals_aaaa": 3, "count_if_release_notEquals_aaaa": 2, }, ), ( columns2, "", { "count": 5, "count_if_release_less_bbbb": 3, "count_if_release_lessOrEquals_bbbb": 4, }, ), ] for cols, query, expected in test_cases: result = errors.query( selected_columns=cols, query=query, snuba_params=SnubaParams( start=before_now(minutes=10), end=before_now(minutes=2), projects=[self.project], ), referrer="test_discover_query", ) data = result["data"] assert len(data) == 1 assert data[0] == expected def test_count_if_function_with_unicode(self) -> None: unicode_phrase1 = "\u716e\u6211\u66f4\u591a\u7684\u98df\u7269\uff0c\u6211\u9913\u4e86" unicode_phrase2 = "\u53cd\u6b63\u611b\u60c5\u4e0d\u5c31\u90a3\u6837" for i in range(3): data = load_data("javascript", timestamp=before_now(minutes=5)) data["release"] = unicode_phrase1 self.store_event(data, project_id=self.project.id) data = load_data("javascript", timestamp=before_now(minutes=5)) data["release"] = unicode_phrase2 self.store_event(data, project_id=self.project.id) columns1 = [ "count()", f"count_if(release,equals,{unicode_phrase1})", f"count_if(release,notEquals,{unicode_phrase1})", ] test_cases = [ ( columns1, "", { "count": 4, "count_if_release_equals__u716e_u6211_u66f4_u591a_u7684_u98df_u7269_uff0c_u6211_u9913_u4e86": 3, "count_if_release_notEquals__u716e_u6211_u66f4_u591a_u7684_u98df_u7269_uff0c_u6211_u9913_u4e86": 1, }, ), ] for cols, query, expected in test_cases: result = errors.query( selected_columns=cols, query=query, snuba_params=SnubaParams( start=before_now(minutes=10), end=before_now(minutes=2), projects=[self.project], ), referrer="test_discover_query", ) data = result["data"] assert len(data) == 1 assert data[0] == expected def test_last_seen(self) -> None: project = self.create_project() expected_timestamp = before_now(minutes=3) string_condition_timestamp = before_now(minutes=4).strftime("%Y-%m-%dT%H:%M:%S+00:00") data = load_data("javascript", timestamp=expected_timestamp) data["transaction"] = "/last_seen" self.store_event(data, project_id=project.id) for i in range(6): data = load_data("javascript", timestamp=before_now(minutes=i + 4)) data["transaction"] = "/last_seen" self.store_event(data, project_id=project.id) queries = [ ("", 1, True), (f"last_seen():>{string_condition_timestamp}", 1, True), ("last_seen():>0", 1, False), ] for query, expected_length, use_aggregate_conditions in queries: result = errors.query( selected_columns=["transaction", "last_seen()"], query=query, referrer="errors", orderby=["transaction"], snuba_params=SnubaParams( start=before_now(minutes=10), end=before_now(minutes=2), projects=[project], ), use_aggregate_conditions=use_aggregate_conditions, ) data = result["data"] assert len(data) == expected_length assert data[0]["last_seen"] == expected_timestamp.strftime("%Y-%m-%dT%H:%M:%S+00:00") def test_latest_event(self) -> None: project = self.create_project() expected_timestamp = before_now(minutes=3) data = load_data("javascript", timestamp=expected_timestamp) data["transaction"] = "/latest_event" stored_event = self.store_event(data, project_id=project.id) for i in range(6): data = load_data("javascript", timestamp=before_now(minutes=i + 4)) data["transaction"] = "/latest_event" self.store_event(data, project_id=project.id) result = errors.query( selected_columns=["transaction", "latest_event()"], query="", orderby=["transaction"], referrer="errors", snuba_params=SnubaParams( start=before_now(minutes=10), end=before_now(minutes=2), projects=[project], ), use_aggregate_conditions=False, ) data = result["data"] assert len(data) == 1 assert data[0]["latest_event"] == stored_event.event_id def test_eps(self) -> None: project = self.create_project() for _ in range(6): data = load_data( "javascript", timestamp=before_now(minutes=3), ) data["transaction"] = "/eps" self.store_event(data, project_id=project.id) queries = [ ("", 1, True), ("eps():>1", 0, True), ("eps():>1", 1, False), ("eps(10):>0.5", 1, True), ("tps():>1", 0, True), ("tps():>1", 1, False), ("tps(10):>0.5", 1, True), ] for query, expected_length, use_aggregate_conditions in queries: result = errors.query( selected_columns=[ "transaction", "eps()", "eps(10)", "eps(60)", "tps()", "tps(10)", "tps(60)", ], query=query, orderby=["transaction"], snuba_params=SnubaParams( start=before_now(minutes=4), end=before_now(minutes=2), projects=[project], ), use_aggregate_conditions=use_aggregate_conditions, referrer="errors", ) data = result["data"] assert len(data) == expected_length if expected_length > 0: assert data[0]["eps"] == 0.05 assert data[0]["eps_10"] == 0.6 assert data[0]["eps_60"] == 0.1 assert data[0]["tps"] == 0.05 assert data[0]["tps_10"] == 0.6 assert data[0]["tps_60"] == 0.1 def test_epm(self) -> None: project = self.create_project() for _ in range(6): data = load_data( "javascript", timestamp=before_now(minutes=3), ) data["transaction"] = "/epm" self.store_event(data, project_id=project.id) queries = [ ("", 1, True), ("epm():>3", 0, True), ("epm():>3", 1, False), ("epm(10):>3", 1, True), ("tpm():>3", 0, True), ("tpm():>3", 1, False), ("tpm(10):>3", 1, True), ] for query, expected_length, use_aggregate_conditions in queries: result = errors.query( selected_columns=[ "transaction", "epm()", "epm(10)", "epm(60)", "tpm()", "tpm(10)", "tpm(60)", ], query=query, orderby=["transaction"], snuba_params=SnubaParams( start=before_now(minutes=4), end=before_now(minutes=2), projects=[project], ), use_aggregate_conditions=use_aggregate_conditions, referrer="errors", ) data = result["data"] assert len(data) == expected_length if expected_length > 0: assert data[0]["epm"] == 3 assert data[0]["epm_10"] == 36.0 assert data[0]["epm_60"] == 6 assert data[0]["tpm"] == 3 assert data[0]["tpm_10"] == 36.0 assert data[0]["tpm_60"] == 6 def test_error_handled_alias(self) -> None: data = load_data("android-ndk", timestamp=before_now(minutes=10)) events = ( ("a" * 32, "not handled", False), ("b" * 32, "is handled", True), ("c" * 32, "undefined", None), ) for event in events: data["event_id"] = event[0] data["logentry"] = {"formatted": event[1]} data["exception"]["values"][0]["value"] = event[1] data["exception"]["values"][0]["mechanism"]["handled"] = event[2] self.store_event(data=data, project_id=self.project.id) queries: list[tuple[str, list[int]]] = [ ("", [0, 1, 1]), ("error.handled:true", [1, 1]), ("!error.handled:true", [0]), ("has:error.handled", [1, 1]), ("has:error.handled error.handled:true", [1, 1]), ("error.handled:false", [0]), ("has:error.handled error.handled:false", []), ] for query, expected_data in queries: result = errors.query( selected_columns=["error.handled"], query=query, snuba_params=SnubaParams( organization=self.organization, projects=[self.project], start=before_now(minutes=12), end=before_now(minutes=8), ), referrer="errors", ) data = result["data"] data = sorted(data, key=lambda k: (k["error.handled"] is None, k["error.handled"])) assert len(data) == len(expected_data) assert [item["error.handled"] for item in data] == expected_data def test_error_unhandled_alias(self) -> None: data = load_data("android-ndk", timestamp=before_now(minutes=10)) events = ( ("a" * 32, "not handled", False), ("b" * 32, "is handled", True), ("c" * 32, "undefined", None), ) for event in events: data["event_id"] = event[0] data["logentry"] = {"formatted": event[1]} data["exception"]["values"][0]["value"] = event[1] data["exception"]["values"][0]["mechanism"]["handled"] = event[2] self.store_event(data=data, project_id=self.project.id) queries: list[tuple[str, list[str], list[int]]] = [ ("error.unhandled:true", ["a" * 32], [1]), ("!error.unhandled:true", ["b" * 32, "c" * 32], [0, 0]), ("has:error.unhandled", ["a" * 32], [1]), ("!has:error.unhandled", ["b" * 32, "c" * 32], [0, 0]), ("has:error.unhandled error.unhandled:true", ["a" * 32], [1]), ("error.unhandled:false", ["b" * 32, "c" * 32], [0, 0]), ("has:error.unhandled error.unhandled:false", [], []), ] for query, expected_events, error_handled in queries: result = errors.query( selected_columns=["error.unhandled"], query=query, snuba_params=SnubaParams( organization=self.organization, projects=[self.project], start=before_now(minutes=12), end=before_now(minutes=8), ), referrer="errors", ) data = result["data"] assert len(data) == len(expected_events) assert [item["error.unhandled"] for item in data] == error_handled def test_array_fields(self) -> None: data = load_data("javascript") data["timestamp"] = before_now(minutes=10).isoformat() self.store_event(data=data, project_id=self.project.id) expected_filenames = [ "../../sentry/scripts/views.js", "../../sentry/scripts/views.js", "../../sentry/scripts/views.js", "raven.js", ] queries = [ ("", 1), ("stack.filename:*.js", 1), ("stack.filename:*.py", 0), ("has:stack.filename", 1), ("!has:stack.filename", 0), ] for query, expected_len in queries: result = errors.query( selected_columns=["stack.filename"], query=query, snuba_params=SnubaParams( organization=self.organization, projects=[self.project], start=before_now(minutes=12), end=before_now(minutes=8), ), referrer="errors", ) data = result["data"] assert len(data) == expected_len if len(data) == 0: continue assert len(data[0]["stack.filename"]) == len(expected_filenames) assert sorted(data[0]["stack.filename"]) == expected_filenames result = errors.query( selected_columns=["stack.filename"], query="stack.filename:[raven.js]", referrer="errors", snuba_params=SnubaParams( organization=self.organization, projects=[self.project], start=before_now(minutes=12), end=before_now(minutes=8), ), ) data = result["data"] assert len(data) == 1 assert len(data[0]["stack.filename"]) == len(expected_filenames) assert sorted(data[0]["stack.filename"]) == expected_filenames def test_orderby_field_alias(self) -> None: data = load_data("android-ndk", timestamp=before_now(minutes=10)) events = ( ("a" * 32, "not handled", False), ("b" * 32, "is handled", True), ("c" * 32, "undefined", None), ) for event in events: data["event_id"] = event[0] data["transaction"] = event[0] data["logentry"] = {"formatted": event[1]} data["exception"]["values"][0]["value"] = event[1] data["exception"]["values"][0]["mechanism"]["handled"] = event[2] self.store_event(data=data, project_id=self.project.id) queries = [ (["error.unhandled"], [0, 0, 1]), (["error.unhandled"], [0, 0, 1]), (["-error.unhandled"], [1, 0, 0]), (["-error.unhandled"], [1, 0, 0]), ] for orderby, expected in queries: result = errors.query( selected_columns=["transaction", "error.unhandled"], query="", orderby=orderby, snuba_params=SnubaParams( organization=self.organization, projects=[self.project], start=before_now(minutes=12), end=before_now(minutes=8), ), referrer="errors", ) data = result["data"] assert [x["error.unhandled"] for x in data] == expected def test_orderby_aggregate_function(self) -> None: project = self.create_project() data = load_data("javascript", timestamp=before_now(minutes=5)) data["transaction"] = "/count/1" self.store_event(data, project_id=project.id) data = load_data("javascript", timestamp=before_now(minutes=5)) data["transaction"] = "/count/2" self.store_event(data, project_id=project.id) for i in range(6): data = load_data("javascript", timestamp=before_now(minutes=5)) data["transaction"] = f"/count/{i}" self.store_event(data, project_id=project.id) data = load_data("javascript", timestamp=before_now(minutes=5)) data["transaction"] = "/count/1" self.store_event(data, project_id=project.id) orderbys = [ (["count"], [1, 1, 1, 1, 2, 3]), (["-count"], [3, 2, 1, 1, 1, 1]), (["count()"], [1, 1, 1, 1, 2, 3]), (["-count()"], [3, 2, 1, 1, 1, 1]), ] for orderby, expected in orderbys: result = errors.query( selected_columns=["transaction", "count()"], query="", orderby=orderby, snuba_params=SnubaParams( projects=[project], start=before_now(minutes=10), end=before_now(minutes=2), ), referrer="errors", ) data = result["data"] assert [x["count"] for x in data] == expected def test_field_aliasing_in_selected_columns(self) -> None: result = errors.query( selected_columns=["project.id", "user", "release", "timestamp.to_hour"], query="", snuba_params=self.snuba_params, referrer="errors", ) data = result["data"] assert len(data) == 1 assert data[0]["project.id"] == self.project.id assert data[0]["user"] == "id:99" assert data[0]["release"] == "first-release" event_hour = self.event_time.replace(minute=0, second=0, microsecond=0) assert data[0]["timestamp.to_hour"] == event_hour.isoformat() assert len(result["meta"]["fields"]) == 4 assert result["meta"]["fields"] == { "project.id": "integer", "user": "string", "release": "string", "timestamp.to_hour": "date", } def test_field_alias_with_component(self) -> None: result = errors.query( selected_columns=["project.id", "user", "user.email"], query="", snuba_params=self.snuba_params, referrer="errors", ) data = result["data"] assert len(data) == 1 assert data[0]["project.id"] == self.project.id assert data[0]["user"] == "id:99" assert data[0]["user.email"] == "bruce@example.com" assert len(result["meta"]["fields"]) == 3 assert result["meta"]["fields"] == { "project.id": "integer", "user": "string", "user.email": "string", } def test_field_aliasing_in_aggregate_functions_and_groupby(self) -> None: result = errors.query( selected_columns=["project.id", "count_unique(user.email)"], query="", snuba_params=self.snuba_params, auto_fields=True, referrer="errors", ) data = result["data"] assert len(data) == 1 assert data[0]["project.id"] == self.project.id assert data[0]["count_unique_user_email"] == 1 def test_field_aliasing_in_conditions(self) -> None: result = errors.query( selected_columns=["project.id", "user.email"], query="user.email:bruce@example.com", snuba_params=self.snuba_params, referrer="errors", auto_fields=True, ) data = result["data"] assert len(data) == 1 assert data[0]["project.id"] == self.project.id assert data[0]["user.email"] == "bruce@example.com" def test_auto_fields_simple_fields(self) -> None: result = errors.query( selected_columns=["user.email", "release"], referrer="errors", query="", snuba_params=self.snuba_params, auto_fields=True, ) data = result["data"] assert len(data) == 1 assert data[0]["id"] == self.event.event_id assert data[0]["user.email"] == "bruce@example.com" assert data[0]["release"] == "first-release" assert data[0]["project.name"] == self.project.slug assert len(result["meta"]["fields"]) == 4 assert result["meta"]["fields"] == { "user.email": "string", "release": "string", "id": "string", "project.name": "string", } def test_auto_fields_aggregates(self) -> None: result = errors.query( selected_columns=["count_unique(user.email)"], referrer="errors", query="", snuba_params=self.snuba_params, auto_fields=True, ) data = result["data"] assert len(data) == 1 assert data[0]["count_unique_user_email"] == 1 def test_release_condition(self) -> None: result = errors.query( selected_columns=["id", "message"], query=f"release:{self.create_release(self.project).version}", snuba_params=self.snuba_params, referrer="errors", ) assert len(result["data"]) == 0 result = errors.query( selected_columns=["id", "message"], query=f"release:{self.release.version}", snuba_params=self.snuba_params, referrer="errors", ) assert len(result["data"]) == 1 data = result["data"] assert data[0]["id"] == self.event.event_id assert data[0]["message"] == self.event.message assert "event_id" not in data[0] def test_semver_condition(self) -> None: release_1 = self.create_release(version="test@1.2.3") release_2 = self.create_release(version="test@1.2.4") release_3 = self.create_release(version="test@1.2.5") release_1_e_1 = self.store_event( data={"release": release_1.version, "timestamp": self.one_min_ago.isoformat()}, project_id=self.project.id, ).event_id release_1_e_2 = self.store_event( data={"release": release_1.version, "timestamp": self.one_min_ago.isoformat()}, project_id=self.project.id, ).event_id release_2_e_1 = self.store_event( data={"release": release_2.version, "timestamp": self.one_min_ago.isoformat()}, project_id=self.project.id, ).event_id release_2_e_2 = self.store_event( data={"release": release_2.version, "timestamp": self.one_min_ago.isoformat()}, project_id=self.project.id, ).event_id release_3_e_1 = self.store_event( data={"release": release_3.version, "timestamp": self.one_min_ago.isoformat()}, project_id=self.project.id, ).event_id release_3_e_2 = self.store_event( data={"release": release_3.version, "timestamp": self.one_min_ago.isoformat()}, project_id=self.project.id, ).event_id result = errors.query( selected_columns=["id"], query=f"{SEMVER_ALIAS}:>1.2.3", snuba_params=self.snuba_params, referrer="errors", ) assert {r["id"] for r in result["data"]} == { release_2_e_1, release_2_e_2, release_3_e_1, release_3_e_2, } result = errors.query( selected_columns=["id"], query=f"{SEMVER_ALIAS}:>=1.2.3", snuba_params=self.snuba_params, referrer="errors", ) assert {r["id"] for r in result["data"]} == { release_1_e_1, release_1_e_2, release_2_e_1, release_2_e_2, release_3_e_1, release_3_e_2, } result = errors.query( selected_columns=["id"], query=f"{SEMVER_ALIAS}:<1.2.4", snuba_params=self.snuba_params, referrer="errors", ) assert {r["id"] for r in result["data"]} == {release_1_e_1, release_1_e_2} result = errors.query( selected_columns=["id"], query=f"!{SEMVER_ALIAS}:1.2.3", snuba_params=self.snuba_params, referrer="errors", ) assert {r["id"] for r in result["data"]} == { self.event.event_id, release_2_e_1, release_2_e_2, release_3_e_1, release_3_e_2, } def test_release_stage_condition(self) -> None: replaced_release = self.create_release( version="replaced_release", environments=[self.environment], adopted=timezone.now(), unadopted=timezone.now(), ) adopted_release = self.create_release( version="adopted_release", environments=[self.environment], adopted=timezone.now(), ) self.create_release(version="not_adopted_release", environments=[self.environment]) adopted_release_e_1 = self.store_event( data={ "release": adopted_release.version, "environment": self.environment.name, "timestamp": self.one_min_ago.isoformat(), }, project_id=self.project.id, ).event_id adopted_release_e_2 = self.store_event( data={ "release": adopted_release.version, "environment": self.environment.name, "timestamp": self.one_min_ago.isoformat(), }, project_id=self.project.id, ).event_id replaced_release_e_1 = self.store_event( data={ "release": replaced_release.version, "environment": self.environment.name, "timestamp": self.one_min_ago.isoformat(), }, project_id=self.project.id, ).event_id replaced_release_e_2 = self.store_event( data={ "release": replaced_release.version, "environment": self.environment.name, "timestamp": self.one_min_ago.isoformat(), }, project_id=self.project.id, ).event_id self.snuba_params.environments = [self.environment] result = errors.query( selected_columns=["id"], query=f"{RELEASE_STAGE_ALIAS}:{ReleaseStages.ADOPTED.value}", snuba_params=self.snuba_params, referrer="errors", ) assert {r["id"] for r in result["data"]} == { adopted_release_e_1, adopted_release_e_2, } result = errors.query( selected_columns=["id"], query=f"!{RELEASE_STAGE_ALIAS}:{ReleaseStages.LOW_ADOPTION.value}", snuba_params=self.snuba_params, referrer="errors", ) assert {r["id"] for r in result["data"]} == { adopted_release_e_1, adopted_release_e_2, replaced_release_e_1, replaced_release_e_2, } result = errors.query( selected_columns=["id"], query=f"{RELEASE_STAGE_ALIAS}:[{ReleaseStages.ADOPTED.value}, {ReleaseStages.REPLACED.value}]", snuba_params=self.snuba_params, referrer="errors", ) assert {r["id"] for r in result["data"]} == { adopted_release_e_1, adopted_release_e_2, replaced_release_e_1, replaced_release_e_2, } def test_semver_package_condition(self) -> None: release_1 = self.create_release(version="test@1.2.3") release_2 = self.create_release(version="test2@1.2.4") release_1_e_1 = self.store_event( data={"release": release_1.version, "timestamp": self.one_min_ago.isoformat()}, project_id=self.project.id, ).event_id release_1_e_2 = self.store_event( data={"release": release_1.version, "timestamp": self.one_min_ago.isoformat()}, project_id=self.project.id, ).event_id release_2_e_1 = self.store_event( data={"release": release_2.version, "timestamp": self.one_min_ago.isoformat()}, project_id=self.project.id, ).event_id result = errors.query( selected_columns=["id"], referrer="errors", query=f"{SEMVER_PACKAGE_ALIAS}:test", snuba_params=self.snuba_params, ) assert {r["id"] for r in result["data"]} == { release_1_e_1, release_1_e_2, } result = errors.query( selected_columns=["id"], query=f"{SEMVER_PACKAGE_ALIAS}:test2", referrer="errors", snuba_params=self.snuba_params, ) assert {r["id"] for r in result["data"]} == { release_2_e_1, } def test_semver_build_condition(self) -> None: release_1 = self.create_release(version="test@1.2.3+123") release_2 = self.create_release(version="test2@1.2.4+124") release_1_e_1 = self.store_event( data={"release": release_1.version, "timestamp": self.one_min_ago.isoformat()}, project_id=self.project.id, ).event_id release_1_e_2 = self.store_event( data={"release": release_1.version, "timestamp": self.one_min_ago.isoformat()}, project_id=self.project.id, ).event_id release_2_e_1 = self.store_event( data={"release": release_2.version, "timestamp": self.one_min_ago.isoformat()}, project_id=self.project.id, ).event_id result = errors.query( selected_columns=["id"], query=f"{SEMVER_BUILD_ALIAS}:123", snuba_params=self.snuba_params, referrer="errors", ) assert {r["id"] for r in result["data"]} == { release_1_e_1, release_1_e_2, } result = errors.query( selected_columns=["id"], query=f"{SEMVER_BUILD_ALIAS}:124", snuba_params=self.snuba_params, referrer="errors", ) assert {r["id"] for r in result["data"]} == { release_2_e_1, } result = errors.query( selected_columns=["id"], query=f"{SEMVER_BUILD_ALIAS}:>=123", snuba_params=self.snuba_params, referrer="errors", ) assert {r["id"] for r in result["data"]} == {release_1_e_1, release_1_e_2, release_2_e_1} def test_latest_release_condition(self) -> None: result = errors.query( selected_columns=["id", "message"], query="release:latest", snuba_params=self.snuba_params, referrer="errors", ) assert len(result["data"]) == 1 data = result["data"] assert data[0]["id"] == self.event.event_id assert data[0]["message"] == self.event.message assert "event_id" not in data[0] def test_environment_condition(self) -> None: result = errors.query( selected_columns=["id", "message"], query=f"environment:{self.create_environment(self.project).name}", snuba_params=self.snuba_params, referrer="errors", ) assert len(result["data"]) == 0 result = errors.query( selected_columns=["id", "message"], query=f"environment:{self.environment.name}", snuba_params=self.snuba_params, referrer="errors", ) assert len(result["data"]) == 1 data = result["data"] assert data[0]["id"] == self.event.event_id assert data[0]["message"] == self.event.message def test_conditional_filter(self) -> None: project2 = self.create_project(organization=self.organization) project3 = self.create_project(organization=self.organization) self.store_event( data={"message": "aaaaa", "timestamp": self.one_min_ago.isoformat()}, project_id=project2.id, ) self.store_event( data={"message": "bbbbb", "timestamp": self.one_min_ago.isoformat()}, project_id=project3.id, ) result = errors.query( selected_columns=["project", "message"], query=f"project:{self.project.slug} OR project:{project2.slug}", snuba_params=SnubaParams( projects=[self.project, project2], start=self.two_min_ago, end=self.now, ), orderby=["message"], referrer="errors", ) data = result["data"] assert len(data) == 2 assert data[0]["project"] == project2.slug assert data[1]["project"] == self.project.slug def test_nested_conditional_filter(self) -> None: project2 = self.create_project(organization=self.organization) self.store_event( data={"release": "a" * 32, "timestamp": self.one_min_ago.isoformat()}, project_id=self.project.id, ) self.event = self.store_event( data={"release": "b" * 32, "timestamp": self.one_min_ago.isoformat()}, project_id=self.project.id, ) self.event = self.store_event( data={"release": "c" * 32, "timestamp": self.one_min_ago.isoformat()}, project_id=self.project.id, ) self.event = self.store_event( data={"release": "a" * 32, "timestamp": self.one_min_ago.isoformat()}, project_id=project2.id, ) result = errors.query( selected_columns=["release"], query="(release:{} OR release:{}) AND project:{}".format( "a" * 32, "b" * 32, self.project.slug ), snuba_params=SnubaParams( projects=[self.project, project2], start=self.two_min_ago, end=self.now, ), orderby=["release"], referrer="discover", ) data = result["data"] assert len(data) == 2 assert data[0]["release"] == "a" * 32 assert data[1]["release"] == "b" * 32 def test_conditions_with_special_columns(self) -> None: for val in ["a", "b", "c"]: data = load_data("javascript") data["timestamp"] = self.one_min_ago.isoformat() data["transaction"] = val * 32 data["logentry"] = {"formatted": val * 32} data["tags"] = {"sub_customer.is-Enterprise-42": val * 32} self.store_event(data=data, project_id=self.project.id) result = errors.query( selected_columns=["transaction", "message"], query="event.type:error (transaction:{}* OR message:{}*)".format("a" * 32, "b" * 32), snuba_params=SnubaParams( projects=[self.project], start=self.two_min_ago, end=self.now, ), orderby=["transaction"], referrer="discover", ) data = result["data"] assert len(data) == 2 assert data[0]["transaction"] == "a" * 32 assert data[1]["transaction"] == "b" * 32 result = errors.query( selected_columns=["transaction", "sub_customer.is-Enterprise-42"], query="event.type:error (transaction:{} AND sub_customer.is-Enterprise-42:{})".format( "a" * 32, "a" * 32 ), snuba_params=SnubaParams( projects=[self.project], start=self.two_min_ago, end=self.now, ), orderby=["transaction"], referrer="discover", ) data = result["data"] assert len(data) == 1 assert data[0]["transaction"] == "a" * 32 assert data[0]["sub_customer.is-Enterprise-42"] == "a" * 32 def test_conditions_with_nested_aggregates(self) -> None: events = [("a", 2), ("b", 3), ("c", 4)] for ev in events: val = ev[0] * 32 for i in range(ev[1]): data = load_data("javascript") data["timestamp"] = self.one_min_ago.isoformat() data["transaction"] = f"{val}-{i}" data["logentry"] = {"formatted": val} data["tags"] = {"trek": val} self.store_event(data=data, project_id=self.project.id) result = errors.query( selected_columns=["trek", "count()"], query="(event.type:error AND (trek:{} AND (transaction:*{}* AND count():>2)))".format( "b" * 32, "b" * 32 ), snuba_params=SnubaParams( projects=[self.project], start=self.two_min_ago, end=self.now, ), orderby=["trek"], use_aggregate_conditions=True, referrer="discover", ) data = result["data"] assert len(data) == 1 assert data[0]["trek"] == "b" * 32 assert data[0]["count"] == 3 with pytest.raises(InvalidSearchQuery) as err: errors.query( selected_columns=["trek", "transaction"], query="(event.type:error AND (trek:{} AND (transaction:*{}* AND count():>2)))".format( "b" * 32, "b" * 32 ), referrer="discover", snuba_params=SnubaParams( projects=[self.project], start=self.two_min_ago, end=self.now, ), orderby=["trek"], use_aggregate_conditions=True, ) assert "used in a condition but is not a selected column" in str(err) def test_conditions_with_timestamps(self) -> None: events = [("a", 1), ("b", 2), ("c", 3)] for t, ev in enumerate(events): val = ev[0] * 32 for i in range(ev[1]): data = load_data("javascript", timestamp=self.now - timedelta(seconds=3 * t + 1)) data["transaction"] = f"{val}" self.store_event(data=data, project_id=self.project.id) results = errors.query( selected_columns=["transaction", "count()"], query="event.type:error AND (timestamp:<{} OR timestamp:>{})".format( (self.now - timedelta(seconds=5)).isoformat(), (self.now - timedelta(seconds=3)).isoformat(), ), snuba_params=SnubaParams( projects=[self.project], start=self.two_min_ago, end=self.now, ), orderby=["transaction"], use_aggregate_conditions=True, referrer="discover", ) data = results["data"] assert len(data) == 2 assert data[0]["transaction"] == "a" * 32 assert data[0]["count"] == 1 assert data[1]["transaction"] == "c" * 32 assert data[1]["count"] == 3 def test_timestamp_rollup_filter(self) -> None: event_hour = self.event_time.replace(minute=0, second=0) result = errors.query( selected_columns=["project.id", "user", "release"], query="timestamp.to_hour:" + event_hour.isoformat(), snuba_params=self.snuba_params, referrer="discover", ) data = result["data"] assert len(data) == 1 assert data[0]["project.id"] == self.project.id assert data[0]["user"] == "id:99" assert data[0]["release"] == "first-release" assert len(result["meta"]["fields"]) == 3 assert result["meta"]["fields"] == { "project.id": "integer", "user": "string", "release": "string", } def test_count_with_or(self) -> None: data = load_data("javascript", timestamp=before_now(seconds=3)) data["transaction"] = "a" * 32 self.store_event(data=data, project_id=self.project.id) results = errors.query( selected_columns=["transaction", "count()"], query="event.type:error AND (count():<1 OR count():>0)", snuba_params=self.snuba_params, orderby=["transaction"], use_aggregate_conditions=True, referrer="discover", ) data = results["data"] assert len(data) == 1 assert data[0]["transaction"] == "a" * 32 assert data[0]["count"] == 1 def test_access_to_private_functions(self) -> None: # using private functions directly without access should error with pytest.raises(InvalidSearchQuery, match="array_join: no access to private function"): errors.query( selected_columns=["array_join(tags.key)"], query="", snuba_params=SnubaParams( projects=[self.project], start=self.two_min_ago, end=self.now, ), referrer="discover", ) # using private functions in an aggregation without access should error with pytest.raises(InvalidSearchQuery, match="histogram: no access to private function"): for array_column in ARRAY_COLUMNS: errors.query( selected_columns=[f"histogram({array_column}_value, 1,0,1)"], query=f"histogram({array_column}_value, 1,0,1):>0", snuba_params=SnubaParams( projects=[self.project], start=self.two_min_ago, end=self.now, ), use_aggregate_conditions=True, referrer="discover", ) # using private functions in an aggregation without access should error # with auto aggregation on with pytest.raises(InvalidSearchQuery, match="histogram: no access to private function"): for array_column in ARRAY_COLUMNS: errors.query( selected_columns=["count()"], query=f"histogram({array_column}_value, 1,0,1):>0", snuba_params=SnubaParams( projects=[self.project], start=self.two_min_ago, end=self.now, ), referrer="discover", auto_aggregations=True, use_aggregate_conditions=True, ) def test_any_function(self) -> None: data = load_data("javascript", timestamp=before_now(seconds=3)) data["transaction"] = "a" * 32 self.store_event(data=data, project_id=self.project.id) results = errors.query( selected_columns=["count()", "any(transaction)", "any(user.id)"], query="transaction:{}".format("a" * 32), snuba_params=SnubaParams( projects=[self.project], start=before_now(minutes=5), end=before_now(seconds=1), ), referrer="discover", use_aggregate_conditions=True, ) data = results["data"] assert len(data) == 1 assert data[0]["any_transaction"] == "a" * 32 assert data[0]["any_user_id"] == "1" assert data[0]["count"] == 1 def test_offsets(self) -> None: self.store_event( data={"message": "hello1", "timestamp": self.one_min_ago.isoformat()}, project_id=self.project.id, ) self.store_event( data={"message": "hello2", "timestamp": self.one_min_ago.isoformat()}, project_id=self.project.id, ) result = errors.query( selected_columns=["message"], query="", snuba_params=self.snuba_params, orderby=["message"], limit=1, offset=1, referrer="discover", ) data = result["data"] assert len(data) == 1 # because we're ording by `message`, and offset by 1, the message should be `hello2` assert data[0]["message"] == "hello2"
ErrorsQueryIntegrationTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1404370, "end": 1404758 }
class ____(sgqlc.types.Type, Node, AuditEntry, OrganizationAuditEntryData, RepositoryAuditEntryData): """Audit log entry for a repo.add_member event.""" __schema__ = github_schema __field_names__ = ("visibility",) visibility = sgqlc.types.Field(RepoAddMemberAuditEntryVisibility, graphql_name="visibility") """The visibility of the repository"""
RepoAddMemberAuditEntry
python
huggingface__transformers
src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py
{ "start": 20098, "end": 22284 }
class ____(Qwen3MoeConfig): def __init__( self, vocab_size: Optional[int] = 3072, hidden_size: Optional[int] = 1024, intermediate_size: Optional[int] = 2048, num_hidden_layers: Optional[int] = 20, num_attention_heads: Optional[int] = 16, num_key_value_heads: Optional[int] = 2, hidden_act: Optional[str] = "silu", max_position_embeddings: Optional[int] = 32768, initializer_range: Optional[float] = 0.02, rms_norm_eps: Optional[float] = 0.000001, use_cache: Optional[int] = True, tie_word_embeddings: Optional[bool] = False, rope_parameters: Optional[RopeParameters | dict[str, RopeParameters]] = None, attention_bias: Optional[bool] = False, sliding_window: Optional[int] = None, attention_dropout: Optional[int] = 0, decoder_sparse_step: Optional[int] = 1, moe_intermediate_size: Optional[int] = 384, num_experts_per_tok: Optional[int] = 8, num_experts: Optional[int] = 128, norm_topk_prob: Optional[bool] = False, output_router_logits: Optional[bool] = False, router_aux_loss_coef: Optional[float] = 0.001, mlp_only_layers: Optional[list[int]] = None, **kwargs, ): super().__init__( vocab_size, hidden_size, intermediate_size, num_hidden_layers, num_attention_heads, num_key_value_heads, hidden_act, max_position_embeddings, initializer_range, rms_norm_eps, use_cache, tie_word_embeddings, rope_parameters, attention_bias, False, sliding_window, attention_dropout, decoder_sparse_step, moe_intermediate_size, num_experts_per_tok, num_experts, norm_topk_prob, output_router_logits, router_aux_loss_coef, mlp_only_layers, **kwargs, ) del self.use_sliding_window self.sliding_window = sliding_window
Qwen3OmniMoeTalkerTextConfig
python
astropy__astropy
astropy/modeling/polynomial.py
{ "start": 24287, "end": 27574 }
class ____(_PolyDomainWindow1D): r""" Univariate Legendre series. It is defined as: .. math:: P(x) = \sum_{i=0}^{i=n}C_{i} * L_{i}(x) where ``L_i(x)`` is the corresponding Legendre polynomial. For explanation of ``domain``, and ``window`` see :ref:`Notes regarding usage of domain and window <domain-window-note>`. Parameters ---------- degree : int degree of the series domain : tuple or None, optional window : tuple or None, optional If None, it is set to (-1, 1) Fitters will remap the domain to this window **params : dict keyword: value pairs, representing parameter_name: value Notes ----- This model does not support the use of units/quantities, because each term in the sum of Legendre polynomials is a polynomial in x - since the coefficients within each Legendre polynomial are fixed, we can't use quantities for x since the units would not be compatible. For example, the third Legendre polynomial (P2) is 1.5x^2-0.5, but if x was specified with units, 1.5x^2 and -0.5 would have incompatible units. """ n_inputs = 1 n_outputs = 1 _separable = True def __init__( self, degree, domain=None, window=None, n_models=None, model_set_axis=None, name=None, meta=None, **params, ): super().__init__( degree, domain, window, n_models=n_models, model_set_axis=model_set_axis, name=name, meta=meta, **params, ) def prepare_inputs(self, x, **kwargs): inputs, broadcasted_shapes = super().prepare_inputs(x, **kwargs) x = inputs[0] return (x,), broadcasted_shapes def evaluate(self, x, *coeffs): if self.domain is not None: x = poly_map_domain(x, self.domain, self.window) return self.clenshaw(x, coeffs) def fit_deriv(self, x, *params): """ Computes the Vandermonde matrix. Parameters ---------- x : ndarray input *params throw-away parameter list returned by non-linear fitters Returns ------- result : ndarray The Vandermonde matrix """ x = np.array(x, dtype=float, copy=COPY_IF_NEEDED, ndmin=1) v = np.empty((self.degree + 1,) + x.shape, dtype=x.dtype) v[0] = 1 if self.degree > 0: v[1] = x for i in range(2, self.degree + 1): v[i] = (v[i - 1] * x * (2 * i - 1) - v[i - 2] * (i - 1)) / i return np.rollaxis(v, 0, v.ndim) @staticmethod def clenshaw(x, coeffs): if len(coeffs) == 1: c0 = coeffs[0] c1 = 0 elif len(coeffs) == 2: c0 = coeffs[0] c1 = coeffs[1] else: nd = len(coeffs) c0 = coeffs[-2] c1 = coeffs[-1] for i in range(3, len(coeffs) + 1): tmp = c0 nd = nd - 1 c0 = coeffs[-i] - (c1 * (nd - 1)) / nd c1 = tmp + (c1 * x * (2 * nd - 1)) / nd return c0 + c1 * x
Legendre1D
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_expectations.py
{ "start": 2232, "end": 6149 }
class ____(ExecutingGraphQLContextTestMatrix): def test_basic_expectations_within_compute_step_events( self, graphql_context: WorkspaceRequestContext, snapshot ): selector = infer_job_selector(graphql_context, "job_with_expectations") logs = sync_execute_get_events( context=graphql_context, variables={"executionParams": {"selector": selector}}, ) emit_failed_expectation_event = get_expectation_result(logs, "emit_failed_expectation") assert emit_failed_expectation_event["expectationResult"]["success"] is False assert emit_failed_expectation_event["expectationResult"]["description"] == "Failure" failed_result_metadata = json.loads( emit_failed_expectation_event["expectationResult"]["metadataEntries"][0]["jsonString"] ) assert emit_failed_expectation_event["expectationResult"]["label"] == "always_false" assert failed_result_metadata == {"reason": "Relentless pessimism."} emit_successful_expectation_event = get_expectation_result( logs, "emit_successful_expectation" ) assert emit_successful_expectation_event["expectationResult"]["success"] is True assert emit_successful_expectation_event["expectationResult"]["description"] == "Successful" assert emit_successful_expectation_event["expectationResult"]["label"] == "always_true" successful_result_metadata = json.loads( emit_successful_expectation_event["expectationResult"]["metadataEntries"][0][ "jsonString" ] ) assert successful_result_metadata == {"reason": "Just because."} emit_no_metadata = get_expectation_result(logs, "emit_successful_expectation_no_metadata") assert not emit_no_metadata["expectationResult"]["metadataEntries"] snapshot.assert_match(get_expectation_results(logs, "emit_failed_expectation")) snapshot.assert_match(get_expectation_results(logs, "emit_successful_expectation")) snapshot.assert_match( get_expectation_results(logs, "emit_successful_expectation_no_metadata") ) def test_get_expectation_results_from_step_stats( self, graphql_context: WorkspaceRequestContext ): run_id = _create_run(graphql_context, "job_with_expectations") result = execute_dagster_graphql( graphql_context, GET_EXPECTATIONS_FROM_STEP_STATS, {"runId": run_id} ) assert result.data assert any( len(step["expectationResults"]) > 0 and step["expectationResults"][0] == { "success": False, "label": "always_false", "description": "Failure", "metadataEntries": [ {"jsonString": json.dumps({"reason": "Relentless pessimism."})} ], } for step in result.data["runOrError"]["stepStats"] ) def test_basic_input_output_expectations( self, graphql_context: WorkspaceRequestContext, snapshot ): selector = infer_job_selector(graphql_context, "csv_hello_world_with_expectations") logs = sync_execute_get_events( context=graphql_context, variables={ "executionParams": { "selector": selector, "runConfigData": { "ops": { "sum_op": { "inputs": {"num": file_relative_path(__file__, "../data/num.csv")} } } }, } }, ) expectation_results = get_expectation_results(logs, "df_expectations_op") assert len(expectation_results) == 2 snapshot.assert_match(expectation_results)
TestExpectations
python
pydantic__pydantic
pydantic/v1/types.py
{ "start": 9187, "end": 10640 }
class ____(bytes): strip_whitespace = False to_upper = False to_lower = False min_length: OptionalInt = None max_length: OptionalInt = None strict: bool = False @classmethod def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: update_not_none(field_schema, minLength=cls.min_length, maxLength=cls.max_length) @classmethod def __get_validators__(cls) -> 'CallableGenerator': yield strict_bytes_validator if cls.strict else bytes_validator yield constr_strip_whitespace yield constr_upper yield constr_lower yield constr_length_validator def conbytes( *, strip_whitespace: bool = False, to_upper: bool = False, to_lower: bool = False, min_length: Optional[int] = None, max_length: Optional[int] = None, strict: bool = False, ) -> Type[bytes]: # use kwargs then define conf in a dict to aid with IDE type hinting namespace = dict( strip_whitespace=strip_whitespace, to_upper=to_upper, to_lower=to_lower, min_length=min_length, max_length=max_length, strict=strict, ) return _registered(type('ConstrainedBytesValue', (ConstrainedBytes,), namespace)) if TYPE_CHECKING: StrictBytes = bytes else: class StrictBytes(ConstrainedBytes): strict = True # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ STRING TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ConstrainedBytes
python
vyperlang__vyper
vyper/warnings.py
{ "start": 114, "end": 1368 }
class ____(_BaseVyperException, Warning): pass # print a warning def vyper_warn(warning: VyperWarning | str, node=None): if isinstance(warning, str): warning = VyperWarning(warning, node) warnings.warn(warning, stacklevel=2) @contextlib.contextmanager def warnings_filter(warnings_control: Optional[str]): # note: using warnings.catch_warnings() since it saves and restores # the warnings filter with warnings.catch_warnings(): set_warnings_filter(warnings_control) yield def set_warnings_filter(warnings_control: Optional[str]): if warnings_control == "error": warnings_filter = "error" elif warnings_control == "none": warnings_filter = "ignore" else: assert warnings_control is None # sanity warnings_filter = "default" if warnings_control is not None: # warnings.simplefilter only adds to the warnings filters, # so we should clear warnings filter between calls to simplefilter() warnings.resetwarnings() # NOTE: in the future we can do more fine-grained control by setting # category to specific warning types warnings.simplefilter(warnings_filter, category=VyperWarning) # type: ignore[arg-type]
VyperWarning
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/asset_defs.py
{ "start": 30198, "end": 35228 }
class ____(AirbyteCoreCacheableAssetsDefinition): def __init__( self, airbyte_resource_def: Union[ResourceDefinition, AirbyteResource], workspace_id: Optional[str], key_prefix: Sequence[str], create_assets_for_normalization_tables: bool, connection_meta_to_group_fn: Optional[Callable[[AirbyteConnectionMetadata], Optional[str]]], connection_to_io_manager_key_fn: Optional[Callable[[str], Optional[str]]], connection_filter: Optional[Callable[[AirbyteConnectionMetadata], bool]], connection_to_asset_key_fn: Optional[Callable[[AirbyteConnectionMetadata, str], AssetKey]], connection_to_freshness_policy_fn: Optional[ Callable[[AirbyteConnectionMetadata], Optional[LegacyFreshnessPolicy]] ], connection_to_auto_materialize_policy_fn: Optional[ Callable[[AirbyteConnectionMetadata], Optional[AutoMaterializePolicy]] ] = None, ): super().__init__( key_prefix=key_prefix, create_assets_for_normalization_tables=create_assets_for_normalization_tables, connection_meta_to_group_fn=connection_meta_to_group_fn, connection_to_io_manager_key_fn=connection_to_io_manager_key_fn, connection_filter=connection_filter, connection_to_asset_key_fn=connection_to_asset_key_fn, connection_to_freshness_policy_fn=connection_to_freshness_policy_fn, connection_to_auto_materialize_policy_fn=connection_to_auto_materialize_policy_fn, ) self._workspace_id = workspace_id if isinstance(airbyte_resource_def, AirbyteResource): # We hold a copy which is not fully processed, this retains e.g. EnvVars for # display in the UI self._partially_initialized_airbyte_instance = airbyte_resource_def # The processed copy is used to query the Airbyte instance self._airbyte_instance: AirbyteResource = ( self._partially_initialized_airbyte_instance.process_config_and_initialize() ) else: self._partially_initialized_airbyte_instance = airbyte_resource_def( build_init_resource_context() ) self._airbyte_instance: AirbyteResource = self._partially_initialized_airbyte_instance def _get_connections(self) -> Sequence[tuple[str, AirbyteConnectionMetadata]]: workspace_id = self._workspace_id if not workspace_id: workspaces = cast( "list[dict[str, Any]]", check.not_none( self._airbyte_instance.make_request(endpoint="/workspaces/list", data={}) ).get("workspaces", []), ) check.invariant(len(workspaces) <= 1, "Airbyte instance has more than one workspace") check.invariant(len(workspaces) > 0, "Airbyte instance has no workspaces") workspace_id = workspaces[0].get("workspaceId") connections = cast( "list[dict[str, Any]]", check.not_none( self._airbyte_instance.make_request( endpoint="/connections/list", data={"workspaceId": workspace_id} ) ).get("connections", []), ) output_connections: list[tuple[str, AirbyteConnectionMetadata]] = [] for connection_json in connections: connection_id = cast("str", connection_json.get("connectionId")) operations_json = cast( "dict[str, Any]", check.not_none( self._airbyte_instance.make_request( endpoint="/operations/list", data={"connectionId": connection_id}, ) ), ) destination_id = cast("str", connection_json.get("destinationId")) destination_json = cast( "dict[str, Any]", check.not_none( self._airbyte_instance.make_request( endpoint="/destinations/get", data={"destinationId": destination_id}, ) ), ) connection = AirbyteConnectionMetadata.from_api_json( connection_json, operations_json, destination_json ) # Filter out connections that don't match the filter function if self._connection_filter and not self._connection_filter(connection): continue output_connections.append((connection_id, connection)) return output_connections def build_definitions( self, data: Sequence[AssetsDefinitionCacheableData] ) -> Sequence[AssetsDefinition]: return super()._build_definitions_with_resources( data, {"airbyte": self._partially_initialized_airbyte_instance.get_resource_definition()}, )
AirbyteInstanceCacheableAssetsDefinition
python
getsentry__sentry
src/sentry/workflow_engine/handlers/condition/issue_category_handler.py
{ "start": 358, "end": 1332 }
class ____(DataConditionHandler[WorkflowEventData]): group = DataConditionHandler.Group.ACTION_FILTER subgroup = DataConditionHandler.Subgroup.ISSUE_ATTRIBUTES comparison_json_schema = { "type": "object", "properties": { "value": {"type": "integer", "enum": [*GroupCategory]}, }, "required": ["value"], "additionalProperties": False, } @staticmethod def evaluate_value(event_data: WorkflowEventData, comparison: Any) -> bool: group = event_data.group try: value: GroupCategory = GroupCategory(int(comparison["value"])) except (TypeError, ValueError, KeyError): return False try: issue_category = group.issue_category issue_category_v2 = group.issue_category_v2 except ValueError: return False return bool(value == issue_category or value == issue_category_v2)
IssueCategoryConditionHandler
python
ray-project__ray
python/ray/cloudpickle/cloudpickle.py
{ "start": 39896, "end": 55282 }
class ____(pickle.Pickler): # set of reducers defined and used by cloudpickle (private) _dispatch_table = {} _dispatch_table[classmethod] = _classmethod_reduce _dispatch_table[io.TextIOWrapper] = _file_reduce _dispatch_table[logging.Logger] = _logger_reduce _dispatch_table[logging.RootLogger] = _root_logger_reduce _dispatch_table[memoryview] = _memoryview_reduce _dispatch_table[property] = _property_reduce _dispatch_table[staticmethod] = _classmethod_reduce _dispatch_table[CellType] = _cell_reduce _dispatch_table[types.CodeType] = _code_reduce _dispatch_table[types.GetSetDescriptorType] = _getset_descriptor_reduce _dispatch_table[types.ModuleType] = _module_reduce _dispatch_table[types.MethodType] = _method_reduce _dispatch_table[types.MappingProxyType] = _mappingproxy_reduce _dispatch_table[weakref.WeakSet] = _weakset_reduce _dispatch_table[typing.TypeVar] = _typevar_reduce _dispatch_table[_collections_abc.dict_keys] = _dict_keys_reduce _dispatch_table[_collections_abc.dict_values] = _dict_values_reduce _dispatch_table[_collections_abc.dict_items] = _dict_items_reduce _dispatch_table[type(OrderedDict().keys())] = _odict_keys_reduce _dispatch_table[type(OrderedDict().values())] = _odict_values_reduce _dispatch_table[type(OrderedDict().items())] = _odict_items_reduce _dispatch_table[abc.abstractmethod] = _classmethod_reduce _dispatch_table[abc.abstractclassmethod] = _classmethod_reduce _dispatch_table[abc.abstractstaticmethod] = _classmethod_reduce _dispatch_table[abc.abstractproperty] = _property_reduce _dispatch_table[dataclasses._FIELD_BASE] = _dataclass_field_base_reduce dispatch_table = ChainMap(_dispatch_table, copyreg.dispatch_table) # function reducers are defined as instance methods of cloudpickle.Pickler # objects, as they rely on a cloudpickle.Pickler attribute (globals_ref) def _dynamic_function_reduce(self, func): """Reduce a function that is not pickleable via attribute lookup.""" newargs = self._function_getnewargs(func) state = _function_getstate(func) return (_make_function, newargs, state, None, None, _function_setstate) def _function_reduce(self, obj): """Reducer for function objects. If obj is a top-level attribute of a file-backed module, this reducer returns NotImplemented, making the cloudpickle.Pickler fall back to traditional pickle.Pickler routines to save obj. Otherwise, it reduces obj using a custom cloudpickle reducer designed specifically to handle dynamic functions. """ if _should_pickle_by_reference(obj): return NotImplemented else: return self._dynamic_function_reduce(obj) def _function_getnewargs(self, func): code = func.__code__ # base_globals represents the future global namespace of func at # unpickling time. Looking it up and storing it in # cloudpickle.Pickler.globals_ref allow functions sharing the same # globals at pickling time to also share them once unpickled, at one # condition: since globals_ref is an attribute of a cloudpickle.Pickler # instance, and that a new cloudpickle.Pickler is created each time # cloudpickle.dump or cloudpickle.dumps is called, functions also need # to be saved within the same invocation of # cloudpickle.dump/cloudpickle.dumps (for example: # cloudpickle.dumps([f1, f2])). There is no such limitation when using # cloudpickle.Pickler.dump, as long as the multiple invocations are # bound to the same cloudpickle.Pickler instance. base_globals = self.globals_ref.setdefault(id(func.__globals__), {}) if base_globals == {}: # Add module attributes used to resolve relative imports # instructions inside func. for k in ["__package__", "__name__", "__path__", "__file__"]: if k in func.__globals__: base_globals[k] = func.__globals__[k] # Do not bind the free variables before the function is created to # avoid infinite recursion. if func.__closure__ is None: closure = None else: closure = tuple(_make_empty_cell() for _ in range(len(code.co_freevars))) return code, base_globals, None, None, closure def dump(self, obj): try: return super().dump(obj) except RuntimeError as e: if len(e.args) > 0 and "recursion" in e.args[0]: msg = "Could not pickle object as excessively deep recursion required." raise pickle.PicklingError(msg) from e else: raise def __init__(self, file, protocol=None, buffer_callback=None): if protocol is None: protocol = DEFAULT_PROTOCOL super().__init__(file, protocol=protocol, buffer_callback=buffer_callback) # map functions __globals__ attribute ids, to ensure that functions # sharing the same global namespace at pickling time also share # their global namespace at unpickling time. self.globals_ref = {} self.proto = int(protocol) if not PYPY: # pickle.Pickler is the C implementation of the CPython pickler and # therefore we rely on reduce_override method to customize the pickler # behavior. # `cloudpickle.Pickler.dispatch` is only left for backward # compatibility - note that when using protocol 5, # `cloudpickle.Pickler.dispatch` is not an extension of # `pickle._Pickler.dispatch` dictionary, because `cloudpickle.Pickler` # subclasses the C-implemented `pickle.Pickler`, which does not expose # a `dispatch` attribute. Earlier versions of `cloudpickle.Pickler` # used `cloudpickle.Pickler.dispatch` as a class-level attribute # storing all reducers implemented by cloudpickle, but the attribute # name was not a great choice given because it would collide with a # similarly named attribute in the pure-Python `pickle._Pickler` # implementation in the standard library. dispatch = dispatch_table # Implementation of the reducer_override callback, in order to # efficiently serialize dynamic functions and classes by subclassing # the C-implemented `pickle.Pickler`. # TODO: decorrelate reducer_override (which is tied to CPython's # implementation - would it make sense to backport it to pypy? - and # pickle's protocol 5 which is implementation agnostic. Currently, the # availability of both notions coincide on CPython's pickle, but it may # not be the case anymore when pypy implements protocol 5. def reducer_override(self, obj): """Type-agnostic reducing callback for function and classes. For performance reasons, subclasses of the C `pickle.Pickler` class cannot register custom reducers for functions and classes in the dispatch_table attribute. Reducers for such types must instead implemented via the special `reducer_override` method. Note that this method will be called for any object except a few builtin-types (int, lists, dicts etc.), which differs from reducers in the Pickler's dispatch_table, each of them being invoked for objects of a specific type only. This property comes in handy for classes: although most classes are instances of the ``type`` metaclass, some of them can be instances of other custom metaclasses (such as enum.EnumMeta for example). In particular, the metaclass will likely not be known in advance, and thus cannot be special-cased using an entry in the dispatch_table. reducer_override, among other things, allows us to register a reducer that will be called for any class, independently of its type. Notes: * reducer_override has the priority over dispatch_table-registered reducers. * reducer_override can be used to fix other limitations of cloudpickle for other types that suffered from type-specific reducers, such as Exceptions. See https://github.com/cloudpipe/cloudpickle/issues/248 """ t = type(obj) try: is_anyclass = issubclass(t, type) except TypeError: # t is not a class (old Boost; see SF #502085) is_anyclass = False if is_anyclass: return _class_reduce(obj) elif isinstance(obj, types.FunctionType): return self._function_reduce(obj) else: # fallback to save_global, including the Pickler's # dispatch_table return NotImplemented else: # When reducer_override is not available, hack the pure-Python # Pickler's types.FunctionType and type savers. Note: the type saver # must override Pickler.save_global, because pickle.py contains a # hard-coded call to save_global when pickling meta-classes. dispatch = pickle.Pickler.dispatch.copy() def _save_reduce_pickle5( self, func, args, state=None, listitems=None, dictitems=None, state_setter=None, obj=None, ): save = self.save write = self.write self.save_reduce( func, args, state=None, listitems=listitems, dictitems=dictitems, obj=obj, ) # backport of the Python 3.8 state_setter pickle operations save(state_setter) save(obj) # simple BINGET opcode as obj is already memoized. save(state) write(pickle.TUPLE2) # Trigger a state_setter(obj, state) function call. write(pickle.REDUCE) # The purpose of state_setter is to carry-out an # inplace modification of obj. We do not care about what the # method might return, so its output is eventually removed from # the stack. write(pickle.POP) def save_global(self, obj, name=None, pack=struct.pack): """Main dispatch method. The name of this method is somewhat misleading: all types get dispatched here. """ if obj is type(None): # noqa return self.save_reduce(type, (None,), obj=obj) elif obj is type(Ellipsis): return self.save_reduce(type, (Ellipsis,), obj=obj) elif obj is type(NotImplemented): return self.save_reduce(type, (NotImplemented,), obj=obj) elif obj in _BUILTIN_TYPE_NAMES: return self.save_reduce( _builtin_type, (_BUILTIN_TYPE_NAMES[obj],), obj=obj ) if name is not None: super().save_global(obj, name=name) elif not _should_pickle_by_reference(obj, name=name): self._save_reduce_pickle5(*_dynamic_class_reduce(obj), obj=obj) else: super().save_global(obj, name=name) dispatch[type] = save_global def save_function(self, obj, name=None): """Registered with the dispatch to handle all function types. Determines what kind of function obj is (e.g. lambda, defined at interactive prompt, etc) and handles the pickling appropriately. """ if _should_pickle_by_reference(obj, name=name): return super().save_global(obj, name=name) elif PYPY and isinstance(obj.__code__, builtin_code_type): return self.save_pypy_builtin_func(obj) else: return self._save_reduce_pickle5( *self._dynamic_function_reduce(obj), obj=obj ) def save_pypy_builtin_func(self, obj): """Save pypy equivalent of builtin functions. PyPy does not have the concept of builtin-functions. Instead, builtin-functions are simple function instances, but with a builtin-code attribute. Most of the time, builtin functions should be pickled by attribute. But PyPy has flaky support for __qualname__, so some builtin functions such as float.__new__ will be classified as dynamic. For this reason only, we created this special routine. Because builtin-functions are not expected to have closure or globals, there is no additional hack (compared the one already implemented in pickle) to protect ourselves from reference cycles. A simple (reconstructor, newargs, obj.__dict__) tuple is save_reduced. Note also that PyPy improved their support for __qualname__ in v3.6, so this routing should be removed when cloudpickle supports only PyPy 3.6 and later. """ rv = ( types.FunctionType, (obj.__code__, {}, obj.__name__, obj.__defaults__, obj.__closure__), obj.__dict__, ) self.save_reduce(*rv, obj=obj) dispatch[types.FunctionType] = save_function # Shorthands similar to pickle.dump/pickle.dumps def dump(obj, file, protocol=None, buffer_callback=None): """Serialize obj as bytes streamed into file protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to pickle.HIGHEST_PROTOCOL. This setting favors maximum communication speed between processes running the same Python version. Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure compatibility with older versions of Python (although this is not always guaranteed to work because cloudpickle relies on some internal implementation details that can change from one Python version to the next). """ Pickler(file, protocol=protocol, buffer_callback=buffer_callback).dump(obj) def dumps(obj, protocol=None, buffer_callback=None): """Serialize obj as a string of bytes allocated in memory protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to pickle.HIGHEST_PROTOCOL. This setting favors maximum communication speed between processes running the same Python version. Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure compatibility with older versions of Python (although this is not always guaranteed to work because cloudpickle relies on some internal implementation details that can change from one Python version to the next). """ with io.BytesIO() as file: cp = Pickler(file, protocol=protocol, buffer_callback=buffer_callback) cp.dump(obj) return file.getvalue() # Include pickles unloading functions in this namespace for convenience. load, loads = pickle.load, pickle.loads # Backward compat alias. CloudPickler = Pickler
Pickler
python
ray-project__ray
rllib/utils/tests/test_utils.py
{ "start": 694, "end": 17376 }
class ____(unittest.TestCase): # Nested struct of data with B=3. struct = { "a": np.array([1, 3, 2]), "b": ( np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]), np.array( [[[8.0], [7.0], [6.0]], [[5.0], [4.0], [3.0]], [[2.0], [1.0], [0.0]]] ), ), "c": { "ca": np.array([[1, 2], [3, 5], [0, 1]]), "cb": np.array([1.0, 2.0, 3.0]), }, } # Nested struct of data with B=2 and T=1. struct_w_time_axis = { "a": np.array([[1], [3]]), "b": ( np.array([[[1.0, 2.0, 3.0]], [[4.0, 5.0, 6.0]]]), np.array([[[[8.0], [7.0], [6.0]]], [[[5.0], [4.0], [3.0]]]]), ), "c": {"ca": np.array([[[1, 2]], [[3, 5]]]), "cb": np.array([[1.0], [2.0]])}, } # Corresponding space struct. spaces = { "a": gym.spaces.Discrete(4), "b": (gym.spaces.Box(-1.0, 10.0, (3,)), gym.spaces.Box(-1.0, 1.0, (3, 1))), "c": { "ca": gym.spaces.MultiDiscrete([4, 6]), "cb": gym.spaces.Box(-1.0, 1.0, ()), }, } @classmethod def setUpClass(cls) -> None: tf1.enable_eager_execution() ray.init() @classmethod def tearDownClass(cls) -> None: ray.shutdown() def test_make_action_immutable(self): from types import MappingProxyType # Test Box space. space = gym.spaces.Box(low=-1.0, high=1.0, shape=(8,), dtype=np.float32) action = space.sample() action = make_action_immutable(action) self.assertFalse(action.flags["WRITEABLE"]) # Test Discrete space. # Nothing to be tested as sampled actions are integers # and integers are immutable by nature. # Test MultiDiscrete space. space = gym.spaces.MultiDiscrete([3, 3, 3]) action = space.sample() action = make_action_immutable(action) self.assertFalse(action.flags["WRITEABLE"]) # Test MultiBinary space. space = gym.spaces.MultiBinary([2, 2, 2]) action = space.sample() action = make_action_immutable(action) self.assertFalse(action.flags["WRITEABLE"]) # Test Tuple space. space = gym.spaces.Tuple( ( gym.spaces.Discrete(2), gym.spaces.Box(low=-1.0, high=1.0, shape=(8,), dtype=np.float32), ) ) action = space.sample() action = tree.traverse(make_action_immutable, action, top_down=False) self.assertFalse(action[1].flags["WRITEABLE"]) # Test Dict space. space = gym.spaces.Dict( { "a": gym.spaces.Discrete(2), "b": gym.spaces.Box(low=-1.0, high=1.0, shape=(8,), dtype=np.float32), "c": gym.spaces.Tuple( ( gym.spaces.Discrete(2), gym.spaces.Box( low=-1.0, high=1.0, shape=(8,), dtype=np.float32 ), ) ), } ) action = space.sample() action = tree.traverse(make_action_immutable, action, top_down=False) def fail_fun(obj): obj["a"] = 5 self.assertRaises(TypeError, fail_fun, action) self.assertFalse(action["b"].flags["WRITEABLE"]) self.assertFalse(action["c"][1].flags["WRITEABLE"]) self.assertTrue(isinstance(action, MappingProxyType)) def test_flatten_inputs_to_1d_tensor(self): # B=3; no time axis. check( flatten_np(self.struct, spaces_struct=self.spaces), np.array( [ [ 0.0, 1.0, 0.0, 0.0, 1.0, 2.0, 3.0, 8.0, 7.0, 6.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, ], [ 0.0, 0.0, 0.0, 1.0, 4.0, 5.0, 6.0, 5.0, 4.0, 3.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 2.0, ], [ 0.0, 0.0, 1.0, 0.0, 7.0, 8.0, 9.0, 2.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 3.0, ], ] ), ) struct_tf = tree.map_structure(lambda s: tf.convert_to_tensor(s), self.struct) check( flatten_tf(struct_tf, spaces_struct=self.spaces), np.array( [ [ 0.0, 1.0, 0.0, 0.0, 1.0, 2.0, 3.0, 8.0, 7.0, 6.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, ], [ 0.0, 0.0, 0.0, 1.0, 4.0, 5.0, 6.0, 5.0, 4.0, 3.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 2.0, ], [ 0.0, 0.0, 1.0, 0.0, 7.0, 8.0, 9.0, 2.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 3.0, ], ] ), ) struct_torch = tree.map_structure(lambda s: torch.from_numpy(s), self.struct) check( flatten_torch(struct_torch, spaces_struct=self.spaces), np.array( [ [ 0.0, 1.0, 0.0, 0.0, 1.0, 2.0, 3.0, 8.0, 7.0, 6.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, ], [ 0.0, 0.0, 0.0, 1.0, 4.0, 5.0, 6.0, 5.0, 4.0, 3.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 2.0, ], [ 0.0, 0.0, 1.0, 0.0, 7.0, 8.0, 9.0, 2.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 3.0, ], ] ), ) def test_flatten_inputs_to_1d_tensor_w_time_axis(self): # B=2; T=1 check( flatten_np( self.struct_w_time_axis, spaces_struct=self.spaces, time_axis=True ), np.array( [ [ [ 0.0, 1.0, 0.0, 0.0, 1.0, 2.0, 3.0, 8.0, 7.0, 6.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, ] ], [ [ 0.0, 0.0, 0.0, 1.0, 4.0, 5.0, 6.0, 5.0, 4.0, 3.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 2.0, ] ], ] ), ) struct_tf = tree.map_structure( lambda s: tf.convert_to_tensor(s), self.struct_w_time_axis ) check( flatten_tf(struct_tf, spaces_struct=self.spaces, time_axis=True), np.array( [ [ [ 0.0, 1.0, 0.0, 0.0, 1.0, 2.0, 3.0, 8.0, 7.0, 6.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, ] ], [ [ 0.0, 0.0, 0.0, 1.0, 4.0, 5.0, 6.0, 5.0, 4.0, 3.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 2.0, ] ], ] ), ) struct_torch = tree.map_structure( lambda s: torch.from_numpy(s), self.struct_w_time_axis ) check( flatten_torch(struct_torch, spaces_struct=self.spaces, time_axis=True), np.array( [ [ [ 0.0, 1.0, 0.0, 0.0, 1.0, 2.0, 3.0, 8.0, 7.0, 6.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, ] ], [ [ 0.0, 0.0, 0.0, 1.0, 4.0, 5.0, 6.0, 5.0, 4.0, 3.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 2.0, ] ], ] ), ) def test_one_hot(self): space = gym.spaces.MultiDiscrete([[3, 3], [3, 3]]) # TF x = tf.Variable([[0, 2, 1, 0]], dtype=tf.int32) y = one_hot_tf(x, space) self.assertTrue(([1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0] == y.numpy()).all()) # Torch x = torch.tensor([[0, 2, 1, 0]], dtype=torch.int32) y = one_hot_torch(x, space) self.assertTrue(([1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0] == y.numpy()).all()) def test_l2_loss(self): for _ in range(10): tensor = np.random.random(8) tf_loss = tf_l2_loss(tf.constant(tensor)) torch_loss = torch_l2_loss(torch.Tensor(tensor)) self.assertAlmostEqual(tf_loss.numpy(), torch_loss.numpy(), places=3) if __name__ == "__main__": import sys import pytest sys.exit(pytest.main(["-v", __file__]))
TestUtils
python
joke2k__faker
faker/providers/currency/pl_PL/__init__.py
{ "start": 46, "end": 280 }
class ____(CurrencyProvider): price_formats = ["#,##", "%#,##", "%##,##", "%.###,##", "%#.###,##"] def pricetag(self) -> str: return self.numerify(self.random_element(self.price_formats)) + "\N{NO-BREAK SPACE}zł"
Provider
python
doocs__leetcode
solution/1600-1699/1628.Design an Expression Tree With Evaluate Function/Solution.py
{ "start": 298, "end": 972 }
class ____(Node): def __init__(self, val): self.val = val self.left = None self.right = None def evaluate(self) -> int: x = self.val if x.isdigit(): return int(x) left, right = self.left.evaluate(), self.right.evaluate() if x == '+': return left + right if x == '-': return left - right if x == '*': return left * right if x == '/': return left // right """ This is the TreeBuilder class. You can treat it as the driver code that takes the postinfix input and returns the expression tree represnting it as a Node. """
MyNode
python
pytorch__pytorch
torch/testing/_internal/common_optimizers.py
{ "start": 1766, "end": 2403 }
class ____: """ An OptimizerInput that will cause the optimizer to throw an error when constructed. Includes the type and string of the resulting error. """ __slots__ = ["optimizer_error_input", "error_on", "error_type", "error_regex"] def __init__( self, optimizer_error_input, *, error_on=OptimizerErrorEnum.CONSTRUCTION_ERROR, error_type=RuntimeError, error_regex="", ): self.optimizer_error_input = optimizer_error_input self.error_on = error_on self.error_type = error_type self.error_regex = error_regex
ErrorOptimizerInput
python
ray-project__ray
python/ray/data/_internal/planner/plan_expression/expression_evaluator.py
{ "start": 20147, "end": 27519 }
class ____(_ExprVisitor[Union[BlockColumn, ScalarType]]): """Visitor-based expression evaluator that uses Block and BlockColumns This evaluator implements the visitor pattern to traverse expression trees and evaluate them against Block data structures. It maintains operation mappings in shared state and returns consistent BlockColumn types. """ def __init__(self, block: Block): """Initialize the evaluator with a block and operation mappings. Args: block: The Block to evaluate expressions against. """ self.block = block self.block_accessor = BlockAccessor.for_block(block) # Use BlockAccessor to determine operation mappings block_type = self.block_accessor.block_type() if block_type == BlockType.PANDAS: self.ops = _PANDAS_EXPR_OPS_MAP elif block_type == BlockType.ARROW: self.ops = _ARROW_EXPR_OPS_MAP else: raise TypeError(f"Unsupported block type: {block_type}") def visit_column(self, expr: ColumnExpr) -> Union[BlockColumn, ScalarType]: """Visit a column expression and return the column data. Args: expr: The column expression. Returns: The column data as a BlockColumn. """ return self.block[expr.name] def visit_literal(self, expr: LiteralExpr) -> Union[BlockColumn, ScalarType]: """Visit a literal expression and return the literal value. Args: expr: The literal expression. Returns: The literal value. """ # Given that expressions support pandas blocks, we need to return the value as is. # Pandas has multiple dtype_backends, so there's no guarantee on the return type. return expr.value def visit_binary(self, expr: BinaryExpr) -> Union[BlockColumn, ScalarType]: """Visit a binary expression and return the result of the operation. Args: expr: The binary expression. Returns: The result of the binary operation as a BlockColumn. """ left_result = self.visit(expr.left) right_result = self.visit(expr.right) return self.ops[expr.op](left_result, right_result) def visit_unary(self, expr: UnaryExpr) -> Union[BlockColumn, ScalarType]: """Visit a unary expression and return the result of the operation. Args: expr: The unary expression. Returns: The result of the unary operation as a BlockColumn. """ operand_result = self.visit(expr.operand) return self.ops[expr.op](operand_result) def visit_udf(self, expr: UDFExpr) -> Union[BlockColumn, ScalarType]: """Visit a UDF expression and return the result of the function call. Args: expr: The UDF expression. Returns: The result of the UDF call as a BlockColumn. """ args = [self.visit(arg) for arg in expr.args] kwargs = {k: self.visit(v) for k, v in expr.kwargs.items()} result = expr.fn(*args, **kwargs) if not isinstance(result, (pd.Series, np.ndarray, pa.Array, pa.ChunkedArray)): function_name = expr.fn.__name__ raise TypeError( f"UDF '{function_name}' returned invalid type {type(result).__name__}. " f"Expected type (pandas.Series, numpy.ndarray, pyarrow.Array, or pyarrow.ChunkedArray)" ) return result def visit_alias(self, expr: AliasExpr) -> Union[BlockColumn, ScalarType]: """Visit an alias expression and return the renamed result. Args: expr: The alias expression. Returns: A Block with the data from the inner expression. """ # Evaluate the inner expression return self.visit(expr.expr) def visit_star(self, expr: StarExpr) -> Union[BlockColumn, ScalarType]: """Visit a star expression. Args: expr: The star expression. Returns: TypeError: StarExpr cannot be evaluated as a regular expression. """ # star() should not be evaluated directly - it's handled at Project level raise TypeError( "StarExpr cannot be evaluated as a regular expression. " "It should only be used in Project operations." ) def visit_download(self, expr: DownloadExpr) -> Union[BlockColumn, ScalarType]: """Visit a download expression. Args: expr: The download expression. Returns: TypeError: DownloadExpr evaluation not yet implemented. """ raise TypeError( "DownloadExpr evaluation is not yet implemented in NativeExpressionEvaluator." ) def eval_expr(expr: Expr, block: Block) -> Union[BlockColumn, ScalarType]: """Evaluate an expression against a block using the visitor pattern. Args: expr: The expression to evaluate. block: The Block to evaluate against. Returns: The evaluated result as a BlockColumn or a scalar value. """ evaluator = NativeExpressionEvaluator(block) return evaluator.visit(expr) def eval_projection(projection_exprs: List[Expr], block: Block) -> Block: """ Evaluate a projection (list of expressions) against a block. Handles projection semantics including: - Empty projections - Star() expressions for preserving existing columns - Rename detection - Column ordering Args: projection_exprs: List of expressions to evaluate (may include StarExpr) block: The block to project Returns: A new block with the projected schema """ block_accessor = BlockAccessor.for_block(block) # Skip projection only for schema-less empty blocks. if block_accessor.num_rows() == 0 and len(block_accessor.column_names()) == 0: return block # Handle simple cases early. if len(projection_exprs) == 0: return block_accessor.select([]) input_column_names = list(block_accessor.column_names()) # Collect input column rename map from the projection list input_column_rename_map = _extract_input_columns_renaming_mapping(projection_exprs) # Expand star expr (if any) if isinstance(projection_exprs[0], StarExpr): # Cherry-pick input block's columns that aren't explicitly removed via # renaming input_column_ref_exprs = [ col(c) for c in input_column_names if c not in input_column_rename_map ] projection_exprs = input_column_ref_exprs + projection_exprs[1:] names, output_cols = zip(*[(e.name, eval_expr(e, block)) for e in projection_exprs]) # This clumsy workaround is necessary to be able to fill in Pyarrow tables # that has to be "seeded" from existing table with N rows, and couldn't be # started from a truly empty table. # # TODO fix new_block = BlockAccessor.for_block(block).fill_column("__stub__", None) new_block = BlockAccessor.for_block(new_block).drop(input_column_names) for name, output_col in zip(names, output_cols): new_block = BlockAccessor.for_block(new_block).fill_column(name, output_col) return BlockAccessor.for_block(new_block).drop(["__stub__"])
NativeExpressionEvaluator
python
pyqtgraph__pyqtgraph
pyqtgraph/widgets/ColorMapMenu.py
{ "start": 4644, "end": 11201 }
class ____(QtWidgets.QMenu): sigColorMapTriggered = QtCore.Signal(object) def __init__(self, *, userList=None, showGradientSubMenu=False, showColorMapSubMenus=False): """ Creates a new ColorMapMenu. Parameters ---------- userList : list of ColorMapSpecifier, optional Supported values for ColorMapSpecifier are ``str``, ``(str, str)``, :class:`~pyqtgraph.ColorMap` Example: ``["viridis", ("glasbey", "colorcet"), ("rainbow", "matplotlib")]`` showGradientSubMenu : bool, default=False Adds legacy gradients in a submenu. showColorMapSubMenus : bool, default=False Adds bundled colormaps and external (colorcet, matplotlib) colormaps in submenus. """ super().__init__() self.setTitle("ColorMaps") self.triggered.connect(self.onTriggered) topmenu = self act = topmenu.addAction('None') act.setData(PrivateActionData(None, None)) if userList is not None: buildUserSubMenu(topmenu, userList) if any([showGradientSubMenu, showColorMapSubMenus]): topmenu.addSeparator() # render the submenus only if the user actually clicks on it if showGradientSubMenu: submenu = topmenu.addMenu('preset gradient') submenu.aboutToShow.connect(self.buildGradientSubMenu) if not showColorMapSubMenus: return submenu = topmenu.addMenu('local') submenu.aboutToShow.connect(self.buildLocalSubMenu) have_colorcet = importlib.util.find_spec('colorcet') is not None # arranged in the order listed in https://colorcet.com/ cet_types = ["Linear", "Divergent", "Rainbow", "Cyclic", "Isoluminant", "Color Blind"] # the local cet files are a subset of the colorcet module. # expose just one of them. if not have_colorcet: submenu = topmenu.addMenu('cet (local)') for cet_type in cet_types: sub2menu = submenu.addMenu(cet_type) sub2menu.aboutToShow.connect(self.buildCetLocalSubMenu) else: submenu = topmenu.addMenu('cet (external)') for cet_type in cet_types: sub2menu = submenu.addMenu(cet_type) sub2menu.aboutToShow.connect(self.buildCetExternalSubMenu) if importlib.util.find_spec('matplotlib') is not None: submenu = topmenu.addMenu('matplotlib') # skip 1st entry which is "Perceptually Uniform Sequential" # since pyqtgraph has those already for category, _ in MATPLOTLIB_CMAPS[1:]: sub2menu = submenu.addMenu(category) sub2menu.aboutToShow.connect(self.buildMplCategorySubMenu) if find_mpl_leftovers(): sub2menu = submenu.addMenu("Others") sub2menu.aboutToShow.connect(self.buildMplOthersSubMenu) if have_colorcet: submenu = topmenu.addMenu('colorcet') submenu.aboutToShow.connect(self.buildColorcetSubMenu) @QtCore.Slot(QtGui.QAction) def onTriggered(self, action): if not isinstance(data := action.data(), PrivateActionData): return cmap = self.actionDataToColorMap(data) self.sigColorMapTriggered.emit(cmap) @QtCore.Slot() def buildGradientSubMenu(self): source = 'preset-gradient' names = list(Gradients.keys()) self.buildSubMenu(names, source, sort=False) @QtCore.Slot() def buildLocalSubMenu(self): source = None names = colormap.listMaps(source=source) names = [x for x in names if not x.startswith('CET')] names = [x for x in names if not x.startswith('PAL-relaxed')] self.buildSubMenu(names, source) @QtCore.Slot() def buildCetLocalSubMenu(self): # in Qt6 we could have used Qt.ConnectionType.SingleShotConnection menu = self.sender() menu.aboutToShow.disconnect() source = None cet_type = menu.title() buildCetSubMenu(menu, source, cet_type) @QtCore.Slot() def buildCetExternalSubMenu(self): # in Qt6 we could have used Qt.ConnectionType.SingleShotConnection menu = self.sender() menu.aboutToShow.disconnect() source = 'colorcet' cet_type = menu.title() buildCetSubMenu(menu, source, cet_type) @QtCore.Slot() def buildMplCategorySubMenu(self): # in Qt6 we could have used Qt.ConnectionType.SingleShotConnection menu = self.sender() menu.aboutToShow.disconnect() source = 'matplotlib' category = menu.title() categories = [x[0] for x in MATPLOTLIB_CMAPS] names = MATPLOTLIB_CMAPS[categories.index(category)][1] for name in names: try: buildMenuEntryAction(menu, name, source) except ValueError: # the names are not programmatically discovered, # so to be safe, we wrap around try except pass @QtCore.Slot() def buildMplOthersSubMenu(self): self.buildSubMenu(find_mpl_leftovers(), "matplotlib") @QtCore.Slot() def buildColorcetSubMenu(self): # colorcet colormaps with shorter/simpler aliases source = 'colorcet' import colorcet names = list(colorcet.palette_n.keys()) self.buildSubMenu(names, source) def buildSubMenu(self, names, source, sort=True): # in Qt6 we could have used Qt.ConnectionType.SingleShotConnection menu = self.sender() menu.aboutToShow.disconnect() if sort: names = sorted_filenames(names) for name in names: buildMenuEntryAction(menu, name, source) @staticmethod def actionDataToColorMap(data): name, source = data if isinstance(source, colormap.ColorMap): cmap = source elif name is None: cmap = colormap.ColorMap(None, [0.0, 1.0]) elif source == 'preset-gradient': cmap = preset_gradient_to_colormap(name) cmap.name = f"{source}:{name}" # for GradientEditorItem else: # colormap module maintains a cache keyed by name only. # thus if a colormap has the same name in two different sources, # we will end up getting whatever was already cached. cmap = colormap.get(name, source=source) return cmap
ColorMapMenu
python
MongoEngine__mongoengine
mongoengine/base/datastructures.py
{ "start": 3290, "end": 6569 }
class ____(list): """A special list so we can watch any changes.""" _dereferenced = False _instance = None _name = None def __init__(self, list_items, instance, name): BaseDocument = _import_class("BaseDocument") if isinstance(instance, BaseDocument): if isinstance(instance, weakref.ProxyTypes): self._instance = instance else: self._instance = weakref.proxy(instance) self._name = name super().__init__(list_items) def __getitem__(self, key): # change index to positive value because MongoDB does not support negative one if isinstance(key, int) and key < 0: key = len(self) + key value = super().__getitem__(key) if isinstance(key, slice): # When receiving a slice operator, we don't convert the structure and bind # to parent's instance. This is buggy for now but would require more work to be handled properly return value EmbeddedDocument = _import_class("EmbeddedDocument") if isinstance(value, EmbeddedDocument) and value._instance is None: value._instance = self._instance elif isinstance(value, dict) and not isinstance(value, BaseDict): # Replace dict by BaseDict value = BaseDict(value, None, f"{self._name}.{key}") super().__setitem__(key, value) value._instance = self._instance elif isinstance(value, list) and not isinstance(value, BaseList): # Replace list by BaseList value = BaseList(value, None, f"{self._name}.{key}") super().__setitem__(key, value) value._instance = self._instance return value def __iter__(self): yield from super().__iter__() def __getstate__(self): self.instance = None self._dereferenced = False return self def __setstate__(self, state): self = state return self def __setitem__(self, key, value): changed_key = key if isinstance(key, slice): # In case of slice, we don't bother to identify the exact elements being updated # instead, we simply marks the whole list as changed changed_key = None result = super().__setitem__(key, value) self._mark_as_changed(changed_key) return result append = mark_as_changed_wrapper(list.append) extend = mark_as_changed_wrapper(list.extend) insert = mark_as_changed_wrapper(list.insert) pop = mark_as_changed_wrapper(list.pop) remove = mark_as_changed_wrapper(list.remove) reverse = mark_as_changed_wrapper(list.reverse) sort = mark_as_changed_wrapper(list.sort) clear = mark_as_changed_wrapper(list.clear) __delitem__ = mark_as_changed_wrapper(list.__delitem__) __iadd__ = mark_as_changed_wrapper(list.__iadd__) __imul__ = mark_as_changed_wrapper(list.__imul__) def _mark_as_changed(self, key=None): if hasattr(self._instance, "_mark_as_changed"): if key is not None: self._instance._mark_as_changed(f"{self._name}.{key % len(self)}") else: self._instance._mark_as_changed(self._name)
BaseList
python
readthedocs__readthedocs.org
readthedocs/projects/forms.py
{ "start": 24295, "end": 25020 }
class ____(forms.ModelForm, ProjectPRBuildsMixin): """Project pull requests configuration form.""" class Meta: model = Project fields = [ "external_builds_enabled", "external_builds_privacy_level", "show_build_overview_in_comment", ] def __init__(self, *args, **kwargs): self.project = kwargs.pop("project", None) super().__init__(*args, **kwargs) self.setup_external_builds_option() if not self.instance.is_github_app_project: self.fields.pop("show_build_overview_in_comment") if not settings.ALLOW_PRIVATE_REPOS: self.fields.pop("external_builds_privacy_level")
ProjectPullRequestForm
python
apache__airflow
providers/openlineage/tests/unit/openlineage/extractors/test_base.py
{ "start": 3397, "end": 3828 }
class ____(BaseOperator): def execute(self, context) -> Any: pass def get_openlineage_facets_on_start(self) -> OperatorLineage: return OperatorLineage() def get_openlineage_facets_on_complete(self, task_instance) -> OperatorLineage: return OperatorLineage() def get_openlineage_facets_on_failure(self, task_instance) -> OperatorLineage: return OperatorLineage()
SimpleCustomOperator
python
pydantic__pydantic
tests/benchmarks/shared.py
{ "start": 1104, "end": 1186 }
class ____(BaseModel): field1: str field2: int field3: float
SimpleModel
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_getlimits.py
{ "start": 2981, "end": 4106 }
class ____(TestCase): def test_basic(self): dts = list( zip( ["i1", "i2", "i4", "i8", "u1", "u2", "u4", "u8"], [ np.int8, np.int16, np.int32, np.int64, np.uint8, ], ) ) for dt1, dt2 in dts: for attr in ("bits", "min", "max"): assert_equal(getattr(iinfo(dt1), attr), getattr(iinfo(dt2), attr), attr) with assert_raises((TypeError, ValueError)): iinfo("f4") @parametrize( "T", [ np.uint8, # xfail: unsupported add (uint[16,32,64]) subtest(np.uint16, decorators=[] if TEST_WITH_TORCHDYNAMO else [xfail]), subtest(np.uint32, decorators=[] if TEST_WITH_TORCHDYNAMO else [xfail]), subtest(np.uint64, decorators=[] if TEST_WITH_TORCHDYNAMO else [xfail]), ], ) def test_unsigned_max(self, T): max_calculated = T(0) - T(1) assert_equal(iinfo(T).max, max_calculated)
TestIinfo