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
ethereum__web3.py
web3/_utils/filters.py
{ "start": 6033, "end": 6081 }
class ____(AsyncFilter): pass
AsyncBlockFilter
python
allegroai__clearml
clearml/backend_api/services/v2_20/events.py
{ "start": 161421, "end": 165142 }
class ____(Response): """ Response of events.scalar_metrics_iter_raw endpoint. :param variants: Raw data points for each variant :type variants: dict :param total: Total data points count. If count_total is false, null is returned :type total: int :param returned: Number of data points returned in this call. If 0 results were returned, no more results are avilable :type returned: int :param scroll_id: Scroll ID. Use to get more data points when calling this endpoint again :type scroll_id: str """ _service = "events" _action = "scalar_metrics_iter_raw" _version = "2.20" _schema = { "definitions": {}, "properties": { "returned": { "description": "Number of data points returned in this call. If 0 results were returned, no more results are avilable", "type": ["integer", "null"], }, "scroll_id": { "description": "Scroll ID. Use to get more data points when calling this endpoint again", "type": ["string", "null"], }, "total": { "description": "Total data points count. If count_total is false, null is returned", "type": ["integer", "null"], }, "variants": { "additionalProperties": True, "description": "Raw data points for each variant", "type": ["object", "null"], }, }, "type": "object", } def __init__( self, variants: Optional[dict] = None, total: Optional[int] = None, returned: Optional[int] = None, scroll_id: Optional[str] = None, **kwargs: Any ) -> None: super(ScalarMetricsIterRawResponse, self).__init__(**kwargs) self.variants = variants self.total = total self.returned = returned self.scroll_id = scroll_id @schema_property("variants") def variants(self) -> Optional[dict]: return self._property_variants @variants.setter def variants(self, value: Optional[dict]) -> None: if value is None: self._property_variants = None return self.assert_isinstance(value, "variants", (dict,)) self._property_variants = value @schema_property("total") def total(self) -> Optional[int]: return self._property_total @total.setter def total(self, value: Optional[int]) -> None: if value is None: self._property_total = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "total", six.integer_types) self._property_total = value @schema_property("returned") def returned(self) -> Optional[int]: return self._property_returned @returned.setter def returned(self, value: Optional[int]) -> None: if value is None: self._property_returned = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "returned", six.integer_types) self._property_returned = value @schema_property("scroll_id") def scroll_id(self) -> Optional[str]: return self._property_scroll_id @scroll_id.setter def scroll_id(self, value: Optional[str]) -> None: if value is None: self._property_scroll_id = None return self.assert_isinstance(value, "scroll_id", six.string_types) self._property_scroll_id = value
ScalarMetricsIterRawResponse
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI036.py
{ "start": 1139, "end": 1473 }
class ____: def __exit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None, weird_extra_arg: int = ..., *args: int, **kwargs: str) -> None: ... async def __aexit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> Awaitable[None]: ...
GoodFive
python
astropy__astropy
astropy/io/votable/converters.py
{ "start": 29658, "end": 30857 }
class ____(NumericArray): """ Handles a fixed-size array of complex numbers. """ vararray_type = ComplexArrayVarArray def __init__(self, field, base, arraysize, config=None, pos=None): NumericArray.__init__(self, field, base, arraysize, config, pos) self._items *= 2 def parse(self, value, config=None, pos=None): parts = self._splitter(value, config, pos) if parts == [""]: parts = [] return self.parse_parts(parts, config, pos) def parse_parts(self, parts, config=None, pos=None): if len(parts) != self._items: vo_raise(E02, (self._items, len(parts)), config, pos) base_parse = self._base.parse_parts result = [] result_mask = [] for i in range(0, self._items, 2): value = [float(x) for x in parts[i : i + 2]] value, mask = base_parse(value, config, pos) result.append(value) result_mask.append(mask) result = np.array(result, dtype=self._base.format).reshape(self._arraysize) result_mask = np.array(result_mask, dtype="bool").reshape(self._arraysize) return result, result_mask
ComplexArray
python
getsentry__sentry
tests/sentry/seer/fetch_issues/test_by_text_query.py
{ "start": 1998, "end": 9459 }
class ____(IntegrationTestCase, CreateEventTestCase): provider = GitHubIntegrationProvider def setUp(self): super().setUp() self.gh_repo: Repository = self.create_repo( name="getsentry/sentry", provider="integrations:github", integration_id=self.integration.id, project=self.project, url="https://github.com/getsentry/sentry", external_id="123456", ) self.code_mapping = self.create_code_mapping( project=self.project, repo=self.gh_repo, ) def test_fetch_issues_message_substring_search(self): """Test that text queries do case-insensitive substring search in issue messages.""" group = self._create_event( filenames=["auth.py", "utils.py"], function_names=["authenticate", "validate"], culprit="Authentication failed", user_id="1", ).group # Test queries that should match content in the message # Message will be something like: "hello! Error auth.py authenticate Authentication failed" # Test 1: Should find with substring from event message assert self.gh_repo.external_id is not None seer_response = fetch_issues( organization_id=self.organization.id, provider="integrations:github", external_id=self.gh_repo.external_id, query="hello", ) assert "error" not in seer_response assert len(seer_response["issues"]) > 0, "Should find issue with 'hello' substring" assert group.id in seer_response["issues"] # Test 2: Should find with substring from filename in message assert self.gh_repo.external_id is not None seer_response = fetch_issues( organization_id=self.organization.id, provider="integrations:github", external_id=self.gh_repo.external_id, query="auth", ) assert "error" not in seer_response assert len(seer_response["issues"]) > 0, "Should find issue with 'auth' substring" assert group.id in seer_response["issues"] # Check metadata and message fields are present in end-to-end call first_issue = seer_response["issues_full"][0] assert "metadata" in first_issue assert "message" in first_issue # Verify the metadata and message are non-empty and have expected content metadata = first_issue["metadata"] assert isinstance(metadata, dict) assert len(metadata) > 0, "metadata should not be empty" message = first_issue["message"] assert isinstance(message, str) assert len(message) > 0, "message should not be empty" # Check that the group ID matches assert first_issue["id"] == str(group.id) def test_fetch_issues_no_match(self): """Test that non-matching queries return empty results.""" self._create_event( filenames=["models/user.py"], function_names=["validate_user"], culprit="Authentication error", user_id="1", ) # Query for something that shouldn't match anything in the message assert self.gh_repo.external_id is not None seer_response = fetch_issues( organization_id=self.organization.id, provider="integrations:github", external_id=self.gh_repo.external_id, query="nonexistent_keyword_xyz123", ) # Should return empty results assert seer_response == {"issues": [], "issues_full": []} def test_fetch_issues_culprit_search(self): """Test that queries match content in the culprit field.""" group = self._create_event( filenames=["test.py"], function_names=["test_func"], culprit="Database connection timeout", user_id="1", ).group # Query for a keyword from the culprit assert self.gh_repo.external_id is not None seer_response = fetch_issues( organization_id=self.organization.id, provider="integrations:github", external_id=self.gh_repo.external_id, query="database conn", ) assert "error" not in seer_response assert len(seer_response["issues"]) > 0 assert group.id in seer_response["issues"] def test_fetch_issues_limit_parameter(self): """Test that the limit parameter is respected.""" # Create multiple matching events for i in range(5): self._create_event( filenames=["common.py"], function_names=[f"func_{i}"], culprit=f"Error {i}", user_id=str(i), ) limit = 2 assert self.gh_repo.external_id is not None seer_response = fetch_issues( organization_id=self.organization.id, provider="integrations:github", external_id=self.gh_repo.external_id, query="common.py", limit=limit, ) assert "error" not in seer_response assert len(seer_response["issues"]) <= limit def test_fetch_issues_from_repo_projects_returns_groups(self): """Test that _fetch_issues_from_repo_projects returns a list of Group objects.""" # Create a group that should match the search query event = self._create_event( filenames=["auth.py", "utils.py"], function_names=["authenticate", "validate"], culprit="Authentication failed", user_id="1", ) expected_group = event.group # Get repo projects assert self.gh_repo.external_id is not None repo_projects = get_repo_and_projects( organization_id=self.organization.id, provider="integrations:github", external_id=self.gh_repo.external_id, ) # Test the internal function directly with a query that should match the created event # Use "hello" which appears in the event message (from other tests we know this works) results = _fetch_issues_from_repo_projects(repo_projects=repo_projects, query="hello") assert isinstance(results, list) assert len(results) > 0, "Expected to find at least one matching group" for result in results: assert isinstance(result, Group) # Verify our expected group is in the results result_ids = [result.id for result in results] assert expected_group.id in result_ids def test_fetch_issues_from_repo_projects_empty_result(self): """Test that _fetch_issues_from_repo_projects returns empty list when no matches.""" # Get repo projects but don't create any matching events assert self.gh_repo.external_id is not None repo_projects = get_repo_and_projects( organization_id=self.organization.id, provider="integrations:github", external_id=self.gh_repo.external_id, ) # Test the internal function with a query that won't match anything results = _fetch_issues_from_repo_projects( repo_projects=repo_projects, query="nonexistent_search_term_xyz123" ) # Verify it returns an empty list assert isinstance(results, list) assert len(results) == 0
TestFetchIssuesByTextQuery
python
pytorch__pytorch
torch/testing/_internal/common_subclass.py
{ "start": 2230, "end": 3161 }
class ____(WrapperTensor): @classmethod def get_wrapper_properties(cls, t, requires_grad=False): return t, {"requires_grad": requires_grad, "dispatch_sizes_strides_policy": "sizes"} def __init__(self, t, requires_grad=False): self.t = t @classmethod def __torch_dispatch__(cls, func, types, args=(), kwargs=None): if not all(issubclass(cls, t) for t in types): return NotImplemented if kwargs is None: kwargs = {} def unwrap(e): return e.t if isinstance(e, WrapperTensorWithCustomSizes) else e def wrap(e): return WrapperTensorWithCustomSizes(e) if isinstance(e, torch.Tensor) else e rs = tree_map(wrap, func(*tree_map(unwrap, args), **tree_map(unwrap, kwargs or {}))) return rs def __repr__(self): return super().__repr__(tensor_contents=f"t={self.t}")
WrapperTensorWithCustomSizes
python
tornadoweb__tornado
demos/facebook/facebook.py
{ "start": 3426, "end": 3613 }
class ____(BaseHandler, tornado.auth.FacebookGraphMixin): def get(self): self.clear_cookie("fbdemo_user") self.redirect(self.get_argument("next", "/"))
AuthLogoutHandler
python
boto__boto3
tests/unit/dynamodb/test_transform.py
{ "start": 15331, "end": 18368 }
class ____(BaseTransformationTest): def setUp(self): super().setUp() self.add_shape({'ConditionExpression': {'type': 'string'}}) self.add_shape({'KeyExpression': {'type': 'string'}}) shapes = self.json_model['shapes'] input_members = shapes['SampleOperationInputOutput']['members'] input_members['KeyCondition'] = {'shape': 'KeyExpression'} input_members['AttrCondition'] = {'shape': 'ConditionExpression'} self.injector = TransformationInjector() self.build_models() def test_non_condition_input(self): params = {'KeyCondition': 'foo', 'AttrCondition': 'bar'} self.injector.inject_condition_expressions( params, self.operation_model ) assert params == {'KeyCondition': 'foo', 'AttrCondition': 'bar'} def test_single_attr_condition_expression(self): params = {'AttrCondition': Attr('foo').eq('bar')} self.injector.inject_condition_expressions( params, self.operation_model ) assert params == { 'AttrCondition': '#n0 = :v0', 'ExpressionAttributeNames': {'#n0': 'foo'}, 'ExpressionAttributeValues': {':v0': 'bar'}, } def test_single_key_conditon_expression(self): params = {'KeyCondition': Key('foo').eq('bar')} self.injector.inject_condition_expressions( params, self.operation_model ) assert params == { 'KeyCondition': '#n0 = :v0', 'ExpressionAttributeNames': {'#n0': 'foo'}, 'ExpressionAttributeValues': {':v0': 'bar'}, } def test_key_and_attr_conditon_expression(self): params = { 'KeyCondition': Key('foo').eq('bar'), 'AttrCondition': Attr('biz').eq('baz'), } self.injector.inject_condition_expressions( params, self.operation_model ) assert params == { 'KeyCondition': '#n1 = :v1', 'AttrCondition': '#n0 = :v0', 'ExpressionAttributeNames': {'#n0': 'biz', '#n1': 'foo'}, 'ExpressionAttributeValues': {':v0': 'baz', ':v1': 'bar'}, } def test_key_and_attr_conditon_expression_with_placeholders(self): params = { 'KeyCondition': Key('foo').eq('bar'), 'AttrCondition': Attr('biz').eq('baz'), 'ExpressionAttributeNames': {'#a': 'b'}, 'ExpressionAttributeValues': {':c': 'd'}, } self.injector.inject_condition_expressions( params, self.operation_model ) assert params == { 'KeyCondition': '#n1 = :v1', 'AttrCondition': '#n0 = :v0', 'ExpressionAttributeNames': { '#n0': 'biz', '#n1': 'foo', '#a': 'b', }, 'ExpressionAttributeValues': { ':v0': 'baz', ':v1': 'bar', ':c': 'd', }, }
TestTransformConditionExpression
python
django__django
tests/staticfiles_tests/test_storage.py
{ "start": 36663, "end": 38949 }
class ____(CollectionTestCase): """ Files referenced from CSS use the correct final hashed name regardless of the order in which the files are post-processed. """ hashed_file_path = hashed_file_path def setUp(self): super().setUp() self._temp_dir = temp_dir = tempfile.mkdtemp() os.makedirs(os.path.join(temp_dir, "test")) self.addCleanup(shutil.rmtree, temp_dir) def _get_filename_path(self, filename): return os.path.join(self._temp_dir, "test", filename) def test_file_change_after_collectstatic(self): # Create initial static files. file_contents = ( ("foo.png", "foo"), ("bar.css", 'url("foo.png")\nurl("xyz.png")'), ("xyz.png", "xyz"), ) for filename, content in file_contents: with open(self._get_filename_path(filename), "w") as f: f.write(content) with self.modify_settings(STATICFILES_DIRS={"append": self._temp_dir}): finders.get_finder.cache_clear() err = StringIO() # First collectstatic run. call_command("collectstatic", interactive=False, verbosity=0, stderr=err) relpath = self.hashed_file_path("test/bar.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"foo.acbd18db4cc2.png", content) self.assertIn(b"xyz.d16fb36f0911.png", content) # Change the contents of the png files. for filename in ("foo.png", "xyz.png"): with open(self._get_filename_path(filename), "w+b") as f: f.write(b"new content of file to change its hash") # The hashes of the png files in the CSS file are updated after # a second collectstatic. call_command("collectstatic", interactive=False, verbosity=0, stderr=err) relpath = self.hashed_file_path("test/bar.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"foo.57a5cb9ba68d.png", content) self.assertIn(b"xyz.57a5cb9ba68d.png", content)
TestCollectionHashedFilesCache
python
pydantic__pydantic
pydantic/deprecated/config.py
{ "start": 475, "end": 958 }
class ____(type): def __getattr__(self, item: str) -> Any: try: obj = _config.config_defaults[item] warnings.warn(_config.DEPRECATION_MESSAGE, DeprecationWarning) return obj except KeyError as exc: raise AttributeError(f"type object '{self.__name__}' has no attribute {exc}") from exc @deprecated('BaseConfig is deprecated. Use the `pydantic.ConfigDict` instead.', category=PydanticDeprecatedSince20)
_ConfigMetaclass
python
wandb__wandb
wandb/sdk/internal/file_stream.py
{ "start": 10455, "end": 25640 }
class ____: """Pushes chunks of files to our streaming endpoint. This class is used as a singleton. It has a thread that serializes access to the streaming endpoint and performs rate-limiting and batching. TODO: Differentiate between binary/text encoding. """ class Finish(NamedTuple): exitcode: int class Preempting(NamedTuple): pass class PushSuccess(NamedTuple): artifact_id: str save_name: str MAX_ITEMS_PER_PUSH = 10000 def __init__( self, api: "internal_api.Api", run_id: str, start_time: float, timeout: float = 0, settings: Optional[dict] = None, ) -> None: settings = settings or dict() # NOTE: exc_info is set in thread_except_body context and readable by calling threads self._exc_info: Optional[ Union[ Tuple[Type[BaseException], BaseException, TracebackType], Tuple[None, None, None], ] ] = None self._settings = settings self._api = api self._run_id = run_id self._start_time = start_time self._client = requests.Session() timeout = timeout or 0 if timeout > 0: self._client.post = functools.partial(self._client.post, timeout=timeout) # type: ignore[method-assign] self._client.auth = api.client.transport.session.auth self._client.headers.update(api.client.transport.headers or {}) self._client.cookies.update(api.client.transport.cookies or {}) # type: ignore[no-untyped-call] self._client.proxies.update(api.client.transport.session.proxies or {}) self._file_policies: Dict[str, DefaultFilePolicy] = {} self._dropped_chunks: int = 0 self._queue: queue.Queue = queue.Queue() self._thread = threading.Thread(target=self._thread_except_body) # It seems we need to make this a daemon thread to get sync.py's atexit handler to run, which # cleans this thread up. self._thread.name = "FileStreamThread" self._thread.daemon = True self._init_endpoint() def _init_endpoint(self) -> None: settings = self._api.settings() settings.update(self._settings) self._endpoint = "{base}/files/{entity}/{project}/{run}/file_stream".format( base=settings["base_url"], entity=settings["entity"], project=settings["project"], run=self._run_id, ) def start(self) -> None: self._init_endpoint() self._thread.start() def set_default_file_policy( self, filename: str, file_policy: "DefaultFilePolicy" ) -> None: """Set an upload policy for a file unless one has already been set.""" if filename not in self._file_policies: self._file_policies[filename] = file_policy def set_file_policy(self, filename: str, file_policy: "DefaultFilePolicy") -> None: self._file_policies[filename] = file_policy @property def heartbeat_seconds(self) -> Union[int, float]: # Defaults to 30 heartbeat_seconds: Union[int, float] = self._api.dynamic_settings[ "heartbeat_seconds" ] return heartbeat_seconds def rate_limit_seconds(self) -> Union[int, float]: run_time = time.time() - self._start_time if run_time < 60: return max(1.0, self.heartbeat_seconds / 15) elif run_time < 300: return max(2.5, self.heartbeat_seconds / 3) else: return max(5.0, self.heartbeat_seconds) def _read_queue(self) -> List: # called from the push thread (_thread_body), this does an initial read # that'll block for up to rate_limit_seconds. Then it tries to read # as much out of the queue as it can. We do this because the http post # to the server happens within _thread_body, and can take longer than # our rate limit. So next time we get a chance to read the queue we want # read all the stuff that queue'd up since last time. # # If we have more than MAX_ITEMS_PER_PUSH in the queue then the push thread # will get behind and data will buffer up in the queue. return util.read_many_from_queue( self._queue, self.MAX_ITEMS_PER_PUSH, self.rate_limit_seconds() ) def _thread_body(self) -> None: posted_data_time = time.time() posted_anything_time = time.time() ready_chunks = [] uploaded: Set[str] = set() finished: Optional[FileStreamApi.Finish] = None while finished is None: items = self._read_queue() for item in items: if isinstance(item, self.Finish): finished = item elif isinstance(item, self.Preempting): request_with_retry( self._client.post, self._endpoint, json={ "complete": False, "preempting": True, "dropped": self._dropped_chunks, "uploaded": list(uploaded), }, ) uploaded = set() elif isinstance(item, self.PushSuccess): uploaded.add(item.save_name) else: # item is Chunk ready_chunks.append(item) cur_time = time.time() if ready_chunks and ( finished or cur_time - posted_data_time > self.rate_limit_seconds() ): posted_data_time = cur_time posted_anything_time = cur_time success = self._send(ready_chunks, uploaded=uploaded) ready_chunks = [] if success: uploaded = set() # If there aren't ready chunks or uploaded files, we still want to # send regular heartbeats so the backend doesn't erroneously mark this # run as crashed. if cur_time - posted_anything_time > self.heartbeat_seconds: posted_anything_time = cur_time # If we encountered an error trying to publish the # list of uploaded files, don't reset the `uploaded` # list. Retry publishing the list on the next attempt. if not isinstance( request_with_retry( self._client.post, self._endpoint, json={ "complete": False, "failed": False, "dropped": self._dropped_chunks, "uploaded": list(uploaded), }, ), Exception, ): uploaded = set() # post the final close message. (item is self.Finish instance now) request_with_retry( self._client.post, self._endpoint, json={ "complete": True, "exitcode": int(finished.exitcode), "dropped": self._dropped_chunks, "uploaded": list(uploaded), }, ) def _thread_except_body(self) -> None: # TODO: Consolidate with internal_util.ExceptionThread try: self._thread_body() except Exception: exc_info = sys.exc_info() self._exc_info = exc_info logger.exception("generic exception in filestream thread") get_sentry().exception(exc_info) raise def _handle_response(self, response: Union[Exception, "requests.Response"]) -> None: """Log dropped chunks and updates dynamic settings.""" if isinstance(response, Exception): wandb.termerror( "Dropped streaming file chunk (see wandb/debug-internal.log)" ) logger.exception(f"dropped chunk {response}") self._dropped_chunks += 1 else: parsed: Optional[dict] = None try: parsed = response.json() except Exception: pass if isinstance(parsed, dict): limits = parsed.get("limits") if isinstance(limits, dict): self._api.dynamic_settings.update(limits) def _send(self, chunks: List[Chunk], uploaded: Optional[Set[str]] = None) -> bool: uploaded_list = list(uploaded or []) # create files dict. dict of <filename: chunks> pairs where chunks are a list of # [chunk_id, chunk_data] tuples (as lists since this will be json). files = {} # Groupby needs group keys to be consecutive, so sort first. chunks.sort(key=lambda c: c.filename) for filename, file_chunks in itertools.groupby(chunks, lambda c: c.filename): file_chunks_list = list(file_chunks) # groupby returns iterator # Specific file policies are set by internal/sender.py self.set_default_file_policy(filename, DefaultFilePolicy()) files[filename] = self._file_policies[filename].process_chunks( file_chunks_list ) if not files[filename]: del files[filename] for fs in file_stream_utils.split_files(files, max_bytes=util.MAX_LINE_BYTES): self._handle_response( request_with_retry( self._client.post, self._endpoint, json={"files": fs, "dropped": self._dropped_chunks}, retry_callback=self._api.retry_callback, ) ) if uploaded_list: if isinstance( request_with_retry( self._client.post, self._endpoint, json={ "complete": False, "failed": False, "dropped": self._dropped_chunks, "uploaded": uploaded_list, }, ), Exception, ): return False return True def stream_file(self, path: str) -> None: name = path.split("/")[-1] with open(path) as f: self._send([Chunk(name, line) for line in f]) def enqueue_preempting(self) -> None: self._queue.put(self.Preempting()) def push(self, filename: str, data: str) -> None: """Push a chunk of a file to the streaming endpoint. Args: filename: Name of file to append to. data: Text to append to the file. """ self._queue.put(Chunk(filename, data)) def push_success(self, artifact_id: str, save_name: str) -> None: """Notification that a file upload has been successfully completed. Args: artifact_id: ID of artifact save_name: saved name of the uploaded file """ self._queue.put(self.PushSuccess(artifact_id, save_name)) def finish(self, exitcode: int) -> None: """Clean up. Anything pushed after finish will be dropped. Args: exitcode: The exitcode of the watched process. """ logger.info("file stream finish called") self._queue.put(self.Finish(exitcode)) # TODO(jhr): join on a thread which exited with an exception is a noop, clean up this path self._thread.join() logger.info("file stream finish is done") if self._exc_info: logger.error("FileStream exception", exc_info=self._exc_info) # re-raising the original exception, will get re-caught in internal.py for the sender thread if self._exc_info[1] is not None: raise self._exc_info[1].with_traceback(self._exc_info[2]) MAX_SLEEP_SECONDS = 60 * 5 def request_with_retry( func: Callable, *args: Any, **kwargs: Any, ) -> Union["requests.Response", "requests.RequestException"]: """Perform a requests http call, retrying with exponential backoff. Args: func: An http-requesting function to call, like requests.post max_retries: Maximum retries before giving up. By default, we retry 30 times in ~2 hours before dropping the chunk *args: passed through to func **kwargs: passed through to func """ max_retries: int = kwargs.pop("max_retries", 30) retry_callback: Optional[Callable] = kwargs.pop("retry_callback", None) sleep = 2 retry_count = 0 while True: try: response: requests.Response = func(*args, **kwargs) response.raise_for_status() return response except ( requests.exceptions.ConnectionError, requests.exceptions.HTTPError, requests.exceptions.Timeout, ) as e: if isinstance(e, requests.exceptions.HTTPError): # Non-retriable HTTP errors. # # We retry 500s just to be cautious, and because the back end # returns them when there are infrastructure issues. If retrying # some request winds up being problematic, we'll change the # back end to indicate that it shouldn't be retried. if e.response is not None and e.response.status_code in { 400, 403, 404, 409, }: return e if retry_count == max_retries: return e retry_count += 1 delay = sleep + random.random() * 0.25 * sleep if isinstance(e, requests.exceptions.HTTPError) and ( e.response is not None and e.response.status_code == 429 ): err_str = ( f"Filestream rate limit exceeded, retrying in {delay:.1f} seconds. " ) if retry_callback: retry_callback(e.response.status_code, err_str) logger.info(err_str) else: logger.warning( "requests_with_retry encountered retryable exception: %s. func: %s, args: %s, kwargs: %s", e, func, args, kwargs, ) time.sleep(delay) sleep *= 2 if sleep > MAX_SLEEP_SECONDS: sleep = MAX_SLEEP_SECONDS except requests.exceptions.RequestException as e: error_message = "unknown error" try: error_message = response.json()["error"] # todo: clean this up except Exception: pass logger.exception(f"requests_with_retry error: {error_message}") return e
FileStreamApi
python
matplotlib__matplotlib
lib/matplotlib/backends/backend_gtk3.py
{ "start": 22384, "end": 22540 }
class ____(_FigureManagerGTK): _toolbar2_class = NavigationToolbar2GTK3 _toolmanager_toolbar_class = ToolbarGTK3 @_BackendGTK.export
FigureManagerGTK3
python
pypa__setuptools
setuptools/_distutils/tests/test_install_headers.py
{ "start": 214, "end": 936 }
class ____( support.TempdirManager, ): def test_simple_run(self): # we have two headers header_list = self.mkdtemp() header1 = os.path.join(header_list, 'header1') header2 = os.path.join(header_list, 'header2') self.write_file(header1) self.write_file(header2) headers = [header1, header2] pkg_dir, dist = self.create_dist(headers=headers) cmd = install_headers(dist) assert cmd.get_inputs() == headers # let's run the command cmd.install_dir = os.path.join(pkg_dir, 'inst') cmd.ensure_finalized() cmd.run() # let's check the results assert len(cmd.get_outputs()) == 2
TestInstallHeaders
python
numba__numba
numba/core/types/abstract.py
{ "start": 9724, "end": 9863 }
class ____(Sized): """ For types that have a constant size """ @abstractmethod def __len__(self): pass
ConstSized
python
python-excel__xlwt
xlwt/BIFFRecords.py
{ "start": 14716, "end": 15244 }
class ____(BiffRecord): """ This record specifies if the formulas in the workbook can use natural language formulas. This type of formula can refer to cells by its content or the content of the column or row header cell. Record USESELFS, BIFF8: Offset Size Contents 0 2 0 = Do not use natural language formulas 1 = Use natural language formulas """ _REC_ID = 0x0160 def __init__(self): self._rec_data = pack('<H', 0x01)
UseSelfsRecord
python
davidhalter__parso
parso/normalizer.py
{ "start": 297, "end": 3132 }
class ____(metaclass=_NormalizerMeta): _rule_type_instances: Dict[str, List[type]] = {} _rule_value_instances: Dict[str, List[type]] = {} def __init__(self, grammar, config): self.grammar = grammar self._config = config self.issues = [] self._rule_type_instances = self._instantiate_rules('rule_type_classes') self._rule_value_instances = self._instantiate_rules('rule_value_classes') def _instantiate_rules(self, attr): dct = {} for base in type(self).mro(): rules_map = getattr(base, attr, {}) for type_, rule_classes in rules_map.items(): new = [rule_cls(self) for rule_cls in rule_classes] dct.setdefault(type_, []).extend(new) return dct def walk(self, node): self.initialize(node) value = self.visit(node) self.finalize() return value def visit(self, node): try: children = node.children except AttributeError: return self.visit_leaf(node) else: with self.visit_node(node): return ''.join(self.visit(child) for child in children) @contextmanager def visit_node(self, node): self._check_type_rules(node) yield def _check_type_rules(self, node): for rule in self._rule_type_instances.get(node.type, []): rule.feed_node(node) def visit_leaf(self, leaf): self._check_type_rules(leaf) for rule in self._rule_value_instances.get(leaf.value, []): rule.feed_node(leaf) return leaf.prefix + leaf.value def initialize(self, node): pass def finalize(self): pass def add_issue(self, node, code, message): issue = Issue(node, code, message) if issue not in self.issues: self.issues.append(issue) return True @classmethod def register_rule(cls, *, value=None, values=(), type=None, types=()): """ Use it as a class decorator:: normalizer = Normalizer('grammar', 'config') @normalizer.register_rule(value='foo') class MyRule(Rule): error_code = 42 """ values = list(values) types = list(types) if value is not None: values.append(value) if type is not None: types.append(type) if not values and not types: raise ValueError("You must register at least something.") def decorator(rule_cls): for v in values: cls.rule_value_classes.setdefault(v, []).append(rule_cls) for t in types: cls.rule_type_classes.setdefault(t, []).append(rule_cls) return rule_cls return decorator
Normalizer
python
joke2k__faker
tests/providers/test_person.py
{ "start": 56690, "end": 57205 }
class ____(unittest.TestCase): def setUp(self): self.fake = Faker("sv_SE") Faker.seed(0) def test_gender_first_names(self): """simple test to verify that we are pulling gender specific names""" name = self.fake.first_name_female() assert name in SvSEProvider.first_names_female name = self.fake.first_name_male() assert name in SvSEProvider.first_names_male name = self.fake.first_name() assert name in SvSEProvider.first_names
TestSvSE
python
joke2k__faker
faker/providers/company/zh_CN/__init__.py
{ "start": 45, "end": 1602 }
class ____(CompanyProvider): formats = ["{{company_prefix}}{{company_suffix}}"] company_prefixes = [ "超艺", "和泰", "九方", "鑫博腾飞", "戴硕电子", "济南亿次元", "海创", "创联世纪", "凌云", "泰麒麟", "彩虹", "兰金电子", "晖来计算机", "天益", "恒聪百汇", "菊风公司", "惠派国际公司", "创汇", "思优", "时空盒数字", "易动力", "飞海科技", "华泰通安", "盟新", "商软冠联", "图龙信息", "易动力", "华远软件", "创亿", "时刻", "开发区世创", "明腾", "良诺", "天开", "毕博诚", "快讯", "凌颖信息", "黄石金承", "恩悌", "雨林木风计算机", "双敏电子", "维旺明", "网新恒天", "数字100", "飞利信", "立信电子", "联通时科", "中建创业", "新格林耐特", "新宇龙信息", "浙大万朋", "MBP软件", "昂歌信息", "万迅电脑", "方正科技", "联软", "七喜", "南康", "银嘉", "巨奥", "佳禾", "国讯", "信诚致远", "浦华众城", "迪摩", "太极", "群英", "合联电子", "同兴万点", "襄樊地球村", "精芯", "艾提科信", "昊嘉", "鸿睿思博", "四通", "富罳", "商软冠联", "诺依曼软件", "东方峻景", "华成育卓", "趋势", "维涛", "通际名联", ] company_suffixes = [n + "有限公司" for n in ["科技", "网络", "信息", "传媒"]] def company_prefix(self) -> str: return self.random_element(self.company_prefixes)
Provider
python
django__django
tests/forms_tests/widget_tests/test_textarea.py
{ "start": 129, "end": 2205 }
class ____(WidgetTest): widget = Textarea() def test_render(self): self.check_html( self.widget, "msg", "value", html=('<textarea rows="10" cols="40" name="msg">value</textarea>'), ) def test_render_required(self): widget = Textarea() widget.is_required = True self.check_html( widget, "msg", "value", html='<textarea rows="10" cols="40" name="msg">value</textarea>', ) def test_render_empty(self): self.check_html( self.widget, "msg", "", html='<textarea rows="10" cols="40" name="msg"></textarea>', ) def test_render_none(self): self.check_html( self.widget, "msg", None, html='<textarea rows="10" cols="40" name="msg"></textarea>', ) def test_escaping(self): self.check_html( self.widget, "msg", 'some "quoted" & ampersanded value', html=( '<textarea rows="10" cols="40" name="msg">' "some &quot;quoted&quot; &amp; ampersanded value</textarea>" ), ) def test_mark_safe(self): self.check_html( self.widget, "msg", mark_safe("pre &quot;quoted&quot; value"), html=( '<textarea rows="10" cols="40" name="msg">pre &quot;quoted&quot; value' "</textarea>" ), ) def test_fieldset(self): class TestForm(Form): template_name = "forms_tests/use_fieldset.html" field = CharField(widget=self.widget) form = TestForm() self.assertIs(self.widget.use_fieldset, False) self.assertHTMLEqual( '<div><label for="id_field">Field:</label>' '<textarea cols="40" id="id_field" name="field" ' 'required rows="10"></textarea></div>', form.render(), )
TextareaTest
python
modin-project__modin
asv_bench/benchmarks/benchmarks.py
{ "start": 16816, "end": 17850 }
class ____: param_names = ["value_type", "shape", "limit"] params = [ ["scalar", "dict", "Series"], get_benchmark_shapes("TimeFillnaSeries"), [None, 0.8], ] def setup(self, value_type, shape, limit): self.series = gen_nan_data(*shape) if value_type == "scalar": self.value = 18.19 elif value_type == "dict": self.value = {k: k * 1.23 for k in range(shape[0])} elif value_type == "Series": self.value = IMPL.Series( [k * 1.23 for k in range(shape[0])], index=IMPL.RangeIndex(shape[0]) ) else: assert False limit = int(limit * shape[0]) if limit else None self.kw = {"value": self.value, "limit": limit} def time_fillna(self, value_type, shape, limit): execute(self.series.fillna(**self.kw)) def time_fillna_inplace(self, value_type, shape, limit): self.series.fillna(inplace=True, **self.kw) execute(self.series)
TimeFillnaSeries
python
pypa__warehouse
tests/unit/admin/views/test_users.py
{ "start": 59686, "end": 60631 }
class ____: def test_user_email_domain_check(self, db_request): user = UserFactory.create(with_verified_primary_email=True) db_request.POST["email_address"] = user.primary_email.email db_request.route_path = pretend.call_recorder(lambda *a, **kw: "/foobar") db_request.session = pretend.stub( flash=pretend.call_recorder(lambda *a, **kw: None) ) result = views.user_email_domain_check(user, db_request) assert isinstance(result, HTTPSeeOther) assert result.headers["Location"] == "/foobar" assert db_request.session.flash.calls == [ pretend.call( f"Domain status check for '{user.primary_email.domain}' completed", queue="success", ) ] assert user.primary_email.domain_last_checked is not None assert user.primary_email.domain_last_status == ["active"]
TestUserEmailDomainCheck
python
ray-project__ray
python/ray/data/_internal/execution/interfaces/task_context.py
{ "start": 323, "end": 2782 }
class ____: """This describes the information of a task running block transform.""" # The index of task. Each task has a unique task index within the same # operator. task_idx: int # Name of the operator that this task belongs to. op_name: str # The dictionary of sub progress bar to update. The key is name of sub progress # bar. Note this is only used on driver side. # TODO(chengsu): clean it up from TaskContext with new optimizer framework. sub_progress_bar_dict: Optional[Dict[str, ProgressBar]] = None # NOTE(hchen): `upstream_map_transformer` and `upstream_map_ray_remote_args` # are only used for `RandomShuffle`. DO NOT use them for other operators. # Ideally, they should be handled by the optimizer, and should be transparent # to the specific operators. # But for `RandomShuffle`, the AllToAllOperator doesn't do the shuffle itself. # It uses `ExchangeTaskScheduler` to launch new tasks to do the shuffle. # That's why we need to pass them to `ExchangeTaskScheduler`. # TODO(hchen): Use a physical operator to do the shuffle directly. # The underlying function called in a MapOperator; this is used when fusing # an AllToAllOperator with an upstream MapOperator. upstream_map_transformer: Optional["MapTransformer"] = None # The Ray remote arguments of the fused upstream MapOperator. # This should be set if upstream_map_transformer is set. upstream_map_ray_remote_args: Optional[Dict[str, Any]] = None # Override of the target max-block-size for the task target_max_block_size_override: Optional[int] = None # Additional keyword arguments passed to the task. kwargs: Dict[str, Any] = field(default_factory=dict) @classmethod def get_current(cls) -> Optional["TaskContext"]: """Get the TaskContext for the current thread. Returns None if no TaskContext has been set. """ return getattr(_thread_local, "task_context", None) @classmethod def set_current(cls, context): """Set the TaskContext for the current thread. Args: context: The TaskContext instance to set for this thread """ _thread_local.task_context = context @classmethod def reset_current(cls): """Clear the current thread's TaskContext.""" if hasattr(_thread_local, "task_context"): delattr(_thread_local, "task_context")
TaskContext
python
openai__gym
tests/wrappers/test_filter_observation.py
{ "start": 168, "end": 1533 }
class ____(gym.Env): def __init__( self, render_mode=None, observation_keys: Tuple[str, ...] = ("state",) ): self.observation_space = spaces.Dict( { name: spaces.Box(shape=(2,), low=-1, high=1, dtype=np.float32) for name in observation_keys } ) self.action_space = spaces.Box(shape=(1,), low=-1, high=1, dtype=np.float32) self.render_mode = render_mode def render(self, mode="human"): image_shape = (32, 32, 3) return np.zeros(image_shape, dtype=np.uint8) def reset(self, *, seed: Optional[int] = None, options: Optional[dict] = None): super().reset(seed=seed) observation = self.observation_space.sample() return observation, {} def step(self, action): del action observation = self.observation_space.sample() reward, terminal, info = 0.0, False, {} return observation, reward, terminal, info FILTER_OBSERVATION_TEST_CASES = ( (("key1", "key2"), ("key1",)), (("key1", "key2"), ("key1", "key2")), (("key1",), None), (("key1",), ("key1",)), ) ERROR_TEST_CASES = ( ("key", ValueError, "All the filter_keys must be included..*"), (False, TypeError, "'bool' object is not iterable"), (1, TypeError, "'int' object is not iterable"), )
FakeEnvironment
python
google__jax
jax/_src/test_util.py
{ "start": 20620, "end": 25417 }
class ____: """A mixin with methods allowing to skip arch specific tests.""" def skip_unless_sm90a(self): if not is_cuda_compute_capability_equal("9.0"): self.skipTest("Only works on GPU with capability sm90a") # pytype: disable=attribute-error def skip_unless_sm100a(self): if not is_cuda_compute_capability_equal("10.0"): self.skipTest("Only works on GPU with capability sm100a") # pytype: disable=attribute-error def _get_device_tags(): """returns a set of tags defined for the device under test""" if is_device_rocm(): return {device_under_test(), "rocm"} elif is_device_cuda(): return {device_under_test(), "cuda"} elif device_under_test() == "METAL": return {device_under_test(), "gpu"} else: return {device_under_test()} def test_device_matches(device_types: Iterable[str]) -> bool: assert not isinstance( device_types, str ), 'device_types should be a list of strings' tags = _get_device_tags() for device_type in device_types: assert isinstance(device_type, str), device_type if device_type in tags: return True return False test_device_matches.__test__ = False # This isn't a test case, pytest. def _device_filter(predicate): def skip(test_method): @functools.wraps(test_method) def test_method_wrapper(self, *args, **kwargs): device_tags = _get_device_tags() if not predicate(): test_name = getattr(test_method, '__name__', '[unknown test]') raise unittest.SkipTest( f"{test_name} not supported on device with tags {device_tags}.") return test_method(self, *args, **kwargs) return test_method_wrapper return skip def skip_on_devices(*disabled_devices): """A decorator for test methods to skip the test on certain devices.""" return _device_filter(lambda: not test_device_matches(disabled_devices)) def run_on_devices(*enabled_devices): """A decorator for test methods to run the test only on certain devices.""" return _device_filter(lambda: test_device_matches(enabled_devices)) def device_supports_buffer_donation(): """A decorator for test methods to run the test only on devices that support buffer donation.""" return _device_filter( lambda: test_device_matches(mlir._platforms_with_donation) ) def request_cpu_devices(nr_devices: int): """Requests at least `nr_devices` CPU devices. request_cpu_devices should be called at the top-level of a test module before main() runs. It is not guaranteed that the number of CPU devices will be exactly `nr_devices`: it may be more or less, depending on how exactly the test is invoked. Test cases that require a specific number of devices should skip themselves if that number is not met. """ if xla_bridge.num_cpu_devices.value < nr_devices: xla_bridge.get_backend.cache_clear() # Don't raise an error for `request_cpu_devices` because we initialize the # backend in OSS during collecting tests in pytest via `device_under_test`. try: config.update("jax_num_cpu_devices", nr_devices) except RuntimeError: pass def skip_on_flag(flag_name, skip_value): """A decorator for test methods to skip the test when flags are set.""" def skip(test_method): # pylint: disable=missing-docstring @functools.wraps(test_method) def test_method_wrapper(self, *args, **kwargs): flag_value = config._read(flag_name) if flag_value == skip_value: test_name = getattr(test_method, '__name__', '[unknown test]') raise unittest.SkipTest( f"{test_name} not supported when FLAGS.{flag_name} is {flag_value}") return test_method(self, *args, **kwargs) return test_method_wrapper return skip def pytest_mark_if_available(marker: str): """A decorator for test classes or methods to pytest.mark if installed.""" def wrap(func_or_class): try: import pytest # pytype: disable=import-error except ImportError: return func_or_class return getattr(pytest.mark, marker)(func_or_class) return wrap def is_running_under_pytest(): return "pytest" in sys.modules def skip_under_pytest(reason: str): """A decorator for test methods to skip the test when run under pytest.""" reason = "Running under pytest: " + reason def skip(test_method): return unittest.skipIf(is_running_under_pytest(), reason)(test_method) return skip def format_test_name_suffix(opname, shapes, dtypes): arg_descriptions = (format_shape_dtype_string(shape, dtype) for shape, dtype in zip(shapes, dtypes)) return '{}_{}'.format(opname.capitalize(), '_'.join(arg_descriptions)) # We use special symbols, represented as singleton objects, to distinguish # between NumPy scalars, Python scalars, and 0-D arrays.
CudaArchSpecificTest
python
mwaskom__seaborn
seaborn/_marks/area.py
{ "start": 356, "end": 2527 }
class ____: def _plot(self, split_gen, scales, orient): patches = defaultdict(list) for keys, data, ax in split_gen(): kws = {} data = self._standardize_coordinate_parameters(data, orient) resolved = resolve_properties(self, keys, scales) verts = self._get_verts(data, orient) ax.update_datalim(verts) # TODO should really move this logic into resolve_color fc = resolve_color(self, keys, "", scales) if not resolved["fill"]: fc = mpl.colors.to_rgba(fc, 0) kws["facecolor"] = fc kws["edgecolor"] = resolve_color(self, keys, "edge", scales) kws["linewidth"] = resolved["edgewidth"] kws["linestyle"] = resolved["edgestyle"] patches[ax].append(mpl.patches.Polygon(verts, **kws)) for ax, ax_patches in patches.items(): for patch in ax_patches: self._postprocess_artist(patch, ax, orient) ax.add_patch(patch) def _standardize_coordinate_parameters(self, data, orient): return data def _postprocess_artist(self, artist, ax, orient): pass def _get_verts(self, data, orient): dv = {"x": "y", "y": "x"}[orient] data = data.sort_values(orient, kind="mergesort") verts = np.concatenate([ data[[orient, f"{dv}min"]].to_numpy(), data[[orient, f"{dv}max"]].to_numpy()[::-1], ]) if orient == "y": verts = verts[:, ::-1] return verts def _legend_artist(self, variables, value, scales): keys = {v: value for v in variables} resolved = resolve_properties(self, keys, scales) fc = resolve_color(self, keys, "", scales) if not resolved["fill"]: fc = mpl.colors.to_rgba(fc, 0) return mpl.patches.Patch( facecolor=fc, edgecolor=resolve_color(self, keys, "edge", scales), linewidth=resolved["edgewidth"], linestyle=resolved["edgestyle"], **self.artist_kws, ) @document_properties @dataclass
AreaBase
python
pytorch__pytorch
test/distributed/checkpoint/test_planner.py
{ "start": 2890, "end": 20617 }
class ____(TestCase): @with_fake_comms(rank=1, world_size=4) def test_local_plan(self): tensor = torch.rand(10) val = [1, 2, 3] st = create_sharded_tensor(rank=1, world_size=4, shards_per_rank=1) state_dict = {"tensor": tensor, "value": val, "st": st} plan = create_default_local_save_plan(state_dict, False) self.assertEqual(3, len(plan.items)) wi = plan.items[0] self.assertEqual(wi.index, MetadataIndex("tensor", [0])) self.assertEqual(wi.type, WriteItemType.TENSOR) self.assertEqual(wi.tensor_data.size, tensor.size()) self.assertEqual( wi.tensor_data.properties, TensorProperties.create_from_tensor(torch.zeros(1)), ) self.assertEqual(wi.tensor_data.chunk.offsets, torch.Size([0])) self.assertEqual(wi.tensor_data.chunk.sizes, torch.Size([10])) st_wi = plan.items[2] self.assertEqual(st_wi.index, MetadataIndex("st", [8])) self.assertEqual(st_wi.type, WriteItemType.SHARD) self.assertEqual(st_wi.tensor_data.size, st.size()) self.assertEqual( st_wi.tensor_data.properties, TensorProperties.create_from_tensor(torch.zeros(1)), ) self.assertEqual(st_wi.tensor_data.chunk.offsets, torch.Size([8])) self.assertEqual(st_wi.tensor_data.chunk.sizes, torch.Size([8])) # Coordinator rank, should include replicated items as well plan = create_default_local_save_plan(state_dict, True) self.assertEqual(3, len(plan.items)) tensor_wi = next(wi for wi in plan.items if wi.type == WriteItemType.TENSOR) self.assertEqual(tensor_wi.index, MetadataIndex("tensor", [0])) self.assertEqual(tensor_wi.tensor_data.size, tensor.size()) self.assertEqual( tensor_wi.tensor_data.properties, TensorProperties.create_from_tensor(tensor), ) self.assertEqual(tensor_wi.tensor_data.chunk.offsets, torch.Size([0])) self.assertEqual(tensor_wi.tensor_data.chunk.sizes, torch.Size([10])) bytes_wi = next(wi for wi in plan.items if wi.type == WriteItemType.BYTE_IO) self.assertEqual(bytes_wi.index, MetadataIndex("value")) self.assertIsNone(bytes_wi.tensor_data) @with_fake_comms(rank=1, world_size=4) def test_local_plan_with_caching(self): tensor = torch.rand(10) val = [1, 2, 3] st = create_sharded_tensor(rank=1, world_size=4, shards_per_rank=1) state_dict = {"tensor": tensor, "value": val, "st": st} planner = DefaultSavePlanner(enable_plan_caching=True) planner.set_up_planner(state_dict, is_coordinator=False) # First iteration, should create a new plan first_plan = planner.create_local_plan() # Validate that the plan has been cached cached_plan = SavePlanner._cached_save_plan[planner._cached_plans_key] self.assertEqual(first_plan, cached_plan) # second iteration, should create an empty unusable plan second_plan = planner.create_local_plan() self.assertFalse(second_plan.usable) self.assertEqual(0, len(second_plan.items)) self.assertIsNone(second_plan.planner_data) self.assertIsNone(second_plan.storage_data) def test_global_plan(self): def create_data(rank): with with_dist(rank=rank, world_size=4): tensor = torch.rand(10) val = [1, 2, 3] st = create_sharded_tensor(rank=rank, world_size=4, shards_per_rank=1) state_dict = {"tensor": tensor, "value": val, "st": st} return create_default_local_save_plan(state_dict, rank == 0) all_plans = [create_data(0), create_data(1), create_data(2), create_data(3)] all_plans = dedup_save_plans(all_plans) final_plans, metadata = create_default_global_save_plan(all_plans=all_plans) # The default global plan updates all indexes to include hints for new_plan, old_plan in zip(final_plans, all_plans): for new_item, old_item in zip(new_plan.items, old_plan.items): self.assertEqual(new_item.index, old_item.index) self.assertEqual(new_item.type, old_item.type) self.assertEqual(new_item.tensor_data, old_item.tensor_data) self.assertIn(new_item.index.fqn, metadata.state_dict_metadata) item_md = metadata.state_dict_metadata[new_item.index.fqn] if new_item.type == WriteItemType.BYTE_IO: self.assertTrue(isinstance(item_md, BytesStorageMetadata)) else: self.assertTrue(isinstance(item_md, TensorStorageMetadata)) self.assertEqual(item_md.size, old_item.tensor_data.size) self.assertEqual( item_md.properties, old_item.tensor_data.properties ) self.assertIsNotNone(new_item.index.index) # Make sure the hint is correct self.assertEqual( item_md.chunks[new_item.index.index], old_item.tensor_data.chunk ) def test_dedup_plans(self): def create_data(rank): with with_dist(rank=rank, world_size=4): tensor = torch.rand(10) val = [1, 2, 3] st = create_sharded_tensor(rank=rank, world_size=4, shards_per_rank=1) state_dict = {"tensor": tensor, "value": val, "st": st} return create_default_local_save_plan(state_dict, rank == 0) all_plans = [create_data(0), create_data(1), create_data(2), create_data(3)] deduped_plans = dedup_save_plans(all_plans) # Number of plans should remain unchanged self.assertEqual(len(all_plans), len(deduped_plans)) # Number of items in the deduped plans should be less than the original plans for new_plan, old_plan in zip(deduped_plans, all_plans): self.assertFalse(_compare_save_plans(new_plan, old_plan)) self.assertTrue(len(new_plan.items) < len(old_plan.items)) def test_global_plan_with_caching(self): def create_data(rank): with with_dist(rank=rank, world_size=4): planner = DefaultSavePlanner(enable_plan_caching=True) tensor = torch.rand(10) val = [1, 2, 3] st = create_sharded_tensor(rank=rank, world_size=4, shards_per_rank=1) state_dict = {"tensor": tensor, "value": val, "st": st} planner.set_up_planner(state_dict, is_coordinator=(rank == 0)) return planner.create_local_plan() all_plans = [create_data(0), create_data(1), create_data(2), create_data(3)] planner = DefaultSavePlanner(enable_plan_caching=True) # First iteration, should create a new plan first_global_plan, first_metadata = planner.create_global_plan(all_plans) # Validate that the plan has been cached cached_global_plan = SavePlanner._cached_global_plan[planner._cached_plans_key] self.assertEqual(cached_global_plan, first_global_plan) # Validate that all_plans are cached cached_all_plans = SavePlanner._cached_all_plans[planner._cached_plans_key] self.assertEqual(cached_all_plans, all_plans) # Second iteration, should return empty plans # Recreate the plans as the previous ones are deduped. all_plans = [create_data(0), create_data(1), create_data(2), create_data(3)] second_global_plan, second_metadata = planner.create_global_plan(all_plans) # All the plans should be empty and usable for plan in second_global_plan: self.assertFalse(plan.usable) self.assertEqual(0, len(plan.items)) self.assertIsNone(plan.planner_data) self.assertIsNone(plan.storage_data) self.assertEqual(first_metadata, second_metadata) self.assertEqual( second_metadata, planner._cached_metadata[planner._cached_plans_key] ) # Validate that all_plans are cached and remain unchanged. cached_all_plans = SavePlanner._cached_all_plans[planner._cached_plans_key] self.assertEqual(cached_all_plans, all_plans) # Third iteration with changed plans def create_data_v2(rank): with with_dist(rank=rank, world_size=4): planner = DefaultSavePlanner(enable_plan_caching=True) tensor = torch.rand(20) val = [1, 2, 3] st = create_sharded_tensor(rank=rank, world_size=4, shards_per_rank=1) state_dict = {"tensor": tensor, "value": val, "st": st} planner.set_up_planner(state_dict, is_coordinator=(rank == 0)) return planner.create_local_plan() all_plans = [ create_data_v2(0), create_data_v2(1), create_data_v2(2), create_data_v2(3), ] third_global_plan, third_metadata = planner.create_global_plan(all_plans) # Only the rank 0 plan should be non-empty. The rest should be empty tensor_plan = third_global_plan[0] self.assertNotEqual(0, len(tensor_plan.items)) self.assertTrue(tensor_plan.usable) # Validate that all_plans are updated and cached cached_all_plans = SavePlanner._cached_all_plans[planner._cached_plans_key] self.assertEqual(cached_all_plans, all_plans) for plan in third_global_plan[1:]: self.assertFalse(plan.usable) self.assertEqual(0, len(plan.items)) self.assertIsNone(plan.planner_data) self.assertIsNone(plan.storage_data) # Global metadata should be different as one plan has changed self.assertNotEqual(second_metadata, third_metadata) # Validate that the metadata is cached self.assertEqual( third_metadata, planner._cached_metadata[planner._cached_plans_key] ) # Validate that the new plan has been cached cached_global_plan = SavePlanner._cached_global_plan[planner._cached_plans_key][ 0 ] self.assertEqual(cached_global_plan, tensor_plan) def test_finish_plan_with_caching(self): planner = DefaultSavePlanner(enable_plan_caching=True) tensor = torch.rand(10) val = [1, 2, 3] state_dict = {"tensor": tensor, "value": val} planner.set_up_planner(state_dict, is_coordinator=True) plan = planner.create_local_plan() # First iteration, should create a new plan first_finished_plan = planner.finish_plan(plan) # Validate that the plan has been cached cached_finished_plan = SavePlanner._cached_final_save_plan[ planner._cached_plans_key ] self.assertEqual(first_finished_plan, cached_finished_plan) # second iteration, should return the cached plan second_finished_plan = planner.finish_plan(SavePlan([], usable=False)) self.assertEqual(second_finished_plan, first_finished_plan) def test_local_load_plan(self): def create_state_dict(rank): with with_dist(rank=rank, world_size=4): tensor = torch.rand(10) val = [1, 2, 3] st = create_sharded_tensor(rank=rank, world_size=4, shards_per_rank=1) return {"tensor": tensor, "value": val, "st": st} state_dict = create_state_dict(1) metadata = _create_default_local_metadata(state_dict) load_plan = create_default_local_load_plan(state_dict, metadata) # This will create 3 entries self.assertEqual(3, len(load_plan.items)) st_item = next(ri for ri in load_plan.items if ri.dest_index.fqn == "st") tensor_item = next( ri for ri in load_plan.items if ri.dest_index.fqn == "tensor" ) bytes_item = next(ri for ri in load_plan.items if ri.dest_index.fqn == "value") self.assertEqual(st_item.type, LoadItemType.TENSOR) # This is an exact copy self.assertEqual(st_item.dest_index, MetadataIndex("st", [8])) self.assertEqual(st_item.dest_offsets, torch.Size([0])) self.assertEqual(st_item.storage_index, MetadataIndex("st", [8])) self.assertEqual(st_item.storage_offsets, torch.Size([0])) self.assertEqual(st_item.lengths, torch.Size([8])) self.assertEqual(tensor_item.type, LoadItemType.TENSOR) self.assertEqual(tensor_item.dest_index, MetadataIndex("tensor", [0])) self.assertEqual(tensor_item.dest_offsets, torch.Size([0])) self.assertEqual(tensor_item.storage_index, MetadataIndex("tensor", [0])) self.assertEqual(tensor_item.storage_offsets, torch.Size([0])) self.assertEqual(tensor_item.lengths, torch.Size([10])) self.assertEqual(bytes_item.type, LoadItemType.BYTE_IO) self.assertEqual(bytes_item.dest_index, MetadataIndex("value")) def test_load_with_resharding(self): def create_state_dict(rank, world_size): with with_dist(rank=rank, world_size=world_size): return { "st": create_sharded_tensor( rank=rank, world_size=world_size, shards_per_rank=1, shard_size=128 // world_size, ) } # Rank 1 has a 16 bytes shard from [16, 32[ world8_state_dict = create_state_dict(rank=1, world_size=8) world8_metadata = _create_default_local_metadata(world8_state_dict) # Rank 1 has a 32 bytes shard from [32, 64[ world4_state_dict = create_state_dict(rank=1, world_size=4) world4_metadata = _create_default_local_metadata(world4_state_dict) # First scenario, going from world=8 to world=4, need to load 2 shards # Each 4-world shard has 32 elements, so it needs to load 2 shards load_plan = create_default_local_load_plan(world4_state_dict, world8_metadata) self.assertEqual(2, len(load_plan.items)) low_ri = next( ri for ri in load_plan.items if ri.dest_offsets == torch.Size([0]) ) high_ri = next( ri for ri in load_plan.items if ri.dest_offsets == torch.Size([16]) ) self.assertEqual(low_ri.storage_index, MetadataIndex("st", [32])) self.assertEqual(low_ri.storage_offsets, torch.Size([0])) self.assertEqual(low_ri.dest_index, MetadataIndex("st", [32])) self.assertEqual(low_ri.dest_offsets, torch.Size([0])) self.assertEqual(low_ri.lengths, torch.Size([16])) self.assertEqual(high_ri.storage_index, MetadataIndex("st", [48])) self.assertEqual(high_ri.storage_offsets, torch.Size([0])) self.assertEqual(high_ri.dest_index, MetadataIndex("st", [32])) self.assertEqual(high_ri.dest_offsets, torch.Size([16])) self.assertEqual(high_ri.lengths, torch.Size([16])) # Second scenario, going from world=4 to world=8, need to load half of 1 shard # rank1 on 8-world needs to load the upper half of the rank0 4-world shard load_plan = create_default_local_load_plan(world8_state_dict, world4_metadata) self.assertEqual(1, len(load_plan.items)) ri = load_plan.items[0] self.assertEqual(ri.storage_index, MetadataIndex("st", [0])) self.assertEqual(ri.storage_offsets, torch.Size([16])) self.assertEqual(ri.dest_index, MetadataIndex("st", [16])) self.assertEqual(ri.dest_offsets, torch.Size([0])) self.assertEqual(ri.lengths, torch.Size([16])) def test_load_with_world_size_diff_by_one(self): def create_state_dict(rank, world_size): with with_dist(rank=rank, world_size=world_size): return { "st": create_sharded_tensor( rank=rank, world_size=world_size, shards_per_rank=1, shard_size=120 // world_size, ) } # rank 1 has a 30 bytes shard from [30, 60[ world4_state_dict = create_state_dict(rank=1, world_size=4) world4_metadata = _create_default_local_metadata(world4_state_dict) # rank 1 has a 40 bytes shard from [40, 80[ world3_state_dict = create_state_dict(rank=1, world_size=3) load_plan = create_default_local_load_plan(world3_state_dict, world4_metadata) self.assertEqual(2, len(load_plan.items)) # this is [30, 60] to load [40, 60] low_ri = next( ri for ri in load_plan.items if ri.dest_offsets == torch.Size([0]) ) # this is [60, 90] to load [60, 80] high_ri = next( ri for ri in load_plan.items if ri.dest_offsets == torch.Size([20]) ) self.assertEqual(low_ri.storage_index, MetadataIndex("st", [30])) self.assertEqual(low_ri.storage_offsets, torch.Size([10])) self.assertEqual(low_ri.dest_index, MetadataIndex("st", [40])) self.assertEqual(low_ri.dest_offsets, torch.Size([0])) self.assertEqual(low_ri.lengths, torch.Size([20])) self.assertEqual(high_ri.storage_index, MetadataIndex("st", [60])) self.assertEqual(high_ri.storage_offsets, torch.Size([0])) self.assertEqual(high_ri.dest_index, MetadataIndex("st", [40])) self.assertEqual(high_ri.dest_offsets, torch.Size([20])) self.assertEqual(high_ri.lengths, torch.Size([20]))
TestSavePlan
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/context_creation_job.py
{ "start": 3508, "end": 5727 }
class ____(NamedTuple): job: IJob resolved_run_config: ResolvedRunConfig dagster_run: DagsterRun executor_def: ExecutorDefinition instance: DagsterInstance resource_keys_to_init: AbstractSet[str] execution_plan: ExecutionPlan @property def job_def(self) -> JobDefinition: return self.job.get_definition() @property def repository_def(self) -> Optional[RepositoryDefinition]: return self.job.get_repository_definition() def create_context_creation_data( job: IJob, execution_plan: ExecutionPlan, run_config: Mapping[str, object], dagster_run: DagsterRun, instance: DagsterInstance, ) -> "ContextCreationData": job_def = job.get_definition() resolved_run_config = ResolvedRunConfig.build(job_def, run_config) executor_def = job_def.executor_def return ContextCreationData( job=job, resolved_run_config=resolved_run_config, dagster_run=dagster_run, executor_def=executor_def, instance=instance, resource_keys_to_init=get_required_resource_keys_to_init(execution_plan, job_def), execution_plan=execution_plan, ) def create_plan_data( context_creation_data: "ContextCreationData", raise_on_error: bool, retry_mode: RetryMode, step_dependency_config: StepDependencyConfig, ) -> PlanData: return PlanData( job=context_creation_data.job, dagster_run=context_creation_data.dagster_run, instance=context_creation_data.instance, execution_plan=context_creation_data.execution_plan, raise_on_error=raise_on_error, retry_mode=retry_mode, step_dependency_config=step_dependency_config, ) def create_execution_data( context_creation_data: "ContextCreationData", scoped_resources_builder: ScopedResourcesBuilder, ) -> ExecutionData: return ExecutionData( scoped_resources_builder=scoped_resources_builder, resolved_run_config=context_creation_data.resolved_run_config, job_def=context_creation_data.job_def, repository_def=context_creation_data.repository_def, ) TContextType = TypeVar("TContextType", bound=IPlanContext)
ContextCreationData
python
plotly__plotly.py
plotly/graph_objs/scatterpolar/marker/_gradient.py
{ "start": 233, "end": 4917 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scatterpolar.marker" _path_str = "scatterpolar.marker.gradient" _valid_props = {"color", "colorsrc", "type", "typesrc"} @property def color(self): """ Sets the final color of the gradient fill: the center color for radial, the right for horizontal, or the bottom for vertical. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list - A list or array of any of the above Returns ------- str|numpy.ndarray """ return self["color"] @color.setter def color(self, val): self["color"] = val @property def colorsrc(self): """ Sets the source reference on Chart Studio Cloud for `color`. The 'colorsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["colorsrc"] @colorsrc.setter def colorsrc(self, val): self["colorsrc"] = val @property def type(self): """ Sets the type of gradient used to fill the markers The 'type' property is an enumeration that may be specified as: - One of the following enumeration values: ['radial', 'horizontal', 'vertical', 'none'] - A tuple, list, or one-dimensional numpy array of the above Returns ------- Any|numpy.ndarray """ return self["type"] @type.setter def type(self, val): self["type"] = val @property def typesrc(self): """ Sets the source reference on Chart Studio Cloud for `type`. The 'typesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["typesrc"] @typesrc.setter def typesrc(self, val): self["typesrc"] = val @property def _prop_descriptions(self): return """\ color Sets the final color of the gradient fill: the center color for radial, the right for horizontal, or the bottom for vertical. colorsrc Sets the source reference on Chart Studio Cloud for `color`. type Sets the type of gradient used to fill the markers typesrc Sets the source reference on Chart Studio Cloud for `type`. """ def __init__( self, arg=None, color=None, colorsrc=None, type=None, typesrc=None, **kwargs ): """ Construct a new Gradient object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scatterpolar.marker.Gradient` color Sets the final color of the gradient fill: the center color for radial, the right for horizontal, or the bottom for vertical. colorsrc Sets the source reference on Chart Studio Cloud for `color`. type Sets the type of gradient used to fill the markers typesrc Sets the source reference on Chart Studio Cloud for `type`. Returns ------- Gradient """ super().__init__("gradient") 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.scatterpolar.marker.Gradient constructor must be a dict or an instance of :class:`plotly.graph_objs.scatterpolar.marker.Gradient`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("color", arg, color) self._set_property("colorsrc", arg, colorsrc) self._set_property("type", arg, type) self._set_property("typesrc", arg, typesrc) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Gradient
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_connections.py
{ "start": 33957, "end": 36589 }
class ____(TestConnectionEndpoint): def setup_method(self): try: metadata("apache-airflow-providers-sqlite") except PackageNotFoundError: pytest.skip("The SQlite distribution package is not installed.") @mock.patch.dict(os.environ, {"AIRFLOW__CORE__TEST_CONNECTION": "Enabled"}) @pytest.mark.parametrize( ("body", "message"), [ ({"connection_id": TEST_CONN_ID, "conn_type": "sqlite"}, "Connection successfully tested"), ( {"connection_id": TEST_CONN_ID, "conn_type": "fs", "extra": '{"path": "/"}'}, "Path / is existing.", ), ], ) def test_should_respond_200(self, test_client, body, message): response = test_client.post("/connections/test", json=body) assert response.status_code == 200 assert response.json() == { "status": True, "message": message, } def test_should_respond_401(self, unauthenticated_test_client): response = unauthenticated_test_client.post( "/connections/test", json={"connection_id": TEST_CONN_ID, "conn_type": "sqlite"} ) assert response.status_code == 401 def test_should_respond_403(self, unauthorized_test_client): response = unauthorized_test_client.post( "/connections/test", json={"connection_id": TEST_CONN_ID, "conn_type": "sqlite"} ) assert response.status_code == 403 @skip_if_force_lowest_dependencies_marker @mock.patch.dict(os.environ, {"AIRFLOW__CORE__TEST_CONNECTION": "Enabled"}) @pytest.mark.parametrize( "body", [ {"connection_id": TEST_CONN_ID, "conn_type": "sqlite"}, {"connection_id": TEST_CONN_ID, "conn_type": "ftp"}, ], ) def test_connection_env_is_cleaned_after_run(self, test_client, body): test_client.post("/connections/test", json=body) assert not any([key.startswith(CONN_ENV_PREFIX) for key in os.environ.keys()]) @pytest.mark.parametrize( "body", [ {"connection_id": TEST_CONN_ID, "conn_type": "sqlite"}, {"connection_id": TEST_CONN_ID, "conn_type": "ftp"}, ], ) def test_should_respond_403_by_default(self, test_client, body): response = test_client.post("/connections/test", json=body) assert response.status_code == 403 assert response.json() == { "detail": "Testing connections is disabled in Airflow configuration. " "Contact your deployment admin to enable it." }
TestConnection
python
ray-project__ray
python/ray/serve/_private/router.py
{ "start": 20301, "end": 20846 }
class ____(ABC): @abstractmethod def running_replicas_populated(self) -> bool: pass @abstractmethod def assign_request( self, request_meta: RequestMetadata, *request_args, **request_kwargs, ) -> concurrent.futures.Future[ReplicaResult]: pass @abstractmethod def shutdown(self) -> concurrent.futures.Future: pass async def create_event() -> asyncio.Event: """Helper to create an asyncio event in the current event loop.""" return asyncio.Event()
Router
python
langchain-ai__langchain
libs/core/langchain_core/_api/deprecation.py
{ "start": 711, "end": 840 }
class ____(DeprecationWarning): """A class for issuing deprecation warnings for LangChain users."""
LangChainDeprecationWarning
python
getsentry__sentry
src/sentry/web/forms/fields.py
{ "start": 1825, "end": 2128 }
class ____(Widget): def render(self, name, value, attrs=None, renderer=None): final_attrs = self.build_attrs(attrs) if not value: value = mark_safe("<em>%s</em>" % _("Not set")) return format_html("<div{0}>{1}</div>", flatatt(final_attrs), value)
ReadOnlyTextWidget
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/interfaces.py
{ "start": 13333, "end": 14881 }
class ____(_DCAttributeOptions): __slots__ = () _default_scalar_value: Any _disable_dataclass_default_factory: bool = False def _get_dataclass_setup_options( self, decl_scan: _ClassScanAbstractConfig, key: str, dataclass_setup_arguments: _DataclassArguments, enable_descriptor_defaults: bool, ) -> _AttributeOptions: disable_descriptor_defaults = ( not enable_descriptor_defaults or getattr(decl_scan.cls, "_sa_disable_descriptor_defaults", False) ) if disable_descriptor_defaults: return self._attribute_options dataclasses_default = self._attribute_options.dataclasses_default dataclasses_default_factory = ( self._attribute_options.dataclasses_default_factory ) if dataclasses_default is not _NoArg.NO_ARG and not callable( dataclasses_default ): self._default_scalar_value = ( self._attribute_options.dataclasses_default ) return self._attribute_options._replace( dataclasses_default=DONT_SET, ) elif ( self._disable_dataclass_default_factory and dataclasses_default_factory is not _NoArg.NO_ARG ): return self._attribute_options._replace( dataclasses_default=DONT_SET, dataclasses_default_factory=_NoArg.NO_ARG, ) return self._attribute_options
_DataclassDefaultsDontSet
python
automl__auto-sklearn
autosklearn/ensemble_building/builder.py
{ "start": 1144, "end": 41032 }
class ____: """Builds ensembles out of runs that exist in the Backend This is used by EnsembleBuilderManager and created in a dask-client every time a run finishes and there is currently no EnsembleBuilder active. """ def __init__( self, backend: Backend, dataset_name: str, task_type: int, metrics: Sequence[Scorer], ensemble_class: Type[AbstractEnsemble] = EnsembleSelection, ensemble_kwargs: Mapping[str, Any] | None = None, ensemble_nbest: int | float = 50, max_models_on_disc: int | float | None = 100, seed: int = 1, precision: int = 32, memory_limit: int | None = 1024, read_at_most: int | None = None, logger_port: int = logging.handlers.DEFAULT_TCP_LOGGING_PORT, random_state: int | np.random.RandomState | None = None, ): """ Parameters ---------- backend: Backend backend to write and read files dataset_name: str name of dataset task_type: int type of ML task metrics: Sequence[Scorer] Metrics to optimize the ensemble for. These must be non-duplicated. ensemble_class: Type[AbstractEnsemble] Implementation of the ensemble algorithm. ensemble_kwargs: Mapping[str, Any] | None Arguments passed to the constructor of the ensemble algorithm. ensemble_nbest: int | float = 50 * int: consider only the n best prediction (> 0) * float: consider only this fraction of the best, between (0, 1) Both with respect to the validation predictions. max_models_on_disc: int | float | None = 100 Defines the maximum number of models that are kept in the disc. It defines an upper bound on the models that can be used in the ensemble. * int: and dictates the max number of models to keep. (>= 1) * float: it will be interpreted as the max megabytes allowed of disc space. If the number of ensemble candidates require more disc space than this float value, the worst models are deleted to keep within this budget. Models and predictions of the worst-performing models will be deleted then. * None: the feature is disabled. seed: int = 1 random seed that is used as part of the filename precision: int [16 | 32 | 64 | 128] = 32 precision of floats to read the predictions memory_limit: int | None = 1024 memory limit in mb. If ``None``, no memory limit is enforced. read_at_most: int | None = None read at most n new prediction files in each iteration. If `None`, will read the predictions and calculate losses for all runs that require it. logger_port: int = DEFAULT_TCP_LOGGING_PORT port that receives logging records random_state: int | RandomState | None = None An int or RandomState object used for generating the ensemble. """ if isinstance(ensemble_nbest, int) and ensemble_nbest < 1: raise ValueError(f"int ensemble_nbest ({ensemble_nbest}) must be (>1)") if isinstance(ensemble_nbest, float) and not (0 <= ensemble_nbest <= 1): raise ValueError(f"float ensemble_nbest ({ensemble_nbest}) not in (0,1)") if max_models_on_disc is not None and max_models_on_disc < 0: raise ValueError("max_models_on_disc must be positive or None") if read_at_most is not None and (read_at_most < 1 or read_at_most == np.inf): raise ValueError("Read at most must be int greater than 1 or None") # Setup the logger self.logger = get_named_client_logger(name="EnsembleBuilder", port=logger_port) self.logger_port = logger_port # Log the behaviour if ensemble_nbest == 1: t = type(ensemble_nbest) self.logger.debug(f"Using behaviour when {t} for {ensemble_nbest}:{t}") self.seed = seed self.metrics = metrics self.backend = backend self.precision = precision self.task_type = task_type self.memory_limit = memory_limit self.read_at_most = read_at_most self.random_state = check_random_state(random_state) self.dataset_name = dataset_name self.ensemble_class = ensemble_class self.ensemble_kwargs = ensemble_kwargs self.ensemble_nbest = ensemble_nbest # Decide if self.max_models_on_disc is a memory limit or model limit self.max_models_on_disc: int | None = None self.model_memory_limit: float | None = None if isinstance(max_models_on_disc, int): self.max_models_on_disc = max_models_on_disc elif isinstance(max_models_on_disc, float): self.model_memory_limit = max_models_on_disc # The starting time of the procedure self.start_time: float = 0.0 # Track the ensemble performance self.ensemble_history: list[dict[str, Any]] = [] # Keep running knowledge of its validation performance self.validation_performance_ = np.inf # Data we may need # TODO: The test data is needlessly loaded but automl_common has no concept of # these and is perhaps too rigid datamanager: XYDataManager = self.backend.load_datamanager() self._X_test: SUPPORTED_FEAT_TYPES | None = datamanager.data.get("X_test", None) self._y_test: np.ndarray | None = datamanager.data.get("Y_test", None) self._X_ensemble: SUPPORTED_FEAT_TYPES | None = None self._y_ensemble: np.ndarray | None = None @property def previous_candidates_path(self) -> Path: """Path to the cached losses we store between runs""" return Path(self.backend.internals_directory) / CANDIDATES_FILENAME def previous_candidates(self) -> dict[RunID, Run]: """Load any previous candidates that were saved from previous runs Returns ------- dict[RunID, Run] A dictionary from RunId's to the previous candidates """ if self.previous_candidates_path.exists(): with self.previous_candidates_path.open("rb") as f: return pickle.load(f) else: return {} def available_runs(self) -> dict[RunID, Run]: """Get a dictionary of all available runs on the filesystem Returns ------- dict[RunID, Run] A dictionary from RunId's to the available runs """ runs_dir = Path(self.backend.get_runs_directory()) runs = iter(Run(path=dir) for dir in runs_dir.iterdir() if Run.valid(dir)) return {run.id: run for run in runs} def targets(self, kind: str = "ensemble") -> np.ndarray | None: """The ensemble targets used for training the ensemble It will attempt to load and cache them in memory but return None if it can't. Returns ------- np.ndarray | None The ensemble targets, if they can be loaded """ if kind == "ensemble": if self._y_ensemble is None: if os.path.exists(self.backend._get_targets_ensemble_filename()): self._y_ensemble = self.backend.load_targets_ensemble() return self._y_ensemble elif kind == "test": return self._y_test else: raise NotImplementedError(kind) def X_data(self, kind: str = "ensemble") -> SUPPORTED_FEAT_TYPES: """The ensemble targets used for training the ensemble It will attempt to load and cache them in memory but return None if it can't. Returns ------- np.ndarray | None The ensemble targets, if they can be loaded """ if kind == "ensemble": if self._X_ensemble is None: if os.path.exists(self.backend._get_input_ensemble_filename()): self._X_ensemble = self.backend.load_input_ensemble() return self._X_ensemble elif kind == "test": return self._X_test else: raise NotImplementedError(kind) def run( self, iteration: int, pynisher_context: str | None = None, time_left: float | None = None, end_at: float | None = None, time_buffer: int = 5, ) -> tuple[list[dict[str, Any]], int | float]: """Run the ensemble building process Parameters ---------- iteration : int What iteration to associate with this run pynisher_context : str | None = None The pynisher context to run in. If None, defaults to multiprocessing.get_context(None) time_left : float | None = None How much time should be left for this run. Either this or `end_at` must be provided. end_at : float | None = None When this run should end. Either this or `time_left` must be provided. time_buffer : int = 5 How much extra time to add as a buffer to this run. This means there is always some amount of time to do something useful. Returns ------- (ensemble_history, nbest) """ if time_left is None and end_at is None: raise ValueError("Must provide either time_left or end_at.") elif time_left is not None and end_at is not None: raise ValueError("Cannot provide both time_left and end_at.") if not self.logger: self.logger = get_named_client_logger( name="EnsembleBuilder", port=self.logger_port, ) process_start_time = time.time() while True: if time_left is not None: time_elapsed = time.time() - process_start_time time_left -= time_elapsed else: assert end_at is not None current_time = time.time() if current_time > end_at: break else: time_left = end_at - current_time wall_time_in_s = int(time_left - time_buffer) if wall_time_in_s < 1: break context = multiprocessing.get_context(pynisher_context) preload_modules(context) safe_ensemble_script = pynisher.enforce_limits( wall_time_in_s=wall_time_in_s, mem_in_mb=self.memory_limit, logger=self.logger, context=context, )(self.main) safe_ensemble_script(time_left, iteration) status = safe_ensemble_script.exit_status if isinstance(status, pynisher.MemorylimitException): # if ensemble script died because of memory error, # reduce nbest to reduce memory consumption and try it again # ATTENTION: main will start from scratch; # all data structures are empty again try: self.previous_candidates_path.unlink() except: # noqa E722 pass if ( isinstance(self.ensemble_nbest, numbers.Integral) and self.ensemble_nbest <= 1 ): if self.read_at_most == 1: self.logger.error( "Memory Exception -- Unable to further reduce the number" " of ensemble members and can no further limit the number" " of ensemble members loaded per iteration, please restart" " Auto-sklearn with a higher value for the argument" f" `memory_limit` (current limit is {self.memory_limit}MB)." " The ensemble builder will keep running to delete files" " from disk in case this was enabled.", ) self.ensemble_nbest = 0 else: self.read_at_most = 1 self.logger.warning( "Memory Exception -- Unable to further reduce the number of" " ensemble members. Now reducing the number of predictions" " per call to read at most to 1." ) else: if isinstance(self.ensemble_nbest, numbers.Integral): self.ensemble_nbest = max(1, int(self.ensemble_nbest / 2)) else: self.ensemble_nbest = self.ensemble_nbest / 2 self.logger.warning( "Memory Exception -- restart with " "less ensemble_nbest: %d" % self.ensemble_nbest ) return [], self.ensemble_nbest elif isinstance(status, pynisher.AnythingException): return ([], self.ensemble_nbest) else: return safe_ensemble_script.result return [], self.ensemble_nbest def main( self, time_left: float | None = None, iteration: int = 0, ) -> tuple[list[dict[str, Any]], int | float]: """Run the main loop of ensemble building The process is: * Load all available runs + previous candidates (if any) * Update the loss of those that require * From these runs, get a list of candidates * Save candidates * Delete models that are not candidates * Build an ensemble from the candidates if there are new candidates Parameters ---------- time_left : float | None = None How much time is left for this run iteration : int = 0 The iteration of this run Returns ------- (ensemble_history: list[dict[str, Any]], nbest: int | float) """ # Pynisher jobs inside dask 'forget' the logger configuration. # So we have to set it up accordingly self.logger = get_named_client_logger( name="EnsembleBuilder", port=self.logger_port, ) if time_left is not None: self.start_time = time.time() used_time = time.time() - self.start_time left_for_iter = time_left - used_time itr = iteration if str(iteration) is not None else "" self.logger.debug(f"Starting iteration {itr}, time left: {left_for_iter}") # Can't load data, exit early if not os.path.exists(self.backend._get_targets_ensemble_filename()): self.logger.debug(f"No targets for ensemble: {traceback.format_exc()}") raise RuntimeError("No targets for ensemble") # We will delete runs once we are complete deletable_runs: set[Run] = set() # Load in information from previous candidates and also runs available_runs = self.available_runs() # Update runs with information of available previous candidates previous_candidates = self.previous_candidates() available_runs.update(previous_candidates) # We just need the values now, not the key value pairs {run.id: Run} runs = list(available_runs.values()) if len(runs) == 0: self.logger.debug("Found no runs") raise RuntimeError("Found no runs") # We load in `X_data` if we need it if any(m._needs_X for m in self.metrics): ensemble_X_data = self.X_data("ensemble") if ensemble_X_data is None: msg = "No `X_data` for 'ensemble' which was required by metrics" self.logger.debug(msg) raise RuntimeError(msg) else: ensemble_X_data = None # Calculate the loss for those that require it requires_update = self.requires_loss_update(runs) if self.read_at_most is not None: requires_update = requires_update[: self.read_at_most] for run in requires_update: run.record_modified_times() # So we don't count as modified next time run.losses = { metric.name: self.loss(run, metric=metric, X_data=ensemble_X_data) for metric in self.metrics } # Get the dummy and real runs dummies, candidates = split(runs, by=lambda r: r.is_dummy()) # We see if we need to delete any of the real runs before we waste compute # on evaluating their candidacy for ensemble building if any(candidates): candidates, to_delete = self.requires_deletion( candidates, max_models=self.max_models_on_disc, memory_limit=self.model_memory_limit, ) # If there are no candidates left, we just keep the best one, ordered by # objectives and finally num_run if not any(candidates): best = min( to_delete, key=lambda r: ( *[r.losses.get(m.name, np.inf) for m in self.metrics], r.num_run, ), ) candidates = [best] to_delete.remove(best) if any(to_delete): self.logger.info( f"Deleting runs {to_delete} due to" f" max_models={self.max_models_on_disc} and/or" f" memory_limit={self.model_memory_limit}" ) deletable_runs.update(to_delete) # If there are any candidates, perform candidates selection if any(candidates): candidates, to_delete = self.candidate_selection( runs=candidates, dummies=dummies, better_than_dummy=True, nbest=self.ensemble_nbest, ) if any(to_delete): self.logger.info( f"Deleting runs {to_delete} due to" f" nbest={self.ensemble_nbest} or worse than dummies" ) deletable_runs.update(to_delete) else: candidates = dummies self.logger.warning("No runs were available to build an ensemble from") # In case we record test predictions and not every model has test predictions, # only use the subset of models that has predictions for both the test set and # the ensemble optimization set. candidates_set = set(candidates) test_subset = {r for r in candidates if r.pred_path("test").exists()} if len(test_subset) > 0: candidates = sorted(test_subset, key=lambda r: r.id) test_models = candidates to_delete = candidates_set - test_subset if any(to_delete): self.logger.info( f"Deleting runs {to_delete} due to runs not" ' having "test_predictions" while others do not:' f"\nHave test_predictions = {test_subset}" f"\nNo test_predictions = {to_delete}" ) deletable_runs.update(to_delete) else: candidates = sorted(candidates_set, key=lambda r: r.id) test_models = [] # Save the candidates for the next round with self.previous_candidates_path.open("wb") as f: pickle.dump({run.id: run for run in candidates}, f) # If there was any change from the previous run, either in terms of # runs or one of those runs had its loss updated, then we need to # fit the ensemble builder previous_candidate_ids = set(previous_candidates) current_candidate_ids = set(run.id for run in candidates) difference = previous_candidate_ids ^ current_candidate_ids was_updated_candidates = list(run in candidates for run in requires_update) if not any(difference) and not any(was_updated_candidates): self.logger.info("All ensemble candidates the same, no update required") return self.ensemble_history, self.ensemble_nbest targets = cast(np.ndarray, self.targets("ensemble")) # Sure they exist ensemble = self.fit_ensemble( candidates=candidates, targets=targets, runs=runs, ensemble_class=self.ensemble_class, ensemble_kwargs=self.ensemble_kwargs, X_data=ensemble_X_data, task=self.task_type, metrics=self.metrics, precision=self.precision, random_state=self.random_state, ) self.logger.info(str(ensemble)) ens_perf = ensemble.get_validation_performance() self.validation_performance_ = min(self.validation_performance_, ens_perf) self.backend.save_ensemble( ensemble=ensemble, idx=iteration, seed=self.seed # type: ignore ) performance_stamp = {"Timestamp": pd.Timestamp.now()} for kind, score_name, models in [ ("ensemble", "optimization", candidates), ("test", "test", test_models), ]: if len(models) == 0: continue pred_targets = self.targets(kind) if pred_targets is None: self.logger.warning(f"No ensemble targets for {kind}") continue run_preds = [r.predictions(kind, precision=self.precision) for r in models] pred = ensemble.predict(run_preds) if any(m._needs_X for m in self.metrics): X_data = self.X_data(kind) if X_data is None: msg = f"No `X` data for '{kind}' which was required by metrics" self.logger.debug(msg) raise RuntimeError(msg) else: X_data = None scores = calculate_scores( solution=pred_targets, prediction=pred, task_type=self.task_type, metrics=self.metrics, X_data=X_data, scoring_functions=None, ) # TODO only one metric in history # # We should probably return for all metrics but this makes # automl::performance_history a lot more complicated, will # tackle in a future PR first_metric = self.metrics[0] performance_stamp[f"ensemble_{score_name}_score"] = scores[ first_metric.name ] # Add the performance stamp to the history self.ensemble_history.append(performance_stamp) # Lastly, delete any runs that need to be deleted. We save this as the last step # so that we have an ensemble saved that is up to date. If we do not do so, # there could be runs deleted that are in th previous ensemble and we do not # manage to update the ensemble due to a crash or the process being killed # before it could be updated self.delete_runs(deletable_runs) return self.ensemble_history, self.ensemble_nbest def requires_loss_update( self, runs: Sequence[Run], metrics: Sequence[Scorer] | None = None, ) -> list[Run]: """ Parameters ---------- runs : Sequence[Run] The runs to process metrics: Sequence[Scorer] | None = None The metrics to check for, defaults to builders Returns ------- list[Run] The runs that require a loss to be calculated """ metrics = metrics if metrics is not None else self.metrics queue = [] for run in sorted(runs, key=lambda run: run.recorded_mtimes["ensemble"]): if any(metric.name not in run.losses for metric in metrics): queue.append(run) elif run.was_modified(): self.logger.debug(f"{run.id} had its predictions modified?") queue.append(run) return queue def candidate_selection( self, runs: Sequence[Run], dummies: Run | list[Run], *, better_than_dummy: bool = False, nbest: int | float | None = None, metrics: Sequence[Scorer] | None = None, ) -> tuple[list[Run], set[Run]]: """Get a list of candidates from `runs`, garuanteeing at least one Applies a set of reductions in order of parameters to reach a set of final candidates. Expects at least one `dummies` run. Parameters ---------- runs : Sequence[Run] The runs to evaluate candidates from. dummies: Run | Sequence[Run] The dummy run to base from better_than_dummy: bool = False Whether the run must be better than the best dummy run to be a candidate. In the case where there are no candidates left, the dummies will then be used. nbest : int | float | None The nbest models to select. If `int`, acts as an absolute limit. If `float`, acts as a percentage of available candidates. metrics : Sequence[Scorer] | None = None The metrics to consider, defaults to the builders Returns ------- (candidates: list[Run], discarded: set[Run]) A tuple of runs that are candidates and also those that didn't make it """ metrics = metrics if metrics else self.metrics if isinstance(dummies, Run): dummies = [dummies] assert len(dummies) > 0 and len(runs) > 0, "At least 1 real run and dummy run" all_discarded: set[Run] = set() # We filter out all runs that don't have any predictions for the ensemble candidates, discarded = split( runs, by=lambda run: run.pred_path("ensemble").exists(), ) all_discarded.update(discarded) if len(candidates) == 0: self.logger.debug("No runs with predictions on ensemble set, using dummies") return dummies, all_discarded for run in discarded: self.logger.warning(f"Have no ensemble predictions for {run}") # Get all the ones that have all metrics and tangible losses has_metrics = lambda r: all(m.name in r.losses for m in metrics) tangible_losses = lambda r: all(loss < np.inf for loss in r.losses.values()) candidates, discarded = split( candidates, by=lambda r: has_metrics(r) and tangible_losses(r), ) all_discarded.update(discarded) if len(candidates) == 0: self.logger.debug("No runs with a usable loss, using dummies") return dummies, all_discarded if better_than_dummy: # In the single objective case, they must explicitly be better than dummy if len(metrics) == 1: metric = metrics[0] best_dummy = min(dummies, key=lambda d: d.losses[metric.name]) self.logger.debug(f"Using dummy {best_dummy} to filter candidates") candidates, discarded = split( candidates, by=lambda r: r.losses[metric.name] < best_dummy.losses[metric.name], ) # In the multiobjective case, they must be better than at least one of the # best dummies, where there is a best dummy for each metric else: best_dummies = { metric.name: min(dummies, key=lambda d: d.losses[metric.name]) for metric in metrics } self.logger.debug(f"Using dummies {best_dummies} to filter candidates") candidates, discarded = split( candidates, by=lambda r: any( r.losses[metric_name] < best_dummy.losses[metric_name] for metric_name, best_dummy in best_dummies.items() ), ) all_discarded.update(discarded) # If there are no real candidates left, use the dummies if len(candidates) == 0: self.logger.warning( "No models better than random - using Dummy losses!" f"\n\tModels besides current dummy model: {len(candidates)}" f"\n\tDummy models: {len(dummies)}", ) return dummies, all_discarded if nbest is not None: # We order the runs according to a roundrobin of the metrics # i.e. the 1st run will be best in metric[0], # the 2nd run will be best in metric[1], # the 3rd run will be second best in metric[0], # the 4th run will be second best in metric[1], # ... whoops, what would be the 5th run, third best in metric[0] was # also the same as the 4th run. This was skipped # the 5th run will be third best in metric[1] **as we skipped above** # # With removing duplicates, this means if a run was already contained, it # will skip to the next member in the roundrobin fashion. sorted_candidates = [ sorted( candidates, key=lambda r: (r.losses.get(m.name, np.inf), r.num_run), ) for m in metrics ] candidates = list(roundrobin(*sorted_candidates, duplicates=False)) # Determine how many to keep, always keeping one if isinstance(nbest, float): nkeep = int(len(candidates) * nbest) else: nkeep = nbest candidates, discarded = cut(candidates, nkeep) self.logger.info(f"Discarding {len(discarded)}/{len(candidates)} runs") # Always preserve at least one, the best if len(candidates) == 0: candidates, discared = cut(discarded, 1) self.logger.warning("nbest too aggresive, using single best") all_discarded.update(discarded) return candidates, all_discarded def fit_ensemble( self, candidates: Sequence[Run], runs: Sequence[Run], *, targets: np.ndarray | None = None, ensemble_class: Type[AbstractEnsemble] = EnsembleSelection, ensemble_kwargs: Mapping[str, Any] | None = None, X_data: SUPPORTED_FEAT_TYPES | None = None, task: int | None = None, metrics: Sequence[Scorer] | None = None, precision: int | None = None, random_state: int | np.random.RandomState | None = None, ) -> AbstractEnsemble: """Fit an ensemble from the provided runs. Note ---- Expects all runs to have the "ensemble" predictions present Parameters ---------- candidates: Sequence[Run] List of runs to build an ensemble from runs: Sequence[Run] List of all runs (also pruned ones and dummy runs) targets: np.ndarray | None = None The targets to build the ensemble with ensemble_class: Type[AbstractEnsemble] Implementation of the ensemble algorithm. ensemble_kwargs: Mapping[str, Any] | None Arguments passed to the constructor of the ensemble algorithm. X_data: SUPPORTED_FEAT_TYPES | None = None The base level data. task: int | None = None The kind of task performed metrics: Sequence[Scorer] | None = None Metrics to optimize the ensemble for. precision: int | None = None The precision with which to load run predictions random_state: int | RandomState | None = None The random state to use Returns ------- AbstractEnsemble """ # Validate we have targets if None specified if targets is None: targets = self.targets("ensemble") if targets is None: path = self.backend._get_targets_ensemble_filename() raise ValueError(f"`fit_ensemble` could not find any targets at {path}") ensemble_class = ( ensemble_class if ensemble_class is not None else self.ensemble_class ) # Create the ensemble_kwargs, favouring in order: # 1) function kwargs, 2) function params 3) init_kwargs 4) init_params # Collect func params in dict if they're not None params = { k: v for k, v in [ ("task_type", task), ("metrics", metrics), ("random_state", random_state), ] if v is not None } kwargs = { "backend": self.backend, "task_type": self.task_type, "metrics": self.metrics, "random_state": self.random_state, **(self.ensemble_kwargs or {}), **params, **(ensemble_kwargs or {}), } ensemble = ensemble_class(**kwargs) # type: AbstractEnsemble self.logger.debug(f"Fitting ensemble on {len(candidates)} models") start_time = time.time() precision = precision if precision is not None else self.precision predictions_train = [ run.predictions("ensemble", precision=precision) for run in candidates ] ensemble.fit( base_models_predictions=predictions_train, X_data=X_data, true_targets=targets, model_identifiers=[run.id for run in candidates], runs=runs, ) duration = time.time() - start_time self.logger.debug(f"Fitting the ensemble took {duration} seconds.") return ensemble def requires_deletion( self, runs: Sequence[Run], *, max_models: int | None = None, memory_limit: float | None = None, metrics: Sequence[Scorer] | None = None, ) -> tuple[list[Run], set[Run]]: """Cut a list of runs into those to keep and those to delete If neither params are specified, this method should do nothing. In the case of multiple metrics, we interleave these according to the order of the provided metrics. Parameters ---------- runs : Sequence[Run] The runs to check max_models : int | None = None The maximum amount of models to have on disk. Leave `None` for no effect memory_limit : float | None = None The memory limit in MB, leave `None` for no effect metrics: Sequence[Scorer] | None = None The metrics to consider for the runs, defaults to `self.metrics` passed during construction if `None`. Returns ------- (keep: list[Run], delete: set[Run]) The list of runs to keep and those to delete """ if memory_limit is None and max_models is None: return list(runs), set() metrics = metrics if metrics is not None else self.metrics # We order the runs according to a roundrobin of the metrics # i.e. the 1st run will be best in metric[0], # the 2nd run will be best in metric[1], # the 3rd run will be second best in metric[0], # the 4th run will be second best in metric[1], # ... whoops, what would be the 5th run, third best in metric[0] was also # ... the same as the 4th run. This was skipped # the 5th run will be third best in metric[1] **as we skipped above** # # With removing duplicates, this means if a run was already contained, it will # skip to the next member in the roundrobin fashion. sorted_runs = [ sorted(runs, key=lambda r: (r.losses.get(metric.name, np.inf), r.num_run)) for metric in metrics ] keep = list(roundrobin(*sorted_runs, duplicates=False)) delete: set[Run] = set() if max_models is not None and max_models < len(runs): keep, to_delete = cut(keep, max_models) if any(to_delete): self.logger.info( "Limiting num of models via `max_models_on_disc`" f" max_models={max_models}" f" remaining={len(keep)}" f" discarded={len(to_delete)}" ) delete.update(to_delete) if memory_limit is not None: largest = max(runs, key=lambda r: r.mem_usage) cutoff = memory_limit - largest.mem_usage accumulated_mem_usage = accumulate(r.mem_usage for r in runs) cutpoint = findwhere(accumulated_mem_usage, lambda mem: mem > cutoff) keep, to_delete = cut(keep, cutpoint) if any(to_delete): self.logger.info( "Limiting num of models via `memory_limit`" f" memory_limit={memory_limit}" f" cutoff={cutoff}" f" largest={largest.mem_usage}" f" remaining={len(keep)}" f" discarded={len(to_delete)}" ) delete.update(to_delete) return keep, delete def loss( self, run: Run, metric: Scorer, *, X_data: SUPPORTED_FEAT_TYPES | None = None, kind: str = "ensemble", ) -> float: """Calculate the loss for a run Parameters ---------- run: Run The run to calculate the loss for metric: Scorer The metric to calculate the loss of X_data: SUPPORTED_FEAT_TYPES | None = None Any X_data required to be passed to the metric kind: str = "ensemble" The kind of targets to use for the run Returns ------- float The loss for the run """ targets = self.targets(kind) if targets is None: self.logger.error(f"No targets of {kind}") return np.inf try: predictions = run.predictions(kind, precision=self.precision) loss: float = calculate_loss( solution=targets, prediction=predictions, task_type=self.task_type, metric=metric, X_data=X_data, ) except Exception as e: tb = traceback.format_exc() self.logger.error(f"Error getting loss `{metric.name}` for {run}:{e}{tb}") loss = np.inf finally: return loss def delete_runs(self, runs: Iterable[Run]) -> None: """Delete runs Will not delete dummy runs Parameters ---------- runs : Sequence[Run] The runs to delete """ items = iter(run for run in runs if not run.is_dummy() and run.dir.exists()) for run in items: try: rmtree(run.dir, atomic=True) self.logger.info(f"Deleted files for {run}") except Exception as e: self.logger.error(f"Failed to delete files for {run}: \n{e}")
EnsembleBuilder
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 65848, "end": 66098 }
class ____(BaseModel): """ Asset event collection response. """ asset_events: Annotated[list[AssetEventResponse], Field(title="Asset Events")] total_entries: Annotated[int, Field(title="Total Entries")]
AssetEventCollectionResponse
python
celery__celery
examples/stamping/visitors.py
{ "start": 160, "end": 385 }
class ____(StampingVisitor): def on_signature(self, sig: Signature, **headers) -> dict: logger.critical(f"Visitor: Sig '{sig}' is stamped with: mystamp") return {"mystamp": "I am a stamp!"}
MyStampingVisitor
python
Unity-Technologies__ml-agents
ml-agents-envs/mlagents_envs/base_env.py
{ "start": 6235, "end": 6944 }
class ____(NamedTuple): """ Contains the data a single Agent collected when its episode ended. - obs is a list of numpy arrays observations collected by the agent. - reward is a float. Corresponds to the rewards collected by the agent since the last simulation step. - interrupted is a bool. Is true if the Agent was interrupted since the last decision step. For example, if the Agent reached the maximum number of steps for the episode. - agent_id is an int and an unique identifier for the corresponding Agent. """ obs: List[np.ndarray] reward: float interrupted: bool agent_id: AgentId group_id: GroupId group_reward: float
TerminalStep
python
mahmoud__boltons
boltons/fileutils.py
{ "start": 22396, "end": 25486 }
class ____: # TODO: raise ValueErrors on closed for all methods? # TODO: enforce read/write def __init__(self, path, mode='r', buffering=None): self.name = path self.mode = mode self.closed = False self.errors = None self.isatty = False self.encoding = None self.newlines = None self.softspace = 0 def close(self): self.closed = True def fileno(self): return -1 def flush(self): if self.closed: raise ValueError('I/O operation on a closed file') return def next(self): raise StopIteration() def read(self, size=0): if self.closed: raise ValueError('I/O operation on a closed file') return '' def readline(self, size=0): if self.closed: raise ValueError('I/O operation on a closed file') return '' def readlines(self, size=0): if self.closed: raise ValueError('I/O operation on a closed file') return [] def seek(self): if self.closed: raise ValueError('I/O operation on a closed file') return def tell(self): if self.closed: raise ValueError('I/O operation on a closed file') return 0 def truncate(self): if self.closed: raise ValueError('I/O operation on a closed file') return def write(self, string): if self.closed: raise ValueError('I/O operation on a closed file') return def writelines(self, list_of_strings): if self.closed: raise ValueError('I/O operation on a closed file') return def __next__(self): raise StopIteration() def __enter__(self): if self.closed: raise ValueError('I/O operation on a closed file') return def __exit__(self, exc_type, exc_val, exc_tb): return def rotate_file(filename, *, keep: int = 5): """ If *filename.ext* exists, it will be moved to *filename.1.ext*, with all conflicting filenames being moved up by one, dropping any files beyond *keep*. After rotation, *filename* will be available for creation as a new file. Fails if *filename* is not a file or if *keep* is not > 0. """ if keep < 1: raise ValueError(f'expected "keep" to be >=1, not {keep}') if not os.path.exists(filename): return if not os.path.isfile(filename): raise ValueError(f'expected {filename} to be a file') fn_root, fn_ext = os.path.splitext(filename) kept_names = [] for i in range(1, keep + 1): if fn_ext: kept_names.append(f'{fn_root}.{i}{fn_ext}') else: kept_names.append(f'{fn_root}.{i}') fns = [filename] + kept_names for orig_name, kept_name in reversed(list(zip(fns, fns[1:]))): if not os.path.exists(orig_name): continue os.rename(orig_name, kept_name) if os.path.exists(kept_names[-1]): os.remove(kept_names[-1]) return
DummyFile
python
dagster-io__dagster
python_modules/dagster/dagster/components/lib/shim_components/asset_check.py
{ "start": 342, "end": 458 }
class ____(BaseModel): """Parameters for the AssetCheckScaffolder.""" asset_key: str
AssetCheckScaffoldParams
python
EpistasisLab__tpot
tpot/builtin_modules/arithmetictransformer.py
{ "start": 1726, "end": 5415 }
class ____(TransformerMixin, BaseEstimator): #functions = ["add", "mul_neg_1", "mul", "safe_reciprocal", "eq","ne","ge","gt","le","lt", "min","max","0","1"] def __init__(self, function,): """ A transformer that applies a function to the input array along axis 1. Parameters ---------- function : str The function to apply to the input array. The following functions are supported: - 'add' : Add all elements along axis 1 - 'mul_neg_1' : Multiply all elements along axis 1 by -1 - 'mul' : Multiply all elements along axis 1 - 'safe_reciprocal' : Take the reciprocal of all elements along axis 1, with a safe division by zero - 'eq' : Check if all elements along axis 1 are equal - 'ne' : Check if all elements along axis 1 are not equal - 'ge' : Check if all elements along axis 1 are greater than or equal to 0 - 'gt' : Check if all elements along axis 1 are greater than 0 - 'le' : Check if all elements along axis 1 are less than or equal to 0 - 'lt' : Check if all elements along axis 1 are less than 0 - 'min' : Take the minimum of all elements along axis 1 - 'max' : Take the maximum of all elements along axis 1 - '0' : Return an array of zeros - '1' : Return an array of ones """ self.function = function def fit(self, X, y=None): return self def transform(self, X): transformed_X = np.array(self.transform_helper(np.array(X))) if transformed_X.dtype != float: transformed_X = transformed_X.astype(float) return transformed_X def transform_helper(self, X): X = np.array(X) if len(X.shape) == 1: X = np.expand_dims(X,0) if self.function == "add": return np.expand_dims(np.sum(X,1),1) elif self.function == "mul_neg_1": return X*-1 elif self.function == "mul": return np.expand_dims(np.prod(X,1),1) elif self.function == "safe_reciprocal": results = np.divide(1.0, X.astype(float), out=np.zeros_like(X).astype(float), where=X!=0) #TODO remove astypefloat? return results elif self.function == "eq": return np.expand_dims(np.all(X == X[0,:], axis = 1),1).astype(float) elif self.function == "ne": return 1- np.expand_dims(np.all(X == X[0,:], axis = 1),1).astype(float) #TODO these could be "sorted order" elif self.function == "ge": result = X >= 0 return result.astype(float) elif self.function == "gt": result = X > 0 return result.astype(float) elif self.function == "le": result = X <= 0 return result.astype(float) elif self.function == "lt": result = X < 0 return result.astype(float) elif self.function == "min": return np.expand_dims(np.amin(X,1),1) elif self.function == "max": return np.expand_dims(np.amax(X,1),1) elif self.function == "0": return np.zeros((X.shape[0],1)) elif self.function == "1": return np.ones((X.shape[0],1)) def issorted(x, rev=False): if rev: s = sorted(x) s.reverse() if s == x: return True else: if sorted(x) == x: return True return False
ArithmeticTransformer
python
django__django
django/contrib/gis/gdal/datasource.py
{ "start": 1639, "end": 4603 }
class ____(GDALBase): "Wraps an OGR Data Source object." destructor = capi.destroy_ds def __init__(self, ds_input, ds_driver=False, write=False, encoding="utf-8"): # The write flag. self._write = capi.GDAL_OF_UPDATE if write else capi.GDAL_OF_READONLY # See also https://gdal.org/development/rfc/rfc23_ogr_unicode.html self.encoding = encoding Driver.ensure_registered() if isinstance(ds_input, (str, Path)): try: # GDALOpenEx will auto-detect the data source type. ds = capi.open_ds( force_bytes(ds_input), self._write | capi.GDAL_OF_VECTOR, None, None, None, ) except GDALException: # Making the error message more clear rather than something # like "Invalid pointer returned from OGROpen". raise GDALException('Could not open the datasource at "%s"' % ds_input) elif isinstance(ds_input, self.ptr_type) and isinstance( ds_driver, Driver.ptr_type ): ds = ds_input else: raise GDALException("Invalid data source input type: %s" % type(ds_input)) if ds: self.ptr = ds driver = capi.get_dataset_driver(ds) self.driver = Driver(driver) else: # Raise an exception if the returned pointer is NULL raise GDALException('Invalid data source file "%s"' % ds_input) def __getitem__(self, index): "Allows use of the index [] operator to get a layer at the index." if isinstance(index, str): try: layer = capi.get_layer_by_name(self.ptr, force_bytes(index)) except GDALException: raise IndexError("Invalid OGR layer name given: %s." % index) elif isinstance(index, int): if 0 <= index < self.layer_count: layer = capi.get_layer(self._ptr, index) else: raise IndexError( "Index out of range when accessing layers in a datasource: %s." % index ) else: raise TypeError("Invalid index type: %s" % type(index)) return Layer(layer, self) def __len__(self): "Return the number of layers within the data source." return self.layer_count def __str__(self): "Return OGR GetName and Driver for the Data Source." return "%s (%s)" % (self.name, self.driver) @property def layer_count(self): "Return the number of layers in the data source." return capi.get_layer_count(self._ptr) @property def name(self): "Return the name of the data source." name = capi.get_ds_name(self._ptr) return force_str(name, self.encoding, strings_only=True)
DataSource
python
huggingface__transformers
src/transformers/models/instructblipvideo/modular_instructblipvideo.py
{ "start": 6543, "end": 6655 }
class ____(InstructBlipPreTrainedModel): input_modalities = ("video", "text")
InstructBlipVideoPreTrainedModel
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/ui/structure.py
{ "start": 1542, "end": 1669 }
class ____(BaseGraphResponse[EdgeResponse, NodeResponse]): """Structure Data serializer for responses."""
StructureDataResponse
python
pandas-dev__pandas
asv_bench/benchmarks/frame_methods.py
{ "start": 21807, "end": 22176 }
class ____: def setup(self): self.df = DataFrame(np.random.randn(100000, 2), columns=list("AB")) self.df2 = self.df.copy() self.df2["A"] = self.df2["A"].astype("object") def time_memory_usage(self): self.df.memory_usage(deep=True) def time_memory_usage_object_dtype(self): self.df2.memory_usage(deep=True)
MemoryUsage
python
PyCQA__pylint
tests/functional/n/no/no_member_assign_same_line.py
{ "start": 280, "end": 463 }
class ____: """This class attempts to assign and access a member in the same line.""" def __init__(self): self.member = self.member # [no-member]
AssignMemberInSameLine
python
wandb__wandb
wandb/apis/public/reports.py
{ "start": 413, "end": 4302 }
class ____(SizedPaginator["BetaReport"]): """Reports is a lazy iterator of `BetaReport` objects. Args: client (`wandb.apis.internal.Api`): The API client instance to use. project (`wandb.sdk.internal.Project`): The project to fetch reports from. name (str, optional): The name of the report to filter by. If `None`, fetches all reports. entity (str, optional): The entity name for the project. Defaults to the project entity. per_page (int): Number of reports to fetch per page (default is 50). """ QUERY = gql( """ query ProjectViews($project: String!, $entity: String!, $reportCursor: String, $reportLimit: Int!, $viewType: String = "runs", $viewName: String) { project(name: $project, entityName: $entity) { allViews(viewType: $viewType, viewName: $viewName, first: $reportLimit, after: $reportCursor) { edges { node { id name displayName description user { username photoUrl email } spec updatedAt createdAt } cursor } pageInfo { endCursor hasNextPage } } } } """ ) def __init__(self, client, project, name=None, entity=None, per_page=50): self.project = project self.name = name variables = { "project": project.name, "entity": project.entity, "viewName": self.name, } super().__init__(client, variables, per_page) @property def _length(self): """The number of reports in the project. <!-- lazydoc-ignore: internal --> """ # TODO: Add the count the backend if self.last_response: return len(self.objects) else: return None @property def more(self) -> bool: """Returns whether there are more files to fetch. <!-- lazydoc-ignore: internal --> """ if self.last_response: return bool( self.last_response["project"]["allViews"]["pageInfo"]["hasNextPage"] ) else: return True @property def cursor(self): """Returns the cursor position for pagination of file results. <!-- lazydoc-ignore: internal --> """ if self.last_response: return self.last_response["project"]["allViews"]["edges"][-1]["cursor"] else: return None def update_variables(self): """Updates the GraphQL query variables for pagination.""" self.variables.update( {"reportCursor": self.cursor, "reportLimit": self.per_page} ) def convert_objects(self): """Converts GraphQL edges to File objects.""" if self.last_response["project"] is None: raise ValueError( f"Project {self.variables['project']} does not exist under entity {self.variables['entity']}" ) return [ BetaReport( self.client, r["node"], entity=self.project.entity, project=self.project.name, ) for r in self.last_response["project"]["allViews"]["edges"] ] def __repr__(self): return "<Reports {}>".format("/".join(self.project.path))
Reports
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 30286, "end": 31008 }
class ____(themeable): """ x-axis line Parameters ---------- theme_element : element_line """ position = "bottom" _omit = ["solid_capstyle"] def apply_ax(self, ax: Axes): super().apply_ax(ax) properties = self.properties # MPL has a default zorder of 2.5 for spines # so layers 3+ would be drawn on top of the spines if "zorder" not in properties: properties["zorder"] = 10000 ax.spines["top"].set_visible(False) ax.spines["bottom"].set(**properties) def blank_ax(self, ax: Axes): super().blank_ax(ax) ax.spines["top"].set_visible(False) ax.spines["bottom"].set_visible(False)
axis_line_x
python
pypa__warehouse
warehouse/packaging/services.py
{ "start": 5864, "end": 7211 }
class ____(GenericBlobStorage): def get(self, path: str): path = self._get_path(path) try: file_obj = io.BytesIO() downloaded_file = self.bucket.download_file_by_name(path) downloaded_file.save(file_obj) file_obj.seek(0) return file_obj except b2sdk.v2.exception.FileNotPresent: raise FileNotFoundError(f"No such key: {path!r}") from None def get_metadata(self, path: str): path = self._get_path(path) try: return self.bucket.get_file_info_by_name(path).file_info except b2sdk.v2.exception.FileNotPresent: raise FileNotFoundError(f"No such key: {path!r}") from None def get_checksum(self, path: str): path = self._get_path(path) try: return self.bucket.get_file_info_by_id( self.bucket.get_file_info_by_name(path).id_ ).content_md5 except b2sdk.v2.exception.FileNotPresent: raise FileNotFoundError(f"No such key: {path!r}") from None def store(self, path: str, file_path, *, meta=None): path = self._get_path(path) self.bucket.upload_local_file( local_file=file_path, file_name=path, file_infos=meta, ) @implementer(IFileStorage)
GenericB2BlobStorage
python
networkx__networkx
networkx/algorithms/tests/test_distance_measures.py
{ "start": 417, "end": 6154 }
class ____: def setup_method(self): self.G = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted") @pytest.mark.parametrize("seed", list(range(10))) @pytest.mark.parametrize("n", list(range(10, 20))) @pytest.mark.parametrize("prob", [x / 10 for x in range(0, 10, 2)]) def test_use_bounds_on_off_consistency(self, seed, n, prob): """Test for consistency of distance metrics when using usebounds=True. We validate consistency for `networkx.diameter`, `networkx.radius`, `networkx.periphery` and `networkx.center` when passing `usebounds=True`. Expectation is that method returns the same result whether we pass usebounds=True or not. For this we generate random connected graphs and validate method returns the same. """ metrics = [nx.diameter, nx.radius, nx.periphery, nx.center] max_weight = [5, 10, 1000] rng = Random(seed) # we compose it with a random tree to ensure graph is connected G = nx.compose( nx.random_labeled_tree(n, seed=rng), nx.erdos_renyi_graph(n, prob, seed=rng), ) for metric in metrics: # checking unweighted case assert metric(G) == metric(G, usebounds=True) for w in max_weight: for u, v in G.edges(): G[u][v]["w"] = rng.randint(0, w) # checking weighted case assert metric(G, weight="w") == metric(G, weight="w", usebounds=True) def test_eccentricity(self): assert nx.eccentricity(self.G, 1) == 6 e = nx.eccentricity(self.G) assert e[1] == 6 sp = dict(nx.shortest_path_length(self.G)) e = nx.eccentricity(self.G, sp=sp) assert e[1] == 6 e = nx.eccentricity(self.G, v=1) assert e == 6 # This behavior changed in version 1.8 (ticket #739) e = nx.eccentricity(self.G, v=[1, 1]) assert e[1] == 6 e = nx.eccentricity(self.G, v=[1, 2]) assert e[1] == 6 # test against graph with one node G = nx.path_graph(1) e = nx.eccentricity(G) assert e[0] == 0 e = nx.eccentricity(G, v=0) assert e == 0 pytest.raises(nx.NetworkXError, nx.eccentricity, G, 1) # test against empty graph G = nx.empty_graph() e = nx.eccentricity(G) assert e == {} def test_diameter(self): assert nx.diameter(self.G) == 6 def test_harmonic_diameter(self): assert nx.harmonic_diameter(self.G) == pytest.approx(2.0477815699658715) assert nx.harmonic_diameter(nx.star_graph(3)) == pytest.approx(1.333333) def test_harmonic_diameter_empty(self): assert math.isnan(nx.harmonic_diameter(nx.empty_graph())) def test_harmonic_diameter_single_node(self): assert math.isnan(nx.harmonic_diameter(nx.empty_graph(1))) def test_harmonic_diameter_discrete(self): assert math.isinf(nx.harmonic_diameter(nx.empty_graph(3))) def test_harmonic_diameter_not_strongly_connected(self): DG = nx.DiGraph() DG.add_edge(0, 1) assert nx.harmonic_diameter(DG) == 2 def test_harmonic_diameter_weighted_paths(self): G = nx.star_graph(3) # check defaults G.add_weighted_edges_from([(*e, 1) for i, e in enumerate(G.edges)], "weight") assert nx.harmonic_diameter(G) == pytest.approx(1.333333) assert nx.harmonic_diameter(G, weight="weight") == pytest.approx(1.333333) # check impact of weights and alternate weight name G.add_weighted_edges_from([(*e, i) for i, e in enumerate(G.edges)], "dist") assert nx.harmonic_diameter(G, weight="dist") == pytest.approx(1.8) def test_radius(self): assert nx.radius(self.G) == 4 def test_periphery(self): assert set(nx.periphery(self.G)) == {1, 4, 13, 16} def test_center_simple_tree(self): G = nx.Graph([(1, 2), (1, 3), (2, 4), (2, 5)]) assert nx.center(G) == [1, 2] @pytest.mark.parametrize("r", range(2, 5)) @pytest.mark.parametrize("h", range(1, 5)) def test_center_balanced_tree(self, r, h): G = nx.balanced_tree(r, h) assert nx.center(G) == [0] def test_center(self): assert set(nx.center(self.G)) == {6, 7, 10, 11} @pytest.mark.parametrize("n", [1, 2, 99, 100]) def test_center_path_graphs(self, n): G = nx.path_graph(n) expected = {(n - 1) // 2, math.ceil((n - 1) / 2)} assert set(nx.center(G)) == expected def test_bound_diameter(self): assert nx.diameter(self.G, usebounds=True) == 6 def test_bound_radius(self): assert nx.radius(self.G, usebounds=True) == 4 def test_bound_periphery(self): result = {1, 4, 13, 16} assert set(nx.periphery(self.G, usebounds=True)) == result def test_bound_center(self): result = {6, 7, 10, 11} assert set(nx.center(self.G, usebounds=True)) == result def test_radius_exception(self): G = nx.Graph() G.add_edge(1, 2) G.add_edge(3, 4) pytest.raises(nx.NetworkXError, nx.diameter, G) def test_eccentricity_infinite(self): with pytest.raises(nx.NetworkXError): G = nx.Graph([(1, 2), (3, 4)]) e = nx.eccentricity(G) def test_eccentricity_undirected_not_connected(self): with pytest.raises(nx.NetworkXError): G = nx.Graph([(1, 2), (3, 4)]) e = nx.eccentricity(G, sp=1) def test_eccentricity_directed_weakly_connected(self): with pytest.raises(nx.NetworkXError): DG = nx.DiGraph([(1, 2), (1, 3)]) nx.eccentricity(DG)
TestDistance
python
getsentry__sentry
tests/sentry/integrations/api/endpoints/test_data_forwarding.py
{ "start": 283, "end": 889 }
class ____(APITestCase): endpoint = "sentry-api-0-organization-forwarding" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) def get_response(self, *args, **kwargs): """ Override get_response to always add the required feature flag. """ with self.feature( { "organizations:data-forwarding-revamp-access": True, "organizations:data-forwarding": True, } ): return super().get_response(*args, **kwargs) @region_silo_test
DataForwardingIndexEndpointTest
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_eth_address_positive_balance.py
{ "start": 1061, "end": 2097 }
class ____(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.valid_eth_address_positive_balance" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _pandas(cls, column, **kwargs): return column.apply(lambda x: has_eth_address_positive_balance(x)) # This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine # @column_condition_partial(engine=SqlAlchemyExecutionEngine) # def _sqlalchemy(cls, column, _dialect, **kwargs): # raise NotImplementedError # This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine # @column_condition_partial(engine=SparkDFExecutionEngine) # def _spark(cls, column, **kwargs): # raise NotImplementedError # This class defines the Expectation itself
ColumnValuesEthAddressPositiveBalance
python
pytorch__pytorch
test/torch_np/numpy_tests/linalg/test_linalg.py
{ "start": 57005, "end": 57091 }
class ____(_TestNormBase, TestCase): dt = np.double dec = 12
_TestNormDoubleBase
python
ethereum__web3.py
web3/providers/persistent/request_processor.py
{ "start": 1081, "end": 13647 }
class ____: _subscription_queue_synced_with_ws_stream: bool = False # set by the subscription manager when it is initialized _subscription_container: SubscriptionContainer | None = None def __init__( self, provider: "PersistentConnectionProvider", subscription_response_queue_size: int = 500, request_information_cache_size: int = 500, ) -> None: self._provider = provider self._request_information_cache: SimpleCache = SimpleCache( request_information_cache_size ) self._request_response_cache: SimpleCache = SimpleCache(500) self._subscription_response_queue: TaskReliantQueue[ RPCResponse | TaskNotRunning ] = TaskReliantQueue(maxsize=subscription_response_queue_size) self._handler_subscription_queue: TaskReliantQueue[ RPCResponse | TaskNotRunning | SubscriptionProcessingFinished ] = TaskReliantQueue(maxsize=subscription_response_queue_size) @property def active_subscriptions(self) -> dict[str, Any]: return { value.subscription_id: {"params": value.params} for key, value in self._request_information_cache.items() if value.method == "eth_subscribe" } # request information cache def cache_request_information( self, request_id: RPCId | None, method: RPCEndpoint, params: Any, response_formatters: tuple[ dict[str, Callable[..., Any]] | Callable[..., Any], Callable[..., Any], Callable[..., Any], ], ) -> str | None: cached_requests_key = generate_cache_key((method, params)) if cached_requests_key in self._provider._request_cache._data: cached_response = self._provider._request_cache._data[cached_requests_key] cached_response_id = cached_response.get("id") cache_key = generate_cache_key(cached_response_id) if cache_key in self._request_information_cache: self._provider.logger.debug( "This is a cached request, not caching request info because it is " "not unique:\n method=%s,\n params=%s", method, params, ) return None if request_id is None: if not self._provider._is_batching: raise Web3ValueError( "Request id must be provided when not batching requests." ) cache_key = generate_cache_key(request_id) request_info = RequestInformation( method, params, response_formatters, ) self._provider.logger.debug( "Caching request info:\n request_id=%s,\n" " cache_key=%s,\n request_info=%s", request_id, cache_key, request_info.__dict__, ) self._request_information_cache.cache( cache_key, request_info, ) if self._request_information_cache.is_full(): self._provider.logger.warning( "Request information cache is full. This may result in unexpected " "behavior. Consider increasing the ``request_information_cache_size`` " "on the provider." ) return cache_key def pop_cached_request_information( self, cache_key: str ) -> RequestInformation | None: request_info = self._request_information_cache.pop(cache_key) if request_info is not None: self._provider.logger.debug( "Request info popped from cache:\n" " cache_key=%s,\n request_info=%s", cache_key, request_info.__dict__, ) return request_info def get_request_information_for_response( self, response: RPCResponse, ) -> RequestInformation: if "method" in response and response["method"] == "eth_subscription": if "params" not in response: raise Web3ValueError("Subscription response must have params field") if "subscription" not in response["params"]: raise Web3ValueError( "Subscription response params must have subscription field" ) # retrieve the request info from the cache using the subscription id cache_key = generate_cache_key(response["params"]["subscription"]) request_info = ( # don't pop the request info from the cache, since we need to keep it # to process future subscription responses # i.e. subscription request information remains in the cache self._request_information_cache.get_cache_entry(cache_key) ) else: # retrieve the request info from the cache using the response id cache_key = generate_cache_key(response["id"]) if response in self._provider._request_cache._data.values(): request_info = ( # don't pop the request info from the cache, since we need to keep # it to process future responses # i.e. request information remains in the cache self._request_information_cache.get_cache_entry(cache_key) ) else: request_info = ( # pop the request info from the cache since we don't need to keep it # this keeps the cache size bounded self.pop_cached_request_information(cache_key) ) if ( request_info is not None and request_info.method == "eth_unsubscribe" and response.get("result") is True ): # if successful unsubscribe request, remove the subscription request # information from the cache since it is no longer needed subscription_id = request_info.params[0] subscribe_cache_key = generate_cache_key(subscription_id) self.pop_cached_request_information(subscribe_cache_key) return request_info def append_middleware_response_processor( self, response: RPCResponse, middleware_response_processor: Callable[..., Any], ) -> None: response_id = response.get("id", None) if response_id is not None: cache_key = generate_cache_key(response_id) cached_request_info_for_id: RequestInformation = ( self._request_information_cache.get_cache_entry(cache_key) ) if cached_request_info_for_id is not None: cached_request_info_for_id.middleware_response_processors.append( middleware_response_processor ) else: self._provider.logger.debug( "No cached request info for response id `%s`. Cannot " "append middleware response processor for response: %s", response_id, response, ) else: self._provider.logger.debug( "No response `id` in response. Cannot append middleware response " "processor for response: %s", response, ) # raw response cache def _is_batch_response(self, raw_response: list[RPCResponse] | RPCResponse) -> bool: return isinstance(raw_response, list) or ( isinstance(raw_response, dict) and raw_response.get("id") is None and self._provider._is_batching ) async def cache_raw_response( self, raw_response: Any, subscription: bool = False ) -> None: if subscription: if self._subscription_response_queue.full(): self._provider.logger.debug( "Subscription queue is full. Waiting for provider to consume " "messages before caching." ) self._provider._listen_event.clear() await self._provider._listen_event.wait() self._provider.logger.debug( "Caching subscription response:\n response=%s", raw_response ) subscription_id = raw_response.get("params", {}).get("subscription") sub_container = self._subscription_container if sub_container and sub_container.get_handler_subscription_by_id( subscription_id ): # if the subscription has a handler, put it in the handler queue await self._handler_subscription_queue.put(raw_response) else: # otherwise, put it in the subscription response queue so a response # can be yielded by the message stream await self._subscription_response_queue.put(raw_response) elif self._is_batch_response(raw_response): # Since only one batch should be in the cache at all times, we use a # constant cache key for the batch response. cache_key = generate_cache_key(BATCH_REQUEST_ID) self._provider.logger.debug( "Caching batch response:\n cache_key=%s,\n response=%s", cache_key, raw_response, ) self._request_response_cache.cache(cache_key, raw_response) else: response_id = raw_response.get("id") cache_key = generate_cache_key(response_id) self._provider.logger.debug( "Caching response:\n response_id=%s,\n" " cache_key=%s,\n response=%s", response_id, cache_key, raw_response, ) self._request_response_cache.cache(cache_key, raw_response) async def pop_raw_response( self, cache_key: str = None, subscription: bool = False ) -> Any: if subscription: qsize = self._subscription_response_queue.qsize() raw_response = await self._subscription_response_queue.get() if not self._provider._listen_event.is_set(): self._provider._listen_event.set() if qsize == 0: if not self._subscription_queue_synced_with_ws_stream: self._subscription_queue_synced_with_ws_stream = True self._provider.logger.info( "Subscription response queue synced with websocket message " "stream." ) else: if self._subscription_queue_synced_with_ws_stream: self._subscription_queue_synced_with_ws_stream = False self._provider.logger.info( "Subscription response queue has %s subscriptions. " "Processing as FIFO.", qsize, ) self._provider.logger.debug( "Subscription response popped from queue to be processed:\n" " raw_response=%s", raw_response, ) else: if not cache_key: raise Web3ValueError( "Must provide cache key when popping a non-subscription response." ) raw_response = self._request_response_cache.pop(cache_key) if raw_response is not None: self._provider.logger.debug( "Cached response popped from cache to be processed:\n" " cache_key=%s,\n raw_response=%s", cache_key, raw_response, ) return raw_response # cache methods def _reset_handler_subscription_queue(self) -> None: self._handler_subscription_queue = TaskReliantQueue( maxsize=self._handler_subscription_queue.maxsize ) def clear_caches(self) -> None: """Clear the request processor caches.""" self._request_information_cache.clear() self._request_response_cache.clear() self._subscription_response_queue = TaskReliantQueue( maxsize=self._subscription_response_queue.maxsize ) self._reset_handler_subscription_queue()
RequestProcessor
python
boto__boto3
boto3/dynamodb/conditions.py
{ "start": 5067, "end": 5138 }
class ____(ComparisonCondition): expression_operator = '<>'
NotEquals
python
spyder-ide__spyder
spyder/plugins/editor/api/run.py
{ "start": 364, "end": 792 }
class ____(TypedDict): """Editor supported run configuration schema.""" # Name of the plugin that is extending the editor supported run # configurations origin: str # Filename extension for which the editor should be able to provide # run configurations. extension: str # List of contexts for which the editor should produce run configurations. contexts: List[Context]
EditorRunConfiguration
python
keras-team__keras
keras/src/ops/linalg.py
{ "start": 299, "end": 1524 }
class ____(Operation): def __init__(self, upper=False, *, name=None): super().__init__(name=name) self.upper = upper def call(self, x): return _cholesky(x, self.upper) def compute_output_spec(self, x): _assert_2d(x) _assert_square(x) return KerasTensor(x.shape, x.dtype) @keras_export(["keras.ops.cholesky", "keras.ops.linalg.cholesky"]) def cholesky(x, upper=False): """Computes the Cholesky decomposition of a positive semi-definite matrix. Args: x: Input tensor of shape `(..., M, M)`. upper (bool): If True, returns the upper-triangular Cholesky factor. If False (default), returns the lower-triangular Cholesky factor. Returns: A tensor of shape `(..., M, M)` representing the Cholesky factor of `x`. """ if any_symbolic_tensors((x,)): return Cholesky(upper=upper).symbolic_call(x) return _cholesky(x, upper=upper) def _cholesky(x, upper=False): x = backend.convert_to_tensor(x) _assert_2d(x) _assert_square(x) try: return backend.linalg.cholesky(x, upper=upper) except Exception as e: raise ValueError(f"Cholesky decomposition failed: {e}")
Cholesky
python
getsentry__sentry
tests/sentry/manager/test_team_manager.py
{ "start": 142, "end": 2085 }
class ____(TestCase): def test_simple(self) -> None: user = self.create_user() org = self.create_organization() team = self.create_team(organization=org, name="Test") self.create_member(organization=org, user=user, teams=[team]) result = Team.objects.get_for_user(organization=org, user=user) assert result == [team] def test_simple_with_rpc_user(self) -> None: user = user_service.get_user(self.create_user().id) assert user is not None org = self.create_organization() team = self.create_team(organization=org, name="Test") self.create_member(organization=org, user_id=user.id, teams=[team]) result = Team.objects.get_for_user(organization=org, user=user) assert result == [team] def test_invalid_scope(self) -> None: user = self.create_user() org = self.create_organization() team = self.create_team(organization=org, name="Test") self.create_member(organization=org, user=user, teams=[team]) result = Team.objects.get_for_user(organization=org, user=user, scope="idontexist") assert result == [] def test_valid_scope(self) -> None: user = self.create_user() org = self.create_organization() team = self.create_team(organization=org, name="Test") self.create_member(organization=org, user=user, teams=[team]) result = Team.objects.get_for_user(organization=org, user=user, scope="project:read") assert result == [team] def test_user_no_access(self) -> None: user = self.create_user() user2 = self.create_user() org = self.create_organization() team = self.create_team(organization=org, name="Test") self.create_member(organization=org, user=user, teams=[team]) result = Team.objects.get_for_user(organization=org, user=user2) assert result == []
TeamManagerTest
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/bulk_persistence.py
{ "start": 12855, "end": 21890 }
class ____(_AbstractORMCompileState): is_dml_returning = True from_statement_ctx: Optional[_ORMFromStatementCompileState] = None @classmethod def _get_orm_crud_kv_pairs( cls, mapper, statement, kv_iterator, needs_to_be_cacheable ): core_get_crud_kv_pairs = UpdateDMLState._get_crud_kv_pairs for k, v in kv_iterator: k = coercions.expect(roles.DMLColumnRole, k) if isinstance(k, str): desc = _entity_namespace_key(mapper, k, default=NO_VALUE) if not isinstance(desc, PropComparator): yield ( coercions.expect(roles.DMLColumnRole, k), ( coercions.expect( roles.ExpressionElementRole, v, type_=sqltypes.NullType(), is_crud=True, ) if needs_to_be_cacheable else v ), ) else: yield from core_get_crud_kv_pairs( statement, desc._bulk_update_tuples(v), needs_to_be_cacheable, ) elif "entity_namespace" in k._annotations: k_anno = k._annotations attr = _entity_namespace_key( k_anno["entity_namespace"], k_anno["proxy_key"] ) assert isinstance(attr, PropComparator) yield from core_get_crud_kv_pairs( statement, attr._bulk_update_tuples(v), needs_to_be_cacheable, ) else: yield ( k, ( v if not needs_to_be_cacheable else coercions.expect( roles.ExpressionElementRole, v, type_=sqltypes.NullType(), is_crud=True, ) ), ) @classmethod def _get_dml_plugin_subject(cls, statement): plugin_subject = statement.table._propagate_attrs.get("plugin_subject") if ( not plugin_subject or not plugin_subject.mapper or plugin_subject is not statement._propagate_attrs["plugin_subject"] ): return None return plugin_subject @classmethod def _get_multi_crud_kv_pairs(cls, statement, kv_iterator): plugin_subject = cls._get_dml_plugin_subject(statement) if not plugin_subject: return UpdateDMLState._get_multi_crud_kv_pairs( statement, kv_iterator ) return [ dict( cls._get_orm_crud_kv_pairs( plugin_subject.mapper, statement, value_dict.items(), False ) ) for value_dict in kv_iterator ] @classmethod def _get_crud_kv_pairs(cls, statement, kv_iterator, needs_to_be_cacheable): assert ( needs_to_be_cacheable ), "no test coverage for needs_to_be_cacheable=False" plugin_subject = cls._get_dml_plugin_subject(statement) if not plugin_subject: return UpdateDMLState._get_crud_kv_pairs( statement, kv_iterator, needs_to_be_cacheable ) return list( cls._get_orm_crud_kv_pairs( plugin_subject.mapper, statement, kv_iterator, needs_to_be_cacheable, ) ) @classmethod def get_entity_description(cls, statement): ext_info = statement.table._annotations["parententity"] mapper = ext_info.mapper if ext_info.is_aliased_class: _label_name = ext_info.name else: _label_name = mapper.class_.__name__ return { "name": _label_name, "type": mapper.class_, "expr": ext_info.entity, "entity": ext_info.entity, "table": mapper.local_table, } @classmethod def get_returning_column_descriptions(cls, statement): def _ent_for_col(c): return c._annotations.get("parententity", None) def _attr_for_col(c, ent): if ent is None: return c proxy_key = c._annotations.get("proxy_key", None) if not proxy_key: return c else: return getattr(ent.entity, proxy_key, c) return [ { "name": c.key, "type": c.type, "expr": _attr_for_col(c, ent), "aliased": ent.is_aliased_class, "entity": ent.entity, } for c, ent in [ (c, _ent_for_col(c)) for c in statement._all_selected_columns ] ] def _setup_orm_returning( self, compiler, orm_level_statement, dml_level_statement, dml_mapper, *, use_supplemental_cols=True, ): """establish ORM column handlers for an INSERT, UPDATE, or DELETE which uses explicit returning(). called within compilation level create_for_statement. The _return_orm_returning() method then receives the Result after the statement was executed, and applies ORM loading to the state that we first established here. """ if orm_level_statement._returning: fs = FromStatement( orm_level_statement._returning, dml_level_statement, _adapt_on_names=False, ) fs = fs.execution_options(**orm_level_statement._execution_options) fs = fs.options(*orm_level_statement._with_options) self.select_statement = fs self.from_statement_ctx = fsc = ( _ORMFromStatementCompileState.create_for_statement( fs, compiler ) ) fsc.setup_dml_returning_compile_state(dml_mapper) dml_level_statement = dml_level_statement._generate() dml_level_statement._returning = () cols_to_return = [c for c in fsc.primary_columns if c is not None] # since we are splicing result sets together, make sure there # are columns of some kind returned in each result set if not cols_to_return: cols_to_return.extend(dml_mapper.primary_key) if use_supplemental_cols: dml_level_statement = dml_level_statement.return_defaults( # this is a little weird looking, but by passing # primary key as the main list of cols, this tells # return_defaults to omit server-default cols (and # actually all cols, due to some weird thing we should # clean up in crud.py). # Since we have cols_to_return, just return what we asked # for (plus primary key, which ORM persistence needs since # we likely set bookkeeping=True here, which is another # whole thing...). We dont want to clutter the # statement up with lots of other cols the user didn't # ask for. see #9685 *dml_mapper.primary_key, supplemental_cols=cols_to_return, ) else: dml_level_statement = dml_level_statement.returning( *cols_to_return ) return dml_level_statement @classmethod def _return_orm_returning( cls, session, statement, params, execution_options, bind_arguments, result, ): execution_context = result.context compile_state = execution_context.compiled.compile_state if ( compile_state.from_statement_ctx and not compile_state.from_statement_ctx.compile_options._is_star ): load_options = execution_options.get( "_sa_orm_load_options", QueryContext.default_load_options ) querycontext = QueryContext( compile_state.from_statement_ctx, compile_state.select_statement, statement, params, session, load_options, execution_options, bind_arguments, ) return loading.instances(result, querycontext) else: return result
_ORMDMLState
python
getsentry__sentry
src/sentry/utils/rust.py
{ "start": 6244, "end": 6596 }
class ____(Integration): identifier = "rust_info" @staticmethod def setup_once(): @add_global_event_processor def processor(event, hint): if sentry_sdk.get_client().get_integration(RustInfoIntegration) is None: return event return merge_rust_info_frames(event, hint)
RustInfoIntegration
python
pytorch__pytorch
torch/distributed/elastic/utils/data/elastic_distributed_sampler.py
{ "start": 493, "end": 3056 }
class ____(DistributedSampler[T]): """ Sampler that restricts data loading to a subset of the dataset for elastic training. It is especially useful in conjunction with :class:`torch.nn.parallel.DistributedDataParallel`. In such case, each process can pass a DistributedSampler instance as a DataLoader sampler, and load a subset of the original dataset that is exclusive to it. .. note:: Dataset is assumed to be of constant size. Args: dataset: Dataset used for sampling. num_replicas (optional): Number of processes participating in distributed training. rank (optional): Rank of the current process within num_replicas. start_index (optional): Which index of the dataset to start sampling from """ def __init__( self, dataset: Dataset[T], num_replicas: int | None = None, rank: int | None = None, start_index: int = 0, ): super().__init__(dataset=dataset, num_replicas=num_replicas, rank=rank) if not isinstance(dataset, Sized): raise TypeError("Dataset must be an instance of collections.abc.Sized") # Cast to Sized for mypy # pyrefly: ignore [redundant-cast] sized_dataset = cast(Sized, dataset) if start_index >= len(sized_dataset): raise ValueError( f"Start index {start_index} should be less than dataset size {len(sized_dataset)}" ) self.start_index = start_index sized_dataset = cast(Sized, self.dataset) self.num_samples = math.ceil( float(len(sized_dataset) - self.start_index) / self.num_replicas ) self.total_size = self.num_samples * self.num_replicas def __iter__(self) -> Iterator[T]: # deterministically shuffle based on epoch g = torch.Generator() g.manual_seed(self.epoch) sized_dataset = cast(Sized, self.dataset) indices = ( torch.randperm(len(sized_dataset) - self.start_index, generator=g) .add(self.start_index) .tolist() ) # add extra samples to make it evenly divisible indices += indices[: (self.total_size - len(indices))] assert len(indices) == self.total_size # subsample indices = indices[self.rank : self.total_size : self.num_replicas] assert len(indices) == self.num_samples return iter(indices) def __len__(self) -> int: return self.num_samples
ElasticDistributedSampler
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/functions.py
{ "start": 27156, "end": 28870 }
class ____(BinaryExpression[Any]): _traverse_internals = [ ("sql_function", InternalTraversal.dp_clauseelement), ("left_index", InternalTraversal.dp_plain_obj), ("right_index", InternalTraversal.dp_plain_obj), ("modifiers", InternalTraversal.dp_plain_dict), ] sql_function: FunctionElement[Any] left_index: int right_index: int def _gen_cache_key(self, anon_map: Any, bindparams: Any) -> Any: return ColumnElement._gen_cache_key(self, anon_map, bindparams) def __init__( self, fn: FunctionElement[Any], left_index: int, right_index: int ) -> None: self.sql_function = fn self.left_index = left_index self.right_index = right_index self.operator = operators.function_as_comparison_op self.type = sqltypes.BOOLEANTYPE self.negate = None self._is_implicitly_boolean = True self.modifiers = util.immutabledict({}) @property def left_expr(self) -> ColumnElement[Any]: return self.sql_function.clauses.clauses[self.left_index - 1] @left_expr.setter def left_expr(self, value: ColumnElement[Any]) -> None: self.sql_function.clauses.clauses[self.left_index - 1] = value @property def right_expr(self) -> ColumnElement[Any]: return self.sql_function.clauses.clauses[self.right_index - 1] @right_expr.setter def right_expr(self, value: ColumnElement[Any]) -> None: self.sql_function.clauses.clauses[self.right_index - 1] = value if not TYPE_CHECKING: # mypy can't accommodate @property to replace an instance # variable left = left_expr right = right_expr
FunctionAsBinary
python
celery__celery
t/unit/events/test_state.py
{ "start": 7911, "end": 10427 }
class ____: def test_equality(self): assert Task(uuid='foo').uuid == 'foo' assert Task(uuid='foo') == Task(uuid='foo') assert Task(uuid='foo') != Task(uuid='bar') assert hash(Task(uuid='foo')) == hash(Task(uuid='foo')) assert hash(Task(uuid='foo')) != hash(Task(uuid='bar')) def test_info(self): task = Task(uuid='abcdefg', name='tasks.add', args='(2, 2)', kwargs='{}', retries=2, result=42, eta=1, runtime=0.0001, expires=1, parent_id='bdefc', root_id='dedfef', foo=None, exception=1, received=time() - 10, started=time() - 8, exchange='celery', routing_key='celery', succeeded=time()) assert sorted(list(task._info_fields)) == sorted(task.info().keys()) assert (sorted(list(task._info_fields + ('received',))) == sorted(task.info(extra=('received',)))) assert (sorted(['args', 'kwargs']) == sorted(task.info(['args', 'kwargs']).keys())) assert not list(task.info('foo')) def test_reduce_direct(self): task = Task(uuid='uuid', name='tasks.add', args='(2, 2)') fun, args = task.__reduce__() task2 = fun(*args) assert task == task2 def test_ready(self): task = Task(uuid='abcdefg', name='tasks.add') task.event('received', time(), time()) assert not task.ready task.event('succeeded', time(), time()) assert task.ready def test_sent(self): task = Task(uuid='abcdefg', name='tasks.add') task.event('sent', time(), time()) assert task.state == states.PENDING def test_merge(self): task = Task() task.event('failed', time(), time()) task.event('started', time(), time()) task.event('received', time(), time(), { 'name': 'tasks.add', 'args': (2, 2), }) assert task.state == states.FAILURE assert task.name == 'tasks.add' assert task.args == (2, 2) task.event('retried', time(), time()) assert task.state == states.RETRY def test_repr(self): assert repr(Task(uuid='xxx', name='tasks.add'))
test_Task
python
tornadoweb__tornado
tornado/test/auth_test.py
{ "start": 787, "end": 1385 }
class ____(RequestHandler, OpenIdMixin): def initialize(self, test): self._OPENID_ENDPOINT = test.get_url("/openid/server/authenticate") @gen.coroutine def get(self): if self.get_argument("openid.mode", None): user = yield self.get_authenticated_user( http_client=self.settings["http_client"] ) if user is None: raise Exception("user is None") self.finish(user) return res = self.authenticate_redirect() # type: ignore assert res is None
OpenIdClientLoginHandler
python
scipy__scipy
scipy/interpolate/tests/test_bsplines.py
{ "start": 27311, "end": 36347 }
class ____: @pytest.mark.parametrize('xval', [0.0, 1.0, 2.5, 4, 6.5, 7.0]) def test_insert(self, xval, xp): # insert a knot, incl edges (0.0, 7.0) and exactly at an existing knot (4.0) x = xp.arange(8, dtype=xp.float64) y = xp.sin(x)**3 spl = make_interp_spline(x, y, k=3) tck = (spl._t, spl._c, spl.k) spl_1f = BSpline(*insert(xval, tck)) # FITPACK spl_1 = spl.insert_knot(xval) xp_assert_close(spl_1.t, xp.asarray(spl_1f.t), atol=1e-15) xp_assert_close(spl_1.c, xp.asarray(spl_1f.c[:-spl.k-1]), atol=1e-15) # knot insertion preserves values, unless multiplicity >= k+1 xx = x if xval != x[-1] else x[:-1] xx = xp.concat((xx, 0.5*(x[1:] + x[:-1]))) xp_assert_close(spl(xx), spl_1(xx), atol=1e-15) # ... repeat with ndim > 1 y1 = xp.cos(x)**3 spl_y1 = make_interp_spline(x, y1, k=3) spl_yy = make_interp_spline(x, xp.stack((y, y1), axis=1), k=3) spl_yy1 = spl_yy.insert_knot(xval) xp_assert_close(spl_yy1.t, spl_1.t, atol=1e-15) xp_assert_close( spl_yy1.c, xp.stack((spl.insert_knot(xval).c, spl_y1.insert_knot(xval).c), axis=1), atol=1e-15 ) xx = x if xval != x[-1] else x[:-1] xx = xp.concat((xx, 0.5*(x[1:] + x[:-1]))) xp_assert_close(spl_yy(xx), spl_yy1(xx), atol=1e-15) @pytest.mark.parametrize( 'xval, m', [(0.0, 2), (1.0, 3), (1.5, 5), (4, 2), (7.0, 2)] ) def test_insert_multi(self, xval, m, xp): x = xp.arange(8, dtype=xp.float64) y = xp.sin(x)**3 spl = make_interp_spline(x, y, k=3) spl_1f = BSpline(*insert(xval, (spl._t, spl._c, spl.k), m=m)) spl_1 = spl.insert_knot(xval, m) xp_assert_close(spl_1.t, xp.asarray(spl_1f.t), atol=1e-15) xp_assert_close(spl_1.c, xp.asarray(spl_1f.c[:-spl.k-1]), atol=1e-15) xx = x if xval != x[-1] else x[:-1] xx = xp.concat((xx, 0.5*(x[1:] + x[:-1]))) xp_assert_close(spl(xx), spl_1(xx), atol=1e-15) def test_insert_random(self, xp): rng = np.random.default_rng(12345) n, k = 11, 3 t = xp.asarray(np.sort(rng.uniform(size=n+k+1))) c = xp.asarray(rng.uniform(size=(n, 3, 2))) spl = BSpline(t, c, k) xv = xp.asarray(rng.uniform(low=t[k+1], high=t[-k-1])) spl_1 = spl.insert_knot(xv) xx = xp.asarray(rng.uniform(low=t[k+1], high=t[-k-1], size=33)) xp_assert_close(spl(xx), spl_1(xx), atol=1e-15) @pytest.mark.parametrize('xv', [0, 0.1, 2.0, 4.0, 4.5, # l.h. edge 5.5, 6.0, 6.1, 7.0] # r.h. edge ) def test_insert_periodic(self, xv, xp): x = xp.arange(8, dtype=xp.float64) y = xp.sin(x)**3 t, c, k = splrep(x, y, k=3) t, c = map(xp.asarray, (t, c)) spl = BSpline(t, c, k, extrapolate="periodic") spl_1 = spl.insert_knot(xv) tf, cf, k = insert(xv, spl.tck, per=True) xp_assert_close(spl_1.t, xp.asarray(tf), atol=1e-15) xp_assert_close(spl_1.c[:-k-1], xp.asarray(cf[:-k-1]), atol=1e-15) xx_np = np.random.default_rng(1234).uniform(low=0, high=7, size=41) xx = xp.asarray(xx_np) xp_assert_close(spl_1(xx), xp.asarray(splev(xx_np, (tf, cf, k))), atol=1e-15) @pytest.mark.parametrize('extrapolate', [None, 'periodic']) def test_complex(self, extrapolate, xp): x = xp.arange(8, dtype=xp.float64) * 2 * np.pi y_re, y_im = xp.sin(x), xp.cos(x) spl = make_interp_spline(x, y_re + 1j*y_im, k=3) spl.extrapolate = extrapolate spl_re = make_interp_spline(x, y_re, k=3) spl_re.extrapolate = extrapolate spl_im = make_interp_spline(x, y_im, k=3) spl_im.extrapolate = extrapolate xv = 3.5 spl_1 = spl.insert_knot(xv) spl_1re = spl_re.insert_knot(xv) spl_1im = spl_im.insert_knot(xv) xp_assert_close(spl_1.t, spl_1re.t, atol=1e-15) xp_assert_close(spl_1.t, spl_1im.t, atol=1e-15) xp_assert_close(spl_1.c, spl_1re.c + 1j*spl_1im.c, atol=1e-15) def test_insert_periodic_too_few_internal_knots(self): # both FITPACK and spl.insert_knot raise when there's not enough # internal knots to make a periodic extension. # Below the internal knots are 2, 3, , 4, 5 # ^ # 2, 3, 3.5, 4, 5 # so two knots from each side from the new one, while need at least # from either left or right. xv = 3.5 k = 3 t = np.array([0]*(k+1) + [2, 3, 4, 5] + [7]*(k+1)) c = np.ones(len(t) - k - 1) spl = BSpline(t, c, k, extrapolate="periodic") with assert_raises(ValueError): insert(xv, (t, c, k), per=True) with assert_raises(ValueError): spl.insert_knot(xv) def test_insert_no_extrap(self): k = 3 t = np.array([0]*(k+1) + [2, 3, 4, 5] + [7]*(k+1)) c = np.ones(len(t) - k - 1) spl = BSpline(t, c, k) with assert_raises(ValueError): spl.insert_knot(-1) with assert_raises(ValueError): spl.insert_knot(8) with assert_raises(ValueError): spl.insert_knot(3, m=0) def test_knots_multiplicity(): # Take a spline w/ random coefficients, throw in knots of varying # multiplicity. def check_splev(b, j, der=0, atol=1e-14, rtol=1e-14): # check evaluations against FITPACK, incl extrapolations t, c, k = b.tck x = np.unique(t) x = np.r_[t[0]-0.1, 0.5*(x[1:] + x[:1]), t[-1]+0.1] xp_assert_close(splev(x, (t, c, k), der), b(x, der), atol=atol, rtol=rtol, err_msg=f'der = {der} k = {b.k}') # test loop itself # [the index `j` is for interpreting the traceback in case of a failure] for k in [1, 2, 3, 4, 5]: b = _make_random_spline(k=k) for j, b1 in enumerate(_make_multiples(b)): check_splev(b1, j) for der in range(1, k+1): check_splev(b1, j, der, 1e-12, 1e-12) def _naive_B(x, k, i, t): """ Naive way to compute B-spline basis functions. Useful only for testing! computes B(x; t[i],..., t[i+k+1]) """ if k == 0: return 1.0 if t[i] <= x < t[i+1] else 0.0 if t[i+k] == t[i]: c1 = 0.0 else: c1 = (x - t[i])/(t[i+k] - t[i]) * _naive_B(x, k-1, i, t) if t[i+k+1] == t[i+1]: c2 = 0.0 else: c2 = (t[i+k+1] - x)/(t[i+k+1] - t[i+1]) * _naive_B(x, k-1, i+1, t) return (c1 + c2) def _naive_eval(x, t, c, k, *, xp): """ Naive B-spline evaluation. Useful only for testing! """ if x == t[k]: i = k else: i = xp.searchsorted(t, x) - 1 assert t[i] <= x <= t[i+1] assert i >= k and i < t.shape[0] - k return sum(c[i-j] * _naive_B(x, k, i-j, t) for j in range(0, k+1)) def _naive_eval_2(x, t, c, k, *, xp): """Naive B-spline evaluation, another way.""" n = t.shape[0] - (k+1) assert n >= k+1 assert c.shape[0] >= n assert t[k] <= x <= t[n] return sum(c[i] * _naive_B(x, k, i, t) for i in range(n)) def _sum_basis_elements(x, t, c, k): n = len(t) - (k+1) assert n >= k+1 assert c.shape[0] >= n s = 0. for i in range(n): b = BSpline.basis_element(t[i:i+k+2], extrapolate=False)(x) s += c[i] * np.nan_to_num(b) # zero out out-of-bounds elements return s def B_012(x, xp=np): """ A linear B-spline function B(x | 0, 1, 2).""" x = np.atleast_1d(x) result = np.piecewise(x, [(x < 0) | (x > 2), (x >= 0) & (x < 1), (x >= 1) & (x <= 2)], [lambda x: 0., lambda x: x, lambda x: 2.-x]) return xp.asarray(result) def B_0123(x, der=0): """A quadratic B-spline function B(x | 0, 1, 2, 3).""" x = np.atleast_1d(x) conds = [x < 1, (x > 1) & (x < 2), x > 2] if der == 0: funcs = [lambda x: x*x/2., lambda x: 3./4 - (x-3./2)**2, lambda x: (3.-x)**2 / 2] elif der == 2: funcs = [lambda x: 1., lambda x: -2., lambda x: 1.] else: raise ValueError(f'never be here: der={der}') pieces = np.piecewise(x, conds, funcs) return pieces def _make_random_spline(n=35, k=3, xp=np): rng = np.random.RandomState(123) t = np.sort(rng.random(n+k+1)) c = rng.random(n) t, c = xp.asarray(t), xp.asarray(c) return BSpline.construct_fast(t, c, k) def _make_multiples(b): """Increase knot multiplicity.""" c, k = b.c, b.k t1 = b.t.copy() t1[17:19] = t1[17] t1[22] = t1[21] yield BSpline(t1, c, k) t1 = b.t.copy() t1[:k+1] = t1[0] yield BSpline(t1, c, k) t1 = b.t.copy() t1[-k-1:] = t1[-1] yield BSpline(t1, c, k)
TestInsert
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/check_ops_test.py
{ "start": 76542, "end": 84666 }
class ____(test.TestCase): @test_util.run_in_graph_and_eager_modes def test_assert_shapes_sparse_tensor_scalar_target_success(self): sparse_float = sparse_tensor.SparseTensor( constant_op.constant([[]], dtypes.int64), constant_op.constant([42], dtypes.float32), constant_op.constant([], dtypes.int64)) assertion = check_ops.assert_shapes([(sparse_float, [])]) with ops.control_dependencies([assertion]): out = array_ops.identity(sparse_float) self.evaluate(out) def test_assert_shapes_sparse_tensor_nonscalar_target_fail(self): sparse_float = sparse_tensor.SparseTensor( constant_op.constant([[]], dtypes.int64), constant_op.constant([42], dtypes.float32), constant_op.constant([], dtypes.int64)) with self.assertRaisesRegex(ValueError, r"must have rank 2.*Received rank 0"): assertion = check_ops.assert_shapes([(sparse_float, [None, None])]) with ops.control_dependencies([assertion]): out = array_ops.identity(sparse_float) self.evaluate(out) @test_util.run_in_graph_and_eager_modes def test_assert_shapes_sparse_tensor_fully_specified_target_success(self): sparse_float = sparse_tensor.SparseTensor( constant_op.constant([[111], [232]], dtypes.int64), constant_op.constant([23.4, -43.2], dtypes.float32), constant_op.constant([500], dtypes.int64)) assertion = check_ops.assert_shapes([(sparse_float, [500])]) with ops.control_dependencies([assertion]): out = array_ops.identity(sparse_float) self.evaluate(out) @test_util.run_in_graph_and_eager_modes def test_assert_shapes_sparse_tensor_fully_specified_target_fail(self): sparse_float = sparse_tensor.SparseTensor( constant_op.constant([[111], [232]], dtypes.int64), constant_op.constant([23.4, -43.2], dtypes.float32), constant_op.constant([500], dtypes.int64)) with self.assertRaisesRegex(ValueError, r"dimension 0 must have size 499"): assertion = check_ops.assert_shapes([(sparse_float, [499])]) with ops.control_dependencies([assertion]): out = array_ops.identity(sparse_float) self.evaluate(out) @test_util.run_in_graph_and_eager_modes def test_assert_shapes_sparse_tensor_partially_specified_target_success(self): sparse_int = sparse_tensor.SparseTensor( constant_op.constant([[5, 6], [7, 8]], dtypes.int64), constant_op.constant([23, -43], dtypes.int32), constant_op.constant([30, 40], dtypes.int64)) assertion = check_ops.assert_shapes([(sparse_int, [None, 40])]) with ops.control_dependencies([assertion]): out = array_ops.identity(sparse_int) self.evaluate(out) @test_util.run_in_graph_and_eager_modes def test_assert_shapes_sparse_tensor_symbolic_match_success(self): sparse_int = sparse_tensor.SparseTensor( constant_op.constant([[5, 6, 7], [8, 9, 10]], dtypes.int64), constant_op.constant([23, -43], dtypes.int32), constant_op.constant([30, 30, 40], dtypes.int64)) assertion = check_ops.assert_shapes([(sparse_int, ["N", "N", "D"])]) with ops.control_dependencies([assertion]): out = array_ops.identity(sparse_int) self.evaluate(out) @test_util.run_in_graph_and_eager_modes def test_assert_shapes_sparse_tensor_partially_specified_target_fail(self): sparse_int = sparse_tensor.SparseTensor( constant_op.constant([[5, 6], [7, 8]], dtypes.int64), constant_op.constant([23, -43], dtypes.int32), constant_op.constant([30, 40], dtypes.int64)) with self.assertRaisesRegex(ValueError, r"dimension 1 must have size 41"): assertion = check_ops.assert_shapes([(sparse_int, [None, 41])]) with ops.control_dependencies([assertion]): out = array_ops.identity(sparse_int) self.evaluate(out) @test_util.run_in_graph_and_eager_modes def test_assert_shapes_sparse_tensor_wrong_rank_fail(self): sparse_int = sparse_tensor.SparseTensor( constant_op.constant([[5, 6], [7, 8]], dtypes.int64), constant_op.constant([23, -43], dtypes.int32), constant_op.constant([30, 40], dtypes.int64)) with self.assertRaisesRegex(ValueError, r"must have rank 3\..* Received rank 2"): assertion = check_ops.assert_shapes([(sparse_int, [None, None, 40])]) with ops.control_dependencies([assertion]): out = array_ops.identity(sparse_int) self.evaluate(out) @test_util.run_in_graph_and_eager_modes def test_assert_shapes_sparse_tensor_wrong_symbolic_match_fail(self): sparse_int = sparse_tensor.SparseTensor( constant_op.constant([[5, 6], [7, 8]], dtypes.int64), constant_op.constant([23, -43], dtypes.int32), constant_op.constant([30, 40], dtypes.int64)) with self.assertRaisesRegex(ValueError, r"dimension 1 must have size 30"): assertion = check_ops.assert_shapes([(sparse_int, ["D", "D"])]) with ops.control_dependencies([assertion]): out = array_ops.identity(sparse_int) self.evaluate(out) @test_util.run_in_graph_and_eager_modes def test_assert_shapes_sparse_tensor_multiple_assertions_success(self): sparse_scalar = sparse_tensor.SparseTensor( constant_op.constant([[]], dtypes.int64), constant_op.constant([42], dtypes.float32), constant_op.constant([], dtypes.int64)) sparse_2d = sparse_tensor.SparseTensor( constant_op.constant([[5, 6], [7, 8]], dtypes.int64), constant_op.constant([23, -43], dtypes.int32), constant_op.constant([30, 30], dtypes.int64)) assertion = check_ops.assert_shapes([(sparse_scalar, []), (sparse_2d, ["N", "N"])]) with ops.control_dependencies([assertion]): out = array_ops.identity(sparse_2d) self.evaluate(out) @test_util.run_in_graph_and_eager_modes def test_assert_shapes_sparse_tensor_multiple_assertions_fail(self): sparse_scalar = sparse_tensor.SparseTensor( constant_op.constant([[]], dtypes.int64), constant_op.constant([42], dtypes.float32), constant_op.constant([], dtypes.int64)) sparse_2d = sparse_tensor.SparseTensor( constant_op.constant([[5, 6], [7, 8]], dtypes.int64), constant_op.constant([23, -43], dtypes.int32), constant_op.constant([30, 40], dtypes.int64)) with self.assertRaisesRegex(ValueError, r"dimension 1 must have size 30"): assertion = check_ops.assert_shapes([(sparse_scalar, []), (sparse_2d, ["N", "N"])]) with ops.control_dependencies([assertion]): out = array_ops.identity(sparse_2d) self.evaluate(out) @test_util.run_in_graph_and_eager_modes def test_assert_shapes_sparse_tensor_mixed_dense_and_sparse_success(self): dense_scalar = constant_op.constant([42], dtypes.float32) sparse_2d = sparse_tensor.SparseTensor( constant_op.constant([[5, 6], [7, 8]], dtypes.int64), constant_op.constant([23, -43], dtypes.int32), constant_op.constant([30, 30], dtypes.int64)) assertion = check_ops.assert_shapes([(dense_scalar, []), (sparse_2d, ["N", "N"])]) with ops.control_dependencies([assertion]): out = array_ops.identity(sparse_2d) self.evaluate(out) @test_util.run_in_graph_and_eager_modes def test_assert_shapes_sparse_tensor_mixed_dense_and_sparse_fail(self): dense_scalar = constant_op.constant([42], dtypes.float32) sparse_2d = sparse_tensor.SparseTensor( constant_op.constant([[5, 6], [7, 8]], dtypes.int64), constant_op.constant([23, -43], dtypes.int32), constant_op.constant([30, 40], dtypes.int64)) with self.assertRaisesRegex(ValueError, r"dimension 1 must have size 30"): assertion = check_ops.assert_shapes([(dense_scalar, []), (sparse_2d, ["N", "N"])]) with ops.control_dependencies([assertion]): out = array_ops.identity(sparse_2d) self.evaluate(out)
AssertShapesSparseTensorTest
python
kamyu104__LeetCode-Solutions
Python/repeated-substring-pattern.py
{ "start": 29, "end": 898 }
class ____(object): def repeatedSubstringPattern(self, str): """ :type str: str :rtype: bool """ def getPrefix(pattern): prefix = [-1] * len(pattern) j = -1 for i in xrange(1, len(pattern)): while j > -1 and pattern[j + 1] != pattern[i]: j = prefix[j] if pattern[j + 1] == pattern[i]: j += 1 prefix[i] = j return prefix prefix = getPrefix(str) return prefix[-1] != -1 and \ (prefix[-1] + 1) % (len(str) - prefix[-1] - 1) == 0 def repeatedSubstringPattern2(self, str): """ :type str: str :rtype: bool """ if not str: return False ss = (str + str)[1:-1] return ss.find(str) != -1
Solution
python
Netflix__metaflow
test/core/tests/resume_succeeded_step.py
{ "start": 67, "end": 1646 }
class ____(MetaflowTest): """ Resuming from the succeeded end step should work """ RESUME = True # resuming on a successful step. RESUME_STEP = "a" PRIORITY = 3 SKIP_GRAPHS = [ "simple_switch", "nested_switch", "branch_in_switch", "foreach_in_switch", "switch_in_branch", "switch_in_foreach", "recursive_switch", "recursive_switch_inside_foreach", ] PARAMETERS = {"int_param": {"default": 123}} @steps(0, ["start"]) def step_start(self): if is_resumed(): self.data = "start_r" else: self.data = "start" @steps(0, ["singleton-end"], required=True) def step_end(self): if is_resumed(): self.data = "end_r" else: self.data = "end" raise ResumeFromHere() @steps(2, ["all"]) def step_all(self): if is_resumed(): self.data = "test_r" else: self.data = "test" def check_results(self, flow, checker): for step in flow: # task copied in resume will not have artifact with "_r" suffix. if step.name == "start": checker.assert_artifact(step.name, "data", "start") # resumed step will rerun and hence data will have this "_r" suffix. elif step.name == "a": checker.assert_artifact(step.name, "data", "test_r") elif step.name == "end": checker.assert_artifact(step.name, "data", "end_r")
ResumeSucceededStepTest
python
wandb__wandb
wandb/sdk/lib/redirect.py
{ "start": 2314, "end": 3846 }
class ____: """Class encapsulating a single character, its foreground, background and style attributes.""" __slots__ = ( "data", "fg", "bg", "bold", "italics", "underscore", "blink", "strikethrough", "reverse", ) def __init__( self, data=" ", fg=ANSI_FG_DEFAULT, bg=ANSI_BG_DEFAULT, bold=False, italics=False, underscore=False, blink=False, strikethrough=False, reverse=False, ): self.data = data self.fg = fg self.bg = bg self.bold = bold self.italics = italics self.underscore = underscore self.blink = blink self.strikethrough = strikethrough self.reverse = reverse def reset(self): # Reset everything other than data to defaults default = self.__class__() for k in self.__slots__[1:]: self[k] = default[k] def __getitem__(self, k): return getattr(self, k) def __setitem__(self, k, v): setattr(self, k, v) def copy(self, **kwargs): attrs = {} for k in self.__slots__: if k in kwargs: attrs[k] = kwargs[k] else: attrs[k] = self[k] return self.__class__(**attrs) def __eq__(self, other): for k in self.__slots__: if self[k] != other[k]: return False return True _defchar = Char()
Char
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_exceptions.py
{ "start": 2673, "end": 68408 }
class ____(__TestCase): def raise_catch(self, exc, excname): with self.subTest(exc=exc, excname=excname): try: raise exc("spam") except exc as err: buf1 = str(err) try: raise exc("spam") except exc as err: buf2 = str(err) self.assertEqual(buf1, buf2) self.assertEqual(exc.__name__, excname) def testRaising(self): self.raise_catch(AttributeError, "AttributeError") self.assertRaises(AttributeError, getattr, sys, "undefined_attribute") self.raise_catch(EOFError, "EOFError") fp = open(TESTFN, 'w', encoding="utf-8") fp.close() fp = open(TESTFN, 'r', encoding="utf-8") savestdin = sys.stdin try: try: import marshal marshal.loads(b'') except EOFError: pass finally: sys.stdin = savestdin fp.close() unlink(TESTFN) self.raise_catch(OSError, "OSError") self.assertRaises(OSError, open, 'this file does not exist', 'r') self.raise_catch(ImportError, "ImportError") self.assertRaises(ImportError, __import__, "undefined_module") self.raise_catch(IndexError, "IndexError") x = [] self.assertRaises(IndexError, x.__getitem__, 10) self.raise_catch(KeyError, "KeyError") x = {} self.assertRaises(KeyError, x.__getitem__, 'key') self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt") self.raise_catch(MemoryError, "MemoryError") self.raise_catch(NameError, "NameError") try: x = undefined_variable except NameError: pass self.raise_catch(OverflowError, "OverflowError") x = 1 for dummy in range(128): x += x # this simply shouldn't blow up self.raise_catch(RuntimeError, "RuntimeError") self.raise_catch(RecursionError, "RecursionError") self.raise_catch(SyntaxError, "SyntaxError") try: exec('/\n') except SyntaxError: pass self.raise_catch(IndentationError, "IndentationError") self.raise_catch(TabError, "TabError") try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n", '<string>', 'exec') except TabError: pass else: self.fail("TabError not raised") self.raise_catch(SystemError, "SystemError") self.raise_catch(SystemExit, "SystemExit") self.assertRaises(SystemExit, sys.exit, 0) self.raise_catch(TypeError, "TypeError") try: [] + () except TypeError: pass self.raise_catch(ValueError, "ValueError") self.assertRaises(ValueError, chr, 17<<16) self.raise_catch(ZeroDivisionError, "ZeroDivisionError") try: x = 1/0 except ZeroDivisionError: pass self.raise_catch(Exception, "Exception") try: x = 1/0 except Exception as e: pass self.raise_catch(StopAsyncIteration, "StopAsyncIteration") def testSyntaxErrorMessage(self): # make sure the right exception message is raised for each of # these code fragments def ckmsg(src, msg): with self.subTest(src=src, msg=msg): try: compile(src, '<fragment>', 'exec') except SyntaxError as e: if e.msg != msg: self.fail("expected %s, got %s" % (msg, e.msg)) else: self.fail("failed to get expected SyntaxError") s = '''if 1: try: continue except: pass''' ckmsg(s, "'continue' not properly in loop") ckmsg("continue\n", "'continue' not properly in loop") ckmsg("f'{6 0}'", "invalid syntax. Perhaps you forgot a comma?") def testSyntaxErrorMissingParens(self): def ckmsg(src, msg, exception=SyntaxError): try: compile(src, '<fragment>', 'exec') except exception as e: if e.msg != msg: self.fail("expected %s, got %s" % (msg, e.msg)) else: self.fail("failed to get expected SyntaxError") s = '''print "old style"''' ckmsg(s, "Missing parentheses in call to 'print'. Did you mean print(...)?") s = '''print "old style",''' ckmsg(s, "Missing parentheses in call to 'print'. Did you mean print(...)?") s = 'print f(a+b,c)' ckmsg(s, "Missing parentheses in call to 'print'. Did you mean print(...)?") s = '''exec "old style"''' ckmsg(s, "Missing parentheses in call to 'exec'. Did you mean exec(...)?") s = 'exec f(a+b,c)' ckmsg(s, "Missing parentheses in call to 'exec'. Did you mean exec(...)?") # Check that we don't incorrectly identify '(...)' as an expression to the right # of 'print' s = 'print (a+b,c) $ 42' ckmsg(s, "invalid syntax") s = 'exec (a+b,c) $ 42' ckmsg(s, "invalid syntax") # should not apply to subclasses, see issue #31161 s = '''if True:\nprint "No indent"''' ckmsg(s, "expected an indented block after 'if' statement on line 1", IndentationError) s = '''if True:\n print()\n\texec "mixed tabs and spaces"''' ckmsg(s, "inconsistent use of tabs and spaces in indentation", TabError) def check(self, src, lineno, offset, end_lineno=None, end_offset=None, encoding='utf-8'): with self.subTest(source=src, lineno=lineno, offset=offset): with self.assertRaises(SyntaxError) as cm: compile(src, '<fragment>', 'exec') self.assertEqual(cm.exception.lineno, lineno) self.assertEqual(cm.exception.offset, offset) if end_lineno is not None: self.assertEqual(cm.exception.end_lineno, end_lineno) if end_offset is not None: self.assertEqual(cm.exception.end_offset, end_offset) if cm.exception.text is not None: if not isinstance(src, str): src = src.decode(encoding, 'replace') line = src.split('\n')[lineno-1] self.assertIn(line, cm.exception.text) def test_error_offset_continuation_characters(self): check = self.check check('"\\\n"(1 for c in I,\\\n\\', 2, 2) def testSyntaxErrorOffset(self): check = self.check check('def fact(x):\n\treturn x!\n', 2, 10) check('1 +\n', 1, 4) check('def spam():\n print(1)\n print(2)', 3, 10) check('Python = "Python" +', 1, 20) check('Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +', 1, 20) check(b'# -*- coding: cp1251 -*-\nPython = "\xcf\xb3\xf2\xee\xed" +', 2, 19, encoding='cp1251') check(b'Python = "\xcf\xb3\xf2\xee\xed" +', 1, 10) check('x = "a', 1, 5) check('lambda x: x = 2', 1, 1) check('f{a + b + c}', 1, 2) check('[file for str(file) in []\n]', 1, 11) check('a = « hello » « world »', 1, 5) check('[\nfile\nfor str(file)\nin\n[]\n]', 3, 5) check('[file for\n str(file) in []]', 2, 2) check("ages = {'Alice'=22, 'Bob'=23}", 1, 9) check('match ...:\n case {**rest, "key": value}:\n ...', 2, 19) check("[a b c d e f]", 1, 2) check("for x yfff:", 1, 7) check("f(a for a in b, c)", 1, 3, 1, 15) check("f(a for a in b if a, c)", 1, 3, 1, 20) check("f(a, b for b in c)", 1, 6, 1, 18) check("f(a, b for b in c, d)", 1, 6, 1, 18) # Errors thrown by compile.c check('class foo:return 1', 1, 11) check('def f():\n continue', 2, 3) check('def f():\n break', 2, 3) check('try:\n pass\nexcept:\n pass\nexcept ValueError:\n pass', 3, 1) check('try:\n pass\nexcept*:\n pass', 3, 8) check('try:\n pass\nexcept*:\n pass\nexcept* ValueError:\n pass', 3, 8) # Errors thrown by the tokenizer check('(0x+1)', 1, 3) check('x = 0xI', 1, 6) check('0010 + 2', 1, 1) check('x = 32e-+4', 1, 8) check('x = 0o9', 1, 7) check('\u03b1 = 0xI', 1, 6) check(b'\xce\xb1 = 0xI', 1, 6) check(b'# -*- coding: iso8859-7 -*-\n\xe1 = 0xI', 2, 6, encoding='iso8859-7') check(b"""if 1: def foo(): ''' def bar(): pass def baz(): '''quux''' """, 9, 24) check("pass\npass\npass\n(1+)\npass\npass\npass", 4, 4) check("(1+)", 1, 4) check("[interesting\nfoo()\n", 1, 1) check(b"\xef\xbb\xbf#coding: utf8\nprint('\xe6\x88\x91')\n", 0, -1) check("""f''' { (123_a) }'''""", 3, 17) check("""f''' { f\"\"\" { (123_a) } \"\"\" }'''""", 5, 17) check('''f""" { 6 0="""''', 5, 13) check('b"fooжжж"'.encode(), 1, 1, 1, 10) # Errors thrown by symtable.c check('x = [(yield i) for i in range(3)]', 1, 7) check('def f():\n from _ import *', 2, 17) check('def f(x, x):\n pass', 1, 10) check('{i for i in range(5) if (j := 0) for j in range(5)}', 1, 38) check('def f(x):\n nonlocal x', 2, 3) check('def f(x):\n x = 1\n global x', 3, 3) check('nonlocal x', 1, 1) check('def f():\n global x\n nonlocal x', 2, 3) # Errors thrown by future.c check('from __future__ import doesnt_exist', 1, 24) check('from __future__ import braces', 1, 24) check('x=1\nfrom __future__ import division', 2, 1) check('foo(1=2)', 1, 5) check('def f():\n x, y: int', 2, 3) check('[*x for x in xs]', 1, 2) check('foo(x for x in range(10), 100)', 1, 5) check('for 1 in []: pass', 1, 5) check('(yield i) = 2', 1, 2) check('def f(*):\n pass', 1, 7) @unittest.skipIf(INT_MAX >= sys.maxsize, "Downcasting to int is safe for col_offset") @support.requires_resource('cpu') @support.bigmemtest(INT_MAX, memuse=2, dry_run=False) def testMemoryErrorBigSource(self, size): src = b"if True:\n%*s" % (size, b"pass") with self.assertRaisesRegex(OverflowError, "Parser column offset overflow"): compile(src, '<fragment>', 'exec') @cpython_only def testSettingException(self): # test that setting an exception at the C level works even if the # exception object can't be constructed. with torch._dynamo.error_on_graph_break(False): class BadException(Exception): def __init__(self_): raise RuntimeError("can't instantiate BadException") class InvalidException: pass @unittest.skipIf(_testcapi is None, "requires _testcapi") def test_capi1(): try: _testcapi.raise_exception(BadException, 1) except TypeError as err: co = err.__traceback__.tb_frame.f_code self.assertEqual(co.co_name, "test_capi1") self.assertTrue(co.co_filename.endswith('test_exceptions.py')) else: self.fail("Expected exception") @unittest.skipIf(_testcapi is None, "requires _testcapi") def test_capi2(): try: _testcapi.raise_exception(BadException, 0) except RuntimeError as err: tb = err.__traceback__.tb_next co = tb.tb_frame.f_code self.assertEqual(co.co_name, "__init__") self.assertTrue(co.co_filename.endswith('test_exceptions.py')) co2 = tb.tb_frame.f_back.f_code self.assertEqual(co2.co_name, "test_capi2") else: self.fail("Expected exception") @unittest.skipIf(_testcapi is None, "requires _testcapi") def test_capi3(): self.assertRaises(SystemError, _testcapi.raise_exception, InvalidException, 1) test_capi1() test_capi2() test_capi3() def test_WindowsError(self): try: WindowsError except NameError: pass else: self.assertIs(WindowsError, OSError) self.assertEqual(str(OSError(1001)), "1001") self.assertEqual(str(OSError(1001, "message")), "[Errno 1001] message") # POSIX errno (9 aka EBADF) is untranslated w = OSError(9, 'foo', 'bar') self.assertEqual(w.errno, 9) self.assertEqual(w.winerror, None) self.assertEqual(str(w), "[Errno 9] foo: 'bar'") # ERROR_PATH_NOT_FOUND (win error 3) becomes ENOENT (2) w = OSError(0, 'foo', 'bar', 3) self.assertEqual(w.errno, 2) self.assertEqual(w.winerror, 3) self.assertEqual(w.strerror, 'foo') self.assertEqual(w.filename, 'bar') self.assertEqual(w.filename2, None) self.assertEqual(str(w), "[WinError 3] foo: 'bar'") # Unknown win error becomes EINVAL (22) w = OSError(0, 'foo', None, 1001) self.assertEqual(w.errno, 22) self.assertEqual(w.winerror, 1001) self.assertEqual(w.strerror, 'foo') self.assertEqual(w.filename, None) self.assertEqual(w.filename2, None) self.assertEqual(str(w), "[WinError 1001] foo") # Non-numeric "errno" w = OSError('bar', 'foo') self.assertEqual(w.errno, 'bar') self.assertEqual(w.winerror, None) self.assertEqual(w.strerror, 'foo') self.assertEqual(w.filename, None) self.assertEqual(w.filename2, None) @unittest.skipUnless(sys.platform == 'win32', 'test specific to Windows') def test_windows_message(self): """Should fill in unknown error code in Windows error message""" ctypes = import_module('ctypes') # this error code has no message, Python formats it as hexadecimal code = 3765269347 with self.assertRaisesRegex(OSError, 'Windows Error 0x%x' % code): ctypes.pythonapi.PyErr_SetFromWindowsErr(code) def testAttributes(self): # test that exception attributes are happy exceptionList = [ (BaseException, (), {}, {'args' : ()}), (BaseException, (1, ), {}, {'args' : (1,)}), (BaseException, ('foo',), {}, {'args' : ('foo',)}), (BaseException, ('foo', 1), {}, {'args' : ('foo', 1)}), (SystemExit, ('foo',), {}, {'args' : ('foo',), 'code' : 'foo'}), (OSError, ('foo',), {}, {'args' : ('foo',), 'filename' : None, 'filename2' : None, 'errno' : None, 'strerror' : None}), (OSError, ('foo', 'bar'), {}, {'args' : ('foo', 'bar'), 'filename' : None, 'filename2' : None, 'errno' : 'foo', 'strerror' : 'bar'}), (OSError, ('foo', 'bar', 'baz'), {}, {'args' : ('foo', 'bar'), 'filename' : 'baz', 'filename2' : None, 'errno' : 'foo', 'strerror' : 'bar'}), (OSError, ('foo', 'bar', 'baz', None, 'quux'), {}, {'args' : ('foo', 'bar'), 'filename' : 'baz', 'filename2': 'quux'}), (OSError, ('errnoStr', 'strErrorStr', 'filenameStr'), {}, {'args' : ('errnoStr', 'strErrorStr'), 'strerror' : 'strErrorStr', 'errno' : 'errnoStr', 'filename' : 'filenameStr'}), (OSError, (1, 'strErrorStr', 'filenameStr'), {}, {'args' : (1, 'strErrorStr'), 'errno' : 1, 'strerror' : 'strErrorStr', 'filename' : 'filenameStr', 'filename2' : None}), (SyntaxError, (), {}, {'msg' : None, 'text' : None, 'filename' : None, 'lineno' : None, 'offset' : None, 'end_offset': None, 'print_file_and_line' : None}), (SyntaxError, ('msgStr',), {}, {'args' : ('msgStr',), 'text' : None, 'print_file_and_line' : None, 'msg' : 'msgStr', 'filename' : None, 'lineno' : None, 'offset' : None, 'end_offset': None}), (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr', 'textStr', 'endLinenoStr', 'endOffsetStr')), {}, {'offset' : 'offsetStr', 'text' : 'textStr', 'args' : ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr', 'textStr', 'endLinenoStr', 'endOffsetStr')), 'print_file_and_line' : None, 'msg' : 'msgStr', 'filename' : 'filenameStr', 'lineno' : 'linenoStr', 'end_lineno': 'endLinenoStr', 'end_offset': 'endOffsetStr'}), (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr', 'textStr', 'endLinenoStr', 'endOffsetStr', 'print_file_and_lineStr'), {}, {'text' : None, 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr', 'textStr', 'endLinenoStr', 'endOffsetStr', 'print_file_and_lineStr'), 'print_file_and_line' : None, 'msg' : 'msgStr', 'filename' : None, 'lineno' : None, 'offset' : None, 'end_lineno': None, 'end_offset': None}), (UnicodeError, (), {}, {'args' : (),}), (UnicodeEncodeError, ('ascii', 'a', 0, 1, 'ordinal not in range'), {}, {'args' : ('ascii', 'a', 0, 1, 'ordinal not in range'), 'encoding' : 'ascii', 'object' : 'a', 'start' : 0, 'reason' : 'ordinal not in range'}), (UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1, 'ordinal not in range'), {}, {'args' : ('ascii', bytearray(b'\xff'), 0, 1, 'ordinal not in range'), 'encoding' : 'ascii', 'object' : b'\xff', 'start' : 0, 'reason' : 'ordinal not in range'}), (UnicodeDecodeError, ('ascii', b'\xff', 0, 1, 'ordinal not in range'), {}, {'args' : ('ascii', b'\xff', 0, 1, 'ordinal not in range'), 'encoding' : 'ascii', 'object' : b'\xff', 'start' : 0, 'reason' : 'ordinal not in range'}), (UnicodeTranslateError, ("\u3042", 0, 1, "ouch"), {}, {'args' : ('\u3042', 0, 1, 'ouch'), 'object' : '\u3042', 'reason' : 'ouch', 'start' : 0, 'end' : 1}), (NaiveException, ('foo',), {}, {'args': ('foo',), 'x': 'foo'}), (SlottedNaiveException, ('foo',), {}, {'args': ('foo',), 'x': 'foo'}), (AttributeError, ('foo',), dict(name='name', obj='obj'), dict(args=('foo',), name='name', obj='obj')), ] try: # More tests are in test_WindowsError exceptionList.append( (WindowsError, (1, 'strErrorStr', 'filenameStr'), {}, {'args' : (1, 'strErrorStr'), 'strerror' : 'strErrorStr', 'winerror' : None, 'errno' : 1, 'filename' : 'filenameStr', 'filename2' : None}) ) except NameError: pass for exc, args, kwargs, expected in exceptionList: try: e = exc(*args, **kwargs) except: print(f"\nexc={exc!r}, args={args!r}", file=sys.stderr) # raise else: # Verify module name if not type(e).__name__.endswith('NaiveException'): self.assertEqual(type(e).__module__, 'builtins') # Verify no ref leaks in Exc_str() s = str(e) for checkArgName in expected: value = getattr(e, checkArgName) self.assertEqual(repr(value), repr(expected[checkArgName]), '%r.%s == %r, expected %r' % ( e, checkArgName, value, expected[checkArgName])) # test for pickling support for p in [pickle]: for protocol in range(p.HIGHEST_PROTOCOL + 1): s = p.dumps(e, protocol) new = p.loads(s) for checkArgName in expected: got = repr(getattr(new, checkArgName)) if exc == AttributeError and checkArgName == 'obj': # See GH-103352, we're not pickling # obj at this point. So verify it's None. want = repr(None) else: want = repr(expected[checkArgName]) self.assertEqual(got, want, 'pickled "%r", attribute "%s' % (e, checkArgName)) def test_setstate(self): e = Exception(42) e.blah = 53 self.assertEqual(e.args, (42,)) self.assertEqual(e.blah, 53) self.assertRaises(AttributeError, getattr, e, 'a') self.assertRaises(AttributeError, getattr, e, 'b') e.__setstate__({'a': 1 , 'b': 2}) self.assertEqual(e.args, (42,)) self.assertEqual(e.blah, 53) self.assertEqual(e.a, 1) self.assertEqual(e.b, 2) e.__setstate__({'a': 11, 'args': (1,2,3), 'blah': 35}) self.assertEqual(e.args, (1,2,3)) self.assertEqual(e.blah, 35) self.assertEqual(e.a, 11) self.assertEqual(e.b, 2) def test_invalid_setstate(self): e = Exception(42) with self.assertRaisesRegex(TypeError, "state is not a dictionary"): e.__setstate__(42) def test_notes(self): for e in [BaseException(1), Exception(2), ValueError(3)]: with self.subTest(e=e): self.assertFalse(hasattr(e, '__notes__')) e.add_note("My Note") self.assertEqual(e.__notes__, ["My Note"]) with self.assertRaises(TypeError): e.add_note(42) self.assertEqual(e.__notes__, ["My Note"]) e.add_note("Your Note") self.assertEqual(e.__notes__, ["My Note", "Your Note"]) del e.__notes__ self.assertFalse(hasattr(e, '__notes__')) e.add_note("Our Note") self.assertEqual(e.__notes__, ["Our Note"]) e.__notes__ = 42 self.assertEqual(e.__notes__, 42) with self.assertRaises(TypeError): e.add_note("will not work") self.assertEqual(e.__notes__, 42) def testWithTraceback(self): try: raise IndexError(4) except Exception as e: tb = e.__traceback__ e = BaseException().with_traceback(tb) self.assertIsInstance(e, BaseException) self.assertEqual(e.__traceback__, tb) e = IndexError(5).with_traceback(tb) self.assertIsInstance(e, IndexError) self.assertEqual(e.__traceback__, tb) with torch._dynamo.error_on_graph_break(False): class MyException(Exception): pass e = MyException().with_traceback(tb) self.assertIsInstance(e, MyException) self.assertEqual(e.__traceback__, tb) def testInvalidTraceback(self): try: Exception().__traceback__ = 5 except TypeError as e: self.assertIn("__traceback__ must be a traceback", str(e)) else: self.fail("No exception raised") def test_invalid_setattr(self): TE = TypeError exc = Exception() msg = "'int' object is not iterable" self.assertRaisesRegex(TE, msg, setattr, exc, 'args', 1) msg = "__traceback__ must be a traceback or None" self.assertRaisesRegex(TE, msg, setattr, exc, '__traceback__', 1) msg = "exception cause must be None or derive from BaseException" self.assertRaisesRegex(TE, msg, setattr, exc, '__cause__', 1) msg = "exception context must be None or derive from BaseException" self.assertRaisesRegex(TE, msg, setattr, exc, '__context__', 1) def test_invalid_delattr(self): TE = TypeError try: raise IndexError(4) except Exception as e: exc = e msg = "may not be deleted" self.assertRaisesRegex(TE, msg, delattr, exc, 'args') self.assertRaisesRegex(TE, msg, delattr, exc, '__traceback__') self.assertRaisesRegex(TE, msg, delattr, exc, '__cause__') self.assertRaisesRegex(TE, msg, delattr, exc, '__context__') def testNoneClearsTracebackAttr(self): try: raise IndexError(4) except Exception as e: tb = e.__traceback__ e = Exception() e.__traceback__ = tb e.__traceback__ = None self.assertEqual(e.__traceback__, None) def testChainingAttrs(self): e = Exception() self.assertIsNone(e.__context__) self.assertIsNone(e.__cause__) e = TypeError() self.assertIsNone(e.__context__) self.assertIsNone(e.__cause__) with torch._dynamo.error_on_graph_break(False): class MyException(OSError): pass e = MyException() self.assertIsNone(e.__context__) self.assertIsNone(e.__cause__) def testChainingDescriptors(self): try: raise Exception() except Exception as exc: e = exc self.assertIsNone(e.__context__) self.assertIsNone(e.__cause__) self.assertFalse(e.__suppress_context__) e.__context__ = NameError() e.__cause__ = None self.assertIsInstance(e.__context__, NameError) self.assertIsNone(e.__cause__) self.assertTrue(e.__suppress_context__) e.__suppress_context__ = False self.assertFalse(e.__suppress_context__) def testKeywordArgs(self): # test that builtin exception don't take keyword args, # but user-defined subclasses can if they want self.assertRaises(TypeError, BaseException, a=1) with torch._dynamo.error_on_graph_break(False): class DerivedException(BaseException): def __init__(self, fancy_arg): BaseException.__init__(self) self.fancy_arg = fancy_arg x = DerivedException(fancy_arg=42) self.assertEqual(x.fancy_arg, 42) @no_tracing def testInfiniteRecursion(self): def f(): return f() self.assertRaises(RecursionError, f) def g(): try: return g() except ValueError: return -1 self.assertRaises(RecursionError, g) def test_str(self): # Make sure both instances and classes have a str representation. self.assertTrue(str(Exception)) self.assertTrue(str(Exception('a'))) self.assertTrue(str(Exception('a', 'b'))) def test_exception_cleanup_names(self): # Make sure the local variable bound to the exception instance by # an "except" statement is only visible inside the except block. try: raise Exception() except Exception as e: self.assertIsInstance(e, Exception) self.assertNotIn('e', locals()) with self.assertRaises(UnboundLocalError): e def test_exception_cleanup_names2(self): # Make sure the cleanup doesn't break if the variable is explicitly deleted. try: raise Exception() except Exception as e: self.assertIsInstance(e, Exception) del e self.assertNotIn('e', locals()) with self.assertRaises(UnboundLocalError): e def testExceptionCleanupState(self): # Make sure exception state is cleaned up as soon as the except # block is left. See #2507 with torch._dynamo.error_on_graph_break(False): class MyException(Exception): def __init__(self, obj): self.obj = obj class MyObj: pass def inner_raising_func(): # Create some references in exception value and traceback local_ref = obj raise MyException(obj) # Qualified "except" with "as" obj = MyObj() wr = weakref.ref(obj) try: inner_raising_func() except MyException as e: pass obj = None gc_collect() # For PyPy or other GCs. obj = wr() self.assertIsNone(obj) # Qualified "except" without "as" obj = MyObj() wr = weakref.ref(obj) try: inner_raising_func() except MyException: pass obj = None gc_collect() # For PyPy or other GCs. obj = wr() self.assertIsNone(obj) # Bare "except" obj = MyObj() wr = weakref.ref(obj) try: inner_raising_func() except: pass obj = None gc_collect() # For PyPy or other GCs. obj = wr() self.assertIsNone(obj) # "except" with premature block leave obj = MyObj() wr = weakref.ref(obj) for i in [0]: try: inner_raising_func() except: break obj = None gc_collect() # For PyPy or other GCs. obj = wr() self.assertIsNone(obj) # "except" block raising another exception obj = MyObj() wr = weakref.ref(obj) try: try: inner_raising_func() except: raise KeyError except KeyError as e: # We want to test that the except block above got rid of # the exception raised in inner_raising_func(), but it # also ends up in the __context__ of the KeyError, so we # must clear the latter manually for our test to succeed. e.__context__ = None obj = None gc_collect() # For PyPy or other GCs. obj = wr() # guarantee no ref cycles on CPython (don't gc_collect) if check_impl_detail(cpython=False): gc_collect() self.assertIsNone(obj) # Some complicated construct obj = MyObj() wr = weakref.ref(obj) try: inner_raising_func() except MyException: try: try: raise finally: raise except MyException: pass obj = None if check_impl_detail(cpython=False): gc_collect() obj = wr() self.assertIsNone(obj) # Inside an exception-silencing "with" block with torch._dynamo.error_on_graph_break(False): class Context: def __enter__(self): return self def __exit__ (self, exc_type, exc_value, exc_tb): return True obj = MyObj() wr = weakref.ref(obj) with Context(): inner_raising_func() obj = None if check_impl_detail(cpython=False): gc_collect() obj = wr() self.assertIsNone(obj) def test_exception_target_in_nested_scope(self): # issue 4617: This used to raise a SyntaxError # "can not delete variable 'e' referenced in nested scope" def print_error(): e try: something except Exception as e: print_error() # implicit "del e" here def test_generator_leaking(self): # Test that generator exception state doesn't leak into the calling # frame def yield_raise(): try: raise KeyError("caught") except KeyError: yield sys.exception() yield sys.exception() yield sys.exception() g = yield_raise() self.assertIsInstance(next(g), KeyError) self.assertIsNone(sys.exception()) self.assertIsInstance(next(g), KeyError) self.assertIsNone(sys.exception()) self.assertIsNone(next(g)) # Same test, but inside an exception handler try: raise TypeError("foo") except TypeError: g = yield_raise() self.assertIsInstance(next(g), KeyError) self.assertIsInstance(sys.exception(), TypeError) self.assertIsInstance(next(g), KeyError) self.assertIsInstance(sys.exception(), TypeError) self.assertIsInstance(next(g), TypeError) del g self.assertIsInstance(sys.exception(), TypeError) def test_generator_leaking2(self): # See issue 12475. def g(): yield try: raise RuntimeError except RuntimeError: it = g() next(it) try: next(it) except StopIteration: pass self.assertIsNone(sys.exception()) def test_generator_leaking3(self): # See issue #23353. When gen.throw() is called, the caller's # exception state should be save and restored. def g(): try: yield except ZeroDivisionError: yield sys.exception() it = g() next(it) try: 1/0 except ZeroDivisionError as e: self.assertIs(sys.exception(), e) gen_exc = it.throw(e) self.assertIs(sys.exception(), e) self.assertIs(gen_exc, e) self.assertIsNone(sys.exception()) def test_generator_leaking4(self): # See issue #23353. When an exception is raised by a generator, # the caller's exception state should still be restored. def g(): try: 1/0 except ZeroDivisionError: yield sys.exception() raise it = g() try: raise TypeError except TypeError: # The caller's exception state (TypeError) is temporarily # saved in the generator. tp = type(next(it)) self.assertIs(tp, ZeroDivisionError) try: next(it) # We can't check it immediately, but while next() returns # with an exception, it shouldn't have restored the old # exception state (TypeError). except ZeroDivisionError as e: self.assertIs(sys.exception(), e) # We used to find TypeError here. self.assertIsNone(sys.exception()) def test_generator_doesnt_retain_old_exc(self): def g(): self.assertIsInstance(sys.exception(), RuntimeError) yield self.assertIsNone(sys.exception()) it = g() try: raise RuntimeError except RuntimeError: next(it) self.assertRaises(StopIteration, next, it) def test_generator_finalizing_and_sys_exception(self): # See #7173 def simple_gen(): yield 1 def run_gen(): gen = simple_gen() try: raise RuntimeError except RuntimeError: return next(gen) run_gen() gc_collect() self.assertIsNone(sys.exception()) def _check_generator_cleanup_exc_state(self, testfunc): # Issue #12791: exception state is cleaned up as soon as a generator # is closed (reference cycles are broken). with torch._dynamo.error_on_graph_break(False): class MyException(Exception): def __init__(self, obj): self.obj = obj class MyObj: pass def raising_gen(): try: raise MyException(obj) except MyException: yield obj = MyObj() wr = weakref.ref(obj) g = raising_gen() next(g) testfunc(g) g = obj = None gc_collect() # For PyPy or other GCs. obj = wr() self.assertIsNone(obj) def test_generator_throw_cleanup_exc_state(self): def do_throw(g): try: g.throw(RuntimeError()) except RuntimeError: pass self._check_generator_cleanup_exc_state(do_throw) def test_generator_close_cleanup_exc_state(self): def do_close(g): g.close() self._check_generator_cleanup_exc_state(do_close) def test_generator_del_cleanup_exc_state(self): def do_del(g): g = None self._check_generator_cleanup_exc_state(do_del) def test_generator_next_cleanup_exc_state(self): def do_next(g): try: next(g) except StopIteration: pass else: self.fail("should have raised StopIteration") self._check_generator_cleanup_exc_state(do_next) def test_generator_send_cleanup_exc_state(self): def do_send(g): try: g.send(None) except StopIteration: pass else: self.fail("should have raised StopIteration") self._check_generator_cleanup_exc_state(do_send) def test_3114(self): # Bug #3114: in its destructor, MyObject retrieves a pointer to # obsolete and/or deallocated objects. with torch._dynamo.error_on_graph_break(False): class MyObject: def __del__(self): nonlocal e e = sys.exception() e = () try: raise Exception(MyObject()) except: pass gc_collect() # For PyPy or other GCs. self.assertIsNone(e) def test_raise_does_not_create_context_chain_cycle(self): with torch._dynamo.error_on_graph_break(False): class A(Exception): pass class B(Exception): pass class C(Exception): pass # Create a context chain: # C -> B -> A # Then raise A in context of C. try: try: raise A except A as a_: a = a_ try: raise B except B as b_: b = b_ try: raise C except C as c_: c = c_ self.assertIsInstance(a, A) self.assertIsInstance(b, B) self.assertIsInstance(c, C) self.assertIsNone(a.__context__) self.assertIs(b.__context__, a) self.assertIs(c.__context__, b) raise a except A as e: exc = e # Expect A -> C -> B, without cycle self.assertIs(exc, a) self.assertIs(a.__context__, c) self.assertIs(c.__context__, b) self.assertIsNone(b.__context__) def test_no_hang_on_context_chain_cycle1(self): # See issue 25782. Cycle in context chain. def cycle(): try: raise ValueError(1) except ValueError as ex: ex.__context__ = ex raise TypeError(2) try: cycle() except Exception as e: exc = e self.assertIsInstance(exc, TypeError) self.assertIsInstance(exc.__context__, ValueError) self.assertIs(exc.__context__.__context__, exc.__context__) def test_no_hang_on_context_chain_cycle2(self): # See issue 25782. Cycle at head of context chain. with torch._dynamo.error_on_graph_break(False): class A(Exception): pass class B(Exception): pass class C(Exception): pass # Context cycle: # +-----------+ # V | # C --> B --> A with self.assertRaises(C) as cm: try: raise A() except A as _a: a = _a try: raise B() except B as _b: b = _b try: raise C() except C as _c: c = _c a.__context__ = c raise c self.assertIs(cm.exception, c) # Verify the expected context chain cycle self.assertIs(c.__context__, b) self.assertIs(b.__context__, a) self.assertIs(a.__context__, c) def test_no_hang_on_context_chain_cycle3(self): # See issue 25782. Longer context chain with cycle. with torch._dynamo.error_on_graph_break(False): class A(Exception): pass class B(Exception): pass class C(Exception): pass class D(Exception): pass class E(Exception): pass # Context cycle: # +-----------+ # V | # E --> D --> C --> B --> A with self.assertRaises(E) as cm: try: raise A() except A as _a: a = _a try: raise B() except B as _b: b = _b try: raise C() except C as _c: c = _c a.__context__ = c try: raise D() except D as _d: d = _d e = E() raise e self.assertIs(cm.exception, e) # Verify the expected context chain cycle self.assertIs(e.__context__, d) self.assertIs(d.__context__, c) self.assertIs(c.__context__, b) self.assertIs(b.__context__, a) self.assertIs(a.__context__, c) def test_context_of_exception_in_try_and_finally(self): try: try: te = TypeError(1) raise te finally: ve = ValueError(2) raise ve except Exception as e: exc = e self.assertIs(exc, ve) self.assertIs(exc.__context__, te) def test_context_of_exception_in_except_and_finally(self): try: try: te = TypeError(1) raise te except: ve = ValueError(2) raise ve finally: oe = OSError(3) raise oe except Exception as e: exc = e self.assertIs(exc, oe) self.assertIs(exc.__context__, ve) self.assertIs(exc.__context__.__context__, te) def test_context_of_exception_in_else_and_finally(self): try: try: pass except: pass else: ve = ValueError(1) raise ve finally: oe = OSError(2) raise oe except Exception as e: exc = e self.assertIs(exc, oe) self.assertIs(exc.__context__, ve) def test_unicode_change_attributes(self): # See issue 7309. This was a crasher. u = UnicodeEncodeError('baz', 'xxxxx', 1, 5, 'foo') self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: foo") u.end = 2 self.assertEqual(str(u), "'baz' codec can't encode character '\\x78' in position 1: foo") u.end = 5 u.reason = 0x345345345345345345 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: 965230951443685724997") u.encoding = 4000 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1-4: 965230951443685724997") u.start = 1000 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1000-4: 965230951443685724997") u = UnicodeDecodeError('baz', b'xxxxx', 1, 5, 'foo') self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: foo") u.end = 2 self.assertEqual(str(u), "'baz' codec can't decode byte 0x78 in position 1: foo") u.end = 5 u.reason = 0x345345345345345345 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: 965230951443685724997") u.encoding = 4000 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1-4: 965230951443685724997") u.start = 1000 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1000-4: 965230951443685724997") u = UnicodeTranslateError('xxxx', 1, 5, 'foo') self.assertEqual(str(u), "can't translate characters in position 1-4: foo") u.end = 2 self.assertEqual(str(u), "can't translate character '\\x78' in position 1: foo") u.end = 5 u.reason = 0x345345345345345345 self.assertEqual(str(u), "can't translate characters in position 1-4: 965230951443685724997") u.start = 1000 self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997") def test_unicode_errors_no_object(self): # See issue #21134. klasses = UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError for klass in klasses: self.assertEqual(str(klass.__new__(klass)), "") def test_unicode_error_str_does_not_crash(self): # Test that str(UnicodeError(...)) does not crash. # See https://github.com/python/cpython/issues/123378. for start, end, objlen in product( range(-5, 5), range(-5, 5), range(7), ): obj = 'a' * objlen with self.subTest('encode', objlen=objlen, start=start, end=end): exc = UnicodeEncodeError('utf-8', obj, start, end, '') self.assertIsInstance(str(exc), str) with self.subTest('translate', objlen=objlen, start=start, end=end): exc = UnicodeTranslateError(obj, start, end, '') self.assertIsInstance(str(exc), str) encoded = obj.encode() with self.subTest('decode', objlen=objlen, start=start, end=end): exc = UnicodeDecodeError('utf-8', encoded, start, end, '') self.assertIsInstance(str(exc), str) @no_tracing def test_badisinstance(self): # Bug #2542: if issubclass(e, MyException) raises an exception, # it should be ignored with torch._dynamo.error_on_graph_break(False): class Meta(type): def __subclasscheck__(cls, subclass): raise ValueError() class MyException(Exception, metaclass=Meta): pass with captured_stderr() as stderr: try: raise KeyError() except MyException as e: self.fail("exception should not be a MyException") except KeyError: pass except: self.fail("Should have raised KeyError") else: self.fail("Should have raised KeyError") def g(): try: return g() except RecursionError as e: return e exc = g() self.assertIsInstance(exc, RecursionError, type(exc)) self.assertIn("maximum recursion depth exceeded", str(exc)) @cpython_only @support.requires_resource('cpu') def test_trashcan_recursion(self): # See bpo-33930 def foo(): o = object() for x in range(1_000_000): # Create a big chain of method objects that will trigger # a deep chain of calls when they need to be destructed. o = o.__dir__ foo() support.gc_collect() @cpython_only def test_recursion_normalizing_exception(self): import_module("_testinternalcapi") # Issue #22898. # Test that a RecursionError is raised when tstate->recursion_depth is # equal to recursion_limit in PyErr_NormalizeException() and check # that a ResourceWarning is printed. # Prior to #22898, the recursivity of PyErr_NormalizeException() was # controlled by tstate->recursion_depth and a PyExc_RecursionErrorInst # singleton was being used in that case, that held traceback data and # locals indefinitely and would cause a segfault in _PyExc_Fini() upon # finalization of these locals. code = """if 1: import sys from _testinternalcapi import get_recursion_depth from test import support class MyException(Exception): pass def setrecursionlimit(depth): while 1: try: sys.setrecursionlimit(depth) return depth except RecursionError: # sys.setrecursionlimit() raises a RecursionError if # the new recursion limit is too low (issue #25274). depth += 1 def recurse(cnt): cnt -= 1 if cnt: recurse(cnt) else: generator.throw(MyException) def gen(): f = open(%a, mode='rb', buffering=0) yield generator = gen() next(generator) recursionlimit = sys.getrecursionlimit() try: recurse(support.exceeds_recursion_limit()) finally: sys.setrecursionlimit(recursionlimit) print('Done.') """ % __file__ rc, out, err = script_helper.assert_python_failure("-Wd", "-c", code) # Check that the program does not fail with SIGABRT. self.assertEqual(rc, 1) self.assertIn(b'RecursionError', err) self.assertIn(b'ResourceWarning', err) self.assertIn(b'Done.', out) @cpython_only @unittest.skipIf(_testcapi is None, "requires _testcapi") @force_not_colorized def test_recursion_normalizing_infinite_exception(self): # Issue #30697. Test that a RecursionError is raised when # maximum recursion depth has been exceeded when creating # an exception code = """if 1: import _testcapi try: raise _testcapi.RecursingInfinitelyError finally: print('Done.') """ rc, out, err = script_helper.assert_python_failure("-c", code) self.assertEqual(rc, 1) expected = b'RecursionError: maximum recursion depth exceeded' self.assertTrue(expected in err, msg=f"{expected!r} not found in {err[:3_000]!r}... (truncated)") self.assertIn(b'Done.', out) def test_recursion_in_except_handler(self): def set_relative_recursion_limit(n): depth = 1 while True: try: sys.setrecursionlimit(depth) except RecursionError: depth += 1 else: break sys.setrecursionlimit(depth+n) def recurse_in_except(): try: 1/0 except: recurse_in_except() def recurse_after_except(): try: 1/0 except: pass recurse_after_except() def recurse_in_body_and_except(): try: recurse_in_body_and_except() except: recurse_in_body_and_except() recursionlimit = sys.getrecursionlimit() try: set_relative_recursion_limit(10) for func in (recurse_in_except, recurse_after_except, recurse_in_body_and_except): with self.subTest(func=func): try: func() except RecursionError: pass else: self.fail("Should have raised a RecursionError") finally: sys.setrecursionlimit(recursionlimit) @cpython_only # Python built with Py_TRACE_REFS fail with a fatal error in # _PyRefchain_Trace() on memory allocation error. @unittest.skipIf(support.Py_TRACE_REFS, 'cannot test Py_TRACE_REFS build') @unittest.skipIf(_testcapi is None, "requires _testcapi") def test_recursion_normalizing_with_no_memory(self): # Issue #30697. Test that in the abort that occurs when there is no # memory left and the size of the Python frames stack is greater than # the size of the list of preallocated MemoryError instances, the # Fatal Python error message mentions MemoryError. code = """if 1: import _testcapi class C(): pass def recurse(cnt): cnt -= 1 if cnt: recurse(cnt) else: _testcapi.set_nomemory(0) C() recurse(16) """ with SuppressCrashReport(): rc, out, err = script_helper.assert_python_failure("-c", code) self.assertIn(b'MemoryError', err) @cpython_only @unittest.skipIf(_testcapi is None, "requires _testcapi") def test_MemoryError(self): # PyErr_NoMemory always raises the same exception instance. # Check that the traceback is not doubled. import traceback from _testcapi import raise_memoryerror def raiseMemError(): try: raise_memoryerror() except MemoryError as e: tb = e.__traceback__ else: self.fail("Should have raised a MemoryError") return traceback.format_tb(tb) tb1 = raiseMemError() tb2 = raiseMemError() self.assertEqual(tb1, tb2) @cpython_only @unittest.skipIf(_testcapi is None, "requires _testcapi") def test_exception_with_doc(self): doc2 = "This is a test docstring." doc4 = "This is another test docstring." self.assertRaises(SystemError, _testcapi.make_exception_with_doc, "error1") # test basic usage of PyErr_NewException error1 = _testcapi.make_exception_with_doc("_testcapi.error1") self.assertIs(type(error1), type) self.assertTrue(issubclass(error1, Exception)) self.assertIsNone(error1.__doc__) # test with given docstring error2 = _testcapi.make_exception_with_doc("_testcapi.error2", doc2) self.assertEqual(error2.__doc__, doc2) # test with explicit base (without docstring) error3 = _testcapi.make_exception_with_doc("_testcapi.error3", base=error2) self.assertTrue(issubclass(error3, error2)) # test with explicit base tuple with torch._dynamo.error_on_graph_break(False): class C(object): pass error4 = _testcapi.make_exception_with_doc("_testcapi.error4", doc4, (error3, C)) self.assertTrue(issubclass(error4, error3)) self.assertTrue(issubclass(error4, C)) self.assertEqual(error4.__doc__, doc4) # test with explicit dictionary error5 = _testcapi.make_exception_with_doc("_testcapi.error5", "", error4, {'a': 1}) self.assertTrue(issubclass(error5, error4)) self.assertEqual(error5.a, 1) self.assertEqual(error5.__doc__, "") @cpython_only @unittest.skipIf(_testcapi is None, "requires _testcapi") def test_memory_error_cleanup(self): # Issue #5437: preallocated MemoryError instances should not keep # traceback objects alive. from _testcapi import raise_memoryerror with torch._dynamo.error_on_graph_break(False): class C: pass wr = None def inner(): nonlocal wr c = C() wr = weakref.ref(c) raise_memoryerror() # We cannot use assertRaises since it manually deletes the traceback try: inner() except MemoryError as e: self.assertNotEqual(wr(), None) else: self.fail("MemoryError not raised") gc_collect() # For PyPy or other GCs. self.assertEqual(wr(), None) @no_tracing def test_recursion_error_cleanup(self): # Same test as above, but with "recursion exceeded" errors with torch._dynamo.error_on_graph_break(False): class C: pass wr = None def inner(): nonlocal wr c = C() wr = weakref.ref(c) inner() # We cannot use assertRaises since it manually deletes the traceback try: inner() except RecursionError as e: self.assertNotEqual(wr(), None) else: self.fail("RecursionError not raised") gc_collect() # For PyPy or other GCs. self.assertEqual(wr(), None) def test_errno_ENOTDIR(self): # Issue #12802: "not a directory" errors are ENOTDIR even on Windows with self.assertRaises(OSError) as cm: os.listdir(__file__) self.assertEqual(cm.exception.errno, errno.ENOTDIR, cm.exception) def test_unraisable(self): # Issue #22836: PyErr_WriteUnraisable() should give sensible reports with torch._dynamo.error_on_graph_break(False): class BrokenDel: def __del__(self): exc = ValueError("del is broken") # The following line is included in the traceback report: raise exc obj = BrokenDel() with support.catch_unraisable_exception() as cm: del obj gc_collect() # For PyPy or other GCs. self.assertEqual(cm.unraisable.object, BrokenDel.__del__) self.assertIsNotNone(cm.unraisable.exc_traceback) def test_unhandled(self): # Check for sensible reporting of unhandled exceptions for exc_type in (ValueError, BrokenStrException): with self.subTest(exc_type): try: exc = exc_type("test message") # The following line is included in the traceback report: raise exc except exc_type: with captured_stderr() as stderr: sys.__excepthook__(*sys.exc_info()) report = stderr.getvalue() self.assertIn("test_exceptions.py", report) self.assertIn("raise exc", report) self.assertIn(exc_type.__name__, report) if exc_type is BrokenStrException: self.assertIn("<exception str() failed>", report) else: self.assertIn("test message", report) self.assertTrue(report.endswith("\n")) @cpython_only # Python built with Py_TRACE_REFS fail with a fatal error in # _PyRefchain_Trace() on memory allocation error. @unittest.skipIf(support.Py_TRACE_REFS, 'cannot test Py_TRACE_REFS build') @unittest.skipIf(_testcapi is None, "requires _testcapi") def test_memory_error_in_PyErr_PrintEx(self): code = """if 1: import _testcapi class C(): pass _testcapi.set_nomemory(0, %d) C() """ # Issue #30817: Abort in PyErr_PrintEx() when no memory. # Span a large range of tests as the CPython code always evolves with # changes that add or remove memory allocations. for i in range(1, 20): rc, out, err = script_helper.assert_python_failure("-c", code % i) self.assertIn(rc, (1, 120)) self.assertIn(b'MemoryError', err) def test_yield_in_nested_try_excepts(self): #Issue #25612 with torch._dynamo.error_on_graph_break(False): class MainError(Exception): pass class SubError(Exception): pass def main(): try: raise MainError() except MainError: try: yield except SubError: pass raise coro = main() coro.send(None) with self.assertRaises(MainError): coro.throw(SubError()) def test_generator_doesnt_retain_old_exc2(self): #Issue 28884#msg282532 def g(): try: raise ValueError except ValueError: yield 1 self.assertIsNone(sys.exception()) yield 2 gen = g() try: raise IndexError except IndexError: self.assertEqual(next(gen), 1) self.assertEqual(next(gen), 2) def test_raise_in_generator(self): #Issue 25612#msg304117 def g(): yield 1 raise yield 2 with self.assertRaises(ZeroDivisionError): i = g() try: 1/0 except: next(i) next(i) @unittest.skipUnless(__debug__, "Won't work if __debug__ is False") def test_assert_shadowing(self): # Shadowing AssertionError would cause the assert statement to # misbehave. global AssertionError AssertionError = TypeError try: assert False, 'hello' except BaseException as e: del AssertionError self.assertIsInstance(e, AssertionError) self.assertEqual(str(e), 'hello') else: del AssertionError self.fail('Expected exception') def test_memory_error_subclasses(self): # bpo-41654: MemoryError instances use a freelist of objects that are # linked using the 'dict' attribute when they are inactive/dead. # Subclasses of MemoryError should not participate in the freelist # schema. This test creates a MemoryError object and keeps it alive # (therefore advancing the freelist) and then it creates and destroys a # subclass object. Finally, it checks that creating a new MemoryError # succeeds, proving that the freelist is not corrupted. with torch._dynamo.error_on_graph_break(False): class TestException(MemoryError): pass try: raise MemoryError except MemoryError as exc: inst = exc try: raise TestException except Exception: pass for _ in range(10): try: raise MemoryError except MemoryError as exc: pass gc_collect() @unittest.skipIf(_testcapi is None, "requires _testcapi") def test_memory_error_in_subinterp(self): # gh-109894: subinterpreters shouldn't count on last resort memory error # when MemoryError is raised through PyErr_NoMemory() call, # and should preallocate memory errors as does the main interpreter. # interp.static_objects.last_resort_memory_error.args # should be initialized to empty tuple to avoid crash on attempt to print it. code = f"""if 1: import _testcapi _testcapi.run_in_subinterp(\"[0]*{sys.maxsize}\") exit(0) """ rc, _, err = script_helper.assert_python_ok("-c", code) self.assertIn(b'MemoryError', err)
ExceptionTests
python
pytorch__pytorch
test/distributed/test_c10d_gloo.py
{ "start": 102129, "end": 103090 }
class ____(test_c10d_common.AbstractLargeCommTest, MultiProcessTestCase): def setUp(self): super().setUp() self._spawn_processes() def tearDown(self): super().tearDown() try: os.remove(self.file_name) except OSError: pass @property def device(self): return torch.device("cpu") @requires_gloo() def test_new_group_local_sync(self): self._test_new_group_local_sync(backend="gloo") @requires_gloo() def test_new_group_local_sync_sanity_check(self): self._test_new_group_local_sync_sanity_check(backend="gloo") @requires_gloo() def test_new_group_local_sync_duplicate_pg(self): self._test_new_group_local_sync_duplicate_pg(backend="gloo") if __name__ == "__main__": assert not torch.cuda._initialized, ( "test_distributed must not have initialized CUDA context on main process" ) run_tests()
LargeCommTest
python
huggingface__transformers
examples/pytorch/image-classification/run_image_classification.py
{ "start": 2258, "end": 4497 }
class ____: """ Arguments pertaining to what data we are going to input our model for training and eval. Using `HfArgumentParser` we can turn this class into argparse arguments to be able to specify them on the command line. """ dataset_name: Optional[str] = field( default=None, metadata={ "help": "Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub)." }, ) dataset_config_name: Optional[str] = field( default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) train_dir: Optional[str] = field(default=None, metadata={"help": "A folder containing the training data."}) validation_dir: Optional[str] = field(default=None, metadata={"help": "A folder containing the validation data."}) train_val_split: Optional[float] = field( default=0.15, metadata={"help": "Percent to split off of train for validation."} ) max_train_samples: Optional[int] = field( default=None, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) }, ) max_eval_samples: Optional[int] = field( default=None, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) }, ) image_column_name: str = field( default="image", metadata={"help": "The name of the dataset column containing the image data. Defaults to 'image'."}, ) label_column_name: str = field( default="label", metadata={"help": "The name of the dataset column containing the labels. Defaults to 'label'."}, ) def __post_init__(self): if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None): raise ValueError( "You must specify either a dataset name from the hub or a train and/or validation directory." ) @dataclass
DataTrainingArguments
python
weaviate__weaviate-python-client
weaviate/collections/classes/grpc.py
{ "start": 2363, "end": 3166 }
class ____(_WeaviateInput): """Define which metadata should be returned in the query's results.""" creation_time: bool = Field(default=False) last_update_time: bool = Field(default=False) distance: bool = Field(default=False) certainty: bool = Field(default=False) score: bool = Field(default=False) explain_score: bool = Field(default=False) is_consistent: bool = Field(default=False) @classmethod def full(cls) -> "MetadataQuery": """Return a MetadataQuery with all fields set to True.""" return cls( creation_time=True, last_update_time=True, distance=True, certainty=True, score=True, explain_score=True, is_consistent=True, ) @dataclass
MetadataQuery
python
mitmproxy__pdoc
test/testdata/flavors_google.py
{ "start": 12587, "end": 14188 }
class ____: """Summary of class here. Longer class information.... Longer class information.... Attributes: likes_spam: A boolean indicating if we like SPAM or not. eggs: An integer count of the eggs we have laid. """ def __init__(self, likes_spam=False): """Inits SampleClass with blah.""" self.likes_spam = likes_spam self.eggs = 0 def public_method(self): """Performs operation blah.""" def invalid_format(test): """ In this example, there is no colon after the argument and an empty section. Args: test there is a colon missing in the previous line Returns: """ def example_code(): """ Test case for https://github.com/mitmproxy/pdoc/issues/264. Example: ```python tmp = a2() tmp2 = a() ``` """ def newline_after_args(test: str): """ Test case for https://github.com/mitmproxy/pdoc/pull/458. Args: test there is unexpected whitespace before test. """ def alternative_section_names(test: str): """ In this example, we check whether alternative section names aliased to 'Args' are handled properly. Parameters: test: the test string """ def keyword_arguments(**kwargs): """ This an example for a function with keyword arguments documented in the docstring. Args: **kwargs: A dictionary containing user info. Keyword Arguments: str_arg (str): First string argument. int_arg (int): Second integer argument. """
SampleClass
python
jazzband__django-simple-history
simple_history/tests/tests/test_models.py
{ "start": 81102, "end": 95780 }
class ____(TestCase): def setUp(self): self.model = PollWithManyToMany self.history_model = self.model.history.model self.place = Place.objects.create(name="Home") self.poll = PollWithManyToMany.objects.create( question="what's up?", pub_date=today ) def assertDatetimesEqual(self, time1, time2): self.assertAlmostEqual(time1, time2, delta=timedelta(seconds=2)) def assertRecordValues(self, record, klass, values_dict): for key, value in values_dict.items(): self.assertEqual(getattr(record, key), value) self.assertEqual(record.history_object.__class__, klass) for key, value in values_dict.items(): if key not in ["history_type", "history_change_reason"]: self.assertEqual(getattr(record.history_object, key), value) def test_create(self): # There should be 1 history record for our poll, the create from setUp self.assertEqual(self.poll.history.all().count(), 1) # The created history row should be normal and correct (record,) = self.poll.history.all() self.assertRecordValues( record, self.model, { "question": "what's up?", "pub_date": today, "id": self.poll.id, "history_type": "+", }, ) self.assertDatetimesEqual(record.history_date, datetime.now()) historical_poll = self.poll.history.all()[0] # There should be no places associated with the current poll yet self.assertEqual(historical_poll.places.count(), 0) # Add a many-to-many child self.poll.places.add(self.place) # A new history row has been created by adding the M2M self.assertEqual(self.poll.history.all().count(), 2) # The new row has a place attached to it m2m_record = self.poll.history.all()[0] self.assertEqual(m2m_record.places.count(), 1) # And the historical place is the correct one historical_place = m2m_record.places.first() self.assertEqual(historical_place.place, self.place) def test_remove(self): # Add and remove a many-to-many child self.poll.places.add(self.place) self.poll.places.remove(self.place) # Two new history exist for the place add & remove self.assertEqual(self.poll.history.all().count(), 3) # The newest row has no place attached to it m2m_record = self.poll.history.all()[0] self.assertEqual(m2m_record.places.count(), 0) # The previous one should have one place previous_m2m_record = m2m_record.prev_record self.assertEqual(previous_m2m_record.places.count(), 1) # And the previous row still has the correct one historical_place = previous_m2m_record.places.first() self.assertEqual(historical_place.place, self.place) def test_clear(self): # Add some places place_2 = Place.objects.create(name="Place 2") place_3 = Place.objects.create(name="Place 3") place_4 = Place.objects.create(name="Place 4") self.poll.places.add(self.place) self.poll.places.add(place_2) self.poll.places.add(place_3) self.poll.places.add(place_4) # Should be 5 history rows, one for the create, one from each add self.assertEqual(self.poll.history.all().count(), 5) # Most recent should have 4 places m2m_record = self.poll.history.all()[0] self.assertEqual(m2m_record.places.all().count(), 4) # Previous one should have 3 prev_record = m2m_record.prev_record self.assertEqual(prev_record.places.all().count(), 3) # Clear all places self.poll.places.clear() # Clearing M2M should create a new history entry self.assertEqual(self.poll.history.all().count(), 6) # Most recent should have no places m2m_record = self.poll.history.all()[0] self.assertEqual(m2m_record.places.all().count(), 0) def test_delete_child(self): # Add a place original_place_id = self.place.id self.poll.places.add(self.place) self.assertEqual(self.poll.history.all().count(), 2) # Delete the place instance self.place.delete() # No new history row is created when the Place is deleted self.assertEqual(self.poll.history.all().count(), 2) # The newest row still has a place attached to it m2m_record = self.poll.history.all()[0] self.assertEqual(m2m_record.places.count(), 1) # Place instance cannot be created... historical_place = m2m_record.places.first() with self.assertRaises(ObjectDoesNotExist): historical_place.place.id # But the values persist historical_place_values = m2m_record.places.all().values()[0] self.assertEqual(historical_place_values["history_id"], m2m_record.history_id) self.assertEqual(historical_place_values["place_id"], original_place_id) self.assertEqual(historical_place_values["pollwithmanytomany_id"], self.poll.id) def test_delete_parent(self): # Add a place self.poll.places.add(self.place) self.assertEqual(self.poll.history.all().count(), 2) # Delete the poll instance self.poll.delete() # History row is created when the Poll is deleted, but all m2m relations have # been deleted self.assertEqual(self.model.history.all().count(), 3) # Confirm the newest row (the delete) has no relations m2m_record = self.model.history.all()[0] self.assertEqual(m2m_record.places.count(), 0) # Confirm the previous row still has one prev_record = m2m_record.prev_record self.assertEqual(prev_record.places.count(), 1) # And it is the correct one historical_place = prev_record.places.first() self.assertEqual(historical_place.place, self.place) def test_update_child(self): self.poll.places.add(self.place) # Only two history rows, one for create and one for the M2M add self.assertEqual(self.poll.history.all().count(), 2) self.place.name = "Updated" self.place.save() # Updating the referenced M2M does not add history self.assertEqual(self.poll.history.all().count(), 2) # The newest row has the updated place m2m_record = self.poll.history.all()[0] self.assertEqual(m2m_record.places.count(), 1) historical_place = m2m_record.places.first() self.assertEqual(historical_place.place.name, "Updated") def test_update_parent(self): self.poll.places.add(self.place) # Only two history rows, one for create and one for the M2M add self.assertEqual(self.poll.history.all().count(), 2) self.poll.question = "Updated?" self.poll.save() # Updating the model with the M2M on it creates new history self.assertEqual(self.poll.history.all().count(), 3) # The newest row still has the associated Place m2m_record = self.poll.history.all()[0] self.assertEqual(m2m_record.places.count(), 1) historical_place = m2m_record.places.first() self.assertEqual(historical_place.place, self.place) def test_bulk_add_remove(self): # Add some places Place.objects.create(name="Place 2") Place.objects.create(name="Place 3") Place.objects.create(name="Place 4") # Bulk add all of the places self.poll.places.add(*Place.objects.all()) # Should be 2 history rows, one for the create, one from the bulk add self.assertEqual(self.poll.history.all().count(), 2) # Most recent should have 4 places m2m_record = self.poll.history.all()[0] self.assertEqual(m2m_record.places.all().count(), 4) # Previous one should have 0 prev_record = m2m_record.prev_record self.assertEqual(prev_record.places.all().count(), 0) # Remove all places but the first self.poll.places.remove(*Place.objects.exclude(pk=self.place.pk)) self.assertEqual(self.poll.history.all().count(), 3) # Most recent should only have the first Place remaining m2m_record = self.poll.history.all()[0] self.assertEqual(m2m_record.places.all().count(), 1) historical_place = m2m_record.places.first() self.assertEqual(historical_place.place, self.place) def test_add_remove_set_and_clear_methods_make_expected_num_queries(self): for num_places in (1, 2, 4): with self.subTest(num_places=num_places): start_pk = 100 + num_places places = Place.objects.bulk_create( Place(pk=pk, name=f"Place {pk}") for pk in range(start_pk, start_pk + num_places) ) self.assertEqual(len(places), num_places) self.assertEqual(self.poll.places.count(), 0) # The number of queries should stay the same, regardless of # the number of places added or removed with self.assertNumQueries(5): self.poll.places.add(*places) self.assertEqual(self.poll.places.count(), num_places) with self.assertNumQueries(3): self.poll.places.remove(*places) self.assertEqual(self.poll.places.count(), 0) with self.assertNumQueries(6): self.poll.places.set(places) self.assertEqual(self.poll.places.count(), num_places) with self.assertNumQueries(4): self.poll.places.set([]) self.assertEqual(self.poll.places.count(), 0) with self.assertNumQueries(5): self.poll.places.add(*places) self.assertEqual(self.poll.places.count(), num_places) with self.assertNumQueries(3): self.poll.places.clear() self.assertEqual(self.poll.places.count(), 0) def test_m2m_relation(self): # Ensure only the correct M2Ms are saved and returned for history objects poll_2 = PollWithManyToMany.objects.create(question="Why", pub_date=today) place_2 = Place.objects.create(name="Place 2") poll_2.places.add(self.place) poll_2.places.add(place_2) self.assertEqual(self.poll.history.all()[0].places.count(), 0) self.assertEqual(poll_2.history.all()[0].places.count(), 2) def test_skip_history_when_updating_an_object(self): skip_poll = PollWithManyToMany.objects.create( question="skip history?", pub_date=today ) self.assertEqual(skip_poll.history.all().count(), 1) self.assertEqual(skip_poll.history.all()[0].places.count(), 0) skip_poll.skip_history_when_saving = True skip_poll.question = "huh?" skip_poll.save() skip_poll.places.add(self.place) self.assertEqual(skip_poll.history.all().count(), 1) self.assertEqual(skip_poll.history.all()[0].places.count(), 0) del skip_poll.skip_history_when_saving place_2 = Place.objects.create(name="Place 2") skip_poll.places.add(place_2) self.assertEqual(skip_poll.history.all().count(), 2) self.assertEqual(skip_poll.history.all()[0].places.count(), 2) def test_skip_history_when_creating_an_object(self): initial_poll_count = PollWithManyToMany.objects.count() skip_poll = PollWithManyToMany(question="skip history?", pub_date=today) skip_poll.skip_history_when_saving = True skip_poll.save() skip_poll.places.add(self.place) self.assertEqual(skip_poll.history.count(), 0) self.assertEqual(PollWithManyToMany.objects.count(), initial_poll_count + 1) self.assertEqual(skip_poll.places.count(), 1) @override_settings(SIMPLE_HISTORY_ENABLED=False) def test_saving_with_disabled_history_doesnt_create_records(self): # 1 from `setUp()` self.assertEqual(PollWithManyToMany.history.count(), 1) poll = PollWithManyToMany.objects.create( question="skip history?", pub_date=today ) poll.question = "huh?" poll.save() poll.places.add(self.place) self.assertEqual(poll.history.count(), 0) # The count should not have changed self.assertEqual(PollWithManyToMany.history.count(), 1) def test_diff_against(self): self.poll.places.add(self.place) add_record, create_record = self.poll.history.all() with self.assertNumQueries(2): # Once for each record delta = add_record.diff_against(create_record) expected_change = ModelChange( "places", [], [{"pollwithmanytomany": self.poll.pk, "place": self.place.pk}] ) expected_delta = ModelDelta( [expected_change], ["places"], create_record, add_record ) self.assertEqual(delta, expected_delta) with self.assertNumQueries(2): # Once for each record delta = add_record.diff_against(create_record, included_fields=["places"]) self.assertEqual(delta, expected_delta) with self.assertNumQueries(0): delta = add_record.diff_against(create_record, excluded_fields=["places"]) expected_delta = dataclasses.replace( expected_delta, changes=[], changed_fields=[] ) self.assertEqual(delta, expected_delta) self.poll.places.clear() # First and third records are effectively the same. del_record, add_record, create_record = self.poll.history.all() with self.assertNumQueries(2): # Once for each record delta = del_record.diff_against(create_record) self.assertNotIn("places", delta.changed_fields) with self.assertNumQueries(2): # Once for each record delta = del_record.diff_against(add_record) # Second and third should have the same diffs as first and second, but with # old and new reversed expected_change = ModelChange( "places", [{"place": self.place.pk, "pollwithmanytomany": self.poll.pk}], [] ) expected_delta = ModelDelta( [expected_change], ["places"], add_record, del_record ) self.assertEqual(delta, expected_delta) @override_settings(**database_router_override_settings)
ManyToManyTest
python
kamyu104__LeetCode-Solutions
Python/number-of-possible-sets-of-closing-branches.py
{ "start": 1408, "end": 2675 }
class ____(object): def numberOfSets(self, n, maxDistance, roads): """ :type n: int :type maxDistance: int :type roads: List[List[int]] :rtype: int """ def check(mask, dist): return all(dist[i][j] <= maxDistance for i in xrange(n) if mask&(1<<i) for j in xrange(i+1, n) if mask&(1<<j)) def floydWarshall(mask, dist): for k in xrange(len(dist[0])): if mask&(1<<k) == 0: continue for i in xrange(len(dist)): if mask&(1<<i) == 0: # optional, to speed up performance continue for j in xrange(i+1, len(dist[i])): if mask&(1<<j) == 0: # optional, to speed up performance continue dist[j][i] = dist[i][j] = min(dist[i][j], dist[i][k]+dist[k][j]) return check(mask, dist) dist = [[0 if u == v else float("inf") for v in xrange(n)] for u in xrange(n)] for u, v, w in roads: dist[u][v] = min(dist[u][v], w) dist[v][u] = min(dist[v][u], w) return sum(floydWarshall(mask, [d[:] for d in dist]) for mask in xrange(1<<n))
Solution2
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 570492, "end": 572365 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "content", "created_at", "reactors", "subject", "users", "viewer_has_reacted", ) content = sgqlc.types.Field( sgqlc.types.non_null(ReactionContent), graphql_name="content" ) created_at = sgqlc.types.Field(DateTime, graphql_name="createdAt") reactors = sgqlc.types.Field( sgqlc.types.non_null("ReactorConnection"), graphql_name="reactors", args=sgqlc.types.ArgDict( ( ("after", sgqlc.types.Arg(String, graphql_name="after", default=None)), ( "before", sgqlc.types.Arg(String, graphql_name="before", default=None), ), ("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)), ("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)), ) ), ) subject = sgqlc.types.Field(sgqlc.types.non_null(Reactable), graphql_name="subject") users = sgqlc.types.Field( sgqlc.types.non_null(ReactingUserConnection), graphql_name="users", args=sgqlc.types.ArgDict( ( ("after", sgqlc.types.Arg(String, graphql_name="after", default=None)), ( "before", sgqlc.types.Arg(String, graphql_name="before", default=None), ), ("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)), ("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)), ) ), ) viewer_has_reacted = sgqlc.types.Field( sgqlc.types.non_null(Boolean), graphql_name="viewerHasReacted" )
ReactionGroup
python
numpy__numpy
numpy/typing/tests/data/pass/shape.py
{ "start": 86, "end": 439 }
class ____(NamedTuple): x_axis: int y_axis: int # Test variance of _ShapeT_co def accepts_2d(a: np.ndarray[tuple[int, int], Any]) -> None: return None accepts_2d(np.empty(XYGrid(2, 2))) accepts_2d(np.zeros(XYGrid(2, 2), dtype=int)) accepts_2d(np.ones(XYGrid(2, 2), dtype=int)) accepts_2d(np.full(XYGrid(2, 2), fill_value=5, dtype=int))
XYGrid
python
tensorflow__tensorflow
tensorflow/python/tpu/client/client.py
{ "start": 3555, "end": 14785 }
class ____: """Client for working with the Cloud TPU API. This client is intended to be used for resolving tpu name to ip addresses. It's recommended to use this library as a contextlib to utilize all functionality. """ def __init__(self, tpu=None, zone=None, project=None, credentials='default', service=None, discovery_url=None): if isinstance(tpu, list): if not tpu: raise ValueError('At least one TPU must be specified.') if len(tpu) != 1: raise NotImplementedError( 'Using multiple TPUs in a single session is not yet implemented') tpu = tpu[0] tpu = _get_tpu_name(tpu) if tpu is None: tpu_node_config = _get_tpu_node_config() if tpu_node_config: tpu = tpu_node_config.get('tpu_node_name') project = project or tpu_node_config.get('project') zone = zone or tpu_node_config.get('zone') else: raise ValueError('Please provide a TPU Name to connect to.') self._tpu = _as_text(tpu) self._use_api = not self._tpu.startswith('grpc://') self._service = service self._credentials = None self._project = None self._zone = None self._discovery_url = None if self._use_api: if credentials != 'default': self._credentials = credentials # Automatically detect project and zone if unspecified. if project: self._project = _as_text(project) else: self._project = _request_compute_metadata('project/project-id') if zone: self._zone = _as_text(zone) else: zone_path = _request_compute_metadata('instance/zone') self._zone = zone_path.split('/')[-1] self._discovery_url = _environment_discovery_url() or discovery_url def _symptom_msg(self, msg): """Return the structured Symptom message.""" return 'Symptom: ' + msg def _oom_event(self, symptoms): """Check if a runtime OOM event is reported.""" if not symptoms: return False for symptom in reversed(symptoms): if symptom['symptomType'] != 'OUT_OF_MEMORY': continue oom_datetime_str = symptom['createTime'].split('.')[0] oom_datetime = datetime.datetime.strptime(oom_datetime_str, '%Y-%m-%dT%H:%M:%S') time_diff = _utcnow() - oom_datetime if time_diff < datetime.timedelta(seconds=_OOM_EVENT_COOL_TIME_SEC): logging.warning( self._symptom_msg( 'a recent runtime OOM has occurred ~{} seconds ago. The model ' 'script will terminate automatically. To prevent future OOM ' 'events, please consider reducing the model size. To disable this ' 'behavior, set flag --runtime_oom_exit=false when starting the ' 'script.'.format(time_diff.seconds))) return True return False def _hbm_oom_event(self, symptoms): """Check if a HBM OOM event is reported.""" if not symptoms: return False for symptom in reversed(symptoms): if symptom['symptomType'] != 'HBM_OUT_OF_MEMORY': continue oom_datetime_str = symptom['createTime'].split('.')[0] oom_datetime = datetime.datetime.strptime(oom_datetime_str, '%Y-%m-%dT%H:%M:%S') time_diff = _utcnow() - oom_datetime if time_diff < datetime.timedelta(seconds=_OOM_EVENT_COOL_TIME_SEC): logging.warning( self._symptom_msg( 'a recent HBM OOM has occurred ~{} seconds ago. The model ' 'script will terminate automatically. To prevent future HBM OOM ' 'events, please consider reducing the model size. To disable this ' 'behavior, set flag --hbm_oom_exit=false when starting the ' 'script.'.format(time_diff.seconds))) return True return False def _tpu_service(self): """Creates a new Cloud TPU API object. This works around an issue where the underlying HTTP connection sometimes times out when the script has been running for too long. Other methods in this object call this method to get a new API object whenever they need to communicate with the Cloud API. Raises: RuntimeError: If the dependent Python packages are missing. Returns: A Google Cloud TPU API object. """ if self._service: return self._service if not _GOOGLE_API_CLIENT_INSTALLED: raise RuntimeError('Missing runtime dependency on the Google API client. ' 'Run `pip install cloud-tpu-client` to fix.') credentials = self._credentials if credentials is None or credentials == 'default': credentials = client.GoogleCredentials.get_application_default() if self._discovery_url: return discovery.build( 'tpu', 'v1', credentials=credentials, discoveryServiceUrl=self._discovery_url, cache_discovery=False) else: return discovery.build( 'tpu', 'v1', credentials=credentials, cache_discovery=False) def _full_name(self): """Returns the full Cloud name for this TPU.""" return 'projects/%s/locations/%s/nodes/%s' % ( self._project, self._zone, self._tpu) def _fetch_cloud_tpu_metadata(self): """Returns the TPU metadata object from the TPU Get API call.""" service = self._tpu_service() try: r = service.projects().locations().nodes().get(name=self._full_name()) return r.execute() except Exception as e: raise ValueError("Could not lookup TPU metadata from name '%s'. Please " 'doublecheck the tpu argument in the TPUClusterResolver ' 'constructor. Exception: %s' % (self._tpu, e)) def _get_tpu_property(self, key): if self._use_api: metadata = self._fetch_cloud_tpu_metadata() return metadata.get(key) return None def __enter__(self): self._open = True def __exit__(self, type, value, traceback): # pylint: disable=redefined-builtin del type, value, traceback def recoverable(self): """Returns true if the TPU is in a state where training should eventually resume. If false the TPU is in a unrecoverable state and should be recreated. """ state = self.state() symptoms = self.symptoms() if state and state in ['TERMINATED', 'PREEMPTED']: return False elif FLAGS.runtime_oom_exit and self._oom_event(symptoms): return False elif FLAGS.hbm_oom_exit and self._hbm_oom_event(symptoms): return False return True def symptoms(self): """Return Cloud TPU Symptoms of the TPU.""" return self._get_tpu_property('symptoms') def state(self): """Return state of the TPU.""" return self._get_tpu_property('state') def health(self): """Return health of the TPU.""" return self._get_tpu_property('health') def runtime_version(self): """Return runtime version of the TPU.""" if not self._use_api: # Fallback on getting version directly from TPU. url = _VERSION_SWITCHER_ENDPOINT.format( self.network_endpoints()[0]['ipAddress']) try: req = urllib.request.Request(url) resp = urllib.request.urlopen(req) version_details = json.loads(resp.read()) return version_details.get('currentVersion') except urllib.error.HTTPError as e: status_code = e.code if status_code == 404: return None else: raise e return self._get_tpu_property('tensorflowVersion') def accelerator_type(self): """Return accelerator type of the TPU.""" return self._get_tpu_property('acceleratorType') def api_available(self): """Return if the Cloud TPU API is available, if not certain features will not work.""" return self._use_api def name(self): """Return the name of the tpu, or the ip address if name is not provided.""" return self._tpu def get_local_ip(self): """Return the local ip address of the Google Cloud VM the workload is running on.""" return _request_compute_metadata('instance/network-interfaces/0/ip') def network_endpoints(self): """Return a list of tpu endpoints.""" if not self._use_api: return list(_environment_var_to_network_endpoints(self._tpu)) response = self._fetch_cloud_tpu_metadata() if response.get('state') != 'READY': raise RuntimeError('TPU "%s" is not yet ready; state: "%s"' % (self._tpu, response.get('state'))) if 'networkEndpoints' in response: return response['networkEndpoints'] else: return [{'ipAddress': response['ipAddress'], 'port': response['port']}] def wait_for_healthy(self, timeout_s=1200, interval=30): """Wait for TPU to become healthy or raise error if timeout reached. Args: timeout_s (int): The timeout in seconds for waiting TPU to become healthy. interval (int): The interval in seconds to poll the TPU for health. Raises: RuntimeError: If the TPU doesn't become healthy by the timeout. """ timeout = time.time() + timeout_s while self.health() != 'HEALTHY': logging.warning( ('Waiting for TPU "%s" with state "%s" ' 'and health "%s" to become healthy'), self.name(), self.state(), self.health()) if time.time() + interval > timeout: raise RuntimeError( 'Timed out waiting for TPU "%s" to become healthy' % self.name()) time.sleep(interval) logging.warning('TPU "%s" is healthy.', self.name()) def configure_tpu_version(self, version, restart_type='always'): """Configure TPU software version. Args: version (string): Version of software to configure the TPU with. restart_type (string): Restart behaviour when switching versions, defaults to always restart. Options are 'always', 'ifNeeded'. """ def configure_worker(worker): """Configure individual TPU worker. Args: worker: A dict with the field ipAddress where the configure request will be sent. """ ip_address = worker['ipAddress'] url = (_VERSION_SWITCHER_ENDPOINT + '/{}?restartType={}').format( ip_address, version, restart_type) req = urllib.request.Request(url, data=b'') try: urllib.request.urlopen(req) except urllib.error.HTTPError as e: status_code = e.code if status_code == 404: raise Exception( 'Tensorflow version {} is not available on Cloud TPU, ' 'try a previous nightly version or refer to ' 'https://cloud.google.com/tpu/docs/release-notes for ' 'the latest official version.'.format(version)) else: raise Exception('Failed to configure worker {}'.format(ip_address)) workers = self.network_endpoints() with futures.ThreadPoolExecutor(max_workers=len(workers)) as executor: results = executor.map(configure_worker, workers) for result in results: if result: result.result()
Client
python
spack__spack
lib/spack/spack/vendor/attr/_make.py
{ "start": 88356, "end": 91629 }
class ____: """ Intermediate representation of attributes that uses a counter to preserve the order in which the attributes have been defined. *Internal* data structure of the attrs library. Running into is most likely the result of a bug like a forgotten `@attr.s` decorator. """ __slots__ = ( "counter", "_default", "repr", "eq", "eq_key", "order", "order_key", "hash", "init", "metadata", "_validator", "converter", "type", "kw_only", "on_setattr", ) __attrs_attrs__ = tuple( Attribute( name=name, default=NOTHING, validator=None, repr=True, cmp=None, hash=True, init=True, kw_only=False, eq=True, eq_key=None, order=False, order_key=None, inherited=False, on_setattr=None, ) for name in ( "counter", "_default", "repr", "eq", "order", "hash", "init", "on_setattr", ) ) + ( Attribute( name="metadata", default=None, validator=None, repr=True, cmp=None, hash=False, init=True, kw_only=False, eq=True, eq_key=None, order=False, order_key=None, inherited=False, on_setattr=None, ), ) cls_counter = 0 def __init__( self, default, validator, repr, cmp, hash, init, converter, metadata, type, kw_only, eq, eq_key, order, order_key, on_setattr, ): _CountingAttr.cls_counter += 1 self.counter = _CountingAttr.cls_counter self._default = default self._validator = validator self.converter = converter self.repr = repr self.eq = eq self.eq_key = eq_key self.order = order self.order_key = order_key self.hash = hash self.init = init self.metadata = metadata self.type = type self.kw_only = kw_only self.on_setattr = on_setattr def validator(self, meth): """ Decorator that adds *meth* to the list of validators. Returns *meth* unchanged. .. versionadded:: 17.1.0 """ if self._validator is None: self._validator = meth else: self._validator = and_(self._validator, meth) return meth def default(self, meth): """ Decorator that allows to set the default for an attribute. Returns *meth* unchanged. :raises DefaultAlreadySetError: If default has been set before. .. versionadded:: 17.1.0 """ if self._default is not NOTHING: raise DefaultAlreadySetError() self._default = Factory(meth, takes_self=True) return meth _CountingAttr = _add_eq(_add_repr(_CountingAttr))
_CountingAttr
python
getsentry__sentry
src/sentry/interfaces/geo.py
{ "start": 67, "end": 555 }
class ____(Interface): """ The (approximate) geographical location of the end user. >>> { >>> 'country_code': 'US', >>> 'city': 'San Francisco', >>> 'region': 'CA', >>> } """ @classmethod def to_python(cls, data, **kwargs): data = { "country_code": data.get("country_code"), "city": data.get("city"), "region": data.get("region"), } return super().to_python(data, **kwargs)
Geo
python
airbytehq__airbyte
airbyte-integrations/connectors/source-mixpanel/source_mixpanel/source.py
{ "start": 1859, "end": 2078 }
class ____(TokenAuthenticator): def __init__(self, token: str): token = base64.b64encode(token.encode("utf8")).decode("utf8") super().__init__(token=token, auth_method="Basic")
TokenAuthenticatorBase64
python
kamyu104__LeetCode-Solutions
Python/compute-decimal-representation.py
{ "start": 39, "end": 387 }
class ____(object): def decimalRepresentation(self, n): """ :type n: int :rtype: List[int] """ result = [] base = 1 while n: n, r = divmod(n, 10) if r: result.append(r*base) base *= 10 result.reverse() return result
Solution
python
GoogleCloudPlatform__python-docs-samples
compute/client_library/snippets/instances/custom_machine_types/helper_class.py
{ "start": 989, "end": 8320 }
class ____: """ Allows to create custom machine types to be used with the VM instances. """ @unique class CPUSeries(Enum): N1 = "custom" N2 = "n2-custom" N2D = "n2d-custom" E2 = "e2-custom" E2_MICRO = "e2-custom-micro" E2_SMALL = "e2-custom-small" E2_MEDIUM = "e2-custom-medium" TypeLimits = namedtuple( "TypeLimits", [ "allowed_cores", "min_mem_per_core", "max_mem_per_core", "allow_extra_memory", "extra_memory_limit", ], ) # The limits for various CPU types are described on: # https://cloud.google.com/compute/docs/general-purpose-machines LIMITS = { CPUSeries.E2: TypeLimits(frozenset(range(2, 33, 2)), 512, 8192, False, 0), CPUSeries.E2_MICRO: TypeLimits(frozenset(), 1024, 2048, False, 0), CPUSeries.E2_SMALL: TypeLimits(frozenset(), 2048, 4096, False, 0), CPUSeries.E2_MEDIUM: TypeLimits(frozenset(), 4096, 8192, False, 0), CPUSeries.N2: TypeLimits( frozenset(range(2, 33, 2)).union(set(range(36, 129, 4))), 512, 8192, True, gb_to_mb(624), ), CPUSeries.N2D: TypeLimits( frozenset({2, 4, 8, 16, 32, 48, 64, 80, 96}), 512, 8192, True, gb_to_mb(768) ), CPUSeries.N1: TypeLimits( frozenset({1}.union(range(2, 97, 2))), 922, 6656, True, gb_to_mb(624) ), } def __init__( self, zone: str, cpu_series: CPUSeries, memory_mb: int, core_count: int = 0 ): self.zone = zone self.cpu_series = cpu_series self.limits = self.LIMITS[self.cpu_series] # Shared machine types (e2-small, e2-medium and e2-micro) always have # 2 vCPUs: https://cloud.google.com/compute/docs/general-purpose-machines#e2_limitations self.core_count = 2 if self.is_shared() else core_count self.memory_mb = memory_mb self._checked = False self._check_parameters() self.extra_memory_used = self._check_extra_memory() def is_shared(self): return self.cpu_series in ( CustomMachineType.CPUSeries.E2_SMALL, CustomMachineType.CPUSeries.E2_MICRO, CustomMachineType.CPUSeries.E2_MEDIUM, ) def _check_extra_memory(self) -> bool: if self._checked: return self.memory_mb > self.core_count * self.limits.max_mem_per_core else: raise RuntimeError( "You need to call _check_parameters() before calling _check_extra_memory()" ) def _check_parameters(self): """ Check whether the requested parameters are allowed. Find more information about limitations of custom machine types at: https://cloud.google.com/compute/docs/general-purpose-machines#custom_machine_types """ # Check the number of cores if ( self.limits.allowed_cores and self.core_count not in self.limits.allowed_cores ): raise RuntimeError( f"Invalid number of cores requested. Allowed number of cores for {self.cpu_series.name} is: {sorted(self.limits.allowed_cores)}" ) # Memory must be a multiple of 256 MB if self.memory_mb % 256 != 0: raise RuntimeError("Requested memory must be a multiple of 256 MB.") # Check if the requested memory isn't too little if self.memory_mb < self.core_count * self.limits.min_mem_per_core: raise RuntimeError( f"Requested memory is too low. Minimal memory for {self.cpu_series.name} is {self.limits.min_mem_per_core} MB per core." ) # Check if the requested memory isn't too much if self.memory_mb > self.core_count * self.limits.max_mem_per_core: if self.limits.allow_extra_memory: if self.memory_mb > self.limits.extra_memory_limit: raise RuntimeError( f"Requested memory is too large.. Maximum memory allowed for {self.cpu_series.name} is {self.limits.extra_memory_limit} MB." ) else: raise RuntimeError( f"Requested memory is too large.. Maximum memory allowed for {self.cpu_series.name} is {self.limits.max_mem_per_core} MB per core." ) self._checked = True def __str__(self) -> str: """ Return the custom machine type in form of a string acceptable by Compute Engine API. """ if self.cpu_series in { self.CPUSeries.E2_SMALL, self.CPUSeries.E2_MICRO, self.CPUSeries.E2_MEDIUM, }: return f"zones/{self.zone}/machineTypes/{self.cpu_series.value}-{self.memory_mb}" if self.extra_memory_used: return f"zones/{self.zone}/machineTypes/{self.cpu_series.value}-{self.core_count}-{self.memory_mb}-ext" return f"zones/{self.zone}/machineTypes/{self.cpu_series.value}-{self.core_count}-{self.memory_mb}" def short_type_str(self) -> str: """ Return machine type in a format without the zone. For example, n2-custom-0-10240. This format is used to create instance templates. """ return str(self).rsplit("/", maxsplit=1)[1] @classmethod def from_str(cls, machine_type: str): """ Construct a new object from a string. The string needs to be a valid custom machine type like: - https://www.googleapis.com/compute/v1/projects/diregapic-mestiv/zones/us-central1-b/machineTypes/e2-custom-4-8192 - zones/us-central1-b/machineTypes/e2-custom-4-8192 - e2-custom-4-8192 (in this case, the zone parameter will not be set) """ zone = None if machine_type.startswith("http"): machine_type = machine_type[machine_type.find("zones/") :] if machine_type.startswith("zones/"): _, zone, _, machine_type = machine_type.split("/") extra_mem = machine_type.endswith("-ext") if machine_type.startswith("custom"): cpu = cls.CPUSeries.N1 _, cores, memory = machine_type.rsplit("-", maxsplit=2) else: if extra_mem: cpu_series, _, cores, memory, _ = machine_type.split("-") else: cpu_series, _, cores, memory = machine_type.split("-") if cpu_series == "n2": cpu = cls.CPUSeries.N2 elif cpu_series == "n2d": cpu = cls.CPUSeries.N2D elif cpu_series == "e2": cpu = cls.CPUSeries.E2 if cores == "micro": cpu = cls.CPUSeries.E2_MICRO cores = 2 elif cores == "small": cpu = cls.CPUSeries.E2_SMALL cores = 2 elif cores == "medium": cpu = cls.CPUSeries.E2_MEDIUM cores = 2 else: raise RuntimeError("Unknown CPU series.") cores = int(cores) memory = int(memory) return cls(zone, cpu, memory, cores) # [END compute_custom_machine_type_helper_class]
CustomMachineType
python
openai__openai-python
src/openai/_exceptions.py
{ "start": 4836, "end": 5008 }
class ____(ValueError): """Raised when a webhook signature is invalid, meaning the computed signature does not match the expected signature."""
InvalidWebhookSignatureError
python
scrapy__scrapy
tests/test_squeues.py
{ "start": 3770, "end": 3856 }
class ____(PickleFifoDiskQueueTest): chunksize = 1
ChunkSize1PickleFifoDiskQueueTest
python
patrick-kidger__equinox
equinox/_module/_module.py
{ "start": 1357, "end": 1721 }
class ____(eqx.Module): foo: Callable def __init__(self): self.foo = self.bar def bar(self): ... ``` this is because Equinox modules are PyTrees -- but the above does not have a tree structure! `self.foo.__self__` is a cycle that brings us back to `self`. In the above example, you probably want something like this instead: ```
MyModule
python
huggingface__transformers
src/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py
{ "start": 24885, "end": 27286 }
class ____(GradientCheckpointingLayer): """Conformer block based on https://huggingface.co/papers/2005.08100.""" def __init__(self, config): super().__init__() embed_dim = config.hidden_size dropout = config.attention_dropout # Feed-forward 1 self.ffn1_layer_norm = nn.LayerNorm(embed_dim) self.ffn1 = Wav2Vec2ConformerFeedForward(config) # Self-Attention self.self_attn_layer_norm = nn.LayerNorm(embed_dim) self.self_attn_dropout = nn.Dropout(dropout) self.self_attn = Wav2Vec2ConformerSelfAttention(config) # Conformer Convolution self.conv_module = Wav2Vec2ConformerConvolutionModule(config) # Feed-forward 2 self.ffn2_layer_norm = nn.LayerNorm(embed_dim) self.ffn2 = Wav2Vec2ConformerFeedForward(config) self.final_layer_norm = nn.LayerNorm(embed_dim) def forward( self, hidden_states, attention_mask: Optional[torch.Tensor] = None, relative_position_embeddings: Optional[torch.Tensor] = None, output_attentions: bool = False, ): # 1. Feed-Forward 1 layer residual = hidden_states hidden_states = self.ffn1_layer_norm(hidden_states) hidden_states = self.ffn1(hidden_states) hidden_states = hidden_states * 0.5 + residual residual = hidden_states # 2. Self-Attention layer hidden_states = self.self_attn_layer_norm(hidden_states) hidden_states, attn_weigts = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, relative_position_embeddings=relative_position_embeddings, output_attentions=output_attentions, ) hidden_states = self.self_attn_dropout(hidden_states) hidden_states = hidden_states + residual # 3. Convolutional Layer residual = hidden_states hidden_states = self.conv_module(hidden_states) hidden_states = residual + hidden_states # 4. Feed-Forward 2 Layer residual = hidden_states hidden_states = self.ffn2_layer_norm(hidden_states) hidden_states = self.ffn2(hidden_states) hidden_states = hidden_states * 0.5 + residual hidden_states = self.final_layer_norm(hidden_states) return hidden_states, attn_weigts
Wav2Vec2ConformerEncoderLayer
python
MongoEngine__mongoengine
mongoengine/base/datastructures.py
{ "start": 12347, "end": 14563 }
class ____: __slots__ = () _special_fields = {"get", "pop", "iteritems", "items", "keys", "create"} _classes = {} def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) def __getitem__(self, key): key = "_reserved_" + key if key in self._special_fields else key try: return getattr(self, key) except AttributeError: raise KeyError(key) def __setitem__(self, key, value): key = "_reserved_" + key if key in self._special_fields else key return setattr(self, key, value) def __contains__(self, key): return hasattr(self, key) def get(self, key, default=None): try: return self[key] except KeyError: return default def pop(self, key, default=None): v = self.get(key, default) try: delattr(self, key) except AttributeError: pass return v def iteritems(self): for key in self: yield key, self[key] def items(self): return [(k, self[k]) for k in iter(self)] def iterkeys(self): return iter(self) def keys(self): return list(iter(self)) def __iter__(self): return (key for key in self.__slots__ if hasattr(self, key)) def __len__(self): return len(list(self.items())) def __eq__(self, other): return list(self.items()) == list(other.items()) def __ne__(self, other): return not (self == other) @classmethod def create(cls, allowed_keys): allowed_keys_tuple = tuple( ("_reserved_" + k if k in cls._special_fields else k) for k in allowed_keys ) allowed_keys = frozenset(allowed_keys_tuple) if allowed_keys not in cls._classes: class SpecificStrictDict(cls): __slots__ = allowed_keys_tuple def __repr__(self): return "{%s}" % ", ".join( f'"{k!s}": {v!r}' for k, v in self.items() ) cls._classes[allowed_keys] = SpecificStrictDict return cls._classes[allowed_keys]
StrictDict
python
pennersr__django-allauth
allauth/idp/oidc/models.py
{ "start": 6185, "end": 6572 }
class ____(models.query.QuerySet): def valid(self): return self.filter( Q(expires_at__isnull=True) | Q(expires_at__gt=timezone.now()) ) def by_value(self, value: str): return self.filter(hash=get_adapter().hash_token(value)) def lookup(self, type, value): return self.valid().by_value(value).filter(type=type).first()
TokenQuerySet
python
getsentry__sentry
tests/sentry/codecov/endpoints/test_repositories.py
{ "start": 1654, "end": 7526 }
class ____(APITestCase): endpoint_name = "sentry-api-0-repositories" def setUp(self) -> None: super().setUp() self.organization = self.create_organization(owner=self.user) self.integration = self.create_integration( organization=self.organization, external_id="1234", name="testowner", provider="github", status=ObjectStatus.ACTIVE, ) self.login_as(user=self.user) def reverse_url(self, owner="testowner"): """Custom reverse URL method to handle required URL parameters""" return reverse( self.endpoint_name, kwargs={ "organization_id_or_slug": self.organization.slug, "owner": self.integration.id, }, ) @patch("sentry.codecov.endpoints.repositories.repositories.CodecovApiClient") def test_get_returns_mock_response_with_default_variables( self, mock_codecov_client_class: MagicMock ) -> None: mock_codecov_client_instance = Mock() mock_response = Mock() mock_response.json.return_value = mock_graphql_response_populated mock_codecov_client_instance.query.return_value = mock_response mock_codecov_client_class.return_value = mock_codecov_client_instance url = self.reverse_url() response = self.client.get(url) mock_codecov_client_class.assert_called_once_with(git_provider_org="testowner") # Verify the correct variables are passed to the GraphQL query expected_variables = { "owner": "testowner", "filters": { "term": None, }, "direction": "DESC", "ordering": "COMMIT_DATE", "first": 50, "last": None, "after": None, "before": None, } mock_codecov_client_instance.query.assert_called_once() call_args = mock_codecov_client_instance.query.call_args assert call_args[1]["variables"] == expected_variables assert response.status_code == 200 assert len(response.data["results"]) == 2 assert response.data["pageInfo"]["endCursor"] == "cursor123" assert response.data["pageInfo"]["hasNextPage"] is False assert response.data["pageInfo"]["hasPreviousPage"] is False assert response.data["pageInfo"]["startCursor"] is None assert response.data["totalCount"] == 2 serializer_fields = set(NodeSerializer().fields.keys()) response_keys = set(response.data["results"][0].keys()) assert ( response_keys == serializer_fields ), f"Response keys {response_keys} don't match serializer fields {serializer_fields}" @patch("sentry.codecov.endpoints.repositories.repositories.CodecovApiClient") def test_get_with_query_parameters(self, mock_codecov_client_class: MagicMock) -> None: mock_codecov_client_instance = Mock() mock_response = Mock() mock_response.json.return_value = mock_graphql_response_empty mock_codecov_client_instance.query.return_value = mock_response mock_codecov_client_class.return_value = mock_codecov_client_instance url = self.reverse_url() query_params = { "term": "search-term", "limit": "3", } response = self.client.get(url, query_params) # Verify the correct variables are passed with custom query parameters expected_variables = { "owner": "testowner", "filters": { "term": "search-term", }, "direction": "DESC", "ordering": "COMMIT_DATE", "first": 3, "last": None, "after": None, "before": None, } call_args = mock_codecov_client_instance.query.call_args assert call_args[1]["variables"] == expected_variables assert response.status_code == 200 @patch("sentry.codecov.endpoints.repositories.repositories.CodecovApiClient") def test_get_with_cursor_and_direction(self, mock_codecov_client_class: MagicMock) -> None: mock_codecov_client_instance = Mock() mock_response = Mock() mock_response.json.return_value = mock_graphql_response_empty mock_codecov_client_instance.query.return_value = mock_response mock_codecov_client_class.return_value = mock_codecov_client_instance url = self.reverse_url() query_params = {"cursor": "cursor123", "limit": "10", "navigation": "prev"} response = self.client.get(url, query_params) expected_variables = { "owner": "testowner", "filters": { "term": None, }, "direction": "DESC", "ordering": "COMMIT_DATE", "first": None, "last": 10, "before": "cursor123", "after": None, } call_args = mock_codecov_client_instance.query.call_args assert call_args[1]["variables"] == expected_variables assert response.status_code == 200 def test_get_with_negative_limit_returns_bad_request(self) -> None: url = self.reverse_url() query_params = {"limit": "-5"} response = self.client.get(url, query_params) assert response.status_code == 400 assert response.data == {"details": "provided `limit` parameter must be a positive integer"} def test_get_with_limit_as_string_returns_bad_request(self) -> None: url = self.reverse_url() query_params = {"limit": "asdf"} response = self.client.get(url, query_params) assert response.status_code == 400 assert response.data == {"details": "provided `limit` parameter must be a positive integer"}
RepositoriesEndpointTest
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_selection01.py
{ "start": 315, "end": 807 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("selection01.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.set_selection("B4:C5") workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
PyCQA__pylint
tests/functional/u/undefined/undefined_variable_py30.py
{ "start": 1898, "end": 1988 }
class ____(metaclass=int): """ int is not a proper metaclass, but it is defined. """
Good
python
kamyu104__LeetCode-Solutions
Python/minimum-rounds-to-complete-all-tasks.py
{ "start": 69, "end": 337 }
class ____(object): def minimumRounds(self, tasks): """ :type tasks: List[int] :rtype: int """ cnt = collections.Counter(tasks) return sum((x+2)//3 for x in cnt.itervalues()) if 1 not in cnt.itervalues() else -1
Solution
python
pytest-dev__pytest
testing/test_pastebin.py
{ "start": 2702, "end": 6547 }
class ____: @pytest.fixture def pastebin(self, request): return request.config.pluginmanager.getplugin("pastebin") @pytest.fixture def mocked_urlopen_invalid(self, monkeypatch: MonkeyPatch): """Monkeypatch the actual urlopen calls done by the internal plugin function that connects to bpaste service, but return a url in an unexpected format.""" calls = [] def mocked(url, data): calls.append((url, data)) class DummyFile: def read(self): # part of html of a normal response return b'View <a href="/invalid/3c0c6750bd">raw</a>.' return DummyFile() import urllib.request monkeypatch.setattr(urllib.request, "urlopen", mocked) return calls @pytest.fixture def mocked_urlopen(self, monkeypatch: MonkeyPatch): """Monkeypatch the actual urlopen calls done by the internal plugin function that connects to bpaste service.""" calls = [] def mocked(url, data): calls.append((url, data)) class DummyFile: def read(self): # part of html of a normal response return b'View <a href="/raw/3c0c6750bd">raw</a>.' return DummyFile() import urllib.request monkeypatch.setattr(urllib.request, "urlopen", mocked) return calls def test_pastebin_invalid_url(self, pastebin, mocked_urlopen_invalid) -> None: result = pastebin.create_new_paste(b"full-paste-contents") assert ( result == "bad response: invalid format ('View <a href=\"/invalid/3c0c6750bd\">raw</a>.')" ) assert len(mocked_urlopen_invalid) == 1 def test_pastebin_http_error(self, pastebin) -> None: import urllib.error with mock.patch( "urllib.request.urlopen", side_effect=urllib.error.HTTPError( url="https://bpa.st", code=400, msg="Bad request", hdrs=email.message.Message(), fp=io.BytesIO(), ), ) as mock_urlopen: result = pastebin.create_new_paste(b"full-paste-contents") assert result == "bad response: HTTP Error 400: Bad request" assert len(mock_urlopen.mock_calls) == 1 def test_pastebin_url_error(self, pastebin) -> None: import urllib.error with mock.patch( "urllib.request.urlopen", side_effect=urllib.error.URLError("the url was bad"), ) as mock_urlopen: result = pastebin.create_new_paste(b"full-paste-contents") assert result == "bad response: <urlopen error the url was bad>" assert len(mock_urlopen.mock_calls) == 1 def test_create_new_paste(self, pastebin, mocked_urlopen) -> None: result = pastebin.create_new_paste(b"full-paste-contents") assert result == "https://bpa.st/show/3c0c6750bd" assert len(mocked_urlopen) == 1 url, data = mocked_urlopen[0] assert type(data) is bytes lexer = "text" assert url == "https://bpa.st" assert f"lexer={lexer}" in data.decode() assert "code=full-paste-contents" in data.decode() assert "expiry=1week" in data.decode() def test_create_new_paste_failure(self, pastebin, monkeypatch: MonkeyPatch) -> None: import io import urllib.request def response(url, data): stream = io.BytesIO(b"something bad occurred") return stream monkeypatch.setattr(urllib.request, "urlopen", response) result = pastebin.create_new_paste(b"full-paste-contents") assert result == "bad response: invalid format ('something bad occurred')"
TestPaste
python
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py
{ "start": 9034, "end": 10927 }
class ____(Exception): """For internal use when backend raises UnsupportedOperation""" def __init__(self, traceback): self.traceback = traceback def build_sdist(sdist_directory, config_settings): """Invoke the mandatory build_sdist hook.""" backend = _build_backend() try: return backend.build_sdist(sdist_directory, config_settings) except getattr(backend, 'UnsupportedOperation', _DummyException): raise GotUnsupportedOperation(traceback.format_exc()) HOOK_NAMES = { 'get_requires_for_build_wheel', 'prepare_metadata_for_build_wheel', 'build_wheel', 'get_requires_for_build_editable', 'prepare_metadata_for_build_editable', 'build_editable', 'get_requires_for_build_sdist', 'build_sdist', '_supported_features', } def main(): if len(sys.argv) < 3: sys.exit("Needs args: hook_name, control_dir") hook_name = sys.argv[1] control_dir = sys.argv[2] if hook_name not in HOOK_NAMES: sys.exit("Unknown hook: %s" % hook_name) hook = globals()[hook_name] hook_input = read_json(pjoin(control_dir, 'input.json')) json_out = {'unsupported': False, 'return_val': None} try: json_out['return_val'] = hook(**hook_input['kwargs']) except BackendUnavailable as e: json_out['no_backend'] = True json_out['traceback'] = e.traceback except BackendInvalid as e: json_out['backend_invalid'] = True json_out['backend_error'] = e.message except GotUnsupportedOperation as e: json_out['unsupported'] = True json_out['traceback'] = e.traceback except HookMissing as e: json_out['hook_missing'] = True json_out['missing_hook_name'] = e.hook_name or hook_name write_json(json_out, pjoin(control_dir, 'output.json'), indent=2) if __name__ == '__main__': main()
GotUnsupportedOperation
python
celery__celery
t/unit/app/test_utils.py
{ "start": 1574, "end": 1790 }
class ____: def test_no_conn_driver_info(self): self.app.connection = Mock() conn = self.app.connection.return_value = Mock() conn.transport = None bugreport(self.app)
test_bugreport
python
falconry__falcon
tests/test_headers.py
{ "start": 5447, "end": 6239 }
class ____: def on_get(self, req, resp): resp.append_header('X-Things', 'thing-1') resp.append_header('X-THINGS', 'thing-2') resp.append_header('x-thiNgs', 'thing-3') def on_head(self, req, resp): resp.set_header('X-things', 'thing-1') resp.append_header('X-THINGS', 'thing-2') resp.append_header('x-thiNgs', 'thing-3') def on_post(self, req, resp): resp.append_header('X-Things', 'thing-1') c1 = ( 'ut_existing_user=1; expires=Mon, 14-Jan-2019 21:20:08 GMT;' ' Max-Age=600; path=/' ) resp.append_header('Set-Cookie', c1) c2 = 'partner_source=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0' resp.append_header('seT-cookie', c2)
AppendHeaderResource
python
cython__cython
Cython/Compiler/PyrexTypes.py
{ "start": 182825, "end": 183727 }
class ____: """Used to help Cython interpret indexed types from the typing module (or similar) """ modifier_name = None contains_none = False def allows_none(self): return ( self.modifier_name == 'typing.Optional' or self.modifier_name == 'typing.Union' and self.contains_none ) def set_python_type_constructor_name(self, name): self.python_type_constructor_name = name def specialize_here(self, pos, env, template_values=None): # for a lot of the typing classes it doesn't really matter what the template is # (i.e. typing.Dict[int] is really just a dict) return self def __repr__(self): if self.base_type: return "%s[%r]" % (self.name, self.base_type) else: return self.name def is_template_type(self): return True
PythonTypeConstructorMixin
python
openai__openai-python
src/openai/_types.py
{ "start": 5931, "end": 6190 }
class ____(Protocol): """Represents a type that has inherited from `Generic` The `__orig_bases__` property can be used to determine the resolved type variable for a given base class. """ __orig_bases__: tuple[_GenericAlias]
InheritsGeneric
python
getsentry__sentry
src/sentry/relocation/utils.py
{ "start": 9347, "end": 12092 }
class ____(ExportCheckpointer): """ An export checkpointer that uses GCP cloud storage to store encrypted checkpoints for every model we export for a SAAS_TO_SAAS relocation. """ def __init__( self, *, crypto: EncryptorDecryptorPair, uuid: UUID, storage: Storage, ): self.__crypto = crypto self.__uuid = uuid self.__storage = storage def _get_path_name(self, model_name: NormalizedModelName) -> str: return f"runs/{self.__uuid}/saas_to_saas_export/_checkpoints/{str(model_name)}.enc.tar" def get(self, model_name: NormalizedModelName) -> RpcExportOk | None: logger_data: dict[str, Any] = {"uuid": str(self.__uuid), "model": str(model_name)} path_name = self._get_path_name(model_name) if not self.__storage.exists(path_name): logger.info( "Export checkpointer: miss", extra=logger_data, ) return None try: with self.__storage.open(path_name, "rb") as fp: logger_data["encrypted_contents_size"] = fp.tell() json_data = decrypt_encrypted_tarball(fp, self.__crypto.decryptor) parsed_json = self._parse_cached_json(json_data) if parsed_json is None: logger.info( "Export checkpointer: miss", extra=logger_data, ) else: logger_data["max_pk"] = parsed_json.max_pk logger.info( "Export checkpointer: read", extra=logger_data, ) return parsed_json except (FileNotFoundError, DecryptionError, JSONDecodeError, ExportCheckpointerError): logger.info( "Export checkpointer: miss", extra=logger_data, ) return None def add(self, model_name: NormalizedModelName, json_export: Any) -> None: logger_data: dict[str, Any] = {"uuid": str(self.__uuid), "model": str(model_name)} path_name = self._get_path_name(model_name) if not isinstance(json_export, list): return None out_bytes = create_encrypted_export_tarball(json_export, self.__crypto.encryptor).getvalue() fp = BytesIO() fp.write(out_bytes) fp.seek(0) self.__storage.save(path_name, fp) logger_data["encrypted_contents_size"] = fp.tell() logger_data["model_count"] = len(json_export) logger.info( "Export checkpointer: write", extra=logger_data, )
StorageBackedCheckpointExporter