language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
huggingface__transformers
src/transformers/models/speech_to_text/tokenization_speech_to_text.py
{ "start": 1319, "end": 11500 }
class ____(PreTrainedTokenizer): """ Construct an Speech2Text tokenizer. This tokenizer inherits from [`PreTrainedTokenizer`] which contains some of the main methods. Users should refer to the superclass for more information regarding such methods. Args: vocab_file (`str`): File containing the vocabulary. spm_file (`str`): Path to the [SentencePiece](https://github.com/google/sentencepiece) model file bos_token (`str`, *optional*, defaults to `"<s>"`): The beginning of sentence token. eos_token (`str`, *optional*, defaults to `"</s>"`): The end of sentence token. unk_token (`str`, *optional*, defaults to `"<unk>"`): The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead. pad_token (`str`, *optional*, defaults to `"<pad>"`): The token used for padding, for example when batching sequences of different lengths. do_upper_case (`bool`, *optional*, defaults to `False`): Whether or not to uppercase the output when decoding. do_lower_case (`bool`, *optional*, defaults to `False`): Whether or not to lowercase the input when tokenizing. tgt_lang (`str`, *optional*): A string representing the target language. sp_model_kwargs (`dict`, *optional*): Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things, to set: - `enable_sampling`: Enable subword regularization. - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout. - `nbest_size = {0,1}`: No sampling is performed. - `nbest_size > 1`: samples from the nbest_size results. - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice) using forward-filtering-and-backward-sampling algorithm. - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for BPE-dropout. **kwargs Additional keyword arguments passed along to [`PreTrainedTokenizer`] """ vocab_files_names = VOCAB_FILES_NAMES model_input_names = ["input_ids", "attention_mask"] prefix_tokens: list[int] = [] def __init__( self, vocab_file, spm_file, bos_token="<s>", eos_token="</s>", pad_token="<pad>", unk_token="<unk>", do_upper_case=False, do_lower_case=False, tgt_lang=None, lang_codes=None, additional_special_tokens=None, sp_model_kwargs: Optional[dict[str, Any]] = None, **kwargs, ) -> None: self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs self.do_upper_case = do_upper_case self.do_lower_case = do_lower_case self.encoder = load_json(vocab_file) self.decoder = {v: k for k, v in self.encoder.items()} self.spm_file = spm_file self.sp_model = load_spm(spm_file, self.sp_model_kwargs) if lang_codes is not None: self.lang_codes = lang_codes self.langs = LANGUAGES[lang_codes] self.lang_tokens = [f"<lang:{lang}>" for lang in self.langs] self.lang_code_to_id = {lang: self.sp_model.PieceToId(f"<lang:{lang}>") for lang in self.langs} if additional_special_tokens is not None: additional_special_tokens = self.lang_tokens + additional_special_tokens else: additional_special_tokens = self.lang_tokens self._tgt_lang = tgt_lang if tgt_lang is not None else self.langs[0] self.set_tgt_lang_special_tokens(self._tgt_lang) else: self.lang_code_to_id = {} super().__init__( bos_token=bos_token, eos_token=eos_token, unk_token=unk_token, pad_token=pad_token, do_upper_case=do_upper_case, do_lower_case=do_lower_case, tgt_lang=tgt_lang, lang_codes=lang_codes, sp_model_kwargs=self.sp_model_kwargs, additional_special_tokens=additional_special_tokens, **kwargs, ) @property def vocab_size(self) -> int: return len(self.encoder) def get_vocab(self) -> dict: vocab = self.encoder.copy() vocab.update(self.added_tokens_encoder) return vocab @property def tgt_lang(self) -> str: return self._tgt_lang @tgt_lang.setter def tgt_lang(self, new_tgt_lang) -> None: self._tgt_lang = new_tgt_lang self.set_tgt_lang_special_tokens(new_tgt_lang) def set_tgt_lang_special_tokens(self, tgt_lang: str) -> None: """Reset the special tokens to the target language setting. prefix=[eos, tgt_lang_code] and suffix=[eos].""" lang_code_id = self.lang_code_to_id[tgt_lang] self.prefix_tokens = [lang_code_id] def _tokenize(self, text: str) -> list[str]: return self.sp_model.encode(text, out_type=str) def _convert_token_to_id(self, token): return self.encoder.get(token, self.encoder[self.unk_token]) def _convert_id_to_token(self, index: int) -> str: """Converts an index (integer) in a token (str) using the decoder.""" return self.decoder.get(index, self.unk_token) def convert_tokens_to_string(self, tokens: list[str]) -> str: """Converts a sequence of tokens (strings for sub-words) in a single string.""" current_sub_tokens = [] out_string = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: decoded = self.sp_model.decode(current_sub_tokens) out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " " current_sub_tokens = [] else: current_sub_tokens.append(token) decoded = self.sp_model.decode(current_sub_tokens) out_string += decoded.upper() if self.do_upper_case else decoded return out_string.strip() def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None) -> list[int]: """Build model inputs from a sequence by appending eos_token_id.""" if token_ids_1 is None: return self.prefix_tokens + token_ids_0 + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_0 + token_ids_1 + [self.eos_token_id] def get_special_tokens_mask( self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False ) -> list[int]: """ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer `prepare_for_model` method. Args: token_ids_0 (`list[int]`): List of IDs. token_ids_1 (`list[int]`, *optional*): Optional second list of IDs for sequence pairs. already_has_special_tokens (`bool`, *optional*, defaults to `False`): Whether or not the token list is already formatted with special tokens for the model. Returns: `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token. """ if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True ) prefix_ones = [1] * len(self.prefix_tokens) suffix_ones = [1] if token_ids_1 is None: return prefix_ones + ([0] * len(token_ids_0)) + suffix_ones return prefix_ones + ([0] * len(token_ids_0)) + ([0] * len(token_ids_1)) + suffix_ones def __getstate__(self) -> dict: state = self.__dict__.copy() state["sp_model"] = None return state def __setstate__(self, d: dict) -> None: self.__dict__ = d # for backward compatibility if not hasattr(self, "sp_model_kwargs"): self.sp_model_kwargs = {} self.sp_model = load_spm(self.spm_file, self.sp_model_kwargs) def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]: save_dir = Path(save_directory) assert save_dir.is_dir(), f"{save_directory} should be a directory" vocab_save_path = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"] ) spm_save_path = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"] ) save_json(self.encoder, vocab_save_path) if os.path.abspath(self.spm_file) != os.path.abspath(spm_save_path) and os.path.isfile(self.spm_file): copyfile(self.spm_file, spm_save_path) elif not os.path.isfile(self.spm_file): with open(spm_save_path, "wb") as fi: content_spiece_model = self.sp_model.serialized_model_proto() fi.write(content_spiece_model) return (str(vocab_save_path), str(spm_save_path)) def load_spm(path: str, sp_model_kwargs: dict[str, Any]) -> sentencepiece.SentencePieceProcessor: spm = sentencepiece.SentencePieceProcessor(**sp_model_kwargs) spm.Load(str(path)) return spm def load_json(path: str) -> Union[dict, list]: with open(path, "r") as f: return json.load(f) def save_json(data, path: str) -> None: with open(path, "w") as f: json.dump(data, f, indent=2) __all__ = ["Speech2TextTokenizer"]
Speech2TextTokenizer
python
lxml__lxml
src/lxml/tests/test_etree.py
{ "start": 197325, "end": 201950 }
class ____(HelperTestCase): def test_write(self): tree = self.parse(b'<a><b/></a>') f = BytesIO() tree.write(f) s = f.getvalue() self.assertEqual(b'<a><b/></a>', s) def test_write_doctype(self): tree = self.parse(b'<a><b/></a>') f = BytesIO() tree.write(f, doctype='HUHU') s = f.getvalue() self.assertEqual(b'HUHU\n<a><b/></a>', s) def test_write_gzip(self): tree = self.parse(b'<a>'+b'<b/>'*200+b'</a>') f = BytesIO() tree.write(f, compression=9) with gzip.GzipFile(fileobj=BytesIO(f.getvalue())) as gzfile: s = gzfile.read() self.assertEqual(b'<a>'+b'<b/>'*200+b'</a>', s) def test_write_gzip_doctype(self): tree = self.parse(b'<a>'+b'<b/>'*200+b'</a>') f = BytesIO() tree.write(f, compression=9, doctype='<!DOCTYPE a>') with gzip.GzipFile(fileobj=BytesIO(f.getvalue())) as gzfile: s = gzfile.read() self.assertEqual(b'<!DOCTYPE a>\n<a>'+b'<b/>'*200+b'</a>', s) def test_write_gzip_level(self): tree = self.parse(b'<a>'+b'<b/>'*200+b'</a>') f = BytesIO() tree.write(f, compression=0) s0 = f.getvalue() f = BytesIO() tree.write(f) self.assertEqual(f.getvalue(), s0) f = BytesIO() tree.write(f, compression=1) s = f.getvalue() self.assertTrue(len(s) <= len(s0)) with gzip.GzipFile(fileobj=BytesIO(s)) as gzfile: s1 = gzfile.read() f = BytesIO() tree.write(f, compression=9) s = f.getvalue() self.assertTrue(len(s) <= len(s0)) with gzip.GzipFile(fileobj=BytesIO(s)) as gzfile: s9 = gzfile.read() self.assertEqual(b'<a>'+b'<b/>'*200+b'</a>', s0) self.assertEqual(b'<a>'+b'<b/>'*200+b'</a>', s1) self.assertEqual(b'<a>'+b'<b/>'*200+b'</a>', s9) def test_write_file(self): tree = self.parse(b'<a><b/></a>') with tmpfile() as filename: tree.write(filename) data = read_file(filename, 'rb') self.assertEqual(b'<a><b/></a>', data) def test_write_file_pathlike(self): tree = self.parse(b'<a><b/></a>') with tmpfile() as filename: tree.write(SimpleFSPath(filename)) data = read_file(filename, 'rb') self.assertEqual(b'<a><b/></a>', data) def test_write_file_gzip(self): tree = self.parse(b'<a>'+b'<b/>'*200+b'</a>') with tmpfile() as filename: tree.write(filename, compression=9) with gzip.open(filename, 'rb') as f: data = f.read() self.assertEqual(b'<a>'+b'<b/>'*200+b'</a>', data) def test_write_file_gzip_pathlike(self): tree = self.parse(b'<a>'+b'<b/>'*200+b'</a>') with tmpfile() as filename: tree.write(SimpleFSPath(filename), compression=9) with gzip.open(filename, 'rb') as f: data = f.read() self.assertEqual(b'<a>'+b'<b/>'*200+b'</a>', data) @needs_feature("zlib") def test_write_file_gzip_parse(self): tree = self.parse(b'<a>'+b'<b/>'*200+b'</a>') parser = etree.XMLParser(decompress=True) with tmpfile() as filename: tree.write(filename, compression=9) data = etree.tostring(etree.parse(filename, parser)) self.assertEqual(b'<a>'+b'<b/>'*200+b'</a>', data) @needs_feature("zlib") def test_write_file_gzipfile_parse(self): tree = self.parse(b'<a>'+b'<b/>'*200+b'</a>') with tmpfile() as filename: tree.write(filename, compression=9) with gzip.GzipFile(filename) as f: data = etree.tostring(etree.parse(f)) self.assertEqual(b'<a>'+b'<b/>'*200+b'</a>', data) def test_write_file_url(self): xml = b'<a>'+b'<b/>'*200+b'</a>' tree = self.parse(xml) with tmpfile(prefix="p+%20", suffix=".xml") as filename: url = 'file://' + (filename if sys.platform != 'win32' else '/' + filename.replace('\\', '/')) tree.write(url) data = read_file(filename, 'rb').replace(b'\n', b'') self.assertEqual(data, xml)
ETreeWriteTestCase
python
jina-ai__jina
tests/integration/docarray_v2/docker/executor2/executor.py
{ "start": 367, "end": 1272 }
class ____(Executor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._indexer = InMemoryExactNNIndex[MyDoc]() @requests(on='/index') def index(self, docs: DocList[MyDoc], **kwargs) -> DocList[MyDoc]: self._indexer.index(docs) return docs @requests(on='/search') def search(self, docs: DocList[MyDoc], **kwargs) -> DocList[MyDocWithMatches]: res = DocList[MyDocWithMatches]() ret = self._indexer.find_batched(docs, search_field='embedding') matched_documents = ret.documents matched_scores = ret.scores for query, matches, scores in zip(docs, matched_documents, matched_scores): output_doc = MyDocWithMatches(**query.dict()) output_doc.matches = matches output_doc.scores = scores.tolist() res.append(output_doc) return res
Indexer
python
huggingface__transformers
tests/models/llava/test_image_processing_llava.py
{ "start": 3732, "end": 10397 }
class ____(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = LlavaImageProcessor if is_vision_available() else None fast_image_processing_class = LlavaImageProcessorFast if is_torchvision_available() else None def setUp(self): super().setUp() self.image_processor_tester = LlavaImageProcessingTester(self) @property def image_processor_dict(self): return self.image_processor_tester.prepare_image_processor_dict() # Ignore copy def test_image_processor_properties(self): for image_processing_class in self.image_processor_list: image_processing = image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(image_processing, "do_pad")) self.assertTrue(hasattr(image_processing, "do_resize")) self.assertTrue(hasattr(image_processing, "size")) self.assertTrue(hasattr(image_processing, "do_center_crop")) self.assertTrue(hasattr(image_processing, "center_crop")) self.assertTrue(hasattr(image_processing, "do_normalize")) self.assertTrue(hasattr(image_processing, "image_mean")) self.assertTrue(hasattr(image_processing, "image_std")) self.assertTrue(hasattr(image_processing, "do_convert_rgb")) def test_image_processor_from_dict_with_kwargs(self): for image_processing_class in self.image_processor_list: image_processor = image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size, {"shortest_edge": 20}) self.assertEqual(image_processor.crop_size, {"height": 18, "width": 18}) image_processor = image_processing_class.from_dict(self.image_processor_dict, size=42, crop_size=84) self.assertEqual(image_processor.size, {"shortest_edge": 42}) self.assertEqual(image_processor.crop_size, {"height": 84, "width": 84}) # Ignore copy def test_padding(self): """ LLaVA needs to pad images to square size before processing as per orig implementation. Checks that image processor pads images correctly given different background colors. """ # taken from original implementation: https://github.com/haotian-liu/LLaVA/blob/c121f0432da27facab705978f83c4ada465e46fd/llava/mm_utils.py#L152 def pad_to_square_original( image: Image.Image, background_color: int | tuple[int, int, int] = 0 ) -> Image.Image: width, height = image.size if width == height: return image elif width > height: result = Image.new(image.mode, (width, width), background_color) result.paste(image, (0, (width - height) // 2)) return result else: result = Image.new(image.mode, (height, height), background_color) result.paste(image, ((height - width) // 2, 0)) return result for i, image_processing_class in enumerate(self.image_processor_list): image_processor = image_processing_class.from_dict(self.image_processor_dict) numpify = i == 0 torchify = i == 1 image_inputs = self.image_processor_tester.prepare_image_inputs( equal_resolution=False, numpify=numpify, torchify=torchify ) # test with images in channel-last and channel-first format (only channel-first for torch) for image in image_inputs: padded_image = image_processor.pad_to_square(image) if i == 0: padded_image_original = pad_to_square_original(Image.fromarray(image)) padded_image_original = np.array(padded_image_original) np.testing.assert_allclose(padded_image, padded_image_original) padded_image = image_processor.pad_to_square( image.transpose(2, 0, 1), input_data_format="channels_first" ) padded_image = padded_image.transpose(1, 2, 0) np.testing.assert_allclose(padded_image, padded_image_original) else: padded_image_original = pad_to_square_original(F.to_pil_image(image)) padded_image = padded_image.permute(1, 2, 0) np.testing.assert_allclose(padded_image, padded_image_original) # test background color background_color = (122, 116, 104) for image in image_inputs: padded_image = image_processor.pad_to_square(image, background_color=background_color) if i == 0: padded_image_original = pad_to_square_original( Image.fromarray(image), background_color=background_color ) else: padded_image_original = pad_to_square_original( F.to_pil_image(image), background_color=background_color ) padded_image = padded_image.permute(1, 2, 0) padded_image_original = np.array(padded_image_original) np.testing.assert_allclose(padded_image, padded_image_original) background_color = 122 for image in image_inputs: padded_image = image_processor.pad_to_square(image, background_color=background_color) if i == 0: padded_image_original = pad_to_square_original( Image.fromarray(image), background_color=background_color ) else: padded_image_original = pad_to_square_original( F.to_pil_image(image), background_color=background_color ) padded_image = padded_image.permute(1, 2, 0) padded_image_original = np.array(padded_image_original) np.testing.assert_allclose(padded_image, padded_image_original) # background color length should match channel length with self.assertRaises(ValueError): padded_image = image_processor.pad_to_square(image_inputs[0], background_color=(122, 104)) with self.assertRaises(ValueError): padded_image = image_processor.pad_to_square(image_inputs[0], background_color=(122, 104, 0, 0)) @unittest.skip(reason="LLaVa does not support 4 channel images yet") # Ignore copy def test_call_numpy_4_channels(self): pass
LlavaImageProcessingTest
python
huggingface__transformers
src/transformers/models/audioflamingo3/processing_audioflamingo3.py
{ "start": 1187, "end": 1643 }
class ____(ProcessingKwargs, total=False): _defaults = { "text_kwargs": { "padding": True, }, "audio_kwargs": { "sampling_rate": 16000, "chunk_length": 30.0, "return_attention_mask": True, "padding": "max_length", }, "common_kwargs": { "return_tensors": "pt", "padding_side": "left", }, }
AudioFlamingo3ProcessorKwargs
python
bokeh__bokeh
src/bokeh/resources.py
{ "start": 7590, "end": 7713 }
class ____(Protocol): @staticmethod def __call__(components: list[str], kind: Kind) -> Hashes: ... @dataclass
HashesFn
python
django__django
tests/admin_docs/views.py
{ "start": 489, "end": 635 }
class ____(View): """ This is a view for :model:`myapp.Company` """ def get(self, request): return HttpResponse()
CompanyView
python
dask__distributed
distributed/comm/registry.py
{ "start": 375, "end": 2430 }
class ____(ABC): """ A communication backend, selected by a given URI scheme (e.g. 'tcp'). """ # I/O @abstractmethod def get_connector(self): """ Get a connector object usable for connecting to addresses. """ @abstractmethod def get_listener(self, loc, handle_comm, deserialize, **connection_args): """ Get a listener object for the scheme-less address *loc*. """ # Address handling @abstractmethod def get_address_host(self, loc): """ Get a host name (normally an IP address) identifying the host the address is located on. *loc* is a scheme-less address. """ @abstractmethod def resolve_address(self, loc): """ Resolve the address into a canonical form. *loc* is a scheme-less address. Simple implementations may return *loc* unchanged. """ def get_address_host_port(self, loc): """ Get the (host, port) tuple of the scheme-less address *loc*. This should only be implemented by IP-based transports. """ raise NotImplementedError @abstractmethod def get_local_address_for(self, loc): """ Get the local listening address suitable for reaching *loc*. """ # The {scheme: Backend} mapping backends: dict[str, Backend] = {} def get_backend(scheme: str) -> Backend: """ Get the Backend instance for the given *scheme*. It looks for matching scheme in dask's internal cache, and falls-back to package metadata for the group name ``distributed.comm.backends`` """ backend = backends.get(scheme) if backend is not None: return backend for backend_class_ep in _entry_points( name=scheme, group="distributed.comm.backends" ): backend = backend_class_ep.load()() backends[scheme] = backend return backend raise ValueError( f"unknown address scheme {scheme!r} (known schemes: {sorted(backends)})" )
Backend
python
doocs__leetcode
solution/3400-3499/3427.Sum of Variable Length Subarrays/Solution.py
{ "start": 0, "end": 189 }
class ____: def subarraySum(self, nums: List[int]) -> int: s = list(accumulate(nums, initial=0)) return sum(s[i + 1] - s[max(0, i - x)] for i, x in enumerate(nums))
Solution
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 642178, "end": 642797 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("branch", "git_url", "name", "path", "subproject_commit_oid") branch = sgqlc.types.Field(String, graphql_name="branch") git_url = sgqlc.types.Field(sgqlc.types.non_null(URI), graphql_name="gitUrl") name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name") path = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="path") subproject_commit_oid = sgqlc.types.Field( GitObjectID, graphql_name="subprojectCommitOid" )
Submodule
python
psf__black
tests/data/cases/line_ranges_fmt_off_decorator.py
{ "start": 266, "end": 774 }
class ____: # fmt: off @decorator ( ) # fmt: on def method(): print ( "str" ) @decor( a=1, # fmt: off b=(2, 3), # fmt: on ) def func(): pass # output # flags: --line-ranges=12-12 --line-ranges=21-21 # NOTE: If you need to modify this file, pay special attention to the --line-ranges= # flag above as it's formatting specifically these lines. # Regression test for an edge case involving decorators and fmt: off/on.
MyClass
python
ansible__ansible
lib/ansible/_internal/_wrapt.py
{ "start": 3448, "end": 3921 }
class ____(type): def __new__(cls, name, bases, dictionary): # Copy our special properties into the class so that they # always take precedence over attributes of the same name added # during construction of a derived class. This is to save # duplicating the implementation for them in all derived classes. dictionary.update(vars(_ObjectProxyMethods)) return type.__new__(cls, name, bases, dictionary)
_ObjectProxyMetaType
python
huggingface__transformers
src/transformers/models/roformer/modeling_roformer.py
{ "start": 44361, "end": 47693 }
class ____(RoFormerPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.roformer = RoFormerModel(config) self.classifier = RoFormerClassificationHead(config) # Initialize weights and apply final processing self.post_init() @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[SequenceClassifierOutput, tuple[torch.Tensor]]: r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.roformer( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] logits = self.classifier(sequence_output) loss = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: self.config.problem_type = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): self.config.problem_type = "single_label_classification" else: self.config.problem_type = "multi_label_classification" if self.config.problem_type == "regression": loss_fct = MSELoss() if self.num_labels == 1: loss = loss_fct(logits.squeeze(), labels.squeeze()) else: loss = loss_fct(logits, labels) elif self.config.problem_type == "single_label_classification": loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) elif self.config.problem_type == "multi_label_classification": loss_fct = BCEWithLogitsLoss() loss = loss_fct(logits, labels) if not return_dict: output = (logits,) + outputs[1:] return ((loss,) + output) if loss is not None else output return SequenceClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @auto_docstring
RoFormerForSequenceClassification
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/internal/conjecture/data.py
{ "start": 7968, "end": 9975 }
class ____: """There are many properties of spans that we calculate by essentially rerunning the test case multiple times based on the calls which we record in SpanProperty. This class defines a visitor, subclasses of which can be used to calculate these properties. """ def __init__(self, spans: "Spans"): self.span_stack: list[int] = [] self.spans = spans self.span_count = 0 self.choice_count = 0 def run(self) -> Any: """Rerun the test case with this visitor and return the results of ``self.finish()``.""" for record in self.spans.trail: if record == TrailType.STOP_SPAN_DISCARD: self.__pop(discarded=True) elif record == TrailType.STOP_SPAN_NO_DISCARD: self.__pop(discarded=False) elif record == TrailType.CHOICE: self.choice_count += 1 else: # everything after TrailType.CHOICE is the label of a span start. self.__push(record - TrailType.CHOICE - 1) return self.finish() def __push(self, label_index: int) -> None: i = self.span_count assert i < len(self.spans) self.start_span(i, label_index=label_index) self.span_count += 1 self.span_stack.append(i) def __pop(self, *, discarded: bool) -> None: i = self.span_stack.pop() self.stop_span(i, discarded=discarded) def start_span(self, i: int, label_index: int) -> None: """Called at the start of each span, with ``i`` the index of the span and ``label_index`` the index of its label in ``self.spans.labels``.""" def stop_span(self, i: int, *, discarded: bool) -> None: """Called at the end of each span, with ``i`` the index of the span and ``discarded`` being ``True`` if ``stop_span`` was called with ``discard=True``.""" def finish(self) -> Any: raise NotImplementedError
SpanProperty
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_outline02.py
{ "start": 315, "end": 3023 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("outline02.xlsx") self.ignore_files = [ "xl/calcChain.xml", "[Content_Types].xml", "xl/_rels/workbook.xml.rels", ] def test_create_file(self): """ Test the creation of a outlines in a XlsxWriter file. These tests are based on the outline programs in the examples directory. """ workbook = Workbook(self.got_filename) worksheet2 = workbook.add_worksheet("Collapsed Rows") bold = workbook.add_format({"bold": 1}) worksheet2.set_row(1, None, None, {"level": 2, "hidden": True}) worksheet2.set_row(2, None, None, {"level": 2, "hidden": True}) worksheet2.set_row(3, None, None, {"level": 2, "hidden": True}) worksheet2.set_row(4, None, None, {"level": 2, "hidden": True}) worksheet2.set_row(5, None, None, {"level": 1, "hidden": True}) worksheet2.set_row(6, None, None, {"level": 2, "hidden": True}) worksheet2.set_row(7, None, None, {"level": 2, "hidden": True}) worksheet2.set_row(8, None, None, {"level": 2, "hidden": True}) worksheet2.set_row(9, None, None, {"level": 2, "hidden": True}) worksheet2.set_row(10, None, None, {"level": 1, "hidden": True}) worksheet2.set_row(11, None, None, {"collapsed": True}) worksheet2.set_column("A:A", 20) worksheet2.set_selection("A14") worksheet2.write("A1", "Region", bold) worksheet2.write("A2", "North") worksheet2.write("A3", "North") worksheet2.write("A4", "North") worksheet2.write("A5", "North") worksheet2.write("A6", "North Total", bold) worksheet2.write("B1", "Sales", bold) worksheet2.write("B2", 1000) worksheet2.write("B3", 1200) worksheet2.write("B4", 900) worksheet2.write("B5", 1200) worksheet2.write("B6", "=SUBTOTAL(9,B2:B5)", bold, 4300) worksheet2.write("A7", "South") worksheet2.write("A8", "South") worksheet2.write("A9", "South") worksheet2.write("A10", "South") worksheet2.write("A11", "South Total", bold) worksheet2.write("B7", 400) worksheet2.write("B8", 600) worksheet2.write("B9", 500) worksheet2.write("B10", 600) worksheet2.write("B11", "=SUBTOTAL(9,B7:B10)", bold, 2100) worksheet2.write("A12", "Grand Total", bold) worksheet2.write("B12", "=SUBTOTAL(9,B2:B10)", bold, 6400) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
astropy__astropy
astropy/units/tests/test_quantity_decorator.py
{ "start": 8812, "end": 12358 }
class ____: @pytest.mark.parametrize( "annot", [u.m, u.Quantity[u.m], u.Quantity[u.m, "more"]], ) # Note: parametrization is done even if test class is skipped def test_single_annotation_unit(self, annot): """Try a variety of valid annotations.""" @u.quantity_input def myfunc_args(x: annot, y: str): return x, y i_q, i_str = 2 * u.m, "cool string" o_q, o_str = myfunc_args(i_q, i_str) assert o_q == i_q assert o_str == i_str def test_args_None(): x_target = u.deg x_unit = u.arcsec y_target = u.km y_unit = u.kpc @u.quantity_input(x=[x_target, None], y=[None, y_target]) def myfunc_args(x, y): return x, y x, y = myfunc_args(1 * x_unit, None) assert isinstance(x, u.Quantity) assert x.unit == x_unit assert y is None x, y = myfunc_args(None, 1 * y_unit) assert isinstance(y, u.Quantity) assert y.unit == y_unit assert x is None def test_args_None_kwarg(): x_target = u.deg x_unit = u.arcsec y_target = u.km @u.quantity_input(x=x_target, y=y_target) def myfunc_args(x, y=None): return x, y x, y = myfunc_args(1 * x_unit) assert isinstance(x, u.Quantity) assert x.unit == x_unit assert y is None x, y = myfunc_args(1 * x_unit, None) assert isinstance(x, u.Quantity) assert x.unit == x_unit assert y is None with pytest.raises(TypeError): x, y = myfunc_args(None, None) @pytest.mark.parametrize("val", [1.0, 1, np.arange(10), np.arange(10.0)]) def test_allow_dimensionless_numeric(val): """ When dimensionless_unscaled is an allowed unit, numbers and numeric numpy arrays are allowed through """ @u.quantity_input(velocity=[u.km / u.s, u.dimensionless_unscaled]) def myfunc(velocity): return velocity assert np.all(myfunc(val) == val) @pytest.mark.parametrize("val", [1.0, 1, np.arange(10), np.arange(10.0)]) def test_allow_dimensionless_numeric_strict(val): """ When dimensionless_unscaled is an allowed unit, but we are being strict, don't allow numbers and numeric numpy arrays through """ @u.quantity_input( velocity=[u.km / u.s, u.dimensionless_unscaled], strict_dimensionless=True ) def myfunc(velocity): return velocity with pytest.raises(TypeError): assert myfunc(val) @pytest.mark.parametrize("val", [1 * u.deg, [1, 2, 3] * u.m]) def test_dimensionless_with_nondimensionless_input(val): """ When dimensionless_unscaled is the only allowed unit, don't let input with non-dimensionless units through """ @u.quantity_input(x=u.dimensionless_unscaled) def myfunc(x): return x with pytest.raises(u.UnitsError): myfunc(val) def test_annotated_not_quantity(): """Test when annotation looks like a Quantity[X], but isn't.""" @u.quantity_input() def myfunc(x: typing.Annotated[object, u.m]): return x # nothing happens when wrong unit is passed assert myfunc(1) == 1 assert myfunc(1 * u.m) == 1 * u.m assert myfunc(1 * u.s) == 1 * u.s def test_annotated_not_unit(): """Test when annotation looks like a Quantity[X], but the unit's wrong.""" @u.quantity_input() def myfunc(x: typing.Annotated[u.Quantity, object()]): return x # nothing happens when wrong unit is passed assert myfunc(1) == 1 assert myfunc(1 * u.m) == 1 * u.m assert myfunc(1 * u.s) == 1 * u.s
TestTypeAnnotations
python
matplotlib__matplotlib
doc/sphinxext/math_symbol_table.py
{ "start": 4291, "end": 5476 }
class ____(Directive): has_content = False required_arguments = 0 optional_arguments = 0 final_argument_whitespace = False option_spec = {} def run(self): return run(self.state_machine) def setup(app): app.add_directive("math_symbol_table", MathSymbolTableDirective) metadata = {'parallel_read_safe': True, 'parallel_write_safe': True} return metadata if __name__ == "__main__": # Do some verification of the tables print("SYMBOLS NOT IN STIX:") all_symbols = {} for category, columns, syms in symbols: if category == "Standard Function Names": continue for sym in syms: if len(sym) > 1: all_symbols[sym[1:]] = None if sym[1:] not in _mathtext_data.tex2uni: print(sym) # Add accents all_symbols.update({v[1:]: k for k, v in _mathtext.Parser._accent_map.items()}) all_symbols.update({v: v for v in _mathtext.Parser._wide_accents}) print("SYMBOLS NOT IN TABLE:") for sym, val in _mathtext_data.tex2uni.items(): if sym not in all_symbols: print(f"{sym} = {chr(val)}")
MathSymbolTableDirective
python
google__pytype
pytype/pytd/visitors.py
{ "start": 68573, "end": 71033 }
class ____(Visitor): """Visitor for verifying that Literal[object] contains an enum. Other valid Literal types are checked by the parser, e.g. to make sure no `float` values are used in Literals. Checking that an object in a Literal is an enum member is more complex, so it gets its own visitor. Because this visitor walks up the class hierarchy, it must be run after ClassType pointers are filled in. """ def EnterLiteral(self, node): value = node.value if not isinstance(value, pytd.Constant): # This Literal does not hold an object, no need to check further. return if value.name in ("builtins.True", "builtins.False"): # When outputting `x: Literal[True]` from a source file, we write it as # a Literal(Constant("builtins.True", type=ClassType("builtins.bool"))) # This is fine and does not need to be checked for enum-ness. return typ = value.type if not isinstance(typ, pytd.ClassType): # This happens sometimes, e.g. with stdlib type stubs that interact with # C extensions. (tkinter.pyi, for example.) There's no point in trying to # handle these case. return this_cls = typ.cls assert ( this_cls ), "VerifyLiterals visitor must be run after ClassType pointers are filled." # The fun part: Walk through each class in the MRO and figure out if it # inherits from enum.Enum. stack = [this_cls] while stack: cls = stack.pop() if cls.name == "enum.Enum": break # We're only going to handle ClassType and Class here. The other types # that may appear in ClassType.cls pointers or Class.bases lists are not # common and may indicate that something is wrong. if isinstance(cls, pytd.ClassType): stack.extend(cls.cls.bases) elif isinstance(cls, pytd.Class): stack.extend(cls.bases) else: n = pytd_utils.Print(node) raise LiteralValueError( f"In {n}: {this_cls.name} is not an enum and " "cannot be used in typing.Literal" ) # Second check: The member named in the Literal exists in the enum. # We know at this point that value.name is "file.enum_class.member_name". _, member_name = value.name.rsplit(".", 1) if member_name not in this_cls: n = pytd_utils.Print(node) msg = f"In {n}: {value.name} is not a member of enum {this_cls.name}" raise LiteralValueError(msg)
VerifyLiterals
python
astropy__astropy
astropy/modeling/tests/test_fitters.py
{ "start": 13511, "end": 24416 }
class ____: """Tests non-linear least squares fitting and the SLSQP algorithm.""" def setup_class(self): self.initial_values = [100, 5, 1] self.xdata = np.arange(0, 10, 0.1) sigma = 4.0 * np.ones_like(self.xdata) with NumpyRNGContext(_RANDOM_SEED): yerror = np.random.normal(0, sigma) def func(p, x): return p[0] * np.exp(-0.5 / p[2] ** 2 * (x - p[1]) ** 2) self.ydata = func(self.initial_values, self.xdata) + yerror self.gauss = models.Gaussian1D(100, 5, stddev=1) @pytest.mark.parametrize("fitter0", non_linear_fitters_bounds) @pytest.mark.parametrize("fitter1", non_linear_fitters_bounds) def test_estimated_vs_analytic_deriv(self, fitter0, fitter1): """ Runs `LevMarLSQFitter` and `TRFLSQFitter` with estimated and analytic derivatives of a `Gaussian1D`. """ fitter0 = fitter0() model = fitter0(self.gauss, self.xdata, self.ydata) g1e = models.Gaussian1D(100, 5.0, stddev=1) fitter1 = fitter1() emodel = fitter1(g1e, self.xdata, self.ydata, estimate_jacobian=True) assert_allclose(model.parameters, emodel.parameters, rtol=10 ** (-3)) @pytest.mark.parametrize("fitter0", non_linear_fitters_bounds) @pytest.mark.parametrize("fitter1", non_linear_fitters_bounds) def test_estimated_vs_analytic_deriv_with_weights(self, fitter0, fitter1): """ Runs `LevMarLSQFitter` and `TRFLSQFitter` with estimated and analytic derivatives of a `Gaussian1D`. """ weights = 1.0 / (self.ydata / 10.0) fitter0 = fitter0() model = fitter0(self.gauss, self.xdata, self.ydata, weights=weights) g1e = models.Gaussian1D(100, 5.0, stddev=1) fitter1 = fitter1() emodel = fitter1( g1e, self.xdata, self.ydata, weights=weights, estimate_jacobian=True ) assert_allclose(model.parameters, emodel.parameters, rtol=10 ** (-3)) @pytest.mark.parametrize("fitter", non_linear_fitters_bounds) def test_with_optimize(self, fitter): """ Tests results from `LevMarLSQFitter` and `TRFLSQFitter` against `scipy.optimize.leastsq`. """ fitter = fitter() model = fitter(self.gauss, self.xdata, self.ydata, estimate_jacobian=True) def func(p, x): return p[0] * np.exp(-0.5 / p[2] ** 2 * (x - p[1]) ** 2) def errfunc(p, x, y): return func(p, x) - y result = optimize.leastsq( errfunc, self.initial_values, args=(self.xdata, self.ydata) ) assert_allclose(model.parameters, result[0], rtol=10 ** (-3)) @pytest.mark.parametrize("fitter", non_linear_fitters_bounds) def test_with_weights(self, fitter): """ Tests results from `LevMarLSQFitter` and `TRFLSQFitter` with weights. """ fitter = fitter() # part 1: weights are equal to 1 model = fitter(self.gauss, self.xdata, self.ydata, estimate_jacobian=True) withw = fitter( self.gauss, self.xdata, self.ydata, estimate_jacobian=True, weights=np.ones_like(self.xdata), ) assert_allclose(model.parameters, withw.parameters, rtol=10 ** (-4)) # part 2: weights are 0 or 1 (effectively, they are a mask) weights = np.zeros_like(self.xdata) weights[::2] = 1.0 mask = weights >= 1.0 model = fitter( self.gauss, self.xdata[mask], self.ydata[mask], estimate_jacobian=True ) withw = fitter( self.gauss, self.xdata, self.ydata, estimate_jacobian=True, weights=weights ) assert_allclose(model.parameters, withw.parameters, rtol=10 ** (-4)) @pytest.mark.filterwarnings(r"ignore:.* Maximum number of iterations reached") @pytest.mark.filterwarnings( r"ignore:Values in x were outside bounds during a minimize step, " r"clipping to bounds" ) @pytest.mark.parametrize("fitter_class", fitters) @pytest.mark.parametrize("fitter", non_linear_fitters_bounds) def test_fitter_against_LevMar(self, fitter_class, fitter): """ Tests results from non-linear fitters against `LevMarLSQFitter` and `TRFLSQFitter` """ fitter = fitter() fitter_cls = fitter_class() # This emits a warning from fitter that we need to ignore with # pytest.mark.filterwarnings above. new_model = fitter_cls(self.gauss, self.xdata, self.ydata) model = fitter(self.gauss, self.xdata, self.ydata) assert_allclose(model.parameters, new_model.parameters, rtol=10 ** (-4)) @pytest.mark.filterwarnings( r"ignore:Values in x were outside bounds during a minimize step, " r"clipping to bounds" ) @pytest.mark.parametrize("fitter", non_linear_fitters_bounds) def test_LSQ_SLSQP_with_constraints(self, fitter): """ Runs `LevMarLSQFitter`/`TRFLSQFitter` and `SLSQPLSQFitter` on a model with constraints. """ fitter = fitter() g1 = models.Gaussian1D(100, 5, stddev=1) g1.mean.fixed = True fslsqp = SLSQPLSQFitter() slsqp_model = fslsqp(g1, self.xdata, self.ydata) model = fitter(g1, self.xdata, self.ydata) assert_allclose(model.parameters, slsqp_model.parameters, rtol=10 ** (-4)) @pytest.mark.parametrize("fitter", non_linear_fitters_bounds) def test_non_linear_lsq_fitter_with_weights(self, fitter): """ Tests that issue #11581 has been solved. """ fitter = fitter() np.random.seed(42) norder = 2 fitter2 = LinearLSQFitter() model = models.Polynomial1D(norder) npts = 10000 c = [2.0, -10.0, 7.0] tw = np.random.uniform(0.0, 10.0, npts) tx = np.random.uniform(0.0, 10.0, npts) ty = c[0] + c[1] * tx + c[2] * (tx**2) ty += np.random.normal(0.0, 1.5, npts) with pytest.warns(AstropyUserWarning, match=r"Model is linear in parameters"): tf1 = fitter(model, tx, ty, weights=tw) tf2 = fitter2(model, tx, ty, weights=tw) assert_allclose(tf1.parameters, tf2.parameters, atol=10 ** (-16)) assert_allclose(tf1.parameters, c, rtol=10 ** (-2), atol=10 ** (-2)) model = models.Gaussian1D() if isinstance(fitter, (TRFLSQFitter, LMLSQFitter)): with pytest.warns( AstropyUserWarning, match=r"The fit may be unsuccessful; *." ): fitter(model, tx, ty, weights=tw) else: fitter(model, tx, ty, weights=tw) model = models.Polynomial2D(norder) nxpts = 100 nypts = 150 npts = nxpts * nypts c = [1.0, 4.0, 7.0, -8.0, -9.0, -3.0] tw = np.random.uniform(0.0, 10.0, npts).reshape(nxpts, nypts) tx = np.random.uniform(0.0, 10.0, npts).reshape(nxpts, nypts) ty = np.random.uniform(0.0, 10.0, npts).reshape(nxpts, nypts) tz = ( c[0] + c[1] * tx + c[2] * (tx**2) + c[3] * ty + c[4] * (ty**2) + c[5] * tx * ty ) tz += np.random.normal(0.0, 1.5, npts).reshape(nxpts, nypts) with pytest.warns(AstropyUserWarning, match=r"Model is linear in parameters"): tf1 = fitter(model, tx, ty, tz, weights=tw) tf2 = fitter2(model, tx, ty, tz, weights=tw) assert_allclose(tf1.parameters, tf2.parameters, atol=10 ** (-16)) assert_allclose(tf1.parameters, c, rtol=10 ** (-2), atol=10 ** (-2)) def test_simplex_lsq_fitter(self): """A basic test for the `SimplexLSQ` fitter.""" class Rosenbrock(Fittable2DModel): a = Parameter() b = Parameter() @staticmethod def evaluate(x, y, a, b): return (a - x) ** 2 + b * (y - x**2) ** 2 x = y = np.linspace(-3.0, 3.0, 100) with NumpyRNGContext(_RANDOM_SEED): z = Rosenbrock.evaluate(x, y, 1.0, 100.0) z += np.random.normal(0.0, 0.1, size=z.shape) fitter = SimplexLSQFitter() r_i = Rosenbrock(1, 100) r_f = fitter(r_i, x, y, z) assert_allclose(r_f.parameters, [1.0, 100.0], rtol=1e-2) @pytest.mark.parametrize("fitter", non_linear_fitters) def test_param_cov(self, fitter): """ Tests that the 'param_cov' fit_info entry gets the right answer for *linear* least squares, where the answer is exact """ fitter = fitter() a = 2 b = 100 with NumpyRNGContext(_RANDOM_SEED): x = np.linspace(0, 1, 100) # y scatter is amplitude ~1 to make sure covariance is # non-negligible y = x * a + b + np.random.randn(len(x)) # first compute the ordinary least squares covariance matrix X = np.vstack([x, np.ones(len(x))]).T beta = np.matmul(np.matmul(np.linalg.inv(np.matmul(X.T, X)), X.T), y.T) s2 = np.sum((y - np.matmul(X, beta).ravel()) ** 2) / (len(y) - len(beta)) olscov = np.linalg.inv(np.matmul(X.T, X)) * s2 # now do the non-linear least squares fit mod = models.Linear1D(a, b) with pytest.warns(AstropyUserWarning, match=r"Model is linear in parameters"): fmod = fitter(mod, x, y) assert_allclose(fmod.parameters, beta.ravel()) assert_allclose(olscov, fitter.fit_info["param_cov"]) @pytest.mark.parametrize("fitter", non_linear_fitters) def test_param_cov_with_uncertainties(self, fitter): """ Tests that the 'param_cov' fit_info entry gets the right answer for *linear* least squares, where the answer is exact """ fitter = fitter() a = 2 b = 100 with NumpyRNGContext(_RANDOM_SEED): x = np.linspace(0, 1, 100) # y scatter is amplitude ~1 to make sure covariance is # non-negligible y = x * a + b + np.random.normal(size=len(x)) sigma = np.random.normal(loc=1, scale=0.1, size=len(x)) # compute the ordinary least squares covariance matrix # accounting for measurement uncertainties `sigma` X = np.vstack([x, np.ones(len(x))]).T inv_N = np.linalg.inv(np.diag(sigma) ** 2) cov = np.linalg.inv(X.T @ inv_N @ X) beta = cov @ X.T @ inv_N @ y.T # now do the non-linear least squares fit mod = models.Linear1D(a, b) with pytest.warns(AstropyUserWarning, match=r"Model is linear in parameters"): fmod = fitter(mod, x, y, weights=sigma**-1) assert_allclose(fmod.parameters, beta.ravel()) assert_allclose(cov, fitter.fit_info["param_cov"])
TestNonLinearFitters
python
scipy__scipy
scipy/stats/tests/test_qmc.py
{ "start": 30482, "end": 33423 }
class ____(QMCEngineTests): qmce = qmc.Sobol can_scramble = True # theoretical values from Joe Kuo2010 unscramble_nd = np.array([[0., 0.], [0.5, 0.5], [0.75, 0.25], [0.25, 0.75], [0.375, 0.375], [0.875, 0.875], [0.625, 0.125], [0.125, 0.625]]) # theoretical values unknown: convergence properties checked scramble_nd = np.array([[0.25331921, 0.41371179], [0.8654213, 0.9821167], [0.70097554, 0.03664616], [0.18027647, 0.60895735], [0.10521339, 0.21897069], [0.53019685, 0.66619033], [0.91122276, 0.34580743], [0.45337471, 0.78912079]]) def test_warning(self): with pytest.warns(UserWarning, match=r"The balance properties of " r"Sobol' points"): engine = qmc.Sobol(1) engine.random(10) def test_random_base2(self): engine = qmc.Sobol(2, scramble=False) sample = engine.random_base2(2) assert_array_equal(self.unscramble_nd[:4], sample) # resampling still having N=2**n sample = engine.random_base2(2) assert_array_equal(self.unscramble_nd[4:8], sample) # resampling again but leading to N!=2**n with pytest.raises(ValueError, match=r"The balance properties of " r"Sobol' points"): engine.random_base2(2) def test_raise(self): with pytest.raises(ValueError, match=r"Maximum supported " r"dimensionality"): qmc.Sobol(qmc.Sobol.MAXDIM + 1) with pytest.raises(ValueError, match=r"Maximum supported " r"'bits' is 64"): qmc.Sobol(1, bits=65) def test_high_dim(self): engine = qmc.Sobol(1111, scramble=False) count1 = Counter(engine.random().flatten().tolist()) count2 = Counter(engine.random().flatten().tolist()) assert_equal(count1, Counter({0.0: 1111})) assert_equal(count2, Counter({0.5: 1111})) @pytest.mark.parametrize("bits", [2, 3]) def test_bits(self, bits): engine = qmc.Sobol(2, scramble=False, bits=bits) ns = 2**bits sample = engine.random(ns) assert_array_equal(self.unscramble_nd[:ns], sample) with pytest.raises(ValueError, match="increasing `bits`"): engine.random() def test_64bits(self): engine = qmc.Sobol(2, scramble=False, bits=64) sample = engine.random(8) assert_array_equal(self.unscramble_nd, sample)
TestSobol
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingIn2.py
{ "start": 85, "end": 585 }
class ____(enum.Enum): A = enum.auto() B = enum.auto() C = enum.auto() def func1(x: MyEnum): if x is MyEnum.C: return elif x in (MyEnum.A, MyEnum.B): reveal_type(x, expected_text="Literal[MyEnum.A, MyEnum.B]") else: reveal_type(x, expected_text="Never") def func2(x: MyEnum): if x in (MyEnum.A, MyEnum.B): reveal_type(x, expected_text="Literal[MyEnum.A, MyEnum.B]") else: reveal_type(x, expected_text="Literal[MyEnum.C]")
MyEnum
python
kamyu104__LeetCode-Solutions
Python/longest-valid-parentheses.py
{ "start": 723, "end": 1272 }
class ____(object): # @param s, a string # @return an integer def longestValidParentheses(self, s): longest, last, indices = 0, -1, [] for i in xrange(len(s)): if s[i] == '(': indices.append(i) elif not indices: last = i else: indices.pop() if not indices: longest = max(longest, i - last) else: longest = max(longest, i - indices[-1]) return longest
Solution2
python
PyCQA__pylint
doc/data/messages/t/too-few-public-methods/bad.py
{ "start": 0, "end": 272 }
class ____: # [too-few-public-methods] def __init__(self, name: str, fruit_of_residence: Fruit): self.name = name self.fruit_of_residence = fruit_of_residence def bore(self): print(f"{self.name} is boring into {self.fruit_of_residence}")
Worm
python
docker__docker-py
tests/integration/api_container_test.py
{ "start": 52024, "end": 53066 }
class ____(BaseAPIIntegrationTest): def test_pause_unpause(self): container = self.client.create_container(TEST_IMG, ['sleep', '9999']) id = container['Id'] self.tmp_containers.append(id) self.client.start(container) self.client.pause(id) container_info = self.client.inspect_container(id) assert 'State' in container_info state = container_info['State'] assert 'ExitCode' in state assert state['ExitCode'] == 0 assert 'Running' in state assert state['Running'] is True assert 'Paused' in state assert state['Paused'] is True self.client.unpause(id) container_info = self.client.inspect_container(id) assert 'State' in container_info state = container_info['State'] assert 'ExitCode' in state assert state['ExitCode'] == 0 assert 'Running' in state assert state['Running'] is True assert 'Paused' in state assert state['Paused'] is False
PauseTest
python
scipy__scipy
scipy/sparse/_coo.py
{ "start": 70441, "end": 74632 }
class ____(spmatrix, _coo_base): """ A sparse matrix in COOrdinate format. Also known as the 'ijv' or 'triplet' format. This can be instantiated in several ways: coo_matrix(D) where D is a 2-D ndarray coo_matrix(S) with another sparse array or matrix S (equivalent to S.tocoo()) coo_matrix((M, N), [dtype]) to construct an empty matrix with shape (M, N) dtype is optional, defaulting to dtype='d'. coo_matrix((data, (i, j)), [shape=(M, N)]) to construct from three arrays: 1. data[:] the entries of the matrix, in any order 2. i[:] the row indices of the matrix entries 3. j[:] the column indices of the matrix entries Where ``A[i[k], j[k]] = data[k]``. When shape is not specified, it is inferred from the index arrays Attributes ---------- dtype : dtype Data type of the matrix shape : 2-tuple Shape of the matrix ndim : int Number of dimensions (this is always 2) nnz size data COO format data array of the matrix row COO format row index array of the matrix col COO format column index array of the matrix has_canonical_format : bool Whether the matrix has sorted indices and no duplicates format T Notes ----- Sparse matrices can be used in arithmetic operations: they support addition, subtraction, multiplication, division, and matrix power. Advantages of the COO format - facilitates fast conversion among sparse formats - permits duplicate entries (see example) - very fast conversion to and from CSR/CSC formats Disadvantages of the COO format - does not directly support: + arithmetic operations + slicing Intended Usage - COO is a fast format for constructing sparse matrices - Once a COO matrix has been constructed, convert to CSR or CSC format for fast arithmetic and matrix vector operations - By default when converting to CSR or CSC format, duplicate (i,j) entries will be summed together. This facilitates efficient construction of finite element matrices and the like. (see example) Canonical format - Entries and coordinates sorted by row, then column. - There are no duplicate entries (i.e. duplicate (i,j) locations) - Data arrays MAY have explicit zeros. Examples -------- >>> # Constructing an empty matrix >>> import numpy as np >>> from scipy.sparse import coo_matrix >>> coo_matrix((3, 4), dtype=np.int8).toarray() array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], dtype=int8) >>> # Constructing a matrix using ijv format >>> row = np.array([0, 3, 1, 0]) >>> col = np.array([0, 3, 1, 2]) >>> data = np.array([4, 5, 7, 9]) >>> coo_matrix((data, (row, col)), shape=(4, 4)).toarray() array([[4, 0, 9, 0], [0, 7, 0, 0], [0, 0, 0, 0], [0, 0, 0, 5]]) >>> # Constructing a matrix with duplicate coordinates >>> row = np.array([0, 0, 1, 3, 1, 0, 0]) >>> col = np.array([0, 2, 1, 3, 1, 0, 0]) >>> data = np.array([1, 1, 1, 1, 1, 1, 1]) >>> coo = coo_matrix((data, (row, col)), shape=(4, 4)) >>> # Duplicate coordinates are maintained until implicitly or explicitly summed >>> np.max(coo.data) 1 >>> coo.toarray() array([[3, 0, 1, 0], [0, 2, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1]]) """ def __setstate__(self, state): if 'coords' not in state: # For retro-compatibility with the previous attributes # storing nnz coordinates for 2D COO matrix. state['coords'] = (state.pop('row'), state.pop('col')) self.__dict__.update(state) def __getitem__(self, key): raise TypeError("'coo_matrix' object is not subscriptable") def __setitem__(self, key): raise TypeError("'coo_matrix' object does not support item assignment")
coo_matrix
python
scipy__scipy
scipy/stats/_warnings_errors.py
{ "start": 606, "end": 927 }
class ____(DegenerateDataWarning): """Warns when all values in data are nearly equal.""" def __init__(self, msg=None): if msg is None: msg = ("All values in data are nearly equal; " "results may not be reliable.") self.args = (msg,) # Errors
NearConstantInputWarning
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/roles.py
{ "start": 1702, "end": 1795 }
class ____(SQLRole): __slots__ = () _role_name = "Column expression"
ColumnArgumentRole
python
django__django
tests/backends/sqlite/tests.py
{ "start": 11136, "end": 13220 }
class ____(SimpleTestCase): databases = {"default"} def test_default_transaction_mode(self): with CaptureQueriesContext(connection) as captured_queries: with transaction.atomic(): pass begin_query, commit_query = captured_queries self.assertEqual(begin_query["sql"], "BEGIN") self.assertEqual(commit_query["sql"], "COMMIT") def test_invalid_transaction_mode(self): msg = ( "settings.DATABASES['default']['OPTIONS']['transaction_mode'] is " "improperly configured to 'invalid'. Use one of 'DEFERRED', 'EXCLUSIVE', " "'IMMEDIATE', or None." ) with self.change_transaction_mode("invalid") as new_connection: with self.assertRaisesMessage(ImproperlyConfigured, msg): new_connection.ensure_connection() def test_valid_transaction_modes(self): valid_transaction_modes = ("deferred", "immediate", "exclusive") for transaction_mode in valid_transaction_modes: with ( self.subTest(transaction_mode=transaction_mode), self.change_transaction_mode(transaction_mode) as new_connection, CaptureQueriesContext(new_connection) as captured_queries, ): new_connection.set_autocommit( False, force_begin_transaction_with_broken_autocommit=True ) new_connection.commit() expected_transaction_mode = transaction_mode.upper() begin_sql = captured_queries[0]["sql"] self.assertEqual(begin_sql, f"BEGIN {expected_transaction_mode}") @contextmanager def change_transaction_mode(self, transaction_mode): new_connection = connection.copy() new_connection.settings_dict["OPTIONS"] = { **new_connection.settings_dict["OPTIONS"], "transaction_mode": transaction_mode, } try: yield new_connection finally: new_connection._close()
TestTransactionMode
python
kamyu104__LeetCode-Solutions
Python/count-houses-in-a-circular-street-ii.py
{ "start": 56, "end": 213 }
class ____: def closeDoor(self): pass def isDoorOpen(self): pass def moveRight(self): pass # constructive algorithms
Street
python
pallets__flask
src/flask/testing.py
{ "start": 8823, "end": 10114 }
class ____(CliRunner): """A :class:`~click.testing.CliRunner` for testing a Flask app's CLI commands. Typically created using :meth:`~flask.Flask.test_cli_runner`. See :ref:`testing-cli`. """ def __init__(self, app: Flask, **kwargs: t.Any) -> None: self.app = app super().__init__(**kwargs) def invoke( # type: ignore self, cli: t.Any = None, args: t.Any = None, **kwargs: t.Any ) -> Result: """Invokes a CLI command in an isolated environment. See :meth:`CliRunner.invoke <click.testing.CliRunner.invoke>` for full method documentation. See :ref:`testing-cli` for examples. If the ``obj`` argument is not given, passes an instance of :class:`~flask.cli.ScriptInfo` that knows how to load the Flask app being tested. :param cli: Command object to invoke. Default is the app's :attr:`~flask.app.Flask.cli` group. :param args: List of strings to invoke the command with. :return: a :class:`~click.testing.Result` object. """ if cli is None: cli = self.app.cli if "obj" not in kwargs: kwargs["obj"] = ScriptInfo(create_app=lambda: self.app) return super().invoke(cli, args, **kwargs)
FlaskCliRunner
python
dagster-io__dagster
python_modules/dagster/dagster/_config/snap.py
{ "start": 6155, "end": 6260 }
class ____: value: str description: Optional[str] @whitelist_for_serdes @record
ConfigEnumValueSnap
python
weaviate__weaviate-python-client
weaviate/collections/data/executor.py
{ "start": 1527, "end": 28273 }
class ____(Generic[ConnectionType, Properties]): def __init__( self, connection: ConnectionType, name: str, consistency_level: Optional[ConsistencyLevel], tenant: Optional[str], validate_arguments: bool, type_: Optional[Type[Properties]] = None, ) -> None: self._connection = connection self.name = name self._consistency_level = consistency_level self._tenant = tenant self._validate_arguments = validate_arguments self.__batch_grpc = _BatchGRPC( weaviate_version=connection._weaviate_version, consistency_level=consistency_level, grpc_max_msg_size=connection._grpc_max_msg_size, ) self.__batch_rest = _BatchREST(consistency_level=consistency_level) self.__batch_delete = _BatchDeleteGRPC( weaviate_version=connection._weaviate_version, consistency_level=consistency_level, ) self._type = type_ def insert( self, properties: Properties, references: Optional[ReferenceInputs] = None, uuid: Optional[UUID] = None, vector: Optional[VECTORS] = None, ) -> executor.Result[uuid_package.UUID]: """Insert a single object into the collection. Args: properties: The properties of the object, REQUIRED. references: Any references to other objects in Weaviate. uuid: The UUID of the object. If not provided, a random UUID will be generated. vector: The vector(s) of the object. Supported types are: - for single vectors: `list`, 'numpy.ndarray`, `torch.Tensor`, `tf.Tensor`, `pd.Series` and `pl.Series`, by default None. - for named vectors: Dict[str, *list above*], where the string is the name of the vector. Returns: The UUID of the inserted object. Raises: weaviate.exceptions.UnexpectedStatusCodeError: If any unexpected error occurs during the insert operatio, for example the given UUID already exists. """ path = "/objects" if self._validate_arguments: _validate_input( [ _ValidateArgument(expected=[UUID, None], name="uuid", value=uuid), _ValidateArgument(expected=[Mapping], name="properties", value=properties), _ValidateArgument( expected=[Mapping, None], name="references", value=references ), ], ) props = self.__serialize_props(properties) if properties is not None else {} refs = self.__serialize_refs(references) if references is not None else {} weaviate_obj: Dict[str, Any] = { "class": self.name, "properties": {**props, **refs}, "id": str(uuid if uuid is not None else uuid_package.uuid4()), } if vector is not None: weaviate_obj = self.__parse_vector(weaviate_obj, vector) params, weaviate_obj = self.__apply_context_to_params_and_object({}, weaviate_obj) def resp(res: Response) -> uuid_package.UUID: return uuid_package.UUID(weaviate_obj["id"]) return executor.execute( response_callback=resp, method=self._connection.post, path=path, weaviate_object=weaviate_obj, params=params, error_msg="Object was not added", status_codes=_ExpectedStatusCodes(ok_in=200, error="insert object"), ) def insert_many( self, objects: Sequence[Union[Properties, DataObject[Properties, Optional[ReferenceInputs]]]], ) -> executor.Result[BatchObjectReturn]: """Insert multiple objects into the collection. Args: objects: The objects to insert. This can be either a list of `Properties` or `DataObject[Properties, ReferenceInputs]` If you didn't set `data_model` then `Properties` will be `Data[str, Any]` in which case you can insert simple dictionaries here. If you want to insert references, vectors, or UUIDs alongside your properties, you will have to use `DataObject` instead. Raises: weaviate.exceptions.WeaviateGRPCBatchError: If any unexpected error occurs during the batch operation. weaviate.exceptions.WeaviateInsertInvalidPropertyError: If a property is invalid. I.e., has name `id` or `vector`, which are reserved. weaviate.exceptions.WeaviateInsertManyAllFailedError: If every object in the batch fails to be inserted. The exception message contains details about the failure. """ objs = [ ( _BatchObject( collection=self.name, vector=obj.vector, uuid=str(obj.uuid if obj.uuid is not None else uuid_package.uuid4()), properties=cast(dict, obj.properties), tenant=self._tenant, references=obj.references, index=idx, ) if isinstance(obj, DataObject) else _BatchObject( collection=self.name, vector=None, uuid=str(uuid_package.uuid4()), properties=cast(dict, obj), tenant=self._tenant, references=None, index=idx, ) ) for idx, obj in enumerate(objects) ] def resp(res: BatchObjectReturn) -> BatchObjectReturn: if (n_obj_errs := len(res.errors)) > 0: logger.error( { "message": f"Failed to send {n_obj_errs} objects in a batch of {len(objs)}. Please inspect the errors variable of the returned object for more information.", "errors": res.errors, } ) return res return executor.execute( response_callback=resp, method=self.__batch_grpc.objects, connection=self._connection, objects=objs, timeout=self._connection.timeout_config.insert, max_retries=2, ) def exists(self, uuid: UUID) -> executor.Result[bool]: """Check for existence of a single object in the collection. Args: uuid: The UUID of the object. Returns: True if objects exists and False if not Raises: weaviate.exceptions.UnexpectedStatusCodeError: If any unexpected error occurs during the operation. """ _validate_input(_ValidateArgument(expected=[UUID], name="uuid", value=uuid)) path = "/objects/" + self.name + "/" + str(uuid) params = self.__apply_context({}) def resp(res: Response) -> bool: return res.status_code == 204 return executor.execute( response_callback=resp, method=self._connection.head, path=path, params=params, error_msg="object existence", status_codes=_ExpectedStatusCodes(ok_in=[204, 404], error="object existence"), ) def replace( self, uuid: UUID, properties: Properties, references: Optional[ReferenceInputs] = None, vector: Optional[VECTORS] = None, ) -> executor.Result[None]: """Replace an object in the collection. This is equivalent to a PUT operation. Args: uuid: The UUID of the object, REQUIRED. properties: The properties of the object, REQUIRED. references: Any references to other objects in Weaviate, REQUIRED. vector: The vector(s) of the object. Supported types are: - for single vectors: `list`, 'numpy.ndarray`, `torch.Tensor`, `tf.Tensor`, `pd.Series` and `pl.Series`, by default None. - for named vectors: Dict[str, *list above*], where the string is the name of the vector. Raises: weaviate.exceptions.WeaviateConnectionError: If the network connection to Weaviate fails. weaviate.exceptions.WeaviateInvalidInputError: If any of the arguments are invalid. weaviate.exceptions.UnexpectedStatusCodeError: If Weaviate reports a non-OK status. weaviate.exceptions.WeaviateInsertInvalidPropertyError: If a property is invalid. I.e., has name `id` or `vector`, which are reserved. """ path = f"/objects/{self.name}/{uuid}" if self._validate_arguments: _validate_input( [ _ValidateArgument(expected=[UUID], name="uuid", value=uuid), _ValidateArgument(expected=[Mapping], name="properties", value=properties), _ValidateArgument( expected=[Mapping, None], name="references", value=references ), ] ) props = self.__serialize_props(properties) if properties is not None else {} refs = self.__serialize_refs(references) if references is not None else {} weaviate_obj: Dict[str, Any] = { "class": self.name, "properties": {**props, **refs}, } if vector is not None: weaviate_obj = self.__parse_vector(weaviate_obj, vector) params, weaviate_obj = self.__apply_context_to_params_and_object({}, weaviate_obj) weaviate_obj["id"] = str(uuid) # must add ID to payload for PUT request def resp(res: Response) -> None: return None return executor.execute( response_callback=resp, method=self._connection.put, path=path, weaviate_object=weaviate_obj, params=params, error_msg="Object was not replaced.", status_codes=_ExpectedStatusCodes(ok_in=200, error="replace object"), ) def update( self, uuid: UUID, properties: Optional[Properties] = None, references: Optional[ReferenceInputs] = None, vector: Optional[VECTORS] = None, ) -> executor.Result[None]: """Update an object in the collection. This is equivalent to a PATCH operation. Args: uuid: The UUID of the object, REQUIRED. properties: The properties of the object. references: Any references to other objects in Weaviate. vector: The vector(s) of the object. Supported types are: - for single vectors: `list`, 'numpy.ndarray`, `torch.Tensor`, `tf.Tensor`, `pd.Series` and `pl.Series`, by default None. - for named vectors: Dict[str, *list above*], where the string is the name of the vector. """ path = f"/objects/{self.name}/{uuid}" if self._validate_arguments: _validate_input( [ _ValidateArgument(expected=[UUID], name="uuid", value=uuid), _ValidateArgument( expected=[Mapping, None], name="properties", value=properties ), _ValidateArgument( expected=[Mapping, None], name="references", value=references ), ], ) props = self.__serialize_props(properties) if properties is not None else {} refs = self.__serialize_refs(references) if references is not None else {} weaviate_obj: Dict[str, Any] = { "class": self.name, "properties": {**props, **refs}, } if vector is not None: weaviate_obj = self.__parse_vector(weaviate_obj, vector) params, weaviate_obj = self.__apply_context_to_params_and_object({}, weaviate_obj) def resp(res: Response) -> None: return None return executor.execute( response_callback=resp, method=self._connection.patch, path=path, weaviate_object=weaviate_obj, params=params, error_msg="Object was not updated.", status_codes=_ExpectedStatusCodes(ok_in=[200, 204], error="update object"), ) def reference_add( self, from_uuid: UUID, from_property: str, to: SingleReferenceInput, ) -> executor.Result[None]: """Create a reference between an object in this collection and any other object in Weaviate. Args: from_uuid: The UUID of the object in this collection, REQUIRED. from_property: The name of the property in the object in this collection, REQUIRED. to: The reference to add, REQUIRED. Raises: weaviate.exceptions.WeaviateConnectionError: If the network connection to Weaviate fails. weaviate.exceptions.UnexpectedStatusCodeError: If Weaviate reports a non-OK status. """ params: Dict[str, str] = {} path = f"/objects/{self.name}/{from_uuid}/references/{from_property}" if self._validate_arguments: _validate_input( [ _ValidateArgument(expected=[UUID], name="from_uuid", value=from_uuid), _ValidateArgument(expected=[str], name="from_property", value=from_property), _ValidateArgument( expected=[UUID, ReferenceToMulti], name="references", value=to ), ], ) if isinstance(to, ReferenceToMulti): ref = _Reference(target_collection=to.target_collection, uuids=to.uuids) else: ref = _Reference(target_collection=None, uuids=to) if ref.is_one_to_many: raise WeaviateInvalidInputError( "reference_add does not support adding multiple objects to a reference at once. Use reference_add_many or reference_replace instead." ) if isinstance(self._connection, ConnectionAsync): async def _execute() -> None: await asyncio.gather( *[ executor.aresult( self._connection.post( path=path, weaviate_object=beacon, params=self.__apply_context(params), error_msg="Reference was not added.", status_codes=_ExpectedStatusCodes( ok_in=200, error="add reference to object" ), ) ) for beacon in ref._to_beacons() ] ) return _execute() for beacon in ref._to_beacons(): executor.result( self._connection.post( path=path, weaviate_object=beacon, params=self.__apply_context(params), error_msg="Reference was not added.", status_codes=_ExpectedStatusCodes(ok_in=200, error="add reference to object"), ) ) def reference_add_many( self, refs: List[DataReferences], ) -> executor.Result[BatchReferenceReturn]: """Create multiple references on a property in batch between objects in this collection and any other object in Weaviate. Args: refs: The references to add including the prop name, from UUID, and to UUID. Returns: A `BatchReferenceReturn` object containing the results of the batch operation. Raises: weaviate.exceptions.WeaviateConnectionError: If the network connection to Weaviate fails. weaviate.UnexpectedStatusCodeErro: If Weaviate reports a non-OK status. """ batch = [ _BatchReference( from_=f"{BEACON}{self.name}/{ref.from_uuid}/{ref.from_property}", to=beacon, tenant=self._tenant, from_uuid=str(ref.from_uuid), to_uuid=None, # not relevant here, this entry is only needed for the batch module index=idx, ) for idx, ref in enumerate(refs) for beacon in ref._to_beacons() ] return self.__batch_rest.references(self._connection, references=list(batch)) def reference_delete( self, from_uuid: UUID, from_property: str, to: SingleReferenceInput, ) -> executor.Result[None]: """Delete a reference from an object within the collection. Args: from_uuid: The UUID of the object in this collection, REQUIRED. from_property: The name of the property in the object in this collection from which the reference should be deleted, REQUIRED. to: The reference to delete, REQUIRED. """ params: Dict[str, str] = {} path = f"/objects/{self.name}/{from_uuid}/references/{from_property}" if self._validate_arguments: _validate_input( [ _ValidateArgument(expected=[UUID], name="from_uuid", value=from_uuid), _ValidateArgument(expected=[str], name="from_property", value=from_property), _ValidateArgument( expected=[UUID, ReferenceToMulti], name="references", value=to ), ] ) if isinstance(to, ReferenceToMulti): ref = _Reference(target_collection=to.target_collection, uuids=to.uuids) else: ref = _Reference(target_collection=None, uuids=to) if ref.is_one_to_many: raise WeaviateInvalidInputError( "reference_delete does not support deleting multiple objects from a reference at once. Use reference_replace instead." ) if isinstance(self._connection, ConnectionAsync): async def _execute() -> None: await asyncio.gather( *[ executor.aresult( self._connection.delete( path=path, weaviate_object=beacon, params=self.__apply_context(params), error_msg="Reference was not deleted.", status_codes=_ExpectedStatusCodes( ok_in=204, error="delete reference from object" ), ) ) for beacon in ref._to_beacons() ] ) return _execute() for beacon in ref._to_beacons(): executor.result( self._connection.delete( path=path, weaviate_object=beacon, params=self.__apply_context(params), error_msg="Reference was not deleted.", status_codes=_ExpectedStatusCodes( ok_in=204, error="delete reference from object" ), ) ) def reference_replace( self, from_uuid: UUID, from_property: str, to: ReferenceInput, ) -> executor.Result[None]: """Replace a reference of an object within the collection. Args: from_uuid: The UUID of the object in this collection, REQUIRED. from_property: The name of the property in the object in this collection from which the reference should be replaced, REQUIRED. to: The reference to replace, REQUIRED. """ params: Dict[str, str] = {} path = f"/objects/{self.name}/{from_uuid}/references/{from_property}" if self._validate_arguments: _validate_input( [ _ValidateArgument(expected=[UUID], name="from_uuid", value=from_uuid), _ValidateArgument(expected=[str], name="from_property", value=from_property), _ValidateArgument( expected=[ UUID, ReferenceToMulti, List[str], List[uuid_package.UUID], List[UUID], ], name="references", value=to, ), ] ) if isinstance(to, ReferenceToMulti): ref = _Reference(target_collection=to.target_collection, uuids=to.uuids) else: ref = _Reference(target_collection=None, uuids=to) def resp(res: Response) -> None: return None return executor.execute( response_callback=resp, method=self._connection.put, path=path, weaviate_object=ref._to_beacons(), params=self.__apply_context(params), error_msg="Reference was not replaced.", status_codes=_ExpectedStatusCodes(ok_in=200, error="replace reference on object"), ) def delete_by_id(self, uuid: UUID) -> executor.Result[bool]: """Delete an object from the collection based on its UUID. Args: uuid: The UUID of the object to delete, REQUIRED. """ path = f"/objects/{self.name}/{uuid}" def resp(res: Response) -> bool: return res.status_code == 204 return executor.execute( response_callback=resp, method=self._connection.delete, path=path, params=self.__apply_context({}), error_msg="Object could not be deleted.", status_codes=_ExpectedStatusCodes(ok_in=[204, 404], error="delete object"), ) @overload def delete_many( self, where: _Filters, *, verbose: Literal[False] = False, dry_run: bool = False ) -> executor.Result[DeleteManyReturn[None]]: ... @overload def delete_many( self, where: _Filters, *, verbose: Literal[True], dry_run: bool = False ) -> executor.Result[DeleteManyReturn[List[DeleteManyObject]]]: ... @overload def delete_many( self, where: _Filters, *, verbose: bool = False, dry_run: bool = False ) -> executor.Result[ Union[DeleteManyReturn[List[DeleteManyObject]], DeleteManyReturn[None]] ]: ... def delete_many( self, where: _Filters, *, verbose: bool = False, dry_run: bool = False ) -> executor.Result[Union[DeleteManyReturn[List[DeleteManyObject]], DeleteManyReturn[None]]]: """Delete multiple objects from the collection based on a filter. Args: where: The filter to apply. This filter is the same that is used when performing queries and has the same syntax, REQUIRED. verbose: Whether to return the deleted objects in the response. dry_run: Whether to perform a dry run. If set to `True`, the objects will not be deleted, but the response will contain the objects that would have been deleted. Raises: weaviate.exceptions.WeaviateConnectionError: If the network connection to Weaviate fails. weaviate.exceptions.UnexpectedStatusCodeError: If Weaviate reports a non-OK status. """ _ValidateArgument(expected=[_Filters], name="where", value=where) return self.__batch_delete.batch_delete( self._connection, name=self.name, filters=where, verbose=verbose, dry_run=dry_run, tenant=self._tenant, ) def __apply_context(self, params: Dict[str, Any]) -> Dict[str, Any]: if self._tenant is not None: params["tenant"] = self._tenant if self._consistency_level is not None: params["consistency_level"] = self._consistency_level.value return params def __apply_context_to_params_and_object( self, params: Dict[str, Any], obj: Dict[str, Any] ) -> Tuple[Dict[str, Any], Dict[str, Any]]: if self._tenant is not None: obj["tenant"] = self._tenant if self._consistency_level is not None: params["consistency_level"] = self._consistency_level.value return params, obj def __serialize_props(self, props: Properties) -> Dict[str, Any]: return {key: self.__serialize_primitive(val) for key, val in props.items()} def __serialize_refs(self, refs: ReferenceInputs) -> Dict[str, Any]: return { key: ( val._to_beacons() if isinstance(val, _Reference) or isinstance(val, ReferenceToMulti) else _Reference(target_collection=None, uuids=val)._to_beacons() ) for key, val in refs.items() } def __serialize_primitive(self, value: WeaviateField) -> Any: if isinstance(value, str) or isinstance(value, int) or isinstance(value, float): return value if isinstance(value, uuid_package.UUID): return str(value) if isinstance(value, datetime.datetime): return _datetime_to_string(value) if isinstance(value, GeoCoordinate): return value._to_dict() if isinstance(value, PhoneNumber): return value._to_dict() if isinstance(value, _PhoneNumber): raise WeaviateInvalidInputError( "Cannot use _PhoneNumber when inserting a phone number. Use PhoneNumber instead." ) if isinstance(value, Mapping): return {key: self.__serialize_primitive(val) for key, val in value.items()} if isinstance(value, Sequence): return [self.__serialize_primitive(val) for val in value] if value is None: return value raise WeaviateInvalidInputError( f"Cannot serialize value of type {type(value)} to Weaviate." ) def __parse_vector(self, obj: Dict[str, Any], vector: VECTORS) -> Dict[str, Any]: if isinstance(vector, dict): obj["vectors"] = {key: _get_vector_v4(val) for key, val in vector.items()} else: obj["vector"] = _get_vector_v4(vector) return obj
_DataCollectionExecutor
python
pytest-dev__pytest
src/_pytest/pathlib.py
{ "start": 15096, "end": 15262 }
class ____(Enum): """Possible values for `mode` parameter of `import_path`.""" prepend = "prepend" append = "append" importlib = "importlib"
ImportMode
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1297402, "end": 1299945 }
class ____(sgqlc.types.Type, Node): """Information about a specific package version.""" __schema__ = github_schema __field_names__ = ("files", "package", "platform", "pre_release", "readme", "release", "statistics", "summary", "version") files = sgqlc.types.Field( sgqlc.types.non_null(PackageFileConnection), graphql_name="files", args=sgqlc.types.ArgDict( ( ( "order_by", sgqlc.types.Arg(PackageFileOrder, graphql_name="orderBy", default={"field": "CREATED_AT", "direction": "ASC"}), ), ("after", sgqlc.types.Arg(String, graphql_name="after", default=None)), ("before", sgqlc.types.Arg(String, graphql_name="before", default=None)), ("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)), ("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)), ) ), ) """List of files associated with this package version Arguments: * `order_by` (`PackageFileOrder`): Ordering of the returned package files. (default: `{field: CREATED_AT, direction: ASC}`) * `after` (`String`): Returns the elements in the list that come after the specified cursor. * `before` (`String`): Returns the elements in the list that come before the specified cursor. * `first` (`Int`): Returns the first _n_ elements from the list. * `last` (`Int`): Returns the last _n_ elements from the list. """ package = sgqlc.types.Field(Package, graphql_name="package") """The package associated with this version.""" platform = sgqlc.types.Field(String, graphql_name="platform") """The platform this version was built for.""" pre_release = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="preRelease") """Whether or not this version is a pre-release.""" readme = sgqlc.types.Field(String, graphql_name="readme") """The README of this package version.""" release = sgqlc.types.Field("Release", graphql_name="release") """The release associated with this package version.""" statistics = sgqlc.types.Field(PackageVersionStatistics, graphql_name="statistics") """Statistics about package activity.""" summary = sgqlc.types.Field(String, graphql_name="summary") """The package version summary.""" version = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="version") """The version string."""
PackageVersion
python
getsentry__sentry
tests/sentry/sudo/test_views.py
{ "start": 6079, "end": 6600 }
class ____(BaseTestCase): def test_redirect_to_sudo_simple(self) -> None: response = redirect_to_sudo("/foo") self.assertEqual(response.status_code, 302) self.assertEqual(response["Location"], "/account/sudo/?next=/foo") def test_redirect_to_sudo_with_querystring(self) -> None: response = redirect_to_sudo("/foo?foo=bar") self.assertEqual(response.status_code, 302) self.assertEqual(response["Location"], "/account/sudo/?next=/foo%3Ffoo%3Dbar")
RedirectToSudoTestCase
python
walkccc__LeetCode
solutions/2560. House Robber IV/2560.py
{ "start": 0, "end": 375 }
class ____: def minCapability(self, nums: list[int], k: int) -> int: def numStolenHouses(capacity: int) -> int: stolenHouses = 0 i = 0 while i < len(nums): if nums[i] <= capacity: stolenHouses += 1 i += 1 i += 1 return stolenHouses return bisect.bisect_left(range(max(nums)), k, key=numStolenHouses)
Solution
python
getsentry__sentry
src/sentry/dashboards/endpoints/organization_dashboard_widget_details.py
{ "start": 567, "end": 1988 }
class ____(OrganizationEndpoint): publish_status = { "POST": ApiPublishStatus.PRIVATE, } owner = ApiOwner.DASHBOARDS permission_classes = (OrganizationDashboardsPermission,) def post(self, request: Request, organization: Organization) -> Response: """ Validate a Widget ````````````````` Ensure that a dashboard widget contains a valid queries, and has a high chance of success when the dashboard is saved. """ if not features.has("organizations:dashboards-edit", organization, actor=request.user): return Response(status=404) serializer = DashboardWidgetSerializer( data=request.data, context={ "organization": organization, "projects": self.get_projects(request, organization), "displayType": request.data.get("displayType"), "environment": request.GET.getlist("environment"), "request": request, }, ) if not serializer.is_valid(): errors = serializer.errors.copy() # need to include warnings even if there are errors errors.update({"warnings": serializer.query_warnings}) return Response(errors, status=400) return Response({"warnings": serializer.query_warnings}, status=200)
OrganizationDashboardWidgetDetailsEndpoint
python
openai__openai-python
src/openai/types/realtime/realtime_conversation_item_function_call_output.py
{ "start": 247, "end": 1103 }
class ____(BaseModel): call_id: str """The ID of the function call this output is for.""" output: str """ The output of the function call, this is free text and can contain any information or simply be empty. """ type: Literal["function_call_output"] """The type of the item. Always `function_call_output`.""" id: Optional[str] = None """The unique ID of the item. This may be provided by the client or generated by the server. """ object: Optional[Literal["realtime.item"]] = None """Identifier for the API object being returned - always `realtime.item`. Optional when creating a new item. """ status: Optional[Literal["completed", "incomplete", "in_progress"]] = None """The status of the item. Has no effect on the conversation."""
RealtimeConversationItemFunctionCallOutput
python
pydata__xarray
asv_bench/benchmarks/interp.py
{ "start": 377, "end": 1945 }
class ____: def setup(self, *args, **kwargs): self.ds = xr.Dataset( { "var1": (("x", "y"), randn_xy), "var2": (("x", "t"), randn_xt), "var3": (("t",), randn_t), "var4": (("z",), np.array(["text"])), "var5": (("k",), np.array(["a", "b", "c"])), }, coords={ "x": np.arange(nx), "y": np.linspace(0, 1, ny), "t": pd.date_range("1970-01-01", periods=nt, freq="D"), "x_coords": ("x", np.linspace(1.1, 2.1, nx)), "z": np.array([1]), "k": np.linspace(0, nx, 3), }, ) @parameterized(["method", "is_short"], (["linear", "cubic"], [True, False])) def time_interpolation_numeric_1d(self, method, is_short): new_x = new_x_short if is_short else new_x_long self.ds.interp(x=new_x, method=method).compute() @parameterized(["method"], (["linear", "nearest"])) def time_interpolation_numeric_2d(self, method): self.ds.interp(x=new_x_long, y=new_y_long, method=method).compute() @parameterized(["is_short"], ([True, False])) def time_interpolation_string_scalar(self, is_short): new_z = new_x_short if is_short else new_x_long self.ds.interp(z=new_z).compute() @parameterized(["is_short"], ([True, False])) def time_interpolation_string_1d(self, is_short): new_k = new_x_short if is_short else new_x_long self.ds.interp(k=new_k).compute()
Interpolation
python
huggingface__transformers
src/transformers/models/hgnet_v2/modeling_hgnet_v2.py
{ "start": 1633, "end": 1859 }
class ____(PreTrainedModel): config: HGNetV2Config base_model_prefix = "hgnetv2" main_input_name = "pixel_values" input_modalities = ("image",) _no_split_modules = ["HGNetV2BasicLayer"]
HGNetV2PreTrainedModel
python
huggingface__transformers
src/transformers/models/sew_d/modeling_sew_d.py
{ "start": 11870, "end": 12876 }
class ____(GradientCheckpointingLayer): def __init__(self, config, layer_id=0): super().__init__() self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1 self.out_conv_dim = config.conv_dim[layer_id] self.conv = nn.Conv1d( self.in_conv_dim, self.out_conv_dim, kernel_size=config.conv_kernel[layer_id], stride=config.conv_stride[layer_id], bias=config.conv_bias, ) self.activation = ACT2FN[config.feat_extract_activation] self.layer_norm = nn.GroupNorm(num_groups=self.out_conv_dim, num_channels=self.out_conv_dim, affine=True) def forward(self, hidden_states): hidden_states = self.conv(hidden_states) hidden_states = self.layer_norm(hidden_states) hidden_states = self.activation(hidden_states) return hidden_states # Copied from transformers.models.sew.modeling_sew.SEWPositionalConvEmbedding with SEW->SEWD
SEWDGroupNormConvLayer
python
dagster-io__dagster
helm/dagster/schema/schema/charts/dagster/subschema/webserver.py
{ "start": 129, "end": 246 }
class ____(BaseModel): host: str port: int name: Optional[str] = None ssl: Optional[bool] = None
Server
python
google__flatbuffers
tests/py_test.py
{ "start": 85001, "end": 86692 }
class ____(unittest.TestCase): def test_object_is_nested_error(self): b = flatbuffers.Builder(0) b.StartObject(0) assertRaises( self, lambda: b.StartObject(0), flatbuffers.builder.IsNestedError ) def test_object_is_not_nested_error(self): b = flatbuffers.Builder(0) assertRaises( self, lambda: b.EndObject(), flatbuffers.builder.IsNotNestedError ) def test_struct_is_not_inline_error(self): b = flatbuffers.Builder(0) b.StartObject(0) assertRaises( self, lambda: b.PrependStructSlot(0, 1, 0), flatbuffers.builder.StructIsNotInlineError, ) def test_unreachable_error(self): b = flatbuffers.Builder(0) assertRaises( self, lambda: b.PrependUOffsetTRelative(1), flatbuffers.builder.OffsetArithmeticError, ) def test_create_shared_string_is_nested_error(self): b = flatbuffers.Builder(0) b.StartObject(0) s = 'test1' assertRaises( self, lambda: b.CreateSharedString(s), flatbuffers.builder.IsNestedError ) def test_create_string_is_nested_error(self): b = flatbuffers.Builder(0) b.StartObject(0) s = 'test1' assertRaises( self, lambda: b.CreateString(s), flatbuffers.builder.IsNestedError ) def test_create_byte_vector_is_nested_error(self): b = flatbuffers.Builder(0) b.StartObject(0) s = b'test1' assertRaises( self, lambda: b.CreateByteVector(s), flatbuffers.builder.IsNestedError ) def test_finished_bytes_error(self): b = flatbuffers.Builder(0) assertRaises( self, lambda: b.Output(), flatbuffers.builder.BuilderNotFinishedError )
TestExceptions
python
networkx__networkx
networkx/algorithms/traversal/tests/test_edgedfs.py
{ "start": 812, "end": 4775 }
class ____: @classmethod def setup_class(cls): cls.nodes = [0, 1, 2, 3] cls.edges = [(0, 1), (1, 0), (1, 0), (2, 1), (3, 1)] def test_empty(self): G = nx.Graph() edges = list(edge_dfs(G)) assert edges == [] def test_graph(self): G = nx.Graph(self.edges) x = list(edge_dfs(G, self.nodes)) x_ = [(0, 1), (1, 2), (1, 3)] assert x == x_ def test_digraph(self): G = nx.DiGraph(self.edges) x = list(edge_dfs(G, self.nodes)) x_ = [(0, 1), (1, 0), (2, 1), (3, 1)] assert x == x_ def test_digraph_orientation_invalid(self): G = nx.DiGraph(self.edges) edge_iterator = edge_dfs(G, self.nodes, orientation="hello") pytest.raises(nx.NetworkXError, list, edge_iterator) def test_digraph_orientation_none(self): G = nx.DiGraph(self.edges) x = list(edge_dfs(G, self.nodes, orientation=None)) x_ = [(0, 1), (1, 0), (2, 1), (3, 1)] assert x == x_ def test_digraph_orientation_original(self): G = nx.DiGraph(self.edges) x = list(edge_dfs(G, self.nodes, orientation="original")) x_ = [(0, 1, FORWARD), (1, 0, FORWARD), (2, 1, FORWARD), (3, 1, FORWARD)] assert x == x_ def test_digraph2(self): G = nx.DiGraph() nx.add_path(G, range(4)) x = list(edge_dfs(G, [0])) x_ = [(0, 1), (1, 2), (2, 3)] assert x == x_ def test_digraph_rev(self): G = nx.DiGraph(self.edges) x = list(edge_dfs(G, self.nodes, orientation="reverse")) x_ = [(1, 0, REVERSE), (0, 1, REVERSE), (2, 1, REVERSE), (3, 1, REVERSE)] assert x == x_ def test_digraph_rev2(self): G = nx.DiGraph() nx.add_path(G, range(4)) x = list(edge_dfs(G, [3], orientation="reverse")) x_ = [(2, 3, REVERSE), (1, 2, REVERSE), (0, 1, REVERSE)] assert x == x_ def test_multigraph(self): G = nx.MultiGraph(self.edges) x = list(edge_dfs(G, self.nodes)) x_ = [(0, 1, 0), (1, 0, 1), (0, 1, 2), (1, 2, 0), (1, 3, 0)] # This is an example of where hash randomization can break. # There are 3! * 2 alternative outputs, such as: # [(0, 1, 1), (1, 0, 0), (0, 1, 2), (1, 3, 0), (1, 2, 0)] # But note, the edges (1,2,0) and (1,3,0) always follow the (0,1,k) # edges. So the algorithm only guarantees a partial order. A total # order is guaranteed only if the graph data structures are ordered. assert x == x_ def test_multidigraph(self): G = nx.MultiDiGraph(self.edges) x = list(edge_dfs(G, self.nodes)) x_ = [(0, 1, 0), (1, 0, 0), (1, 0, 1), (2, 1, 0), (3, 1, 0)] assert x == x_ def test_multidigraph_rev(self): G = nx.MultiDiGraph(self.edges) x = list(edge_dfs(G, self.nodes, orientation="reverse")) x_ = [ (1, 0, 0, REVERSE), (0, 1, 0, REVERSE), (1, 0, 1, REVERSE), (2, 1, 0, REVERSE), (3, 1, 0, REVERSE), ] assert x == x_ def test_digraph_ignore(self): G = nx.DiGraph(self.edges) x = list(edge_dfs(G, self.nodes, orientation="ignore")) x_ = [(0, 1, FORWARD), (1, 0, FORWARD), (2, 1, REVERSE), (3, 1, REVERSE)] assert x == x_ def test_digraph_ignore2(self): G = nx.DiGraph() nx.add_path(G, range(4)) x = list(edge_dfs(G, [0], orientation="ignore")) x_ = [(0, 1, FORWARD), (1, 2, FORWARD), (2, 3, FORWARD)] assert x == x_ def test_multidigraph_ignore(self): G = nx.MultiDiGraph(self.edges) x = list(edge_dfs(G, self.nodes, orientation="ignore")) x_ = [ (0, 1, 0, FORWARD), (1, 0, 0, FORWARD), (1, 0, 1, REVERSE), (2, 1, 0, REVERSE), (3, 1, 0, REVERSE), ] assert x == x_
TestEdgeDFS
python
kamyu104__LeetCode-Solutions
Python/find-the-maximum-length-of-a-good-subsequence-i.py
{ "start": 1180, "end": 1727 }
class ____(object): def maximumLength(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ dp = [[0]*(k+1) for _ in xrange(len(nums))] result = 0 for i in xrange(len(nums)): dp[i][0] = 1 for l in xrange(k+1): for j in xrange(i): dp[i][l] = max(dp[i][l], dp[j][l]+1 if nums[j] == nums[i] else 1, dp[j][l-1]+1 if l-1 >= 0 else 1) result = max(result, dp[i][l]) return result
Solution
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/selector.py
{ "start": 9662, "end": 10071 }
class ____: """The information needed to resolve a graph within a host process.""" location_name: str repository_name: str graph_name: str def to_graphql_input(self): return { "repositoryLocationName": self.location_name, "repositoryName": self.repository_name, "graphName": self.graph_name, } @whitelist_for_serdes @record
GraphSelector
python
pyca__cryptography
tests/hazmat/primitives/test_pkcs12.py
{ "start": 27466, "end": 35963 }
class ____: def test_generate_valid_truststore(self, backend): # serialize_java_truststore adds a special attribute to each # certificate's safebag. As we cannot read this back currently, # comparison against a pre-verified file is necessary. cert1 = _load_cert( backend, os.path.join("x509", "custom", "dsa_selfsigned_ca.pem") ) cert2 = _load_cert(backend, os.path.join("x509", "letsencryptx3.pem")) encryption = serialization.NoEncryption() p12 = serialize_java_truststore( [ PKCS12Certificate(cert1, b"cert1"), PKCS12Certificate(cert2, None), ], encryption, ) # The golden file was verified with: # keytool -list -keystore java-truststore.p12 # Ensuring both entries are listed with "trustedCertEntry" golden_bytes = load_vectors_from_file( os.path.join("pkcs12", "java-truststore.p12"), lambda data: data.read(), mode="rb", ) # The last 49 bytes are the MAC digest, and will vary each call, so we # can ignore them. mac_digest_size = 49 assert p12[:-mac_digest_size] == golden_bytes[:-mac_digest_size] def test_generate_certs_friendly_names(self, backend): cert1 = _load_cert( backend, os.path.join("x509", "custom", "dsa_selfsigned_ca.pem") ) cert2 = _load_cert(backend, os.path.join("x509", "letsencryptx3.pem")) encryption = serialization.NoEncryption() p12 = serialize_java_truststore( [ PKCS12Certificate(cert1, b"cert1"), PKCS12Certificate(cert2, None), ], encryption, ) p12_cert = load_pkcs12(p12, None, backend) cas = p12_cert.additional_certs assert cas[0].certificate == cert1 assert cas[0].friendly_name == b"cert1" assert cas[1].certificate == cert2 assert cas[1].friendly_name is None @pytest.mark.parametrize( ("enc_alg", "enc_alg_der"), [ ( PBES.PBESv2SHA256AndAES256CBC, [ b"\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x05\x0d", # PBESv2 b"\x06\x09\x60\x86\x48\x01\x65\x03\x04\x01\x2a", # AES ], ), ( PBES.PBESv1SHA1And3KeyTripleDESCBC, [b"\x06\x0a\x2a\x86\x48\x86\xf7\x0d\x01\x0c\x01\x03"], ), ( None, [], ), ], ) @pytest.mark.parametrize( ("mac_alg", "mac_alg_der"), [ (hashes.SHA1(), b"\x06\x05\x2b\x0e\x03\x02\x1a"), (hashes.SHA256(), b"\x06\t`\x86H\x01e\x03\x04\x02\x01"), (None, None), ], ) @pytest.mark.parametrize( ("iters", "iter_der"), [ (420, b"\x02\x02\x01\xa4"), (22222, b"\x02\x02\x56\xce"), (None, None), ], ) def test_key_serialization_encryption( self, backend, enc_alg, enc_alg_der, mac_alg, mac_alg_der, iters, iter_der, ): builder = serialization.PrivateFormat.PKCS12.encryption_builder() if enc_alg is not None: builder = builder.key_cert_algorithm(enc_alg) if mac_alg is not None: builder = builder.hmac_hash(mac_alg) if iters is not None: builder = builder.kdf_rounds(iters) encryption = builder.build(b"password") cert = _load_cert( backend, os.path.join("x509", "custom", "dsa_selfsigned_ca.pem") ) assert isinstance(cert, x509.Certificate) p12 = serialize_java_truststore( [PKCS12Certificate(cert, b"name")], encryption ) # We want to know if we've serialized something that has the parameters # we expect, so we match on specific byte strings of OIDs & DER values. for der in enc_alg_der: assert der in p12 if mac_alg_der is not None: assert mac_alg_der in p12 if iter_der is not None: assert iter_der in p12 _, _, parsed_more_certs = load_key_and_certificates( p12, b"password", backend ) assert parsed_more_certs == [cert] def test_invalid_utf8_friendly_name(self, backend): cert, _ = _load_ca(backend) with pytest.raises(ValueError): serialize_java_truststore( [PKCS12Certificate(cert, b"\xc9")], serialization.NoEncryption(), ) def test_generate_empty_certs(self): with pytest.raises(ValueError) as exc: serialize_java_truststore([], serialization.NoEncryption()) assert str(exc.value) == ("You must supply at least one cert") def test_generate_unsupported_encryption_type(self, backend): cert, _ = _load_ca(backend) with pytest.raises(ValueError) as exc: serialize_java_truststore( [PKCS12Certificate(cert, None)], DummyKeySerializationEncryption(), ) assert str(exc.value) == "Unsupported key encryption type" def test_generate_wrong_types(self, backend): cert, key = _load_ca(backend) encryption = serialization.NoEncryption() with pytest.raises(TypeError) as exc: serialize_java_truststore(cert, encryption) with pytest.raises(TypeError) as exc: serialize_java_truststore([cert], encryption) assert "object cannot be cast as" in str( exc.value ) and "PKCS12Certificate" in str(exc.value) with pytest.raises(TypeError) as exc: serialize_java_truststore( [PKCS12Certificate(cert, None), key], encryption, ) assert "object cannot be cast as" in str( exc.value ) and "PKCS12Certificate" in str(exc.value) with pytest.raises(TypeError) as exc: serialize_java_truststore([PKCS12Certificate(cert, None)], cert) assert str(exc.value) == ( "Key encryption algorithm must be a " "KeySerializationEncryption instance" ) with pytest.raises(TypeError) as exc: serialize_java_truststore([key], encryption) assert "object cannot be cast as" in str( exc.value ) and "PKCS12Certificate" in str(exc.value) @pytest.mark.skip_fips( reason="PKCS12 unsupported in FIPS mode. So much bad crypto in it." ) def test_pkcs12_ordering(): """ In OpenSSL < 3.0.0 PKCS12 parsing reverses the order. However, we accidentally thought it was **encoding** that did it, leading to bug https://github.com/pyca/cryptography/issues/5872 This test ensures our ordering is correct going forward. """ def make_cert(name): key = ec.generate_private_key(ec.SECP256R1()) subject = x509.Name( [ x509.NameAttribute(x509.NameOID.COMMON_NAME, name), ] ) now = datetime.now(timezone.utc).replace(tzinfo=None) cert = ( x509.CertificateBuilder() .subject_name(subject) .issuer_name(subject) .public_key(key.public_key()) .serial_number(x509.random_serial_number()) .not_valid_before(now) .not_valid_after(now) .sign(key, hashes.SHA256()) ) return (key, cert) # Make some certificates with distinct names. a_name = "A" * 20 b_name = "B" * 20 c_name = "C" * 20 a_key, a_cert = make_cert(a_name) _, b_cert = make_cert(b_name) _, c_cert = make_cert(c_name) # Bundle them in a PKCS#12 file in order A, B, C. p12 = serialize_key_and_certificates( b"p12", a_key, a_cert, [b_cert, c_cert], serialization.NoEncryption() ) # Parse them out. The API should report them in the same order. (_, cert, certs) = load_key_and_certificates(p12, None) assert cert == a_cert assert certs == [b_cert, c_cert] # The ordering in the PKCS#12 file itself should also match. a_idx = p12.index(a_name.encode("utf-8")) b_idx = p12.index(b_name.encode("utf-8")) c_idx = p12.index(c_name.encode("utf-8")) assert a_idx < b_idx < c_idx
TestPKCS12TrustStoreCreation
python
kamyu104__LeetCode-Solutions
Python/stamping-the-sequence.py
{ "start": 70, "end": 1306 }
class ____(object): def movesToStamp(self, stamp, target): M, N = len(stamp), len(target) q = collections.deque() lookup = [False]*N result = [] A = [] for i in xrange(N-M+1): made, todo = set(), set() for j, c in enumerate(stamp): if c == target[i+j]: made.add(i+j) else: todo.add(i+j) A.append((made, todo)) if todo: continue result.append(i) for m in made: if lookup[m]: continue q.append(m) lookup[m] = True while q: i = q.popleft() for j in xrange(max(0, i-M+1), min(N-M, i)+1): made, todo = A[j] if i not in todo: continue todo.discard(i) if todo: continue result.append(j) for m in made: if lookup[m]: continue q.append(m) lookup[m] = True return result[::-1] if all(lookup) else []
Solution
python
django__django
tests/migrations/migrations_test_apps/with_generic_model/models.py
{ "start": 599, "end": 657 }
class ____(Parent1[T1, T3], Parent2[T2, T3]): pass
Child
python
pytransitions__transitions
transitions/extensions/diagrams.py
{ "start": 12288, "end": 12508 }
class ____(TransitionGraphSupport, NestedTransition): """ A transition type to be used with (subclasses of) `HierarchicalGraphMachine` and `LockedHierarchicalGraphMachine`. """
NestedGraphTransition
python
django__django
django/contrib/admin/filters.py
{ "start": 25056, "end": 27668 }
class ____(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): if not field.empty_strings_allowed and not field.null: raise ImproperlyConfigured( "The list filter '%s' cannot be used with field '%s' which " "doesn't allow empty strings and nulls." % ( self.__class__.__name__, field.name, ) ) self.lookup_kwarg = "%s__isempty" % field_path self.lookup_val = get_last_value_from_parameters(params, self.lookup_kwarg) super().__init__(field, request, params, model, model_admin, field_path) def get_lookup_condition(self): lookup_conditions = [] if self.field.empty_strings_allowed: lookup_conditions.append((self.field_path, "")) if self.field.null: lookup_conditions.append((f"{self.field_path}__isnull", True)) return models.Q.create(lookup_conditions, connector=models.Q.OR) def queryset(self, request, queryset): if self.lookup_kwarg not in self.used_parameters: return queryset if self.lookup_val not in ("0", "1"): raise IncorrectLookupParameters lookup_condition = self.get_lookup_condition() if self.lookup_val == "1": return queryset.filter(lookup_condition) return queryset.exclude(lookup_condition) def expected_parameters(self): return [self.lookup_kwarg] def get_facet_counts(self, pk_attname, filtered_qs): lookup_condition = self.get_lookup_condition() return { "empty__c": models.Count(pk_attname, filter=lookup_condition), "not_empty__c": models.Count(pk_attname, filter=~lookup_condition), } def choices(self, changelist): add_facets = changelist.add_facets facet_counts = self.get_facet_queryset(changelist) if add_facets else None for lookup, title, count_field in ( (None, _("All"), None), ("1", _("Empty"), "empty__c"), ("0", _("Not empty"), "not_empty__c"), ): if add_facets: if count_field is not None: count = facet_counts[count_field] title = f"{title} ({count})" yield { "selected": self.lookup_val == lookup, "query_string": changelist.get_query_string( {self.lookup_kwarg: lookup} ), "display": title, }
EmptyFieldListFilter
python
doocs__leetcode
solution/0300-0399/0333.Largest BST Subtree/Solution.py
{ "start": 192, "end": 714 }
class ____: def largestBSTSubtree(self, root: Optional[TreeNode]) -> int: def dfs(root): if root is None: return inf, -inf, 0 lmi, lmx, ln = dfs(root.left) rmi, rmx, rn = dfs(root.right) nonlocal ans if lmx < root.val < rmi: ans = max(ans, ln + rn + 1) return min(lmi, root.val), max(rmx, root.val), ln + rn + 1 return -inf, inf, 0 ans = 0 dfs(root) return ans
Solution
python
chroma-core__chroma
chromadb/errors.py
{ "start": 123, "end": 520 }
class ____(Exception, EnforceOverrides): trace_id: Optional[str] = None def code(self) -> int: """Return an appropriate HTTP response code for this error""" return 400 # Bad Request def message(self) -> str: return ", ".join(self.args) @classmethod @abstractmethod def name(cls) -> str: """Return the error name""" pass
ChromaError
python
keras-team__keras
keras/src/metrics/accuracy_metrics.py
{ "start": 5343, "end": 8482 }
class ____(reduction_metrics.MeanMetricWrapper): """Calculates how often predictions match one-hot labels. You can provide logits of classes as `y_pred`, since argmax of logits and probabilities are same. This metric creates two local variables, `total` and `count` that are used to compute the frequency with which `y_pred` matches `y_true`. This frequency is ultimately returned as `categorical accuracy`: an idempotent operation that simply divides `total` by `count`. `y_pred` and `y_true` should be passed in as vectors of probabilities, rather than as labels. If necessary, use `ops.one_hot` to expand `y_true` as a vector. If `sample_weight` is `None`, weights default to 1. Use `sample_weight` of 0 to mask values. Args: name: (Optional) string name of the metric instance. dtype: (Optional) data type of the metric result. Example: >>> m = keras.metrics.CategoricalAccuracy() >>> m.update_state([[0, 0, 1], [0, 1, 0]], [[0.1, 0.9, 0.8], ... [0.05, 0.95, 0]]) >>> m.result() 0.5 >>> m.reset_state() >>> m.update_state([[0, 0, 1], [0, 1, 0]], [[0.1, 0.9, 0.8], ... [0.05, 0.95, 0]], ... sample_weight=[0.7, 0.3]) >>> m.result() 0.3 Usage with `compile()` API: ```python model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=[keras.metrics.CategoricalAccuracy()]) ``` """ def __init__(self, name="categorical_accuracy", dtype=None): super().__init__(fn=categorical_accuracy, name=name, dtype=dtype) # Metric should be maximized during optimization. self._direction = "up" def get_config(self): return {"name": self.name, "dtype": self.dtype} @keras_export("keras.metrics.sparse_categorical_accuracy") def sparse_categorical_accuracy(y_true, y_pred): reshape_matches = False y_pred = ops.convert_to_tensor(y_pred) y_true = ops.convert_to_tensor(y_true, dtype=y_pred.dtype) y_true_org_shape = ops.shape(y_true) y_pred_rank = len(y_pred.shape) y_true_rank = len(y_true.shape) # If the shape of y_true is (num_samples, 1), squeeze to (num_samples,) if ( (y_true_rank is not None) and (y_pred_rank is not None) and (len(y_true.shape) == len(y_pred.shape)) and ops.shape(y_true)[-1] == 1 ): y_true = ops.squeeze(y_true, -1) reshape_matches = True y_pred = ops.argmax(y_pred, axis=-1) # If the predicted output and actual output types don't match, force cast # them to match. if y_pred.dtype is not y_true.dtype: y_pred = ops.cast(y_pred, y_true.dtype) matches = ops.cast(ops.equal(y_true, y_pred), backend.floatx()) if reshape_matches: matches = ops.reshape(matches, y_true_org_shape) # if shape is (num_samples, 1) squeeze if len(matches.shape) > 1 and matches.shape[-1] == 1: matches = ops.squeeze(matches, -1) return matches @keras_export("keras.metrics.SparseCategoricalAccuracy")
CategoricalAccuracy
python
walkccc__LeetCode
solutions/2816. Double a Number Represented as a Linked List/2816-2.py
{ "start": 0, "end": 313 }
class ____: def doubleIt(self, head: ListNode | None) -> ListNode | None: if head.val >= 5: head = ListNode(0, head) curr = head while curr: curr.val *= 2 curr.val %= 10 if curr.next and curr.next.val >= 5: curr.val += 1 curr = curr.next return head
Solution
python
run-llama__llama_index
llama-index-core/llama_index/core/selectors/pydantic_selectors.py
{ "start": 3325, "end": 5207 }
class ____(BaseSelector): def __init__( self, selector_program: BasePydanticProgram, max_outputs: Optional[int] = None ) -> None: self._selector_program = selector_program self._max_outputs = max_outputs @classmethod def from_defaults( cls, program: Optional[BasePydanticProgram] = None, llm: Optional["OpenAI"] = None, prompt_template_str: str = DEFAULT_MULTI_PYD_SELECT_PROMPT_TMPL, max_outputs: Optional[int] = None, verbose: bool = False, ) -> "PydanticMultiSelector": if program is None: program = FunctionCallingProgram.from_defaults( output_cls=MultiSelection, prompt_template_str=prompt_template_str, llm=llm, verbose=verbose, ) return cls(selector_program=program, max_outputs=max_outputs) def _get_prompts(self) -> Dict[str, Any]: """Get prompts.""" # TODO: no accessible prompts for a base pydantic program return {} def _update_prompts(self, prompts: PromptDictType) -> None: """Update prompts.""" def _select( self, choices: Sequence[ToolMetadata], query: QueryBundle ) -> SelectorResult: # prepare input context_list = _build_choices_text(choices) max_outputs = self._max_outputs or len(choices) # predict prediction = self._selector_program( num_choices=len(choices), max_outputs=max_outputs, context_list=context_list, query_str=query.query_str, ) # parse output return _pydantic_output_to_selector_result(prediction) async def _aselect( self, choices: Sequence[ToolMetadata], query: QueryBundle ) -> SelectorResult: return self._select(choices, query)
PydanticMultiSelector
python
Lightning-AI__lightning
tests/tests_pytorch/trainer/optimization/test_manual_optimization.py
{ "start": 5174, "end": 10311 }
class ____(BoringModel): count = 0 called = collections.defaultdict(int) detach = False def __init__(self): super().__init__() self.automatic_optimization = False @property def should_update(self): return self.count % 2 == 0 def on_train_batch_start(self, batch, batch_idx): self.called["on_train_batch_start"] += 1 self.weight_before = self.layer.weight.clone() def training_step(self, batch, batch_idx): self.called["training_step"] += 1 opt = self.optimizers() loss = self.step(batch) loss /= loss.clone().detach() loss *= 0.1 if self.should_update: self.manual_backward(loss) opt.step() opt.zero_grad() return loss.detach() if self.detach else loss def on_train_batch_end(self, *_): self.called["on_train_batch_end"] += 1 after_before = self.layer.weight.clone() if self.should_update: # TODO: Figure out why 1 every 3 runs, weights don't get updated on count = 4" with contextlib.suppress(Exception): # todo: specify the possible exception assert not torch.equal(self.weight_before, after_before), self.count else: try: assert torch.equal(self.weight_before, after_before) # todo: specify the possible exception except Exception: # almost no diff between before and after assert torch.abs(torch.sum(self.weight_before) - torch.sum(after_before)).item() < 10e-6 assert_emtpy_grad(self.layer.weight.grad) self.count += 1 def on_train_end(self): assert self.called["training_step"] == 10 assert self.called["on_train_batch_start"] == 10 assert self.called["on_train_batch_end"] == 10 @RunIf(min_cuda_gpus=2) def test_manual_optimization_and_return_tensor(tmp_path): """This test verify that in `manual_optimization` we don't add gradient when the user return loss in `training_step`""" model = ManualOptimizationExtendedModel() trainer = Trainer( max_epochs=1, default_root_dir=tmp_path, limit_train_batches=10, limit_test_batches=0, limit_val_batches=0, precision="16-mixed", strategy="ddp_spawn", accelerator="gpu", devices=2, ) trainer.fit(model) @RunIf(min_cuda_gpus=1) def test_manual_optimization_and_accumulated_gradient(tmp_path): """This test verify that in `automatic_optimization=False`, step is being called only when we shouldn't accumulate.""" seed_everything(234) class ExtendedModel(BoringModel): count = 1 called = collections.defaultdict(int) detach = False def __init__(self): super().__init__() self.automatic_optimization = False @property def should_update(self): return self.count % 2 == 0 @property def should_have_updated(self): return self.count % 4 == 0 @property def has_gradient(self): return self.layer.weight.grad is not None def on_train_batch_start(self, batch, batch_idx): self.called["on_train_batch_start"] += 1 self.weight_before = self.layer.weight.clone() def training_step(self, batch, batch_idx): self.called["training_step"] += 1 opt = self.optimizers() loss = self.step(batch) loss /= loss.clone().detach() loss *= 0.1 if self.should_update: self.manual_backward(loss) if self.should_have_updated: opt.step() opt.zero_grad() return loss.detach() if self.detach else loss def on_train_batch_end(self, *_): self.called["on_train_batch_end"] += 1 after_before = self.layer.weight.clone() if self.should_update and self.should_have_updated: assert not torch.equal(self.weight_before, after_before), self.count assert_emtpy_grad(self.layer.weight.grad) else: assert torch.equal(self.weight_before, after_before) if self.count > 1: if self.count % 4 == 1: assert_emtpy_grad(self.layer.weight.grad) else: assert torch.sum(self.layer.weight.grad) != 0 self.count += 1 def on_train_epoch_end(self, *_, **__): assert self.called["training_step"] == 20 assert self.called["on_train_batch_start"] == 20 assert self.called["on_train_batch_end"] == 20 model = ExtendedModel() trainer = Trainer( max_epochs=1, default_root_dir=tmp_path, limit_train_batches=20, limit_test_batches=0, limit_val_batches=0, precision="16-mixed", accelerator="gpu", devices=1, ) trainer.fit(model)
ManualOptimizationExtendedModel
python
getsentry__sentry
src/sentry/relay/projectconfig_debounce_cache/redis.py
{ "start": 368, "end": 3143 }
class ____(ProjectConfigDebounceCache): def __init__(self, **options): self._key_prefix = options.pop("key_prefix", "relayconfig-debounce") self._debounce_ttl = options.pop("debounce_ttl", REDIS_CACHE_TIMEOUT) self.is_redis_cluster, self.cluster, options = get_dynamic_cluster_from_options( "SENTRY_RELAY_PROJECTCONFIG_DEBOUNCE_CACHE_OPTIONS", options ) super().__init__(**options) def _get_redis_key(self, public_key, project_id, organization_id): if organization_id: return f"{self._key_prefix}:o:{organization_id}" elif project_id: return f"{self._key_prefix}:p:{project_id}" elif public_key: return f"{self._key_prefix}:k:{public_key}" else: raise ValueError() def validate(self): validate_dynamic_cluster(self.is_redis_cluster, self.cluster) def _get_redis_client(self, routing_key: str) -> rb.Cluster | RedisCluster: if is_instance_redis_cluster(self.cluster, self.is_redis_cluster): return self.cluster elif is_instance_rb_cluster(self.cluster, self.is_redis_cluster): return self.cluster.get_local_client_for_key(routing_key) else: raise AssertionError("unreachable") def is_debounced(self, *, public_key, project_id, organization_id): if organization_id: key = self._get_redis_key( public_key=None, project_id=None, organization_id=organization_id ) client = self._get_redis_client(key) if client.get(key): return True if project_id: key = self._get_redis_key(public_key=None, project_id=project_id, organization_id=None) client = self._get_redis_client(key) if client.get(key): return True if public_key: key = self._get_redis_key(public_key=public_key, project_id=None, organization_id=None) client = self._get_redis_client(key) if client.get(key): return True return False def debounce(self, *, public_key, project_id, organization_id): key = self._get_redis_key(public_key, project_id, organization_id) client = self._get_redis_client(key) client.setex(key, self._debounce_ttl, 1) metrics.incr("relay.projectconfig_debounce_cache.debounce") def mark_task_done(self, *, public_key, project_id, organization_id): key = self._get_redis_key(public_key, project_id, organization_id) client = self._get_redis_client(key) ret = client.delete(key) metrics.incr("relay.projectconfig_debounce_cache.task_done") return ret
RedisProjectConfigDebounceCache
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/pipelines/resource.py
{ "start": 1716, "end": 1874 }
class ____(graphene.ObjectType): class Meta: name = "ResourceConnection" resources = non_null_list(GrapheneResource)
GrapheneResourceConnection
python
tiangolo__fastapi
docs_src/body_nested_models/tutorial006_py310.py
{ "start": 144, "end": 475 }
class ____(BaseModel): name: str description: str | None = None price: float tax: float | None = None tags: set[str] = set() images: list[Image] | None = None @app.put("/items/{item_id}") async def update_item(item_id: int, item: Item): results = {"item_id": item_id, "item": item} return results
Item
python
conda__conda
conda/plugins/prefix_data_loaders/pypi/pkg_format.py
{ "start": 41608, "end": 48524 }
class ____: """This class is used to evaluate marker expressions.""" operations = { "==": lambda x, y: x == y, "===": lambda x, y: x == y, "~=": lambda x, y: x == y or x > y, "!=": lambda x, y: x != y, "<": lambda x, y: x < y, "<=": lambda x, y: x == y or x < y, ">": lambda x, y: x > y, ">=": lambda x, y: x == y or x > y, "and": lambda x, y: x and y, "or": lambda x, y: x or y, "in": lambda x, y: x in y, "not in": lambda x, y: x not in y, } def evaluate(self, expr, context): """ Evaluate a marker expression returned by the :func:`parse_requirement` function in the specified context. """ if isinstance(expr, str): if expr[0] in "'\"": result = expr[1:-1] else: if expr not in context: raise SyntaxError(f"unknown variable: {expr}") result = context[expr] else: if not isinstance(expr, dict): raise TypeError("'expr' must be a dict.") op = expr["op"] if op not in self.operations: raise NotImplementedError(f"op not implemented: {op}") elhs = expr["lhs"] erhs = expr["rhs"] if _is_literal(expr["lhs"]) and _is_literal(expr["rhs"]): raise SyntaxError(f"invalid comparison: {elhs} {op} {erhs}") lhs = self.evaluate(elhs, context) rhs = self.evaluate(erhs, context) result = self.operations[op](lhs, rhs) return result # def update_marker_context(python_version): # """Update default marker context to include environment python version.""" # updated_context = DEFAULT_MARKER_CONTEXT.copy() # context = { # 'python_full_version': python_version, # 'python_version': '.'.join(python_version.split('.')[:2]), # 'extra': '', # } # updated_context.update(context) # return updated_context def get_default_marker_context(): """Return the default context dictionary to use when parsing markers.""" def format_full_version(info): version = f"{info.major}.{info.minor}.{info.micro}" kind = info.releaselevel if kind != "final": version += kind[0] + str(info.serial) return version if hasattr(sys, "implementation"): implementation_version = format_full_version(sys.implementation.version) implementation_name = sys.implementation.name else: implementation_version = "0" implementation_name = "" # TODO: we can't use this result = { # See: https://www.python.org/dev/peps/pep-0508/#environment-markers "implementation_name": implementation_name, "implementation_version": implementation_version, "os_name": os_name, "platform_machine": platform.machine(), "platform_python_implementation": platform.python_implementation(), "platform_release": platform.release(), "platform_system": platform.system(), "platform_version": platform.version(), "python_full_version": platform.python_version(), "python_version": ".".join(platform.python_version().split(".")[:2]), "sys_platform": sys.platform, # See: https://www.python.org/dev/peps/pep-0345/#environment-markers "os.name": os_name, "platform.python_implementation": platform.python_implementation(), "platform.version": platform.version(), "platform.machine": platform.machine(), "sys.platform": sys.platform, "extra": "", } return result DEFAULT_MARKER_CONTEXT = get_default_marker_context() evaluator = Evaluator() # FIXME: Should this raise errors, or fail silently or with a warning? def interpret(marker, execution_context=None): """ Interpret a marker and return a result depending on environment. :param marker: The marker to interpret. :type marker: str :param execution_context: The context used for name lookup. :type execution_context: mapping """ try: expr, rest = parse_marker(marker) except Exception as e: raise SyntaxError(f"Unable to interpret marker syntax: {marker}: {e}") if rest and rest[0] != "#": raise SyntaxError(f"unexpected trailing data in marker: {marker}: {rest}") context = DEFAULT_MARKER_CONTEXT.copy() if execution_context: context.update(execution_context) return evaluator.evaluate(expr, context) def read_python_record(prefix_path, anchor_file, python_version): """ Convert a python package defined by an anchor file (Metadata information) into a conda prefix record object. """ pydist = PythonDistribution.init(prefix_path, anchor_file, python_version) depends, constrains = pydist.get_conda_dependencies() if isinstance(pydist, PythonInstalledDistribution): channel = Channel("pypi") build = "pypi_0" package_type = PackageType.VIRTUAL_PYTHON_WHEEL paths_tups = pydist.get_paths() paths_data = PathsData( paths_version=1, paths=( PathDataV1( _path=path, path_type=PathType.hardlink, sha256=checksum, size_in_bytes=size, ) for (path, checksum, size) in paths_tups ), ) files = tuple(p[0] for p in paths_tups) elif isinstance(pydist, PythonEggLinkDistribution): channel = Channel("<develop>") build = "dev_0" package_type = PackageType.VIRTUAL_PYTHON_EGG_LINK paths_data, files = PathsData(paths_version=1, paths=()), () elif isinstance(pydist, PythonEggInfoDistribution): channel = Channel("pypi") build = "pypi_0" if pydist.is_manageable: package_type = PackageType.VIRTUAL_PYTHON_EGG_MANAGEABLE paths_tups = pydist.get_paths() files = tuple(p[0] for p in paths_tups) paths_data = PathsData( paths_version=1, paths=( PathData(_path=path, path_type=PathType.hardlink) for path in files ), ) else: package_type = PackageType.VIRTUAL_PYTHON_EGG_UNMANAGEABLE paths_data, files = PathsData(paths_version=1, paths=()), () else: raise NotImplementedError() return PrefixRecord( package_type=package_type, name=pydist.norm_name, version=pydist.version, channel=channel, subdir="pypi", fn=pydist.sp_reference, build=build, build_number=0, paths_data=paths_data, files=files, depends=depends, constrains=constrains, )
Evaluator
python
walkccc__LeetCode
solutions/1472. Design Browser History/1472.py
{ "start": 0, "end": 591 }
class ____: def __init__(self, homepage: str): self.urls = [] self.index = -1 self.lastIndex = -1 self.visit(homepage) def visit(self, url: str) -> None: self.index += 1 if self.index < len(self.urls): self.urls[self.index] = url else: self.urls.append(url) self.lastIndex = self.index def back(self, steps: int) -> str: self.index = max(0, self.index - steps) return self.urls[self.index] def forward(self, steps: int) -> str: self.index = min(self.lastIndex, self.index + steps) return self.urls[self.index]
BrowserHistory
python
pytorch__pytorch
test/distributed/checkpoint/test_quantized_hf_storage.py
{ "start": 502, "end": 11348 }
class ____(TestCase): def setUp(self): super().setUp() """Set up common test fixtures.""" self.temp_dir = tempfile.TemporaryDirectory() self.path = self.temp_dir.name def tearDown(self): """Clean up test fixtures.""" self.temp_dir.cleanup() def test_dequantization(self): """Test quantized tensors with weights and scales in both same and different files.""" reader = QuantizedHuggingFaceStorageReader(self.path, thread_count=1) # Test data for two different weights quantized_tensor1 = torch.ones(4, 4, dtype=torch.float32) quantized_tensor2 = ( torch.ones(4, 4, dtype=torch.float32) * 3.0 ) # Different values scale_inv1 = torch.tensor([[2.0]], dtype=torch.float32) scale_inv2 = torch.tensor([[0.5]], dtype=torch.float32) # Different scale # Define weight and scale tensor names weight1_fqn = "model.layers.0.self_attn.q_proj.weight" # Scale in same file scale1_fqn = "model.layers.0.self_attn.q_proj.weight_scale_inv" weight2_fqn = ( "model.layers.0.self_attn.k_proj.weight" # Scale in different file ) scale2_fqn = "model.layers.0.self_attn.k_proj.weight_scale_inv" file1_name = "model-00001-of-00002.safetensors" file2_name = "model-00002-of-00002.safetensors" # Setup weight-scale mapping and file locations reader._weight_scale_mapping = { weight1_fqn: scale1_fqn, weight2_fqn: scale2_fqn, } reader._weight_map = { weight1_fqn: file1_name, # Weight in file 1 scale1_fqn: file1_name, # Scale also in file 1 (same file scenario) weight2_fqn: file1_name, # Weight in file 1 scale2_fqn: file2_name, # Scale in file 2 (different file scenario) } # Populate the tensor shapes cache that would normally be built by read_metadata() reader._tensor_full_shapes = { weight1_fqn: torch.Size([4, 4]), weight2_fqn: torch.Size([4, 4]), } # Mock the main safetensors file (file1) mock_file1 = MagicMock() # Mock get_slice to return different tensors based on tensor name def mock_get_slice(tensor_name): mock_tensor = MagicMock() if tensor_name == weight1_fqn: mock_tensor.__getitem__ = lambda _, _slice: quantized_tensor1 elif tensor_name == weight2_fqn: mock_tensor.__getitem__ = lambda _, _slice: quantized_tensor2 return mock_tensor mock_file1.get_slice = mock_get_slice # Mock get_tensor for same-file scale (scale1) mock_file1.get_tensor.return_value = scale_inv1 # Mock the cross-file safetensors file (file2) for scale2 mock_file2 = MagicMock() mock_file2.get_tensor.return_value = scale_inv2 # Test 1: Same-file scenario (weight1 + scale1 both in file1) read_item1 = ReadItem( type=LoadItemType.TENSOR, storage_index=MetadataIndex( fqn=weight1_fqn, offset=torch.Size([0, 0]), ), dest_index=MetadataIndex( fqn=weight1_fqn, offset=torch.Size([0, 0]), ), storage_offsets=[0, 0], dest_offsets=[0, 0], lengths=[4, 4], ) target_tensor1 = torch.zeros(4, 4, dtype=torch.float32) mock_planner1 = MagicMock() mock_planner1.resolve_tensor.return_value = target_tensor1 # Process first weight (same file scenario) reader._process_read_request(mock_file1, read_item1, mock_planner1) # Verify first tensor was dequantized (ones * 2.0 = twos) expected_result1 = torch.ones(4, 4, dtype=torch.float32) * 2.0 mock_planner1.commit_tensor.assert_called_once() # Check that target_tensor1 was updated correctly args1, _ = mock_planner1.commit_tensor.call_args committed_tensor1 = args1[1] torch.testing.assert_close(committed_tensor1, expected_result1) # Test 2: Cross-file scenario (weight2 in file1, scale2 in file2) read_item2 = ReadItem( type=LoadItemType.TENSOR, storage_index=MetadataIndex( fqn=weight2_fqn, offset=torch.Size([0, 0]), ), dest_index=MetadataIndex( fqn=weight2_fqn, offset=torch.Size([0, 0]), ), storage_offsets=[0, 0], dest_offsets=[0, 0], lengths=[4, 4], ) target_tensor2 = torch.zeros(4, 4, dtype=torch.float32) mock_planner2 = MagicMock() mock_planner2.resolve_tensor.return_value = target_tensor2 # Mock the entire safetensors module since it may not be available in test environment mock_safetensors = MagicMock() mock_safe_open = MagicMock() mock_safetensors.safe_open = mock_safe_open # Set up the mock to return a context manager that yields mock_file2 mock_safe_open.return_value.__enter__.return_value = mock_file2 mock_safe_open.return_value.__exit__.return_value = False # Mock the module import and safe_open function with patch.dict("sys.modules", {"safetensors": mock_safetensors}): # Process second weight (cross-file scenario) reader._process_read_request(mock_file1, read_item2, mock_planner2) # Verify safe_open was called with the correct file path expected_path = f"{self.path}/{file2_name}" mock_safe_open.assert_called_once() call_args = mock_safe_open.call_args[0] self.assertEqual(str(call_args[0]), expected_path) # Verify the scale tensor was loaded from the correct file mock_file2.get_tensor.assert_called_once_with(scale2_fqn) # Verify second tensor was dequantized (3.0 * 0.5 = 1.5) expected_result2 = torch.ones(4, 4, dtype=torch.float32) * 3.0 * 0.5 # 1.5 mock_planner2.commit_tensor.assert_called_once() # Check that target_tensor2 was updated correctly args2, _ = mock_planner2.commit_tensor.call_args committed_tensor2 = args2[1] torch.testing.assert_close(committed_tensor2, expected_result2) def test_dtensor_slice_dequantization_block_alignment(self): """Test DTensor slice dequantization with proper block alignment logic.""" reader = QuantizedHuggingFaceStorageReader( self.path, thread_count=1, block_size=4, # Small block size for easier testing ) # Create a larger tensor to test multiple blocks # Full tensor is 8x8, block size is 4x4, so we have 2x2 = 4 blocks full_tensor_shape = torch.Size([8, 8]) # Create quantized tensor data for a slice (rows 2:6, cols 1:5) # This slice spans across multiple blocks slice_tensor = torch.ones(4, 4, dtype=torch.float32) * 2.0 # Create scale inverse tensor with different values for each block # Scale tensor shape: (2, 2) for 2x2 blocks scale_inv = torch.tensor( [ [1.0, 2.0], # Block (0,0)=1.0, Block (0,1)=2.0 [3.0, 4.0], # Block (1,0)=3.0, Block (1,1)=4.0 ], dtype=torch.float32, ) # Define tensor names weight_fqn = "model.layers.0.attn.q_proj.weight" scale_fqn = "model.layers.0.attn.q_proj.weight_scale_inv" file_name = "model-00001-of-00001.safetensors" # Setup mappings reader._weight_scale_mapping = {weight_fqn: scale_fqn} reader._weight_map = {weight_fqn: file_name, scale_fqn: file_name} # Mock storage_data to provide tensor shape information reader.storage_data = { MetadataIndex(fqn=weight_fqn, offset=[0, 0]): _HFStorageInfo( relative_path=file_name, shape=full_tensor_shape, dtype=torch.float32 ) } # Populate the tensor shapes cache that would normally be built by read_metadata() reader._tensor_full_shapes = { weight_fqn: full_tensor_shape, } # Create ReadItem for a slice that spans multiple blocks # Request slice [2:6, 1:5] from the full 8x8 tensor read_item = ReadItem( type=LoadItemType.TENSOR, storage_index=MetadataIndex( fqn=weight_fqn, offset=torch.Size([0, 0]), ), dest_index=MetadataIndex( fqn=weight_fqn, offset=torch.Size([0, 0]), ), storage_offsets=[2, 1], # Start at row 2, col 1 dest_offsets=[0, 0], lengths=[4, 4], # 4x4 slice ) # Mock safetensors file mock_file = MagicMock() # Mock get_slice to return the slice tensor mock_tensor_slice = MagicMock() mock_tensor_slice.__getitem__ = lambda _, _slice: slice_tensor mock_file.get_slice.return_value = mock_tensor_slice # Mock get_tensor for scale mock_file.get_tensor.return_value = scale_inv # Create target tensor target_tensor = torch.zeros(4, 4, dtype=torch.float32) mock_planner = MagicMock() mock_planner.resolve_tensor.return_value = target_tensor # Process the request reader._process_read_request(mock_file, read_item, mock_planner) # Verify the result mock_planner.commit_tensor.assert_called_once() args, _ = mock_planner.commit_tensor.call_args committed_tensor = args[1] # Expected result calculation: # The slice [2:6, 1:5] intersects with blocks as follows: # - Block (0,0): covers [0:4, 0:4] -> intersection [2:4, 1:4] -> local [0:2, 0:3] with scale 1.0 # - Block (0,1): covers [0:4, 4:8] -> intersection [2:4, 4:5] -> local [0:2, 3:4] with scale 2.0 # - Block (1,0): covers [4:8, 0:4] -> intersection [4:6, 1:4] -> local [2:4, 0:3] with scale 3.0 # - Block (1,1): covers [4:8, 4:8] -> intersection [4:6, 4:5] -> local [2:4, 3:4] with scale 4.0 expected_result = torch.zeros(4, 4, dtype=torch.float32) # Fill expected values based on block intersections expected_result[0:2, 0:3] = 2.0 * 1.0 # Block (0,0) intersection expected_result[0:2, 3:4] = 2.0 * 2.0 # Block (0,1) intersection expected_result[2:4, 0:3] = 2.0 * 3.0 # Block (1,0) intersection expected_result[2:4, 3:4] = 2.0 * 4.0 # Block (1,1) intersection torch.testing.assert_close(committed_tensor, expected_result) if __name__ == "__main__": run_tests()
TestQuantizedHfStorage
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-sec-filings/llama_index/readers/sec_filings/prepline_sec_filings/sec_document.py
{ "start": 2005, "end": 18393 }
class ____(HTMLDocument): filing_type = None def _filter_table_of_contents(self, elements: List[Text]) -> List[Text]: """Filter out unnecessary elements in the table of contents using keyword search.""" if self.filing_type in REPORT_TYPES: # NOTE(yuming): Narrow TOC as all elements within # the first two titles that contain the keyword 'part i\b'. start, end = None, None for i, element in enumerate(elements): if bool(re.match(r"(?i)part i\b", clean_sec_text(element.text))): if start is None: # NOTE(yuming): Found the start of the TOC section. start = i else: # NOTE(yuming): Found the end of the TOC section. end = i - 1 return elements[start:end] elif self.filing_type in S1_TYPES: # NOTE(yuming): Narrow TOC as all elements within # the first pair of duplicated titles that contain the keyword 'prospectus'. title_indices = defaultdict(list) for i, element in enumerate(elements): clean_title_text = clean_sec_text(element.text).lower() title_indices[clean_title_text].append(i) duplicate_title_indices = { k: v for k, v in title_indices.items() if len(v) > 1 } for title, indices in duplicate_title_indices.items(): # NOTE(yuming): Make sure that we find the pair of duplicated titles. if "prospectus" in title and len(indices) == 2: start = indices[0] end = indices[1] - 1 return elements[start:end] # NOTE(yuming): Probably better ways to improve TOC, # but now we return [] if it fails to find the keyword. return [] def get_table_of_contents(self) -> HTMLDocument: """Identifies text sections that are likely the table of contents.""" out_cls = self.__class__ _raise_for_invalid_filing_type(self.filing_type) title_locs = to_sklearn_format(self.elements) if len(title_locs) == 0: return out_cls.from_elements([]) # NOTE(alan): Might be a way to do the same thing that doesn't involve the transformations # necessary to get it into sklearn. We're just looking for densely packed Titles. res = DBSCAN(eps=6.0).fit_predict(title_locs) for i in range(res.max() + 1): idxs = cluster_num_to_indices(i, title_locs, res) cluster_elements: List[Text] = [self.elements[i] for i in idxs] if any( # TODO(alan): Maybe swap risk title out for something more generic? It helps to # have 2 markers though, I think. is_risk_title(el.text, self.filing_type) for el in cluster_elements if isinstance(el, Title) ) and any( is_toc_title(el.text) for el in cluster_elements if isinstance(el, Title) ): return out_cls.from_elements( self._filter_table_of_contents(cluster_elements) ) return out_cls.from_elements(self._filter_table_of_contents(self.elements)) def get_section_narrative_no_toc(self, section: SECSection) -> List[NarrativeText]: """ Identifies narrative text sections that fall under the given section heading without using the table of contents. """ _raise_for_invalid_filing_type(self.filing_type) # NOTE(robinson) - We are not skipping table text because the risk narrative section # usually does not contain any tables and sometimes tables are used for # title formatting section_elements: List[NarrativeText] = [] in_section = False for element in self.elements: is_title = is_possible_title(element.text) if in_section: if is_title and is_item_title(element.text, self.filing_type): if section_elements: return section_elements else: in_section = False elif isinstance(element, (NarrativeText, ListItem)): section_elements.append(element) if is_title and is_section_elem(section, element, self.filing_type): in_section = True return section_elements def _get_toc_sections( self, section: SECSection, toc: HTMLDocument ) -> Tuple[Text, Text]: """Identifies section title and next section title in TOC under the given section heading.""" # Note(yuming): The matching section and the section after the matching section # can be thought of as placeholders to look for matching content below the toc. section_toc = first( el for el in toc.elements if is_section_elem(section, el, self.filing_type) ) if section_toc is None: # NOTE(yuming): unable to identify the section in TOC return (None, None) after_section_toc = toc.after_element(section_toc) next_section_toc = first( el for el in after_section_toc.elements if not is_section_elem(section, el, self.filing_type) ) if next_section_toc is None: # NOTE(yuming): unable to identify the next section title in TOC, # will leads to failure in finding the end of the section return (section_toc, None) return (section_toc, next_section_toc) def get_section_narrative(self, section: SECSection) -> List[NarrativeText]: """Identifies narrative text sections that fall under the given section heading.""" _raise_for_invalid_filing_type(self.filing_type) # NOTE(robinson) - We are not skipping table text because the risk narrative section # usually does not contain any tables and sometimes tables are used for # title formatting toc = self.get_table_of_contents() if not toc.pages: return self.get_section_narrative_no_toc(section) # Note(yuming): section_toc is the section title in TOC, # next_section_toc is the section title right after section_toc in TOC section_toc, next_section_toc = self._get_toc_sections(section, toc) if section_toc is None: # NOTE(yuming): fail to find the section title in TOC return [] # NOTE(yuming): we use doc after next_section_toc instead of after toc # to workaround an issue where the TOC grabbed too many elements by # starting to parse after the section matched in the TOC doc_after_section_toc = self.after_element( next_section_toc if next_section_toc else section_toc ) # NOTE(yuming): map section_toc to the section title after TOC # to find the start of the section section_start_element = get_element_by_title( reversed(doc_after_section_toc.elements), section_toc.text, self.filing_type ) if section_start_element is None: return [] doc_after_section_heading = self.after_element(section_start_element) # NOTE(yuming): Checks if section_toc is the last section in toc based on # the structure of the report filings or fails to find the section title in TOC. # returns everything up to the next Title element # to avoid the worst case of returning the entire doc. if self._is_last_section_in_report(section, toc) or next_section_toc is None: # returns everything after section_start_element in doc return get_narrative_texts(doc_after_section_heading, up_to_next_title=True) # NOTE(yuming): map next_section_toc to the section title after TOC # to find the start of the next section, which is also the end of the section we want section_end_element = get_element_by_title( doc_after_section_heading.elements, next_section_toc.text, self.filing_type ) if section_end_element is None: # NOTE(yuming): returns everything up to the next Title element # to avoid the worst case of returning the entire doc. return get_narrative_texts(doc_after_section_heading, up_to_next_title=True) return get_narrative_texts( doc_after_section_heading.before_element(section_end_element) ) def get_risk_narrative(self) -> List[NarrativeText]: """Identifies narrative text sections that fall under the "risk" heading.""" return self.get_section_narrative(SECSection.RISK_FACTORS) def doc_after_cleaners( self, skip_headers_and_footers=False, skip_table_text=False, inplace=False ) -> HTMLDocument: new_doc = super().doc_after_cleaners( skip_headers_and_footers, skip_table_text, inplace ) if not inplace: # NOTE(alan): Copy filing_type since this attribute isn't in the base class new_doc.filing_type = self.filing_type return new_doc def _read_xml(self, content): super()._read_xml(content) # NOTE(alan): Get filing type from xml since this is not relevant to the base class. type_tag = self.document_tree.find(".//type") if type_tag is not None: self.filing_type = type_tag.text.strip() return self.document_tree def _is_last_section_in_report( self, section: SECSection, toc: HTMLDocument ) -> bool: """Checks to see if the section is the last section in toc for a report types filing.""" # Note(yuming): This method assume the section already exists in toc. if self.filing_type in ["10-K", "10-K/A"]: # try to get FORM_SUMMARY as last section, else then try to get EXHIBITS. if section == SECSection.FORM_SUMMARY: return True if section == SECSection.EXHIBITS: form_summary_section = first( el for el in toc.elements if is_section_elem(SECSection.FORM_SUMMARY, el, self.filing_type) ) # if FORM_SUMMARY is not in toc, the last section is EXHIBITS if form_summary_section is None: return True if self.filing_type in ["10-Q", "10-Q/A"]: # try to get EXHIBITS as last section. if section == SECSection.EXHIBITS: return True return False def get_narrative_texts( doc: HTMLDocument, up_to_next_title: Optional[bool] = False ) -> List[Text]: """ Returns a list of NarrativeText or ListItem from document, with option to return narrative texts only up to next Title element. """ if up_to_next_title: narrative_texts = [] for el in doc.elements: if isinstance(el, (NarrativeText, ListItem)): narrative_texts.append(el) else: break return narrative_texts else: return [el for el in doc.elements if isinstance(el, (NarrativeText, ListItem))] def is_section_elem( section: SECSection, elem: Text, filing_type: Optional[str] ) -> bool: """Checks to see if a text element matches the section title for a given filing type.""" _raise_for_invalid_filing_type(filing_type) if section is SECSection.RISK_FACTORS: return is_risk_title(elem.text, filing_type=filing_type) else: def _is_matching_section_pattern(text): return bool( re.search(section.pattern, clean_sec_text(text, lowercase=True)) ) if filing_type in REPORT_TYPES: return _is_matching_section_pattern( remove_item_from_section_text(elem.text) ) else: return _is_matching_section_pattern(elem.text) def is_item_title(title: str, filing_type: Optional[str]) -> bool: """Determines if a title corresponds to an item heading.""" if filing_type in REPORT_TYPES: return is_10k_item_title(title) elif filing_type in S1_TYPES: return is_s1_section_title(title) return False def is_risk_title(title: str, filing_type: Optional[str]) -> bool: """Checks to see if the title matches the pattern for the risk heading.""" if filing_type in REPORT_TYPES: return is_10k_risk_title(clean_sec_text(title, lowercase=True)) elif filing_type in S1_TYPES: return is_s1_risk_title(clean_sec_text(title, lowercase=True)) return False def is_toc_title(title: str) -> bool: """Checks to see if the title matches the pattern for the table of contents.""" clean_title = clean_sec_text(title, lowercase=True) return (clean_title == "table of contents") or (clean_title == "index") def is_10k_item_title(title: str) -> bool: """Determines if a title corresponds to a 10-K item heading.""" return ITEM_TITLE_RE.match(clean_sec_text(title, lowercase=True)) is not None def is_10k_risk_title(title: str) -> bool: """Checks to see if the title matches the pattern for the risk heading.""" return ( "1a" in title.lower() or "risk factors" in title.lower() ) and "summary" not in title.lower() def is_s1_section_title(title: str) -> bool: """Determines if a title corresponds to a section title.""" return title.strip().isupper() def is_s1_risk_title(title: str) -> bool: """Checks to see if the title matches the pattern for the risk heading.""" return title.strip().lower() == "risk factors" def to_sklearn_format(elements: List[Element]) -> npt.NDArray[np.float32]: """ The input to clustering needs to be locations in euclidean space, so we need to interpret the locations of Titles within the sequence of elements as locations in 1d space. """ is_title: npt.NDArray[np.bool_] = np.array( [is_possible_title(el.text) for el in elements][: len(elements)], dtype=bool ) return np.arange(len(is_title)).astype(np.float32)[is_title].reshape(-1, 1) def cluster_num_to_indices( num: int, elem_idxs: npt.NDArray[np.float32], res: npt.NDArray[np.int_] ) -> List[int]: """ Keeping in mind the input to clustering was indices in a list of elements interpreted as location in 1-d space, this function gives back the original indices of elements that are members of the cluster with the given number. """ return elem_idxs[res == num].astype(int).flatten().tolist() def first(it: Iterable) -> Any: """Grabs the first item in an iterator.""" try: out = next(iter(it)) except StopIteration: out = None return out def match_s1_toc_title_to_section(text: str, title: str) -> bool: """ Matches an S-1 style title from the table of contents to the associated title in the document body. """ return text == title def match_10k_toc_title_to_section(text: str, title: str) -> bool: """ Matches a 10-K style title from the table of contents to the associated title in the document body. """ if re.match(ITEM_TITLE_RE, title): return text.startswith(title) else: text = remove_item_from_section_text(text) return text.startswith(title) def remove_item_from_section_text(text: str) -> str: """ Removes 'item' heading from section text for 10-K/Q forms as preparation for other matching techniques. """ return re.sub(ITEM_TITLE_RE, "", text).strip() def get_element_by_title( elements: Iterator[Element], title: str, filing_type: Optional[str], ) -> Optional[Element]: """Get element from Element list whose text approximately matches title.""" _raise_for_invalid_filing_type(filing_type) if filing_type in REPORT_TYPES: match = match_10k_toc_title_to_section elif filing_type in S1_TYPES: match = match_s1_toc_title_to_section return first( el for el in elements if match( clean_sec_text(el.text, lowercase=True), clean_sec_text(title, lowercase=True), ) )
SECDocument
python
scipy__scipy
scipy/stats/_morestats.py
{ "start": 162052, "end": 177966 }
class ____: def __init__(self, mean_direction, mean_resultant_length): self.mean_direction = mean_direction self.mean_resultant_length = mean_resultant_length def __repr__(self): return (f"DirectionalStats(mean_direction={self.mean_direction}," f" mean_resultant_length={self.mean_resultant_length})") @xp_capabilities() def directional_stats(samples, *, axis=0, normalize=True): """ Computes sample statistics for directional data. Computes the directional mean (also called the mean direction vector) and mean resultant length of a sample of vectors. The directional mean is a measure of "preferred direction" of vector data. It is analogous to the sample mean, but it is for use when the length of the data is irrelevant (e.g. unit vectors). The mean resultant length is a value between 0 and 1 used to quantify the dispersion of directional data: the smaller the mean resultant length, the greater the dispersion. Several definitions of directional variance involving the mean resultant length are given in [1]_ and [2]_. Parameters ---------- samples : array_like Input array. Must be at least two-dimensional, and the last axis of the input must correspond with the dimensionality of the vector space. When the input is exactly two dimensional, this means that each row of the data is a vector observation. axis : int, default: 0 Axis along which the directional mean is computed. normalize: boolean, default: True If True, normalize the input to ensure that each observation is a unit vector. It the observations are already unit vectors, consider setting this to False to avoid unnecessary computation. Returns ------- res : DirectionalStats An object containing attributes: mean_direction : ndarray Directional mean. mean_resultant_length : ndarray The mean resultant length [1]_. See Also -------- circmean: circular mean; i.e. directional mean for 2D *angles* circvar: circular variance; i.e. directional variance for 2D *angles* Notes ----- This uses a definition of directional mean from [1]_. Assuming the observations are unit vectors, the calculation is as follows. .. code-block:: python mean = samples.mean(axis=0) mean_resultant_length = np.linalg.norm(mean) mean_direction = mean / mean_resultant_length This definition is appropriate for *directional* data (i.e. vector data for which the magnitude of each observation is irrelevant) but not for *axial* data (i.e. vector data for which the magnitude and *sign* of each observation is irrelevant). Several definitions of directional variance involving the mean resultant length ``R`` have been proposed, including ``1 - R`` [1]_, ``1 - R**2`` [2]_, and ``2 * (1 - R)`` [2]_. Rather than choosing one, this function returns ``R`` as attribute `mean_resultant_length` so the user can compute their preferred measure of dispersion. References ---------- .. [1] Mardia, Jupp. (2000). *Directional Statistics* (p. 163). Wiley. .. [2] https://en.wikipedia.org/wiki/Directional_statistics Examples -------- >>> import numpy as np >>> from scipy.stats import directional_stats >>> data = np.array([[3, 4], # first observation, 2D vector space ... [6, -8]]) # second observation >>> dirstats = directional_stats(data) >>> dirstats.mean_direction array([1., 0.]) In contrast, the regular sample mean of the vectors would be influenced by the magnitude of each observation. Furthermore, the result would not be a unit vector. >>> data.mean(axis=0) array([4.5, -2.]) An exemplary use case for `directional_stats` is to find a *meaningful* center for a set of observations on a sphere, e.g. geographical locations. >>> data = np.array([[0.8660254, 0.5, 0.], ... [0.8660254, -0.5, 0.]]) >>> dirstats = directional_stats(data) >>> dirstats.mean_direction array([1., 0., 0.]) The regular sample mean on the other hand yields a result which does not lie on the surface of the sphere. >>> data.mean(axis=0) array([0.8660254, 0., 0.]) The function also returns the mean resultant length, which can be used to calculate a directional variance. For example, using the definition ``Var(z) = 1 - R`` from [2]_ where ``R`` is the mean resultant length, we can calculate the directional variance of the vectors in the above example as: >>> 1 - dirstats.mean_resultant_length 0.13397459716167093 """ xp = array_namespace(samples) samples = xp.asarray(samples) if samples.ndim < 2: raise ValueError("samples must at least be two-dimensional. " f"Instead samples has shape: {tuple(samples.shape)}") samples = xp.moveaxis(samples, axis, 0) if is_marray(xp): _xp = array_namespace(samples.mask) mask = _xp.any(samples.mask, axis=-1, keepdims=True) samples = xp.asarray(samples.data, mask=mask) if normalize: vectornorms = xp_vector_norm(samples, axis=-1, keepdims=True, xp=xp) samples = samples/vectornorms mean = xp.mean(samples, axis=0) mean_resultant_length = xp_vector_norm(mean, axis=-1, keepdims=True, xp=xp) mean_direction = mean / mean_resultant_length mrl = xp.squeeze(mean_resultant_length, axis=-1) mean_resultant_length = mrl[()] if mrl.ndim == 0 else mrl return DirectionalStats(mean_direction, mean_resultant_length) @xp_capabilities(skip_backends=[('dask.array', "no take_along_axis")], jax_jit=False) def false_discovery_control(ps, *, axis=0, method='bh'): """Adjust p-values to control the false discovery rate. The false discovery rate (FDR) is the expected proportion of rejected null hypotheses that are actually true. If the null hypothesis is rejected when the *adjusted* p-value falls below a specified level, the false discovery rate is controlled at that level. Parameters ---------- ps : 1D array_like The p-values to adjust. Elements must be real numbers between 0 and 1. axis : int The axis along which to perform the adjustment. The adjustment is performed independently along each axis-slice. If `axis` is None, `ps` is raveled before performing the adjustment. method : {'bh', 'by'} The false discovery rate control procedure to apply: ``'bh'`` is for Benjamini-Hochberg [1]_ (Eq. 1), ``'by'`` is for Benjaminini-Yekutieli [2]_ (Theorem 1.3). The latter is more conservative, but it is guaranteed to control the FDR even when the p-values are not from independent tests. Returns ------- ps_adusted : array_like The adjusted p-values. If the null hypothesis is rejected where these fall below a specified level, the false discovery rate is controlled at that level. See Also -------- combine_pvalues statsmodels.stats.multitest.multipletests Notes ----- In multiple hypothesis testing, false discovery control procedures tend to offer higher power than familywise error rate control procedures (e.g. Bonferroni correction [1]_). If the p-values correspond with independent tests (or tests with "positive regression dependencies" [2]_), rejecting null hypotheses corresponding with Benjamini-Hochberg-adjusted p-values below :math:`q` controls the false discovery rate at a level less than or equal to :math:`q m_0 / m`, where :math:`m_0` is the number of true null hypotheses and :math:`m` is the total number of null hypotheses tested. The same is true even for dependent tests when the p-values are adjusted accorded to the more conservative Benjaminini-Yekutieli procedure. The adjusted p-values produced by this function are comparable to those produced by the R function ``p.adjust`` and the statsmodels function `statsmodels.stats.multitest.multipletests`. Please consider the latter for more advanced methods of multiple comparison correction. References ---------- .. [1] Benjamini, Yoav, and Yosef Hochberg. "Controlling the false discovery rate: a practical and powerful approach to multiple testing." Journal of the Royal statistical society: series B (Methodological) 57.1 (1995): 289-300. .. [2] Benjamini, Yoav, and Daniel Yekutieli. "The control of the false discovery rate in multiple testing under dependency." Annals of statistics (2001): 1165-1188. .. [3] TileStats. FDR - Benjamini-Hochberg explained - Youtube. https://www.youtube.com/watch?v=rZKa4tW2NKs. .. [4] Neuhaus, Karl-Ludwig, et al. "Improved thrombolysis in acute myocardial infarction with front-loaded administration of alteplase: results of the rt-PA-APSAC patency study (TAPS)." Journal of the American College of Cardiology 19.5 (1992): 885-891. Examples -------- We follow the example from [1]_. Thrombolysis with recombinant tissue-type plasminogen activator (rt-PA) and anisoylated plasminogen streptokinase activator (APSAC) in myocardial infarction has been proved to reduce mortality. [4]_ investigated the effects of a new front-loaded administration of rt-PA versus those obtained with a standard regimen of APSAC, in a randomized multicentre trial in 421 patients with acute myocardial infarction. There were four families of hypotheses tested in the study, the last of which was "cardiac and other events after the start of thrombolitic treatment". FDR control may be desired in this family of hypotheses because it would not be appropriate to conclude that the front-loaded treatment is better if it is merely equivalent to the previous treatment. The p-values corresponding with the 15 hypotheses in this family were >>> ps = [0.0001, 0.0004, 0.0019, 0.0095, 0.0201, 0.0278, 0.0298, 0.0344, ... 0.0459, 0.3240, 0.4262, 0.5719, 0.6528, 0.7590, 1.000] If the chosen significance level is 0.05, we may be tempted to reject the null hypotheses for the tests corresponding with the first nine p-values, as the first nine p-values fall below the chosen significance level. However, this would ignore the problem of "multiplicity": if we fail to correct for the fact that multiple comparisons are being performed, we are more likely to incorrectly reject true null hypotheses. One approach to the multiplicity problem is to control the family-wise error rate (FWER), that is, the rate at which the null hypothesis is rejected when it is actually true. A common procedure of this kind is the Bonferroni correction [1]_. We begin by multiplying the p-values by the number of hypotheses tested. >>> import numpy as np >>> np.array(ps) * len(ps) array([1.5000e-03, 6.0000e-03, 2.8500e-02, 1.4250e-01, 3.0150e-01, 4.1700e-01, 4.4700e-01, 5.1600e-01, 6.8850e-01, 4.8600e+00, 6.3930e+00, 8.5785e+00, 9.7920e+00, 1.1385e+01, 1.5000e+01]) To control the FWER at 5%, we reject only the hypotheses corresponding with adjusted p-values less than 0.05. In this case, only the hypotheses corresponding with the first three p-values can be rejected. According to [1]_, these three hypotheses concerned "allergic reaction" and "two different aspects of bleeding." An alternative approach is to control the false discovery rate: the expected fraction of rejected null hypotheses that are actually true. The advantage of this approach is that it typically affords greater power: an increased rate of rejecting the null hypothesis when it is indeed false. To control the false discovery rate at 5%, we apply the Benjamini-Hochberg p-value adjustment. >>> from scipy import stats >>> stats.false_discovery_control(ps) array([0.0015 , 0.003 , 0.0095 , 0.035625 , 0.0603 , 0.06385714, 0.06385714, 0.0645 , 0.0765 , 0.486 , 0.58118182, 0.714875 , 0.75323077, 0.81321429, 1. ]) Now, the first *four* adjusted p-values fall below 0.05, so we would reject the null hypotheses corresponding with these *four* p-values. Rejection of the fourth null hypothesis was particularly important to the original study as it led to the conclusion that the new treatment had a "substantially lower in-hospital mortality rate." For simplicity of exposition, the p-values in the example above were given in sorted order, but this is not required; `false_discovery_control` returns adjusted p-values in order corresponding with the input `ps`. >>> stats.false_discovery_control([0.5, 0.6, 0.1, 0.001]) array([0.6 , 0.6 , 0.2 , 0.004]) """ xp = array_namespace(ps) # Input Validation and Special Cases ps = xp.asarray(ps) ps_in_range = (xp.isdtype(ps.dtype, ("integral", "real floating")) and xp.all(ps == xp.clip(ps, 0., 1.))) if not ps_in_range: raise ValueError("`ps` must include only numbers between 0 and 1.") methods = {'bh', 'by'} if method.lower() not in methods: raise ValueError(f"Unrecognized `method` '{method}'." f"Method must be one of {methods}.") method = method.lower() if axis is None: axis = 0 ps = xp_ravel(ps) axis = np.asarray(axis)[()] # use of NumPy for input validation is OK if not np.issubdtype(axis.dtype, np.integer) or axis.size != 1: raise ValueError("`axis` must be an integer or `None`") axis = int(axis) if xp_size(ps) <= 1 or ps.shape[axis] <= 1: return ps[()] if ps.ndim == 0 else ps ps = xp.moveaxis(ps, axis, -1) m = ps.shape[-1] # Main Algorithm # Equivalent to the ideas of [1] and [2], except that this adjusts the # p-values as described in [3]. The results are similar to those produced # by R's p.adjust. # "Let [ps] be the ordered observed p-values..." order = xp.argsort(ps, axis=-1) ps = xp.take_along_axis(ps, order, axis=-1) # this copies ps # Equation 1 of [1] rearranged to reject when p is less than specified q i = xp.arange(1, m+1, dtype=ps.dtype, device=xp_device(ps)) # ps *= m / i ps = xpx.at(ps)[...].multiply(m / i) # Theorem 1.3 of [2] if method == 'by': # ps *= np.sum(1 / i) ps = xpx.at(ps)[...].multiply(xp.sum(1 / i)) # accounts for rejecting all null hypotheses i for i < k, where k is # defined in Eq. 1 of either [1] or [2]. See [3]. Starting with the index j # of the second to last element, we replace element j with element j+1 if # the latter is smaller. if is_numpy(xp): np.minimum.accumulate(ps[..., ::-1], out=ps[..., ::-1], axis=-1) else: n = ps.shape[-1] for j in range(n-2, -1, -1): # ps[..., j] = xp.minimum(ps[..., j], ps[..., j+1]) ps = xpx.at(ps)[..., j].set(xp.minimum(ps[..., j], ps[..., j+1])) # Restore original order of axes and data ps = _reorder_along_axis(ps, order, axis=-1, xp=xp) ps = xp.moveaxis(ps, -1, axis) return xp.clip(ps, 0., 1.) def _reorder_along_axis(x, i, *, axis, xp): if is_jax(xp): return xp.put_along_axis(x, i, values=x, axis=axis, inplace=False) if hasattr(xp, 'put_along_axis'): xp.put_along_axis(x, i, values=x.copy(), axis=axis) return x else: return xp.take_along_axis(x, xp.argsort(i, axis=-1), axis=-1)
DirectionalStats
python
huggingface__transformers
src/transformers/models/deepseek_vl_hybrid/modular_deepseek_vl_hybrid.py
{ "start": 8096, "end": 8934 }
class ____(DeepseekVLPreTrainedModel): @torch.no_grad() def _init_weights(self, module): """Initialize the weights""" if isinstance(module, nn.Linear): init.normal_(module.weight, mean=0.0, std=self.config.text_config.initializer_range) if module.bias is not None: init.zeros_(module.bias) elif isinstance(module, nn.Conv2d): init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu") if module.bias is not None: init.zeros_(module.bias) elif isinstance(module, DeepseekVLHybridLayerNorm): init.ones_(module.weight) init.zeros_(module.bias) elif isinstance(module, DeepseekVLHybridModel): init.zeros_(module.high_res_vision_alpha)
DeepseekVLHybridPreTrainedModel
python
dagster-io__dagster
python_modules/dagster-test/dagster_test/test_project/__init__.py
{ "start": 3210, "end": 4467 }
class ____(ReconstructableJob): def __new__( cls, reconstructable_job: ReconstructableJob, ): return super().__new__( cls, reconstructable_job.repository, reconstructable_job.job_name, reconstructable_job.op_selection, ) def get_python_origin(self): """Hack! Inject origin that the docker-celery images will use. The BK image uses a different directory structure (/workdir/python_modules/dagster-test/dagster_test/test_project) than the test that creates the ReconstructableJob. As a result the normal origin won't work, we need to inject this one. """ return JobPythonOrigin( self.job_name, RepositoryPythonOrigin( executable_path="python", code_pointer=FileCodePointer( "/dagster_test/test_project/test_jobs/repo.py", "define_demo_execution_repo", ), container_image=self.repository.container_image, entry_point=DEFAULT_DAGSTER_ENTRY_POINT, container_context=self.repository.container_context, ), )
ReOriginatedReconstructableJobForTest
python
wandb__wandb
wandb/vendor/pygments/lexers/c_cpp.py
{ "start": 7809, "end": 8245 }
class ____(CFamilyLexer): """ For C source code with preprocessor directives. """ name = 'C' aliases = ['c'] filenames = ['*.c', '*.h', '*.idc'] mimetypes = ['text/x-chdr', 'text/x-csrc'] priority = 0.1 def analyse_text(text): if re.search('^\s*#include [<"]', text, re.MULTILINE): return 0.1 if re.search('^\s*#ifn?def ', text, re.MULTILINE): return 0.1
CLexer
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 48781, "end": 50672 }
class ____(TestCase): """Tests for ``split_after()``""" def test_starts_with_sep(self): actual = list(mi.split_after('xooxoo', lambda c: c == 'x')) expected = [['x'], ['o', 'o', 'x'], ['o', 'o']] self.assertEqual(actual, expected) def test_ends_with_sep(self): actual = list(mi.split_after('ooxoox', lambda c: c == 'x')) expected = [['o', 'o', 'x'], ['o', 'o', 'x']] self.assertEqual(actual, expected) def test_no_sep(self): actual = list(mi.split_after('ooo', lambda c: c == 'x')) expected = [['o', 'o', 'o']] self.assertEqual(actual, expected) def test_max_split(self): for args, expected in [ ( ('a,b,c,d', lambda c: c == ',', -1), [['a', ','], ['b', ','], ['c', ','], ['d']], ), ( ('a,b,c,d', lambda c: c == ',', 0), [['a', ',', 'b', ',', 'c', ',', 'd']], ), ( ('a,b,c,d', lambda c: c == ',', 1), [['a', ','], ['b', ',', 'c', ',', 'd']], ), ( ('a,b,c,d', lambda c: c == ',', 2), [['a', ','], ['b', ','], ['c', ',', 'd']], ), ( ('a,b,c,d', lambda c: c == ',', 10), [['a', ','], ['b', ','], ['c', ','], ['d']], ), ( ('a,b,c,d', lambda c: c == '@', 2), [['a', ',', 'b', ',', 'c', ',', 'd']], ), ( ('a,b,c,d', lambda c: c != ',', 2), [['a'], [',', 'b'], [',', 'c', ',', 'd']], ), ( ([1], lambda x: x == 1, 1), [[1]], ), ]: actual = list(mi.split_after(*args)) self.assertEqual(actual, expected)
SplitAfterTest
python
fluentpython__example-code-2e
15-more-types/protocol/abs_demo.py
{ "start": 56, "end": 660 }
class ____(NamedTuple): x: float y: float def __abs__(self) -> float: # <1> return math.hypot(self.x, self.y) def is_unit(v: SupportsAbs[float]) -> bool: # <2> """'True' if the magnitude of 'v' is close to 1.""" return math.isclose(abs(v), 1.0) # <3> assert issubclass(Vector2d, SupportsAbs) # <4> v0 = Vector2d(0, 1) # <5> sqrt2 = math.sqrt(2) v1 = Vector2d(sqrt2 / 2, sqrt2 / 2) v2 = Vector2d(1, 1) v3 = complex(.5, math.sqrt(3) / 2) v4 = 1 # <6> assert is_unit(v0) assert is_unit(v1) assert not is_unit(v2) assert is_unit(v3) assert is_unit(v4) print('OK')
Vector2d
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 335981, "end": 337733 }
class ____(VegaLiteSchema): """ ErrorBarConfig schema wrapper. Parameters ---------- extent : :class:`ErrorBarExtent`, Literal['ci', 'iqr', 'stderr', 'stdev'] The extent of the rule. Available options include: * ``"ci"``: Extend the rule to the 95% bootstrapped confidence interval of the mean. * ``"stderr"``: The size of rule are set to the value of standard error, extending from the mean. * ``"stdev"``: The size of rule are set to the value of standard deviation, extending from the mean. * ``"iqr"``: Extend the rule to the q1 and q3. **Default value:** ``"stderr"``. rule : bool, dict, :class:`BarConfig`, :class:`AreaConfig`, :class:`LineConfig`, :class:`MarkConfig`, :class:`RectConfig`, :class:`TickConfig`, :class:`AnyMarkConfig` size : float Size of the ticks of an error bar thickness : float Thickness of the ticks and the bar of an error bar ticks : bool, dict, :class:`BarConfig`, :class:`AreaConfig`, :class:`LineConfig`, :class:`MarkConfig`, :class:`RectConfig`, :class:`TickConfig`, :class:`AnyMarkConfig` """ _schema = {"$ref": "#/definitions/ErrorBarConfig"} def __init__( self, extent: Optional[SchemaBase | ErrorBarExtent_T] = Undefined, rule: Optional[bool | SchemaBase | Map] = Undefined, size: Optional[float] = Undefined, thickness: Optional[float] = Undefined, ticks: Optional[bool | SchemaBase | Map] = Undefined, **kwds, ): super().__init__( extent=extent, rule=rule, size=size, thickness=thickness, ticks=ticks, **kwds, )
ErrorBarConfig
python
numpy__numpy
numpy/_core/tests/test_multiarray.py
{ "start": 307445, "end": 308910 }
class ____: def _create_data(self): m = np.array([1, 2, 3, 4, 5, 6]) m_rect = m.reshape((2, 3)) return m, m_rect def test_basic(self): m, _ = self._create_data() A = np.repeat(m, [1, 3, 2, 1, 1, 2]) assert_equal(A, [1, 2, 2, 2, 3, 3, 4, 5, 6, 6]) def test_broadcast1(self): m, _ = self._create_data() A = np.repeat(m, 2) assert_equal(A, [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6]) def test_axis_spec(self): _, m_rect = self._create_data() A = np.repeat(m_rect, [2, 1], axis=0) assert_equal(A, [[1, 2, 3], [1, 2, 3], [4, 5, 6]]) A = np.repeat(m_rect, [1, 3, 2], axis=1) assert_equal(A, [[1, 2, 2, 2, 3, 3], [4, 5, 5, 5, 6, 6]]) def test_broadcast2(self): _, m_rect = self._create_data() A = np.repeat(m_rect, 2, axis=0) assert_equal(A, [[1, 2, 3], [1, 2, 3], [4, 5, 6], [4, 5, 6]]) A = np.repeat(m_rect, 2, axis=1) assert_equal(A, [[1, 1, 2, 2, 3, 3], [4, 4, 5, 5, 6, 6]]) # TODO: test for multidimensional NEIGH_MODE = {'zero': 0, 'one': 1, 'constant': 2, 'circular': 3, 'mirror': 4} @pytest.mark.parametrize('dt', [float, Decimal], ids=['float', 'object'])
TestRepeat
python
getsentry__sentry
src/sentry/users/models/identity.py
{ "start": 994, "end": 1084 }
class ____: UNKNOWN = 0 VALID = 1 INVALID = 2 @control_silo_model
IdentityStatus
python
airbytehq__airbyte
airbyte-integrations/connectors/source-zenloop/source_zenloop/streams.py
{ "start": 3062, "end": 4539 }
class ____(ZenloopStream, ABC): # checkpoint stream reads after 1000 records. state_checkpoint_interval = 1000 cursor_field = "inserted_at" def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]) -> Mapping[str, Any]: # latest_record has objects in answers if latest_record: # add 1 second to not pull latest_record again latest_record_date = ( datetime.strptime(latest_record[self.cursor_field], "%Y-%m-%dT%H:%M:%S.%fZ") + timedelta(seconds=1) ).isoformat() + str("Z") else: latest_record_date = "" max_record = max(latest_record_date, current_stream_state.get(self.cursor_field, "")) return {self.cursor_field: max_record} def request_params( self, stream_state: Mapping[str, Any], stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None ) -> MutableMapping[str, Any]: params = super().request_params(stream_state, stream_slice, next_page_token) if stream_state: # if looped through all slices take its date_from parameter # else no survey_id or survey_group_id provided -> take cursor_field if stream_slice: params["date_from"] = stream_slice["date_from"] else: params["date_from"] = stream_state[self.cursor_field] return params
IncrementalZenloopStream
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/compiler.py
{ "start": 11070, "end": 11213 }
class ____(TypedDict): asfrom_froms: Set[FromClause] correlate_froms: Set[FromClause] selectable: ReturnsRows
_BaseCompilerStackEntry
python
openai__openai-python
src/openai/types/realtime/realtime_response.py
{ "start": 1131, "end": 1198 }
class ____(BaseModel): output: Optional[AudioOutput] = None
Audio
python
django__django
django/http/multipartparser.py
{ "start": 21133, "end": 21720 }
class ____: """ An iterable that will yield chunks of data. Given a file-like object as the constructor, yield chunks of read operations from that object. """ def __init__(self, flo, chunk_size=64 * 1024): self.flo = flo self.chunk_size = chunk_size def __next__(self): try: data = self.flo.read(self.chunk_size) except InputStreamExhausted: raise StopIteration() if data: return data else: raise StopIteration() def __iter__(self): return self
ChunkIter
python
pennersr__django-allauth
allauth/socialaccount/providers/stocktwits/provider.py
{ "start": 227, "end": 463 }
class ____(ProviderAccount): def get_avatar_url(self): return self.account.extra_data.get("user", {}).get("avatar_url_ssl") def get_user_data(self): return self.account.extra_data.get("user", {})
StocktwitsAccount
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP049_1.py
{ "start": 1665, "end": 1830 }
class ____[_T]: T = 42 v1 = cast(_T, ...) v2 = cast('_T', ...) # Unfixable as the new name collides with a variable visible from one of the inner scopes
C
python
PyCQA__pylint
pylint/config/argument.py
{ "start": 13819, "end": 14859 }
class ____(_Argument): """Class representing an callable argument to be parsed by an argparse.ArgumentsParser. This is based on the parameters passed to argparse.ArgumentsParser.add_message. See: https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument """ def __init__( self, *, flags: list[str], action: type[_CallbackAction], arg_help: str, kwargs: dict[str, Any], hide_help: bool, section: str | None, metavar: str | None, ) -> None: super().__init__( flags=flags, arg_help=arg_help, hide_help=hide_help, section=section ) self.action = action """The action to perform with the argument.""" self.kwargs = kwargs """Any additional arguments passed to the action.""" self.metavar = metavar """The metavar of the argument. See: https://docs.python.org/3/library/argparse.html#metavar """
_CallableArgument
python
Farama-Foundation__Gymnasium
docs/tutorials/training_agents/frozenlake_q_learning.py
{ "start": 904, "end": 2841 }
class ____(NamedTuple): total_episodes: int # Total episodes learning_rate: float # Learning rate gamma: float # Discounting rate epsilon: float # Exploration probability map_size: int # Number of tiles of one side of the squared environment seed: int # Define a seed so that we get reproducible results is_slippery: bool # If true the player will move in intended direction with probability of 1/3 else will move in either perpendicular direction with equal probability of 1/3 in both directions n_runs: int # Number of runs action_size: int # Number of possible actions state_size: int # Number of possible states proba_frozen: float # Probability that a tile is frozen params = Params( total_episodes=2000, learning_rate=0.8, gamma=0.95, epsilon=0.1, map_size=5, seed=123, is_slippery=False, n_runs=20, action_size=None, state_size=None, proba_frozen=0.9, ) params # Set the seed rng = np.random.default_rng(params.seed) # %% # The FrozenLake environment # -------------------------- # env = gym.make( "FrozenLake-v1", is_slippery=params.is_slippery, render_mode="rgb_array", desc=generate_random_map( size=params.map_size, p=params.proba_frozen, seed=params.seed ), ) # %% # Creating the Q-table # ~~~~~~~~~~~~~~~~~~~~ # # In this tutorial we'll be using Q-learning as our learning algorithm and # :math:`\epsilon`-greedy to decide which action to pick at each step. You # can have a look at the `References section <#References>`__ for some # refreshers on the theory. Now, let's create our Q-table initialized at # zero with the states number as rows and the actions number as columns. # params = params._replace(action_size=env.action_space.n) params = params._replace(state_size=env.observation_space.n) print(f"Action size: {params.action_size}") print(f"State size: {params.state_size}")
Params
python
ansible__ansible
lib/ansible/galaxy/collection/galaxy_api_proxy.py
{ "start": 762, "end": 7805 }
class ____: """A proxy that abstracts talking to multiple Galaxy instances.""" def __init__(self, apis: t.Iterable[GalaxyAPI], concrete_artifacts_manager: ConcreteArtifactsManager, offline: bool = False) -> None: """Initialize the target APIs list.""" self._apis = apis self._concrete_art_mgr = concrete_artifacts_manager self._offline = offline # Prevent all GalaxyAPI calls @property def is_offline_mode_requested(self): return self._offline def _assert_that_offline_mode_is_not_requested(self) -> None: if self.is_offline_mode_requested: raise NotImplementedError("The calling code is not supposed to be invoked in 'offline' mode.") def _get_collection_versions(self, requirement: Requirement) -> t.Iterator[tuple[GalaxyAPI, str]]: """Helper for get_collection_versions. Yield api, version pairs for all APIs, and reraise the last error if no valid API was found. """ if self._offline: return found_api = False last_error: Exception | None = None api_lookup_order = ( (requirement.src, ) if isinstance(requirement.src, GalaxyAPI) else self._apis ) for api in api_lookup_order: try: versions = api.get_collection_versions(requirement.namespace, requirement.name) except GalaxyError as api_err: last_error = api_err except Exception as unknown_err: display.warning( "Skipping Galaxy server {server!s}. " "Got an unexpected error when getting " "available versions of collection {fqcn!s}: {err!s}". format( server=api.api_server, fqcn=requirement.fqcn, err=to_text(unknown_err), ) ) last_error = unknown_err else: found_api = True for version in versions: yield api, version if not found_api and last_error is not None: raise last_error def get_collection_versions(self, requirement: Requirement) -> t.Iterable[tuple[str, GalaxyAPI]]: """Get a set of unique versions for FQCN on Galaxy servers.""" if requirement.is_concrete_artifact: return { ( self._concrete_art_mgr. get_direct_collection_version(requirement), requirement.src, ), } api_lookup_order = ( (requirement.src, ) if isinstance(requirement.src, GalaxyAPI) else self._apis ) return set( (version, api) for api, version in self._get_collection_versions( requirement, ) ) def get_collection_version_metadata(self, collection_candidate: Candidate) -> CollectionVersionMetadata: """Retrieve collection metadata of a given candidate.""" self._assert_that_offline_mode_is_not_requested() api_lookup_order = ( (collection_candidate.src, ) if isinstance(collection_candidate.src, GalaxyAPI) else self._apis ) last_err: t.Optional[Exception] for api in api_lookup_order: try: version_metadata = api.get_collection_version_metadata( collection_candidate.namespace, collection_candidate.name, collection_candidate.ver, ) except GalaxyError as api_err: last_err = api_err except Exception as unknown_err: # `verify` doesn't use `get_collection_versions` since the version is already known. # Do the same as `install` and `download` by trying all APIs before failing. # Warn for debugging purposes, since the Galaxy server may be unexpectedly down. last_err = unknown_err display.warning( "Skipping Galaxy server {server!s}. " "Got an unexpected error when getting " "available versions of collection {fqcn!s}: {err!s}". format( server=api.api_server, fqcn=collection_candidate.fqcn, err=to_text(unknown_err), ) ) else: self._concrete_art_mgr.save_collection_source( collection_candidate, version_metadata.download_url, version_metadata.artifact_sha256, api.token, version_metadata.signatures_url, version_metadata.signatures, ) return version_metadata raise last_err def get_collection_dependencies(self, collection_candidate: Candidate) -> dict[str, str]: # FIXME: return Requirement instances instead? """Retrieve collection dependencies of a given candidate.""" if collection_candidate.is_concrete_artifact: return ( self. _concrete_art_mgr. get_direct_collection_dependencies )(collection_candidate) return ( self. get_collection_version_metadata(collection_candidate). dependencies ) def get_signatures(self, collection_candidate: Candidate) -> list[str]: self._assert_that_offline_mode_is_not_requested() namespace = collection_candidate.namespace name = collection_candidate.name version = collection_candidate.ver last_err: Exception | None = None api_lookup_order = ( (collection_candidate.src, ) if isinstance(collection_candidate.src, GalaxyAPI) else self._apis ) for api in api_lookup_order: try: return api.get_collection_signatures(namespace, name, version) except GalaxyError as api_err: last_err = api_err except Exception as unknown_err: # Warn for debugging purposes, since the Galaxy server may be unexpectedly down. last_err = unknown_err display.warning( "Skipping Galaxy server {server!s}. " "Got an unexpected error when getting " "available versions of collection {fqcn!s}: {err!s}". format( server=api.api_server, fqcn=collection_candidate.fqcn, err=to_text(unknown_err), ) ) if last_err: raise last_err return []
MultiGalaxyAPIProxy
python
great-expectations__great_expectations
great_expectations/execution_engine/execution_engine.py
{ "start": 3295, "end": 3552 }
class ____: """compute_domain_kwargs, accessor_domain_kwargs when partitioned from domain_kwargs The union of compute_domain_kwargs, accessor_domain_kwargs is the input domain_kwargs """ compute: dict accessor: dict
PartitionDomainKwargs
python
django__django
tests/contenttypes_tests/models.py
{ "start": 1467, "end": 1688 }
class ____(FooWithoutUrl): """ Fake model defining a ``get_absolute_url`` method containing an error """ def get_absolute_url(self): return "/users/%s/" % self.unknown_field
FooWithBrokenAbsoluteUrl
python
streamlit__streamlit
lib/streamlit/testing/v1/element_tree.py
{ "start": 6814, "end": 7439 }
class ____(Element, ABC): """Widget base class for testing.""" id: str = field(repr=False) disabled: bool key: str | None _value: Any def __init__(self, proto: Any, root: ElementTree) -> None: self.proto = proto self.root = root self.key = user_key_from_element_id(self.id) self._value = None def set_value(self, v: Any) -> Self: """Set the value of the widget.""" self._value = v return self @property @abstractmethod def _widget_state(self) -> WidgetState: ... El_co = TypeVar("El_co", bound=Element, covariant=True)
Widget
python
airbytehq__airbyte
airbyte-ci/connectors/metadata_service/lib/tests/test_registry.py
{ "start": 3770, "end": 5172 }
class ____: """Tests for _convert_json_to_metrics_dict function.""" @pytest.mark.parametrize( "jsonl_input,expected_output,description", [ ( '{"_airbyte_data": {"connector_definition_id": "conn-123", "airbyte_platform": "cloud", "usage": 100}}', {"conn-123": {"cloud": {"connector_definition_id": "conn-123", "airbyte_platform": "cloud", "usage": 100}}}, "single connector", ), ( '{"_airbyte_data": {"connector_definition_id": "conn-123", "airbyte_platform": "cloud", "usage": 100}}\n{"_airbyte_data": {"connector_definition_id": "conn-456", "airbyte_platform": "oss", "usage": 50}}', { "conn-123": {"cloud": {"connector_definition_id": "conn-123", "airbyte_platform": "cloud", "usage": 100}}, "conn-456": {"oss": {"connector_definition_id": "conn-456", "airbyte_platform": "oss", "usage": 50}}, }, "multiple connectors", ), ("", {}, "empty input"), ], ) def test_convert_json_to_metrics_dict_valid_jsonl(self, jsonl_input, expected_output, description): """Test JSONL string conversion to metrics dictionary.""" result = _convert_json_to_metrics_dict(jsonl_input) assert result == expected_output
TestConvertJsonToMetricsDict
python
ethereum__web3.py
web3/types.py
{ "start": 9785, "end": 9882 }
class ____(TypedDict): key: HexStr proof: Sequence[HexStr] value: HexBytes
StorageProof
python
doocs__leetcode
solution/2600-2699/2646.Minimize the Total Price of the Trips/Solution.py
{ "start": 0, "end": 927 }
class ____: def minimumTotalPrice( self, n: int, edges: List[List[int]], price: List[int], trips: List[List[int]] ) -> int: def dfs(i: int, fa: int, k: int) -> bool: cnt[i] += 1 if i == k: return True ok = any(j != fa and dfs(j, i, k) for j in g[i]) if not ok: cnt[i] -= 1 return ok def dfs2(i: int, fa: int) -> (int, int): a = cnt[i] * price[i] b = a // 2 for j in g[i]: if j != fa: x, y = dfs2(j, i) a += min(x, y) b += x return a, b g = [[] for _ in range(n)] for a, b in edges: g[a].append(b) g[b].append(a) cnt = Counter() for start, end in trips: dfs(start, -1, end) return min(dfs2(0, -1))
Solution
python
getsentry__sentry
tests/sentry/auth_v2/utils/test_session.py
{ "start": 327, "end": 802 }
class ____(SessionBase): """Mock session class for testing.""" def __init__(self): self.data = {} def get(self, key, default=None): return self.data.get(key, default) def __getitem__(self, key): return self.data[key] def __setitem__(self, key, value): self.data[key] = value def __contains__(self, key): return key in self.data def get_expiry_date(self, **kwargs): return EXPIRY_DATE
MockSession
python
davidhalter__parso
parso/python/errors.py
{ "start": 45516, "end": 45795 }
class ____(_CheckAssignmentRule): def is_issue(self, del_stmt): child = del_stmt.children[1] if child.type != 'expr_list': # Already handled. self._check_assignment(child, is_deletion=True) @ErrorFinder.register_rule(type='expr_list')
_DelStmtRule
python
getsentry__sentry
tests/sentry/sentry_apps/models/test_sentryapp.py
{ "start": 460, "end": 4144 }
class ____(TestCase): def setUp(self) -> None: self.user = self.create_user() self.org = self.create_organization(owner=self.user) self.proxy = self.create_user() self.application = ApiApplication.objects.create(owner=self.proxy) self.sentry_app = SentryApp( application=self.application, name="NullDB", proxy_user=self.proxy, owner_id=self.org.id, scope_list=("project:read",), webhook_url="http://example.com", slug="nulldb", ) self.sentry_app.save() def test_paranoid(self) -> None: self.sentry_app.save() self.sentry_app.delete() assert self.sentry_app.date_deleted is not None assert self.sentry_app not in SentryApp.objects.all() def test_date_updated(self) -> None: self.sentry_app.save() date_updated = self.sentry_app.date_updated self.sentry_app.save() assert not self.sentry_app.date_updated == date_updated def test_related_names(self) -> None: self.sentry_app.save() assert self.sentry_app.application is not None assert self.sentry_app.proxy_user is not None assert self.sentry_app.application.sentry_app == self.sentry_app assert self.sentry_app.proxy_user.sentry_app == self.sentry_app def test_is_unpublished(self) -> None: self.sentry_app.status = SentryAppStatus.UNPUBLISHED self.sentry_app.save() assert self.sentry_app.is_unpublished def test_is_published(self) -> None: self.sentry_app.status = SentryAppStatus.PUBLISHED self.sentry_app.save() assert self.sentry_app.is_published def test_is_internal(self) -> None: self.sentry_app.status = SentryAppStatus.INTERNAL self.sentry_app.save() assert self.sentry_app.is_internal def test_is_installed_on(self) -> None: other_app = self.create_sentry_app() self.create_sentry_app_installation( organization=self.org, slug=self.sentry_app.slug, prevent_token_exchange=True ) assert self.sentry_app.is_installed_on(self.org) assert not other_app.is_installed_on(self.org) def test_not_installed_on_org(self) -> None: other_org = self.create_organization() self.create_sentry_app_installation( organization=other_org, slug=self.sentry_app.slug, prevent_token_exchange=True ) assert not self.sentry_app.is_installed_on(self.org) def test_save_outbox_update(self) -> None: # Clear the outbox created in setup() ControlOutbox.objects.filter(category=OutboxCategory.SENTRY_APP_UPDATE).delete() self.sentry_app.update(name="NoneDB") outboxes = ControlOutbox.objects.filter(category=OutboxCategory.SENTRY_APP_UPDATE).all() assert len(outboxes) == 2 assert outboxes[0].shard_identifier == self.sentry_app.id assert outboxes[0].region_name def test_regions_with_installations(self) -> None: self.us_org = self.create_organization(name="us test name", region="us") self.create_sentry_app_installation( organization=self.us_org, slug=self.sentry_app.slug, prevent_token_exchange=True ) assert self.sentry_app.regions_with_installations() == {"us"} self.eu_org = self.create_organization(name="eu test name", region="eu") self.create_sentry_app_installation( organization=self.eu_org, slug=self.sentry_app.slug, prevent_token_exchange=True ) assert self.sentry_app.regions_with_installations() == {"us", "eu"}
SentryAppTest
python
pypa__warehouse
tests/unit/admin/views/test_helpscout.py
{ "start": 227, "end": 3955 }
class ____: def test_no_secret(self, db_request): db_request.headers["X-HelpScout-Signature"] = base64.b64encode(b"bitsnbytes") result = views.helpscout(db_request) assert result == {"Error": "NotAuthorized"} def test_no_auth(self, db_request): db_request.registry.settings["admin.helpscout.app_secret"] = "s3cr3t" result = views.helpscout(db_request) assert result == {"Error": "NotAuthorized"} def test_invalid_auth(self, db_request): db_request.body = b"" db_request.registry.settings["admin.helpscout.app_secret"] = "s3cr3t" db_request.headers["X-HelpScout-Signature"] = base64.b64encode(b"bitsnbytes") result = views.helpscout(db_request) assert result == {"Error": "NotAuthorized"} def test_valid_auth_no_payload(self, db_request): db_request.registry.settings["admin.helpscout.app_secret"] = "s3cr3t" db_request.body = b"{}" db_request.json_body = {} db_request.headers["X-HelpScout-Signature"] = base64.b64encode( hmac.digest( db_request.registry.settings["admin.helpscout.app_secret"].encode(), db_request.body, hashlib.sha1, ) ) result = views.helpscout(db_request) assert result == { "html": '<span class="badge pending">No PyPI user found</span>' } @pytest.mark.parametrize( "search_email", [ "wutang@loudrecords.com", "wutang+pypi@loudrecords.com", ], ) def test_valid_auth_no_such_email(self, db_request, search_email): EmailFactory.create(email="wutang@defjam.com") db_request.registry.settings["admin.helpscout.app_secret"] = "s3cr3t" db_request.json_body = {"customer": {"email": search_email}} db_request.body = json.dumps(db_request.json_body).encode() db_request.headers["X-HelpScout-Signature"] = base64.b64encode( hmac.digest( db_request.registry.settings["admin.helpscout.app_secret"].encode(), db_request.body, hashlib.sha1, ) ) result = views.helpscout(db_request) assert result == { "html": '<span class="badge pending">No PyPI user found</span>' } @pytest.mark.parametrize( ("search_email", "user_email"), [ ("wutang@loudrecords.com", "wutang@loudrecords.com"), ("wutang+pypi@loudrecords.com", "wutang@loudrecords.com"), ("wutang@loudrecords.com", "wutang+pypi@loudrecords.com"), ], ) def test_valid_auth_email_found(self, db_request, search_email, user_email): email = EmailFactory.create(email=user_email) db_request.registry.settings["admin.helpscout.app_secret"] = "s3cr3t" db_request.json_body = {"customer": {"email": f"{search_email}"}} db_request.body = json.dumps(db_request.json_body).encode() db_request.headers["X-HelpScout-Signature"] = base64.b64encode( hmac.digest( db_request.registry.settings["admin.helpscout.app_secret"].encode(), db_request.body, hashlib.sha1, ) ) db_request.route_url = pretend.call_recorder( lambda *a, **kw: "http://example.com" ) result = views.helpscout(db_request) assert db_request.route_url.calls == [ pretend.call("accounts.profile", username=email.user.username), pretend.call("admin.user.detail", username=email.user.username), ] assert result["html"][:26] == '<div class="c-sb-section">'
TestHelpscoutApp
python
apache__thrift
lib/py/test/thrift_TSerializer.py
{ "start": 1419, "end": 2767 }
class ____(unittest.TestCase): def setUp(self): self.message = Message("hello thrift", 42) self.binary_serialized = b"\x0b\x00\x01\x00\x00\x00\x0chello thrift\n\x00\x02\x00\x00\x00\x00\x00\x00\x00*\x00" self.compact_serialized = b'\x18\x0chello thrift\x16T\x00' def verify(self, serialized, factory): self.assertEqual(serialized, serialize(self.message, factory)) self.assertEqual( "hello thrift", deserialize(Message(), serialized, factory).body, ) self.assertEqual( 42, deserialize(Message(), serialized, factory).num ) self.assertRaises(EOFError, deserialize, Message(), b'', factory) def test_TBinaryProtocol(self): factory = TBinaryProtocolFactory() self.verify(self.binary_serialized, factory) def test_TBinaryProtocolAccelerated(self): factory = TBinaryProtocolAcceleratedFactory() self.verify(self.binary_serialized, factory) def test_TCompactProtocol(self): factory = TCompactProtocolFactory() self.verify(self.compact_serialized, factory) def test_TCompactProtocolAccelerated(self): factory = TCompactProtocolAcceleratedFactory() self.verify(self.compact_serialized, factory) if __name__ == "__main__": unittest.main()
TestSerializer
python
run-llama__llama_index
llama-index-core/llama_index/core/schema.py
{ "start": 40435, "end": 44679 }
class ____(Document): """Backward compatible wrapper around Document containing an image.""" def __init__(self, **kwargs: Any) -> None: image = kwargs.pop("image", None) image_path = kwargs.pop("image_path", None) image_url = kwargs.pop("image_url", None) image_mimetype = kwargs.pop("image_mimetype", None) text_embedding = kwargs.pop("text_embedding", None) if image: kwargs["image_resource"] = MediaResource( data=image, mimetype=image_mimetype ) elif image_path: if not is_image_pil(image_path): raise ValueError("The specified file path is not an accessible image") kwargs["image_resource"] = MediaResource( path=image_path, mimetype=image_mimetype ) elif image_url: if not is_image_url_pil(image_url): raise ValueError("The specified URL is not an accessible image") kwargs["image_resource"] = MediaResource( url=image_url, mimetype=image_mimetype ) super().__init__(**kwargs) @property def image(self) -> str | None: if self.image_resource and self.image_resource.data: return self.image_resource.data.decode("utf-8") return None @image.setter def image(self, image: str) -> None: self.image_resource = MediaResource(data=image.encode("utf-8")) @property def image_path(self) -> str | None: if self.image_resource and self.image_resource.path: return str(self.image_resource.path) return None @image_path.setter def image_path(self, image_path: str) -> None: self.image_resource = MediaResource(path=Path(image_path)) @property def image_url(self) -> str | None: if self.image_resource and self.image_resource.url: return str(self.image_resource.url) return None @image_url.setter def image_url(self, image_url: str) -> None: self.image_resource = MediaResource(url=AnyUrl(url=image_url)) @property def image_mimetype(self) -> str | None: if self.image_resource: return self.image_resource.mimetype return None @image_mimetype.setter def image_mimetype(self, image_mimetype: str) -> None: if self.image_resource: self.image_resource.mimetype = image_mimetype @property def text_embedding(self) -> list[float] | None: if self.text_resource and self.text_resource.embeddings: return self.text_resource.embeddings.get("dense") return None @text_embedding.setter def text_embedding(self, embeddings: list[float]) -> None: if self.text_resource: if self.text_resource.embeddings is None: self.text_resource.embeddings = {} self.text_resource.embeddings["dense"] = embeddings @classmethod def class_name(cls) -> str: return "ImageDocument" def resolve_image(self, as_base64: bool = False) -> BytesIO: """ Resolve an image such that PIL can read it. Args: as_base64 (bool): whether the resolved image should be returned as base64-encoded bytes """ if self.image_resource is None: return BytesIO() if self.image_resource.data is not None: if as_base64: return BytesIO(self.image_resource.data) return BytesIO(base64.b64decode(self.image_resource.data)) elif self.image_resource.path is not None: img_bytes = self.image_resource.path.read_bytes() if as_base64: return BytesIO(base64.b64encode(img_bytes)) return BytesIO(img_bytes) elif self.image_resource.url is not None: # load image from URL response = requests.get(str(self.image_resource.url), timeout=(60, 60)) img_bytes = response.content if as_base64: return BytesIO(base64.b64encode(img_bytes)) return BytesIO(img_bytes) else: raise ValueError("No image found in the chat message!") @dataclass
ImageDocument
python
encode__starlette
starlette/routing.py
{ "start": 21532, "end": 22382 }
class ____(AbstractAsyncContextManager[_T]): def __init__(self, cm: AbstractContextManager[_T]): self._cm = cm async def __aenter__(self) -> _T: return self._cm.__enter__() async def __aexit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: types.TracebackType | None, ) -> bool | None: return self._cm.__exit__(exc_type, exc_value, traceback) def _wrap_gen_lifespan_context( lifespan_context: Callable[[Any], Generator[Any, Any, Any]], ) -> Callable[[Any], AbstractAsyncContextManager[Any]]: cmgr = contextlib.contextmanager(lifespan_context) @functools.wraps(cmgr) def wrapper(app: Any) -> _AsyncLiftContextManager[Any]: return _AsyncLiftContextManager(cmgr(app)) return wrapper
_AsyncLiftContextManager
python
huggingface__transformers
tests/models/moshi/test_modeling_moshi.py
{ "start": 37201, "end": 43782 }
class ____(unittest.TestCase): @cached_property def feature_extractor(self): return AutoFeatureExtractor.from_pretrained("kmhf/hf-moshiko") @cached_property def tokenizer(self): return AutoTokenizer.from_pretrained("kmhf/hf-moshiko") def _load_datasample(self): ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") dataset = ds.cast_column("audio", Audio(sampling_rate=self.feature_extractor.sampling_rate)) # automatic decoding with librispeech speech_sample = dataset.sort("id")[0]["audio"]["array"] return speech_sample @slow def test_moshika_conditional_greedy(self): model = MoshiForConditionalGeneration.from_pretrained( "kmhf/hf-moshika", dtype=torch.float16, device_map="auto" ) inputs = self.feature_extractor(self._load_datasample(), return_tensors="pt").to( device=torch_device, dtype=torch.float16 ) user_audio_codes = model.audio_encoder.encode(**inputs, num_quantizers=8).audio_codes input_ids = self.tokenizer.encode("<pad><pad><pad><pad><unk> Hello,<pad><unk>", return_tensors="pt").to( torch_device ) # fmt: off moshi_audio_codes = [[[1049, 127, 1880, 972, 972, 1156, 1913, 415, 1933], [1700, 243, 91, 91, 91, 745, 1478, 638, 57], [1626, 457, 457, 457, 457, 1839, 200, 2011, 1142], [546, 290, 390, 390, 290, 1408, 1812, 1187, 1911], [306, 306, 1314, 1314, 1314, 759, 796, 854, 1466], [1443, 1443, 1030, 317, 347, 1178, 613, 1576, 2023], [1871, 428, 1433, 1433, 1978, 1405, 1755, 820, 610], [2008, 1744, 1511, 568, 1533, 550, 237, 1412, 1401]]] # fmt: on moshi_audio_codes = torch.tensor(moshi_audio_codes, device=torch_device) user_audio_codes = user_audio_codes[:, :, : moshi_audio_codes.shape[-1]] model_outputs = model.generate( user_audio_codes=user_audio_codes, moshi_audio_codes=moshi_audio_codes, input_ids=input_ids, do_sample=False, depth_decoder_do_sample=False, return_audio_codes=True, max_new_tokens=2, ) expected_text_token = 452 expected_audio_tokens = [916, 1396, 1238, 579, 1105, 914, 1257, 810] # fmt: skip self.assertTrue(expected_text_token == model_outputs.sequences[0, -2].item()) self.assertTrue(expected_audio_tokens == model_outputs.audio_codes[0, :, -1].tolist()) @slow def test_moshiko_greedy_unconditional_fp16_eager(self): model = MoshiForConditionalGeneration.from_pretrained( "kmhf/hf-moshiko", dtype=torch.float16, device_map="auto" ) some_expected_audio_tokens = [[1049, 127], [1700, 243], [1626, 457], [546, 290], [306, 306], [1443, 1443], [1871, 428], [2008, 1744]] # fmt: skip model_outputs = model.generate( do_sample=False, depth_decoder_do_sample=False, return_audio_codes=True, max_new_tokens=10 ) # eager equivalence is not as strict as sdpa. self.assertTrue(some_expected_audio_tokens == model_outputs.audio_codes[0, :, :2].tolist()) @slow def test_moshiko_greedy_unconditional_fp32(self): model = MoshiForConditionalGeneration.from_pretrained( "kmhf/hf-moshiko", dtype=torch.float32, device_map="auto" ) expected_audio_codesum = 72065 expected_text_tokens = [3, 3, 3, 0, 11725, 261, 3, 3, 3, 3] # fmt: skip some_expected_audio_tokens = [[1049, 127], [1700, 243], [1626, 457], [546, 290], [306, 306], [1443, 1443], [1871, 428], [2008, 1744]] # fmt: skip model_outputs = model.generate( do_sample=False, depth_decoder_do_sample=False, return_audio_codes=True, max_new_tokens=10 ) # make sure audio encoded codes are correct audio_code_sums = model_outputs.audio_codes.sum().item() self.assertTrue(np.abs(audio_code_sums - expected_audio_codesum) <= (3e-3 * audio_code_sums)) self.assertTrue(expected_text_tokens == model_outputs.sequences[0, 1:].tolist()) self.assertTrue(some_expected_audio_tokens == model_outputs.audio_codes[0, :, :2].tolist()) @slow @require_torch_fp16 def test_moshiko_greedy_unconditional_fp16(self): model = MoshiForConditionalGeneration.from_pretrained( "kmhf/hf-moshiko", dtype=torch.float16, device_map="auto" ) expected_audio_codesum = 72065 expected_text_tokens = [3, 3, 3, 0, 11725, 261, 3, 3, 3, 3] # fmt: skip some_expected_audio_tokens = [[1049, 127], [1700, 243], [1626, 457], [546, 290], [306, 306], [1443, 1443], [1871, 428], [2008, 1744]] # fmt: skip model_outputs = model.generate( do_sample=False, depth_decoder_do_sample=False, return_audio_codes=True, max_new_tokens=10 ) # make sure audio encoded codes are correct audio_code_sums = model_outputs.audio_codes.sum().item() self.assertTrue(np.abs(audio_code_sums - expected_audio_codesum) <= (3e-3 * audio_code_sums)) self.assertTrue(expected_text_tokens == model_outputs.sequences[0, 1:].tolist()) self.assertTrue(some_expected_audio_tokens == model_outputs.audio_codes[0, :, :2].tolist()) @slow @require_torch_fp16 def test_moshika_greedy_unconditional_fp16(self): model = MoshiForConditionalGeneration.from_pretrained( "kmhf/hf-moshika", dtype=torch.float16, device_map="auto" ) expected_audio_codesum = 72932 expected_text_tokens = [3, 3, 3, 0, 667, 263, 3, 3, 0, 705] # fmt: skip some_expected_audio_tokens = [[1049, 127], [1700, 243], [1626, 457], [546, 290], [306, 306], [1443, 347], [1871, 428], [2008, 2008]] # fmt: skip model_outputs = model.generate( do_sample=False, depth_decoder_do_sample=False, return_audio_codes=True, max_new_tokens=10 ) # make sure audio encoded codes are correct audio_code_sums = model_outputs.audio_codes.sum().item() self.assertTrue(np.abs(audio_code_sums - expected_audio_codesum) <= 2048) self.assertTrue(expected_text_tokens == model_outputs.sequences[0, 1:].tolist()) self.assertTrue(some_expected_audio_tokens == model_outputs.audio_codes[0, :, :2].tolist())
MoshiIntegrationTests
python
Textualize__textual
tests/option_list/test_option_messages.py
{ "start": 264, "end": 4303 }
class ____(App[None]): """Test option list application.""" def __init__(self) -> None: super().__init__() self.messages: list[tuple[str, str, int]] = [] def compose(self) -> ComposeResult: yield OptionList(*[Option(str(n), id=str(n)) for n in range(10)]) def _record(self, event: OptionList.OptionMessage) -> None: assert isinstance(event.option_id, str) assert event.option_list is event.control self.messages.append( (event.__class__.__name__, event.option_id, event.option_index) ) def on_option_list_option_highlighted( self, event: OptionList.OptionHighlighted ) -> None: self._record(event) def on_option_list_option_selected(self, event: OptionList.OptionSelected) -> None: self._record(event) async def test_messages_on_startup() -> None: """There should be a highlighted message when a non-empty option list first starts up.""" async with OptionListApp().run_test() as pilot: assert isinstance(pilot.app, OptionListApp) await pilot.pause() assert pilot.app.messages == [("OptionHighlighted", "0", 0)] async def test_same_highlight_message() -> None: """Highlighting a highlight should result in no message.""" async with OptionListApp().run_test() as pilot: assert isinstance(pilot.app, OptionListApp) await pilot.pause() pilot.app.query_one(OptionList).highlighted = 0 await pilot.pause() assert pilot.app.messages == [("OptionHighlighted", "0", 0)] async def test_highlight_disabled_option_no_message() -> None: """Highlighting a disabled option should result in no messages.""" async with OptionListApp().run_test() as pilot: assert isinstance(pilot.app, OptionListApp) await pilot.pause() pilot.app.query_one(OptionList).disable_option("1") pilot.app.query_one(OptionList).highlighted = 1 await pilot.pause() assert pilot.app.messages[1:] == [] async def test_new_highlight() -> None: """Setting the highlight to a new option should result in a message.""" async with OptionListApp().run_test() as pilot: assert isinstance(pilot.app, OptionListApp) await pilot.pause() pilot.app.query_one(OptionList).highlighted = 2 await pilot.pause() assert pilot.app.messages[1:] == [("OptionHighlighted", "2", 2)] async def test_move_highlight_with_keyboard() -> None: """Changing option via the keyboard should result in a message.""" async with OptionListApp().run_test() as pilot: assert isinstance(pilot.app, OptionListApp) await pilot.press("tab", "down") assert pilot.app.messages[1:] == [("OptionHighlighted", "1", 1)] async def test_select_message_with_keyboard() -> None: """Hitting enter on an option should result in a message.""" async with OptionListApp().run_test() as pilot: assert isinstance(pilot.app, OptionListApp) await pilot.press("tab", "down", "enter") assert pilot.app.messages[1:] == [ ("OptionHighlighted", "1", 1), ("OptionSelected", "1", 1), ] async def test_click_option_with_mouse() -> None: """Clicking on an option via the mouse should result in highlight and select messages.""" async with OptionListApp().run_test() as pilot: assert isinstance(pilot.app, OptionListApp) await pilot.click(OptionList, Offset(2, 2)) assert pilot.app.messages[1:] == [ ("OptionHighlighted", "1", 1), ("OptionSelected", "1", 1), ] async def test_click_disabled_option_with_mouse() -> None: """Clicking on a disabled option via the mouse should result no messages.""" async with OptionListApp().run_test() as pilot: assert isinstance(pilot.app, OptionListApp) pilot.app.query_one(OptionList).disable_option("1") await pilot.click(OptionList, Offset(1, 1)) assert pilot.app.messages[1:] == []
OptionListApp
python
GoogleCloudPlatform__python-docs-samples
endpoints/bookstore-grpc-transcoding/bookstore_pb2_grpc.py
{ "start": 3277, "end": 7927 }
class ____: """A simple Bookstore API. The API manages shelves and books resources. Shelves contain books. """ def ListShelves(self, request, context): """Returns a list of all shelves in the bookstore.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def CreateShelf(self, request, context): """Creates a new shelf in the bookstore.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def GetShelf(self, request, context): """Returns a specific bookstore shelf.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def DeleteShelf(self, request, context): """Deletes a shelf, including all books that are stored on the shelf.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def ListBooks(self, request, context): """Returns a list of books on a shelf.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def CreateBook(self, request, context): """Creates a new book.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def GetBook(self, request, context): """Returns a specific book.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def DeleteBook(self, request, context): """Deletes a book from a shelf.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def add_BookstoreServicer_to_server(servicer, server): rpc_method_handlers = { "ListShelves": grpc.unary_unary_rpc_method_handler( servicer.ListShelves, request_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, response_serializer=bookstore__pb2.ListShelvesResponse.SerializeToString, ), "CreateShelf": grpc.unary_unary_rpc_method_handler( servicer.CreateShelf, request_deserializer=bookstore__pb2.CreateShelfRequest.FromString, response_serializer=bookstore__pb2.Shelf.SerializeToString, ), "GetShelf": grpc.unary_unary_rpc_method_handler( servicer.GetShelf, request_deserializer=bookstore__pb2.GetShelfRequest.FromString, response_serializer=bookstore__pb2.Shelf.SerializeToString, ), "DeleteShelf": grpc.unary_unary_rpc_method_handler( servicer.DeleteShelf, request_deserializer=bookstore__pb2.DeleteShelfRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, ), "ListBooks": grpc.unary_unary_rpc_method_handler( servicer.ListBooks, request_deserializer=bookstore__pb2.ListBooksRequest.FromString, response_serializer=bookstore__pb2.ListBooksResponse.SerializeToString, ), "CreateBook": grpc.unary_unary_rpc_method_handler( servicer.CreateBook, request_deserializer=bookstore__pb2.CreateBookRequest.FromString, response_serializer=bookstore__pb2.Book.SerializeToString, ), "GetBook": grpc.unary_unary_rpc_method_handler( servicer.GetBook, request_deserializer=bookstore__pb2.GetBookRequest.FromString, response_serializer=bookstore__pb2.Book.SerializeToString, ), "DeleteBook": grpc.unary_unary_rpc_method_handler( servicer.DeleteBook, request_deserializer=bookstore__pb2.DeleteBookRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( "endpoints.examples.bookstore.Bookstore", rpc_method_handlers ) server.add_generic_rpc_handlers((generic_handler,))
BookstoreServicer
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 221014, "end": 221589 }
class ____(Operation): def call(self, x): return backend.numpy.negative(x) def compute_output_spec(self, x): sparse = getattr(x, "sparse", False) return KerasTensor(x.shape, dtype=x.dtype, sparse=sparse) @keras_export(["keras.ops.negative", "keras.ops.numpy.negative"]) def negative(x): """Numerical negative, element-wise. Args: x: Input tensor. Returns: Output tensor, `y = -x`. """ if any_symbolic_tensors((x,)): return Negative().symbolic_call(x) return backend.numpy.negative(x)
Negative
python
readthedocs__readthedocs.org
readthedocs/core/unresolver.py
{ "start": 979, "end": 1041 }
class ____(UnresolverError): pass
InvalidXRTDSlugHeaderError