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
weaviate__weaviate-python-client
weaviate/collections/batch/base.py
{ "start": 6003, "end": 32005 }
class ____: def __init__( self, connection: ConnectionSync, consistency_level: Optional[ConsistencyLevel], results: _BatchDataWrapper, batch_mode: _BatchMode, executor: ThreadPoolExecutor, vectorizer_batching: bool, objects: Optional[ObjectsBatchRequest] = None, references: Optional[ReferencesBatchRequest] = None, ) -> None: self.__batch_objects = objects or ObjectsBatchRequest() self.__batch_references = references or ReferencesBatchRequest() self.__connection = connection self.__consistency_level: Optional[ConsistencyLevel] = consistency_level self.__vectorizer_batching = vectorizer_batching self.__batch_grpc = _BatchGRPC( connection._weaviate_version, self.__consistency_level, connection._grpc_max_msg_size ) self.__batch_rest = _BatchREST(self.__consistency_level) # lookup table for objects that are currently being processed - is used to not send references from objects that have not been added yet self.__uuid_lookup: Set[str] = set() # we do not want that users can access the results directly as they are not thread-safe self.__results_for_wrapper_backup = results self.__results_for_wrapper = _BatchDataWrapper() self.__cluster = _ClusterBatch(self.__connection) self.__batching_mode: _BatchMode = batch_mode self.__max_batch_size: int = 1000 self.__executor = executor self.__objs_count = 0 self.__refs_count = 0 self.__objs_logs_count = 0 self.__refs_logs_count = 0 if isinstance(self.__batching_mode, _FixedSizeBatching): self.__recommended_num_objects = self.__batching_mode.batch_size self.__concurrent_requests = self.__batching_mode.concurrent_requests elif isinstance(self.__batching_mode, _RateLimitedBatching): # Batch with rate limiting should never send more than the given amount of objects per minute. # We could send all objects in a single batch every 60 seconds but that could cause problems with too large requests. Therefore, we # limit the size of a batch to self.__max_batch_size and send multiple batches of equal size and send them in equally space in time. # Example: # 3000 objects, 1000/min -> 3 batches of 1000 objects, send every 20 seconds self.__concurrent_requests = ( self.__batching_mode.requests_per_minute + self.__max_batch_size ) // self.__max_batch_size self.__recommended_num_objects = ( self.__batching_mode.requests_per_minute // self.__concurrent_requests ) elif isinstance(self.__batching_mode, _DynamicBatching) and not self.__vectorizer_batching: self.__recommended_num_objects = 10 self.__concurrent_requests = 2 else: assert isinstance(self.__batching_mode, _DynamicBatching) and self.__vectorizer_batching self.__recommended_num_objects = VECTORIZER_BATCHING_STEP_SIZE self.__concurrent_requests = 2 self.__dynamic_batching_sleep_time: int = 0 self._batch_send: bool = False self.__recommended_num_refs: int = 50 self.__active_requests = 0 # dynamic batching self.__time_last_scale_up: float = 0 self.__rate_queue: deque = deque(maxlen=50) # 5s with 0.1s refresh rate self.__took_queue: deque = deque(maxlen=CONCURRENT_REQUESTS_DYNAMIC_VECTORIZER) # fixed rate batching self.__time_stamp_last_request: float = 0 # do 62 secs to give us some buffer to the "per-minute" calculation self.__fix_rate_batching_base_time = 62 self.__active_requests_lock = threading.Lock() self.__uuid_lookup_lock = threading.Lock() self.__results_lock = threading.Lock() self.__bg_thread = self.__start_bg_threads() self.__bg_thread_exception: Optional[Exception] = None @property def number_errors(self) -> int: """Return the number of errors in the batch.""" return len(self.__results_for_wrapper.failed_objects) + len( self.__results_for_wrapper.failed_references ) def _start(self): pass def _shutdown(self) -> None: """Shutdown the current batch and wait for all requests to be finished.""" self.flush() # we are done, shut bg threads down and end the event loop self.__shut_background_thread_down.set() while self.__bg_thread.is_alive(): time.sleep(0.01) # copy the results to the public results self.__results_for_wrapper_backup.results = self.__results_for_wrapper.results self.__results_for_wrapper_backup.failed_objects = self.__results_for_wrapper.failed_objects self.__results_for_wrapper_backup.failed_references = ( self.__results_for_wrapper.failed_references ) self.__results_for_wrapper_backup.imported_shards = ( self.__results_for_wrapper.imported_shards ) def __batch_send(self) -> None: refresh_time: float = 0.01 while ( self.__shut_background_thread_down is not None and not self.__shut_background_thread_down.is_set() ): if isinstance(self.__batching_mode, _RateLimitedBatching): if ( time.time() - self.__time_stamp_last_request < self.__fix_rate_batching_base_time // self.__concurrent_requests ): time.sleep(1) continue refresh_time = 0 elif isinstance(self.__batching_mode, _DynamicBatching) and self.__vectorizer_batching: if self.__dynamic_batching_sleep_time > 0: if ( time.time() - self.__time_stamp_last_request < self.__dynamic_batching_sleep_time ): time.sleep(1) continue if ( self.__active_requests < self.__concurrent_requests and len(self.__batch_objects) + len(self.__batch_references) > 0 ): self.__time_stamp_last_request = time.time() self._batch_send = True with self.__active_requests_lock: self.__active_requests += 1 start = time.time() while (len_o := len(self.__batch_objects)) < self.__recommended_num_objects and ( len_r := len(self.__batch_references) ) < self.__recommended_num_refs: # wait for more objects to be added up to the recommended number time.sleep(0.01) if ( self.__shut_background_thread_down is not None and self.__shut_background_thread_down.is_set() ): # shutdown was requested, exit the loop break if time.time() - start >= 1 and ( len_o == len(self.__batch_objects) or len_r == len(self.__batch_references) ): # no new objects were added in the last second, exit the loop break objs = self.__batch_objects.pop_items(self.__recommended_num_objects) refs = self.__batch_references.pop_items( self.__recommended_num_refs, uuid_lookup=self.__uuid_lookup, ) # do not block the thread - the results are written to a central (locked) list and we want to have multiple concurrent batch-requests ctx = contextvars.copy_context() self.__executor.submit( ctx.run, functools.partial( self.__send_batch, objs, refs, readd_rate_limit=isinstance(self.__batching_mode, _RateLimitedBatching), ), ) time.sleep(refresh_time) def __dynamic_batch_rate_loop(self) -> None: refresh_time = 1 while ( self.__shut_background_thread_down is not None and not self.__shut_background_thread_down.is_set() ): if not isinstance(self.__batching_mode, _DynamicBatching): return try: self.__dynamic_batching() except Exception as e: logger.debug(repr(e)) time.sleep(refresh_time) def __start_bg_threads(self) -> threading.Thread: """Create a background thread that periodically checks how congested the batch queue is.""" self.__shut_background_thread_down = threading.Event() def dynamic_batch_rate_wrapper() -> None: try: self.__dynamic_batch_rate_loop() except Exception as e: self.__bg_thread_exception = e demonDynamic = threading.Thread( target=dynamic_batch_rate_wrapper, daemon=True, name="BgDynamicBatchRate", ) demonDynamic.start() def batch_send_wrapper() -> None: try: self.__batch_send() except Exception as e: logger.error(e) self.__bg_thread_exception = e demonBatchSend = threading.Thread( target=batch_send_wrapper, daemon=True, name="BgBatchScheduler", ) demonBatchSend.start() return demonBatchSend def __dynamic_batching(self) -> None: status = self.__cluster.get_nodes_status() if "batchStats" not in status[0] or "queueLength" not in status[0]["batchStats"]: # async indexing - just send a lot self.__batching_mode = _FixedSizeBatching(1000, 10) self.__recommended_num_objects = 1000 self.__concurrent_requests = 10 return rate: int = status[0]["batchStats"]["ratePerSecond"] rate_per_worker = rate / self.__concurrent_requests batch_length = status[0]["batchStats"]["queueLength"] self.__rate_queue.append(rate) if self.__vectorizer_batching: # slow vectorizer, we want to send larger batches that can take a bit longer, but fewer of them. We might need to sleep if len(self.__took_queue) > 0 and self._batch_send: max_took = max(self.__took_queue) self.__dynamic_batching_sleep_time = 0 if max_took > 2 * BATCH_TIME_TARGET: self.__concurrent_requests = 1 self.__recommended_num_objects = VECTORIZER_BATCHING_STEP_SIZE elif max_took > BATCH_TIME_TARGET: current_step = self.__recommended_num_objects // VECTORIZER_BATCHING_STEP_SIZE if self.__concurrent_requests > 1: self.__concurrent_requests -= 1 elif current_step > 1: self.__recommended_num_objects = VECTORIZER_BATCHING_STEP_SIZE * ( current_step - 1 ) else: # cannot scale down, sleep a bit self.__dynamic_batching_sleep_time = max_took - BATCH_TIME_TARGET elif max_took < 3 * BATCH_TIME_TARGET // 4: if self.__dynamic_batching_sleep_time > 0: self.__dynamic_batching_sleep_time = 0 elif self.__concurrent_requests < 3: self.__concurrent_requests += 1 else: current_step = ( self.__recommended_num_objects // VECTORIZER_BATCHING_STEP_SIZE ) self.__recommended_num_objects = VECTORIZER_BATCHING_STEP_SIZE * ( current_step + 1 ) self._batch_send = False else: if batch_length == 0: # scale up if queue is empty self.__recommended_num_objects = min( self.__recommended_num_objects + 50, self.__max_batch_size, ) if ( self.__max_batch_size == self.__recommended_num_objects and len(self.__batch_objects) > self.__recommended_num_objects and time.time() - self.__time_last_scale_up > 1 and self.__concurrent_requests < MAX_CONCURRENT_REQUESTS ): self.__concurrent_requests += 1 self.__time_last_scale_up = time.time() else: ratio = batch_length / rate if 2.1 > ratio > 1.9: # ideal, send exactly as many objects as weaviate can process self.__recommended_num_objects = math.floor(rate_per_worker) elif ratio <= 1.9: # we can send more self.__recommended_num_objects = math.floor( min( self.__recommended_num_objects * 1.5, rate_per_worker * 2 / ratio, ) ) if self.__max_batch_size == self.__recommended_num_objects: self.__concurrent_requests += 1 elif ratio < 10: # too high, scale down self.__recommended_num_objects = math.floor(rate_per_worker * 2 / ratio) if self.__recommended_num_objects < 100 and self.__concurrent_requests > 2: self.__concurrent_requests -= 1 else: # way too high, stop sending new batches self.__recommended_num_objects = 0 self.__concurrent_requests = 2 def __send_batch( self, objs: List[_BatchObject], refs: List[_BatchReference], readd_rate_limit: bool, ) -> None: if (n_objs := len(objs)) > 0: start = time.time() try: response_obj = executor.result( self.__batch_grpc.objects( connection=self.__connection, objects=objs, timeout=DEFAULT_REQUEST_TIMEOUT, max_retries=MAX_RETRIES, ) ) if response_obj.has_errors: logger.error( { "message": f"Failed to send {len(response_obj.errors)} in a batch of {len(objs)}", "errors": {err.message for err in response_obj.errors.values()}, } ) except Exception as e: errors_obj = { idx: ErrorObject(message=repr(e), object_=BatchObject._from_internal(obj)) for idx, obj in enumerate(objs) } logger.error( { "message": f"Failed to send all objects in a batch of {len(objs)}", "error": repr(e), } ) response_obj = BatchObjectReturn( _all_responses=list(errors_obj.values()), elapsed_seconds=time.time() - start, errors=errors_obj, has_errors=True, ) readded_uuids = set() readded_objects = [] highest_retry_count = 0 for i, err in response_obj.errors.items(): if ( ( "support@cohere.com" in err.message and ( "rate limit" in err.message or "500 error: internal server error" in err.message ) ) or ( "OpenAI" in err.message and ( "Rate limit reached" in err.message or "on tokens per min (TPM)" in err.message or "503 error: Service Unavailable." in err.message or "500 error: The server had an error while processing your request." in err.message ) ) or ("failed with status: 503 error" in err.message) # huggingface ): if err.object_.retry_count > highest_retry_count: highest_retry_count = err.object_.retry_count if err.object_.retry_count > 5: continue # too many retries, give up err.object_.retry_count += 1 readded_objects.append(i) if len(readded_objects) > 0: _Warnings.batch_rate_limit_reached( response_obj.errors[readded_objects[0]].message, self.__fix_rate_batching_base_time * (highest_retry_count + 1), ) readd_objects = [ err.object_._to_internal() for i, err in response_obj.errors.items() if i in readded_objects ] readded_uuids = {obj.uuid for obj in readd_objects} self.__batch_objects.prepend(readd_objects) new_errors = { i: err for i, err in response_obj.errors.items() if i not in readded_objects } response_obj = BatchObjectReturn( uuids={ i: uid for i, uid in response_obj.uuids.items() if i not in readded_objects }, errors=new_errors, has_errors=len(new_errors) > 0, _all_responses=[ err for i, err in enumerate(response_obj.all_responses) if i not in readded_objects ], elapsed_seconds=response_obj.elapsed_seconds, ) if readd_rate_limit: # for rate limited batching the timing is handled by the outer loop => no sleep here self.__time_stamp_last_request = ( time.time() + self.__fix_rate_batching_base_time * (highest_retry_count + 1) ) # skip a full minute to recover from the rate limit self.__fix_rate_batching_base_time += ( 1 # increase the base time as the current one is too low ) else: # sleep a bit to recover from the rate limit in other cases time.sleep(2**highest_retry_count) with self.__uuid_lookup_lock: self.__uuid_lookup.difference_update( obj.uuid for obj in objs if obj.uuid not in readded_uuids ) if (n_obj_errs := len(response_obj.errors)) > 0 and self.__objs_logs_count < 30: logger.error( { "message": f"Failed to send {n_obj_errs} objects in a batch of {n_objs}. Please inspect client.batch.failed_objects or collection.batch.failed_objects for the failed objects.", } ) self.__objs_logs_count += 1 if self.__objs_logs_count > 30: logger.error( { "message": "There have been more than 30 failed object batches. Further errors will not be logged.", } ) with self.__results_lock: self.__results_for_wrapper.results.objs += response_obj self.__results_for_wrapper.failed_objects.extend(response_obj.errors.values()) self.__took_queue.append(time.time() - start) if (n_refs := len(refs)) > 0: start = time.time() try: response_ref = executor.result( self.__batch_rest.references(connection=self.__connection, references=refs) ) except Exception as e: errors_ref = { idx: ErrorReference( message=repr(e), reference=BatchReference._from_internal(ref) ) for idx, ref in enumerate(refs) } response_ref = BatchReferenceReturn( elapsed_seconds=time.time() - start, errors=errors_ref, has_errors=True, ) if (n_ref_errs := len(response_ref.errors)) > 0 and self.__refs_logs_count < 30: logger.error( { "message": f"Failed to send {n_ref_errs} references in a batch of {n_refs}. Please inspect client.batch.failed_references or collection.batch.failed_references for the failed references.", "errors": response_ref.errors, } ) self.__refs_logs_count += 1 if self.__refs_logs_count > 30: logger.error( { "message": "There have been more than 30 failed reference batches. Further errors will not be logged.", } ) with self.__results_lock: self.__results_for_wrapper.results.refs += response_ref self.__results_for_wrapper.failed_references.extend(response_ref.errors.values()) with self.__active_requests_lock: self.__active_requests -= 1 def flush(self) -> None: """Flush the batch queue and wait for all requests to be finished.""" # bg thread is sending objs+refs automatically, so simply wait for everything to be done while ( self.__active_requests > 0 or len(self.__batch_objects) > 0 or len(self.__batch_references) > 0 ): time.sleep(0.01) self.__check_bg_thread_alive() def _add_object( self, collection: str, properties: Optional[WeaviateProperties] = None, references: Optional[ReferenceInputs] = None, uuid: Optional[UUID] = None, vector: Optional[VECTORS] = None, tenant: Optional[str] = None, ) -> UUID: self.__check_bg_thread_alive() try: batch_object = BatchObject( collection=collection, properties=properties, references=references, uuid=uuid, vector=vector, tenant=tenant, index=self.__objs_count, ) self.__objs_count += 1 self.__results_for_wrapper.imported_shards.add( Shard(collection=collection, tenant=tenant) ) except ValidationError as e: raise WeaviateBatchValidationError(repr(e)) self.__uuid_lookup.add(str(batch_object.uuid)) self.__batch_objects.add(batch_object._to_internal()) # block if queue gets too long or weaviate is overloaded - reading files is faster them sending them so we do # not need a long queue while ( self.__recommended_num_objects == 0 or len(self.__batch_objects) >= self.__recommended_num_objects * 2 ): self.__check_bg_thread_alive() time.sleep(0.01) assert batch_object.uuid is not None return batch_object.uuid def _add_reference( self, from_object_uuid: UUID, from_object_collection: str, from_property_name: str, to: ReferenceInput, tenant: Optional[str] = None, ) -> None: self.__check_bg_thread_alive() if isinstance(to, ReferenceToMulti): to_strs: Union[List[str], List[UUID]] = to.uuids_str elif isinstance(to, str) or isinstance(to, uuid_package.UUID): to_strs = [to] else: to_strs = list(to) for uid in to_strs: try: batch_reference = BatchReference( from_object_collection=from_object_collection, from_object_uuid=from_object_uuid, from_property_name=from_property_name, to_object_collection=( to.target_collection if isinstance(to, ReferenceToMulti) else None ), to_object_uuid=uid, tenant=tenant, index=self.__refs_count, ) self.__refs_count += 1 except ValidationError as e: raise WeaviateBatchValidationError(repr(e)) self.__batch_references.add(batch_reference._to_internal()) # block if queue gets too long or weaviate is overloaded while self.__recommended_num_objects == 0: time.sleep(0.01) # block if weaviate is overloaded, also do not send any refs self.__check_bg_thread_alive() def __check_bg_thread_alive(self) -> None: if self.__bg_thread.is_alive(): return raise self.__bg_thread_exception or Exception("Batch thread died unexpectedly")
_BatchBase
python
huggingface__transformers
src/transformers/models/wavlm/modeling_wavlm.py
{ "start": 63613, "end": 69788 }
class ____(WavLMPreTrainedModel): def __init__(self, config): super().__init__(config) self.wavlm = WavLMModel(config) num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings if config.use_weighted_layer_sum: self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers) self.projector = nn.Linear(config.hidden_size, config.tdnn_dim[0]) tdnn_layers = [TDNNLayer(config, i) for i in range(len(config.tdnn_dim))] self.tdnn = nn.ModuleList(tdnn_layers) self.feature_extractor = nn.Linear(config.tdnn_dim[-1] * 2, config.xvector_output_dim) self.classifier = nn.Linear(config.xvector_output_dim, config.xvector_output_dim) self.objective = AMSoftmaxLoss(config.xvector_output_dim, config.num_labels) self.post_init() def freeze_feature_encoder(self): """ Calling this function will disable the gradient computation for the feature encoder so that its parameter will not be updated during training. """ self.wavlm.feature_extractor._freeze_parameters() def freeze_base_model(self): """ Calling this function will disable the gradient computation for the base model so that its parameters will not be updated during training. Only the classification head will be updated. """ for param in self.wavlm.parameters(): param.requires_grad = False def _get_tdnn_output_lengths(self, input_lengths: Union[torch.LongTensor, int]): """ Computes the output length of the TDNN layers """ def _conv_out_length(input_length, kernel_size, stride): # 1D convolutional layer output length formula taken # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html return (input_length - kernel_size) // stride + 1 for kernel_size in self.config.tdnn_kernel: input_lengths = _conv_out_length(input_lengths, kernel_size, 1) return input_lengths @auto_docstring def forward( self, input_values: Optional[torch.Tensor], attention_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, labels: Optional[torch.Tensor] = None, ) -> Union[tuple, XVectorOutput]: r""" input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or the soundfile library (`pip install soundfile`). To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion into a tensor of type `torch.FloatTensor`. See [`WavLMProcessor.__call__`] for details. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states outputs = self.wavlm( input_values, attention_mask=attention_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) if self.config.use_weighted_layer_sum: hidden_states = outputs[_HIDDEN_STATES_START_POSITION] hidden_states = torch.stack(hidden_states, dim=1) norm_weights = nn.functional.softmax(self.layer_weights, dim=-1) hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1) else: hidden_states = outputs[0] hidden_states = self.projector(hidden_states) for tdnn_layer in self.tdnn: hidden_states = tdnn_layer(hidden_states) # Statistic Pooling if attention_mask is None: mean_features = hidden_states.mean(dim=1) std_features = hidden_states.std(dim=1) else: feat_extract_output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(dim=1)) tdnn_output_lengths = self._get_tdnn_output_lengths(feat_extract_output_lengths) mean_features = [] std_features = [] for i, length in enumerate(tdnn_output_lengths): mean_features.append(hidden_states[i, :length].mean(dim=0)) std_features.append(hidden_states[i, :length].std(dim=0)) mean_features = torch.stack(mean_features) std_features = torch.stack(std_features) statistic_pooling = torch.cat([mean_features, std_features], dim=-1) output_embeddings = self.feature_extractor(statistic_pooling) logits = self.classifier(output_embeddings) loss = None if labels is not None: loss = self.objective(logits, labels) if not return_dict: output = (logits, output_embeddings) + outputs[_HIDDEN_STATES_START_POSITION:] return ((loss,) + output) if loss is not None else output return XVectorOutput( loss=loss, logits=logits, embeddings=output_embeddings, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) __all__ = [ "WavLMForAudioFrameClassification", "WavLMForCTC", "WavLMForSequenceClassification", "WavLMForXVector", "WavLMModel", "WavLMPreTrainedModel", ]
WavLMForXVector
python
donnemartin__interactive-coding-challenges
graphs_trees/tree_level_lists/test_tree_level_lists.py
{ "start": 18, "end": 1062 }
class ____(unittest.TestCase): def test_tree_level_lists(self): bst = BstLevelLists(Node(5)) bst.insert(3) bst.insert(8) bst.insert(2) bst.insert(4) bst.insert(1) bst.insert(7) bst.insert(6) bst.insert(9) bst.insert(10) bst.insert(11) levels = bst.create_level_lists() results_list = [] for level in levels: results = Results() for node in level: results.add_result(node) results_list.append(results) self.assertEqual(str(results_list[0]), '[5]') self.assertEqual(str(results_list[1]), '[3, 8]') self.assertEqual(str(results_list[2]), '[2, 4, 7, 9]') self.assertEqual(str(results_list[3]), '[1, 6, 10]') self.assertEqual(str(results_list[4]), '[11]') print('Success: test_tree_level_lists') def main(): test = TestTreeLevelLists() test.test_tree_level_lists() if __name__ == '__main__': main()
TestTreeLevelLists
python
ray-project__ray
python/ray/data/preprocessors/utils.py
{ "start": 1124, "end": 1669 }
class ____(BaseStatSpec): """Represents an AggregateFnV2 spec for a single column.""" def __init__( self, *, aggregator_fn: Union[AggregateFnV2, Callable[[str], AggregateFnV2]], post_process_fn: Callable = lambda x: x, post_key_fn: Callable[[str], str], column: Optional[str] = None, ): super().__init__( stat_fn=aggregator_fn, post_process_fn=post_process_fn, post_key_fn=post_key_fn, ) self.column = column
AggregateStatSpec
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pycodestyle/E30.py
{ "start": 5512, "end": 5680 }
class ____: """Class for minimal repo.""" def method(cls) -> None: pass @classmethod def cls_method(cls) -> None: pass # end # E301
Class
python
scipy__scipy
benchmarks/benchmarks/signal.py
{ "start": 2734, "end": 3203 }
class ____(Benchmark): param_names = ['mode', 'size'] params = [ ['full', 'valid', 'same'], [(a, b) for a, b in product((40, 200, 3000), repeat=2) if b < a] ] def setup(self, mode, size): rng = np.random.default_rng(1234) self.a = rng.standard_normal(size[0]) self.b = rng.standard_normal(size[1]) def time_convolve2d(self, mode, size): signal.oaconvolve(self.a, self.b, mode=mode)
OAConvolve
python
getsentry__sentry
fixtures/safe_migrations_apps/good_flow_safe_run_sql_with_run_sql_disabled_app/migrations/0001_initial.py
{ "start": 171, "end": 293 }
class ____(CheckedMigration): initial = True dependencies = [] operations = [SafeRunSQL("select 1;")]
Migration
python
scrapy__scrapy
tests/test_crawl.py
{ "start": 15329, "end": 33009 }
class ____: mockserver: MockServer @classmethod def setup_class(cls): cls.mockserver = MockServer() cls.mockserver.__enter__() @classmethod def teardown_class(cls): cls.mockserver.__exit__(None, None, None) async def _run_spider( self, spider_cls: type[Spider] ) -> tuple[LogCapture, list[Any], StatsCollector]: items = [] def _on_item_scraped(item): items.append(item) crawler = get_crawler(spider_cls) crawler.signals.connect(_on_item_scraped, signals.item_scraped) with LogCapture() as log: await maybe_deferred_to_future( crawler.crawl( self.mockserver.url("/status?n=200"), mockserver=self.mockserver ) ) assert crawler.stats return log, items, crawler.stats @inlineCallbacks def test_crawlspider_with_parse(self): crawler = get_crawler(CrawlSpiderWithParseMethod) with LogCapture() as log: yield crawler.crawl(mockserver=self.mockserver) assert "[parse] status 200 (foo: None)" in str(log) assert "[parse] status 201 (foo: None)" in str(log) assert "[parse] status 202 (foo: bar)" in str(log) @inlineCallbacks def test_crawlspider_with_async_callback(self): crawler = get_crawler(CrawlSpiderWithAsyncCallback) with LogCapture() as log: yield crawler.crawl(mockserver=self.mockserver) assert "[parse_async] status 200 (foo: None)" in str(log) assert "[parse_async] status 201 (foo: None)" in str(log) assert "[parse_async] status 202 (foo: bar)" in str(log) @inlineCallbacks def test_crawlspider_with_async_generator_callback(self): crawler = get_crawler(CrawlSpiderWithAsyncGeneratorCallback) with LogCapture() as log: yield crawler.crawl(mockserver=self.mockserver) assert "[parse_async_gen] status 200 (foo: None)" in str(log) assert "[parse_async_gen] status 201 (foo: None)" in str(log) assert "[parse_async_gen] status 202 (foo: bar)" in str(log) @inlineCallbacks def test_crawlspider_with_errback(self): crawler = get_crawler(CrawlSpiderWithErrback) with LogCapture() as log: yield crawler.crawl(mockserver=self.mockserver) assert "[parse] status 200 (foo: None)" in str(log) assert "[parse] status 201 (foo: None)" in str(log) assert "[parse] status 202 (foo: bar)" in str(log) assert "[errback] status 404" in str(log) assert "[errback] status 500" in str(log) assert "[errback] status 501" in str(log) @inlineCallbacks def test_crawlspider_process_request_cb_kwargs(self): crawler = get_crawler(CrawlSpiderWithProcessRequestCallbackKeywordArguments) with LogCapture() as log: yield crawler.crawl(mockserver=self.mockserver) assert "[parse] status 200 (foo: process_request)" in str(log) assert "[parse] status 201 (foo: process_request)" in str(log) assert "[parse] status 202 (foo: bar)" in str(log) @inlineCallbacks def test_async_def_parse(self): crawler = get_crawler(AsyncDefSpider) with LogCapture() as log: yield crawler.crawl( self.mockserver.url("/status?n=200"), mockserver=self.mockserver ) assert "Got response 200" in str(log) @pytest.mark.only_asyncio @inlineCallbacks def test_async_def_asyncio_parse(self): crawler = get_crawler( AsyncDefAsyncioSpider, { "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor" }, ) with LogCapture() as log: yield crawler.crawl( self.mockserver.url("/status?n=200"), mockserver=self.mockserver ) assert "Got response 200" in str(log) @pytest.mark.only_asyncio @deferred_f_from_coro_f async def test_async_def_asyncio_parse_items_list(self): log, items, _ = await self._run_spider(AsyncDefAsyncioReturnSpider) assert "Got response 200" in str(log) assert {"id": 1} in items assert {"id": 2} in items @pytest.mark.only_asyncio @inlineCallbacks def test_async_def_asyncio_parse_items_single_element(self): items = [] def _on_item_scraped(item): items.append(item) crawler = get_crawler(AsyncDefAsyncioReturnSingleElementSpider) crawler.signals.connect(_on_item_scraped, signals.item_scraped) with LogCapture() as log: yield crawler.crawl( self.mockserver.url("/status?n=200"), mockserver=self.mockserver ) assert "Got response 200" in str(log) assert {"foo": 42} in items @pytest.mark.only_asyncio @deferred_f_from_coro_f async def test_async_def_asyncgen_parse(self): log, _, stats = await self._run_spider(AsyncDefAsyncioGenSpider) assert "Got response 200" in str(log) itemcount = stats.get_value("item_scraped_count") assert itemcount == 1 @pytest.mark.only_asyncio @deferred_f_from_coro_f async def test_async_def_asyncgen_parse_loop(self): log, items, stats = await self._run_spider(AsyncDefAsyncioGenLoopSpider) assert "Got response 200" in str(log) itemcount = stats.get_value("item_scraped_count") assert itemcount == 10 for i in range(10): assert {"foo": i} in items @pytest.mark.only_asyncio @deferred_f_from_coro_f async def test_async_def_asyncgen_parse_exc(self): log, items, stats = await self._run_spider(AsyncDefAsyncioGenExcSpider) log = str(log) assert "Spider error processing" in log assert "ValueError" in log itemcount = stats.get_value("item_scraped_count") assert itemcount == 7 for i in range(7): assert {"foo": i} in items @pytest.mark.only_asyncio @deferred_f_from_coro_f async def test_async_def_asyncgen_parse_complex(self): _, items, stats = await self._run_spider(AsyncDefAsyncioGenComplexSpider) itemcount = stats.get_value("item_scraped_count") assert itemcount == 156 # some random items for i in [1, 4, 21, 22, 207, 311]: assert {"index": i} in items for i in [10, 30, 122]: assert {"index2": i} in items @pytest.mark.only_asyncio @deferred_f_from_coro_f async def test_async_def_asyncio_parse_reqs_list(self): log, *_ = await self._run_spider(AsyncDefAsyncioReqsReturnSpider) for req_id in range(3): assert f"Got response 200, req_id {req_id}" in str(log) @pytest.mark.only_not_asyncio @deferred_f_from_coro_f async def test_async_def_deferred_direct(self): _, items, _ = await self._run_spider(AsyncDefDeferredDirectSpider) assert items == [{"code": 200}] @pytest.mark.only_asyncio @deferred_f_from_coro_f async def test_async_def_deferred_wrapped(self): _, items, _ = await self._run_spider(AsyncDefDeferredWrappedSpider) assert items == [{"code": 200}] @deferred_f_from_coro_f async def test_async_def_deferred_maybe_wrapped(self): _, items, _ = await self._run_spider(AsyncDefDeferredMaybeWrappedSpider) assert items == [{"code": 200}] @inlineCallbacks def test_response_ssl_certificate_none(self): crawler = get_crawler(SingleRequestSpider) url = self.mockserver.url("/echo?body=test", is_secure=False) yield crawler.crawl(seed=url, mockserver=self.mockserver) assert crawler.spider.meta["responses"][0].certificate is None @inlineCallbacks def test_response_ssl_certificate(self): crawler = get_crawler(SingleRequestSpider) url = self.mockserver.url("/echo?body=test", is_secure=True) yield crawler.crawl(seed=url, mockserver=self.mockserver) cert = crawler.spider.meta["responses"][0].certificate assert isinstance(cert, Certificate) assert cert.getSubject().commonName == b"localhost" assert cert.getIssuer().commonName == b"localhost" @pytest.mark.xfail( reason="Responses with no body return early and contain no certificate" ) @inlineCallbacks def test_response_ssl_certificate_empty_response(self): crawler = get_crawler(SingleRequestSpider) url = self.mockserver.url("/status?n=200", is_secure=True) yield crawler.crawl(seed=url, mockserver=self.mockserver) cert = crawler.spider.meta["responses"][0].certificate assert isinstance(cert, Certificate) assert cert.getSubject().commonName == b"localhost" assert cert.getIssuer().commonName == b"localhost" @inlineCallbacks def test_dns_server_ip_address_none(self): crawler = get_crawler(SingleRequestSpider) url = self.mockserver.url("/status?n=200") yield crawler.crawl(seed=url, mockserver=self.mockserver) ip_address = crawler.spider.meta["responses"][0].ip_address assert ip_address is None @inlineCallbacks def test_dns_server_ip_address(self): crawler = get_crawler(SingleRequestSpider) url = self.mockserver.url("/echo?body=test") expected_netloc, _ = urlparse(url).netloc.split(":") yield crawler.crawl(seed=url, mockserver=self.mockserver) ip_address = crawler.spider.meta["responses"][0].ip_address assert isinstance(ip_address, IPv4Address) assert str(ip_address) == gethostbyname(expected_netloc) @inlineCallbacks def test_bytes_received_stop_download_callback(self): crawler = get_crawler(BytesReceivedCallbackSpider) yield crawler.crawl(mockserver=self.mockserver) assert crawler.spider.meta.get("failure") is None assert isinstance(crawler.spider.meta["response"], Response) assert crawler.spider.meta["response"].body == crawler.spider.meta.get( "bytes_received" ) assert ( len(crawler.spider.meta["response"].body) < crawler.spider.full_response_length ) @inlineCallbacks def test_bytes_received_stop_download_errback(self): crawler = get_crawler(BytesReceivedErrbackSpider) yield crawler.crawl(mockserver=self.mockserver) assert crawler.spider.meta.get("response") is None assert isinstance(crawler.spider.meta["failure"], Failure) assert isinstance(crawler.spider.meta["failure"].value, StopDownload) assert isinstance(crawler.spider.meta["failure"].value.response, Response) assert crawler.spider.meta[ "failure" ].value.response.body == crawler.spider.meta.get("bytes_received") assert ( len(crawler.spider.meta["failure"].value.response.body) < crawler.spider.full_response_length ) @inlineCallbacks def test_headers_received_stop_download_callback(self): crawler = get_crawler(HeadersReceivedCallbackSpider) yield crawler.crawl(mockserver=self.mockserver) assert crawler.spider.meta.get("failure") is None assert isinstance(crawler.spider.meta["response"], Response) assert crawler.spider.meta["response"].headers == crawler.spider.meta.get( "headers_received" ) @inlineCallbacks def test_headers_received_stop_download_errback(self): crawler = get_crawler(HeadersReceivedErrbackSpider) yield crawler.crawl(mockserver=self.mockserver) assert crawler.spider.meta.get("response") is None assert isinstance(crawler.spider.meta["failure"], Failure) assert isinstance(crawler.spider.meta["failure"].value, StopDownload) assert isinstance(crawler.spider.meta["failure"].value.response, Response) assert crawler.spider.meta[ "failure" ].value.response.headers == crawler.spider.meta.get("headers_received") @inlineCallbacks def test_spider_errback(self): failures = [] def eb(failure: Failure) -> Failure: failures.append(failure) return failure crawler = get_crawler(SingleRequestSpider) with LogCapture() as log: yield crawler.crawl( seed=self.mockserver.url("/status?n=400"), errback_func=eb ) assert len(failures) == 1 assert "HTTP status code is not handled or not allowed" in str(log) assert "Spider error processing" not in str(log) @inlineCallbacks def test_spider_errback_silence(self): failures = [] def eb(failure: Failure) -> None: failures.append(failure) crawler = get_crawler(SingleRequestSpider) with LogCapture() as log: yield crawler.crawl( seed=self.mockserver.url("/status?n=400"), errback_func=eb ) assert len(failures) == 1 assert "HTTP status code is not handled or not allowed" not in str(log) assert "Spider error processing" not in str(log) @inlineCallbacks def test_spider_errback_exception(self): def eb(failure: Failure) -> None: raise ValueError("foo") crawler = get_crawler(SingleRequestSpider) with LogCapture() as log: yield crawler.crawl( seed=self.mockserver.url("/status?n=400"), errback_func=eb ) assert "Spider error processing" in str(log) @inlineCallbacks def test_spider_errback_item(self): def eb(failure: Failure) -> Any: return {"foo": "bar"} crawler = get_crawler(SingleRequestSpider) with LogCapture() as log: yield crawler.crawl( seed=self.mockserver.url("/status?n=400"), errback_func=eb ) assert "HTTP status code is not handled or not allowed" not in str(log) assert "Spider error processing" not in str(log) assert "'item_scraped_count': 1" in str(log) @inlineCallbacks def test_spider_errback_request(self): def eb(failure: Failure) -> Request: return Request(self.mockserver.url("/")) crawler = get_crawler(SingleRequestSpider) with LogCapture() as log: yield crawler.crawl( seed=self.mockserver.url("/status?n=400"), errback_func=eb ) assert "HTTP status code is not handled or not allowed" not in str(log) assert "Spider error processing" not in str(log) assert "Crawled (200)" in str(log) @inlineCallbacks def test_spider_errback_downloader_error(self): failures = [] def eb(failure: Failure) -> Failure: failures.append(failure) return failure crawler = get_crawler(SingleRequestSpider) with LogCapture() as log: yield crawler.crawl( seed=self.mockserver.url("/drop?abort=1"), errback_func=eb ) assert len(failures) == 1 assert "Error downloading" in str(log) assert "Spider error processing" not in str(log) @inlineCallbacks def test_spider_errback_downloader_error_exception(self): def eb(failure: Failure) -> None: raise ValueError("foo") crawler = get_crawler(SingleRequestSpider) with LogCapture() as log: yield crawler.crawl( seed=self.mockserver.url("/drop?abort=1"), errback_func=eb ) assert "Error downloading" in str(log) assert "Spider error processing" in str(log) @inlineCallbacks def test_spider_errback_downloader_error_item(self): def eb(failure: Failure) -> Any: return {"foo": "bar"} crawler = get_crawler(SingleRequestSpider) with LogCapture() as log: yield crawler.crawl( seed=self.mockserver.url("/drop?abort=1"), errback_func=eb ) assert "HTTP status code is not handled or not allowed" not in str(log) assert "Spider error processing" not in str(log) assert "'item_scraped_count': 1" in str(log) @inlineCallbacks def test_spider_errback_downloader_error_request(self): def eb(failure: Failure) -> Request: return Request(self.mockserver.url("/")) crawler = get_crawler(SingleRequestSpider) with LogCapture() as log: yield crawler.crawl( seed=self.mockserver.url("/drop?abort=1"), errback_func=eb ) assert "HTTP status code is not handled or not allowed" not in str(log) assert "Spider error processing" not in str(log) assert "Crawled (200)" in str(log) @inlineCallbacks def test_raise_closespider(self): def cb(response): raise CloseSpider crawler = get_crawler(SingleRequestSpider) with LogCapture() as log: yield crawler.crawl(seed=self.mockserver.url("/"), callback_func=cb) assert "Closing spider (cancelled)" in str(log) assert "Spider error processing" not in str(log) @inlineCallbacks def test_raise_closespider_reason(self): def cb(response): raise CloseSpider("my_reason") crawler = get_crawler(SingleRequestSpider) with LogCapture() as log: yield crawler.crawl(seed=self.mockserver.url("/"), callback_func=cb) assert "Closing spider (my_reason)" in str(log) assert "Spider error processing" not in str(log)
TestCrawlSpider
python
google__jax
docs/sphinxext/jax_list_config_options.py
{ "start": 1749, "end": 5561 }
class ____(SphinxDirective): required_arguments = 0 optional_arguments = 0 has_content = False def run(self) -> List[nodes.Node]: from jax._src.config import config as jax_config config_options = sorted(jax_config.meta.items(), key=itemgetter(0)) result = [] for name, (opt_type, meta_args, meta_kwargs) in config_options: if name in _deprecations: continue holder = jax_config._value_holders[name] # Create target for linking target = nodes.target() target['ids'].append(name) result.append(target) # Create a section for this option option_section = nodes.section() option_section['ids'].append(name) option_section['classes'].append('config-option-section') # Create a title with the option name (important for TOC) title = nodes.title() title['classes'] = ['h4'] title += nodes.Text(name.replace("jax_", "").replace("_", " ").title()) option_section += title # Create a field list for side-by-side display field_list = nodes.field_list() field_list['classes'].append('config-field-list') # Add type information as a field item if opt_type == "enum": type_para = nodes.paragraph() emphasis_node = nodes.emphasis() emphasis_node += nodes.Text("Enum values: ") type_para += emphasis_node for i, value in enumerate(enum_values := meta_kwargs.get('enum_values', [])): type_para += nodes.literal(text=repr(value)) if i < len(enum_values) - 1: type_para += nodes.Text(", ") elif opt_type == "enum_class": type_para = nodes.paragraph() emphasis_node = nodes.emphasis() emphasis_node += nodes.Text("Enum values: ") type_para += emphasis_node enum_class = meta_kwargs.get('enum_class') members = enum_class.__members__ for i, value in enumerate(members.keys()): type_para += nodes.literal(text=value) if i < len(members) - 1: type_para += nodes.Text(", ") else: type_para = nodes.paragraph() type_para += nodes.literal(text=opt_type.__name__) field_list += create_field_item("Type", type_para) # Add default value information default_para = nodes.paragraph() default_para += nodes.literal(text=repr(holder.value)) field_list += create_field_item("Default Value", default_para) # Add configuration string information string_para = nodes.paragraph() string_para += nodes.literal(text=repr(name)) field_list += create_field_item("Configuration String", string_para) string_para = nodes.paragraph() string_para += nodes.literal(text=name.upper()) field_list += create_field_item("Environment Variable", string_para) # Add the field list to the section option_section += field_list # Add help text in a description box if (help_text := meta_kwargs.get('help')): help_para = nodes.paragraph() # logger.error(name) # logger.warning(help_text) # If we get here, help text seems valid - proceed with normal parsing # parsed = nodes.Text(help_text) help_para += self.parse_text_to_nodes(help_text) option_section += help_para result.append(option_section) # Add an extra paragraph to ensure proper separation result.append(nodes.paragraph()) result.append(nodes.paragraph()) # ensure new line return result def get_location(self) -> Any: return (self.env.docname, self.lineno) def setup(app): app.add_directive("list_config_options", ConfigOptionDirective) return { "version": "0.1", "parallel_read_safe": True, "parallel_write_safe": True, }
ConfigOptionDirective
python
lepture__authlib
authlib/oauth1/rfc5849/errors.py
{ "start": 776, "end": 1010 }
class ____(OAuth1Error): error = "insecure_transport" description = "OAuth 2 MUST utilize https." @classmethod def check(cls, uri): if not is_secure_transport(uri): raise cls()
InsecureTransportError
python
apache__airflow
providers/asana/src/airflow/providers/asana/operators/asana_tasks.py
{ "start": 1057, "end": 2381 }
class ____(BaseOperator): """ This operator can be used to create Asana tasks. .. seealso:: For more information on Asana optional task parameters: https://developers.asana.com/docs/create-a-task .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:AsanaCreateTaskOperator` :param conn_id: The Asana connection to use. :param name: Name of the Asana task. :param task_parameters: Any of the optional task creation parameters. See https://developers.asana.com/docs/create-a-task for a complete list. You must specify at least one of 'workspace', 'parent', or 'projects' either here or in the connection. """ def __init__( self, *, name: str, task_parameters: dict | None = None, conn_id: str = "asana_default", **kwargs, ) -> None: super().__init__(**kwargs) self.conn_id = conn_id self.name = name self.task_parameters = task_parameters def execute(self, context: Context) -> str: hook = AsanaHook(conn_id=self.conn_id) response = hook.create_task(self.name, self.task_parameters) self.log.info(response) return response["gid"]
AsanaCreateTaskOperator
python
getsentry__sentry
src/sentry/models/groupopenperiod.py
{ "start": 1419, "end": 10498 }
class ____(DefaultFieldsModel): """ A GroupOpenPeriod is a period of time where a group is considered "open", i.e. having a status that is not resolved. This is primarily used for detector-based issues to track the period of time that an issue is open for. """ __relocation_scope__ = RelocationScope.Excluded project = FlexibleForeignKey("sentry.Project") group = FlexibleForeignKey("sentry.Group") resolution_activity = FlexibleForeignKey( "sentry.Activity", null=True, on_delete=models.SET_NULL ) # if the user is not set, it's assumed to be the system user_id = HybridCloudForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete="SET_NULL") date_started = models.DateTimeField(default=timezone.now) date_ended = models.DateTimeField(null=True) data = models.JSONField(default=dict) class Meta: app_label = "sentry" db_table = "sentry_groupopenperiod" indexes = ( # get all open periods since a certain date models.Index(fields=("group", "date_started")), models.Index( models.F("data__pending_incident_detector_id"), name="data__pend_inc_detector_id_idx", ), ) constraints = ( ExclusionConstraint( name="exclude_overlapping_date_start_end", expressions=[ (models.F("group"), RangeOperators.EQUAL), ( TsTzRange( "date_started", "date_ended", RangeBoundary(inclusive_lower=True, inclusive_upper=True), ), RangeOperators.OVERLAPS, ), ], ), ) __repr__ = sane_repr("project_id", "group_id", "date_started", "date_ended", "user_id") def close_open_period( self, resolution_activity: Activity, resolution_time: datetime, ) -> None: if self.date_ended is not None: logger.warning("Open period is already closed", extra={"group_id": self.group.id}) return self.update( date_ended=resolution_time, resolution_activity=resolution_activity, user_id=resolution_activity.user_id, ) if get_group_type_by_type_id(self.group.type).detector_settings is not None: GroupOpenPeriodActivity.objects.create( group_open_period=self, type=OpenPeriodActivityType.CLOSED, ) def reopen_open_period(self) -> None: if self.date_ended is None: logger.warning("Open period is not closed", extra={"group_id": self.group.id}) return self.update(date_ended=None, resolution_activity=None, user_id=None) def get_last_checked_for_open_period(group: Group) -> datetime: from sentry.incidents.grouptype import MetricIssue from sentry.incidents.models.alert_rule import AlertRule event = group.get_latest_event() last_checked = group.last_seen if event and group.type == MetricIssue.type_id: alert_rule_id = event.data.get("contexts", {}).get("metric_alert", {}).get("alert_rule_id") if alert_rule_id: try: alert_rule = AlertRule.objects.get(id=alert_rule_id) now = timezone.now() last_checked = now - timedelta(seconds=alert_rule.snuba_query.time_window) except AlertRule.DoesNotExist: pass return last_checked def get_open_periods_for_group( group: Group, query_start: datetime | None = None, query_end: datetime | None = None, limit: int | None = None, ) -> BaseQuerySet[GroupOpenPeriod]: """ Get open periods for a group that overlap with the query time range. To overlap with [query_start, query_end], an open period must: 1. Start before the query ends 2. End after the query starts (or still be open) This covers all overlap cases: - Period starts before query and ends within query range - Period starts before query and ends after query (open period spans entire query range) - Period starts within query and ends within query (open period completely inside query range) - Period starts within query and ends after query - Period starts before query and is still open - Period starts within query and is still open """ if not should_create_open_periods(group.type): return GroupOpenPeriod.objects.none() if not query_start: # use whichever date is more recent to reduce the query range. first_seen could be > 90 days ago query_start = max(group.first_seen, timezone.now() - timedelta(days=90)) if not query_end: query_end = timezone.now() started_before_query_ends = Q(date_started__lte=query_end) ended_after_query_starts = Q(date_ended__gte=query_start) still_open = Q(date_ended__isnull=True) group_open_periods = ( GroupOpenPeriod.objects.filter( group=group, ) .filter(started_before_query_ends & (ended_after_query_starts | still_open)) .order_by("-date_started") ) return group_open_periods[:limit] def create_open_period(group: Group, start_time: datetime) -> None: # no-op if the group does not create open periods if not should_create_open_periods(group.type): return None latest_open_period = get_latest_open_period(group) if latest_open_period and latest_open_period.date_ended is None: logger.warning("Latest open period is not closed", extra={"group_id": group.id}) return # There are some historical cases where we log multiple regressions for the same group, # but we only want to create a new open period for the first regression with transaction.atomic(router.db_for_write(Group)): # Force a Group lock before the create to establish consistent lock ordering # This prevents deadlocks by ensuring we always acquire the Group lock first Group.objects.select_for_update().filter(id=group.id).first() # There are some historical cases where we log multiple regressions for the same group, # but we only want to create a new open period for the first regression open_period = GroupOpenPeriod.objects.create( group=group, project=group.project, date_started=start_time, date_ended=None, resolution_activity=None, ) # If we care about this group's activity, create activity entry if get_group_type_by_type_id(group.type).detector_settings is not None: GroupOpenPeriodActivity.objects.create( date_added=start_time, group_open_period=open_period, type=OpenPeriodActivityType.OPENED, value=group.priority, ) def update_group_open_period( group: Group, new_status: int, resolution_time: datetime | None = None, resolution_activity: Activity | None = None, ) -> None: """ Update an existing open period when the group is resolved or unresolved. On resolution, we set the date_ended to the resolution time and link the activity to the open period. On unresolved, we clear the date_ended and resolution_activity fields. This is only done if the group is unresolved manually without a regression. If the group is unresolved due to a regression, the open periods will be updated during ingestion. """ # if the group does not track open periods, this is a no-op if not should_create_open_periods(group.type): return None # If a group was missed during backfill, we can create a new open period for it on unresolve. if not has_any_open_period(group) and new_status == GroupStatus.UNRESOLVED: create_open_period(group, timezone.now()) return open_period = get_latest_open_period(group) if open_period is None: logger.warning("No open period found for group", extra={"group_id": group.id}) return if new_status == GroupStatus.RESOLVED: if resolution_activity is None or resolution_time is None: logger.warning( "Missing information to close open period", extra={"group_id": group.id}, ) return open_period.close_open_period( resolution_activity=resolution_activity, resolution_time=resolution_time, ) elif new_status == GroupStatus.UNRESOLVED: open_period.reopen_open_period() def has_any_open_period(group: Group) -> bool: return GroupOpenPeriod.objects.filter(group=group).exists() def get_latest_open_period(group: Group) -> GroupOpenPeriod | None: if not should_create_open_periods(group.type): return None return GroupOpenPeriod.objects.filter(group=group).order_by("-date_started").first()
GroupOpenPeriod
python
has2k1__plotnine
plotnine/scales/scale_stroke.py
{ "start": 1657, "end": 1711 }
class ____(scale_stroke_continuous): pass
scale_stroke
python
getsentry__sentry
src/sentry/integrations/slack/views/link_team.py
{ "start": 2269, "end": 3676 }
class ____(SlackLinkageView, LinkTeamView): """ Django view for linking team to slack channel. Creates an entry on ExternalActor table. """ def notify_on_success(self, channel_id: str, integration: RpcIntegration, message: str) -> None: try: client = SlackSdkClient(integration_id=integration.id) client.chat_postMessage(channel=channel_id, text=message) except SlackApiError: # whether or not we send a Slack message, the team was linked successfully pass def notify_team_already_linked( self, request: HttpRequest, channel_id: str, integration: RpcIntegration, team: Team ) -> HttpResponse: message = ALREADY_LINKED_MESSAGE.format(slug=team.slug) try: client = SlackSdkClient(integration_id=integration.id) client.chat_postMessage(channel=channel_id, text=message) except SlackApiError: # whether or not we send a Slack message, the team is already linked pass return render_to_response( "sentry/integrations/slack/post-linked-team.html", request=request, context={ "heading_text": ALREADY_LINKED_TITLE, "body_text": message, "channel_id": channel_id, "team_id": integration.external_id, }, )
SlackLinkTeamView
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_django/DJ008.py
{ "start": 2212, "end": 2512 }
class ____(Model): new_field = models.CharField(max_length=10) class Meta: abstract = True def __str__(self): return self.new_field @property def my_brand_new_property(self): return 1 def my_beautiful_method(self): return 2
AbstractTestModel3
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_checks/asset_checks_definition.py
{ "start": 485, "end": 2248 }
class ____(AssetsDefinition): """Defines a set of checks that are produced by the same op or op graph. AssetChecksDefinition should not be instantiated directly, but rather produced using the `@asset_check` decorator or `AssetChecksDefinition.create` method. """ @staticmethod def create( *, keys_by_input_name: Mapping[str, AssetKey], node_def: OpDefinition, check_specs_by_output_name: Mapping[str, AssetCheckSpec], can_subset: bool, resource_defs: Optional[Mapping[str, ResourceDefinition]] = None, ): """Create an AssetChecksDefinition.""" return AssetChecksDefinition( keys_by_input_name=keys_by_input_name, keys_by_output_name={}, node_def=node_def, partitions_def=None, partition_mappings=None, asset_deps=None, selected_asset_keys=None, can_subset=can_subset, resource_defs=resource_defs, group_names_by_key=None, metadata_by_key=None, tags_by_key=None, legacy_freshness_policies_by_key=None, backfill_policy=None, descriptions_by_key=None, check_specs_by_output_name=check_specs_by_output_name, selected_asset_check_keys=None, is_subset=False, owners_by_key=None, ) # This is still needed in a few places where we need to handle normal AssetsDefinition and # AssetChecksDefinition differently, but eventually those areas should be refactored and this should # be removed. def has_only_asset_checks(assets_def: AssetsDefinition) -> bool: return len(assets_def.keys) == 0 and len(assets_def.check_keys) > 0
AssetChecksDefinition
python
readthedocs__readthedocs.org
readthedocs/proxito/views/hosting.py
{ "start": 9999, "end": 10119 }
class ____(RemoveFieldsMixin, VersionSerializer): FIELDS_TO_REMOVE = [ "_links", ]
VersionAddonsSerializer
python
pydata__xarray
xarray/core/missing.py
{ "start": 2226, "end": 2588 }
class ____: """Generic interpolator class for normalizing interpolation methods""" cons_kwargs: dict[str, Any] call_kwargs: dict[str, Any] f: Callable method: str def __call__(self, x): return self.f(x, **self.call_kwargs) def __repr__(self): return f"{self.__class__.__name__}: method={self.method}"
BaseInterpolator
python
huggingface__transformers
src/transformers/models/convnextv2/modeling_convnextv2.py
{ "start": 5722, "end": 7743 }
class ____(nn.Module): """This corresponds to the `Block` class in the original implementation. There are two equivalent implementations: [DwConv, LayerNorm (channels_first), Conv, GELU,1x1 Conv]; all in (N, C, H, W) (2) [DwConv, Permute to (N, H, W, C), LayerNorm (channels_last), Linear, GELU, Linear]; Permute back The authors used (2) as they find it slightly faster in PyTorch. Args: config ([`ConvNextV2Config`]): Model configuration class. dim (`int`): Number of input channels. drop_path (`float`): Stochastic depth rate. Default: 0.0. """ def __init__(self, config, dim, drop_path=0): super().__init__() # depthwise conv self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim) self.layernorm = ConvNextV2LayerNorm(dim, eps=1e-6) # pointwise/1x1 convs, implemented with linear layers self.pwconv1 = nn.Linear(dim, 4 * dim) self.act = ACT2FN[config.hidden_act] self.grn = ConvNextV2GRN(4 * dim) self.pwconv2 = nn.Linear(4 * dim, dim) self.drop_path = ConvNextV2DropPath(drop_path) if drop_path > 0.0 else nn.Identity() def forward(self, features: torch.Tensor) -> torch.Tensor: residual = features features = self.dwconv(features) # (batch_size, num_channels, height, width) -> (batch_size, height, width, num_channels) features = features.permute(0, 2, 3, 1) features = self.layernorm(features) features = self.pwconv1(features) features = self.act(features) features = self.grn(features) features = self.pwconv2(features) # (batch_size, height, width, num_channels) -> (batch_size, num_channels, height, width) features = features.permute(0, 3, 1, 2) features = residual + self.drop_path(features) return features # Copied from transformers.models.convnext.modeling_convnext.ConvNextStage with ConvNeXT->ConvNeXTV2, ConvNext->ConvNextV2
ConvNextV2Layer
python
walkccc__LeetCode
solutions/3381. Maximum Subarray Sum With Length Divisible by K/3381.py
{ "start": 0, "end": 414 }
class ____: def maxSubarraySum(self, nums: list[int], k: int) -> int: ans = -math.inf prefix = 0 # minPrefix[i % k] := the minimum prefix sum of the first i numbers minPrefix = [math.inf] * k minPrefix[k - 1] = 0 for i, num in enumerate(nums): prefix += num ans = max(ans, prefix - minPrefix[i % k]) minPrefix[i % k] = min(minPrefix[i % k], prefix) return ans
Solution
python
falconry__falcon
falcon/_typing.py
{ "start": 7989, "end": 8190 }
class ____(Protocol[_AReqT]): """ASGI middleware with WebSocket request handler.""" async def process_request_ws(self, req: _AReqT, ws: WebSocket) -> None: ...
AsgiMiddlewareWithProcessRequestWs
python
great-expectations__great_expectations
great_expectations/expectations/expectation.py
{ "start": 83810, "end": 85637 }
class ____(BatchExpectation, ABC): """Base class for column aggregate Expectations. These types of Expectation produce an aggregate metric for a column, such as the mean, standard deviation, number of unique values, column type, etc. --Documentation-- - https://docs.greatexpectations.io/docs/guides/expectations/creating_custom_expectations/how_to_create_custom_column_aggregate_expectations/ Args: domain_keys (tuple): A tuple of the keys used to determine the domain of the expectation. success_keys (tuple): A tuple of the keys used to determine the success of the expectation. - A "column" key is required for column expectations. Raises: InvalidExpectationConfigurationError: If no `column` is specified """ # noqa: E501 # FIXME CoP column: StrictStr = Field(min_length=1, description=COLUMN_DESCRIPTION) row_condition: RowConditionType = None condition_parser: Union[ConditionParser, None] = None domain_keys: ClassVar[Tuple[str, ...]] = ( "batch_id", "column", "row_condition", "condition_parser", ) domain_type: ClassVar[MetricDomainTypes] = MetricDomainTypes.COLUMN class Config: @staticmethod def schema_extra(schema: Dict[str, Any], model: Type[ColumnAggregateExpectation]) -> None: BatchExpectation.Config.schema_extra(schema, model) schema["properties"]["metadata"]["properties"].update( { "domain_type": { "title": "Domain Type", "type": "string", "const": model.domain_type, "description": "Column Aggregate", } } )
ColumnAggregateExpectation
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/variables/variable_scope_test.py
{ "start": 2478, "end": 60782 }
class ____(test.TestCase): def tearDown(self): gc.collect() # This will only contain uncollectable garbage, i.e. reference cycles # involving objects with __del__ defined. self.assertEqual(0, len(gc.garbage)) @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testGetVar(self): vs = variable_scope._get_default_variable_store() v = vs.get_variable("v", [1]) v1 = vs.get_variable("v", [1]) self.assertIs(v, v1) @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testResource(self): vs = variable_scope._get_default_variable_store() v1 = vs.get_variable("v", [1], use_resource=True) self.assertTrue(isinstance(v1, resource_variable_ops.ResourceVariable)) @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testNameExists(self): vs = variable_scope._get_default_variable_store() # No check by default, so we can both create and get existing names. v = vs.get_variable("v", [1]) v1 = vs.get_variable("v", [1]) self.assertIs(v, v1) # When reuse is False, we fail when variables are already there. vs.get_variable("w", [1], reuse=False) # That's ok. with self.assertRaises(ValueError): vs.get_variable("v", [1], reuse=False) # That fails. # When reuse is True, we fail when variables are new. vs.get_variable("v", [1], reuse=True) # That's ok. with self.assertRaises(ValueError): vs.get_variable("u", [1], reuse=True) # That fails. @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testNamelessStore(self): vs = variable_scope._get_default_variable_store() vs.get_variable("v1", [2]) vs.get_variable("v2", [2]) expected_names = ["%s:0" % name for name in ["v1", "v2"]] self.assertEqual( set(expected_names), set(v.name for v in vs._vars.values())) # Not converted to use wrap_function because of # TypeError: Expected tf.group() expected Tensor arguments not 'None' with # type '<type 'NoneType'>' @test_util.run_in_graph_and_eager_modes def testVarScopeInitializer(self): init = init_ops.constant_initializer(0.3) with variable_scope.variable_scope("tower0") as tower: with variable_scope.variable_scope("foo", initializer=init): v = variable_scope.get_variable("v", []) self.evaluate(variables_lib.variables_initializer([v])) self.assertAllClose(self.evaluate(v.value()), 0.3) with variable_scope.variable_scope(tower, initializer=init): w = variable_scope.get_variable("w", []) self.evaluate(variables_lib.variables_initializer([w])) self.assertAllClose(self.evaluate(w.value()), 0.3) @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testVarScopeConstraint(self): constraint = lambda x: 0. * x with variable_scope.variable_scope("tower1") as tower: with variable_scope.variable_scope("foo", constraint=constraint): v = variable_scope.get_variable("v", []) self.assertEqual(v.constraint, constraint) with variable_scope.variable_scope(tower, constraint=constraint): w = variable_scope.get_variable("w", []) self.assertEqual(w.constraint, constraint) @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testVarScopeNestingError(self): with variable_scope.variable_scope("aa"): scope = variable_scope.variable_scope("bb") scope.__enter__() with variable_scope.variable_scope("cc"): with self.assertRaises(RuntimeError): scope.__exit__(None, None, None) scope.__exit__(None, None, None) # Not converted to use wrap_function because of # TypeError: Fetch argument <tf.Variable 'string:0' shape=() dtype=string> # has invalid type <class '...ResourceVariable'>, must be a string or Tensor. # (Can not convert a ResourceVariable into a Tensor or Operation.) @test_util.run_deprecated_v1 def testStringDefaultInitializer(self): with self.cached_session(): v = variable_scope.get_variable("string", shape=[], dtype=dtypes.string) variables_lib.global_variables_initializer().run() self.assertAllEqual(compat.as_bytes(self.evaluate(v)), b"") @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testVarScopeDType(self): with variable_scope.variable_scope("tower2") as tower: with variable_scope.variable_scope("foo", dtype=dtypes.float16): v = variable_scope.get_variable("v", []) self.assertEqual(v.dtype.base_dtype, dtypes.float16) with variable_scope.variable_scope(tower, dtype=dtypes.float16): w = variable_scope.get_variable("w", []) self.assertEqual(w.dtype.base_dtype, dtypes.float16) def testGetVariableInGraphNestedUnderEagerContext(self): with context.eager_mode(): @def_function.function def f(v): self.assertEqual(type(v), resource_variable_ops.ResourceVariable) var = variable_scope.get_variable("should_be_resource", []) f(var) def testEagerVariableStore(self): with context.eager_mode(): store = variable_scope.EagerVariableStore() with store.as_default(): v = variable_scope.get_variable("v", shape=(), trainable=True) w = variable_scope.get_variable("w", shape=(), trainable=False) self.assertTrue(v in store.variables()) self.assertTrue(w in store.variables()) self.assertTrue(v in store.trainable_variables()) self.assertFalse(w in store.trainable_variables()) self.assertFalse(v in store.non_trainable_variables()) self.assertTrue(w in store.non_trainable_variables()) # Test copying. new_store = store.copy() with new_store.as_default(): new_v = variable_scope.get_variable("v") new_w = variable_scope.get_variable("w") self.assertEqual(new_v.numpy(), v.numpy()) self.assertEqual(new_w.numpy(), w.numpy()) self.assertTrue(new_v in new_store.variables()) self.assertTrue(new_w in new_store.variables()) self.assertTrue(new_v in new_store.trainable_variables()) self.assertFalse(new_w in new_store.trainable_variables()) self.assertFalse(new_v in new_store.non_trainable_variables()) self.assertTrue(new_w in new_store.non_trainable_variables()) # Check that variables are separate instances. for v in store.variables(): v.assign(-1) for v in new_store.variables(): v.assign(1) for v in store.variables(): self.assertEqual(v.numpy(), -1) for v in new_store.variables(): self.assertEqual(v.numpy(), 1) # Not converted to use wrap_function because of # obtaining different results in the eager case compared to the graph one @test_util.run_in_graph_and_eager_modes def testEagerVariablesStoreAddsToCollections(self): store = variable_scope.EagerVariableStore() with store.as_default(): trainable = variable_scope.get_variable("v1", [], trainable=True) not_trainable = variable_scope.get_variable("v2", [], trainable=False) concat = variable_scope.get_variable( "v3", [], collections=[ops.GraphKeys.CONCATENATED_VARIABLES]) self.assertEqual( ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES), [trainable, not_trainable]) self.assertEqual( ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES), [trainable, concat]) self.assertEqual( ops.get_collection(ops.GraphKeys.CONCATENATED_VARIABLES), [concat]) def testEagerVariablesOutsideStoreNotAddedToCollections(self): with context.eager_mode(): variable_scope.get_variable("v1", [], trainable=True) variable_scope.get_variable("v2", [], trainable=False) self.assertFalse(ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)) self.assertFalse(ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES)) # Not converted to use wrap_function because of # TypeError: Expected tf.group() expected Tensor arguments not 'None' with # type '<type 'NoneType'>'. @test_util.run_in_graph_and_eager_modes def testInitFromNonTensorValue(self): v = variable_scope.get_variable("v4", initializer=4, dtype=dtypes.int32) self.evaluate(variables_lib.variables_initializer([v])) self.assertAllClose(self.evaluate(v.value()), 4) w = variable_scope.get_variable( "w4", initializer=numpy.array([1, 2, 3]), dtype=dtypes.int64) self.evaluate(variables_lib.variables_initializer([w])) self.assertAllClose(self.evaluate(w.value()), [1, 2, 3]) # A quirk to be revisited? error = ValueError if context.executing_eagerly() else TypeError with self.assertRaises(error): variable_scope.get_variable("x4", initializer={}) # Not converted to use wrap_function because of # InvalidArgumentError=: You must feed a value for placeholder tensor # 'ReadVariableOp/resource' with dtype resource @test_util.run_in_graph_and_eager_modes def testInitFromNonInitializer(self): # Test various dtypes with zeros initializer as following: types = [ dtypes.int8, dtypes.uint8, dtypes.int16, dtypes.uint16, dtypes.int32, dtypes.int64, dtypes.bool ] # Use different variable_name to distinguish various dtypes for (i, dtype) in enumerate(types): x = variable_scope.get_variable( name="xx%d" % i, shape=(3, 4), dtype=dtype) y = variable_scope.get_variable( name="yy%d" % i, shape=(3, 4), dtype=dtype, initializer=init_ops.zeros_initializer(dtype=dtype)) self.evaluate(variables_lib.global_variables_initializer()) self.assertAllEqual(self.evaluate(x.value()), self.evaluate(y.value())) # Not converted to use wrap_function because of # InvalidArgumentError: /job:moo/replica:0/task:0/device:CPU:0 unknown device. @test_util.run_deprecated_v1 def testVarScopeCachingDevice(self): with self.cached_session(): caching_device = "/job:moo" with variable_scope.variable_scope("tower"): with variable_scope.variable_scope( "caching", caching_device=caching_device): v = variable_scope.get_variable("v", []) self.assertTrue(v.value().device.startswith(caching_device)) with variable_scope.variable_scope("child"): v2 = variable_scope.get_variable("v", []) self.assertTrue(v2.value().device.startswith(caching_device)) with variable_scope.variable_scope("not_cached", caching_device=""): v2_not_cached = variable_scope.get_variable("v", []) self.assertFalse( v2_not_cached.value().device.startswith(caching_device)) with variable_scope.variable_scope( "not_cached_identity_device", caching_device=lambda op: op.device): v2_identity_device = variable_scope.get_variable("v", []) self.assertFalse( v2_identity_device.value().device.startswith(caching_device)) with variable_scope.variable_scope("we_will_do_it_live") as vs_live: vs_live.set_caching_device("/job:live") v_live = variable_scope.get_variable("v", []) self.assertTrue(v_live.value().device.startswith("/job:live")) v_tower = variable_scope.get_variable("v", []) self.assertFalse(v_tower.value().device.startswith(caching_device)) # Not converted to use wrap_function because of # AttributeError: Tensor.name is meaningless when eager execution is enabled. @test_util.run_in_graph_and_eager_modes def testVarScopeRegularizer(self): init = init_ops.constant_initializer(0.3) def regularizer1(v): return math_ops.reduce_mean(v) + 0.1 def regularizer2(v): return math_ops.reduce_mean(v) + 0.2 with variable_scope.variable_scope( "tower3", regularizer=regularizer1) as tower: with variable_scope.variable_scope("foo", initializer=init): v = variable_scope.get_variable("v", []) self.evaluate(variables_lib.variables_initializer([v])) losses = ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES) self.assertEqual(1, len(losses)) self.assertAllClose(self.evaluate(losses[0]), 0.4) with variable_scope.variable_scope(tower, initializer=init) as vs: u = variable_scope.get_variable("u", []) vs.set_regularizer(regularizer2) w = variable_scope.get_variable("w", []) # Next 3 variable not regularized to test disabling regularization. x = variable_scope.get_variable( "x", [], regularizer=variable_scope.no_regularizer) with variable_scope.variable_scope( "baz", regularizer=variable_scope.no_regularizer): y = variable_scope.get_variable("y", []) vs.set_regularizer(variable_scope.no_regularizer) z = variable_scope.get_variable("z", []) # Check results. losses = ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES) self.assertEqual(3, len(losses)) self.evaluate(variables_lib.variables_initializer([u, w, x, y, z])) self.assertAllClose(self.evaluate(losses[0]), 0.4) self.assertAllClose(self.evaluate(losses[1]), 0.4) self.assertAllClose(self.evaluate(losses[2]), 0.5) with variable_scope.variable_scope("foo", reuse=True): # reuse=True is for now only supported when eager execution is disabled. if not context.executing_eagerly(): v = variable_scope.get_variable("v", []) # "v" is already there, reused losses = ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES) self.assertEqual(3, len(losses)) # No new loss added. # Not converted to use wrap_function because of # ValueError: Tensor-typed variable initializers must either be wrapped in an # init_scope or callable... @test_util.run_in_graph_and_eager_modes def testInitializeFromValue(self): init = constant_op.constant(0.1) w = variable_scope.get_variable("v", initializer=init) self.evaluate(variables_lib.variables_initializer([w])) self.assertAllClose(self.evaluate(w.value()), 0.1) with self.assertRaisesRegex(ValueError, "shape"): # We disallow explicit shape specification when initializer is constant. variable_scope.get_variable("u", [1], initializer=init) with variable_scope.variable_scope("foo", initializer=init): # Constant initializer can be passed through scopes if needed. v = variable_scope.get_variable("v") self.evaluate(variables_lib.variables_initializer([v])) self.assertAllClose(self.evaluate(v.value()), 0.1) # Check that non-float32 initializer creates a non-float32 variable. init = constant_op.constant(1, dtype=dtypes.int32) t = variable_scope.get_variable("t", initializer=init) self.assertEqual(t.dtype.base_dtype, dtypes.int32) # Raise error if `initializer` dtype and `dtype` are not identical. with self.assertRaisesRegex(ValueError, "don't match"): variable_scope.get_variable("s", initializer=init, dtype=dtypes.float64) # Not converted to use wrap_function because of # TypeError: Fetch argument <tf.Variable 'v0:0' shape=(1,) dtype=float32> has # invalid type <class '...ops.resource_variable_ops.ResourceVariable'>, must # be a string or Tensor. (Can not convert a ResourceVariable into a Tensor or # Operation.) @test_util.run_deprecated_v1 def testControlDeps(self): with self.cached_session() as sess: v0 = variable_scope.get_variable( "v0", [1], initializer=init_ops.constant_initializer(0)) with ops.control_dependencies([v0.value()]): v1 = variable_scope.get_variable( "v1", [1], initializer=init_ops.constant_initializer(1)) add = v1 + v0 # v0 should be uninitialized. with self.assertRaisesRegex(errors.OpError, "uninitialized"): self.evaluate(v0) # We should be able to initialize and run v1 without initializing # v0, even if the variable was created with a control dep on v0. self.evaluate(v1.initializer) self.assertEqual(1, self.evaluate(v1)) # v0 should still be uninitialized. with self.assertRaisesRegex(errors.OpError, "uninitialized"): self.evaluate(v0) with self.assertRaisesRegex(errors.OpError, "uninitialized"): self.evaluate(add) # If we initialize v0 we should be able to run 'add'. self.evaluate(v0.initializer) self.evaluate(add) # Not converted to use wrap_function because of # AssertionError: True is not false (last assertFalse) @test_util.run_deprecated_v1 def testEnableResourceVariables(self): old = resource_variables_toggle._DEFAULT_USE_RESOURCE try: resource_variables_toggle.enable_resource_variables() self.assertIsInstance( variable_v1.VariableV1(1.0), resource_variable_ops.ResourceVariable) resource_variables_toggle.disable_resource_variables() self.assertNotIsInstance( variable_v1.VariableV1(1.0), resource_variable_ops.ResourceVariable) finally: resource_variables_toggle._DEFAULT_USE_RESOURCE = old # Not converted to use wrap_function because of # TypeError: Fetch argument None has invalid type <type 'NoneType'> @test_util.run_deprecated_v1 def testControlFlow(self): with self.cached_session() as sess: v0 = variable_scope.get_variable( "v0", [], initializer=init_ops.constant_initializer(0)) var_dict = {} # Call get_variable in each of the cond clauses. def var_in_then_clause(): v1 = variable_scope.get_variable( "v1", [1], initializer=init_ops.constant_initializer(1)) var_dict["v1"] = v1 return v1 + v0 def var_in_else_clause(): v2 = variable_scope.get_variable( "v2", [1], initializer=init_ops.constant_initializer(2)) var_dict["v2"] = v2 return v2 + v0 add = cond.cond( math_ops.less(v0, 10), var_in_then_clause, var_in_else_clause) v1 = var_dict["v1"] v2 = var_dict["v2"] # We should be able to initialize and run v1 and v2 without initializing # v0, even if the variable was created with a control dep on v0. self.evaluate(v1.initializer) self.assertEqual([1], self.evaluate(v1)) self.evaluate(v2.initializer) self.assertEqual([2], self.evaluate(v2)) # v0 should still be uninitialized. with self.assertRaisesRegex(errors.OpError, "uninitialized"): self.evaluate(v0) # We should not be able to run 'add' yet. with self.assertRaisesRegex(errors.OpError, "uninitialized"): self.evaluate(add) # If we initialize v0 we should be able to run 'add'. self.evaluate(v0.initializer) self.evaluate(add) # Not converted to use wrap_function because of # TypeError: Expected tf.group() expected Tensor arguments not 'None' with # type '<type 'NoneType'>'. @test_util.run_in_graph_and_eager_modes def testGetVariableScope(self): # Test the get_variable_scope() function and setting properties of result. init = init_ops.constant_initializer(0.3) with variable_scope.variable_scope("bar"): new_init1 = variable_scope.get_variable_scope().initializer self.assertEqual(new_init1, None) # Check that we can set initializer like this. variable_scope.get_variable_scope().set_initializer(init) v = variable_scope.get_variable("v", []) self.evaluate(variables_lib.variables_initializer([v])) self.assertAllClose(self.evaluate(v.value()), 0.3) if not context.executing_eagerly(): # Check that we can set reuse. variable_scope.get_variable_scope().reuse_variables() with self.assertRaises(ValueError): # Fail, w does not exist yet. variable_scope.get_variable("w", [1]) # Check that the set initializer goes away. new_init = variable_scope.get_variable_scope().initializer self.assertEqual(new_init, None) @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testVarScope(self): with variable_scope.variable_scope("tower4") as tower: self.assertEqual(tower.name, "tower4") with ops.name_scope("scope") as sc: self.assertEqual(sc, "tower4/scope/") with variable_scope.variable_scope("tower5"): with variable_scope.variable_scope("bar") as bar: self.assertEqual(bar.name, "tower5/bar") with ops.name_scope("scope") as sc: self.assertEqual(sc, "tower5/bar/scope/") with variable_scope.variable_scope("tower6"): with variable_scope.variable_scope(tower, reuse=True) as tower_shared: self.assertEqual(tower_shared.name, "tower4") with ops.name_scope("scope") as sc: self.assertEqual(sc, "tower6/tower4/scope/") @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testVarScopeNameScope(self): with ops.name_scope("testVarScopeNameScope1"): with variable_scope.variable_scope("tower") as tower: with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "testVarScopeNameScope1/tower/scope2/") if not context.executing_eagerly(): with variable_scope.variable_scope( tower): # Re-entering acts like another "tower". with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "testVarScopeNameScope1/tower_1/scope2/") with variable_scope.variable_scope( "tower"): # Re-entering by string acts the same. with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "testVarScopeNameScope1/tower_2/scope2/") with ops.name_scope("testVarScopeNameScope2"): with variable_scope.variable_scope("tower"): with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "testVarScopeNameScope2/tower/scope2/") if not context.executing_eagerly(): with variable_scope.variable_scope(tower): with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "testVarScopeNameScope2/tower_1/scope2/") root_var_scope = variable_scope.get_variable_scope() with ops.name_scope("testVarScopeNameScope3"): with variable_scope.variable_scope(root_var_scope): with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "testVarScopeNameScope3/scope2/") @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testVarScopeOriginalNameScope(self): with self.cached_session(): with ops.name_scope("scope1"): with variable_scope.variable_scope("tower") as tower: self.assertEqual(tower.original_name_scope, "scope1/tower/") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "scope1/tower/scope2/") with ops.name_scope("scope2"): with variable_scope.variable_scope(tower) as tower1: # Re-entering preserves original name scope. self.assertEqual(tower1.original_name_scope, "scope1/tower/") with ops.name_scope("foo") as sc2: self.assertEqual(sc2, "scope2/tower/foo/") # Test re-entering original name scope. with ops.name_scope(tower.original_name_scope): with ops.name_scope("bar") as sc3: self.assertEqual(sc3, "scope1/tower/bar/") with ops.name_scope("scope2"): with variable_scope.variable_scope(tower): with ops.name_scope(tower.original_name_scope): with ops.name_scope("bar") as sc3: self.assertEqual(sc3, "scope1/tower/bar_1/") @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testVarScopeObjectReuse(self): with self.cached_session(): vs = None with variable_scope.variable_scope("jump", reuse=True) as scope: vs = scope with variable_scope.variable_scope(vs) as jump: self.assertTrue(jump.reuse) with variable_scope.variable_scope(vs, reuse=True) as jump_reuse: self.assertTrue(jump_reuse.reuse) with variable_scope.variable_scope(vs, reuse=False) as jump_no_reuse: self.assertTrue(jump_no_reuse.reuse) # Inherited, cannot be undone. with variable_scope.variable_scope("jump", reuse=False) as scope: vs = scope with variable_scope.variable_scope(vs) as jump: self.assertFalse(jump.reuse) with variable_scope.variable_scope(vs, reuse=True) as jump_reuse: self.assertTrue(jump_reuse.reuse) with variable_scope.variable_scope(vs, reuse=False) as jump_no_reuse: self.assertFalse(jump_no_reuse.reuse) @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testVarScopeGetOrCreateReuse(self): with self.cached_session(): def test_value(value): x = constant_op.constant(value) with variable_scope.variable_scope( "testVarScopeGetOrCreateReuse_bar", reuse=variable_scope.AUTO_REUSE): _ = state_ops.assign(variable_scope.get_variable("var", []), x) with variable_scope.variable_scope( "testVarScopeGetOrCreateReuse_bar", reuse=variable_scope.AUTO_REUSE): _ = variable_scope.get_variable("var", []) self.assertEqual(value, self.evaluate(x)) test_value(42.) # Variable is created. test_value(13.) # Variable is reused hereafter. test_value(17.) @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testVarOpScope(self): with self.cached_session(): with ops.name_scope("testVarOpScope1"): with variable_scope.variable_scope("tower", "default", []): self.assertEqual( variable_scope.get_variable("w", []).name, "tower/w:0") with ops.name_scope("testVarOpScope2") as sc2: self.assertEqual(sc2, "testVarOpScope1/tower/testVarOpScope2/") with variable_scope.variable_scope("tower", "default", []): with self.assertRaises(ValueError): variable_scope.get_variable("w", []) with ops.name_scope("testVarOpScope2") as sc2: self.assertEqual(sc2, "testVarOpScope1/tower_1/testVarOpScope2/") with ops.name_scope("testVarOpScope2"): with variable_scope.variable_scope(None, "default", []): self.assertEqual( variable_scope.get_variable("w", []).name, "default/w:0") with ops.name_scope("testVarOpScope2") as sc2: self.assertEqual(sc2, "testVarOpScope2/default/testVarOpScope2/") with variable_scope.variable_scope(None, "default", []): self.assertEqual( variable_scope.get_variable("w", []).name, "default_1/w:0") with ops.name_scope("testVarOpScope2") as sc2: self.assertEqual(sc2, "testVarOpScope2/default_1/testVarOpScope2/") @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testVarOpScopeUniqueNamesInterleavedSubstringScopes(self): with self.cached_session(): with variable_scope.variable_scope(None, "defaultScope1"): with variable_scope.variable_scope(None, "layer"): self.assertEqual( variable_scope.get_variable("w", []).name, "defaultScope1/layer/w:0") with variable_scope.variable_scope(None, "defaultScope1"): with variable_scope.variable_scope(None, "layer"): self.assertEqual( variable_scope.get_variable("w", []).name, "defaultScope1_1/layer/w:0") with variable_scope.variable_scope(None, "defaultScope"): with variable_scope.variable_scope(None, "layer"): self.assertEqual( variable_scope.get_variable("w", []).name, "defaultScope/layer/w:0") with variable_scope.variable_scope(None, "defaultScope1"): with variable_scope.variable_scope(None, "layer"): self.assertEqual( variable_scope.get_variable("w", []).name, "defaultScope1_2/layer/w:0") @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testVarOpScopeUniqueNamesWithJump(self): with self.cached_session(): with variable_scope.variable_scope("default") as default: with variable_scope.variable_scope(None, "layer"): self.assertEqual( variable_scope.get_variable("w", []).name, "default/layer/w:0") with variable_scope.variable_scope(None, "layer"): self.assertEqual( variable_scope.get_variable("w", []).name, "default/layer_1/w:0") with variable_scope.variable_scope(default): pass # No matter the jump in the middle, unique numbering continues. with variable_scope.variable_scope(None, "layer"): self.assertEqual( variable_scope.get_variable("w", []).name, "default/layer_2/w:0") @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testVarOpScopeReuse(self): with self.cached_session(): with variable_scope.variable_scope("outer") as outer: with variable_scope.variable_scope("tower", "default", []): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/tower/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer/tower/scope2/") with variable_scope.variable_scope(None, "default", []): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/default/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer/default/scope2/") with variable_scope.variable_scope(outer, reuse=True) as outer: with variable_scope.variable_scope("tower", "default", []): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/tower/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer_1/tower/scope2/") with variable_scope.variable_scope(None, "default", []): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/default/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer_1/default/scope2/") @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testVarScopeGetVar(self): with self.cached_session(): with variable_scope.variable_scope("root"): with variable_scope.variable_scope("towerA") as tower_a: va = variable_scope.get_variable("v", [1]) self.assertEqual(va.name, "root/towerA/v:0") with variable_scope.variable_scope(tower_a, reuse=True): va2 = variable_scope.get_variable("v", [1]) self.assertIs(va2, va) with variable_scope.variable_scope("towerB"): vb = variable_scope.get_variable("v", [1]) self.assertEqual(vb.name, "root/towerB/v:0") with self.assertRaises(ValueError): with variable_scope.variable_scope("towerA"): va2 = variable_scope.get_variable("v", [1]) with variable_scope.variable_scope("towerA", reuse=True): va2 = variable_scope.get_variable("v", [1]) self.assertIs(va2, va) with variable_scope.variable_scope("foo"): with variable_scope.variable_scope("bar"): v = variable_scope.get_variable("v", [1]) self.assertEqual(v.name, "root/foo/bar/v:0") with variable_scope.variable_scope(tower_a, reuse=True): va3 = variable_scope.get_variable("v", [1]) self.assertIs(va, va3) with self.assertRaises(ValueError): with variable_scope.variable_scope(tower_a, reuse=True): with variable_scope.variable_scope("baz"): variable_scope.get_variable("v", [1]) with self.assertRaises(ValueError) as exc: with variable_scope.variable_scope(tower_a, reuse=True): variable_scope.get_variable("v", [2]) # Different shape. self.assertEqual("shape" in str(exc.exception), True) with self.assertRaises(ValueError) as exc: with variable_scope.variable_scope(tower_a, reuse=True): variable_scope.get_variable("v", [1], dtype=dtypes.int32) self.assertEqual("dtype" in str(exc.exception), True) @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testVarScopeOuterScope(self): with self.cached_session(): with variable_scope.variable_scope("outer") as outer: pass with variable_scope.variable_scope(outer): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer_1/scope2/") with variable_scope.variable_scope("default"): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/default/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer_1/default/scope2/") with variable_scope.variable_scope(outer, reuse=True): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer_2/scope2/") with variable_scope.variable_scope("default", reuse=True): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/default/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer_2/default/scope2/") @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testVarScopeNestedOuterScope(self): with self.cached_session(): with variable_scope.variable_scope("outer") as outer: with variable_scope.variable_scope(outer): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer/outer/scope2/") with variable_scope.variable_scope("default"): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/default/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer/default/scope2/") with variable_scope.variable_scope(outer, reuse=True): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer/outer_1/scope2/") with variable_scope.variable_scope("default", reuse=True): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/default/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer/default_1/scope2/") @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testVarOpScopeReuseParam(self): with self.cached_session(): with variable_scope.variable_scope("outer") as outer: with variable_scope.variable_scope("tower", "default", []): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/tower/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer/tower/scope2/") with variable_scope.variable_scope(None, "default", []): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/default/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer/default/scope2/") with variable_scope.variable_scope(outer) as outer: with variable_scope.variable_scope("tower", "default", reuse=True): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/tower/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer_1/tower/scope2/") outer.reuse_variables() with variable_scope.variable_scope(None, "default", []): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/default/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer_1/default/scope2/") @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testVarOpScopeReuseError(self): with self.cached_session(): with self.assertRaises(ValueError): with variable_scope.variable_scope(None, "default", reuse=True): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/tower/w:0") @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testVarOpScopeOuterScope(self): with self.cached_session(): with variable_scope.variable_scope("outer") as outer: pass with variable_scope.variable_scope(outer, "default", []): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer_1/scope2/") with variable_scope.variable_scope(None, "default", []): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/default/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer_1/default/scope2/") with variable_scope.variable_scope(outer, "default", reuse=True): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer_2/scope2/") outer.reuse_variables() with variable_scope.variable_scope(None, "default", []): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/default/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer_2/default/scope2/") @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testVarOpScopeNestedOuterScope(self): with self.cached_session(): with variable_scope.variable_scope("outer") as outer: with variable_scope.variable_scope(outer, "default", []): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer/outer/scope2/") with variable_scope.variable_scope(None, "default", []): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/default/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer/default/scope2/") with variable_scope.variable_scope(outer, "default", reuse=True): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer_1/scope2/") with variable_scope.variable_scope(None, "default", []): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/default/w:0") with ops.name_scope("scope2") as sc2: self.assertEqual(sc2, "outer_1/default/scope2/") @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testBasicWhenAuxiliaryNameScopeIsFalse(self): with self.cached_session(): with variable_scope.variable_scope( "scope", auxiliary_name_scope=False) as scope: self.assertEqual(scope.original_name_scope, "") self.assertEqual( variable_scope.get_variable("w", []).name, "scope/w:0") self.assertEqual(constant_op.constant([], name="c").name, "c:0") with variable_scope.variable_scope(scope, auxiliary_name_scope=False): self.assertEqual(scope.original_name_scope, "") self.assertEqual( variable_scope.get_variable("w1", []).name, "scope/w1:0") self.assertEqual(constant_op.constant([], name="c1").name, "c1:0") # Recheck: new name scope is NOT created before with ops.name_scope("scope"): self.assertEqual(constant_op.constant([], name="c").name, "scope/c:0") with variable_scope.variable_scope("outer"): with variable_scope.variable_scope( "inner", auxiliary_name_scope=False) as inner: self.assertEqual(inner.original_name_scope, "outer/") self.assertEqual( variable_scope.get_variable("w", []).name, "outer/inner/w:0") self.assertEqual( constant_op.constant([], name="c").name, "outer/c:0") with variable_scope.variable_scope( inner, auxiliary_name_scope=False) as inner1: self.assertEqual(inner1.original_name_scope, "outer/") self.assertEqual( variable_scope.get_variable("w1", []).name, "outer/inner/w1:0") self.assertEqual( constant_op.constant([], name="c1").name, "outer/c1:0") # Recheck: new name scope is NOT created before with ops.name_scope("inner"): self.assertEqual( constant_op.constant([], name="c").name, "outer/inner/c:0") @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testCreatedByDefaultNameWhenAuxiliaryNameScopeIsFalse(self): with self.cached_session(): with variable_scope.variable_scope( None, default_name="default", auxiliary_name_scope=False) as scope: self.assertEqual(scope.original_name_scope, "") self.assertEqual( variable_scope.get_variable("w", []).name, "default/w:0") self.assertEqual(constant_op.constant([], name="c").name, "c:0") # Recheck: new name scope is NOT created before with ops.name_scope("default"): self.assertEqual( constant_op.constant([], name="c").name, "default/c:0") with variable_scope.variable_scope("outer"): with variable_scope.variable_scope( None, default_name="default", auxiliary_name_scope=False) as inner: self.assertEqual(inner.original_name_scope, "outer/") self.assertEqual( variable_scope.get_variable("w", []).name, "outer/default/w:0") self.assertEqual( constant_op.constant([], name="c").name, "outer/c:0") # Recheck: new name scope is NOT created before with ops.name_scope("default"): self.assertEqual( constant_op.constant([], name="c").name, "outer/default/c:0") @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testReenterRootScopeWhenAuxiliaryNameScopeIsFalse(self): with self.cached_session(): root_scope = variable_scope.get_variable_scope() with variable_scope.variable_scope( root_scope, auxiliary_name_scope=False) as scope: self.assertEqual(scope.original_name_scope, "") self.assertEqual(variable_scope.get_variable("w", []).name, "w:0") self.assertEqual(constant_op.constant([], name="c").name, "c:0") with variable_scope.variable_scope("outer"): with variable_scope.variable_scope( root_scope, auxiliary_name_scope=False) as inner: self.assertEqual(inner.original_name_scope, "") self.assertEqual(variable_scope.get_variable("w1", []).name, "w1:0") self.assertEqual( constant_op.constant([], name="c1").name, "outer/c1:0") @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testAuxiliaryNameScopeIsInvalid(self): with self.cached_session(): with self.assertRaisesRegex(TypeError, "auxiliary_name_scope"): with variable_scope.variable_scope( None, default_name="scope", auxiliary_name_scope="invalid"): pass with self.assertRaisesRegex(TypeError, "auxiliary_name_scope"): with variable_scope.variable_scope( "scope", auxiliary_name_scope="invalid"): pass with variable_scope.variable_scope("scope") as scope: pass with self.assertRaisesRegex(TypeError, "auxiliary_name_scope"): with variable_scope.variable_scope( scope, auxiliary_name_scope="invalid"): pass @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testReuseScopeWithoutNameScopeCollision(self): # Github issue: #13429 with self.cached_session(): with variable_scope.variable_scope("outer"): with variable_scope.variable_scope("inner") as inner: pass with variable_scope.variable_scope( inner, auxiliary_name_scope=False) as scope: with ops.name_scope(scope.original_name_scope): self.assertEqual( variable_scope.get_variable("w", []).name, "outer/inner/w:0") self.assertEqual( constant_op.constant([], name="c").name, "outer/inner/c:0") with ops.name_scope("inner"): self.assertEqual( constant_op.constant([], name="c").name, "inner/c:0") with variable_scope.variable_scope("another"): with variable_scope.variable_scope( inner, auxiliary_name_scope=False) as scope1: with ops.name_scope(scope1.original_name_scope): self.assertEqual( variable_scope.get_variable("w1", []).name, "outer/inner/w1:0") self.assertEqual( constant_op.constant([], name="c1").name, "outer/inner/c1:0") with ops.name_scope("inner"): self.assertEqual( constant_op.constant([], name="c").name, "another/inner/c:0") # Not converted to use wrap_function because of # obtaining different results in the eager case compared to the graph one # (different assertions failing after wrapping, in both execution modes) @test_util.run_in_graph_and_eager_modes def testGetLocalVar(self): # Check that local variable respects naming. with variable_scope.variable_scope("outer") as outer: with variable_scope.variable_scope(outer, "default", []): local_var = variable_scope.get_local_variable( "w", [], collections=["foo"]) self.assertEqual(local_var.name, "outer/w:0") if not context.executing_eagerly(): # Since variable is local, it should be in the local variable collection # but not the trainable collection. self.assertIn(local_var, ops.get_collection(ops.GraphKeys.LOCAL_VARIABLES)) self.assertIn(local_var, ops.get_collection("foo")) self.assertNotIn(local_var, ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES)) # Check that local variable respects `reuse`. with variable_scope.variable_scope(outer, "default", reuse=True): self.assertEqual( variable_scope.get_local_variable("w", []).name, "outer/w:0") @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testSignatureGetVarVsGetLocalVar(self): """get_{local,}variable() must take the same list of args.""" arg_names = tf_inspect.getargspec(variable_scope.get_variable)[0] local_arg_names = tf_inspect.getargspec( variable_scope.get_local_variable)[0] self.assertEqual(arg_names, local_arg_names) @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testGetVarWithDevice(self): g = ops.Graph() varname_type = [] def device_func(op): if op.type in ["Variable", "VariableV2", "VarHandleOp"]: varname_type.append((op.name, op.get_attr("dtype"))) return "/device:GPU:0" with g.as_default(): with ops.device(device_func): _ = variable_scope.get_variable("x", (100, 200)) _ = variable_scope.get_variable( "y", dtype=dtypes.int64, initializer=numpy.arange(73)) self.assertEqual(varname_type[0], ("x", dtypes.float32)) self.assertEqual(varname_type[1], ("y", dtypes.int64)) # Not converted to use wrap_function because of # obtaining different results in the eager case compared to the graph one @test_util.run_deprecated_v1 def testGetCollection(self): with self.cached_session(): _ = variable_scope.get_variable("testGetCollection_a", []) _ = variable_scope.get_variable( "testGetCollection_b", [], trainable=False) with variable_scope.variable_scope("testGetCollection_foo_") as scope1: _ = variable_scope.get_variable("testGetCollection_a", []) _ = variable_scope.get_variable( "testGetCollection_b", [], trainable=False) self.assertEqual([ v.name for v in scope1.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES) ], ["testGetCollection_foo_/testGetCollection_a:0"]) self.assertEqual([ v.name for v in scope1.get_collection(ops.GraphKeys.GLOBAL_VARIABLES) ], [ "testGetCollection_foo_/testGetCollection_a:0", "testGetCollection_foo_/testGetCollection_b:0" ]) with variable_scope.variable_scope("testGetCollection_foo") as scope2: _ = variable_scope.get_variable("testGetCollection_a", []) _ = variable_scope.get_variable( "testGetCollection_b", [], trainable=False) self.assertEqual([ v.name for v in scope2.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES) ], ["testGetCollection_foo/testGetCollection_a:0"]) self.assertEqual([ v.name for v in scope2.get_collection(ops.GraphKeys.GLOBAL_VARIABLES) ], [ "testGetCollection_foo/testGetCollection_a:0", "testGetCollection_foo/testGetCollection_b:0" ]) scope = variable_scope.get_variable_scope() self.assertEqual([ v.name for v in scope.get_collection(ops.GraphKeys.GLOBAL_VARIABLES) ], [ "testGetCollection_a:0", "testGetCollection_b:0", "testGetCollection_foo_/testGetCollection_a:0", "testGetCollection_foo_/testGetCollection_b:0", "testGetCollection_foo/testGetCollection_a:0", "testGetCollection_foo/testGetCollection_b:0" ]) self.assertEqual([ v.name for v in scope.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES) ], [ "testGetCollection_a:0", "testGetCollection_foo_/testGetCollection_a:0", "testGetCollection_foo/testGetCollection_a:0" ]) # Not converted to use wrap_function because of # obtaining different results in the eager case compared to the graph one @test_util.run_deprecated_v1 def testGetTrainableVariablesWithGetVariable(self): with self.cached_session(): _ = variable_scope.get_variable("testGetTrainableVariables_a", []) with variable_scope.variable_scope( "testGetTrainableVariables_foo") as scope: _ = variable_scope.get_variable("testGetTrainableVariables_b", []) _ = variable_scope.get_variable( "testGetTrainableVariables_c", [], trainable=False) # sync `ON_READ` sets trainable=False _ = variable_scope.get_variable( "testGetTrainableVariables_d", [], synchronization=variable_scope.VariableSynchronization.ON_READ) self.assertEqual( [v.name for v in scope.trainable_variables()], ["testGetTrainableVariables_foo/testGetTrainableVariables_b:0"]) _ = variable_scope.get_variable( "testGetTrainableVariables_e", [], synchronization=variable_scope.VariableSynchronization.ON_READ, trainable=True) self.assertEqual([v.name for v in scope.trainable_variables()], [ "testGetTrainableVariables_foo/testGetTrainableVariables_b:0", "testGetTrainableVariables_foo/testGetTrainableVariables_e:0", ]) # All other sync values sets trainable=True _ = variable_scope.get_variable( "testGetTrainableVariables_f", [], synchronization=variable_scope.VariableSynchronization.ON_WRITE) self.assertEqual([v.name for v in scope.trainable_variables()], [ "testGetTrainableVariables_foo/testGetTrainableVariables_b:0", "testGetTrainableVariables_foo/testGetTrainableVariables_e:0", "testGetTrainableVariables_foo/testGetTrainableVariables_f:0", ]) # Not converted to use wrap_function because of # obtaining different results in the eager case compared to the graph one @test_util.run_deprecated_v1 def testGetTrainableVariablesWithVariable(self): with self.cached_session(): _ = variable_v1.VariableV1(1.0, name="testGetTrainableVariables_a") with variable_scope.variable_scope( "testGetTrainableVariables_foo") as scope: _ = variable_v1.VariableV1(1.0, name="testGetTrainableVariables_b") _ = variable_v1.VariableV1( 1.0, name="testGetTrainableVariables_c", trainable=False) # sync `ON_READ` sets trainable=False _ = variable_v1.VariableV1( 1.0, name="testGetTrainableVariables_d", synchronization=variable_scope.VariableSynchronization.ON_READ) self.assertEqual( [v.name for v in scope.trainable_variables()], ["testGetTrainableVariables_foo/testGetTrainableVariables_b:0"]) _ = variable_v1.VariableV1( 1.0, name="testGetTrainableVariables_e", synchronization=variable_scope.VariableSynchronization.ON_READ, trainable=True) self.assertEqual([v.name for v in scope.trainable_variables()], [ "testGetTrainableVariables_foo/testGetTrainableVariables_b:0", "testGetTrainableVariables_foo/testGetTrainableVariables_e:0", ]) # All other sync values sets trainable=True _ = variable_v1.VariableV1( 1.0, name="testGetTrainableVariables_f", synchronization=variable_scope.VariableSynchronization.ON_WRITE) self.assertEqual([v.name for v in scope.trainable_variables()], [ "testGetTrainableVariables_foo/testGetTrainableVariables_b:0", "testGetTrainableVariables_foo/testGetTrainableVariables_e:0", "testGetTrainableVariables_foo/testGetTrainableVariables_f:0", ]) # Not converted to use wrap_function because of # obtaining different results in the eager case compared to the graph one @test_util.run_deprecated_v1 def testGetGlobalVariables(self): with self.cached_session(): _ = variable_scope.get_variable("testGetGlobalVariables_a", []) with variable_scope.variable_scope("testGetGlobalVariables_foo") as scope: _ = variable_scope.get_variable("testGetGlobalVariables_b", []) self.assertEqual( [v.name for v in scope.global_variables()], ["testGetGlobalVariables_foo/" "testGetGlobalVariables_b:0"]) # Not converted to use wrap_function because of # obtaining different results in the eager case compared to the graph one @test_util.run_deprecated_v1 def testGetLocalVariables(self): with self.cached_session(): _ = variable_scope.get_variable( "a", [], collections=[ops.GraphKeys.LOCAL_VARIABLES]) with variable_scope.variable_scope("foo") as scope: _ = variable_scope.get_variable( "b", [], collections=[ops.GraphKeys.LOCAL_VARIABLES]) _ = variable_scope.get_variable("c", []) self.assertEqual([v.name for v in scope.local_variables()], ["foo/b:0"]) @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testGetVariableWithRefDtype(self): v = variable_scope.get_variable("v", shape=[3, 4], dtype=dtypes.float32) # Ensure it is possible to do get_variable with a _ref dtype passed in. _ = variable_scope.get_variable("w", shape=[5, 6], dtype=v.dtype) @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testGetVariableWithInitializerWhichTakesNoArgs(self): v = variable_scope.get_variable("foo", initializer=lambda: [2]) self.assertEqual(v.name, "foo:0") @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testGetVariableWithInitializerWhichTakesOptionalArgs(self): v = variable_scope.get_variable("foo", initializer=lambda x=True: [2]) self.assertEqual(v.name, "foo:0") @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testGetVariableWithInitializerWhichTakesUnprovidedArgsAndNoShape(self): with self.assertRaisesRegex( ValueError, "The initializer passed is not valid. It should be a callable with no " "arguments and the shape should not be provided or an instance of " "`tf.keras.initializers.*' and `shape` should be fully defined."): variable_scope.get_variable("foo", initializer=lambda x: [2]) @test_util.run_in_graph_and_eager_modes @run_inside_wrap_function_in_eager_mode def testTwoGraphs(self): def f(): g1 = ops.Graph() g2 = ops.Graph() with g1.as_default(): with g2.as_default(): with variable_scope.variable_scope("_"): pass self.assertRaisesRegex(ValueError, "'_' is not a valid (?:root )?scope name", f) def axis0_into1_partitioner(shape=None, **unused_kwargs): part = [1] * len(shape) return part def axis0_into2_partitioner(shape=None, **unused_kwargs): part = [1] * len(shape) part[0] = 2 return part def axis0_into3_partitioner(shape=None, **unused_kwargs): part = [1] * len(shape) part[0] = 3 return part
VariableScopeTest
python
sympy__sympy
bin/sympy_time_cache.py
{ "start": 55, "end": 3191 }
class ____(object): def __init__(self, name): self._name = name self._children = [] self._time = 0 def __str__(self): return "%s: %s" % (self._name, self._time) __repr__ = __str__ def add_child(self, node): self._children.append(node) def children(self): return self._children def child(self, i): return self.children()[i] def set_time(self, time): self._time = time def time(self): return self._time total_time = time def exclusive_time(self): return self.total_time() - sum(child.time() for child in self.children()) def name(self): return self._name def linearize(self): res = [self] for child in self.children(): res.extend(child.linearize()) return res def print_tree(self, level=0, max_depth=None): print(" "*level + str(self)) if max_depth is not None and max_depth <= level: return for child in self.children(): child.print_tree(level + 1, max_depth=max_depth) def print_generic(self, n=50, method="time"): slowest = sorted((getattr(node, method)(), node.name()) for node in self.linearize())[-n:] for time, name in slowest[::-1]: print("%s %s" % (time, name)) def print_slowest(self, n=50): self.print_generic(n=50, method="time") def print_slowest_exclusive(self, n=50): self.print_generic(n, method="exclusive_time") def write_cachegrind(self, f): if isinstance(f, str): f = open(f, "w") f.write("events: Microseconds\n") f.write("fl=sympyallimport\n") must_close = True else: must_close = False f.write("fn=%s\n" % self.name()) f.write("1 %s\n" % self.exclusive_time()) counter = 2 for child in self.children(): f.write("cfn=%s\n" % child.name()) f.write("calls=1 1\n") f.write("%s %s\n" % (counter, child.time())) counter += 1 f.write("\n\n") for child in self.children(): child.write_cachegrind(f) if must_close: f.close() pp = TreeNode(None) # We have to use pp since there is a sage function #called parent that gets imported seen = set() def new_import(name, globals={}, locals={}, fromlist=[]): global pp if name in seen: return old_import(name, globals, locals, fromlist) seen.add(name) node = TreeNode(name) pp.add_child(node) old_pp = pp pp = node #Do the actual import t1 = timeit.default_timer() module = old_import(name, globals, locals, fromlist) t2 = timeit.default_timer() node.set_time(int(1000000*(t2 - t1))) pp = old_pp return module old_import = __builtins__.__import__ __builtins__.__import__ = new_import old_sum = sum from sympy import * # noqa sum = old_sum sageall = pp.child(0) sageall.write_cachegrind("sympy.cachegrind") print("Timings saved. Do:\n$ kcachegrind sympy.cachegrind")
TreeNode
python
matplotlib__matplotlib
lib/matplotlib/projections/polar.py
{ "start": 19003, "end": 24723 }
class ____(maxis.YTick): """ A radial-axis tick. This subclass of `.YTick` provides radial ticks with some small modification to their re-positioning such that ticks are rotated based on axes limits. This results in ticks that are correctly perpendicular to the spine. Labels are also rotated to be perpendicular to the spine, when 'auto' rotation is enabled. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.label1.set_rotation_mode('anchor') self.label2.set_rotation_mode('anchor') def _determine_anchor(self, mode, angle, start): # Note: angle is the (spine angle - 90) because it's used for the tick # & text setup, so all numbers below are -90 from (normed) spine angle. if mode == 'auto': if start: if -90 <= angle <= 90: return 'left', 'center' else: return 'right', 'center' else: if -90 <= angle <= 90: return 'right', 'center' else: return 'left', 'center' else: if start: if angle < -68.5: return 'center', 'top' elif angle < -23.5: return 'left', 'top' elif angle < 22.5: return 'left', 'center' elif angle < 67.5: return 'left', 'bottom' elif angle < 112.5: return 'center', 'bottom' elif angle < 157.5: return 'right', 'bottom' elif angle < 202.5: return 'right', 'center' elif angle < 247.5: return 'right', 'top' else: return 'center', 'top' else: if angle < -68.5: return 'center', 'bottom' elif angle < -23.5: return 'right', 'bottom' elif angle < 22.5: return 'right', 'center' elif angle < 67.5: return 'right', 'top' elif angle < 112.5: return 'center', 'top' elif angle < 157.5: return 'left', 'top' elif angle < 202.5: return 'left', 'center' elif angle < 247.5: return 'left', 'bottom' else: return 'center', 'bottom' def update_position(self, loc): super().update_position(loc) axes = self.axes thetamin = axes.get_thetamin() thetamax = axes.get_thetamax() direction = axes.get_theta_direction() offset_rad = axes.get_theta_offset() offset = np.rad2deg(offset_rad) full = _is_full_circle_deg(thetamin, thetamax) if full: angle = (axes.get_rlabel_position() * direction + offset) % 360 - 90 tick_angle = 0 else: angle = (thetamin * direction + offset) % 360 - 90 if direction > 0: tick_angle = np.deg2rad(angle) else: tick_angle = np.deg2rad(angle + 180) text_angle = (angle + 90) % 180 - 90 # between -90 and +90. mode, user_angle = self._labelrotation if mode == 'auto': text_angle += user_angle else: text_angle = user_angle if full: ha = self.label1.get_horizontalalignment() va = self.label1.get_verticalalignment() else: ha, va = self._determine_anchor(mode, angle, direction > 0) self.label1.set_horizontalalignment(ha) self.label1.set_verticalalignment(va) self.label1.set_rotation(text_angle) marker = self.tick1line.get_marker() if marker == mmarkers.TICKLEFT: trans = mtransforms.Affine2D().rotate(tick_angle) elif marker == '_': trans = mtransforms.Affine2D().rotate(tick_angle + np.pi / 2) elif marker == mmarkers.TICKRIGHT: trans = mtransforms.Affine2D().scale(-1, 1).rotate(tick_angle) else: # Don't modify custom tick line markers. trans = self.tick1line._marker._transform self.tick1line._marker._transform = trans if full: self.label2.set_visible(False) self.tick2line.set_visible(False) angle = (thetamax * direction + offset) % 360 - 90 if direction > 0: tick_angle = np.deg2rad(angle) else: tick_angle = np.deg2rad(angle + 180) text_angle = (angle + 90) % 180 - 90 # between -90 and +90. mode, user_angle = self._labelrotation if mode == 'auto': text_angle += user_angle else: text_angle = user_angle ha, va = self._determine_anchor(mode, angle, direction < 0) self.label2.set_ha(ha) self.label2.set_va(va) self.label2.set_rotation(text_angle) marker = self.tick2line.get_marker() if marker == mmarkers.TICKLEFT: trans = mtransforms.Affine2D().rotate(tick_angle) elif marker == '_': trans = mtransforms.Affine2D().rotate(tick_angle + np.pi / 2) elif marker == mmarkers.TICKRIGHT: trans = mtransforms.Affine2D().scale(-1, 1).rotate(tick_angle) else: # Don't modify custom tick line markers. trans = self.tick2line._marker._transform self.tick2line._marker._transform = trans
RadialTick
python
airbytehq__airbyte
airbyte-integrations/connectors/source-webflow/source_webflow/webflow_to_airbyte_mapping.py
{ "start": 63, "end": 1257 }
class ____: """ The following disctionary is used for dynamically pulling the schema from Webflow, and mapping it to an Airbyte-compatible json-schema Webflow: https://developers.webflow.com/#get-collection-with-full-schema Airbyte/json-schema: https://docs.airbyte.com/understanding-airbyte/supported-data-types/ """ webflow_to_airbyte_mapping = { "Bool": {"type": ["null", "boolean"]}, "Date": { "type": ["null", "string"], "format": "date-time", }, "Email": { "type": ["null", "string"], }, "ImageRef": {"type": ["null", "object"], "additionalProperties": True}, "ItemRef": {"type": ["null", "string"]}, "ItemRefSet": {"type": ["null", "array"]}, "Link": {"type": ["null", "string"]}, "Number": {"type": ["null", "number"]}, "Option": {"type": ["null", "string"]}, "PlainText": {"type": ["null", "string"]}, "RichText": {"type": ["null", "string"]}, "User": {"type": ["null", "string"]}, "Video": {"type": ["null", "string"]}, "FileRef": {"type": ["null", "object"]}, }
WebflowToAirbyteMapping
python
getsentry__sentry
src/sentry/models/activity.py
{ "start": 1288, "end": 3507 }
class ____(BaseManager["Activity"]): def get_activities_for_group(self, group: Group, num: int) -> Sequence[Activity]: activities = [] activity_qs = self.filter(group=group).order_by("-datetime") # Check if 'initial_priority' is available initial_priority_value = group.get_event_metadata().get( "initial_priority", None ) or group.get_event_metadata().get("initial_priority", None) initial_priority = ( PriorityLevel(initial_priority_value).to_str() if initial_priority_value else None ) prev_sig = None sig = None # we select excess so we can filter dupes for item in activity_qs[: num * 2]: prev_sig = sig sig = (item.type, item.ident, item.user_id, item.data) if item.type == ActivityType.NOTE.value: activities.append(item) continue if sig != prev_sig: activities.append(item) activities.append( Activity( id=0, project=group.project, group=group, type=ActivityType.FIRST_SEEN.value, data={"priority": initial_priority}, datetime=group.first_seen, ) ) return activities[:num] def create_group_activity( self, group: Group, type: ActivityType, user: User | RpcUser | None = None, user_id: int | None = None, data: Mapping[str, Any] | None = None, send_notification: bool = True, datetime: datetime | None = None, ) -> Activity: if user: user_id = user.id activity_args = { "project_id": group.project_id, "group": group, "type": type.value, "data": data, } if user_id is not None: activity_args["user_id"] = user_id if datetime is not None: activity_args["datetime"] = datetime activity = self.create(**activity_args) if send_notification: activity.send_notification() return activity @region_silo_model
ActivityManager
python
numba__numba
numba/core/types/npytypes.py
{ "start": 19667, "end": 19876 }
class ____(Type): def __init__(self, *args, **kwargs): super(NumPyRandomBitGeneratorType, self).__init__(*args, **kwargs) self.name = 'NumPyRandomBitGeneratorType'
NumPyRandomBitGeneratorType
python
jazzband__django-polymorphic
example/orders/migrations/0001_initial.py
{ "start": 43, "end": 5200 }
class ____(migrations.Migration): dependencies = [("contenttypes", "0002_remove_content_type_name")] operations = [ migrations.CreateModel( name="Order", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("title", models.CharField(max_length=200, verbose_name="Title")), ], options={ "ordering": ("title",), "verbose_name": "Organisation", "verbose_name_plural": "Organisations", }, ), migrations.CreateModel( name="Payment", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("currency", models.CharField(default=b"USD", max_length=3)), ("amount", models.DecimalField(max_digits=10, decimal_places=2)), ], options={"verbose_name": "Payment", "verbose_name_plural": "Payments"}, ), migrations.CreateModel( name="BankPayment", fields=[ ( "payment_ptr", models.OneToOneField( parent_link=True, auto_created=True, primary_key=True, serialize=False, on_delete=models.CASCADE, to="orders.Payment", ), ), ("bank_name", models.CharField(max_length=100)), ("swift", models.CharField(max_length=20)), ], options={ "verbose_name": "Bank Payment", "verbose_name_plural": "Bank Payments", }, bases=("orders.payment",), ), migrations.CreateModel( name="CreditCardPayment", fields=[ ( "payment_ptr", models.OneToOneField( parent_link=True, auto_created=True, primary_key=True, serialize=False, on_delete=models.CASCADE, to="orders.Payment", ), ), ("card_type", models.CharField(max_length=10)), ( "expiry_month", models.PositiveSmallIntegerField( choices=[ (1, "jan"), (2, "feb"), (3, "mar"), (4, "apr"), (5, "may"), (6, "jun"), (7, "jul"), (8, "aug"), (9, "sep"), (10, "oct"), (11, "nov"), (12, "dec"), ] ), ), ("expiry_year", models.PositiveIntegerField()), ], options={ "verbose_name": "Credit Card Payment", "verbose_name_plural": "Credit Card Payments", }, bases=("orders.payment",), ), migrations.CreateModel( name="SepaPayment", fields=[ ( "payment_ptr", models.OneToOneField( parent_link=True, auto_created=True, primary_key=True, serialize=False, on_delete=models.CASCADE, to="orders.Payment", ), ), ("iban", models.CharField(max_length=34)), ("bic", models.CharField(max_length=11)), ], options={ "verbose_name": "Bank Payment", "verbose_name_plural": "Bank Payments", }, bases=("orders.payment",), ), migrations.AddField( model_name="payment", name="order", field=models.ForeignKey(to="orders.Order", on_delete=models.CASCADE), ), migrations.AddField( model_name="payment", name="polymorphic_ctype", field=models.ForeignKey( related_name="polymorphic_orders.payment_set+", editable=False, on_delete=models.CASCADE, to="contenttypes.ContentType", null=True, ), ), ]
Migration
python
astropy__astropy
astropy/coordinates/tests/test_representation_arithmetic.py
{ "start": 1731, "end": 18104 }
class ____: def setup_method(self): # Choose some specific coordinates, for which ``sum`` and ``dot`` # works out nicely. self.lon = Longitude(np.arange(0, 12.1, 2), u.hourangle) self.lat = Latitude(np.arange(-90, 91, 30), u.deg) self.distance = [5.0, 12.0, 4.0, 2.0, 4.0, 12.0, 5.0] * u.kpc self.spherical = SphericalRepresentation(self.lon, self.lat, self.distance) self.unit_spherical = self.spherical.represent_as(UnitSphericalRepresentation) self.cartesian = self.spherical.to_cartesian() def test_norm_spherical(self): norm_s = self.spherical.norm() assert isinstance(norm_s, u.Quantity) # Just to be sure, test against getting object arrays. assert norm_s.dtype.kind == "f" assert np.all(norm_s == self.distance) @pytest.mark.parametrize( "representation", ( PhysicsSphericalRepresentation, CartesianRepresentation, CylindricalRepresentation, ), ) def test_norm(self, representation): in_rep = self.spherical.represent_as(representation) norm_rep = in_rep.norm() assert isinstance(norm_rep, u.Quantity) assert_quantity_allclose(norm_rep, self.distance) def test_norm_unitspherical(self): norm_rep = self.unit_spherical.norm() assert norm_rep.unit == u.dimensionless_unscaled assert np.all(norm_rep == 1.0 * u.dimensionless_unscaled) @pytest.mark.parametrize( "representation", ( SphericalRepresentation, PhysicsSphericalRepresentation, CartesianRepresentation, CylindricalRepresentation, UnitSphericalRepresentation, ), ) def test_neg_pos(self, representation): in_rep = self.cartesian.represent_as(representation) pos_rep = +in_rep assert type(pos_rep) is type(in_rep) assert pos_rep is not in_rep assert np.all(representation_equal(pos_rep, in_rep)) neg_rep = -in_rep assert type(neg_rep) is type(in_rep) assert np.all(neg_rep.norm() == in_rep.norm()) in_rep_xyz = in_rep.to_cartesian().xyz assert_quantity_allclose( neg_rep.to_cartesian().xyz, -in_rep_xyz, atol=1.0e-10 * in_rep_xyz.unit ) def test_mul_div_spherical(self): s0 = self.spherical / (1.0 * u.Myr) assert isinstance(s0, SphericalRepresentation) assert s0.distance.dtype.kind == "f" assert np.all(s0.lon == self.spherical.lon) assert np.all(s0.lat == self.spherical.lat) assert np.all(s0.distance == self.distance / (1.0 * u.Myr)) s1 = (1.0 / u.Myr) * self.spherical assert isinstance(s1, SphericalRepresentation) assert np.all(representation_equal(s1, s0)) s2 = self.spherical * np.array([[1.0], [2.0]]) assert isinstance(s2, SphericalRepresentation) assert s2.shape == (2, self.spherical.shape[0]) assert np.all(s2.lon == self.spherical.lon) assert np.all(s2.lat == self.spherical.lat) assert np.all(s2.distance == self.spherical.distance * np.array([[1.0], [2.0]])) s3 = np.array([[1.0], [2.0]]) * self.spherical assert isinstance(s3, SphericalRepresentation) assert np.all(representation_equal(s3, s2)) s4 = -self.spherical assert isinstance(s4, SphericalRepresentation) assert quantity_allclose( s4.to_cartesian().xyz, -self.spherical.to_cartesian().xyz, atol=1e-15 * self.spherical.distance.unit, ) assert np.all(s4.distance == self.spherical.distance) s5 = +self.spherical assert s5 is not self.spherical assert np.all(representation_equal(s5, self.spherical)) @pytest.mark.parametrize( "representation", ( PhysicsSphericalRepresentation, CartesianRepresentation, CylindricalRepresentation, ), ) def test_mul_div(self, representation): in_rep = self.spherical.represent_as(representation) r1 = in_rep / (1.0 * u.Myr) assert isinstance(r1, representation) for component in in_rep.components: in_rep_comp = getattr(in_rep, component) r1_comp = getattr(r1, component) if in_rep_comp.unit == self.distance.unit: assert np.all(r1_comp == in_rep_comp / (1.0 * u.Myr)) else: assert np.all(r1_comp == in_rep_comp) r2 = np.array([[1.0], [2.0]]) * in_rep assert isinstance(r2, representation) assert r2.shape == (2, in_rep.shape[0]) assert_quantity_allclose(r2.norm(), self.distance * np.array([[1.0], [2.0]])) r3 = -in_rep assert_representation_allclose( r3.to_cartesian(), (in_rep * -1.0).to_cartesian(), atol=1e-5 * u.pc ) with pytest.raises(TypeError): in_rep * in_rep with pytest.raises(TypeError): {} * in_rep def test_mul_div_unit_spherical(self): s1 = self.unit_spherical * self.distance assert isinstance(s1, SphericalRepresentation) assert np.all(s1.lon == self.unit_spherical.lon) assert np.all(s1.lat == self.unit_spherical.lat) assert np.all(s1.distance == self.spherical.distance) s2 = self.unit_spherical / u.s assert isinstance(s2, SphericalRepresentation) assert np.all(s2.lon == self.unit_spherical.lon) assert np.all(s2.lat == self.unit_spherical.lat) assert np.all(s2.distance == 1.0 / u.s) u3 = -self.unit_spherical assert isinstance(u3, UnitSphericalRepresentation) assert_quantity_allclose(u3.lon, self.unit_spherical.lon + 180.0 * u.deg) assert np.all(u3.lat == -self.unit_spherical.lat) assert_quantity_allclose( u3.to_cartesian().xyz, -self.unit_spherical.to_cartesian().xyz, atol=1.0e-10 * u.dimensionless_unscaled, ) u4 = +self.unit_spherical assert isinstance(u4, UnitSphericalRepresentation) assert u4 is not self.unit_spherical assert np.all(representation_equal(u4, self.unit_spherical)) def test_add_sub_cartesian(self): c1 = self.cartesian + self.cartesian assert isinstance(c1, CartesianRepresentation) assert c1.x.dtype.kind == "f" assert np.all(representation_equal(c1, 2.0 * self.cartesian)) with pytest.raises(TypeError): self.cartesian + 10.0 * u.m with pytest.raises(u.UnitsError): self.cartesian + (self.cartesian / u.s) c2 = self.cartesian - self.cartesian assert isinstance(c2, CartesianRepresentation) assert np.all( representation_equal( c2, CartesianRepresentation(0.0 * u.m, 0.0 * u.m, 0.0 * u.m) ) ) c3 = self.cartesian - self.cartesian / 2.0 assert isinstance(c3, CartesianRepresentation) assert np.all(representation_equal(c3, self.cartesian / 2.0)) @pytest.mark.parametrize( "representation", ( PhysicsSphericalRepresentation, SphericalRepresentation, CylindricalRepresentation, ), ) def test_add_sub(self, representation): in_rep = self.cartesian.represent_as(representation) r1 = in_rep + in_rep assert isinstance(r1, representation) expected = 2.0 * in_rep for component in in_rep.components: assert_quantity_allclose( getattr(r1, component), getattr(expected, component) ) with pytest.raises(TypeError): 10.0 * u.m + in_rep with pytest.raises(u.UnitsError): in_rep + (in_rep / u.s) r2 = in_rep - in_rep assert isinstance(r2, representation) assert_representation_allclose( r2.to_cartesian(), CartesianRepresentation(0.0 * u.m, 0.0 * u.m, 0.0 * u.m), atol=1e-15 * u.kpc, ) r3 = in_rep - in_rep / 2.0 assert isinstance(r3, representation) expected = in_rep / 2.0 assert_representation_allclose(r3, expected) def test_add_sub_unit_spherical(self): s1 = self.unit_spherical + self.unit_spherical assert isinstance(s1, SphericalRepresentation) expected = 2.0 * self.unit_spherical for component in s1.components: assert_quantity_allclose( getattr(s1, component), getattr(expected, component) ) with pytest.raises(TypeError): 10.0 * u.m - self.unit_spherical with pytest.raises(u.UnitsError): self.unit_spherical + (self.unit_spherical / u.s) s2 = self.unit_spherical - self.unit_spherical / 2.0 assert isinstance(s2, SphericalRepresentation) expected = self.unit_spherical / 2.0 for component in s2.components: assert_quantity_allclose( getattr(s2, component), getattr(expected, component) ) @pytest.mark.parametrize( "representation", ( CartesianRepresentation, PhysicsSphericalRepresentation, SphericalRepresentation, CylindricalRepresentation, ), ) def test_sum_mean(self, representation): in_rep = self.spherical.represent_as(representation) r_sum = in_rep.sum() assert isinstance(r_sum, representation) expected = SphericalRepresentation( 90.0 * u.deg, 0.0 * u.deg, 14.0 * u.kpc ).represent_as(representation) for component in expected.components: exp_component = getattr(expected, component) assert_quantity_allclose( getattr(r_sum, component), exp_component, atol=1e-10 * exp_component.unit, ) r_mean = in_rep.mean() assert isinstance(r_mean, representation) expected = expected / len(in_rep) for component in expected.components: exp_component = getattr(expected, component) assert_quantity_allclose( getattr(r_mean, component), exp_component, atol=1e-10 * exp_component.unit, ) def test_sum_mean_unit_spherical(self): s_sum = self.unit_spherical.sum() assert isinstance(s_sum, SphericalRepresentation) expected = SphericalRepresentation( 90.0 * u.deg, 0.0 * u.deg, 3.0 * u.dimensionless_unscaled ) for component in expected.components: exp_component = getattr(expected, component) assert_quantity_allclose( getattr(s_sum, component), exp_component, atol=1e-10 * exp_component.unit, ) s_mean = self.unit_spherical.mean() assert isinstance(s_mean, SphericalRepresentation) expected = expected / len(self.unit_spherical) for component in expected.components: exp_component = getattr(expected, component) assert_quantity_allclose( getattr(s_mean, component), exp_component, atol=1e-10 * exp_component.unit, ) @pytest.mark.parametrize( "representation", ( CartesianRepresentation, PhysicsSphericalRepresentation, SphericalRepresentation, CylindricalRepresentation, ), ) def test_dot(self, representation): in_rep = self.cartesian.represent_as(representation) r_dot_r = in_rep.dot(in_rep) assert isinstance(r_dot_r, u.Quantity) assert r_dot_r.shape == in_rep.shape assert_quantity_allclose(np.sqrt(r_dot_r), self.distance) r_dot_r_rev = in_rep.dot(in_rep[::-1]) assert isinstance(r_dot_r_rev, u.Quantity) assert r_dot_r_rev.shape == in_rep.shape expected = [-25.0, -126.0, 2.0, 4.0, 2.0, -126.0, -25.0] * u.kpc**2 assert_quantity_allclose(r_dot_r_rev, expected) for axis in "xyz": project = CartesianRepresentation( *( (1.0 if axis == _axis else 0.0) * u.dimensionless_unscaled for _axis in "xyz" ) ) assert_quantity_allclose( in_rep.dot(project), getattr(self.cartesian, axis), atol=1.0 * u.upc ) with pytest.raises(TypeError): in_rep.dot(self.cartesian.xyz) def test_dot_unit_spherical(self): u_dot_u = self.unit_spherical.dot(self.unit_spherical) assert isinstance(u_dot_u, u.Quantity) assert u_dot_u.shape == self.unit_spherical.shape assert_quantity_allclose(u_dot_u, 1.0 * u.dimensionless_unscaled) cartesian = self.unit_spherical.to_cartesian() for axis in "xyz": project = CartesianRepresentation( *( (1.0 if axis == _axis else 0.0) * u.dimensionless_unscaled for _axis in "xyz" ) ) assert_quantity_allclose( self.unit_spherical.dot(project), getattr(cartesian, axis), atol=1.0e-10 ) @pytest.mark.parametrize( "representation", ( CartesianRepresentation, PhysicsSphericalRepresentation, SphericalRepresentation, CylindricalRepresentation, ), ) def test_cross(self, representation): in_rep = self.cartesian.represent_as(representation) r_cross_r = in_rep.cross(in_rep) assert isinstance(r_cross_r, representation) assert_quantity_allclose(r_cross_r.norm(), 0.0 * u.kpc**2, atol=1.0 * u.mpc**2) r_cross_r_rev = in_rep.cross(in_rep[::-1]) sep = angular_separation(self.lon, self.lat, self.lon[::-1], self.lat[::-1]) expected = self.distance * self.distance[::-1] * np.sin(sep) assert_quantity_allclose(r_cross_r_rev.norm(), expected, atol=1.0 * u.mpc**2) unit_vectors = CartesianRepresentation( [1.0, 0.0, 0.0] * u.one, [0.0, 1.0, 0.0] * u.one, [0.0, 0.0, 1.0] * u.one )[:, np.newaxis] r_cross_uv = in_rep.cross(unit_vectors) assert r_cross_uv.shape == (3, 7) assert_quantity_allclose( r_cross_uv.dot(unit_vectors), 0.0 * u.kpc, atol=1.0 * u.upc ) assert_quantity_allclose( r_cross_uv.dot(in_rep), 0.0 * u.kpc**2, atol=1.0 * u.mpc**2 ) zeros = np.zeros(len(in_rep)) * u.kpc expected = CartesianRepresentation( u.Quantity((zeros, -self.cartesian.z, self.cartesian.y)), u.Quantity((self.cartesian.z, zeros, -self.cartesian.x)), u.Quantity((-self.cartesian.y, self.cartesian.x, zeros)), ) # Comparison with spherical is hard since some distances are zero, # implying the angles are undefined. r_cross_uv_cartesian = r_cross_uv.to_cartesian() assert_representation_allclose(r_cross_uv_cartesian, expected, atol=1.0 * u.upc) # A final check, with the side benefit of ensuring __truediv__ and norm # work on multi-D representations. r_cross_uv_by_distance = r_cross_uv / self.distance uv_sph = unit_vectors.represent_as(UnitSphericalRepresentation) sep = angular_separation(self.lon, self.lat, uv_sph.lon, uv_sph.lat) assert_quantity_allclose(r_cross_uv_by_distance.norm(), np.sin(sep), atol=1e-9) with pytest.raises(TypeError): in_rep.cross(self.cartesian.xyz) def test_cross_unit_spherical(self): u_cross_u = self.unit_spherical.cross(self.unit_spherical) assert isinstance(u_cross_u, SphericalRepresentation) assert_quantity_allclose(u_cross_u.norm(), 0.0 * u.one, atol=1.0e-10 * u.one) u_cross_u_rev = self.unit_spherical.cross(self.unit_spherical[::-1]) assert isinstance(u_cross_u_rev, SphericalRepresentation) sep = angular_separation(self.lon, self.lat, self.lon[::-1], self.lat[::-1]) expected = np.sin(sep) assert_quantity_allclose(u_cross_u_rev.norm(), expected, atol=1.0e-10 * u.one)
TestArithmetic
python
doocs__leetcode
solution/2400-2499/2469.Convert the Temperature/Solution.py
{ "start": 0, "end": 135 }
class ____: def convertTemperature(self, celsius: float) -> List[float]: return [celsius + 273.15, celsius * 1.8 + 32]
Solution
python
scikit-learn__scikit-learn
sklearn/calibration.py
{ "start": 48230, "end": 61415 }
class ____(_BinaryClassifierCurveDisplayMixin): """Calibration curve (also known as reliability diagram) visualization. It is recommended to use :func:`~sklearn.calibration.CalibrationDisplay.from_estimator` or :func:`~sklearn.calibration.CalibrationDisplay.from_predictions` to create a `CalibrationDisplay`. All parameters are stored as attributes. Read more about calibration in the :ref:`User Guide <calibration>` and more about the scikit-learn visualization API in :ref:`visualizations`. For an example on how to use the visualization, see :ref:`sphx_glr_auto_examples_calibration_plot_calibration_curve.py`. .. versionadded:: 1.0 Parameters ---------- prob_true : ndarray of shape (n_bins,) The proportion of samples whose class is the positive class (fraction of positives), in each bin. prob_pred : ndarray of shape (n_bins,) The mean predicted probability in each bin. y_prob : ndarray of shape (n_samples,) Probability estimates for the positive class, for each sample. estimator_name : str, default=None Name of estimator. If None, the estimator name is not shown. pos_label : int, float, bool or str, default=None The positive class when calibration curve computed. If not `None`, this value is displayed in the x- and y-axes labels. .. versionadded:: 1.1 Attributes ---------- line_ : matplotlib Artist Calibration curve. ax_ : matplotlib Axes Axes with calibration curve. figure_ : matplotlib Figure Figure containing the curve. See Also -------- calibration_curve : Compute true and predicted probabilities for a calibration curve. CalibrationDisplay.from_predictions : Plot calibration curve using true and predicted labels. CalibrationDisplay.from_estimator : Plot calibration curve using an estimator and data. Examples -------- >>> from sklearn.datasets import make_classification >>> from sklearn.model_selection import train_test_split >>> from sklearn.linear_model import LogisticRegression >>> from sklearn.calibration import calibration_curve, CalibrationDisplay >>> X, y = make_classification(random_state=0) >>> X_train, X_test, y_train, y_test = train_test_split( ... X, y, random_state=0) >>> clf = LogisticRegression(random_state=0) >>> clf.fit(X_train, y_train) LogisticRegression(random_state=0) >>> y_prob = clf.predict_proba(X_test)[:, 1] >>> prob_true, prob_pred = calibration_curve(y_test, y_prob, n_bins=10) >>> disp = CalibrationDisplay(prob_true, prob_pred, y_prob) >>> disp.plot() <...> """ def __init__( self, prob_true, prob_pred, y_prob, *, estimator_name=None, pos_label=None ): self.prob_true = prob_true self.prob_pred = prob_pred self.y_prob = y_prob self.estimator_name = estimator_name self.pos_label = pos_label def plot(self, *, ax=None, name=None, ref_line=True, **kwargs): """Plot visualization. Extra keyword arguments will be passed to :func:`matplotlib.pyplot.plot`. Parameters ---------- ax : Matplotlib Axes, default=None Axes object to plot on. If `None`, a new figure and axes is created. name : str, default=None Name for labeling curve. If `None`, use `estimator_name` if not `None`, otherwise no labeling is shown. ref_line : bool, default=True If `True`, plots a reference line representing a perfectly calibrated classifier. **kwargs : dict Keyword arguments to be passed to :func:`matplotlib.pyplot.plot`. Returns ------- display : :class:`~sklearn.calibration.CalibrationDisplay` Object that stores computed values. """ self.ax_, self.figure_, name = self._validate_plot_params(ax=ax, name=name) info_pos_label = ( f"(Positive class: {self.pos_label})" if self.pos_label is not None else "" ) default_line_kwargs = {"marker": "s", "linestyle": "-"} if name is not None: default_line_kwargs["label"] = name line_kwargs = _validate_style_kwargs(default_line_kwargs, kwargs) ref_line_label = "Perfectly calibrated" existing_ref_line = ref_line_label in self.ax_.get_legend_handles_labels()[1] if ref_line and not existing_ref_line: self.ax_.plot([0, 1], [0, 1], "k:", label=ref_line_label) self.line_ = self.ax_.plot(self.prob_pred, self.prob_true, **line_kwargs)[0] # We always have to show the legend for at least the reference line self.ax_.legend(loc="lower right") xlabel = f"Mean predicted probability {info_pos_label}" ylabel = f"Fraction of positives {info_pos_label}" self.ax_.set(xlabel=xlabel, ylabel=ylabel) return self @classmethod def from_estimator( cls, estimator, X, y, *, n_bins=5, strategy="uniform", pos_label=None, name=None, ax=None, ref_line=True, **kwargs, ): """Plot calibration curve using a binary classifier and data. A calibration curve, also known as a reliability diagram, uses inputs from a binary classifier and plots the average predicted probability for each bin against the fraction of positive classes, on the y-axis. Extra keyword arguments will be passed to :func:`matplotlib.pyplot.plot`. Read more about calibration in the :ref:`User Guide <calibration>` and more about the scikit-learn visualization API in :ref:`visualizations`. .. versionadded:: 1.0 Parameters ---------- estimator : estimator instance Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline` in which the last estimator is a classifier. The classifier must have a :term:`predict_proba` method. X : {array-like, sparse matrix} of shape (n_samples, n_features) Input values. y : array-like of shape (n_samples,) Binary target values. n_bins : int, default=5 Number of bins to discretize the [0, 1] interval into when calculating the calibration curve. A bigger number requires more data. strategy : {'uniform', 'quantile'}, default='uniform' Strategy used to define the widths of the bins. - `'uniform'`: The bins have identical widths. - `'quantile'`: The bins have the same number of samples and depend on predicted probabilities. pos_label : int, float, bool or str, default=None The positive class when computing the calibration curve. By default, `estimators.classes_[1]` is considered as the positive class. .. versionadded:: 1.1 name : str, default=None Name for labeling curve. If `None`, the name of the estimator is used. ax : matplotlib axes, default=None Axes object to plot on. If `None`, a new figure and axes is created. ref_line : bool, default=True If `True`, plots a reference line representing a perfectly calibrated classifier. **kwargs : dict Keyword arguments to be passed to :func:`matplotlib.pyplot.plot`. Returns ------- display : :class:`~sklearn.calibration.CalibrationDisplay`. Object that stores computed values. See Also -------- CalibrationDisplay.from_predictions : Plot calibration curve using true and predicted labels. Examples -------- >>> import matplotlib.pyplot as plt >>> from sklearn.datasets import make_classification >>> from sklearn.model_selection import train_test_split >>> from sklearn.linear_model import LogisticRegression >>> from sklearn.calibration import CalibrationDisplay >>> X, y = make_classification(random_state=0) >>> X_train, X_test, y_train, y_test = train_test_split( ... X, y, random_state=0) >>> clf = LogisticRegression(random_state=0) >>> clf.fit(X_train, y_train) LogisticRegression(random_state=0) >>> disp = CalibrationDisplay.from_estimator(clf, X_test, y_test) >>> plt.show() """ y_prob, pos_label, name = cls._validate_and_get_response_values( estimator, X, y, response_method="predict_proba", pos_label=pos_label, name=name, ) return cls.from_predictions( y, y_prob, n_bins=n_bins, strategy=strategy, pos_label=pos_label, name=name, ref_line=ref_line, ax=ax, **kwargs, ) @classmethod def from_predictions( cls, y_true, y_prob, *, n_bins=5, strategy="uniform", pos_label=None, name=None, ax=None, ref_line=True, **kwargs, ): """Plot calibration curve using true labels and predicted probabilities. Calibration curve, also known as reliability diagram, uses inputs from a binary classifier and plots the average predicted probability for each bin against the fraction of positive classes, on the y-axis. Extra keyword arguments will be passed to :func:`matplotlib.pyplot.plot`. Read more about calibration in the :ref:`User Guide <calibration>` and more about the scikit-learn visualization API in :ref:`visualizations`. .. versionadded:: 1.0 Parameters ---------- y_true : array-like of shape (n_samples,) True labels. y_prob : array-like of shape (n_samples,) The predicted probabilities of the positive class. n_bins : int, default=5 Number of bins to discretize the [0, 1] interval into when calculating the calibration curve. A bigger number requires more data. strategy : {'uniform', 'quantile'}, default='uniform' Strategy used to define the widths of the bins. - `'uniform'`: The bins have identical widths. - `'quantile'`: The bins have the same number of samples and depend on predicted probabilities. pos_label : int, float, bool or str, default=None The positive class when computing the calibration curve. When `pos_label=None`, if `y_true` is in {-1, 1} or {0, 1}, `pos_label` is set to 1, otherwise an error will be raised. .. versionadded:: 1.1 name : str, default=None Name for labeling curve. ax : matplotlib axes, default=None Axes object to plot on. If `None`, a new figure and axes is created. ref_line : bool, default=True If `True`, plots a reference line representing a perfectly calibrated classifier. **kwargs : dict Keyword arguments to be passed to :func:`matplotlib.pyplot.plot`. Returns ------- display : :class:`~sklearn.calibration.CalibrationDisplay`. Object that stores computed values. See Also -------- CalibrationDisplay.from_estimator : Plot calibration curve using an estimator and data. Examples -------- >>> import matplotlib.pyplot as plt >>> from sklearn.datasets import make_classification >>> from sklearn.model_selection import train_test_split >>> from sklearn.linear_model import LogisticRegression >>> from sklearn.calibration import CalibrationDisplay >>> X, y = make_classification(random_state=0) >>> X_train, X_test, y_train, y_test = train_test_split( ... X, y, random_state=0) >>> clf = LogisticRegression(random_state=0) >>> clf.fit(X_train, y_train) LogisticRegression(random_state=0) >>> y_prob = clf.predict_proba(X_test)[:, 1] >>> disp = CalibrationDisplay.from_predictions(y_test, y_prob) >>> plt.show() """ pos_label_validated, name = cls._validate_from_predictions_params( y_true, y_prob, sample_weight=None, pos_label=pos_label, name=name ) prob_true, prob_pred = calibration_curve( y_true, y_prob, n_bins=n_bins, strategy=strategy, pos_label=pos_label ) disp = cls( prob_true=prob_true, prob_pred=prob_pred, y_prob=y_prob, estimator_name=name, pos_label=pos_label_validated, ) return disp.plot(ax=ax, ref_line=ref_line, **kwargs)
CalibrationDisplay
python
euske__pdfminer
pdfminer/layout.py
{ "start": 7799, "end": 8177 }
class ____(LTContainer): def __init__(self): LTContainer.__init__(self, (+INF, +INF, -INF, -INF)) return def add(self, obj): LTContainer.add(self, obj) self.set_bbox((min(self.x0, obj.x0), min(self.y0, obj.y0), max(self.x1, obj.x1), max(self.y1, obj.y1))) return ## LTTextContainer ##
LTExpandableContainer
python
getsentry__sentry
src/sentry/issues/priority.py
{ "start": 646, "end": 5988 }
class ____(StrEnum): ESCALATING = "escalating" ONGOING = "ongoing" ISSUE_PLATFORM = "issue_platform" PRIORITY_TO_GROUP_HISTORY_STATUS = { PriorityLevel.HIGH: GroupHistoryStatus.PRIORITY_HIGH, PriorityLevel.MEDIUM: GroupHistoryStatus.PRIORITY_MEDIUM, PriorityLevel.LOW: GroupHistoryStatus.PRIORITY_LOW, } def update_priority( group: Group, priority: PriorityLevel | None, sender: str, reason: PriorityChangeReason | None = None, actor: User | RpcUser | None = None, project: Project | None = None, is_regression: bool = False, ) -> None: """ Update the priority of a group and record the change in the activity and group history. """ from sentry.incidents.grouptype import MetricIssue from sentry.models.groupopenperiod import get_latest_open_period, should_create_open_periods from sentry.models.groupopenperiodactivity import ( GroupOpenPeriodActivity, OpenPeriodActivityType, ) from sentry.workflow_engine.models.incident_groupopenperiod import ( update_incident_activity_based_on_group_activity, ) if priority is None or group.priority == priority: return previous_priority = PriorityLevel(group.priority) if group.priority is not None else None group.update(priority=priority) Activity.objects.create_group_activity( group=group, type=ActivityType.SET_PRIORITY, user=actor, data={ "priority": priority.to_str(), "reason": reason, }, ) record_group_history(group, status=PRIORITY_TO_GROUP_HISTORY_STATUS[priority], actor=actor) # TODO (aci cleanup): if the group corresponds to a metric issue, then update its incident activity # we will remove this once we've fully deprecated the Incident model if group.type == MetricIssue.type_id: update_incident_activity_based_on_group_activity(group, priority) issue_update_priority.send_robust( group=group, project=project, new_priority=priority.to_str(), previous_priority=previous_priority.to_str() if previous_priority else None, user_id=actor.id if actor else None, reason=reason.value if reason else None, sender=sender, ) # create a row in the GroupOpenPeriodActivity table open_period = get_latest_open_period(group) if open_period is None: if should_create_open_periods(group.type): metrics.incr("issues.priority.no_open_period_found") logger.error("No open period found for group", extra={"group_id": group.id}) return if is_regression: try: activity_entry_to_update = GroupOpenPeriodActivity.objects.get( group_open_period=open_period, type=OpenPeriodActivityType.OPENED ) activity_entry_to_update.update(value=priority) except GroupOpenPeriodActivity.DoesNotExist: # in case the rollout somehow goes out between open period creation and priority update metrics.incr("issues.priority.open_period_activity_race_condition") GroupOpenPeriodActivity.objects.create( date_added=open_period.date_started, group_open_period=open_period, type=OpenPeriodActivityType.OPENED, value=priority, ) else: # make a new activity entry GroupOpenPeriodActivity.objects.create( group_open_period=open_period, type=OpenPeriodActivityType.STATUS_CHANGE, value=priority, ) def get_priority_for_escalating_group(group: Group) -> PriorityLevel: """ Get the priority for a group that is escalating by incrementing it one level. """ if group.priority and group.priority == PriorityLevel.LOW: return PriorityLevel.MEDIUM return PriorityLevel.HIGH def get_initial_priority(group: Group) -> PriorityLevel | None: initial_priority = group.data.get("metadata", {}).get( "initial_priority", None ) or group.data.get("initial_priority", None) return PriorityLevel(initial_priority) if initial_priority else None def get_priority_for_ongoing_group(group: Group) -> PriorityLevel | None: # Fall back to the initial priority new_priority = get_initial_priority(group) if not new_priority: logger.error( "get_priority_for_ongoing_group.initial_priority_not_found", extra={"group": group.id}, ) return None return new_priority def auto_update_priority(group: Group, reason: PriorityChangeReason) -> None: """ Update the priority of a group due to state changes. """ if group.priority_locked_at is not None: return None new_priority = None if reason == PriorityChangeReason.ESCALATING: new_priority = get_priority_for_escalating_group(group) elif reason == PriorityChangeReason.ONGOING: new_priority = get_priority_for_ongoing_group(group) if new_priority is not None and new_priority != group.priority: update_priority( group=group, priority=new_priority, sender="auto_update_priority", reason=reason, actor=None, project=group.project, )
PriorityChangeReason
python
pytest-dev__pytest-django
pytest_django/runner.py
{ "start": 98, "end": 1393 }
class ____: """A Django test runner which uses pytest to discover and run tests when using `manage.py test`.""" def __init__( self, *, verbosity: int = 1, failfast: bool = False, keepdb: bool = False, **kwargs: Any, # noqa: ARG002 ) -> None: self.verbosity = verbosity self.failfast = failfast self.keepdb = keepdb @classmethod def add_arguments(cls, parser: ArgumentParser) -> None: parser.add_argument( "--keepdb", action="store_true", help="Preserves the test DB between runs." ) def run_tests( self, test_labels: Iterable[str], **kwargs: Any, # noqa: ARG002 ) -> int: """Run pytest and return the exitcode. It translates some of Django's test command option to pytest's. """ import pytest argv = [] if self.verbosity == 0: argv.append("--quiet") elif self.verbosity >= 2: verbosity = "v" * (self.verbosity - 1) argv.append(f"-{verbosity}") if self.failfast: argv.append("--exitfirst") if self.keepdb: argv.append("--reuse-db") argv.extend(test_labels) return pytest.main(argv)
TestRunner
python
getsentry__sentry
src/sentry/backup/findings.py
{ "start": 221, "end": 864 }
class ____(NamedTuple): """Every entry in the generated backup JSON file should have a unique model+ordinal combination, which serves as its identifier.""" model: str # The order that this model appeared in the JSON inputs. Because we validate that the same # number of models of each kind are present on both the left and right side when validating, we # can use the ordinal as a unique identifier. ordinal: int | None = None def pretty(self) -> str: out = f"InstanceID(model: {self.model!r}" if self.ordinal: out += f", ordinal: {self.ordinal}" return out + ")"
InstanceID
python
kamyu104__LeetCode-Solutions
Python/escape-the-ghosts.py
{ "start": 29, "end": 340 }
class ____(object): def escapeGhosts(self, ghosts, target): """ :type ghosts: List[List[int]] :type target: List[int] :rtype: bool """ total = abs(target[0])+abs(target[1]) return all(total < abs(target[0]-i)+abs(target[1]-j) for i, j in ghosts)
Solution
python
pytorch__pytorch
torch/fx/experimental/proxy_tensor.py
{ "start": 58973, "end": 64115 }
class ____(TorchDispatchMode): # Ensure this is read-only; this exists only for legacy reasons @property def enable_tracing(self) -> bool: return True def __init__( self, tracer: _ProxyTracer, tracing_mode: str, pre_dispatch: bool = False, _allow_fake_constant: bool = False, _error_on_data_dependent_ops: bool = True, ) -> None: dk = torch._C.DispatchKey.PreDispatch if pre_dispatch else None super().__init__(dk) self.tracer = tracer self.tracing_mode = tracing_mode self.pre_dispatch = pre_dispatch self._allow_fake_constant = _allow_fake_constant self._error_on_data_dependent_ops = _error_on_data_dependent_ops # Indicates to our torch_dispatch dispatching infra that # this is an "infra" mode with lower dispatching precedence. self._mode_key = torch._C._TorchDispatchModeKey.PROXY # Every time we enter a mode, we maintain a stack telling us what the previous # ProxyTorchDispatchMode state was (if there was any). # This lets us properly reset the state on exit. self.enter_stack: list[Optional[ProxyTorchDispatchMode]] = [] self.decomp_layers: int = 0 from torch._inductor import config self.emulate_precision_casts: bool = config.emulate_precision_casts @count def __torch_dispatch__( self, func: OpOverload, types: tuple[torch._C._TensorMeta, ...], args: tuple[object, ...] = (), kwargs: Optional[dict[str, object]] = None, ) -> object: with set_original_aten_op(func): kwargs = kwargs or {} if func == prim.device.default: return func(*args, **kwargs) return proxy_call(self, func, self.pre_dispatch, args, kwargs) def __enter__(self) -> Self: # Stash and store the previous proxy mode (there may or may not be one) maybe_prev_proxy_mode = _unset_infra_mode(torch._C._TorchDispatchModeKey.PROXY) self.enter_stack.append(maybe_prev_proxy_mode) return super().__enter__() def __exit__( self, exc_type: Optional[type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[types.TracebackType], ) -> Optional[bool]: b = super().__exit__(exc_type, exc_value, traceback) # Re-enable the previous proxy mode, if there was one. mb_previous_proxy_mode = self.enter_stack.pop() if mb_previous_proxy_mode is not None: _push_mode(mb_previous_proxy_mode) return b @classmethod def is_infra_mode(cls) -> bool: return True def __sym_dispatch__( self, func: OpOverload, types: tuple[torch._C._TensorMeta, ...], args: tuple[object, ...], kwargs: dict[str, object], ) -> object: # Peephole optimize multiply by one # NB: be careful not to trigger guards here! if func is operator.mul: if isinstance(args[1], int) and args[1] == 1: return args[0] elif isinstance(args[0], int) and args[0] == 1: return args[1] # For speed, we assume there are no nested data structures # (otherwise we could use tree_map) # We also assume there are no keyword arguments. assert not kwargs out = func(*args, **kwargs) _sym_register(self.tracer, func, args, out) return out def _sym_register( tracer: _ProxyTracer, func: OpOverload, args: tuple[object, ...], out: object ) -> None: # If func returned a constant, we don't need to trace; we have # determined that the result is constant (no matter if the inputs # were symbolic) and it is no longer necessary to trace the # computation. This could occur if func triggered some guards. if isinstance(out, py_sym_types): p_out_thunk = thunkify( tracer, _compute_proxy, tracer, func=func, args=args, out=out ) set_proxy_slot(out, tracer, p_out_thunk) def _compute_proxy( tracer: _ProxyTracer, func: OpOverload, args: tuple[object, ...], out: PySymType ) -> Proxy: # Handle torch.sym_sum n_args: tuple[object, ...] if len(args) == 1 and isinstance(args[0], (list, tuple)): n_args = ( tuple( ( get_proxy_slot(a, tracer).force().node if isinstance(a, py_sym_types) else a ) for a in args[0] ), ) else: n_args = tuple( ( get_proxy_slot(a, tracer).force().node if isinstance(a, py_sym_types) else a ) for a in args ) # func doesn't have a __torch_function__ that Proxy can interpose, so # we gotta do it manually n_out = tracer.create_node("call_function", func, n_args, {}) # type: ignore[arg-type] p_out = fx.Proxy(n_out, tracer) set_meta(p_out, out) return p_out
ProxyTorchDispatchMode
python
sanic-org__sanic
sanic/application/constants.py
{ "start": 594, "end": 711 }
class ____(IntEnum): """Server stages.""" STOPPED = auto() PARTIAL = auto() SERVING = auto()
ServerStage
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/namedTuple8.py
{ "start": 183, "end": 400 }
class ____(GenericNT[str]): def geturl(self) -> str: ... def func(x: SpecializedNT): reveal_type(x.__iter__, expected_text="() -> Iterator[str]") reveal_type(list(x), expected_text="list[str]")
SpecializedNT
python
vyperlang__vyper
vyper/venom/context.py
{ "start": 279, "end": 569 }
class ____: data: IRLabel | bytes # can be raw data or bytes def __str__(self): if isinstance(self.data, IRLabel): return f"@{self.data}" else: assert isinstance(self.data, bytes) return f'x"{self.data.hex()}"' @dataclass
DataItem
python
spyder-ide__spyder
spyder/plugins/variableexplorer/widgets/objectexplorer/tests/test_objectexplorer.py
{ "start": 8428, "end": 10234 }
class ____: contents: object def test_objectexplorer_refresh_nested(): """ Open an editor for a `Box` object containing a list, and then open another editor for the nested list. Test that refreshing the second editor works. """ old_data = Box([1, 2, 3]) new_data = Box([4, 5]) editor = ObjectExplorer( old_data, name='data', data_function=lambda: new_data) model = editor.obj_tree.model() root_index = model.index(0, 0) contents_index = model.index(0, 0, root_index) editor.obj_tree.edit(contents_index) delegate = editor.obj_tree.delegate nested_editor = list(delegate._editors.values())[0]['editor'] assert nested_editor.get_value() == [1, 2, 3] nested_editor.widget.refresh_action.trigger() assert nested_editor.get_value() == [4, 5] def test_objectexplorer_refresh_doubly_nested(): """ Open an editor for a `Box` object containing another `Box` object which in turn contains a list. Then open a second editor for the nested list. Test that refreshing the second editor works. """ old_data = Box(Box([1, 2, 3])) new_data = Box(Box([4, 5])) editor = ObjectExplorer( old_data, name='data', data_function=lambda: new_data) model = editor.obj_tree.model() root_index = model.index(0, 0) inner_box_index = model.index(0, 0, root_index) editor.obj_tree.expand(inner_box_index) contents_index = model.index(0, 0, inner_box_index) editor.obj_tree.edit(contents_index) delegate = editor.obj_tree.delegate nested_editor = list(delegate._editors.values())[0]['editor'] assert nested_editor.get_value() == [1, 2, 3] nested_editor.widget.refresh_action.trigger() assert nested_editor.get_value() == [4, 5] if __name__ == "__main__": pytest.main()
Box
python
keon__algorithms
tests/test_compression.py
{ "start": 1277, "end": 1698 }
class ____(unittest.TestCase): def test_encode_rle(self): self.assertEqual('12W1B12W3B24W1B14W', encode_rle('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW')) def test_decode_rle(self): self.assertEqual('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW', decode_rle('12W1B12W3B24W1B14W'))
TestRLECompression
python
cookiecutter__cookiecutter
cookiecutter/exceptions.py
{ "start": 3548, "end": 3730 }
class ____(CookiecutterException): """ Exception for un-importable extension. Raised when an environment is unable to import a required extension. """
UnknownExtension
python
jmcnamara__XlsxWriter
examples/http_server.py
{ "start": 447, "end": 2024 }
class ____(http.server.SimpleHTTPRequestHandler): def do_GET(self): # Create an in-memory output file for the new workbook. output = io.BytesIO() # Even though the final file will be in memory the module uses temp # files during assembly for efficiency. To avoid this on servers that # don't allow temp files set the 'in_memory' constructor option to True. # # Note: The Python 3 Runtime Environment in Google App Engine supports # a filesystem with read/write access to /tmp which means that the # 'in_memory' option isn't required there and can be omitted. See: # # https://cloud.google.com/appengine/docs/standard/python3/runtime#filesystem # workbook = xlsxwriter.Workbook(output, {"in_memory": True}) worksheet = workbook.add_worksheet() # Write some test data. worksheet.write(0, 0, "Hello, world!") # Close the workbook before streaming the data. workbook.close() # Rewind the buffer. output.seek(0) # Construct a server response. self.send_response(200) self.send_header("Content-Disposition", "attachment; filename=test.xlsx") self.send_header( "Content-type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ) self.end_headers() self.wfile.write(output.read()) return print("Server listening on port 8000...") httpd = socketserver.TCPServer(("", 8000), Handler) httpd.serve_forever()
Handler
python
sphinx-doc__sphinx
sphinx/domains/c/__init__.py
{ "start": 12008, "end": 12882 }
class ____(CObject): object_type = 'member' @property def display_object_type(self) -> str: # the distinction between var and member is only cosmetic assert self.objtype in {'member', 'var'} return self.objtype _function_doc_field_types = [ TypedField( 'parameter', label=_('Parameters'), names=('param', 'parameter', 'arg', 'argument'), typerolename='expr', typenames=('type',), ), GroupedField( 'retval', label=_('Return values'), names=('retvals', 'retval'), can_collapse=True, ), Field( 'returnvalue', label=_('Returns'), has_arg=False, names=('returns', 'return'), ), Field( 'returntype', label=_('Return type'), has_arg=False, names=('rtype',), ), ]
CMemberObject
python
numpy__numpy
numpy/lib/tests/test_shape_base.py
{ "start": 11854, "end": 17103 }
class ____: def test_integer_0_split(self): a = np.arange(10) assert_raises(ValueError, array_split, a, 0) def test_integer_split(self): a = np.arange(10) res = array_split(a, 1) desired = [np.arange(10)] compare_results(res, desired) res = array_split(a, 2) desired = [np.arange(5), np.arange(5, 10)] compare_results(res, desired) res = array_split(a, 3) desired = [np.arange(4), np.arange(4, 7), np.arange(7, 10)] compare_results(res, desired) res = array_split(a, 4) desired = [np.arange(3), np.arange(3, 6), np.arange(6, 8), np.arange(8, 10)] compare_results(res, desired) res = array_split(a, 5) desired = [np.arange(2), np.arange(2, 4), np.arange(4, 6), np.arange(6, 8), np.arange(8, 10)] compare_results(res, desired) res = array_split(a, 6) desired = [np.arange(2), np.arange(2, 4), np.arange(4, 6), np.arange(6, 8), np.arange(8, 9), np.arange(9, 10)] compare_results(res, desired) res = array_split(a, 7) desired = [np.arange(2), np.arange(2, 4), np.arange(4, 6), np.arange(6, 7), np.arange(7, 8), np.arange(8, 9), np.arange(9, 10)] compare_results(res, desired) res = array_split(a, 8) desired = [np.arange(2), np.arange(2, 4), np.arange(4, 5), np.arange(5, 6), np.arange(6, 7), np.arange(7, 8), np.arange(8, 9), np.arange(9, 10)] compare_results(res, desired) res = array_split(a, 9) desired = [np.arange(2), np.arange(2, 3), np.arange(3, 4), np.arange(4, 5), np.arange(5, 6), np.arange(6, 7), np.arange(7, 8), np.arange(8, 9), np.arange(9, 10)] compare_results(res, desired) res = array_split(a, 10) desired = [np.arange(1), np.arange(1, 2), np.arange(2, 3), np.arange(3, 4), np.arange(4, 5), np.arange(5, 6), np.arange(6, 7), np.arange(7, 8), np.arange(8, 9), np.arange(9, 10)] compare_results(res, desired) res = array_split(a, 11) desired = [np.arange(1), np.arange(1, 2), np.arange(2, 3), np.arange(3, 4), np.arange(4, 5), np.arange(5, 6), np.arange(6, 7), np.arange(7, 8), np.arange(8, 9), np.arange(9, 10), np.array([])] compare_results(res, desired) def test_integer_split_2D_rows(self): a = np.array([np.arange(10), np.arange(10)]) res = array_split(a, 3, axis=0) tgt = [np.array([np.arange(10)]), np.array([np.arange(10)]), np.zeros((0, 10))] compare_results(res, tgt) assert_(a.dtype.type is res[-1].dtype.type) # Same thing for manual splits: res = array_split(a, [0, 1], axis=0) tgt = [np.zeros((0, 10)), np.array([np.arange(10)]), np.array([np.arange(10)])] compare_results(res, tgt) assert_(a.dtype.type is res[-1].dtype.type) def test_integer_split_2D_cols(self): a = np.array([np.arange(10), np.arange(10)]) res = array_split(a, 3, axis=-1) desired = [np.array([np.arange(4), np.arange(4)]), np.array([np.arange(4, 7), np.arange(4, 7)]), np.array([np.arange(7, 10), np.arange(7, 10)])] compare_results(res, desired) def test_integer_split_2D_default(self): """ This will fail if we change default axis """ a = np.array([np.arange(10), np.arange(10)]) res = array_split(a, 3) tgt = [np.array([np.arange(10)]), np.array([np.arange(10)]), np.zeros((0, 10))] compare_results(res, tgt) assert_(a.dtype.type is res[-1].dtype.type) # perhaps should check higher dimensions @pytest.mark.skipif(not IS_64BIT, reason="Needs 64bit platform") def test_integer_split_2D_rows_greater_max_int32(self): a = np.broadcast_to([0], (1 << 32, 2)) res = array_split(a, 4) chunk = np.broadcast_to([0], (1 << 30, 2)) tgt = [chunk] * 4 for i in range(len(tgt)): assert_equal(res[i].shape, tgt[i].shape) def test_index_split_simple(self): a = np.arange(10) indices = [1, 5, 7] res = array_split(a, indices, axis=-1) desired = [np.arange(0, 1), np.arange(1, 5), np.arange(5, 7), np.arange(7, 10)] compare_results(res, desired) def test_index_split_low_bound(self): a = np.arange(10) indices = [0, 5, 7] res = array_split(a, indices, axis=-1) desired = [np.array([]), np.arange(0, 5), np.arange(5, 7), np.arange(7, 10)] compare_results(res, desired) def test_index_split_high_bound(self): a = np.arange(10) indices = [0, 5, 7, 10, 12] res = array_split(a, indices, axis=-1) desired = [np.array([]), np.arange(0, 5), np.arange(5, 7), np.arange(7, 10), np.array([]), np.array([])] compare_results(res, desired)
TestArraySplit
python
matplotlib__matplotlib
lib/matplotlib/tests/test_category.py
{ "start": 1912, "end": 4144 }
class ____: """ Based on the pandas conversion and factorization tests: ref: /pandas/tseries/tests/test_converter.py /pandas/tests/test_algos.py:TestFactorize """ test_cases = [("unicode", ["Здравствуйте мир"]), ("ascii", ["hello world"]), ("single", ['a', 'b', 'c']), ("integer string", ["1", "2"]), ("single + values>10", ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"])] ids, values = zip(*test_cases) failing_test_cases = [("mixed", [3.14, 'A', np.inf]), ("string integer", ['42', 42])] fids, fvalues = zip(*failing_test_cases) @pytest.fixture(autouse=True) def mock_axis(self, request): self.cc = cat.StrCategoryConverter() # self.unit should be probably be replaced with real mock unit self.unit = cat.UnitData() self.ax = FakeAxis(self.unit) @pytest.mark.parametrize("vals", values, ids=ids) def test_convert(self, vals): np.testing.assert_allclose(self.cc.convert(vals, self.ax.units, self.ax), range(len(vals))) @pytest.mark.parametrize("value", ["hi", "мир"], ids=["ascii", "unicode"]) def test_convert_one_string(self, value): assert self.cc.convert(value, self.unit, self.ax) == 0 @pytest.mark.parametrize("fvals", fvalues, ids=fids) def test_convert_fail(self, fvals): with pytest.raises(TypeError): self.cc.convert(fvals, self.unit, self.ax) def test_axisinfo(self): axis = self.cc.axisinfo(self.unit, self.ax) assert isinstance(axis.majloc, cat.StrCategoryLocator) assert isinstance(axis.majfmt, cat.StrCategoryFormatter) def test_default_units(self): assert isinstance(self.cc.default_units(["a"], self.ax), cat.UnitData) PLOT_LIST = [Axes.scatter, Axes.plot, Axes.bar] PLOT_IDS = ["scatter", "plot", "bar"]
TestStrCategoryConverter
python
PyCQA__pydocstyle
src/pydocstyle/violations.py
{ "start": 3554, "end": 11291 }
class ____: """A registry of all error codes, divided to groups.""" groups = [] # type: ignore class ErrorGroup: """A group of similarly themed errors.""" def __init__(self, prefix: str, name: str) -> None: """Initialize the object. `Prefix` should be the common prefix for errors in this group, e.g., "D1". `name` is the name of the group (its subject). """ self.prefix = prefix self.name = name self.errors = [] # type: List[ErrorParams] def create_error( self, error_code: str, error_desc: str, error_context: Optional[str] = None, ) -> Callable[[Iterable[str]], Error]: """Create an error, register it to this group and return it.""" # TODO: check prefix error_params = ErrorParams(error_code, error_desc, error_context) factory = partial(Error, *error_params) self.errors.append(error_params) return factory @classmethod def create_group(cls, prefix: str, name: str) -> ErrorGroup: """Create a new error group and return it.""" group = cls.ErrorGroup(prefix, name) cls.groups.append(group) return group @classmethod def get_error_codes(cls) -> Iterable[str]: """Yield all registered codes.""" for group in cls.groups: for error in group.errors: yield error.code @classmethod def to_rst(cls) -> str: """Output the registry as reStructuredText, for documentation.""" max_len = max( len(error.short_desc) for group in cls.groups for error in group.errors ) sep_line = '+' + 6 * '-' + '+' + '-' * (max_len + 2) + '+\n' blank_line = '|' + (max_len + 9) * ' ' + '|\n' table = '' for group in cls.groups: table += sep_line table += blank_line table += '|' + f'**{group.name}**'.center(max_len + 9) + '|\n' table += blank_line for error in group.errors: table += sep_line table += ( '|' + error.code.center(6) + '| ' + error.short_desc.ljust(max_len + 1) + '|\n' ) table += sep_line return table D1xx = ErrorRegistry.create_group('D1', 'Missing Docstrings') D100 = D1xx.create_error( 'D100', 'Missing docstring in public module', ) D101 = D1xx.create_error( 'D101', 'Missing docstring in public class', ) D102 = D1xx.create_error( 'D102', 'Missing docstring in public method', ) D103 = D1xx.create_error( 'D103', 'Missing docstring in public function', ) D104 = D1xx.create_error( 'D104', 'Missing docstring in public package', ) D105 = D1xx.create_error( 'D105', 'Missing docstring in magic method', ) D106 = D1xx.create_error( 'D106', 'Missing docstring in public nested class', ) D107 = D1xx.create_error( 'D107', 'Missing docstring in __init__', ) D2xx = ErrorRegistry.create_group('D2', 'Whitespace Issues') D200 = D2xx.create_error( 'D200', 'One-line docstring should fit on one line ' 'with quotes', 'found {0}', ) D201 = D2xx.create_error( 'D201', 'No blank lines allowed before function docstring', 'found {0}', ) D202 = D2xx.create_error( 'D202', 'No blank lines allowed after function docstring', 'found {0}', ) D203 = D2xx.create_error( 'D203', '1 blank line required before class docstring', 'found {0}', ) D204 = D2xx.create_error( 'D204', '1 blank line required after class docstring', 'found {0}', ) D205 = D2xx.create_error( 'D205', '1 blank line required between summary line and description', 'found {0}', ) D206 = D2xx.create_error( 'D206', 'Docstring should be indented with spaces, not tabs', ) D207 = D2xx.create_error( 'D207', 'Docstring is under-indented', ) D208 = D2xx.create_error( 'D208', 'Docstring is over-indented', ) D209 = D2xx.create_error( 'D209', 'Multi-line docstring closing quotes should be on a separate line', ) D210 = D2xx.create_error( 'D210', 'No whitespaces allowed surrounding docstring text', ) D211 = D2xx.create_error( 'D211', 'No blank lines allowed before class docstring', 'found {0}', ) D212 = D2xx.create_error( 'D212', 'Multi-line docstring summary should start at the first line', ) D213 = D2xx.create_error( 'D213', 'Multi-line docstring summary should start at the second line', ) D214 = D2xx.create_error( 'D214', 'Section is over-indented', '{0!r}', ) D215 = D2xx.create_error( 'D215', 'Section underline is over-indented', 'in section {0!r}', ) D3xx = ErrorRegistry.create_group('D3', 'Quotes Issues') D300 = D3xx.create_error( 'D300', 'Use """triple double quotes"""', 'found {0}-quotes', ) D301 = D3xx.create_error( 'D301', 'Use r""" if any backslashes in a docstring', ) D302 = D3xx.create_error( 'D302', 'Deprecated: Use u""" for Unicode docstrings', ) D4xx = ErrorRegistry.create_group('D4', 'Docstring Content Issues') D400 = D4xx.create_error( 'D400', 'First line should end with a period', 'not {0!r}', ) D401 = D4xx.create_error( 'D401', 'First line should be in imperative mood', "perhaps '{0}', not '{1}'", ) D401b = D4xx.create_error( 'D401', 'First line should be in imperative mood; try rephrasing', "found '{0}'", ) D402 = D4xx.create_error( 'D402', 'First line should not be the function\'s "signature"', ) D403 = D4xx.create_error( 'D403', 'First word of the first line should be properly capitalized', '{0!r}, not {1!r}', ) D404 = D4xx.create_error( 'D404', 'First word of the docstring should not be `This`', ) D405 = D4xx.create_error( 'D405', 'Section name should be properly capitalized', '{0!r}, not {1!r}', ) D406 = D4xx.create_error( 'D406', 'Section name should end with a newline', '{0!r}, not {1!r}', ) D407 = D4xx.create_error( 'D407', 'Missing dashed underline after section', '{0!r}', ) D408 = D4xx.create_error( 'D408', 'Section underline should be in the line following the section\'s name', '{0!r}', ) D409 = D4xx.create_error( 'D409', 'Section underline should match the length of its name', 'Expected {0!r} dashes in section {1!r}, got {2!r}', ) D410 = D4xx.create_error( 'D410', 'Missing blank line after section', '{0!r}', ) D411 = D4xx.create_error( 'D411', 'Missing blank line before section', '{0!r}', ) D412 = D4xx.create_error( 'D412', 'No blank lines allowed between a section header and its content', '{0!r}', ) D413 = D4xx.create_error( 'D413', 'Missing blank line after last section', '{0!r}', ) D414 = D4xx.create_error( 'D414', 'Section has no content', '{0!r}', ) D415 = D4xx.create_error( 'D415', ( 'First line should end with a period, question ' 'mark, or exclamation point' ), 'not {0!r}', ) D416 = D4xx.create_error( 'D416', 'Section name should end with a colon', '{0!r}, not {1!r}', ) D417 = D4xx.create_error( 'D417', 'Missing argument descriptions in the docstring', 'argument(s) {0} are missing descriptions in {1!r} docstring', ) D418 = D4xx.create_error( 'D418', 'Function/ Method decorated with @overload shouldn\'t contain a docstring', ) D419 = D4xx.create_error( 'D419', 'Docstring is empty', )
ErrorRegistry
python
pytorch__pytorch
torch/nn/utils/prune.py
{ "start": 21488, "end": 24458 }
class ____(BasePruningMethod): r"""Prune (currently unpruned) units in a tensor by zeroing out the ones with the lowest L1-norm. Args: amount (int or float): quantity of parameters to prune. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If ``int``, it represents the absolute number of parameters to prune. """ PRUNING_TYPE = "unstructured" def __init__(self, amount) -> None: # Check range of validity of pruning amount _validate_pruning_amount_init(amount) self.amount = amount def compute_mask(self, t, default_mask): # Check that the amount of units to prune is not > than the number of # parameters in t tensor_size = t.nelement() # Compute number of units to prune: amount if int, # else amount * tensor_size nparams_toprune = _compute_nparams_toprune(self.amount, tensor_size) # This should raise an error if the number of units to prune is larger # than the number of units in the tensor _validate_pruning_amount(nparams_toprune, tensor_size) mask = default_mask.clone(memory_format=torch.contiguous_format) if nparams_toprune != 0: # k=0 not supported by torch.kthvalue # largest=True --> top k; largest=False --> bottom k # Prune the smallest k topk = torch.topk(torch.abs(t).view(-1), k=nparams_toprune, largest=False) # topk will have .indices and .values mask.view(-1)[topk.indices] = 0 return mask @classmethod def apply(cls, module, name, amount, importance_scores=None): # type: ignore[override] r"""Add pruning on the fly and reparametrization of a tensor. Adds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Args: module (nn.Module): module containing the tensor to prune name (str): parameter name within ``module`` on which pruning will act. amount (int or float): quantity of parameters to prune. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If ``int``, it represents the absolute number of parameters to prune. importance_scores (torch.Tensor): tensor of importance scores (of same shape as module parameter) used to compute mask for pruning. The values in this tensor indicate the importance of the corresponding elements in the parameter being pruned. If unspecified or None, the module parameter will be used in its place. """ return super().apply( module, name, amount=amount, importance_scores=importance_scores )
L1Unstructured
python
apache__airflow
airflow-core/tests/unit/ti_deps/deps/test_prev_dagrun_dep.py
{ "start": 1488, "end": 14226 }
class ____: def teardown_method(self): clear_db_runs() def test_first_task_run_of_new_task(self, testing_dag_bundle): """ The first task run of a new task in an old DAG should pass if the task has ignore_first_depends_on_past set to True. """ dag = DAG("test_dag", schedule=timedelta(days=1), start_date=START_DATE) old_task = BaseOperator( task_id="test_task", dag=dag, depends_on_past=True, start_date=START_DATE, wait_for_downstream=False, ) scheduler_dag = sync_dag_to_db(dag) # Old DAG run will include only TaskInstance of old_task scheduler_dag.create_dagrun( run_id="old_run", state=TaskInstanceState.SUCCESS, logical_date=old_task.start_date, run_type=DagRunType.SCHEDULED, data_interval=(old_task.start_date, old_task.start_date), run_after=old_task.start_date, triggered_by=DagRunTriggeredByType.TEST, ) new_task = BaseOperator( task_id="new_task", dag=dag, depends_on_past=True, ignore_first_depends_on_past=True, start_date=old_task.start_date, ) # New DAG run will include 1st TaskInstance of new_task logical_date = convert_to_utc(datetime(2016, 1, 2)) dr = create_scheduler_dag(dag).create_dagrun( run_id="new_run", state=DagRunState.RUNNING, logical_date=logical_date, run_type=DagRunType.SCHEDULED, data_interval=(logical_date, logical_date), run_after=logical_date, triggered_by=DagRunTriggeredByType.TEST, ) ti = dr.get_task_instance(new_task.task_id) ti.task = new_task dep_context = DepContext(ignore_depends_on_past=False) dep = PrevDagrunDep() with patch.object(dep, "_has_any_prior_tis", Mock(return_value=False)) as mock_has_any_prior_tis: assert dep.is_met(ti=ti, dep_context=dep_context) mock_has_any_prior_tis.assert_called_once_with(ti, session=ANY) @pytest.mark.parametrize( "kwargs", [ # If the task does not set depends_on_past, the previous dagrun should # be ignored, even though previous_ti would otherwise fail the dep. # wait_for_past_depends_before_skipping is False, past_depends_met xcom should not be sent pytest.param( dict( depends_on_past=False, wait_for_past_depends_before_skipping=False, wait_for_downstream=False, # wait_for_downstream=True overrides depends_on_past=False. prev_tis=[Mock(state=None, **{"are_dependents_done.return_value": False})], context_ignore_depends_on_past=False, expected_dep_met=True, past_depends_met_xcom_sent=False, ), id="not_depends_on_past", ), # If the task does not set depends_on_past, the previous dagrun should # be ignored, even though previous_ti would otherwise fail the dep. # wait_for_past_depends_before_skipping is True, past_depends_met xcom should be sent pytest.param( dict( depends_on_past=False, wait_for_past_depends_before_skipping=True, wait_for_downstream=False, # wait_for_downstream=True overrides depends_on_past=False. prev_tis=[Mock(state=None, **{"are_dependents_done.return_value": False})], context_ignore_depends_on_past=False, expected_dep_met=True, past_depends_met_xcom_sent=True, ), id="not_depends_on_past_with_wait", ), # If the context overrides depends_on_past, the dep should be met even # though there is no previous_ti which would normally fail the dep. # wait_for_past_depends_before_skipping is False, past_depends_met xcom should not be sent pytest.param( dict( depends_on_past=True, wait_for_past_depends_before_skipping=False, wait_for_downstream=False, prev_tis=[ Mock(state=TaskInstanceState.SUCCESS, **{"are_dependents_done.return_value": True}) ], context_ignore_depends_on_past=True, expected_dep_met=True, past_depends_met_xcom_sent=False, ), id="context_ignore_depends_on_past", ), # If the context overrides depends_on_past, the dep should be met even # though there is no previous_ti which would normally fail the dep. # wait_for_past_depends_before_skipping is True, past_depends_met xcom should be sent pytest.param( dict( depends_on_past=True, wait_for_past_depends_before_skipping=True, wait_for_downstream=False, prev_tis=[ Mock(state=TaskInstanceState.SUCCESS, **{"are_dependents_done.return_value": True}) ], context_ignore_depends_on_past=True, expected_dep_met=True, past_depends_met_xcom_sent=True, ), id="context_ignore_depends_on_past_with_wait", ), # The first task run should pass since it has no previous dagrun. # wait_for_past_depends_before_skipping is False, past_depends_met xcom should not be sent pytest.param( dict( depends_on_past=True, wait_for_past_depends_before_skipping=False, wait_for_downstream=False, prev_tis=[], context_ignore_depends_on_past=False, expected_dep_met=True, past_depends_met_xcom_sent=False, ), id="first_task_run", ), # The first task run should pass since it has no previous dagrun. # wait_for_past_depends_before_skipping is True, past_depends_met xcom should be sent pytest.param( dict( depends_on_past=True, wait_for_past_depends_before_skipping=True, wait_for_downstream=False, prev_tis=[], context_ignore_depends_on_past=False, expected_dep_met=True, past_depends_met_xcom_sent=True, ), id="first_task_run_wait", ), # Previous TI did not complete execution. This dep should fail. pytest.param( dict( depends_on_past=True, wait_for_past_depends_before_skipping=False, wait_for_downstream=False, prev_tis=[Mock(state=None, **{"are_dependents_done.return_value": True})], context_ignore_depends_on_past=False, expected_dep_met=False, past_depends_met_xcom_sent=False, ), id="prev_ti_bad_state", ), # Previous TI specified to wait for the downstream tasks of the previous # dagrun. It should fail this dep if the previous TI's downstream TIs # are not done. pytest.param( dict( depends_on_past=True, wait_for_past_depends_before_skipping=False, wait_for_downstream=True, prev_tis=[ Mock(state=TaskInstanceState.SUCCESS, **{"are_dependents_done.return_value": False}) ], context_ignore_depends_on_past=False, expected_dep_met=False, past_depends_met_xcom_sent=False, ), id="failed_wait_for_downstream", ), # All the conditions for the dep are met. # wait_for_past_depends_before_skipping is False, past_depends_met xcom should not be sent pytest.param( dict( depends_on_past=True, wait_for_past_depends_before_skipping=False, wait_for_downstream=True, prev_tis=[ Mock(state=TaskInstanceState.SUCCESS, **{"are_dependents_done.return_value": True}) ], context_ignore_depends_on_past=False, expected_dep_met=True, past_depends_met_xcom_sent=False, ), id="all_met", ), # All the conditions for the dep are met # wait_for_past_depends_before_skipping is True, past_depends_met xcom should be sent pytest.param( dict( depends_on_past=True, wait_for_past_depends_before_skipping=True, wait_for_downstream=True, prev_tis=[ Mock(state=TaskInstanceState.SUCCESS, **{"are_dependents_done.return_value": True}) ], context_ignore_depends_on_past=False, expected_dep_met=True, past_depends_met_xcom_sent=True, ), id="all_met_with_wait", ), ], ) @patch("airflow.models.dagrun.DagRun.get_previous_scheduled_dagrun") @patch("airflow.models.dagrun.DagRun.get_previous_dagrun") def test_dagrun_dep(mock_get_previous_dagrun, mock_get_previous_scheduled_dagrun, kwargs): depends_on_past = kwargs["depends_on_past"] wait_for_past_depends_before_skipping = kwargs["wait_for_past_depends_before_skipping"] wait_for_downstream = kwargs["wait_for_downstream"] prev_tis = kwargs["prev_tis"] context_ignore_depends_on_past = kwargs["context_ignore_depends_on_past"] expected_dep_met = kwargs["expected_dep_met"] past_depends_met_xcom_sent = kwargs["past_depends_met_xcom_sent"] task = BaseOperator( task_id="test_task", dag=DAG("test_dag", schedule=timedelta(days=1), start_date=datetime(2016, 1, 1)), depends_on_past=depends_on_past, start_date=datetime(2016, 1, 1), wait_for_downstream=wait_for_downstream, ) if prev_tis: prev_dagrun = Mock(logical_date=datetime(2016, 1, 2)) else: prev_dagrun = None mock_get_previous_scheduled_dagrun.return_value = prev_dagrun mock_get_previous_dagrun.return_value = prev_dagrun dagrun = Mock( **{ "get_previous_dagrun.return_value": prev_dagrun, "backfill_id": None, "logical_date": datetime(2016, 1, 3), "dag_id": "test_dag", }, ) ti = Mock( task=task, task_id=task.task_id, **{"get_dagrun.return_value": dagrun, "xcom_push.return_value": None}, ) dep_context = DepContext( ignore_depends_on_past=context_ignore_depends_on_past, wait_for_past_depends_before_skipping=wait_for_past_depends_before_skipping, ) unsuccessful_tis_count = sum( int(ti.state not in {TaskInstanceState.SUCCESS, TaskInstanceState.SKIPPED}) for ti in prev_tis ) mock_has_tis = Mock(return_value=bool(prev_tis)) mock_has_any_prior_tis = Mock(return_value=bool(prev_tis)) mock_count_unsuccessful_tis = Mock(return_value=unsuccessful_tis_count) mock_has_unsuccessful_dependants = Mock(return_value=any(not ti.are_dependents_done() for ti in prev_tis)) dep = PrevDagrunDep() with patch.multiple( dep, _has_tis=mock_has_tis, _has_any_prior_tis=mock_has_any_prior_tis, _count_unsuccessful_tis=mock_count_unsuccessful_tis, _has_unsuccessful_dependants=mock_has_unsuccessful_dependants, ): actual_dep_met = dep.is_met(ti=ti, dep_context=dep_context) mock_has_any_prior_tis.assert_not_called() if depends_on_past and not context_ignore_depends_on_past and prev_tis: mock_has_tis.assert_called_once_with(prev_dagrun, "test_task", session=ANY) mock_count_unsuccessful_tis.assert_called_once_with(prev_dagrun, "test_task", session=ANY) else: mock_has_tis.assert_not_called() mock_count_unsuccessful_tis.assert_not_called() if depends_on_past and not context_ignore_depends_on_past and prev_tis and not unsuccessful_tis_count: mock_has_unsuccessful_dependants.assert_called_once_with(prev_dagrun, task, session=ANY) else: mock_has_unsuccessful_dependants.assert_not_called() assert actual_dep_met == expected_dep_met if past_depends_met_xcom_sent: ti.xcom_push.assert_called_with(key="past_depends_met", value=True) else: ti.xcom_push.assert_not_called()
TestPrevDagrunDep
python
coleifer__peewee
peewee.py
{ "start": 56540, "end": 57080 }
class ____(WrappedNode): def __sql__(self, ctx): with ctx.scope_column(): return ctx.sql(self.node) def qualify_names(node): # Search a node heirarchy to ensure that any column-like objects are # referenced using fully-qualified names. if isinstance(node, Expression): return node.__class__(qualify_names(node.lhs), node.op, qualify_names(node.rhs), node.flat) elif isinstance(node, ColumnBase): return QualifiedNames(node) return node
QualifiedNames
python
apache__avro
lang/py/avro/ipc.py
{ "start": 17015, "end": 18284 }
class ____: """ A simple HTTP-based transceiver implementation. Useful for clients but not for servers """ def __init__(self, host, port, req_resource="/"): self.req_resource = req_resource self.conn = http.client.HTTPConnection(host, port) self.conn.connect() self.remote_name = self.conn.sock.getsockname() def transceive(self, request): self.write_framed_message(request) result = self.read_framed_message() return result def read_framed_message(self): response = self.conn.getresponse() response_reader = FramedReader(response) framed_message = response_reader.read_framed_message() response.read() # ensure we're ready for subsequent requests return framed_message def write_framed_message(self, message): req_method = "POST" req_headers = {"Content-Type": "avro/binary"} req_body_buffer = FramedWriter(io.BytesIO()) req_body_buffer.write_framed_message(message) req_body = req_body_buffer.writer.getvalue() self.conn.request(req_method, self.req_resource, req_body, req_headers) def close(self): self.conn.close() # # Server Implementations (none yet) #
HTTPTransceiver
python
scikit-learn__scikit-learn
sklearn/gaussian_process/tests/test_gpr.py
{ "start": 28956, "end": 30038 }
class ____(C): """ A custom kernel that has a diag method that returns the first column of the input matrix X. This is a helper for the test to check that the input matrix X is not mutated. """ def diag(self, X): return X[:, 0] def test_gpr_predict_input_not_modified(): """ Check that the input X is not modified by the predict method of the GaussianProcessRegressor when setting return_std=True. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/24340 """ gpr = GaussianProcessRegressor(kernel=CustomKernel()).fit(X, y) X2_copy = np.copy(X2) _, _ = gpr.predict(X2, return_std=True) assert_allclose(X2, X2_copy) @pytest.mark.parametrize("kernel", kernels) def test_gpr_predict_no_cov_no_std_return(kernel): """ Check that only y_mean is returned when return_cov=False and return_std=False. """ gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y) y_pred = gpr.predict(X, return_cov=False, return_std=False) assert_allclose(y_pred, y)
CustomKernel
python
arrow-py__arrow
arrow/locales.py
{ "start": 21914, "end": 23033 }
class ____(Locale): names = ["zh", "zh-cn"] past = "{0}前" future = "{0}后" timeframes = { "now": "刚才", "second": "1秒", "seconds": "{0}秒", "minute": "1分钟", "minutes": "{0}分钟", "hour": "1小时", "hours": "{0}小时", "day": "1天", "days": "{0}天", "week": "1周", "weeks": "{0}周", "month": "1个月", "months": "{0}个月", "year": "1年", "years": "{0}年", } month_names = [ "", "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月", ] month_abbreviations = [ "", " 1", " 2", " 3", " 4", " 5", " 6", " 7", " 8", " 9", "10", "11", "12", ] day_names = [ "", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日", ] day_abbreviations = ["", "一", "二", "三", "四", "五", "六", "日"]
ChineseCNLocale
python
google__pytype
pytype/pyi/function.py
{ "start": 1677, "end": 6234 }
class ____(pytd_function.NameAndSig): """Internal representation of function signatures.""" @classmethod def from_function( cls, function: astlib.FunctionDef, props: SigProperties ) -> "NameAndSig": """Constructor from an ast.FunctionDef node.""" name = function.name decorators = cast(list[pytd.Alias], function.decorator_list) mutually_exclusive = {"property", "staticmethod", "classmethod"} if len({d.type.name for d in decorators} & mutually_exclusive) > 1: raise _ParseError( f"'{name}' can be decorated with at most one of " "property, staticmethod, and classmethod" ) exceptions = [] mutators = [] for i, x in enumerate(function.body): if isinstance(x, types.Raise): exceptions.append(x.exception) elif isinstance(x, Mutator): mutators.append(x) elif isinstance(x, types.Ellipsis): pass elif ( isinstance(x, astlib.Expr) and isinstance(x.value, astlib.Constant) and isinstance(x.value.value, str) and i == 0 ): # docstring pass else: msg = textwrap.dedent(""" Unexpected statement in function body. Only `raise` statements and type mutations are valid """).lstrip() if isinstance(x, astlib.AST): raise _ParseError(msg).at(x) else: raise _ParseError(msg) # exceptions sig = _pytd_signature(function, props.is_async, exceptions=exceptions) # mutators # If `self` is generic, a type parameter is being mutated. if ( sig.params and sig.params[0].name == "self" and isinstance(sig.params[0].type, pytd.GenericType) ): mutators.append(Mutator("self", sig.params[0].type)) for mutator in mutators: try: sig = sig.Visit(mutator) except NotImplementedError as e: raise _ParseError(str(e)) from e if not mutator.successful: raise _ParseError(f"No parameter named {mutator.name!r}") return cls( name, sig, tuple(decorators), props.abstract, props.coroutine, props.final, props.overload, ) def _pytd_signature( function: astlib.FunctionDef, is_async: bool, exceptions: list[pytd.Type] | None = None, ) -> pytd.Signature: """Construct a pytd signature from an ast.FunctionDef node.""" name = function.name args = function.args # Positional-only parameters are new in Python 3.8. posonly_params = [ Param.from_arg(a, pytd.ParameterKind.POSONLY) for a in getattr(args, "posonlyargs", ()) ] pos_params = [ Param.from_arg(a, pytd.ParameterKind.REGULAR) for a in args.args ] kwonly_params = [ Param.from_arg(a, pytd.ParameterKind.KWONLY) for a in args.kwonlyargs ] _apply_defaults(posonly_params + pos_params, args.defaults) _apply_defaults(kwonly_params, args.kw_defaults) all_params = posonly_params + pos_params + kwonly_params params = tuple(x.to_pytd() for x in all_params) starargs = _pytd_star_param(args.vararg) starstarargs = _pytd_starstar_param(args.kwarg) ret = pytd_function.pytd_return_type(name, function.returns, is_async) exceptions = exceptions or [] return pytd.Signature( params=params, return_type=ret, starargs=starargs, starstarargs=starstarargs, exceptions=tuple(exceptions), template=(), ) def _pytd_star_param(arg: astlib.arg) -> pytd.Parameter | None: """Return a pytd.Parameter for a *args argument.""" if not arg: return None # Temporary hack: until pytype supports Unpack, treat it as Any. unpack = parser_constants.EXTERNAL_NAME_PREFIX + "typing_extensions.Unpack" if ( isinstance(arg.annotation, pytd.GenericType) and arg.annotation.base_type.name == unpack ): arg.annotation = pytd.AnythingType() return pytd_function.pytd_star_param(arg.arg, arg.annotation) # pytype: disable=wrong-arg-types def _pytd_starstar_param(arg: astlib.arg | None) -> pytd.Parameter | None: """Return a pytd.Parameter for a **kwargs argument.""" if not arg: return None return pytd_function.pytd_starstar_param(arg.arg, arg.annotation) # pytype: disable=wrong-arg-types def _apply_defaults(params: list[Param], defaults: list[Any]) -> None: for p, d in zip(reversed(params), reversed(defaults)): if d is None: continue elif isinstance(d, types.Pyval): p.default = d.to_pytd() else: p.default = pytd.AnythingType()
NameAndSig
python
mwaskom__seaborn
tests/_marks/test_dot.py
{ "start": 730, "end": 2478 }
class ____(DotBase): def test_simple(self): x = [1, 2, 3] y = [4, 5, 2] p = Plot(x=x, y=y).add(Dot()).plot() ax = p._figure.axes[0] points, = ax.collections C0, *_ = p._theme["axes.prop_cycle"].by_key()["color"] self.check_offsets(points, x, y) self.check_colors("face", points, [C0] * 3, 1) self.check_colors("edge", points, [C0] * 3, 1) def test_filled_unfilled_mix(self): x = [1, 2] y = [4, 5] marker = ["a", "b"] shapes = ["o", "x"] mark = Dot(edgecolor="w", stroke=2, edgewidth=1) p = Plot(x=x, y=y).add(mark, marker=marker).scale(marker=shapes).plot() ax = p._figure.axes[0] points, = ax.collections C0, *_ = p._theme["axes.prop_cycle"].by_key()["color"] self.check_offsets(points, x, y) self.check_colors("face", points, [C0, to_rgba(C0, 0)], None) self.check_colors("edge", points, ["w", C0], 1) expected = [mark.edgewidth, mark.stroke] assert_array_equal(points.get_linewidths(), expected) def test_missing_coordinate_data(self): x = [1, float("nan"), 3] y = [5, 3, 4] p = Plot(x=x, y=y).add(Dot()).plot() ax = p._figure.axes[0] points, = ax.collections self.check_offsets(points, [1, 3], [5, 4]) @pytest.mark.parametrize("prop", ["color", "fill", "marker", "pointsize"]) def test_missing_semantic_data(self, prop): x = [1, 2, 3] y = [5, 3, 4] z = ["a", float("nan"), "b"] p = Plot(x=x, y=y, **{prop: z}).add(Dot()).plot() ax = p._figure.axes[0] points, = ax.collections self.check_offsets(points, [1, 3], [5, 4])
TestDot
python
numba__numba
numba/tests/test_function_type.py
{ "start": 1842, "end": 2392 }
class ____(types.WrapperAddressProtocol): """An example implementation of wrapper address protocol. """ def __init__(self, func, sig): self.pyfunc = func self.cfunc = cfunc(sig)(func) self.sig = sig def __wrapper_address__(self): return self.cfunc._wrapper_address def signature(self): return self.sig def __call__(self, *args, **kwargs): return self.pyfunc(*args, **kwargs) def mk_wap_func(sig): def wap_func(func): return WAP(func, sig) return wap_func
WAP
python
getsentry__sentry
src/sentry/hybridcloud/rpc/resolvers.py
{ "start": 2563, "end": 3662 }
class ____(RegionResolutionStrategy): """Resolve to the only region in a single-organization environment. Calling a service method with this resolution strategy will cause an error if the environment is not configured with the "single organization" or has more than one region. """ def resolve(self, arguments: ArgumentDict) -> Region: from sentry.models.organizationmapping import OrganizationMapping if not settings.SENTRY_SINGLE_ORGANIZATION: raise RegionResolutionError("Method is available only in single-org environment") all_region_names = list( OrganizationMapping.objects.all().values_list("region_name", flat=True).distinct()[:2] ) if len(all_region_names) == 0: return get_region_by_name(settings.SENTRY_MONOLITH_REGION) if len(all_region_names) != 1: raise RegionResolutionError("Expected single-org environment to have only one region") (single_region_name,) = all_region_names return get_region_by_name(single_region_name)
RequireSingleOrganization
python
pytorch__pytorch
benchmarks/tensorexpr/broadcast.py
{ "start": 2711, "end": 4570 }
class ____(benchmark.Benchmark): def __init__(self, mode, device, dtype, M, N, K, L): super().__init__(mode, device, dtype) self.M = M self.N = N self.K = K self.L = L self.d1 = self.rand( [M, N], device=device, dtype=dtype, requires_grad=self.requires_grad ) self.d2 = self.rand( [K, M, 1], device=device, dtype=dtype, requires_grad=self.requires_grad ) self.d3 = self.rand( [L, K, 1, 1], device=device, dtype=dtype, requires_grad=self.requires_grad ) self.inputs = [self.d1, self.d2, self.d3] def forward(self, d1, d2, d3): y = d1 + d2 + d3 return y def reference(self): return self.numpy(self.d1) + self.numpy(self.d2) + self.numpy(self.d3) def config(self): return [self.M, self.N, self.K, self.L] @staticmethod def default_configs(): return [[32, 16, 64, 128]] def memory_workload(self): if self.mode == "fwd": sol_count = 1 algorithmic_count = 1 else: sol_count = (1) + (1) algorithmic_count = 1 + (1 + 1 + 1) buffer_size = self.M * self.N * self.K * self.L * 4 return { "sol": buffer_size * sol_count, "algorithmic": buffer_size * algorithmic_count, } @staticmethod def module(): return "broadcast_3args" # benchmark.register_benchmark_class(BroadcastRowBench) # benchmark.register_benchmark_class(BroadcastMidBench) # benchmark.register_benchmark_class(BroadcastColBench) # benchmark.register_benchmark_class(BroadcastThreeArgs) # TODO: merge this with elementwise bench # A template class for elementwise operations. # A derived class will override the class instance to customize its behavior.
BroadcastThreeArgs
python
coleifer__peewee
tests/test_utils.py
{ "start": 442, "end": 2541 }
class ____(ModelTestCase): requires = [DataItem, Data] def test_count(self): with count_queries() as count: Data.create(key='k1') Data.create(key='k2') self.assertEqual(count.count, 2) with count_queries() as count: items = [item.key for item in Data.select().order_by(Data.key)] self.assertEqual(items, ['k1', 'k2']) Data.get(Data.key == 'k1') Data.get(Data.key == 'k2') self.assertEqual(count.count, 3) def test_only_select(self): with count_queries(only_select=True) as count: for i in range(10): Data.create(key=str(i)) items = [item.key for item in Data.select()] Data.get(Data.key == '0') Data.get(Data.key == '9') Data.delete().where( Data.key << ['1', '3', '5', '7', '9']).execute() items = [item.key for item in Data.select().order_by(Data.key)] self.assertEqual(items, ['0', '2', '4', '6', '8']) self.assertEqual(count.count, 4) def test_assert_query_count_decorator(self): @assert_query_count(2) def will_fail_under(): Data.create(key='x') @assert_query_count(2) def will_fail_over(): for i in range(3): Data.create(key=str(i)) @assert_query_count(4) def will_succeed(): for i in range(4): Data.create(key=str(i + 100)) will_succeed() self.assertRaises(AssertionError, will_fail_under) self.assertRaises(AssertionError, will_fail_over) def test_assert_query_count_ctx_mgr(self): with assert_query_count(3): for i in range(3): Data.create(key=str(i)) def will_fail(): with assert_query_count(2): Data.create(key='x') self.assertRaises(AssertionError, will_fail) @assert_query_count(3) def test_only_three(self): for i in range(3): Data.create(key=str(i))
TestQueryCounter
python
huggingface__transformers
src/transformers/models/sam2_video/modeling_sam2_video.py
{ "start": 68717, "end": 132725 }
class ____(Sam2VideoPreTrainedModel): input_modalities = ("video", "text") _can_record_outputs = {"mask_decoder_attentions": OutputRecorder(Sam2VideoTwoWayAttentionBlock, index=2)} _keys_to_ignore_on_load_unexpected = [] _tied_weights_keys = { "prompt_encoder.shared_embedding.positional_embedding": "shared_image_embedding.positional_embedding" } # need to be ignored, as it's a buffer and will not be correctly detected as tied weight _keys_to_ignore_on_load_missing = ["prompt_encoder.shared_embedding.positional_embedding"] def __init__(self, config: Sam2VideoConfig): super().__init__(config) self.shared_image_embedding = Sam2VideoPositionalEmbedding(config.prompt_encoder_config) self.vision_encoder = AutoModel.from_config(config.vision_config) self.prompt_encoder = Sam2VideoPromptEncoder(config.prompt_encoder_config) # The module using it is not a PreTrainedModel subclass so we need this config.mask_decoder_config._attn_implementation = config._attn_implementation self.mask_decoder = Sam2VideoMaskDecoder(config.mask_decoder_config) self.num_feature_levels = config.vision_config.num_feature_levels self.backbone_feature_sizes = config.vision_config.backbone_feature_sizes # a single token to indicate no memory embedding from previous frames self.hidden_dim = config.vision_config.fpn_hidden_size self.no_memory_embedding = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim)) self.config = config # For video sequence inference self.image_size = config.image_size self.memory_attention = Sam2VideoMemoryAttention(config) self.memory_encoder = Sam2VideoMemoryEncoder(config) self.no_memory_positional_encoding = torch.nn.Parameter( torch.zeros(1, 1, config.vision_config.fpn_hidden_size) ) self.mem_dim = config.memory_encoder_output_channels self.num_maskmem = config.num_maskmem # Number of memories accessible # Temporal encoding of the memories self.memory_temporal_positional_encoding = torch.nn.Parameter( torch.zeros(self.num_maskmem, 1, 1, self.mem_dim) ) self.no_object_pointer = torch.nn.Parameter(torch.zeros(1, self.hidden_dim)) # A conv layer to downsample the mask prompt to stride 4 (the same stride as # low-res SAM mask logits) and to change its scales from 0~1 to SAM logit scale, # so that it can be fed into the SAM mask decoder to generate a pointer. self.mask_downsample = torch.nn.Conv2d(1, 1, kernel_size=4, stride=4) # a feedforward layer on SAM output tokens to turn them into object pointers self.object_pointer_proj = Sam2VideoFeedForward(self.hidden_dim, self.hidden_dim, self.hidden_dim, 3) if self.config.enable_temporal_pos_encoding_for_object_pointers: # a linear projection on temporal positional encoding in object pointers to # avoid potential interference with spatial positional encoding self.temporal_positional_encoding_projection_layer = torch.nn.Linear(self.hidden_dim, self.mem_dim) else: self.temporal_positional_encoding_projection_layer = torch.nn.Identity() self.occlusion_spatial_embedding_parameter = None # compatibility with Sam2 if config.enable_occlusion_spatial_embedding: self.occlusion_spatial_embedding_parameter = torch.nn.Parameter(torch.zeros(1, self.mem_dim)) self.post_init() def get_input_embeddings(self): return self.vision_encoder.get_input_embeddings() def get_image_wide_positional_embeddings(self) -> torch.Tensor: size = self.prompt_encoder.image_embedding_size target_device = self.shared_image_embedding.positional_embedding.device target_dtype = self.shared_image_embedding.positional_embedding.dtype grid = torch.ones(size, device=target_device, dtype=target_dtype) y_embed = grid.cumsum(dim=0) - 0.5 x_embed = grid.cumsum(dim=1) - 0.5 y_embed = y_embed / size[0] x_embed = x_embed / size[1] positional_embedding = self.shared_image_embedding(torch.stack([x_embed, y_embed], dim=-1)) return positional_embedding.permute(2, 0, 1).unsqueeze(0) # channel x height x width @torch.no_grad() def get_image_embeddings( self, pixel_values: torch.FloatTensor, **kwargs: Unpack[TransformersKwargs], ) -> list[torch.Tensor]: r""" Returns the image embeddings by passing the pixel values through the vision encoder. Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Input pixel values """ batch_size = pixel_values.shape[0] feature_maps, _, _, _ = self.get_image_features(pixel_values, **kwargs) # add no memory embedding to the last feature map feature_maps[-1] = feature_maps[-1] + self.no_memory_embedding # reshape feature maps to the same shape as the backbone feature sizes image_embeddings = [ feat.permute(1, 2, 0).view(batch_size, -1, *feat_size) for feat, feat_size in zip(feature_maps, self.backbone_feature_sizes) ] return image_embeddings @torch.no_grad() def get_prompt_embeddings( self, input_points: Optional[torch.FloatTensor] = None, input_labels: Optional[torch.LongTensor] = None, input_boxes: Optional[torch.FloatTensor] = None, input_masks: Optional[torch.LongTensor] = None, ) -> tuple[torch.Tensor, torch.Tensor]: r""" Returns the prompt embeddings by passing the input points, labels, boxes and masks through the prompt encoder. Args: input_points (`torch.FloatTensor` of shape `(batch_size, point_batch_size, num_points_per_image, 2)`): Optional input points for the prompt encoder. The padding of the point is automatically done by the processor. `point_batch_size` refers to the number of masks that we want the model to predict per point. The model will output `point_batch_size` times 3 masks in total. input_labels (`torch.LongTensor` of shape `(batch_size, point_batch_size, num_points_per_image)`): Optional input labels for the prompt encoder. The padding of the labels is automatically done by the processor, or can be fed by the user. input_boxes (`torch.FloatTensor` of shape `(batch_size, num_boxes_per_image, 4)`): Optional input boxes for the prompt encoder. The padding of the boxes is automatically done by the processor. users can also pass manually the input boxes. input_masks (`torch.LongTensor` of shape `(batch_size, image_size, image_size)`): Optional input masks for the prompt encoder. """ prompt_output = self.prompt_encoder( input_points=input_points, input_labels=input_labels, input_boxes=input_boxes, input_masks=input_masks, ) return prompt_output @torch.inference_mode() @auto_docstring(custom_intro="Propagate the objects through a streamed video frame.") def forward( self, inference_session: Sam2VideoInferenceSession, frame_idx: Optional[int] = None, frame: Optional[torch.Tensor] = None, reverse: bool = False, run_mem_encoder: bool = True, ) -> Sam2VideoSegmentationOutput: r""" inference_session (`Sam2VideoInferenceSession`): The video inference session object. frame_idx (`int`, *optional*): The index of the frame on which to run inference. No need to provide when inferring on a new streamed frame. frame (`torch.Tensor`, *optional*): The frame to process. Provide when streaming. reverse (`bool`, *optional*, defaults to `False`): Whether to propagate in reverse. run_mem_encoder (`bool`, *optional*, defaults to `True`): Whether to run the memory encoder on predicted masks. The memory encoder is batched across all objects for efficiency. """ if frame is not None: frame_idx = inference_session.add_new_frame(frame, frame_idx) if frame is not None and inference_session.get_obj_num() == 0: raise ValueError("No objects are provided for tracking; please add inputs first.") num_objects = inference_session.get_obj_num() pred_masks_per_obj = [None] * num_objects object_score_logits_per_obj = [None] * num_objects # Collect data for batched memory encoding objects_needing_memory_encoding = [] high_res_masks_for_memory = [] object_score_logits_for_memory = [] is_mask_from_pts_per_obj = [] # Note: We avoid batched inference here because per-object inputs (clicks/masks) # can differ across objects. for obj_idx in range(num_objects): obj_id = inference_session.obj_idx_to_id(obj_idx) has_new_inputs = obj_id in inference_session.obj_with_new_inputs has_cond_output = frame_idx in inference_session.output_dict_per_obj[obj_idx]["cond_frame_outputs"] # If this object has no new inputs and this frame already has a # conditioning output, reuse the cached masks instead of recomputing. if (not has_new_inputs) and has_cond_output: pred_masks = inference_session.get_output(obj_idx, frame_idx, "pred_masks", is_conditioning_frame=True) object_score_logits = inference_session.get_output( obj_idx, frame_idx, "object_score_logits", is_conditioning_frame=True ) is_init_cond_frame = True else: # Defaults when there are no new inputs is_init_cond_frame = False point_inputs = None mask_inputs = None if has_new_inputs: is_init_cond_frame = frame_idx not in inference_session.frames_tracked_per_obj[obj_idx] if is_init_cond_frame: reverse = False point_inputs = inference_session.point_inputs_per_obj[obj_idx].get(frame_idx, None) mask_inputs = inference_session.mask_inputs_per_obj[obj_idx].get(frame_idx, None) if point_inputs is not None or mask_inputs is not None: inference_session.obj_with_new_inputs.remove(obj_id) current_out = self._run_single_frame_inference( inference_session=inference_session, obj_idx=obj_idx, frame_idx=frame_idx, batch_size=1, # run on the slice of a single object is_init_cond_frame=is_init_cond_frame, point_inputs=point_inputs, mask_inputs=mask_inputs, reverse=reverse, streaming=frame is not None, ) inference_session.store_output( obj_idx, frame_idx, output_value=current_out, is_conditioning_frame=is_init_cond_frame ) pred_masks = current_out["pred_masks"] object_score_logits = current_out["object_score_logits"] # Collect data for batched memory encoding if run_mem_encoder and self.num_maskmem > 0: objects_needing_memory_encoding.append(obj_idx) high_res_masks_for_memory.append(current_out["high_res_masks"]) object_score_logits_for_memory.append(object_score_logits) is_mask_from_pts_per_obj.append(point_inputs is not None or mask_inputs is not None) pred_masks_per_obj[obj_idx] = pred_masks object_score_logits_per_obj[obj_idx] = object_score_logits.squeeze(-1) if not is_init_cond_frame: # only for tracked frames, not for initial conditioning frames inference_session.frames_tracked_per_obj[obj_idx][frame_idx] = {"reverse": reverse} # Batch encode memories for all objects at once self._batch_encode_memories( inference_session=inference_session, frame_idx=frame_idx, objects_needing_memory_encoding=objects_needing_memory_encoding, high_res_masks_for_memory=high_res_masks_for_memory, object_score_logits_for_memory=object_score_logits_for_memory, is_mask_from_pts_per_obj=is_mask_from_pts_per_obj, ) # Resize the output mask to the original video resolution (we directly use # the mask scores on GPU for output to avoid any CPU conversion in between) if len(pred_masks_per_obj) > 1: all_pred_masks = torch.cat(pred_masks_per_obj, dim=0) all_object_score_logits = torch.cat(object_score_logits_per_obj, dim=0) else: all_pred_masks = pred_masks_per_obj[0] all_object_score_logits = object_score_logits_per_obj[0] return Sam2VideoSegmentationOutput( object_ids=inference_session.obj_ids.copy(), pred_masks=all_pred_masks, object_score_logits=all_object_score_logits, frame_idx=frame_idx, ) def get_image_features( self, pixel_values: torch.FloatTensor, **kwargs: Unpack[TransformersKwargs], ) -> tuple[ list[torch.Tensor], list[torch.Tensor], Optional[tuple[torch.FloatTensor, ...]], Optional[tuple[torch.FloatTensor, ...]], ]: r""" Extract and preprocess image features using the vision encoder. Args: pixel_values (`torch.FloatTensor`): Input pixel values of shape `(batch_size, num_channels, height, width)`. Returns: `tuple`: A tuple containing: - feature_maps (`list[torch.Tensor]`): List of feature maps from different levels. - feature_maps_position_embeddings (`list[torch.Tensor]`): List of positional embeddings for each feature level. - vision_hidden_states (`tuple[torch.FloatTensor]`, *optional*): Hidden states from the vision encoder. - vision_attentions (`tuple[torch.FloatTensor]`, *optional*): Attention weights from the vision encoder. """ vision_outputs: Sam2VideoVisionEncoderOutput = self.vision_encoder( pixel_values, **kwargs, ) feature_maps = vision_outputs.fpn_hidden_states feature_maps_position_embeddings = vision_outputs.fpn_position_encoding # precompute projected level 0 and level 1 features in SAM decoder # to avoid running it again on every SAM click feature_maps = list(feature_maps) feature_maps[0] = self.mask_decoder.conv_s0(feature_maps[0]) feature_maps[1] = self.mask_decoder.conv_s1(feature_maps[1]) # flatten NxCxHxW to HWxNxC feature_maps = [feature_map.flatten(2).permute(2, 0, 1) for feature_map in feature_maps] feature_maps_position_embeddings = [ feature_map_position_embedding.flatten(2).permute(2, 0, 1) for feature_map_position_embedding in feature_maps_position_embeddings ] return feature_maps, feature_maps_position_embeddings, vision_outputs.hidden_states, vision_outputs.attentions def _prepare_vision_features( self, inference_session: Sam2VideoInferenceSession, frame_idx: int, batch_size: int, ) -> tuple[torch.Tensor, list[torch.Tensor]]: """Prepare vision features for a frame.""" # Check if features are cached if cached_features := inference_session.cache.get_vision_features(frame_idx): vision_feats = cached_features["vision_feats"] vision_pos_embeds = cached_features["vision_pos_embeds"] else: # Compute features using image encoder image_batch = inference_session.get_frame(frame_idx).unsqueeze(0) # Add batch dimension vision_feats, vision_pos_embeds, _, _ = self.get_image_features(image_batch) # Cache features inference_session.cache.cache_vision_features( frame_idx, {"vision_feats": vision_feats, "vision_pos_embeds": vision_pos_embeds} ) # Expand to batch size if needed if batch_size > 1: vision_feats = vision_feats.expand(batch_size, -1, -1, -1) vision_pos_embeds = [pe.expand(batch_size, -1, -1, -1) for pe in vision_pos_embeds] return vision_feats, vision_pos_embeds def _single_frame_forward( self, pixel_values: Optional[torch.FloatTensor] = None, input_points: Optional[torch.FloatTensor] = None, input_labels: Optional[torch.LongTensor] = None, input_boxes: Optional[torch.FloatTensor] = None, input_masks: Optional[torch.LongTensor] = None, image_embeddings: Optional[torch.FloatTensor] = None, multimask_output: bool = True, attention_similarity: Optional[torch.FloatTensor] = None, target_embedding: Optional[torch.FloatTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> Sam2VideoImageSegmentationOutput: """ input_points (`torch.FloatTensor` of shape `(batch_size, num_points, 2)`): Input 2D spatial points, this is used by the prompt encoder to encode the prompt. Generally yields to much better results. The points can be obtained by passing a list of list of list to the processor that will create corresponding `torch` tensors of dimension 4. The first dimension is the image batch size, the second dimension is the point batch size (i.e. how many segmentation masks do we want the model to predict per input point), the third dimension is the number of points per segmentation mask (it is possible to pass multiple points for a single mask), and the last dimension is the x (vertical) and y (horizontal) coordinates of the point. If a different number of points is passed either for each image, or for each mask, the processor will create "PAD" points that will correspond to the (0, 0) coordinate, and the computation of the embedding will be skipped for these points using the labels. input_labels (`torch.LongTensor` of shape `(batch_size, point_batch_size, num_points)`): Input labels for the points, this is used by the prompt encoder to encode the prompt. According to the official implementation, there are 3 types of labels - `1`: the point is a point that contains the object of interest - `0`: the point is a point that does not contain the object of interest - `-1`: the point corresponds to the background We added the label: - `-10`: the point is a padding point, thus should be ignored by the prompt encoder The padding labels should be automatically done by the processor. input_boxes (`torch.FloatTensor` of shape `(batch_size, num_boxes, 4)`): Input boxes for the points, this is used by the prompt encoder to encode the prompt. Generally yields to much better generated masks. The boxes can be obtained by passing a list of list of list to the processor, that will generate a `torch` tensor, with each dimension corresponding respectively to the image batch size, the number of boxes per image and the coordinates of the top left and bottom right point of the box. In the order (`x1`, `y1`, `x2`, `y2`): - `x1`: the x coordinate of the top left point of the input box - `y1`: the y coordinate of the top left point of the input box - `x2`: the x coordinate of the bottom right point of the input box - `y2`: the y coordinate of the bottom right point of the input box input_masks (`torch.FloatTensor` of shape `(batch_size, image_size, image_size)`): SAM model also accepts segmentation masks as input. The mask will be embedded by the prompt encoder to generate a corresponding embedding, that will be fed later on to the mask decoder. These masks needs to be manually fed by the user, and they need to be of shape (`batch_size`, `image_size`, `image_size`). image_embeddings (`torch.FloatTensor` of shape `(batch_size, output_channels, window_size, window_size)`): Image embeddings, this is used by the mask decoder to generate masks and iou scores. For more memory efficient computation, users can first retrieve the image embeddings using the `get_image_embeddings` method, and then feed them to the `forward` method instead of feeding the `pixel_values`. multimask_output (`bool`, *optional*): In the original implementation and paper, the model always outputs 3 masks per image (or per point / per bounding box if relevant). However, it is possible to just output a single mask, that corresponds to the "best" mask, by specifying `multimask_output=False`. attention_similarity (`torch.FloatTensor`, *optional*): Attention similarity tensor, to be provided to the mask decoder for target-guided attention in case the model is used for personalization as introduced in [PerSAM](https://huggingface.co/papers/2305.03048). target_embedding (`torch.FloatTensor`, *optional*): Embedding of the target concept, to be provided to the mask decoder for target-semantic prompting in case the model is used for personalization as introduced in [PerSAM](https://huggingface.co/papers/2305.03048). """ if not ((pixel_values is None) ^ (image_embeddings is None)): raise ValueError("Exactly one of pixel_values or image_embeddings must be provided.") if input_points is not None and input_boxes is not None: if input_points.shape[1] != input_boxes.shape[1]: raise ValueError( f"You should provide as many bounding boxes as input points per box. Got {input_points.shape[1]} and {input_boxes.shape[1]}." ) elif input_points is not None: num_objects = input_points.shape[1] elif input_boxes is not None: num_objects = input_boxes.shape[1] elif input_masks is not None: num_objects = input_masks.shape[1] else: num_objects = 1 image_positional_embeddings = self.get_image_wide_positional_embeddings() # repeat with batch size batch_size = pixel_values.shape[0] if pixel_values is not None else image_embeddings[-1].shape[0] image_positional_embeddings = image_positional_embeddings.repeat(batch_size, 1, 1, 1) vision_attentions = None vision_hidden_states = None if pixel_values is not None: feature_maps, _, vision_hidden_states, vision_attentions = self.get_image_features( pixel_values, **kwargs, ) # add no memory embedding to the last feature map feature_maps[-1] = feature_maps[-1] + self.no_memory_embedding # reshape feature maps to the same shape as the backbone feature sizes image_embeddings = [ feat.permute(1, 2, 0).view(batch_size, -1, *feat_size) for feat, feat_size in zip(feature_maps, self.backbone_feature_sizes) ] if input_points is not None and input_labels is None: input_labels = torch.ones_like(input_points[:, :, :, 0], dtype=torch.int, device=input_points.device) if input_points is None and input_boxes is None: # If no points are provide, pad with an empty point (with label -1) input_points = torch.zeros( batch_size, 1, 1, 2, dtype=image_embeddings[-1].dtype, device=image_embeddings[-1].device ) input_labels = -torch.ones(batch_size, 1, 1, dtype=torch.int32, device=image_embeddings[-1].device) if input_masks is not None: # If mask_inputs is provided, downsize it into low-res mask input if needed # and feed it as a dense mask prompt into the SAM mask encoder if input_masks.shape[-2:] != self.prompt_encoder.mask_input_size: input_masks = F.interpolate( input_masks.float(), size=self.prompt_encoder.mask_input_size, align_corners=False, mode="bilinear", antialias=True, # use antialias for downsampling ).to(input_masks.dtype) sparse_embeddings, dense_embeddings = self.prompt_encoder( input_points=input_points, input_labels=input_labels, input_boxes=input_boxes, input_masks=input_masks, ) low_res_multimasks, iou_scores, sam_output_tokens, object_score_logits = self.mask_decoder( image_embeddings=image_embeddings[-1], image_positional_embeddings=image_positional_embeddings, sparse_prompt_embeddings=sparse_embeddings, dense_prompt_embeddings=dense_embeddings, multimask_output=multimask_output, high_resolution_features=image_embeddings[:-1], attention_similarity=attention_similarity, target_embedding=target_embedding, **kwargs, ) is_obj_appearing = object_score_logits > 0 # Mask used for spatial memories is always a *hard* choice between obj and no obj, # consistent with the actual mask prediction low_res_multimasks = torch.where( is_obj_appearing[:, None, None], low_res_multimasks, NO_OBJ_SCORE, ) # convert masks from possibly bfloat16 (or float16) to float32 # (older PyTorch versions before 2.1 don't support `interpolate` on bf16) high_res_multimasks = ( F.interpolate( low_res_multimasks.squeeze(1).float(), size=(self.image_size, self.image_size), mode="bilinear", align_corners=False, ) .unsqueeze(1) .to(low_res_multimasks.dtype) ) sam_output_token = sam_output_tokens[:, :, 0] if multimask_output: # take the best mask prediction (with the highest IoU estimation) best_iou_inds = torch.argmax(iou_scores, dim=-1) batch_inds = torch.arange(batch_size, device=high_res_multimasks.device) object_batch_inds = torch.arange(num_objects, device=high_res_multimasks.device) low_res_masks = low_res_multimasks[batch_inds, object_batch_inds, best_iou_inds] high_res_masks = high_res_multimasks[batch_inds, object_batch_inds, best_iou_inds] if sam_output_tokens.size(2) > 1: sam_output_token = sam_output_tokens[batch_inds, object_batch_inds, best_iou_inds] else: low_res_masks, high_res_masks = low_res_multimasks[:, :, 0], high_res_multimasks[:, :, 0] # Extract object pointer from the SAM output token (with occlusion handling) object_pointer = self.object_pointer_proj(sam_output_token) lambda_is_obj_appearing = is_obj_appearing.to(object_pointer.dtype) object_pointer = lambda_is_obj_appearing * object_pointer object_pointer = object_pointer + (1 - lambda_is_obj_appearing) * self.no_object_pointer return Sam2VideoImageSegmentationOutput( iou_scores=iou_scores, pred_masks=low_res_masks, high_res_masks=high_res_masks, object_pointer=object_pointer, object_score_logits=object_score_logits, image_embeddings=image_embeddings, vision_hidden_states=vision_hidden_states, vision_attentions=vision_attentions, ) def _use_mask_as_output( self, backbone_features: torch.Tensor, high_res_features: list[torch.Tensor], mask_inputs: torch.Tensor, ) -> Sam2VideoImageSegmentationOutput: """ Directly turn binary `mask_inputs` into a output mask logits without using SAM. (same input and output shapes as in forward above). """ # Use -10/+20 as logits for neg/pos pixels (very close to 0/1 in prob after sigmoid). out_scale, out_bias = 20.0, -10.0 # sigmoid(-10.0)=4.5398e-05 mask_inputs_float = mask_inputs.to(backbone_features[0].dtype) # Ensure mask is at self.image_size resolution for consistency if mask_inputs_float.shape[-2:] != (self.image_size, self.image_size): mask_inputs_float = F.interpolate( mask_inputs_float.float(), size=(self.image_size, self.image_size), align_corners=False, mode="bilinear", antialias=True, ).to(mask_inputs.dtype) high_res_masks = mask_inputs_float * out_scale + out_bias low_res_masks = F.interpolate( high_res_masks.float(), size=self.prompt_encoder.mask_input_size, align_corners=False, mode="bilinear", antialias=True, # use antialias for downsampling ).to(backbone_features[0].dtype) # a dummy IoU prediction of all 1's under mask input iou_scores = mask_inputs.new_ones(mask_inputs.size(0), 1).to(backbone_features[0].dtype) # produce an object pointer using the SAM decoder from the mask input object_pointer = self._single_frame_forward( input_masks=self.mask_downsample(mask_inputs_float.to(backbone_features[0].dtype)), image_embeddings=high_res_features + [backbone_features], ).object_pointer # In this method, we are treating mask_input as output, e.g. using it directly to create spatial mem; # Below, we follow the same design axiom to use mask_input to decide if obj appears or not instead of relying # on the object_scores from the SAM decoder. is_obj_appearing = torch.any(mask_inputs.flatten(1).float() > 0.0, dim=1) is_obj_appearing = is_obj_appearing[..., None] lambda_is_obj_appearing = is_obj_appearing.to(backbone_features[0].dtype) object_score_logits = out_scale * lambda_is_obj_appearing + out_bias object_pointer = lambda_is_obj_appearing * object_pointer object_pointer = object_pointer + (1 - lambda_is_obj_appearing) * self.no_object_pointer return Sam2VideoImageSegmentationOutput( iou_scores=iou_scores, pred_masks=low_res_masks, high_res_masks=high_res_masks, object_pointer=object_pointer, object_score_logits=object_score_logits.unsqueeze(-1), image_embeddings=high_res_features + [backbone_features], ) def _select_closest_cond_frames(self, frame_idx, cond_frame_outputs, max_cond_frame_num): """ Select up to `max_cond_frame_num` conditioning frames from `cond_frame_outputs` that are temporally closest to the current frame at `frame_idx`. Here, we take - a) the closest conditioning frame before `frame_idx` (if any); - b) the closest conditioning frame after `frame_idx` (if any); - c) any other temporally closest conditioning frames until reaching a total of `max_cond_frame_num` conditioning frames. Outputs: - selected_outputs: selected items (keys & values) from `cond_frame_outputs`. - unselected_outputs: items (keys & values) not selected in `cond_frame_outputs`. """ if max_cond_frame_num == -1 or len(cond_frame_outputs) <= max_cond_frame_num: selected_outputs = cond_frame_outputs unselected_outputs = {} else: selected_outputs = {} # the closest conditioning frame before `frame_idx` (if any) idx_before = max((t for t in cond_frame_outputs if t < frame_idx), default=None) if idx_before is not None: selected_outputs[idx_before] = cond_frame_outputs[idx_before] # the closest conditioning frame after `frame_idx` (if any) idx_after = min((t for t in cond_frame_outputs if t >= frame_idx), default=None) if idx_after is not None: selected_outputs[idx_after] = cond_frame_outputs[idx_after] # add other temporally closest conditioning frames until reaching a total # of `max_cond_frame_num` conditioning frames. num_remain = max_cond_frame_num - len(selected_outputs) inds_remain = sorted( (t for t in cond_frame_outputs if t not in selected_outputs), key=lambda x: abs(x - frame_idx), )[:num_remain] selected_outputs.update((t, cond_frame_outputs[t]) for t in inds_remain) unselected_outputs = {t: v for t, v in cond_frame_outputs.items() if t not in selected_outputs} return selected_outputs, unselected_outputs def _gather_memory_frame_outputs( self, inference_session: Sam2VideoInferenceSession, obj_idx: int, frame_idx: int, track_in_reverse_time: bool = False, ) -> list[tuple[int, dict]]: """ Get memory frames from conditioning and non-conditioning outputs. Returns: List of (relative_temporal_offset, output_data) tuples. """ temporal_positions_and_previous_outputs = [] # Add conditioning frame outputs (limited by max_cond_frame_num) conditioning_outputs = inference_session.output_dict_per_obj[obj_idx]["cond_frame_outputs"] if not conditioning_outputs: raise ValueError( "maskmem_features in conditioning outputs cannot be empty when not is_initial_conditioning_frame" ) conditioning_outputs, unselected_conditioning_outputs = self._select_closest_cond_frames( frame_idx, conditioning_outputs, max_cond_frame_num=self.config.max_cond_frame_num ) # Store (temporal_position, output_data) tuples temporal_positions_and_previous_outputs = [(0, out) for out in conditioning_outputs.values()] # Add non-conditioning memory frames (up to self.num_maskmem - 1) # These are typically frames tracked by the model without direct user input. # Frames are selected with a stride, prioritizing the most recent ones. Here we only support stride = 1 for simplicity. for relative_temporal_offset in range(self.num_maskmem - 1, 0, -1): # relative_temporal_offset: how many frames before (or after if reversing) the current frame if not track_in_reverse_time: previous_frame_idx = frame_idx - relative_temporal_offset else: previous_frame_idx = frame_idx + relative_temporal_offset # check if the output is already stored without using get_output to avoid unnecessary memory transfers between CPU and GPU output_data = inference_session.output_dict_per_obj[obj_idx]["non_cond_frame_outputs"].get( previous_frame_idx, unselected_conditioning_outputs.get(previous_frame_idx, None) ) temporal_positions_and_previous_outputs.append((relative_temporal_offset, output_data)) return temporal_positions_and_previous_outputs def _build_memory_attention_inputs( self, temporal_positions_and_previous_outputs: list[tuple[int, dict]], device: torch.device, ) -> tuple[list[torch.Tensor], list[torch.Tensor]]: """ Concatenate memory features and positional embeddings from previous frames. Returns: Tuple of (memories_to_concatenate, memory_positional_embeddings_to_concatenate). """ memories_to_concatenate = [] memory_positional_embeddings_to_concatenate = [] for relative_temporal_offset, prev_output_data in temporal_positions_and_previous_outputs: if prev_output_data is None: continue # Skip if no output data for this temporal position (e.g., padding frames) # Load memory features (potentially from CPU to GPU) # Features are flattened: (Batch, Channels, H, W) -> (H*W, Batch, Channels) memory_features = prev_output_data["maskmem_features"].to(device, non_blocking=True) memories_to_concatenate.append(memory_features) # Spatial positional encoding (potentially from CPU to GPU) spatial_memory_pos_embed = prev_output_data["maskmem_pos_enc"].to(device, non_blocking=True) # Add temporal positional encoding # self.memory_temporal_positional_encoding shape: (NumMaskMem, 1, 1, MemDim) combined_memory_pos_embed = ( spatial_memory_pos_embed + self.memory_temporal_positional_encoding[relative_temporal_offset - 1] ) memory_positional_embeddings_to_concatenate.append(combined_memory_pos_embed) return memories_to_concatenate, memory_positional_embeddings_to_concatenate def _get_object_pointers( self, inference_session: Sam2VideoInferenceSession, obj_idx: int, frame_idx: int, num_total_frames: int, device: torch.device, track_in_reverse_time: bool = False, streaming: bool = False, ) -> tuple[list[int], list[torch.Tensor], int]: """ Get object pointers and their positional embeddings from past frames. Returns: Tuple of (temporal_offsets, pointer_tokens, max_object_pointers_to_use). """ temporal_position_sign_multiplier = -1 if track_in_reverse_time else 1 # Determine max object pointers to use if streaming: max_object_pointers_to_use = self.config.max_object_pointers_in_encoder else: max_object_pointers_to_use = min(num_total_frames, self.config.max_object_pointers_in_encoder) temporal_offsets: list[int] = [] pointer_tokens: list[torch.Tensor] = [] # Add object pointers from selected conditioning frames # Optionally, only include pointers from past frames during evaluation conditioning_outputs = inference_session.output_dict_per_obj[obj_idx]["cond_frame_outputs"] eligible_conditioning_outputs = conditioning_outputs if not self.training: eligible_conditioning_outputs = { temporal_idx: out for temporal_idx, out in conditioning_outputs.items() if (temporal_idx >= frame_idx if track_in_reverse_time else temporal_idx <= frame_idx) } for temporal_idx, out_data in eligible_conditioning_outputs.items(): temporal_difference = (frame_idx - temporal_idx) * temporal_position_sign_multiplier temporal_offsets.append(temporal_difference) pointer_tokens.append(out_data["object_pointer"].to(device)) # Add object pointers from non-conditioning frames (up to max_object_pointers_to_use - 1) for t_diff_offset in range(1, max_object_pointers_to_use): ref_frame_idx = frame_idx + t_diff_offset if track_in_reverse_time else frame_idx - t_diff_offset if ref_frame_idx < 0 or ( not streaming and num_total_frames is not None and ref_frame_idx >= num_total_frames ): break # Stop if frame index is out of bounds # check if the output is already stored without using get_output to avoid unnecessary memory transfers between CPU and GPU out_data = inference_session.output_dict_per_obj[obj_idx]["non_cond_frame_outputs"].get( ref_frame_idx, None ) if out_data is not None: temporal_offsets.append(t_diff_offset) pointer_tokens.append(out_data["object_pointer"].to(device)) return temporal_offsets, pointer_tokens, max_object_pointers_to_use def _process_object_pointers( self, temporal_offsets: list[int], pointer_tokens: list[torch.Tensor], max_object_pointers_to_use: int, batch_size: int, num_channels: int, device: torch.device, ) -> tuple[torch.Tensor, torch.Tensor]: """ Process object pointers and compute their positional embeddings. Returns: Tuple of (object_pointers, object_pointers_pos_embed). """ if not pointer_tokens: return None, None # Stack object pointers: List of (Batch, Channels) -> (SeqLen_ptr, Batch, Channels) object_pointers = torch.stack(pointer_tokens, dim=0) if self.config.enable_temporal_pos_encoding_for_object_pointers: max_temporal_diff = float(max_object_pointers_to_use - 1) # Determine dimensionality for temporal positional encoding of pointers pointer_tpos_dim = num_channels # Normalize temporal differences before sine PE calculation normalized_temporal_diffs = ( torch.tensor(temporal_offsets, device=device, dtype=torch.float32) / max_temporal_diff ) sine_pe = get_1d_sine_pe(normalized_temporal_diffs, dim=pointer_tpos_dim).to(object_pointers.dtype) projected_sine_pe = self.temporal_positional_encoding_projection_layer(sine_pe) object_pointers_pos_embed = projected_sine_pe.unsqueeze(1).expand(-1, batch_size, self.mem_dim) else: object_pointers_pos_embed = object_pointers.new_zeros( len(temporal_offsets), batch_size, self.mem_dim, dtype=object_pointers.dtype ) if self.mem_dim < num_channels: # If memory dimension is smaller, reshape/split pointers and repeat positional encoding num_splits = num_channels // self.mem_dim object_pointers = object_pointers.reshape(-1, batch_size, num_splits, self.mem_dim) object_pointers = object_pointers.permute(0, 2, 1, 3).flatten( 0, 1 ) # (SeqLen_ptr*num_splits, Batch, MemDim) object_pointers_pos_embed = object_pointers_pos_embed.repeat_interleave(num_splits, dim=0) return object_pointers, object_pointers_pos_embed def _prepare_memory_conditioned_features( self, inference_session: Sam2VideoInferenceSession, frame_idx: int, obj_idx: int, is_initial_conditioning_frame: bool, current_vision_features: list[torch.Tensor], current_vision_positional_embeddings: list[torch.Tensor], num_total_frames: int, track_in_reverse_time: bool = False, streaming: bool = False, ) -> torch.Tensor: """ Fuse current frame's visual features with memory from previous frames for enhanced object tracking. This method conditions the current frame's visual features on temporal memory from previous frames, enabling consistent object tracking across video sequences. For initial conditioning frames, it uses no-memory embeddings. For subsequent frames, it retrieves and integrates memory features from both conditioning frames (user interactions) and non-conditioning frames (tracked results) via cross-attention. Args: inference_session (`Sam2VideoInferenceSession`): The video inference session object. frame_idx (`int`): Index of the current frame being processed. obj_idx (`int`): Index of the object being processed. is_initial_conditioning_frame (`bool`): Whether this is an initial conditioning frame with user inputs (True) or a subsequent tracking frame (False). current_vision_features (`torch.Tensor`): Highest-level vision features of shape `(seq_len, batch_size, channels)`. current_vision_positional_embeddings (`torch.Tensor`): Positional embedding tensors corresponding to the highest-level vision features. num_total_frames (`int`): Total number of frames in the video sequence. track_in_reverse_time (`bool`, *optional*, defaults to `False`): Whether tracking is performed in reverse temporal order. streaming (`bool`, *optional*, defaults to `False`): Whether this is streaming inference mode. Returns: `torch.Tensor`: Memory-conditioned feature tensor of shape `(batch_size, channels, height, width)` suitable for input to the SAM decoder. """ # Get dimensions from the highest-level (lowest-resolution) feature map batch_size = current_vision_features.size(1) num_channels = self.hidden_dim height, width = self.backbone_feature_sizes[-1] device = current_vision_features.device # If memory is disabled (e.g., for single image SAM), return current features directly. if self.num_maskmem == 0: # Permute (SeqLen, Batch, Channels) -> (Batch, Channels, SeqLen) then view as (Batch, Channels, Height, Width) # Assuming SeqLen = Height * Width for the last feature map current_feature_map = current_vision_features.permute(1, 2, 0).view( batch_size, num_channels, height, width ) return current_feature_map # Step 1: Handle initial conditioning frames if is_initial_conditioning_frame: # For initial conditioning frames, no prior memory is used directly in this block. # If configured, directly add a learnable "no memory" embedding. # current_vision_features has shape (SeqLen, Batch, Channels) conditioned_feature_map_flat = current_vision_features + self.no_memory_embedding # Reshape to (Batch, Channels, Height, Width) conditioned_feature_map = conditioned_feature_map_flat.permute(1, 2, 0).view( batch_size, num_channels, height, width ) return conditioned_feature_map # Step 2: Get memory frames and concatenate their features temporal_positions_and_previous_outputs = self._gather_memory_frame_outputs( inference_session, obj_idx, frame_idx, track_in_reverse_time ) memories_to_concatenate, memory_positional_embeddings_to_concatenate = self._build_memory_attention_inputs( temporal_positions_and_previous_outputs, device ) # Step 3: Get and process object pointers temporal_offsets, pointer_tokens, max_object_pointers_to_use = self._get_object_pointers( inference_session, obj_idx, frame_idx, num_total_frames, device, track_in_reverse_time, streaming ) num_object_pointer_tokens = 0 if pointer_tokens: object_pointers, object_pointers_pos_embed = self._process_object_pointers( temporal_offsets, pointer_tokens, max_object_pointers_to_use, batch_size, num_channels, device ) if object_pointers is not None: memories_to_concatenate.append(object_pointers) memory_positional_embeddings_to_concatenate.append(object_pointers_pos_embed) num_object_pointer_tokens = object_pointers.shape[0] # Step 4: Concatenate all retrieved memories and their positional embeddings combined_memory = torch.cat(memories_to_concatenate, dim=0) combined_memory_positional_embeddings = torch.cat(memory_positional_embeddings_to_concatenate, dim=0) # Step 5: Forward through the memory attention mechanism conditioned_feature_map_flat = self.memory_attention( current_vision_features=current_vision_features, current_vision_position_embeddings=current_vision_positional_embeddings, memory=combined_memory, memory_posision_embeddings=combined_memory_positional_embeddings, # Corrected typo from API num_object_pointer_tokens=num_object_pointer_tokens, ) # Reshape from (Batch, H*W, Channels) to (Batch, Channels, Height, Width) conditioned_feature_map = ( conditioned_feature_map_flat.squeeze(1).permute(0, 2, 1).view(batch_size, num_channels, height, width) ) return conditioned_feature_map def _use_multimask(self, is_init_cond_frame: bool, point_inputs: Optional[dict]) -> bool: """Whether to use multimask output in the SAM head.""" num_pts = 0 if point_inputs is None else point_inputs["point_labels"].size(2) multimask_output = ( self.config.multimask_output_in_sam and (is_init_cond_frame or self.config.multimask_output_for_tracking) and (self.config.multimask_min_pt_num <= num_pts <= self.config.multimask_max_pt_num) ) return multimask_output def _run_single_frame_inference( self, inference_session: Sam2VideoInferenceSession, frame_idx: int, obj_idx: int, batch_size: int, is_init_cond_frame: bool, point_inputs: Optional[torch.Tensor], mask_inputs: Optional[torch.Tensor], reverse: bool, prev_sam_mask_logits: Optional[torch.Tensor] = None, streaming: bool = False, ) -> dict[str, Any]: """ Perform a single tracking step for video object segmentation. Args: inference_session (`Sam2VideoInferenceSession`): The video inference session object. frame_idx (`int`): Index of the current frame. obj_idx (`int`): Index of the current object. batch_size (`int`): Batch size of the current frame. is_init_cond_frame (`bool`): Whether this is an initial conditioning frame with user inputs. point_inputs (`dict`, *optional*): Point prompt inputs for the current frame. mask_inputs (`torch.Tensor`, *optional*): Mask prompt inputs for the current frame. reverse (`bool`, *optional*, defaults to `False`): Whether to track in reverse time order. prev_sam_mask_logits (`torch.Tensor`, *optional*): Previously predicted SAM mask logits that can be fed with new clicks. streaming (`bool`, *optional*, defaults to `False`): Whether this is streaming inference. Returns: `dict`: Dictionary containing the tracking results for the current frame, including: - pred_masks: Predicted low-resolution masks. - object_pointer: Object pointer for memory. - high_res_masks: High-resolution masks for batched memory encoding. - object_score_logits: Object score logits (inference only). """ # Retrieve correct image features current_vision_feats, current_vision_pos_embeds = self._prepare_vision_features( inference_session, frame_idx, batch_size ) # point and mask should not appear as input simultaneously on the same frame if point_inputs is not None and mask_inputs is not None: raise ValueError( "point_inputs and mask_inputs should not appear as input simultaneously on the same frame" ) # High-resolution feature maps for the SAM head, reshape (HW)BC => BCHW if len(current_vision_feats) > 1: high_res_features = [ x.permute(1, 2, 0).view(x.size(1), x.size(2), *s) for x, s in zip(current_vision_feats[:-1], self.backbone_feature_sizes[:-1]) ] else: high_res_features = None if mask_inputs is not None: # We directly output the mask input (see it as a GT mask) without using a SAM prompt encoder + mask decoder. pix_feat = current_vision_feats[-1].permute(1, 2, 0) pix_feat = pix_feat.view(-1, self.hidden_dim, *self.backbone_feature_sizes[-1]) sam_outputs = self._use_mask_as_output(pix_feat, high_res_features, mask_inputs) else: # fused the visual feature with previous memory features in the memory bank pix_feat = self._prepare_memory_conditioned_features( inference_session=inference_session, frame_idx=frame_idx, obj_idx=obj_idx, is_initial_conditioning_frame=is_init_cond_frame, current_vision_features=current_vision_feats[-1], current_vision_positional_embeddings=current_vision_pos_embeds[-1], num_total_frames=inference_session.num_frames, track_in_reverse_time=reverse, streaming=streaming, ) # apply SAM-style segmentation head # here we might feed previously predicted low-res SAM mask logits into the SAM mask decoder, # e.g. in demo where such logits come from earlier interaction instead of correction sampling # (in this case, any `mask_inputs` shouldn't reach here as they are sent to _use_mask_as_output instead) if prev_sam_mask_logits is not None: mask_inputs = prev_sam_mask_logits multimask_output = self._use_multimask(is_init_cond_frame, point_inputs) sam_outputs = self._single_frame_forward( pixel_values=None, # Vision features already computed input_points=point_inputs["point_coords"] if point_inputs is not None else None, input_labels=point_inputs["point_labels"] if point_inputs is not None else None, input_masks=mask_inputs, image_embeddings=high_res_features + [pix_feat], multimask_output=multimask_output, ) # Memory encoding is now handled in batch by the caller (forward method) current_out = { "pred_masks": sam_outputs.pred_masks, "object_pointer": sam_outputs.object_pointer, "high_res_masks": sam_outputs.high_res_masks, # Needed for batched memory encoding } if not self.training: current_out["object_score_logits"] = sam_outputs.object_score_logits return current_out def _encode_new_memory( self, current_vision_feats: torch.Tensor, pred_masks_high_res: torch.Tensor, object_score_logits: torch.Tensor, is_mask_from_pts: bool, ) -> tuple[torch.Tensor, list[torch.Tensor]]: """Encode the current image and its prediction into a memory feature.""" batch_size = current_vision_feats.size(1) # batch size on this frame channels = self.hidden_dim height, width = self.backbone_feature_sizes[-1] # top-level (lowest-resolution) feature size mask_input_size_h, mask_input_size_w = self.prompt_encoder.mask_input_size mask_mem_size_h = mask_input_size_h * 4 mask_mem_size_w = mask_input_size_w * 4 if pred_masks_high_res.shape[2:] != (mask_mem_size_h, mask_mem_size_w): # downsample the predicted high-res masks into the mask encoder input size pred_masks_high_res = F.interpolate( pred_masks_high_res.float(), size=(mask_mem_size_h, mask_mem_size_w), align_corners=False, mode="bilinear", antialias=True, # use antialias for downsampling ).to(pred_masks_high_res.dtype) # top-level feature, (HW)BC => BCHW pix_feat = current_vision_feats.permute(1, 2, 0).view(batch_size, channels, height, width) if is_mask_from_pts and not self.training: # binarize the mask logits mask_for_mem = (pred_masks_high_res > 0).to(pred_masks_high_res.dtype) else: # apply sigmoid on the raw mask logits to turn them into range (0, 1) mask_for_mem = torch.sigmoid(pred_masks_high_res) # apply scale and bias terms to the sigmoid probabilities mask_for_mem = mask_for_mem * self.config.sigmoid_scale_for_mem_enc mask_for_mem = mask_for_mem + self.config.sigmoid_bias_for_mem_enc maskmem_features, maskmem_pos_enc = self.memory_encoder( pix_feat, mask_for_mem, ) # add a no-object embedding to the spatial memory to indicate that the frame # is predicted to be occluded (i.e. no object is appearing in the frame) if self.occlusion_spatial_embedding_parameter is not None: is_obj_appearing = (object_score_logits > 0).float() maskmem_features += (1 - is_obj_appearing[..., None]) * self.occlusion_spatial_embedding_parameter[ ..., None, None ].expand(*maskmem_features.shape) # convert to bfloat16 to save memory, and for consistency with the original implementation maskmem_features = maskmem_features.to(torch.bfloat16).flatten(2).permute(2, 0, 1) maskmem_pos_enc = maskmem_pos_enc.to(pred_masks_high_res.dtype).flatten(2).permute(2, 0, 1) return maskmem_features, maskmem_pos_enc def _batch_encode_memories( self, inference_session: Sam2VideoInferenceSession, frame_idx: int, objects_needing_memory_encoding: list[int], high_res_masks_for_memory: list[torch.Tensor], object_score_logits_for_memory: list[torch.Tensor], is_mask_from_pts_per_obj: list[bool], ): """ Batch encode memories for multiple objects at once. Args: inference_session: The video inference session object frame_idx: Index of the current frame objects_needing_memory_encoding: List of object indices that need memory encoding high_res_masks_for_memory: List of high-resolution masks for each object object_score_logits_for_memory: List of object score logits for each object is_mask_from_pts_per_obj: List of booleans indicating if mask is from points for each object """ if not objects_needing_memory_encoding: return # Get vision features once for all objects current_vision_feats, _ = self._prepare_vision_features(inference_session, frame_idx, batch_size=1) # Stack all high-res masks and object scores high_res_masks_batched = torch.cat(high_res_masks_for_memory, dim=0) object_score_logits_batched = torch.cat(object_score_logits_for_memory, dim=0) # Expand vision features to match batch size expanded_vision_feats = current_vision_feats[-1].expand(-1, len(objects_needing_memory_encoding), -1) # Encode all memories in one batch call maskmem_features_batched, maskmem_pos_enc_batched = self._encode_new_memory( current_vision_feats=expanded_vision_feats, pred_masks_high_res=high_res_masks_batched, object_score_logits=object_score_logits_batched, is_mask_from_pts=any(is_mask_from_pts_per_obj), ) # Split and store encoded memories per object for i, obj_idx in enumerate(objects_needing_memory_encoding): # Extract per-object memory from batched result maskmem_features = maskmem_features_batched[:, i : i + 1] maskmem_pos_enc = maskmem_pos_enc_batched[:, i : i + 1] # Update the stored output with memory features output_dict = inference_session.output_dict_per_obj[obj_idx] # Determine if this was a conditioning frame storage_key = ( "cond_frame_outputs" if frame_idx in output_dict["cond_frame_outputs"] else "non_cond_frame_outputs" ) if frame_idx in output_dict[storage_key]: output_dict[storage_key][frame_idx]["maskmem_features"] = maskmem_features output_dict[storage_key][frame_idx]["maskmem_pos_enc"] = maskmem_pos_enc @torch.inference_mode() @auto_docstring( custom_intro=""" Propagate the objects through the video frames. Used when initializing an inference session with a whole video. Yields Sam2VideoSegmentationOutput for each frame. """ ) def propagate_in_video_iterator( self, inference_session: Sam2VideoInferenceSession, start_frame_idx: Optional[int] = None, max_frame_num_to_track: Optional[int] = None, reverse: bool = False, show_progress_bar: bool = False, ) -> Iterator[Sam2VideoSegmentationOutput]: r""" inference_session (`Sam2VideoInferenceSession`): The video inference session object. start_frame_idx (`int`, *optional*): The starting frame index for propagation. Need to be provided if `forward` hasn't been called on new inputs yet. If not provided, the starting frame index will be the earliest frame with input points. max_frame_num_to_track (`int`, *optional*): The maximum number of frames to track. reverse (`bool`, *optional*, defaults to `False`): Whether to propagate in reverse. show_progress_bar (`bool`, *optional*, defaults to `False`): Whether to show a progress bar during propagation. """ num_frames = inference_session.num_frames # set start index, end index, and processing order if start_frame_idx is None: # default: start from the earliest frame with input points frames_with_inputs = [ frame_idx for obj_output_dict in inference_session.output_dict_per_obj.values() for frame_idx in obj_output_dict["cond_frame_outputs"] ] if not frames_with_inputs: raise ValueError( "Cannot determine the starting frame index; please specify it manually, or run inference on a frame with inputs first." ) start_frame_idx = min(frames_with_inputs) if max_frame_num_to_track is None: # default: track all the frames in the video max_frame_num_to_track = num_frames if reverse: end_frame_idx = max(start_frame_idx - max_frame_num_to_track, 0) if start_frame_idx > 0: processing_order = range(start_frame_idx, end_frame_idx - 1, -1) else: processing_order = [] # skip reverse tracking if starting from frame 0 else: end_frame_idx = min(start_frame_idx + max_frame_num_to_track, num_frames - 1) processing_order = range(start_frame_idx, end_frame_idx + 1) for frame_idx in tqdm(processing_order, desc="propagate in video", disable=not show_progress_bar): sam2_video_output = self(inference_session, frame_idx=frame_idx, reverse=reverse) yield sam2_video_output __all__ = ["Sam2VideoModel", "Sam2VideoInferenceSession", "Sam2VideoPreTrainedModel"]
Sam2VideoModel
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 9896, "end": 10198 }
class ____(BaseModel): """ DagProcessor info serializer for responses. """ status: Annotated[str | None, Field(title="Status")] = None latest_dag_processor_heartbeat: Annotated[str | None, Field(title="Latest Dag Processor Heartbeat")] = ( None )
DagProcessorInfoResponse
python
OmkarPathak__pygorithm
tests/test_searching.py
{ "start": 2321, "end": 2590 }
class ____(TestSearchingAlgorithm): def test_exponential_search(self): self.assertEqual(exponential_search.search(self.array, 7), 7) alpha_result = linear_search.search(self.alphaArray, 'n') self.assertIs(alpha_result, 5)
TestExponentialSearch
python
run-llama__llama_index
llama-index-core/llama_index/core/indices/struct_store/sql_retriever.py
{ "start": 6284, "end": 18186 }
class ____(BaseRetriever, PromptMixin): """ Text-to-SQL Retriever. Retrieves via text. Args: sql_database (SQLDatabase): SQL database. text_to_sql_prompt (BasePromptTemplate): Prompt template for text-to-sql. Defaults to DEFAULT_TEXT_TO_SQL_PROMPT. context_query_kwargs (dict): Mapping from table name to context query. Defaults to None. tables (Union[List[str], List[Table]]): List of table names or Table objects. table_retriever (ObjectRetriever[SQLTableSchema]): Object retriever for SQLTableSchema objects. Defaults to None. rows_retriever (Dict[str, VectorIndexRetriever]): a mapping between table name and a vector index retriever of its rows. Defaults to None. context_str_prefix (str): Prefix for context string. Defaults to None. return_raw (bool): Whether to return plain-text dump of SQL results, or parsed into Nodes. handle_sql_errors (bool): Whether to handle SQL errors. Defaults to True. sql_only (bool) : Whether to get only sql and not the sql query result. Default to False. llm (Optional[LLM]): Language model to use. """ def __init__( self, sql_database: SQLDatabase, text_to_sql_prompt: Optional[BasePromptTemplate] = None, context_query_kwargs: Optional[dict] = None, tables: Optional[Union[List[str], List[Table]]] = None, table_retriever: Optional[ObjectRetriever[SQLTableSchema]] = None, rows_retrievers: Optional[dict[str, BaseRetriever]] = None, cols_retrievers: Optional[dict[str, dict[str, BaseRetriever]]] = None, context_str_prefix: Optional[str] = None, sql_parser_mode: SQLParserMode = SQLParserMode.DEFAULT, llm: Optional[LLM] = None, embed_model: Optional[BaseEmbedding] = None, return_raw: bool = True, handle_sql_errors: bool = True, sql_only: bool = False, callback_manager: Optional[CallbackManager] = None, verbose: bool = False, **kwargs: Any, ) -> None: """Initialize params.""" self._sql_retriever = SQLRetriever(sql_database, return_raw=return_raw) self._sql_database = sql_database self._get_tables = self._load_get_tables_fn( sql_database, tables, context_query_kwargs, table_retriever ) self._context_str_prefix = context_str_prefix self._llm = llm or Settings.llm self._text_to_sql_prompt = text_to_sql_prompt or DEFAULT_TEXT_TO_SQL_PROMPT self._sql_parser_mode = sql_parser_mode embed_model = embed_model or Settings.embed_model self._sql_parser = self._load_sql_parser(sql_parser_mode, embed_model) self._handle_sql_errors = handle_sql_errors self._sql_only = sql_only self._verbose = verbose # To retrieve relevant rows or cols from each retrieved table self._rows_retrievers = rows_retrievers self._cols_retrievers = cols_retrievers super().__init__( callback_manager=callback_manager or Settings.callback_manager, verbose=verbose, ) def _get_prompts(self) -> Dict[str, Any]: """Get prompts.""" return { "text_to_sql_prompt": self._text_to_sql_prompt, } def _update_prompts(self, prompts: PromptDictType) -> None: """Update prompts.""" if "text_to_sql_prompt" in prompts: self._text_to_sql_prompt = prompts["text_to_sql_prompt"] def _get_prompt_modules(self) -> PromptMixinType: """Get prompt modules.""" return {} def _load_sql_parser( self, sql_parser_mode: SQLParserMode, embed_model: BaseEmbedding ) -> BaseSQLParser: """Load SQL parser.""" if sql_parser_mode == SQLParserMode.DEFAULT: return DefaultSQLParser() elif sql_parser_mode == SQLParserMode.PGVECTOR: return PGVectorSQLParser(embed_model=embed_model) else: raise ValueError(f"Unknown SQL parser mode: {sql_parser_mode}") def _load_get_tables_fn( self, sql_database: SQLDatabase, tables: Optional[Union[List[str], List[Table]]] = None, context_query_kwargs: Optional[dict] = None, table_retriever: Optional[ObjectRetriever[SQLTableSchema]] = None, ) -> Callable[[str], List[SQLTableSchema]]: """Load get_tables function.""" context_query_kwargs = context_query_kwargs or {} if table_retriever is not None: return lambda query_str: cast(Any, table_retriever).retrieve(query_str) else: if tables is not None: table_names: List[str] = [ t.name if isinstance(t, Table) else t for t in tables ] else: table_names = list(sql_database.get_usable_table_names()) context_strs = [context_query_kwargs.get(t, None) for t in table_names] table_schemas = [ SQLTableSchema(table_name=t, context_str=c) for t, c in zip(table_names, context_strs) ] return lambda _: table_schemas def retrieve_with_metadata( self, str_or_query_bundle: QueryType ) -> Tuple[List[NodeWithScore], Dict]: """Retrieve with metadata.""" if isinstance(str_or_query_bundle, str): query_bundle = QueryBundle(str_or_query_bundle) else: query_bundle = str_or_query_bundle table_desc_str = self._get_table_context(query_bundle) logger.info(f"> Table desc str: {table_desc_str}") if self._verbose: print(f"> Table desc str: {table_desc_str}") response_str = self._llm.predict( self._text_to_sql_prompt, query_str=query_bundle.query_str, schema=table_desc_str, dialect=self._sql_database.dialect, ) sql_query_str = self._sql_parser.parse_response_to_sql( response_str, query_bundle ) # assume that it's a valid SQL query logger.debug(f"> Predicted SQL query: {sql_query_str}") if self._verbose: print(f"> Predicted SQL query: {sql_query_str}") if self._sql_only: sql_only_node = TextNode(text=f"{sql_query_str}") retrieved_nodes = [NodeWithScore(node=sql_only_node)] metadata = {"result": sql_query_str} else: try: retrieved_nodes, metadata = self._sql_retriever.retrieve_with_metadata( sql_query_str ) except BaseException as e: # if handle_sql_errors is True, then return error message if self._handle_sql_errors: err_node = TextNode(text=f"Error: {e!s}") retrieved_nodes = [NodeWithScore(node=err_node)] metadata = {} else: raise return retrieved_nodes, {"sql_query": sql_query_str, **metadata} async def aretrieve_with_metadata( self, str_or_query_bundle: QueryType ) -> Tuple[List[NodeWithScore], Dict]: """Async retrieve with metadata.""" if isinstance(str_or_query_bundle, str): query_bundle = QueryBundle(str_or_query_bundle) else: query_bundle = str_or_query_bundle table_desc_str = self._get_table_context(query_bundle) logger.info(f"> Table desc str: {table_desc_str}") response_str = await self._llm.apredict( self._text_to_sql_prompt, query_str=query_bundle.query_str, schema=table_desc_str, dialect=self._sql_database.dialect, ) sql_query_str = self._sql_parser.parse_response_to_sql( response_str, query_bundle ) # assume that it's a valid SQL query logger.debug(f"> Predicted SQL query: {sql_query_str}") if self._sql_only: sql_only_node = TextNode(text=f"{sql_query_str}") retrieved_nodes = [NodeWithScore(node=sql_only_node)] metadata: Dict[str, Any] = {} else: try: ( retrieved_nodes, metadata, ) = await self._sql_retriever.aretrieve_with_metadata(sql_query_str) except BaseException as e: # if handle_sql_errors is True, then return error message if self._handle_sql_errors: err_node = TextNode(text=f"Error: {e!s}") retrieved_nodes = [NodeWithScore(node=err_node)] metadata = {} else: raise return retrieved_nodes, {"sql_query": sql_query_str, **metadata} def _retrieve(self, query_bundle: QueryBundle) -> List[NodeWithScore]: """Retrieve nodes given query.""" retrieved_nodes, _ = self.retrieve_with_metadata(query_bundle) return retrieved_nodes async def _aretrieve(self, query_bundle: QueryBundle) -> List[NodeWithScore]: """Async retrieve nodes given query.""" retrieved_nodes, _ = await self.aretrieve_with_metadata(query_bundle) return retrieved_nodes def _get_table_context(self, query_bundle: QueryBundle) -> str: """Get table context string.""" table_schema_objs = self._get_tables(query_bundle.query_str) context_strs = [] for table_schema_obj in table_schema_objs: # first append table info + additional context table_info = self._sql_database.get_single_table_info( table_schema_obj.table_name ) if table_schema_obj.context_str: table_opt_context = " The table description is: " table_opt_context += table_schema_obj.context_str table_info += table_opt_context # also lookup vector index to return relevant table rows # if rows_retrievers was not passed, no rows will be returned if self._rows_retrievers is not None: rows_retriever = self._rows_retrievers[table_schema_obj.table_name] relevant_nodes = rows_retriever.retrieve(query_bundle.query_str) if len(relevant_nodes) > 0: table_row_context = "\nHere are some relevant example rows (values in the same order as columns above)\n" for node in relevant_nodes: table_row_context += str(node.get_content()) + "\n" table_info += table_row_context # lookup column index to return relevant column values if self._cols_retrievers is not None: cols_retrievers = self._cols_retrievers[table_schema_obj.table_name] col_values_context = ( "\nHere are some relevant values of text columns:\n" ) has_col_values = False for col_name, retriever in cols_retrievers.items(): relevant_nodes = retriever.retrieve(query_bundle.query_str) if len(relevant_nodes) > 0: col_values_context += ( f"{col_name}: " + ", ".join( [str(node.get_content()) for node in relevant_nodes] ) + "\n" ) has_col_values = True if has_col_values: table_info += col_values_context if self._verbose: print(f"> Table Info: {table_info}") context_strs.append(table_info) return "\n\n".join(context_strs)
NLSQLRetriever
python
plotly__plotly.py
plotly/graph_objs/layout/template/_data.py
{ "start": 235, "end": 49447 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout.template" _path_str = "layout.template.data" _valid_props = { "bar", "barpolar", "box", "candlestick", "carpet", "choropleth", "choroplethmap", "choroplethmapbox", "cone", "contour", "contourcarpet", "densitymap", "densitymapbox", "funnel", "funnelarea", "heatmap", "histogram", "histogram2d", "histogram2dcontour", "icicle", "image", "indicator", "isosurface", "mesh3d", "ohlc", "parcats", "parcoords", "pie", "sankey", "scatter", "scatter3d", "scattercarpet", "scattergeo", "scattergl", "scattermap", "scattermapbox", "scatterpolar", "scatterpolargl", "scattersmith", "scatterternary", "splom", "streamtube", "sunburst", "surface", "table", "treemap", "violin", "volume", "waterfall", } @property def barpolar(self): """ The 'barpolar' property is a tuple of instances of Barpolar that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Barpolar - A list or tuple of dicts of string/value properties that will be passed to the Barpolar constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Barpolar] """ return self["barpolar"] @barpolar.setter def barpolar(self, val): self["barpolar"] = val @property def bar(self): """ The 'bar' property is a tuple of instances of Bar that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Bar - A list or tuple of dicts of string/value properties that will be passed to the Bar constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Bar] """ return self["bar"] @bar.setter def bar(self, val): self["bar"] = val @property def box(self): """ The 'box' property is a tuple of instances of Box that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Box - A list or tuple of dicts of string/value properties that will be passed to the Box constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Box] """ return self["box"] @box.setter def box(self, val): self["box"] = val @property def candlestick(self): """ The 'candlestick' property is a tuple of instances of Candlestick that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Candlestick - A list or tuple of dicts of string/value properties that will be passed to the Candlestick constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Candlestick] """ return self["candlestick"] @candlestick.setter def candlestick(self, val): self["candlestick"] = val @property def carpet(self): """ The 'carpet' property is a tuple of instances of Carpet that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Carpet - A list or tuple of dicts of string/value properties that will be passed to the Carpet constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Carpet] """ return self["carpet"] @carpet.setter def carpet(self, val): self["carpet"] = val @property def choroplethmapbox(self): """ The 'choroplethmapbox' property is a tuple of instances of Choroplethmapbox that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Choroplethmapbox - A list or tuple of dicts of string/value properties that will be passed to the Choroplethmapbox constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Choroplethmapbox] """ return self["choroplethmapbox"] @choroplethmapbox.setter def choroplethmapbox(self, val): self["choroplethmapbox"] = val @property def choroplethmap(self): """ The 'choroplethmap' property is a tuple of instances of Choroplethmap that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Choroplethmap - A list or tuple of dicts of string/value properties that will be passed to the Choroplethmap constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Choroplethmap] """ return self["choroplethmap"] @choroplethmap.setter def choroplethmap(self, val): self["choroplethmap"] = val @property def choropleth(self): """ The 'choropleth' property is a tuple of instances of Choropleth that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Choropleth - A list or tuple of dicts of string/value properties that will be passed to the Choropleth constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Choropleth] """ return self["choropleth"] @choropleth.setter def choropleth(self, val): self["choropleth"] = val @property def cone(self): """ The 'cone' property is a tuple of instances of Cone that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Cone - A list or tuple of dicts of string/value properties that will be passed to the Cone constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Cone] """ return self["cone"] @cone.setter def cone(self, val): self["cone"] = val @property def contourcarpet(self): """ The 'contourcarpet' property is a tuple of instances of Contourcarpet that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Contourcarpet - A list or tuple of dicts of string/value properties that will be passed to the Contourcarpet constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Contourcarpet] """ return self["contourcarpet"] @contourcarpet.setter def contourcarpet(self, val): self["contourcarpet"] = val @property def contour(self): """ The 'contour' property is a tuple of instances of Contour that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Contour - A list or tuple of dicts of string/value properties that will be passed to the Contour constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Contour] """ return self["contour"] @contour.setter def contour(self, val): self["contour"] = val @property def densitymapbox(self): """ The 'densitymapbox' property is a tuple of instances of Densitymapbox that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Densitymapbox - A list or tuple of dicts of string/value properties that will be passed to the Densitymapbox constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Densitymapbox] """ return self["densitymapbox"] @densitymapbox.setter def densitymapbox(self, val): self["densitymapbox"] = val @property def densitymap(self): """ The 'densitymap' property is a tuple of instances of Densitymap that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Densitymap - A list or tuple of dicts of string/value properties that will be passed to the Densitymap constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Densitymap] """ return self["densitymap"] @densitymap.setter def densitymap(self, val): self["densitymap"] = val @property def funnelarea(self): """ The 'funnelarea' property is a tuple of instances of Funnelarea that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Funnelarea - A list or tuple of dicts of string/value properties that will be passed to the Funnelarea constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Funnelarea] """ return self["funnelarea"] @funnelarea.setter def funnelarea(self, val): self["funnelarea"] = val @property def funnel(self): """ The 'funnel' property is a tuple of instances of Funnel that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Funnel - A list or tuple of dicts of string/value properties that will be passed to the Funnel constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Funnel] """ return self["funnel"] @funnel.setter def funnel(self, val): self["funnel"] = val @property def heatmap(self): """ The 'heatmap' property is a tuple of instances of Heatmap that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Heatmap - A list or tuple of dicts of string/value properties that will be passed to the Heatmap constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Heatmap] """ return self["heatmap"] @heatmap.setter def heatmap(self, val): self["heatmap"] = val @property def histogram2dcontour(self): """ The 'histogram2dcontour' property is a tuple of instances of Histogram2dContour that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Histogram2dContour - A list or tuple of dicts of string/value properties that will be passed to the Histogram2dContour constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Histogram2dContour] """ return self["histogram2dcontour"] @histogram2dcontour.setter def histogram2dcontour(self, val): self["histogram2dcontour"] = val @property def histogram2d(self): """ The 'histogram2d' property is a tuple of instances of Histogram2d that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Histogram2d - A list or tuple of dicts of string/value properties that will be passed to the Histogram2d constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Histogram2d] """ return self["histogram2d"] @histogram2d.setter def histogram2d(self, val): self["histogram2d"] = val @property def histogram(self): """ The 'histogram' property is a tuple of instances of Histogram that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Histogram - A list or tuple of dicts of string/value properties that will be passed to the Histogram constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Histogram] """ return self["histogram"] @histogram.setter def histogram(self, val): self["histogram"] = val @property def icicle(self): """ The 'icicle' property is a tuple of instances of Icicle that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Icicle - A list or tuple of dicts of string/value properties that will be passed to the Icicle constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Icicle] """ return self["icicle"] @icicle.setter def icicle(self, val): self["icicle"] = val @property def image(self): """ The 'image' property is a tuple of instances of Image that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Image - A list or tuple of dicts of string/value properties that will be passed to the Image constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Image] """ return self["image"] @image.setter def image(self, val): self["image"] = val @property def indicator(self): """ The 'indicator' property is a tuple of instances of Indicator that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Indicator - A list or tuple of dicts of string/value properties that will be passed to the Indicator constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Indicator] """ return self["indicator"] @indicator.setter def indicator(self, val): self["indicator"] = val @property def isosurface(self): """ The 'isosurface' property is a tuple of instances of Isosurface that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Isosurface - A list or tuple of dicts of string/value properties that will be passed to the Isosurface constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Isosurface] """ return self["isosurface"] @isosurface.setter def isosurface(self, val): self["isosurface"] = val @property def mesh3d(self): """ The 'mesh3d' property is a tuple of instances of Mesh3d that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Mesh3d - A list or tuple of dicts of string/value properties that will be passed to the Mesh3d constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Mesh3d] """ return self["mesh3d"] @mesh3d.setter def mesh3d(self, val): self["mesh3d"] = val @property def ohlc(self): """ The 'ohlc' property is a tuple of instances of Ohlc that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Ohlc - A list or tuple of dicts of string/value properties that will be passed to the Ohlc constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Ohlc] """ return self["ohlc"] @ohlc.setter def ohlc(self, val): self["ohlc"] = val @property def parcats(self): """ The 'parcats' property is a tuple of instances of Parcats that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Parcats - A list or tuple of dicts of string/value properties that will be passed to the Parcats constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Parcats] """ return self["parcats"] @parcats.setter def parcats(self, val): self["parcats"] = val @property def parcoords(self): """ The 'parcoords' property is a tuple of instances of Parcoords that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Parcoords - A list or tuple of dicts of string/value properties that will be passed to the Parcoords constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Parcoords] """ return self["parcoords"] @parcoords.setter def parcoords(self, val): self["parcoords"] = val @property def pie(self): """ The 'pie' property is a tuple of instances of Pie that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Pie - A list or tuple of dicts of string/value properties that will be passed to the Pie constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Pie] """ return self["pie"] @pie.setter def pie(self, val): self["pie"] = val @property def sankey(self): """ The 'sankey' property is a tuple of instances of Sankey that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Sankey - A list or tuple of dicts of string/value properties that will be passed to the Sankey constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Sankey] """ return self["sankey"] @sankey.setter def sankey(self, val): self["sankey"] = val @property def scatter3d(self): """ The 'scatter3d' property is a tuple of instances of Scatter3d that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Scatter3d - A list or tuple of dicts of string/value properties that will be passed to the Scatter3d constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Scatter3d] """ return self["scatter3d"] @scatter3d.setter def scatter3d(self, val): self["scatter3d"] = val @property def scattercarpet(self): """ The 'scattercarpet' property is a tuple of instances of Scattercarpet that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Scattercarpet - A list or tuple of dicts of string/value properties that will be passed to the Scattercarpet constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Scattercarpet] """ return self["scattercarpet"] @scattercarpet.setter def scattercarpet(self, val): self["scattercarpet"] = val @property def scattergeo(self): """ The 'scattergeo' property is a tuple of instances of Scattergeo that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Scattergeo - A list or tuple of dicts of string/value properties that will be passed to the Scattergeo constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Scattergeo] """ return self["scattergeo"] @scattergeo.setter def scattergeo(self, val): self["scattergeo"] = val @property def scattergl(self): """ The 'scattergl' property is a tuple of instances of Scattergl that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Scattergl - A list or tuple of dicts of string/value properties that will be passed to the Scattergl constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Scattergl] """ return self["scattergl"] @scattergl.setter def scattergl(self, val): self["scattergl"] = val @property def scattermapbox(self): """ The 'scattermapbox' property is a tuple of instances of Scattermapbox that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Scattermapbox - A list or tuple of dicts of string/value properties that will be passed to the Scattermapbox constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Scattermapbox] """ return self["scattermapbox"] @scattermapbox.setter def scattermapbox(self, val): self["scattermapbox"] = val @property def scattermap(self): """ The 'scattermap' property is a tuple of instances of Scattermap that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Scattermap - A list or tuple of dicts of string/value properties that will be passed to the Scattermap constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Scattermap] """ return self["scattermap"] @scattermap.setter def scattermap(self, val): self["scattermap"] = val @property def scatterpolargl(self): """ The 'scatterpolargl' property is a tuple of instances of Scatterpolargl that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Scatterpolargl - A list or tuple of dicts of string/value properties that will be passed to the Scatterpolargl constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Scatterpolargl] """ return self["scatterpolargl"] @scatterpolargl.setter def scatterpolargl(self, val): self["scatterpolargl"] = val @property def scatterpolar(self): """ The 'scatterpolar' property is a tuple of instances of Scatterpolar that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Scatterpolar - A list or tuple of dicts of string/value properties that will be passed to the Scatterpolar constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Scatterpolar] """ return self["scatterpolar"] @scatterpolar.setter def scatterpolar(self, val): self["scatterpolar"] = val @property def scatter(self): """ The 'scatter' property is a tuple of instances of Scatter that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Scatter - A list or tuple of dicts of string/value properties that will be passed to the Scatter constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Scatter] """ return self["scatter"] @scatter.setter def scatter(self, val): self["scatter"] = val @property def scattersmith(self): """ The 'scattersmith' property is a tuple of instances of Scattersmith that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Scattersmith - A list or tuple of dicts of string/value properties that will be passed to the Scattersmith constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Scattersmith] """ return self["scattersmith"] @scattersmith.setter def scattersmith(self, val): self["scattersmith"] = val @property def scatterternary(self): """ The 'scatterternary' property is a tuple of instances of Scatterternary that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Scatterternary - A list or tuple of dicts of string/value properties that will be passed to the Scatterternary constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Scatterternary] """ return self["scatterternary"] @scatterternary.setter def scatterternary(self, val): self["scatterternary"] = val @property def splom(self): """ The 'splom' property is a tuple of instances of Splom that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Splom - A list or tuple of dicts of string/value properties that will be passed to the Splom constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Splom] """ return self["splom"] @splom.setter def splom(self, val): self["splom"] = val @property def streamtube(self): """ The 'streamtube' property is a tuple of instances of Streamtube that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Streamtube - A list or tuple of dicts of string/value properties that will be passed to the Streamtube constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Streamtube] """ return self["streamtube"] @streamtube.setter def streamtube(self, val): self["streamtube"] = val @property def sunburst(self): """ The 'sunburst' property is a tuple of instances of Sunburst that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Sunburst - A list or tuple of dicts of string/value properties that will be passed to the Sunburst constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Sunburst] """ return self["sunburst"] @sunburst.setter def sunburst(self, val): self["sunburst"] = val @property def surface(self): """ The 'surface' property is a tuple of instances of Surface that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Surface - A list or tuple of dicts of string/value properties that will be passed to the Surface constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Surface] """ return self["surface"] @surface.setter def surface(self, val): self["surface"] = val @property def table(self): """ The 'table' property is a tuple of instances of Table that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Table - A list or tuple of dicts of string/value properties that will be passed to the Table constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Table] """ return self["table"] @table.setter def table(self, val): self["table"] = val @property def treemap(self): """ The 'treemap' property is a tuple of instances of Treemap that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Treemap - A list or tuple of dicts of string/value properties that will be passed to the Treemap constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Treemap] """ return self["treemap"] @treemap.setter def treemap(self, val): self["treemap"] = val @property def violin(self): """ The 'violin' property is a tuple of instances of Violin that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Violin - A list or tuple of dicts of string/value properties that will be passed to the Violin constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Violin] """ return self["violin"] @violin.setter def violin(self, val): self["violin"] = val @property def volume(self): """ The 'volume' property is a tuple of instances of Volume that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Volume - A list or tuple of dicts of string/value properties that will be passed to the Volume constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Volume] """ return self["volume"] @volume.setter def volume(self, val): self["volume"] = val @property def waterfall(self): """ The 'waterfall' property is a tuple of instances of Waterfall that may be specified as: - A list or tuple of instances of plotly.graph_objs.layout.template.data.Waterfall - A list or tuple of dicts of string/value properties that will be passed to the Waterfall constructor Returns ------- tuple[plotly.graph_objs.layout.template.data.Waterfall] """ return self["waterfall"] @waterfall.setter def waterfall(self, val): self["waterfall"] = val @property def _prop_descriptions(self): return """\ barpolar A tuple of :class:`plotly.graph_objects.Barpolar` instances or dicts with compatible properties bar A tuple of :class:`plotly.graph_objects.Bar` instances or dicts with compatible properties box A tuple of :class:`plotly.graph_objects.Box` instances or dicts with compatible properties candlestick A tuple of :class:`plotly.graph_objects.Candlestick` instances or dicts with compatible properties carpet A tuple of :class:`plotly.graph_objects.Carpet` instances or dicts with compatible properties choroplethmapbox A tuple of :class:`plotly.graph_objects.Choroplethmapbox` instances or dicts with compatible properties choroplethmap A tuple of :class:`plotly.graph_objects.Choroplethmap` instances or dicts with compatible properties choropleth A tuple of :class:`plotly.graph_objects.Choropleth` instances or dicts with compatible properties cone A tuple of :class:`plotly.graph_objects.Cone` instances or dicts with compatible properties contourcarpet A tuple of :class:`plotly.graph_objects.Contourcarpet` instances or dicts with compatible properties contour A tuple of :class:`plotly.graph_objects.Contour` instances or dicts with compatible properties densitymapbox A tuple of :class:`plotly.graph_objects.Densitymapbox` instances or dicts with compatible properties densitymap A tuple of :class:`plotly.graph_objects.Densitymap` instances or dicts with compatible properties funnelarea A tuple of :class:`plotly.graph_objects.Funnelarea` instances or dicts with compatible properties funnel A tuple of :class:`plotly.graph_objects.Funnel` instances or dicts with compatible properties heatmap A tuple of :class:`plotly.graph_objects.Heatmap` instances or dicts with compatible properties histogram2dcontour A tuple of :class:`plotly.graph_objects.Histogram2dContour` instances or dicts with compatible properties histogram2d A tuple of :class:`plotly.graph_objects.Histogram2d` instances or dicts with compatible properties histogram A tuple of :class:`plotly.graph_objects.Histogram` instances or dicts with compatible properties icicle A tuple of :class:`plotly.graph_objects.Icicle` instances or dicts with compatible properties image A tuple of :class:`plotly.graph_objects.Image` instances or dicts with compatible properties indicator A tuple of :class:`plotly.graph_objects.Indicator` instances or dicts with compatible properties isosurface A tuple of :class:`plotly.graph_objects.Isosurface` instances or dicts with compatible properties mesh3d A tuple of :class:`plotly.graph_objects.Mesh3d` instances or dicts with compatible properties ohlc A tuple of :class:`plotly.graph_objects.Ohlc` instances or dicts with compatible properties parcats A tuple of :class:`plotly.graph_objects.Parcats` instances or dicts with compatible properties parcoords A tuple of :class:`plotly.graph_objects.Parcoords` instances or dicts with compatible properties pie A tuple of :class:`plotly.graph_objects.Pie` instances or dicts with compatible properties sankey A tuple of :class:`plotly.graph_objects.Sankey` instances or dicts with compatible properties scatter3d A tuple of :class:`plotly.graph_objects.Scatter3d` instances or dicts with compatible properties scattercarpet A tuple of :class:`plotly.graph_objects.Scattercarpet` instances or dicts with compatible properties scattergeo A tuple of :class:`plotly.graph_objects.Scattergeo` instances or dicts with compatible properties scattergl A tuple of :class:`plotly.graph_objects.Scattergl` instances or dicts with compatible properties scattermapbox A tuple of :class:`plotly.graph_objects.Scattermapbox` instances or dicts with compatible properties scattermap A tuple of :class:`plotly.graph_objects.Scattermap` instances or dicts with compatible properties scatterpolargl A tuple of :class:`plotly.graph_objects.Scatterpolargl` instances or dicts with compatible properties scatterpolar A tuple of :class:`plotly.graph_objects.Scatterpolar` instances or dicts with compatible properties scatter A tuple of :class:`plotly.graph_objects.Scatter` instances or dicts with compatible properties scattersmith A tuple of :class:`plotly.graph_objects.Scattersmith` instances or dicts with compatible properties scatterternary A tuple of :class:`plotly.graph_objects.Scatterternary` instances or dicts with compatible properties splom A tuple of :class:`plotly.graph_objects.Splom` instances or dicts with compatible properties streamtube A tuple of :class:`plotly.graph_objects.Streamtube` instances or dicts with compatible properties sunburst A tuple of :class:`plotly.graph_objects.Sunburst` instances or dicts with compatible properties surface A tuple of :class:`plotly.graph_objects.Surface` instances or dicts with compatible properties table A tuple of :class:`plotly.graph_objects.Table` instances or dicts with compatible properties treemap A tuple of :class:`plotly.graph_objects.Treemap` instances or dicts with compatible properties violin A tuple of :class:`plotly.graph_objects.Violin` instances or dicts with compatible properties volume A tuple of :class:`plotly.graph_objects.Volume` instances or dicts with compatible properties waterfall A tuple of :class:`plotly.graph_objects.Waterfall` instances or dicts with compatible properties """ def __init__( self, arg=None, barpolar=None, bar=None, box=None, candlestick=None, carpet=None, choroplethmapbox=None, choroplethmap=None, choropleth=None, cone=None, contourcarpet=None, contour=None, densitymapbox=None, densitymap=None, funnelarea=None, funnel=None, heatmap=None, histogram2dcontour=None, histogram2d=None, histogram=None, icicle=None, image=None, indicator=None, isosurface=None, mesh3d=None, ohlc=None, parcats=None, parcoords=None, pie=None, sankey=None, scatter3d=None, scattercarpet=None, scattergeo=None, scattergl=None, scattermapbox=None, scattermap=None, scatterpolargl=None, scatterpolar=None, scatter=None, scattersmith=None, scatterternary=None, splom=None, streamtube=None, sunburst=None, surface=None, table=None, treemap=None, violin=None, volume=None, waterfall=None, **kwargs, ): """ Construct a new Data object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.layout.template.Data` barpolar A tuple of :class:`plotly.graph_objects.Barpolar` instances or dicts with compatible properties bar A tuple of :class:`plotly.graph_objects.Bar` instances or dicts with compatible properties box A tuple of :class:`plotly.graph_objects.Box` instances or dicts with compatible properties candlestick A tuple of :class:`plotly.graph_objects.Candlestick` instances or dicts with compatible properties carpet A tuple of :class:`plotly.graph_objects.Carpet` instances or dicts with compatible properties choroplethmapbox A tuple of :class:`plotly.graph_objects.Choroplethmapbox` instances or dicts with compatible properties choroplethmap A tuple of :class:`plotly.graph_objects.Choroplethmap` instances or dicts with compatible properties choropleth A tuple of :class:`plotly.graph_objects.Choropleth` instances or dicts with compatible properties cone A tuple of :class:`plotly.graph_objects.Cone` instances or dicts with compatible properties contourcarpet A tuple of :class:`plotly.graph_objects.Contourcarpet` instances or dicts with compatible properties contour A tuple of :class:`plotly.graph_objects.Contour` instances or dicts with compatible properties densitymapbox A tuple of :class:`plotly.graph_objects.Densitymapbox` instances or dicts with compatible properties densitymap A tuple of :class:`plotly.graph_objects.Densitymap` instances or dicts with compatible properties funnelarea A tuple of :class:`plotly.graph_objects.Funnelarea` instances or dicts with compatible properties funnel A tuple of :class:`plotly.graph_objects.Funnel` instances or dicts with compatible properties heatmap A tuple of :class:`plotly.graph_objects.Heatmap` instances or dicts with compatible properties histogram2dcontour A tuple of :class:`plotly.graph_objects.Histogram2dContour` instances or dicts with compatible properties histogram2d A tuple of :class:`plotly.graph_objects.Histogram2d` instances or dicts with compatible properties histogram A tuple of :class:`plotly.graph_objects.Histogram` instances or dicts with compatible properties icicle A tuple of :class:`plotly.graph_objects.Icicle` instances or dicts with compatible properties image A tuple of :class:`plotly.graph_objects.Image` instances or dicts with compatible properties indicator A tuple of :class:`plotly.graph_objects.Indicator` instances or dicts with compatible properties isosurface A tuple of :class:`plotly.graph_objects.Isosurface` instances or dicts with compatible properties mesh3d A tuple of :class:`plotly.graph_objects.Mesh3d` instances or dicts with compatible properties ohlc A tuple of :class:`plotly.graph_objects.Ohlc` instances or dicts with compatible properties parcats A tuple of :class:`plotly.graph_objects.Parcats` instances or dicts with compatible properties parcoords A tuple of :class:`plotly.graph_objects.Parcoords` instances or dicts with compatible properties pie A tuple of :class:`plotly.graph_objects.Pie` instances or dicts with compatible properties sankey A tuple of :class:`plotly.graph_objects.Sankey` instances or dicts with compatible properties scatter3d A tuple of :class:`plotly.graph_objects.Scatter3d` instances or dicts with compatible properties scattercarpet A tuple of :class:`plotly.graph_objects.Scattercarpet` instances or dicts with compatible properties scattergeo A tuple of :class:`plotly.graph_objects.Scattergeo` instances or dicts with compatible properties scattergl A tuple of :class:`plotly.graph_objects.Scattergl` instances or dicts with compatible properties scattermapbox A tuple of :class:`plotly.graph_objects.Scattermapbox` instances or dicts with compatible properties scattermap A tuple of :class:`plotly.graph_objects.Scattermap` instances or dicts with compatible properties scatterpolargl A tuple of :class:`plotly.graph_objects.Scatterpolargl` instances or dicts with compatible properties scatterpolar A tuple of :class:`plotly.graph_objects.Scatterpolar` instances or dicts with compatible properties scatter A tuple of :class:`plotly.graph_objects.Scatter` instances or dicts with compatible properties scattersmith A tuple of :class:`plotly.graph_objects.Scattersmith` instances or dicts with compatible properties scatterternary A tuple of :class:`plotly.graph_objects.Scatterternary` instances or dicts with compatible properties splom A tuple of :class:`plotly.graph_objects.Splom` instances or dicts with compatible properties streamtube A tuple of :class:`plotly.graph_objects.Streamtube` instances or dicts with compatible properties sunburst A tuple of :class:`plotly.graph_objects.Sunburst` instances or dicts with compatible properties surface A tuple of :class:`plotly.graph_objects.Surface` instances or dicts with compatible properties table A tuple of :class:`plotly.graph_objects.Table` instances or dicts with compatible properties treemap A tuple of :class:`plotly.graph_objects.Treemap` instances or dicts with compatible properties violin A tuple of :class:`plotly.graph_objects.Violin` instances or dicts with compatible properties volume A tuple of :class:`plotly.graph_objects.Volume` instances or dicts with compatible properties waterfall A tuple of :class:`plotly.graph_objects.Waterfall` instances or dicts with compatible properties Returns ------- Data """ super().__init__("data") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.layout.template.Data constructor must be a dict or an instance of :class:`plotly.graph_objs.layout.template.Data`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("barpolar", arg, barpolar) self._set_property("bar", arg, bar) self._set_property("box", arg, box) self._set_property("candlestick", arg, candlestick) self._set_property("carpet", arg, carpet) self._set_property("choroplethmapbox", arg, choroplethmapbox) self._set_property("choroplethmap", arg, choroplethmap) self._set_property("choropleth", arg, choropleth) self._set_property("cone", arg, cone) self._set_property("contourcarpet", arg, contourcarpet) self._set_property("contour", arg, contour) self._set_property("densitymapbox", arg, densitymapbox) self._set_property("densitymap", arg, densitymap) self._set_property("funnelarea", arg, funnelarea) self._set_property("funnel", arg, funnel) self._set_property("heatmap", arg, heatmap) self._set_property("histogram2dcontour", arg, histogram2dcontour) self._set_property("histogram2d", arg, histogram2d) self._set_property("histogram", arg, histogram) self._set_property("icicle", arg, icicle) self._set_property("image", arg, image) self._set_property("indicator", arg, indicator) self._set_property("isosurface", arg, isosurface) self._set_property("mesh3d", arg, mesh3d) self._set_property("ohlc", arg, ohlc) self._set_property("parcats", arg, parcats) self._set_property("parcoords", arg, parcoords) self._set_property("pie", arg, pie) self._set_property("sankey", arg, sankey) self._set_property("scatter3d", arg, scatter3d) self._set_property("scattercarpet", arg, scattercarpet) self._set_property("scattergeo", arg, scattergeo) self._set_property("scattergl", arg, scattergl) self._set_property("scattermapbox", arg, scattermapbox) self._set_property("scattermap", arg, scattermap) self._set_property("scatterpolargl", arg, scatterpolargl) self._set_property("scatterpolar", arg, scatterpolar) self._set_property("scatter", arg, scatter) self._set_property("scattersmith", arg, scattersmith) self._set_property("scatterternary", arg, scatterternary) self._set_property("splom", arg, splom) self._set_property("streamtube", arg, streamtube) self._set_property("sunburst", arg, sunburst) self._set_property("surface", arg, surface) self._set_property("table", arg, table) self._set_property("treemap", arg, treemap) self._set_property("violin", arg, violin) self._set_property("volume", arg, volume) self._set_property("waterfall", arg, waterfall) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Data
python
pyca__cryptography
docs/_ext/cryptography-docs.py
{ "start": 1041, "end": 1631 }
class ____(nodes.Admonition, nodes.Element): pass def html_visit_hazmat_node(self, node): return self.visit_admonition(node, "danger") def latex_visit_hazmat_node(self, node): return self.visit_admonition(node) def depart_hazmat_node(self, node): return self.depart_admonition(node) def setup(app): app.add_node( Hazmat, html=(html_visit_hazmat_node, depart_hazmat_node), latex=(latex_visit_hazmat_node, depart_hazmat_node), ) app.add_directive("hazmat", HazmatDirective) return { "parallel_read_safe": True, }
Hazmat
python
falconry__falcon
falcon/bench/queues/stats.py
{ "start": 586, "end": 671 }
class ____: def on_get(self, req, resp, tenant_id, queue_name): pass
Resource
python
getsentry__sentry-python
sentry_sdk/integrations/threading.py
{ "start": 702, "end": 7109 }
class ____(Integration): identifier = "threading" def __init__(self, propagate_hub=None, propagate_scope=True): # type: (Optional[bool], bool) -> None if propagate_hub is not None: logger.warning( "Deprecated: propagate_hub is deprecated. This will be removed in the future." ) # Note: propagate_hub did not have any effect on propagation of scope data # scope data was always propagated no matter what the value of propagate_hub was # This is why the default for propagate_scope is True self.propagate_scope = propagate_scope if propagate_hub is not None: self.propagate_scope = propagate_hub @staticmethod def setup_once(): # type: () -> None old_start = Thread.start try: from django import VERSION as django_version # noqa: N811 import channels # type: ignore[import-untyped] channels_version = channels.__version__ except ImportError: django_version = None channels_version = None is_async_emulated_with_threads = ( sys.version_info < (3, 9) and channels_version is not None and channels_version < "4.0.0" and django_version is not None and django_version >= (3, 0) and django_version < (4, 0) ) @wraps(old_start) def sentry_start(self, *a, **kw): # type: (Thread, *Any, **Any) -> Any integration = sentry_sdk.get_client().get_integration(ThreadingIntegration) if integration is None: return old_start(self, *a, **kw) if integration.propagate_scope: if is_async_emulated_with_threads: warnings.warn( "There is a known issue with Django channels 2.x and 3.x when using Python 3.8 or older. " "(Async support is emulated using threads and some Sentry data may be leaked between those threads.) " "Please either upgrade to Django channels 4.0+, use Django's async features " "available in Django 3.1+ instead of Django channels, or upgrade to Python 3.9+.", stacklevel=2, ) isolation_scope = sentry_sdk.get_isolation_scope() current_scope = sentry_sdk.get_current_scope() else: isolation_scope = sentry_sdk.get_isolation_scope().fork() current_scope = sentry_sdk.get_current_scope().fork() else: isolation_scope = None current_scope = None # Patching instance methods in `start()` creates a reference cycle if # done in a naive way. See # https://github.com/getsentry/sentry-python/pull/434 # # In threading module, using current_thread API will access current thread instance # without holding it to avoid a reference cycle in an easier way. with capture_internal_exceptions(): new_run = _wrap_run( isolation_scope, current_scope, getattr(self.run, "__func__", self.run), ) self.run = new_run # type: ignore return old_start(self, *a, **kw) Thread.start = sentry_start # type: ignore ThreadPoolExecutor.submit = _wrap_threadpool_executor_submit( # type: ignore ThreadPoolExecutor.submit, is_async_emulated_with_threads ) def _wrap_run(isolation_scope_to_use, current_scope_to_use, old_run_func): # type: (Optional[sentry_sdk.Scope], Optional[sentry_sdk.Scope], F) -> F @wraps(old_run_func) def run(*a, **kw): # type: (*Any, **Any) -> Any def _run_old_run_func(): # type: () -> Any try: self = current_thread() return old_run_func(self, *a[1:], **kw) except Exception: reraise(*_capture_exception()) if isolation_scope_to_use is not None and current_scope_to_use is not None: with use_isolation_scope(isolation_scope_to_use): with use_scope(current_scope_to_use): return _run_old_run_func() else: return _run_old_run_func() return run # type: ignore def _wrap_threadpool_executor_submit(func, is_async_emulated_with_threads): # type: (Callable[..., Future[T]], bool) -> Callable[..., Future[T]] """ Wrap submit call to propagate scopes on task submission. """ @wraps(func) def sentry_submit(self, fn, *args, **kwargs): # type: (ThreadPoolExecutor, Callable[..., T], *Any, **Any) -> Future[T] integration = sentry_sdk.get_client().get_integration(ThreadingIntegration) if integration is None: return func(self, fn, *args, **kwargs) if integration.propagate_scope and is_async_emulated_with_threads: isolation_scope = sentry_sdk.get_isolation_scope() current_scope = sentry_sdk.get_current_scope() elif integration.propagate_scope: isolation_scope = sentry_sdk.get_isolation_scope().fork() current_scope = sentry_sdk.get_current_scope().fork() else: isolation_scope = None current_scope = None def wrapped_fn(*args, **kwargs): # type: (*Any, **Any) -> Any if isolation_scope is not None and current_scope is not None: with use_isolation_scope(isolation_scope): with use_scope(current_scope): return fn(*args, **kwargs) return fn(*args, **kwargs) return func(self, wrapped_fn, *args, **kwargs) return sentry_submit def _capture_exception(): # type: () -> ExcInfo exc_info = sys.exc_info() client = sentry_sdk.get_client() if client.get_integration(ThreadingIntegration) is not None: event, hint = event_from_exception( exc_info, client_options=client.options, mechanism={"type": "threading", "handled": False}, ) sentry_sdk.capture_event(event, hint=hint) return exc_info
ThreadingIntegration
python
pytorch__pytorch
torch/nn/modules/transformer.py
{ "start": 23578, "end": 28090 }
class ____(Module): r"""TransformerDecoder is a stack of N decoder layers. This TransformerDecoder layer implements the original architecture described in the `Attention Is All You Need <https://arxiv.org/abs/1706.03762>`_ paper. The intent of this layer is as a reference implementation for foundational understanding and thus it contains only limited features relative to newer Transformer architectures. Given the fast pace of innovation in transformer-like architectures, we recommend exploring this `tutorial <https://pytorch.org/tutorials/intermediate/transformer_building_blocks.html>`_ to build efficient layers from building blocks in core or using higher level libraries from the `PyTorch Ecosystem <https://landscape.pytorch.org/>`_. .. warning:: All layers in the TransformerDecoder are initialized with the same parameters. It is recommended to manually initialize the layers after creating the TransformerDecoder instance. Args: decoder_layer: an instance of the TransformerDecoderLayer() class (required). num_layers: the number of sub-decoder-layers in the decoder (required). norm: the layer normalization component (optional). Examples: >>> decoder_layer = nn.TransformerDecoderLayer(d_model=512, nhead=8) >>> transformer_decoder = nn.TransformerDecoder(decoder_layer, num_layers=6) >>> memory = torch.rand(10, 32, 512) >>> tgt = torch.rand(20, 32, 512) >>> out = transformer_decoder(tgt, memory) """ __constants__ = ["norm"] def __init__( self, decoder_layer: "TransformerDecoderLayer", num_layers: int, norm: Optional[Module] = None, ) -> None: super().__init__() torch._C._log_api_usage_once(f"torch.nn.modules.{self.__class__.__name__}") self.layers = _get_clones(decoder_layer, num_layers) self.num_layers = num_layers self.norm = norm def forward( self, tgt: Tensor, memory: Tensor, tgt_mask: Optional[Tensor] = None, memory_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None, tgt_is_causal: Optional[bool] = None, memory_is_causal: bool = False, ) -> Tensor: r"""Pass the inputs (and mask) through the decoder layer in turn. Args: tgt: the sequence to the decoder (required). memory: the sequence from the last layer of the encoder (required). tgt_mask: the mask for the tgt sequence (optional). memory_mask: the mask for the memory sequence (optional). tgt_key_padding_mask: the mask for the tgt keys per batch (optional). memory_key_padding_mask: the mask for the memory keys per batch (optional). tgt_is_causal: If specified, applies a causal mask as ``tgt mask``. Default: ``None``; try to detect a causal mask. Warning: ``tgt_is_causal`` provides a hint that ``tgt_mask`` is the causal mask. Providing incorrect hints can result in incorrect execution, including forward and backward compatibility. memory_is_causal: If specified, applies a causal mask as ``memory mask``. Default: ``False``. Warning: ``memory_is_causal`` provides a hint that ``memory_mask`` is the causal mask. Providing incorrect hints can result in incorrect execution, including forward and backward compatibility. Shape: see the docs in :class:`~torch.nn.Transformer`. """ output = tgt seq_len = _get_seq_len(tgt, self.layers[0].self_attn.batch_first) tgt_is_causal = _detect_is_causal_mask(tgt_mask, tgt_is_causal, seq_len) for mod in self.layers: output = mod( output, memory, tgt_mask=tgt_mask, memory_mask=memory_mask, tgt_key_padding_mask=tgt_key_padding_mask, memory_key_padding_mask=memory_key_padding_mask, tgt_is_causal=tgt_is_causal, memory_is_causal=memory_is_causal, ) if self.norm is not None: output = self.norm(output) return output
TransformerDecoder
python
tensorflow__tensorflow
tensorflow/python/data/ops/options.py
{ "start": 1161, "end": 3256 }
class ____(enum.Enum): """Represents the type of autotuning algorithm to use. DEFAULT: The default behavior is implementation specific and may change over time. HILL_CLIMB: In each optimization step, this algorithm chooses the optimal parameter and increases its value by 1. GRADIENT_DESCENT: In each optimization step, this algorithm updates the parameter values in the optimal direction. MAX_PARALLELISM: Similar to HILL_CLIMB but uses a relaxed stopping condition, allowing the optimization to oversubscribe the CPU. STAGE_BASED: In each optimization step, this algorithm chooses the worst bottleneck parameter and increases its value by 1. """ DEFAULT = 0 HILL_CLIMB = 1 GRADIENT_DESCENT = 2 MAX_PARALLELISM = 3 STAGE_BASED = 4 @classmethod def _to_proto(cls, obj): if obj == cls.DEFAULT: return model_pb2.AutotuneAlgorithm.DEFAULT if obj == cls.HILL_CLIMB: return model_pb2.AutotuneAlgorithm.HILL_CLIMB if obj == cls.GRADIENT_DESCENT: return model_pb2.AutotuneAlgorithm.GRADIENT_DESCENT if obj == cls.MAX_PARALLELISM: return model_pb2.AutotuneAlgorithm.MAX_PARALLELISM if obj == cls.STAGE_BASED: return model_pb2.AutotuneAlgorithm.STAGE_BASED raise ValueError( f"Invalid `obj.` Supported values include `DEFAULT`, `HILL_CLIMB` " f"`GRADIENT_DESCENT`, and `STAGE_BASED`. Got {obj.name}.") @classmethod def _from_proto(cls, pb): if pb == model_pb2.AutotuneAlgorithm.DEFAULT: return cls.DEFAULT if pb == model_pb2.AutotuneAlgorithm.HILL_CLIMB: return cls.HILL_CLIMB if pb == model_pb2.AutotuneAlgorithm.GRADIENT_DESCENT: return cls.GRADIENT_DESCENT if pb == model_pb2.AutotuneAlgorithm.MAX_PARALLELISM: return cls.MAX_PARALLELISM if pb == model_pb2.AutotuneAlgorithm.STAGE_BASED: return cls.STAGE_BASED raise ValueError( f"Invalid `pb.` Supported values include `DEFAULT`, `HILL_CLIMB`, " f"`GRADIENT_DESCENT` and `STAGE_BASED`. Got {pb}.") @tf_export("data.experimental.AutoShardPolicy")
AutotuneAlgorithm
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 47182, "end": 47464 }
class ____( legend_frame, legend_background, panel_background, panel_border, plot_background, strip_background, ): """ All rectangle elements Parameters ---------- theme_element : element_rect """ # themeables with scalar values
rect
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 298747, "end": 299648 }
class ____(SimpleCallNode): # Python C-API Function call (only created in transforms) # By default, we assume that the call never returns None, as this # is true for most C-API functions in CPython. If this does not # apply to a call, set the following to True (or None to inherit # the default behaviour). may_return_none = False def __init__(self, pos, function_name, func_type, utility_code = None, py_name=None, **kwargs): self.type = func_type.return_type self.result_ctype = self.type self.function = PythonCapiFunctionNode( pos, py_name, function_name, func_type, utility_code = utility_code) # call this last so that we can override the constructed # attributes above with explicit keyword arguments if required SimpleCallNode.__init__(self, pos, **kwargs)
PythonCapiCallNode
python
pytorch__pytorch
benchmarks/fastrnns/bench.py
{ "start": 1079, "end": 10845 }
class ____: def __init__(self, enable_timing): pass def record(self): self.time = time.perf_counter() def elapsed_time(self, end_event): assert isinstance(end_event, Event) return end_event.time - self.time def trainbench( name, rnn_creator, nloops=100, warmup=10, seqLength=100, numLayers=1, inputSize=512, hiddenSize=512, miniBatch=64, device="cuda", seed=None, ): def train_batch(modeldef): # CUDA events for timing if device == "cuda": timer_class = torch.cuda.Event else: timer_class = Event fwd_start_event = timer_class(enable_timing=True) fwd_end_event = timer_class(enable_timing=True) bwd_start_event = timer_class(enable_timing=True) bwd_end_event = timer_class(enable_timing=True) gc.collect() fwd_start_event.record() with record_function("## forward ##"): forward_output = modeldef.forward(*modeldef.inputs) fwd_end_event.record() # XXX: Use if need to print something # print(modeldef.forward.graph_for(*modeldef.inputs)) if modeldef.backward_setup is not None: backward_input = modeldef.backward_setup(forward_output) else: backward_input = forward_output gc.collect() bwd_start_event.record() if modeldef.backward is not None: modeldef.backward(*backward_input) bwd_end_event.record() if modeldef.backward is not None: with torch.no_grad(): for param in modeldef.params: assert param.grad is not None param.grad.zero_() if device == "cuda": torch.cuda.synchronize() fwd_time = fwd_start_event.elapsed_time(fwd_end_event) bwd_time = bwd_start_event.elapsed_time(bwd_end_event) return fwd_time, bwd_time creator_args = { "seqLength": seqLength, "numLayers": numLayers, "inputSize": inputSize, "hiddenSize": hiddenSize, "miniBatch": miniBatch, "device": device, "seed": seed, } modeldef = rnn_creator(**creator_args) [train_batch(modeldef) for _ in range(warmup)] results = [train_batch(modeldef) for _ in range(nloops)] fwd_times, bwd_times = zip(*results) fwd_times = torch.tensor(fwd_times) bwd_times = torch.tensor(bwd_times) return BenchResult( name=name, avg_fwd=fwd_times.mean().item(), std_fwd=fwd_times.std().item(), info_fwd=fwd_times, avg_bwd=bwd_times.mean().item(), std_bwd=bwd_times.std().item(), info_bwd=bwd_times, ) def print_stderr(*args, **kwargs): kwargs["file"] = sys.stderr return print(*args, **kwargs) def print_json_oss_format(results): oss_results = {} for group_name, group_val in results.items(): oss_results[group_name] = {} for model_name, run_time in group_val.items(): # Output for OSS oss_results[group_name][model_name] = run_time["avg"] print(json.dumps(oss_results)) def print_json_pep_format(results): # print the AI-PEP format json string for each model for group_name, group_val in results.items(): for model_name, run_time in group_val.items(): # Output for AI-PEP num_iters = len(run_time["info"]) info = run_time["info"].tolist() for i in range(num_iters): print( "Caffe2Observer " + json.dumps( { "type": "NET", "metric": group_name + "-" + model_name, "unit": "ms", "value": str(info[i]), } ) ) def bench(rnn_runners, group_name, print_json=False, sep=" ", **params): print_stderr(print_header(sep=sep)) results = {} for name, creator, context in rnn_runners: with context(): try: result = trainbench(name, creator, **params) # Replace the value of info_fwd and info_bwd to None result_with_no_info = result._replace(info_fwd="None", info_bwd="None") print_stderr(pretty_print(result_with_no_info, sep=sep)) results[name] = result except Exception: if not print_json: raise return { group_name: { k: {"avg": v.avg_fwd, "std": v.std_fwd, "info": v.info_fwd} for k, v in results.items() }, f"{group_name}-backward": { k: {"avg": v.avg_bwd, "std": v.std_bwd, "info": v.info_bwd} for k, v in results.items() }, } def bench_group(model_list, bench_name, bench_group, bench_args): print_stderr(f"Benchmarking {bench_name}s...") nn_results = bench(get_nn_runners(*model_list), bench_group, **bench_args) print_stderr("") return nn_results if __name__ == "__main__": parser = argparse.ArgumentParser(description="Profile RNNs") # groups help control which test group you want to run # if you only want to run one/two benchmark, run it with # e.g: python -m fastrnns.bench --rnns jit and --group rnns default_groups = ["cnns", "rnns"] parser.add_argument("--seqLength", default="100", type=int) parser.add_argument("--numLayers", default="1", type=int) parser.add_argument("--inputSize", default="512", type=int) parser.add_argument("--hiddenSize", default="512", type=int) parser.add_argument("--miniBatch", default="64", type=int) parser.add_argument("--warmup", default="10", type=int) parser.add_argument("--nloops", default="100", type=int) parser.add_argument("--device", default="cuda", type=str) parser.add_argument( "--variable-lstms", "--variable_lstms", action="store_true", help="Also benchmark variable sequence length lstms " "Note that some of these run really slowly " "and that the `seqLength` flag will be ignored.", ) parser.add_argument("--sep", default=" ", type=str) parser.add_argument("--print-json", nargs="?", default=None, const="oss") parser.add_argument("--rnns", nargs="*", help="What to run. cudnn, aten, jit, etc") parser.add_argument( "--cnns", nargs="*", help="What to run. resnet18, resnet18_jit, resnet50, etc" ) parser.add_argument( "--group", nargs="*", default=default_groups, help="Which group to run. cnns, rnns, etc.", ) parser.add_argument( "--fuser", default="te", type=str, help="The fuser backend to use. One of: te, old, or none", ) parser.add_argument( "--executor", default=None, type=str, help="The executor to use. One of: legacy, simple, profiling", ) parser.add_argument( "--cuda-pointwise-loop-level", "--cuda_pointwise_loop_level", default=None, type=int, ) parser.add_argument( "--cuda-pointwise-block-count", "--cuda_pointwise_block_count", default=None, type=int, ) parser.add_argument( "--cuda-pointwise-block-size", "--cuda_pointwise_block_size", default=None, type=int, ) args = parser.parse_args() set_fuser(args.fuser, args.executor) if args.cuda_pointwise_loop_level: torch._C._jit_set_te_cuda_pointwise_loop_levels(args.cuda_pointwise_loop_level) if args.cuda_pointwise_block_count: torch._C._jit_set_te_cuda_pointwise_block_count(args.cuda_pointwise_block_count) if args.cuda_pointwise_block_size: torch._C._jit_set_te_cuda_pointwise_block_size(args.cuda_pointwise_block_size) rnns = args.rnns or [ "cudnn", "aten", "jit", "jit_premul", "jit_premul_bias", "jit_simple", "jit_multilayer", "py", ] cnns = args.cnns or ["resnet18", "resnet18_jit", "resnet50", "resnet50_jit"] # TODO: Maybe add a separate section for the layernorm/dropout lstms # 'cudnn_layernorm', jit_layernorm', 'jit_layernom_decom', # 'jit', 'jit_dropout', 'cudnn_dropout' vlrnns = ["vl_cudnn", "vl_jit", "vl_py"] if args.print_json: print_stderr = lambda *args, **kwargs: None # noqa: E731,F811 print_stderr(args) bench_args = copy.deepcopy(vars(args)) should_bench_varlen_lstms = args.variable_lstms del bench_args["group"] del bench_args["rnns"] del bench_args["cnns"] del bench_args["variable_lstms"] del bench_args["fuser"] del bench_args["executor"] del bench_args["cuda_pointwise_loop_level"] del bench_args["cuda_pointwise_block_count"] del bench_args["cuda_pointwise_block_size"] results = {} if should_bench_varlen_lstms: if args.nloops + args.warmup > 30: print_stderr( "WARNING: some of the variable sequence length lstms are " "very unoptimized and therefore take forever to run." ) results.update( bench_group(vlrnns, "variable-length sequence LSTM", "vl_lstm", bench_args) ) if "rnns" in args.group: results.update(bench_group(rnns, "LSTM", "lstm", bench_args)) if "cnns" in args.group: results.update(bench_group(cnns, "ResNet", "resnet", bench_args)) if args.print_json == "oss": print_json_oss_format(results) elif args.print_json == "pep": print_json_pep_format(results)
Event
python
jazzband__django-model-utils
tests/test_fields/test_field_tracker.py
{ "start": 36195, "end": 36286 }
class ____(ModelTrackerTests): tracked_class = TrackedAbstract
AbstractModelTrackerTests
python
PrefectHQ__prefect
src/prefect/server/database/orm_models.py
{ "start": 12226, "end": 16193 }
class ____(Base): """ Common columns and logic for FlowRun and TaskRun models """ __abstract__ = True name: Mapped[str] = mapped_column(default=lambda: generate_slug(2), index=True) state_type: Mapped[Optional[schemas.states.StateType]] = mapped_column( sa.Enum(schemas.states.StateType, name="state_type") ) state_name: Mapped[Optional[str]] state_timestamp: Mapped[Optional[DateTime]] run_count: Mapped[int] = mapped_column(server_default="0", default=0) expected_start_time: Mapped[Optional[DateTime]] next_scheduled_start_time: Mapped[Optional[DateTime]] start_time: Mapped[Optional[DateTime]] end_time: Mapped[Optional[DateTime]] total_run_time: Mapped[datetime.timedelta] = mapped_column( server_default="0", default=datetime.timedelta(0) ) @hybrid_property def estimated_run_time(self) -> datetime.timedelta: """Total run time is incremented in the database whenever a RUNNING state is exited. To give up-to-date estimates, we estimate incremental run time for any runs currently in a RUNNING state.""" if self.state_type and self.state_type == schemas.states.StateType.RUNNING: if TYPE_CHECKING: assert self.state_timestamp is not None return self.total_run_time + (now("UTC") - self.state_timestamp) else: return self.total_run_time @estimated_run_time.inplace.expression @classmethod def _estimated_run_time_expression(cls) -> sa.Label[datetime.timedelta]: return ( sa.select( sa.case( ( cls.state_type == schemas.states.StateType.RUNNING, sa.func.interval_add( cls.total_run_time, sa.func.date_diff(sa.func.now(), cls.state_timestamp), ), ), else_=cls.total_run_time, ) ) # add a correlate statement so this can reuse the `FROM` clause # of any parent query .correlate(cls) .label("estimated_run_time") ) @hybrid_property def estimated_start_time_delta(self) -> datetime.timedelta: """The delta to the expected start time (or "lateness") is computed as the difference between the actual start time and expected start time. To give up-to-date estimates, we estimate lateness for any runs that don't have a start time and are not in a final state and were expected to start already.""" if ( self.start_time and self.expected_start_time is not None and self.start_time > (self.expected_start_time) ): return self.start_time - self.expected_start_time elif ( self.start_time is None and self.expected_start_time and self.expected_start_time < now("UTC") and self.state_type not in schemas.states.TERMINAL_STATES ): return now("UTC") - self.expected_start_time else: return datetime.timedelta(0) @estimated_start_time_delta.inplace.expression @classmethod def _estimated_start_time_delta_expression( cls, ) -> sa.SQLColumnExpression[datetime.timedelta]: return sa.case( ( cls.start_time > cls.expected_start_time, sa.func.date_diff(cls.start_time, cls.expected_start_time), ), ( sa.and_( cls.start_time.is_(None), cls.state_type.not_in(schemas.states.TERMINAL_STATES), cls.expected_start_time < sa.func.now(), ), sa.func.date_diff(sa.func.now(), cls.expected_start_time), ), else_=datetime.timedelta(0), )
Run
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/ddl.py
{ "start": 38504, "end": 38670 }
class ____(_CreateDropBase["Constraint"]): """Represent a COMMENT ON CONSTRAINT IS statement.""" __visit_name__ = "set_constraint_comment"
SetConstraintComment
python
django__django
tests/delete/models.py
{ "start": 5354, "end": 5451 }
class ____(models.Model): r = models.ForeignKey(R, models.CASCADE, related_name="+")
HiddenUser
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 376778, "end": 394726 }
class ____(VegaLiteSchema): """ FacetedEncoding schema wrapper. Parameters ---------- angle : dict, :class:`NumericMarkPropDef`, :class:`FieldOrDatumDefWithConditionDatumDefnumber`, :class:`FieldOrDatumDefWithConditionMarkPropFieldDefnumber`, :class:`ValueDefWithConditionMarkPropFieldOrDatumDefnumber` Rotation angle of point and text marks. color : dict, :class:`ColorDef`, :class:`FieldOrDatumDefWithConditionDatumDefGradientstringnull`, :class:`FieldOrDatumDefWithConditionMarkPropFieldDefGradientstringnull`, :class:`ValueDefWithConditionMarkPropFieldOrDatumDefGradientstringnull` Color of the marks - either fill or stroke color based on the ``filled`` property of mark definition. By default, ``color`` represents fill color for ``"area"``, ``"bar"``, ``"tick"``, ``"text"``, ``"trail"``, ``"circle"``, and ``"square"`` / stroke color for ``"line"`` and ``"point"``. **Default value:** If undefined, the default color depends on `mark config <https://vega.github.io/vega-lite/docs/config.html#mark-config>`__'s ``color`` property. *Note:* 1) For fine-grained control over both fill and stroke colors of the marks, please use the ``fill`` and ``stroke`` channels. The ``fill`` or ``stroke`` encodings have higher precedence than ``color``, thus may override the ``color`` encoding if conflicting encodings are specified. 2) See the scale documentation for more information about customizing `color scheme <https://vega.github.io/vega-lite/docs/scale.html#scheme>`__. column : dict, :class:`RowColumnEncodingFieldDef` A field definition for the horizontal facet of trellis plots. description : dict, :class:`StringFieldDefWithCondition`, :class:`StringValueDefWithCondition` A text description of this mark for ARIA accessibility (SVG output only). For SVG output the ``"aria-label"`` attribute will be set to this description. detail : dict, :class:`FieldDefWithoutScale`, Sequence[dict, :class:`FieldDefWithoutScale`] Additional levels of detail for grouping data in aggregate views and in line, trail, and area marks without mapping data to a specific visual channel. facet : dict, :class:`FacetEncodingFieldDef` A field definition for the (flexible) facet of trellis plots. If either ``row`` or ``column`` is specified, this channel will be ignored. fill : dict, :class:`ColorDef`, :class:`FieldOrDatumDefWithConditionDatumDefGradientstringnull`, :class:`FieldOrDatumDefWithConditionMarkPropFieldDefGradientstringnull`, :class:`ValueDefWithConditionMarkPropFieldOrDatumDefGradientstringnull` Fill color of the marks. **Default value:** If undefined, the default color depends on `mark config <https://vega.github.io/vega-lite/docs/config.html#mark-config>`__'s ``color`` property. *Note:* The ``fill`` encoding has higher precedence than ``color``, thus may override the ``color`` encoding if conflicting encodings are specified. fillOpacity : dict, :class:`NumericMarkPropDef`, :class:`FieldOrDatumDefWithConditionDatumDefnumber`, :class:`FieldOrDatumDefWithConditionMarkPropFieldDefnumber`, :class:`ValueDefWithConditionMarkPropFieldOrDatumDefnumber` Fill opacity of the marks. **Default value:** If undefined, the default opacity depends on `mark config <https://vega.github.io/vega-lite/docs/config.html#mark-config>`__'s ``fillOpacity`` property. href : dict, :class:`StringFieldDefWithCondition`, :class:`StringValueDefWithCondition` A URL to load upon mouse click. key : dict, :class:`FieldDefWithoutScale` A data field to use as a unique key for data binding. When a visualization's data is updated, the key value will be used to match data elements to existing mark instances. Use a key channel to enable object constancy for transitions over dynamic data. latitude : dict, :class:`DatumDef`, :class:`LatLongDef`, :class:`LatLongFieldDef` Latitude position of geographically projected marks. latitude2 : dict, :class:`DatumDef`, :class:`Position2Def`, :class:`PositionValueDef`, :class:`SecondaryFieldDef` Latitude-2 position for geographically projected ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. longitude : dict, :class:`DatumDef`, :class:`LatLongDef`, :class:`LatLongFieldDef` Longitude position of geographically projected marks. longitude2 : dict, :class:`DatumDef`, :class:`Position2Def`, :class:`PositionValueDef`, :class:`SecondaryFieldDef` Longitude-2 position for geographically projected ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. opacity : dict, :class:`NumericMarkPropDef`, :class:`FieldOrDatumDefWithConditionDatumDefnumber`, :class:`FieldOrDatumDefWithConditionMarkPropFieldDefnumber`, :class:`ValueDefWithConditionMarkPropFieldOrDatumDefnumber` Opacity of the marks. **Default value:** If undefined, the default opacity depends on `mark config <https://vega.github.io/vega-lite/docs/config.html#mark-config>`__'s ``opacity`` property. order : dict, :class:`OrderOnlyDef`, :class:`OrderFieldDef`, :class:`OrderValueDef`, Sequence[dict, :class:`OrderFieldDef`] Order of the marks. * For stacked marks, this ``order`` channel encodes `stack order <https://vega.github.io/vega-lite/docs/stack.html#order>`__. * For line and trail marks, this ``order`` channel encodes order of data points in the lines. This can be useful for creating `a connected scatterplot <https://vega.github.io/vega-lite/examples/connected_scatterplot.html>`__. Setting ``order`` to ``{"value": null}`` makes the line marks use the original order in the data sources. * Otherwise, this ``order`` channel encodes layer order of the marks. **Note**: In aggregate plots, ``order`` field should be aggregated to avoid creating additional aggregation grouping. radius : dict, :class:`PolarDef`, :class:`PositionValueDef`, :class:`PositionDatumDefBase`, :class:`PositionFieldDefBase` The outer radius in pixels of arc marks. radius2 : dict, :class:`DatumDef`, :class:`Position2Def`, :class:`PositionValueDef`, :class:`SecondaryFieldDef` The inner radius in pixels of arc marks. row : dict, :class:`RowColumnEncodingFieldDef` A field definition for the vertical facet of trellis plots. shape : dict, :class:`ShapeDef`, :class:`FieldOrDatumDefWithConditionDatumDefstringnull`, :class:`FieldOrDatumDefWithConditionMarkPropFieldDefTypeForShapestringnull`, :class:`ValueDefWithConditionMarkPropFieldOrDatumDefTypeForShapestringnull` Shape of the mark. 1. For ``point`` marks the supported values include: - plotting shapes: ``"circle"``, ``"square"``, ``"cross"``, ``"diamond"``, ``"triangle-up"``, ``"triangle-down"``, ``"triangle-right"``, or ``"triangle-left"``. - the line symbol ``"stroke"`` - centered directional shapes ``"arrow"``, ``"wedge"``, or ``"triangle"`` - a custom `SVG path string <https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths>`__ (For correct sizing, custom shape paths should be defined within a square bounding box with coordinates ranging from -1 to 1 along both the x and y dimensions.) 2. For ``geoshape`` marks it should be a field definition of the geojson data **Default value:** If undefined, the default shape depends on `mark config <https://vega.github.io/vega-lite/docs/config.html#point-config>`__'s ``shape`` property. (``"circle"`` if unset.) size : dict, :class:`NumericMarkPropDef`, :class:`FieldOrDatumDefWithConditionDatumDefnumber`, :class:`FieldOrDatumDefWithConditionMarkPropFieldDefnumber`, :class:`ValueDefWithConditionMarkPropFieldOrDatumDefnumber` Size of the mark. * For ``"point"``, ``"square"`` and ``"circle"``, - the symbol size, or pixel area of the mark. * For ``"bar"`` and ``"tick"`` - the bar and tick's size. * For ``"text"`` - the text's font size. * Size is unsupported for ``"line"``, ``"area"``, and ``"rect"``. (Use ``"trail"`` instead of line with varying size) stroke : dict, :class:`ColorDef`, :class:`FieldOrDatumDefWithConditionDatumDefGradientstringnull`, :class:`FieldOrDatumDefWithConditionMarkPropFieldDefGradientstringnull`, :class:`ValueDefWithConditionMarkPropFieldOrDatumDefGradientstringnull` Stroke color of the marks. **Default value:** If undefined, the default color depends on `mark config <https://vega.github.io/vega-lite/docs/config.html#mark-config>`__'s ``color`` property. *Note:* The ``stroke`` encoding has higher precedence than ``color``, thus may override the ``color`` encoding if conflicting encodings are specified. strokeDash : dict, :class:`NumericArrayMarkPropDef`, :class:`FieldOrDatumDefWithConditionDatumDefnumberArray`, :class:`FieldOrDatumDefWithConditionMarkPropFieldDefnumberArray`, :class:`ValueDefWithConditionMarkPropFieldOrDatumDefnumberArray` Stroke dash of the marks. **Default value:** ``[1,0]`` (No dash). strokeOpacity : dict, :class:`NumericMarkPropDef`, :class:`FieldOrDatumDefWithConditionDatumDefnumber`, :class:`FieldOrDatumDefWithConditionMarkPropFieldDefnumber`, :class:`ValueDefWithConditionMarkPropFieldOrDatumDefnumber` Stroke opacity of the marks. **Default value:** If undefined, the default opacity depends on `mark config <https://vega.github.io/vega-lite/docs/config.html#mark-config>`__'s ``strokeOpacity`` property. strokeWidth : dict, :class:`NumericMarkPropDef`, :class:`FieldOrDatumDefWithConditionDatumDefnumber`, :class:`FieldOrDatumDefWithConditionMarkPropFieldDefnumber`, :class:`ValueDefWithConditionMarkPropFieldOrDatumDefnumber` Stroke width of the marks. **Default value:** If undefined, the default stroke width depends on `mark config <https://vega.github.io/vega-lite/docs/config.html#mark-config>`__'s ``strokeWidth`` property. text : dict, :class:`TextDef`, :class:`ValueDefWithConditionStringFieldDefText`, :class:`FieldOrDatumDefWithConditionStringDatumDefText`, :class:`FieldOrDatumDefWithConditionStringFieldDefText` Text of the ``text`` mark. theta : dict, :class:`PolarDef`, :class:`PositionValueDef`, :class:`PositionDatumDefBase`, :class:`PositionFieldDefBase` * For arc marks, the arc length in radians if theta2 is not specified, otherwise the start arc angle. (A value of 0 indicates up or “north”, increasing values proceed clockwise.) * For text marks, polar coordinate angle in radians. theta2 : dict, :class:`DatumDef`, :class:`Position2Def`, :class:`PositionValueDef`, :class:`SecondaryFieldDef` The end angle of arc marks in radians. A value of 0 indicates up or “north”, increasing values proceed clockwise. time : dict, :class:`TimeDef` tooltip : dict, :class:`StringFieldDefWithCondition`, :class:`StringValueDefWithCondition`, Sequence[dict, :class:`StringFieldDef`], None The tooltip text to show upon mouse hover. Specifying ``tooltip`` encoding overrides `the tooltip property in the mark definition <https://vega.github.io/vega-lite/docs/mark.html#mark-def>`__. See the `tooltip <https://vega.github.io/vega-lite/docs/tooltip.html>`__ documentation for a detailed discussion about tooltip in Vega-Lite. url : dict, :class:`StringFieldDefWithCondition`, :class:`StringValueDefWithCondition` The URL of an image mark. x : dict, :class:`PositionDef`, :class:`PositionDatumDef`, :class:`PositionFieldDef`, :class:`PositionValueDef` X coordinates of the marks, or width of horizontal ``"bar"`` and ``"area"`` without specified ``x2`` or ``width``. The ``value`` of this channel can be a number or a string ``"width"`` for the width of the plot. x2 : dict, :class:`DatumDef`, :class:`Position2Def`, :class:`PositionValueDef`, :class:`SecondaryFieldDef` X2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. The ``value`` of this channel can be a number or a string ``"width"`` for the width of the plot. xError : dict, :class:`ValueDefnumber`, :class:`SecondaryFieldDef` Error value of x coordinates for error specified ``"errorbar"`` and ``"errorband"``. xError2 : dict, :class:`ValueDefnumber`, :class:`SecondaryFieldDef` Secondary error value of x coordinates for error specified ``"errorbar"`` and ``"errorband"``. xOffset : dict, :class:`OffsetDef`, :class:`ScaleDatumDef`, :class:`ScaleFieldDef`, :class:`ValueDefnumber` Offset of x-position of the marks y : dict, :class:`PositionDef`, :class:`PositionDatumDef`, :class:`PositionFieldDef`, :class:`PositionValueDef` Y coordinates of the marks, or height of vertical ``"bar"`` and ``"area"`` without specified ``y2`` or ``height``. The ``value`` of this channel can be a number or a string ``"height"`` for the height of the plot. y2 : dict, :class:`DatumDef`, :class:`Position2Def`, :class:`PositionValueDef`, :class:`SecondaryFieldDef` Y2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. The ``value`` of this channel can be a number or a string ``"height"`` for the height of the plot. yError : dict, :class:`ValueDefnumber`, :class:`SecondaryFieldDef` Error value of y coordinates for error specified ``"errorbar"`` and ``"errorband"``. yError2 : dict, :class:`ValueDefnumber`, :class:`SecondaryFieldDef` Secondary error value of y coordinates for error specified ``"errorbar"`` and ``"errorband"``. yOffset : dict, :class:`OffsetDef`, :class:`ScaleDatumDef`, :class:`ScaleFieldDef`, :class:`ValueDefnumber` Offset of y-position of the marks """ _schema = {"$ref": "#/definitions/FacetedEncoding"} def __init__( self, angle: Optional[SchemaBase | Map] = Undefined, color: Optional[SchemaBase | Map] = Undefined, column: Optional[SchemaBase | Map] = Undefined, description: Optional[SchemaBase | Map] = Undefined, detail: Optional[SchemaBase | Sequence[SchemaBase | Map] | Map] = Undefined, facet: Optional[SchemaBase | Map] = Undefined, fill: Optional[SchemaBase | Map] = Undefined, fillOpacity: Optional[SchemaBase | Map] = Undefined, href: Optional[SchemaBase | Map] = Undefined, key: Optional[SchemaBase | Map] = Undefined, latitude: Optional[SchemaBase | Map] = Undefined, latitude2: Optional[SchemaBase | Map] = Undefined, longitude: Optional[SchemaBase | Map] = Undefined, longitude2: Optional[SchemaBase | Map] = Undefined, opacity: Optional[SchemaBase | Map] = Undefined, order: Optional[SchemaBase | Sequence[SchemaBase | Map] | Map] = Undefined, radius: Optional[SchemaBase | Map] = Undefined, radius2: Optional[SchemaBase | Map] = Undefined, row: Optional[SchemaBase | Map] = Undefined, shape: Optional[SchemaBase | Map] = Undefined, size: Optional[SchemaBase | Map] = Undefined, stroke: Optional[SchemaBase | Map] = Undefined, strokeDash: Optional[SchemaBase | Map] = Undefined, strokeOpacity: Optional[SchemaBase | Map] = Undefined, strokeWidth: Optional[SchemaBase | Map] = Undefined, text: Optional[SchemaBase | Map] = Undefined, theta: Optional[SchemaBase | Map] = Undefined, theta2: Optional[SchemaBase | Map] = Undefined, time: Optional[SchemaBase | Map] = Undefined, tooltip: Optional[ SchemaBase | Sequence[SchemaBase | Map] | Map | None ] = Undefined, url: Optional[SchemaBase | Map] = Undefined, x: Optional[SchemaBase | Map] = Undefined, x2: Optional[SchemaBase | Map] = Undefined, xError: Optional[SchemaBase | Map] = Undefined, xError2: Optional[SchemaBase | Map] = Undefined, xOffset: Optional[SchemaBase | Map] = Undefined, y: Optional[SchemaBase | Map] = Undefined, y2: Optional[SchemaBase | Map] = Undefined, yError: Optional[SchemaBase | Map] = Undefined, yError2: Optional[SchemaBase | Map] = Undefined, yOffset: Optional[SchemaBase | Map] = Undefined, **kwds, ): super().__init__( angle=angle, color=color, column=column, description=description, detail=detail, facet=facet, fill=fill, fillOpacity=fillOpacity, href=href, key=key, latitude=latitude, latitude2=latitude2, longitude=longitude, longitude2=longitude2, opacity=opacity, order=order, radius=radius, radius2=radius2, row=row, shape=shape, size=size, stroke=stroke, strokeDash=strokeDash, strokeOpacity=strokeOpacity, strokeWidth=strokeWidth, text=text, theta=theta, theta2=theta2, time=time, tooltip=tooltip, url=url, x=x, x2=x2, xError=xError, xError2=xError2, xOffset=xOffset, y=y, y2=y2, yError=yError, yError2=yError2, yOffset=yOffset, **kwds, )
FacetedEncoding
python
huggingface__transformers
src/transformers/models/codegen/configuration_codegen.py
{ "start": 816, "end": 6210 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`CodeGenModel`]. It is used to instantiate a CodeGen model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the CodeGen [Salesforce/codegen-2B-mono](https://huggingface.co/Salesforce/codegen-2B-mono) architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: vocab_size (`int`, *optional*, defaults to 50400): Vocabulary size of the CodeGen model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`CodeGenModel`]. n_positions (`int`, *optional*, defaults to 2048): The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). n_ctx (`int`, *optional*, defaults to 2048): This attribute is used in `CodeGenModel.__init__` without any real effect. n_embd (`int`, *optional*, defaults to 4096): Dimensionality of the embeddings and hidden states. n_layer (`int`, *optional*, defaults to 28): Number of hidden layers in the Transformer encoder. n_head (`int`, *optional*, defaults to 16): Number of attention heads for each attention layer in the Transformer encoder. rotary_dim (`int`, *optional*, defaults to 64): Number of dimensions in the embedding that Rotary Position Embedding is applied to. n_inner (`int`, *optional*): Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd activation_function (`str`, *optional*, defaults to `"gelu_new"`): Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new"]`. resid_pdrop (`float`, *optional*, defaults to 0.0): The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. embd_pdrop (`int`, *optional*, defaults to 0.0): The dropout ratio for the embeddings. attn_pdrop (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention. layer_norm_epsilon (`float`, *optional*, defaults to 1e-05): The epsilon to use in the layer normalization layers. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). bos_token_id (`int`, *optional*, defaults to 50256): Beginning of stream token id. eos_token_id (`int`, *optional*, defaults to 50256): End of stream token id. tie_word_embeddings (`bool`, *optional*, defaults to `False`): Whether the model's input and output word embeddings should be tied. Note that this is only relevant if the model has a output word embedding layer. Example: ```python >>> from transformers import CodeGenConfig, CodeGenModel >>> # Initializing a CodeGen 6B configuration >>> configuration = CodeGenConfig() >>> # Initializing a model (with random weights) from the configuration >>> model = CodeGenModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "codegen" attribute_map = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self, vocab_size=50400, n_positions=2048, n_ctx=2048, n_embd=4096, n_layer=28, n_head=16, rotary_dim=64, n_inner=None, activation_function="gelu_new", resid_pdrop=0.0, embd_pdrop=0.0, attn_pdrop=0.0, layer_norm_epsilon=1e-5, initializer_range=0.02, use_cache=True, bos_token_id=50256, eos_token_id=50256, tie_word_embeddings=False, **kwargs, ): self.vocab_size = vocab_size self.n_ctx = n_ctx self.n_positions = n_positions self.n_embd = n_embd self.n_layer = n_layer self.n_head = n_head self.n_inner = n_inner self.rotary_dim = rotary_dim self.activation_function = activation_function self.resid_pdrop = resid_pdrop self.embd_pdrop = embd_pdrop self.attn_pdrop = attn_pdrop self.layer_norm_epsilon = layer_norm_epsilon self.initializer_range = initializer_range self.use_cache = use_cache self.bos_token_id = bos_token_id self.eos_token_id = eos_token_id super().__init__( bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs ) __all__ = ["CodeGenConfig"]
CodeGenConfig
python
sphinx-doc__sphinx
tests/test_intl/test_intl.py
{ "start": 27060, "end": 27572 }
class ____(_MockClock): """Object for mocking :func:`time.time_ns` on Windows platforms. The result is in 'nanoseconds' but with a microsecond resolution so that the division by 1_000 does not cause rounding issues. """ def __init__(self) -> None: self.us: int = 0 # current microsecond 'tick' def time(self) -> int: ret = 1_000 * self.us self.us += 1 return ret def sleep(self, ds: float) -> None: self.us += int(ds * 1e6)
_MockWindowsClock
python
langchain-ai__langchain
libs/langchain/langchain_classic/retrievers/document_compressors/base.py
{ "start": 261, "end": 3145 }
class ____(BaseDocumentCompressor): """Document compressor that uses a pipeline of Transformers.""" transformers: list[BaseDocumentTransformer | BaseDocumentCompressor] """List of document filters that are chained together and run in sequence.""" model_config = ConfigDict( arbitrary_types_allowed=True, ) def compress_documents( self, documents: Sequence[Document], query: str, callbacks: Callbacks | None = None, ) -> Sequence[Document]: """Transform a list of documents.""" for _transformer in self.transformers: if isinstance(_transformer, BaseDocumentCompressor): accepts_callbacks = ( signature(_transformer.compress_documents).parameters.get( "callbacks", ) is not None ) if accepts_callbacks: documents = _transformer.compress_documents( documents, query, callbacks=callbacks, ) else: documents = _transformer.compress_documents(documents, query) elif isinstance(_transformer, BaseDocumentTransformer): documents = _transformer.transform_documents(documents) else: msg = f"Got unexpected transformer type: {_transformer}" # type: ignore[unreachable] raise ValueError(msg) # noqa: TRY004 return documents async def acompress_documents( self, documents: Sequence[Document], query: str, callbacks: Callbacks | None = None, ) -> Sequence[Document]: """Compress retrieved documents given the query context.""" for _transformer in self.transformers: if isinstance(_transformer, BaseDocumentCompressor): accepts_callbacks = ( signature(_transformer.acompress_documents).parameters.get( "callbacks", ) is not None ) if accepts_callbacks: documents = await _transformer.acompress_documents( documents, query, callbacks=callbacks, ) else: documents = await _transformer.acompress_documents(documents, query) elif isinstance(_transformer, BaseDocumentTransformer): documents = await _transformer.atransform_documents(documents) else: msg = f"Got unexpected transformer type: {_transformer}" # type: ignore[unreachable] raise ValueError(msg) # noqa: TRY004 return documents
DocumentCompressorPipeline
python
astropy__astropy
astropy/utils/console.py
{ "start": 949, "end": 9991 }
class ____: """Singleton class given access to IPython streams, etc.""" @classproperty def OutStream(cls): if not hasattr(cls, "_OutStream"): if HAS_IPYKERNEL: from ipykernel.iostream import OutStream cls._OutStream = OutStream else: cls._OutStream = None return cls._OutStream @classproperty def ipyio(cls): if not hasattr(cls, "_ipyio"): if HAS_IPYTHON: from IPython.utils import io cls._ipyio = io else: cls._ipyio = None return cls._ipyio def isatty(file): """ Returns `True` if ``file`` is a tty. Most built-in Python file-like objects have an `isatty` member, but some user-defined types may not, so this assumes those are not ttys. """ if ( multiprocessing.current_process().name != "MainProcess" or threading.current_thread().name != "MainThread" ): return False if hasattr(file, "isatty"): return file.isatty() if _IPython.OutStream is None or (not isinstance(file, _IPython.OutStream)): return False return getattr(file, "name", None) == "stdout" @deprecated("6.1", alternative="shutil.get_terminal_size") def terminal_size(file=None): """ Returns a tuple (height, width) containing the height and width of the terminal. This function will look for the width in height in multiple areas before falling back on the width and height in astropy's configuration. """ if file is None: file = sys.stdout try: s = struct.pack("HHHH", 0, 0, 0, 0) x = fcntl.ioctl(file, termios.TIOCGWINSZ, s) (lines, width, xpixels, ypixels) = struct.unpack("HHHH", x) if lines > 12: lines -= 6 if width > 10: width -= 1 if lines <= 0 or width <= 0: raise Exception("unable to get terminal size") return (lines, width) except Exception: try: # see if POSIX standard variables will work return (int(os.environ.get("LINES")), int(os.environ.get("COLUMNS"))) except TypeError: # fall back on configuration variables, or if not # set, (25, 80) lines = conf.max_lines width = conf.max_width if lines is None: lines = 25 if width is None: width = 80 return lines, width def _color_text(text, color): """Returns a string wrapped in ANSI color codes for coloring the text in a terminal. :: colored_text = color_text('Here is a message', 'blue') This won't actually effect the text until it is printed to the terminal. Parameters ---------- text : str The string to return, bounded by the color codes. color : str An ANSI terminal color name. Must be one of: black, red, green, brown, blue, magenta, cyan, lightgrey, default, darkgrey, lightred, lightgreen, yellow, lightblue, lightmagenta, lightcyan, white, or '' (the empty string). """ color_mapping = { "black": "0;30", "red": "0;31", "green": "0;32", "brown": "0;33", "blue": "0;34", "magenta": "0;35", "cyan": "0;36", "lightgrey": "0;37", "default": "0;39", "darkgrey": "1;30", "lightred": "1;31", "lightgreen": "1;32", "yellow": "1;33", "lightblue": "1;34", "lightmagenta": "1;35", "lightcyan": "1;36", "white": "1;37", } if sys.platform == "win32" and _IPython.OutStream is None: # On Windows do not colorize text unless in IPython return text color_code = color_mapping.get(color, "0;39") return f"\033[{color_code}m{text}\033[0m" def _write_with_fallback(s, write, fileobj): """Write the supplied string with the given write function like ``write(s)``, but use a writer for the locale's preferred encoding in case of a UnicodeEncodeError. Failing that attempt to write with 'utf-8' or 'latin-1'. """ try: write(s) return write except UnicodeEncodeError: # Let's try the next approach... pass enc = locale.getpreferredencoding() try: Writer = codecs.getwriter(enc) except LookupError: Writer = codecs.getwriter("utf-8") f = Writer(fileobj) write = f.write try: write(s) return write except UnicodeEncodeError: Writer = codecs.getwriter("latin-1") f = Writer(fileobj) write = f.write # If this doesn't work let the exception bubble up; I'm out of ideas write(s) return write def color_print(*args, end="\n", **kwargs): """ Prints colors and styles to the terminal uses ANSI escape sequences. :: color_print('This is the color ', 'default', 'GREEN', 'green') Parameters ---------- positional args : str The positional arguments come in pairs (*msg*, *color*), where *msg* is the string to display and *color* is the color to display it in. *color* is an ANSI terminal color name. Must be one of: black, red, green, brown, blue, magenta, cyan, lightgrey, default, darkgrey, lightred, lightgreen, yellow, lightblue, lightmagenta, lightcyan, white, or '' (the empty string). file : :term:`file-like (writeable)`, optional Where to write to. Defaults to `sys.stdout`. If file is not a tty (as determined by calling its `isatty` member, if one exists), no coloring will be included. end : str, optional The ending of the message. Defaults to ``\\n``. The end will be printed after resetting any color or font state. """ file = kwargs.get("file", sys.stdout) write = file.write if isatty(file) and conf.use_color: for i in range(0, len(args), 2): msg = args[i] if i + 1 == len(args): color = "" else: color = args[i + 1] if color: msg = _color_text(msg, color) # Some file objects support writing unicode sensibly on some Python # versions; if this fails try creating a writer using the locale's # preferred encoding. If that fails too give up. write = _write_with_fallback(msg, write, file) write(end) else: for i in range(0, len(args), 2): msg = args[i] write(msg) write(end) def human_time(seconds): """ Returns a human-friendly time string that is always exactly 6 characters long. Depending on the number of seconds given, can be one of:: 1w 3d 2d 4h 1h 5m 1m 4s 15s Will be in color if console coloring is turned on. Parameters ---------- seconds : int The number of seconds to represent Returns ------- time : str A human-friendly representation of the given number of seconds that is always exactly 6 characters. """ units = [ ("y", 60 * 60 * 24 * 7 * 52), ("w", 60 * 60 * 24 * 7), ("d", 60 * 60 * 24), ("h", 60 * 60), ("m", 60), ("s", 1), ] seconds = int(seconds) if seconds < 60: return f" {seconds:2d}s" for i in range(len(units) - 1): unit1, limit1 = units[i] unit2, limit2 = units[i + 1] if seconds >= limit1: return ( f"{seconds // limit1:2d}{unit1}{(seconds % limit1) // limit2:2d}{unit2}" ) return " ~inf" def human_file_size(size): """ Returns a human-friendly string representing a file size that is 2-4 characters long. For example, depending on the number of bytes given, can be one of:: 256b 64k 1.1G Parameters ---------- size : int The size of the file (in bytes) Returns ------- size : str A human-friendly representation of the size of the file """ if hasattr(size, "unit"): # Import units only if necessary because the import takes a # significant time [#4649] from astropy import units as u size = u.Quantity(size, u.byte).value suffixes = " kMGTPEZY" if size == 0: num_scale = 0 else: num_scale = math.floor(math.log(size) / math.log(1000)) if num_scale > 7: suffix = "?" else: suffix = suffixes[num_scale] num_scale = int(math.pow(1000, num_scale)) value = size / num_scale str_value = str(value) if suffix == " ": str_value = str_value[: str_value.index(".")] elif str_value[2] == ".": str_value = str_value[:2] else: str_value = str_value[:3] return f"{str_value:>3s}{suffix}"
_IPython
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/solverHigherOrder8.py
{ "start": 212, "end": 327 }
class ____(Protocol[P, R]): @classmethod def collect(cls, *args: P.args, **kwargs: P.kwargs) -> R: ...
Proto1
python
numba__numba
numba/cuda/testing.py
{ "start": 1614, "end": 6064 }
class ____(CUDATestCase): """ For tests where the context needs to be reset after each test. Typically these inspect or modify parts of the context that would usually be expected to be internal implementation details (such as the state of allocations and deallocations, etc.). """ def tearDown(self): super().tearDown() from numba.cuda.cudadrv.devices import reset reset() def ensure_supported_ccs_initialized(): from numba.cuda import is_available as cuda_is_available from numba.cuda.cudadrv import nvvm if cuda_is_available(): # Ensure that cudart.so is loaded and the list of supported compute # capabilities in the nvvm module is populated before a fork. This is # needed because some compilation tests don't require a CUDA context, # but do use NVVM, and it is required that libcudart.so should be # loaded before a fork (note that the requirement is not explicitly # documented). nvvm.get_supported_ccs() def skip_on_cudasim(reason): """Skip this test if running on the CUDA simulator""" return unittest.skipIf(config.ENABLE_CUDASIM, reason) def skip_unless_cudasim(reason): """Skip this test if running on CUDA hardware""" return unittest.skipUnless(config.ENABLE_CUDASIM, reason) def skip_unless_conda_cudatoolkit(reason): """Skip test if the CUDA toolkit was not installed by Conda""" return unittest.skipUnless(get_conda_ctk() is not None, reason) def skip_if_external_memmgr(reason): """Skip test if an EMM Plugin is in use""" return unittest.skipIf(config.CUDA_MEMORY_MANAGER != 'default', reason) def skip_under_cuda_memcheck(reason): return unittest.skipIf(os.environ.get('CUDA_MEMCHECK') is not None, reason) def skip_without_nvdisasm(reason): nvdisasm_path = shutil.which('nvdisasm') return unittest.skipIf(nvdisasm_path is None, reason) def skip_with_nvdisasm(reason): nvdisasm_path = shutil.which('nvdisasm') return unittest.skipIf(nvdisasm_path is not None, reason) def skip_on_arm(reason): cpu = platform.processor() is_arm = cpu.startswith('arm') or cpu.startswith('aarch') return unittest.skipIf(is_arm, reason) def skip_if_cuda_includes_missing(fn): # Skip when cuda.h is not available - generally this should indicate # whether the CUDA includes are available or not cuda_h = os.path.join(config.CUDA_INCLUDE_PATH, 'cuda.h') cuda_h_file = (os.path.exists(cuda_h) and os.path.isfile(cuda_h)) reason = 'CUDA include dir not available on this system' return unittest.skipUnless(cuda_h_file, reason)(fn) def skip_if_mvc_enabled(reason): """Skip a test if Minor Version Compatibility is enabled""" return unittest.skipIf(config.CUDA_ENABLE_MINOR_VERSION_COMPATIBILITY, reason) def skip_if_mvc_libraries_unavailable(fn): libs_available = False try: import cubinlinker # noqa: F401 import ptxcompiler # noqa: F401 libs_available = True except ImportError: pass return unittest.skipUnless(libs_available, "Requires cubinlinker and ptxcompiler")(fn) def cc_X_or_above(major, minor): if not config.ENABLE_CUDASIM: cc = devices.get_context().device.compute_capability return cc >= (major, minor) else: return True def skip_unless_cc_50(fn): return unittest.skipUnless(cc_X_or_above(5, 0), "requires cc >= 5.0")(fn) def skip_unless_cc_53(fn): return unittest.skipUnless(cc_X_or_above(5, 3), "requires cc >= 5.3")(fn) def skip_unless_cc_60(fn): return unittest.skipUnless(cc_X_or_above(6, 0), "requires cc >= 6.0")(fn) def skip_unless_cc_75(fn): return unittest.skipUnless(cc_X_or_above(7, 5), "requires cc >= 7.5")(fn) def xfail_unless_cudasim(fn): if config.ENABLE_CUDASIM: return fn else: return unittest.expectedFailure(fn) def skip_with_cuda_python(reason): return unittest.skipIf(driver.USE_NV_BINDING, reason) def cudadevrt_missing(): if config.ENABLE_CUDASIM: return False try: path = libs.get_cudalib('cudadevrt', static=True) libs.check_static_lib(path) except FileNotFoundError: return True return False def skip_if_cudadevrt_missing(fn): return unittest.skipIf(cudadevrt_missing(), 'cudadevrt missing')(fn)
ContextResettingTestCase
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/forLoop1.py
{ "start": 855, "end": 1158 }
class ____(object): def __getitem__(self, item) -> str: return "hello" def testGetItemIterator() -> str: objWithGetItem = ClassWithGetItem() for f in objWithGetItem: return f return "none" # This should generate a syntax error. for in range(3): pass
ClassWithGetItem
python
getsentry__sentry
tests/sentry/sentry_apps/api/endpoints/test_sentry_internal_app_token_details.py
{ "start": 397, "end": 4797 }
class ____(APITestCase): endpoint = "sentry-api-0-sentry-internal-app-token-details" method = "delete" def setUp(self) -> None: self.user = self.create_user(email="boop@example.com") self.org = self.create_organization(owner=self.user, name="My Org") self.project = self.create_project(organization=self.org) self.internal_sentry_app = self.create_internal_integration( name="My Internal App", organization=self.org ) self.api_token = self.create_internal_integration_token( user=self.user, internal_integration=self.internal_sentry_app ) self.superuser = self.create_user(is_superuser=True) def test_delete_token(self) -> None: self.login_as(user=self.user) token_id = self.api_token.id self.get_success_response( self.internal_sentry_app.slug, token_id, status_code=status.HTTP_204_NO_CONTENT, ) assert not ApiToken.objects.filter(pk=token_id).exists() assert_org_audit_log_exists( organization=self.org, event=audit_log.get_event_id("INTERNAL_INTEGRATION_REMOVE_TOKEN"), target_object=token_id, actor=self.user, ) def test_delete_invalid_token(self) -> None: self.login_as(user=self.user) self.get_error_response( self.internal_sentry_app.slug, "random", status_code=status.HTTP_404_NOT_FOUND, ) def test_delete_token_another_app(self) -> None: another_app = self.create_internal_integration(name="Another app", organization=self.org) api_token = self.create_internal_integration_token( user=self.user, internal_integration=another_app ) self.login_as(user=self.user) self.get_error_response( self.internal_sentry_app.slug, api_token.id, status_code=status.HTTP_404_NOT_FOUND, ) def test_non_internal_app(self) -> None: sentry_app = self.create_sentry_app(name="My External App", organization=self.org) install = self.create_sentry_app_installation( slug=sentry_app.slug, organization=self.org, user=self.user ) self.login_as(user=self.user) response = self.get_error_response( install.sentry_app.slug, install.api_token.id, status_code=status.HTTP_403_FORBIDDEN, ) assert response.data == "This route is limited to internal integrations only" def test_sentry_app_not_found(self) -> None: self.login_as(user=self.user) self.get_error_response( "not_a_slug", self.api_token.id, status_code=status.HTTP_404_NOT_FOUND, ) def test_cannot_delete_partner_app_token(self) -> None: self.login_as(user=self.user) self.internal_sentry_app.update(metadata={"partnership_restricted": True}) self.get_error_response( self.internal_sentry_app.slug, self.api_token.id, status_code=status.HTTP_403_FORBIDDEN, ) def test_superuser_can_delete(self) -> None: self.login_as(self.superuser, superuser=True) self.get_success_response( self.internal_sentry_app.slug, self.api_token.id, status_code=status.HTTP_204_NO_CONTENT, ) assert not ApiToken.objects.filter(pk=self.api_token.id).exists() @override_settings(SENTRY_SELF_HOSTED=False) @override_options({"superuser.read-write.ga-rollout": True}) def test_superuser_read_write_delete(self) -> None: self.login_as(self.superuser, superuser=True) # superuser read cannot delete self.get_error_response( self.internal_sentry_app.slug, self.api_token.id, status_code=status.HTTP_403_FORBIDDEN, ) assert ApiToken.objects.filter(pk=self.api_token.id).exists() # superuser write can delete self.add_user_permission(self.superuser, "superuser.write") self.get_success_response( self.internal_sentry_app.slug, self.api_token.id, status_code=status.HTTP_204_NO_CONTENT, ) assert not ApiToken.objects.filter(pk=self.api_token.id).exists()
SentryInternalAppTokenCreationTest
python
anthropics__anthropic-sdk-python
src/anthropic/types/citation_char_location_param.py
{ "start": 253, "end": 538 }
class ____(TypedDict, total=False): cited_text: Required[str] document_index: Required[int] document_title: Required[Optional[str]] end_char_index: Required[int] start_char_index: Required[int] type: Required[Literal["char_location"]]
CitationCharLocationParam
python
pytorch__pytorch
.github/scripts/generate_ci_workflows.py
{ "start": 737, "end": 1323 }
class ____: # For use to enable workflows to run on pytorch/pytorch-canary run_on_canary: bool = False labels: set[str] = field(default_factory=set) # Certain jobs might not want to be part of the ciflow/[all,trunk] workflow isolated_workflow: bool = False unstable: bool = False def __post_init__(self) -> None: if not self.isolated_workflow: if LABEL_CIFLOW_PERIODIC not in self.labels: self.labels.add( LABEL_CIFLOW_TRUNK if not self.unstable else LABEL_CIFLOW_UNSTABLE )
CIFlowConfig
python
getsentry__sentry
tests/sentry/monitors/endpoints/test_project_monitor_checkin_index.py
{ "start": 344, "end": 516 }
class ____(BaseListMonitorCheckInsTest, BaseProjectMonitorTest): endpoint = "sentry-api-0-project-monitor-check-in-index" __test__ = True
ProjectListMonitorCheckInsTest
python
pypa__warehouse
warehouse/packaging/interfaces.py
{ "start": 3161, "end": 3407 }
class ____(ProjectNameUnavailableError): """Project name is too similar to existing project.""" def __init__(self, similar_project_name: str): self.similar_project_name: str = similar_project_name
ProjectNameUnavailableSimilarError
python
astropy__astropy
astropy/utils/metadata/merge.py
{ "start": 3633, "end": 3948 }
class ____(MergeStrategy): """ Merge ``left`` and ``right`` objects using the plus operator. This merge strategy is globally enabled by default. """ types = [(list, list), (tuple, tuple)] enabled = True @classmethod def merge(cls, left, right): return left + right
MergePlus
python
getsentry__sentry
src/sentry/sentry_apps/services/app/model.py
{ "start": 915, "end": 2109 }
class ____(RpcModel): id: int = -1 ident: str | None = None sentry_app_id: int = -1 avatar_type: int = 0 color: bool = False AVATAR_TYPES = SentryAppAvatarTypes.get_choices() url_path = "sentry-app-avatar" FILE_TYPE = "avatar.file" def __hash__(self) -> int: # Mimic the behavior of hashing a Django ORM entity, for compatibility with # serializers, as this avatar object is often used for that. return id(self) def get_avatar_type_display(self) -> str: return self.AVATAR_TYPES[self.avatar_type][1] def get_cache_key(self, size: int) -> str: color_identifier = "color" if self.color else "simple" return f"sentry_app_avatar:{self.sentry_app_id}:{color_identifier}:{size}" def get_avatar_photo_type(self) -> SentryAppAvatarPhotoTypes: return SentryAppAvatarPhotoTypes.LOGO if self.color else SentryAppAvatarPhotoTypes.ICON def absolute_url(self) -> str: """ Modified from AvatarBase.absolute_url for SentryAppAvatar """ url_base = options.get("system.url-prefix") return urljoin(url_base, f"/{self.url_path}/{self.ident}/")
RpcSentryAppAvatar
python
pytorch__pytorch
test/test_mps.py
{ "start": 561563, "end": 572090 }
class ____(TestCaseMPS): def test_metal_arange(self): x = torch.zeros(12, device="mps", dtype=torch.half) lib = torch.mps.compile_shader(""" kernel void arange(device half* x, uint idx [[thread_position_in_grid]]) { x[idx] = idx; } """) lib.arange(x) self.assertEqual(x, torch.arange(x.numel(), device='mps', dtype=x.dtype)) def test_metal_dispatch_3d(self): x = torch.empty(12, device="mps") y = torch.empty_like(x) z = torch.empty_like(x) lib = torch.mps.compile_shader(""" kernel void arange_x(device float* x, uint3 idx [[thread_position_in_grid]]) { x[idx.x + idx.y + idx.z] = idx.x; } kernel void arange_y(device float* x, uint3 idx [[thread_position_in_grid]]) { x[idx.x + idx.y + idx.z] = idx.y; } kernel void arange_z(device float* x, uint3 idx [[thread_position_in_grid]]) { x[idx.x + idx.y + idx.z] = idx.z; } """) # Check that one can enumerate all shaders self.assertEqual(set(dir(lib)), {f"arange_{i}" for i in ["x", "y", "z"]}) lib.arange_x(x) lib.arange_y(y, threads=(1, y.numel())) lib.arange_z(z, threads=(1, 1, z.numel())) self.assertEqual(x, torch.arange(x.numel(), device='mps', dtype=x.dtype)) self.assertEqual(x, y) self.assertEqual(x, z) def test_metal_arange_with_arg(self, start=3.14, step=.5): x = torch.zeros(12, device="mps") lib = torch.mps.compile_shader(""" kernel void arange(device float* x, constant float& start, constant float& step, uint idx [[thread_position_in_grid]]) { x[idx] = start + idx * step; } """) lib.arange(x, start, step) self.assertEqual(x, torch.arange(start, 8.66, .5, device='mps')) def test_metal_arange_with_arg_and_scalar_tensor(self): self.test_metal_arange_with_arg(step=torch.tensor(.5)) def test_metal_arange_with_arg_and_scalar_tensor_float64(self): self.test_metal_arange_with_arg(step=torch.tensor(.5, dtype=torch.float64)) def test_metal_arange_with_arg_and_cast(self): x = torch.zeros(12, device="mps", dtype=torch.half) y = torch.zeros(12, device="mps", dtype=torch.half) lib = torch.mps.compile_shader(""" kernel void arange_all_half(device half* x, constant half2& start_step, uint idx [[thread_position_in_grid]]) { x[idx] = start_step.x + idx * start_step.y; } kernel void arange_half_float(device half* x, constant half& start, constant float& step, uint idx [[thread_position_in_grid]]) { x[idx] = start + idx * step; } """) lib.arange_all_half(x, [3.14, .5], arg_casts="fp16") lib.arange_half_float(y, 3.14, .5, arg_casts={1: "fp16"}) self.assertEqual(x, torch.arange(3.14, 8.66, .5, device='mps', dtype=x.dtype)) self.assertEqual(x, y) def test_metal_error_checking(self): # Syntax error asserts self.assertRaises(SyntaxError, lambda: torch.mps.compile_shader("Syntax error")) cpu_tensor = torch.rand(3) mps_tensor = torch.rand(3, device="mps") lib = torch.mps.compile_shader("kernel void full(device half* x) { x[0] = 1.0; }") # Passing CPU tensor asserts self.assertRaises(RuntimeError, lambda: lib.full(cpu_tensor)) # Passing invalid shader name asserts self.assertRaises(RuntimeError, lambda: lib.non_existing(mps_tensor)) # Passing no tensors asserts self.assertRaises(RuntimeError, lambda: lib.full(12)) # Exceeing thread group size asserts max_thread_group_size = lib.full.max_threads_per_threadgroup self.assertRaises(ValueError, lambda: lib.full(mps_tensor, group_size=max_thread_group_size + 5)) self.assertRaises(ValueError, lambda: lib.full(mps_tensor, threads=(3, max_thread_group_size), group_size=(3, max_thread_group_size))) def test_metal_include(self): # Checks that includes embedding works lib = torch.mps.compile_shader("#include <c10/metal/special_math.h>") self.assertIsNotNone(lib) @parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16, torch.int32, torch.int64]) def test_reduction_utils(self, dtype): from torch._inductor.codegen.mps import DTYPE_TO_METAL lib = torch.mps.compile_shader(f""" #include <c10/metal/reduction_utils.h> kernel void do_sum(device {DTYPE_TO_METAL[dtype]}* out, constant {DTYPE_TO_METAL[dtype]}* inp, uint idx [[thread_position_in_grid]]) {{ out[idx] = c10::metal::simd_sum(inp[idx]); }} kernel void do_max(device {DTYPE_TO_METAL[dtype]}* out0, device int* out1, constant {DTYPE_TO_METAL[dtype]}* inp, uint idx [[thread_position_in_grid]]) {{ auto rc = c10::metal::simd_argmax(inp[idx]); out0[idx] = rc.first; out1[idx] = rc.second; }} """) x = torch.testing.make_tensor(28, device="mps", dtype=dtype) y = torch.empty_like(x) z0 = torch.empty_like(x) z1 = torch.empty_like(x, dtype=torch.int32) lib.do_sum(y, x) lib.do_max(z0, z1, x) x_sum = x.sum() x_max, x_max_idx = x.max(dim=0) max_err = (y - x_sum).abs().max().item() self.assertLess(max_err, 1e-2 if dtype == torch.float16 else 1e-5, f"results are {y}, but all elements should have been {x_sum.item()}") self.assertTrue((z0 == x_max).all().item(), f"results are {z0}, but all elements should have been {x_max.item()}") self.assertTrue((z1 == x_max_idx).all().item(), f"results are {z1}, but all elements should have been {x_max_idx.item()}") # Test nan propagation if not dtype.is_floating_point: return idx = 25 x[idx] = torch.nan lib.do_max(z0, z1, x) self.assertTrue(z0.isnan().all().item(), f"results are {z0}, but all elements should have been nan") self.assertTrue((z1 == idx).all().item(), f"results are {z1}, but all elements should have been {idx}") @parametrize("dtype", [torch.float32, torch.float16, torch.int32, torch.bfloat16]) def test_atomic_add(self, dtype): from torch._inductor.codegen.mps import DTYPE_TO_METAL mdtype = DTYPE_TO_METAL[dtype] lib = torch.mps.compile_shader(f""" #include <c10/metal/atomic.h> using namespace c10::metal; kernel void atomic_add(device AtomicType<{mdtype}>::type* out, constant {mdtype}* inc, uint idx [[thread_position_in_grid]]) {{ AtomicType<{mdtype}>::atomic_add(out, idx & 1 ? 3 : 4, inc[idx]); }} """) x = torch.arange(16, device="mps", dtype=dtype) y = torch.arange(16, device="mps", dtype=dtype) lib.atomic_add(x, y) self.assertEqual(x[3], 67) self.assertEqual(x[4], 60) def test_argument_buffers(self): lib = torch.mps.compile_shader(""" constant constexpr auto nbuffers = 64; struct Inputs { metal::array<device float *, nbuffers> args; }; kernel void sum_all(device float* output, constant Inputs& inputs, uint idx [[thread_position_in_grid]]) { auto rc = inputs.args[0][idx]; for(auto i = 1; i < nbuffers; ++i) { rc += inputs.args[i][idx]; } output[idx] = rc; } """) inputs = torch.rand(64, 32, device="mps").unbind(0) output = torch.empty_like(inputs[0]) lib.sum_all(output, inputs) correct = torch.zeros_like(inputs[0]) for inp in inputs: correct += inp self.assertEqual(correct, output) @unittest.skipIf(not torch.mps.profiler.is_metal_capture_enabled(), "Set MTL_CAPTURE_ENABLED and try again") def test_metal_capture(self): lib = torch.mps.compile_shader("kernel void full(device float* x, uint idx [[thread_position_in_grid]]) { x[idx] = 1.0; }") mps_tensor = torch.rand(32, device="mps") capture_name = f"lib_full{''.join(random.choice('0123456789') for i in range(5))}" capture_dirname = f"0000-{capture_name}.gputrace" if os.path.exists(capture_dirname): shutil.rmtree(capture_dirname) with torch.mps.profiler.metal_capture(capture_name): self.assertTrue(torch.mps.profiler.is_capturing_metal()) lib.full(mps_tensor) self.assertEqual(mps_tensor.sum().item(), 32.0) self.assertTrue(os.path.exists(capture_dirname), f"Capture file {capture_dirname} has not been generated") capture_listdir = os.listdir(capture_dirname) shutil.rmtree(capture_dirname) self.assertGreater(len(capture_listdir), 3, f"Capture file {capture_dirname} contains only metadata, i.e. {capture_listdir}") # TODO: Actually instantiate that test for the "mps" device to better reflect what it is doing. # This requires mps to be properly registered in the device generic test framework which is not the # case right now. We can probably use `allow_mps` introduced in https://github.com/pytorch/pytorch/pull/87342 # to achieve this. instantiate_device_type_tests(TestConsistency, globals(), allow_mps=True, only_for="mps") instantiate_device_type_tests(TestErrorInputs, globals(), allow_mps=True, only_for="mps") instantiate_device_type_tests(TestCommon, globals(), allow_mps=True, only_for="mps") instantiate_device_type_tests(TestLinalgMPS, globals(), allow_mps=True, only_for="mps") instantiate_parametrized_tests(TestAutocastMPS) instantiate_parametrized_tests(TestLogical) instantiate_parametrized_tests(TestMPS) instantiate_parametrized_tests(TestSDPA) instantiate_parametrized_tests(TestSmoothL1Loss) instantiate_parametrized_tests(TestMetalLibrary) if __name__ == "__main__": run_tests()
TestMetalLibrary
python
modin-project__modin
modin/tests/pandas/utils.py
{ "start": 30080, "end": 58377 }
class ____(Exception): pass def eval_general( modin_df, pandas_df, operation, comparator=df_equals, __inplace__=False, expected_exception=None, check_kwargs_callable=True, md_extra_kwargs=None, comparator_kwargs=None, check_for_execution_propagation=True, no_check_for_execution_propagation_reason=None, **kwargs, ): md_kwargs, pd_kwargs = {}, {} if isinstance(modin_df, (pd.DataFrame, pd.Series)): original_engine = modin_df._query_compiler.engine original_storage_format = modin_df._query_compiler.storage_format else: original_engine = None original_storage_format = None def execute_callable(fn, inplace=False, md_kwargs={}, pd_kwargs={}): try: pd_result = fn(pandas_df, **pd_kwargs) except Exception as pd_e: try: if inplace: _ = fn(modin_df, **md_kwargs) try_cast_to_pandas(modin_df) # force materialization else: try_cast_to_pandas( fn(modin_df, **md_kwargs) ) # force materialization except Exception as md_e: assert isinstance( md_e, type(pd_e) ), "Got Modin Exception type {}, but pandas Exception type {} was expected".format( type(md_e), type(pd_e) ) if expected_exception: if Engine.get() == "Ray": from ray.exceptions import RayTaskError # unwrap ray exceptions from remote worker if isinstance(md_e, RayTaskError): md_e = md_e.args[0] assert ( type(md_e) is type(expected_exception) and md_e.args == expected_exception.args ), f"not acceptable Modin's exception: [{repr(md_e)}]" assert ( pd_e.args == expected_exception.args ), f"not acceptable Pandas' exception: [{repr(pd_e)}]" elif expected_exception is False: # The only way to disable exception message checking. pass else: # It’s not enough that Modin and pandas have the same types of exceptions; # we need to explicitly specify the instance of an exception # (using `expected_exception`) in tests so that we can check exception messages. # This allows us to eliminate situations where exceptions are thrown # that we don't expect, which could hide different bugs. raise pd_e else: raise NoModinException( f"Modin doesn't throw an exception, while pandas does: [{repr(pd_e)}]" ) else: md_result = fn(modin_df, **md_kwargs) return (md_result, pd_result) if not inplace else (modin_df, pandas_df) for key, value in kwargs.items(): if check_kwargs_callable and callable(value): values = execute_callable(value) # that means, that callable raised an exception if values is None: return else: md_value, pd_value = values else: md_value, pd_value = value, value md_kwargs[key] = md_value pd_kwargs[key] = pd_value if md_extra_kwargs: assert isinstance(md_extra_kwargs, dict) md_kwargs.update(md_extra_kwargs) values = execute_callable( operation, md_kwargs=md_kwargs, pd_kwargs=pd_kwargs, inplace=__inplace__ ) if values is not None: assert isinstance(values, tuple) and len(values) == 2 modin_result, pandas_result = values if ( isinstance(modin_result, (pd.DataFrame, pd.Series)) and original_engine is not None and original_storage_format is not None ): if check_for_execution_propagation: assert modin_result._query_compiler.engine == original_engine, ( f"Result engine {modin_result._query_compiler.engine} does " + f"not match expected engine {original_engine}" ) assert ( modin_result._query_compiler.storage_format == original_storage_format ), ( "Result storage format " + f"{modin_result._query_compiler.storage_format} does " + f"not match expected storage format {original_storage_format}" ) else: assert ( isinstance(no_check_for_execution_propagation_reason, str) and len(no_check_for_execution_propagation_reason) > 0 ), ( "Must provide a reason for not expecting the operation to " + "propagate dataframe/series engine." ) comparator(modin_result, pandas_result, **(comparator_kwargs or {})) def eval_io( fn_name, comparator=df_equals, cast_to_str=False, expected_exception=None, check_kwargs_callable=True, modin_warning=None, modin_warning_str_match=None, md_extra_kwargs=None, *args, **kwargs, ): """Evaluate I/O operation outputs equality check. Parameters ---------- fn_name: str I/O operation name ("read_csv" for example). comparator: obj Function to perform comparison. cast_to_str: bool There could be some mismatches in dtypes, so we're casting the whole frame to `str` before comparison. See issue #1931 for details. expected_exception: Exception Exception that should be raised even if it is raised both by Pandas and Modin. modin_warning: obj Warning that should be raised by Modin. modin_warning_str_match: str If `modin_warning` is set, checks that the raised warning matches this string. md_extra_kwargs: dict Modin operation specific kwargs. """ def applyier(module, *args, **kwargs): result = getattr(module, fn_name)(*args, **kwargs) if cast_to_str: result = result.astype(str) if isinstance(result, (pd.DataFrame, pd.Series)): # Input methods that return a dataframe, e.g. read_csv, should # return a dataframe with engine and storage_format that match # the default Engine and StorageFormat, respectively. assert result._query_compiler.engine == Engine.get() assert result._query_compiler.storage_format == StorageFormat.get() return result def call_eval_general(): eval_general( pd, pandas, applyier, comparator=comparator, expected_exception=expected_exception, check_kwargs_callable=check_kwargs_callable, md_extra_kwargs=md_extra_kwargs, *args, **kwargs, ) warn_match = modin_warning_str_match if modin_warning is not None else None if modin_warning: with pytest.warns(modin_warning, match=warn_match): call_eval_general() else: call_eval_general() def eval_io_from_str(csv_str: str, unique_filename: str, **kwargs): """Evaluate I/O operation outputs equality check by using `csv_str` data passed as python str (csv test file will be created from `csv_str`). Parameters ---------- csv_str: str Test data for storing to csv file. unique_filename: str csv file name. """ with open(unique_filename, "w") as f: f.write(csv_str) eval_io( filepath_or_buffer=unique_filename, fn_name="read_csv", **kwargs, ) def create_test_dfs( *args, post_fn=None, backend=None, **kwargs ) -> tuple[pd.DataFrame, pandas.DataFrame]: if post_fn is None: post_fn = lambda df: ( # noqa: E731 df.convert_dtypes(dtype_backend=backend) if backend is not None else df ) elif backend is not None: post_fn = lambda df: post_fn(df).convert_dtypes( # noqa: E731 dtype_backend=backend ) return tuple( map(post_fn, [pd.DataFrame(*args, **kwargs), pandas.DataFrame(*args, **kwargs)]) ) def create_test_series( vals, sort=False, backend=None, **kwargs ) -> tuple[pd.Series, pandas.Series]: if isinstance(vals, dict): modin_series = pd.Series(vals[next(iter(vals.keys()))], **kwargs) pandas_series = pandas.Series(vals[next(iter(vals.keys()))], **kwargs) else: modin_series = pd.Series(vals, **kwargs) pandas_series = pandas.Series(vals, **kwargs) if sort: modin_series = modin_series.sort_values().reset_index(drop=True) pandas_series = pandas_series.sort_values().reset_index(drop=True) if backend is not None: modin_series = modin_series.convert_dtypes(dtype_backend=backend) pandas_series = pandas_series.convert_dtypes(dtype_backend=backend) return modin_series, pandas_series def generate_dfs(): df = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, 6, 7], "col3": [8, 9, 10, 11], "col4": [12, 13, 14, 15], "col5": [0, 0, 0, 0], } ) df2 = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, 6, 7], "col3": [8, 9, 10, 11], "col6": [12, 13, 14, 15], "col7": [0, 0, 0, 0], } ) return df, df2 def generate_multiindex_dfs(axis=1): def generate_multiindex(index): return pandas.MultiIndex.from_tuples( [("a", x) for x in index.values], names=["name1", "name2"] ) df1, df2 = generate_dfs() df1.axes[axis], df2.axes[axis] = map( generate_multiindex, [df1.axes[axis], df2.axes[axis]] ) return df1, df2 def generate_multiindex(elements_number, nlevels=2, is_tree_like=False): def generate_level(length, nlevel): src = ["bar", "baz", "foo", "qux"] return [src[i % len(src)] + f"-{nlevel}-{i}" for i in range(length)] if is_tree_like: for penalty_level in [0, 1]: lvl_len_f, lvl_len_d = math.modf( round(elements_number ** (1 / (nlevels - penalty_level)), 12) ) if lvl_len_d >= 2 and lvl_len_f == 0: break if lvl_len_d < 2 or lvl_len_f != 0: raise RuntimeError( f"Can't generate Tree-like MultiIndex with lenght: {elements_number} and number of levels: {nlevels}" ) lvl_len = int(lvl_len_d) result = pd.MultiIndex.from_product( [generate_level(lvl_len, i) for i in range(nlevels - penalty_level)], names=[f"level-{i}" for i in range(nlevels - penalty_level)], ) if penalty_level: result = pd.MultiIndex.from_tuples( [("base_level", *ml_tuple) for ml_tuple in result], names=[f"level-{i}" for i in range(nlevels)], ) return result.sort_values() else: base_level = ["first"] * (elements_number // 2 + elements_number % 2) + [ "second" ] * (elements_number // 2) primary_levels = [generate_level(elements_number, i) for i in range(1, nlevels)] arrays = [base_level] + primary_levels return pd.MultiIndex.from_tuples( list(zip(*arrays)), names=[f"level-{i}" for i in range(nlevels)] ).sort_values() def generate_none_dfs(): df = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, None, 7], "col3": [8, 9, 10, 11], "col4": [12, 13, 14, 15], "col5": [None, None, None, None], } ) df2 = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, 6, 7], "col3": [8, 9, 10, 11], "col6": [12, 13, 14, 15], "col7": [0, 0, 0, 0], } ) return df, df2 def get_unique_filename( test_name: str = "test", kwargs: dict = {}, extension: str = "csv", data_dir: Union[str, Path] = "", suffix: str = "", debug_mode=False, ): """Returns unique file name with specified parameters. Parameters ---------- test_name: str name of the test for which the unique file name is needed. kwargs: list of ints Unique combiantion of test parameters for creation of unique name. extension: str, default: "csv" Extension of unique file. data_dir: Union[str, Path] Data directory where test files will be created. suffix: str String to append to the resulted name. debug_mode: bool, default: False Get unique filename containing kwargs values. Otherwise kwargs values will be replaced with hash equivalent. Returns ------- Unique file name. """ suffix_part = f"_{suffix}" if suffix else "" extension_part = f".{extension}" if extension else "" if debug_mode: # shortcut if kwargs parameter are not provided if len(kwargs) == 0 and extension == "csv" and suffix == "": return os.path.join(data_dir, (test_name + suffix_part + f".{extension}")) assert "." not in extension, "please provide pure extension name without '.'" prohibited_chars = ['"', "\n"] non_prohibited_char = "np_char" char_counter = 0 kwargs_name = dict(kwargs) for key, value in kwargs_name.items(): for char in prohibited_chars: if isinstance(value, str) and char in value or callable(value): kwargs_name[key] = non_prohibited_char + str(char_counter) char_counter += 1 parameters_values = "_".join( [ ( str(value) if not isinstance(value, (list, tuple)) else "_".join([str(x) for x in value]) ) for value in kwargs_name.values() ] ) return os.path.join( data_dir, test_name + parameters_values + suffix_part + extension_part ) else: import uuid return os.path.join(data_dir, uuid.uuid1().hex + suffix_part + extension_part) def get_random_string(): random_string = "".join( random_state.choice([x for x in ascii_letters], size=10).tolist() ) return random_string def insert_lines_to_csv( csv_name: str, lines_positions: list, lines_type: str = "blank", encoding: str = None, **csv_reader_writer_params, ): """Insert lines to ".csv" file. Parameters ---------- csv_name: str ".csv" file that should be modified. lines_positions: list of ints Lines postions that sghould be modified (serial number of line - begins from 0, ends in <rows_number> - 1). lines_type: str Lines types that should be inserted to ".csv" file. Possible types: "blank" - empty line without any delimiters/separators, "bad" - lines with len(lines_data) > cols_number encoding: str Encoding type that should be used during file reading and writing. """ if lines_type == "blank": lines_data = [] elif lines_type == "bad": cols_number = len(pandas.read_csv(csv_name, nrows=1).columns) lines_data = [x for x in range(cols_number + 1)] else: raise ValueError( f"acceptable values for parameter are ['blank', 'bad'], actually passed {lines_type}" ) lines = [] with open(csv_name, "r", encoding=encoding, newline="") as read_file: try: dialect = csv.Sniffer().sniff(read_file.read()) read_file.seek(0) except Exception: dialect = None reader = csv.reader( read_file, dialect=dialect if dialect is not None else "excel", **csv_reader_writer_params, ) counter = 0 for row in reader: if counter in lines_positions: lines.append(lines_data) else: lines.append(row) counter += 1 with open(csv_name, "w", encoding=encoding, newline="") as write_file: writer = csv.writer( write_file, dialect=dialect if dialect is not None else "excel", **csv_reader_writer_params, ) writer.writerows(lines) def _get_open_files(): """ psutil open_files() can return a lot of extra information that we can allow to be different, like file position; for simplicity we care about path and fd only. """ return sorted((info.path, info.fd) for info in psutil.Process().open_files()) def check_file_leaks(func): """ A decorator that ensures that no *newly* opened file handles are left after decorated function is finished. """ if not TrackFileLeaks.get(): return func @functools.wraps(func) def check(*a, **kw): fstart = _get_open_files() try: return func(*a, **kw) finally: leaks = [] for item in _get_open_files(): try: fstart.remove(item) except ValueError: # Ignore files in /proc/, as they have nothing to do with # modin reading any data (and this is what we care about). if item[0].startswith("/proc/"): continue # Ignore files in /tmp/ray/session_*/logs (ray session logs) # because Ray intends to keep these logs open even after # work has been done. if re.search(r"/tmp/ray/session_.*/logs", item[0]): continue leaks.append(item) assert ( not leaks ), f"Unexpected open handles left for: {', '.join(item[0] for item in leaks)}" return check def dummy_decorator(): """A problematic decorator that does not use `functools.wraps`. This introduces unwanted local variables for inspect.currentframe. This decorator is used in test_io to test `read_csv` and `read_table` """ def wrapper(method): def wrapped_function(self, *args, **kwargs): result = method(self, *args, **kwargs) return result return wrapped_function return wrapper def generate_dataframe(row_size=NROWS, additional_col_values=None, idx_name=None): dates = pandas.date_range("2000", freq="h", periods=row_size) data = { "col1": np.arange(row_size) * 10, "col2": [str(x.date()) for x in dates], "col3": np.arange(row_size) * 10, "col4": [str(x.time()) for x in dates], "col5": [get_random_string() for _ in range(row_size)], "col6": random_state.uniform(low=0.0, high=10000.0, size=row_size), } index = None if idx_name is None else pd.RangeIndex(0, row_size, name=idx_name) if additional_col_values is not None: assert isinstance(additional_col_values, (list, tuple)) data.update({"col7": random_state.choice(additional_col_values, size=row_size)}) return pandas.DataFrame(data, index=index) def _make_csv_file(data_dir): def _csv_file_maker( filename=None, row_size=NROWS, force=True, delimiter=",", encoding=None, compression="infer", additional_col_values=None, remove_randomness=False, add_blank_lines=False, add_bad_lines=False, add_nan_lines=False, thousands_separator=None, decimal_separator=None, comment_col_char=None, quoting=csv.QUOTE_MINIMAL, quotechar='"', doublequote=True, escapechar=None, lineterminator=None, ): if filename is None: filename = get_unique_filename(data_dir=data_dir) if os.path.exists(filename) and not force: return None else: df = generate_dataframe(row_size, additional_col_values) if remove_randomness: df = df[["col1", "col2", "col3", "col4"]] if add_nan_lines: for i in range(0, row_size, row_size // (row_size // 10)): df.loc[i] = pandas.Series() if comment_col_char: char = comment_col_char if isinstance(comment_col_char, str) else "#" df.insert( loc=0, column="col_with_comments", value=[char if (x + 2) == 0 else x for x in range(row_size)], ) if thousands_separator is not None: for col_id in ["col1", "col3"]: df[col_id] = df[col_id].apply( lambda x: f"{x:,d}".replace(",", thousands_separator) ) df["col6"] = df["col6"].apply( lambda x: f"{x:,f}".replace(",", thousands_separator) ) filename = ( f"{filename}.{COMP_TO_EXT[compression]}" if compression != "infer" else filename ) df.to_csv( filename, sep=delimiter, encoding=encoding, compression=compression, index=False, decimal=decimal_separator if decimal_separator else ".", lineterminator=lineterminator, quoting=quoting, quotechar=quotechar, doublequote=doublequote, escapechar=escapechar, ) csv_reader_writer_params = { "delimiter": delimiter, "doublequote": doublequote, "escapechar": escapechar, "lineterminator": lineterminator if lineterminator else os.linesep, "quotechar": quotechar, "quoting": quoting, } if add_blank_lines: insert_lines_to_csv( csv_name=filename, lines_positions=[ x for x in range(5, row_size, row_size // (row_size // 10)) ], lines_type="blank", encoding=encoding, **csv_reader_writer_params, ) if add_bad_lines: insert_lines_to_csv( csv_name=filename, lines_positions=[ x for x in range(6, row_size, row_size // (row_size // 10)) ], lines_type="bad", encoding=encoding, **csv_reader_writer_params, ) return filename return _csv_file_maker def sort_index_for_equal_values(df, ascending=True): """Sort `df` indices of equal rows.""" if df.index.dtype == np.float64: # HACK: workaround for pandas bug: # https://github.com/pandas-dev/pandas/issues/34455 df.index = df.index.astype("str") res = df.groupby(by=df if df.ndim == 1 else df.columns, sort=False).apply( lambda df: df.sort_index(ascending=ascending) ) if res.index.nlevels > df.index.nlevels: # Sometimes GroupBy adds an extra level with 'by' to the result index. # GroupBy is very inconsistent about when it's doing this, so that's # why this clumsy if-statement is used. res.index = res.index.droplevel(0) # GroupBy overwrites original index names with 'by', so the following line restores original names res.index.names = df.index.names return res def df_equals_with_non_stable_indices(df1, df2): """Assert equality of two frames regardless of the index order for equal values.""" df1, df2 = map(try_cast_to_pandas, (df1, df2)) np.testing.assert_array_equal(df1.values, df2.values) sorted1, sorted2 = map(sort_index_for_equal_values, (df1, df2)) df_equals(sorted1, sorted2) def rotate_decimal_digits_or_symbols(value): if value.dtype == object: # When dtype is object, we assume that it is actually strings from MultiIndex level names return [x[-1] + x[:-1] for x in value] else: tens = value // 10 ones = value % 10 return tens + ones * 10 def make_default_file(file_type: str, data_dir: str): """Helper function for pytest fixtures.""" def _create_file(filename, force, nrows, ncols, func: str, func_kw=None): """ Helper function that creates a dataframe before writing it to a file. Eliminates the duplicate code that is needed before of output functions calls. Notes ----- Importantly, names of created files are added to `filenames` variable for their further automatic deletion. Without this step, files created by `pytest` fixtures will not be deleted. """ if force or not os.path.exists(filename): df = pandas.DataFrame( {f"col{x + 1}": np.arange(nrows) for x in range(ncols)} ) getattr(df, func)(filename, **func_kw if func_kw else {}) file_type_to_extension = { "excel": "xlsx", "fwf": "txt", "pickle": "pkl", } extension = file_type_to_extension.get(file_type, file_type) def _make_default_file(nrows=NROWS, ncols=2, force=True, **kwargs): filename = get_unique_filename(extension=extension, data_dir=data_dir) if file_type == "json": lines = kwargs.get("lines") func_kw = {"lines": lines, "orient": "records"} if lines else {} _create_file(filename, force, nrows, ncols, "to_json", func_kw) elif file_type in ("html", "excel", "feather", "stata", "pickle"): _create_file(filename, force, nrows, ncols, f"to_{file_type}") elif file_type == "hdf": func_kw = {"key": "df", "format": kwargs.get("format")} _create_file(filename, force, nrows, ncols, "to_hdf", func_kw) elif file_type == "fwf": if force or not os.path.exists(filename): fwf_data = kwargs.get("fwf_data") if fwf_data is None: with open("modin/tests/pandas/data/test_data.fwf", "r") as fwf_file: fwf_data = fwf_file.read() with open(filename, "w") as f: f.write(fwf_data) else: raise ValueError(f"Unsupported file type: {file_type}") return filename return _make_default_file def value_equals(obj1, obj2): """Check wherher two scalar or list-like values are equal and raise an ``AssertionError`` if they aren't.""" if is_list_like(obj1): np.testing.assert_array_equal(obj1, obj2) else: assert (obj1 == obj2) or (np.isnan(obj1) and np.isnan(obj2)) def dict_equals(dict1, dict2): """Check whether two dictionaries are equal and raise an ``AssertionError`` if they aren't.""" for key1, key2 in itertools.zip_longest(sorted(dict1), sorted(dict2)): value_equals(key1, key2) value_equals(dict1[key1], dict2[key2]) @contextmanager def switch_execution(engine: str, storage_format: str): old_engine = Engine.get() old_storage = StorageFormat.get() try: set_execution(engine, storage_format) yield finally: set_execution(old_engine, old_storage) def is_native_shallow_copy() -> bool: """Return if the current configuration uses native pandas execution and performs shallow copies.""" return ( Backend.get() == "Pandas" and not NativePandasDeepCopy.get() and not pandas.get_option("mode.copy_on_write") )
NoModinException
python
getsentry__sentry
src/sentry/workflow_engine/handlers/detector/stateful.py
{ "start": 2519, "end": 11829 }
class ____: dedupe_updates: dict[DetectorGroupKey, int] counter_updates: dict[DetectorGroupKey, DetectorCounters] state_updates: dict[DetectorGroupKey, tuple[bool, DetectorPriorityLevel]] counter_names: list[DetectorCounter] detector: Detector def __init__( self, detector: Detector, counter_names: list[DetectorCounter] | None = None, ): self.detector = detector self.counter_names = counter_names or [] self.dedupe_updates = {} self.counter_updates = {} self.state_updates = {} def enqueue_dedupe_update(self, group_key: DetectorGroupKey, dedupe_value: int): self.dedupe_updates[group_key] = dedupe_value def enqueue_counter_reset(self, group_key: DetectorGroupKey = None) -> None: """ Resets the counter values for the detector. This method is to reset the counters when the detector is resolved. """ self.counter_updates[group_key] = {key: None for key in self.counter_names} def enqueue_counter_update( self, group_key: DetectorGroupKey, counter_updates: DetectorCounters ): self.counter_updates[group_key] = counter_updates def enqueue_state_update( self, group_key: DetectorGroupKey, is_triggered: bool, priority: DetectorPriorityLevel ): self.state_updates[group_key] = (is_triggered, priority) def get_redis_keys_for_group_keys( self, group_keys: list[DetectorGroupKey] ) -> dict[str, tuple[DetectorGroupKey, str | DetectorCounter]]: """ Generate all Redis keys needed for the given group keys. Returns {redis_key: (group_key, key_type)} for efficient bulk fetching and processing. key_type can be: - "dedupe" for dedupe value keys - DetectorCounter (str | DetectorPriorityLevel) for counter keys """ key_mapping: dict[str, tuple[DetectorGroupKey, str | DetectorCounter]] = {} # Dedupe keys for group_key in group_keys: dedupe_key = self.build_key(group_key, "dedupe_value") key_mapping[dedupe_key] = (group_key, "dedupe") # Counter keys for group_key in group_keys: for counter_name in self.counter_names: counter_key = self.build_key(group_key, counter_name) key_mapping[counter_key] = (group_key, counter_name) return key_mapping def bulk_get_redis_values(self, redis_keys: list[str]) -> dict[str, Any]: """ Fetch multiple Redis values in a single pipeline operation. """ if not redis_keys: return {} pipeline = get_redis_client().pipeline() for key in redis_keys: pipeline.get(key) values = pipeline.execute() return dict(zip(redis_keys, values)) def bulk_get_detector_state( self, group_keys: list[DetectorGroupKey] ) -> dict[DetectorGroupKey, DetectorState]: """ Bulk fetches detector state for the passed `group_keys`. Returns a dict keyed by each `group_key` with the fetched `DetectorStateData`. If there's no `DetectorState` row for a `detector`/`group_key` pair then we'll exclude the group_key from the returned dict. """ # TODO: Cache this query (or individual fetches, then bulk fetch anything missing) query_filter = Q( detector_group_key__in=[group_key for group_key in group_keys if group_key is not None] ) if None in group_keys: query_filter |= Q(detector_group_key__isnull=True) return { detector_state.detector_group_key: detector_state for detector_state in self.detector.detectorstate_set.filter(query_filter) } def build_key( self, group_key: DetectorGroupKey = None, postfix: str | int | None = None ) -> str: key = f"detector:{self.detector.id}" group_postfix = f"{group_key if group_key is not None else ''}" if postfix: group_postfix = f"{group_postfix}:{postfix}" if group_postfix: return f"{key}:{group_postfix}" return key def commit_state_updates(self): self._bulk_commit_detector_state() self._bulk_commit_redis_state() def _bulk_commit_dedupe_values(self, pipeline): for group_key, dedupe_value in self.dedupe_updates.items(): pipeline.set(self.build_key(group_key, "dedupe_value"), dedupe_value, ex=REDIS_TTL) def _bulk_commit_counter_updates(self, pipeline): for group_key, counter_updates in self.counter_updates.items(): for counter_name, counter_value in counter_updates.items(): key_name = self.build_key(group_key, counter_name) if counter_value is None: pipeline.delete(key_name) else: pipeline.set(key_name, counter_value, ex=REDIS_TTL) def _bulk_commit_redis_state(self, key: DetectorGroupKey | None = None): pipeline = get_redis_client().pipeline() if self.dedupe_updates: self._bulk_commit_dedupe_values(pipeline) if self.counter_updates: self._bulk_commit_counter_updates(pipeline) pipeline.execute() self.dedupe_updates.clear() self.counter_updates.clear() def _bulk_commit_detector_state(self): # TODO: We should already have these loaded from earlier, figure out how to cache and reuse detector_state_lookup = self.bulk_get_detector_state( [update for update in self.state_updates.keys()] ) created_detector_states = [] updated_detector_states = [] for group_key, (is_triggered, priority) in self.state_updates.items(): detector_state = detector_state_lookup.get(group_key) if not detector_state: created_detector_states.append( DetectorState( detector_group_key=group_key, detector=self.detector, is_triggered=is_triggered, state=priority, ) ) elif is_triggered != detector_state.is_triggered or priority != detector_state.state: detector_state.is_triggered = is_triggered detector_state.state = priority updated_detector_states.append(detector_state) if created_detector_states: DetectorState.objects.bulk_create(created_detector_states) if updated_detector_states: DetectorState.objects.bulk_update(updated_detector_states, ["is_triggered", "state"]) self.state_updates.clear() def get_state_data( self, group_keys: list[DetectorGroupKey] ) -> dict[DetectorGroupKey, DetectorStateData]: """ Fetches state data associated with this detector for the associated `group_keys`. Returns a dict keyed by each group_key with the fetched `DetectorStateData`. If data isn't currently stored, falls back to default values. """ group_key_detectors = self.bulk_get_detector_state(group_keys) # Get Redis keys and fetch values in single pipeline operation redis_key_mapping = self.get_redis_keys_for_group_keys(group_keys) redis_values = self.bulk_get_redis_values(list(redis_key_mapping.keys())) # Process values using the mapping group_key_dedupe_values: dict[DetectorGroupKey, int] = {} counter_updates: dict[DetectorGroupKey, DetectorCounters] = {} # Initialize counter_updates for all group keys for group_key in group_keys: counter_updates[group_key] = {} # Process all values using the mapping for redis_key, redis_value in redis_values.items(): group_key, key_type = redis_key_mapping[redis_key] if key_type == "dedupe": group_key_dedupe_values[group_key] = int(redis_value) if redis_value else 0 else: # key_type is a counter name (DetectorCounter) counter_updates[group_key][key_type] = ( int(redis_value) if redis_value is not None else redis_value ) # Ensure all group keys have dedupe values (default to 0 if not found) for group_key in group_keys: if group_key not in group_key_dedupe_values: group_key_dedupe_values[group_key] = 0 results = {} for group_key in group_keys: detector_state = group_key_detectors.get(group_key) results[group_key] = DetectorStateData( group_key=group_key, is_triggered=detector_state.is_triggered if detector_state else False, status=( DetectorPriorityLevel(int(detector_state.state)) if detector_state else DetectorPriorityLevel.OK ), dedupe_value=group_key_dedupe_values[group_key], counter_updates=counter_updates.get(group_key, {}), ) return results DetectorThresholds = dict[DetectorPriorityLevel, int]
DetectorStateManager
python
huggingface__transformers
src/transformers/models/mask2former/modeling_mask2former.py
{ "start": 75447, "end": 84796 }
class ____(GradientCheckpointingLayer): """ The Mask2FormerMaskedAttentionDecoderLayer is made up of self-attention, cross (masked) attention as well as FFN blocks. The cross attention block used as part of `Mask2FormerMaskedAttentionDecoderLayer` is actually a `masked attention` block that restricts the attention to localized features centered around predicted segments which leads to faster convergence and improved performance. The order of self and cross (i.e. masked) attention blocks have also been swapped in Mask2FormerMaskedAttentionDecoder compared to a standard DetrDecoder as an optimization improvement. Args: config (`Mask2FormerConfig`): The configuration used to initialize the Mask2FormerMaskedAttentionDecoder. """ def __init__(self, config: Mask2FormerConfig): super().__init__() self.config = config self.embed_dim = self.config.hidden_dim self.pre_norm = self.config.pre_norm self.self_attn = Mask2FormerAttention( embed_dim=self.embed_dim, num_heads=config.num_attention_heads, dropout=config.dropout, is_decoder=True, ) self.dropout = self.config.dropout self.activation_fn = ACT2FN[self.config.activation_function] self.activation_dropout = self.config.dropout self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim) self.cross_attn = nn.MultiheadAttention(self.embed_dim, self.config.num_attention_heads, self.config.dropout) self.cross_attn_layer_norm = nn.LayerNorm(self.embed_dim) self.fc1 = nn.Linear(self.embed_dim, self.config.dim_feedforward) self.fc2 = nn.Linear(self.config.dim_feedforward, self.embed_dim) self.final_layer_norm = nn.LayerNorm(self.embed_dim) def with_pos_embed(self, tensor, pos: Optional[Tensor]): return tensor if pos is None else tensor + pos def forward_post( self, hidden_states: torch.Tensor, level_index: Optional[int] = None, attention_mask: Optional[torch.Tensor] = None, position_embeddings: Optional[torch.Tensor] = None, query_position_embeddings: Optional[torch.Tensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = False, ): # Masked(Cross)-Attention Block cross_attn_weights = None self_attn_weights = None residual = hidden_states hidden_states, cross_attn_weights = self.cross_attn( query=self.with_pos_embed(hidden_states, query_position_embeddings), key=self.with_pos_embed(encoder_hidden_states[level_index], position_embeddings[level_index]), value=encoder_hidden_states[level_index], attn_mask=encoder_attention_mask, key_padding_mask=None, ) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states hidden_states = self.cross_attn_layer_norm(hidden_states) # Self Attention Block residual = hidden_states hidden_states, self_attn_weights = self.self_attn( hidden_states=hidden_states, position_embeddings=query_position_embeddings, attention_mask=None, output_attentions=True, ) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states hidden_states = self.self_attn_layer_norm(hidden_states) # Fully Connected residual = hidden_states hidden_states = self.activation_fn(self.fc1(hidden_states)) hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training) hidden_states = self.fc2(hidden_states) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states hidden_states = self.final_layer_norm(hidden_states) outputs = (hidden_states,) if output_attentions: outputs += (self_attn_weights, cross_attn_weights) return outputs def forward_pre( self, hidden_states: torch.Tensor, level_index: Optional[int] = None, attention_mask: Optional[torch.Tensor] = None, position_embeddings: Optional[torch.Tensor] = None, query_position_embeddings: Optional[torch.Tensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = False, ): # Masked(Cross)-Attention Block cross_attn_weights = None self_attn_weights = None residual = hidden_states hidden_states = self.cross_attn_layer_norm(hidden_states) hidden_states, cross_attn_weights = self.cross_attn( query=self.with_pos_embed(hidden_states, query_position_embeddings), key=self.with_pos_embed(encoder_hidden_states[level_index], position_embeddings[level_index]), value=encoder_hidden_states[level_index], attn_mask=encoder_attention_mask, key_padding_mask=None, ) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states # Self Attention Block residual = hidden_states hidden_states = self.self_attn_layer_norm(hidden_states) hidden_states, self_attn_weights = self.self_attn( hidden_states=hidden_states, position_embeddings=query_position_embeddings, attention_mask=None, output_attentions=True, ) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states # Fully Connected residual = hidden_states hidden_states = self.final_layer_norm(hidden_states) hidden_states = self.activation_fn(self.fc1(hidden_states)) hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training) hidden_states = self.fc2(hidden_states) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states outputs = (hidden_states,) if output_attentions: outputs += (self_attn_weights, cross_attn_weights) return outputs def forward( self, hidden_states: torch.Tensor, level_index: Optional[int] = None, attention_mask: Optional[torch.Tensor] = None, position_embeddings: Optional[torch.Tensor] = None, query_position_embeddings: Optional[torch.Tensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = False, ): """ Args: hidden_states (`torch.FloatTensor`): Input to the layer of shape `(seq_len, batch, embed_dim)`. attention_mask (`torch.FloatTensor`): Attention mask of shape `(1, seq_len, tgt_len, src_len)`. position_embeddings (`torch.FloatTensor`, *optional*): Position embeddings that are added to the keys in the masked-attention layer. query_position_embeddings (`torch.FloatTensor`, *optional*): Position embeddings that are added to the queries and keys in the self-attention layer. encoder_hidden_states (`torch.FloatTensor`): Cross attention input to the layer of shape `(seq_len, batch, embed_dim)`. encoder_attention_mask (`torch.FloatTensor`): Encoder attention mask of size`(1, seq_len, tgt_len, src_len)`. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. """ if self.pre_norm: outputs = self.forward_pre( hidden_states=hidden_states, level_index=level_index, position_embeddings=position_embeddings, query_position_embeddings=query_position_embeddings, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, output_attentions=output_attentions, ) else: outputs = self.forward_post( hidden_states=hidden_states, level_index=level_index, position_embeddings=position_embeddings, query_position_embeddings=query_position_embeddings, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, output_attentions=output_attentions, ) return outputs
Mask2FormerMaskedAttentionDecoderLayer
python
jupyterlab__jupyterlab
jupyterlab/handlers/extension_manager_handler.py
{ "start": 369, "end": 5063 }
class ____(APIHandler): def initialize(self, manager: ExtensionManager): super().initialize() self.manager = manager @web.authenticated async def get(self): """GET query returns info on extensions Query arguments: refresh: [optional] Force refreshing the list of extensions - ["0", "1"]; default 0 query: [optional] Query to search for extensions - default None (i.e. returns installed extensions) page: [optional] Result page - default 1 (min. 1) per_page: [optional] Number of results per page - default 30 (max. 100) """ query = self.get_argument("query", None) page = max(1, int(self.get_argument("page", "1"))) per_page = min(100, int(self.get_argument("per_page", "30"))) if self.get_argument("refresh", "0") == "1": await self.manager.refresh(query, page, per_page) extensions, last_page = await self.manager.list_extensions(query, page, per_page) self.set_status(200) if last_page is not None: links = [] query_args = {"page": last_page, "per_page": per_page} if query is not None: query_args["query"] = query last = urlunparse( ( self.request.protocol, self.request.host, self.request.path, "", urlencode(query_args, doseq=True), "", ) ) links.append(f'<{last}>; rel="last"') if page > 1: query_args["page"] = max(1, page - 1) prev = urlunparse( ( self.request.protocol, self.request.host, self.request.path, "", urlencode(query_args, doseq=True), "", ) ) links.append(f'<{prev}>; rel="prev"') if page < last_page: query_args["page"] = min(page + 1, last_page) next_ = urlunparse( ( self.request.protocol, self.request.host, self.request.path, "", urlencode(query_args, doseq=True), "", ) ) links.append(f'<{next_}>; rel="next"') query_args["page"] = 1 first = urlunparse( ( self.request.protocol, self.request.host, self.request.path, "", urlencode(query_args, doseq=True), "", ) ) links.append(f'<{first}>; rel="first"') self.set_header("Link", ", ".join(links)) self.finish(json.dumps(list(map(dataclasses.asdict, extensions)))) @web.authenticated async def post(self): """POST query performs an action on a specific extension Body arguments: { "cmd": Action to perform - ["install", "uninstall", "enable", "disable"] "extension_name": Extension name "extension_version": [optional] Extension version (used only for install action) } """ data = self.get_json_body() cmd = data["cmd"] name = data["extension_name"] version = data.get("extension_version") if cmd not in ("install", "uninstall", "enable", "disable") or not name: raise web.HTTPError( 422, f"Could not process instruction {cmd!r} with extension name {name!r}", ) ret_value = None try: if cmd == "install": ret_value = await self.manager.install(name, version) elif cmd == "uninstall": ret_value = await self.manager.uninstall(name) elif cmd == "enable": ret_value = await self.manager.enable(name) elif cmd == "disable": ret_value = await self.manager.disable(name) except Exception as e: raise web.HTTPError(500, str(e)) from e if ret_value.status == "error": self.set_status(500) else: self.set_status(201) self.finish(json.dumps(dataclasses.asdict(ret_value))) # The path for lab extensions handler. extensions_handler_path = r"/lab/api/extensions"
ExtensionHandler
python
django-extensions__django-extensions
tests/test_management_command.py
{ "start": 2125, "end": 2549 }
class ____(TestCase): def test_some_output(self): out = StringIO() call_command("show_template_tags", stdout=out) output = out.getvalue() # Once django_extension is installed during tests it should appear with # its templatetags self.assertIn("django_extensions", output) # let's check at least one self.assertIn("syntax_color", output)
ShowTemplateTagsTests
python
scrapy__scrapy
tests/test_downloadermiddleware.py
{ "start": 6134, "end": 7965 }
class ____(TestManagerBase): @deferred_f_from_coro_f async def test_invalid_process_request(self): """Invalid return value for process_request method should raise an exception""" req = Request("http://example.com/index.html") class InvalidProcessRequestMiddleware: def process_request(self, request): return 1 async with self.get_mwman() as mwman: mwman._add_middleware(InvalidProcessRequestMiddleware()) with pytest.raises(_InvalidOutput): await self._download(mwman, req) @deferred_f_from_coro_f async def test_invalid_process_response(self): """Invalid return value for process_response method should raise an exception""" req = Request("http://example.com/index.html") class InvalidProcessResponseMiddleware: def process_response(self, request, response): return 1 async with self.get_mwman() as mwman: mwman._add_middleware(InvalidProcessResponseMiddleware()) with pytest.raises(_InvalidOutput): await self._download(mwman, req) @deferred_f_from_coro_f async def test_invalid_process_exception(self): """Invalid return value for process_exception method should raise an exception""" req = Request("http://example.com/index.html") class InvalidProcessExceptionMiddleware: def process_request(self, request): raise RuntimeError def process_exception(self, request, exception): return 1 async with self.get_mwman() as mwman: mwman._add_middleware(InvalidProcessExceptionMiddleware()) with pytest.raises(_InvalidOutput): await self._download(mwman, req)
TestInvalidOutput