language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
pytorch__pytorch
benchmarks/dynamo/pr_time_benchmarks/benchmarks/basic_modules_benchmarks.py
{ "start": 137, "end": 505 }
class ____(nn.Module): def __init__(self): super().__init__() self.linears = nn.ModuleList([nn.Linear(10, 10) for i in range(20)]) def forward(self, x): # ModuleList can act as an iterable, or be indexed using ints for i, l in enumerate(self.linears): x = self.linears[i // 2](x) + l(x) return x
ListOfLinears
python
apache__airflow
airflow-core/src/airflow/models/taskmap.py
{ "start": 1730, "end": 1950 }
class ____(enum.Enum): """ Task map variant. Possible values are **dict** (for a key-value mapping) and **list** (for an ordered value sequence). """ DICT = "dict" LIST = "list"
TaskMapVariant
python
huggingface__transformers
src/transformers/models/granite/modular_granite.py
{ "start": 5051, "end": 9168 }
class ____(LlamaModel): def __init__(self, config: GraniteConfig): super().__init__(config) self.embedding_multiplier = config.embedding_multiplier self.layers = nn.ModuleList( [GraniteDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> BaseModelOutputWithPast: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if self.gradient_checkpointing and self.training and use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`." ) use_cache = False if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids) inputs_embeds = inputs_embeds * self.embedding_multiplier # main diff with Llama if use_cache and past_key_values is None: past_key_values = DynamicCache(config=self.config) if cache_position is None: past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 cache_position = torch.arange( past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device ) if position_ids is None: position_ids = cache_position.unsqueeze(0) causal_mask = create_causal_mask( config=self.config, input_embeds=inputs_embeds, attention_mask=attention_mask, cache_position=cache_position, past_key_values=past_key_values, position_ids=position_ids, ) hidden_states = inputs_embeds position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids) # decoder layers all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None for decoder_layer in self.layers[: self.config.num_hidden_layers]: if output_hidden_states: all_hidden_states += (hidden_states,) layer_outputs = decoder_layer( hidden_states, attention_mask=causal_mask, position_ids=position_ids, past_key_values=past_key_values, output_attentions=output_attentions, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, **kwargs, ) hidden_states = layer_outputs[0] if output_attentions: all_self_attns += (layer_outputs[1],) hidden_states = self.norm(hidden_states) # add hidden states from the last decoder layer if output_hidden_states: all_hidden_states += (hidden_states,) return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=past_key_values if use_cache else None, hidden_states=all_hidden_states, attentions=all_self_attns, )
GraniteModel
python
Pylons__pyramid
tests/test_viewderivers.py
{ "start": 68209, "end": 70369 }
class ____(unittest.TestCase): def setUp(self): self.config = testing.setUp() def tearDown(self): self.config = None testing.tearDown() def _getViewCallable( self, config, ctx_iface=None, request_iface=None, name='' ): from zope.interface import Interface from pyramid.interfaces import IRequest, IView, IViewClassifier classifier = IViewClassifier if ctx_iface is None: ctx_iface = Interface if request_iface is None: request_iface = IRequest return config.registry.adapters.lookup( (classifier, request_iface, ctx_iface), IView, name=name, default=None, ) def _makeRequest(self, config): request = DummyRequest() request.registry = config.registry return request def test_view_options(self): response = DummyResponse() view = lambda *arg: response response.deriv = [] def deriv1(view, info): response.deriv.append(info.options['deriv1']) return view deriv1.options = ('deriv1',) def deriv2(view, info): response.deriv.append(info.options['deriv2']) return view deriv2.options = ('deriv2',) self.config.add_view_deriver(deriv1, 'deriv1') self.config.add_view_deriver(deriv2, 'deriv2') self.config.add_view(view, deriv1='test1', deriv2='test2') wrapper = self._getViewCallable(self.config) request = self._makeRequest(self.config) request.method = 'GET' self.assertEqual(wrapper(None, request), response) self.assertEqual(['test1', 'test2'], response.deriv) def test_unexpected_view_options(self): from pyramid.exceptions import ConfigurationError def deriv1(view, info): # pragma: no cover pass self.config.add_view_deriver(deriv1, 'deriv1') self.assertRaises( ConfigurationError, lambda: self.config.add_view(lambda r: {}, deriv1='test1'), ) @implementer(IResponse)
TestDeriverIntegration
python
bokeh__bokeh
src/bokeh/protocol/exceptions.py
{ "start": 1881, "end": 2472 }
class ____(Exception): ''' Indicate an error validating wire protocol fragments. This exception typically indicates that a binary message fragment was received when a text fragment was expected, or vice-versa. ''' pass #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
ValidationError
python
PrefectHQ__prefect
src/prefect/types/entrypoint.py
{ "start": 24, "end": 328 }
class ____(Enum): """ Enum representing a entrypoint type. File path entrypoints are in the format: `path/to/file.py:function_name`. Module path entrypoints are in the format: `path.to.module.function_name`. """ FILE_PATH = "file_path" MODULE_PATH = "module_path"
EntrypointType
python
pennersr__django-allauth
allauth/socialaccount/providers/pocket/provider.py
{ "start": 313, "end": 896 }
class ____(OAuthProvider): id = "pocket" name = "Pocket" account_class = PocketAccount oauth_adapter_class = PocketOAuthAdapter def extract_uid(self, data): return data["username"] def extract_common_fields(self, data): return dict( email=data["username"], ) def extract_email_addresses(self, data): return [ EmailAddress( email=data["username"], verified=True, primary=True, ) ] provider_classes = [PocketProvider]
PocketProvider
python
RaRe-Technologies__gensim
gensim/models/doc2vec.py
{ "start": 6354, "end": 51237 }
class ____(Word2Vec): def __init__( self, documents=None, corpus_file=None, vector_size=100, dm_mean=None, dm=1, dbow_words=0, dm_concat=0, dm_tag_count=1, dv=None, dv_mapfile=None, comment=None, trim_rule=None, callbacks=(), window=5, epochs=10, shrink_windows=True, **kwargs, ): """Class for training, using and evaluating neural networks described in `Distributed Representations of Sentences and Documents <http://arxiv.org/abs/1405.4053v2>`_. Parameters ---------- documents : iterable of list of :class:`~gensim.models.doc2vec.TaggedDocument`, optional Input corpus, can be simply a list of elements, but for larger corpora,consider an iterable that streams the documents directly from disk/network. If you don't supply `documents` (or `corpus_file`), the model is left uninitialized -- use if you plan to initialize it in some other way. corpus_file : str, optional Path to a corpus file in :class:`~gensim.models.word2vec.LineSentence` format. You may use this argument instead of `documents` to get performance boost. Only one of `documents` or `corpus_file` arguments need to be passed (or none of them, in that case, the model is left uninitialized). Documents' tags are assigned automatically and are equal to line number, as in :class:`~gensim.models.doc2vec.TaggedLineDocument`. dm : {1,0}, optional Defines the training algorithm. If `dm=1`, 'distributed memory' (PV-DM) is used. Otherwise, `distributed bag of words` (PV-DBOW) is employed. vector_size : int, optional Dimensionality of the feature vectors. window : int, optional The maximum distance between the current and predicted word within a sentence. alpha : float, optional The initial learning rate. min_alpha : float, optional Learning rate will linearly drop to `min_alpha` as training progresses. seed : int, optional Seed for the random number generator. Initial vectors for each word are seeded with a hash of the concatenation of word + `str(seed)`. Note that for a fully deterministically-reproducible run, you must also limit the model to a single worker thread (`workers=1`), to eliminate ordering jitter from OS thread scheduling. In Python 3, reproducibility between interpreter launches also requires use of the `PYTHONHASHSEED` environment variable to control hash randomization. min_count : int, optional Ignores all words with total frequency lower than this. max_vocab_size : int, optional Limits the RAM during vocabulary building; if there are more unique words than this, then prune the infrequent ones. Every 10 million word types need about 1GB of RAM. Set to `None` for no limit. sample : float, optional The threshold for configuring which higher-frequency words are randomly downsampled, useful range is (0, 1e-5). workers : int, optional Use these many worker threads to train the model (=faster training with multicore machines). epochs : int, optional Number of iterations (epochs) over the corpus. Defaults to 10 for Doc2Vec. hs : {1,0}, optional If 1, hierarchical softmax will be used for model training. If set to 0, and `negative` is non-zero, negative sampling will be used. negative : int, optional If > 0, negative sampling will be used, the int for negative specifies how many "noise words" should be drawn (usually between 5-20). If set to 0, no negative sampling is used. ns_exponent : float, optional The exponent used to shape the negative sampling distribution. A value of 1.0 samples exactly in proportion to the frequencies, 0.0 samples all words equally, while a negative value samples low-frequency words more than high-frequency words. The popular default value of 0.75 was chosen by the original Word2Vec paper. More recently, in https://arxiv.org/abs/1804.04212, Caselles-Dupré, Lesaint, & Royo-Letelier suggest that other values may perform better for recommendation applications. dm_mean : {1,0}, optional If 0, use the sum of the context word vectors. If 1, use the mean. Only applies when `dm` is used in non-concatenative mode. dm_concat : {1,0}, optional If 1, use concatenation of context vectors rather than sum/average; Note concatenation results in a much-larger model, as the input is no longer the size of one (sampled or arithmetically combined) word vector, but the size of the tag(s) and all words in the context strung together. dm_tag_count : int, optional Expected constant number of document tags per document, when using dm_concat mode. dbow_words : {1,0}, optional If set to 1 trains word-vectors (in skip-gram fashion) simultaneous with DBOW doc-vector training; If 0, only trains doc-vectors (faster). trim_rule : function, optional Vocabulary trimming rule, specifies whether certain words should remain in the vocabulary, be trimmed away, or handled using the default (discard if word count < min_count). Can be None (min_count will be used, look to :func:`~gensim.utils.keep_vocab_item`), or a callable that accepts parameters (word, count, min_count) and returns either :attr:`gensim.utils.RULE_DISCARD`, :attr:`gensim.utils.RULE_KEEP` or :attr:`gensim.utils.RULE_DEFAULT`. The rule, if given, is only used to prune vocabulary during current method call and is not stored as part of the model. The input parameters are of the following types: * `word` (str) - the word we are examining * `count` (int) - the word's frequency count in the corpus * `min_count` (int) - the minimum count threshold. callbacks : :obj: `list` of :obj: `~gensim.models.callbacks.CallbackAny2Vec`, optional List of callbacks that need to be executed/run at specific stages during training. shrink_windows : bool, optional New in 4.1. Experimental. If True, the effective window size is uniformly sampled from [1, `window`] for each target word during training, to match the original word2vec algorithm's approximate weighting of context words by distance. Otherwise, the effective window size is always fixed to `window` words to either side. Some important internal attributes are the following: Attributes ---------- wv : :class:`~gensim.models.keyedvectors.KeyedVectors` This object essentially contains the mapping between words and embeddings. After training, it can be used directly to query those embeddings in various ways. See the module level docstring for examples. dv : :class:`~gensim.models.keyedvectors.KeyedVectors` This object contains the paragraph vectors learned from the training data. There will be one such vector for each unique document tag supplied during training. They may be individually accessed using the tag as an indexed-access key. For example, if one of the training documents used a tag of 'doc003': .. sourcecode:: pycon >>> model.dv['doc003'] """ corpus_iterable = documents if dm_mean is not None: self.cbow_mean = dm_mean self.dbow_words = int(dbow_words) self.dm_concat = int(dm_concat) self.dm_tag_count = int(dm_tag_count) if dm and dm_concat: self.layer1_size = (dm_tag_count + (2 * window)) * vector_size logger.info("using concatenative %d-dimensional layer1", self.layer1_size) self.vector_size = vector_size self.dv = dv or KeyedVectors(self.vector_size, mapfile_path=dv_mapfile) # EXPERIMENTAL lockf feature; create minimal no-op lockf arrays (1 element of 1.0) # advanced users should directly resize/adjust as desired after any vocab growth self.dv.vectors_lockf = np.ones(1, dtype=REAL) # 0.0 values suppress word-backprop-updates; 1.0 allows super(Doc2Vec, self).__init__( sentences=corpus_iterable, corpus_file=corpus_file, vector_size=self.vector_size, sg=(1 + dm) % 2, null_word=self.dm_concat, callbacks=callbacks, window=window, epochs=epochs, shrink_windows=shrink_windows, **kwargs, ) @property def dm(self): """Indicates whether 'distributed memory' (PV-DM) will be used, else 'distributed bag of words' (PV-DBOW) is used. """ return not self.sg # opposite of SG @property def dbow(self): """Indicates whether 'distributed bag of words' (PV-DBOW) will be used, else 'distributed memory' (PV-DM) is used. """ return self.sg # same as SG @property @deprecated("The `docvecs` property has been renamed `dv`.") def docvecs(self): return self.dv @docvecs.setter @deprecated("The `docvecs` property has been renamed `dv`.") def docvecs(self, value): self.dv = value def _clear_post_train(self): """Resets the current word vectors. """ self.wv.norms = None self.dv.norms = None def init_weights(self): super(Doc2Vec, self).init_weights() # to not use an identical rnd stream as words, deterministically change seed (w/ 1000th prime) self.dv.resize_vectors(seed=self.seed + 7919) def reset_from(self, other_model): """Copy shareable data structures from another (possibly pre-trained) model. This specifically causes some structures to be shared, so is limited to structures (like those rleated to the known word/tag vocabularies) that won't change during training or thereafter. Beware vocabulary edits/updates to either model afterwards: the partial sharing and out-of-band modification may leave the other model in a broken state. Parameters ---------- other_model : :class:`~gensim.models.doc2vec.Doc2Vec` Other model whose internal data structures will be copied over to the current object. """ self.wv.key_to_index = other_model.wv.key_to_index self.wv.index_to_key = other_model.wv.index_to_key self.wv.expandos = other_model.wv.expandos self.cum_table = other_model.cum_table self.corpus_count = other_model.corpus_count self.dv.key_to_index = other_model.dv.key_to_index self.dv.index_to_key = other_model.dv.index_to_key self.dv.expandos = other_model.dv.expandos self.init_weights() def _do_train_epoch( self, corpus_file, thread_id, offset, cython_vocab, thread_private_mem, cur_epoch, total_examples=None, total_words=None, offsets=None, start_doctags=None, **kwargs ): work, neu1 = thread_private_mem doctag_vectors = self.dv.vectors doctags_lockf = self.dv.vectors_lockf offset = offsets[thread_id] start_doctag = start_doctags[thread_id] if self.sg: examples, tally, raw_tally = d2v_train_epoch_dbow( self, corpus_file, offset, start_doctag, cython_vocab, cur_epoch, total_examples, total_words, work, neu1, len(self.dv), doctag_vectors=doctag_vectors, doctags_lockf=doctags_lockf, train_words=self.dbow_words) elif self.dm_concat: examples, tally, raw_tally = d2v_train_epoch_dm_concat( self, corpus_file, offset, start_doctag, cython_vocab, cur_epoch, total_examples, total_words, work, neu1, len(self.dv), doctag_vectors=doctag_vectors, doctags_lockf=doctags_lockf) else: examples, tally, raw_tally = d2v_train_epoch_dm( self, corpus_file, offset, start_doctag, cython_vocab, cur_epoch, total_examples, total_words, work, neu1, len(self.dv), doctag_vectors=doctag_vectors, doctags_lockf=doctags_lockf) return examples, tally, raw_tally def _do_train_job(self, job, alpha, inits): """Train model using `job` data. Parameters ---------- job : iterable of list of :class:`~gensim.models.doc2vec.TaggedDocument` The corpus chunk to be used for training this batch. alpha : float Learning rate to be used for training this batch. inits : (np.ndarray, np.ndarray) Each worker threads private work memory. Returns ------- (int, int) 2-tuple (effective word count after ignoring unknown words and sentence length trimming, total word count). """ work, neu1 = inits tally = 0 for doc in job: doctag_indexes = [self.dv.get_index(tag) for tag in doc.tags if tag in self.dv] doctag_vectors = self.dv.vectors doctags_lockf = self.dv.vectors_lockf if self.sg: tally += train_document_dbow( self, doc.words, doctag_indexes, alpha, work, train_words=self.dbow_words, doctag_vectors=doctag_vectors, doctags_lockf=doctags_lockf ) elif self.dm_concat: tally += train_document_dm_concat( self, doc.words, doctag_indexes, alpha, work, neu1, doctag_vectors=doctag_vectors, doctags_lockf=doctags_lockf ) else: tally += train_document_dm( self, doc.words, doctag_indexes, alpha, work, neu1, doctag_vectors=doctag_vectors, doctags_lockf=doctags_lockf ) return tally, self._raw_word_count(job) def train( self, corpus_iterable=None, corpus_file=None, total_examples=None, total_words=None, epochs=None, start_alpha=None, end_alpha=None, word_count=0, queue_factor=2, report_delay=1.0, callbacks=(), **kwargs, ): """Update the model's neural weights. To support linear learning-rate decay from (initial) `alpha` to `min_alpha`, and accurate progress-percentage logging, either `total_examples` (count of documents) or `total_words` (count of raw words in documents) **MUST** be provided. If `documents` is the same corpus that was provided to :meth:`~gensim.models.word2vec.Word2Vec.build_vocab` earlier, you can simply use `total_examples=self.corpus_count`. To avoid common mistakes around the model's ability to do multiple training passes itself, an explicit `epochs` argument **MUST** be provided. In the common and recommended case where :meth:`~gensim.models.word2vec.Word2Vec.train` is only called once, you can set `epochs=self.iter`. Parameters ---------- corpus_iterable : iterable of list of :class:`~gensim.models.doc2vec.TaggedDocument`, optional Can be simply a list of elements, but for larger corpora,consider an iterable that streams the documents directly from disk/network. If you don't supply `documents` (or `corpus_file`), the model is left uninitialized -- use if you plan to initialize it in some other way. corpus_file : str, optional Path to a corpus file in :class:`~gensim.models.word2vec.LineSentence` format. You may use this argument instead of `documents` to get performance boost. Only one of `documents` or `corpus_file` arguments need to be passed (not both of them). Documents' tags are assigned automatically and are equal to line number, as in :class:`~gensim.models.doc2vec.TaggedLineDocument`. total_examples : int, optional Count of documents. total_words : int, optional Count of raw words in documents. epochs : int, optional Number of iterations (epochs) over the corpus. start_alpha : float, optional Initial learning rate. If supplied, replaces the starting `alpha` from the constructor, for this one call to `train`. Use only if making multiple calls to `train`, when you want to manage the alpha learning-rate yourself (not recommended). end_alpha : float, optional Final learning rate. Drops linearly from `start_alpha`. If supplied, this replaces the final `min_alpha` from the constructor, for this one call to :meth:`~gensim.models.doc2vec.Doc2Vec.train`. Use only if making multiple calls to :meth:`~gensim.models.doc2vec.Doc2Vec.train`, when you want to manage the alpha learning-rate yourself (not recommended). word_count : int, optional Count of words already trained. Set this to 0 for the usual case of training on all words in documents. queue_factor : int, optional Multiplier for size of queue (number of workers * queue_factor). report_delay : float, optional Seconds to wait before reporting progress. callbacks : :obj: `list` of :obj: `~gensim.models.callbacks.CallbackAny2Vec`, optional List of callbacks that need to be executed/run at specific stages during training. """ if corpus_file is None and corpus_iterable is None: raise TypeError("Either one of corpus_file or corpus_iterable value must be provided") if corpus_file is not None and corpus_iterable is not None: raise TypeError("Both corpus_file and corpus_iterable must not be provided at the same time") if corpus_iterable is None and not os.path.isfile(corpus_file): raise TypeError("Parameter corpus_file must be a valid path to a file, got %r instead" % corpus_file) if corpus_iterable is not None and not isinstance(corpus_iterable, Iterable): raise TypeError("corpus_iterable must be an iterable of TaggedDocument, got %r instead" % corpus_iterable) if corpus_file is not None: # Calculate offsets for each worker along with initial doctags (doctag ~ document/line number in a file) offsets, start_doctags = self._get_offsets_and_start_doctags_for_corpusfile(corpus_file, self.workers) kwargs['offsets'] = offsets kwargs['start_doctags'] = start_doctags super(Doc2Vec, self).train( corpus_iterable=corpus_iterable, corpus_file=corpus_file, total_examples=total_examples, total_words=total_words, epochs=epochs, start_alpha=start_alpha, end_alpha=end_alpha, word_count=word_count, queue_factor=queue_factor, report_delay=report_delay, callbacks=callbacks, **kwargs) @classmethod def _get_offsets_and_start_doctags_for_corpusfile(cls, corpus_file, workers): """Get offset and initial document tag in a corpus_file for each worker. Firstly, approximate offsets are calculated based on number of workers and corpus_file size. Secondly, for each approximate offset we find the maximum offset which points to the beginning of line and less than approximate offset. Parameters ---------- corpus_file : str Path to a corpus file in :class:`~gensim.models.word2vec.LineSentence` format. workers : int Number of workers. Returns ------- list of int, list of int Lists with offsets and document tags with length = number of workers. """ corpus_file_size = os.path.getsize(corpus_file) approx_offsets = [int(corpus_file_size // workers * i) for i in range(workers)] offsets = [] start_doctags = [] with utils.open(corpus_file, mode='rb') as fin: curr_offset_idx = 0 prev_filepos = 0 for line_no, line in enumerate(fin): if curr_offset_idx == len(approx_offsets): break curr_filepos = prev_filepos + len(line) while curr_offset_idx != len(approx_offsets) and approx_offsets[curr_offset_idx] < curr_filepos: offsets.append(prev_filepos) start_doctags.append(line_no) curr_offset_idx += 1 prev_filepos = curr_filepos return offsets, start_doctags def _raw_word_count(self, job): """Get the number of words in a given job. Parameters ---------- job : iterable of list of :class:`~gensim.models.doc2vec.TaggedDocument` Corpus chunk. Returns ------- int Number of raw words in the corpus chunk. """ return sum(len(sentence.words) for sentence in job) def estimated_lookup_memory(self): """Get estimated memory for tag lookup, 0 if using pure int tags. Returns ------- int The estimated RAM required to look up a tag in bytes. """ return 60 * len(self.dv) + 140 * len(self.dv) def infer_vector(self, doc_words, alpha=None, min_alpha=None, epochs=None): """Infer a vector for given post-bulk training document. Notes ----- Subsequent calls to this function may infer different representations for the same document. For a more stable representation, increase the number of epochs to assert a stricter convergence. Parameters ---------- doc_words : list of str A document for which the vector representation will be inferred. alpha : float, optional The initial learning rate. If unspecified, value from model initialization will be reused. min_alpha : float, optional Learning rate will linearly drop to `min_alpha` over all inference epochs. If unspecified, value from model initialization will be reused. epochs : int, optional Number of times to train the new document. Larger values take more time, but may improve quality and run-to-run stability of inferred vectors. If unspecified, the `epochs` value from model initialization will be reused. Returns ------- np.ndarray The inferred paragraph vector for the new document. """ if isinstance(doc_words, str): # a common mistake; fail with a nicer error raise TypeError("Parameter doc_words of infer_vector() must be a list of strings (not a single string).") alpha = alpha or self.alpha min_alpha = min_alpha or self.min_alpha epochs = epochs or self.epochs doctag_vectors = pseudorandom_weak_vector(self.dv.vector_size, seed_string=' '.join(doc_words)) doctag_vectors = doctag_vectors.reshape(1, self.dv.vector_size) doctags_lockf = np.ones(1, dtype=REAL) doctag_indexes = [0] work = zeros(self.layer1_size, dtype=REAL) if not self.sg: neu1 = matutils.zeros_aligned(self.layer1_size, dtype=REAL) alpha_delta = (alpha - min_alpha) / max(epochs - 1, 1) for i in range(epochs): if self.sg: train_document_dbow( self, doc_words, doctag_indexes, alpha, work, learn_words=False, learn_hidden=False, doctag_vectors=doctag_vectors, doctags_lockf=doctags_lockf ) elif self.dm_concat: train_document_dm_concat( self, doc_words, doctag_indexes, alpha, work, neu1, learn_words=False, learn_hidden=False, doctag_vectors=doctag_vectors, doctags_lockf=doctags_lockf ) else: train_document_dm( self, doc_words, doctag_indexes, alpha, work, neu1, learn_words=False, learn_hidden=False, doctag_vectors=doctag_vectors, doctags_lockf=doctags_lockf ) alpha -= alpha_delta return doctag_vectors[0] def __getitem__(self, tag): """Get the vector representation of (possibly multi-term) tag. Parameters ---------- tag : {str, int, list of str, list of int} The tag (or tags) to be looked up in the model. Returns ------- np.ndarray The vector representations of each tag as a matrix (will be 1D if `tag` was a single tag) """ if isinstance(tag, (str, int, integer,)): if tag not in self.wv: return self.dv[tag] return self.wv[tag] return vstack([self[i] for i in tag]) def __str__(self): """Abbreviated name reflecting major configuration parameters. Returns ------- str Human readable representation of the models internal state. """ segments = [] if self.comment: segments.append('"%s"' % self.comment) if self.sg: if self.dbow_words: segments.append('dbow+w') # also training words else: segments.append('dbow') # PV-DBOW (skip-gram-style) else: # PV-DM... if self.dm_concat: segments.append('dm/c') # ...with concatenative context layer else: if self.cbow_mean: segments.append('dm/m') else: segments.append('dm/s') segments.append('d%d' % self.dv.vector_size) # dimensions if self.negative: segments.append('n%d' % self.negative) # negative samples if self.hs: segments.append('hs') if not self.sg or (self.sg and self.dbow_words): segments.append('w%d' % self.window) # window size, when relevant if self.min_count > 1: segments.append('mc%d' % self.min_count) if self.sample > 0: segments.append('s%g' % self.sample) if self.workers > 1: segments.append('t%d' % self.workers) return '%s<%s>' % (self.__class__.__name__, ','.join(segments)) def save_word2vec_format(self, fname, doctag_vec=False, word_vec=True, prefix='*dt_', fvocab=None, binary=False): """Store the input-hidden weight matrix in the same format used by the original C word2vec-tool. Parameters ---------- fname : str The file path used to save the vectors in. doctag_vec : bool, optional Indicates whether to store document vectors. word_vec : bool, optional Indicates whether to store word vectors. prefix : str, optional Uniquely identifies doctags from word vocab, and avoids collision in case of repeated string in doctag and word vocab. fvocab : str, optional Optional file path used to save the vocabulary. binary : bool, optional If True, the data will be saved in binary word2vec format, otherwise - will be saved in plain text. """ total_vec = None # save word vectors if word_vec: if doctag_vec: total_vec = len(self.wv) + len(self.dv) self.wv.save_word2vec_format(fname, fvocab, binary, total_vec) # save document vectors if doctag_vec: write_header = True append = False if word_vec: # simply appending to existing file write_header = False append = True self.dv.save_word2vec_format( fname, prefix=prefix, fvocab=fvocab, binary=binary, write_header=write_header, append=append, sort_attr='doc_count') @deprecated( "Gensim 4.0.0 implemented internal optimizations that make calls to init_sims() unnecessary. " "init_sims() is now obsoleted and will be completely removed in future versions. " "See https://github.com/RaRe-Technologies/gensim/wiki/Migrating-from-Gensim-3.x-to-4" ) def init_sims(self, replace=False): """ Precompute L2-normalized vectors. Obsoleted. If you need a single unit-normalized vector for some key, call :meth:`~gensim.models.keyedvectors.KeyedVectors.get_vector` instead: ``doc2vec_model.dv.get_vector(key, norm=True)``. To refresh norms after you performed some atypical out-of-band vector tampering, call `:meth:`~gensim.models.keyedvectors.KeyedVectors.fill_norms()` instead. Parameters ---------- replace : bool If True, forget the original trained vectors and only keep the normalized ones. You lose information if you do this. """ self.dv.init_sims(replace=replace) @classmethod def load(cls, *args, **kwargs): """Load a previously saved :class:`~gensim.models.doc2vec.Doc2Vec` model. Parameters ---------- fname : str Path to the saved file. *args : object Additional arguments, see `~gensim.models.word2vec.Word2Vec.load`. **kwargs : object Additional arguments, see `~gensim.models.word2vec.Word2Vec.load`. See Also -------- :meth:`~gensim.models.doc2vec.Doc2Vec.save` Save :class:`~gensim.models.doc2vec.Doc2Vec` model. Returns ------- :class:`~gensim.models.doc2vec.Doc2Vec` Loaded model. """ try: return super(Doc2Vec, cls).load(*args, rethrow=True, **kwargs) except AttributeError as ae: logger.error( "Model load error. Was model saved using code from an older Gensim version? " "Try loading older model using gensim-3.8.3, then re-saving, to restore " "compatibility with current code.") raise ae def estimate_memory(self, vocab_size=None, report=None): """Estimate required memory for a model using current settings. Parameters ---------- vocab_size : int, optional Number of raw words in the vocabulary. report : dict of (str, int), optional A dictionary from string representations of the **specific** model's memory consuming members to their size in bytes. Returns ------- dict of (str, int), optional A dictionary from string representations of the model's memory consuming members to their size in bytes. Includes members from the base classes as well as weights and tag lookup memory estimation specific to the class. """ report = report or {} report['doctag_lookup'] = self.estimated_lookup_memory() report['doctag_syn0'] = len(self.dv) * self.vector_size * dtype(REAL).itemsize return super(Doc2Vec, self).estimate_memory(vocab_size, report=report) def build_vocab( self, corpus_iterable=None, corpus_file=None, update=False, progress_per=10000, keep_raw_vocab=False, trim_rule=None, **kwargs, ): """Build vocabulary from a sequence of documents (can be a once-only generator stream). Parameters ---------- documents : iterable of list of :class:`~gensim.models.doc2vec.TaggedDocument`, optional Can be simply a list of :class:`~gensim.models.doc2vec.TaggedDocument` elements, but for larger corpora, consider an iterable that streams the documents directly from disk/network. See :class:`~gensim.models.doc2vec.TaggedBrownCorpus` or :class:`~gensim.models.doc2vec.TaggedLineDocument` corpus_file : str, optional Path to a corpus file in :class:`~gensim.models.word2vec.LineSentence` format. You may use this argument instead of `documents` to get performance boost. Only one of `documents` or `corpus_file` arguments need to be passed (not both of them). Documents' tags are assigned automatically and are equal to a line number, as in :class:`~gensim.models.doc2vec.TaggedLineDocument`. update : bool If true, the new words in `documents` will be added to model's vocab. progress_per : int Indicates how many words to process before showing/updating the progress. keep_raw_vocab : bool If not true, delete the raw vocabulary after the scaling is done and free up RAM. trim_rule : function, optional Vocabulary trimming rule, specifies whether certain words should remain in the vocabulary, be trimmed away, or handled using the default (discard if word count < min_count). Can be None (min_count will be used, look to :func:`~gensim.utils.keep_vocab_item`), or a callable that accepts parameters (word, count, min_count) and returns either :attr:`gensim.utils.RULE_DISCARD`, :attr:`gensim.utils.RULE_KEEP` or :attr:`gensim.utils.RULE_DEFAULT`. The rule, if given, is only used to prune vocabulary during current method call and is not stored as part of the model. The input parameters are of the following types: * `word` (str) - the word we are examining * `count` (int) - the word's frequency count in the corpus * `min_count` (int) - the minimum count threshold. **kwargs Additional key word arguments passed to the internal vocabulary construction. """ total_words, corpus_count = self.scan_vocab( corpus_iterable=corpus_iterable, corpus_file=corpus_file, progress_per=progress_per, trim_rule=trim_rule, ) self.corpus_count = corpus_count self.corpus_total_words = total_words report_values = self.prepare_vocab(update=update, keep_raw_vocab=keep_raw_vocab, trim_rule=trim_rule, **kwargs) report_values['memory'] = self.estimate_memory(vocab_size=report_values['num_retained_words']) self.prepare_weights(update=update) def build_vocab_from_freq(self, word_freq, keep_raw_vocab=False, corpus_count=None, trim_rule=None, update=False): """Build vocabulary from a dictionary of word frequencies. Build model vocabulary from a passed dictionary that contains a (word -> word count) mapping. Words must be of type unicode strings. Parameters ---------- word_freq : dict of (str, int) Word <-> count mapping. keep_raw_vocab : bool, optional If not true, delete the raw vocabulary after the scaling is done and free up RAM. corpus_count : int, optional Even if no corpus is provided, this argument can set corpus_count explicitly. trim_rule : function, optional Vocabulary trimming rule, specifies whether certain words should remain in the vocabulary, be trimmed away, or handled using the default (discard if word count < min_count). Can be None (min_count will be used, look to :func:`~gensim.utils.keep_vocab_item`), or a callable that accepts parameters (word, count, min_count) and returns either :attr:`gensim.utils.RULE_DISCARD`, :attr:`gensim.utils.RULE_KEEP` or :attr:`gensim.utils.RULE_DEFAULT`. The rule, if given, is only used to prune vocabulary during :meth:`~gensim.models.doc2vec.Doc2Vec.build_vocab` and is not stored as part of the model. The input parameters are of the following types: * `word` (str) - the word we are examining * `count` (int) - the word's frequency count in the corpus * `min_count` (int) - the minimum count threshold. update : bool, optional If true, the new provided words in `word_freq` dict will be added to model's vocab. """ logger.info("processing provided word frequencies") # Instead of scanning text, this will assign provided word frequencies dictionary(word_freq) # to be directly the raw vocab. raw_vocab = word_freq logger.info( "collected %i different raw words, with total frequency of %i", len(raw_vocab), sum(raw_vocab.values()), ) # Since no documents are provided, this is to control the corpus_count self.corpus_count = corpus_count or 0 self.raw_vocab = raw_vocab # trim by min_count & precalculate downsampling report_values = self.prepare_vocab(keep_raw_vocab=keep_raw_vocab, trim_rule=trim_rule, update=update) report_values['memory'] = self.estimate_memory(vocab_size=report_values['num_retained_words']) self.prepare_weights(update=update) def _scan_vocab(self, corpus_iterable, progress_per, trim_rule): document_no = -1 total_words = 0 min_reduce = 1 interval_start = default_timer() - 0.00001 # guard against next sample being identical interval_count = 0 checked_string_types = 0 vocab = defaultdict(int) max_rawint = -1 # highest raw int tag seen (-1 for none) doctags_lookup = {} doctags_list = [] for document_no, document in enumerate(corpus_iterable): if not checked_string_types: if isinstance(document.words, str): logger.warning( "Each 'words' should be a list of words (usually unicode strings). " "First 'words' here is instead plain %s.", type(document.words), ) checked_string_types += 1 if document_no % progress_per == 0: interval_rate = (total_words - interval_count) / (default_timer() - interval_start) logger.info( "PROGRESS: at example #%i, processed %i words (%i words/s), %i word types, %i tags", document_no, total_words, interval_rate, len(vocab), len(doctags_list) ) interval_start = default_timer() interval_count = total_words document_length = len(document.words) for tag in document.tags: # Note a document tag during initial corpus scan, for structure sizing. if isinstance(tag, (int, integer,)): max_rawint = max(max_rawint, tag) else: if tag in doctags_lookup: doctags_lookup[tag].doc_count += 1 doctags_lookup[tag].word_count += document_length else: doctags_lookup[tag] = Doctag(index=len(doctags_list), word_count=document_length, doc_count=1) doctags_list.append(tag) for word in document.words: vocab[word] += 1 total_words += len(document.words) if self.max_vocab_size and len(vocab) > self.max_vocab_size: utils.prune_vocab(vocab, min_reduce, trim_rule=trim_rule) min_reduce += 1 corpus_count = document_no + 1 if len(doctags_list) > corpus_count: logger.warning("More unique tags (%i) than documents (%i).", len(doctags_list), corpus_count) if max_rawint > corpus_count: logger.warning( "Highest int doctag (%i) larger than count of documents (%i). This means " "at least %i excess, unused slots (%i bytes) will be allocated for vectors.", max_rawint, corpus_count, max_rawint - corpus_count, (max_rawint - corpus_count) * self.vector_size * dtype(REAL).itemsize, ) if max_rawint > -1: # adjust indexes/list to account for range of pure-int keyed doctags for key in doctags_list: doctags_lookup[key].index = doctags_lookup[key].index + max_rawint + 1 doctags_list = list(range(0, max_rawint + 1)) + doctags_list self.dv.index_to_key = doctags_list for t, dt in doctags_lookup.items(): self.dv.key_to_index[t] = dt.index self.dv.set_vecattr(t, 'word_count', dt.word_count) self.dv.set_vecattr(t, 'doc_count', dt.doc_count) self.raw_vocab = vocab return total_words, corpus_count def scan_vocab(self, corpus_iterable=None, corpus_file=None, progress_per=100000, trim_rule=None): """Create the model's vocabulary: a mapping from unique words in the corpus to their frequency count. Parameters ---------- documents : iterable of :class:`~gensim.models.doc2vec.TaggedDocument`, optional The tagged documents used to create the vocabulary. Their tags can be either str tokens or ints (faster). corpus_file : str, optional Path to a corpus file in :class:`~gensim.models.word2vec.LineSentence` format. You may use this argument instead of `documents` to get performance boost. Only one of `documents` or `corpus_file` arguments need to be passed (not both of them). progress_per : int Progress will be logged every `progress_per` documents. trim_rule : function, optional Vocabulary trimming rule, specifies whether certain words should remain in the vocabulary, be trimmed away, or handled using the default (discard if word count < min_count). Can be None (min_count will be used, look to :func:`~gensim.utils.keep_vocab_item`), or a callable that accepts parameters (word, count, min_count) and returns either :attr:`gensim.utils.RULE_DISCARD`, :attr:`gensim.utils.RULE_KEEP` or :attr:`gensim.utils.RULE_DEFAULT`. The rule, if given, is only used to prune vocabulary during :meth:`~gensim.models.doc2vec.Doc2Vec.build_vocab` and is not stored as part of the model. The input parameters are of the following types: * `word` (str) - the word we are examining * `count` (int) - the word's frequency count in the corpus * `min_count` (int) - the minimum count threshold. Returns ------- (int, int) Tuple of `(total words in the corpus, number of documents)`. """ logger.info("collecting all words and their counts") if corpus_file is not None: corpus_iterable = TaggedLineDocument(corpus_file) total_words, corpus_count = self._scan_vocab(corpus_iterable, progress_per, trim_rule) logger.info( "collected %i word types and %i unique tags from a corpus of %i examples and %i words", len(self.raw_vocab), len(self.dv), corpus_count, total_words, ) return total_words, corpus_count def similarity_unseen_docs(self, doc_words1, doc_words2, alpha=None, min_alpha=None, epochs=None): """Compute cosine similarity between two post-bulk out of training documents. Parameters ---------- model : :class:`~gensim.models.doc2vec.Doc2Vec` An instance of a trained `Doc2Vec` model. doc_words1 : list of str Input document. doc_words2 : list of str Input document. alpha : float, optional The initial learning rate. min_alpha : float, optional Learning rate will linearly drop to `min_alpha` as training progresses. epochs : int, optional Number of epoch to train the new document. Returns ------- float The cosine similarity between `doc_words1` and `doc_words2`. """ d1 = self.infer_vector(doc_words=doc_words1, alpha=alpha, min_alpha=min_alpha, epochs=epochs) d2 = self.infer_vector(doc_words=doc_words2, alpha=alpha, min_alpha=min_alpha, epochs=epochs) return np.dot(matutils.unitvec(d1), matutils.unitvec(d2))
Doc2Vec
python
huggingface__transformers
src/transformers/models/gemma3n/modular_gemma3n.py
{ "start": 71403, "end": 74627 }
class ____(PreTrainedModel): """ An audio encoder based on the [Universal Speech Model](https://huggingface.co/papers/2303.01037) architecture. """ config: Gemma3nAudioConfig main_input_name = "audio_mel" input_modalities = "audio" def __init__(self, config: Gemma3nAudioConfig): super().__init__(config) self.config = config self.subsample_conv_projection = Gemma3nAudioSubSampleConvProjection(config) self.conformer = nn.ModuleList( [Gemma3nAudioConformerBlock(config) for _ in range(config.conf_num_hidden_layers)] ) def forward( self, audio_mel: torch.Tensor, audio_mel_mask: torch.BoolTensor ) -> tuple[torch.Tensor, torch.BoolTensor]: """Encodes a batch of MELs. Args: audio_mel: a torch.Tensor of shape [batch, num_frames, num_channels, mel_bins]. Returns: audio_encodings: a torch.Tensor of shape `[batch_size, self.config.audio_soft_tokens_per_image, self.config.audio_config.hidden_size]` audio_mel_mask: a torch.BoolTensor of shape [batch, num_frames]. """ audio_encodings = self.subsample_conv_projection(audio_mel) # audio_encodings: [B, T_sub, D] # Subsample the input audio_mel_mask to match the time dimension of audio_encodings (T_sub) t_sub = audio_encodings.shape[1] time_stride_product = 1 for stride_pair_idx in range(len(self.config.sscp_conv_stride_size)): time_stride_product *= self.config.sscp_conv_stride_size[stride_pair_idx][0] # Create indices for gathering from the original mask. # These indices map to original time steps corresponding to the start of each # receptive field in the subsampled output. indices = torch.arange(t_sub, device=audio_mel_mask.device) * time_stride_product indices = torch.clamp(indices, max=audio_mel_mask.shape[1] - 1) # Ensure indices are valid # Expand indices for batch compatibility if B > 1 and indices is 1D. if audio_mel_mask.ndim > 1 and indices.ndim == 1: indices = indices.unsqueeze(0).expand(audio_mel_mask.shape[0], -1) # [B, T_sub] elif ( audio_mel_mask.ndim == indices.ndim and audio_mel_mask.shape[0] == 1 and indices.shape[0] != 1 and t_sub == indices.shape[0] ): # Handle case where B=1 but indices became [T_sub] instead of [1, T_sub] indices = indices.unsqueeze(0) current_mask = torch.gather(audio_mel_mask, 1, indices) # [B, T_sub] for block in self.conformer: audio_encodings = block(audio_encodings, current_mask) # Pass the processed mask if self.config.conf_reduction_factor > 1: audio_encodings = audio_encodings[:, :: self.config.conf_reduction_factor] # Reduce the mask as well current_mask = current_mask[:, :: self.config.conf_reduction_factor] audio_encodings = audio_encodings.masked_fill(current_mask.unsqueeze(-1), 0.0) return audio_encodings, current_mask # ==== Language Model ====
Gemma3nAudioEncoder
python
jmcnamara__XlsxWriter
xlsxwriter/rich_value_structure.py
{ "start": 333, "end": 2553 }
class ____(xmlwriter.XMLwriter): """ A class for writing the Excel XLSX rdrichvaluestructure.xml file. """ ########################################################################### # # Public API. # ########################################################################### def __init__(self) -> None: """ Constructor. """ super().__init__() self.has_embedded_descriptions = False ########################################################################### # # Private API. # ########################################################################### def _assemble_xml_file(self) -> None: # Assemble and write the XML file. # Write the XML declaration. self._xml_declaration() # Write the rvStructures element. self._write_rv_structures() self._xml_end_tag("rvStructures") # Close the file. self._xml_close() ########################################################################### # # XML methods. # ########################################################################### def _write_rv_structures(self) -> None: # Write the <rvStructures> element. xmlns = "http://schemas.microsoft.com/office/spreadsheetml/2017/richdata" count = "1" attributes = [ ("xmlns", xmlns), ("count", count), ] self._xml_start_tag("rvStructures", attributes) # Write the s element. self._write_s() def _write_s(self) -> None: # Write the <s> element. t = "_localImage" attributes = [("t", t)] self._xml_start_tag("s", attributes) # Write the k elements. self._write_k("_rvRel:LocalImageIdentifier", "i") self._write_k("CalcOrigin", "i") if self.has_embedded_descriptions: self._write_k("Text", "s") self._xml_end_tag("s") def _write_k(self, name, k_type) -> None: # Write the <k> element. attributes = [ ("n", name), ("t", k_type), ] self._xml_empty_tag("k", attributes)
RichValueStructure
python
django-haystack__django-haystack
test_haystack/elasticsearch_tests/test_elasticsearch_backend.py
{ "start": 5696, "end": 6298 }
class ____(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, default="") name = indexes.CharField(faceted=True) is_active = indexes.BooleanField(faceted=True) post_count = indexes.IntegerField() post_count_i = indexes.FacetIntegerField(facet_for="post_count") average_rating = indexes.FloatField(faceted=True) pub_date = indexes.DateField(faceted=True) created = indexes.DateTimeField(faceted=True) sites = indexes.MultiValueField(faceted=True) def get_model(self): return MockModel
ElasticsearchComplexFacetsMockSearchIndex
python
python-pillow__Pillow
src/PIL/ImageTransform.py
{ "start": 3638, "end": 3916 }
class ____(Transform): """ Define a mesh image transform. A mesh transform consists of one or more individual quad transforms. See :py:meth:`.Image.transform` :param data: A list of (bbox, quad) tuples. """ method = Image.Transform.MESH
MeshTransform
python
ipython__ipython
IPython/core/history.py
{ "start": 19613, "end": 36361 }
class ____(HistoryAccessor): """A class to organize all history-related functionality in one place.""" # Public interface # An instance of the IPython shell we are attached to shell = Instance( "IPython.core.interactiveshell.InteractiveShellABC", allow_none=False ) # Lists to hold processed and raw history. These start with a blank entry # so that we can index them starting from 1 input_hist_parsed = List([""]) input_hist_raw = List([""]) # A list of directories visited during session dir_hist: List = List() @default("dir_hist") def _dir_hist_default(self) -> list[Path]: try: return [Path.cwd()] except OSError: return [] # A dict of output history, keyed with ints from the shell's # execution count. output_hist = Dict() # The text/plain repr of outputs. output_hist_reprs: typing.Dict[int, str] = Dict() # type: ignore [assignment] # Maps execution_count to MIME bundles outputs: typing.Dict[int, typing.List[HistoryOutput]] = defaultdict(list) # Maps execution_count to exception tracebacks exceptions: typing.Dict[int, typing.Dict[str, Any]] = Dict() # type: ignore [assignment] # The number of the current session in the history database session_number: int = Integer() # type: ignore [assignment] db_log_output = Bool( False, help="Should the history database include output? (default: no)" ).tag(config=True) db_cache_size = Integer( 0, help="Write to database every x commands (higher values save disk access & power).\n" "Values of 1 or less effectively disable caching.", ).tag(config=True) # The input and output caches db_input_cache: List[tuple[int, str, str]] = List() db_output_cache: List[tuple[int, str]] = List() # History saving in separate thread save_thread = Instance("IPython.core.history.HistorySavingThread", allow_none=True) @property def save_flag(self) -> threading.Event | None: if self.save_thread is not None: return self.save_thread.save_flag return None # Private interface # Variables used to store the three last inputs from the user. On each new # history update, we populate the user's namespace with these, shifted as # necessary. _i00 = Unicode("") _i = Unicode("") _ii = Unicode("") _iii = Unicode("") # A regex matching all forms of the exit command, so that we don't store # them in the history (it's annoying to rewind the first entry and land on # an exit call). _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$") _instances: WeakSet[HistoryManager] = WeakSet() _max_inst: int | float = float("inf") def __init__( self, shell: InteractiveShell, config: Optional[Configuration] = None, **traits: typing.Any, ): """Create a new history manager associated with a shell instance.""" super().__init__(shell=shell, config=config, **traits) self.db_input_cache_lock = threading.Lock() self.db_output_cache_lock = threading.Lock() try: self.new_session() except OperationalError: self.log.error( "Failed to create history session in %s. History will not be saved.", self.hist_file, exc_info=True, ) self.hist_file = ":memory:" if self.enabled and self.hist_file != ":memory:": self.save_thread = HistorySavingThread(self) try: self.save_thread.start() except RuntimeError: self.log.error( "Failed to start history saving thread. History will not be saved.", exc_info=True, ) self.hist_file = ":memory:" self._instances.add(self) assert len(HistoryManager._instances) <= HistoryManager._max_inst, ( len(HistoryManager._instances), HistoryManager._max_inst, ) def __del__(self) -> None: if self.save_thread is not None: self.save_thread.stop() def _get_hist_file_name(self, profile: Optional[str] = None) -> Path: """Get default history file name based on the Shell's profile. The profile parameter is ignored, but must exist for compatibility with the parent class.""" profile_dir = self.shell.profile_dir.location return Path(profile_dir) / "history.sqlite" @only_when_enabled def new_session(self, conn: Optional[sqlite3.Connection] = None) -> None: """Get a new session number.""" if conn is None: conn = self.db with conn: cur = conn.execute( """INSERT INTO sessions VALUES (NULL, ?, NULL, NULL, '') """, (datetime.datetime.now().isoformat(" "),), ) assert isinstance(cur.lastrowid, int) self.session_number = cur.lastrowid def end_session(self) -> None: """Close the database session, filling in the end time and line count.""" self.writeout_cache() with self.db: self.db.execute( """UPDATE sessions SET end=?, num_cmds=? WHERE session==?""", ( datetime.datetime.now(datetime.timezone.utc).isoformat(" "), len(self.input_hist_parsed) - 1, self.session_number, ), ) self.session_number = 0 def name_session(self, name: str) -> None: """Give the current session a name in the history database.""" warn( "name_session is deprecated in IPython 9.0 and will be removed in future versions", DeprecationWarning, stacklevel=2, ) with self.db: self.db.execute( "UPDATE sessions SET remark=? WHERE session==?", (name, self.session_number), ) def reset(self, new_session: bool = True) -> None: """Clear the session history, releasing all object references, and optionally open a new session.""" self.output_hist.clear() self.outputs.clear() self.exceptions.clear() # The directory history can't be completely empty self.dir_hist[:] = [Path.cwd()] if new_session: if self.session_number: self.end_session() self.input_hist_parsed[:] = [""] self.input_hist_raw[:] = [""] self.new_session() # ------------------------------ # Methods for retrieving history # ------------------------------ def get_session_info( self, session: int = 0 ) -> tuple[int, datetime.datetime, Optional[datetime.datetime], Optional[int], str]: """Get info about a session. Parameters ---------- session : int Session number to retrieve. The current session is 0, and negative numbers count back from current session, so -1 is the previous session. Returns ------- session_id : int Session ID number start : datetime Timestamp for the start of the session. end : datetime Timestamp for the end of the session, or None if IPython crashed. num_cmds : int Number of commands run, or None if IPython crashed. remark : str A manually set description. """ if session <= 0: session += self.session_number return super(HistoryManager, self).get_session_info(session=session) @catch_corrupt_db def get_tail( self, n: int = 10, raw: bool = True, output: bool = False, include_latest: bool = False, ) -> Iterable[tuple[int, int, InOrInOut]]: """Get the last n lines from the history database. Most recent entry last. Completion will be reordered so that that the last ones are when possible from current session. Parameters ---------- n : int The number of lines to get raw, output : bool See :meth:`get_range` include_latest : bool If False (default), n+1 lines are fetched, and the latest one is discarded. This is intended to be used where the function is called by a user command, which it should not return. Returns ------- Tuples as :meth:`get_range` """ self.writeout_cache() if not include_latest: n += 1 # cursor/line/entry this_cur = list( self._run_sql( "WHERE session == ? ORDER BY line DESC LIMIT ? ", (self.session_number, n), raw=raw, output=output, ) ) other_cur = list( self._run_sql( "WHERE session != ? ORDER BY session DESC, line DESC LIMIT ?", (self.session_number, n), raw=raw, output=output, ) ) everything: list[tuple[int, int, InOrInOut]] = this_cur + other_cur everything = everything[:n] if not include_latest: return list(everything)[:0:-1] return list(everything)[::-1] def _get_range_session( self, start: int = 1, stop: Optional[int] = None, raw: bool = True, output: bool = False, ) -> Iterable[tuple[int, int, InOrInOut]]: """Get input and output history from the current session. Called by get_range, and takes similar parameters.""" input_hist = self.input_hist_raw if raw else self.input_hist_parsed n = len(input_hist) if start < 0: start += n if not stop or (stop > n): stop = n elif stop < 0: stop += n line: InOrInOut for i in range(start, stop): if output: line = (input_hist[i], self.output_hist_reprs.get(i)) else: line = input_hist[i] yield (0, i, line) def get_range( self, session: int = 0, start: int = 1, stop: Optional[int] = None, raw: bool = True, output: bool = False, ) -> Iterable[tuple[int, int, InOrInOut]]: """Retrieve input by session. Parameters ---------- session : int Session number to retrieve. The current session is 0, and negative numbers count back from current session, so -1 is previous session. start : int First line to retrieve. stop : int End of line range (excluded from output itself). If None, retrieve to the end of the session. raw : bool If True, return untranslated input output : bool If True, attempt to include output. This will be 'real' Python objects for the current session, or text reprs from previous sessions if db_log_output was enabled at the time. Where no output is found, None is used. Returns ------- entries An iterator over the desired lines. Each line is a 3-tuple, either (session, line, input) if output is False, or (session, line, (input, output)) if output is True. """ if session <= 0: session += self.session_number if session == self.session_number: # Current session return self._get_range_session(start, stop, raw, output) return super(HistoryManager, self).get_range(session, start, stop, raw, output) ## ---------------------------- ## Methods for storing history: ## ---------------------------- def store_inputs( self, line_num: int, source: str, source_raw: Optional[str] = None ) -> None: """Store source and raw input in history and create input cache variables ``_i*``. Parameters ---------- line_num : int The prompt number of this input. source : str Python input. source_raw : str, optional If given, this is the raw input without any IPython transformations applied to it. If not given, ``source`` is used. """ if source_raw is None: source_raw = source source = source.rstrip("\n") source_raw = source_raw.rstrip("\n") # do not store exit/quit commands if self._exit_re.match(source_raw.strip()): return self.input_hist_parsed.append(source) self.input_hist_raw.append(source_raw) with self.db_input_cache_lock: self.db_input_cache.append((line_num, source, source_raw)) # Trigger to flush cache and write to DB. if len(self.db_input_cache) >= self.db_cache_size: if self.save_flag: self.save_flag.set() # update the auto _i variables self._iii = self._ii self._ii = self._i self._i = self._i00 self._i00 = source_raw # hackish access to user namespace to create _i1,_i2... dynamically new_i = "_i%s" % line_num to_main = {"_i": self._i, "_ii": self._ii, "_iii": self._iii, new_i: self._i00} if self.shell is not None: self.shell.push(to_main, interactive=False) def store_output(self, line_num: int) -> None: """If database output logging is enabled, this saves all the outputs from the indicated prompt number to the database. It's called by run_cell after code has been executed. Parameters ---------- line_num : int The line number from which to save outputs """ if (not self.db_log_output) or (line_num not in self.output_hist_reprs): return lnum: int = line_num output = self.output_hist_reprs[line_num] with self.db_output_cache_lock: self.db_output_cache.append((line_num, output)) if self.db_cache_size <= 1 and self.save_flag is not None: self.save_flag.set() def _writeout_input_cache(self, conn: sqlite3.Connection) -> None: with conn: for line in self.db_input_cache: conn.execute( "INSERT INTO history VALUES (?, ?, ?, ?)", (self.session_number,) + line, ) def _writeout_output_cache(self, conn: sqlite3.Connection) -> None: with conn: for line in self.db_output_cache: conn.execute( "INSERT INTO output_history VALUES (?, ?, ?)", (self.session_number,) + line, ) @only_when_enabled def writeout_cache(self, conn: Optional[sqlite3.Connection] = None) -> None: """Write any entries in the cache to the database.""" if conn is None: conn = self.db with self.db_input_cache_lock: try: self._writeout_input_cache(conn) except sqlite3.IntegrityError: self.new_session(conn) print( "ERROR! Session/line number was not unique in", "database. History logging moved to new session", self.session_number, ) try: # Try writing to the new session. If this fails, don't # recurse self._writeout_input_cache(conn) except sqlite3.IntegrityError: pass finally: self.db_input_cache = [] with self.db_output_cache_lock: try: self._writeout_output_cache(conn) except sqlite3.IntegrityError: print( "!! Session/line number for output was not unique", "in database. Output will not be stored.", ) finally: self.db_output_cache = [] from typing import Callable, Iterator from weakref import ReferenceType @contextmanager def hold(ref: ReferenceType[HistoryManager]) -> Iterator[ReferenceType[HistoryManager]]: """ Context manger that hold a reference to a weak ref to make sure it is not GC'd during it's context. """ r = ref() yield ref del r
HistoryManager
python
doocs__leetcode
solution/1900-1999/1994.The Number of Good Subsets/Solution.py
{ "start": 0, "end": 745 }
class ____: def numberOfGoodSubsets(self, nums: List[int]) -> int: primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] cnt = Counter(nums) mod = 10**9 + 7 n = len(primes) f = [0] * (1 << n) f[0] = pow(2, cnt[1]) for x in range(2, 31): if cnt[x] == 0 or x % 4 == 0 or x % 9 == 0 or x % 25 == 0: continue mask = 0 for i, p in enumerate(primes): if x % p == 0: mask |= 1 << i for state in range((1 << n) - 1, 0, -1): if state & mask == mask: f[state] = (f[state] + cnt[x] * f[state ^ mask]) % mod return sum(f[i] for i in range(1, 1 << n)) % mod
Solution
python
kamyu104__LeetCode-Solutions
Python/regular-expression-matching.py
{ "start": 2875, "end": 3416 }
class ____(object): # @return a boolean def isMatch(self, s, p): if not p: return not s if len(p) == 1 or p[1] != '*': if len(s) > 0 and (p[0] == s[0] or p[0] == '.'): return self.isMatch(s[1:], p[1:]) else: return False else: while len(s) > 0 and (p[0] == s[0] or p[0] == '.'): if self.isMatch(s, p[2:]): return True s = s[1:] return self.isMatch(s, p[2:])
Solution4
python
django-extensions__django-extensions
django_extensions/db/models.py
{ "start": 2911, "end": 3904 }
class ____(models.Model): """ ActivatorModel An abstract base class model that provides activate and deactivate fields. """ INACTIVE_STATUS = 0 ACTIVE_STATUS = 1 STATUS_CHOICES = ( (INACTIVE_STATUS, _("Inactive")), (ACTIVE_STATUS, _("Active")), ) status = models.IntegerField( _("status"), choices=STATUS_CHOICES, default=ACTIVE_STATUS ) activate_date = models.DateTimeField( blank=True, null=True, help_text=_("keep empty for an immediate activation") ) deactivate_date = models.DateTimeField( blank=True, null=True, help_text=_("keep empty for indefinite activation") ) objects = ActivatorModelManager() class Meta: ordering = ( "status", "-activate_date", ) abstract = True def save(self, *args, **kwargs): if not self.activate_date: self.activate_date = now() super().save(*args, **kwargs)
ActivatorModel
python
pandas-dev__pandas
pandas/tests/arithmetic/test_categorical.py
{ "start": 103, "end": 742 }
class ____: def test_categorical_nan_equality(self): cat = Series(Categorical(["a", "b", "c", np.nan])) expected = Series([True, True, True, False]) result = cat == cat tm.assert_series_equal(result, expected) def test_categorical_tuple_equality(self): # GH 18050 ser = Series([(0, 0), (0, 1), (0, 0), (1, 0), (1, 1)]) expected = Series([True, False, True, False, False]) result = ser == (0, 0) tm.assert_series_equal(result, expected) result = ser.astype("category") == (0, 0) tm.assert_series_equal(result, expected)
TestCategoricalComparisons
python
huggingface__transformers
src/transformers/models/swin/modeling_swin.py
{ "start": 7250, "end": 11162 }
class ____(nn.Module): """ Construct the patch and position embeddings. Optionally, also the mask token. """ def __init__(self, config, use_mask_token=False): super().__init__() self.patch_embeddings = SwinPatchEmbeddings(config) num_patches = self.patch_embeddings.num_patches self.patch_grid = self.patch_embeddings.grid_size self.mask_token = nn.Parameter(torch.zeros(1, 1, config.embed_dim)) if use_mask_token else None if config.use_absolute_embeddings: self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.embed_dim)) else: self.position_embeddings = None self.norm = nn.LayerNorm(config.embed_dim) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.patch_size = config.patch_size self.config = config # Copied from transformers.models.vit.modeling_vit.ViTEmbeddings.interpolate_pos_encoding def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor: """ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution images. This method is also adapted to support torch.jit tracing. Adapted from: - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211 """ num_patches = embeddings.shape[1] - 1 num_positions = self.position_embeddings.shape[1] - 1 # always interpolate when tracing to ensure the exported model works for dynamic input shapes if not torch.jit.is_tracing() and num_patches == num_positions and height == width: return self.position_embeddings class_pos_embed = self.position_embeddings[:, :1] patch_pos_embed = self.position_embeddings[:, 1:] dim = embeddings.shape[-1] new_height = height // self.patch_size new_width = width // self.patch_size sqrt_num_positions = torch_int(num_positions**0.5) patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim) patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2) patch_pos_embed = nn.functional.interpolate( patch_pos_embed, size=(new_height, new_width), mode="bicubic", align_corners=False, ) patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) return torch.cat((class_pos_embed, patch_pos_embed), dim=1) def forward( self, pixel_values: Optional[torch.FloatTensor], bool_masked_pos: Optional[torch.BoolTensor] = None, interpolate_pos_encoding: bool = False, ) -> tuple[torch.Tensor]: _, num_channels, height, width = pixel_values.shape embeddings, output_dimensions = self.patch_embeddings(pixel_values) embeddings = self.norm(embeddings) batch_size, seq_len, _ = embeddings.size() if bool_masked_pos is not None: mask_tokens = self.mask_token.expand(batch_size, seq_len, -1) # replace the masked visual tokens by mask_tokens mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens) embeddings = embeddings * (1.0 - mask) + mask_tokens * mask if self.position_embeddings is not None: if interpolate_pos_encoding: embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width) else: embeddings = embeddings + self.position_embeddings embeddings = self.dropout(embeddings) return embeddings, output_dimensions
SwinEmbeddings
python
great-expectations__great_expectations
great_expectations/expectations/regex_based_column_map_expectation.py
{ "start": 3719, "end": 14570 }
class ____(ColumnMapExpectation, ABC): """Base class for RegexBasedColumnMapExpectations. RegexBasedColumnMapExpectations facilitate regex parsing as the core logic for a Map Expectation. Example Definition: ```python ExpectColumnValuesToOnlyContainVowels(SetBasedColumnMapExpectation): regex_camel_name = 'Vowel' regex = '^[aeiouyAEIOUY]*$' semantic_type_name_plural = 'vowels' map_metric = RegexBasedColumnMapExpectation.register_metric( regex_camel_name=regex_camel_name, regex=regex ) ``` Args: regex_camel_name (str): A name describing a regex pattern, in camel case. regex_ (str): A valid regex pattern. semantic_type_name_plural (optional[str]): The plural form of a semantic type being validated by a regex pattern. map_metric (str): The name of an ephemeral metric, as returned by `register_metric(...)`. """ # noqa: E501 # FIXME CoP @staticmethod def register_metric( regex_camel_name: str, regex_: str, ) -> str: """Register an ephemeral metric using a constructed name with the logic provided by RegexColumnMapMetricProvider. Args: regex_camel_name: A name describing a regex pattern, in camel case. regex_: A valid regex pattern. Returns: map_metric: The constructed name of the ephemeral metric. """ # noqa: E501 # FIXME CoP regex_snake_name: str = camel_to_snake(regex_camel_name) map_metric: str = "column_values.match_" + regex_snake_name + "_regex" # Define the class using `type`. This allows us to name it dynamically. new_column_regex_metric_provider = type( # noqa: F841 # never used f"(ColumnValuesMatch{regex_camel_name}Regex", (RegexColumnMapMetricProvider,), { "condition_metric_name": map_metric, "regex": regex_, }, ) return map_metric @override def validate_configuration( self, configuration: Optional[ExpectationConfiguration] = None ) -> None: """Raise an exception if the configuration is not viable for an expectation. Args: configuration: An ExpectationConfiguration Raises: InvalidExpectationConfigurationError: If no `regex` or `column` specified, or if `mostly` parameter incorrectly defined. """ # noqa: E501 # FIXME CoP super().validate_configuration(configuration) try: assert getattr(self, "regex", None) is not None, ( "regex is required for RegexBasedColumnMap Expectations" ) assert ( "column" in configuration.kwargs # type: ignore[union-attr] # This method is being removed ), "'column' parameter is required for column map expectations" if "mostly" in configuration.kwargs: # type: ignore[union-attr] # This method is being removed mostly = configuration.kwargs["mostly"] # type: ignore[union-attr] # This method is being removed assert isinstance(mostly, (int, float)), ( "'mostly' parameter must be an integer or float" ) assert 0 <= mostly <= 1, "'mostly' parameter must be between 0 and 1" except AssertionError as e: raise InvalidExpectationConfigurationError(str(e)) # question, descriptive, prescriptive, diagnostic @classmethod @renderer(renderer_type=LegacyRendererType.QUESTION) def _question_renderer(cls, configuration, result=None, runtime_configuration=None): column = configuration.kwargs.get("column") mostly = configuration.kwargs.get("mostly") regex = getattr(cls, "regex", None) semantic_type_name_plural = getattr(cls, "semantic_type_name_plural", None) if mostly == 1 or mostly is None: if semantic_type_name_plural is not None: return f'Are all values in column "{column}" valid {semantic_type_name_plural}, as judged by matching the regular expression {regex}?' # noqa: E501 # FIXME CoP else: return f'Do all values in column "{column}" match the regular expression {regex}?' else: # noqa: PLR5501 # FIXME CoP if semantic_type_name_plural is not None: return f'Are at least {mostly * 100}% of values in column "{column}" valid {semantic_type_name_plural}, as judged by matching the regular expression {regex}?' # noqa: E501 # FIXME CoP else: return f'Do at least {mostly * 100}% of values in column "{column}" match the regular expression {regex}?' # noqa: E501 # FIXME CoP @classmethod @renderer(renderer_type=LegacyRendererType.ANSWER) def _answer_renderer(cls, configuration=None, result=None, runtime_configuration=None): column = result.expectation_config.kwargs.get("column") mostly = result.expectation_config.kwargs.get("mostly") regex = result.expectation_config.kwargs.get("regex") semantic_type_name_plural = configuration.kwargs.get("semantic_type_name_plural") if result.success: if mostly == 1 or mostly is None: if semantic_type_name_plural is not None: return f'All values in column "{column}" are valid {semantic_type_name_plural}, as judged by matching the regular expression {regex}.' # noqa: E501 # FIXME CoP else: return f'All values in column "{column}" match the regular expression {regex}.' else: # noqa: PLR5501 # FIXME CoP if semantic_type_name_plural is not None: return f'At least {mostly * 100}% of values in column "{column}" are valid {semantic_type_name_plural}, as judged by matching the regular expression {regex}.' # noqa: E501 # FIXME CoP else: return f'At least {mostly * 100}% of values in column "{column}" match the regular expression {regex}.' # noqa: E501 # FIXME CoP else: # noqa: PLR5501 # FIXME CoP if semantic_type_name_plural is not None: return f' Less than {mostly * 100}% of values in column "{column}" are valid {semantic_type_name_plural}, as judged by matching the regular expression {regex}.' # noqa: E501 # FIXME CoP else: return f'Less than {mostly * 100}% of values in column "{column}" match the regular expression {regex}.' # noqa: E501 # FIXME CoP @override @classmethod def _prescriptive_template( cls, renderer_configuration: RendererConfiguration, ): add_param_args: AddParamArgs = ( ("column", RendererValueType.STRING), ("mostly", RendererValueType.NUMBER), ("regex", RendererValueType.STRING), ) for name, param_type in add_param_args: renderer_configuration.add_param(name=name, param_type=param_type) params = renderer_configuration.params if not params.regex: template_str = "values must match a regular expression but none was specified." else: template_str = "values must match this regular expression: $regex" if params.mostly and params.mostly.value < 1.0: renderer_configuration = cls._add_mostly_pct_param( renderer_configuration=renderer_configuration ) template_str += ", at least $mostly_pct % of the time." else: template_str += "." if renderer_configuration.include_column_name: template_str = "$column " + template_str renderer_configuration.template_str = template_str return renderer_configuration @override @classmethod @renderer(renderer_type=LegacyRendererType.PRESCRIPTIVE) @render_suite_parameter_string def _prescriptive_renderer( cls, configuration: Optional[ExpectationConfiguration] = None, result: Optional[ExpectationValidationResult] = None, runtime_configuration: Optional[dict] = None, **kwargs, ): runtime_configuration = runtime_configuration or {} include_column_name = runtime_configuration.get("include_column_name") is not False styling = runtime_configuration.get("styling") kwargs = configuration.kwargs if configuration else {} params = substitute_none_for_missing( kwargs, ["column", "regex", "mostly", "row_condition", "condition_parser"], ) if not params.get("regex"): template_str = "values must match a regular expression but none was specified." else: template_str = "values must match this regular expression: $regex" if params["mostly"] is not None: params["mostly_pct"] = num_to_str(params["mostly"] * 100, no_scientific=True) # params["mostly_pct"] = "{:.14f}".format(params["mostly"]*100).rstrip("0").rstrip(".") # noqa: E501 # FIXME CoP template_str += ", at least $mostly_pct % of the time." else: template_str += "." if include_column_name: template_str = "$column " + template_str if params["row_condition"] is not None: conditional_template_str = parse_row_condition_string(params["row_condition"]) template_str, styling = _style_row_condition( conditional_template_str, template_str, params, styling, ) params_with_json_schema = { # noqa: F841 # never used "column": {"schema": {"type": "string"}, "value": params.get("column")}, "mostly": {"schema": {"type": "number"}, "value": params.get("mostly")}, "mostly_pct": { "schema": {"type": "number"}, "value": params.get("mostly_pct"), }, "regex": {"schema": {"type": "string"}, "value": params.get("regex")}, "row_condition": { "schema": {"type": "string"}, "value": params.get("row_condition"), }, "condition_parser": { "schema": {"type": "string"}, "value": params.get("condition_parser"), }, } return [ RenderedStringTemplateContent( content_block_type="string_template", string_template={ "template": template_str, "params": params, "styling": styling, }, ) ]
RegexBasedColumnMapExpectation
python
pytorch__pytorch
torch/_inductor/fx_passes/dedupe_symint_uses.py
{ "start": 240, "end": 668 }
class ____: """ Hash for a py_sym_types that will use the underlying sympy expression """ sym_obj: SymInt | SymFloat | SymBool def __hash__(self) -> int: return hash((type(self.sym_obj), self.sym_obj.node.expr)) def __eq__(self, value) -> bool: if not isinstance(value, _SymExprHash): return False return self.sym_obj.node.expr == value.sym_obj.node.expr
_SymExprHash
python
kamyu104__LeetCode-Solutions
Python/student-attendance-record-ii.py
{ "start": 29, "end": 427 }
class ____(object): def checkRecord(self, n): """ :type n: int :rtype: int """ M = 1000000007 a0l0, a0l1, a0l2, a1l0, a1l1, a1l2 = 1, 0, 0, 0, 0, 0 for i in xrange(n+1): a0l2, a0l1, a0l0 = a0l1, a0l0, (a0l0 + a0l1 + a0l2) % M a1l2, a1l1, a1l0 = a1l1, a1l0, (a0l0 + a1l0 + a1l1 + a1l2) % M return a1l0
Solution
python
python-pillow__Pillow
Tests/test_file_png.py
{ "start": 1372, "end": 29644 }
class ____: def get_chunks(self, filename: Path) -> list[bytes]: chunks = [] with open(filename, "rb") as fp: fp.read(8) with PngImagePlugin.PngStream(fp) as png: while True: cid, pos, length = png.read() chunks.append(cid) try: s = png.call(cid, pos, length) except EOFError: break png.crc(cid, s) return chunks def test_sanity(self, tmp_path: Path) -> None: # internal version number version = features.version_codec("zlib") assert version is not None assert re.search(r"\d+(\.\d+){1,3}(\.zlib\-ng)?$", version) test_file = tmp_path / "temp.png" hopper("RGB").save(test_file) with Image.open(test_file) as im: im.load() assert im.mode == "RGB" assert im.size == (128, 128) assert im.format == "PNG" assert im.get_format_mimetype() == "image/png" for mode in ["1", "L", "P", "RGB", "I;16", "I;16B"]: im = hopper(mode) im.save(test_file) with Image.open(test_file) as reloaded: if mode == "I;16B": reloaded = reloaded.convert(mode) assert_image_equal(reloaded, im) def test_invalid_file(self) -> None: invalid_file = "Tests/images/flower.jpg" with pytest.raises(SyntaxError): PngImagePlugin.PngImageFile(invalid_file) def test_broken(self) -> None: # Check reading of totally broken files. In this case, the test # file was checked into Subversion as a text file. test_file = "Tests/images/broken.png" with pytest.raises(OSError): with Image.open(test_file): pass def test_bad_text(self) -> None: # Make sure PIL can read malformed tEXt chunks (@PIL152) im = load(HEAD + chunk(b"tEXt") + TAIL) assert im.info == {} im = load(HEAD + chunk(b"tEXt", b"spam") + TAIL) assert im.info == {"spam": ""} im = load(HEAD + chunk(b"tEXt", b"spam\0") + TAIL) assert im.info == {"spam": ""} im = load(HEAD + chunk(b"tEXt", b"spam\0egg") + TAIL) assert im.info == {"spam": "egg"} im = load(HEAD + chunk(b"tEXt", b"spam\0egg\0") + TAIL) assert im.info == {"spam": "egg\x00"} def test_bad_ztxt(self) -> None: # Test reading malformed zTXt chunks (python-pillow/Pillow#318) im = load(HEAD + chunk(b"zTXt") + TAIL) assert im.info == {} im = load(HEAD + chunk(b"zTXt", b"spam") + TAIL) assert im.info == {"spam": ""} im = load(HEAD + chunk(b"zTXt", b"spam\0") + TAIL) assert im.info == {"spam": ""} im = load(HEAD + chunk(b"zTXt", b"spam\0\0") + TAIL) assert im.info == {"spam": ""} im = load(HEAD + chunk(b"zTXt", b"spam\0\0" + zlib.compress(b"egg")[:1]) + TAIL) assert im.info == {"spam": ""} im = load(HEAD + chunk(b"zTXt", b"spam\0\0" + zlib.compress(b"egg")) + TAIL) assert im.info == {"spam": "egg"} def test_bad_itxt(self) -> None: im = load(HEAD + chunk(b"iTXt") + TAIL) assert im.info == {} im = load(HEAD + chunk(b"iTXt", b"spam") + TAIL) assert im.info == {} im = load(HEAD + chunk(b"iTXt", b"spam\0") + TAIL) assert im.info == {} im = load(HEAD + chunk(b"iTXt", b"spam\0\x02") + TAIL) assert im.info == {} im = load(HEAD + chunk(b"iTXt", b"spam\0\0\0foo\0") + TAIL) assert im.info == {} im = load(HEAD + chunk(b"iTXt", b"spam\0\0\0en\0Spam\0egg") + TAIL) assert im.info == {"spam": "egg"} assert im.info["spam"].lang == "en" assert im.info["spam"].tkey == "Spam" im = load( HEAD + chunk(b"iTXt", b"spam\0\1\0en\0Spam\0" + zlib.compress(b"egg")[:1]) + TAIL ) assert im.info == {"spam": ""} im = load( HEAD + chunk(b"iTXt", b"spam\0\1\1en\0Spam\0" + zlib.compress(b"egg")) + TAIL ) assert im.info == {} im = load( HEAD + chunk(b"iTXt", b"spam\0\1\0en\0Spam\0" + zlib.compress(b"egg")) + TAIL ) assert im.info == {"spam": "egg"} assert im.info["spam"].lang == "en" assert im.info["spam"].tkey == "Spam" def test_interlace(self) -> None: test_file = "Tests/images/pil123p.png" with Image.open(test_file) as im: assert_image(im, "P", (162, 150)) assert im.info.get("interlace") im.load() test_file = "Tests/images/pil123rgba.png" with Image.open(test_file) as im: assert_image(im, "RGBA", (162, 150)) assert im.info.get("interlace") im.load() def test_load_transparent_p(self) -> None: test_file = "Tests/images/pil123p.png" with Image.open(test_file) as im: assert_image(im, "P", (162, 150)) im = im.convert("RGBA") assert_image(im, "RGBA", (162, 150)) # image has 124 unique alpha values colors = im.getchannel("A").getcolors() assert colors is not None assert len(colors) == 124 def test_load_transparent_rgb(self) -> None: test_file = "Tests/images/rgb_trns.png" with Image.open(test_file) as im: assert im.info["transparency"] == (0, 255, 52) assert_image(im, "RGB", (64, 64)) im = im.convert("RGBA") assert_image(im, "RGBA", (64, 64)) # image has 876 transparent pixels colors = im.getchannel("A").getcolors() assert colors is not None assert colors[0][0] == 876 def test_save_p_transparent_palette(self, tmp_path: Path) -> None: in_file = "Tests/images/pil123p.png" with Image.open(in_file) as im: # 'transparency' contains a byte string with the opacity for # each palette entry assert len(im.info["transparency"]) == 256 test_file = tmp_path / "temp.png" im.save(test_file) # check if saved image contains same transparency with Image.open(test_file) as im: assert len(im.info["transparency"]) == 256 assert_image(im, "P", (162, 150)) im = im.convert("RGBA") assert_image(im, "RGBA", (162, 150)) # image has 124 unique alpha values colors = im.getchannel("A").getcolors() assert colors is not None assert len(colors) == 124 def test_save_p_single_transparency(self, tmp_path: Path) -> None: in_file = "Tests/images/p_trns_single.png" with Image.open(in_file) as im: # pixel value 164 is full transparent assert im.info["transparency"] == 164 assert im.getpixel((31, 31)) == 164 test_file = tmp_path / "temp.png" im.save(test_file) # check if saved image contains same transparency with Image.open(test_file) as im: assert im.info["transparency"] == 164 assert im.getpixel((31, 31)) == 164 assert_image(im, "P", (64, 64)) im = im.convert("RGBA") assert_image(im, "RGBA", (64, 64)) assert im.getpixel((31, 31)) == (0, 255, 52, 0) # image has 876 transparent pixels colors = im.getchannel("A").getcolors() assert colors is not None assert colors[0][0] == 876 def test_save_p_transparent_black(self, tmp_path: Path) -> None: # check if solid black image with full transparency # is supported (check for #1838) im = Image.new("RGBA", (10, 10), (0, 0, 0, 0)) assert im.getcolors() == [(100, (0, 0, 0, 0))] im = im.convert("P") test_file = tmp_path / "temp.png" im.save(test_file) # check if saved image contains same transparency with Image.open(test_file) as im: assert len(im.info["transparency"]) == 256 assert_image(im, "P", (10, 10)) im = im.convert("RGBA") assert_image(im, "RGBA", (10, 10)) assert im.getcolors() == [(100, (0, 0, 0, 0))] def test_save_grayscale_transparency(self, tmp_path: Path) -> None: for mode, num_transparent in {"1": 1994, "L": 559, "I;16": 559}.items(): in_file = "Tests/images/" + mode.split(";")[0].lower() + "_trns.png" with Image.open(in_file) as im: assert im.mode == mode assert im.info["transparency"] == 255 im_rgba = im.convert("RGBA") colors = im_rgba.getchannel("A").getcolors() assert colors is not None assert colors[0][0] == num_transparent test_file = tmp_path / "temp.png" im.save(test_file) with Image.open(test_file) as test_im: assert test_im.mode == mode assert test_im.info["transparency"] == 255 assert_image_equal(im, test_im) test_im_rgba = test_im.convert("RGBA") colors = test_im_rgba.getchannel("A").getcolors() assert colors is not None assert colors[0][0] == num_transparent def test_save_rgb_single_transparency(self, tmp_path: Path) -> None: in_file = "Tests/images/caption_6_33_22.png" with Image.open(in_file) as im: test_file = tmp_path / "temp.png" im.save(test_file) def test_load_verify(self) -> None: # Check open/load/verify exception (@PIL150) with Image.open(TEST_PNG_FILE) as im: # Assert that there is no unclosed file warning with warnings.catch_warnings(): warnings.simplefilter("error") im.verify() with Image.open(TEST_PNG_FILE) as im: im.load() with pytest.raises(RuntimeError): im.verify() def test_verify_struct_error(self) -> None: # Check open/load/verify exception (#1755) # offsets to test, -10: breaks in i32() in read. (OSError) # -13: breaks in crc, txt chunk. # -14: malformed chunk for offset in (-10, -13, -14): with open(TEST_PNG_FILE, "rb") as f: test_file = f.read()[:offset] with Image.open(BytesIO(test_file)) as im: assert im.fp is not None with pytest.raises((OSError, SyntaxError)): im.verify() def test_verify_ignores_crc_error(self, monkeypatch: pytest.MonkeyPatch) -> None: # check ignores crc errors in ancillary chunks chunk_data = chunk(b"tEXt", b"spam") broken_crc_chunk_data = chunk_data[:-1] + b"q" # break CRC image_data = HEAD + broken_crc_chunk_data + TAIL with pytest.raises(SyntaxError): PngImagePlugin.PngImageFile(BytesIO(image_data)) monkeypatch.setattr(ImageFile, "LOAD_TRUNCATED_IMAGES", True) im = load(image_data) assert im is not None def test_verify_not_ignores_crc_error_in_required_chunk( self, monkeypatch: pytest.MonkeyPatch ) -> None: # check does not ignore crc errors in required chunks image_data = MAGIC + IHDR[:-1] + b"q" + TAIL monkeypatch.setattr(ImageFile, "LOAD_TRUNCATED_IMAGES", True) with pytest.raises(SyntaxError): PngImagePlugin.PngImageFile(BytesIO(image_data)) def test_roundtrip_dpi(self) -> None: # Check dpi roundtripping with Image.open(TEST_PNG_FILE) as im: im = roundtrip(im, dpi=(100.33, 100.33)) assert im.info["dpi"] == (100.33, 100.33) def test_load_float_dpi(self) -> None: with Image.open(TEST_PNG_FILE) as im: assert im.info["dpi"] == (95.9866, 95.9866) def test_roundtrip_text(self) -> None: # Check text roundtripping with Image.open(TEST_PNG_FILE) as im: info = PngImagePlugin.PngInfo() info.add_text("TXT", "VALUE") info.add_text("ZIP", "VALUE", zip=True) im = roundtrip(im, pnginfo=info) assert im.info == {"TXT": "VALUE", "ZIP": "VALUE"} assert im.text == {"TXT": "VALUE", "ZIP": "VALUE"} def test_roundtrip_itxt(self) -> None: # Check iTXt roundtripping im = Image.new("RGB", (32, 32)) info = PngImagePlugin.PngInfo() info.add_itxt("spam", "Eggs", "en", "Spam") info.add_text("eggs", PngImagePlugin.iTXt("Spam", "en", "Eggs"), zip=True) im = roundtrip(im, pnginfo=info) assert im.info == {"spam": "Eggs", "eggs": "Spam"} assert im.text == {"spam": "Eggs", "eggs": "Spam"} assert isinstance(im.text["spam"], PngImagePlugin.iTXt) assert im.text["spam"].lang == "en" assert im.text["spam"].tkey == "Spam" assert isinstance(im.text["eggs"], PngImagePlugin.iTXt) assert im.text["eggs"].lang == "en" assert im.text["eggs"].tkey == "Eggs" def test_nonunicode_text(self) -> None: # Check so that non-Unicode text is saved as a tEXt rather than iTXt im = Image.new("RGB", (32, 32)) info = PngImagePlugin.PngInfo() info.add_text("Text", "Ascii") im = roundtrip(im, pnginfo=info) assert isinstance(im.info["Text"], str) def test_unicode_text(self) -> None: # Check preservation of non-ASCII characters def rt_text(value: str) -> None: im = Image.new("RGB", (32, 32)) info = PngImagePlugin.PngInfo() info.add_text("Text", value) im = roundtrip(im, pnginfo=info) assert im.info == {"Text": value} rt_text(" Aa" + chr(0xA0) + chr(0xC4) + chr(0xFF)) # Latin1 rt_text(chr(0x400) + chr(0x472) + chr(0x4FF)) # Cyrillic # CJK: rt_text(chr(0x4E00) + chr(0x66F0) + chr(0x9FBA) + chr(0x3042) + chr(0xAC00)) rt_text("A" + chr(0xC4) + chr(0x472) + chr(0x3042)) # Combined def test_scary(self) -> None: # Check reading of evil PNG file. For information, see: # http://scary.beasts.org/security/CESA-2004-001.txt # The first byte is removed from pngtest_bad.png # to avoid classification as malware. with open("Tests/images/pngtest_bad.png.bin", "rb") as fd: data = b"\x89" + fd.read() pngfile = BytesIO(data) with pytest.raises(OSError): with Image.open(pngfile): pass def test_trns_rgb(self) -> None: # Check writing and reading of tRNS chunks for RGB images. # Independent file sample provided by Sebastian Spaeth. test_file = "Tests/images/caption_6_33_22.png" with Image.open(test_file) as im: assert im.info["transparency"] == (248, 248, 248) # check saving transparency by default im = roundtrip(im) assert im.info["transparency"] == (248, 248, 248) im = roundtrip(im, transparency=(0, 1, 2)) assert im.info["transparency"] == (0, 1, 2) def test_trns_p(self, tmp_path: Path) -> None: # Check writing a transparency of 0, issue #528 im = hopper("P") im.info["transparency"] = 0 f = tmp_path / "temp.png" im.save(f) with Image.open(f) as im2: assert "transparency" in im2.info assert_image_equal(im2.convert("RGBA"), im.convert("RGBA")) def test_trns_null(self) -> None: # Check reading images with null tRNS value, issue #1239 test_file = "Tests/images/tRNS_null_1x1.png" with Image.open(test_file) as im: assert im.info["transparency"] == 0 def test_save_icc_profile(self) -> None: with Image.open("Tests/images/icc_profile_none.png") as im: assert im.info["icc_profile"] is None with Image.open("Tests/images/icc_profile.png") as with_icc: expected_icc = with_icc.info["icc_profile"] im = roundtrip(im, icc_profile=expected_icc) assert im.info["icc_profile"] == expected_icc def test_discard_icc_profile(self) -> None: with Image.open("Tests/images/icc_profile.png") as im: assert "icc_profile" in im.info im = roundtrip(im, icc_profile=None) assert "icc_profile" not in im.info def test_roundtrip_icc_profile(self) -> None: with Image.open("Tests/images/icc_profile.png") as im: expected_icc = im.info["icc_profile"] im = roundtrip(im) assert im.info["icc_profile"] == expected_icc def test_roundtrip_no_icc_profile(self) -> None: with Image.open("Tests/images/icc_profile_none.png") as im: assert im.info["icc_profile"] is None im = roundtrip(im) assert "icc_profile" not in im.info def test_repr_png(self) -> None: im = hopper() b = im._repr_png_() assert b is not None with Image.open(BytesIO(b)) as repr_png: assert repr_png.format == "PNG" assert_image_equal(im, repr_png) def test_repr_png_error_returns_none(self) -> None: im = hopper("F") assert im._repr_png_() is None def test_chunk_order(self, tmp_path: Path) -> None: with Image.open("Tests/images/icc_profile.png") as im: test_file = tmp_path / "temp.png" im.convert("P").save(test_file, dpi=(100, 100)) chunks = self.get_chunks(test_file) # https://www.w3.org/TR/PNG/#5ChunkOrdering # IHDR - shall be first assert chunks.index(b"IHDR") == 0 # PLTE - before first IDAT assert chunks.index(b"PLTE") < chunks.index(b"IDAT") # iCCP - before PLTE and IDAT assert chunks.index(b"iCCP") < chunks.index(b"PLTE") assert chunks.index(b"iCCP") < chunks.index(b"IDAT") # tRNS - after PLTE, before IDAT assert chunks.index(b"tRNS") > chunks.index(b"PLTE") assert chunks.index(b"tRNS") < chunks.index(b"IDAT") # pHYs - before IDAT assert chunks.index(b"pHYs") < chunks.index(b"IDAT") def test_getchunks(self) -> None: im = hopper() chunks = PngImagePlugin.getchunks(im) assert len(chunks) == 3 def test_read_private_chunks(self) -> None: with Image.open("Tests/images/exif.png") as im: assert isinstance(im, PngImagePlugin.PngImageFile) assert im.private_chunks == [(b"orNT", b"\x01")] def test_roundtrip_private_chunk(self) -> None: # Check private chunk roundtripping with Image.open(TEST_PNG_FILE) as im: info = PngImagePlugin.PngInfo() info.add(b"prIV", b"VALUE") info.add(b"atEC", b"VALUE2") info.add(b"prIV", b"VALUE3", True) im = roundtrip(im, pnginfo=info) assert im.private_chunks == [(b"prIV", b"VALUE"), (b"atEC", b"VALUE2")] im.load() assert im.private_chunks == [ (b"prIV", b"VALUE"), (b"atEC", b"VALUE2"), (b"prIV", b"VALUE3", True), ] def test_textual_chunks_after_idat(self, monkeypatch: pytest.MonkeyPatch) -> None: with Image.open("Tests/images/hopper.png") as im: assert isinstance(im, PngImagePlugin.PngImageFile) assert "comment" in im.text for k, v in { "date:create": "2014-09-04T09:37:08+03:00", "date:modify": "2014-09-04T09:37:08+03:00", }.items(): assert im.text[k] == v # Raises a SyntaxError in load_end with Image.open("Tests/images/broken_data_stream.png") as im: assert isinstance(im, PngImagePlugin.PngImageFile) with pytest.raises(OSError): assert isinstance(im.text, dict) # Raises an EOFError in load_end with Image.open("Tests/images/hopper_idat_after_image_end.png") as im: assert isinstance(im, PngImagePlugin.PngImageFile) assert im.text == {"TXT": "VALUE", "ZIP": "VALUE"} # Raises a UnicodeDecodeError in load_end with Image.open("Tests/images/truncated_image.png") as im: assert isinstance(im, PngImagePlugin.PngImageFile) # The file is truncated with pytest.raises(OSError): im.text monkeypatch.setattr(ImageFile, "LOAD_TRUNCATED_IMAGES", True) assert isinstance(im.text, dict) def test_unknown_compression_method(self) -> None: with pytest.raises(SyntaxError, match="Unknown compression method"): PngImagePlugin.PngImageFile("Tests/images/unknown_compression_method.png") def test_padded_idat(self) -> None: # This image has been manually hexedited # so that the IDAT chunk has padding at the end # Set MAXBLOCK to the length of the actual data # so that the decoder finishes reading before the chunk ends MAXBLOCK = ImageFile.MAXBLOCK ImageFile.MAXBLOCK = 45 ImageFile.LOAD_TRUNCATED_IMAGES = True with Image.open("Tests/images/padded_idat.png") as im: im.load() ImageFile.MAXBLOCK = MAXBLOCK ImageFile.LOAD_TRUNCATED_IMAGES = False assert_image_equal_tofile(im, "Tests/images/bw_gradient.png") @pytest.mark.parametrize( "cid", (b"IHDR", b"sRGB", b"pHYs", b"acTL", b"fcTL", b"fdAT") ) def test_truncated_chunks( self, cid: bytes, monkeypatch: pytest.MonkeyPatch ) -> None: fp = BytesIO() with PngImagePlugin.PngStream(fp) as png: with pytest.raises(ValueError): png.call(cid, 0, 0) monkeypatch.setattr(ImageFile, "LOAD_TRUNCATED_IMAGES", True) png.call(cid, 0, 0) @pytest.mark.parametrize("save_all", (True, False)) def test_specify_bits(self, save_all: bool, tmp_path: Path) -> None: im = hopper("P") out = tmp_path / "temp.png" im.save(out, bits=4, save_all=save_all) with Image.open(out) as reloaded: assert isinstance(reloaded, PngImagePlugin.PngImageFile) assert reloaded.png is not None assert reloaded.png.im_palette is not None assert len(reloaded.png.im_palette[1]) == 48 def test_plte_length(self, tmp_path: Path) -> None: im = Image.new("P", (1, 1)) im.putpalette((1, 1, 1)) out = tmp_path / "temp.png" im.save(out) with Image.open(out) as reloaded: assert isinstance(reloaded, PngImagePlugin.PngImageFile) assert reloaded.png is not None assert reloaded.png.im_palette is not None assert len(reloaded.png.im_palette[1]) == 3 def test_getxmp(self) -> None: with Image.open("Tests/images/color_snakes.png") as im: if ElementTree is None: with pytest.warns( UserWarning, match="XMP data cannot be read without defusedxml dependency", ): assert im.getxmp() == {} else: assert "xmp" in im.info xmp = im.getxmp() description = xmp["xmpmeta"]["RDF"]["Description"] assert description["PixelXDimension"] == "10" assert description["subject"]["Seq"] is None def test_exif(self) -> None: # With an EXIF chunk with Image.open("Tests/images/exif.png") as im: assert isinstance(im, PngImagePlugin.PngImageFile) exif_data = im._getexif() assert exif_data is not None assert exif_data[274] == 1 # With an ImageMagick zTXt chunk with Image.open("Tests/images/exif_imagemagick.png") as im: assert isinstance(im, PngImagePlugin.PngImageFile) exif_data = im._getexif() assert exif_data is not None assert exif_data[274] == 1 # Assert that info still can be extracted # when the image is no longer a PngImageFile instance exif = im.copy().getexif() assert exif[274] == 1 # With a tEXt chunk with Image.open("Tests/images/exif_text.png") as im: assert isinstance(im, PngImagePlugin.PngImageFile) exif_data = im._getexif() assert exif_data is not None assert exif_data[274] == 1 # With XMP tags with Image.open("Tests/images/xmp_tags_orientation.png") as im: exif = im.getexif() assert exif[274] == 3 def test_exif_save(self, tmp_path: Path) -> None: # Test exif is not saved from info test_file = tmp_path / "temp.png" with Image.open("Tests/images/exif.png") as im: im.save(test_file) with Image.open(test_file) as reloaded: assert isinstance(reloaded, PngImagePlugin.PngImageFile) assert reloaded._getexif() is None # Test passing in exif with Image.open("Tests/images/exif.png") as im: im.save(test_file, exif=im.getexif()) with Image.open(test_file) as reloaded: assert isinstance(reloaded, PngImagePlugin.PngImageFile) exif_data = reloaded._getexif() assert exif_data is not None assert exif_data[274] == 1 @mark_if_feature_version( pytest.mark.valgrind_known_error, "libjpeg_turbo", "2.0", reason="Known Failing" ) def test_exif_from_jpg(self, tmp_path: Path) -> None: with Image.open("Tests/images/pil_sample_rgb.jpg") as im: test_file = tmp_path / "temp.png" im.save(test_file, exif=im.getexif()) with Image.open(test_file) as reloaded: exif = reloaded._getexif() assert exif[305] == "Adobe Photoshop CS Macintosh" def test_exif_argument(self, tmp_path: Path) -> None: with Image.open(TEST_PNG_FILE) as im: test_file = tmp_path / "temp.png" im.save(test_file, exif=b"exifstring") with Image.open(test_file) as reloaded: assert reloaded.info["exif"] == b"Exif\x00\x00exifstring" def test_tell(self) -> None: with Image.open(TEST_PNG_FILE) as im: assert im.tell() == 0 def test_seek(self) -> None: with Image.open(TEST_PNG_FILE) as im: im.seek(0) with pytest.raises(EOFError): im.seek(1) @pytest.mark.parametrize("buffer", (True, False)) def test_save_stdout(self, buffer: bool, monkeypatch: pytest.MonkeyPatch) -> None: class MyStdOut: buffer = BytesIO() mystdout: MyStdOut | BytesIO = MyStdOut() if buffer else BytesIO() monkeypatch.setattr(sys, "stdout", mystdout) with Image.open(TEST_PNG_FILE) as im: im.save(sys.stdout, "PNG") if isinstance(mystdout, MyStdOut): mystdout = mystdout.buffer with Image.open(mystdout) as reloaded: assert_image_equal_tofile(reloaded, TEST_PNG_FILE) def test_truncated_end_chunk(self, monkeypatch: pytest.MonkeyPatch) -> None: with Image.open("Tests/images/truncated_end_chunk.png") as im: with pytest.raises(OSError): im.load() monkeypatch.setattr(ImageFile, "LOAD_TRUNCATED_IMAGES", True) with Image.open("Tests/images/truncated_end_chunk.png") as im: assert_image_equal_tofile(im, "Tests/images/hopper.png") def test_deprecation(self, tmp_path: Path) -> None: test_file = tmp_path / "out.png" im = hopper("I") with pytest.warns(DeprecationWarning, match="Saving I mode images as PNG"): im.save(test_file) with Image.open(test_file) as reloaded: assert_image_equal(im, reloaded.convert("I")) @pytest.mark.skipif(is_win32(), reason="Requires Unix or macOS") @skip_unless_feature("zlib")
TestFilePng
python
google__pytype
pytype/pytd/codegen/function.py
{ "start": 1354, "end": 4846 }
class ____: """Internal representation of function signatures.""" name: str signature: pytd.Signature decorators: tuple[pytd.Alias, ...] = () is_abstract: bool = False is_coroutine: bool = False is_final: bool = False is_overload: bool = False @classmethod def make( cls, name: str, args: list[tuple[str, pytd.Type]], return_type: pytd.Type ) -> "NameAndSig": """Make a new NameAndSig from an argument list.""" params = tuple(Param(n, t).to_pytd() for (n, t) in args) sig = pytd.Signature(params=params, return_type=return_type, starargs=None, starstarargs=None, exceptions=(), template=()) return cls(name, sig) def pytd_return_type( name: str, return_type: pytd.Type | None, is_async: bool ) -> pytd.Type: """Convert function return type to pytd.""" if name == "__init__": if (return_type is None or isinstance(return_type, pytd.AnythingType)): ret = pytd.NamedType("NoneType") else: ret = return_type elif is_async: base = pytd.NamedType("typing.Coroutine") params = (pytd.AnythingType(), pytd.AnythingType(), return_type) ret = pytd.GenericType(base, params) elif return_type is None: ret = pytd.AnythingType() else: ret = return_type return ret def pytd_default_star_param() -> pytd.Parameter: return pytd.Parameter( "args", pytd.NamedType("tuple"), pytd.ParameterKind.REGULAR, True, None) def pytd_default_starstar_param() -> pytd.Parameter: return pytd.Parameter( "kwargs", pytd.NamedType("dict"), pytd.ParameterKind.REGULAR, True, None) def pytd_star_param(name: str, annotation: pytd.Type) -> pytd.Parameter: """Return a pytd.Parameter for a *args argument.""" if annotation is None: param_type = pytd.NamedType("tuple") else: param_type = pytd.GenericType( pytd.NamedType("tuple"), (annotation,)) return pytd.Parameter( name, param_type, pytd.ParameterKind.REGULAR, True, None) def pytd_starstar_param( name: str, annotation: pytd.Type ) -> pytd.Parameter: """Return a pytd.Parameter for a **kwargs argument.""" if annotation is None: param_type = pytd.NamedType("dict") else: param_type = pytd.GenericType( pytd.NamedType("dict"), (pytd.NamedType("str"), annotation)) return pytd.Parameter( name, param_type, pytd.ParameterKind.REGULAR, True, None) def _make_param(attr: pytd.Constant, kw_only: bool = False) -> pytd.Parameter: p = Param(name=attr.name, type=attr.type, default=attr.value) if kw_only: p.kind = pytd.ParameterKind.KWONLY return p.to_pytd() def generate_init( fields: Iterable[pytd.Constant], kw_fields: Iterable[pytd.Constant] ) -> pytd.Function: """Build an __init__ method from pytd class constants.""" self_arg = Param("self").to_pytd() params = (self_arg,) + tuple(_make_param(c) for c in fields) params += tuple(_make_param(c, True) for c in kw_fields) # We call this at 'runtime' rather than from the parser, so we need to use the # resolved type of None, rather than NamedType("NoneType") ret = pytd.ClassType("builtins.NoneType") sig = pytd.Signature(params=params, return_type=ret, starargs=None, starstarargs=None, exceptions=(), template=()) return pytd.Function("__init__", (sig,), kind=pytd.MethodKind.METHOD) # ------------------------------------------- # Method signature merging @dataclasses.dataclass
NameAndSig
python
ethereum__web3.py
web3/utils/subscriptions.py
{ "start": 2389, "end": 6016 }
class ____(Generic[TSubscriptionResult]): _id: HexStr = None manager: "SubscriptionManager" = None def __init__( self: TSubscription, subscription_params: Sequence[Any] | None = None, handler: EthSubscriptionHandler | None = None, handler_context: dict[str, Any] | None = None, label: str | None = None, parallelize: bool | None = None, ) -> None: self._subscription_params = subscription_params self._handler = handler_wrapper(handler) self._handler_context = handler_context or {} self._label = label self.parallelize = parallelize self.handler_call_count = 0 @property def _default_label(self) -> str: return f"{self.__class__.__name__}{self.subscription_params}" @classmethod def _create_type_aware_subscription( cls, subscription_params: Sequence[Any] | None, handler: EthSubscriptionHandler | None = None, handler_context: dict[str, Any] | None = None, label: str | None = None, parallelize: bool | None = None, ) -> "EthSubscription[Any]": subscription_type = subscription_params[0] subscription_arg = ( subscription_params[1] if len(subscription_params) > 1 else None ) if subscription_type == "newHeads": return NewHeadsSubscription( handler=handler, handler_context=handler_context, label=label, parallelize=parallelize, ) elif subscription_type == "logs": subscription_arg = subscription_arg or {} return LogsSubscription( **subscription_arg, handler=handler, handler_context=handler_context, label=label, parallelize=parallelize, ) elif subscription_type == "newPendingTransactions": subscription_arg = subscription_arg or False return PendingTxSubscription( full_transactions=subscription_arg, handler=handler, handler_context=handler_context, label=label, parallelize=parallelize, ) elif subscription_type == "syncing": return SyncingSubscription( handler=handler, handler_context=handler_context, label=label, parallelize=parallelize, ) else: params = ( (subscription_type, subscription_arg) if subscription_arg else (subscription_type,) ) return cls( params, handler=handler, handler_context=handler_context, label=label, parallelize=parallelize, ) @property def subscription_params(self) -> Sequence[Any]: return self._subscription_params @property def label(self) -> str: if not self._label: self._label = self._default_label return self._label @property def id(self) -> HexStr: if not self._id: raise Web3ValueError("No `id` found for subscription.") return self._id async def unsubscribe(self) -> bool: return await self.manager.unsubscribe(self) LogsSubscriptionContext = EthSubscriptionContext[ "LogsSubscription", "EthSubscriptionResult" ] LogsSubscriptionHandler = Callable[[LogsSubscriptionContext], Coroutine[Any, Any, None]]
EthSubscription
python
getsentry__sentry
tests/sentry/workflow_engine/endpoints/test_organization_detector_details.py
{ "start": 6265, "end": 29955 }
class ____(OrganizationDetectorDetailsBaseTest): method = "PUT" def setUp(self) -> None: super().setUp() self.valid_data = { "id": self.detector.id, "projectId": self.project.id, "name": "Updated Detector", "type": MetricIssue.slug, "dateCreated": self.detector.date_added, "dateUpdated": timezone.now(), "dataSources": [ { "queryType": self.snuba_query.type, "dataset": self.snuba_query.dataset, "query": "updated query", "aggregate": self.snuba_query.aggregate, "timeWindow": 300, "environment": self.environment.name, "eventTypes": [event_type.name for event_type in self.snuba_query.event_types], } ], "conditionGroup": { "id": self.data_condition_group.id, "organizationId": self.organization.id, "logicType": self.data_condition_group.logic_type, "conditions": [ { "id": self.condition.id, "comparison": 100, "type": Condition.GREATER, "conditionResult": DetectorPriorityLevel.HIGH, "conditionGroupId": self.condition.condition_group.id, }, { "id": self.resolve_condition.id, "comparison": 100, "type": Condition.LESS_OR_EQUAL, "conditionResult": DetectorPriorityLevel.OK, "conditionGroupId": self.condition.condition_group.id, }, ], }, "config": self.detector.config, } assert SnubaQuery.objects.get(id=self.snuba_query.id) def assert_detector_updated(self, detector: Detector) -> None: assert detector.name == "Updated Detector" assert detector.type == MetricIssue.slug assert detector.project_id == self.project.id def assert_condition_group_updated(self, condition_group: DataConditionGroup | None) -> None: assert condition_group assert condition_group.logic_type == DataConditionGroup.Type.ANY assert condition_group.organization_id == self.organization.id def assert_data_condition_updated(self, condition: DataCondition) -> None: assert condition.type == Condition.GREATER.value assert condition.comparison == 100 assert condition.condition_result == DetectorPriorityLevel.HIGH def assert_snuba_query_updated(self, snuba_query: SnubaQuery) -> None: assert snuba_query.query == "updated query" assert snuba_query.time_window == 300 @mock.patch("sentry.incidents.metric_issue_detector.schedule_update_project_config") def test_update(self, mock_schedule_update_project_config: mock.MagicMock) -> None: with self.tasks(): response = self.get_success_response( self.organization.slug, self.detector.id, **self.valid_data, status_code=200, ) detector = Detector.objects.get(id=response.data["id"]) assert response.data == serialize([detector])[0] self.assert_detector_updated(detector) condition_group = detector.workflow_condition_group self.assert_condition_group_updated(condition_group) conditions = list(DataCondition.objects.filter(condition_group=condition_group)) assert len(conditions) == 2 condition = conditions[0] self.assert_data_condition_updated(condition) data_source_detector = DataSourceDetector.objects.get(detector=detector) data_source = DataSource.objects.get(id=data_source_detector.data_source.id) query_subscription = QuerySubscription.objects.get(id=data_source.source_id) snuba_query = SnubaQuery.objects.get(id=query_subscription.snuba_query.id) self.assert_snuba_query_updated(snuba_query) mock_schedule_update_project_config.assert_called_once_with(detector) def test_update_description(self) -> None: assert self.detector.description is None data = { "description": "New description for the detector", } with self.tasks(): self.get_success_response( self.organization.slug, self.detector.id, **data, status_code=200, ) self.detector.refresh_from_db() assert self.detector.description == "New description for the detector" def test_update_add_data_condition(self) -> None: """ Test that we can add an additional data condition """ data = {**self.valid_data} condition_group_data = { "comparison": 50, "type": Condition.GREATER, "conditionResult": DetectorPriorityLevel.MEDIUM, "conditionGroupId": self.condition.condition_group.id, } data["conditionGroup"]["conditions"].append(condition_group_data) with self.tasks(): response = self.get_success_response( self.organization.slug, self.detector.id, **data, status_code=200, ) detector = Detector.objects.get(id=response.data["id"]) condition_group = detector.workflow_condition_group assert condition_group conditions = list(DataCondition.objects.filter(condition_group=condition_group)) assert len(conditions) == 3 def test_update_bad_schema(self) -> None: """ Test when we encounter bad data in the payload """ data = {**self.valid_data} condition_group_data = { "comparison": "betterThan", "type": Condition.GREATER, "conditionResult": DetectorPriorityLevel.MEDIUM, "conditionGroupId": self.condition.condition_group.id, } data["conditionGroup"]["conditions"].append(condition_group_data) with self.tasks(): self.get_error_response( self.organization.slug, self.detector.id, **data, status_code=400, ) def test_update_owner_to_user(self) -> None: # Initially no owner assert self.detector.owner_user_id is None assert self.detector.owner_team_id is None data = { "owner": self.user.get_actor_identifier(), } with self.tasks(): response = self.get_success_response( self.organization.slug, self.detector.id, **data, status_code=200, ) detector = Detector.objects.get(id=response.data["id"]) # Verify owner is set correctly assert detector.owner_user_id == self.user.id assert detector.owner_team_id is None assert detector.owner is not None assert detector.owner.identifier == self.user.get_actor_identifier() # Verify serialized response includes owner assert response.data["owner"] == { "email": self.user.email, "id": str(self.user.id), "name": self.user.get_username(), "type": "user", } def test_update_owner_to_team(self) -> None: # Set initial user owner self.detector.owner_user_id = self.user.id self.detector.save() # Create a team team = self.create_team(organization=self.organization) data = { "owner": f"team:{team.id}", } with self.tasks(): response = self.get_success_response( self.organization.slug, self.detector.id, **data, status_code=200, ) detector = Detector.objects.get(id=response.data["id"]) # Verify owner changed to team assert detector.owner_user_id is None assert detector.owner_team_id == team.id assert detector.owner is not None assert detector.owner.identifier == f"team:{team.id}" # Verify serialized response includes team owner assert response.data["owner"] == { "id": str(team.id), "name": team.slug, "type": "team", } def test_update_clear_owner(self) -> None: # Set initial owner self.detector.owner_user_id = self.user.id self.detector.save() data = { "owner": None, } with self.tasks(): response = self.get_success_response( self.organization.slug, self.detector.id, **data, status_code=200, ) detector = Detector.objects.get(id=response.data["id"]) # Verify owner is cleared assert detector.owner_user_id is None assert detector.owner_team_id is None assert detector.owner is None # Verify serialized response shows no owner assert response.data["owner"] is None def test_disable_detector(self) -> None: assert self.detector.enabled is True assert self.detector.status == ObjectStatus.ACTIVE data = { "enabled": False, } with self.tasks(): response = self.get_success_response( self.organization.slug, self.detector.id, **data, status_code=200, ) detector = Detector.objects.get(id=response.data["id"]) assert detector.enabled is False assert detector.status == ObjectStatus.DISABLED def test_enable_detector(self) -> None: self.detector.update(enabled=False) self.detector.update(status=ObjectStatus.DISABLED) data = { "enabled": True, } with self.tasks(): response = self.get_success_response( self.organization.slug, self.detector.id, **data, status_code=200, ) detector = Detector.objects.get(id=response.data["id"]) assert detector.enabled is True assert detector.status == ObjectStatus.ACTIVE def test_update_workflows_add_workflow(self) -> None: workflow1 = self.create_workflow(organization_id=self.organization.id) workflow2 = self.create_workflow(organization_id=self.organization.id) assert DetectorWorkflow.objects.filter(detector=self.detector).count() == 0 data = { "workflowIds": [workflow1.id, workflow2.id], } with outbox_runner(): response = self.get_success_response( self.organization.slug, self.detector.id, **data, status_code=200, ) assert response.data["workflowIds"] == [str(workflow1.id), str(workflow2.id)] detector_workflows = DetectorWorkflow.objects.filter(detector=self.detector) assert detector_workflows.count() == 2 workflow_ids = {dw.workflow_id for dw in detector_workflows} assert workflow_ids == {workflow1.id, workflow2.id} with assume_test_silo_mode(SiloMode.CONTROL): audit_entries = AuditLogEntry.objects.filter( event=audit_log.get_event_id("DETECTOR_WORKFLOW_ADD"), actor=self.user, ) assert audit_entries.count() == 2 assert audit_entries[0].target_object == detector_workflows[0].id assert audit_entries[1].target_object == detector_workflows[1].id def test_update_workflows_replace_workflows(self) -> None: """Test replacing existing workflows with new ones""" existing_workflow = self.create_workflow(organization_id=self.organization.id) new_workflow = self.create_workflow(organization_id=self.organization.id) existing_detector_workflow = DetectorWorkflow.objects.create( detector=self.detector, workflow=existing_workflow ) assert DetectorWorkflow.objects.filter(detector=self.detector).count() == 1 data = { "workflowIds": [new_workflow.id], } with outbox_runner(): response = self.get_success_response( self.organization.slug, self.detector.id, **data, status_code=200, ) assert response.data["workflowIds"] == [str(new_workflow.id)] # Verify old workflow was removed and new one added detector_workflows = DetectorWorkflow.objects.filter(detector=self.detector) assert detector_workflows.count() == 1 detector_workflow = detector_workflows.first() assert detector_workflow is not None assert detector_workflow.workflow_id == new_workflow.id # Verify audit log entries for both adding new workflow and removing old workflow with assume_test_silo_mode(SiloMode.CONTROL): assert ( AuditLogEntry.objects.filter( event=audit_log.get_event_id("DETECTOR_WORKFLOW_ADD"), actor=self.user, target_object=detector_workflow.id, ).count() == 1 ) assert ( AuditLogEntry.objects.filter( event=audit_log.get_event_id("DETECTOR_WORKFLOW_REMOVE"), actor=self.user, target_object=existing_detector_workflow.id, ).count() == 1 ) def test_update_workflows_remove_all_workflows(self) -> None: """Test removing all workflows by passing empty list""" # Create and connect a workflow initially workflow = self.create_workflow(organization_id=self.organization.id) detector_workflow = DetectorWorkflow.objects.create( detector=self.detector, workflow=workflow ) assert DetectorWorkflow.objects.filter(detector=self.detector).count() == 1 data = { **self.valid_data, "workflowIds": [], } with outbox_runner(): response = self.get_success_response( self.organization.slug, self.detector.id, **data, status_code=200, ) assert response.data["workflowIds"] == [] # Verify all workflows were removed assert DetectorWorkflow.objects.filter(detector=self.detector).count() == 0 # Verify audit log entry for removing workflow with assume_test_silo_mode(SiloMode.CONTROL): assert ( AuditLogEntry.objects.filter( event=audit_log.get_event_id("DETECTOR_WORKFLOW_REMOVE"), actor=self.user, target_object=detector_workflow.id, ).count() == 1 ) def test_update_workflows_invalid_workflow_ids(self) -> None: """Test validation failure with non-existent workflow IDs""" data = { **self.valid_data, "workflowIds": [999999], } response = self.get_error_response( self.organization.slug, self.detector.id, **data, status_code=400, ) assert "Some workflows do not exist" in str(response.data) def test_update_workflows_from_different_organization(self) -> None: """Test validation failure when workflows belong to different organization""" other_org = self.create_organization() other_workflow = self.create_workflow(organization_id=other_org.id) data = { **self.valid_data, "workflowIds": [other_workflow.id], } response = self.get_error_response( self.organization.slug, self.detector.id, **data, status_code=400, ) assert "Some workflows do not exist" in str(response.data) def test_update_workflows_transaction_rollback_on_validation_failure(self) -> None: """Test that detector updates are rolled back when workflow validation fails""" existing_workflow = self.create_workflow(organization_id=self.organization.id) DetectorWorkflow.objects.create(detector=self.detector, workflow=existing_workflow) initial_detector_name = self.detector.name initial_workflow_count = DetectorWorkflow.objects.filter(detector=self.detector).count() data = { **self.valid_data, "name": "Should Not Be Updated", "workflowIds": [999999], } with outbox_runner(): response = self.get_error_response( self.organization.slug, self.detector.id, **data, status_code=400, ) self.detector.refresh_from_db() assert self.detector.name == initial_detector_name assert ( DetectorWorkflow.objects.filter(detector=self.detector).count() == initial_workflow_count ) assert "Some workflows do not exist" in str(response.data) # Verify no workflow-related audit entries were created with assume_test_silo_mode(SiloMode.CONTROL): assert ( AuditLogEntry.objects.filter( event=audit_log.get_event_id("DETECTOR_WORKFLOW_ADD"), actor=self.user, ).count() == 0 ) assert ( AuditLogEntry.objects.filter( event=audit_log.get_event_id("DETECTOR_WORKFLOW_REMOVE"), actor=self.user, ).count() == 0 ) def test_update_without_workflow_ids(self) -> None: """Test that omitting workflowIds doesn't affect existing workflow connections""" workflow = self.create_workflow(organization_id=self.organization.id) DetectorWorkflow.objects.create(detector=self.detector, workflow=workflow) assert DetectorWorkflow.objects.filter(detector=self.detector).count() == 1 data = { **self.valid_data, "name": "Updated Without Workflows", } with outbox_runner(): response = self.get_success_response( self.organization.slug, self.detector.id, **data, status_code=200, ) assert response.data["workflowIds"] == [str(workflow.id)] self.detector.refresh_from_db() assert self.detector.name == "Updated Without Workflows" assert DetectorWorkflow.objects.filter(detector=self.detector).count() == 1 def test_update_workflows_no_changes(self) -> None: """Test that passing the same workflow IDs doesn't change anything""" workflow = self.create_workflow(organization_id=self.organization.id) DetectorWorkflow.objects.create(detector=self.detector, workflow=workflow) assert DetectorWorkflow.objects.filter(detector=self.detector).count() == 1 data = { **self.valid_data, "workflowIds": [workflow.id], # Same workflow ID that's already connected } with outbox_runner(): response = self.get_success_response( self.organization.slug, self.detector.id, **data, status_code=200, ) assert response.data["workflowIds"] == [str(workflow.id)] assert DetectorWorkflow.objects.filter(detector=self.detector).count() == 1 # Verify no workflow-related audit entries were created since no changes were made with assume_test_silo_mode(SiloMode.CONTROL): assert ( AuditLogEntry.objects.filter( event=audit_log.get_event_id("DETECTOR_WORKFLOW_ADD"), actor=self.user, ).count() == 0 ) assert ( AuditLogEntry.objects.filter( event=audit_log.get_event_id("DETECTOR_WORKFLOW_REMOVE"), actor=self.user, ).count() == 0 ) def test_update_config_valid(self) -> None: """Test updating detector config with valid schema data""" # Initial config initial_config = {"detection_type": "static", "comparison_delta": None} self.detector.config = initial_config self.detector.save() # Update with valid new config updated_config = {"detection_type": "percent", "comparison_delta": 3600} data = { "config": updated_config, } with self.tasks(): response = self.get_success_response( self.organization.slug, self.detector.id, **data, status_code=200, ) self.detector.refresh_from_db() # Verify config was updated in database (snake_case) assert self.detector.config == updated_config # API returns camelCase assert response.data["config"] == { "detectionType": "percent", "comparisonDelta": 3600, } def test_update_config_invalid_schema(self) -> None: """Test updating detector config with invalid schema data fails validation""" # Config missing required field 'detection_type' invalid_config = {"comparison_delta": 3600} data = { "config": invalid_config, } with self.tasks(): response = self.get_error_response( self.organization.slug, self.detector.id, **data, status_code=400, ) assert "config" in response.data assert "detection_type" in str(response.data["config"]) # Verify config was not updated self.detector.refresh_from_db() assert self.detector.config != invalid_config @with_feature("organizations:anomaly-detection-alerts") @mock.patch("sentry.seer.anomaly_detection.delete_rule.delete_rule_in_seer") def test_anomaly_detection_to_static(self, mock_seer_request: mock.MagicMock) -> None: self.detector.config = {"detection_type": AlertRuleDetectionType.DYNAMIC} self.detector.save() updated_config = {"detection_type": AlertRuleDetectionType.STATIC} data = {"config": updated_config} mock_seer_request.return_value = True with self.tasks(): response = self.get_success_response( self.organization.slug, self.detector.id, **data, status_code=200, ) self.detector.refresh_from_db() # Verify config was updated in database (snake_case) assert self.detector.config == updated_config # API returns camelCase assert response.data["config"] == {"detectionType": "static"} mock_seer_request.assert_called_once_with( source_id=int(self.data_source.source_id), organization=self.organization ) @region_silo_test
OrganizationDetectorDetailsPutTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/genericType34.py
{ "start": 381, "end": 510 }
class ____(Generic[_T_co, _N]): ... def func1(n: _N) -> ClassA[Literal[0], _N]: ... v1: ClassA[int, Literal[1]] = func1(1)
ClassA
python
Textualize__textual
docs/examples/widgets/input_validation.py
{ "start": 1427, "end": 1881 }
class ____(Validator): # (5)! def validate(self, value: str) -> ValidationResult: """Check a string is equal to its reverse.""" if self.is_palindrome(value): return self.success() else: return self.failure("That's not a palindrome :/") @staticmethod def is_palindrome(value: str) -> bool: return value == value[::-1] app = InputApp() if __name__ == "__main__": app.run()
Palindrome
python
wandb__wandb
wandb/sdk/integration_utils/auto_logging.py
{ "start": 876, "end": 5426 }
class ____: def __init__( self, name: str, symbols: Sequence[str], resolver: ArgumentResponseResolver, ) -> None: """Patches the API to log wandb Media or metrics.""" # name of the LLM provider, e.g. "Cohere" or "OpenAI" or package name like "Transformers" self.name = name # api library name, e.g. "cohere" or "openai" or "transformers" self._api = None # dictionary of original methods self.original_methods: Dict[str, Any] = {} # list of symbols to patch, e.g. ["Client.generate", "Edit.create"] or ["Pipeline.__call__"] self.symbols = symbols # resolver callable to convert args/response into a dictionary of wandb media objects or metrics self.resolver = resolver @property def set_api(self) -> Any: """Returns the API module.""" lib_name = self.name.lower() if self._api is None: self._api = wandb.util.get_module( name=lib_name, required=f"To use the W&B {self.name} Autolog, " f"you need to have the `{lib_name}` python " f"package installed. Please install it with `pip install {lib_name}`.", lazy=False, ) return self._api def patch(self, run: "wandb.Run") -> None: """Patches the API to log media or metrics to W&B.""" for symbol in self.symbols: # split on dots, e.g. "Client.generate" -> ["Client", "generate"] symbol_parts = symbol.split(".") # and get the attribute from the module original = functools.reduce(getattr, symbol_parts, self.set_api) def method_factory(original_method: Any): async def async_method(*args, **kwargs): future = asyncio.Future() async def callback(coro): try: result = await coro loggable_dict = self.resolver( args, kwargs, result, timer.start_time, timer.elapsed ) if loggable_dict is not None: run.log(loggable_dict) future.set_result(result) except Exception as e: logger.warning(e) with Timer() as timer: coro = original_method(*args, **kwargs) asyncio.ensure_future(callback(coro)) return await future def sync_method(*args, **kwargs): with Timer() as timer: result = original_method(*args, **kwargs) try: loggable_dict = self.resolver( args, kwargs, result, timer.start_time, timer.elapsed ) if loggable_dict is not None: run.log(loggable_dict) except Exception as e: logger.warning(e) return result if inspect.iscoroutinefunction(original_method): return functools.wraps(original_method)(async_method) else: return functools.wraps(original_method)(sync_method) # save original method self.original_methods[symbol] = original # monkey patch the method if len(symbol_parts) == 1: setattr(self.set_api, symbol_parts[0], method_factory(original)) else: setattr( functools.reduce(getattr, symbol_parts[:-1], self.set_api), symbol_parts[-1], method_factory(original), ) def unpatch(self) -> None: """Unpatches the API.""" for symbol, original in self.original_methods.items(): # split on dots, e.g. "Client.generate" -> ["Client", "generate"] symbol_parts = symbol.split(".") # unpatch the method if len(symbol_parts) == 1: setattr(self.set_api, symbol_parts[0], original) else: setattr( functools.reduce(getattr, symbol_parts[:-1], self.set_api), symbol_parts[-1], original, )
PatchAPI
python
walkccc__LeetCode
solutions/516. Longest Palindromic Subsequence/516-2.py
{ "start": 0, "end": 441 }
class ____: def longestPalindromeSubseq(self, s: str) -> int: n = len(s) # dp[i][j] := the length of LPS(s[i..j]) dp = [[0] * n for _ in range(n)] for i in range(n): dp[i][i] = 1 for d in range(1, n): for i in range(n - d): j = i + d if s[i] == s[j]: dp[i][j] = 2 + dp[i + 1][j - 1] else: dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]) return dp[0][n - 1]
Solution
python
ansible__ansible
test/units/module_utils/facts/test_facts.py
{ "start": 7142, "end": 7314 }
class ____(BaseTestFactsPlatform): platform_id = 'HP-UX' fact_class = virtual.hpux.HPUXVirtual collector_class = virtual.hpux.HPUXVirtualCollector
TestHPUXVirtual
python
tensorflow__tensorflow
tensorflow/tools/compatibility/ast_edits_test.py
{ "start": 3843, "end": 4199 }
class ____(ast_edits.NoUpdateSpec): """A specification where both keyword aliases are removed from h. The new API is def h(a, kw1, kw2): ... """ def __init__(self): ast_edits.NoUpdateSpec.__init__(self) self.function_keyword_renames["h"] = { "kw1_alias": "kw1", "kw2_alias": "kw2", }
RemoveMultipleKeywordArguments
python
plotly__plotly.py
_plotly_utils/basevalidators.py
{ "start": 84012, "end": 86442 }
class ____(CompoundValidator): def __init__(self, plotly_name, parent_name, data_class_str, data_docs, **kwargs): super(BaseTemplateValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=data_class_str, data_docs=data_docs, **kwargs, ) def description(self): compound_description = super(BaseTemplateValidator, self).description() compound_description += """ - The name of a registered template where current registered templates are stored in the plotly.io.templates configuration object. The names of all registered templates can be retrieved with: >>> import plotly.io as pio >>> list(pio.templates) # doctest: +ELLIPSIS ['ggplot2', 'seaborn', 'simple_white', 'plotly', 'plotly_white', ...] - A string containing multiple registered template names, joined on '+' characters (e.g. 'template1+template2'). In this case the resulting template is computed by merging together the collection of registered templates""" return compound_description def validate_coerce(self, v, skip_invalid=False): import plotly.io as pio try: # Check if v is a template identifier # (could be any hashable object) if v in pio.templates: return copy.deepcopy(pio.templates[v]) # Otherwise, if v is a string, check to see if it consists of # multiple template names joined on '+' characters elif isinstance(v, str): template_names = v.split("+") if all([name in pio.templates for name in template_names]): return pio.templates.merge_templates(*template_names) except TypeError: # v is un-hashable pass # Check for empty template if v == {} or isinstance(v, self.data_class) and v.to_plotly_json() == {}: # Replace empty template with {'data': {'scatter': [{}]}} so that we can # tell the difference between an un-initialized template and a template # explicitly set to empty. return self.data_class(data_scatter=[{}]) return super(BaseTemplateValidator, self).validate_coerce( v, skip_invalid=skip_invalid )
BaseTemplateValidator
python
doocs__leetcode
solution/2000-2099/2033.Minimum Operations to Make a Uni-Value Grid/Solution.py
{ "start": 0, "end": 382 }
class ____: def minOperations(self, grid: List[List[int]], x: int) -> int: nums = [] mod = grid[0][0] % x for row in grid: for v in row: if v % x != mod: return -1 nums.append(v) nums.sort() mid = nums[len(nums) >> 1] return sum(abs(v - mid) // x for v in nums)
Solution
python
apache__airflow
providers/apache/hive/tests/integration/apache/hive/transfers/test_mssql_to_hive.py
{ "start": 1189, "end": 3465 }
class ____: def setup_method(self, mocker): os.environ["AIRFLOW_CONN_MSSQL_DEFAULT"] = AIRFLOW_CONN_MSSQL_DEFAULT hook = MsSqlHook() conn = hook.get_conn() hook.set_autocommit(conn, True) self.cursor = conn.cursor() self.cursor.execute(f"""CREATE TABLE {TEST_TABLE_ID} ( PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255) )""") self.kwargs = dict( sql=f"SELECT * FROM {TEST_TABLE_ID}", hive_table="table", task_id="test_mssql_to_hive", dag=None ) def teardown_method(self): self.cursor.execute(f"DROP TABLE {TEST_TABLE_ID}") @patch("airflow.providers.apache.hive.transfers.mssql_to_hive.csv") @patch("airflow.providers.apache.hive.transfers.mssql_to_hive.NamedTemporaryFile") @patch("airflow.providers.apache.hive.transfers.mssql_to_hive.HiveCliHook") def test_execute(self, mock_hive_hook, mock_tmp_file, mock_csv): type(mock_tmp_file).name = PropertyMock(return_value="tmp_file") mock_tmp_file.return_value.__enter__ = Mock(return_value=mock_tmp_file) mssql_to_hive_transfer = MsSqlToHiveOperator(**self.kwargs) mssql_to_hive_transfer.execute(context={}) mock_tmp_file.assert_called_with(mode="w", encoding="utf-8") mock_csv.writer.assert_called_once_with(mock_tmp_file, delimiter=mssql_to_hive_transfer.delimiter) mock_hive_hook.return_value.load_file.assert_has_calls( [ call( "tmp_file", "table", field_dict={ "PersonID": "INT", "LastName": "STRING", "FirstName": "STRING", "Address": "STRING", "City": "STRING", }, create=True, partition={}, delimiter="\x01", recreate=False, tblproperties=None, ) ] )
TestMsSqlToHiveTransfer
python
getsentry__sentry
tests/sentry/integrations/repository/issue_alert/test_issue_alert_notification_message_repository.py
{ "start": 6613, "end": 12720 }
class ____( BaseIssueAlertNotificationMessageRepositoryTest ): def test_returns_all_when_no_filters(self) -> None: # Create additional notification messages additional_notification = NotificationMessage.objects.create( rule_fire_history=self.rule_fire_history, rule_action_uuid=str(uuid4()), message_identifier="123abc", ) # Call the method without any filters parent_notifications = list( self.repository.get_all_parent_notification_messages_by_filters() ) result_ids = [] for parent_notification in parent_notifications: result_ids.append(parent_notification.id) # Check if all notification messages are returned assert len(result_ids) == 2 assert additional_notification.id in result_ids assert self.parent_notification_message.id in result_ids def test_returns_filtered_messages_for_project_id(self) -> None: # Create some notification message that should not be returned new_project = self.create_project() additional_rule_fire_history = RuleFireHistory.objects.create( project=new_project, rule=self.rule, group=self.group, event_id=self.event_id, notification_uuid=str(uuid4()), ) notification_message_that_should_not_be_returned = NotificationMessage.objects.create( rule_fire_history=additional_rule_fire_history, rule_action_uuid=str(uuid4()), message_identifier="zxcvb", ) # Call the method with filters specifying the specific project id parent_notifications = list( self.repository.get_all_parent_notification_messages_by_filters( project_ids=[self.project.id] ) ) result_ids = [] for parent_notification in parent_notifications: result_ids.append(parent_notification.id) # Check if only the notifications related to the specified project assert len(result_ids) == 1 assert result_ids[0] == self.parent_notification_message.id assert notification_message_that_should_not_be_returned.id not in result_ids def test_returns_filtered_messages_for_group_id(self) -> None: # Create some notification message that should not be returned new_group = self.create_group(project=self.project) additional_rule_fire_history = RuleFireHistory.objects.create( project=self.project, rule=self.rule, group=new_group, event_id=self.event_id, notification_uuid=str(uuid4()), ) notification_message_that_should_not_be_returned = NotificationMessage.objects.create( rule_fire_history=additional_rule_fire_history, rule_action_uuid=str(uuid4()), message_identifier="zxcvb", ) # Call the method with filters specifying the specific project id parent_notifications = list( self.repository.get_all_parent_notification_messages_by_filters( group_ids=[self.group.id] ) ) result_ids = [] for parent_notification in parent_notifications: result_ids.append(parent_notification.id) # Check if only the notifications related to the specified project assert len(result_ids) == 1 assert result_ids[0] == self.parent_notification_message.id assert notification_message_that_should_not_be_returned.id not in result_ids @freeze_time("2025-01-01 00:00:00") def test_returns_correct_message_when_open_period_start_is_not_none(self) -> None: NotificationMessage.objects.create( rule_fire_history=self.rule_fire_history, rule_action_uuid=str(uuid4()), message_identifier="period123", open_period_start=timezone.now(), ) n2 = NotificationMessage.objects.create( rule_fire_history=self.rule_fire_history, rule_action_uuid=str(uuid4()), message_identifier="period123", open_period_start=timezone.now() + timedelta(seconds=1), ) n3 = NotificationMessage.objects.create( rule_fire_history=self.rule_fire_history, rule_action_uuid=str(uuid4()), message_identifier="period123", open_period_start=timezone.now() + timedelta(seconds=1), ) result = list( self.repository.get_all_parent_notification_messages_by_filters( project_ids=[self.project.id], group_ids=[self.group.id], open_period_start=timezone.now() + timedelta(seconds=1), ) ) result_ids = [] for parent_notification in result: result_ids.append(parent_notification.id) assert len(result_ids) == 2 assert n3.id in result_ids assert n2.id in result_ids @freeze_time("2025-01-01 00:00:00") def test_returns_none_when_open_period_start_does_not_match(self) -> None: # Create notifications with different open periods NotificationMessage.objects.create( rule_fire_history=self.rule_fire_history, rule_action_uuid=self.action_uuid, message_identifier="period1", open_period_start=timezone.now(), ) NotificationMessage.objects.create( rule_fire_history=self.rule_fire_history, rule_action_uuid=self.action_uuid, message_identifier="period2", open_period_start=timezone.now() + timedelta(days=1), ) # Query with a different open period instance = self.repository.get_parent_notification_message( rule_id=self.rule.id, group_id=self.group.id, rule_action_uuid=self.action_uuid, open_period_start=timezone.now() + timedelta(seconds=1), ) assert instance is None
TestGetAllParentNotificationMessagesByFilters
python
kubernetes-client__python
kubernetes/client/models/v1alpha1_volume_attributes_class_list.py
{ "start": 383, "end": 7328 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'api_version': 'str', 'items': 'list[V1alpha1VolumeAttributesClass]', 'kind': 'str', 'metadata': 'V1ListMeta' } attribute_map = { 'api_version': 'apiVersion', 'items': 'items', 'kind': 'kind', 'metadata': 'metadata' } def __init__(self, api_version=None, items=None, kind=None, metadata=None, local_vars_configuration=None): # noqa: E501 """V1alpha1VolumeAttributesClassList - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._api_version = None self._items = None self._kind = None self._metadata = None self.discriminator = None if api_version is not None: self.api_version = api_version self.items = items if kind is not None: self.kind = kind if metadata is not None: self.metadata = metadata @property def api_version(self): """Gets the api_version of this V1alpha1VolumeAttributesClassList. # noqa: E501 APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 :return: The api_version of this V1alpha1VolumeAttributesClassList. # noqa: E501 :rtype: str """ return self._api_version @api_version.setter def api_version(self, api_version): """Sets the api_version of this V1alpha1VolumeAttributesClassList. APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 :param api_version: The api_version of this V1alpha1VolumeAttributesClassList. # noqa: E501 :type: str """ self._api_version = api_version @property def items(self): """Gets the items of this V1alpha1VolumeAttributesClassList. # noqa: E501 items is the list of VolumeAttributesClass objects. # noqa: E501 :return: The items of this V1alpha1VolumeAttributesClassList. # noqa: E501 :rtype: list[V1alpha1VolumeAttributesClass] """ return self._items @items.setter def items(self, items): """Sets the items of this V1alpha1VolumeAttributesClassList. items is the list of VolumeAttributesClass objects. # noqa: E501 :param items: The items of this V1alpha1VolumeAttributesClassList. # noqa: E501 :type: list[V1alpha1VolumeAttributesClass] """ if self.local_vars_configuration.client_side_validation and items is None: # noqa: E501 raise ValueError("Invalid value for `items`, must not be `None`") # noqa: E501 self._items = items @property def kind(self): """Gets the kind of this V1alpha1VolumeAttributesClassList. # noqa: E501 Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :return: The kind of this V1alpha1VolumeAttributesClassList. # noqa: E501 :rtype: str """ return self._kind @kind.setter def kind(self, kind): """Sets the kind of this V1alpha1VolumeAttributesClassList. Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :param kind: The kind of this V1alpha1VolumeAttributesClassList. # noqa: E501 :type: str """ self._kind = kind @property def metadata(self): """Gets the metadata of this V1alpha1VolumeAttributesClassList. # noqa: E501 :return: The metadata of this V1alpha1VolumeAttributesClassList. # noqa: E501 :rtype: V1ListMeta """ return self._metadata @metadata.setter def metadata(self, metadata): """Sets the metadata of this V1alpha1VolumeAttributesClassList. :param metadata: The metadata of this V1alpha1VolumeAttributesClassList. # noqa: E501 :type: V1ListMeta """ self._metadata = metadata def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1alpha1VolumeAttributesClassList): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1alpha1VolumeAttributesClassList): return True return self.to_dict() != other.to_dict()
V1alpha1VolumeAttributesClassList
python
apache__airflow
helm-tests/tests/helm_tests/other/test_flower.py
{ "start": 27507, "end": 28197 }
class ____: """Tests flower secret.""" def test_should_add_annotations_to_flower_secret(self): docs = render_chart( values={ "flower": { "enabled": True, "username": "username", "password": "password", "secretAnnotations": {"test_annotation": "test_annotation_value"}, } }, show_only=["templates/secrets/flower-secret.yaml"], )[0] assert "annotations" in jmespath.search("metadata", docs) assert jmespath.search("metadata.annotations", docs)["test_annotation"] == "test_annotation_value"
TestFlowerSecret
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/hooks/test_sns.py
{ "start": 1535, "end": 3349 }
class ____: @pytest.fixture(autouse=True) def setup_moto(self): with mock_aws(): yield @pytest.fixture def hook(self): return SnsHook(aws_conn_id="aws_default") @pytest.fixture def target(self, hook): return hook.get_conn().create_topic(Name=TOPIC_NAME).get(TOPIC_ARN_KEY) def test_get_conn_returns_a_boto3_connection(self, hook): assert hook.get_conn() is not None def test_publish_to_target_with_subject(self, hook, target): response = hook.publish_to_target(target, MESSAGE, SUBJECT) assert MESSAGE_ID_KEY in response def test_publish_to_target_with_attributes(self, hook, target): response = hook.publish_to_target(target, MESSAGE, message_attributes=VALID_ATTRIBUTES) assert MESSAGE_ID_KEY in response def test_publish_to_target_plain(self, hook, target): response = hook.publish_to_target(target, MESSAGE) assert MESSAGE_ID_KEY in response def test_publish_to_target_error(self, hook, target): with pytest.raises(TypeError, match=INVALID_ATTRIBUTES_MSG): hook.publish_to_target(target, MESSAGE, message_attributes=INVALID_ATTRIBUTES) def test_publish_to_target_with_deduplication(self, hook): fifo_target = ( hook.get_conn() .create_topic( Name=f"{TOPIC_NAME}.fifo", Attributes={ "FifoTopic": "true", "ContentBasedDeduplication": "false", }, ) .get("TopicArn") ) response = hook.publish_to_target( fifo_target, MESSAGE, message_deduplication_id=DEDUPE_ID, message_group_id=GROUP_ID ) assert MESSAGE_ID_KEY in response @pytest.mark.asyncio
TestSnsHook
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 27881, "end": 28104 }
class ____(sgqlc.types.Enum): """ See source code for more info. """ __schema__ = graphql_schema __choices__ = ("APPROVED", "CHANGES_REQUESTED", "COMMENTED", "DISMISSED", "PENDING")
PullRequestReviewState
python
google__pytype
pytype/types/classes.py
{ "start": 168, "end": 1047 }
class ____(base.BaseValue, abc.ABC): """Base class for representation of python classes.""" @property @abc.abstractmethod def name(self) -> str: """Class name.""" @property @abc.abstractmethod def bases(self) -> Sequence[base.BaseValue]: """Class bases.""" @property @abc.abstractmethod def mro(self) -> Sequence[base.BaseValue]: """Class MRO.""" @property @abc.abstractmethod def metaclass(self) -> base.BaseValue: """Class metaclass.""" @property @abc.abstractmethod def decorators(self) -> Sequence[str]: """Class decoratotrs.""" @property @abc.abstractmethod def members(self) -> Mapping[str, base.BaseValue]: """Class members.""" @property @abc.abstractmethod def metadata(self) -> Mapping[str, Any]: """Metadata used in overlays and other metaprogramming contexts.""" @dataclasses.dataclass
Class
python
django__django
django/db/migrations/operations/fields.py
{ "start": 7071, "end": 9603 }
class ____(FieldOperation): """ Alter a field's database column (e.g. null, max_length) to the provided new field. """ category = OperationCategory.ALTERATION def __init__(self, model_name, name, field, preserve_default=True): self.preserve_default = preserve_default super().__init__(model_name, name, field) def deconstruct(self): kwargs = { "model_name": self.model_name, "name": self.name, "field": self.field, } if self.preserve_default is not True: kwargs["preserve_default"] = self.preserve_default return (self.__class__.__name__, [], kwargs) def state_forwards(self, app_label, state): state.alter_field( app_label, self.model_name_lower, self.name, self.field, self.preserve_default, ) def database_forwards(self, app_label, schema_editor, from_state, to_state): to_model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, to_model): from_model = from_state.apps.get_model(app_label, self.model_name) from_field = from_model._meta.get_field(self.name) to_field = to_model._meta.get_field(self.name) if not self.preserve_default: to_field.default = self.field.default schema_editor.alter_field(from_model, from_field, to_field) if not self.preserve_default: to_field.default = NOT_PROVIDED def database_backwards(self, app_label, schema_editor, from_state, to_state): self.database_forwards(app_label, schema_editor, from_state, to_state) def describe(self): return "Alter field %s on %s" % (self.name, self.model_name) @property def migration_name_fragment(self): return "alter_%s_%s" % (self.model_name_lower, self.name_lower) def reduce(self, operation, app_label): if isinstance( operation, (AlterField, RemoveField) ) and self.is_same_field_operation(operation): return [operation] elif ( isinstance(operation, RenameField) and self.is_same_field_operation(operation) and self.field.db_column is None ): return [ operation, replace(self, name=operation.new_name), ] return super().reduce(operation, app_label)
AlterField
python
kamyu104__LeetCode-Solutions
Python/shortest-string-that-contains-three-strings.py
{ "start": 1521, "end": 2136 }
class ____(object): def minimumString(self, a, b, c): """ :type a: str :type b: str :type c: str :rtype: str """ def merge(a, b): if a in b: return b l = next((l for l in reversed(xrange(1, min(len(a), len(b)))) if a[-l:] == b[:l]), 0) return a+b[l:] result = [merge(a, merge(b, c)), merge(a, merge(c, b)), merge(b, merge(a, c)), merge(b, merge(c, a)), merge(c, merge(a, b)), merge(c, merge(b, a))] return min(result, key=lambda x: (len(x), x))
Solution2
python
pytorch__pytorch
torch/_export/serde/schema.py
{ "start": 4673, "end": 4807 }
class ____: real: Annotated[float, 10] imag: Annotated[float, 20] # This is actually a union type @_union_dataclass
ComplexValue
python
python-markdown__markdown
markdown/postprocessors.py
{ "start": 4180, "end": 4493 }
class ____(Postprocessor): """ Restore escaped chars. """ RE = re.compile(r'{}(\d+){}'.format(util.STX, util.ETX)) def unescape(self, m: re.Match[str]) -> str: return chr(int(m.group(1))) def run(self, text: str) -> str: return self.RE.sub(self.unescape, text)
UnescapePostprocessor
python
squidfunk__mkdocs-material
material/plugins/social/config.py
{ "start": 1493, "end": 2845 }
class ____(Config): enabled = Type(bool, default = True) concurrency = Type(int, default = max(1, os.cpu_count() - 1)) # Settings for caching cache = Type(bool, default = True) cache_dir = Type(str, default = ".cache/plugin/social") # Settings for logging log = Type(bool, default = True) log_level = _LogLevel(default = "warn") # Settings for cards cards = Type(bool, default = True) cards_dir = Type(str, default = "assets/images/social") cards_layout_dir = Type(str, default = "layouts") cards_layout = Type(str, default = "default") cards_layout_options = Type(dict, default = {}) cards_include = ListOfItems(Type(str), default = []) cards_exclude = ListOfItems(Type(str), default = []) # Settings for debugging debug = Type(bool, default = False) debug_on_build = Type(bool, default = False) debug_grid = Type(bool, default = True) debug_grid_step = Type(int, default = 32) debug_color = Type(str, default = "grey") # Deprecated settings cards_color = Deprecated( message = "Deprecated, use 'cards_layout_options.background_color' " "and 'cards_layout_options.color' with 'default' layout" ) cards_font = Deprecated( message = "Deprecated, use 'cards_layout_options.font_family'" )
SocialConfig
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_data_labels24.py
{ "start": 315, "end": 1875 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_data_labels24.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "column"}) chart.axis_ids = [45937792, 45939712] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) chart.add_series( { "values": "=Sheet1!$A$1:$A$5", "data_labels": { "value": 1, "font": { "name": "Consolas", "size": 12, "baseline": 1 * -1, "pitch_family": 49, "charset": 0, }, }, } ) chart.add_series( { "values": "=Sheet1!$B$1:$B$5", "data_labels": {"value": 1, "position": "inside_base"}, } ) chart.add_series({"values": "=Sheet1!$C$1:$C$5"}) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
matplotlib__matplotlib
lib/mpl_toolkits/axes_grid1/inset_locator.py
{ "start": 434, "end": 1310 }
class ____(AnchoredOffsetbox): def __init__(self, bbox_to_anchor, offsetbox, loc, borderpad=0.5, bbox_transform=None): super().__init__( loc, pad=0., child=None, borderpad=borderpad, bbox_to_anchor=bbox_to_anchor, bbox_transform=bbox_transform ) def draw(self, renderer): raise RuntimeError("No draw method should be called") def __call__(self, ax, renderer): fig = ax.get_figure(root=False) if renderer is None: renderer = fig._get_renderer() self.axes = ax bbox = self.get_window_extent(renderer) px, py = self.get_offset(bbox.width, bbox.height, 0, 0, renderer) bbox_canvas = Bbox.from_bounds(px, py, bbox.width, bbox.height) tr = fig.transSubfigure.inverted() return TransformedBbox(bbox_canvas, tr)
AnchoredLocatorBase
python
pytest-dev__pytest
src/_pytest/_io/terminalwriter.py
{ "start": 1211, "end": 8994 }
class ____: _esctable = dict( black=30, red=31, green=32, yellow=33, blue=34, purple=35, cyan=36, white=37, Black=40, Red=41, Green=42, Yellow=43, Blue=44, Purple=45, Cyan=46, White=47, bold=1, light=2, blink=5, invert=7, ) def __init__(self, file: TextIO | None = None) -> None: if file is None: file = sys.stdout if hasattr(file, "isatty") and file.isatty() and sys.platform == "win32": try: import colorama except ImportError: pass else: file = colorama.AnsiToWin32(file).stream assert file is not None self._file = file self.hasmarkup = should_do_markup(file) self._current_line = "" self._terminal_width: int | None = None self.code_highlight = True @property def fullwidth(self) -> int: if self._terminal_width is not None: return self._terminal_width return get_terminal_width() @fullwidth.setter def fullwidth(self, value: int) -> None: self._terminal_width = value @property def width_of_current_line(self) -> int: """Return an estimate of the width so far in the current line.""" return wcswidth(self._current_line) def markup(self, text: str, **markup: bool) -> str: for name in markup: if name not in self._esctable: raise ValueError(f"unknown markup: {name!r}") if self.hasmarkup: esc = [self._esctable[name] for name, on in markup.items() if on] if esc: text = "".join(f"\x1b[{cod}m" for cod in esc) + text + "\x1b[0m" return text def sep( self, sepchar: str, title: str | None = None, fullwidth: int | None = None, **markup: bool, ) -> None: if fullwidth is None: fullwidth = self.fullwidth # The goal is to have the line be as long as possible # under the condition that len(line) <= fullwidth. if sys.platform == "win32": # If we print in the last column on windows we are on a # new line but there is no way to verify/neutralize this # (we may not know the exact line width). # So let's be defensive to avoid empty lines in the output. fullwidth -= 1 if title is not None: # we want 2 + 2*len(fill) + len(title) <= fullwidth # i.e. 2 + 2*len(sepchar)*N + len(title) <= fullwidth # 2*len(sepchar)*N <= fullwidth - len(title) - 2 # N <= (fullwidth - len(title) - 2) // (2*len(sepchar)) N = max((fullwidth - len(title) - 2) // (2 * len(sepchar)), 1) fill = sepchar * N line = f"{fill} {title} {fill}" else: # we want len(sepchar)*N <= fullwidth # i.e. N <= fullwidth // len(sepchar) line = sepchar * (fullwidth // len(sepchar)) # In some situations there is room for an extra sepchar at the right, # in particular if we consider that with a sepchar like "_ " the # trailing space is not important at the end of the line. if len(line) + len(sepchar.rstrip()) <= fullwidth: line += sepchar.rstrip() self.line(line, **markup) def write(self, msg: str, *, flush: bool = False, **markup: bool) -> None: if msg: current_line = msg.rsplit("\n", 1)[-1] if "\n" in msg: self._current_line = current_line else: self._current_line += current_line msg = self.markup(msg, **markup) self.write_raw(msg, flush=flush) def write_raw(self, msg: str, *, flush: bool = False) -> None: try: self._file.write(msg) except UnicodeEncodeError: # Some environments don't support printing general Unicode # strings, due to misconfiguration or otherwise; in that case, # print the string escaped to ASCII. # When the Unicode situation improves we should consider # letting the error propagate instead of masking it (see #7475 # for one brief attempt). msg = msg.encode("unicode-escape").decode("ascii") self._file.write(msg) if flush: self.flush() def line(self, s: str = "", **markup: bool) -> None: self.write(s, **markup) self.write("\n") def flush(self) -> None: self._file.flush() def _write_source(self, lines: Sequence[str], indents: Sequence[str] = ()) -> None: """Write lines of source code possibly highlighted. Keeping this private for now because the API is clunky. We should discuss how to evolve the terminal writer so we can have more precise color support, for example being able to write part of a line in one color and the rest in another, and so on. """ if indents and len(indents) != len(lines): raise ValueError( f"indents size ({len(indents)}) should have same size as lines ({len(lines)})" ) if not indents: indents = [""] * len(lines) source = "\n".join(lines) new_lines = self._highlight(source).splitlines() # Would be better to strict=True but that fails some CI jobs. for indent, new_line in zip(indents, new_lines, strict=False): self.line(indent + new_line) def _get_pygments_lexer(self, lexer: Literal["python", "diff"]) -> Lexer: if lexer == "python": return PythonLexer() elif lexer == "diff": return DiffLexer() else: assert_never(lexer) def _get_pygments_formatter(self) -> TerminalFormatter: from _pytest.config.exceptions import UsageError theme = os.getenv("PYTEST_THEME") theme_mode = os.getenv("PYTEST_THEME_MODE", "dark") try: return TerminalFormatter(bg=theme_mode, style=theme) except pygments.util.ClassNotFound as e: raise UsageError( f"PYTEST_THEME environment variable has an invalid value: '{theme}'. " "Hint: See available pygments styles with `pygmentize -L styles`." ) from e except pygments.util.OptionError as e: raise UsageError( f"PYTEST_THEME_MODE environment variable has an invalid value: '{theme_mode}'. " "The allowed values are 'dark' (default) and 'light'." ) from e def _highlight( self, source: str, lexer: Literal["diff", "python"] = "python" ) -> str: """Highlight the given source if we have markup support.""" if not source or not self.hasmarkup or not self.code_highlight: return source pygments_lexer = self._get_pygments_lexer(lexer) pygments_formatter = self._get_pygments_formatter() highlighted: str = pygments.highlight( source, pygments_lexer, pygments_formatter ) # pygments terminal formatter may add a newline when there wasn't one. # We don't want this, remove. if highlighted[-1] == "\n" and source[-1] != "\n": highlighted = highlighted[:-1] # Some lexers will not set the initial color explicitly # which may lead to the previous color being propagated to the # start of the expression, so reset first. highlighted = "\x1b[0m" + highlighted return highlighted
TerminalWriter
python
pypa__pip
src/pip/_internal/operations/install/wheel.py
{ "start": 1548, "end": 12379 }
class ____(Protocol): src_record_path: RecordPath dest_path: str changed: bool def save(self) -> None: pass logger = logging.getLogger(__name__) RecordPath = NewType("RecordPath", str) InstalledCSVRow = tuple[RecordPath, str, Union[int, str]] def rehash(path: str, blocksize: int = 1 << 20) -> tuple[str, str]: """Return (encoded_digest, length) for path using hashlib.sha256()""" h, length = hash_file(path, blocksize) digest = "sha256=" + urlsafe_b64encode(h.digest()).decode("latin1").rstrip("=") return (digest, str(length)) def csv_io_kwargs(mode: str) -> dict[str, Any]: """Return keyword arguments to properly open a CSV file in the given mode. """ return {"mode": mode, "newline": "", "encoding": "utf-8"} def fix_script(path: str) -> bool: """Replace #!python with #!/path/to/python Return True if file was changed. """ # XXX RECORD hashes will need to be updated assert os.path.isfile(path) with open(path, "rb") as script: firstline = script.readline() if not firstline.startswith(b"#!python"): return False exename = sys.executable.encode(sys.getfilesystemencoding()) firstline = b"#!" + exename + os.linesep.encode("ascii") rest = script.read() with open(path, "wb") as script: script.write(firstline) script.write(rest) return True def wheel_root_is_purelib(metadata: Message) -> bool: return metadata.get("Root-Is-Purelib", "").lower() == "true" def get_entrypoints(dist: BaseDistribution) -> tuple[dict[str, str], dict[str, str]]: console_scripts = {} gui_scripts = {} for entry_point in dist.iter_entry_points(): if entry_point.group == "console_scripts": console_scripts[entry_point.name] = entry_point.value elif entry_point.group == "gui_scripts": gui_scripts[entry_point.name] = entry_point.value return console_scripts, gui_scripts def message_about_scripts_not_on_PATH(scripts: Sequence[str]) -> str | None: """Determine if any scripts are not on PATH and format a warning. Returns a warning message if one or more scripts are not on PATH, otherwise None. """ if not scripts: return None # Group scripts by the path they were installed in grouped_by_dir: dict[str, set[str]] = collections.defaultdict(set) for destfile in scripts: parent_dir = os.path.dirname(destfile) script_name = os.path.basename(destfile) grouped_by_dir[parent_dir].add(script_name) # We don't want to warn for directories that are on PATH. not_warn_dirs = [ os.path.normcase(os.path.normpath(i)).rstrip(os.sep) for i in os.environ.get("PATH", "").split(os.pathsep) ] # If an executable sits with sys.executable, we don't warn for it. # This covers the case of venv invocations without activating the venv. not_warn_dirs.append( os.path.normcase(os.path.normpath(os.path.dirname(sys.executable))) ) warn_for: dict[str, set[str]] = { parent_dir: scripts for parent_dir, scripts in grouped_by_dir.items() if os.path.normcase(os.path.normpath(parent_dir)) not in not_warn_dirs } if not warn_for: return None # Format a message msg_lines = [] for parent_dir, dir_scripts in warn_for.items(): sorted_scripts: list[str] = sorted(dir_scripts) if len(sorted_scripts) == 1: start_text = f"script {sorted_scripts[0]} is" else: start_text = "scripts {} are".format( ", ".join(sorted_scripts[:-1]) + " and " + sorted_scripts[-1] ) msg_lines.append( f"The {start_text} installed in '{parent_dir}' which is not on PATH." ) last_line_fmt = ( "Consider adding {} to PATH or, if you prefer " "to suppress this warning, use --no-warn-script-location." ) if len(msg_lines) == 1: msg_lines.append(last_line_fmt.format("this directory")) else: msg_lines.append(last_line_fmt.format("these directories")) # Add a note if any directory starts with ~ warn_for_tilde = any( i[0] == "~" for i in os.environ.get("PATH", "").split(os.pathsep) if i ) if warn_for_tilde: tilde_warning_msg = ( "NOTE: The current PATH contains path(s) starting with `~`, " "which may not be expanded by all applications." ) msg_lines.append(tilde_warning_msg) # Returns the formatted multiline message return "\n".join(msg_lines) def _normalized_outrows( outrows: Iterable[InstalledCSVRow], ) -> list[tuple[str, str, str]]: """Normalize the given rows of a RECORD file. Items in each row are converted into str. Rows are then sorted to make the value more predictable for tests. Each row is a 3-tuple (path, hash, size) and corresponds to a record of a RECORD file (see PEP 376 and PEP 427 for details). For the rows passed to this function, the size can be an integer as an int or string, or the empty string. """ # Normally, there should only be one row per path, in which case the # second and third elements don't come into play when sorting. # However, in cases in the wild where a path might happen to occur twice, # we don't want the sort operation to trigger an error (but still want # determinism). Since the third element can be an int or string, we # coerce each element to a string to avoid a TypeError in this case. # For additional background, see-- # https://github.com/pypa/pip/issues/5868 return sorted( (record_path, hash_, str(size)) for record_path, hash_, size in outrows ) def _record_to_fs_path(record_path: RecordPath, lib_dir: str) -> str: return os.path.join(lib_dir, record_path) def _fs_to_record_path(path: str, lib_dir: str) -> RecordPath: # On Windows, do not handle relative paths if they belong to different # logical disks if os.path.splitdrive(path)[0].lower() == os.path.splitdrive(lib_dir)[0].lower(): path = os.path.relpath(path, lib_dir) path = path.replace(os.path.sep, "/") return cast("RecordPath", path) def get_csv_rows_for_installed( old_csv_rows: list[list[str]], installed: dict[RecordPath, RecordPath], changed: set[RecordPath], generated: list[str], lib_dir: str, ) -> list[InstalledCSVRow]: """ :param installed: A map from archive RECORD path to installation RECORD path. """ installed_rows: list[InstalledCSVRow] = [] for row in old_csv_rows: if len(row) > 3: logger.warning("RECORD line has more than three elements: %s", row) old_record_path = cast("RecordPath", row[0]) new_record_path = installed.pop(old_record_path, old_record_path) if new_record_path in changed: digest, length = rehash(_record_to_fs_path(new_record_path, lib_dir)) else: digest = row[1] if len(row) > 1 else "" length = row[2] if len(row) > 2 else "" installed_rows.append((new_record_path, digest, length)) for f in generated: path = _fs_to_record_path(f, lib_dir) digest, length = rehash(f) installed_rows.append((path, digest, length)) return installed_rows + [ (installed_record_path, "", "") for installed_record_path in installed.values() ] def get_console_script_specs(console: dict[str, str]) -> list[str]: """ Given the mapping from entrypoint name to callable, return the relevant console script specs. """ # Don't mutate caller's version console = console.copy() scripts_to_generate = [] # Special case pip and setuptools to generate versioned wrappers # # The issue is that some projects (specifically, pip and setuptools) use # code in setup.py to create "versioned" entry points - pip2.7 on Python # 2.7, pip3.3 on Python 3.3, etc. But these entry points are baked into # the wheel metadata at build time, and so if the wheel is installed with # a *different* version of Python the entry points will be wrong. The # correct fix for this is to enhance the metadata to be able to describe # such versioned entry points. # Currently, projects using versioned entry points will either have # incorrect versioned entry points, or they will not be able to distribute # "universal" wheels (i.e., they will need a wheel per Python version). # # Because setuptools and pip are bundled with _ensurepip and virtualenv, # we need to use universal wheels. As a workaround, we # override the versioned entry points in the wheel and generate the # correct ones. # # To add the level of hack in this section of code, in order to support # ensurepip this code will look for an ``ENSUREPIP_OPTIONS`` environment # variable which will control which version scripts get installed. # # ENSUREPIP_OPTIONS=altinstall # - Only pipX.Y and easy_install-X.Y will be generated and installed # ENSUREPIP_OPTIONS=install # - pipX.Y, pipX, easy_install-X.Y will be generated and installed. Note # that this option is technically if ENSUREPIP_OPTIONS is set and is # not altinstall # DEFAULT # - The default behavior is to install pip, pipX, pipX.Y, easy_install # and easy_install-X.Y. pip_script = console.pop("pip", None) if pip_script: if "ENSUREPIP_OPTIONS" not in os.environ: scripts_to_generate.append("pip = " + pip_script) if os.environ.get("ENSUREPIP_OPTIONS", "") != "altinstall": scripts_to_generate.append(f"pip{sys.version_info[0]} = {pip_script}") scripts_to_generate.append(f"pip{get_major_minor_version()} = {pip_script}") # Delete any other versioned pip entry points pip_ep = [k for k in console if re.match(r"pip(\d+(\.\d+)?)?$", k)] for k in pip_ep: del console[k] easy_install_script = console.pop("easy_install", None) if easy_install_script: if "ENSUREPIP_OPTIONS" not in os.environ: scripts_to_generate.append("easy_install = " + easy_install_script) scripts_to_generate.append( f"easy_install-{get_major_minor_version()} = {easy_install_script}" ) # Delete any other versioned easy_install entry points easy_install_ep = [ k for k in console if re.match(r"easy_install(-\d+\.\d+)?$", k) ] for k in easy_install_ep: del console[k] # Generate the console entry points specified in the wheel scripts_to_generate.extend(starmap("{} = {}".format, console.items())) return scripts_to_generate
File
python
numpy__numpy
numpy/distutils/system_info.py
{ "start": 42596, "end": 42923 }
class ____(fftw_info): section = 'fftw' dir_env_var = 'FFTW' ver_info = [{'name':'dfftw threads', 'libs':['drfftw_threads', 'dfftw_threads'], 'includes':['dfftw_threads.h', 'drfftw_threads.h'], 'macros':[('SCIPY_DFFTW_THREADS_H', None)]}]
dfftw_threads_info
python
doocs__leetcode
solution/0800-0899/0802.Find Eventual Safe States/Solution.py
{ "start": 0, "end": 566 }
class ____: def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: rg = defaultdict(list) indeg = [0] * len(graph) for i, vs in enumerate(graph): for j in vs: rg[j].append(i) indeg[i] = len(vs) q = deque([i for i, v in enumerate(indeg) if v == 0]) while q: i = q.popleft() for j in rg[i]: indeg[j] -= 1 if indeg[j] == 0: q.append(j) return [i for i, v in enumerate(indeg) if v == 0]
Solution
python
zarr-developers__zarr-python
src/zarr/storage/_local.py
{ "start": 2688, "end": 10346 }
class ____(Store): """ Store for the local file system. Parameters ---------- root : str or Path Directory to use as root of store. read_only : bool Whether the store is read-only Attributes ---------- supports_writes supports_deletes supports_listing root """ supports_writes: bool = True supports_deletes: bool = True supports_listing: bool = True root: Path def __init__(self, root: Path | str, *, read_only: bool = False) -> None: super().__init__(read_only=read_only) if isinstance(root, str): root = Path(root) if not isinstance(root, Path): raise TypeError( f"'root' must be a string or Path instance. Got an instance of {type(root)} instead." ) self.root = root def with_read_only(self, read_only: bool = False) -> Self: # docstring inherited return type(self)( root=self.root, read_only=read_only, ) @classmethod async def open( cls, root: Path | str, *, read_only: bool = False, mode: AccessModeLiteral | None = None ) -> Self: """ Create and open the store. Parameters ---------- root : str or Path Directory to use as root of store. read_only : bool Whether the store is read-only mode : Mode in which to create the store. This only affects opening the store, and the final read-only state of the store is controlled through the read_only parameter. Returns ------- Store The opened store instance. """ # If mode = 'r+', want to open in read only mode (fail if exists), # but return a writeable store if mode is not None: read_only_creation = mode in ["r", "r+"] else: read_only_creation = read_only store = cls(root, read_only=read_only_creation) await store._open() # Set read_only state store = store.with_read_only(read_only) await store._open() return store async def _open(self, *, mode: AccessModeLiteral | None = None) -> None: if not self.read_only: self.root.mkdir(parents=True, exist_ok=True) if not self.root.exists(): raise FileNotFoundError(f"{self.root} does not exist") return await super()._open() async def clear(self) -> None: # docstring inherited self._check_writable() shutil.rmtree(self.root) self.root.mkdir() def __str__(self) -> str: return f"file://{self.root.as_posix()}" def __repr__(self) -> str: return f"LocalStore('{self}')" def __eq__(self, other: object) -> bool: return isinstance(other, type(self)) and self.root == other.root async def get( self, key: str, prototype: BufferPrototype | None = None, byte_range: ByteRequest | None = None, ) -> Buffer | None: # docstring inherited if prototype is None: prototype = default_buffer_prototype() if not self._is_open: await self._open() assert isinstance(key, str) path = self.root / key try: return await asyncio.to_thread(_get, path, prototype, byte_range) except (FileNotFoundError, IsADirectoryError, NotADirectoryError): return None async def get_partial_values( self, prototype: BufferPrototype, key_ranges: Iterable[tuple[str, ByteRequest | None]], ) -> list[Buffer | None]: # docstring inherited args = [] for key, byte_range in key_ranges: assert isinstance(key, str) path = self.root / key args.append((_get, path, prototype, byte_range)) return await concurrent_map(args, asyncio.to_thread, limit=None) # TODO: fix limit async def set(self, key: str, value: Buffer) -> None: # docstring inherited return await self._set(key, value) async def set_if_not_exists(self, key: str, value: Buffer) -> None: # docstring inherited try: return await self._set(key, value, exclusive=True) except FileExistsError: pass async def _set(self, key: str, value: Buffer, exclusive: bool = False) -> None: if not self._is_open: await self._open() self._check_writable() assert isinstance(key, str) if not isinstance(value, Buffer): raise TypeError( f"LocalStore.set(): `value` must be a Buffer instance. Got an instance of {type(value)} instead." ) path = self.root / key await asyncio.to_thread(_put, path, value, exclusive=exclusive) async def delete(self, key: str) -> None: """ Remove a key from the store. Parameters ---------- key : str Notes ----- If ``key`` is a directory within this store, the entire directory at ``store.root / key`` is deleted. """ # docstring inherited self._check_writable() path = self.root / key if path.is_dir(): # TODO: support deleting directories? shutil.rmtree? shutil.rmtree(path) else: await asyncio.to_thread(path.unlink, True) # Q: we may want to raise if path is missing async def delete_dir(self, prefix: str) -> None: # docstring inherited self._check_writable() path = self.root / prefix if path.is_dir(): shutil.rmtree(path) elif path.is_file(): raise ValueError(f"delete_dir was passed a {prefix=!r} that is a file") else: # Non-existent directory # This path is tested by test_group:test_create_creates_parents for one pass async def exists(self, key: str) -> bool: # docstring inherited path = self.root / key return await asyncio.to_thread(path.is_file) async def list(self) -> AsyncIterator[str]: # docstring inherited to_strip = self.root.as_posix() + "/" for p in list(self.root.rglob("*")): if p.is_file(): yield p.as_posix().replace(to_strip, "") async def list_prefix(self, prefix: str) -> AsyncIterator[str]: # docstring inherited to_strip = self.root.as_posix() + "/" prefix = prefix.rstrip("/") for p in (self.root / prefix).rglob("*"): if p.is_file(): yield p.as_posix().replace(to_strip, "") async def list_dir(self, prefix: str) -> AsyncIterator[str]: # docstring inherited base = self.root / prefix try: key_iter = base.iterdir() for key in key_iter: yield key.relative_to(base).as_posix() except (FileNotFoundError, NotADirectoryError): pass async def move(self, dest_root: Path | str) -> None: """ Move the store to another path. The old root directory is deleted. """ if isinstance(dest_root, str): dest_root = Path(dest_root) os.makedirs(dest_root.parent, exist_ok=True) if os.path.exists(dest_root): raise FileExistsError(f"Destination root {dest_root} already exists.") shutil.move(self.root, dest_root) self.root = dest_root async def getsize(self, key: str) -> int: return os.path.getsize(self.root / key)
LocalStore
python
doocs__leetcode
solution/0800-0899/0882.Reachable Nodes In Subdivided Graph/Solution.py
{ "start": 0, "end": 722 }
class ____: def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int: g = defaultdict(list) for u, v, cnt in edges: g[u].append((v, cnt + 1)) g[v].append((u, cnt + 1)) q = [(0, 0)] dist = [0] + [inf] * n while q: d, u = heappop(q) for v, cnt in g[u]: if (t := d + cnt) < dist[v]: dist[v] = t q.append((t, v)) ans = sum(d <= maxMoves for d in dist) for u, v, cnt in edges: a = min(cnt, max(0, maxMoves - dist[u])) b = min(cnt, max(0, maxMoves - dist[v])) ans += min(cnt, a + b) return ans
Solution
python
walkccc__LeetCode
solutions/2380. Time Needed to Rearrange a Binary String/2380.py
{ "start": 0, "end": 236 }
class ____: def secondsToRemoveOccurrences(self, s: str) -> int: ans = 0 zeros = 0 for c in s: if c == '0': zeros += 1 elif zeros > 0: # c == '1' ans = max(ans + 1, zeros) return ans
Solution
python
numba__numba
numba/tests/annotation_usecases.py
{ "start": 129, "end": 316 }
class ____: """ A class with annotated methods. """ def __init__(self, v: int): self.x = v def add(self, v: int) -> int: return self.x + v
AnnotatedClass
python
docker__docker-py
docker/credentials/errors.py
{ "start": 93, "end": 440 }
class ____(StoreError): pass def process_store_error(cpe, program): message = cpe.output.decode('utf-8') if 'credentials not found in native keychain' in message: return CredentialsNotFound(f'No matching credentials in {program}') return StoreError(f'Credentials store {program} exited with "{message}".')
InitializationError
python
pytoolz__toolz
toolz/functoolz.py
{ "start": 14156, "end": 18815 }
class ____: """ A composition of functions See Also: compose """ __slots__ = 'first', 'funcs' def __init__(self, funcs): funcs = tuple(reversed(funcs)) self.first = funcs[0] self.funcs = funcs[1:] def __call__(self, *args, **kwargs): ret = self.first(*args, **kwargs) for f in self.funcs: ret = f(ret) return ret def __getstate__(self): return self.first, self.funcs def __setstate__(self, state): self.first, self.funcs = state @instanceproperty(classval=__doc__) def __doc__(self): def composed_doc(*fs): """Generate a docstring for the composition of fs. """ if not fs: # Argument name for the docstring. return '*args, **kwargs' return f'{fs[0].__name__}({composed_doc(*fs[1:])})' try: return ( 'lambda *args, **kwargs: ' + composed_doc(*reversed((self.first,) + self.funcs)) ) except AttributeError: # One of our callables does not have a `__name__`, whatever. return 'A composition of functions' @property def __name__(self): try: return '_of_'.join( f.__name__ for f in reversed((self.first,) + self.funcs) ) except AttributeError: return type(self).__name__ def __repr__(self): return '{.__class__.__name__}{!r}'.format( self, tuple(reversed((self.first, ) + self.funcs))) def __eq__(self, other): if isinstance(other, Compose): return other.first == self.first and other.funcs == self.funcs return NotImplemented def __ne__(self, other): equality = self.__eq__(other) return NotImplemented if equality is NotImplemented else not equality def __hash__(self): return hash(self.first) ^ hash(self.funcs) # Mimic the descriptor behavior of python functions. # i.e. let Compose be called as a method when bound to a class. # adapted from # docs.python.org/3/howto/descriptor.html#functions-and-methods def __get__(self, obj, objtype=None): return self if obj is None else MethodType(self, obj) # introspection with Signature is only possible from py3.3+ @instanceproperty def __signature__(self): base = inspect.signature(self.first) last = inspect.signature(self.funcs[-1]) return base.replace(return_annotation=last.return_annotation) __wrapped__ = instanceproperty(attrgetter('first')) def compose(*funcs): """ Compose functions to operate in series. Returns a function that applies other functions in sequence. Functions are applied from right to left so that ``compose(f, g, h)(x, y)`` is the same as ``f(g(h(x, y)))``. If no arguments are provided, the identity function (f(x) = x) is returned. >>> inc = lambda i: i + 1 >>> compose(str, inc)(3) '4' See Also: compose_left pipe """ if not funcs: return identity if len(funcs) == 1: return funcs[0] else: return Compose(funcs) def compose_left(*funcs): """ Compose functions to operate in series. Returns a function that applies other functions in sequence. Functions are applied from left to right so that ``compose_left(f, g, h)(x, y)`` is the same as ``h(g(f(x, y)))``. If no arguments are provided, the identity function (f(x) = x) is returned. >>> inc = lambda i: i + 1 >>> compose_left(inc, str)(3) '4' See Also: compose pipe """ return compose(*reversed(funcs)) def pipe(data, *funcs): """ Pipe a value through a sequence of functions I.e. ``pipe(data, f, g, h)`` is equivalent to ``h(g(f(data)))`` We think of the value as progressing through a pipe of several transformations, much like pipes in UNIX ``$ cat data | f | g | h`` >>> double = lambda i: 2 * i >>> pipe(3, double, str) '6' See Also: compose compose_left thread_first thread_last """ for func in funcs: data = func(data) return data def complement(func): """ Convert a predicate function to its logical complement. In other words, return a function that, for inputs that normally yield True, yields False, and vice-versa. >>> def iseven(n): return n % 2 == 0 >>> isodd = complement(iseven) >>> iseven(2) True >>> isodd(2) False """ return compose(not_, func)
Compose
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_cloud_logging_sink.py
{ "start": 4920, "end": 11443 }
class ____: def test_template_fields(self): operator = CloudLoggingCreateSinkOperator(task_id=TASK_ID, project_id=PROJECT_ID, sink_config=sink) assert "sink_config" in operator.template_fields assert "unique_writer_identity" in operator.template_fields _assert_common_template_fields(operator.template_fields) def test_missing_required_params(self): with pytest.raises(AirflowException) as excinfo: CloudLoggingCreateSinkOperator( task_id=TASK_ID, sink_config=None, project_id=None, ).execute(context={}) assert "Required parameters are missing: ['project_id', 'sink_config']." in str(excinfo.value) @mock.patch(CLOUD_LOGGING_HOOK_PATH) @pytest.mark.parametrize("sink_config", create_test_cases, ids=create_test_ids) def test_create_with_pubsub_sink(self, hook_mock, sink_config): hook_instance = hook_mock.return_value hook_instance.create_sink.return_value = LogSink(**sink_config) operator = CloudLoggingCreateSinkOperator( task_id=TASK_ID, sink_config=sink_config, project_id=PROJECT_ID, unique_writer_identity=UNIQUE_WRITER_IDENTITY, ) operator.execute(context=mock.MagicMock()) hook_instance.create_sink.assert_called_once_with( project_id=PROJECT_ID, sink=sink_config, unique_writer_identity=UNIQUE_WRITER_IDENTITY ) @mock.patch(CLOUD_LOGGING_HOOK_PATH) @pytest.mark.parametrize("sink_config", create_test_cases, ids=create_test_ids) def test_create_sink_already_exists(self, hook_mock, sink_config): hook_instance = hook_mock.return_value hook_instance.create_sink.side_effect = AlreadyExists("Sink already exists") hook_instance.get_sink.return_value = LogSink(**sink_config) operator = CloudLoggingCreateSinkOperator( task_id=TASK_ID, sink_config=sink_config, project_id=PROJECT_ID, ) result = operator.execute(context=mock.MagicMock()) hook_instance.create_sink.assert_called_once_with( project_id=PROJECT_ID, sink=sink_config, unique_writer_identity=False ) assert result["name"] == sink_config["name"] assert result["destination"] == sink_config["destination"] @mock.patch(CLOUD_LOGGING_HOOK_PATH) @pytest.mark.parametrize("sink_config", create_test_cases, ids=create_test_ids) def test_create_sink_raises_error(self, hook_mock, sink_config): hook_instance = hook_mock.return_value hook_instance.create_sink.side_effect = GoogleCloudError("Failed to create sink") hook_instance.get_sink.return_value = sink_config operator = CloudLoggingCreateSinkOperator( task_id=TASK_ID, sink_config=sink_config, project_id=PROJECT_ID, ) with pytest.raises(GoogleCloudError, match="Failed to create sink"): operator.execute(context=mock.MagicMock()) hook_instance.create_sink.assert_called_once() @mock.patch(CLOUD_LOGGING_HOOK_PATH) @pytest.mark.parametrize( "impersonation_chain", [ ["user1@project.iam.gserviceaccount.com", "user2@project.iam.gserviceaccount.com"], "user2@project.iam.gserviceaccount.com", ], ) def test_create_with_impersonation_chain(self, hook_mock, impersonation_chain): hook_instance = hook_mock.return_value hook_instance.create_sink.return_value = sink operator = CloudLoggingCreateSinkOperator( task_id=TASK_ID, sink_config=sink, impersonation_chain=impersonation_chain, project_id=PROJECT_ID, ) operator.execute(context=mock.MagicMock()) hook_mock.assert_called_once_with( gcp_conn_id="google_cloud_default", impersonation_chain=impersonation_chain, ) def test_missing_rendered_field_raises(self): with DAG( dag_id="test_render_native", start_date=datetime(1997, 9, 25), render_template_as_native_obj=True, ) as dag: operator = CloudLoggingCreateSinkOperator( task_id=TASK_ID, sink_config="{{ var.value.sink_config }}", project_id="{{ var.value.project_id }}", dag=dag, ) context = { "var": {"value": {"project_id": PROJECT_ID, "sink_config": None}}, } operator.render_template_fields(context) with pytest.raises( AirflowException, match=re.escape( "Required parameters are missing: ['sink_config']. These must be passed as keyword parameters." ), ): operator.execute(context) @mock.patch(CLOUD_LOGGING_HOOK_PATH) @pytest.mark.parametrize("sink_config", create_test_cases, ids=create_test_ids) def test_template_rendering(self, hook_mock, sink_config): with DAG( dag_id="test_render_native", start_date=datetime(2024, 1, 1), render_template_as_native_obj=True, ) as dag: operator = CloudLoggingCreateSinkOperator( task_id=TASK_ID, sink_config="{{ var.value.sink_config }}", project_id="{{ var.value.project_id }}", dag=dag, ) context = { "var": {"value": {"project_id": PROJECT_ID, "sink_config": sink_config}}, } hook_instance = hook_mock.return_value hook_instance.create_sink.return_value = LogSink(**sink_config) operator.render_template_fields(context) operator.execute(context) assert isinstance(operator.sink_config, dict) assert operator.sink_config == sink_config @mock.patch(CLOUD_LOGGING_HOOK_PATH) def test_create_with_empty_sink_name_raises(self, hook_mock): sink.name = None hook_instance = hook_mock.return_value hook_instance.create_sink.side_effect = InvalidArgument("Required parameter 'sink.name' is empty") with pytest.raises( InvalidArgument, match="400 Required parameter 'sink.name' is empty", ): CloudLoggingCreateSinkOperator(task_id=TASK_ID, sink_config=sink, project_id=PROJECT_ID).execute( context={} )
TestCloudLoggingCreateSinkOperator
python
dateutil__dateutil
src/dateutil/tz/win.py
{ "start": 3793, "end": 6640 }
class ____(tzrangebase): """tzinfo class based on win32's timezones available in the registry.""" def __init__(self): raise NotImplementedError('tzwinbase is an abstract base class') def __eq__(self, other): # Compare on all relevant dimensions, including name. if not isinstance(other, tzwinbase): return NotImplemented return (self._std_offset == other._std_offset and self._dst_offset == other._dst_offset and self._stddayofweek == other._stddayofweek and self._dstdayofweek == other._dstdayofweek and self._stdweeknumber == other._stdweeknumber and self._dstweeknumber == other._dstweeknumber and self._stdhour == other._stdhour and self._dsthour == other._dsthour and self._stdminute == other._stdminute and self._dstminute == other._dstminute and self._std_abbr == other._std_abbr and self._dst_abbr == other._dst_abbr) @staticmethod def list(): """Return a list of all time zones known to the system.""" with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle: with winreg.OpenKey(handle, TZKEYNAME) as tzkey: result = [winreg.EnumKey(tzkey, i) for i in range(winreg.QueryInfoKey(tzkey)[0])] return result def display(self): """ Return the display name of the time zone. """ return self._display def transitions(self, year): """ For a given year, get the DST on and off transition times, expressed always on the standard time side. For zones with no transitions, this function returns ``None``. :param year: The year whose transitions you would like to query. :return: Returns a :class:`tuple` of :class:`datetime.datetime` objects, ``(dston, dstoff)`` for zones with an annual DST transition, or ``None`` for fixed offset zones. """ if not self.hasdst: return None dston = picknthweekday(year, self._dstmonth, self._dstdayofweek, self._dsthour, self._dstminute, self._dstweeknumber) dstoff = picknthweekday(year, self._stdmonth, self._stddayofweek, self._stdhour, self._stdminute, self._stdweeknumber) # Ambiguous dates default to the STD side dstoff -= self._dst_base_offset return dston, dstoff def _get_hasdst(self): return self._dstmonth != 0 @property def _dst_base_offset(self): return self._dst_base_offset_
tzwinbase
python
davidhalter__jedi
test/completion/django.py
{ "start": 227, "end": 328 }
class ____(models.Manager): def specially_filtered_tags(self): return self.all()
TagManager
python
gevent__gevent
src/gevent/tests/test__example_udp_client.py
{ "start": 154, "end": 884 }
class ____(util.TestServer): start_kwargs = {'timeout': 10} example = 'udp_client.py' example_args = ['Test_udp_client'] def test(self): log = [] def handle(message, address): log.append(message) server.sendto(b'reply-from-server', address) server = DatagramServer('127.0.0.1:9001', handle) server.start() try: self.run_example() finally: server.close() self.assertEqual(log, [b'Test_udp_client']) if __name__ == '__main__': # Running this following test__example_portforwarder on Appveyor # doesn't work in the same process for some reason. main() # pragma: testrunner-no-combine
Test_udp_client
python
airbytehq__airbyte
airbyte-integrations/connectors/source-mixpanel/source_mixpanel/streams.py
{ "start": 1494, "end": 6310 }
class ____(HttpStream, ABC): """ Formatted API Rate Limit (https://help.mixpanel.com/hc/en-us/articles/115004602563-Rate-Limits-for-API-Endpoints): A maximum of 5 concurrent queries 60 queries per hour. """ DEFAULT_REQS_PER_HOUR_LIMIT = 60 @property def state_checkpoint_interval(self) -> int: # to meet the requirement of emitting state at least once per 15 minutes, # we assume there's at least 1 record per request returned. Given that each request is followed by a 60 seconds sleep # we'll have to emit state every 15 records return 15 @property def url_base(self): prefix = "eu." if self.region == "EU" else "" return f"https://{prefix}mixpanel.com/api/query/" @property def reqs_per_hour_limit(self): # https://help.mixpanel.com/hc/en-us/articles/115004602563-Rate-Limits-for-Export-API-Endpoints#api-export-endpoint-rate-limits return self._reqs_per_hour_limit @reqs_per_hour_limit.setter def reqs_per_hour_limit(self, value): self._reqs_per_hour_limit = value def __init__( self, authenticator: AuthBase, region: str, project_timezone: Optional[str] = "US/Pacific", start_date: Optional[Date] = None, end_date: Optional[Date] = None, date_window_size: int = 30, # in days attribution_window: int = 0, # in days export_lookback_window: int = 0, # in seconds select_properties_by_default: bool = True, project_id: int = None, reqs_per_hour_limit: int = DEFAULT_REQS_PER_HOUR_LIMIT, **kwargs, ): self.start_date = start_date self.end_date = end_date self.date_window_size = date_window_size self.attribution_window = attribution_window self.export_lookback_window = export_lookback_window self.additional_properties = select_properties_by_default self.region = region self.project_timezone = project_timezone self.project_id = project_id self._reqs_per_hour_limit = reqs_per_hour_limit super().__init__(authenticator=authenticator) def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]: """Define abstract method""" return None def request_headers( self, stream_state: Mapping[str, Any], stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None ) -> Mapping[str, Any]: return {"Accept": "application/json"} def process_response(self, response: requests.Response, **kwargs) -> Iterable[Mapping]: json_response = response.json() if self.data_field is not None: data = json_response.get(self.data_field, []) elif isinstance(json_response, list): data = json_response elif isinstance(json_response, dict): data = [json_response] for record in data: fix_date_time(record) yield record def parse_response( self, response: requests.Response, stream_state: Mapping[str, Any], **kwargs, ) -> Iterable[Mapping]: # parse the whole response yield from self.process_response(response, stream_state=stream_state, **kwargs) if self.reqs_per_hour_limit > 0: # we skip this block, if self.reqs_per_hour_limit = 0, # in all other cases wait for X seconds to match API limitations self.logger.info(f"Sleep for {3600 / self.reqs_per_hour_limit} seconds to match API limitations after reading from {self.name}") time.sleep(3600 / self.reqs_per_hour_limit) def get_backoff_strategy(self) -> Optional[Union[BackoffStrategy, List[BackoffStrategy]]]: return MixpanelStreamBackoffStrategy(stream=self) def get_error_handler(self) -> Optional[ErrorHandler]: return ExportErrorHandler(logger=self.logger, stream=self) def get_stream_params(self) -> Mapping[str, Any]: """ Fetch required parameters in a given stream. Used to create sub-streams """ params = { "authenticator": self._http_client._session.auth, "region": self.region, "project_timezone": self.project_timezone, "reqs_per_hour_limit": self.reqs_per_hour_limit, } if self.project_id: params["project_id"] = self.project_id return params 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]: if self.project_id: return {"project_id": str(self.project_id)} return {}
MixpanelStream
python
facebook__pyre-check
client/coverage_data.py
{ "start": 1145, "end": 1619 }
class ____(json_mixins.SnakeCaseAndExcludeJsonMixin): start_line: int start_column: int end_line: int end_column: int @staticmethod def from_code_range(code_range: CodeRange) -> Location: return Location( start_line=code_range.start.line, start_column=code_range.start.column, end_line=code_range.end.line, end_column=code_range.end.column, ) @dataclasses.dataclass(frozen=True)
Location
python
walkccc__LeetCode
solutions/1480. Running Sum of 1d Array/1480.py
{ "start": 0, "end": 108 }
class ____: def runningSum(self, nums: list[int]) -> list[int]: return itertools.accumulate(nums)
Solution
python
PyCQA__pylint
tests/functional/m/membership_protocol_py3.py
{ "start": 603, "end": 924 }
class ____(metaclass=MetaContainer): pass def test(): 1 in IterableClass 1 in OldIterableClass 1 in ContainerClass 1 in IterableClass() # [unsupported-membership-test] 1 in OldIterableClass() # [unsupported-membership-test] 1 in ContainerClass() # [unsupported-membership-test]
ContainerClass
python
run-llama__llama_index
llama-index-core/llama_index/core/chat_engine/simple.py
{ "start": 511, "end": 7207 }
class ____(BaseChatEngine): """ Simple Chat Engine. Have a conversation with the LLM. This does not make use of a knowledge base. """ def __init__( self, llm: LLM, memory: BaseMemory, prefix_messages: List[ChatMessage], callback_manager: Optional[CallbackManager] = None, ) -> None: self._llm = llm self._memory = memory self._prefix_messages = prefix_messages self.callback_manager = callback_manager or CallbackManager([]) @classmethod def from_defaults( cls, chat_history: Optional[List[ChatMessage]] = None, memory: Optional[BaseMemory] = None, memory_cls: Type[BaseMemory] = ChatMemoryBuffer, system_prompt: Optional[str] = None, prefix_messages: Optional[List[ChatMessage]] = None, llm: Optional[LLM] = None, **kwargs: Any, ) -> "SimpleChatEngine": """Initialize a SimpleChatEngine from default parameters.""" llm = llm or Settings.llm chat_history = chat_history or [] memory = memory or memory_cls.from_defaults(chat_history=chat_history, llm=llm) if system_prompt is not None: if prefix_messages is not None: raise ValueError( "Cannot specify both system_prompt and prefix_messages" ) prefix_messages = [ ChatMessage(content=system_prompt, role=llm.metadata.system_role) ] prefix_messages = prefix_messages or [] return cls( llm=llm, memory=memory, prefix_messages=prefix_messages, callback_manager=Settings.callback_manager, ) @trace_method("chat") def chat( self, message: str, chat_history: Optional[List[ChatMessage]] = None ) -> AgentChatResponse: if chat_history is not None: self._memory.set(chat_history) self._memory.put(ChatMessage(content=message, role="user")) if hasattr(self._memory, "tokenizer_fn"): initial_token_count = len( self._memory.tokenizer_fn( " ".join( [ (m.content or "") for m in self._prefix_messages if isinstance(m.content, str) ] ) ) ) else: initial_token_count = 0 all_messages = self._prefix_messages + self._memory.get( initial_token_count=initial_token_count ) chat_response = self._llm.chat(all_messages) ai_message = chat_response.message self._memory.put(ai_message) return AgentChatResponse(response=str(chat_response.message.content)) @trace_method("chat") def stream_chat( self, message: str, chat_history: Optional[List[ChatMessage]] = None ) -> StreamingAgentChatResponse: if chat_history is not None: self._memory.set(chat_history) self._memory.put(ChatMessage(content=message, role="user")) if hasattr(self._memory, "tokenizer_fn"): initial_token_count = len( self._memory.tokenizer_fn( " ".join( [ (m.content or "") for m in self._prefix_messages if isinstance(m.content, str) ] ) ) ) else: initial_token_count = 0 all_messages = self._prefix_messages + self._memory.get( initial_token_count=initial_token_count ) chat_response = StreamingAgentChatResponse( chat_stream=self._llm.stream_chat(all_messages) ) thread = Thread( target=chat_response.write_response_to_history, args=(self._memory,) ) thread.start() return chat_response @trace_method("chat") async def achat( self, message: str, chat_history: Optional[List[ChatMessage]] = None ) -> AgentChatResponse: if chat_history is not None: await self._memory.aset(chat_history) await self._memory.aput(ChatMessage(content=message, role="user")) if hasattr(self._memory, "tokenizer_fn"): initial_token_count = len( self._memory.tokenizer_fn( " ".join( [ (m.content or "") for m in self._prefix_messages if isinstance(m.content, str) ] ) ) ) else: initial_token_count = 0 all_messages = self._prefix_messages + ( await self._memory.aget(initial_token_count=initial_token_count) ) chat_response = await self._llm.achat(all_messages) ai_message = chat_response.message await self._memory.aput(ai_message) return AgentChatResponse(response=str(chat_response.message.content)) @trace_method("chat") async def astream_chat( self, message: str, chat_history: Optional[List[ChatMessage]] = None ) -> StreamingAgentChatResponse: if chat_history is not None: await self._memory.aset(chat_history) await self._memory.aput(ChatMessage(content=message, role="user")) if hasattr(self._memory, "tokenizer_fn"): initial_token_count = len( self._memory.tokenizer_fn( " ".join( [ (m.content or "") for m in self._prefix_messages if isinstance(m.content, str) ] ) ) ) else: initial_token_count = 0 all_messages = self._prefix_messages + ( await self._memory.aget(initial_token_count=initial_token_count) ) chat_response = StreamingAgentChatResponse( achat_stream=await self._llm.astream_chat(all_messages) ) chat_response.awrite_response_to_history_task = asyncio.create_task( chat_response.awrite_response_to_history(self._memory) ) return chat_response def reset(self) -> None: self._memory.reset() @property def chat_history(self) -> List[ChatMessage]: """Get chat history.""" return self._memory.get_all()
SimpleChatEngine
python
mitmproxy__pdoc
test/testdata/misc_py310.py
{ "start": 140, "end": 267 }
class ____: pass NewStyleDict = dict[str, str] """New-style dict.""" OldStyleDict = Dict[str, str] """Old-style dict."""
Foo
python
spack__spack
var/spack/test_repos/spack_repo/flags_test/packages/u/package.py
{ "start": 216, "end": 326 }
class ____(Package): version("6.0") depends_on("y cflags='-e1 -e2'") depends_on("c", type="build")
U
python
pytorch__pytorch
.github/scripts/test_gitutils.py
{ "start": 1002, "end": 1464 }
class ____(TestCase): def test_double_asterisks(self) -> None: allowed_patterns = [ "aten/src/ATen/native/**LinearAlgebra*", ] patterns_re = patterns_to_regex(allowed_patterns) fnames = [ "aten/src/ATen/native/LinearAlgebra.cpp", "aten/src/ATen/native/cpu/LinearAlgebraKernel.cpp", ] for filename in fnames: self.assertTrue(patterns_re.match(filename))
TestPattern
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 53857, "end": 53957 }
class ____(BaseModel): models: Dict[str, "ModelUsage"] = Field(..., description="")
InferenceUsage
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/layer_fix.py
{ "start": 171, "end": 345 }
class ____(Vertical): def compose(self) -> ComposeResult: """Compose the child widgets.""" yield Label("This should not cause a scrollbar to appear")
Dialog
python
Lightning-AI__lightning
tests/tests_pytorch/helpers/datamodules.py
{ "start": 898, "end": 1925 }
class ____(LightningDataModule): def __init__(self, data_dir: str = "./", batch_size: int = 32, use_trials: bool = False) -> None: super().__init__() self.data_dir = data_dir self.batch_size = batch_size # TrialMNIST is a constrained MNIST dataset self.dataset_cls = TrialMNIST if use_trials else MNIST def prepare_data(self): # download only self.dataset_cls(self.data_dir, train=True, download=True) self.dataset_cls(self.data_dir, train=False, download=True) def setup(self, stage: str): if stage == "fit": self.mnist_train = self.dataset_cls(self.data_dir, train=True) if stage == "test": self.mnist_test = self.dataset_cls(self.data_dir, train=False) def train_dataloader(self): return DataLoader(self.mnist_train, batch_size=self.batch_size, shuffle=False) def test_dataloader(self): return DataLoader(self.mnist_test, batch_size=self.batch_size, shuffle=False)
MNISTDataModule
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/util/queue.py
{ "start": 1381, "end": 2124 }
class ____(Generic[_T]): maxsize: int use_lifo: bool def __init__(self, maxsize: int = 0, use_lifo: bool = False): ... def empty(self) -> bool: raise NotImplementedError() def full(self) -> bool: raise NotImplementedError() def qsize(self) -> int: raise NotImplementedError() def put_nowait(self, item: _T) -> None: raise NotImplementedError() def put( self, item: _T, block: bool = True, timeout: Optional[float] = None ) -> None: raise NotImplementedError() def get_nowait(self) -> _T: raise NotImplementedError() def get(self, block: bool = True, timeout: Optional[float] = None) -> _T: raise NotImplementedError()
QueueCommon
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1521553, "end": 1522797 }
class ____(Transform): """ LookupTransform schema wrapper. Parameters ---------- lookup : str Key in primary data source. default : Any The default value to use if lookup fails. **Default value:** ``null`` as : str, :class:`FieldName`, Sequence[str, :class:`FieldName`] The output fields on which to store the looked up data values. For data lookups, this property may be left blank if ``from.fields`` has been specified (those field names will be used); if ``from.fields`` has not been specified, ``as`` must be a string. For selection lookups, this property is optional: if unspecified, looked up values will be stored under a property named for the selection; and if specified, it must correspond to ``from.fields``. from : dict, :class:`LookupData`, :class:`LookupSelection` Data source or selection for secondary data reference. """ _schema = {"$ref": "#/definitions/LookupTransform"} def __init__( self, lookup: Optional[str] = Undefined, default: Optional[Any] = Undefined, **kwds, ): super().__init__(lookup=lookup, default=default, **kwds)
LookupTransform
python
doocs__leetcode
solution/1800-1899/1884.Egg Drop With 2 Eggs and N Floors/Solution.py
{ "start": 0, "end": 236 }
class ____: def twoEggDrop(self, n: int) -> int: f = [0] + [inf] * n for i in range(1, n + 1): for j in range(1, i + 1): f[i] = min(f[i], 1 + max(j - 1, f[i - j])) return f[n]
Solution
python
pyqtgraph__pyqtgraph
pyqtgraph/examples/optics/pyoptic.py
{ "start": 2810, "end": 3787 }
class ____(object): # Just a helper for tracking parameters and responding to changes def __init__(self): self.__params = {} def __setitem__(self, item, val): self.setParam(item, val) def setParam(self, param, val): self.setParams(**{param:val}) def setParams(self, **params): """Set parameters for this optic. This is a good function to override for subclasses.""" self.__params.update(params) self.paramStateChanged() def paramStateChanged(self): pass def __getitem__(self, item): # bug in pyside 1.2.2 causes getitem to be called inside QGraphicsObject.parentItem: return self.getParam(item) # PySide bug: https://bugreports.qt.io/browse/PYSIDE-671 def __len__(self): # Workaround for PySide bug: https://bugreports.qt.io/browse/PYSIDE-671 return 0 def getParam(self, param): return self.__params[param]
ParamObj
python
tensorflow__tensorflow
tensorflow/python/framework/errors_impl.py
{ "start": 10527, "end": 10964 }
class ____(OpError): """Raised when a deadline expires before an operation could complete. This exception is not currently used. """ def __init__(self, node_def, op, message, *args): """Creates a `DeadlineExceededError`.""" super(DeadlineExceededError, self).__init__(node_def, op, message, DEADLINE_EXCEEDED, *args) @tf_export("errors.NotFoundError")
DeadlineExceededError
python
tensorflow__tensorflow
tensorflow/python/distribute/experimental/dtensor_strategy_extended.py
{ "start": 1404, "end": 11727 }
class ____(distribute_lib.StrategyExtendedV2): """Strategy extension that support both single and multi worker strategy.""" # Note that the unit test for this class is via the strategy interface. def __init__(self, container_strategy, mesh): super().__init__(container_strategy) self._mesh = mesh self._num_clients = d_config.num_clients() self._client_id = d_config.client_id() def _create_variable(self, next_creator, **kwargs): # Make sure the pop the `use_resource` which is not supported by the # base tf.Variable. The `use_resource` is added by # creator_with_resource_vars in distribute_lib.py kwargs.pop('use_resource', None) # Ignore the colocate_with for the mirrored strategy. Each of the device # will get same copy of variable in the DTensor's case. # `colocate_with` is added when user call: # strategy.extended.colocate_vars_with(variable) kwargs.pop('colocate_with', None) # Ignore expected_shape, which is from the v1 Variable. Keras was somehow # using the v1 Variable, but didn't specify that value particularly. kwargs.pop('expected_shape', None) # Make sure to call DVariable initializer under the scope so that it will # have the proper replicated layout. The initial_value is multi-typed, # eg it can be a tensor, or a python/numpy type, or a callable that # produce tensor/python/numpy types. In all those cases, we need to wrap # them invoke convert_to_tensor() under the scope so that the proper # layout can be assigned. # TODO(scottzhu): The layout information should be injected via kwargs, or # lazily set later. initial_value = kwargs.pop('initial_value') dtype = kwargs.get('dtype', None) def new_initial_value(): if callable(initial_value): init_var = ops.convert_to_tensor(initial_value(), dtype=dtype) else: init_var = ops.convert_to_tensor(initial_value, dtype=dtype) rank = init_var.shape.rank return d_api.copy_to_mesh( init_var, layout.Layout.replicated(self._mesh, rank)) return d_variable.DVariable(new_initial_value, **kwargs) @property def _num_replicas_in_sync(self): # The mesh should be 1D with batch sharding only. # In the model parallel case, it should only return the size of # batch dimension. return self._mesh.size def value_container(self, value): return value @property def worker_devices(self): # Note that in either single worker (MirroredStrategy) or multi worker ( # MultiWorkerMirroredStrategy), worker_devices refers to the local worker # devices. return tuple(self._mesh.local_devices()) @property def parameter_devices(self): # Same as the worker_devices. return self.worker_devices def _in_multi_worker_mode(self): return d_config.num_clients() > 1 def _get_local_replica_id(self, replica_id_in_sync_group): return replica_id_in_sync_group def _default_device_scope(self): return d_api.default_mesh(self._mesh) def _experimental_distribute_dataset(self, dataset, options): # Strategy always assume the user input data is a batched dataset for # experimental_distribute_dataset(). # TODO(yuefengz): Add check for whether a dataset is batched for all # strategies. # TODO(b/265198795): Support dataset already batched to global batch size. # Since DTensorDataset doesn't support batched dataset that is already # batched global batch size, it only supports dataset that is batched to # local batch size, we need to infer the batch size, and unbatch the dataset # until the b/265198795 is resolved. batch_size = distribute.compute_batch_size(dataset) # There are multiple case that the batch is not static, eg partial batch, # or uneven batch, in all those case, it will return -1. if batch_size.numpy() < 0: # When we don't have a static batch size. raise ValueError('DTensor strategy requires a static batch size for now.' 'The dynamic batch size will be supported in future') # Unbatch the dataset for now since the DTensorDataset has some limitation # about the local batch size as well as the mesh size. dataset = dataset.unbatch() def _create_batch_layout(tensor_spec): # For unbatched dataset, the new layout need to have +1 rank for # the batched result. rank = len(tensor_spec.shape) + 1 return layout.Layout.batch_sharded( self._mesh, batch_dim=dtensor_util.DEFAULT_BATCH_MESH_DIM_NAME, rank=rank) layouts = nest.map_structure(_create_batch_layout, dataset.element_spec) return input_util.DTensorDataset( dataset=dataset, mesh=self._mesh, layouts=layouts, global_batch_size=batch_size, dataset_already_batched=False, batch_dim=dtensor_util.DEFAULT_BATCH_MESH_DIM_NAME, # TODO(scottzhu): Add prefetch support by inspecting the input dataset. prefetch=None, tf_data_service_config=None ) def _make_dataset_iterator(self, dataset): raise NotImplementedError( 'Strategy.make_dataset_iterator() is deprecated, and only available ' 'in the V1 API.') def _make_input_fn_iterator(self, input_fn, replication_mode): raise NotImplementedError( 'Strategy.make_input_fn_iterator() is deprecated, and only available ' 'in the V1 API.') def _distribute_datasets_from_function(self, dataset_fn, options): # TODO(scottzhu): Implement the logic for options in future del options input_context = distribute_lib.InputContext( num_input_pipelines=self._num_clients, input_pipeline_id=self._client_id, num_replicas_in_sync=self._num_replicas_in_sync ) dataset = dataset_fn(input_context) # Note that the dataset should already batched to local per-relica batch def _create_batch_layout(tensor_spec): rank = len(tensor_spec.shape) return layout.Layout.batch_sharded( self._mesh, batch_dim=dtensor_util.DEFAULT_BATCH_MESH_DIM_NAME, rank=rank) layouts = nest.map_structure(_create_batch_layout, dataset.element_spec) batch_size = distribute.compute_batch_size(dataset) # There are multiple case that the batch is not static, eg partial batch, # or uneven batch, in all those case, it will return -1. if batch_size.numpy() < 0: # When we don't have a static batch size. raise ValueError('DTensor strategy requires a static batch size for now.' 'The dynamic batch size will be supported in future') global_batch_size = batch_size.numpy() * self._num_replicas_in_sync return input_util.DTensorDataset( dataset=dataset, mesh=self._mesh, layouts=layouts, global_batch_size=global_batch_size, dataset_already_batched=True, batch_dim=dtensor_util.DEFAULT_BATCH_MESH_DIM_NAME, # TODO(scottzhu): Add prefetch support by inspecting the input dataset. prefetch=None, tf_data_service_config=None ) def _experimental_distribute_values_from_function(self, value_fn): per_replica_values = [] # Note that in the multi-worker setting, this function only return the # slide of DistributedValue for the current worker. for i in range(self._mesh.num_local_devices()): # In the case of 2 worker with 2 local devices on each worker, # worker 0 will get 0 and 1 for replica_id. # worker 1 will get 2 and 3 for replica_id. replica_id = d_config.client_id() * self._mesh.num_local_devices() + i per_replica_values.append(value_fn( distribute_lib.ValueContext(replica_id, self._num_replicas_in_sync))) # Instead of using the DistributeVariable, return a DTensor instead since # the run() will expect a DTensor instance. result = distribute_utils.regroup(per_replica_values, always_wrap=True) map_fn = functools.partial(dtensor_util.convert_per_replica_to_dtensor, mesh=self._mesh) return nest.map_structure(map_fn, result) def call_for_each_replica(self, fn, args=(), kwargs=None): """Run `fn` once per replica. This is a method that expected by the strategy base class in its `run()`. Args: fn: function to run (will be run once per replica). args: Tuple or list with positional arguments for `fn`. kwargs: Dict with keyword arguments for `fn`. Returns: Merged return value of `fn` across all replicas. """ # Comparing to the existing MirroredStrategy, which will run the fn on # each of the replica with individual thread, the DTensor will just run # the fn once with the DTensor inputs, and the distribution will be handled # by the DTensor. distribute_lib._require_cross_replica_or_default_context_extended(self) # pylint: disable=protected-access if kwargs is None: kwargs = {} # For any value that is not DTensor, eg normal tf.Tensor or # DistributedValues, we need to convert them into DTensor. map_fn = functools.partial(dtensor_util.convert_inputs_to_dtensor, mesh=self._mesh) d_args = nest.map_structure(map_fn, args) d_kwargs = nest.map_structure(map_fn, kwargs) with self._container_strategy().scope(): with dtensor_util.DTensorReplicaContext(self._container_strategy()): dtensor_result = fn(*d_args, **d_kwargs) return nest.map_structure( dtensor_util.DTensorDistributedValue, dtensor_result) def _gather_to_implementation(self, value, destinations, axis, options): if isinstance(value, dtensor_util.DTensorDistributedValue): value = value.get_dtensor() if not d_api.is_dtensor(value): # This is the current behavior for mirrored strategy, should we raise an # error for unsupported types? return value # Unpack the dtensor components and gather the tensors on the axis components = d_api.unpack(value) return array_ops.concat(components, axis=axis) def _use_merge_call(self): # This is method for V1 StrategyExtended by still used by # tf.__internal__.distribute.strategy_supports_no_merge_call return False
DTensorStrategyExtended
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_eventbridge.py
{ "start": 7476, "end": 9015 }
class ____: def test_init(self): op = EventBridgeDisableRuleOperator( task_id="disable_rule_task", name=RULE_NAME, aws_conn_id="fake-conn-id", region_name="ca-west-1", verify=True, botocore_config={"read_timeout": 42}, ) assert op.name == RULE_NAME assert op.hook.client_type == "events" assert op.hook.resource_type is None assert op.hook.aws_conn_id == "fake-conn-id" assert op.hook._region_name == "ca-west-1" assert op.hook._verify is True assert op.hook._config is not None assert op.hook._config.read_timeout == 42 op = EventBridgeDisableRuleOperator(task_id="disable_rule_task", name=RULE_NAME) assert op.hook.aws_conn_id == "aws_default" assert op.hook._region_name is None assert op.hook._verify is None assert op.hook._config is None @mock.patch.object(EventBridgeHook, "conn") def test_disable_rule(self, mock_conn: MagicMock): disable_rule = EventBridgeDisableRuleOperator( task_id="events_disable_rule_job", name=RULE_NAME, ) disable_rule.execute(context={}) mock_conn.disable_rule.assert_called_with(Name=RULE_NAME) def test_template_fields(self): operator = EventBridgeDisableRuleOperator( task_id="events_disable_rule_job", name=RULE_NAME, ) validate_template_fields(operator)
TestEventBridgeDisableRuleOperator
python
getsentry__sentry
src/sentry/integrations/source_code_management/repo_trees.py
{ "start": 1019, "end": 8973 }
class ____(ABC): """ Base class for integrations that can get trees for an organization's repositories. It is used for finding files in repositories and deriving code mappings. """ CACHE_SECONDS = 3600 * 24 # This method must be implemented @abstractmethod def get_client(self) -> RepoTreesClient: """Returns the client for the integration. The client must be a subclass of RepositoryClient.""" raise NotImplementedError @abstractmethod def get_repositories(self, query: str | None = None) -> list[dict[str, Any]]: raise NotImplementedError @property def org_integration(self) -> RpcOrganizationIntegration | None: raise NotImplementedError @property def integration_name(self) -> str: raise NotImplementedError def get_trees_for_org(self) -> dict[str, RepoTree]: trees = {} with metrics.timer(f"{METRICS_KEY_PREFIX}.populate_repositories.duration"): repositories = self._populate_repositories() if not repositories: logger.warning("Fetching repositories returned an empty list.") else: with metrics.timer(f"{METRICS_KEY_PREFIX}.populate_trees.duration"): trees = self._populate_trees(repositories) return trees def _populate_repositories(self) -> list[dict[str, str]]: if not self.org_integration: raise IntegrationError("Organization Integration does not exist") cache_key = ( f"{self.integration_name}trees:repositories:{self.org_integration.organization_id}" ) repositories: list[dict[str, str]] = cache.get(cache_key, []) use_cache = True if not repositories: use_cache = False repositories = [ # Do not use RepoAndBranch so it stores in the cache as a simple dict { "full_name": repo_info["identifier"], "default_branch": repo_info["default_branch"], } for repo_info in self.get_repositories() if not repo_info.get("archived") ] metrics.incr( f"{METRICS_KEY_PREFIX}.populate_repositories", tags={"cached": use_cache, "integration": self.integration_name}, ) if repositories: cache.set(cache_key, repositories, self.CACHE_SECONDS) return repositories def _populate_trees(self, repositories: Sequence[dict[str, str]]) -> dict[str, RepoTree]: """ For every repository, fetch the tree associated and cache it. This function takes API rate limits into consideration to prevent exhaustion. """ trees: dict[str, RepoTree] = {} use_cache = False connection_error_count = 0 remaining_requests = MINIMUM_REQUESTS_REMAINING try: remaining_requests = self.get_client().get_remaining_api_requests() except Exception: use_cache = True # Report so we can investigate logger.warning( "Loading trees from cache. Execution will continue. Check logs.", exc_info=True ) metrics.incr( f"{METRICS_KEY_PREFIX}.populate_trees", tags={"cached": use_cache, "integration": self.integration_name}, ) for index, repo_info in enumerate(repositories): repo_full_name = repo_info["full_name"] extra = {"repo_full_name": repo_full_name} # Only use the cache if we drop below the lower ceiling # We will fetch after the limit is reset (every hour) if not use_cache and remaining_requests <= MINIMUM_REQUESTS_REMAINING: use_cache = True else: remaining_requests -= 1 try: # The API rate limit is reset every hour # Spread the expiration of the cache of each repo across the day trees[repo_full_name] = self._populate_tree( RepoAndBranch(repo_full_name, repo_info["default_branch"]), use_cache, 3600 * (index % 24), ) except ApiError as error: if self.get_client().should_count_api_error(error, extra): connection_error_count += 1 except Exception: # Report for investigation but do not stop processing logger.exception( "Failed to populate_tree. Investigate. Contining execution.", extra=extra ) # This is a rudimentary circuit breaker if connection_error_count >= MAX_CONNECTION_ERRORS: logger.warning( "Falling back to the cache because we've hit too many error connections.", extra=extra, ) use_cache = True return trees def _populate_tree( self, repo_and_branch: RepoAndBranch, only_use_cache: bool, shifted_seconds: int ) -> RepoTree: full_name = repo_and_branch.name branch = repo_and_branch.branch repo_files = self.get_cached_repo_files( full_name, branch, shifted_seconds, only_use_cache=only_use_cache ) return RepoTree(repo_and_branch, repo_files) def get_cached_repo_files( self, repo_full_name: str, tree_sha: str, shifted_seconds: int, only_source_code_files: bool = True, only_use_cache: bool = False, ) -> list[str]: """It returns all files for a repo or just source code files. repo_full_name: e.g. getsentry/sentry tree_sha: A branch or a commit sha only_source_code_files: Include all files or just the source code files only_use_cache: Do not hit the network but use the value from the cache if any. This is useful if the remaining API requests are low """ key = f"{self.integration_name}:repo:{repo_full_name}:{'source-code' if only_source_code_files else 'all'}" cache_hit = cache.has_key(key) use_api = not cache_hit and not only_use_cache repo_files: list[str] = cache.get(key, []) if use_api: # Cache miss – fetch from API tree = self.get_client().get_tree(repo_full_name, tree_sha) if tree: # Keep files; discard directories repo_files = [node["path"] for node in tree if node["type"] == "blob"] if only_source_code_files: repo_files = filter_source_code_files(files=repo_files) # The backend's caching will skip silently if the object size greater than 5MB # (due to Memcached's max value size limit). # The trees API does not return structures larger than 7MB # As an example, all file paths in Sentry is about 1.3MB # Larger customers may have larger repositories, however, # the cost of not having the files cached # repositories is a single API network request, thus, # being acceptable to sometimes not having everything cached cache.set(key, repo_files, self.CACHE_SECONDS + shifted_seconds) metrics.incr( f"{METRICS_KEY_PREFIX}.get_tree", tags={"fetched": tree is not None, "integration": self.integration_name}, ) metrics.incr( f"{METRICS_KEY_PREFIX}.get_repo_files", tags={ "cached": not use_api, "only_source_code_files": only_source_code_files, "integration": self.integration_name, }, ) return repo_files # These are methods that the client for the integration must implement
RepoTreesIntegration
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/deprecated6.py
{ "start": 215, "end": 416 }
class ____: @deprecated("Use ClassB instead") def __call__(self) -> None: ... a = A() # This should generate an error if reportDeprecated is enabled. a() P = ParamSpec("P") R = TypeVar("R")
A
python
huggingface__transformers
tests/models/hubert/test_modeling_hubert.py
{ "start": 1401, "end": 11516 }
class ____: def __init__( self, parent, batch_size=13, seq_length=1024, # speech is longer is_training=False, hidden_size=16, feat_extract_norm="group", feat_extract_dropout=0.0, feat_extract_activation="gelu", conv_dim=(32, 32, 32), conv_stride=(4, 4, 4), conv_kernel=(8, 8, 8), conv_bias=False, num_conv_pos_embeddings=16, num_conv_pos_embedding_groups=2, num_hidden_layers=2, num_attention_heads=2, hidden_dropout_prob=0.1, # this is most likely not correctly set yet intermediate_size=20, layer_norm_eps=1e-5, hidden_act="gelu", initializer_range=0.02, vocab_size=32, do_stable_layer_norm=False, scope=None, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.hidden_size = hidden_size self.feat_extract_norm = feat_extract_norm self.feat_extract_dropout = feat_extract_dropout self.feat_extract_activation = feat_extract_activation self.conv_dim = conv_dim self.conv_stride = conv_stride self.conv_kernel = conv_kernel self.conv_bias = conv_bias self.num_conv_pos_embeddings = num_conv_pos_embeddings self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.hidden_dropout_prob = hidden_dropout_prob self.intermediate_size = intermediate_size self.layer_norm_eps = layer_norm_eps self.hidden_act = hidden_act self.initializer_range = initializer_range self.vocab_size = vocab_size self.do_stable_layer_norm = do_stable_layer_norm self.scope = scope output_seq_length = self.seq_length for kernel, stride in zip(self.conv_kernel, self.conv_stride): output_seq_length = (output_seq_length - (kernel - 1)) / stride self.output_seq_length = int(math.ceil(output_seq_length)) self.encoder_seq_length = self.output_seq_length def prepare_config_and_inputs(self): input_values = floats_tensor([self.batch_size, self.seq_length], scale=1.0) attention_mask = random_attention_mask([self.batch_size, self.seq_length]) config = self.get_config() return config, input_values, attention_mask def get_config(self): return HubertConfig( hidden_size=self.hidden_size, feat_extract_norm=self.feat_extract_norm, feat_extract_dropout=self.feat_extract_dropout, feat_extract_activation=self.feat_extract_activation, conv_dim=self.conv_dim, conv_stride=self.conv_stride, conv_kernel=self.conv_kernel, conv_bias=self.conv_bias, num_conv_pos_embeddings=self.num_conv_pos_embeddings, num_conv_pos_embedding_groups=self.num_conv_pos_embedding_groups, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, hidden_dropout_prob=self.hidden_dropout_prob, intermediate_size=self.intermediate_size, layer_norm_eps=self.layer_norm_eps, hidden_act=self.hidden_act, initializer_range=self.initializer_range, vocab_size=self.vocab_size, do_stable_layer_norm=self.do_stable_layer_norm, ) def create_and_check_model(self, config, input_values, attention_mask): model = HubertModel(config=config) model.to(torch_device) model.eval() result = model(input_values, attention_mask=attention_mask) self.parent.assertEqual( result.last_hidden_state.shape, (self.batch_size, self.output_seq_length, self.hidden_size) ) def create_and_check_batch_inference(self, config, input_values, *args): # test does not pass for models making use of `group_norm` # check: https://github.com/pytorch/fairseq/issues/3227 model = HubertModel(config=config) model.to(torch_device) model.eval() input_values = input_values[:3] attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.bool) input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] # pad input for i in range(len(input_lengths)): input_values[i, input_lengths[i] :] = 0.0 attention_mask[i, input_lengths[i] :] = 0.0 batch_outputs = model(input_values, attention_mask=attention_mask).last_hidden_state for i in range(input_values.shape[0]): input_slice = input_values[i : i + 1, : input_lengths[i]] output = model(input_slice).last_hidden_state batch_output = batch_outputs[i : i + 1, : output.shape[1]] self.parent.assertTrue(torch.allclose(output, batch_output, atol=1e-3)) def check_ctc_loss(self, config, input_values, *args): model = HubertForCTC(config=config) model.to(torch_device) # make sure that dropout is disabled model.eval() input_values = input_values[:3] attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long) input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) labels = ids_tensor((input_values.shape[0], min(max_length_labels) - 1), model.config.vocab_size) # pad input for i in range(len(input_lengths)): input_values[i, input_lengths[i] :] = 0.0 attention_mask[i, input_lengths[i] :] = 0 model.config.ctc_loss_reduction = "sum" sum_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() model.config.ctc_loss_reduction = "mean" mean_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() self.parent.assertTrue(isinstance(sum_loss, float)) self.parent.assertTrue(isinstance(mean_loss, float)) def check_seq_classifier_loss(self, config, input_values, *args): model = HubertForSequenceClassification(config=config) model.to(torch_device) # make sure that dropout is disabled model.eval() input_values = input_values[:3] attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long) input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label)) # pad input for i in range(len(input_lengths)): input_values[i, input_lengths[i] :] = 0.0 attention_mask[i, input_lengths[i] :] = 0 masked_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() unmasked_loss = model(input_values, labels=labels).loss.item() self.parent.assertTrue(isinstance(masked_loss, float)) self.parent.assertTrue(isinstance(unmasked_loss, float)) self.parent.assertTrue(masked_loss != unmasked_loss) def check_ctc_training(self, config, input_values, *args): config.ctc_zero_infinity = True model = HubertForCTC(config=config) model.to(torch_device) model.train() # freeze feature encoder model.freeze_feature_encoder() input_values = input_values[:3] input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size) # pad input for i in range(len(input_lengths)): input_values[i, input_lengths[i] :] = 0.0 if max_length_labels[i] < labels.shape[-1]: # it's important that we make sure that target lengths are at least # one shorter than logit lengths to prevent -inf labels[i, max_length_labels[i] - 1 :] = -100 loss = model(input_values, labels=labels).loss self.parent.assertFalse(torch.isinf(loss).item()) loss.backward() def check_seq_classifier_training(self, config, input_values, *args): config.ctc_zero_infinity = True model = HubertForSequenceClassification(config=config) model.to(torch_device) model.train() # freeze everything but the classification head model.freeze_base_model() input_values = input_values[:3] input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label)) # pad input for i in range(len(input_lengths)): input_values[i, input_lengths[i] :] = 0.0 loss = model(input_values, labels=labels).loss self.parent.assertFalse(torch.isinf(loss).item()) loss.backward() def check_labels_out_of_vocab(self, config, input_values, *args): model = HubertForCTC(config) model.to(torch_device) model.train() input_values = input_values[:3] input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size + 100) with pytest.raises(ValueError): model(input_values, labels=labels) def prepare_config_and_inputs_for_common(self): config, input_values, attention_mask = self.prepare_config_and_inputs() inputs_dict = {"input_values": input_values, "attention_mask": attention_mask} return config, inputs_dict @require_torch
HubertModelTester
python
getsentry__sentry
src/sentry/core/endpoints/scim/teams.py
{ "start": 4585, "end": 4750 }
class ____(SCIMListBaseResponse): Resources: list[OrganizationTeamSCIMSerializerResponse] @extend_schema(tags=["SCIM"]) @region_silo_endpoint
SCIMListTeamsResponse
python
aimacode__aima-python
learning.py
{ "start": 33988, "end": 45678 }
class ____: def __init__(self, clf, decision_function='ovr'): self.clf = clf self.decision_function = decision_function self.n_class, self.classifiers = 0, [] def fit(self, X, y): """ Trains n_class or n_class * (n_class - 1) / 2 classifiers according to the training method, ovr or ovo respectively. :param X: array of size [n_samples, n_features] holding the training samples :param y: array of size [n_samples] holding the class labels :return: array of classifiers """ labels = np.unique(y) self.n_class = len(labels) if self.decision_function == 'ovr': # one-vs-rest method for label in labels: y1 = np.array(y) y1[y1 != label] = -1.0 y1[y1 == label] = 1.0 self.clf.fit(X, y1) self.classifiers.append(copy.deepcopy(self.clf)) elif self.decision_function == 'ovo': # use one-vs-one method n_labels = len(labels) for i in range(n_labels): for j in range(i + 1, n_labels): neg_id, pos_id = y == labels[i], y == labels[j] X1, y1 = np.r_[X[neg_id], X[pos_id]], np.r_[y[neg_id], y[pos_id]] y1[y1 == labels[i]] = -1.0 y1[y1 == labels[j]] = 1.0 self.clf.fit(X1, y1) self.classifiers.append(copy.deepcopy(self.clf)) else: return ValueError("Decision function must be either 'ovr' or 'ovo'.") return self def predict(self, X): """ Predicts the class of a given example according to the training method. """ n_samples = len(X) if self.decision_function == 'ovr': # one-vs-rest method assert len(self.classifiers) == self.n_class score = np.zeros((n_samples, self.n_class)) for i in range(self.n_class): clf = self.classifiers[i] score[:, i] = clf.predict_score(X) return np.argmax(score, axis=1) elif self.decision_function == 'ovo': # use one-vs-one method assert len(self.classifiers) == self.n_class * (self.n_class - 1) / 2 vote = np.zeros((n_samples, self.n_class)) clf_id = 0 for i in range(self.n_class): for j in range(i + 1, self.n_class): res = self.classifiers[clf_id].predict(X) vote[res < 0, i] += 1.0 # negative sample: class i vote[res > 0, j] += 1.0 # positive sample: class j clf_id += 1 return np.argmax(vote, axis=1) else: return ValueError("Decision function must be either 'ovr' or 'ovo'.") def EnsembleLearner(learners): """Given a list of learning algorithms, have them vote.""" def train(dataset): predictors = [learner(dataset) for learner in learners] def predict(example): return mode(predictor(example) for predictor in predictors) return predict return train def ada_boost(dataset, L, K): """[Figure 18.34]""" examples, target = dataset.examples, dataset.target n = len(examples) eps = 1 / (2 * n) w = [1 / n] * n h, z = [], [] for k in range(K): h_k = L(dataset, w) h.append(h_k) error = sum(weight for example, weight in zip(examples, w) if example[target] != h_k(example)) # avoid divide-by-0 from either 0% or 100% error rates error = np.clip(error, eps, 1 - eps) for j, example in enumerate(examples): if example[target] == h_k(example): w[j] *= error / (1 - error) w = normalize(w) z.append(np.log((1 - error) / error)) return weighted_majority(h, z) def weighted_majority(predictors, weights): """Return a predictor that takes a weighted vote.""" def predict(example): return weighted_mode((predictor(example) for predictor in predictors), weights) return predict def weighted_mode(values, weights): """ Return the value with the greatest total weight. >>> weighted_mode('abbaa', [1, 2, 3, 1, 2]) 'b' """ totals = defaultdict(int) for v, w in zip(values, weights): totals[v] += w return max(totals, key=totals.__getitem__) def RandomForest(dataset, n=5): """An ensemble of Decision Trees trained using bagging and feature bagging.""" def data_bagging(dataset, m=0): """Sample m examples with replacement""" n = len(dataset.examples) return weighted_sample_with_replacement(m or n, dataset.examples, [1] * n) def feature_bagging(dataset, p=0.7): """Feature bagging with probability p to retain an attribute""" inputs = [i for i in dataset.inputs if probability(p)] return inputs or dataset.inputs def predict(example): print([predictor(example) for predictor in predictors]) return mode(predictor(example) for predictor in predictors) predictors = [DecisionTreeLearner(DataSet(examples=data_bagging(dataset), attrs=dataset.attrs, attr_names=dataset.attr_names, target=dataset.target, inputs=feature_bagging(dataset))) for _ in range(n)] return predict def WeightedLearner(unweighted_learner): """ [Page 749 footnote 14] Given a learner that takes just an unweighted dataset, return one that takes also a weight for each example. """ def train(dataset, weights): return unweighted_learner(replicated_dataset(dataset, weights)) return train def replicated_dataset(dataset, weights, n=None): """Copy dataset, replicating each example in proportion to its weight.""" n = n or len(dataset.examples) result = copy.copy(dataset) result.examples = weighted_replicate(dataset.examples, weights, n) return result def weighted_replicate(seq, weights, n): """ Return n selections from seq, with the count of each element of seq proportional to the corresponding weight (filling in fractions randomly). >>> weighted_replicate('ABC', [1, 2, 1], 4) ['A', 'B', 'B', 'C'] """ assert len(seq) == len(weights) weights = normalize(weights) wholes = [int(w * n) for w in weights] fractions = [(w * n) % 1 for w in weights] return (flatten([x] * nx for x, nx in zip(seq, wholes)) + weighted_sample_with_replacement(n - sum(wholes), seq, fractions)) # metrics def accuracy_score(y_pred, y_true): assert y_pred.shape == y_true.shape return np.mean(np.equal(y_pred, y_true)) def r2_score(y_pred, y_true): assert y_pred.shape == y_true.shape return 1. - (np.sum(np.square(y_pred - y_true)) / # sum of square of residuals np.sum(np.square(y_true - np.mean(y_true)))) # total sum of squares # datasets orings = DataSet(name='orings', target='Distressed', attr_names='Rings Distressed Temp Pressure Flightnum') zoo = DataSet(name='zoo', target='type', exclude=['name'], attr_names='name hair feathers eggs milk airborne aquatic predator toothed backbone ' 'breathes venomous fins legs tail domestic catsize type') iris = DataSet(name='iris', target='class', attr_names='sepal-len sepal-width petal-len petal-width class') def RestaurantDataSet(examples=None): """ [Figure 18.3] Build a DataSet of Restaurant waiting examples. """ return DataSet(name='restaurant', target='Wait', examples=examples, attr_names='Alternate Bar Fri/Sat Hungry Patrons Price Raining Reservation Type WaitEstimate Wait') restaurant = RestaurantDataSet() def T(attr_name, branches): branches = {value: (child if isinstance(child, DecisionFork) else DecisionLeaf(child)) for value, child in branches.items()} return DecisionFork(restaurant.attr_num(attr_name), attr_name, print, branches) """ [Figure 18.2] A decision tree for deciding whether to wait for a table at a hotel. """ waiting_decision_tree = T('Patrons', {'None': 'No', 'Some': 'Yes', 'Full': T('WaitEstimate', {'>60': 'No', '0-10': 'Yes', '30-60': T('Alternate', {'No': T('Reservation', {'Yes': 'Yes', 'No': T('Bar', {'No': 'No', 'Yes': 'Yes'})}), 'Yes': T('Fri/Sat', {'No': 'No', 'Yes': 'Yes'})}), '10-30': T('Hungry', {'No': 'Yes', 'Yes': T('Alternate', {'No': 'Yes', 'Yes': T('Raining', {'No': 'No', 'Yes': 'Yes'})})})})}) def SyntheticRestaurant(n=20): """Generate a DataSet with n examples.""" def gen(): example = list(map(random.choice, restaurant.values)) example[restaurant.target] = waiting_decision_tree(example) return example return RestaurantDataSet([gen() for _ in range(n)]) def Majority(k, n): """ Return a DataSet with n k-bit examples of the majority problem: k random bits followed by a 1 if more than half the bits are 1, else 0. """ examples = [] for i in range(n): bits = [random.choice([0, 1]) for _ in range(k)] bits.append(int(sum(bits) > k / 2)) examples.append(bits) return DataSet(name='majority', examples=examples) def Parity(k, n, name='parity'): """ Return a DataSet with n k-bit examples of the parity problem: k random bits followed by a 1 if an odd number of bits are 1, else 0. """ examples = [] for i in range(n): bits = [random.choice([0, 1]) for _ in range(k)] bits.append(sum(bits) % 2) examples.append(bits) return DataSet(name=name, examples=examples) def Xor(n): """Return a DataSet with n examples of 2-input xor.""" return Parity(2, n, name='xor') def ContinuousXor(n): """2 inputs are chosen uniformly from (0.0 .. 2.0]; output is xor of ints.""" examples = [] for i in range(n): x, y = [random.uniform(0.0, 2.0) for _ in '12'] examples.append([x, y, x != y]) return DataSet(name='continuous xor', examples=examples) def compare(algorithms=None, datasets=None, k=10, trials=1): """ Compare various learners on various datasets using cross-validation. Print results as a table. """ # default list of algorithms algorithms = algorithms or [PluralityLearner, NaiveBayesLearner, NearestNeighborLearner, DecisionTreeLearner] # default list of datasets datasets = datasets or [iris, orings, zoo, restaurant, SyntheticRestaurant(20), Majority(7, 100), Parity(7, 100), Xor(100)] print_table([[a.__name__.replace('Learner', '')] + [cross_validation(a, d, k=k, trials=trials) for d in datasets] for a in algorithms], header=[''] + [d.name[0:7] for d in datasets], numfmt='%.2f')
MultiClassLearner
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/datacatalog.py
{ "start": 74051, "end": 79307 }
class ____(GoogleCloudBaseOperator): r""" Searches Data Catalog for multiple resources like entries, tags that match a query. This does not return the complete resource, only the resource identifier and high level fields. Clients can subsequently call ``Get`` methods. Note that searches do not have full recall. There may be results that match your query but are not returned, even in subsequent pages of results. These missing results may vary across repeated calls to search. Do not rely on this method if you need to guarantee full recall. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudDataCatalogSearchCatalogOperator` :param scope: Required. The scope of this search request. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datacatalog_v1beta1.types.Scope` :param query: Required. The query string in search query syntax. The query must be non-empty. Query strings can be simple as "x" or more qualified as: - name:x - column:x - description:y Note: Query tokens need to have a minimum of 3 characters for substring matching to work correctly. See `Data Catalog Search Syntax <https://cloud.google.com/data-catalog/docs/how- to/search-reference>`__ for more information. :param page_size: The maximum number of resources contained in the underlying API response. If page streaming is performed per-resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. :param order_by: Specifies the ordering of results, currently supported case-sensitive choices are: - ``relevance``, only supports descending - ``last_access_timestamp [asc|desc]``, defaults to descending if not specified - ``last_modified_timestamp [asc|desc]``, defaults to descending if not specified If not specified, defaults to ``relevance`` descending. :param retry: A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. :param metadata: Additional metadata that is provided to the method. :param gcp_conn_id: Optional, The connection ID used to connect to Google Cloud. Defaults to 'google_cloud_default'. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). """ template_fields: Sequence[str] = ( "scope", "query", "page_size", "order_by", "retry", "timeout", "metadata", "gcp_conn_id", "impersonation_chain", ) def __init__( self, *, scope: dict | SearchCatalogRequest.Scope, query: str, page_size: int = 100, order_by: str | None = None, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: super().__init__(**kwargs) self.scope = scope self.query = query self.page_size = page_size self.order_by = order_by self.retry = retry self.timeout = timeout self.metadata = metadata self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain def execute(self, context: Context) -> list: hook = CloudDataCatalogHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain ) result = hook.search_catalog( scope=self.scope, query=self.query, page_size=self.page_size, order_by=self.order_by, retry=self.retry, timeout=self.timeout, metadata=self.metadata, ) return [SearchCatalogResult.to_dict(item) for item in result] @deprecated( planned_removal_date="January 30, 2026", use_instead="airflow.providers.google.cloud.operators.dataplex.DataplexCatalogUpdateEntryOperator", reason="The Data Catalog will be discontinued on January 30, 2026 " "in favor of Dataplex Universal Catalog.", category=AirflowProviderDeprecationWarning, )
CloudDataCatalogSearchCatalogOperator
python
django__django
django/test/testcases.py
{ "start": 4979, "end": 5305 }
class ____(_AssertTemplateUsedContext): def test(self): self.test_case.assertFalse( self.template_name in self.rendered_template_names, f"{self.msg_prefix}Template '{self.template_name}' was used " f"unexpectedly in rendering the response", )
_AssertTemplateNotUsedContext
python
PrefectHQ__prefect
src/prefect/server/concurrency/lease_storage/filesystem.py
{ "start": 695, "end": 10350 }
class ____(_ConcurrencyLeaseStorage): """ A file-based concurrency lease storage implementation that stores leases on disk. """ def __init__(self, storage_path: Path | None = None): prefect_home = get_current_settings().home self.storage_path: Path = Path( storage_path or prefect_home / "concurrency_leases" ) def _ensure_storage_path(self) -> None: """Ensure the storage path exists, creating it if necessary.""" self.storage_path.mkdir(parents=True, exist_ok=True) def _lease_file_path(self, lease_id: UUID) -> Path: return self.storage_path / f"{lease_id}.json" def _expiration_index_path(self) -> anyio.Path: return anyio.Path(self.storage_path / "expirations.json") async def _load_expiration_index(self) -> dict[str, str]: """Load the expiration index from disk.""" expiration_file = self._expiration_index_path() if not await expiration_file.exists(): return {} try: return json.loads(await expiration_file.read_text()) except (json.JSONDecodeError, KeyError, ValueError): return {} def _save_expiration_index(self, index: dict[str, str]) -> None: """Save the expiration index to disk.""" self._ensure_storage_path() expiration_file = self._expiration_index_path() with open(expiration_file, "w") as f: json.dump(index, f) async def _update_expiration_index( self, lease_id: UUID, expiration: datetime ) -> None: """Update a single lease's expiration in the index.""" index = await self._load_expiration_index() index[str(lease_id)] = expiration.isoformat() self._save_expiration_index(index) async def _remove_from_expiration_index(self, lease_id: UUID) -> None: """Remove a lease from the expiration index.""" index = await self._load_expiration_index() index.pop(str(lease_id), None) self._save_expiration_index(index) def _serialize_lease( self, lease: ResourceLease[ConcurrencyLimitLeaseMetadata] ) -> _LeaseFile: metadata_dict: dict[str, Any] | None = None if lease.metadata: metadata_dict = {"slots": lease.metadata.slots} if lease.metadata.holder is not None: metadata_dict["holder"] = lease.metadata.holder.model_dump(mode="json") return { "id": str(lease.id), "resource_ids": [str(rid) for rid in lease.resource_ids], "metadata": metadata_dict, "expiration": lease.expiration.isoformat(), "created_at": lease.created_at.isoformat(), } def _deserialize_lease( self, data: _LeaseFile ) -> ResourceLease[ConcurrencyLimitLeaseMetadata]: lease_id = UUID(data["id"]) resource_ids = [UUID(rid) for rid in data["resource_ids"]] metadata = None if data["metadata"]: metadata = ConcurrencyLimitLeaseMetadata( slots=data["metadata"]["slots"], holder=data["metadata"].get("holder") ) expiration = datetime.fromisoformat(data["expiration"]) created_at = datetime.fromisoformat(data["created_at"]) lease = ResourceLease( id=lease_id, resource_ids=resource_ids, metadata=metadata, expiration=expiration, created_at=created_at, ) return lease async def create_lease( self, resource_ids: list[UUID], ttl: timedelta, metadata: ConcurrencyLimitLeaseMetadata | None = None, ) -> ResourceLease[ConcurrencyLimitLeaseMetadata]: expiration = datetime.now(timezone.utc) + ttl lease = ResourceLease( resource_ids=resource_ids, metadata=metadata, expiration=expiration ) self._ensure_storage_path() lease_file = self._lease_file_path(lease.id) lease_data = self._serialize_lease(lease) with open(lease_file, "w") as f: json.dump(lease_data, f) # Update expiration index await self._update_expiration_index(lease.id, expiration) return lease async def read_lease( self, lease_id: UUID ) -> ResourceLease[ConcurrencyLimitLeaseMetadata] | None: lease_file = self._lease_file_path(lease_id) if not lease_file.exists(): return None try: with open(lease_file, "r") as f: lease_data = json.load(f) lease = self._deserialize_lease(lease_data) return lease except (json.JSONDecodeError, KeyError, ValueError): # Clean up corrupted lease file lease_file.unlink(missing_ok=True) await self._remove_from_expiration_index(lease_id) return None async def renew_lease(self, lease_id: UUID, ttl: timedelta) -> bool: """ Atomically renew a concurrency lease by updating its expiration. Checks if the lease exists and updates both the lease file and index, preventing race conditions from creating orphaned index entries. Args: lease_id: The ID of the lease to renew ttl: The new time-to-live duration Returns: True if the lease was renewed, False if it didn't exist """ lease_file = self._lease_file_path(lease_id) if not lease_file.exists(): # Clean up any orphaned index entry await self._remove_from_expiration_index(lease_id) return False try: with open(lease_file, "r") as f: lease_data = json.load(f) # Update expiration time new_expiration = datetime.now(timezone.utc) + ttl lease_data["expiration"] = new_expiration.isoformat() self._ensure_storage_path() # Write updated lease file with open(lease_file, "w") as f: json.dump(lease_data, f) # Verify file still exists after write (could have been deleted) if not lease_file.exists(): # Lease was deleted during update - clean up index await self._remove_from_expiration_index(lease_id) return False # Update expiration index await self._update_expiration_index(lease_id, new_expiration) return True except (json.JSONDecodeError, KeyError, ValueError): # Clean up corrupted lease file lease_file.unlink(missing_ok=True) await self._remove_from_expiration_index(lease_id) return False async def revoke_lease(self, lease_id: UUID) -> None: lease_file = self._lease_file_path(lease_id) lease_file.unlink(missing_ok=True) # Remove from expiration index await self._remove_from_expiration_index(lease_id) async def read_active_lease_ids( self, limit: int = 100, offset: int = 0 ) -> list[UUID]: now = datetime.now(timezone.utc) expiration_index = await self._load_expiration_index() # Collect all active leases first all_active: list[UUID] = [] for lease_id_str, expiration_str in expiration_index.items(): try: lease_id = UUID(lease_id_str) expiration = datetime.fromisoformat(expiration_str) if expiration > now: all_active.append(lease_id) except (ValueError, TypeError): continue # Apply offset and limit return all_active[offset : offset + limit] async def read_expired_lease_ids(self, limit: int = 100) -> list[UUID]: expired_leases: list[UUID] = [] now = datetime.now(timezone.utc) expiration_index = await self._load_expiration_index() for lease_id_str, expiration_str in expiration_index.items(): if len(expired_leases) >= limit: break try: lease_id = UUID(lease_id_str) expiration = datetime.fromisoformat(expiration_str) if expiration < now: expired_leases.append(lease_id) except (ValueError, TypeError): continue return expired_leases async def list_holders_for_limit( self, limit_id: UUID ) -> list[tuple[UUID, ConcurrencyLeaseHolder]]: """List all holders for a given concurrency limit.""" now = datetime.now(timezone.utc) holders_with_leases: list[tuple[UUID, ConcurrencyLeaseHolder]] = [] # Get all active lease IDs - need to paginate through all all_active_lease_ids: list[UUID] = [] offset = 0 batch_size = 100 while True: batch = await self.read_active_lease_ids(limit=batch_size, offset=offset) if not batch: break all_active_lease_ids.extend(batch) if len(batch) < batch_size: break offset += batch_size active_lease_ids = all_active_lease_ids for lease_id in active_lease_ids: lease = await self.read_lease(lease_id) if ( lease and limit_id in lease.resource_ids and lease.expiration > now and lease.metadata and lease.metadata.holder ): holders_with_leases.append((lease.id, lease.metadata.holder)) return holders_with_leases
ConcurrencyLeaseStorage
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_multiarray.py
{ "start": 246347, "end": 248946 }
class ____(TestCase): """ Verify that making a view of a non-contiguous array works as expected. """ def test_smaller_dtype_multiple(self): # x is non-contiguous x = np.arange(10, dtype="<i4")[::2] with pytest.raises(ValueError, match="the last axis must be contiguous"): x.view("<i2") expected = [[0, 0], [2, 0], [4, 0], [6, 0], [8, 0]] assert_array_equal(x[:, np.newaxis].view("<i2"), expected) def test_smaller_dtype_not_multiple(self): # x is non-contiguous x = np.arange(5, dtype="<i4")[::2] with pytest.raises(ValueError, match="the last axis must be contiguous"): x.view("S3") with pytest.raises(ValueError, match="When changing to a smaller dtype"): x[:, np.newaxis].view("S3") # Make sure the problem is because of the dtype size expected = [[b""], [b"\x02"], [b"\x04"]] assert_array_equal(x[:, np.newaxis].view("S4"), expected) def test_larger_dtype_multiple(self): # x is non-contiguous in the first dimension, contiguous in the last x = np.arange(20, dtype="<i2").reshape(10, 2)[::2, :] expected = np.array( [[65536], [327684], [589832], [851980], [1114128]], dtype="<i4" ) assert_array_equal(x.view("<i4"), expected) def test_larger_dtype_not_multiple(self): # x is non-contiguous in the first dimension, contiguous in the last x = np.arange(20, dtype="<i2").reshape(10, 2)[::2, :] with pytest.raises(ValueError, match="When changing to a larger dtype"): x.view("S3") # Make sure the problem is because of the dtype size expected = [ [b"\x00\x00\x01"], [b"\x04\x00\x05"], [b"\x08\x00\t"], [b"\x0c\x00\r"], [b"\x10\x00\x11"], ] assert_array_equal(x.view("S4"), expected) def test_f_contiguous(self): # x is F-contiguous x = np.arange(4 * 3, dtype="<i4").reshape(4, 3).T with pytest.raises(ValueError, match="the last axis must be contiguous"): x.view("<i2") def test_non_c_contiguous(self): # x is contiguous in axis=-1, but not C-contiguous in other axes x = np.arange(2 * 3 * 4, dtype="i1").reshape(2, 3, 4).transpose(1, 0, 2) expected = [ [[256, 770], [3340, 3854]], [[1284, 1798], [4368, 4882]], [[2312, 2826], [5396, 5910]], ] assert_array_equal(x.view("<i2"), expected) @instantiate_parametrized_tests
TestViewDtype
python
faif__python-patterns
tests/structural/test_decorator.py
{ "start": 97, "end": 692 }
class ____(unittest.TestCase): def setUp(self): self.raw_string = TextTag("raw but not cruel") def test_italic(self): self.assertEqual( ItalicWrapper(self.raw_string).render(), "<i>raw but not cruel</i>" ) def test_bold(self): self.assertEqual( BoldWrapper(self.raw_string).render(), "<b>raw but not cruel</b>" ) def test_mixed_bold_and_italic(self): self.assertEqual( BoldWrapper(ItalicWrapper(self.raw_string)).render(), "<b><i>raw but not cruel</i></b>", )
TestTextWrapping
python
celery__celery
t/unit/tasks/test_states.py
{ "start": 43, "end": 1085 }
class ____: @pytest.mark.parametrize('r,l', [ (states.SUCCESS, states.PENDING), (states.FAILURE, states.RECEIVED), (states.REVOKED, states.STARTED), (states.SUCCESS, 'CRASHED'), (states.FAILURE, 'CRASHED'), ]) def test_gt(self, r, l): assert states.state(r) > states.state(l) @pytest.mark.parametrize('r,l', [ ('CRASHED', states.REVOKED), ]) def test_gte(self, r, l): assert states.state(r) >= states.state(l) @pytest.mark.parametrize('r,l', [ (states.PENDING, states.SUCCESS), (states.RECEIVED, states.FAILURE), (states.STARTED, states.REVOKED), ('CRASHED', states.SUCCESS), ('CRASHED', states.FAILURE), (states.REVOKED, 'CRASHED'), ]) def test_lt(self, r, l): assert states.state(r) < states.state(l) @pytest.mark.parametrize('r,l', [ (states.REVOKED, 'CRASHED'), ]) def test_lte(self, r, l): assert states.state(r) <= states.state(l)
test_state_precedence
python
pytorch__pytorch
test/quantization/ao_migration/test_ao_migration.py
{ "start": 6360, "end": 10435 }
class ____(AOMigrationTestCase): def test_modules_import_nn_intrinsic(self): module_list = [ # Modules "_FusedModule", "ConvBn1d", "ConvBn2d", "ConvBn3d", "ConvBnReLU1d", "ConvBnReLU2d", "ConvBnReLU3d", "ConvReLU1d", "ConvReLU2d", "ConvReLU3d", "LinearReLU", "BNReLU2d", "BNReLU3d", "LinearBn1d", ] self._test_function_import("intrinsic", module_list, base="nn") def test_modules_nn_intrinsic_fused(self): function_list = [ "_FusedModule", "ConvBn1d", "ConvBn2d", "ConvBn3d", "ConvBnReLU1d", "ConvBnReLU2d", "ConvBnReLU3d", "ConvReLU1d", "ConvReLU2d", "ConvReLU3d", "LinearReLU", "BNReLU2d", "BNReLU3d", "LinearBn1d", ] self._test_function_import("fused", function_list, base="nn.intrinsic.modules") def test_modules_import_nn_intrinsic_qat(self): module_list = [ "LinearReLU", "LinearBn1d", "ConvReLU1d", "ConvReLU2d", "ConvReLU3d", "ConvBn1d", "ConvBn2d", "ConvBn3d", "ConvBnReLU1d", "ConvBnReLU2d", "ConvBnReLU3d", "update_bn_stats", "freeze_bn_stats", ] self._test_function_import("qat", module_list, base="nn.intrinsic") def test_modules_intrinsic_qat_conv_fused(self): function_list = [ "ConvBn1d", "ConvBnReLU1d", "ConvReLU1d", "ConvBn2d", "ConvBnReLU2d", "ConvReLU2d", "ConvBn3d", "ConvBnReLU3d", "ConvReLU3d", "update_bn_stats", "freeze_bn_stats", ] self._test_function_import( "conv_fused", function_list, base="nn.intrinsic.qat.modules" ) def test_modules_intrinsic_qat_linear_fused(self): function_list = [ "LinearBn1d", ] self._test_function_import( "linear_fused", function_list, base="nn.intrinsic.qat.modules" ) def test_modules_intrinsic_qat_linear_relu(self): function_list = [ "LinearReLU", ] self._test_function_import( "linear_relu", function_list, base="nn.intrinsic.qat.modules" ) def test_modules_import_nn_intrinsic_quantized(self): module_list = [ "BNReLU2d", "BNReLU3d", "ConvReLU1d", "ConvReLU2d", "ConvReLU3d", "LinearReLU", ] self._test_function_import("quantized", module_list, base="nn.intrinsic") def test_modules_intrinsic_quantized_bn_relu(self): function_list = [ "BNReLU2d", "BNReLU3d", ] self._test_function_import( "bn_relu", function_list, base="nn.intrinsic.quantized.modules" ) def test_modules_intrinsic_quantized_conv_relu(self): function_list = [ "ConvReLU1d", "ConvReLU2d", "ConvReLU3d", ] self._test_function_import( "conv_relu", function_list, base="nn.intrinsic.quantized.modules" ) def test_modules_intrinsic_quantized_linear_relu(self): function_list = [ "LinearReLU", ] self._test_function_import( "linear_relu", function_list, base="nn.intrinsic.quantized.modules" ) def test_modules_no_import_nn_intrinsic_quantized_dynamic(self): # TODO(future PR): generalize this import torch _ = torch.ao.nn.intrinsic.quantized.dynamic _ = torch.nn.intrinsic.quantized.dynamic if __name__ == "__main__": raise_on_run_directly("test/test_quantization.py")
TestAOMigrationNNIntrinsic
python
scipy__scipy
scipy/sparse/tests/test_base.py
{ "start": 204303, "end": 204426 }
class ____(_MatrixMixin, TestDIA): spcreator = dia_matrix TestDIA.init_class() TestDIAMatrix.init_class()
TestDIAMatrix
python
huggingface__transformers
tests/models/llama/test_modeling_llama.py
{ "start": 1301, "end": 1430 }
class ____(CausalLMModelTester): if is_torch_available(): base_model_class = LlamaModel @require_torch
LlamaModelTester
python
doocs__leetcode
solution/3100-3199/3194.Minimum Average of Smallest and Largest Elements/Solution.py
{ "start": 0, "end": 184 }
class ____: def minimumAverage(self, nums: List[int]) -> float: nums.sort() n = len(nums) return min(nums[i] + nums[-i - 1] for i in range(n // 2)) / 2
Solution
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 108770, "end": 113313 }
class ____: def test_ab(self): # c >= 0: a, b = [0, inf] for c in [1., 0.]: c = np.asarray(c) a, b = stats.genpareto._get_support(c) assert_equal(a, 0.) assert_(np.isposinf(b)) # c < 0: a=0, b=1/|c| c = np.asarray(-2.) a, b = stats.genpareto._get_support(c) assert_allclose([a, b], [0., 0.5]) def test_c0(self): # with c=0, genpareto reduces to the exponential distribution # rv = stats.genpareto(c=0.) rv = stats.genpareto(c=0.) x = np.linspace(0, 10., 30) assert_allclose(rv.pdf(x), stats.expon.pdf(x)) assert_allclose(rv.cdf(x), stats.expon.cdf(x)) assert_allclose(rv.sf(x), stats.expon.sf(x)) q = np.linspace(0., 1., 10) assert_allclose(rv.ppf(q), stats.expon.ppf(q)) def test_cm1(self): # with c=-1, genpareto reduces to the uniform distr on [0, 1] rv = stats.genpareto(c=-1.) x = np.linspace(0, 10., 30) assert_allclose(rv.pdf(x), stats.uniform.pdf(x)) assert_allclose(rv.cdf(x), stats.uniform.cdf(x)) assert_allclose(rv.sf(x), stats.uniform.sf(x)) q = np.linspace(0., 1., 10) assert_allclose(rv.ppf(q), stats.uniform.ppf(q)) # logpdf(1., c=-1) should be zero assert_allclose(rv.logpdf(1), 0) def test_x_inf(self): # make sure x=inf is handled gracefully rv = stats.genpareto(c=0.1) assert_allclose([rv.pdf(np.inf), rv.cdf(np.inf)], [0., 1.]) assert_(np.isneginf(rv.logpdf(np.inf))) rv = stats.genpareto(c=0.) assert_allclose([rv.pdf(np.inf), rv.cdf(np.inf)], [0., 1.]) assert_(np.isneginf(rv.logpdf(np.inf))) rv = stats.genpareto(c=-1.) assert_allclose([rv.pdf(np.inf), rv.cdf(np.inf)], [0., 1.]) assert_(np.isneginf(rv.logpdf(np.inf))) def test_c_continuity(self): # pdf is continuous at c=0, -1 x = np.linspace(0, 10, 30) for c in [0, -1]: pdf0 = stats.genpareto.pdf(x, c) for dc in [1e-14, -1e-14]: pdfc = stats.genpareto.pdf(x, c + dc) assert_allclose(pdf0, pdfc, atol=1e-12) cdf0 = stats.genpareto.cdf(x, c) for dc in [1e-14, 1e-14]: cdfc = stats.genpareto.cdf(x, c + dc) assert_allclose(cdf0, cdfc, atol=1e-12) def test_c_continuity_ppf(self): q = np.r_[np.logspace(1e-12, 0.01, base=0.1), np.linspace(0.01, 1, 30, endpoint=False), 1. - np.logspace(1e-12, 0.01, base=0.1)] for c in [0., -1.]: ppf0 = stats.genpareto.ppf(q, c) for dc in [1e-14, -1e-14]: ppfc = stats.genpareto.ppf(q, c + dc) assert_allclose(ppf0, ppfc, atol=1e-12) def test_c_continuity_isf(self): q = np.r_[np.logspace(1e-12, 0.01, base=0.1), np.linspace(0.01, 1, 30, endpoint=False), 1. - np.logspace(1e-12, 0.01, base=0.1)] for c in [0., -1.]: isf0 = stats.genpareto.isf(q, c) for dc in [1e-14, -1e-14]: isfc = stats.genpareto.isf(q, c + dc) assert_allclose(isf0, isfc, atol=1e-12) def test_cdf_ppf_roundtrip(self): # this should pass with machine precision. hat tip @pbrod q = np.r_[np.logspace(1e-12, 0.01, base=0.1), np.linspace(0.01, 1, 30, endpoint=False), 1. - np.logspace(1e-12, 0.01, base=0.1)] for c in [1e-8, -1e-18, 1e-15, -1e-15]: assert_allclose(stats.genpareto.cdf(stats.genpareto.ppf(q, c), c), q, atol=1e-15) def test_logsf(self): logp = stats.genpareto.logsf(1e10, .01, 0, 1) assert_allclose(logp, -1842.0680753952365) # Values in 'expected_stats' are # [mean, variance, skewness, excess kurtosis]. @pytest.mark.parametrize( 'c, expected_stats', [(0, [1, 1, 2, 6]), (1/4, [4/3, 32/9, 10/np.sqrt(2), np.nan]), (1/9, [9/8, (81/64)*(9/7), (10/9)*np.sqrt(7), 754/45]), (-1, [1/2, 1/12, 0, -6/5])]) def test_stats(self, c, expected_stats): result = stats.genpareto.stats(c, moments='mvsk') assert_allclose(result, expected_stats, rtol=1e-13, atol=1e-15) def test_var(self): # Regression test for gh-11168. v = stats.genpareto.var(1e-8) assert_allclose(v, 1.000000040000001, rtol=1e-13)
TestGenpareto
python
rapidsai__cudf
python/cudf_polars/cudf_polars/experimental/rapidsmpf/utils.py
{ "start": 1515, "end": 2116 }
class ____: """Metadata payload for an individual ChannelPair.""" __slots__ = ("count", "duplicated", "partitioned_on") count: int """Chunk-count estimate.""" partitioned_on: tuple[str, ...] """Partitioned-on columns.""" duplicated: bool """Whether the data is duplicated on all workers.""" def __init__( self, count: int, *, partitioned_on: tuple[str, ...] = (), duplicated: bool = False, ): self.count = count self.partitioned_on = partitioned_on self.duplicated = duplicated @dataclass
Metadata
python
sympy__sympy
sympy/parsing/maxima.py
{ "start": 201, "end": 1835 }
class ____: def maxima_expand(expr): return expr.expand() def maxima_float(expr): return expr.evalf() def maxima_trigexpand(expr): return expr.expand(trig=True) def maxima_sum(a1, a2, a3, a4): return Sum(a1, (a2, a3, a4)).doit() def maxima_product(a1, a2, a3, a4): return product(a1, (a2, a3, a4)) def maxima_csc(expr): return 1/sin(expr) def maxima_sec(expr): return 1/cos(expr) sub_dict = { 'pi': re.compile(r'%pi'), 'E': re.compile(r'%e'), 'I': re.compile(r'%i'), '**': re.compile(r'\^'), 'oo': re.compile(r'\binf\b'), '-oo': re.compile(r'\bminf\b'), "'-'": re.compile(r'\bminus\b'), 'maxima_expand': re.compile(r'\bexpand\b'), 'maxima_float': re.compile(r'\bfloat\b'), 'maxima_trigexpand': re.compile(r'\btrigexpand'), 'maxima_sum': re.compile(r'\bsum\b'), 'maxima_product': re.compile(r'\bproduct\b'), 'cancel': re.compile(r'\bratsimp\b'), 'maxima_csc': re.compile(r'\bcsc\b'), 'maxima_sec': re.compile(r'\bsec\b') } var_name = re.compile(r'^\s*(\w+)\s*:') def parse_maxima(str, globals=None, name_dict={}): str = str.strip() str = str.rstrip('; ') for k, v in sub_dict.items(): str = v.sub(k, str) assign_var = None var_match = var_name.search(str) if var_match: assign_var = var_match.group(1) str = str[var_match.end():].strip() dct = MaximaHelpers.__dict__.copy() dct.update(name_dict) obj = sympify(str, locals=dct) if assign_var and globals: globals[assign_var] = obj return obj
MaximaHelpers
python
django-haystack__django-haystack
test_haystack/test_discovery.py
{ "start": 832, "end": 2119 }
class ____(TestCase): def test_discovery(self): old_ui = connections["default"].get_unified_index() connections["default"]._index = UnifiedIndex() ui = connections["default"].get_unified_index() self.assertEqual(len(ui.get_indexed_models()), EXPECTED_INDEX_MODEL_COUNT) # Test exclusions. ui.excluded_indexes = ["test_haystack.discovery.search_indexes.BarIndex"] ui.build() indexed_model_names = [str(i._meta) for i in ui.get_indexed_models()] self.assertIn("multipleindex.foo", indexed_model_names) self.assertIn("multipleindex.bar", indexed_model_names) self.assertNotIn("discovery.bar", indexed_model_names) ui.excluded_indexes = [ "test_haystack.discovery.search_indexes.BarIndex", "test_haystack.discovery.search_indexes.FooIndex", ] ui.build() indexed_model_names = [str(i._meta) for i in ui.get_indexed_models()] self.assertIn("multipleindex.foo", indexed_model_names) self.assertIn("multipleindex.bar", indexed_model_names) self.assertListEqual( [], [i for i in indexed_model_names if i.startswith("discovery")] ) connections["default"]._index = old_ui
AutomaticDiscoveryTestCase
python
Textualize__textual
src/textual/worker.py
{ "start": 2541, "end": 13799 }
class ____(Generic[ResultType]): """A class to manage concurrent work (either a task or a thread).""" @rich.repr.auto class StateChanged(Message, bubble=False, namespace="worker"): """The worker state changed.""" def __init__(self, worker: Worker, state: WorkerState) -> None: """Initialize the StateChanged message. Args: worker: The worker object. state: New state. """ self.worker = worker self.state = state super().__init__() def __rich_repr__(self) -> rich.repr.Result: yield self.worker yield self.state def __init__( self, node: DOMNode, work: WorkType, *, name: str = "", group: str = "default", description: str = "", exit_on_error: bool = True, thread: bool = False, ) -> None: """Initialize a Worker. Args: node: The widget, screen, or App that initiated the work. work: A callable, coroutine, or other awaitable object to run in the worker. name: Name of the worker (short string to help identify when debugging). group: The worker group. description: Description of the worker (longer string with more details). exit_on_error: Exit the app if the worker raises an error. Set to `False` to suppress exceptions. thread: Mark the worker as a thread worker. """ self._node = node self._work = work self.name = name self.group = group self.description = ( description if len(description) <= 1000 else description[:1000] + "..." ) self.exit_on_error = exit_on_error self.cancelled_event: Event = Event() """A threading event set when the worker is cancelled.""" self._thread_worker = thread self._state = WorkerState.PENDING self.state = self._state self._error: BaseException | None = None self._completed_steps: int = 0 self._total_steps: int | None = None self._cancelled: bool = False self._created_time = monotonic() self._result: ResultType | None = None self._task: asyncio.Task | None = None self._node.post_message(self.StateChanged(self, self._state)) def __rich_repr__(self) -> rich.repr.Result: yield _ReprText(self.state.name) yield "name", self.name, "" yield "group", self.group, "default" yield "description", self.description, "" yield "progress", round(self.progress, 1), 0.0 @property def node(self) -> DOMNode: """The node where this worker was run from.""" return self._node @property def state(self) -> WorkerState: """The current state of the worker.""" return self._state @state.setter def state(self, state: WorkerState) -> None: """Set the state, and send a message.""" changed = state != self._state self._state = state if changed: self._node.post_message(self.StateChanged(self, state)) @property def is_cancelled(self) -> bool: """Has the work been cancelled? Note that cancelled work may still be running. """ return self._cancelled @property def is_running(self) -> bool: """Is the task running?""" return self.state == WorkerState.RUNNING @property def is_finished(self) -> bool: """Has the task finished (cancelled, error, or success)?""" return self.state in ( WorkerState.CANCELLED, WorkerState.ERROR, WorkerState.SUCCESS, ) @property def completed_steps(self) -> int: """The number of completed steps.""" return self._completed_steps @property def total_steps(self) -> int | None: """The number of total steps, or None if indeterminate.""" return self._total_steps @property def progress(self) -> float: """Progress as a percentage. If the total steps is None, then this will return 0. The percentage will be clamped between 0 and 100. """ if not self._total_steps: return 0.0 return max(0, min(100, (self._completed_steps / self._total_steps) * 100.0)) @property def result(self) -> ResultType | None: """The result of the worker, or `None` if there is no result.""" return self._result @property def error(self) -> BaseException | None: """The exception raised by the worker, or `None` if there was no error.""" return self._error def update( self, completed_steps: int | None = None, total_steps: int | None = -1 ) -> None: """Update the number of completed steps. Args: completed_steps: The number of completed seps, or `None` to not change. total_steps: The total number of steps, `None` for indeterminate, or -1 to leave unchanged. """ if completed_steps is not None: self._completed_steps += completed_steps if total_steps != -1: self._total_steps = None if total_steps is None else max(0, total_steps) def advance(self, steps: int = 1) -> None: """Advance the number of completed steps. Args: steps: Number of steps to advance. """ self._completed_steps += steps async def _run_threaded(self) -> ResultType: """Run a threaded worker. Returns: Return value of the work. """ def run_awaitable(work: Awaitable[ResultType]) -> ResultType: """Set the active worker and await the awaitable.""" async def do_work() -> ResultType: active_worker.set(self) return await work return asyncio.run(do_work()) def run_coroutine( work: Callable[[], Coroutine[None, None, ResultType]], ) -> ResultType: """Set the active worker and await coroutine.""" return run_awaitable(work()) def run_callable(work: Callable[[], ResultType]) -> ResultType: """Set the active worker, and call the callable.""" active_worker.set(self) return work() if ( inspect.iscoroutinefunction(self._work) or hasattr(self._work, "func") and inspect.iscoroutinefunction(self._work.func) ): runner = run_coroutine elif inspect.isawaitable(self._work): runner = run_awaitable elif callable(self._work): runner = run_callable else: raise WorkerError("Unsupported attempt to run a thread worker") loop = asyncio.get_running_loop() assert loop is not None return await loop.run_in_executor(None, runner, self._work) async def _run_async(self) -> ResultType: """Run an async worker. Returns: Return value of the work. """ if ( inspect.iscoroutinefunction(self._work) or hasattr(self._work, "func") and inspect.iscoroutinefunction(self._work.func) ): return await self._work() elif inspect.isawaitable(self._work): return await self._work elif callable(self._work): raise WorkerError("Request to run a non-async function as an async worker") raise WorkerError("Unsupported attempt to run an async worker") async def run(self) -> ResultType: """Run the work. Implement this method in a subclass, or pass a callable to the constructor. Returns: Return value of the work. """ return await ( self._run_threaded() if self._thread_worker else self._run_async() ) async def _run(self, app: App) -> None: """Run the worker. Args: app: App instance. """ with app._context(): active_worker.set(self) self.state = WorkerState.RUNNING app.log.worker(self) try: self._result = await self.run() except asyncio.CancelledError as error: self.state = WorkerState.CANCELLED self._error = error app.log.worker(self) except Exception as error: self.state = WorkerState.ERROR self._error = error app.log.worker(self, "failed", repr(error)) from rich.traceback import Traceback app.log.worker(Traceback()) if self.exit_on_error: worker_failed = WorkerFailed(self._error) app._handle_exception(worker_failed) else: self.state = WorkerState.SUCCESS app.log.worker(self) def _start( self, app: App, done_callback: Callable[[Worker], None] | None = None ) -> None: """Start the worker. Args: app: An app instance. done_callback: A callback to call when the task is done. """ if self._task is not None: return self.state = WorkerState.RUNNING self._task = asyncio.create_task(self._run(app)) def task_done_callback(_task: asyncio.Task) -> None: """Run the callback. Called by `Task.add_done_callback`. Args: The worker's task. """ if done_callback is not None: done_callback(self) self._task.add_done_callback(task_done_callback) def cancel(self) -> None: """Cancel the task.""" self._cancelled = True if self._task is not None: self._task.cancel() self.cancelled_event.set() async def wait(self) -> ResultType: """Wait for the work to complete. Raises: WorkerFailed: If the Worker raised an exception. WorkerCancelled: If the Worker was cancelled before it completed. Returns: The return value of the work. """ try: if active_worker.get() is self: raise DeadlockError( "Can't call worker.wait from within the worker function!" ) except LookupError: # Not in a worker pass if self.state == WorkerState.PENDING: raise WorkerError("Worker must be started before calling this method.") if self._task is not None: try: await self._task except asyncio.CancelledError as error: self.state = WorkerState.CANCELLED self._error = error if self.state == WorkerState.ERROR: assert self._error is not None raise WorkerFailed(self._error) elif self.state == WorkerState.CANCELLED: raise WorkerCancelled("Worker was cancelled, and did not complete.") return cast("ResultType", self._result)
Worker
python
great-expectations__great_expectations
contrib/experimental/great_expectations_experimental/expectations/expect_value_at_index.py
{ "start": 2207, "end": 11242 }
class ____(ColumnMapExpectation): """Expect a specific value at a given index location within each element of the column.""" # These examples will be shown in the public gallery, and also executed as unit tests for your Expectation examples = [ { "data": { "mostly_has_decimal": [ "$125.23", "$0.99", "$0.00", "$1234", "$11.11", "$1.10", "$2.22", "$-1.43", None, None, ], "numeric": [ 125.23, 0.99, 0.00, 1234, 11.11, 1.10, 2.22, -1.43, None, None, ], "words_that_begin_with_a": [ "apple", "alligator", "alibi", "argyle", None, "ambulance", "aardvark", "ambiguous", None, None, ], }, "tests": [ { "title": "positive_test_with_mostly", "exact_match_out": False, "include_in_gallery": True, "in": { "column": "mostly_has_decimal", "value": ".", "index": -3, "mostly": 0.6, }, "out": { "success": True, "unexpected_index_list": [3], "unexpected_list": ["$1234"], }, }, { "title": "negative_test_without_mostly", "exact_match_out": False, "include_in_gallery": True, "in": { "column": "mostly_has_decimal", "value": ".", "index": -3, "mostly": 1.0, }, "out": { "success": False, "unexpected_index_list": [3], "unexpected_list": ["$1234"], }, }, { "title": "negative_test_for_numeric_column", "exact_match_out": False, "include_in_gallery": True, "in": { "column": "numeric", "value": ".", "index": -3, "mostly": 0.6, }, "out": { "success": False, "unexpected_index_list": [0, 1, 2, 3, 4, 5, 6, 7], }, }, { "title": "positive_test_for_column_starting_with_a", "exact_match_out": False, "include_in_gallery": True, "in": { "column": "words_that_begin_with_a", "value": "a", "index": 0, "mostly": 1.0, }, "out": { "success": True, "unexpected_index_list": [], }, }, ], } ] # examples = [{ # "data": { # "mostly_threes": [3, 3, 3, 3, 3, 3, 2, -1, None, None], # }, # "tests": [ # { # "title": "positive_test_with_mostly", # "exact_match_out": False, # "include_in_gallery": True, # "in": {"column": "mostly_threes", "mostly": 0.6}, # "out": { # "success": True, # "unexpected_index_list": [6, 7], # "unexpected_list": [2, -1], # }, # } # ], # }] # This dictionary contains metadata for display in the public gallery library_metadata = { "maturity": "experimental", # "experimental", "beta", or "production" "tags": [ # Tags for this Expectation in the gallery # "experimental" ], "contributors": [ "@prem1835213", "@YaosenLin", # Github handles for all contributors to this Expectation. # "@your_name_here", # Don't forget to add your github handle here! ], } # This is the id string of the Metric used by this Expectation. # For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above. map_metric = "column_values.has_value_at_index" # This is a list of parameter names that can affect whether the Expectation evaluates to True or False # Please see {some doc} for more information about domain and success keys, and other arguments to Expectations success_keys = ("mostly", "value", "index") # This dictionary contains default values for any parameters that should have default values default_kwarg_values = {} # This method defines a question Renderer # For more info on Renderers, see {some doc} #!!! This example renderer should render RenderedStringTemplateContent, not just a string # @classmethod # @renderer(renderer_type="renderer.question") # def _question_renderer( # cls, configuration, result=None, runtime_configuration=None # ): # column = configuration.kwargs.get("column") # mostly = configuration.kwargs.get("mostly") # return f'Do at least {mostly * 100}% of values in column "{column}" equal 3?' # This method defines an answer Renderer #!!! This example renderer should render RenderedStringTemplateContent, not just a string # @classmethod # @renderer(renderer_type="renderer.answer") # def _answer_renderer( # cls, configuration=None, result=None, runtime_configuration=None # ): # column = result.expectation_config.kwargs.get("column") # mostly = result.expectation_config.kwargs.get("mostly") # regex = result.expectation_config.kwargs.get("regex") # if result.success: # return f'At least {mostly * 100}% of values in column "{column}" equal 3.' # else: # return f'Less than {mostly * 100}% of values in column "{column}" equal 3.' # This method defines a prescriptive Renderer # @classmethod # @renderer(renderer_type="renderer.prescriptive") # @render_suite_parameter_string # def _prescriptive_renderer( # cls, # configuration=None, # result=None, # runtime_configuration=None, # **kwargs, # ): #!!! This example renderer should be shorter # runtime_configuration = runtime_configuration or {} # include_column_name = False if runtime_configuration.get("include_column_name") is False else True # styling = runtime_configuration.get("styling") # params = substitute_none_for_missing( # configuration.kwargs, # ["column", "regex", "mostly", "row_condition", "condition_parser"], # ) # template_str = "values must be equal to 3" # if params["mostly"] is not None: # params["mostly_pct"] = num_to_str( # params["mostly"] * 100, precision=15, no_scientific=True # ) # # params["mostly_pct"] = "{:.14f}".format(params["mostly"]*100).rstrip("0").rstrip(".") # template_str += ", at least $mostly_pct % of the time." # else: # template_str += "." # if include_column_name: # template_str = "$column " + template_str # if params["row_condition"] is not None: # ( # conditional_template_str, # conditional_params, # ) = parse_row_condition_string_pandas_engine(params["row_condition"]) # template_str = conditional_template_str + ", then " + template_str # params.update(conditional_params) # return [ # RenderedStringTemplateContent( # **{ # "content_block_type": "string_template", # "string_template": { # "template": template_str, # "params": params, # "styling": styling, # }, # } # ) # ] if __name__ == "__main__": ExpectValueAtIndex().print_diagnostic_checklist()
ExpectValueAtIndex